all: update`import ()` and `[]array`

pull/4607/head
yuyi 2020-04-26 19:49:31 +08:00 committed by GitHub
parent 7b39ab6d06
commit 9f4d498ff1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
59 changed files with 181 additions and 254 deletions

View File

@ -10,11 +10,11 @@ fn main() {
min_str_len := 20 min_str_len := 20
max_str_len := 40 max_str_len := 40
println('Generating $sample_size strings between $min_str_len - $max_str_len chars long...') println('Generating $sample_size strings between $min_str_len - $max_str_len chars long...')
mut bytepile := []byte mut bytepile := []byte{}
for _ in 0 .. sample_size * max_str_len { for _ in 0 .. sample_size * max_str_len {
bytepile << byte(40 + rand.next(125 - 40)) bytepile << byte(40 + rand.next(125 - 40))
} }
mut str_lens := []int mut str_lens := []int{}
for _ in 0 .. sample_size { for _ in 0 .. sample_size {
str_lens << min_str_len + rand.next(max_str_len - min_str_len) str_lens << min_str_len + rand.next(max_str_len - min_str_len)
} }

View File

@ -34,7 +34,7 @@ pub fn (mh mut TestMessageHandler) append_message(msg string) {
} }
pub fn new_test_session(_vargs string) TestSession { pub fn new_test_session(_vargs string) TestSession {
mut skip_files := []string mut skip_files := []string{}
skip_files << '_non_existing_' skip_files << '_non_existing_'
$if solaris { $if solaris {
skip_files << "examples/gg/gg2.v" skip_files << "examples/gg/gg2.v"
@ -59,7 +59,7 @@ pub fn (ts mut TestSession) init() {
pub fn (ts mut TestSession) test() { pub fn (ts mut TestSession) test() {
ts.init() ts.init()
mut remaining_files := []string mut remaining_files := []string{}
for dot_relative_file in ts.files { for dot_relative_file in ts.files {
relative_file := dot_relative_file.replace('./', '') relative_file := dot_relative_file.replace('./', '')
file := os.real_path(relative_file) file := os.real_path(relative_file)
@ -225,7 +225,7 @@ pub fn v_build_failing(zargs string, folder string) bool {
eprintln('v compiler args: "$vargs"') eprintln('v compiler args: "$vargs"')
mut session := new_test_session(vargs) mut session := new_test_session(vargs)
files := os.walk_ext(os.join_path(parent_dir, folder), '.v') files := os.walk_ext(os.join_path(parent_dir, folder), '.v')
mut mains := []string mut mains := []string{}
for f in files { for f in files {
if !f.contains('modules') && !f.contains('preludes') { if !f.contains('modules') && !f.contains('preludes') {
$if windows { $if windows {

View File

@ -51,7 +51,7 @@ fn (c Context) compare_versions() {
// The first is the baseline, against which all the others will be compared. // The first is the baseline, against which all the others will be compared.
// It is the fastest, since hello_world.v has only a single println in it, // It is the fastest, since hello_world.v has only a single println in it,
mut perf_files := []string mut perf_files := []string{}
perf_files << c.compare_v_performance('source_hello', [ perf_files << c.compare_v_performance('source_hello', [
'vprod @DEBUG@ -o source.c examples/hello_world.v', 'vprod @DEBUG@ -o source.c examples/hello_world.v',
'vprod -o source.c examples/hello_world.v', 'vprod -o source.c examples/hello_world.v',
@ -147,7 +147,7 @@ fn (c Context) compare_v_performance(label string, commands []string) string {
timestamp_b,_ := vgit.line_to_timestamp_and_commit(scripting.run('cd $c.b/ ; git rev-list -n1 --timestamp HEAD')) timestamp_b,_ := vgit.line_to_timestamp_and_commit(scripting.run('cd $c.b/ ; git rev-list -n1 --timestamp HEAD'))
debug_option_a := if timestamp_a > 1570877641 { '-g ' } else { '-debug ' } debug_option_a := if timestamp_a > 1570877641 { '-g ' } else { '-debug ' }
debug_option_b := if timestamp_b > 1570877641 { '-g ' } else { '-debug ' } debug_option_b := if timestamp_b > 1570877641 { '-g ' } else { '-debug ' }
mut hyperfine_commands_arguments := []string mut hyperfine_commands_arguments := []string{}
for cmd in commands { for cmd in commands {
println(cmd) println(cmd)
} }

View File

@ -20,7 +20,7 @@ fn (context Context) header() {
println('module ${context.module_name}') println('module ${context.module_name}')
println('') println('')
allfiles := context.files.join(' ') allfiles := context.files.join(' ')
mut options := []string mut options := []string{}
if context.prefix.len > 0 { if context.prefix.len > 0 {
options << '-p ${context.prefix}' options << '-p ${context.prefix}'
} }

View File

@ -74,7 +74,7 @@ fn main() {
eprintln('vfmt env_vflags_and_os_args: ' + args.str()) eprintln('vfmt env_vflags_and_os_args: ' + args.str())
eprintln('vfmt possible_files: ' + possible_files.str()) eprintln('vfmt possible_files: ' + possible_files.str())
} }
mut files := []string mut files := []string{}
for file in possible_files { for file in possible_files {
if !file.ends_with('.v') && !file.ends_with('.vv') { if !file.ends_with('.v') && !file.ends_with('.vv') {
verror('v fmt can only be used on .v files.\nOffending file: "$file"') verror('v fmt can only be used on .v files.\nOffending file: "$file"')
@ -90,7 +90,7 @@ fn main() {
vhelp.show_topic('fmt') vhelp.show_topic('fmt')
exit(0) exit(0)
} }
mut cli_args_no_files := []string mut cli_args_no_files := []string{}
for a in os.args { for a in os.args {
if a !in files { if a !in files {
cli_args_no_files << a cli_args_no_files << a
@ -287,7 +287,7 @@ fn get_compile_name_of_potential_v_project(file string) string {
all_files_in_pfolder := os.ls(pfolder) or { all_files_in_pfolder := os.ls(pfolder) or {
panic(err) panic(err)
} }
mut vfiles := []string mut vfiles := []string{}
for f in all_files_in_pfolder { for f in all_files_in_pfolder {
vf := os.join_path(pfolder, f) vf := os.join_path(pfolder, f)
if f.starts_with('.') || !f.ends_with('.v') || os.is_dir(vf) { if f.starts_with('.') || !f.ends_with('.v') || os.is_dir(vf) {

View File

@ -70,7 +70,7 @@ fn main(){
exit(0) exit(0)
} }
mut files := []string mut files := []string{}
locations := fp.finalize() or { eprintln('Error: ' + err) exit(1) } locations := fp.finalize() or { eprintln('Error: ' + err) exit(1) }
for xloc in locations { for xloc in locations {
loc := os.real_path(xloc) loc := os.real_path(xloc)

View File

@ -275,7 +275,7 @@ fn vpm_help() {
} }
fn vcs_used_in_dir(dir string) ?[]string { fn vcs_used_in_dir(dir string) ?[]string {
mut vcs := []string mut vcs := []string{}
for repo_subfolder in supported_vcs_folders { for repo_subfolder in supported_vcs_folders {
checked_folder := os.real_path(os.join_path(dir,repo_subfolder)) checked_folder := os.real_path(os.join_path(dir,repo_subfolder))
if os.is_dir(checked_folder) { if os.is_dir(checked_folder) {
@ -292,7 +292,7 @@ fn get_installed_modules() []string {
dirs := os.ls(settings.vmodules_path) or { dirs := os.ls(settings.vmodules_path) or {
return [] return []
} }
mut modules := []string mut modules := []string{}
for dir in dirs { for dir in dirs {
adir := os.join_path(settings.vmodules_path,dir) adir := os.join_path(settings.vmodules_path,dir)
if dir in excluded_dirs || !os.is_dir(adir) { if dir in excluded_dirs || !os.is_dir(adir) {
@ -323,7 +323,7 @@ fn get_all_modules() []string {
} }
s := r.text s := r.text
mut read_len := 0 mut read_len := 0
mut modules := []string mut modules := []string{}
for read_len < s.len { for read_len < s.len {
mut start_token := '<a href="/mod' mut start_token := '<a href="/mod'
end_token := '</a>' end_token := '</a>'
@ -359,7 +359,7 @@ fn resolve_dependencies(name, module_path string, module_names []string) {
return return
} }
vmod := parse_vmod(data) vmod := parse_vmod(data)
mut deps := []string mut deps := []string{}
// filter out dependencies that were already specified by the user // filter out dependencies that were already specified by the user
for d in vmod.deps { for d in vmod.deps {
if d !in module_names { if d !in module_names {
@ -440,7 +440,7 @@ fn verbose_println(s string) {
} }
fn get_module_meta_info(name string) ?Mod { fn get_module_meta_info(name string) ?Mod {
mut errors := []string mut errors := []string{}
for server_url in default_vpm_server_urls { for server_url in default_vpm_server_urls {
modurl := server_url + '/jsmod/$name' modurl := server_url + '/jsmod/$name'
verbose_println('Retrieving module metadata from: $modurl ...') verbose_println('Retrieving module metadata from: $modurl ...')

View File

@ -54,7 +54,7 @@ fn v_test_formatting(vargs string) {
} }
fn v_files() []string { fn v_files() []string {
mut files_that_can_be_formatted := []string mut files_that_can_be_formatted := []string{}
all_test_files := os.walk_ext('.', '.v') all_test_files := os.walk_ext('.', '.v')
for tfile in all_test_files { for tfile in all_test_files {
if tfile in known_failing_exceptions { if tfile in known_failing_exceptions {

View File

@ -1,13 +1,11 @@
module main module main
import ( import cli
cli import os
os
)
fn main() { fn main() {
mut cmd := cli.Command{ mut cmd := cli.Command{
name: 'cli', name: 'cli',
description: 'An example of the cli library', description: 'An example of the cli library',
version: '1.0.0', version: '1.0.0',
parent: 0 parent: 0
@ -22,7 +20,7 @@ fn main() {
parent: 0 parent: 0
} }
greet_cmd.add_flag(cli.Flag{ greet_cmd.add_flag(cli.Flag{
flag: .string, flag: .string,
required: true, required: true,
name: 'language', name: 'language',
abbrev: 'l', abbrev: 'l',

View File

@ -1,8 +1,6 @@
module main module main
import ( import some_module
some_module
)
fn main(){ fn main(){
mut sub := some_module.get_subscriber() mut sub := some_module.get_subscriber()

View File

@ -1,8 +1,6 @@
module some_module module some_module
import ( import eventbus
eventbus
)
const ( const (
eb = eventbus.new() eb = eventbus.new()

View File

@ -12,8 +12,8 @@ fn expr_to_rev_pol(expr string) ?[]string {
if expr == '' { if expr == '' {
return error('err: empty expression') return error('err: empty expression')
} }
mut stack := []string mut stack := []string{}
mut rev_pol := []string mut rev_pol := []string{}
mut pos := 0 mut pos := 0
for pos<expr.len { for pos<expr.len {
mut end_pos := pos mut end_pos := pos

View File

@ -9,7 +9,7 @@ const (
fn main() { fn main() {
rand.seed(time.now().unix) rand.seed(time.now().unix)
rand.next(MAX) // skip the first rand.next(MAX) // skip the first
mut arr := []int mut arr := []int{}
for _ in 0..LEN { for _ in 0..LEN {
arr << rand.next(MAX) arr << rand.next(MAX)
} }
@ -33,7 +33,7 @@ fn quick_sort(arr mut []int, l int, r int) {
quick_sort(mut arr, sep+1, r) quick_sort(mut arr, sep+1, r)
} }
[inline] [inline]
fn swap(arr mut []int, i int, j int) { fn swap(arr mut []int, i int, j int) {
temp := arr[i] temp := arr[i]
arr[i] = arr[j] arr[i] = arr[j]

View File

@ -1,10 +1,8 @@
module main module main
import ( import vweb
vweb import vweb.assets
vweb.assets import time
time
)
const ( const (
port = 8081 port = 8081

View File

@ -22,7 +22,7 @@ fn main() {
m[word] = m[word] + 1 // TODO m[key]++ m[word] = m[word] + 1 // TODO m[key]++
} }
// Sort the keys // Sort the keys
mut keys := m.keys() mut keys := m.keys()
keys.sort() keys.sort()
// Print the map // Print the map
for key in keys { for key in keys {
@ -33,7 +33,7 @@ fn main() {
// Creates an array of words from a given string // Creates an array of words from a given string
fn extract_words(contents string) []string { fn extract_words(contents string) []string {
mut splitted := []string mut splitted := []string{}
for space_splitted in contents.to_lower().split(' ') { for space_splitted in contents.to_lower().split(' ') {
if space_splitted.contains('\n') { if space_splitted.contains('\n') {
splitted << space_splitted.split('\n') splitted << space_splitted.split('\n')
@ -43,7 +43,7 @@ fn extract_words(contents string) []string {
} }
} }
mut results := []string mut results := []string{}
for s in splitted { for s in splitted {
result := filter_word(s) result := filter_word(s)
if result == '' { if result == '' {

View File

@ -1,11 +1,9 @@
module main module main
import ( import vweb
vweb import time
time import pg
pg import json
json
)
pub struct App { pub struct App {
mut: mut:
@ -74,4 +72,3 @@ pub fn (app mut App) articles() {
fn (app mut App) time() { fn (app mut App) time() {
app.vweb.text(time.now().format()) app.vweb.text(time.now().format())
} }

View File

@ -145,7 +145,7 @@ fn test_insert() {
// assert a[4] == 5 // assert a[4] == 5
// assert a[3] == 2 // assert a[3] == 2
// assert a.len == 5 // assert a.len == 5
// mut b := []f64 // mut b := []f64{}
// assert b.len == 0 // assert b.len == 0
// b.insert(0, f64(1.1)) // b.insert(0, f64(1.1))
// assert b.len == 1 // assert b.len == 1
@ -155,12 +155,12 @@ fn test_insert() {
// It depends on array.insert // It depends on array.insert
// ----------------------------- // -----------------------------
// fn test_prepend() { // fn test_prepend() {
// mut a := []int // mut a := []int{}
// assert a.len == 0 // assert a.len == 0
// a.prepend(1) // a.prepend(1)
// assert a.len == 1 // assert a.len == 1
// assert a[0] == 1 // assert a[0] == 1
// mut b := []f64 // mut b := []f64{}
// assert b.len == 0 // assert b.len == 0
// b.prepend(f64(1.1)) // b.prepend(f64(1.1))
// assert b.len == 1 // assert b.len == 1

View File

@ -1,9 +1,7 @@
module cli module cli
import ( import term
term import strings
strings
)
const ( const (
BASE_INDENT = 2 BASE_INDENT = 2

View File

@ -2,11 +2,9 @@
// but since Wayland isn't extremely adopted, we are covering almost all Linux distros. // but since Wayland isn't extremely adopted, we are covering almost all Linux distros.
module clipboard module clipboard
import ( import time
time import sync
sync import math
math
)
#flag -lX11 #flag -lX11
#include <X11/Xlib.h> #include <X11/Xlib.h>

View File

@ -7,9 +7,7 @@
module aes module aes
import ( import crypto.internal.subtle
crypto.internal.subtle
)
pub const ( pub const (
// The AES block size in bytes. // The AES block size in bytes.

View File

@ -13,10 +13,8 @@
module aes module aes
import ( import crypto.cipher
crypto.cipher import crypto.internal.subtle
crypto.internal.subtle
)
struct AesCbc { struct AesCbc {
mut: mut:

View File

@ -37,9 +37,7 @@
module aes module aes
import ( import encoding.binary
encoding.binary
)
// Encrypt one block from src into dst, using the expanded key xk. // Encrypt one block from src into dst, using the expanded key xk.
fn encrypt_block_generic(xk []u32, dst, src []byte) { fn encrypt_block_generic(xk []u32, dst, src []byte) {
@ -168,7 +166,7 @@ fn expand_key_generic(key []byte, enc mut []u32, dec mut []u32) {
} }
enc[i] = binary.big_endian_u32(key[4*i..]) enc[i] = binary.big_endian_u32(key[4*i..])
} }
for i < enc.len { for i < enc.len {
mut t := enc[i-1] mut t := enc[i-1]
if i%nk == 0 { if i%nk == 0 {

View File

@ -4,11 +4,6 @@
module aes module aes
import (
// crypto.cipher
// crypto.internal.subtle
)
// new_cipher_generic creates and returns a new cipher.Block // new_cipher_generic creates and returns a new cipher.Block
// this is the generiv v version, no arch optimisations // this is the generiv v version, no arch optimisations
fn new_cipher_generic(key []byte) AesCipher { fn new_cipher_generic(key []byte) AesCipher {

View File

@ -8,10 +8,8 @@
module md5 module md5
import ( import math.bits
math.bits import encoding.binary
encoding.binary
)
fn block_generic(dig mut Digest, p []byte) { fn block_generic(dig mut Digest, p []byte) {
// load state // load state
@ -19,7 +17,7 @@ fn block_generic(dig mut Digest, p []byte) {
mut b := dig.s[1] mut b := dig.s[1]
mut c := dig.s[2] mut c := dig.s[2]
mut d := dig.s[3] mut d := dig.s[3]
for i := 0; i <= p.len-block_size; i += block_size { for i := 0; i <= p.len-block_size; i += block_size {
mut q := p[i..] mut q := p[i..]
q = q[..block_size] q = q[..block_size]

View File

@ -7,10 +7,8 @@
// Last commit: https://github.com/golang/go/commit/3ce865d7a0b88714cc433454ae2370a105210c01 // Last commit: https://github.com/golang/go/commit/3ce865d7a0b88714cc433454ae2370a105210c01
module sha512 module sha512
import ( import crypto
crypto import encoding.binary
encoding.binary
)
pub const ( pub const (
// size is the size, in bytes, of a SHA-512 checksum. // size is the size, in bytes, of a SHA-512 checksum.
@ -322,4 +320,3 @@ pub fn hexhash_512_224(s string) string {
pub fn hexhash_512_256(s string) string { pub fn hexhash_512_256(s string) string {
return sum512_256(s.bytes()).hex() return sum512_256(s.bytes()).hex()
} }

View File

@ -46,7 +46,7 @@ pub fn (r mut Reader) read() ?[]string {
// Once we have multi dimensional array // Once we have multi dimensional array
// pub fn (r mut Reader) read_all() ?[][]string { // pub fn (r mut Reader) read_all() ?[][]string {
// mut records := []string // mut records := []string{}
// for { // for {
// record := r.read_record() or { // record := r.read_record() or {
// if error(err).error == err_eof.error { // if error(err).error == err_eof.error {
@ -110,7 +110,7 @@ fn (r mut Reader) read_record() ?[]string {
} }
break break
} }
mut fields := []string mut fields := []string{}
mut i := -1 mut i := -1
for { for {
// not quoted // not quoted

View File

@ -1,6 +1,4 @@
import ( import eventbus
eventbus
)
struct EventData { struct EventData {
data string data string
@ -10,7 +8,7 @@ fn test_eventbus(){
ev_data := &EventData{'hello'} ev_data := &EventData{'hello'}
mut eb := eventbus.new() mut eb := eventbus.new()
eb.subscriber.subscribe_once("on_test", on_test) eb.subscriber.subscribe_once("on_test", on_test)
assert eb.has_subscriber("on_test") assert eb.has_subscriber("on_test")
assert eb.subscriber.is_subscribed("on_test") assert eb.subscriber.is_subscribed("on_test")

View File

@ -63,7 +63,7 @@ pub fn (f Flag) str() string {
+' desc: $f.val_desc' +' desc: $f.val_desc'
} }
pub fn (af []Flag) str() string { pub fn (af []Flag) str() string {
mut res := []string mut res := []string{}
res << '\n []Flag = [' res << '\n []Flag = ['
for f in af { for f in af {
res << f.str() res << f.str()
@ -140,8 +140,8 @@ fn (fs mut FlagParser) add_flag(name string, abbr byte, usage string, desc strin
// - found arguments and corresponding values are removed from args list // - found arguments and corresponding values are removed from args list
fn (fs mut FlagParser) parse_value(longhand string, shorthand byte) []string { fn (fs mut FlagParser) parse_value(longhand string, shorthand byte) []string {
full := '--$longhand' full := '--$longhand'
mut found_entries := []string mut found_entries := []string{}
mut to_delete := []int mut to_delete := []int{}
mut should_skip_one := false mut should_skip_one := false
for i, arg in fs.args { for i, arg in fs.args {
if should_skip_one { if should_skip_one {
@ -257,7 +257,7 @@ pub fn (fs mut FlagParser) bool(name string, abbr byte, bdefault bool, usage str
pub fn (fs mut FlagParser) int_multi(name string, abbr byte, usage string) []int { pub fn (fs mut FlagParser) int_multi(name string, abbr byte, usage string) []int {
fs.add_flag(name, abbr, usage, '<multiple ints>') fs.add_flag(name, abbr, usage, '<multiple ints>')
parsed := fs.parse_value(name, abbr) parsed := fs.parse_value(name, abbr)
mut value := []int mut value := []int{}
for val in parsed { for val in parsed {
value << val.int() value << val.int()
} }
@ -294,7 +294,7 @@ pub fn (fs mut FlagParser) int(name string, abbr byte, idefault int, usage strin
pub fn (fs mut FlagParser) float_multi(name string, abbr byte, usage string) []f64 { pub fn (fs mut FlagParser) float_multi(name string, abbr byte, usage string) []f64 {
fs.add_flag(name, abbr, usage, '<multiple floats>') fs.add_flag(name, abbr, usage, '<multiple floats>')
parsed := fs.parse_value(name, abbr) parsed := fs.parse_value(name, abbr)
mut value := []f64 mut value := []f64{}
for val in parsed { for val in parsed {
value << val.f64() value << val.f64()
} }
@ -421,7 +421,7 @@ pub fn (fs FlagParser) usage() string {
use += 'This application does not expect any arguments\n\n' use += 'This application does not expect any arguments\n\n'
goto end_of_arguments_handling goto end_of_arguments_handling
} }
mut s:= []string mut s:= []string{}
if positive_min_arg { s << 'at least $fs.min_free_args' } if positive_min_arg { s << 'at least $fs.min_free_args' }
if positive_max_arg { s << 'at most $fs.max_free_args' } if positive_max_arg { s << 'at most $fs.max_free_args' }
if positive_min_arg && positive_max_arg && fs.min_free_args == fs.max_free_args { if positive_min_arg && positive_max_arg && fs.min_free_args == fs.max_free_args {

View File

@ -3,16 +3,15 @@
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
module gg2 module gg2
import ( import glm
glm import gx
gx import os
os import sokol
sokol import sokol.sapp
sokol.sapp import sokol.sgl
sokol.sgl import sokol.gfx
sokol.gfx import sokol.sfons
sokol.sfons
)
const ( const (
default_font_size = 24 default_font_size = 24
) )

View File

@ -1,10 +1,8 @@
module log module log
import ( import os
os import time
time import term
term
)
pub enum Level { pub enum Level {
fatal = 1 fatal = 1

View File

@ -48,7 +48,7 @@ pub fn log_factorial(n f64) f64 {
fn log_factorial_asymptotic_expansion(n int) f64 { fn log_factorial_asymptotic_expansion(n int) f64 {
m := 6 m := 6
mut term := []f64 mut term := []f64{}
xx := f64((n + 1) * (n + 1)) xx := f64((n + 1) * (n + 1))
mut xj := f64(n + 1) mut xj := f64(n + 1)

View File

@ -2,21 +2,21 @@ module stats
import math import math
// TODO: Implement all of them with generics // TODO: Implement all of them with generics
// This module defines the following statistical operations on f64 array // This module defines the following statistical operations on f64 array
// --------------------------- // ---------------------------
// | Summary of Functions | // | Summary of Functions |
// --------------------------- // ---------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// freq - Frequency // freq - Frequency
// mean - Mean // mean - Mean
// geometric_mean - Geometric Mean // geometric_mean - Geometric Mean
// harmonic_mean - Harmonic Mean // harmonic_mean - Harmonic Mean
// median - Median // median - Median
// mode - Mode // mode - Mode
// rms - Root Mean Square // rms - Root Mean Square
// population_variance - Population Variance // population_variance - Population Variance
// sample_variance - Sample Variance // sample_variance - Sample Variance
// population_stddev - Population Standard Deviation // population_stddev - Population Standard Deviation
// sample_stddev - Sample Standard Deviation // sample_stddev - Sample Standard Deviation
@ -29,7 +29,7 @@ import math
// Measure of Occurance // Measure of Occurance
// Frequency of a given number // Frequency of a given number
// Based on // Based on
// https://www.mathsisfun.com/data/frequency-distribution.html // https://www.mathsisfun.com/data/frequency-distribution.html
pub fn freq(arr []f64, val f64) int { pub fn freq(arr []f64, val f64) int {
if arr.len == 0 { if arr.len == 0 {
@ -46,7 +46,7 @@ pub fn freq(arr []f64, val f64) int {
// Measure of Central Tendancy // Measure of Central Tendancy
// Mean of the given input array // Mean of the given input array
// Based on // Based on
// https://www.mathsisfun.com/data/central-measures.html // https://www.mathsisfun.com/data/central-measures.html
pub fn mean(arr []f64) f64 { pub fn mean(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -61,7 +61,7 @@ pub fn mean(arr []f64) f64 {
// Measure of Central Tendancy // Measure of Central Tendancy
// Geometric Mean of the given input array // Geometric Mean of the given input array
// Based on // Based on
// https://www.mathsisfun.com/numbers/geometric-mean.html // https://www.mathsisfun.com/numbers/geometric-mean.html
pub fn geometric_mean(arr []f64) f64 { pub fn geometric_mean(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -76,7 +76,7 @@ pub fn geometric_mean(arr []f64) f64 {
// Measure of Central Tendancy // Measure of Central Tendancy
// Harmonic Mean of the given input array // Harmonic Mean of the given input array
// Based on // Based on
// https://www.mathsisfun.com/numbers/harmonic-mean.html // https://www.mathsisfun.com/numbers/harmonic-mean.html
pub fn harmonic_mean(arr []f64) f64 { pub fn harmonic_mean(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -91,7 +91,7 @@ pub fn harmonic_mean(arr []f64) f64 {
// Measure of Central Tendancy // Measure of Central Tendancy
// Median of the given input array ( input array is assumed to be sorted ) // Median of the given input array ( input array is assumed to be sorted )
// Based on // Based on
// https://www.mathsisfun.com/data/central-measures.html // https://www.mathsisfun.com/data/central-measures.html
pub fn median(arr []f64) f64 { pub fn median(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -108,13 +108,13 @@ pub fn median(arr []f64) f64 {
// Measure of Central Tendancy // Measure of Central Tendancy
// Mode of the given input array // Mode of the given input array
// Based on // Based on
// https://www.mathsisfun.com/data/central-measures.html // https://www.mathsisfun.com/data/central-measures.html
pub fn mode(arr []f64) f64 { pub fn mode(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
return f64(0) return f64(0)
} }
mut freqs := []int mut freqs := []int{}
for v in arr { for v in arr {
freqs<<freq(arr,v) freqs<<freq(arr,v)
} }
@ -128,7 +128,7 @@ pub fn mode(arr []f64) f64 {
} }
// Root Mean Square of the given input array // Root Mean Square of the given input array
// Based on // Based on
// https://en.wikipedia.org/wiki/Root_mean_square // https://en.wikipedia.org/wiki/Root_mean_square
pub fn rms(arr []f64) f64 { pub fn rms(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -143,7 +143,7 @@ pub fn rms(arr []f64) f64 {
// Measure of Dispersion / Spread // Measure of Dispersion / Spread
// Population Variance of the given input array // Population Variance of the given input array
// Based on // Based on
// https://www.mathsisfun.com/data/standard-deviation.html // https://www.mathsisfun.com/data/standard-deviation.html
pub fn population_variance(arr []f64) f64 { pub fn population_variance(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -159,7 +159,7 @@ pub fn population_variance(arr []f64) f64 {
// Measure of Dispersion / Spread // Measure of Dispersion / Spread
// Sample Variance of the given input array // Sample Variance of the given input array
// Based on // Based on
// https://www.mathsisfun.com/data/standard-deviation.html // https://www.mathsisfun.com/data/standard-deviation.html
pub fn sample_variance(arr []f64) f64 { pub fn sample_variance(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -175,7 +175,7 @@ pub fn sample_variance(arr []f64) f64 {
// Measure of Dispersion / Spread // Measure of Dispersion / Spread
// Population Standard Deviation of the given input array // Population Standard Deviation of the given input array
// Based on // Based on
// https://www.mathsisfun.com/data/standard-deviation.html // https://www.mathsisfun.com/data/standard-deviation.html
pub fn population_stddev(arr []f64) f64 { pub fn population_stddev(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -186,7 +186,7 @@ pub fn population_stddev(arr []f64) f64 {
// Measure of Dispersion / Spread // Measure of Dispersion / Spread
// Sample Standard Deviation of the given input array // Sample Standard Deviation of the given input array
// Based on // Based on
// https://www.mathsisfun.com/data/standard-deviation.html // https://www.mathsisfun.com/data/standard-deviation.html
pub fn sample_stddev(arr []f64) f64 { pub fn sample_stddev(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -197,7 +197,7 @@ pub fn sample_stddev(arr []f64) f64 {
// Measure of Dispersion / Spread // Measure of Dispersion / Spread
// Mean Absolute Deviation of the given input array // Mean Absolute Deviation of the given input array
// Based on // Based on
// https://en.wikipedia.org/wiki/Average_absolute_deviation // https://en.wikipedia.org/wiki/Average_absolute_deviation
pub fn mean_absdev(arr []f64) f64 { pub fn mean_absdev(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {
@ -241,7 +241,7 @@ pub fn max(arr []f64) f64 {
// Measure of Dispersion / Spread // Measure of Dispersion / Spread
// Range ( Maximum - Minimum ) of the given input array // Range ( Maximum - Minimum ) of the given input array
// Based on // Based on
// https://www.mathsisfun.com/data/range.html // https://www.mathsisfun.com/data/range.html
pub fn range(arr []f64) f64 { pub fn range(arr []f64) f64 {
if arr.len == 0 { if arr.len == 0 {

View File

@ -247,7 +247,7 @@ fn test_range() {
} }
fn test_passing_empty() { fn test_passing_empty() {
data := []f64 data := []f64{}
assert stats.freq(data,0) == 0 assert stats.freq(data,0) == 0
assert stats.mean(data) == f64(0) assert stats.mean(data) == f64(0)
assert stats.geometric_mean(data) == f64(0) assert stats.geometric_mean(data) == f64(0)
@ -263,5 +263,4 @@ fn test_passing_empty() {
assert stats.min(data) == f64(0) assert stats.min(data) == f64(0)
assert stats.max(data) == f64(0) assert stats.max(data) == f64(0)
assert stats.range(data) == f64(0) assert stats.range(data) == f64(0)
} }

View File

@ -42,7 +42,7 @@ mut:
} }
fn (dtp DTP) read() []byte { fn (dtp DTP) read() []byte {
mut data := []byte mut data := []byte{}
for { for {
buf, len := dtp.sock.recv(1024) buf, len := dtp.sock.recv(1024)
if len == 0 { break } if len == 0 { break }
@ -247,7 +247,7 @@ pub fn (ftp FTP) dir() ?[]string {
} }
dtp.close() dtp.close()
mut dir := []string mut dir := []string{}
sdir := string(byteptr(list_dir.data)) sdir := string(byteptr(list_dir.data))
for lfile in sdir.split('\n') { for lfile in sdir.split('\n') {
if lfile.len >1 { if lfile.len >1 {

View File

@ -3,11 +3,9 @@
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
module http module http
import ( import time
time import arrays
arrays import strings
strings
)
pub struct Cookie { pub struct Cookie {
pub mut: pub mut:

View File

@ -1,7 +1,5 @@
import ( import net.http
net.http import time
time
)
struct SetCookieTestCase { struct SetCookieTestCase {
cookie &http.Cookie cookie &http.Cookie

View File

@ -128,7 +128,7 @@ pub fn get_text(url string) string {
} }
pub fn url_encode_form_data(data map[string]string) string { pub fn url_encode_form_data(data map[string]string) string {
mut pieces := []string mut pieces := []string{}
for _key, _value in data { for _key, _value in data {
key := urllib.query_escape(_key) key := urllib.query_escape(_key)
value := urllib.query_escape(_value) value := urllib.query_escape(_value)
@ -151,7 +151,7 @@ fn build_url_from_fetch(_url string, config FetchConfig) ?string {
if params.keys().len == 0 { if params.keys().len == 0 {
return url.str() return url.str()
} }
mut pieces := []string mut pieces := []string{}
for key in params.keys() { for key in params.keys() {
pieces << '${key}=${params[key]}' pieces << '${key}=${params[key]}'
} }
@ -314,7 +314,7 @@ fn parse_response(resp string) Response {
fn (req &Request) build_request_headers(method, host_name, path string) string { fn (req &Request) build_request_headers(method, host_name, path string) string {
ua := req.user_agent ua := req.user_agent
mut uheaders := []string mut uheaders := []string{}
if 'Host' !in req.headers { if 'Host' !in req.headers {
uheaders << 'Host: $host_name\r\n' uheaders << 'Host: $host_name\r\n'
} }
@ -338,7 +338,7 @@ fn (req &Request) build_request_cookies_header() string {
if req.cookies.keys().len < 1 { if req.cookies.keys().len < 1 {
return '' return ''
} }
mut cookie := []string mut cookie := []string{}
for key, val in req.cookies { for key, val in req.cookies {
cookie << '$key: $val' cookie << '$key: $val'
} }

View File

@ -257,7 +257,7 @@ fn escape(s string, mode EncodingMode) string {
return s return s
} }
buf := [byte(0)].repeat(64) buf := [byte(0)].repeat(64)
mut t := []byte mut t := []byte{}
required := s.len + 2 * hex_count required := s.len + 2 * hex_count
if required <= buf.len { if required <= buf.len {
t = buf[..required] t = buf[..required]
@ -883,7 +883,7 @@ pub fn (v Values) encode() string {
return '' return ''
} }
mut buf := strings.new_builder(200) mut buf := strings.new_builder(200)
mut keys := []string mut keys := []string{}
for k, _ in v.data { for k, _ in v.data {
keys << k keys << k
} }
@ -922,7 +922,7 @@ fn resolve_path(base, ref string) string {
if full == '' { if full == '' {
return '' return ''
} }
mut dst := []string mut dst := []string{}
src := full.split('/') src := full.split('/')
for _, elem in src { for _, elem in src {
match elem { match elem {
@ -1131,4 +1131,3 @@ fn unhex(c byte) byte {
} }
return 0 return 0
} }

View File

@ -1,13 +1,11 @@
module main module main
import ( import net.websocket
net.websocket import eventbus
eventbus import time
time import readline
readline import term
term import benchmark
benchmark
)
const ( const (
eb = eventbus.new() eb = eventbus.new()

View File

@ -1,12 +1,10 @@
module websocket module websocket
import ( import time
time import rand
rand import math
math import crypto.sha1
crypto.sha1 import encoding.base64
encoding.base64
)
fn htonl64(payload_len u64) byteptr { fn htonl64(payload_len u64) byteptr {
mut ret := malloc(8) mut ret := malloc(8)
@ -18,7 +16,7 @@ fn htonl64(payload_len u64) byteptr {
ret[4] = byte(((payload_len & (u64(0xff) << 24)) >> 24) & 0xff) ret[4] = byte(((payload_len & (u64(0xff) << 24)) >> 24) & 0xff)
ret[5] = byte(((payload_len & (u64(0xff) << 16)) >> 16) & 0xff) ret[5] = byte(((payload_len & (u64(0xff) << 16)) >> 16) & 0xff)
ret[6] = byte(((payload_len & (u64(0xff) << 8)) >> 8) & 0xff) ret[6] = byte(((payload_len & (u64(0xff) << 8)) >> 8) & 0xff)
ret[7] = byte(((payload_len & (u64(0xff) << 0)) >> 0) & 0xff) ret[7] = byte(((payload_len & (u64(0xff) << 0)) >> 0) & 0xff)
return ret return ret
} }
@ -46,7 +44,7 @@ fn create_key_challenge_response(seckey string) string {
} }
fn get_nonce() string { fn get_nonce() string {
mut nonce := []byte mut nonce := []byte{}
alphanum := "0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz" alphanum := "0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz"
for i in 0..18 { for i in 0..18 {
nonce << alphanum[rand.next(61)] nonce << alphanum[rand.next(61)]

View File

@ -1,13 +1,11 @@
module websocket module websocket
import ( import net
net import net.urllib
net.urllib import encoding.base64
encoding.base64 import eventbus
eventbus import sync
sync import net.websocket.logger
net.websocket.logger
)
const ( const (
l = logger.new("ws") l = logger.new("ws")
@ -147,7 +145,7 @@ pub fn (ws mut Client) connect() int {
l.d("handshake header:") l.d("handshake header:")
handshake := "GET ${uri.resource}${uri.querystring} HTTP/1.1\r\nHost: ${uri.hostname}:${uri.port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${seckey}\r\nSec-WebSocket-Version: 13\r\n\r\n" handshake := "GET ${uri.resource}${uri.querystring} HTTP/1.1\r\nHost: ${uri.hostname}:${uri.port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${seckey}\r\nSec-WebSocket-Version: 13\r\n\r\n"
l.d(handshake) l.d(handshake)
socket := net.new_socket(ai_family, ai_socktype, 0) or { socket := net.new_socket(ai_family, ai_socktype, 0) or {
l.f(err) l.f(err)
return -1 return -1
@ -542,7 +540,7 @@ pub fn (ws mut Client) read() int {
goto free_data goto free_data
return -1 return -1
} }
mut payload := []byte mut payload := []byte{}
if payload_len > 0 { if payload_len > 0 {
payload = [`0`].repeat(int(payload_len)) payload = [`0`].repeat(int(payload_len))
C.memcpy(payload.data, &data[header_len], payload_len) C.memcpy(payload.data, &data[header_len], payload_len)

View File

@ -77,7 +77,7 @@ mut:
} }
fn init_os_args_wide(argc int, argv &byteptr) []string { fn init_os_args_wide(argc int, argv &byteptr) []string {
mut args := []string mut args := []string{}
for i in 0..argc { for i in 0..argc {
args << string_from_wide(&u16(argv[i])) args << string_from_wide(&u16(argv[i]))
} }
@ -86,7 +86,7 @@ fn init_os_args_wide(argc int, argv &byteptr) []string {
pub fn ls(path string) ?[]string { pub fn ls(path string) ?[]string {
mut find_file_data := Win32finddata{} mut find_file_data := Win32finddata{}
mut dir_files := []string mut dir_files := []string{}
// We can also check if the handle is valid. but using is_dir instead // We can also check if the handle is valid. but using is_dir instead
// h_find_dir := C.FindFirstFile(path.str, &find_file_data) // h_find_dir := C.FindFirstFile(path.str, &find_file_data)
// if (INVALID_HANDLE_VALUE == h_find_dir) { // if (INVALID_HANDLE_VALUE == h_find_dir) {

View File

@ -3,7 +3,7 @@ import rand
import time import time
fn show_u32s(a []u32){ fn show_u32s(a []u32){
mut res := []string mut res := []string{}
for x in a { for x in a {
res << x.str() res << x.str()
} }
@ -32,5 +32,5 @@ fn test_pcg32_reproducibility() {
len := randoms1.len len := randoms1.len
for i in 0..len { for i in 0..len {
assert randoms1[i] == randoms2[i] assert randoms1[i] == randoms2[i]
} }
} }

View File

@ -3,7 +3,7 @@ import rand
import time import time
fn show_u64s(a []u64){ fn show_u64s(a []u64){
mut res := []string mut res := []string{}
for x in a { for x in a {
res << x.str() res << x.str()
} }
@ -32,5 +32,5 @@ fn test_splitmix64_reproducibility() {
len := randoms1.len len := randoms1.len
for i in 0..len { for i in 0..len {
assert randoms1[i] == randoms2[i] assert randoms1[i] == randoms2[i]
} }
} }

View File

@ -2232,7 +2232,7 @@ pub fn (re mut RE) find(in_txt string) (int,int) {
// find all the non overlapping occurrences of the match pattern // find all the non overlapping occurrences of the match pattern
pub fn (re mut RE) find_all(in_txt string) []int { pub fn (re mut RE) find_all(in_txt string) []int {
mut i := 0 mut i := 0
mut res := []int mut res := []int{}
mut ls := -1 mut ls := -1
for i < in_txt.len { for i < in_txt.len {
s,e := re.find(in_txt[i..]) s,e := re.find(in_txt[i..])

View File

@ -3,10 +3,8 @@
* String to float Test * String to float Test
* *
**********************************************************************/ **********************************************************************/
import ( import strconv
strconv import strconv.atofq
strconv.atofq
)
fn test_atof() { fn test_atof() {
// //

View File

@ -2010,7 +2010,7 @@ fn (mut g Gen) struct_init(struct_init ast.StructInit) {
} else { } else {
g.writeln('($styp){') g.writeln('($styp){')
} }
// mut fields := []string // mut fields := []string{}
mut inited_fields := []string{} // TODO this is done in checker, move to ast node mut inited_fields := []string{} // TODO this is done in checker, move to ast node
/* /*
if struct_init.fields.len == 0 && struct_init.exprs.len > 0 { if struct_init.fields.len == 0 && struct_init.exprs.len > 0 {

View File

@ -367,7 +367,7 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
} }
// Generate tmp vars for values that have to be freed. // Generate tmp vars for values that have to be freed.
/* /*
mut tmps := []string mut tmps := []string{}
for arg in node.args { for arg in node.args {
if arg.typ == table.string_type_idx || is_print { if arg.typ == table.string_type_idx || is_print {
tmp := g.new_tmp_var() tmp := g.new_tmp_var()

View File

@ -1,14 +1,12 @@
module parser module parser
import ( import v.ast
v.ast import v.gen
v.gen import v.table
v.table import v.checker
v.checker //import v.eval
// v.eval import v.pref
v.pref import term
term
)
fn test_eval() { fn test_eval() {
/* /*

View File

@ -1 +0,0 @@
empty import

View File

@ -1,7 +0,0 @@
import (
// no module
)
fn main() {
println('empty import')
}

View File

@ -1,7 +1,5 @@
import ( import os
os import time
time
)
const ( const (
vexe = os.getenv('VEXE') vexe = os.getenv('VEXE')

View File

@ -1,11 +1,9 @@
import ( import os
os import time as t
time as t import crypto.sha256
crypto.sha256 import math
math import log as l
log as l import crypto.sha512
crypto.sha512
)
struct TestAliasInStruct { struct TestAliasInStruct {
time t.Time time t.Time
@ -13,7 +11,7 @@ struct TestAliasInStruct {
fn test_import() { fn test_import() {
info := l.Level.info info := l.Level.info
assert os.O_RDONLY == os.O_RDONLY && t.month_days[0] == t.month_days[0] && sha256.size == assert os.O_RDONLY == os.O_RDONLY && t.month_days[0] == t.month_days[0] && sha256.size ==
sha256.size && math.pi == math.pi && info == .info && sha512.size == sha512.size sha256.size && math.pi == math.pi && info == .info && sha512.size == sha512.size
} }

View File

@ -1,10 +1,7 @@
// Build and run files in ./prod/ folder, comparing their output to *.expected.txt files. // Build and run files in ./prod/ folder, comparing their output to *.expected.txt files.
// (Similar to REPL tests, but in -prod mode.) // (Similar to REPL tests, but in -prod mode.)
// import os import v.tests.repl.runner
import ( import benchmark
v.tests.repl.runner
benchmark
)
fn test_all_v_prod_files() { fn test_all_v_prod_files() {
// TODO: Fix running this test on Windows: // TODO: Fix running this test on Windows:

View File

@ -130,7 +130,7 @@ $diff
pub fn new_options() RunnerOptions { pub fn new_options() RunnerOptions {
vexec := full_path_to_v(5) vexec := full_path_to_v(5)
mut wd := os.getwd() mut wd := os.getwd()
mut files := []string mut files := []string{}
if os.args.len > 1 { if os.args.len > 1 {
files = os.args[1..] files = os.args[1..]
} else { } else {
@ -148,7 +148,7 @@ pub fn new_options() RunnerOptions {
pub fn new_prod_options() RunnerOptions { pub fn new_prod_options() RunnerOptions {
wd := os.getwd() wd := os.getwd()
vexec := full_path_to_v(4) vexec := full_path_to_v(4)
mut files := []string mut files := []string{}
if os.args.len > 1 { if os.args.len > 1 {
files = os.args[1..] files = os.args[1..]
} else { } else {

View File

@ -8,8 +8,8 @@ fn test_typeof_on_simple_expressions() {
} }
fn test_typeof_on_atypes() { fn test_typeof_on_atypes() {
aint := []int aint := []int{}
astring := []string astring := []string{}
assert typeof(aint) == 'array_int' assert typeof(aint) == 'array_int'
assert typeof(astring) == 'array_string' assert typeof(astring) == 'array_string'
} }

View File

@ -3,11 +3,9 @@ module assets
// this module provides an AssetManager for combining // this module provides an AssetManager for combining
// and caching javascript & css. // and caching javascript & css.
import ( import os
os import time
time import crypto.md5
crypto.md5
)
const ( const (
UnknownAssetTypeError = 'vweb.assets: unknown asset type' UnknownAssetTypeError = 'vweb.assets: unknown asset type'
@ -21,7 +19,7 @@ pub mut:
// when true assets will be minified // when true assets will be minified
minify bool minify bool
// the directory to store the cached/combined files // the directory to store the cached/combined files
cache_dir string cache_dir string
} }
struct Asset { struct Asset {
@ -75,11 +73,11 @@ fn (am AssetManager) combine(asset_type string, to_file bool) string {
cache_key := am.get_cache_key(asset_type) cache_key := am.get_cache_key(asset_type)
out_file := '$am.cache_dir/${cache_key}.$asset_type' out_file := '$am.cache_dir/${cache_key}.$asset_type'
mut out := '' mut out := ''
// use cache // use cache
if os.exists(out_file) { if os.exists(out_file) {
if to_file { if to_file {
return out_file return out_file
} }
cached := os.read_file(out_file) or { cached := os.read_file(out_file) or {
return '' return ''
} }

View File

@ -1,7 +1,5 @@
import ( import vweb.assets
vweb.assets import os
os
)
// clean_cache_dir used before and after tests that write to a cache directory. // clean_cache_dir used before and after tests that write to a cache directory.
// Because of parallel compilation and therefore test running, // Because of parallel compilation and therefore test running,

View File

@ -4,13 +4,11 @@
module vweb module vweb
import ( import os
os import net
net import net.http
net.http import net.urllib
net.urllib import strings
strings
)
pub const ( pub const (
methods_with_form = ['POST', 'PUT', 'PATCH'] methods_with_form = ['POST', 'PUT', 'PATCH']
@ -186,7 +184,7 @@ fn handle_conn<T>(conn net.Socket, app mut T) {
return return
//continue //continue
} }
mut headers := []string mut headers := []string{}
mut body := '' mut body := ''
mut in_headers := true mut in_headers := true
mut len := 0 mut len := 0