├── .dockerignore ├── .gitattributes ├── .gitignore ├── .scalafmt.conf ├── Dockerfile ├── LambdaNet-Experiments.zip ├── LambdaNet-Poster.pdf ├── README.md ├── build.sbt ├── data ├── compare-with-jsNice.ts ├── comparison │ ├── Microsoft_vsts-extension-samples.ts │ ├── bespoken_bst.ts │ ├── editor-rs_vscode-rust.ts │ ├── firebase_firebase-functions.ts │ ├── funfix_funfix.ts │ ├── gamestdio_colyseus.ts │ ├── jiayihu_pretty-algorithms.ts │ ├── teambition_teambition-sdk.ts │ └── theintern_leadfoot.ts ├── example.ts ├── js-algorithms │ ├── annotated │ │ └── code.ts │ ├── code.ts │ └── unannotated │ │ └── unannotated.ts ├── libTypes-list.txt ├── libraries │ ├── extras.d.ts │ ├── global.d.ts │ ├── lib.dom.d.ts │ ├── lib.es2015.collection.d.ts │ ├── lib.es2015.core.d.ts │ ├── lib.es2015.d.ts │ ├── lib.es2015.generator.d.ts │ ├── lib.es2015.iterable.d.ts │ ├── lib.es2015.promise.d.ts │ ├── lib.es2015.proxy.d.ts │ ├── lib.es2015.reflect.d.ts │ ├── lib.es2015.symbol.d.ts │ ├── lib.es2015.symbol.wellknown.d.ts │ ├── lib.es5.d.ts │ ├── lib.esnext.bigint.d.ts │ └── node │ │ ├── LICENSE │ │ ├── README.md │ │ ├── assert.d.ts │ │ ├── async_hooks.d.ts │ │ ├── base.d.ts │ │ ├── buffer.d.ts │ │ ├── child_process.d.ts │ │ ├── cluster.d.ts │ │ ├── console.d.ts │ │ ├── constants.d.ts │ │ ├── crypto.d.ts │ │ ├── dgram.d.ts │ │ ├── dns.d.ts │ │ ├── domain.d.ts │ │ ├── events.d.ts │ │ ├── fs.d.ts │ │ ├── globals.d.ts │ │ ├── http.d.ts │ │ ├── http2.d.ts │ │ ├── https.d.ts │ │ ├── index.d.ts │ │ ├── inspector.d.ts │ │ ├── module.d.ts │ │ ├── net.d.ts │ │ ├── os.d.ts │ │ ├── package.json │ │ ├── path.d.ts │ │ ├── perf_hooks.d.ts │ │ ├── process.d.ts │ │ ├── punycode.d.ts │ │ ├── querystring.d.ts │ │ ├── readline.d.ts │ │ ├── repl.d.ts │ │ ├── stream.d.ts │ │ ├── string_decoder.d.ts │ │ ├── timers.d.ts │ │ ├── tls.d.ts │ │ ├── trace_events.d.ts │ │ ├── ts3.2 │ │ ├── globals.d.ts │ │ ├── index.d.ts │ │ └── util.d.ts │ │ ├── tty.d.ts │ │ ├── url.d.ts │ │ ├── util.d.ts │ │ ├── v8.d.ts │ │ ├── vm.d.ts │ │ ├── worker_threads.d.ts │ │ └── zlib.d.ts ├── repo-SHAs.txt ├── tests │ ├── c1 │ │ ├── c1.ts │ │ └── ground_truth.serialized │ ├── conditional-type │ │ └── conditional-type.ts │ ├── export-import │ │ ├── chain1.ts │ │ ├── chain2.ts │ │ ├── chian3.ts │ │ ├── dir │ │ │ └── file3.ts │ │ ├── file1.ts │ │ ├── file2.ts │ │ └── importFromModule.ts │ ├── import-unknowns │ │ ├── empty.ts │ │ └── test1.ts │ ├── mergeSort.json │ ├── method-call │ │ └── methodCall.ts │ ├── objects │ │ └── objects.ts │ ├── public-fragment │ │ └── public.ts │ ├── public │ │ └── public.ts │ ├── same-label-classes │ │ └── same.ts │ ├── simple │ │ └── simple.ts │ ├── static-methods │ │ └── static-methods.ts │ ├── symbolic │ │ └── ex1 │ │ │ └── ex1.ts │ ├── syntax │ │ ├── ForIn.ts │ │ ├── Indexing.ts │ │ └── operators │ │ │ └── operators.ts │ ├── union-types │ │ └── union.ts │ └── weirdInterfaces │ │ ├── def.ts │ │ ├── io.ts │ │ └── options.ts ├── toy │ ├── devSet │ │ └── all │ │ │ └── assigns-test.ts │ ├── testSet │ │ └── all │ │ │ ├── assigns-test.ts │ │ │ ├── functions-test.ts │ │ │ └── objects-test.ts │ ├── trainSet │ │ └── all │ │ │ ├── assigns.ts │ │ │ ├── bools.ts │ │ │ ├── functions.ts │ │ │ ├── libraryUsages.ts │ │ │ ├── objects.ts │ │ │ └── toy-example.ts │ └── unannotated │ │ └── tests.ts ├── train │ ├── TypeScript-Algorithms-and-Data-Structures-master │ │ ├── .codeclimate.yml │ │ ├── .eslintignore │ │ ├── .eslintrc │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── README.md │ │ ├── azure-pipelines.yml │ │ ├── jestconfig.json │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── tests │ │ │ ├── BinaryTreeSpec.ts │ │ │ ├── BitArraySpec.ts │ │ │ ├── BitMatrixSpec.ts │ │ │ ├── FindMaximumSubarraySpec.ts │ │ │ ├── Graph │ │ │ │ └── DirectedAdjacencyMatrixGraphSpec.ts │ │ │ ├── HashTableSpec.ts │ │ │ ├── LinkedListSpec.ts │ │ │ ├── ObjectArraySpec.ts │ │ │ ├── QueueSpec.ts │ │ │ ├── RadixTreeNodeSpec.ts │ │ │ ├── RadixTreeSpec.ts │ │ │ ├── RedBlackTreeSpec.ts │ │ │ ├── Sort │ │ │ │ ├── bubbleSortSpec.ts │ │ │ │ ├── gnomeSortSpec.ts │ │ │ │ ├── insertionSortSpec.ts │ │ │ │ ├── mergeSortSpec.ts │ │ │ │ ├── quickSortSpec.ts │ │ │ │ └── selectionSortSpec.ts │ │ │ ├── StackSpec.ts │ │ │ ├── Trie.ts │ │ │ ├── TrieWithValues.ts │ │ │ ├── TypedQueueSpec.ts │ │ │ ├── TypedStackSpec.ts │ │ │ ├── UtilsSpec.ts │ │ │ ├── binarySumSpec.ts │ │ │ ├── functions │ │ │ │ ├── diophantineEquationSolverSpec.ts │ │ │ │ ├── diophantineEquationSpec.ts │ │ │ │ ├── extendedEuclidesAlgorithmSpec.ts │ │ │ │ ├── greatestCommonDivisorSpec.ts │ │ │ │ └── leastCommonMultipleSpec.ts │ │ │ └── linearSearchSpec.ts │ │ ├── ts │ │ │ ├── BinaryTree │ │ │ │ ├── BinaryTree.ts │ │ │ │ ├── BinaryTreeNode.ts │ │ │ │ ├── RedBlackTree.ts │ │ │ │ ├── RedBlackTreeNode.ts │ │ │ │ └── index.ts │ │ │ ├── BitArray.ts │ │ │ ├── BitMatrix.ts │ │ │ ├── CustomTypes │ │ │ │ └── SortingComparator.ts │ │ │ ├── FindMaximumSubarray.ts │ │ │ ├── Graph │ │ │ │ ├── DirectedAdjacencyMatrixGraph.ts │ │ │ │ └── index.ts │ │ │ ├── HashTable.ts │ │ │ ├── ITypedArray.ts │ │ │ ├── Interfaces │ │ │ │ ├── IBinaryTree.ts │ │ │ │ ├── IBinaryTreeNode.ts │ │ │ │ ├── IBitArray.ts │ │ │ │ ├── IBitMatrix.ts │ │ │ │ ├── IExtendedEuclidesAlgorithmResult.ts │ │ │ │ ├── IHashTable.ts │ │ │ │ ├── IKeyValuePair.ts │ │ │ │ ├── ILinkedList.ts │ │ │ │ ├── ILinkedListItem.ts │ │ │ │ └── IObjectArrayProperty.ts │ │ │ ├── LinkedList.ts │ │ │ ├── ObjectArray.ts │ │ │ ├── Queue.ts │ │ │ ├── RadixTree.ts │ │ │ ├── RadixTreeNode.ts │ │ │ ├── Sort │ │ │ │ ├── bubbleSort.ts │ │ │ │ ├── gnomeSort.ts │ │ │ │ ├── index.ts │ │ │ │ ├── insertionSort.ts │ │ │ │ ├── mergeSort.ts │ │ │ │ ├── quickSort.ts │ │ │ │ └── selectionSort.ts │ │ │ ├── Stack.ts │ │ │ ├── Trie.ts │ │ │ ├── TrieWithValue.ts │ │ │ ├── TypedLinkedList.ts │ │ │ ├── TypedQueue.ts │ │ │ ├── TypedStack.ts │ │ │ ├── Utils.ts │ │ │ ├── binarySum.ts │ │ │ ├── functions │ │ │ │ ├── diophantineEquation.ts │ │ │ │ ├── diophantineEquationSolver.ts │ │ │ │ ├── extendedEuclidesAlgorithm.ts │ │ │ │ ├── greatestCommonDivisor.ts │ │ │ │ ├── index.ts │ │ │ │ └── leastCommonMultiple.ts │ │ │ ├── index.ts │ │ │ └── linearSearch.ts │ │ ├── tsconfig.json │ │ └── tslint.json │ ├── algorithms-test │ │ ├── algorithms │ │ │ ├── backtracking │ │ │ │ ├── rat-in-maze.ts │ │ │ │ └── sudoku-solver.ts │ │ │ ├── math │ │ │ │ └── greatest-difference.ts │ │ │ └── search │ │ │ │ └── interpolation-search.ts │ │ ├── data-structures │ │ │ ├── hash-table.ts │ │ │ ├── models │ │ │ │ └── value-pair.ts │ │ │ └── stack.ts │ │ ├── others │ │ │ ├── balanced-symbols.ts │ │ │ ├── base-converter.ts │ │ │ └── hanoi.ts │ │ └── util.ts │ ├── algorithms-train │ │ ├── algorithms │ │ │ ├── dynamic-programing │ │ │ │ ├── knapsack-recursive.ts │ │ │ │ ├── knapsack.ts │ │ │ │ ├── longest-common-subsequence-print.ts │ │ │ │ ├── longest-common-subsequence.ts │ │ │ │ ├── matrix-chain-multiplication.ts │ │ │ │ └── min-coin-change.ts │ │ │ ├── graph │ │ │ │ ├── breadth-first-search.ts │ │ │ │ ├── depth-first-search.ts │ │ │ │ ├── dijkstra.ts │ │ │ │ ├── floyd-warshall.ts │ │ │ │ ├── kruskal.ts │ │ │ │ └── prim.ts │ │ │ ├── greedy │ │ │ │ ├── knapsack.ts │ │ │ │ ├── longest-common-subsequence.ts │ │ │ │ ├── matrix-chain-multiplication.ts │ │ │ │ └── min-coin-change.ts │ │ │ ├── math │ │ │ │ ├── find-divisors.ts │ │ │ │ ├── gcd.ts │ │ │ │ ├── lcm.ts │ │ │ │ ├── primality-test.ts │ │ │ │ └── sieve-eratosthenes.ts │ │ │ ├── search │ │ │ │ ├── binary-search-recursive.ts │ │ │ │ ├── binary-search.ts │ │ │ │ ├── min-max-search.ts │ │ │ │ └── sequential-search.ts │ │ │ ├── shuffle │ │ │ │ └── fisher–yates.ts │ │ │ ├── sorting │ │ │ │ ├── bubble-sort-improved.ts │ │ │ │ ├── bubble-sort.ts │ │ │ │ ├── bucket-sort.ts │ │ │ │ ├── counting-sort.ts │ │ │ │ ├── heap-sort.ts │ │ │ │ ├── insertion-sort.ts │ │ │ │ ├── merge-sort.ts │ │ │ │ ├── quicksort.ts │ │ │ │ ├── radix-sort.ts │ │ │ │ ├── selection-sort.ts │ │ │ │ └── shell-sort.ts │ │ │ └── string │ │ │ │ ├── brute-force.ts │ │ │ │ ├── huffman.ts │ │ │ │ ├── knuth-morris-pratt.ts │ │ │ │ ├── longest-common-substring.ts │ │ │ │ └── rabin-karp.ts │ │ ├── data-structures │ │ │ ├── avl-tree.ts │ │ │ ├── binary-search-tree.ts │ │ │ ├── circular-linked-list.ts │ │ │ ├── deque.ts │ │ │ ├── dictionary.ts │ │ │ ├── doubly-linked-list.ts │ │ │ ├── graph.ts │ │ │ ├── hash-table-linear-probing-lazy.ts │ │ │ ├── hash-table-linear-probing.ts │ │ │ ├── hash-table-separate-chaining.ts │ │ │ ├── heap.ts │ │ │ ├── linked-list.ts │ │ │ ├── models │ │ │ │ ├── linked-list-models.ts │ │ │ │ ├── node.ts │ │ │ │ ├── red-black-node.ts │ │ │ │ ├── value-pair-lazy.ts │ │ │ │ └── value-pair.ts │ │ │ ├── priority-queue-array.ts │ │ │ ├── queue.ts │ │ │ ├── red-black-tree.ts │ │ │ ├── set.ts │ │ │ ├── sorted-linked-list.ts │ │ │ ├── stack-array.ts │ │ │ └── stack-linked-list.ts │ │ ├── others │ │ │ ├── factorial.ts │ │ │ ├── fibonacci.ts │ │ │ ├── hot-potato.ts │ │ │ └── palindrome-checker.ts │ │ ├── parsed.json │ │ └── util.ts │ ├── mojiito-master │ │ ├── .editorconfig │ │ ├── .gitignore │ │ ├── CONTRIBUTING.md │ │ ├── LICENSE │ │ ├── README.md │ │ ├── build.sh │ │ ├── docs │ │ │ ├── README.md │ │ │ ├── bindings.md │ │ │ ├── components.md │ │ │ ├── dependency-injection.md │ │ │ └── getting-started.md │ │ ├── package.json │ │ ├── packages │ │ │ ├── README.md │ │ │ ├── core │ │ │ │ ├── index.ts │ │ │ │ ├── package.json │ │ │ │ ├── public_api.ts │ │ │ │ ├── src │ │ │ │ │ ├── application │ │ │ │ │ │ ├── application.ts │ │ │ │ │ │ ├── application_errors.ts │ │ │ │ │ │ ├── platform.ts │ │ │ │ │ │ └── platform_errors.ts │ │ │ │ │ ├── component │ │ │ │ │ │ ├── factory.ts │ │ │ │ │ │ ├── factory_resolver.ts │ │ │ │ │ │ ├── metadata.ts │ │ │ │ │ │ ├── reference.ts │ │ │ │ │ │ └── resolver.ts │ │ │ │ │ ├── core.ts │ │ │ │ │ ├── di │ │ │ │ │ │ ├── forward_ref.ts │ │ │ │ │ │ ├── injection_token.ts │ │ │ │ │ │ ├── injector.ts │ │ │ │ │ │ ├── metadata.ts │ │ │ │ │ │ ├── provider.ts │ │ │ │ │ │ ├── reflective_errors.ts │ │ │ │ │ │ ├── reflective_injector.ts │ │ │ │ │ │ ├── reflective_key.ts │ │ │ │ │ │ └── reflective_provider.ts │ │ │ │ │ ├── facade │ │ │ │ │ ├── reflection │ │ │ │ │ │ ├── platform_reflection_capabilities.ts │ │ │ │ │ │ ├── reflection.ts │ │ │ │ │ │ ├── reflection_capabilities.ts │ │ │ │ │ │ ├── reflector.ts │ │ │ │ │ │ ├── reflector_reader.ts │ │ │ │ │ │ └── types.ts │ │ │ │ │ ├── render.ts │ │ │ │ │ ├── type.ts │ │ │ │ │ ├── utils │ │ │ │ │ │ └── decorator.ts │ │ │ │ │ └── view │ │ │ │ │ │ ├── element_ref.ts │ │ │ │ │ │ ├── provider.ts │ │ │ │ │ │ ├── refs.ts │ │ │ │ │ │ ├── types.ts │ │ │ │ │ │ ├── utils.ts │ │ │ │ │ │ ├── view.ts │ │ │ │ │ │ ├── view_attach.ts │ │ │ │ │ │ ├── view_container_ref.ts │ │ │ │ │ │ ├── view_ref.ts │ │ │ │ │ │ └── view_utils.ts │ │ │ │ └── tsconfig-build.json │ │ │ ├── facade │ │ │ │ ├── index.ts │ │ │ │ └── src │ │ │ │ │ ├── collection.ts │ │ │ │ │ ├── error.ts │ │ │ │ │ └── lang.ts │ │ │ ├── license-banner.txt │ │ │ ├── platform-browser │ │ │ │ ├── index.ts │ │ │ │ ├── package.json │ │ │ │ ├── public_api.ts │ │ │ │ ├── src │ │ │ │ │ ├── binding_parser.ts │ │ │ │ │ ├── chars.ts │ │ │ │ │ ├── compiler │ │ │ │ │ │ ├── compile_result.ts │ │ │ │ │ │ └── compiler.ts │ │ │ │ │ ├── dom_renderer.ts │ │ │ │ │ ├── dom_traverser.ts │ │ │ │ │ ├── dom_visitor.ts │ │ │ │ │ ├── expression │ │ │ │ │ │ ├── expression.ts │ │ │ │ │ │ └── expression_parser.ts │ │ │ │ │ ├── facade │ │ │ │ │ ├── platform-browser.ts │ │ │ │ │ ├── platform_ref.ts │ │ │ │ │ ├── selector.ts │ │ │ │ │ └── tokens.ts │ │ │ │ └── tsconfig-build.json │ │ │ └── tsconfig.json │ │ ├── playground │ │ │ ├── README.md │ │ │ ├── app │ │ │ │ ├── app.component.ts │ │ │ │ ├── button.component.ts │ │ │ │ ├── dialog.ts │ │ │ │ └── drawer.component.ts │ │ │ ├── index.html │ │ │ ├── main.ts │ │ │ ├── styles.css │ │ │ └── tsconfig.json │ │ ├── scripts │ │ │ ├── _travis_fold.sh │ │ │ ├── build_playground.sh │ │ │ ├── deploy.sh │ │ │ ├── publish.sh │ │ │ └── publish_build_artifacts.sh │ │ └── tslint.json │ ├── philmander-typescript-algorithms │ │ ├── README.md │ │ ├── package.json │ │ ├── src │ │ │ ├── big-o │ │ │ │ ├── o-1.ts │ │ │ │ ├── o-2n.ts │ │ │ │ ├── o-logn.ts │ │ │ │ ├── o-n.ts │ │ │ │ └── o-n2.ts │ │ │ ├── binary-search │ │ │ │ ├── iterative.ts │ │ │ │ ├── random.ts │ │ │ │ └── recursive.ts │ │ │ ├── data-structures │ │ │ │ └── linked-list.ts │ │ │ ├── helpers.ts │ │ │ └── sorting │ │ │ │ ├── bubble-sort.ts │ │ │ │ └── quick-sort.ts │ │ └── tsconfig.json │ └── typehtml-master │ │ ├── .editorconfig │ │ ├── .gitignore │ │ ├── .npmignore │ │ ├── .travis.yml │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── TODO.md │ │ ├── alm.json │ │ ├── package.json │ │ ├── src │ │ ├── dom │ │ │ ├── createElement.ts │ │ │ ├── jsx.ts │ │ │ ├── render.ts │ │ │ └── utils.ts │ │ ├── index.ts │ │ ├── server │ │ │ └── renderToString.ts │ │ ├── tests │ │ │ ├── mocha │ │ │ │ └── basic.tsx │ │ │ ├── testem │ │ │ │ ├── componentClass.tsx │ │ │ │ ├── componentFunction.tsx │ │ │ │ ├── index.ts │ │ │ │ └── intrinsic.tsx │ │ │ └── tools │ │ │ │ └── utils.ts │ │ ├── types.ts │ │ └── vdom │ │ │ ├── README.md │ │ │ ├── h.ts │ │ │ ├── helpers │ │ │ └── attachto.ts │ │ │ ├── htmldomapi.ts │ │ │ ├── is.ts │ │ │ ├── modules │ │ │ ├── attributes.ts │ │ │ ├── class.ts │ │ │ ├── dataset.ts │ │ │ ├── eventlisteners.ts │ │ │ ├── hero.ts │ │ │ ├── module.ts │ │ │ ├── props.ts │ │ │ └── style.ts │ │ │ ├── patch.ts │ │ │ ├── snabbdom.ts │ │ │ ├── thunk.ts │ │ │ └── vnode.ts │ │ ├── testem.json │ │ └── tsconfig.json └── ts-algorithms │ ├── algorithms │ ├── backtracking │ │ ├── rat-in-maze.ts │ │ └── sudoku-solver.ts │ ├── dynamic-programing │ │ ├── knapsack-recursive.ts │ │ ├── knapsack.ts │ │ ├── longest-common-subsequence-print.ts │ │ ├── longest-common-subsequence.ts │ │ ├── matrix-chain-multiplication.ts │ │ └── min-coin-change.ts │ ├── graph │ │ ├── breadth-first-search.ts │ │ ├── depth-first-search.ts │ │ ├── dijkstra.ts │ │ ├── floyd-warshall.ts │ │ ├── kruskal.ts │ │ └── prim.ts │ ├── greedy │ │ ├── knapsack.ts │ │ ├── longest-common-subsequence.ts │ │ ├── matrix-chain-multiplication.ts │ │ └── min-coin-change.ts │ ├── math │ │ ├── find-divisors.ts │ │ ├── gcd.ts │ │ ├── greatest-difference.ts │ │ ├── lcm.ts │ │ ├── primality-test.ts │ │ └── sieve-eratosthenes.ts │ ├── search │ │ ├── binary-search-recursive.ts │ │ ├── binary-search.ts │ │ ├── interpolation-search.ts │ │ ├── min-max-search.ts │ │ └── sequential-search.ts │ ├── shuffle │ │ └── fisher–yates.ts │ ├── sorting │ │ ├── bubble-sort-improved.ts │ │ ├── bubble-sort.ts │ │ ├── bucket-sort.ts │ │ ├── counting-sort.ts │ │ ├── heap-sort.ts │ │ ├── insertion-sort.ts │ │ ├── merge-sort.ts │ │ ├── quicksort.ts │ │ ├── radix-sort.ts │ │ ├── selection-sort.ts │ │ └── shell-sort.ts │ └── string │ │ ├── brute-force.ts │ │ ├── huffman.ts │ │ ├── knuth-morris-pratt.ts │ │ ├── longest-common-substring.ts │ │ └── rabin-karp.ts │ ├── data-structures │ ├── avl-tree.ts │ ├── binary-search-tree.ts │ ├── circular-linked-list.ts │ ├── deque.ts │ ├── dictionary.ts │ ├── doubly-linked-list.ts │ ├── graph.ts │ ├── hash-table-linear-probing-lazy.ts │ ├── hash-table-linear-probing.ts │ ├── hash-table-separate-chaining.ts │ ├── hash-table.ts │ ├── heap.ts │ ├── linked-list.ts │ ├── models │ │ ├── linked-list-models.ts │ │ ├── node.ts │ │ ├── red-black-node.ts │ │ ├── value-pair-lazy.ts │ │ └── value-pair.ts │ ├── priority-queue-array.ts │ ├── queue.ts │ ├── red-black-tree.ts │ ├── set.ts │ ├── sorted-linked-list.ts │ ├── stack-array.ts │ ├── stack-linked-list.ts │ └── stack.ts │ ├── index.ts │ ├── others │ ├── balanced-symbols.ts │ ├── base-converter.ts │ ├── factorial.ts │ ├── fibonacci.ts │ ├── hanoi.ts │ ├── hot-potato.ts │ └── palindrome-checker.ts │ └── util.ts ├── images ├── Header.png └── Logo.png ├── project ├── build.properties └── plugins.sbt ├── results ├── Dec13-7pm(wrong-rnn).txt ├── Dec13-9pm.txt └── experiments.txt ├── scripts ├── ResultsLogger.nb ├── bootstrap │ ├── bootstrap.bundle.js │ ├── bootstrap.bundle.js.map │ ├── bootstrap.css │ ├── bootstrap.css.map │ └── jQuery.js ├── data_clean │ ├── clean.py │ └── filters.py ├── experiment │ ├── test1.ts │ └── typeQuery.ts ├── linux │ └── install-sbt.sh ├── runAnnotsEval.sh ├── runService.sh ├── runTraining.sh ├── ts │ ├── installDependencies.sh │ ├── package-lock.json │ ├── package.json │ ├── parsing.ts │ ├── parsingFromFile.ts │ ├── parsingFromString.ts │ ├── tsconfig.json │ └── tslint.json ├── uploadData-aws.sh └── uploadData.sh └── src ├── main ├── java │ └── driver │ │ └── JavaDriver.java ├── resources │ └── logback.xml └── scala │ ├── WhereAreThings.scala │ ├── botkop │ └── numsca │ │ ├── Tensor.scala │ │ ├── package.scala │ │ └── samples │ │ └── MinCharRnn.scala │ ├── funcdiff │ ├── APITrait.scala │ ├── BatchingService.scala │ ├── CompNode.scala │ ├── DebugTime.scala │ ├── DiffFunc.scala │ ├── Gradient.scala │ ├── GraphNode.scala │ ├── LayerFactory.scala │ ├── Optimizer.scala │ ├── Param.scala │ ├── SimpleMath.scala │ ├── TensorExtension.scala │ └── package.scala │ ├── lambdanet │ ├── Analysis.scala │ ├── Configs.scala │ ├── GType.scala │ ├── ImportStmt.scala │ ├── JSExamples.scala │ ├── JavaAPI.scala │ ├── Model.scala │ ├── NeuralInference.scala │ ├── PredictionSpace.scala │ ├── PrepareRepos.scala │ ├── SequenceModel.scala │ ├── ServerUtils.scala │ ├── Surface.scala │ ├── TypeInferenceService.scala │ ├── architecture │ │ ├── ArchitectureHelper.scala │ │ ├── Architectures.scala │ │ ├── LabelEncoder.scala │ │ ├── NNArchitecture.scala │ │ └── package.scala │ ├── correctness │ │ ├── Accuracy.scala │ │ ├── Assignment.scala │ │ ├── BeamSearchExperiment.scala │ │ ├── Benchmark.scala │ │ ├── CEResultAnalysis.scala │ │ ├── CrossEntropyExperiment.scala │ │ ├── CrossEntropyMethod.scala │ │ ├── CrossEntropyTypeInference.scala │ │ ├── Heuristics.scala │ │ ├── InputUtils.scala │ │ ├── NewestModelService.scala │ │ ├── Objective.scala │ │ ├── OutputUtils.scala │ │ ├── PTypeContext.scala │ │ ├── Sampling.scala │ │ ├── Schedule.scala │ │ ├── Search.scala │ │ ├── ShallowSubtype.scala │ │ ├── SimulatedAnnealing.scala │ │ ├── SimulatedAnnealingExperiment.scala │ │ ├── TypeChecker.scala │ │ ├── TypeCheckingScript.scala │ │ ├── ValidTypeGen.scala │ │ └── package.scala │ ├── package.scala │ ├── test │ │ ├── EvalFileLevelPrediction.scala │ │ ├── EvalUserAnnots.scala │ │ ├── RunTrainedModel.scala │ │ └── TestUtils.scala │ ├── train │ │ ├── DataSet.scala │ │ ├── DecodingResult.scala │ │ ├── MostFreqConstructorBaseline.scala │ │ ├── NamingBaseline.scala │ │ ├── NamingExperiment.scala │ │ ├── Timeouts.scala │ │ ├── Training.scala │ │ ├── TrainingControl.scala │ │ ├── TrainingState.scala │ │ └── package.scala │ ├── translation │ │ ├── IR.scala │ │ ├── ImportsResolution.scala │ │ ├── PLang.scala │ │ ├── PredicateGraph.scala │ │ ├── QLang.scala │ │ └── package.scala │ └── utils │ │ ├── DownloadRepos.scala │ │ ├── EmailService.scala │ │ ├── FileLogger.scala │ │ ├── GraphVisualization.scala │ │ ├── IndexedHashSet.scala │ │ ├── JSonParsing.scala │ │ ├── ModelFormatConversion.scala │ │ ├── PrecomputeResults.scala │ │ ├── PredicateGraphVisualization.scala │ │ ├── PrefixMap.scala │ │ ├── ProcessAngular.scala │ │ ├── ProgramParsing.scala │ │ ├── QLangAccuracy.scala │ │ ├── QLangDisplay.scala │ │ ├── ReportFinish.scala │ │ └── Statistics.scala │ └── plots │ ├── Examples.scala │ ├── JSUtils.scala │ ├── MathematicaBackend.scala │ ├── MathematicaUtils.scala │ ├── PlotlyBackend.scala │ ├── VisualizationFramework.scala │ └── package.scala └── test └── scala ├── expensive └── RnnOptimizationTest.scala ├── funcdiff ├── GradientsCheck.scala ├── LayerCheck.scala ├── OptimizerCheck.scala └── TestUtils.scala └── lambdanet ├── GTypeTest.scala ├── MyTest.scala ├── correctness ├── InconsistentLibDefs.scala ├── MethodCallTest.scala ├── SamplingTest.scala ├── SimulatedAnnealingTest.scala ├── StringNodeBug.scala ├── TypeCheckerTest.scala ├── WeightedOneDifferenceRandomNeighborTest.scala └── WeightedPatchAnyTest.scala └── utils └── ParserTests.scala /.dockerignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### SBT template 3 | # Simple Build Tool 4 | # http://www.scala-sbt.org/release/docs/Getting-Started/Directories.html#configuring-version-control 5 | 6 | dist/* 7 | target/ 8 | lib_managed/ 9 | src_managed/ 10 | project/boot/ 11 | project/plugins/project/ 12 | .history 13 | .cache 14 | .lib/ 15 | ### Example user template template 16 | ### Example user template 17 | 18 | # IntelliJ project files 19 | .idea 20 | *.iml 21 | out 22 | 23 | *.class 24 | *.log 25 | running-result/ 26 | *.tgz 27 | /src/main/scala/learn_cats/ 28 | 29 | # unused scripts 30 | scripts/data_clean 31 | scripts/*.nb 32 | scripts/ts/*.js 33 | 34 | results 35 | images 36 | node_modules 37 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | scripts/ResultsLogger.nb binary 2 | scripts/bootstrap/* binary 3 | data/* linguist-vendored 4 | data/** linguist-vendored 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### SBT template 3 | # Simple Build Tool 4 | # http://www.scala-sbt.org/release/docs/Getting-Started/Directories.html#configuring-version-control 5 | 6 | dist/* 7 | target/ 8 | lib_managed/ 9 | src_managed/ 10 | project/boot/ 11 | project/plugins/project/ 12 | .history 13 | .cache 14 | .lib/ 15 | ### Example user template template 16 | ### Example user template 17 | 18 | # IntelliJ project files 19 | .idea 20 | *.iml 21 | out 22 | 23 | *.class 24 | *.log 25 | SA_results/ 26 | results.serialized 27 | configs/* 28 | running-result/ 29 | *.tgz 30 | /src/main/scala/learn_cats/ 31 | 32 | data/**/*.html 33 | data/**/*.js 34 | data/**/*.css 35 | data/**/*.map 36 | 37 | *.zip 38 | node_modules/ 39 | data/parsedRepos* 40 | docker-sync.yml 41 | models/ 42 | package-lock.json 43 | .DS_STORE 44 | /src/main/scala/lambdanet/correctness/CrossEntropyExperimentScript.scala 45 | /CE_Results/ 46 | 47 | scripts/ts/*.js 48 | package.json 49 | 50 | # VSCode files 51 | .vscode 52 | .metals/ 53 | .bloop/ 54 | .ammonite/ 55 | metals.sbt -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | version = "2.0.0-RC8" 2 | align = some 3 | maxColumn = 92 4 | assumeStandardLibraryStripMargin = true 5 | continuationIndent.defnSite = 4 6 | continuationIndent.callSite = 2 7 | verticalMultiline.newlineBeforeImplicitKW = true 8 | verticalMultiline.arityThreshold = 4 9 | verticalMultiline.newlineAfterOpenParen = true 10 | rewrite.rules = [RedundantParens, PreferCurlyFors] 11 | trailingCommas = preserve 12 | danglingParentheses = true 13 | -------------------------------------------------------------------------------- /LambdaNet-Experiments.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/LambdaNet-Experiments.zip -------------------------------------------------------------------------------- /LambdaNet-Poster.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/LambdaNet-Poster.pdf -------------------------------------------------------------------------------- /data/compare-with-jsNice.ts: -------------------------------------------------------------------------------- 1 | /** Taken from AFASSoftware_maquette/src/projector.ts\ 2 | * JSNice [2/3] 3 | * LambdaNet [1/3] 4 | * */ 5 | 6 | let createParentNodePath = (node: Node, rootNode: Element) => { 7 | let parentNodePath = []; 8 | while (node !== rootNode) { 9 | parentNodePath.push(node); 10 | node = node.parentNode; 11 | } 12 | return parentNodePath; 13 | }; 14 | 15 | /** 16 | * Taken from akserg_ng2-dnd/src/dnd.utils.ts 17 | * JSNice: [2/3] 18 | * LambdaNet [2/3] 19 | */ 20 | function createImage(src: string) { 21 | let img:HTMLImageElement = new HTMLImageElement(); 22 | img.src = src; 23 | return img; 24 | } 25 | 26 | function callFun(fun: Function) { 27 | return fun(); 28 | } 29 | 30 | -------------------------------------------------------------------------------- /data/comparison/gamestdio_colyseus.ts: -------------------------------------------------------------------------------- 1 | // All: 6 JSNice: 2 LamdbaNet: 5 2 | function spliceOne (arr: Array, index: number): boolean { 3 | // manually splice availableRooms array 4 | // http://jsperf.com/manual-splice 5 | if (index === -1 || index >= arr.length) { 6 | return false; 7 | } 8 | 9 | for (var i = index, len = arr.length - 1; i < len; i++) { 10 | arr[i] = arr[i + 1]; 11 | } 12 | 13 | arr.length = len; 14 | 15 | return true; 16 | } 17 | 18 | function merge (a: any, ...objs: any[]) { 19 | for (let i = 0, len = objs.length; i < len; i++) { 20 | let b = objs[i]; 21 | for (let key in b) { 22 | if (b.hasOwnProperty(key)) { 23 | a[key] = b[key] 24 | } 25 | } 26 | } 27 | return a; 28 | } 29 | 30 | function logError (err: Error): void { 31 | if (err) { 32 | console.log(err) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /data/example.ts: -------------------------------------------------------------------------------- 1 | class Matrix { 2 | constructor(public data: Array, size: number){} 3 | 4 | times(matrix: Matrix): Matrix { 5 | return 6 | } 7 | } 8 | 9 | function printResult(a: Matrix, b: Matrix){ 10 | return a.concat(b).times(3); 11 | } -------------------------------------------------------------------------------- /data/libraries/extras.d.ts: -------------------------------------------------------------------------------- 1 | interface Void { 2 | _void: any 3 | } 4 | 5 | declare const Void: undefined; 6 | 7 | declare const arguments: IArguments; 8 | 9 | 10 | type ByteString = String; 11 | 12 | // for testing frameworks 13 | declare const expect; 14 | declare const describe; 15 | declare const it; -------------------------------------------------------------------------------- /data/libraries/node/buffer.d.ts: -------------------------------------------------------------------------------- 1 | declare module "buffer" { 2 | export const INSPECT_MAX_BYTES: number; 3 | const BuffType: typeof Buffer; 4 | 5 | export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; 6 | 7 | export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; 8 | 9 | export const SlowBuffer: { 10 | /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ 11 | new(size: number): Buffer; 12 | prototype: Buffer; 13 | }; 14 | 15 | export { BuffType as Buffer }; 16 | } 17 | -------------------------------------------------------------------------------- /data/libraries/node/console.d.ts: -------------------------------------------------------------------------------- 1 | declare module "console" { 2 | export = console; 3 | } 4 | -------------------------------------------------------------------------------- /data/libraries/node/domain.d.ts: -------------------------------------------------------------------------------- 1 | declare module "domain" { 2 | import * as events from "events"; 3 | 4 | class Domain extends events.EventEmitter implements NodeJS.Domain { 5 | run(fn: Function): void; 6 | add(emitter: events.EventEmitter): void; 7 | remove(emitter: events.EventEmitter): void; 8 | bind(cb: (err: Error, data: any) => any): any; 9 | intercept(cb: (data: any) => any): any; 10 | members: any[]; 11 | enter(): void; 12 | exit(): void; 13 | } 14 | 15 | function create(): Domain; 16 | } 17 | -------------------------------------------------------------------------------- /data/libraries/node/module.d.ts: -------------------------------------------------------------------------------- 1 | declare module "module" { 2 | export = NodeJS.Module; 3 | } 4 | -------------------------------------------------------------------------------- /data/libraries/node/process.d.ts: -------------------------------------------------------------------------------- 1 | declare module "process" { 2 | export = process; 3 | } 4 | -------------------------------------------------------------------------------- /data/libraries/node/punycode.d.ts: -------------------------------------------------------------------------------- 1 | declare module "punycode" { 2 | function decode(string: string): string; 3 | function encode(string: string): string; 4 | function toUnicode(domain: string): string; 5 | function toASCII(domain: string): string; 6 | const ucs2: ucs2; 7 | interface ucs2 { 8 | decode(string: string): number[]; 9 | encode(codePoints: number[]): string; 10 | } 11 | const version: any; 12 | } 13 | -------------------------------------------------------------------------------- /data/libraries/node/querystring.d.ts: -------------------------------------------------------------------------------- 1 | declare module "querystring" { 2 | interface StringifyOptions { 3 | encodeURIComponent?: Function; 4 | } 5 | 6 | interface ParseOptions { 7 | maxKeys?: number; 8 | decodeURIComponent?: Function; 9 | } 10 | 11 | interface ParsedUrlQuery { [key: string]: string | string[]; } 12 | 13 | function stringify(obj?: {}, sep?: string, eq?: string, options?: StringifyOptions): string; 14 | function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; 15 | function escape(str: string): string; 16 | function unescape(str: string): string; 17 | } 18 | -------------------------------------------------------------------------------- /data/libraries/node/string_decoder.d.ts: -------------------------------------------------------------------------------- 1 | declare module "string_decoder" { 2 | interface NodeStringDecoder { 3 | write(buffer: Buffer): string; 4 | end(buffer?: Buffer): string; 5 | } 6 | const StringDecoder: { 7 | new(encoding?: string): NodeStringDecoder; 8 | }; 9 | } 10 | -------------------------------------------------------------------------------- /data/libraries/node/timers.d.ts: -------------------------------------------------------------------------------- 1 | declare module "timers" { 2 | function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; 3 | namespace setTimeout { 4 | function __promisify__(ms: number): Promise; 5 | function __promisify__(ms: number, value: T): Promise; 6 | } 7 | function clearTimeout(timeoutId: NodeJS.Timeout): void; 8 | function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; 9 | function clearInterval(intervalId: NodeJS.Timeout): void; 10 | function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; 11 | namespace setImmediate { 12 | function __promisify__(): Promise; 13 | function __promisify__(value: T): Promise; 14 | } 15 | function clearImmediate(immediateId: NodeJS.Immediate): void; 16 | } 17 | -------------------------------------------------------------------------------- /data/libraries/node/ts3.2/globals.d.ts: -------------------------------------------------------------------------------- 1 | // tslint:disable-next-line:no-bad-reference 2 | /// 3 | 4 | declare namespace NodeJS { 5 | interface HRTime { 6 | bigint(): bigint; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /data/libraries/node/ts3.2/index.d.ts: -------------------------------------------------------------------------------- 1 | // NOTE: These definitions support NodeJS and TypeScript 3.2. 2 | 3 | // NOTE: TypeScript version-specific augmentations can be found in the following paths: 4 | // - ~/base.d.ts - Shared definitions common to all TypeScript versions 5 | // - ~/index.d.ts - Definitions specific to TypeScript 2.1 6 | // - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 7 | 8 | // Reference required types from the default lib: 9 | /// 10 | /// 11 | /// 12 | /// 13 | 14 | // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: 15 | // tslint:disable-next-line:no-bad-reference 16 | /// 17 | 18 | // TypeScript 3.2-specific augmentations: 19 | /// 20 | /// 21 | -------------------------------------------------------------------------------- /data/libraries/node/ts3.2/util.d.ts: -------------------------------------------------------------------------------- 1 | // tslint:disable-next-line:no-bad-reference 2 | /// 3 | declare module "util" { 4 | namespace inspect { 5 | const custom: unique symbol; 6 | } 7 | namespace promisify { 8 | const custom: unique symbol; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /data/libraries/node/v8.d.ts: -------------------------------------------------------------------------------- 1 | declare module "v8" { 2 | interface HeapSpaceInfo { 3 | space_name: string; 4 | space_size: number; 5 | space_used_size: number; 6 | space_available_size: number; 7 | physical_space_size: number; 8 | } 9 | 10 | // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ 11 | type DoesZapCodeSpaceFlag = 0 | 1; 12 | 13 | interface HeapInfo { 14 | total_heap_size: number; 15 | total_heap_size_executable: number; 16 | total_physical_size: number; 17 | total_available_size: number; 18 | used_heap_size: number; 19 | heap_size_limit: number; 20 | malloced_memory: number; 21 | peak_malloced_memory: number; 22 | does_zap_garbage: DoesZapCodeSpaceFlag; 23 | } 24 | 25 | function getHeapStatistics(): HeapInfo; 26 | function getHeapSpaceStatistics(): HeapSpaceInfo[]; 27 | function setFlagsFromString(flags: string): void; 28 | } 29 | -------------------------------------------------------------------------------- /data/tests/c1/c1.ts: -------------------------------------------------------------------------------- 1 | class C1 { 2 | str5: string = ""; 3 | num5: number = 5; 4 | event5: Event = Event.prototype; 5 | window5: Window = window; 6 | bool5: boolean = true; 7 | } 8 | 9 | let c1: C1 = new C1(); -------------------------------------------------------------------------------- /data/tests/c1/ground_truth.serialized: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/data/tests/c1/ground_truth.serialized -------------------------------------------------------------------------------- /data/tests/conditional-type/conditional-type.ts: -------------------------------------------------------------------------------- 1 | type NonNullable = T extends undefined | null ? never : T 2 | type X = NonNullable// number 3 | type Y = NonNullable// number 4 | type Z = NonNullable// never 5 | 6 | let x: X = 1 7 | let y: Y = 2 8 | let z: Z = null -------------------------------------------------------------------------------- /data/tests/export-import/chain1.ts: -------------------------------------------------------------------------------- 1 | import {TestClass} from "./chain2"; 2 | import TestDef from "./chain2"; 3 | 4 | new TestClass(); 5 | 6 | new TestDef(); -------------------------------------------------------------------------------- /data/tests/export-import/chain2.ts: -------------------------------------------------------------------------------- 1 | import { TestClass } from "./chian3"; 2 | 3 | export { TestClass }; 4 | 5 | export default class TestDefault{} -------------------------------------------------------------------------------- /data/tests/export-import/chian3.ts: -------------------------------------------------------------------------------- 1 | export class TestClass{ 2 | 3 | } -------------------------------------------------------------------------------- /data/tests/export-import/dir/file3.ts: -------------------------------------------------------------------------------- 1 | import {result} from "../file2"; 2 | 3 | export class C1 { 4 | x = result; 5 | } -------------------------------------------------------------------------------- /data/tests/export-import/file1.ts: -------------------------------------------------------------------------------- 1 | export function foo(bar: number, z): boolean { 2 | return z; 3 | } -------------------------------------------------------------------------------- /data/tests/export-import/file2.ts: -------------------------------------------------------------------------------- 1 | import {foo as fool} from "./file1"; 2 | import {C1 as C, C1} from "./dir/file3"; 3 | 4 | export var result = fool(5,3); 5 | export function g(){ 6 | return new C(); 7 | } -------------------------------------------------------------------------------- /data/tests/export-import/importFromModule.ts: -------------------------------------------------------------------------------- 1 | declare module MA{ 2 | import { x } from "MB"; 3 | } 4 | 5 | declare module "MB" { 6 | export const x = 4; 7 | } -------------------------------------------------------------------------------- /data/tests/import-unknowns/empty.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/data/tests/import-unknowns/empty.ts -------------------------------------------------------------------------------- /data/tests/import-unknowns/test1.ts: -------------------------------------------------------------------------------- 1 | import f from "./empty"; 2 | 3 | const a = f; 4 | const b = f.foo(); 5 | const c = f.bar.g; -------------------------------------------------------------------------------- /data/tests/method-call/methodCall.ts: -------------------------------------------------------------------------------- 1 | class Add { 2 | k: number 3 | constructor(k: number) { 4 | this.k = k 5 | } 6 | add(x: number, y: number): number { 7 | return x + y; 8 | } 9 | } 10 | 11 | class AddWithAnonymousFunction extends Add { 12 | constructor(k: number) { 13 | super(k) 14 | this.add = function(x: number, y: number): number { 15 | return x + y; 16 | } 17 | } 18 | } 19 | 20 | let adder = new Add(3) 21 | let anon = new AddWithAnonymousFunction(2) 22 | let a = 1 23 | let b = 3 24 | let c = adder.add(a, b) 25 | let d = anon.add(a, b) 26 | let e = adder.k 27 | let f = anon.k -------------------------------------------------------------------------------- /data/tests/objects/objects.ts: -------------------------------------------------------------------------------- 1 | class A1{ 2 | x1: number = 1; 3 | x2: string = "a"; 4 | x3: A1 = new A1(); 5 | x4: number; 6 | } 7 | 8 | class B1{ 9 | x1: string; 10 | x2: B1 = new B1(); 11 | x3: string[]; 12 | x4: boolean; 13 | constructor(){ 14 | this.x1 = "b"; 15 | this.x3 = ["a"]; 16 | } 17 | } 18 | 19 | class C{ 20 | c1: any; 21 | c2: number; 22 | } 23 | 24 | new A1().x4 = 5; 25 | if(new B1().x4){ 26 | new C().c1 = undefined; 27 | new C().c2 = 5; 28 | } 29 | 30 | let x1: number; 31 | let x2: string; 32 | let o1 = {a: 5, b: 'a'}; 33 | x1 = o1.a; 34 | x2 = o1.b; 35 | 36 | let y1: boolean; 37 | let y2: Window; 38 | let o2 = {a: true, b: window}; 39 | y1 = o2.a; 40 | y2 = o2.b; 41 | 42 | class Loss { 43 | name; // require name based reasoning 44 | param; // require reason about usages 45 | data; 46 | 47 | constructor(name, param){ 48 | this.name = name; this.param = param; 49 | } 50 | 51 | // multiple type assignments 52 | gradient(y){ 53 | return this.param * y; 54 | } 55 | } 56 | 57 | // requires chain of uncertain reasoning 58 | function training(loss, epoch=0){ 59 | // some other code... 60 | loss.data = epoch; 61 | } -------------------------------------------------------------------------------- /data/tests/public-fragment/public.ts: -------------------------------------------------------------------------------- 1 | class Vector { 2 | constructor(public x: number, 3 | public y: number, 4 | public z: number) { 5 | } 6 | static times(k: number, v: Vector) { return new Vector(k * v.x, k * v.y, k * v.z); } 7 | static minus(v1: Vector, v2: Vector) { return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); } 8 | static plus(v1: Vector, v2: Vector) { return new Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); } 9 | static dot(v1: Vector, v2: Vector) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } 10 | static mag(v: Vector) { return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z); } 11 | static norm(v: Vector) { 12 | var mag = Vector.mag(v); 13 | var div = (mag === 0) ? Infinity : 1.0 / mag; 14 | return Vector.times(div, v); 15 | } 16 | static cross(v1: Vector, v2: Vector) { 17 | return new Vector(v1.y * v2.z - v1.z * v2.y, 18 | v1.z * v2.x - v1.x * v2.z, 19 | v1.x * v2.y - v1.y * v2.x); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /data/tests/same-label-classes/same.ts: -------------------------------------------------------------------------------- 1 | class A { 2 | x: number 3 | y: boolean 4 | } 5 | 6 | class B { 7 | x: number 8 | y: boolean 9 | } 10 | 11 | let a = new A() 12 | let b = new B() 13 | let c: A = new B() 14 | 15 | a.x = 1 16 | b.y = true -------------------------------------------------------------------------------- /data/tests/simple/simple.ts: -------------------------------------------------------------------------------- 1 | class C3{ 2 | str2: string = "a"; 3 | num4: number; 4 | 5 | constructor(){ 6 | this.num4 = 4; 7 | } 8 | } 9 | 10 | class C1 { 11 | str5: string = ""; 12 | num5: number = 5; 13 | event5: Event = Event.prototype; 14 | window5: Window = window; 15 | bool5: boolean = true; 16 | } 17 | 18 | class C4{ 19 | window5: Window; 20 | number5: number; 21 | } 22 | 23 | 24 | let c1: C1 = new C1(); 25 | let c3: C3 = new C3(); 26 | let c4: C4 = new C4(); 27 | let r1: RegExp = /ab+c/; -------------------------------------------------------------------------------- /data/tests/static-methods/static-methods.ts: -------------------------------------------------------------------------------- 1 | class Test { 2 | constructor(public x: number) { 3 | } 4 | static mag(v: Test) { return Math.sqrt(v.x * v.x); } 5 | 6 | static norm(v: Test) { 7 | var mag = Test.mag(v); 8 | var m1 = Test.mag(v); 9 | var div = (mag === 0) ? Infinity : 1.0 / m1; 10 | return div 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /data/tests/symbolic/ex1/ex1.ts: -------------------------------------------------------------------------------- 1 | class Num{ 2 | 3 | constructor(public v){} 4 | 5 | public plus(that: Num): Num { 6 | return new Num(this.v + that.v) 7 | } 8 | } -------------------------------------------------------------------------------- /data/tests/syntax/ForIn.ts: -------------------------------------------------------------------------------- 1 | const xs = [1,2,3]; 2 | let y = 0; 3 | 4 | for(const x of xs){ 5 | y += x; 6 | } -------------------------------------------------------------------------------- /data/tests/syntax/Indexing.ts: -------------------------------------------------------------------------------- 1 | export class List { 2 | constructor( 3 | public bits: number 4 | ) {} 5 | 6 | [5](): A { 7 | 8 | } 9 | } 10 | 11 | new List(1)[5](); -------------------------------------------------------------------------------- /data/tests/syntax/operators/operators.ts: -------------------------------------------------------------------------------- 1 | var a = 4; 2 | 5 + a; 3 | 4 || a; -------------------------------------------------------------------------------- /data/tests/union-types/union.ts: -------------------------------------------------------------------------------- 1 | export interface VNode { 2 | /** 3 | * The CSS selector containing tagname, css classnames and id. An empty string is used to denote a text node. 4 | */ 5 | readonly vnodeSelector: string; 6 | /** 7 | * Object containing attributes, properties, event handlers and more, see [[h]]. 8 | */ 9 | // readonly properties: VNodeProperties | undefined; 10 | /** 11 | * Array of [[VNode]]s to be used as children. This array is already flattened. 12 | */ 13 | readonly children: VNode[] | undefined; 14 | /** 15 | * Used in a special case when a [[VNode]] only has one child node which is a text node. Only used in combination with children === undefined. 16 | */ 17 | readonly text: string | undefined; 18 | /** 19 | * Used by maquette to store the domNode that was produced from this [[VNode]]. 20 | */ 21 | domNode: Node | null; 22 | } 23 | 24 | let text: string | undefined; 25 | let tex2: undefined | string; 26 | let flattenedChildren: VNode[] | undefined 27 | let flattenedChildren2: undefined | VNode[]; 28 | let result = (text === '') ? undefined : text 29 | -------------------------------------------------------------------------------- /data/tests/weirdInterfaces/def.ts: -------------------------------------------------------------------------------- 1 | // Goal: 2 | // 1) Get rid of empty interfaces from our prediction space. 3 | // 2) Handle empty class single inheritance as equality 4 | 5 | export interface ISnapshottable {} 6 | 7 | export interface IType { 8 | name: string 9 | is(thing: any): thing is S | T 10 | create(snapshot?: S, environment?: any): T 11 | isType: boolean 12 | describe(): string 13 | Type: T 14 | SnapshotType: S 15 | 16 | } 17 | 18 | export interface INode { 19 | readonly type: IType 20 | readonly storedValue: any 21 | readonly path: string 22 | readonly isRoot: boolean 23 | die(): void 24 | } 25 | 26 | export interface ISimpleType extends IType {} -------------------------------------------------------------------------------- /data/toy/devSet/all/assigns-test.ts: -------------------------------------------------------------------------------- 1 | let a: number = 1; 2 | let t: boolean = true; 3 | let s: string = "s"; 4 | let e: Event = Event.prototype; 5 | 6 | class C2{ 7 | str1: string; 8 | num1: number; 9 | 10 | constructor(){ 11 | this.num1 = 2; 12 | this.str1 = "x"; 13 | } 14 | } 15 | 16 | class C3{ 17 | str2: string = "a"; 18 | num4: number; 19 | 20 | constructor(){ 21 | this.num4 = 4; 22 | } 23 | } 24 | 25 | class C1 { 26 | str5: string = ""; 27 | num5: number = 5; 28 | event5: Event = Event.prototype; 29 | window5: Window = window; 30 | bool5: boolean = true; 31 | } 32 | 33 | class C4{ 34 | window5: Window; 35 | number5: number; 36 | } 37 | 38 | 39 | let c1: C1 = new C1(); 40 | let c2: C2 = new C2(); 41 | let c3: C3 = new C3(); 42 | let c4: C4 = new C4(); 43 | 44 | 45 | let c21 = new C2(); 46 | let n: number = c21.num1; 47 | let s6: string = c21.str1; 48 | 49 | new C4().window5 = window; 50 | new C4().number5 = 5; 51 | 52 | let x14: any = window; 53 | x14 = 1; 54 | let x15: number = 5; 55 | x15 = 5; -------------------------------------------------------------------------------- /data/toy/testSet/all/assigns-test.ts: -------------------------------------------------------------------------------- 1 | let a: number = 1; 2 | let t: boolean = true; 3 | let s: string = "s"; 4 | let e: Event = Event.prototype; 5 | 6 | class C2{ 7 | str1: string; 8 | num1: number; 9 | 10 | constructor(){ 11 | this.num1 = 2; 12 | this.str1 = "x"; 13 | } 14 | } 15 | 16 | class C3{ 17 | str2: string = "a"; 18 | num4: number; 19 | 20 | constructor(){ 21 | this.num4 = 4; 22 | } 23 | } 24 | 25 | class C1 { 26 | str5: string = ""; 27 | num5: number = 5; 28 | event5: Event = Event.prototype; 29 | window5: Window = window; 30 | bool5: boolean = true; 31 | } 32 | 33 | class C4{ 34 | window5: Window; 35 | number5: number; 36 | } 37 | 38 | 39 | let c1: C1 = new C1(); 40 | let c2: C2 = new C2(); 41 | let c3: C3 = new C3(); 42 | let c4: C4 = new C4(); 43 | 44 | 45 | let c21 = new C2(); 46 | let n: number = c21.num1; 47 | let s6: string = c21.str1; 48 | 49 | new C4().window5 = window; 50 | new C4().number5 = 5; 51 | 52 | let x14: any = window; 53 | x14 = 1; 54 | let x15: number = 5; 55 | x15 = 5; -------------------------------------------------------------------------------- /data/toy/testSet/all/functions-test.ts: -------------------------------------------------------------------------------- 1 | function f1(x: boolean, z: Window, y: Event): number { 2 | x = true; 3 | z = window; 4 | y = Event.prototype; 5 | return 1; 6 | } 7 | function f2(x: number, c: Window, y: boolean, k: number[]): string { 8 | x = 5; 9 | y = true; 10 | c = window; 11 | k = [5]; 12 | return 'a'; 13 | } 14 | 15 | // tests any prediction 16 | function f3(x: any) { 17 | return x 18 | } 19 | 20 | let x1: boolean; 21 | let y1: Window; 22 | let c1: Event; 23 | let r1: number = f1(x1, y1, c1); 24 | 25 | let x2: Window; 26 | let y2: number; 27 | let c2: boolean; 28 | let w2: number; 29 | let r2: string = f2(y2, x2, c2, w2); 30 | 31 | 32 | function g1(x: number, c: Event, y: boolean): number {} 33 | g1(1,Event.prototype, true) + 1; 34 | 35 | function g3(y: Array, x: string): void {} 36 | g3([1], 'a'); 37 | -------------------------------------------------------------------------------- /data/toy/testSet/all/objects-test.ts: -------------------------------------------------------------------------------- 1 | class A1{ 2 | x1: number = 1; 3 | x2: boolean; 4 | x3: A1 = new A1(); 5 | } 6 | 7 | class D{ 8 | x1: string[]; 9 | x3: boolean; 10 | x4: number; 11 | constructor(){ 12 | this.x1 = ["b"]; 13 | this.x3 = false; 14 | } 15 | } 16 | 17 | class C{ 18 | c2: any; 19 | c1: number; 20 | x4: C; 21 | } 22 | 23 | new A1().x2 = true; 24 | if(new D().x4){ 25 | new C().c1 = 5; 26 | new C().c2 = undefined; 27 | new C().x4 = new C(); 28 | } 29 | 30 | let v1: A1 = new A1(); 31 | let v2: D = new D(); 32 | let v3: C = new C(); 33 | 34 | let y1: number; 35 | let y2: Window; 36 | let o2 = {u: 3, w: window}; 37 | y1 = o2.u; 38 | y2 = o2.w; 39 | -------------------------------------------------------------------------------- /data/toy/trainSet/all/bools.ts: -------------------------------------------------------------------------------- 1 | let x: boolean; 2 | let y: Window; 3 | if(x){ 4 | y = window; 5 | } 6 | let z: boolean = ! true; 7 | let x1: number = 5 + 2; -------------------------------------------------------------------------------- /data/toy/trainSet/all/libraryUsages.ts: -------------------------------------------------------------------------------- 1 | let a: number = "s".length; 2 | let i: number; 3 | let s1: string; 4 | let r1: string = s1.charAt(i); 5 | 6 | let s2: string; 7 | let i2: number; 8 | let r2: number = s2.charCodeAt(i2); 9 | 10 | let r3: boolean = window.closed; 11 | let r4: void = window.blur(); 12 | -------------------------------------------------------------------------------- /data/toy/trainSet/all/objects.ts: -------------------------------------------------------------------------------- 1 | class A1{ 2 | x1: number = 1; 3 | x2: string = "a"; 4 | x3: A1 = new A1(); 5 | x4: number; 6 | } 7 | 8 | class B1{ 9 | x1: string; 10 | x2: B1 = new B1(); 11 | x3: string[]; 12 | x4: boolean; 13 | constructor(){ 14 | this.x1 = "b"; 15 | this.x3 = ["a"]; 16 | } 17 | } 18 | 19 | class C{ 20 | x1: any; 21 | x2: number; 22 | } 23 | 24 | new A1().x4 = 5; 25 | if(new B1().x4){ 26 | new C().x1 = undefined; 27 | new C().x2 = 5; 28 | } 29 | 30 | let x1: number; 31 | let x2: string; 32 | let o1 = {a: 5, b: 'a'}; 33 | x1 = o1.a; 34 | x2 = o1.b; 35 | 36 | let y1: boolean; 37 | let y2: Window; 38 | let o2 = {a: true, b: window}; 39 | y1 = o2.a; 40 | y2 = o2.b; 41 | -------------------------------------------------------------------------------- /data/toy/unannotated/tests.ts: -------------------------------------------------------------------------------- 1 | class A { 2 | x; 3 | y; 4 | constructor(u: boolean) { 5 | this.x = u 6 | } 7 | } 8 | 9 | function f() { 10 | return 1+2 11 | } 12 | let r = f() 13 | -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/.codeclimate.yml: -------------------------------------------------------------------------------- 1 | --- 2 | engines: 3 | duplication: 4 | enabled: true 5 | config: 6 | languages: 7 | - javascript 8 | eslint: 9 | enabled: true 10 | fixme: 11 | enabled: true 12 | ratings: 13 | paths: 14 | - "**.inc" 15 | - "**.js" 16 | - "**.jsx" 17 | - "**.module" 18 | exclude_paths: 19 | - tests/ 20 | -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/.eslintignore: -------------------------------------------------------------------------------- 1 | **/*{.,-}min.js 2 | -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Logs 4 | logs 5 | *.log 6 | npm-debug.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | 13 | # Directory for instrumented libs generated by jscoverage/JSCover 14 | lib-cov 15 | 16 | # Coverage directory used by tools like istanbul 17 | coverage 18 | 19 | # nyc test coverage 20 | .nyc_output 21 | 22 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 23 | .grunt 24 | 25 | # node-waf configuration 26 | .lock-wscript 27 | 28 | # Compiled binary addons (http://nodejs.org/api/addons.html) 29 | build/Release 30 | 31 | # Dependency directories 32 | node_modules 33 | jspm_packages 34 | 35 | # Optional npm cache directory 36 | .npm 37 | 38 | # Optional REPL history 39 | .node_repl_history 40 | 41 | # Webstorm 42 | .idea 43 | dist/ 44 | typings/ 45 | -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | dist: trusty 3 | language: node_js 4 | node_js: 5 | - '10.14.2' 6 | before_install: 7 | after_script: 8 | - npm install -g codeclimate-test-reporter 9 | - codeclimate-test-reporter < ./coverage/lcov.info -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 sularome 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/README.md: -------------------------------------------------------------------------------- 1 | # TypeScript algorithms and data structures 2 | 3 | Useful algorithms and Data structures written in typescript. 4 | 5 | [![Build Status](https://travis-ci.org/sularome/TypeScript-Algorithms-and-Data-Structures.svg?branch=master)](https://travis-ci.org/sularome/TypeScript-Algorithms-and-Data-Structures) [![Code Climate](https://codeclimate.com/github/sularome/JavaScript-Algorithms/badges/gpa.svg)](https://codeclimate.com/github/sularome/JavaScript-Algorithms) [![Test Coverage](https://codeclimate.com/github/sularome/JavaScript-Algorithms/badges/coverage.svg)](https://codeclimate.com/github/sularome/JavaScript-Algorithms/coverage) [![Issue Count](https://codeclimate.com/github/sularome/JavaScript-Algorithms/badges/issue_count.svg)](https://codeclimate.com/github/sularome/JavaScript-Algorithms) 6 | -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # Node.js 2 | # Build a general Node.js project with npm. 3 | # Add steps that analyze code, save build artifacts, deploy, and more: 4 | # https://docs.microsoft.com/azure/devops/pipelines/languages/javascript 5 | 6 | trigger: 7 | - master 8 | 9 | pool: 10 | vmImage: 'Ubuntu-16.04' 11 | 12 | steps: 13 | - task: NodeTool@0 14 | inputs: 15 | versionSpec: '10.x' 16 | displayName: 'Install Node.js' 17 | 18 | - script: | 19 | npm install 20 | npm test 21 | displayName: 'npm install and test' 22 | -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/jestconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "transform": { 3 | "^.+\\.(t|j)sx?$": "ts-jest" 4 | }, 5 | "testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", 6 | "moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"], 7 | "collectCoverage": true, 8 | "coverageDirectory": "coverage" 9 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/FindMaximumSubarraySpec.ts: -------------------------------------------------------------------------------- 1 | import FindMaximumSubarray from "../ts/FindMaximumSubarray"; 2 | describe(`Find maximum subarray`, function () { 3 | it(`Find maximum subarray`, function () { 4 | let [leftIndex, rightIndex, sum] = FindMaximumSubarray([-1, 3, 2, 5, -1]); 5 | expect(leftIndex).toEqual(1); 6 | expect(rightIndex).toEqual(3); 7 | expect(sum).toEqual(10); 8 | [leftIndex, rightIndex, sum] = FindMaximumSubarray([-1, 1]); 9 | expect(leftIndex).toEqual(1); 10 | expect(rightIndex).toEqual(1); 11 | expect(sum).toEqual(1); 12 | [leftIndex, rightIndex, sum] = FindMaximumSubarray([-1, 1, -1]); 13 | expect(leftIndex).toEqual(1); 14 | expect(rightIndex).toEqual(1); 15 | expect(sum).toEqual(1); 16 | [leftIndex, rightIndex, sum] = FindMaximumSubarray([-1]); 17 | expect(leftIndex).toEqual(0); 18 | expect(rightIndex).toEqual(0); 19 | expect(sum).toEqual(0); 20 | }); 21 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/QueueSpec.ts: -------------------------------------------------------------------------------- 1 | import {Queue} from "../ts/Queue"; 2 | describe('Queue', function () { 3 | 4 | describe('enqueue', function () { 5 | it('should add elements to the stack', function () { 6 | var q = new Queue(); 7 | q.enqueue(1); 8 | expect(q.size()).toEqual(1); 9 | q.enqueue(2); 10 | expect(q.size()).toEqual(2); 11 | q.dequeue(); 12 | expect(q.size()).toEqual(1); 13 | }); 14 | }); 15 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/Sort/mergeSortSpec.ts: -------------------------------------------------------------------------------- 1 | import mergeSort from "../../ts/Sort/mergeSort"; 2 | describe("Merge sort", function () { 3 | it("should sort", function () { 4 | expect(mergeSort([1, 4, 2, 3])).toEqual([1, 2, 3, 4]); 5 | expect(mergeSort([11, 4, 2, 3])).toEqual([2, 3, 4, 11]); 6 | expect(mergeSort([11, 4, 2])).toEqual([2, 4, 11]); 7 | expect(mergeSort([11, 4, 2, 3, 5])).toEqual([2, 3, 4, 5, 11]); 8 | expect(mergeSort([5, 2, 4, 6, 1, 3])).toEqual([1, 2, 3, 4, 5, 6]); 9 | }); 10 | 11 | it("should return empty array if empty or one element array is passed", function () { 12 | expect(mergeSort([])).toEqual([]); 13 | expect(mergeSort([1])).toEqual([1]); 14 | }); 15 | 16 | it("should reverse sort", function () { 17 | expect(mergeSort([1, 4, 2, 3], true)).toEqual([4, 3, 2, 1]); 18 | expect(mergeSort([11, 4, 2, 3], true)).toEqual([11, 4, 3, 2]); 19 | expect(mergeSort([5, 2, 4, 6, 1, 3], true)).toEqual([6, 5, 4, 3, 2, 1]); 20 | }); 21 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/Trie.ts: -------------------------------------------------------------------------------- 1 | import {Trie} from "../ts/Trie"; 2 | 3 | describe("Trie", function () { 4 | it("should be able to check if word exist", function () { 5 | const trie = new Trie(); 6 | expect(trie.contains("test")).toEqual(false); 7 | trie.insert("test"); 8 | expect(trie.contains("test")).toEqual(true); 9 | expect(trie.contains("test for non existing word")).toEqual(false); 10 | trie.insert("test with value"); 11 | expect(trie.contains("test with value")).toEqual(true); 12 | }); 13 | 14 | it("should be able to add word", function () { 15 | const trie = new Trie(); 16 | expect(trie.contains("test")).toEqual(false); 17 | trie.insert("test"); 18 | expect(trie.contains("test")).toEqual(true); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/TypedQueueSpec.ts: -------------------------------------------------------------------------------- 1 | import {TypedQueue} from "../ts/TypedQueue"; 2 | describe('Queue', function () { 3 | describe('enqueue', function () { 4 | it('should add elements to the stack', function () { 5 | var q = new TypedQueue(new Uint8Array(3)); 6 | q.enqueue(1); 7 | expect(q.size()).toEqual(1); 8 | expect(q.peek()).toEqual(1); 9 | q.enqueue(2); 10 | expect(q.peek()).toEqual(1); 11 | expect(q.size()).toEqual(2); 12 | q.dequeue(); 13 | expect(q.peek()).toEqual(2); 14 | expect(q.size()).toEqual(1); 15 | q.enqueue(2); 16 | expect(q.size()).toEqual(2); 17 | q.dequeue(); 18 | expect(q.size()).toEqual(1); 19 | }); 20 | }); 21 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/UtilsSpec.ts: -------------------------------------------------------------------------------- 1 | import {Utils} from "../ts/Utils"; 2 | describe("Utils", function () { 3 | describe("minIndex", function () { 4 | it("Should find the lowest index in part of array", function () { 5 | const ar = [3, 4, 5, 1, 2, 3, 1, 2]; 6 | expect(Utils.minIndex(ar)).toEqual(3); 7 | expect(Utils.minIndex(ar, 0, 4)).toEqual(3); 8 | expect(Utils.minIndex(ar, 4)).toEqual(6); 9 | expect(Utils.minIndex([1, 4], 0, 2, Utils.gt)).toEqual(0); 10 | expect(Utils.minIndex([1, 4], 1, 2, Utils.gt)).toEqual(1); 11 | }); 12 | }); 13 | 14 | describe("swapValues", function () { 15 | it("Should swap elements in array", function () { 16 | const ar = [3, 4, 5, 1, 2, 3, 1, 2]; 17 | Utils.swapValues(ar, 0, 1); 18 | expect(ar).toEqual([4, 3, 5, 1, 2, 3, 1, 2]); 19 | Utils.swapValues(ar, 3, 5); 20 | expect(ar).toEqual([4, 3, 5, 3, 2, 1, 1, 2]); 21 | }); 22 | }); 23 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/binarySumSpec.ts: -------------------------------------------------------------------------------- 1 | import binarySum from '../ts/binarySum'; 2 | describe('Binary sum', function () { 3 | it('should sum to arrays', function () { 4 | expect(binarySum([1,1], [0,1])).toEqual([1,0,0]); //3 + 1 = 4 5 | expect(binarySum([1,0], [0,1])).toEqual([0,1,1]); //2 + 1 = 3 6 | expect(binarySum([0,1,1,0], [1,1,1,1])).toEqual([1,0,1,0,1]); //6 + 15 = 3 7 | }); 8 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/functions/diophantineEquationSpec.ts: -------------------------------------------------------------------------------- 1 | import { diophantineEquation } from "../../ts/functions/diophantineEquation"; 2 | 3 | describe("diophantineEquation", () => { 4 | it("should return NaN if both parameters are 0", () => { 5 | expect(diophantineEquation(0, 0, 0)).toBeNull(); 6 | }); 7 | it("should return NaN if gcd(a, b) foes not divide c", () => { 8 | expect(diophantineEquation(15, 20, 3)).toBeNull(); 9 | }); 10 | it("should return result for Diophantine equation when one exist", () => { 11 | expect(diophantineEquation(10, 6, 14)).toEqual([-7, 14]); 12 | }); 13 | it("should return result for Diophantine equation when result is negative", () => { 14 | expect(diophantineEquation(391, 299, -69)).toEqual([9, -12]); 15 | }); 16 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/functions/leastCommonMultipleSpec.ts: -------------------------------------------------------------------------------- 1 | import { leastCommonMultiple } from "../../ts/functions/leastCommonMultiple"; 2 | 3 | describe('leastCommonMultiple', function () { 4 | it('should calculate the least common multiple of two co-prime numbers', function () { 5 | expect(leastCommonMultiple(3, 5)).toEqual(15); 6 | }); 7 | it('should return 0 if both numbers are 0', function () { 8 | expect(leastCommonMultiple(0, 0)).toEqual(0); 9 | }); 10 | it('should return first number if second is 0', function () { 11 | expect(leastCommonMultiple(3, 0)).toEqual(3); 12 | }); 13 | it('should return the second if it is divisible by first', function () { 14 | expect(leastCommonMultiple(15, 30)).toEqual(30); 15 | }); 16 | it('should return the first if it is divisible by second', function () { 17 | expect(leastCommonMultiple(6, 3)).toEqual(6); 18 | }); 19 | it('should work for negative numbers too', function () { 20 | expect(leastCommonMultiple(-5, 3)).toEqual(15); 21 | }); 22 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tests/linearSearchSpec.ts: -------------------------------------------------------------------------------- 1 | import linearSearch from "../ts/linearSearch"; 2 | describe('Linear search', function () { 3 | it('should return null when value is not found', function () { 4 | expect(linearSearch([1,4,2,3], 5)).toBeNull(); 5 | }); 6 | 7 | it('should return index of value', function () { 8 | expect(linearSearch([1,4,2,3], 1)).toEqual(0); 9 | }); 10 | }); -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/BinaryTree/index.ts: -------------------------------------------------------------------------------- 1 | import * as BTImplementatio from "./BinaryTree"; 2 | import {BinaryTreeNode} from "./BinaryTreeNode"; 3 | import RedBlackTree from "./RedBlackTree"; 4 | import RedBlackTreeNode from "./RedBlackTreeNode"; 5 | 6 | const BinaryTree = { 7 | BinaryTree: BTImplementatio.BinaryTree, 8 | BinaryTreeNode, 9 | RedBlackTree, 10 | RedBlackTreeNode 11 | }; 12 | export default BinaryTree; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/CustomTypes/SortingComparator.ts: -------------------------------------------------------------------------------- 1 | type SortingComparator = (a: T, b: T) => boolean; 2 | 3 | export default SortingComparator; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Graph/index.ts: -------------------------------------------------------------------------------- 1 | import {DirectedAdjacencyMatrixGraph} from "./DirectedAdjacencyMatrixGraph"; 2 | 3 | const Graph = { 4 | DirectedAdjacencyMatrixGraph 5 | } 6 | export default Graph; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/IBinaryTree.ts: -------------------------------------------------------------------------------- 1 | interface IBinaryTree { 2 | add: (value: T) => void; 3 | remove: (value: T) => boolean; 4 | reverseTreeWalk: (callback: (pv: any, cv: T) => any, initialValue: any) => any; 5 | inOrderTreeWalk: (callback: (pv: any, cv: T) => any, initialValue: any) => any; 6 | isEmpty: () => boolean; 7 | max: () => U; 8 | min: () => U; 9 | search: (value: T) => U; 10 | successor: (value: T) => U; 11 | } 12 | 13 | export default IBinaryTree; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/IBinaryTreeNode.ts: -------------------------------------------------------------------------------- 1 | export class IBinaryTreeNode{ 2 | left:IBinaryTreeNode; 3 | right:IBinaryTreeNode; 4 | value:T; 5 | parent:IBinaryTreeNode; 6 | hasLeftChild: () => boolean; 7 | hasRightChild: ()=> boolean; 8 | isLeftChild: ()=> boolean; 9 | isRightChild: ()=> boolean; 10 | isRoot: ()=> boolean; 11 | min: ()=> IBinaryTreeNode; 12 | max: ()=> IBinaryTreeNode; 13 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/IBitArray.ts: -------------------------------------------------------------------------------- 1 | export interface IBitArray { 2 | count(): number; 3 | get(index: number): boolean; 4 | getIndexes(): number[]; 5 | reset(): IBitArray; 6 | resize(newSize: number): IBitArray; 7 | size(): number; 8 | set(index: number, value: boolean): IBitArray; 9 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/IBitMatrix.ts: -------------------------------------------------------------------------------- 1 | export interface IBitMatrix { 2 | clone(): IBitMatrix; 3 | count(): number; 4 | get(rowIndex: number, colIndex: number): boolean; 5 | getIndexes(resultPerColumn?: boolean): number[][]; 6 | getRowIndexes(row: number): number[]; 7 | getColIndexes(column: number): number[]; 8 | reset(): IBitMatrix; 9 | resize(newRowCount: number, newColCount: number): IBitMatrix; 10 | size(): number[]; 11 | set(rowIndex: number, colIndex: number, value: boolean): IBitMatrix; 12 | setBuffer(newBuffer: Uint32Array): IBitMatrix; 13 | spliceColumn(startIndex: number, deleteCount: number): IBitMatrix; 14 | spliceRow(startIndex: number, deleteCount: number): IBitMatrix; 15 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/IExtendedEuclidesAlgorithmResult.ts: -------------------------------------------------------------------------------- 1 | export interface IExtendedEuclidesAlgorithmResult { 2 | x: number; 3 | y: number; 4 | gcd: number; 5 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/IHashTable.ts: -------------------------------------------------------------------------------- 1 | import {IKeyValuePair} from "./IKeyValuePair"; 2 | 3 | export interface IHashTable { 4 | clear(): void; 5 | clone(): IHashTable; 6 | contains(value: V): boolean; 7 | containsKey(value: K): boolean; 8 | containsValue(value: V): boolean; 9 | elements(): IKeyValuePair[]; 10 | get(key: K): V; 11 | put(key: K, value: V): void; 12 | putAll(elements: IKeyValuePair[]): void; 13 | remove(key: K): V; 14 | size(): number; 15 | values(): V[]; 16 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/IKeyValuePair.ts: -------------------------------------------------------------------------------- 1 | export interface IKeyValuePair { 2 | key: T; 3 | value: U; 4 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/ILinkedList.ts: -------------------------------------------------------------------------------- 1 | export interface ILinkedList { 2 | forEach:(callback: (item: T, index:number, list:ILinkedList) => void, thisArg:any) => void; 3 | isEmpty: () => boolean; 4 | push: (value:T) => void; 5 | pop: () => T; 6 | remove: (value:T) => void; 7 | shift: () => T; 8 | unshift: (value:T) => void; 9 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/ILinkedListItem.ts: -------------------------------------------------------------------------------- 1 | export interface ILinkedListItem { 2 | next:ILinkedListItem; 3 | prev:ILinkedListItem; 4 | value:T; 5 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Interfaces/IObjectArrayProperty.ts: -------------------------------------------------------------------------------- 1 | import {ITypedArray} from "../ITypedArray"; 2 | export interface IObjectArrayProperty { 3 | name: string; 4 | type: new (size:number) => ITypedArray; 5 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Queue.ts: -------------------------------------------------------------------------------- 1 | export class Queue { 2 | protected queue: T[] = []; 3 | protected head: number = 0; 4 | protected MAX_QUEUE_SIZE = 1000; 5 | 6 | constructor(MAX_QUEUE_SIZE?: number) { 7 | this.MAX_QUEUE_SIZE = MAX_QUEUE_SIZE; 8 | } 9 | 10 | public enqueue (element: T) { 11 | this.queue.push(element); 12 | } 13 | 14 | public dequeue (): T { 15 | const output = this.queue[this.head]; 16 | this.queue[this.head] = null; 17 | this.head++; 18 | if (this.head >= this.MAX_QUEUE_SIZE) { 19 | this.queue.splice(0, this.head); 20 | this.head = 0; 21 | } 22 | 23 | return output; 24 | } 25 | 26 | public size () { 27 | return this.queue.length - this.head; 28 | } 29 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Sort/bubbleSort.ts: -------------------------------------------------------------------------------- 1 | function bubbleSort(array: T[], comparator: (a: T, b: T) => boolean = (a, b) => a > b) { 2 | if (!Array.isArray(array) || array.length < 2) { 3 | return array; 4 | } 5 | let isNotSorted: boolean = true; 6 | let size: number = array.length - 1; 7 | let temp: T; 8 | while (isNotSorted) { 9 | isNotSorted = false; 10 | for (let i = 0; i < size; i++) { 11 | if (comparator(array[i], array[i + 1])) { 12 | temp = array[i + 1]; 13 | array[i + 1] = array[i]; 14 | array[i] = temp; 15 | isNotSorted = true; 16 | } 17 | } 18 | } 19 | return array; 20 | } 21 | 22 | export default bubbleSort; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Sort/gnomeSort.ts: -------------------------------------------------------------------------------- 1 | function gnomeSort(array: T[], comparator: (a: T, b: T) => boolean = (a, b) => a > b) { 2 | if (!Array.isArray(array) || array.length < 2) { 3 | return array; 4 | } 5 | 6 | let position: number = 0; 7 | let length: number = array.length; 8 | let temp: T = null; 9 | while (position < length) { 10 | if (position === 0 || !comparator(array[position - 1], array[position])) { 11 | position++; 12 | } else { 13 | temp = array[position - 1]; 14 | array[position - 1] = array[position]; 15 | array[position] = temp; 16 | position--; 17 | } 18 | } 19 | return array; 20 | } 21 | 22 | export default gnomeSort; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Sort/index.ts: -------------------------------------------------------------------------------- 1 | import bubbleSort from "./bubbleSort"; 2 | import gnomeSort from "./gnomeSort"; 3 | import insertionSort from "./insertionSort"; 4 | import mergeSort from "./mergeSort"; 5 | import quickSort from "./quickSort"; 6 | import selectionSort from "./selectionSort"; 7 | 8 | const Sort = { 9 | bubbleSort, 10 | gnomeSort, 11 | insertionSort, 12 | mergeSort, 13 | quickSort, 14 | selectionSort 15 | }; 16 | 17 | export default Sort; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Sort/insertionSort.ts: -------------------------------------------------------------------------------- 1 | import SortingComparator from "../CustomTypes/SortingComparator"; 2 | import {Utils} from "../Utils"; 3 | function insertionSort (array: T[], comparator: SortingComparator = Utils.gt, startIndex: number = 0, endIndex: number = -1) { 4 | if (!Array.isArray(array)) { 5 | return array; 6 | } 7 | 8 | if (endIndex === -1) { 9 | endIndex = array.length; 10 | } 11 | 12 | if ((endIndex - startIndex) < 2) { 13 | return array; 14 | } 15 | for (let j = startIndex + 1, length = endIndex; j < length; j++) { 16 | let key = array[j]; 17 | let index = j - 1; 18 | while (index >= startIndex && comparator(array[index], key) ) { 19 | array[index + 1] = array[index]; 20 | index--; 21 | } 22 | array[index + 1] = key; 23 | } 24 | 25 | return array; 26 | } 27 | 28 | export default insertionSort; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Sort/selectionSort.ts: -------------------------------------------------------------------------------- 1 | import {Utils} from "../Utils"; 2 | import SortingComparator from "../CustomTypes/SortingComparator"; 3 | function selectionSort(array: T[], comparator: SortingComparator = Utils.gt) { 4 | if (!Array.isArray(array) || array.length < 2) { 5 | return array; 6 | } 7 | 8 | let position: number = 0; 9 | const arraySize: number = array.length; 10 | while (position < arraySize) { 11 | const lowestIndex: number = Utils.minIndex(array, position, arraySize, comparator); 12 | Utils.swapValues(array, position, lowestIndex); 13 | position++; 14 | } 15 | 16 | return array; 17 | } 18 | 19 | export default selectionSort; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/Stack.ts: -------------------------------------------------------------------------------- 1 | export class Stack { 2 | protected stack:T[] = []; 3 | 4 | public clear ():void { 5 | this.stack.length = 0; 6 | } 7 | 8 | public isEmpty ():boolean { 9 | return this.stack.length === 0; 10 | } 11 | 12 | public search (element:T):number { 13 | const index = this.stack.lastIndexOf(element); 14 | return (index < 0) ? -1 : this.stack.length - 1 - index; 15 | } 16 | 17 | public peek ():T { 18 | if (this.isEmpty()) { 19 | throw new Error('The stack is empty'); 20 | } 21 | return this.stack[this.stack.length - 1]; 22 | } 23 | 24 | public pop ():T { 25 | if (this.isEmpty()) { 26 | throw new Error('The stack is empty'); 27 | } 28 | return this.stack.pop(); 29 | } 30 | 31 | public push (element:T):Stack { 32 | this.stack.push(element); 33 | return this; 34 | } 35 | 36 | public size ():number { 37 | return this.stack.length; 38 | } 39 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/TypedLinkedList.ts: -------------------------------------------------------------------------------- 1 | import {ILinkedList} from "./Interfaces/ILinkedList"; 2 | import {ITypedArray} from "./ITypedArray"; 3 | /*class TypedLinkedList implements ILinkedList { 4 | public list:ITypedArray; 5 | public prevList:ITypedArray; 6 | public nextList:ITypedArray; 7 | 8 | constructor (TypedArray:{new(size): ITypedArray}, size:number) { 9 | this.list = new TypedArray(size); 10 | } 11 | }*/ -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/binarySum.ts: -------------------------------------------------------------------------------- 1 | function binarySum(A:number[], B:number[]) { 2 | var i:number = 0; 3 | var n:number = A.length; 4 | var C:number[] = []; 5 | A = A.slice(0).reverse(); 6 | B = B.slice(0).reverse(); 7 | while (i < n) { 8 | let carryOn = C[i]; 9 | C[i] = A[i] ^ B[i] ^ carryOn; 10 | C[i + 1] = (A[i] & B[i]) | (A[i] & carryOn) | (B[i] & carryOn); 11 | i++; 12 | } 13 | return C.reverse(); 14 | } 15 | 16 | export default binarySum; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/functions/diophantineEquation.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Solves diophantine equation with 2 parameters. 3 | * @param {number} a 4 | * @param {number} b 5 | * @param {number} c 6 | */ 7 | import { greatestCommonDivisor } from "./greatestCommonDivisor"; 8 | import { extendedEuclidesAlgorithm } from "./extendedEuclidesAlgorithm"; 9 | import { IExtendedEuclidesAlgorithmResult } from "../Interfaces/IExtendedEuclidesAlgorithmResult"; 10 | 11 | export function diophantineEquation(a: number, b: number, c: number): number[] { 12 | if (a + b === 0) { 13 | return null; 14 | } 15 | const gcd = greatestCommonDivisor(a, b); 16 | const ratio: number = c / gcd; 17 | if (!Number.isInteger(ratio)) { 18 | return null; 19 | } 20 | const extendedEuclid: IExtendedEuclidesAlgorithmResult = extendedEuclidesAlgorithm(a, b); 21 | return [ratio * extendedEuclid.x, ratio * extendedEuclid.y]; 22 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/functions/greatestCommonDivisor.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Euclid's algorithm for finding the greatest common divisor of two numbers greater than 0 3 | * @param {number} a greater than 0 4 | * @param {number} b greater than 0 5 | */ 6 | export function greatestCommonDivisor(a: number, b: number): number { 7 | if (!Number.isInteger(a) || !Number.isInteger(b)) { 8 | return NaN; 9 | } 10 | if (a === 0 && b === 0) { 11 | return NaN; 12 | } 13 | if (a < 0) { 14 | a = Math.abs(a); 15 | } 16 | if (b < 0) { 17 | b = Math.abs(b); 18 | } 19 | if (a === b) { 20 | return a; 21 | } else if (a < b) { 22 | return greatestCommonDivisorInternal(b, a); 23 | } else { 24 | return greatestCommonDivisorInternal(a, b); 25 | } 26 | } 27 | 28 | function greatestCommonDivisorInternal(a: number, b: number): number { 29 | return b > 0 ? greatestCommonDivisor(b , a % b) : a; 30 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/functions/index.ts: -------------------------------------------------------------------------------- 1 | import {diophantineEquation} from "./diophantineEquation"; 2 | import {diophantineEquationSolver} from "./diophantineEquationSolver"; 3 | import {extendedEuclidesAlgorithm} from "./extendedEuclidesAlgorithm"; 4 | import {greatestCommonDivisor} from "./greatestCommonDivisor"; 5 | import {leastCommonMultiple} from "./leastCommonMultiple"; 6 | 7 | const functions = { 8 | diophantineEquation, 9 | diophantineEquationSolver, 10 | extendedEuclidesAlgorithm, 11 | greatestCommonDivisor, 12 | leastCommonMultiple 13 | }; 14 | export default functions; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/functions/leastCommonMultiple.ts: -------------------------------------------------------------------------------- 1 | import { greatestCommonDivisor } from "./greatestCommonDivisor"; 2 | 3 | /** 4 | * Least common multiple algorithm. If a and b are 0 it is a special cases and 0 will be returned. If one of the number is 0 the other one will be returned. 5 | * @param {number} a 6 | * @param {number} b 7 | */ 8 | export function leastCommonMultiple(a: number, b: number): number { 9 | if (a === 0 && b === 0) { 10 | return 0; 11 | } 12 | if (a === 0) { 13 | return b; 14 | } 15 | if (b === 0) { 16 | return Math.abs(a); 17 | } 18 | return Math.abs(a * b) / greatestCommonDivisor(Math.abs(a), Math.abs(b)) 19 | } -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/ts/linearSearch.ts: -------------------------------------------------------------------------------- 1 | function linearSearch (array:number[], value:number) { 2 | let index:number = null; 3 | let counter = 0; 4 | const arraySize = array.length; 5 | while (counter < arraySize && index === null) { 6 | if (value === array[counter]) { 7 | index = counter; 8 | } 9 | counter++; 10 | } 11 | return index; 12 | } 13 | 14 | export default linearSearch; -------------------------------------------------------------------------------- /data/train/TypeScript-Algorithms-and-Data-Structures-master/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "UMD", 4 | "noImplicitAny": true, 5 | "removeComments": true, 6 | "preserveConstEnums": true, 7 | "outDir": "dist/", 8 | "sourceMap": true, 9 | "declaration": true, 10 | "types": ["jest"], 11 | "target": "ES2017", 12 | }, 13 | "exclude": [ 14 | "node_modules", 15 | "wwwroot", 16 | "dist", 17 | "tests" 18 | ] 19 | } -------------------------------------------------------------------------------- /data/train/algorithms-test/algorithms/math/greatest-difference.ts: -------------------------------------------------------------------------------- 1 | export const greatestDifference = (numbers: number[]) => { 2 | let index = 0; 3 | let largest = numbers[0]; 4 | const length = numbers.length; 5 | let number; 6 | let smallest = numbers[0]; 7 | 8 | for (index; index < length; index++) { 9 | number = numbers[index]; 10 | 11 | if (number > largest) { 12 | largest = number; 13 | } 14 | if (number < smallest) { 15 | smallest = number; 16 | } 17 | } 18 | 19 | return largest - smallest; 20 | }; 21 | -------------------------------------------------------------------------------- /data/train/algorithms-test/algorithms/search/interpolation-search.ts: -------------------------------------------------------------------------------- 1 | import { 2 | biggerEquals, 3 | Compare, 4 | defaultCompare, 5 | defaultEquals, 6 | defaultDiff, 7 | DOES_NOT_EXIST, 8 | lesserEquals 9 | } from '../../util'; 10 | 11 | export function interpolationSearch( 12 | array: T[], 13 | value: T, 14 | compareFn = defaultCompare, 15 | equalsFn = defaultEquals, 16 | diffFn = defaultDiff 17 | ) { 18 | const { length } = array; 19 | let low = 0; 20 | let high = length - 1; 21 | let position = -1; 22 | let delta = -1; 23 | while ( 24 | low <= high && 25 | biggerEquals(value, array[low], compareFn) && 26 | lesserEquals(value, array[high], compareFn) 27 | ) { 28 | delta = diffFn(value, array[low]) / diffFn(array[high], array[low]); 29 | position = low + Math.floor((high - low) * delta); 30 | if (equalsFn(array[position], value)) { 31 | return position; 32 | } 33 | if (compareFn(array[position], value) === Compare.LESS_THAN) { 34 | low = position + 1; 35 | } else { 36 | high = position - 1; 37 | } 38 | } 39 | 40 | return DOES_NOT_EXIST; 41 | } 42 | -------------------------------------------------------------------------------- /data/train/algorithms-test/data-structures/models/value-pair.ts: -------------------------------------------------------------------------------- 1 | export class ValuePair { 2 | constructor(public key: K, public value: V) {} 3 | 4 | toString() { 5 | return `[#${this.key}: ${this.value}]`; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /data/train/algorithms-test/others/balanced-symbols.ts: -------------------------------------------------------------------------------- 1 | import Stack from '../data-structures/stack'; 2 | 3 | export function parenthesesChecker(symbols: string) { 4 | const stack = new Stack(); 5 | const opens = '([{'; 6 | const closers = ')]}'; 7 | let balanced = true; 8 | let index = 0; 9 | let symbol: string; 10 | let top: string; 11 | 12 | while (index < symbols.length && balanced) { 13 | symbol = symbols[index]; 14 | if (opens.indexOf(symbol) >= 0) { 15 | stack.push(symbol); 16 | } else { 17 | if (stack.isEmpty()) { 18 | balanced = false; 19 | } else { 20 | top = stack.pop(); 21 | if (!(opens.indexOf(top) === closers.indexOf(symbol))) { 22 | balanced = false; 23 | } 24 | } 25 | } 26 | index++; 27 | } 28 | return balanced && stack.isEmpty(); 29 | } 30 | -------------------------------------------------------------------------------- /data/train/algorithms-test/others/base-converter.ts: -------------------------------------------------------------------------------- 1 | import Stack from '../data-structures/stack'; 2 | 3 | export function decimalToBinary(decNumber: number) { 4 | const remStack = new Stack(); 5 | let rem: number; 6 | let binaryString = ''; 7 | 8 | while (decNumber > 0) { 9 | rem = Math.floor(decNumber % 2); 10 | remStack.push(rem); 11 | decNumber = Math.floor(decNumber / 2); 12 | } 13 | 14 | while (!remStack.isEmpty()) { 15 | binaryString += remStack.pop().toString(); 16 | } 17 | 18 | return binaryString; 19 | } 20 | 21 | export function baseConverter(decNumber: number, base: number) { 22 | const remStack = new Stack(); 23 | const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 24 | let rem: number; 25 | let baseString = ''; 26 | 27 | if (!(base >= 2 && base <= 36)) { 28 | return ''; 29 | } 30 | 31 | while (decNumber > 0) { 32 | rem = Math.floor(decNumber % base); 33 | remStack.push(rem); 34 | decNumber = Math.floor(decNumber / base); 35 | } 36 | 37 | while (!remStack.isEmpty()) { 38 | baseString += digits[remStack.pop()]; 39 | } 40 | 41 | return baseString; 42 | } 43 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/dynamic-programing/knapsack-recursive.ts: -------------------------------------------------------------------------------- 1 | export function knapSack(capacity: number, weights: number[], values: number[], n: number): number { 2 | if (n === 0 || capacity === 0) { 3 | return 0; 4 | } 5 | 6 | if (weights[n - 1] > capacity) { 7 | return knapSack(capacity, weights, values, n - 1); 8 | } else { 9 | const a: number = values[n - 1] + knapSack(capacity - weights[n - 1], weights, values, n - 1); 10 | const b: number = knapSack(capacity, weights, values, n - 1); 11 | return a > b ? a : b; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/dynamic-programing/longest-common-subsequence.ts: -------------------------------------------------------------------------------- 1 | export function lcs(wordX: string, wordY: string) { 2 | const m = wordX.length; 3 | const n = wordY.length; 4 | const l: Array> = []; 5 | 6 | for (let i = 0; i <= m; i++) { 7 | l[i] = []; 8 | for (let j = 0; j <= n; j++) { 9 | l[i][j] = 0; 10 | } 11 | } 12 | 13 | for (let i = 0; i <= m; i++) { 14 | for (let j = 0; j <= n; j++) { 15 | if (i === 0 || j === 0) { 16 | l[i][j] = 0; 17 | } else if (wordX[i - 1] === wordY[j - 1]) { 18 | l[i][j] = l[i - 1][j - 1] + 1; 19 | } else { 20 | const a = l[i - 1][j]; 21 | const b = l[i][j - 1]; 22 | l[i][j] = a > b ? a : b; // max(a,b) 23 | } 24 | } 25 | // console.log(l[i].join()); 26 | } 27 | 28 | return l[m][n]; 29 | } 30 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/dynamic-programing/min-coin-change.ts: -------------------------------------------------------------------------------- 1 | export function minCoinChange(coins: number[], amount: number) { 2 | const cache: Array> = []; 3 | 4 | // tslint:disable-next-line:no-shadowed-variable 5 | const makeChange = function(amount: number) { 6 | if (!amount) { 7 | return []; 8 | } 9 | if (cache[amount]) { 10 | return cache[amount]; 11 | } 12 | let min: number[] = [], 13 | newMin, 14 | newAmount; 15 | for (let i = 0; i < coins.length; i++) { 16 | const coin = coins[i]; 17 | newAmount = amount - coin; 18 | if (newAmount >= 0) { 19 | newMin = makeChange(newAmount); 20 | } 21 | if ( 22 | newAmount >= 0 && 23 | (newMin.length < min.length - 1 || !min.length) && 24 | (newMin.length || !newAmount) 25 | ) { 26 | min = [coin].concat(newMin); 27 | // console.log('new Min ' + min + ' for ' + amount); 28 | } 29 | } 30 | return (cache[amount] = min); 31 | }; 32 | 33 | return makeChange(amount); 34 | } 35 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/graph/dijkstra.ts: -------------------------------------------------------------------------------- 1 | const INF = Number.MAX_SAFE_INTEGER; 2 | 3 | const minDistance = (dist: number[], visited: boolean[]) => { 4 | let min = INF; 5 | let minIndex = -1; 6 | 7 | for (let v = 0; v < dist.length; v++) { 8 | if (visited[v] === false && dist[v] <= min) { 9 | min = dist[v]; 10 | minIndex = v; 11 | } 12 | } 13 | 14 | return minIndex; 15 | }; 16 | 17 | export const dijkstra = (graph: number[][], src: number) => { 18 | const dist: number[] = []; 19 | const visited: boolean[] = []; 20 | const length = graph.length; 21 | 22 | for (let i = 0; i < length; i++) { 23 | dist[i] = INF; 24 | visited[i] = false; 25 | } 26 | 27 | dist[src] = 0; 28 | 29 | for (let i = 0; i < length - 1; i++) { 30 | const u = minDistance(dist, visited); 31 | 32 | visited[u] = true; 33 | 34 | for (let v = 0; v < length; v++) { 35 | if (!visited[v] && graph[u][v] !== 0 && dist[u] !== INF && dist[u] + graph[u][v] < dist[v]) { 36 | dist[v] = dist[u] + graph[u][v]; 37 | } 38 | } 39 | } 40 | 41 | return dist; 42 | }; 43 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/graph/floyd-warshall.ts: -------------------------------------------------------------------------------- 1 | export const floydWarshall = (graph: number[][]) => { 2 | const dist: number[][] = []; 3 | const length = graph.length; 4 | 5 | for (let i = 0; i < length; i++) { 6 | dist[i] = []; 7 | for (let j = 0; j < length; j++) { 8 | if (i === j) { 9 | dist[i][j] = 0; 10 | } else if (!isFinite(graph[i][j])) { 11 | dist[i][j] = Infinity; 12 | } else { 13 | dist[i][j] = graph[i][j]; 14 | } 15 | } 16 | } 17 | 18 | for (let k = 0; k < length; k++) { 19 | for (let i = 0; i < length; i++) { 20 | for (let j = 0; j < length; j++) { 21 | if (dist[i][k] + dist[k][j] < dist[i][j]) { 22 | dist[i][j] = dist[i][k] + dist[k][j]; 23 | } 24 | } 25 | } 26 | } 27 | 28 | return dist; 29 | }; 30 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/graph/prim.ts: -------------------------------------------------------------------------------- 1 | const INF = Number.MAX_SAFE_INTEGER; 2 | 3 | const minKey = (graph: number[][], key: number[], visited: boolean[]) => { 4 | // Initialize min value 5 | let min = INF; 6 | let minIndex = 0; 7 | 8 | for (let v = 0; v < graph.length; v++) { 9 | if (visited[v] === false && key[v] < min) { 10 | min = key[v]; 11 | minIndex = v; 12 | } 13 | } 14 | 15 | return minIndex; 16 | }; 17 | 18 | export const prim = (graph: number[][]) => { 19 | const parent: number[] = []; 20 | const key: number[] = []; 21 | const visited: boolean[] = []; 22 | const length = graph.length; 23 | 24 | for (let i = 0; i < length; i++) { 25 | key[i] = INF; 26 | visited[i] = false; 27 | } 28 | 29 | key[0] = 0; 30 | parent[0] = -1; 31 | 32 | for (let i = 0; i < length - 1; i++) { 33 | const u = minKey(graph, key, visited); 34 | visited[u] = true; 35 | 36 | for (let v = 0; v < length; v++) { 37 | if (graph[u][v] && visited[v] === false && graph[u][v] < key[v]) { 38 | parent[v] = u; 39 | key[v] = graph[u][v]; 40 | } 41 | } 42 | } 43 | 44 | return parent; 45 | }; 46 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/greedy/knapsack.ts: -------------------------------------------------------------------------------- 1 | export function knapSack(capacity: number, weights: number[], values: number[]) { 2 | const n = values.length; 3 | let load = 0; 4 | let val = 0; 5 | 6 | for (let i = 0; i < n && load < capacity; i++) { 7 | if (weights[i] <= capacity - load) { 8 | val += values[i]; 9 | load += weights[i]; 10 | // console.log('using item ' + (i + 1) + ' for the solution'); 11 | } else { 12 | const r = (capacity - load) / weights[i]; 13 | val += r * values[i]; 14 | load += weights[i]; 15 | // console.log('using ratio of ' + r + ' for item ' + (i + 1) + ' for the solution'); 16 | } 17 | } 18 | return val; 19 | } 20 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/greedy/longest-common-subsequence.ts: -------------------------------------------------------------------------------- 1 | export function lcs(wordX: string, wordY: string, m = wordX.length, n = wordY.length): number { 2 | if (m === 0 || n === 0) { 3 | return 0; 4 | } 5 | 6 | if (wordX[m - 1] === wordY[n - 1]) { 7 | return 1 + lcs(wordX, wordY, m - 1, n - 1); 8 | } else { 9 | const a = lcs(wordX, wordY, m, n - 1); 10 | const b = lcs(wordX, wordY, m - 1, n); 11 | return a > b ? a : b; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/greedy/matrix-chain-multiplication.ts: -------------------------------------------------------------------------------- 1 | export function matrixChainOrder(p: number[], i = 1, j = p.length - 1): number { 2 | if (i === j) { 3 | return 0; 4 | } 5 | 6 | let min = Number.MAX_SAFE_INTEGER; 7 | 8 | for (let k = i; k < j; k++) { 9 | const count = 10 | matrixChainOrder(p, i, k) + matrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; 11 | 12 | if (count < min) { 13 | min = count; 14 | } 15 | } 16 | 17 | return min; 18 | } 19 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/greedy/min-coin-change.ts: -------------------------------------------------------------------------------- 1 | export function minCoinChange(coins: number[], amount: number) { 2 | const change: number[] = []; 3 | let total = 0; 4 | for (let i = coins.length; i >= 0; i--) { 5 | const coin = coins[i]; 6 | while (total + coin <= amount) { 7 | change.push(coin); 8 | total += coin; 9 | } 10 | } 11 | return change; 12 | } 13 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/math/find-divisors.ts: -------------------------------------------------------------------------------- 1 | export const findDivisors = (num: number) => { 2 | const divisors = []; 3 | 4 | const sqrt = Math.floor(Math.sqrt(num)); 5 | 6 | for (let i = 1; i <= sqrt; i++) { 7 | if (num % i === 0) { 8 | divisors.push(i); 9 | if (i !== sqrt) { 10 | divisors.push(Math.floor(num / i)); 11 | } 12 | } 13 | } 14 | 15 | if (num >= 2 && !divisors.includes(num)) { 16 | divisors.push(num); 17 | } 18 | 19 | divisors.sort((a, b) => a - b); 20 | 21 | return divisors; 22 | }; 23 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/math/gcd.ts: -------------------------------------------------------------------------------- 1 | export const gcd = (num1: number, num2: number): number => { 2 | if (num1 === 0 || num2 === 0) { 3 | return 0; 4 | } 5 | if (num1 === num2) { 6 | return num1; 7 | } 8 | if (num1 > num2) { 9 | return gcd(num1 - num2, num2); 10 | } 11 | return gcd(num1, num2 - num1); 12 | }; 13 | 14 | export let a = 5; 15 | export function test(){} 16 | 17 | export const gcdArray = (num: number[]) => { 18 | let result = num[0]; 19 | 20 | for (let i = 1; i < num.length; i++) { 21 | result = gcd(num[i], result); 22 | } 23 | 24 | return result; 25 | }; 26 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/math/lcm.ts: -------------------------------------------------------------------------------- 1 | import { gcd } from './gcd'; 2 | 3 | export const lcm = (num1: number, num2: number) => { 4 | if (num1 === 0 || num2 === 0) { 5 | return 0; 6 | } 7 | num1 = Math.abs(num1); 8 | num2 = Math.abs(num2); 9 | return (num1 * num2) / gcd(num1, num2); 10 | }; 11 | 12 | export const lcmArray = (num: number[]) => { 13 | let result = num[0]; 14 | 15 | for (let i = 1; i < num.length; i++) { 16 | result = num[i] * result / gcd(num[i], result); 17 | } 18 | 19 | return result; 20 | }; 21 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/math/primality-test.ts: -------------------------------------------------------------------------------- 1 | export const isPrime = (n: number) => { 2 | if (n <= 1) { 3 | return false; 4 | } 5 | 6 | const sqrt = Math.floor(Math.sqrt(n)); 7 | for (let i = 2; i <= sqrt; i++) { 8 | if (n % i === 0) { 9 | return false; 10 | } 11 | } 12 | 13 | return true; 14 | }; 15 | 16 | export const testPrime = (n: number) => { 17 | if (n <= 1) { 18 | return false; 19 | } else { 20 | if (n === 2 || n === 3) { 21 | return true; 22 | } else if (n % 2 === 0) { 23 | return false; 24 | } else { 25 | const sqrt = Math.floor(Math.sqrt(n)); 26 | for (let i = 3; i <= sqrt; i += 2) { 27 | if (n % i === 0) { 28 | return false; 29 | } 30 | } 31 | } 32 | } 33 | return true; 34 | }; 35 | 36 | // tslint:disable-next-line:max-line-length 37 | export const isPrime2 = (n: number) => (n >= 2) ? (![...Array(n).keys()].slice(2).map(i => !(n % i)).includes(true) && ![0, 1].includes(n)) : false; 38 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/math/sieve-eratosthenes.ts: -------------------------------------------------------------------------------- 1 | export const sieveOfEratosthenes = (n: number) => { 2 | 3 | const sieve: boolean[] = []; 4 | const primes: number[] = []; 5 | 6 | sieve[1] = false; 7 | 8 | for (let i = 2; i <= n; i++) { 9 | sieve[i] = true; 10 | } 11 | 12 | for (let p = 2; p * p <= n; p++) { 13 | if (sieve[p]) { 14 | for (let i = p * 2; i <= n; i += p) { 15 | sieve[i] = false; 16 | } 17 | } 18 | } 19 | 20 | sieve.forEach((value, index) => { 21 | if (value) { 22 | primes.push(index); 23 | } 24 | }, primes); 25 | 26 | return primes; 27 | }; 28 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/search/binary-search-recursive.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, DOES_NOT_EXIST } from '../../util'; 2 | import { quickSort } from '../sorting/quicksort'; 3 | 4 | function binarySearchRecursive( 5 | array: T[], 6 | value: T, 7 | low: number, 8 | high: number, 9 | compareFn = defaultCompare 10 | ): number { 11 | if (low <= high) { 12 | const mid = Math.floor((low + high) / 2); 13 | const element = array[mid]; 14 | 15 | if (compareFn(element, value) === Compare.LESS_THAN) { 16 | return binarySearchRecursive(array, value, mid + 1, high, compareFn); 17 | } else if (compareFn(element, value) === Compare.BIGGER_THAN) { 18 | return binarySearchRecursive(array, value, low, mid - 1, compareFn); 19 | } else { 20 | return mid; 21 | } 22 | } 23 | return DOES_NOT_EXIST; 24 | } 25 | 26 | export function binarySearch(array: T[], value: T, compareFn = defaultCompare) { 27 | const sortedArray = quickSort(array); 28 | const low = 0; 29 | const high = sortedArray.length - 1; 30 | 31 | return binarySearchRecursive(array, value, low, high, compareFn); 32 | } 33 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/search/binary-search.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, DOES_NOT_EXIST } from '../../util'; 2 | import { quickSort } from '../sorting/quicksort'; 3 | 4 | export function binarySearch (array: T[], value: T, compareFn = defaultCompare) { 5 | const sortedArray = quickSort(array); 6 | let low = 0; 7 | let high = sortedArray.length - 1; 8 | 9 | while (low <= high) { 10 | const mid = Math.floor((low + high) / 2); 11 | const element = sortedArray[mid]; 12 | // console.log('mid element is ' + element); 13 | if (compareFn(element, value) === Compare.LESS_THAN) { 14 | low = mid + 1; 15 | // console.log('low is ' + low); 16 | } else if (compareFn(element, value) === Compare.BIGGER_THAN) { 17 | high = mid - 1; 18 | // console.log('high is ' + high); 19 | } else { 20 | // console.log('found it'); 21 | return mid; 22 | } 23 | } 24 | return DOES_NOT_EXIST; 25 | } 26 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/search/min-max-search.ts: -------------------------------------------------------------------------------- 1 | import { defaultCompare, Compare } from '../../util'; 2 | 3 | export function findMaxValue(array: T[], compareFn = defaultCompare) { 4 | if (array && array.length > 0) { 5 | let max = array[0]; 6 | for (let i = 1; i < array.length; i++) { 7 | if (compareFn(max, array[i]) === Compare.LESS_THAN) { 8 | max = array[i]; 9 | } 10 | } 11 | return max; 12 | } 13 | return undefined; 14 | } 15 | 16 | export function findMinValue(array: T[], compareFn = defaultCompare) { 17 | if (array && array.length > 0) { 18 | let min = array[0]; 19 | for (let i = 1; i < array.length; i++) { 20 | if (compareFn(min, array[i]) === Compare.BIGGER_THAN) { 21 | min = array[i]; 22 | } 23 | } 24 | return min; 25 | } 26 | return undefined; 27 | } 28 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/search/sequential-search.ts: -------------------------------------------------------------------------------- 1 | import { defaultEquals, DOES_NOT_EXIST, IEqualsFunction } from '../../util'; 2 | 3 | export function sequentialSearch(array: T[], value: T, equalsFn: IEqualsFunction = defaultEquals) { 4 | for (let i = 0; i < array.length; i++) { 5 | if (equalsFn(value, array[i])) { 6 | return i; 7 | } 8 | } 9 | return DOES_NOT_EXIST; 10 | } 11 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/shuffle/fisher–yates.ts: -------------------------------------------------------------------------------- 1 | import { swap } from '../../util'; 2 | 3 | export function shuffle(array: T[]) { 4 | for (let i = array.length - 1; i > 0; i--) { 5 | const randomIndex = Math.floor(Math.random() * (i + 1)); 6 | swap(array, i, randomIndex); 7 | } 8 | 9 | return array; 10 | } 11 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/sorting/bubble-sort-improved.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, swap } from '../../util'; 2 | 3 | export function modifiedBubbleSort(array: T[], compareFn = defaultCompare) { 4 | const { length } = array; 5 | 6 | for (let i = 0; i < length; i++) { 7 | // console.log('--- '); 8 | for (let j = 0; j < length - 1 - i; j++) { 9 | // console.log('compare ' + array[j] + ' with ' + array[j + 1]); 10 | if (compareFn(array[j], array[j + 1]) === Compare.BIGGER_THAN) { 11 | // console.log('swap ' + array[j] + ' with ' + array[j + 1]); 12 | swap(array, j, j + 1); 13 | } 14 | } 15 | } 16 | 17 | return array; 18 | } 19 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/sorting/bubble-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, swap } from '../../util'; 2 | 3 | export function bubbleSort(array: T[], compareFn = defaultCompare) { 4 | const { length } = array; 5 | 6 | for (let i = 0; i < length; i++) { 7 | // console.log('--- '); 8 | for (let j = 0; j < length - 1; j++) { 9 | // console.log('compare ' + array[j] + ' with ' + array[j + 1]); 10 | if (compareFn(array[j], array[j + 1]) === Compare.BIGGER_THAN) { 11 | // console.log('swap ' + array[j] + ' with ' + array[j + 1]); 12 | swap(array, j, j + 1); 13 | } 14 | } 15 | } 16 | 17 | return array; 18 | } 19 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/sorting/counting-sort.ts: -------------------------------------------------------------------------------- 1 | import { findMaxValue } from '../search/min-max-search'; 2 | 3 | export function countingSort(array: number[]) { 4 | 5 | if (array.length < 2) { 6 | return array; 7 | } 8 | 9 | const maxValue = findMaxValue(array); 10 | let sortedIndex = 0; 11 | const counts = new Array(maxValue + 1); 12 | 13 | array.forEach(element => { 14 | if (!counts[element]) { 15 | counts[element] = 0; 16 | } 17 | counts[element]++; 18 | }); 19 | 20 | // console.log('Frequencies: ' + counts.join()); 21 | 22 | counts.forEach((element, i) => { 23 | while (element > 0) { 24 | array[sortedIndex++] = i; 25 | element--; 26 | } 27 | }); 28 | 29 | return array; 30 | } 31 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/sorting/insertion-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare } from '../../util'; 2 | 3 | export const insertionSort = (array: any[], compareFn = defaultCompare) => { 4 | const { length } = array; 5 | let temp; 6 | for (let i = 1; i < length; i++) { 7 | let j = i; 8 | temp = array[i]; 9 | // console.log('to be inserted ' + temp); 10 | while (j > 0 && compareFn(array[j - 1], temp) === Compare.BIGGER_THAN) { 11 | // console.log('shift ' + array[j - 1]); 12 | array[j] = array[j - 1]; 13 | j--; 14 | } 15 | // console.log('insert ' + temp); 16 | array[j] = temp; 17 | } 18 | 19 | return array; 20 | }; 21 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/sorting/merge-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, ICompareFunction } from '../../util'; 2 | 3 | function merge(left: T[], right: T[], compareFn: ICompareFunction) { 4 | let i = 0; 5 | let j = 0; 6 | const result = []; 7 | 8 | while (i < left.length && j < right.length) { 9 | result.push(compareFn(left[i], right[j]) === Compare.LESS_THAN ? left[i++] : right[j++]); 10 | } 11 | 12 | return result.concat(i < left.length ? left.slice(i) : right.slice(j)); 13 | } 14 | 15 | export function mergeSort(array: T[], compareFn = defaultCompare): T[] { 16 | if (array.length > 1) { 17 | const { length } = array; 18 | const middle = Math.floor(length / 2); 19 | const left = mergeSort(array.slice(0, middle), compareFn); 20 | const right = mergeSort(array.slice(middle, length), compareFn); 21 | array = merge(left, right, compareFn); 22 | } 23 | 24 | return array; 25 | } 26 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/sorting/selection-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, swap } from '../../util'; 2 | 3 | export const selectionSort = (array: any[], compareFn = defaultCompare) => { 4 | const { length } = array; 5 | let indexMin; 6 | 7 | for (let i = 0; i < length - 1; i++) { 8 | indexMin = i; 9 | // console.log('index ' + array[i]); 10 | for (let j = i; j < length; j++) { 11 | if (compareFn(array[indexMin], array[j]) === Compare.BIGGER_THAN) { 12 | // console.log('new index min ' + array[j]); 13 | indexMin = j; 14 | } 15 | } 16 | if (i !== indexMin) { 17 | // console.log('swap ' + array[i] + ' with ' + array[indexMin]); 18 | swap(array, i, indexMin); 19 | } 20 | } 21 | 22 | return array; 23 | }; 24 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/sorting/shell-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare } from '../../util'; 2 | 3 | export function shellSort(array: T[], compareFn = defaultCompare) { 4 | let increment = array.length / 2; 5 | while (increment > 0) { 6 | for (let i = increment; i < array.length; i++) { 7 | let j = i; 8 | const temp = array[i]; 9 | 10 | while (j >= increment && compareFn(array[j - increment], temp) === Compare.BIGGER_THAN) { 11 | array[j] = array[j - increment]; 12 | j = j - increment; 13 | } 14 | 15 | array[j] = temp; 16 | } 17 | 18 | if (increment === 2) { 19 | increment = 1; 20 | } else { 21 | increment = Math.floor(increment * 5 / 11); 22 | } 23 | } 24 | return array; 25 | } 26 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/string/brute-force.ts: -------------------------------------------------------------------------------- 1 | const stringSearch = (text: string, pattern: string) => { 2 | const n = text.length; 3 | const m = pattern.length; 4 | 5 | if (m > n) { 6 | return -1; 7 | } 8 | 9 | for (let i = 0; i < n; i++) { 10 | let j = 0; 11 | for (j = 0; j < m && (i + j) < n; j++) { 12 | if (text.charAt(i + j) !== pattern.charAt(j)) { 13 | break; 14 | } 15 | } 16 | if (j === m) { 17 | return i; 18 | } 19 | } 20 | 21 | return -1; 22 | }; 23 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/string/huffman.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/data/train/algorithms-train/algorithms/string/huffman.ts -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/string/knuth-morris-pratt.ts: -------------------------------------------------------------------------------- 1 | const buildTable = (pattern: string) => { 2 | const length = pattern.length; 3 | const table = []; 4 | let position = 2; 5 | let cnd = 0; 6 | 7 | table[0] = -1; 8 | table[1] = 0; 9 | 10 | while (position < length) { 11 | if (pattern[position - 1] === pattern[cnd]) { 12 | table[position++] = ++cnd; 13 | } else if (cnd > 0) { 14 | cnd = table[cnd]; 15 | } else { 16 | table[position++] = 0; 17 | } 18 | } 19 | 20 | return table; 21 | }; 22 | 23 | const knuthMorrisPratt = (text: string, pattern: string) => { 24 | const textLength = text.length; 25 | const patternLength = pattern.length; 26 | let m = 0; 27 | let i = 0; 28 | const table = buildTable(pattern); 29 | 30 | while (m + i < textLength) { 31 | if (pattern[i] === text[m + i]) { 32 | if (i === patternLength - 1) { 33 | return m; 34 | } 35 | i++; 36 | } else if (table[i] >= 0) { 37 | i = table[i]; 38 | m = m + i - table[i]; 39 | } else { 40 | i = 0; 41 | m++; 42 | } 43 | } 44 | 45 | return textLength; 46 | }; 47 | -------------------------------------------------------------------------------- /data/train/algorithms-train/algorithms/string/longest-common-substring.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/data/train/algorithms-train/algorithms/string/longest-common-substring.ts -------------------------------------------------------------------------------- /data/train/algorithms-train/data-structures/models/linked-list-models.ts: -------------------------------------------------------------------------------- 1 | export class Node { 2 | constructor(public element: T, public next?: Node) {} 3 | } 4 | 5 | export class DoublyNode extends Node { 6 | constructor( 7 | public element: T, 8 | public next?: DoublyNode, 9 | public prev?: DoublyNode 10 | ) { 11 | super(element, next); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /data/train/algorithms-train/data-structures/models/node.ts: -------------------------------------------------------------------------------- 1 | export class Node { 2 | left: Node; 3 | right: Node; 4 | 5 | constructor(public key: K) {} 6 | 7 | toString() { 8 | return `${this.key}`; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /data/train/algorithms-train/data-structures/models/red-black-node.ts: -------------------------------------------------------------------------------- 1 | import { Node } from './node'; 2 | 3 | export enum Colors { 4 | RED = 0, 5 | BLACK = 1 6 | } 7 | 8 | export class RedBlackNode extends Node { 9 | left: RedBlackNode; 10 | right: RedBlackNode; 11 | parent: RedBlackNode; 12 | color: Colors; 13 | 14 | constructor(public key: K) { 15 | super(key); 16 | this.color = Colors.RED; 17 | } 18 | 19 | isRed() { 20 | return this.color === Colors.RED; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /data/train/algorithms-train/data-structures/models/value-pair-lazy.ts: -------------------------------------------------------------------------------- 1 | import { ValuePair } from './value-pair'; 2 | 3 | export class ValuePairLazy extends ValuePair { 4 | constructor(public key: K, public value: V, public isDeleted = false) { 5 | super(key, value); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /data/train/algorithms-train/data-structures/models/value-pair.ts: -------------------------------------------------------------------------------- 1 | export class ValuePair { 2 | constructor(public key: K, public value: V) {} 3 | 4 | toString() { 5 | return `[#${this.key}: ${this.value}]`; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /data/train/algorithms-train/data-structures/stack-array.ts: -------------------------------------------------------------------------------- 1 | export default class StackArray { 2 | private items: T[]; 3 | 4 | constructor() { 5 | this.items = []; 6 | } 7 | 8 | push(element: T) { 9 | this.items.push(element); 10 | } 11 | 12 | pop() { 13 | return this.items.pop(); 14 | } 15 | 16 | peek() { 17 | return this.items[this.items.length - 1]; 18 | } 19 | 20 | isEmpty() { 21 | return this.items.length === 0; 22 | } 23 | 24 | size() { 25 | return this.items.length; 26 | } 27 | 28 | clear() { 29 | this.items = []; 30 | } 31 | 32 | toArray() { 33 | return this.items; 34 | } 35 | 36 | toString() { 37 | return this.items.toString(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /data/train/algorithms-train/data-structures/stack-linked-list.ts: -------------------------------------------------------------------------------- 1 | import DoublyLinkedList from './doubly-linked-list'; 2 | 3 | export default class StackLinkedList { 4 | private items: DoublyLinkedList; 5 | 6 | constructor() { 7 | this.items = new DoublyLinkedList(); 8 | } 9 | 10 | push(element: T) { 11 | this.items.push(element); 12 | } 13 | 14 | pop() { 15 | if (this.isEmpty()) { 16 | return undefined; 17 | } 18 | const result = this.items.removeAt(this.size() - 1); 19 | return result; 20 | } 21 | 22 | peek() { 23 | if (this.isEmpty()) { 24 | return undefined; 25 | } 26 | return this.items.getElementAt(this.size() - 1).element; 27 | } 28 | 29 | isEmpty() { 30 | return this.items.isEmpty(); 31 | } 32 | 33 | size() { 34 | return this.items.size(); 35 | } 36 | 37 | clear() { 38 | this.items.clear(); 39 | } 40 | 41 | toString() { 42 | return this.items.toString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /data/train/algorithms-train/others/factorial.ts: -------------------------------------------------------------------------------- 1 | export function factorialIterative(number: number) { 2 | if (number < 0) { 3 | return undefined; 4 | } 5 | let total = 1; 6 | for (let n = number; n > 1; n--) { 7 | total *= n; 8 | } 9 | return total; 10 | } 11 | 12 | export function factorial(n: number): number { 13 | if (n < 0) { 14 | return undefined; 15 | } 16 | if (n === 1 || n === 0) { 17 | return 1; 18 | } 19 | return n * factorial(n - 1); 20 | } 21 | -------------------------------------------------------------------------------- /data/train/algorithms-train/others/fibonacci.ts: -------------------------------------------------------------------------------- 1 | export function fibonacci(n: number): number { 2 | if (n < 1) { return 0; } // {1} 3 | if (n <= 2) { return 1; } // {2} 4 | return fibonacci(n - 1) + fibonacci(n - 2); // {3} 5 | } 6 | 7 | export function fibonacciIterative(n: number) { 8 | if (n < 1) { return 0; } 9 | let fibNMinus2 = 0; 10 | let fibNMinus1 = 1; 11 | let fibN = n; 12 | for (let i = 2; i <= n; i++) { 13 | // n >= 2 14 | fibN = fibNMinus1 + fibNMinus2; // f(n-1) + f(n-2) 15 | fibNMinus2 = fibNMinus1; 16 | fibNMinus1 = fibN; 17 | } 18 | return fibN; 19 | } 20 | 21 | export function fibonacciMemoization(n: number) { 22 | if (n < 1) { return 0; } 23 | const memo = [0, 1]; 24 | const fibonacciMem = (num: number): number => { 25 | if (memo[num] != null) { return memo[num]; } 26 | return (memo[num] = fibonacciMem(num - 1) + fibonacciMem(num - 2)); 27 | }; 28 | return fibonacciMem(n); 29 | } 30 | -------------------------------------------------------------------------------- /data/train/algorithms-train/others/hot-potato.ts: -------------------------------------------------------------------------------- 1 | import Queue from '../data-structures/queue'; 2 | 3 | export function hotPotato(elementsList: any[], num: number) { 4 | const queue = new Queue(); 5 | const elimitatedList = []; 6 | 7 | for (let i = 0; i < elementsList.length; i++) { 8 | queue.enqueue(elementsList[i]); 9 | } 10 | 11 | while (queue.size() > 1) { 12 | for (let i = 0; i < num; i++) { 13 | queue.enqueue(queue.dequeue()); 14 | } 15 | elimitatedList.push(queue.dequeue()); 16 | } 17 | 18 | return { 19 | elimitated: elimitatedList, 20 | winner: queue.dequeue() 21 | }; 22 | } 23 | -------------------------------------------------------------------------------- /data/train/algorithms-train/others/palindrome-checker.ts: -------------------------------------------------------------------------------- 1 | import Deque from '../data-structures/deque'; 2 | 3 | export function palindromeChecker(aString: string) { 4 | 5 | if (aString === undefined || aString === null || 6 | (aString !== null && aString.length === 0)) { 7 | return false; 8 | } 9 | 10 | const deque = new Deque(); 11 | const lowerString = aString.toLocaleLowerCase().split(' ').join(''); 12 | let firstChar: string, lastChar: string; 13 | 14 | for (let i = 0; i < lowerString.length; i++) { 15 | deque.addBack(lowerString.charAt(i)); 16 | } 17 | 18 | while (deque.size() > 1) { 19 | firstChar = deque.removeFront(); 20 | lastChar = deque.removeBack(); 21 | if (firstChar !== lastChar) { 22 | return false; 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | -------------------------------------------------------------------------------- /data/train/mojiito-master/.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 2 9 | end_of_line = lf 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | 13 | [*.md] 14 | insert_final_newline = false 15 | trim_trailing_whitespace = false 16 | 17 | [*.{diff,md}] 18 | trim_trailing_whitespace = false 19 | -------------------------------------------------------------------------------- /data/train/mojiito-master/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | 7 | # dependencies 8 | /node_modules 9 | 10 | # IDEs and editors 11 | /.idea 12 | /.vscode 13 | .project 14 | .classpath 15 | *.launch 16 | .settings/ 17 | 18 | # misc 19 | /.sass-cache 20 | /connect.lock 21 | /coverage/* 22 | /libpeerconnection.log 23 | npm-debug.log 24 | testem.log 25 | /typings 26 | 27 | # e2e 28 | /e2e/*.js 29 | /e2e/*.map 30 | 31 | #System Files 32 | .DS_Store 33 | Thumbs.db 34 | -------------------------------------------------------------------------------- /data/train/mojiito-master/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Copyright (c) 2017 Thomas Pink and Mojiito contributors 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of 5 | this software and associated documentation files (the "Software"), to deal in 6 | the Software without restriction, including without limitation the rights to 7 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 8 | of the Software, and to permit persons to whom the Software is furnished to do 9 | so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. 21 | -------------------------------------------------------------------------------- /data/train/mojiito-master/docs/README.md: -------------------------------------------------------------------------------- 1 | # Docs 2 | 3 | **Note:** This Documentation is 'work in progress' 4 | 5 | ## Topics 6 | * [Getting Started](./getting-started.md) 7 | * [Components](./components.md) 8 | -------------------------------------------------------------------------------- /data/train/mojiito-master/docs/bindings.md: -------------------------------------------------------------------------------- 1 | # Bindings & Events 2 | *TODO* 3 | 4 | [angular.io/docs/ts/latest/guide/template-syntax.html](https://angular.io/docs/ts/latest/guide/template-syntax.html) 5 | -------------------------------------------------------------------------------- /data/train/mojiito-master/docs/components.md: -------------------------------------------------------------------------------- 1 | # Components 2 | 3 | Mojiito is made up of *components*. Components are the basic building blocks and are a combination of an element (with its subtree of nodes) and a javascript class. Let's look at the example below: 4 | ```ts 5 | import {Component} from 'mojiito-core'; 6 | 7 | @Component({ 8 | selector: 'body' 9 | }) 10 | export class AppComponent { 11 | } 12 | ``` 13 | 14 | As you can see we have declared a normal javascript class called `AppComponent`. To transform this class into a component we need to it wrap with a `Component` decorator function. This `@Component` function takes a metadata object as a parameter which enhances the class with additional information Mojiito needs create instances. 15 | 16 | The most basic metadata object has a `selector` property. Mojiito uses it to finde matching elements in the DOM and creating instances of that component for every found element. Every component needs a least a `selector`, the other metadata properties are optional. 17 | -------------------------------------------------------------------------------- /data/train/mojiito-master/docs/dependency-injection.md: -------------------------------------------------------------------------------- 1 | # Dependency Injection (DI) 2 | 3 | Mojiitos dependency injection is basically the same as in Angular. For more detailed information look at [their documentation](https://angular.io/docs/ts/latest/guide/dependency-injection.html). 4 | 5 | ## Mojiito dependency injection 6 | 7 | Mojiito ships with Angulars dependency injection. 8 | 9 | *TODO* 10 | 11 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/README.md: -------------------------------------------------------------------------------- 1 | 8 | The sources for this package are in the main [Mojiito](https://github.com/mojiito/mojiito) repo. Please file issues and pull requests against that repo. 9 | 10 | License: MIT -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/index.ts: -------------------------------------------------------------------------------- 1 | // This file is not used to build this module. It is only used during editing 2 | // by the TypeScript language service and during build for verification. `ngc` 3 | // replaces this file with production index.ts when it rewrites private symbol 4 | // names. 5 | 6 | export * from './public_api'; 7 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mojiito-core", 3 | "version": "0.0.0-PLACEHOLDER", 4 | "description": "Mojiito Core", 5 | "main": "./bundles/core.umd.js", 6 | "module": "./mojiito/core.es5.js", 7 | "es2015": "./mojiito/core.js", 8 | "typings": "./core.d.ts", 9 | "author": "Mojiito Team", 10 | "license": "MIT", 11 | "peerDependencies": { }, 12 | "repository": { 13 | "type": "git", 14 | "url": "https://github.com/mojiito/mojiito" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/public_api.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @module 3 | * @description 4 | * Entry point for all public APIs of the core package. 5 | */ 6 | export * from './src/core'; 7 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/application/platform_errors.ts: -------------------------------------------------------------------------------- 1 | import { BaseError } from '../facade/error'; 2 | import { stringify } from '../facade/lang'; 3 | import { ClassType } from '../type'; 4 | 5 | export class PlatformAlreadyExistsError extends BaseError { 6 | constructor() { 7 | super(`A platform already exists. Destroy it first before creating this one.`); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/component/factory.ts: -------------------------------------------------------------------------------- 1 | import { ClassType } from '../type'; 2 | import { ComponentRef } from './reference'; 3 | import { Injector } from '../di/injector'; 4 | 5 | export abstract class ComponentFactory { 6 | abstract get selector(): string; 7 | abstract get componentType(): ClassType; 8 | /** 9 | * Creates a new component. 10 | */ 11 | abstract create(injector: Injector, rootSelectorOrNode?: string|any): ComponentRef; 12 | } 13 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/facade: -------------------------------------------------------------------------------- 1 | ../../facade/src -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/reflection/platform_reflection_capabilities.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {Type} from '../type'; 10 | import {GetterFn, MethodFn, SetterFn} from './types'; 11 | 12 | export interface PlatformReflectionCapabilities { 13 | isReflectionEnabled(): boolean; 14 | factory(type: Type): Function; 15 | hasLifecycleHook(type: any, lcProperty: string): boolean; 16 | parameters(type: Type): any[][]; 17 | annotations(type: Type): any[]; 18 | propMetadata(typeOrFunc: Type): {[key: string]: any[]}; 19 | getter(name: string): GetterFn; 20 | setter(name: string): SetterFn; 21 | method(name: string): MethodFn; 22 | importUri(type: Type): string; 23 | resourceUri(type: Type): string; 24 | resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any; 25 | resolveEnum(enumIdentifier: any, name: string): any; 26 | } 27 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/reflection/reflection.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | import {ReflectionCapabilities} from './reflection_capabilities'; 10 | import {Reflector} from './reflector'; 11 | 12 | export {Reflector} from './reflector'; 13 | 14 | /** 15 | * The {@link Reflector} used internally in Angular to access metadata 16 | * about symbols. 17 | */ 18 | export const reflector = new Reflector(new ReflectionCapabilities()); 19 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/reflection/reflector_reader.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | /** 10 | * Provides read-only access to reflection data about symbols. Used internally by Angular 11 | * to power dependency injection and compilation. 12 | */ 13 | export abstract class ReflectorReader { 14 | abstract parameters(typeOrFunc: /*Type*/ any): any[][]; 15 | abstract annotations(typeOrFunc: /*Type*/ any): any[]; 16 | abstract propMetadata(typeOrFunc: /*Type*/ any): {[key: string]: any[]}; 17 | abstract importUri(typeOrFunc: /*Type*/ any): string; 18 | abstract resourceUri(typeOrFunc: /*Type*/ any): string; 19 | abstract resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any): any; 20 | abstract resolveEnum(identifier: any, name: string): any; 21 | } 22 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/reflection/types.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @license 3 | * Copyright Google Inc. All Rights Reserved. 4 | * 5 | * Use of this source code is governed by an MIT-style license that can be 6 | * found in the LICENSE file at https://angular.io/license 7 | */ 8 | 9 | export type SetterFn = (obj: any, value: any) => void; 10 | export type GetterFn = (obj: any) => any; 11 | export type MethodFn = (obj: any, args: any[]) => any; 12 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/type.ts: -------------------------------------------------------------------------------- 1 | export interface ClassType extends Function { 2 | new (...args: Array): T; 3 | constructor: Function | any[]; 4 | [propertyName: string]: any; 5 | name: string; 6 | } 7 | 8 | export function isClassInstance(instance: any): boolean { 9 | return typeof instance === 'object' && !!instance['constructor']; 10 | } 11 | 12 | // tslint:disable:variable-name 13 | export const Type = Function; 14 | 15 | export function isType(v: any): v is Type { 16 | return typeof v === 'function'; 17 | } 18 | 19 | export interface Type extends Function { new (...args: any[]): T; } 20 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/view/element_ref.ts: -------------------------------------------------------------------------------- 1 | export class ElementRef { 2 | public nativeElement: any; 3 | constructor(nativeElement: any) { this.nativeElement = nativeElement; } 4 | } 5 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/view/utils.ts: -------------------------------------------------------------------------------- 1 | import { Injector } from '../di/injector'; 2 | import { ViewDefinition, ViewDefinitionFactory, ViewData } from './types'; 3 | import { createInjector } from './refs'; 4 | 5 | const VIEW_DEFINITION_CACHE = new WeakMap(); 6 | export function resolveViewDefinition(factory: ViewDefinitionFactory): ViewDefinition { 7 | let value: ViewDefinition = VIEW_DEFINITION_CACHE.get(factory); 8 | if (!value) { 9 | value = factory(); 10 | VIEW_DEFINITION_CACHE.set(factory, value); 11 | } 12 | return value; 13 | } 14 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/view/view_ref.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationRef } from '../application/application'; 2 | 3 | export abstract class ViewRef { // extends ChangeDetectorRef { 4 | 5 | /** Destroys the view and all of the data structures associated with it. */ 6 | abstract destroy(): void; 7 | 8 | abstract get destroyed(): boolean; 9 | 10 | abstract onDestroy(callback: Function): any; 11 | 12 | } 13 | 14 | export interface InternalViewRef extends ViewRef { 15 | detachFromAppRef(): void; 16 | attachToAppRef(appRef: ApplicationRef): void; 17 | } 18 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/src/view/view_utils.ts: -------------------------------------------------------------------------------- 1 | // import { View } from './view'; 2 | import { Injector } from '../di/injector'; 3 | import { Renderer, RendererFactory } from '../render'; 4 | import { RootData } from './types'; 5 | 6 | // export function subscribeToElement(view: View, element: any, 7 | // eventNamesAndTargets: string[], listener: (eventName: string, event: any) => any) { 8 | // const disposables: Function[] = []; 9 | // for (let i = 0; i < eventNamesAndTargets.length; i += 2) { 10 | // const eventName = eventNamesAndTargets[i]; 11 | // const eventTarget = eventNamesAndTargets[i + 1]; 12 | // let disposable: Function; 13 | // if (eventTarget) { 14 | // disposable = view.renderer.listenGlobal( 15 | // eventTarget, eventName, listener.bind(view, `${eventTarget}:${eventName}`)); 16 | // } else { 17 | // disposable = view.renderer.listen(element, eventName, listener.bind(view, eventName)); 18 | // } 19 | // disposables.push(disposable); 20 | // } 21 | // return () => disposables.forEach(d => d()); 22 | // } 23 | 24 | 25 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/core/tsconfig-build.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "declaration": true, 5 | "stripInternal": true, 6 | "experimentalDecorators": true, 7 | "module": "es2015", 8 | "moduleResolution": "node", 9 | "outDir": "../../dist/packages/core", 10 | "rootDir": ".", 11 | "sourceMap": true, 12 | "inlineSources": true, 13 | "target": "es2015", 14 | "lib": ["es2015", "dom"], 15 | "skipLibCheck": true, 16 | "types": [] 17 | }, 18 | "files": [ 19 | "public_api.ts" 20 | ], 21 | "angularCompilerOptions": { 22 | "annotateForClosureCompiler": true, 23 | "strictMetadataEmit": true, 24 | "flatModuleOutFile": "index.js", 25 | "flatModuleId": "mojiito-core" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/facade/index.ts: -------------------------------------------------------------------------------- 1 | export * from './src/error'; 2 | export * from './src/lang'; 3 | export * from './src/collection'; 4 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/license-banner.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * @license Mojiito v0.0.0-PLACEHOLDER 3 | * (c) 2010-2017 Thomas Pink 4 | * License: MIT 5 | */ 6 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/index.ts: -------------------------------------------------------------------------------- 1 | // This file is not used to build this module. It is only used during editing 2 | // by the TypeScript language service and during build for verification. `ngc` 3 | // replaces this file with production index.ts when it rewrites private symbol 4 | // names. 5 | 6 | export * from './public_api'; 7 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mojiito-platform-browser", 3 | "version": "0.0.0-PLACEHOLDER", 4 | "description": "Mojiito Platform Browser", 5 | "main": "./bundles/platform-browser.umd.js", 6 | "module": "./mojiito/platform-browser.es5.js", 7 | "es2015": "./mojiito/platform-browser.js", 8 | "typings": "./platform-browser.d.ts", 9 | "author": "Mojiito Team", 10 | "license": "MIT", 11 | "peerDependencies": { 12 | "mojiito-core": "0.0.0-PLACEHOLDER" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/mojiito/mojiito" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/public_api.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @module 3 | * @description 4 | * Entry point for all public APIs of the core package. 5 | */ 6 | export * from './src/platform-browser'; 7 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/src/compiler/compile_result.ts: -------------------------------------------------------------------------------- 1 | import { ClassType, Renderer, ComponentFactory } from 'mojiito-core'; 2 | 3 | export interface CompileComponentSummary { 4 | type: ClassType; 5 | selector: string; 6 | hostListeners: { [key: string]: string }; 7 | childListeners: { [key: string]: string }; 8 | componentFactory: ComponentFactory; 9 | viewDefinitionFactory: () => any; 10 | components: CompileComponentSummary[]; 11 | } 12 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/src/expression/expression.ts: -------------------------------------------------------------------------------- 1 | import { Token, ExpressionParser } from './expression_parser'; 2 | 3 | export { Token, ExpressionParser }; 4 | 5 | export class Expression { 6 | constructor(public tokens: Token[]) { } 7 | } 8 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/src/facade: -------------------------------------------------------------------------------- 1 | ../../facade/src -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/src/platform-browser.ts: -------------------------------------------------------------------------------- 1 | import { 2 | createPlatformFactory, PlatformRef, InjectionToken, RendererFactory, CORE_PROVIDERS, Provider 3 | } from 'mojiito-core'; 4 | import { unimplemented } from './facade/error'; 5 | import { ListWrapper } from './facade/collection'; 6 | import { BrowserPlatformRef } from './platform_ref'; 7 | import { DOCUMENT } from './tokens'; 8 | import { Compiler } from './compiler/compiler'; 9 | import { DomTraverser } from './dom_traverser'; 10 | import { DomRendererFactory } from './dom_renderer'; 11 | import { ExpressionParser } from './expression/expression'; 12 | import { BindingParser } from './binding_parser'; 13 | 14 | export { DOCUMENT, DomRendererFactory, BrowserPlatformRef, ExpressionParser }; 15 | 16 | export const PLATFORM_PROVIDERS: Provider[] = [ 17 | { provide: PlatformRef, useClass: BrowserPlatformRef }, 18 | { provide: DOCUMENT, useValue: document }, 19 | { provide: RendererFactory, useClass: DomRendererFactory}, 20 | Compiler, 21 | ExpressionParser, 22 | BindingParser 23 | ]; 24 | 25 | export const platformBrowser = createPlatformFactory([PLATFORM_PROVIDERS, CORE_PROVIDERS]); 26 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/src/tokens.ts: -------------------------------------------------------------------------------- 1 | import { InjectionToken } from 'mojiito-core'; 2 | 3 | export const DOCUMENT = new InjectionToken('DocumentToken'); 4 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/platform-browser/tsconfig-build.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "declaration": true, 5 | "stripInternal": true, 6 | "experimentalDecorators": true, 7 | "module": "es2015", 8 | "moduleResolution": "node", 9 | "outDir": "../../dist/packages/platform-browser", 10 | "paths": { 11 | "mojiito-core": ["../../dist/packages/core"] 12 | }, 13 | "rootDir": ".", 14 | "sourceMap": true, 15 | "inlineSources": true, 16 | "target": "es2015", 17 | "lib": ["es2015", "dom"], 18 | "skipLibCheck": true, 19 | "types": [] 20 | }, 21 | "files": [ 22 | "public_api.ts" 23 | ], 24 | "angularCompilerOptions": { 25 | "annotateForClosureCompiler": true, 26 | "strictMetadataEmit": true, 27 | "flatModuleOutFile": "index.js", 28 | "flatModuleId": "mojiito-platform-browser" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /data/train/mojiito-master/packages/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "declaration": true, 5 | "experimentalDecorators": true, 6 | "emitDecoratorMetadata": true, 7 | "module": "commonjs", 8 | "moduleResolution": "node", 9 | "outDir": "../dist/all/mojiito", 10 | "noImplicitAny": true, 11 | "noFallthroughCasesInSwitch": true, 12 | "paths": { 13 | "mojiito-*": ["./*"] 14 | }, 15 | "rootDir": ".", 16 | "inlineSourceMap": true, 17 | "lib": ["es2015", "dom"], 18 | "skipDefaultLibCheck": true, 19 | "skipLibCheck": true, 20 | "target": "es5" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /data/train/mojiito-master/playground/README.md: -------------------------------------------------------------------------------- 1 | # Playground 2 | 3 | * First build Mojiito by executing `npm run build` in your command line tool 4 | * Now run `npm run build-playground` to build the playground 5 | * Or `npm run serve-playground` to start a server 6 | 7 | ## Troubleshooting 8 | 9 | #### Error `listen EADDRINUSE 0.0.0.0:4200` 10 | Sometimes if you start the server the following Error occurs: `Error: listen EADDRINUSE 0.0.0.0:4200`. 11 | This happens if there is already a server running on Port `4200` or you didn't quit the process correctly (e.g. Ctrl+Z instead of Ctrl+C). 12 | You can check for running processes on this port by executing `lsof -i tcp:4200 ` in your command line tool. 13 | If there are processes up, please close them (as a last ressort you can kill all node processes with `killall -9 node` 14 | or just a specific one with `killall -15` and the process id) -------------------------------------------------------------------------------- /data/train/mojiito-master/playground/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ViewContainerRef, Renderer, Inject } from 'mojiito-core'; 2 | 3 | import {Dialog, DialogComponent } from './dialog'; 4 | import { ButtonComponent } from './button.component'; 5 | import { DrawerComponent } from './drawer.component'; 6 | 7 | @Component({ 8 | selector: 'body', 9 | components: [ DialogComponent, ButtonComponent, DrawerComponent ], 10 | providers: [Dialog] 11 | }) 12 | export class AppComponent { 13 | private dialogTemplate: string; 14 | constructor(private renderer: Renderer, private _dialog: Dialog) { 15 | const buttonEl = renderer.selectRootElement('#open'); 16 | 17 | renderer.listen(buttonEl, 'click', this.openDialog.bind(this)); 18 | } 19 | 20 | openDialog(event) { 21 | this._dialog.open(); 22 | } 23 | } 24 | 25 | // document.addEventListener 26 | -------------------------------------------------------------------------------- /data/train/mojiito-master/playground/app/button.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ElementRef, HostListener } from 'mojiito-core'; 2 | 3 | @Component({ 4 | selector: '[my-button]' 5 | }) 6 | export class ButtonComponent { 7 | 8 | constructor(private elementRef: ElementRef) { 9 | console.log(elementRef.nativeElement); 10 | } 11 | 12 | @HostListener('click') 13 | clicked() { 14 | console.log('Button clicked'); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /data/train/mojiito-master/playground/app/drawer.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ElementRef, ChildListener } from 'mojiito-core'; 2 | 3 | @Component({ 4 | selector: 'side-drawer' 5 | }) 6 | export class DrawerComponent { 7 | 8 | constructor(private elementRef: ElementRef) { 9 | console.log(elementRef.nativeElement); 10 | } 11 | 12 | @ChildListener('button', 'click') 13 | childClicked() { 14 | console.log('Child clicked'); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /data/train/mojiito-master/playground/main.ts: -------------------------------------------------------------------------------- 1 | import { platformBrowser } from 'mojiito-platform-browser'; 2 | import { AppComponent } from './app/app.component'; 3 | 4 | console.time('bootstrap'); 5 | platformBrowser().bootstrapComponent(AppComponent); 6 | console.timeEnd('bootstrap'); 7 | -------------------------------------------------------------------------------- /data/train/mojiito-master/playground/styles.css: -------------------------------------------------------------------------------- 1 | .page-content { 2 | padding: 30px; 3 | } 4 | 5 | side-drawer { 6 | padding: 20px 0; 7 | } 8 | 9 | [aria-hidden="true"] { 10 | display: none; 11 | } 12 | -------------------------------------------------------------------------------- /data/train/mojiito-master/playground/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "declaration": true, 5 | "stripInternal": true, 6 | "experimentalDecorators": true, 7 | "module": "es2015", 8 | "moduleResolution": "node", 9 | "outDir": "../dist/playground", 10 | "rootDir": ".", 11 | "sourceMap": true, 12 | "inlineSources": true, 13 | "target": "es5", 14 | "lib": ["es2015", "dom"], 15 | "skipLibCheck": true, 16 | "types": [], 17 | "paths": { 18 | "mojiito-core": ["../dist/packages-dist/core"], 19 | "mojiito-platform-browser": ["../dist/packages-dist/platform-browser"] 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /data/train/mojiito-master/scripts/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -u -e -o pipefail 4 | 5 | # Setup environment 6 | readonly thisDir=$(cd $(dirname $0); pwd) 7 | source ${thisDir}/_travis_fold.sh 8 | 9 | if [[ ${TRAVIS} ]]; then 10 | 11 | # If the previous commands in the `script` section of .travis.yaml failed, then abort. 12 | # The variable is not set in early stages of the build, so we default to 0 there. 13 | # https://docs.travis-ci.com/user/environment-variables/ 14 | if [[ ${TRAVIS_TEST_RESULT=0} == 1 ]]; then 15 | exit 1; 16 | fi 17 | 18 | # Don't deploy if this is a PR build 19 | if [[ ${TRAVIS_PULL_REQUEST} != "false" ]]; then 20 | echo "Skipping deploy because this is a PR build." 21 | exit 0 22 | fi 23 | fi 24 | 25 | travisFoldStart "build.packages" 26 | ./build.sh 27 | travisFoldEnd "build.packages" 28 | 29 | travisFoldStart "deploy.packages" 30 | ${thisDir}/publish-build-artifacts.sh 31 | travisFoldEnd "deploy.packages" 32 | -------------------------------------------------------------------------------- /data/train/mojiito-master/scripts/publish.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | 4 | PACKAGES=(core 5 | platform-browser) 6 | 7 | for PACKAGE in ${PACKAGES[@]} 8 | do 9 | echo "====== ${bold}PUBLISHING to NPM: ${green}${PACKAGE}${normal} =====" 10 | DESTDIR=${PWD}/dist/packages-dist/${PACKAGE} 11 | cd $DESTDIR 12 | npm publish 13 | cd ../../../ 14 | done 15 | -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/README.md: -------------------------------------------------------------------------------- 1 | Typescript Algorithms 2 | ========================= 3 | 4 | A collection of well known algorithms and data structures in Typescript 5 | 6 | ## Install 7 | 8 | ``` 9 | npm install 10 | tsc 11 | ``` 12 | 13 | ## Run 14 | 15 | Running each compiled JS file runs the algorithm against data sets of increasing 16 | sizes and prints a chart of the results. -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typescript-algorithms", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "benchmark": "^2.1.2", 13 | "chart": "github:jstrace/chart" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/src/big-o/o-1.ts: -------------------------------------------------------------------------------- 1 | let Benchmark = undefined; 2 | import { generateArray, runBenchmark } from '../helpers'; 3 | 4 | let arrays = [ 5 | generateArray(10), 6 | generateArray(20), 7 | generateArray(30), 8 | generateArray(40), 9 | generateArray(50), 10 | generateArray(60), 11 | generateArray(70), 12 | generateArray(80), 13 | generateArray(90), 14 | generateArray(100) 15 | ]; 16 | 17 | //O(1) 18 | function biggerThan(numbers:Array, biggerThan:number): boolean { 19 | return numbers.length > biggerThan; 20 | } 21 | 22 | const suite = new Benchmark.Suite('O(1) will always execute in the same time regardless of the input size:'); 23 | for(let i = 0; i < arrays.length; i++) { 24 | suite.add(`${arrays[i].length}`, () => biggerThan(arrays[i], 1)); 25 | } 26 | runBenchmark(suite); -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/src/big-o/o-2n.ts: -------------------------------------------------------------------------------- 1 | let Benchmark = undefined; 2 | import { runBenchmark } from '../helpers'; 3 | 4 | let arrays = [ 5 | 1, 2, 3, 4, 5, 6 6 | ]; 7 | 8 | //O(2n) 9 | function fibonacci(num:number):number { 10 | if (num <= 1) { 11 | return num; 12 | } 13 | return fibonacci(num - 2) + fibonacci(num - 1); 14 | } 15 | 16 | const suite = new Benchmark.Suite('O(2^n) will perform in exponentially in proportion to size of the data set'); 17 | for(let i = 0; i < arrays.length; i++) { 18 | suite.add(`${arrays[i]}`, () => fibonacci(arrays[i])); 19 | } 20 | 21 | runBenchmark(suite); -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/src/big-o/o-logn.ts: -------------------------------------------------------------------------------- 1 | let Benchmark = undefined; 2 | import { generateArray, runBenchmark } from '../helpers'; 3 | import binarySeach from '../binary-search/iterative'; 4 | 5 | let arrays = [ 6 | generateArray(1000), 7 | generateArray(2000), 8 | generateArray(3000), 9 | generateArray(4000), 10 | generateArray(5000), 11 | generateArray(6000), 12 | generateArray(7000), 13 | generateArray(8000), 14 | generateArray(9000), 15 | generateArray(10000) 16 | ]; 17 | //O(log(2, n) 18 | const suite = new Benchmark.Suite('O(2, n) will perform logarithmically in proportion to the size of the data set:'); 19 | for(let i = 0; i < arrays.length; i++) { 20 | let toFind = arrays[i][Math.round(arrays[i].length * 0.3)]; 21 | suite.add(`${arrays[i].length}`, () => binarySeach(toFind, arrays[i])); 22 | } 23 | runBenchmark(suite); -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/src/big-o/o-n.ts: -------------------------------------------------------------------------------- 1 | let Benchmark = undefined; 2 | import { generateArray, runBenchmark } from '../helpers'; 3 | 4 | let arrays = [ 5 | generateArray(100), 6 | generateArray(200), 7 | generateArray(300), 8 | generateArray(400), 9 | generateArray(500), 10 | generateArray(600), 11 | generateArray(700), 12 | generateArray(800), 13 | generateArray(900), 14 | generateArray(1000) 15 | ]; 16 | //O(n) 17 | function search(numbers:Array, toFind:number): number { 18 | for(let i of numbers) { 19 | if (toFind === i) { 20 | return i; 21 | } 22 | } 23 | return -1; 24 | } 25 | 26 | const suite = new Benchmark.Suite('O(n) will perform linearly in proportion to the size of the data set:'); 27 | for(let i = 0; i < arrays.length; i++) { 28 | suite.add(`${arrays[i].length}`, () => search(arrays[i], arrays[i][arrays[i].length-1])); 29 | } 30 | runBenchmark(suite); -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/src/big-o/o-n2.ts: -------------------------------------------------------------------------------- 1 | let Benchmark = undefined; 2 | import { generateArray, runBenchmark } from '../helpers'; 3 | 4 | let arrays = [ 5 | generateArray(11), 6 | generateArray(21), 7 | generateArray(31), 8 | generateArray(41), 9 | generateArray(51), 10 | generateArray(61), 11 | generateArray(71), 12 | generateArray(81), 13 | generateArray(91) 14 | ]; 15 | 16 | //O(n^2) 17 | function searchForProduct(numbers:Array, moreNumbers:Array, toFind:number):Array { 18 | for(let i of numbers) { 19 | for(let j of moreNumbers) { 20 | if(i * j === toFind) { 21 | return [i, j]; 22 | } 23 | } 24 | } 25 | return [-1, -1]; 26 | } 27 | 28 | const suite = new Benchmark.Suite('O(n^2) will perform in proportion to the square of the data set'); 29 | for(let i = 0; i < arrays.length; i++) { 30 | let toFind = arrays[i][arrays[i].length-1] * arrays[i][arrays[i].length-1]; 31 | suite.add(`${arrays[i].length}`, () => searchForProduct(arrays[i], arrays[i].slice(0), toFind)); 32 | } 33 | runBenchmark(suite); -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/src/binary-search/random.ts: -------------------------------------------------------------------------------- 1 | export function withinRange(min: number, max: number) { 2 | return Math.floor(Math.random() * (max - min + 1) + min); 3 | } 4 | 5 | export function generateArray(len: number, randomLo:number, randomHi:number) { 6 | let arr = []; 7 | for(let i = 0; i < len; i++) { 8 | arr.push(withinRange(randomLo, randomHi)); 9 | } 10 | arr.sort(); 11 | return arr; 12 | } 13 | -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/src/sorting/bubble-sort.ts: -------------------------------------------------------------------------------- 1 | let Benchmark = undefined; 2 | 3 | import { generateArray, runBenchmark, swap } from '../helpers'; 4 | 5 | let arrays = [ 6 | generateArray(100, false), 7 | generateArray(200, false), 8 | generateArray(300, false), 9 | generateArray(400, false), 10 | generateArray(500, false), 11 | ]; 12 | 13 | function bubbleSort(arr:Array) { 14 | 15 | let swapped = false; 16 | while (swapped); 17 | 18 | return arr; 19 | } 20 | 21 | const suite = new Benchmark.Suite('Bubblesort'); 22 | for(let i = 0; i < arrays.length; i++) { 23 | suite.add(`${arrays[i].length}`, () => bubbleSort(arrays[i])); 24 | } 25 | runBenchmark(suite); -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/src/sorting/quick-sort.ts: -------------------------------------------------------------------------------- 1 | 2 | let Benchmark = undefined; 3 | import { generateArray, runBenchmark, swap } from '../helpers'; 4 | 5 | let arrays = [ 6 | generateArray(100, false), 7 | generateArray(200, false), 8 | generateArray(300, false), 9 | generateArray(400, false), 10 | generateArray(500, false), 11 | ]; 12 | 13 | function quicksort(arr:Array, lo = 0, hi = arr.length - 1) { 14 | 15 | if(lo < hi) { 16 | const p = partition(arr, lo, hi); 17 | quicksort(arr, lo, p -1); 18 | quicksort(arr, p + 1, hi); 19 | } 20 | } 21 | 22 | function partition(arr:Array, lo:number, hi:number):number { 23 | const pivot = arr[hi]; 24 | let i = lo; 25 | for(let j = lo; j < hi; j++) { 26 | if(arr[j] <= pivot) { 27 | swap(arr, i, j); 28 | i++; 29 | } 30 | } 31 | swap(arr, i, hi); 32 | return i 33 | } 34 | 35 | const suite = new Benchmark.Suite('Quicksort'); 36 | for(let i = 0; i < arrays.length; i++) { 37 | suite.add(`${arrays[i].length}`, () => quicksort(arrays[i])); 38 | } 39 | runBenchmark(suite); 40 | -------------------------------------------------------------------------------- /data/train/philmander-typescript-algorithms/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2015" 4 | }, 5 | "moduleResolution": "node" 6 | } -------------------------------------------------------------------------------- /data/train/typehtml-master/.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{js,jsx,ts,tsx}] 2 | indent_style = space 3 | indent_size = 2 4 | trim_trailing_whitespace = true 5 | insert_final_newline = true 6 | 7 | [*.md] 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true -------------------------------------------------------------------------------- /data/train/typehtml-master/.gitignore: -------------------------------------------------------------------------------- 1 | # IDE 2 | .alm 3 | 4 | # Our build assets to deploy 5 | lib 6 | 7 | # Node 8 | node_modules 9 | npm-debug.log* 10 | 11 | # Scratch files 12 | scratch 13 | -------------------------------------------------------------------------------- /data/train/typehtml-master/.npmignore: -------------------------------------------------------------------------------- 1 | # tests 2 | src/tests 3 | lib/tests 4 | lib.es2015/tests 5 | 6 | # build tools 7 | .travis.yml 8 | 9 | # editor settings 10 | .editorconfig 11 | .alm 12 | alm.json 13 | 14 | # npm 15 | npm-debug.log* 16 | 17 | # Scratch files 18 | scratch 19 | -------------------------------------------------------------------------------- /data/train/typehtml-master/.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - '6' 5 | 6 | # Use container-based Travis infrastructure. 7 | sudo: required 8 | dist: trusty 9 | 10 | env: 11 | - CXX=g++-4.8 12 | addons: 13 | firefox: "latest" 14 | apt: 15 | sources: 16 | - ubuntu-toolchain-r-test 17 | packages: 18 | - g++-4.8 19 | 20 | addons: 21 | at: 22 | sources: 23 | - google-chrome 24 | packages: 25 | - google-chrome-stable 26 | - google-chrome-beta 27 | 28 | before_install: 29 | - "nvm use $TRAVIS_NODE_VERSION" 30 | # Repo for newer Node.js versions 31 | - curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - 32 | 33 | before_script: 34 | - "export DISPLAY=:99.0" 35 | - "sh -e /etc/init.d/xvfb start" 36 | -------------------------------------------------------------------------------- /data/train/typehtml-master/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | * `npm install` 2 | * `npm run testem` 3 | 4 | Write tests. Make them pass :rose: 5 | -------------------------------------------------------------------------------- /data/train/typehtml-master/TODO.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | * Add examples using eze 3 | 4 | # Add Mobx 5 | * devdep + peerdep `>=3.0.0` 6 | 7 | # LifeCycle 8 | * Add component lifecycle 9 | 10 | # Mobx wasting renders 11 | One idea is touse mobx.reaction around renders : https://github.com/mobxjs/mobx-react/blob/20bdcb39f43fc6466e050dca1711a64ad8d6252c/src/observer.js#L148 12 | 13 | Alternatively components that are pure should simply mark their `renders` as `@computed` 14 | -------------------------------------------------------------------------------- /data/train/typehtml-master/alm.json: -------------------------------------------------------------------------------- 1 | { 2 | "tests": { 3 | "include": [ 4 | "src/tests/mocha" 5 | ] 6 | } 7 | } -------------------------------------------------------------------------------- /data/train/typehtml-master/src/dom/render.ts: -------------------------------------------------------------------------------- 1 | // import { autorun } from 'mobx'; 2 | import { patch } from '../vdom/patch'; 3 | import { VNode } from '../types'; 4 | 5 | let autorun = undefined; 6 | 7 | export function render(input: () => VNode, dom: Element): void { 8 | /** 9 | * Since snabbdom replaces the input dom element with the vnode 10 | * vs. 11 | * React inserts the dom element into the provided vnode 12 | * 13 | * Add a dom node before giving to patch 14 | **/ 15 | const renderTarget = document.createElement('div'); 16 | dom.appendChild(renderTarget); 17 | 18 | let lastVNode: VNode | Element = renderTarget; 19 | autorun(() => { 20 | const nextVNode = input(); 21 | patch(lastVNode, nextVNode); 22 | lastVNode = nextVNode; 23 | }); 24 | } 25 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/dom/utils.ts: -------------------------------------------------------------------------------- 1 | 2 | /** Object without one particular prop */ 3 | export function objWithoutProps(obj, keys: string[]) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } 4 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @module This is just an example of what the types would look like 3 | */ 4 | import * as types from './types'; 5 | export { types }; 6 | 7 | /** 8 | * Takes JSX and returns a handle to the DOMElement 9 | **/ 10 | import { createElement } from './dom/createElement'; 11 | export { createElement }; 12 | 13 | /** 14 | * Takes JSX and renders it to a string 15 | */ 16 | import { renderToString } from './server/renderToString'; 17 | export { renderToString }; 18 | 19 | 20 | /** 21 | * Takes JSX and renders it to a dom element 22 | */ 23 | import { render } from './dom/render'; 24 | export { render }; 25 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/server/renderToString.ts: -------------------------------------------------------------------------------- 1 | import { VNode } from '../types'; 2 | 3 | export function renderToString(input: VNode): string { 4 | return 'todo'; 5 | } 6 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/tests/mocha/basic.tsx: -------------------------------------------------------------------------------- 1 | /** 2 | * Used as a sample what the code can look like. 3 | * It will not work without us actually writing the code 4 | */ 5 | import * as Th from '../../index' 6 | 7 | /** Create component as a function */ 8 | const FunctionExample = ({ text }: { text: string }) =>
{text}
9 | 10 | /** Or as a class */ 11 | class ClassExample { 12 | constructor(private props: { text: string }) { } 13 | 14 | render() { 15 | return
{this.props.text}
16 | } 17 | } 18 | 19 | /** Use native */ 20 | let nativeExample =
Hello world
21 | 22 | /** Use a function */ 23 | let functionExample = 24 | 25 | /** Use a class */ 26 | let classExample = 27 | 28 | import * as assert from 'assert'; 29 | describe('Server rendering', () => { 30 | it('should render function component to string', () => { 31 | // assert.equal(TH.renderToString(functionExample), '
Hello world
'); 32 | }); 33 | 34 | it('should render class component to string', () => { 35 | // assert.equal(TH.renderToString(classExample), '
Hello world
'); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/tests/testem/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * export all the tests 3 | */ 4 | export import _ = require('./intrinsic'); 5 | export import __ = require('./componentFunction'); 6 | export import ___ = require('./componentClass'); 7 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/tests/tools/utils.ts: -------------------------------------------------------------------------------- 1 | const comparer = document.createElement('div'); 2 | export function sortAttributes(html: string): string { 3 | return html.replace(/<([a-z0-9-]+)((?:\s[a-z0-9:_.-]+=".*?")+)((?:\s*\/)?>)/gi, (_, pre, attrs, after) => { 4 | const attrName = (attribute: string): string => attribute.split('=')[0]; 5 | const list: string[] = attrs.match(/\s[a-z0-9:_.-]+=".*?"/gi).sort( (a, b) => attrName(a) > attrName(b) ? 1 : -1 ); 6 | if (~after.indexOf('/')) { 7 | after = '>'; 8 | } 9 | return '<' + pre + list.join('') + after; 10 | }); 11 | } 12 | 13 | export function innerHTML(HTML: string): string { 14 | comparer.innerHTML = HTML; 15 | return sortAttributes(comparer.innerHTML); 16 | } 17 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/vdom/is.ts: -------------------------------------------------------------------------------- 1 | export const array = Array.isArray; 2 | export function primitive(s: any): s is (string | number) { 3 | return typeof s === 'string' || typeof s === 'number'; 4 | } 5 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/vdom/modules/class.ts: -------------------------------------------------------------------------------- 1 | import { VNode, VNodeData } from '../../types'; 2 | import { Module } from './module'; 3 | 4 | function updateClass(oldVnode: VNode, vnode: VNode): void { 5 | var cur: any, name: string, elm: Element = vnode.elm as Element, 6 | oldClass = (oldVnode.data as VNodeData).class, 7 | klass = (vnode.data as VNodeData).class; 8 | 9 | if (!oldClass && !klass) return; 10 | if (oldClass === klass) return; 11 | oldClass = oldClass || {}; 12 | klass = klass || {}; 13 | 14 | for (name in oldClass) { 15 | if (!klass[name]) { 16 | elm.classList.remove(name); 17 | } 18 | } 19 | for (name in klass) { 20 | cur = klass[name]; 21 | if (cur !== oldClass[name]) { 22 | (elm.classList as any)[cur ? 'add' : 'remove'](name); 23 | } 24 | } 25 | } 26 | 27 | export const classModule = { create: updateClass, update: updateClass } as Module; 28 | export default classModule; 29 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/vdom/modules/dataset.ts: -------------------------------------------------------------------------------- 1 | import {VNode, VNodeData} from '../../types'; 2 | import {Module} from './module'; 3 | 4 | function updateDataset(oldVnode: VNode, vnode: VNode): void { 5 | var elm: HTMLElement = vnode.elm as HTMLElement, 6 | oldDataset = (oldVnode.data as VNodeData).dataset, 7 | dataset = (vnode.data as VNodeData).dataset, 8 | key: string; 9 | 10 | if (!oldDataset && !dataset) return; 11 | if (oldDataset === dataset) return; 12 | oldDataset = oldDataset || {}; 13 | dataset = dataset || {}; 14 | 15 | for (key in oldDataset) { 16 | if (!dataset[key]) { 17 | delete elm.dataset[key]; 18 | } 19 | } 20 | for (key in dataset) { 21 | if (oldDataset[key] !== dataset[key]) { 22 | elm.dataset[key] = dataset[key]; 23 | } 24 | } 25 | } 26 | 27 | export const datasetModule = {create: updateDataset, update: updateDataset} as Module; 28 | export default datasetModule; 29 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/vdom/modules/module.ts: -------------------------------------------------------------------------------- 1 | import { PreHook, CreateHook, UpdateHook, DestroyHook, RemoveHook, PostHook } from '../../types'; 2 | 3 | export interface Module { 4 | pre: PreHook; 5 | create: CreateHook; 6 | update: UpdateHook; 7 | destroy: DestroyHook; 8 | remove: RemoveHook; 9 | post: PostHook; 10 | } 11 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/vdom/modules/props.ts: -------------------------------------------------------------------------------- 1 | import {VNode, VNodeData} from '../../types'; 2 | import {Module} from './module'; 3 | 4 | function updateProps(oldVnode: VNode, vnode: VNode): void { 5 | var key: string, cur: any, old: any, elm = vnode.elm, 6 | oldProps = (oldVnode.data as VNodeData).props, 7 | props = (vnode.data as VNodeData).props; 8 | 9 | if (!oldProps && !props) return; 10 | if (oldProps === props) return; 11 | oldProps = oldProps || {}; 12 | props = props || {}; 13 | 14 | for (key in oldProps) { 15 | if (!props[key]) { 16 | delete (elm as any)[key]; 17 | } 18 | } 19 | for (key in props) { 20 | cur = props[key]; 21 | old = oldProps[key]; 22 | if (old !== cur && (key !== 'value' || (elm as any)[key] !== cur)) { 23 | (elm as any)[key] = cur; 24 | } 25 | } 26 | } 27 | 28 | export const propsModule = {create: updateProps, update: updateProps} as Module; 29 | export default propsModule; 30 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/vdom/patch.ts: -------------------------------------------------------------------------------- 1 | import { VNode } from '../types'; 2 | import { init } from './snabbdom'; 3 | import { attributesModule } from './modules/attributes'; // for setting attributes on DOM elements 4 | import { classModule } from './modules/class'; // makes it easy to toggle classes 5 | import { propsModule } from './modules/props'; // for setting properties on DOM elements 6 | import { styleModule } from './modules/style'; // handles styling on elements with support for animations 7 | import { eventListenersModule } from './modules/eventlisteners'; // attaches event listeners 8 | 9 | export const patch = init([ // Init patch function with choosen modules 10 | attributesModule, 11 | classModule, 12 | propsModule, 13 | styleModule, 14 | eventListenersModule 15 | ]); 16 | -------------------------------------------------------------------------------- /data/train/typehtml-master/src/vdom/vnode.ts: -------------------------------------------------------------------------------- 1 | import { VNode } from '../types'; 2 | 3 | export default function vnode( 4 | sel: string, 5 | data: any | undefined, 6 | children: Array | undefined, 7 | text: string | undefined, 8 | elm: Element | Text | undefined 9 | ): VNode { 10 | let key = data === undefined ? undefined : data.key; 11 | return { 12 | sel: sel, data: data, children: children, 13 | text: text, elm: elm, key: key 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /data/train/typehtml-master/testem.json: -------------------------------------------------------------------------------- 1 | { 2 | "framework": "mocha", 3 | "src_files": [ 4 | "lib/**/*.js" 5 | ], 6 | "serve_files": [ 7 | "scratch/tests.js" 8 | ], 9 | "before_tests": "mkdir -p scratch && browserify -d lib/tests/testem/index.js -o scratch/tests.js", 10 | "on_exit": "rm scratch/tests.js", 11 | "launch_in_dev": [ 12 | "chrome" 13 | ] 14 | } -------------------------------------------------------------------------------- /data/train/typehtml-master/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "jsx": "react", 4 | "reactNamespace": "Th", 5 | "outDir": "lib", 6 | "lib": [ 7 | "es6", 8 | "dom" 9 | ], 10 | "experimentalDecorators": true, 11 | "emitDecoratorMetadata": true 12 | }, 13 | "include": [ 14 | "src" 15 | ] 16 | } -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/dynamic-programing/knapsack-recursive.ts: -------------------------------------------------------------------------------- 1 | export function knapSack(capacity: number, weights: number[], values: number[], n: number): number { 2 | if (n === 0 || capacity === 0) { 3 | return 0; 4 | } 5 | 6 | if (weights[n - 1] > capacity) { 7 | return knapSack(capacity, weights, values, n - 1); 8 | } else { 9 | const a: number = values[n - 1] + knapSack(capacity - weights[n - 1], weights, values, n - 1); 10 | const b: number = knapSack(capacity, weights, values, n - 1); 11 | return a > b ? a : b; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/dynamic-programing/longest-common-subsequence.ts: -------------------------------------------------------------------------------- 1 | export function lcs(wordX: string, wordY: string) { 2 | const m = wordX.length; 3 | const n = wordY.length; 4 | const l: Array> = []; 5 | 6 | for (let i = 0; i <= m; i++) { 7 | l[i] = []; 8 | for (let j = 0; j <= n; j++) { 9 | l[i][j] = 0; 10 | } 11 | } 12 | 13 | for (let i = 0; i <= m; i++) { 14 | for (let j = 0; j <= n; j++) { 15 | if (i === 0 || j === 0) { 16 | l[i][j] = 0; 17 | } else if (wordX[i - 1] === wordY[j - 1]) { 18 | l[i][j] = l[i - 1][j - 1] + 1; 19 | } else { 20 | const a = l[i - 1][j]; 21 | const b = l[i][j - 1]; 22 | l[i][j] = a > b ? a : b; // max(a,b) 23 | } 24 | } 25 | // console.log(l[i].join()); 26 | } 27 | 28 | return l[m][n]; 29 | } 30 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/dynamic-programing/min-coin-change.ts: -------------------------------------------------------------------------------- 1 | export function minCoinChange(coins: number[], amount: number) { 2 | const cache: Array> = []; 3 | 4 | // tslint:disable-next-line:no-shadowed-variable 5 | const makeChange = function(amount: number) { 6 | if (!amount) { 7 | return []; 8 | } 9 | if (cache[amount]) { 10 | return cache[amount]; 11 | } 12 | let min: number[] = [], 13 | newMin, 14 | newAmount; 15 | for (let i = 0; i < coins.length; i++) { 16 | const coin = coins[i]; 17 | newAmount = amount - coin; 18 | if (newAmount >= 0) { 19 | newMin = makeChange(newAmount); 20 | } 21 | if ( 22 | newAmount >= 0 && 23 | (newMin.length < min.length - 1 || !min.length) && 24 | (newMin.length || !newAmount) 25 | ) { 26 | min = [coin].concat(newMin); 27 | // console.log('new Min ' + min + ' for ' + amount); 28 | } 29 | } 30 | return (cache[amount] = min); 31 | }; 32 | 33 | return makeChange(amount); 34 | } 35 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/graph/dijkstra.ts: -------------------------------------------------------------------------------- 1 | const INF = Number.MAX_SAFE_INTEGER; 2 | 3 | const minDistance = (dist: number[], visited: boolean[]) => { 4 | let min = INF; 5 | let minIndex = -1; 6 | 7 | for (let v = 0; v < dist.length; v++) { 8 | if (visited[v] === false && dist[v] <= min) { 9 | min = dist[v]; 10 | minIndex = v; 11 | } 12 | } 13 | 14 | return minIndex; 15 | }; 16 | 17 | export const dijkstra = (graph: number[][], src: number) => { 18 | const dist: number[] = []; 19 | const visited: boolean[] = []; 20 | const length = graph.length; 21 | 22 | for (let i = 0; i < length; i++) { 23 | dist[i] = INF; 24 | visited[i] = false; 25 | } 26 | 27 | dist[src] = 0; 28 | 29 | for (let i = 0; i < length - 1; i++) { 30 | const u = minDistance(dist, visited); 31 | 32 | visited[u] = true; 33 | 34 | for (let v = 0; v < length; v++) { 35 | if (!visited[v] && graph[u][v] !== 0 && dist[u] !== INF && dist[u] + graph[u][v] < dist[v]) { 36 | dist[v] = dist[u] + graph[u][v]; 37 | } 38 | } 39 | } 40 | 41 | return dist; 42 | }; 43 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/graph/floyd-warshall.ts: -------------------------------------------------------------------------------- 1 | export const floydWarshall = (graph: number[][]) => { 2 | const dist: number[][] = []; 3 | const length = graph.length; 4 | 5 | for (let i = 0; i < length; i++) { 6 | dist[i] = []; 7 | for (let j = 0; j < length; j++) { 8 | if (i === j) { 9 | dist[i][j] = 0; 10 | } else if (!isFinite(graph[i][j])) { 11 | dist[i][j] = Infinity; 12 | } else { 13 | dist[i][j] = graph[i][j]; 14 | } 15 | } 16 | } 17 | 18 | for (let k = 0; k < length; k++) { 19 | for (let i = 0; i < length; i++) { 20 | for (let j = 0; j < length; j++) { 21 | if (dist[i][k] + dist[k][j] < dist[i][j]) { 22 | dist[i][j] = dist[i][k] + dist[k][j]; 23 | } 24 | } 25 | } 26 | } 27 | 28 | return dist; 29 | }; 30 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/graph/prim.ts: -------------------------------------------------------------------------------- 1 | const INF = Number.MAX_SAFE_INTEGER; 2 | 3 | const minKey = (graph: number[][], key: number[], visited: boolean[]) => { 4 | // Initialize min value 5 | let min = INF; 6 | let minIndex = 0; 7 | 8 | for (let v = 0; v < graph.length; v++) { 9 | if (visited[v] === false && key[v] < min) { 10 | min = key[v]; 11 | minIndex = v; 12 | } 13 | } 14 | 15 | return minIndex; 16 | }; 17 | 18 | export const prim = (graph: number[][]) => { 19 | const parent: number[] = []; 20 | const key: number[] = []; 21 | const visited: boolean[] = []; 22 | const length = graph.length; 23 | 24 | for (let i = 0; i < length; i++) { 25 | key[i] = INF; 26 | visited[i] = false; 27 | } 28 | 29 | key[0] = 0; 30 | parent[0] = -1; 31 | 32 | for (let i = 0; i < length - 1; i++) { 33 | const u = minKey(graph, key, visited); 34 | visited[u] = true; 35 | 36 | for (let v = 0; v < length; v++) { 37 | if (graph[u][v] && visited[v] === false && graph[u][v] < key[v]) { 38 | parent[v] = u; 39 | key[v] = graph[u][v]; 40 | } 41 | } 42 | } 43 | 44 | return parent; 45 | }; 46 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/greedy/knapsack.ts: -------------------------------------------------------------------------------- 1 | export function knapSack(capacity: number, weights: number[], values: number[]) { 2 | const n = values.length; 3 | let load = 0; 4 | let val = 0; 5 | 6 | for (let i = 0; i < n && load < capacity; i++) { 7 | if (weights[i] <= capacity - load) { 8 | val += values[i]; 9 | load += weights[i]; 10 | // console.log('using item ' + (i + 1) + ' for the solution'); 11 | } else { 12 | const r = (capacity - load) / weights[i]; 13 | val += r * values[i]; 14 | load += weights[i]; 15 | // console.log('using ratio of ' + r + ' for item ' + (i + 1) + ' for the solution'); 16 | } 17 | } 18 | return val; 19 | } 20 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/greedy/longest-common-subsequence.ts: -------------------------------------------------------------------------------- 1 | export function lcs(wordX: string, wordY: string, m = wordX.length, n = wordY.length): number { 2 | if (m === 0 || n === 0) { 3 | return 0; 4 | } 5 | 6 | if (wordX[m - 1] === wordY[n - 1]) { 7 | return 1 + lcs(wordX, wordY, m - 1, n - 1); 8 | } else { 9 | const a = lcs(wordX, wordY, m, n - 1); 10 | const b = lcs(wordX, wordY, m - 1, n); 11 | return a > b ? a : b; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/greedy/matrix-chain-multiplication.ts: -------------------------------------------------------------------------------- 1 | export function matrixChainOrder(p: number[], i = 1, j = p.length - 1): number { 2 | if (i === j) { 3 | return 0; 4 | } 5 | 6 | let min = Number.MAX_SAFE_INTEGER; 7 | 8 | for (let k = i; k < j; k++) { 9 | const count = 10 | matrixChainOrder(p, i, k) + matrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; 11 | 12 | if (count < min) { 13 | min = count; 14 | } 15 | } 16 | 17 | return min; 18 | } 19 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/greedy/min-coin-change.ts: -------------------------------------------------------------------------------- 1 | export function minCoinChange(coins: number[], amount: number) { 2 | const change: number[] = []; 3 | let total = 0; 4 | for (let i = coins.length; i >= 0; i--) { 5 | const coin = coins[i]; 6 | while (total + coin <= amount) { 7 | change.push(coin); 8 | total += coin; 9 | } 10 | } 11 | return change; 12 | } 13 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/math/find-divisors.ts: -------------------------------------------------------------------------------- 1 | export const findDivisors = (num: number) => { 2 | const divisors = []; 3 | 4 | const sqrt = Math.floor(Math.sqrt(num)); 5 | 6 | for (let i = 1; i <= sqrt; i++) { 7 | if (num % i === 0) { 8 | divisors.push(i); 9 | if (i !== sqrt) { 10 | divisors.push(Math.floor(num / i)); 11 | } 12 | } 13 | } 14 | 15 | if (num >= 2 && !divisors.includes(num)) { 16 | divisors.push(num); 17 | } 18 | 19 | divisors.sort((a, b) => a - b); 20 | 21 | return divisors; 22 | }; 23 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/math/gcd.ts: -------------------------------------------------------------------------------- 1 | export const gcd = (num1: number, num2: number): number => { 2 | if (num1 === 0 || num2 === 0) { 3 | return 0; 4 | } 5 | if (num1 === num2) { 6 | return num1; 7 | } 8 | if (num1 > num2) { 9 | return gcd(num1 - num2, num2); 10 | } 11 | return gcd(num1, num2 - num1); 12 | }; 13 | 14 | export let a = 5; 15 | export function test(){} 16 | 17 | export const gcdArray = (num: number[]) => { 18 | let result = num[0]; 19 | 20 | for (let i = 1; i < num.length; i++) { 21 | result = gcd(num[i], result); 22 | } 23 | 24 | return result; 25 | }; 26 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/math/greatest-difference.ts: -------------------------------------------------------------------------------- 1 | export const greatestDifference = (numbers: number[]) => { 2 | let index = 0; 3 | let largest = numbers[0]; 4 | const length = numbers.length; 5 | let number; 6 | let smallest = numbers[0]; 7 | 8 | for (index; index < length; index++) { 9 | number = numbers[index]; 10 | 11 | if (number > largest) { 12 | largest = number; 13 | } 14 | if (number < smallest) { 15 | smallest = number; 16 | } 17 | } 18 | 19 | return largest - smallest; 20 | }; 21 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/math/lcm.ts: -------------------------------------------------------------------------------- 1 | import { gcd } from './gcd'; 2 | 3 | export const lcm = (num1: number, num2: number) => { 4 | if (num1 === 0 || num2 === 0) { 5 | return 0; 6 | } 7 | num1 = Math.abs(num1); 8 | num2 = Math.abs(num2); 9 | return (num1 * num2) / gcd(num1, num2); 10 | }; 11 | 12 | export const lcmArray = (num: number[]) => { 13 | let result = num[0]; 14 | 15 | for (let i = 1; i < num.length; i++) { 16 | result = num[i] * result / gcd(num[i], result); 17 | } 18 | 19 | return result; 20 | }; 21 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/math/primality-test.ts: -------------------------------------------------------------------------------- 1 | export const isPrime = (n: number) => { 2 | if (n <= 1) { 3 | return false; 4 | } 5 | 6 | const sqrt = Math.floor(Math.sqrt(n)); 7 | for (let i = 2; i <= sqrt; i++) { 8 | if (n % i === 0) { 9 | return false; 10 | } 11 | } 12 | 13 | return true; 14 | }; 15 | 16 | export const testPrime = (n: number) => { 17 | if (n <= 1) { 18 | return false; 19 | } else { 20 | if (n === 2 || n === 3) { 21 | return true; 22 | } else if (n % 2 === 0) { 23 | return false; 24 | } else { 25 | const sqrt = Math.floor(Math.sqrt(n)); 26 | for (let i = 3; i <= sqrt; i += 2) { 27 | if (n % i === 0) { 28 | return false; 29 | } 30 | } 31 | } 32 | } 33 | return true; 34 | }; 35 | 36 | // tslint:disable-next-line:max-line-length 37 | export const isPrime2 = (n: number) => (n >= 2) ? (![...Array(n).keys()].slice(2).map(i => !(n % i)).includes(true) && ![0, 1].includes(n)) : false; 38 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/math/sieve-eratosthenes.ts: -------------------------------------------------------------------------------- 1 | export const sieveOfEratosthenes = (n: number) => { 2 | 3 | const sieve: boolean[] = []; 4 | const primes: number[] = []; 5 | 6 | sieve[1] = false; 7 | 8 | for (let i = 2; i <= n; i++) { 9 | sieve[i] = true; 10 | } 11 | 12 | for (let p = 2; p * p <= n; p++) { 13 | if (sieve[p]) { 14 | for (let i = p * 2; i <= n; i += p) { 15 | sieve[i] = false; 16 | } 17 | } 18 | } 19 | 20 | sieve.forEach((value, index) => { 21 | if (value) { 22 | primes.push(index); 23 | } 24 | }, primes); 25 | 26 | return primes; 27 | }; 28 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/search/binary-search-recursive.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, DOES_NOT_EXIST } from '../../util'; 2 | import { quickSort } from '../sorting/quicksort'; 3 | 4 | function binarySearchRecursive( 5 | array: T[], 6 | value: T, 7 | low: number, 8 | high: number, 9 | compareFn = defaultCompare 10 | ): number { 11 | if (low <= high) { 12 | const mid = Math.floor((low + high) / 2); 13 | const element = array[mid]; 14 | 15 | if (compareFn(element, value) === Compare.LESS_THAN) { 16 | return binarySearchRecursive(array, value, mid + 1, high, compareFn); 17 | } else if (compareFn(element, value) === Compare.BIGGER_THAN) { 18 | return binarySearchRecursive(array, value, low, mid - 1, compareFn); 19 | } else { 20 | return mid; 21 | } 22 | } 23 | return DOES_NOT_EXIST; 24 | } 25 | 26 | export function binarySearch(array: T[], value: T, compareFn = defaultCompare) { 27 | const sortedArray = quickSort(array); 28 | const low = 0; 29 | const high = sortedArray.length - 1; 30 | 31 | return binarySearchRecursive(array, value, low, high, compareFn); 32 | } 33 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/search/binary-search.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, DOES_NOT_EXIST } from '../../util'; 2 | import { quickSort } from '../sorting/quicksort'; 3 | 4 | export function binarySearch (array: T[], value: T, compareFn = defaultCompare) { 5 | const sortedArray = quickSort(array); 6 | let low = 0; 7 | let high = sortedArray.length - 1; 8 | 9 | while (low <= high) { 10 | const mid = Math.floor((low + high) / 2); 11 | const element = sortedArray[mid]; 12 | // console.log('mid element is ' + element); 13 | if (compareFn(element, value) === Compare.LESS_THAN) { 14 | low = mid + 1; 15 | // console.log('low is ' + low); 16 | } else if (compareFn(element, value) === Compare.BIGGER_THAN) { 17 | high = mid - 1; 18 | // console.log('high is ' + high); 19 | } else { 20 | // console.log('found it'); 21 | return mid; 22 | } 23 | } 24 | return DOES_NOT_EXIST; 25 | } 26 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/search/interpolation-search.ts: -------------------------------------------------------------------------------- 1 | import { 2 | biggerEquals, 3 | Compare, 4 | defaultCompare, 5 | defaultEquals, 6 | defaultDiff, 7 | DOES_NOT_EXIST, 8 | lesserEquals 9 | } from '../../util'; 10 | 11 | export function interpolationSearch( 12 | array: T[], 13 | value: T, 14 | compareFn = defaultCompare, 15 | equalsFn = defaultEquals, 16 | diffFn = defaultDiff 17 | ) { 18 | const { length } = array; 19 | let low = 0; 20 | let high = length - 1; 21 | let position = -1; 22 | let delta = -1; 23 | while ( 24 | low <= high && 25 | biggerEquals(value, array[low], compareFn) && 26 | lesserEquals(value, array[high], compareFn) 27 | ) { 28 | delta = diffFn(value, array[low]) / diffFn(array[high], array[low]); 29 | position = low + Math.floor((high - low) * delta); 30 | if (equalsFn(array[position], value)) { 31 | return position; 32 | } 33 | if (compareFn(array[position], value) === Compare.LESS_THAN) { 34 | low = position + 1; 35 | } else { 36 | high = position - 1; 37 | } 38 | } 39 | 40 | return DOES_NOT_EXIST; 41 | } 42 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/search/min-max-search.ts: -------------------------------------------------------------------------------- 1 | import { defaultCompare, Compare } from '../../util'; 2 | 3 | export function findMaxValue(array: T[], compareFn = defaultCompare) { 4 | if (array && array.length > 0) { 5 | let max = array[0]; 6 | for (let i = 1; i < array.length; i++) { 7 | if (compareFn(max, array[i]) === Compare.LESS_THAN) { 8 | max = array[i]; 9 | } 10 | } 11 | return max; 12 | } 13 | return undefined; 14 | } 15 | 16 | export function findMinValue(array: T[], compareFn = defaultCompare) { 17 | if (array && array.length > 0) { 18 | let min = array[0]; 19 | for (let i = 1; i < array.length; i++) { 20 | if (compareFn(min, array[i]) === Compare.BIGGER_THAN) { 21 | min = array[i]; 22 | } 23 | } 24 | return min; 25 | } 26 | return undefined; 27 | } 28 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/search/sequential-search.ts: -------------------------------------------------------------------------------- 1 | import { defaultEquals, DOES_NOT_EXIST, IEqualsFunction } from '../../util'; 2 | 3 | export function sequentialSearch(array: T[], value: T, equalsFn: IEqualsFunction = defaultEquals) { 4 | for (let i = 0; i < array.length; i++) { 5 | if (equalsFn(value, array[i])) { 6 | return i; 7 | } 8 | } 9 | return DOES_NOT_EXIST; 10 | } 11 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/shuffle/fisher–yates.ts: -------------------------------------------------------------------------------- 1 | import { swap } from '../../util'; 2 | 3 | export function shuffle(array: T[]) { 4 | for (let i = array.length - 1; i > 0; i--) { 5 | const randomIndex = Math.floor(Math.random() * (i + 1)); 6 | swap(array, i, randomIndex); 7 | } 8 | 9 | return array; 10 | } 11 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/sorting/bubble-sort-improved.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, swap } from '../../util'; 2 | 3 | export function modifiedBubbleSort(array: T[], compareFn = defaultCompare) { 4 | const { length } = array; 5 | 6 | for (let i = 0; i < length; i++) { 7 | // console.log('--- '); 8 | for (let j = 0; j < length - 1 - i; j++) { 9 | // console.log('compare ' + array[j] + ' with ' + array[j + 1]); 10 | if (compareFn(array[j], array[j + 1]) === Compare.BIGGER_THAN) { 11 | // console.log('swap ' + array[j] + ' with ' + array[j + 1]); 12 | swap(array, j, j + 1); 13 | } 14 | } 15 | } 16 | 17 | return array; 18 | } 19 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/sorting/bubble-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, swap } from '../../util'; 2 | 3 | export function bubbleSort(array: T[], compareFn = defaultCompare) { 4 | const { length } = array; 5 | 6 | for (let i = 0; i < length; i++) { 7 | // console.log('--- '); 8 | for (let j = 0; j < length - 1; j++) { 9 | // console.log('compare ' + array[j] + ' with ' + array[j + 1]); 10 | if (compareFn(array[j], array[j + 1]) === Compare.BIGGER_THAN) { 11 | // console.log('swap ' + array[j] + ' with ' + array[j + 1]); 12 | swap(array, j, j + 1); 13 | } 14 | } 15 | } 16 | 17 | return array; 18 | } 19 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/sorting/counting-sort.ts: -------------------------------------------------------------------------------- 1 | import { findMaxValue } from '../search/min-max-search'; 2 | 3 | export function countingSort(array: number[]) { 4 | 5 | if (array.length < 2) { 6 | return array; 7 | } 8 | 9 | const maxValue = findMaxValue(array); 10 | let sortedIndex = 0; 11 | const counts = new Array(maxValue + 1); 12 | 13 | array.forEach(element => { 14 | if (!counts[element]) { 15 | counts[element] = 0; 16 | } 17 | counts[element]++; 18 | }); 19 | 20 | // console.log('Frequencies: ' + counts.join()); 21 | 22 | counts.forEach((element, i) => { 23 | while (element > 0) { 24 | array[sortedIndex++] = i; 25 | element--; 26 | } 27 | }); 28 | 29 | return array; 30 | } 31 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/sorting/insertion-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare } from '../../util'; 2 | 3 | export const insertionSort = (array: any[], compareFn = defaultCompare) => { 4 | const { length } = array; 5 | let temp; 6 | for (let i = 1; i < length; i++) { 7 | let j = i; 8 | temp = array[i]; 9 | // console.log('to be inserted ' + temp); 10 | while (j > 0 && compareFn(array[j - 1], temp) === Compare.BIGGER_THAN) { 11 | // console.log('shift ' + array[j - 1]); 12 | array[j] = array[j - 1]; 13 | j--; 14 | } 15 | // console.log('insert ' + temp); 16 | array[j] = temp; 17 | } 18 | 19 | return array; 20 | }; 21 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/sorting/merge-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, ICompareFunction } from '../../util'; 2 | 3 | function merge(left: T[], right: T[], compareFn: ICompareFunction) { 4 | let i = 0; 5 | let j = 0; 6 | const result = []; 7 | 8 | while (i < left.length && j < right.length) { 9 | result.push(compareFn(left[i], right[j]) === Compare.LESS_THAN ? left[i++] : right[j++]); 10 | } 11 | 12 | return result.concat(i < left.length ? left.slice(i) : right.slice(j)); 13 | } 14 | 15 | export function mergeSort(array: T[], compareFn = defaultCompare): T[] { 16 | if (array.length > 1) { 17 | const { length } = array; 18 | const middle = Math.floor(length / 2); 19 | const left = mergeSort(array.slice(0, middle), compareFn); 20 | const right = mergeSort(array.slice(middle, length), compareFn); 21 | array = merge(left, right, compareFn); 22 | } 23 | 24 | return array; 25 | } 26 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/sorting/selection-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare, swap } from '../../util'; 2 | 3 | export const selectionSort = (array: any[], compareFn = defaultCompare) => { 4 | const { length } = array; 5 | let indexMin; 6 | 7 | for (let i = 0; i < length - 1; i++) { 8 | indexMin = i; 9 | // console.log('index ' + array[i]); 10 | for (let j = i; j < length; j++) { 11 | if (compareFn(array[indexMin], array[j]) === Compare.BIGGER_THAN) { 12 | // console.log('new index min ' + array[j]); 13 | indexMin = j; 14 | } 15 | } 16 | if (i !== indexMin) { 17 | // console.log('swap ' + array[i] + ' with ' + array[indexMin]); 18 | swap(array, i, indexMin); 19 | } 20 | } 21 | 22 | return array; 23 | }; 24 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/sorting/shell-sort.ts: -------------------------------------------------------------------------------- 1 | import { Compare, defaultCompare } from '../../util'; 2 | 3 | export function shellSort(array: T[], compareFn = defaultCompare) { 4 | let increment = array.length / 2; 5 | while (increment > 0) { 6 | for (let i = increment; i < array.length; i++) { 7 | let j = i; 8 | const temp = array[i]; 9 | 10 | while (j >= increment && compareFn(array[j - increment], temp) === Compare.BIGGER_THAN) { 11 | array[j] = array[j - increment]; 12 | j = j - increment; 13 | } 14 | 15 | array[j] = temp; 16 | } 17 | 18 | if (increment === 2) { 19 | increment = 1; 20 | } else { 21 | increment = Math.floor(increment * 5 / 11); 22 | } 23 | } 24 | return array; 25 | } 26 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/string/brute-force.ts: -------------------------------------------------------------------------------- 1 | const stringSearch = (text: string, pattern: string) => { 2 | const n = text.length; 3 | const m = pattern.length; 4 | 5 | if (m > n) { 6 | return -1; 7 | } 8 | 9 | for (let i = 0; i < n; i++) { 10 | let j = 0; 11 | for (j = 0; j < m && (i + j) < n; j++) { 12 | if (text.charAt(i + j) !== pattern.charAt(j)) { 13 | break; 14 | } 15 | } 16 | if (j === m) { 17 | return i; 18 | } 19 | } 20 | 21 | return -1; 22 | }; 23 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/string/huffman.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/data/ts-algorithms/algorithms/string/huffman.ts -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/string/knuth-morris-pratt.ts: -------------------------------------------------------------------------------- 1 | const buildTable = (pattern: string) => { 2 | const length = pattern.length; 3 | const table = []; 4 | let position = 2; 5 | let cnd = 0; 6 | 7 | table[0] = -1; 8 | table[1] = 0; 9 | 10 | while (position < length) { 11 | if (pattern[position - 1] === pattern[cnd]) { 12 | table[position++] = ++cnd; 13 | } else if (cnd > 0) { 14 | cnd = table[cnd]; 15 | } else { 16 | table[position++] = 0; 17 | } 18 | } 19 | 20 | return table; 21 | }; 22 | 23 | const knuthMorrisPratt = (text: string, pattern: string) => { 24 | const textLength = text.length; 25 | const patternLength = pattern.length; 26 | let m = 0; 27 | let i = 0; 28 | const table = buildTable(pattern); 29 | 30 | while (m + i < textLength) { 31 | if (pattern[i] === text[m + i]) { 32 | if (i === patternLength - 1) { 33 | return m; 34 | } 35 | i++; 36 | } else if (table[i] >= 0) { 37 | i = table[i]; 38 | m = m + i - table[i]; 39 | } else { 40 | i = 0; 41 | m++; 42 | } 43 | } 44 | 45 | return textLength; 46 | }; 47 | -------------------------------------------------------------------------------- /data/ts-algorithms/algorithms/string/longest-common-substring.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/data/ts-algorithms/algorithms/string/longest-common-substring.ts -------------------------------------------------------------------------------- /data/ts-algorithms/data-structures/models/linked-list-models.ts: -------------------------------------------------------------------------------- 1 | export class Node { 2 | constructor(public element: T, public next?: Node) {} 3 | } 4 | 5 | export class DoublyNode extends Node { 6 | constructor( 7 | public element: T, 8 | public next?: DoublyNode, 9 | public prev?: DoublyNode 10 | ) { 11 | super(element, next); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /data/ts-algorithms/data-structures/models/node.ts: -------------------------------------------------------------------------------- 1 | export class Node { 2 | left: Node; 3 | right: Node; 4 | 5 | constructor(public key: K) {} 6 | 7 | toString() { 8 | return `${this.key}`; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /data/ts-algorithms/data-structures/models/red-black-node.ts: -------------------------------------------------------------------------------- 1 | import { Node } from './node'; 2 | 3 | export enum Colors { 4 | RED = 0, 5 | BLACK = 1 6 | } 7 | 8 | export class RedBlackNode extends Node { 9 | left: RedBlackNode; 10 | right: RedBlackNode; 11 | parent: RedBlackNode; 12 | color: Colors; 13 | 14 | constructor(public key: K) { 15 | super(key); 16 | this.color = Colors.RED; 17 | } 18 | 19 | isRed() { 20 | return this.color === Colors.RED; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /data/ts-algorithms/data-structures/models/value-pair-lazy.ts: -------------------------------------------------------------------------------- 1 | import { ValuePair } from './value-pair'; 2 | 3 | export class ValuePairLazy extends ValuePair { 4 | constructor(public key: K, public value: V, public isDeleted = false) { 5 | super(key, value); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /data/ts-algorithms/data-structures/models/value-pair.ts: -------------------------------------------------------------------------------- 1 | export class ValuePair { 2 | constructor(public key: K, public value: V) {} 3 | 4 | toString() { 5 | return `[#${this.key}: ${this.value}]`; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /data/ts-algorithms/data-structures/stack-array.ts: -------------------------------------------------------------------------------- 1 | export default class StackArray { 2 | private items: T[]; 3 | 4 | constructor() { 5 | this.items = []; 6 | } 7 | 8 | push(element: T) { 9 | this.items.push(element); 10 | } 11 | 12 | pop() { 13 | return this.items.pop(); 14 | } 15 | 16 | peek() { 17 | return this.items[this.items.length - 1]; 18 | } 19 | 20 | isEmpty() { 21 | return this.items.length === 0; 22 | } 23 | 24 | size() { 25 | return this.items.length; 26 | } 27 | 28 | clear() { 29 | this.items = []; 30 | } 31 | 32 | toArray() { 33 | return this.items; 34 | } 35 | 36 | toString() { 37 | return this.items.toString(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /data/ts-algorithms/data-structures/stack-linked-list.ts: -------------------------------------------------------------------------------- 1 | import DoublyLinkedList from './doubly-linked-list'; 2 | 3 | export default class StackLinkedList { 4 | private items: DoublyLinkedList; 5 | 6 | constructor() { 7 | this.items = new DoublyLinkedList(); 8 | } 9 | 10 | push(element: T) { 11 | this.items.push(element); 12 | } 13 | 14 | pop() { 15 | if (this.isEmpty()) { 16 | return undefined; 17 | } 18 | const result = this.items.removeAt(this.size() - 1); 19 | return result; 20 | } 21 | 22 | peek() { 23 | if (this.isEmpty()) { 24 | return undefined; 25 | } 26 | return this.items.getElementAt(this.size() - 1).element; 27 | } 28 | 29 | isEmpty() { 30 | return this.items.isEmpty(); 31 | } 32 | 33 | size() { 34 | return this.items.size(); 35 | } 36 | 37 | clear() { 38 | this.items.clear(); 39 | } 40 | 41 | toString() { 42 | return this.items.toString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /data/ts-algorithms/others/balanced-symbols.ts: -------------------------------------------------------------------------------- 1 | import Stack from '../data-structures/stack'; 2 | 3 | export function parenthesesChecker(symbols: string) { 4 | const stack = new Stack(); 5 | const opens = '([{'; 6 | const closers = ')]}'; 7 | let balanced = true; 8 | let index = 0; 9 | let symbol: string; 10 | let top: string; 11 | 12 | while (index < symbols.length && balanced) { 13 | symbol = symbols[index]; 14 | if (opens.indexOf(symbol) >= 0) { 15 | stack.push(symbol); 16 | } else { 17 | if (stack.isEmpty()) { 18 | balanced = false; 19 | } else { 20 | top = stack.pop(); 21 | if (!(opens.indexOf(top) === closers.indexOf(symbol))) { 22 | balanced = false; 23 | } 24 | } 25 | } 26 | index++; 27 | } 28 | return balanced && stack.isEmpty(); 29 | } 30 | -------------------------------------------------------------------------------- /data/ts-algorithms/others/base-converter.ts: -------------------------------------------------------------------------------- 1 | import Stack from '../data-structures/stack'; 2 | 3 | export function decimalToBinary(decNumber: number) { 4 | const remStack = new Stack(); 5 | let rem: number; 6 | let binaryString = ''; 7 | 8 | while (decNumber > 0) { 9 | rem = Math.floor(decNumber % 2); 10 | remStack.push(rem); 11 | decNumber = Math.floor(decNumber / 2); 12 | } 13 | 14 | while (!remStack.isEmpty()) { 15 | binaryString += remStack.pop().toString(); 16 | } 17 | 18 | return binaryString; 19 | } 20 | 21 | export function baseConverter(decNumber: number, base: number) { 22 | const remStack = new Stack(); 23 | const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 24 | let rem: number; 25 | let baseString = ''; 26 | 27 | if (!(base >= 2 && base <= 36)) { 28 | return ''; 29 | } 30 | 31 | while (decNumber > 0) { 32 | rem = Math.floor(decNumber % base); 33 | remStack.push(rem); 34 | decNumber = Math.floor(decNumber / base); 35 | } 36 | 37 | while (!remStack.isEmpty()) { 38 | baseString += digits[remStack.pop()]; 39 | } 40 | 41 | return baseString; 42 | } 43 | -------------------------------------------------------------------------------- /data/ts-algorithms/others/factorial.ts: -------------------------------------------------------------------------------- 1 | export function factorialIterative(number: number) { 2 | if (number < 0) { 3 | return undefined; 4 | } 5 | let total = 1; 6 | for (let n = number; n > 1; n--) { 7 | total *= n; 8 | } 9 | return total; 10 | } 11 | 12 | export function factorial(n: number): number { 13 | if (n < 0) { 14 | return undefined; 15 | } 16 | if (n === 1 || n === 0) { 17 | return 1; 18 | } 19 | return n * factorial(n - 1); 20 | } 21 | -------------------------------------------------------------------------------- /data/ts-algorithms/others/fibonacci.ts: -------------------------------------------------------------------------------- 1 | export function fibonacci(n: number): number { 2 | if (n < 1) { return 0; } // {1} 3 | if (n <= 2) { return 1; } // {2} 4 | return fibonacci(n - 1) + fibonacci(n - 2); // {3} 5 | } 6 | 7 | export function fibonacciIterative(n: number) { 8 | if (n < 1) { return 0; } 9 | let fibNMinus2 = 0; 10 | let fibNMinus1 = 1; 11 | let fibN = n; 12 | for (let i = 2; i <= n; i++) { 13 | // n >= 2 14 | fibN = fibNMinus1 + fibNMinus2; // f(n-1) + f(n-2) 15 | fibNMinus2 = fibNMinus1; 16 | fibNMinus1 = fibN; 17 | } 18 | return fibN; 19 | } 20 | 21 | export function fibonacciMemoization(n: number) { 22 | if (n < 1) { return 0; } 23 | const memo = [0, 1]; 24 | const fibonacciMem = (num: number): number => { 25 | if (memo[num] != null) { return memo[num]; } 26 | return (memo[num] = fibonacciMem(num - 1) + fibonacciMem(num - 2)); 27 | }; 28 | return fibonacciMem(n); 29 | } 30 | -------------------------------------------------------------------------------- /data/ts-algorithms/others/hot-potato.ts: -------------------------------------------------------------------------------- 1 | import Queue from '../data-structures/queue'; 2 | 3 | export function hotPotato(elementsList: any[], num: number) { 4 | const queue = new Queue(); 5 | const elimitatedList = []; 6 | 7 | for (let i = 0; i < elementsList.length; i++) { 8 | queue.enqueue(elementsList[i]); 9 | } 10 | 11 | while (queue.size() > 1) { 12 | for (let i = 0; i < num; i++) { 13 | queue.enqueue(queue.dequeue()); 14 | } 15 | elimitatedList.push(queue.dequeue()); 16 | } 17 | 18 | return { 19 | elimitated: elimitatedList, 20 | winner: queue.dequeue() 21 | }; 22 | } 23 | -------------------------------------------------------------------------------- /data/ts-algorithms/others/palindrome-checker.ts: -------------------------------------------------------------------------------- 1 | import Deque from '../data-structures/deque'; 2 | 3 | export function palindromeChecker(aString: string) { 4 | 5 | if (aString === undefined || aString === null || 6 | (aString !== null && aString.length === 0)) { 7 | return false; 8 | } 9 | 10 | const deque = new Deque(); 11 | const lowerString = aString.toLocaleLowerCase().split(' ').join(''); 12 | let firstChar: string, lastChar: string; 13 | 14 | for (let i = 0; i < lowerString.length; i++) { 15 | deque.addBack(lowerString.charAt(i)); 16 | } 17 | 18 | while (deque.size() > 1) { 19 | firstChar = deque.removeFront(); 20 | lastChar = deque.removeBack(); 21 | if (firstChar !== lastChar) { 22 | return false; 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | -------------------------------------------------------------------------------- /images/Header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/images/Header.png -------------------------------------------------------------------------------- /images/Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MrVPlusOne/LambdaNet/f27a7a00ef3b8f453a4d477816806456d7f25f15/images/Logo.png -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version = 1.3.13 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.0") 2 | addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.0.0") 3 | 4 | -------------------------------------------------------------------------------- /results/experiments.txt: -------------------------------------------------------------------------------- 1 | Encoder iterations: 5, 10, 15 2 | Encoding vector dim: 20, 40, 80 -------------------------------------------------------------------------------- /scripts/experiment/test1.ts: -------------------------------------------------------------------------------- 1 | import * as ts from 'typescript'; 2 | 3 | interface MediaStreamError { 4 | readonly constraintName: string | null; 5 | readonly message: string | null; 6 | readonly name: string; 7 | } 8 | 9 | declare var MediaStreamError: { 10 | prototype: MediaStreamError; 11 | new(): MediaStreamError; 12 | }; 13 | 14 | interface MediaStreamErrorEvent extends Event { 15 | readonly error: MediaStreamError | null; 16 | } 17 | 18 | declare var MediaStreamErrorEvent: { 19 | prototype: MediaStreamErrorEvent; 20 | new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent; 21 | }; 22 | 23 | /** The MediaStreamEvent interface represents events that occurs in relation to a MediaStream. Two events of this type can be thrown: addstream and removestream. */ 24 | interface MediaStreamEvent extends Event { 25 | readonly stream: MediaStream | null; 26 | } 27 | 28 | let storage = top.caches; 29 | let keys = storage.keys(); 30 | console.log(keys); 31 | storage = 4; -------------------------------------------------------------------------------- /scripts/experiment/typeQuery.ts: -------------------------------------------------------------------------------- 1 | import * as ts from "typescript"; 2 | 3 | 4 | function main(){ 5 | let program = ts.createProgram(["test1.ts"],{ 6 | target: ts.ScriptTarget.ES2018, 7 | module: ts.ModuleKind.CommonJS 8 | }); 9 | 10 | let src = program.getSourceFile("test1.ts"); 11 | 12 | let diag = program.getSemanticDiagnostics(null, null); 13 | // diag.forEach(console.log); 14 | 15 | console.log(src["locals"]); 16 | 17 | } 18 | 19 | main(); 20 | console.log("Finished."); 21 | -------------------------------------------------------------------------------- /scripts/linux/install-sbt.sh: -------------------------------------------------------------------------------- 1 | echo "deb https://repo.scala-sbt.org/scalasbt/debian all main" | sudo tee /etc/apt/sources.list.d/sbt.list 2 | echo "deb https://repo.scala-sbt.org/scalasbt/debian /" | sudo tee /etc/apt/sources.list.d/sbt_old.list 3 | curl -sL "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x2EE0EA64E40A89B84B2DF73499E82A75642AC823" | sudo apt-key add 4 | sudo apt-get update 5 | sudo apt-get install sbt 6 | -------------------------------------------------------------------------------- /scripts/runAnnotsEval.sh: -------------------------------------------------------------------------------- 1 | export OMP_NUM_THREADS=1 2 | sbt "runMain lambdanet.test.EvalUserAnnots" 3 | -------------------------------------------------------------------------------- /scripts/runService.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | export OMP_NUM_THREADS=1 4 | sbt service 5 | -------------------------------------------------------------------------------- /scripts/runTraining.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # ssh into the remote machine 3 | # start tmux by typing tmux into the shell 4 | # start the process you want inside the started tmux session 5 | # leave/detach the tmux session by typing Ctrl+b and then d 6 | 7 | # When you come back again and want to check the status of your process you 8 | # can use tmux attach to attach to your tmux session. 9 | #cd ./scripts/ts/ 10 | #tsc 11 | #cd ../.. 12 | #git pull # useful when running on server 13 | export OMP_NUM_THREADS=1 14 | sbt "train" 15 | 16 | -------------------------------------------------------------------------------- /scripts/ts/installDependencies.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | npm install -g \ 3 | typescript \ 4 | cloc 5 | 6 | npm i fs source-map-support yargs \ 7 | @types/node @types/source-map-support @types/typescript @types/yargs 8 | # remember to compile the scripts under scripts/ts using tsc 9 | -------------------------------------------------------------------------------- /scripts/ts/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ts-to-scala-parser", 3 | "author": "Maruth Goyal, Jiayi Wei", 4 | "version": "0.1.0", 5 | "dependencies": { 6 | "@types/source-map-support": "^0.5.0", 7 | "@types/typescript": "^2.0.0", 8 | "@types/yargs": "^12.0.10", 9 | "fs": "latest", 10 | "source-map-support": "^0.5.11", 11 | "typescript": "^3.4.1", 12 | "yargs": "^13.2.2" 13 | }, 14 | "devDependencies": { 15 | "@types/node": "^11.10.5" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /scripts/ts/parsingFromFile.ts: -------------------------------------------------------------------------------- 1 | import 'source-map-support/register'; 2 | import {parseFiles} from "./parsing"; 3 | import fs = require("fs"); 4 | 5 | import * as yargs from 'yargs' 6 | import {Argv} from "yargs"; 7 | 8 | let argv = yargs 9 | .command('print', "Parse and print the resulted JSON.", (yargs: Argv) => { 10 | return yargs 11 | .option('src', { 12 | describe: "A list of source files to parse and output", 13 | }) 14 | .option('lib', { 15 | // alias: 'v', 16 | default: [], 17 | }) 18 | .option('out',{ 19 | describe: "If set, write the result json into the specified file instead of printing it.", 20 | default: null 21 | }) 22 | }) 23 | .array("src") 24 | .array("lib") 25 | .argv; 26 | 27 | let result = parseFiles(argv.src as string[], argv.lib as string[]); 28 | let json = JSON.stringify(result); 29 | if(argv.out){ 30 | fs.writeFileSync(argv.out as string, json) 31 | }else{ 32 | console.log(json); 33 | } 34 | -------------------------------------------------------------------------------- /scripts/ts/parsingFromString.ts: -------------------------------------------------------------------------------- 1 | import * as parsing from "./parsing"; 2 | import * as ts from "typescript"; 3 | import 'source-map-support/register'; 4 | import {flattenBlock, GStmt} from "./parsing"; 5 | 6 | let content = process.argv[2]; 7 | 8 | let source = ts.createSourceFile("temp.ts", content, 9 | ts.ScriptTarget.ES2018, true, ts.ScriptKind.TS); 10 | let program = ts.createProgram([], { 11 | target: ts.ScriptTarget.ES2018, 12 | module: ts.ModuleKind.CommonJS 13 | }); 14 | 15 | const checker = program.getTypeChecker(); 16 | program.getSemanticDiagnostics(); 17 | 18 | let out: GStmt[] = []; 19 | 20 | let parser = new parsing.StmtParser(checker); 21 | 22 | source.statements.forEach(s => { 23 | let r = parser.parseStmt(s); 24 | if (!r) { 25 | throw new Error("failed for: " + s.getFullText(source)); 26 | } 27 | out.push(flattenBlock(r)); 28 | }); 29 | 30 | 31 | console.log(JSON.stringify(out)); 32 | -------------------------------------------------------------------------------- /scripts/ts/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "esnext" 6 | ], 7 | "module": "commonjs", 8 | "noImplicitAny": true, 9 | "preserveConstEnums": true, 10 | // "strict": true, 11 | // "sourceMap": true, 12 | "inlineSourceMap": true 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /scripts/ts/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "no-string-throw": true, 4 | "no-unused-expression": true, 5 | "no-duplicate-variable": true, 6 | "curly": true, 7 | "class-name": true, 8 | "semicolon": [ 9 | true, 10 | "always" 11 | ], 12 | "triple-equals": true 13 | }, 14 | "defaultSeverity": "warning" 15 | } 16 | -------------------------------------------------------------------------------- /scripts/uploadData-aws.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "Compressing parsed repo chunks..." 4 | zip parsedRepos-no_any.zip -r data/parsedRepos-no_any 5 | echo "Uploading to AWS..." 6 | scp -r parsedRepos-no_any.zip aws:~/Jiayi/LambdaNet/ 7 | -------------------------------------------------------------------------------- /scripts/uploadData.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | #scp data/predicateGraphs.serialized titan4:~/TypingNet/data/predicateGraphs.serialized; 4 | echo "upload to utopia1..."; 5 | scp -r data/parsedRepos utopia1:~/TypingNet/data/; 6 | echo "upload to utopia2..."; 7 | scp -r data/parsedRepos utopia2:~/TypingNet/data/; -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/main/scala/WhereAreThings.scala: -------------------------------------------------------------------------------- 1 | import lambdanet.translation.PredicateGraph 2 | import lambdanet.LibDefs 3 | 4 | /** 5 | * Type constraints/predicates are defined in [[PredicateGraph]]. 6 | * Examples showing how to generate predicate graphs from source code are 7 | * inside test/scala/lambdanet/utils. Particularly under the test named 8 | * "predicate graph tests". 9 | * Library definitions are stored as a [[LibDefs]] class. But the current 10 | * format might not be optimized for performing type checking. 11 | */ 12 | object WhereAreThings 13 | -------------------------------------------------------------------------------- /src/main/scala/funcdiff/BatchingService.scala: -------------------------------------------------------------------------------- 1 | package funcdiff 2 | 3 | import scala.concurrent.{Future, Promise} 4 | import collection.concurrent.TrieMap 5 | 6 | class BatchingService(f: CompNode => CompNode) { 7 | private val registered = TrieMap[CompNode, Promise[CompNode]]() 8 | 9 | def register(x: CompNode): Future[CompNode] = { 10 | val p = registered.getOrElseUpdate(x, { 11 | Promise[CompNode]() 12 | }) 13 | p.future 14 | } 15 | 16 | def compute(implicit mode: GraphMode): Unit = { 17 | val (xs, ps) = registered.toVector.unzip 18 | val ys = f(stackRows(xs)) 19 | ys.rows.zip(ps).foreach { 20 | case (y, p) => 21 | p.success(y) 22 | } 23 | } 24 | } 25 | 26 | object BatchingService { 27 | def apply(f: CompNode => CompNode) = new BatchingService(f) 28 | } 29 | -------------------------------------------------------------------------------- /src/main/scala/funcdiff/DebugTime.scala: -------------------------------------------------------------------------------- 1 | package funcdiff 2 | 3 | import funcdiff.SimpleMath.TimeLogger 4 | 5 | object DebugTime extends TimeLogger() { 6 | 7 | def doTenTimes[T](f: => T): T = { 8 | f; f; f; f; f; f; f; f; f; f 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/scala/funcdiff/GraphNode.scala: -------------------------------------------------------------------------------- 1 | package funcdiff 2 | 3 | sealed trait GraphMode 4 | /** [[CompNode]] created under this mode consumes less memory but does not support back 5 | * propagation. Use this mode during testing. */ 6 | case object ModeEval extends GraphMode 7 | /** [[CompNode]] created under this mode needs to keep the entire computation graph 8 | * in the memory to support gradient back propagation. Use this mode during training. */ 9 | case object ModeTraining extends GraphMode 10 | -------------------------------------------------------------------------------- /src/main/scala/funcdiff/package.scala: -------------------------------------------------------------------------------- 1 | import scala.language.implicitConversions 2 | 3 | package object funcdiff extends APITrait { 4 | type IS[T] = IndexedSeq[T] 5 | val IS = IndexedSeq 6 | 7 | type Real = Double 8 | 9 | implicit def toPath(str: String): SymbolPath = { 10 | SymbolPath.empty / Symbol(str) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/ServerUtils.scala: -------------------------------------------------------------------------------- 1 | package lambdanet 2 | 3 | object ServerUtils { 4 | 5 | val serverPath = "utopia1:/mnt/nas/jiayi/withAny" 6 | def downloadPredictions(task: String, epoch: Int): String = { 7 | val remoteDir = s"$serverPath/$task/saved/epoch$epoch" 8 | val localDir = s"~/Downloads/LambdaNetDownloads/$task-predictions-epoch$epoch" 9 | 10 | s""" 11 | |mkdir $localDir; 12 | |scp -r $remoteDir/predictions $localDir/predictions; 13 | |scp $remoteDir/correct.html $localDir/correct.html; 14 | |scp $remoteDir/incorrect.html $localDir/incorrect.html; 15 | |scp -r $remoteDir/bootstrap $localDir/bootstrap; 16 | |""".stripMargin 17 | } 18 | 19 | def main(args: Array[String]): Unit = { 20 | println(downloadPredictions("LambdaNet-GAT1-fc2-decay-with_any-lossAgg_sum-8", 60)) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/architecture/ArchitectureHelper.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.architecture 2 | 3 | import botkop.numsca 4 | import botkop.numsca.Tensor 5 | import funcdiff.{CompNode, LayerFactory, SymbolPath, TensorExtension} 6 | 7 | trait ArchitectureHelper { 8 | def dimEmbedding: Int 9 | def layerFactory: LayerFactory 10 | 11 | private val normalizeFactor = 0.1 / math.sqrt(dimEmbedding) 12 | def randomVec(): Tensor = { 13 | numsca.randn(1, dimEmbedding) * normalizeFactor 14 | } 15 | 16 | def randomVar(name: SymbolPath): CompNode = { 17 | layerFactory.getVar(name)(randomVec()) 18 | } 19 | 20 | def randomUnitVec(): Tensor = { 21 | TensorExtension.randomUnitVec(dimEmbedding).reshape(1, dimEmbedding) 22 | } 23 | 24 | def randomUnitVar(name: SymbolPath): CompNode = { 25 | layerFactory.getVar(name)(randomUnitVec()) 26 | } 27 | 28 | def zeroVec() = numsca.zeros(1, dimEmbedding) 29 | } 30 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/architecture/package.scala: -------------------------------------------------------------------------------- 1 | package lambdanet 2 | 3 | import funcdiff.CompNode 4 | import lambdanet.translation.PredicateGraph.ProjNode 5 | 6 | package object architecture { 7 | case class Embedding( 8 | vars: Map[ProjNode, CompNode] 9 | ) 10 | } 11 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/correctness/NewestModelService.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.correctness 2 | 3 | import ammonite.ops.Path 4 | import funcdiff.SimpleMath.readObjectFromFile 5 | import lambdanet.utils.ModelFormatConversion 6 | import lambdanet.{Model, announced} 7 | 8 | object NewestModelService { 9 | val modelDir: Path = ModelFormatConversion.newestModelDir 10 | val modelCachePath: Path = modelDir / "model.serialized" 11 | 12 | lazy val model: Model = 13 | announced(s"Loading model from $modelCachePath") { 14 | readObjectFromFile[Model](modelCachePath) 15 | } 16 | lazy val service: model.PredictionService = 17 | model.PredictionService(numOfThreads = 8, predictTopK = Int.MaxValue) 18 | } 19 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/correctness/OutputUtils.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.correctness 2 | 3 | import ammonite.ops.Path 4 | import ammonite.{ops => amm} 5 | import lambdanet.{SM, announced} 6 | 7 | object OutputUtils { 8 | def save(resultsDir: Path, filename: String, obj: Serializable): Unit = { 9 | if (!amm.exists(resultsDir)) { 10 | amm.mkdir(resultsDir) 11 | } 12 | val path = resultsDir / filename 13 | announced(s"saving $path") { 14 | SM.saveObjectToFile(path.toIO)(obj) 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/correctness/Sampling.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.correctness 2 | 3 | import java.util.concurrent.ThreadLocalRandom 4 | 5 | object Sampling { 6 | 7 | /** 8 | * @param items items with unnormalized PMF 9 | */ 10 | def choose[T](items: Seq[(T, Double)]): T = { 11 | val p = ThreadLocalRandom.current().nextDouble() 12 | choose(items, p) 13 | } 14 | 15 | def choose[T](items: Seq[(T, Double)], p: Double): T = { 16 | assert(0 <= p && p <= 1) 17 | 18 | var totalProb = 0.0 19 | for ((_, prob) <- items) { 20 | totalProb += prob 21 | } 22 | val adjustedProb = totalProb * p 23 | 24 | var sum = 0.0 25 | for ((item, prob) <- items) { 26 | sum += prob 27 | if (sum >= adjustedProb) { 28 | return item 29 | } 30 | } 31 | throw new NoSuchElementException 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/correctness/Schedule.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.correctness 2 | 3 | /** 4 | * Given initial temperature and epoch, returns 5 | */ 6 | trait Schedule extends Function1[Int, Double] { 7 | def t0: Double 8 | 9 | def description: String 10 | } 11 | 12 | case class LogSchedule(t0: Double) extends Schedule { 13 | val description: String = 14 | "Logarithmic schedule (t(k) = t0 * log(2) / log(k+1))" 15 | 16 | def apply(epoch: Int): Double = 17 | t0 * math.log(2) / math.log(epoch + 1) 18 | } 19 | 20 | case class ExpSchedule(t0: Double, gamma: Double) extends Schedule { 21 | val description: String = 22 | "Exponential decay schedule (t(k) = t0 * gamma^(k-1))" 23 | 24 | def apply(epoch: Int): Double = 25 | t0 * math.pow(gamma, epoch - 1) 26 | } 27 | 28 | case class FastSchedule(t0: Double) extends Schedule { 29 | val description: String = 30 | "Fast schedule (t(k) = t0 / k)" 31 | 32 | def apply(epoch: Int): Double = 33 | t0 / epoch 34 | } 35 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/correctness/Search.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.correctness 2 | 3 | trait Search {} 4 | 5 | trait Correction extends (Assignment => Assignment) 6 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/correctness/ValidTypeGen.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.correctness 2 | 3 | import lambdanet.translation.PredicateGraph.{PNode, PType} 4 | 5 | trait ValidTypeGen { 6 | def validTypes( 7 | allTypes: Seq[PType], 8 | nodes: Set[PNode], 9 | assignment: Assignment 10 | ): Seq[PType] 11 | 12 | def toType(assignment: Assignment, nodeOrType: NodeOrType): PType = nodeOrType match { 13 | case Left(node) => assignment(node) 14 | case Right(typ) => typ 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/correctness/package.scala: -------------------------------------------------------------------------------- 1 | package lambdanet 2 | 3 | import lambdanet.train.TopNDistribution 4 | import lambdanet.translation.PredicateGraph.{PNode, PType} 5 | 6 | package object correctness { 7 | type Assignment = Map[PNode, PType] 8 | type TypeDistrs = Map[PNode, TopNDistribution[PType]] 9 | 10 | type NodeOrType = Either[PNode, PType] 11 | type Bounds[T] = Map[PNode, Set[Either[T, T]]] 12 | } 13 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/train/Timeouts.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.train 2 | 3 | import ammonite.ops.{exists, pwd, read} 4 | import lambdanet.{printInfo, printResult, printWarning} 5 | import lambdanet.utils.ProgramParsing 6 | 7 | object Timeouts { 8 | import scala.concurrent.duration._ 9 | type Duration = FiniteDuration 10 | 11 | var restartOnTimeout = true 12 | var forwardTimeout: Duration = 100.seconds 13 | var optimizationTimeout: Duration = 120.seconds 14 | 15 | def readFromFile(): Unit = { 16 | val file = pwd / "configs" / "timeouts.json" 17 | printInfo(s"read timeouts from '$file'") 18 | if (!exists(file)) { 19 | printWarning( 20 | s"Timeouts file not found under '$file', use default timeout values" 21 | ) 22 | return 23 | } 24 | import ProgramParsing._ 25 | val text = read(file) 26 | printResult(s"use timeouts: \n$text") 27 | 28 | val js = parseJson(text) 29 | 30 | restartOnTimeout = asBoolean(js("restartOnTimeout")) 31 | forwardTimeout = asNumber(js("forwardTimeout")).seconds 32 | optimizationTimeout = asNumber(js("optimizationTimeout")).seconds 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/train/TrainingControl.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.train 2 | 3 | import ammonite.ops._ 4 | 5 | /** Use text files to control the training loop (stop, restore, etc) */ 6 | private case class TrainingControl(resultsDir: Path) { 7 | val stopFile: Path = resultsDir / "control" / "stop.txt" 8 | val restoreFile: Path = resultsDir / "control" / "restore.txt" 9 | 10 | def shouldStop(consumeFile: Boolean): Boolean = { 11 | val stop = exists(stopFile) 12 | if (consumeFile && stop) { 13 | rm(stopFile) 14 | } 15 | stop 16 | } 17 | 18 | /** If [[restoreFile]] exists, read the path from the file. 19 | * @param consumeFile if set to true, delete [[restoreFile]] after reading. */ 20 | def restoreFromFile(consumeFile: Boolean): Option[Path] = { 21 | val restore = exists(restoreFile) 22 | if (restore) { 23 | val content = read(restoreFile).trim 24 | val p = try Path(content) 25 | catch { 26 | case _: IllegalArgumentException => restoreFile / up / RelPath(content) 27 | } 28 | if (consumeFile) { 29 | rm(restoreFile) 30 | } 31 | Some(p) 32 | } else None 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/translation/package.scala: -------------------------------------------------------------------------------- 1 | package lambdanet 2 | 3 | import lambdanet.Surface.GStmt 4 | import lambdanet.translation.IR.{BlockStmt, IRStmt} 5 | import lambdanet.translation.PredicateGraph.{PNode, PType} 6 | import lambdanet.translation.QLang.QStmt 7 | 8 | package object translation { 9 | type PAnnot = Annot[PType] 10 | 11 | def makeSureInBlock(stmts: Vector[IRStmt]): BlockStmt = { 12 | stmts match { 13 | case Vector(b: BlockStmt) => b 14 | case _ => BlockStmt(stmts) 15 | } 16 | } 17 | 18 | def makeSureInBlockSurface(stmts: Vector[GStmt]): Surface.BlockStmt = { 19 | stmts match { 20 | case Vector(b: Surface.BlockStmt) => b 21 | case _ => Surface.BlockStmt(stmts) 22 | } 23 | } 24 | 25 | def makeSureInBlockQ(stmt: QStmt): QLang.BlockStmt = { 26 | stmt match { 27 | case b: QLang.BlockStmt => b 28 | case _ => QLang.BlockStmt(Vector(stmt)) 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/utils/IndexedHashSet.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.utils 2 | 3 | import scala.collection.mutable 4 | import scala.util.Random 5 | 6 | class IndexedHashSet[X](var elements: Vector[X]) { 7 | private val set = mutable.HashSet(elements: _*) 8 | 9 | def +=(e: X): Unit = { 10 | if (!set.contains(e)) { 11 | set += e 12 | elements = elements :+ e 13 | } 14 | } 15 | 16 | def sample()(implicit random: Random): X = { 17 | val idx = random.nextInt(elements.size) 18 | elements(idx) 19 | } 20 | } 21 | 22 | object IndexedHashSet { 23 | def apply[X](elements: X*): IndexedHashSet[X] = 24 | new IndexedHashSet(elements.toVector) 25 | } 26 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/utils/PrecomputeResults.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.utils 2 | 3 | import ammonite.ops.pwd 4 | import ammonite.{ops => amm} 5 | import lambdanet.{Model, SM, TypeInferenceService} 6 | 7 | object PrecomputeResults { 8 | val modelDir = ModelFormatConversion.newestModelDir 9 | val modelPath = modelDir / "model.serialized" 10 | 11 | val model = SM.readObjectFromFile[Model](modelPath) 12 | val service = model.PredictionService(numOfThreads = 8, predictTopK = 5) 13 | 14 | def precompute(testName: String, overwrite: Boolean = false): Unit = { 15 | val inputPath = pwd / "data" / "tests" / testName 16 | val outputPath = inputPath / "results.serialized" 17 | if (amm.exists(outputPath) && !overwrite) 18 | return 19 | val results = service.predictOnSourceFiles( 20 | inputPath, 21 | warnOnErrors = false 22 | ) 23 | SM.saveObjectToFile(outputPath.toIO)(results.asInstanceOf[Serializable]) 24 | } 25 | 26 | def main(args: Array[String]): Unit = { 27 | args.foreach(precompute(_)) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/utils/ProcessAngular.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.utils 2 | 3 | import ammonite.ops._ 4 | object ProcessAngular { 5 | def process(rootDir: Path): Unit = { 6 | for { 7 | dir <- ls(rootDir) if dir.isDir 8 | name = dir.last 9 | } { 10 | val file = dir / s"$name.d.ts" 11 | if (exists(file)) { 12 | val target = dir / "index.d.ts" 13 | assert(!exists(target)) 14 | mv(file, target) 15 | val data = 16 | s""" 17 | |{ 18 | | "name": "@angular/$name" 19 | |} 20 | """.stripMargin 21 | write.over(dir / "package.json", data) 22 | } 23 | } 24 | } 25 | 26 | def main(args: Array[String]): Unit = { 27 | import lambdanet.PrepareRepos 28 | process( 29 | PrepareRepos.reposDir / RelPath("/declarations/angular") 30 | ) 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/scala/lambdanet/utils/ReportFinish.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.utils 2 | 3 | import ammonite.ops.{pwd, read} 4 | 5 | object ReportFinish { 6 | def main(args: Array[String]): Unit = { 7 | val (name, emailService) = readEmailInfo("reportFinish") 8 | 9 | emailService.sendMail(emailService.userEmail)( 10 | s"TypingNet: Training process on $name has stopped", 11 | "The training process has stopped." 12 | ) 13 | } 14 | 15 | type MachineName = String 16 | def readEmailInfo(taskName: String): (MachineName, EmailService) = { 17 | val emailFile = pwd / "configs" / "emails.txt" 18 | println(s"reading email credentials from '$emailFile'...") 19 | val Array(email, password, name) = read(emailFile).trim.split("\n") 20 | s"$name-$taskName" -> EmailService(email, password) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/scala/lambdanet/MyTest.scala: -------------------------------------------------------------------------------- 1 | package lambdanet 2 | 3 | import org.scalacheck.{Prop, Test} 4 | import org.scalatest.{Assertion, Matchers} 5 | 6 | trait MyTest extends Matchers { 7 | def checkProp( 8 | prop: Prop, 9 | paramTrans: Test.Parameters => Test.Parameters = identity 10 | ): Assertion = { 11 | val p = paramTrans(Test.Parameters.default.withMaxSize(50)) 12 | val result = Test.check(p, prop) 13 | assert(result.passed, result.status) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/scala/lambdanet/correctness/InconsistentLibDefs.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.correctness 2 | 3 | import ammonite.{ops => amm} 4 | import lambdanet.translation.PredicateGraphLoader.libDefs 5 | import org.scalatest.WordSpec 6 | 7 | class InconsistentLibDefs extends WordSpec { 8 | "Boolean nodes have two versions in LibDefs" in { 9 | val dir = amm.pwd / "data" / "tests" / "c1" 10 | val (graph, _, results) = InputUtils.loadGraphAndPredict(dir) 11 | 12 | val checker = TypeChecker(graph, libDefs) 13 | val node14 = graph.nodes.find(x => x.fromProject && x.getId == 14).get 14 | val booleanNodeInConstraint = checker.subtypesToCheck.find(x => x._1.nameOpt.contains('Boolean) && x._2 == node14).get._1 15 | val booleanInConstraint = libDefs.nodeMapping(booleanNodeInConstraint).typeOpt.get 16 | val booleanInPrediction = results(node14).distr.find(_._2.showSimple.contains("Boolean")).get._2 17 | assert(booleanInConstraint == booleanInPrediction) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/scala/lambdanet/correctness/SamplingTest.scala: -------------------------------------------------------------------------------- 1 | package lambdanet.correctness 2 | 3 | import org.scalatest.WordSpec 4 | 5 | class SamplingTest extends WordSpec { 6 | "choosing from discrete distribution" should { 7 | "pass an simple example" in { 8 | val itemsWithProb = Seq(1, 2, 3, 4).zip(Seq(0.1, 0.4, 0.3, 0.1)) 9 | assert(Sampling.choose(itemsWithProb, 0.11 / 0.9) == 2) 10 | assert(Sampling.choose(itemsWithProb, 0.1 / 0.9) == 1) 11 | assert(Sampling.choose(itemsWithProb, 1) == 4) 12 | } 13 | } 14 | } 15 | --------------------------------------------------------------------------------

2 | 3 |
4 | Mojiito 5 |
6 |
7 |