language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
300
1.632813
2
[]
no_license
package codeOrchestra.flex.processors.transparent; import jetbrains.mps.smodel.SNode; /** * @author Anton.I.Neverov */ public class E4XConditionProcessor extends ParenthesizedExpressionProcessor { public E4XConditionProcessor(SNode node) { super(node); childName = "condition"; } }
TypeScript
UTF-8
784
3.59375
4
[]
no_license
import { Sorter } from "./Sorter"; export class NumbersCollection extends Sorter{ constructor (public data: number[]) { super(); }; /* Notice that the below is equal to line 2: data: number[]; constructor (data: number[]) { this.data = data; } */ get length(): number { return this.data.length; } // this compare function returns true if the left number is more than the right number compare(leftIndex: number, rightIndex: number): boolean { return this.data[leftIndex] > this.data[rightIndex]; } // this swap function doesn't return anything swap(leftIndex: number, rightIndex: number): void { const leftHand = this.data[leftIndex]; this.data[leftIndex] = this.data[rightIndex]; this.data[rightIndex] = leftHand; } }
Markdown
UTF-8
4,388
3.890625
4
[ "MIT" ]
permissive
# Agenda 1. [Why functional programming?](#/2) 1. [Why elixir?](#/3) 1. [Basic types & Operators](#/4) 1. [Pattern matching](#/5) 1. [Functions](#/6) 1. [Recursion](#/7) 1. [Concurrency](#/8) # Why FP? - Abstractions - Immutability - DSLs - Concurrency #Why elixir? - Runs on the Erlang VM - Reuse Erlang libraries - Modern functional language - Erlang VM - Scalable - Fault-Tolerant - Simplified concurrent programming #Basic Types & Operators ## Basic Types ``` Elixir # There are numbers 3 # integer 3.0 # float # Atoms, that are literals, a constant with name. :hello # atom # Strings "hello" # string # Lists that are implemented as linked lists. [1,2,3] # list # Tuples that are stored contiguously in memory. {:ok,"hello",1} # tuple # Maps %{:first_name => "Christian", :last_name => "Drumm"} ``` ## Operators ``` Elixir # Arithmetic operators 1 + 1 2 * 5 10 / 3 div(10, 3) # List operators [1,2,3] ++ [4,5,6] [1,2,3] -- [2] # Boolean operators true and true false or is_atom(:hello) ``` #Pattern matching ## The match operator `=` is called the *match operator* ``` Elixir # not simply an assignment x = 1 # one match succeeds the other fails 1 = x 2 = x ``` ##Pattern matching ``` Elixir # a complex match {a, b, c} = {:hello, "world", 42} # this match fails {a, b, c} = {:hello, "world"} # matching for specific values {:ok, result} = {:ok, 13} # mathing with lists [head | tail] = [1, 2, 3] [h|_] = [3, 4, 5] ``` #Functions * Two types of functions * Anonymous functions * Named functions * Functions are first-class citizens * Can be assigned to variables * Can be function parameters * Can be return value of other functions ##Anonymous & named functions ``` Elixir # Anonymous functions d = &(&1 + &1) s = fn(x) -> x * x end # Named function # Note that function params are patterns defmodule SitMuc1 do def factorial(0) do 1 end def factorial(n) do n * factorial(n-1) end end ``` ##Higher order functions ``` Elixir # Create a list with some data user1 = %{:first_name => "Christian", :last_name => "Drumm"} user2 = %{:first_name => "Martin", :last_name => "Steinberg"} user3 = %{:first_name => "Gregor", :last_name => "Wolf"} users = [user1, user2, user3] # Function that fetches an entry from a map get_element = fn(key_word) -> fn(user) -> user[key_word] end end # Apply the function to the list Enum.map(users, get_element.(:first_name)) Enum.map(users, get_element.(:last_name)) ``` #Recursion ## Recursion vs. Loops * Due to immutability loops are expressed as recursion * Example sum the items in a list* ``` Elixir defmodule Sum # Calculate the sum of items in a list def sum_list([head|tail], acc) do sum_list(tail, acc + head) end def sum_list([], acc) do acc end end ``` *Usually this should be implemente using [Enum.reduce/2](http://elixir-lang.org/docs/v1.0/elixir/Enum.html#reduce/2) ## Tail call optimization * Fibonacci sequence * F(0) = 0 * F(1) = 1 * F(n) = F(n-1) + F(n-2) * Alternative definition > Fibonacci - A problem used to teach recursion in computer science ### Naive implementation ``` Elixir defmodule NaiveFib do def fib(0) do 0 end def fib(1) do 1 end def fib(n) do fib(n-1) + fib(n-2) end end ``` ### Tail call optimized implementation ``` Elixir defmodule Fib do def fib(n) when is_integer(n) and n >= 0 do fibn(n, 1, 0) end defp fibn(0, _, result) do result end defp fibn(n, next, result) do fibn(n-1, next + result, next) end end ``` #Concurrency * Erlang/Elixir uses the [Actor Concurrency Model](http://en.wikipedia.org/wiki/Actor_model) * Leightweight processes * Message passing * Shared nothing ## A simple process ``` Elixir defmodule Router do def route do receive do {[ first | tail ], msg} -> #IO.puts "#{inspect self} received: #{msg}!" #IO.puts "routing to next #{inspect first}" send first, {tail, msg} route {[], msg } -> IO.puts "#{inspect self} Huuray, Got the delivery: #{msg}!" end end end ``` ## Communication between processes ``` Elixir defmodule Messenger do def deliver(message, processes) do [router|routers] = Enum.map(1..processes, fn(_) -> spawn(Router, :route, []) end) send(router, {routers , message}) end end ```
Java
UTF-8
1,684
2.40625
2
[]
no_license
package org; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class ActionsWorking { //Actions and Robotclass working //username given, selecting un and rc copy and paste in pwd action is done //Special task given for Actions and Robot public static void main(String[] args1) throws AWTException { System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.facebook.com/"); //driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop"); WebElement usernamectrl = driver.findElement(By.id("email")); usernamectrl.sendKeys("Hemamalini"); WebElement passwordctrl = driver.findElement(By.name("pass")); Actions a = new Actions(driver); a.doubleClick(usernamectrl).perform(); a.contextClick(usernamectrl).perform(); Robot r = new Robot(); for(int i=1;i<=6;i++) { r.keyPress(KeyEvent.VK_DOWN); r.keyRelease(KeyEvent.VK_DOWN); } r.keyPress(KeyEvent.VK_ENTER); r.keyRelease(KeyEvent.VK_ENTER); r.keyPress(KeyEvent.VK_TAB); r.keyRelease(KeyEvent.VK_TAB); a.contextClick(passwordctrl).perform(); for(int i=1;i<=4;i++) { r.keyPress(KeyEvent.VK_DOWN); r.keyRelease(KeyEvent.VK_DOWN); } r.keyPress(KeyEvent.VK_ENTER); r.keyRelease(KeyEvent.VK_ENTER); WebElement loginbtnctrl = driver.findElement(By.name("login")); a.click(loginbtnctrl).perform(); } }
C#
UTF-8
2,152
3.421875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphsAndTreesAlgorithms.Graphs { public class GraphDistanceCalculator { public IDictionary<string, double> CalculateDistances(Graph graph, string startingNode) { if (!graph.Nodes.Any(n => n.Name == startingNode)) throw new ArgumentException("Starting node must be in graph."); InitializeGraph(graph, startingNode); ProcessGraph(graph, startingNode); return ExtractDistances(graph); } private void InitializeGraph(Graph graph, string startingNode) { foreach (var node in graph.Nodes) node.DistanceFromStart = double.PositiveInfinity; graph.Nodes.Find(n => n.Name == startingNode).DistanceFromStart = 0; } private void ProcessGraph(Graph graph, string startingNode) { var finished = false; var queue = graph.Nodes.ToList(); while (!finished) { var nextNode = queue.OrderBy(n => n.DistanceFromStart).FirstOrDefault(n => n.DistanceFromStart != double.PositiveInfinity); if (nextNode != null) { ProcessNode(nextNode, queue); queue.Remove(nextNode); } else { finished = true; } } } private void ProcessNode(Node node, List<Node> queue) { var connections = node.Connections.Where(c => queue.Contains(c.Target)); foreach (var conn in connections) { var distance = node.DistanceFromStart + conn.Distance; if (distance < conn.Target.DistanceFromStart) conn.Target.DistanceFromStart = distance; } } private IDictionary<string, double> ExtractDistances(Graph graph) { return graph.Nodes.ToDictionary(n => n.Name, n => n.DistanceFromStart); } } }
Java
UTF-8
418
2
2
[]
no_license
package com.nestor.common; /** * <p>业务异常类</p> * * @author bianzeyang * */ public class BizException extends BaseException { /** * */ private static final long serialVersionUID = 4648866296534704666L; private static final int BIZException_CODE = 48; // 业务异常code public BizException(String msg) { super(BIZException_CODE, msg); } }
C
UTF-8
977
3.546875
4
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int sumOfLeftLeaves(struct TreeNode* root) { int sum=0; struct TreeNode* tmp = root; struct TreeNode* left; struct TreeNode* right; if(tmp==NULL) return 0; if(tmp->right !=NULL){ //recursive right childe right = tmp->right; sum += sumOfLeftLeaves(right); } if(tmp->left !=NULL){ left =tmp->left; struct TreeNode* prev; //recorde the previous left childe for left!=NULL while(left!=NULL){ //using left!=NULL instead of left->left!=NULL for not missing left->right !=NULL if(left->right !=NULL) sum+=sumOfLeftLeaves(left->right); prev = left; left = left->left; } if(prev->right==NULL) sum +=prev->val; } return sum; }
Java
UTF-8
140
1.976563
2
[]
no_license
package daytrader.gui; import java.awt.*; public interface IBlotter { void onTrade(String trade); Component getComponent(); }
Go
UTF-8
172
2.890625
3
[]
no_license
package main import "fmt" func main() { c := make(chan int, 1) //buffer : 1 c <- 42 c <- 43 fmt.Println(<-c) //fatal error: all goroutines are asleep - deadlock! }
Java
UTF-8
1,336
2.3125
2
[ "MIT" ]
permissive
package cloud.jgo.net.tcp.http.jor.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import cloud.jgo.net.tcp.http.jor.ResponseType; @Retention(value = RetentionPolicy.RUNTIME) @Target(value = { ElementType.TYPE }) @Documented /** * @author Martire91<br> * This annotation allows the definition of the URL of the object */ public @interface JOR { /** * This method gets the url pattern * * @return the url pattern */ public String url_Pattern(); /** * This method gets the response type * * @return the response type */ public cloud.jgo.net.tcp.http.jor.ResponseType responseType() default ResponseType.HTML; /** * This method gets the field id * * @return the field id */ public String field_id(); // da spiegare a cosa serve, deve essere un field stringa /** * This method returns the URL JOR separator * * @return the URL JOR separator */ public String separator() default "-"; /** * This method allows you to choose <br> * whether or not to save the files created by JOR * * @return the flag */ public boolean SaveFiles() default false; }
Java
UTF-8
1,424
2.40625
2
[]
no_license
package com.lr.simplerpc.zookeeper; import com.lr.simplerpc.common.constant.Constant; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CountDownLatch; /** * @author xu.shijie * @since 2020/9/16 */ public class ZookeeperService { private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperService.class); ZookeeperProperties zookeeperProperties; public ZookeeperService(ZookeeperProperties zookeeperProperties) { this.zookeeperProperties = zookeeperProperties; System.out.println(zookeeperProperties.toString()); } public ZooKeeper connectServer() { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zk = null; try { zk = new ZooKeeper(zookeeperProperties.getIpAddress(), Constant.ZK_SESSION_TIMEOUT, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { latch.countDown(); } } }); latch.await(); } catch (IOException | InterruptedException e) { LOGGER.error("failed", e); } return zk; } }
C++
UTF-8
3,180
3.40625
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <stdlib.h> #include "LinkedList.h" #include "BST.h" // g++ -std=c++11 LinkedList.cpp BST.cpp assignment6.cpp -o assignment6 // ./assignment6 Hemingway_edit.txt >> output.txt void compareOps(int numLines, char *arg); using namespace std; int main(int argc, char *argv[]){ ifstream book; string data; book.open(argv[1]); // throw an error if we couldn't open the file if (!book){ cout << "Error: Could not open file for reading" << endl; return 0; } LL myLL; BST myBST; string word; while(getline(book,data,' ')){ stringstream ss(data); getline(ss,word); myLL.addWords(word); myBST.addWordNode(word); // sometimes adds 2 of the same node } for(int i = 200; i <= 1600; i+=200){ compareOps(i, argv[1]); } cout<<endl; myLL.countNodes(); myLL.countTotalWords(); myBST.countBSTNodes(); myBST.countBSTWords(); cout<<endl; string dmenu = "======Main Menu=====\n" "1. Print Word\n" "2. Print Tree in Order\n" "3. Find Words in Range\n" "4. Quit\n"; int choice; bool exit = false; cout << dmenu << endl; while(cin >> choice) { // flush the newlines and other characters cin.clear(); cin.ignore(); switch (choice) { case 1: { //Print a word from the tree. string toPrint; cout<<"Please enter a word from the book to print: "; cin>>toPrint; cout<<endl; myBST.printWord(toPrint); break; } case 2: { //Print tree in order myBST.printInOrderBST(); break; } case 3: { // Print in Range string min, max; cout<<"Please enter the first word of the range: "; cin>>min; cout<<endl; cout<<"Please enter the second word of the range: "; cin>>max; cout<<endl; myBST.findAlphaRange(min, max); break; } case 4: { // Quit exit = true; break; } } if (exit) { break; } else { cout << endl << dmenu << endl; } } return 0; } // This function compares the average number of comparisons it takes to build a LL vs a BST. void compareOps(int numLines, char *arg){ ifstream book; book.open(arg); LL myLL; BST myBST; int LLops = 0; int BSTops = 0; int loopCounter = 0; float LLMean = 0; float BSTMean = 0; string line, word, data; for(int i = 0; i < numLines; i++){ getline(book,line); stringstream ss1(line); while(getline(ss1,data,' ')){ stringstream ss2(data); getline(ss2,word); LLops = myLL.addWords(word); BSTops = myBST.addWordNode(word); loopCounter++; LLMean+=LLops; BSTMean+=BSTops; } } LLMean/=loopCounter; BSTMean/=loopCounter; cout<<"Lines: "<<numLines<<" | LL Avg. Operations: "<<LLMean<<" | BST Avg. Operations: "<<BSTMean<<endl; }
C#
UTF-8
1,367
2.671875
3
[]
no_license
<Query Kind="FSharpProgram" /> // unshorten urls open System.Net let urls = [ "http://goo.gl/zdf2n" "http://tinyurl.com/8xc9vca" "http://x.co/iEup" "http://is.gd/vTOlz6" "http://bit.ly/FUA4YU" ] type unshortenResult = | Success of status:HttpStatusCode*url:string | Failure of HttpStatusCode | FailureStatus of WebExceptionStatus let unshorten (url:string) = // with help from http://stackoverflow.com/a/9761793/57883 let req = WebRequest.Create(url) :?> HttpWebRequest req.AllowAutoRedirect <- false try use resp = req.GetResponse() use hResp = resp :?> HttpWebResponse match hResp.StatusCode with | HttpStatusCode.MovedPermanently // they should all be returning this code if they are shortened (also seems to return this to redirect to the same url in https) | _ -> let realUrl = resp.Headers.["Location"] Success (hResp.StatusCode,realUrl) // unless it redirects to another shortened link with :? WebException as e -> match e.Status = WebExceptionStatus.ProtocolError with | true -> use resp = e.Response use hResp = resp :?> HttpWebResponse Failure hResp.StatusCode | false -> FailureStatus e.Status urls |> Seq.map (fun x -> x,unshorten x) |> Dump
TypeScript
UTF-8
420
3.671875
4
[]
no_license
interface ObjectValue { category: string; product?: string; } const show = ({category, product}: ObjectValue) => console.log(category, product); show({category: 'Categoria'}); const obj: ObjectValue = {category: 'Categoria 1', product: 'Product 1'}; class Product implements ObjectValue { category: string; } const product = new Product(); product.category = 'Categoria'; console.log(product.category);
Python
UTF-8
4,185
3.40625
3
[]
no_license
import os import sys import argparse def get_args(): """Parses input arguments.""" print(f"Init: Parsing command line arguments.") parser = argparse.ArgumentParser( description="Program to generate CSV list of pairs of artists appearing together at least 50 times in the " "input file.") parser.add_argument( '--input_file', metavar='FILE', default=r'', help='Please provide input .csv file.' ) parser.add_argument( '--output_file', metavar='FILE', default=r'', help='Please provide output .csv file.', ) # Checking if any of the input arg values are empty. empty_args = ','.join(list(k for (k, v) in vars( parser.parse_args()).items() if (len(v) == 0))) if empty_args: print(f"Err : Input args [{empty_args}] are empty. Exiting.") sys.exit() return vars(parser.parse_args()) def chk_perm_n_get_elig_pairs(input_file, output_file): """Call file permission func and create eligible artist dictionary.""" if not os.access(os.path.dirname(output_file), os.W_OK): print( f"Err : Destination dir [{os.path.dirname(output_file)}] if not writable. Exiting.") sys.exit() # Just preliminary check to see if we will be able to create output file in the directory. if not os.path.isfile(input_file): print( f"Err : File [{input_file}] does not exist. Please provide a valid file. Exiting.") sys.exit() if os.path.getsize(input_file) == 0: # file is empty print(f'Err : Zero bytes input file [{input_file}]. Exiting.') sys.exit() d_all_artists = {} # declaring so that I can call .keys() on it try: with open(input_file, 'r', encoding='utf-8') as f_ro: for line_num, line in enumerate(f_ro, start=1): # replacing new lines from the artist names line = line.replace("\n", '') for artist in line.split(','): if artist not in d_all_artists.keys(): d_all_artists[artist] = set() d_all_artists[artist].add(line_num) else: d_all_artists[artist].add(line_num) print( f"Proc: Loaded {[len(d_all_artists.keys())]} artists from input file.") return {k: v for (k, v) in d_all_artists.items() if len(d_all_artists[k]) > 49} except OSError: print(f"Err : {sys.exc_info()[1]}") sys.exit() def get_matching_pairs(d_elig_artists): """Collected matching pairs having more than 50 occurrences together.""" s_matching_pairs = set() # creating empty set to add to it later for key1 in d_elig_artists.keys(): for key2 in d_elig_artists.keys(): if key1 != key2: if len(d_elig_artists[key1].intersection(d_elig_artists[key2])) > 49: s_matching_pairs.add(f"{','.join(sorted([key1, key2]))}\n") print(f"Proc: Collected {[len(s_matching_pairs)]} matching pairs.") return s_matching_pairs def write_matching_pairs(output_file, s_matching_pairs): """Write sorted pairs to the output file.""" try: with open(output_file, 'w', encoding='utf-8') as f_rw: for line in s_matching_pairs: f_rw.write(line) except OSError: print(f"Err : {sys.exc_info()[1]}") sys.exit() print( f"Proc: Wrote {[len(s_matching_pairs)]} matching pairs to {[output_file]} file.") print(f"Info: Exiting.") # main def main(): d_ip_vals = get_args() d_elig_artists = chk_perm_n_get_elig_pairs( d_ip_vals['input_file'], d_ip_vals['output_file']) if not d_elig_artists: print("No artist is appearing on more than 49 lines. Exiting") sys.exit() s_matching_pairs = get_matching_pairs(d_elig_artists) if not s_matching_pairs: print("No artist pairs found appearing together for more than 49 times. Exiting") sys.exit() write_matching_pairs(d_ip_vals['output_file'], s_matching_pairs) # main if __name__ == "__main__": main()
Python
UTF-8
24,550
2.765625
3
[ "MIT" ]
permissive
import io import numpy as np import os import pygtrie import tempfile # shared global variables to be imported from model also UNK = "$UNK$" NUM = "$NUM$" NONE = "O" # special error message class MyIOError(Exception): def __init__(self, filename): # custom error message message = """ ERROR: Unable to locate file {}. FIX: Have you tried running python build_data.py first? This will build vocab file from your train, test and dev sets and trimm your word vectors. """.format(filename) super(MyIOError, self).__init__(message) class CoNLLDataset(object): """Class that iterates over CoNLL Dataset __iter__ method yields a tuple (words, tags) words: list of raw words tags: list of raw tags If processing_word and processing_tag are not None, optional preprocessing is appplied Example: ```python data = CoNLLDataset(filename) for sentence, tags in data: pass ``` """ def __init__(self, file, processing_word=None, processing_tag=None, processing_dict=None, processing_intent=None, max_iter=None, max_sent_len=None): """ Args: file: a path to text file or a file object processing_words: (optional) function that takes a word as input processing_tags: (optional) function that takes a tag as input processing_dict: (optional) function to takes a sentence as input max_iter: (optional) max number of sentences to yield """ self.file = file self.processing_word = processing_word self.processing_tag = processing_tag self.processing_dict = processing_dict self.processing_intent = processing_intent self.max_iter = max_iter self.length = None self.max_sent_len = max_sent_len def __iter__(self): niter = 0 with open(self.file, encoding='utf-8') if isinstance(self.file, str) else self.file as f: intent, words, tags = '', [], [] for line in f: line = line.strip() if len(line) == 0 or line.startswith("-DOCSTART-"): if len(words) != 0: niter += 1 if self.max_iter is not None and niter > self.max_iter: break # add dictionary feature if self.processing_dict is not None: # for word processing, we expect all ids # (letter trigram id, char id and word id, ...) are extracted if len(words) > 0 and type(words[0]) is not tuple: raise Exception("Unexpected, word is not a tuple") word_ids = [word[-1] for word in words] dict_ids = self.processing_dict(word_ids) words = list(map(lambda w, d: ((d,) + w), words, dict_ids)) # max_sent_len if self.max_sent_len is not None: words = words[:self.max_sent_len] tags = tags[:self.max_sent_len] # intent if not intent: intent = 'none' if self.processing_intent is not None: intent = self.processing_intent(intent) yield intent, words, tags intent, words, tags = '', [], [] else: ls = line.split(' ') if len(ls) == 1: if len(intent) != 0: raise Exception('Unexpected line: {}'.format(line)) else: intent = line else: word, tag = ls[0],ls[-1] if self.processing_word is not None: word = self.processing_word(word) if self.processing_tag is not None: tag = self.processing_tag(tag) words += [word] tags += [tag] def __len__(self): """Iterates once over the corpus to set and store length""" if self.length is None: self.length = 0 for _ in self: self.length += 1 return self.length def get_CoNLL_dataset(filename, config, task_id): return CoNLLDataset(filename, config.processing_word, config.processing_tasks_tag[task_id], config.processing_dict, config.processing_task_intents[task_id], config.max_iter, config.max_sent_len) def get_vocabs(datasets): """Build vocabulary from an iterable of datasets objects Args: datasets: a list of dataset objects Returns: a set of all the words in the dataset """ print("Building vocab...") vocab_intents = set() vocab_words = set() vocab_tags = set() for dataset in datasets: for intent, words, tags in dataset: vocab_intents.add(intent) vocab_words.update(words) vocab_tags.update(tags) print("- done. {} tokens".format(len(vocab_words))) return vocab_intents, vocab_words, vocab_tags def get_letter_trigrams(word): bounded_word = '#' + word + '#' letter_trigrams = [bounded_word[i:i+3] for i in range(len(bounded_word) - 2)] # to remove cases like " 16" in "+65 6272 1626" (not ascii space) letter_trigrams = [t for t in letter_trigrams if len(t.strip()) == 3] return letter_trigrams def get_letter_trigram_vocab(vocab_words): vocab_letter_trigrams = set() for word in vocab_words: vocab_letter_trigrams.update(get_letter_trigrams(word)) return vocab_letter_trigrams def get_chunk_vocab(vocab_tags): vocab_chunk_types = set() for tag in vocab_tags: _, chunk_type = get_chunk_type_from_name(tag) vocab_chunk_types.add(chunk_type) return vocab_chunk_types def get_char_vocab(datasets, chars_lowercase=False): """Build char vocabulary from an iterable of datasets objects Args: dataset: a iterator yielding tuples (sentence, tags) Returns: a set of all the characters in the dataset """ vocab_char = set() for dataset in datasets: for _, words, _ in dataset: for word in words: if chars_lowercase: word = word.lower() vocab_char.update(word) return vocab_char def get_glove_vocab(filename): """Load vocab from file Args: filename: path to the glove vectors Returns: vocab: set() of strings """ print("Building vocab...") vocab = set() with open(filename, encoding='utf-8') as f: for line in f: # print(line.split(' ')[0]) word = line.strip().split(' ')[0] vocab.add(word) print("- done. {} tokens".format(len(vocab))) return vocab def get_class_weights(filename, classes_num=None): if os.path.exists(filename): weights = [] with open(filename, encoding='utf-8') as f: for line in f: line = line.strip() if line: weights.append(float(line)) return weights elif classes_num is not None: return [1.0] * classes_num else: raise Exception('Invalid class weights: {}'.format(filename)) def write_vocab(vocab, filename): """Writes a vocab to a file Writes one word per line. Args: vocab: iterable that yields word filename: path to vocab file Returns: write a word per line """ print("Writing vocab...") with open(filename, "w", encoding='utf-8') as f: for i, word in enumerate(vocab): if i != len(vocab) - 1: f.write("{}\n".format(word)) else: f.write(word) print("- done. {} tokens".format(len(vocab))) def load_vocab(filename): """Loads vocab from a file Args: filename: (string) the format of the file must be one word per line. Returns: d: dict[word] = index """ try: d = dict() with open(filename, encoding='utf-8') as f: for idx, word in enumerate(f): word = word.strip() d[word] = idx except IOError: raise MyIOError(filename) return d def trim_words(word_set, data_sets, num): """ trim words number to num Args: word_set: word set data_sets: data set list num: trim number """ word_dict = {} for data in data_sets: for word_list, _ in data: for word in word_list: if word not in word_set: continue if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 sorted_list = sorted(word_dict.keys(), key=lambda w: word_dict[w], reverse=True) result_set = set() result_set.update(sorted_list[:num]) return result_set def export_trimmed_glove_vectors(vocab, glove_filename, trimmed_filename, dim): """Saves glove vectors in numpy array Args: vocab: dictionary vocab[word] = index glove_filename: a path to a glove file trimmed_filename: a path where to store a matrix in npy dim: (int) dimension of embeddings """ embeddings = np.zeros([len(vocab), dim]) with open(glove_filename, encoding='utf-8') as f: for line in f: line = line.strip().split(' ') word = line[0] embedding = [float(x) for x in line[1:]] if word in vocab: word_idx = vocab[word] embeddings[word_idx] = np.asarray(embedding) np.savez_compressed(trimmed_filename, embeddings=embeddings) def get_trimmed_glove_vectors(filename): """ Args: filename: path to the npz file Returns: matrix of embeddings (np array) """ try: with np.load(filename) as data: return data["embeddings"] except IOError: raise MyIOError(filename) def concate_list_and_tuple(a_list, b_num_or_tuple): if type(b_num_or_tuple) is tuple: result = a_list, *b_num_or_tuple else: result = a_list, b_num_or_tuple return result def get_processing_word(vocab_words=None, vocab_chars=None, vocab_letter_trigrams=None, lowercase=False, chars=False, chars_lowercase=False, letter_trigrams=False, allow_unk=True, max_word_len=None): """Return lambda function that transform a word (string) into list, or tuple of (list, id) of int corresponding to the ids of the word and its corresponding characters. Args: vocab: dict[word] = idx Returns: f("cat") = ([12, 4, 32], 12345) = (list of char ids, word id) """ def f(word): # 0. get chars of words if vocab_chars is not None and chars: char_ids = [] char_word = word if chars_lowercase: char_word = char_word.lower() for char in char_word: # ignore chars out of vocabulary if char in vocab_chars: char_ids += [vocab_chars[char]] if max_word_len is not None: char_ids = char_ids[:max_word_len] # 1. preprocess word if lowercase: word = word.lower() if word.isdigit(): word = NUM # 2. get id of letter trigrams if vocab_letter_trigrams is not None and letter_trigrams == True: letter_trigram_ids = [] for l3t in get_letter_trigrams(word): # ignore letter trigrams out of vocabulary if l3t in vocab_letter_trigrams: letter_trigram_ids += [vocab_letter_trigrams[l3t]] if max_word_len is not None: letter_trigram_ids = letter_trigram_ids[:max_word_len] # 3. get id of word if vocab_words is not None: if word in vocab_words: word = vocab_words[word] else: if allow_unk: word = vocab_words[UNK] #else: # raise Exception("Unknown key is not allowed. Check that "\ # "your vocab (tags?) is correct") # 4. return tuple: letter trigram ids, char ids, word id result = word if vocab_chars is not None and chars == True: result = concate_list_and_tuple(char_ids, result) if vocab_letter_trigrams is not None and letter_trigrams == True: result = concate_list_and_tuple(letter_trigram_ids, result) return result return f def get_processing_dict(trie, ndict_types, trie_separator='.s'): def f(word_ids): word_ids = [str(word_id) for word_id in word_ids] dict_feat = [[0] * 2 * ndict_types for word_id in word_ids] for i in range(len(word_ids)): sent = trie_separator.join(word_ids[i:]) prefix, dict_type = trie.longest_prefix(sent) if dict_type is not None: dict_feat[i][2 * dict_type] = 1 for j in range(1, len(prefix.split(trie_separator))): dict_feat[i + j][2 * dict_type + 1] = 1 return tuple(dict_feat) return f def _pad_sequences(sequences, pad_tok, max_length): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with Returns: a list of list where each sublist has same length """ sequence_padded, sequence_length = [], [] for seq in sequences: seq = list(seq) seq_ = seq[:max_length] + [pad_tok]*max(max_length - len(seq), 0) sequence_padded += [seq_] sequence_length += [min(len(seq), max_length)] return sequence_padded, sequence_length def pad_sequences(sequences, pad_tok, nlevels=1): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with nlevels: "depth" of padding, for the case where we have characters ids Returns: a list of list where each sublist has same length """ if nlevels == 1: max_length = max(map(lambda x : len(x), sequences)) sequence_padded, sequence_length = _pad_sequences(sequences, pad_tok, max_length) elif nlevels == 2: max_length_word = max([max(map(lambda x: len(x), seq)) for seq in sequences]) sequence_padded, sequence_length = [], [] for seq in sequences: # all words are same length now sp, sl = _pad_sequences(seq, pad_tok, max_length_word) sequence_padded += [sp] sequence_length += [sl] max_length_sentence = max(map(lambda x : len(x), sequences)) sequence_padded, _ = _pad_sequences(sequence_padded, [pad_tok]*max_length_word, max_length_sentence) sequence_length, _ = _pad_sequences(sequence_length, 0, max_length_sentence) return sequence_padded, sequence_length def minibatches(data, minibatch_size): """ Args: data: generator of (sentence, tags) tuples minibatch_size: (int) Yields: list of tuples """ intent_batch, x_batch, y_batch = [], [], [] for (intent, x, y) in data: if len(x_batch) == minibatch_size: yield intent_batch, x_batch, y_batch intent_batch, x_batch, y_batch = [], [], [] if type(x[0]) == tuple: x = list(zip(*x)) intent_batch.append(intent) x_batch += [x] y_batch += [y] if len(x_batch) != 0: yield intent_batch, x_batch, y_batch def get_chunk_type(tok, idx_to_tag): """ Args: tok: id of token, ex 4 idx_to_tag: dictionary {4: "B-PER", ...} Returns: tuple: "B", "PER" """ tag_name = idx_to_tag[tok] return get_chunk_type_from_name(tag_name) def get_chunk_type_from_name(tag_name): tag_class = tag_name.split('-')[0] tag_type = tag_name.split('-')[-1] return tag_class, tag_type def get_chunks(seq, tags): """Given a sequence of tags, group entities and their position Args: seq: [4, 4, 0, 0, ...] sequence of labels tags: dict["O"] = 4 Returns: list of (chunk_type, chunk_start, chunk_end) Example: seq = [4, 5, 0, 3] tags = {"B-PER": 4, "I-PER": 5, "B-LOC": 3} result = [("PER", 0, 2), ("LOC", 3, 4)] """ default = tags[NONE] idx_to_tag = {idx: tag for tag, idx in tags.items()} chunks = [] chunk_type, chunk_start = None, None for i, tok in enumerate(seq): # End of a chunk 1 if tok == default and chunk_type is not None: # Add a chunk. chunk = (chunk_type, chunk_start, i) chunks.append(chunk) chunk_type, chunk_start = None, None # End of a chunk + start of a chunk! elif tok != default: tok_chunk_class, tok_chunk_type = get_chunk_type(tok, idx_to_tag) if chunk_type is None: chunk_type, chunk_start = tok_chunk_type, i elif tok_chunk_type != chunk_type or tok_chunk_class == "B": chunk = (chunk_type, chunk_start, i) chunks.append(chunk) chunk_type, chunk_start = tok_chunk_type, i else: pass # end condition if chunk_type is not None: chunk = (chunk_type, chunk_start, len(seq)) chunks.append(chunk) return chunks def get_all_chunks(seq, tags): """Also include O chunk Example: seq = [4, 5, 0, 3] tags = {"B-PER": 4, "I-PER": 5, "B-LOC": 3, "O": 0} result = [("PER", 0, 2), ('O', 2, 3) ("LOC", 3, 4)] """ default = tags[NONE] idx_to_tag = {idx: tag for tag, idx in tags.items()} chunks = [] chunk_type, chunk_start = None, None for i, tok in enumerate(seq): tok_chunk_class, tok_chunk_type = get_chunk_type(tok, idx_to_tag) if tok_chunk_class == "B" or tok_chunk_type != chunk_type: if chunk_type is not None and chunk_start is not None: chunk = (chunk_type, chunk_start, i) chunks.append(chunk) chunk_type = tok_chunk_type chunk_start = i if chunk_type is not None and chunk_start is not None: chunk = (chunk_type, chunk_start, len(seq)) chunks.append(chunk) # verify if set([c for c in chunks if c[0] != NONE]) != set(get_chunks(seq, tags)): raise Exception("Result of get_all_chunks is inconsistent with get_chunks") return chunks def get_pr(metrics): out_metrics = np.vstack([ np.divide(metrics[:, 0], metrics[:, 1], out=np.zeros_like(metrics[:, 0]), where=metrics[:, 0]!=0), np.divide(metrics[:, 0], metrics[:, 2], out=np.zeros_like(metrics[:, 0]), where=metrics[:, 0]!=0) ]).transpose() divisor = 2 * np.multiply(out_metrics[:, 0], out_metrics[:, 1]) dividend = np.add(out_metrics[:, 0], out_metrics[:, 1]) out_metrics = np.hstack([ out_metrics, np.divide(divisor, dividend, out=np.zeros_like(divisor), where=dividend!=0).reshape(-1, 1) ]) return out_metrics def get_ordered_keys(dictionary): return [e[0] for e in sorted(dictionary.items(), key=lambda e: e[1])] def get_dict_trie(dict_file_name, processing_word=None, processing_dict_type=None, trie_separator='.'): trie = pygtrie.StringTrie(separator=trie_separator) paths = [] dict_types = set() UNK_word_id = processing_word(UNK) if processing_word is not None else -1 with open(dict_file_name, encoding='utf-8') as f: for line in f: line = line.strip() if line: sent, dict_type = line.split('\t') if processing_word is not None: word_ids = [processing_word(word) for word in sent.split(' ')] if UNK_word_id in word_ids: continue sent = trie_separator.join([str(word_id) for word_id in word_ids]) if processing_dict_type is not None: dict_type = processing_dict_type(dict_type) trie[sent] = dict_type paths.append('{}\t{}'.format(sent, dict_type)) dict_types.add(dict_type) return trie, paths, list(dict_types) def create_memory_file_from_words(words): return io.StringIO('{}\n\n'.format('\n'.join(['{} O'.format(w) for w in words]))) def get_task_vocab(filenames): if all('_' in filename for filename in filenames): return [filename.rsplit('.', 1)[0].rsplit('_', 1)[1] for filename in filenames] else: return list(str(i) for i in range(len(filenames))) def get_name_for_task(prefix, task_name): return "{}_{}.txt".format(prefix, task_name) def merge_lists_alternate(lists, len_per_list): result = [] list_num = len(lists) indexes = [0] * list_num list_lens = [len(l) for l in lists] for _ in range(len_per_list): for i in range(list_num): result.append(lists[i][indexes[i]]) indexes[i] = (indexes[i] + 1) % list_lens[i] return result def merge_datasets(datasets, batch_size, random_seed, mode): datasets_mbs = [] for i, dataset in enumerate(datasets): datasets_mbs.append([(i, mb_enum) for mb_enum in enumerate(minibatches(dataset, batch_size))]) if mode == 'permute': first_mbs = [mbs[0] for mbs in datasets_mbs] remaining_mbs = [mb for mbs in datasets_mbs for mb in mbs[1:]] np.random.RandomState(seed=random_seed).shuffle(remaining_mbs) return first_mbs + remaining_mbs elif mode == 'cycle': for mbs in datasets_mbs: np.random.RandomState(seed=random_seed).shuffle(mbs) return merge_lists_alternate(datasets_mbs, max(len(mbs) for mbs in datasets_mbs)) else: raise Exception('Unsupported mode: {}'.format(mode)) if __name__ == "__main__": seq = [4, 5, 0, 3] tags = {"B-PER": 4, "I-PER": 5, "B-LOC": 3, "O": 0} # Expected: [("PER", 0, 2), ('O', 2, 3) ("LOC", 3, 4)] result = get_all_chunks(seq, tags) print(result) print([c for c in result if c[0] != NONE] == get_chunks(seq, tags)) seq = [4, 5, 5, 4, 0, 0, 3, 5, 3] tags = {"B-PER": 4, "I-PER": 5, "B-LOC": 3, "O": 0} # Expected: [('PER', 0, 3), ('PER', 3, 4), ('O', 4, 6), ('LOC', 6, 7), ('PER', 7, 8), ('LOC', 8, 9)] result = get_all_chunks(seq, tags) print(result) print([c for c in result if c[0] != NONE] == get_chunks(seq, tags)) tmp_dict_filename = '' with tempfile.NamedTemporaryFile("w", delete=False) as tmp: tmp.write("The big bang theory\tTV\n") tmp.write("Game of the thrones\tTV\n") tmp.write("Angry Birds\tMOVIE\n") tmp_dict_filename = tmp.name trie, _, dict_types = get_dict_trie(tmp_dict_filename) print(trie) assert(set(dict_types) == set(['MOVIE', 'TV'])) vocab_words = {'big': 0, 'bang': 1, 'the': 2, 'theory': 3, UNK: 4} processing_words = get_processing_word(vocab_words, lowercase=True, allow_unk=True) vocab_dict_types = {'MOVIE': 0, 'TV': 1} processing_dict_type = get_processing_word(vocab_dict_types) trie, _, dict_types = get_dict_trie(tmp_dict_filename, processing_words, processing_dict_type) print(trie) assert(set(dict_types) == set([0, 1])) words = [([0], 1), ([0, 1], 5), ([0, 1, 2], 3), ([0, 1, 2, 3], 5), ([0, 1, 2, 3, 4], 4), ([0, 1, 2, 3, 4, 5], 62), ([0, 1, 2, 3, 4, 5, 6], 9)] sep = '.' trie = trie = pygtrie.StringTrie(separator=sep) trie['3.5'] = 1 trie['3.5.4'] = 1 trie['3.5.4.6'] = 1 processing_dict = get_processing_dict(trie, 2, sep) dict_ids = processing_dict([word[-1] for word in words]) print(dict_ids) print(list(map(lambda w, d: ((d,) + w), words, dict_ids)))
Java
UTF-8
1,571
2.171875
2
[]
no_license
package com.ustcsoft.jt.controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ustcsoft.jt.mybatis.Page; import com.ustcsoft.jt.service.SysStationRecService; import com.ustcsoft.system.model.SystemStationRecVO; /** * 岗位的rest控制器 * @author 吴金华 * @since 2017年1月10日 */ @RequestMapping("sysStationRec") @RestController public class SystemStationRecRestController extends AbstractRestController { @Resource private SysStationRecService sysStationRecService; /** * 分页查询所有岗位信息 * @author 吴金华 * @since 2017年1月9日 * @return */ @RequestMapping("findStationRecList.do") public Page<SystemStationRecVO> findStationRecList(String empId, @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "rows", defaultValue = "10") int rows) { logger.info("sysStationRec/findStationRecList.do"); // 初始化查询条件 SystemStationRecVO stationRec = new SystemStationRecVO(); stationRec.setEmpId(empId); // 查询并返回 return sysStationRecService.query(stationRec, page, rows); } /** * 加载一条岗位信息 * @author 吴金华 * @since 2017年1月11日 * @param id * @return */ @RequestMapping("load.do") public SystemStationRecVO load(String id) { return sysStationRecService.load(id); } }
Java
UTF-8
1,757
3.5
4
[]
no_license
import java.util.Random; class Student { Random random = new Random(); int id; String name; String faculty; public void SetFaculty() { int ranNum = random.nextInt(3) + 1; switch (ranNum) { case 1: this.faculty = "Science" ; break; case 2: this.faculty = "Business"; break; case 3: this.faculty = "Humanities"; break; default: System.out.println("Something went wrong!!"); break; } } public String GetFaculty() { return this.faculty; } public void SetID(int id) { this.id = id; } public int GetID() { return this.id; } public void SetName(String name) { this.name = name; } public String GetName() { return this.name; } public String Display() { String printOutput; printOutput = "|" + Integer.toString(GetID())+ " " +/*TAB */ " " + "|" + GetName()+ " " +/*TAB */ " " + "|" + GetFaculty(); System.out.println(printOutput); return printOutput; } Student(int id, String name) { SetID(id); SetName(name); SetFaculty(); } Student(int id, String name, String faculty) { SetID(id); SetName(name); SetFaculty(); } }
C
UTF-8
5,692
2.640625
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include <sys/wait.h> #include<fcntl.h> char *inputfile; char *outputfile; void shell_loop(); char* shell_readline(); void outputredirect(char*); void inputredirect(char*); char **shell_splitcommand(char*); char **shell_splitpipes(char*); void shell_execute(char **args); void builtin(char* cmd); int ctr=0; int rec; int pipepresence = 0; pid_t firstchild; int main() { shell_loop(); return 0; } void shell_loop() { char *line; int status; do { ctr = 0; outputfile = NULL; inputfile = NULL; char pth[100], host[100], user[100]; gethostname(host, 100); getlogin_r(user, 100); printf("%s@%s", user, host); printf(":%s>> ", getcwd(pth, 100)); line = shell_readline(); int k=0; int ird = -1; int ord = -1; while(line[k]!='\0') { if(line[k]=='<') ird = k; else if(line[k]=='>') ord = k; k++; } if(ird<ord) { outputredirect(line); if(ird!=-1) { inputredirect(line); } } else if(ird>ord) { inputredirect(line); if(ord!=-1) { outputredirect(line); } } char **cmds; cmds = shell_splitpipes(line); if(ctr==1) { char temp[100]; strcpy(temp, *cmds); char **args; args = shell_splitcommand(temp); if(strcmp(*args,"cd")==0) { if(chdir(*(args+1))<0) { perror(*(args+1)); } free(line); free(cmds); continue; } if(strcmp(*args,"pwd")==0) { printf("%s\n", pth); free(line); free(cmds); continue; } if(strcmp(*args,"exit")==0) { free(line); free(cmds); exit(0); } } rec = ctr; shell_execute(cmds); //status = shell_execute(args); free(line); free(cmds); }while(1); } void shell_execute(char **cmds) { pid_t child_pid; pid_t w_pid; int status; int outputfd, inputfd; int pfd[2]; pipe(pfd); child_pid = fork(); if(child_pid==0) { if(rec!=0) { rec--; shell_execute(cmds); } if(cmds[rec+1]!=NULL) { close(pfd[0]); dup2(pfd[1], 1); } if(rec==ctr-1) { if(outputfile!=NULL) { outputfd = open(outputfile, O_RDWR | O_CREAT | O_EXCL, 0666); dup2(outputfd, 1); } } if(rec==0) { if(inputfile!=NULL) { inputfd = open(inputfile, O_RDWR); dup2(inputfd, 0); } close(pfd[0]); } char **args; args = shell_splitcommand(cmds[rec]); int j; for(j=0;j<ctr;j++) printf("%s", args[j]); char pth[100]; getcwd(pth, 100); if(strcmp(*args,"pwd")==0) { printf("%s\n", pth); close(pfd[1]); exit(0); } if(execvp(args[0], args)==-1) { close(pfd[1]); close(pfd[0]); perror("Shell"); } close(pfd[1]); close(pfd[0]); if(close(outputfd)<0) { perror("file"); exit(EXIT_FAILURE); } exit(0); } else if(child_pid<0) perror("Shell"); else { if(rec!=ctr) { close(pfd[1]); dup2(pfd[0], 0); } //w_pid = waitpid(child_pid, &status, WUNTRACED); do { w_pid = waitpid(child_pid, &status, WUNTRACED); }while(!WIFEXITED(status) && !WIFSIGNALED(status)); rec++; } } char *shell_readline() { char *line = NULL; ssize_t bufsize = 0; getline(&line, &bufsize, stdin); return line; } void outputredirect(char* line) { char* token = strtok(line, ">"); int i = 0; while(token != NULL) { if(i==1) { char* tokenws = strtok(token, " \n"); outputfile = tokenws; return; } token = strtok(NULL, ">"); i++; } } void inputredirect(char* line) { char* token = strtok(line, "<"); int i = 0; while(token != NULL) { if(i==1) { char* tokenws = strtok(token, " \n"); inputfile = tokenws; return; } token = strtok(NULL, "<"); i++; } } char **shell_splitpipes(char* line) { int size = 64; char **args = malloc(size * sizeof(char*)); char* token = strtok(line, "|\n"); int i=0; ctr=0; while(token != NULL) { pipepresence = 1; args[i] = token; token = strtok(NULL, "|\n"); i++; ctr++; } args[i]=NULL; return args; } char **shell_splitcommand(char* line) { int size = 64; char **args = malloc(size * sizeof(char*)); char* token = strtok(line, " \n\""); int i=0; while(token != NULL) { args[i] = token; token = strtok(NULL, " \n\""); i++; } args[i]=NULL; return args; }
Java
UTF-8
394
1.953125
2
[]
no_license
package com.smartparkinglot.backendservice.repository; import com.smartparkinglot.backendservice.domain.ParkingLot; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface ParkingLotRepository extends JpaRepository<ParkingLot,Long> { ParkingLot findByName(String name); List<ParkingLot> findByParkingLotOwnerId(Long parkingLotOwnerId); }
SQL
UTF-8
3,762
3.8125
4
[]
no_license
-- -------------------------------------------------------------------------------- -- Routine DDL -- -------------------------------------------------------------------------------- DELIMITER $$ DROP PROCEDURE IF EXISTS `sp_empresa_insert` $$ CREATE PROCEDURE `sp_empresa_insert`( in sp_in_str_nome varchar(255) ,in sp_in_str_email varchar(200) ,in sp_in_str_senha varchar(100) ,in sp_in_int_telefone varchar(20) ,in sp_in_int_cep varchar(10) ,out sp_out_int_status tinyint ,out sp_out_str_status varchar(120) ) begin #-------documentacao----------------------------------------------------# /* autor: Thiago Paes entradas: sp_in_str_nome sp_in_str_email sp_in_int_telefone sp_in_int_cep saidas: int_status codigo do status da Solicitação str_status descricao do status da Solicitação descricao: Quebra uma lista de e-mails e insere no banco retorno: */ #-------documentacao------------------------------------------------------# #-------declaracoes iniciais----------------------------------------------# declare sp_entradas_validas boolean; #-------fim declaracoes iniciais------------------------------------------# #-------validacao das entrada---------------------------------------------# set sp_entradas_validas = 0 != length(sp_in_str_nome) && 0 != fn_valida_email(sp_in_str_email) && 0 != length(sp_in_str_senha) && 10 = length(fn_somente_numeros(sp_in_int_telefone)) && 8 = length(fn_somente_numeros(sp_in_int_cep)) ; #-------fim validacao das entrada-----------------------------------------# #-------procedimento------------------------------------------------------# if sp_entradas_validas then #-------validação de dados duplicados-------------------------------------# set @novo = true; if (0 != (select count(id_usuario) from usuario where str_email = sp_in_str_email)) then set sp_out_int_status = 2; set @novo = false; end if; #-------fim validação de dados duplicados---------------------------------# if @novo = true then -- insiro a empresa insert into empresa values(null ,sp_in_str_nome ,sp_in_str_email ,fn_somente_numeros(sp_in_int_telefone) ,fn_somente_numeros(sp_in_int_cep) ,substr(sha1(concat(now(), sp_in_str_email)), 1, 30) ,substr(sha1(concat(now(), sp_in_str_nome, sp_in_int_cep)), 1, 30) ,now() ,'1' ); set @empresa = last_insert_id(); -- crio o usuário de acesso call sp_usuario_insert( @empresa ,sp_in_str_nome ,sp_in_str_email ,sp_in_str_senha ,@1 ,@2 ); set sp_out_int_status = 0; end if; else set sp_out_int_status = 1; end if; #-------fim procedimento--------------------------------------------------# #-------mapeamento dos status---------------------------------------------# set sp_out_str_status = case sp_out_int_status when 0 then 'Solicitação efetuada com sucesso.' when 1 then 'Entradas inválidas.' when 2 then 'Já existe um usuário utilizando este e-mail.' else 'Status nao inicializado ou nao mapeado.' end; select sp_out_int_status as int_status, sp_out_str_status as str_status ; #-------fim mapeamento dos status-----------------------------------------# END
PHP
UTF-8
591
2.53125
3
[]
no_license
<?php /** * * @package tmvc * @author Codilar Technologies * @license https://opensource.org/licenses/OSL-3.0 Open Software License v. 3.0 (OSL-3.0) * @link http://www.codilar.com/ */ namespace Tmvc\Framework\Router; class Manager { private $_routerPool; public function __construct() { $this->_routerPool = []; } public function addRouter(RouterInterface $router) { $this->_routerPool[] = $router; } /** * @return RouterInterface[] */ public function getRouterPool() { return $this->_routerPool; } }
Markdown
UTF-8
3,529
3.15625
3
[]
no_license
--- layout: post title: "When to make a Git commit" date: 2017-01-10 19:37 comments: true categories: - Git description: '2 rules I follow for when to make commits.' subheading: '2 rules I follow for when to make commits.' excerpt: '2 rules I follow for when to make commits.' --- You don't have to look through too many commit histories on GitHub to see people are pretty terrible about making commits. ![A sadly common commit history](https://jason.pureconcepts.net/images/git-commit-history.png) Now I'm not going to talk about writing commit messages. Here's *the* [post](http://chris.beams.io/posts/git-commit/) on that. I want to talk about the equally important topic of *when* to make commits. I get asked this a lot at conferences. Enough to where I made two *rules* I've continually put to the test. I make a commit when: 1. I complete a *unit of work*. 2. I have changes I may want to *undo*. Anytime I satisfy one of these rules, I commit that set of changes. To be clear, I commit **only** that set of changes. For example, if I had changes I may want to undo **and** changes that completed a unit of work, I'd make two commits - one containing the changes I may want to undo and one containing the changes that complete the work. I think the second rule is pretty straightforward. So let's tackle it first. Over the course of time, you'll make some changes you *know* will be undone. Be it a promotional feature, patch, or other temporary change someday soon you'll want to undo that work. If that's the case, I'll make these changes in their own commit. This way it's easy to find the changes and use `git revert`. This practice has proven itself time and again, I'll even commit changes I'm simply uncertain about in their own commit. So back to the first rule. I think generally most of us follow this rule. However, you don't have to scroll through too many repositories on GitHub to see that we're pretty bad with commits. The discrepancies come from how we define a *unit of work*. Let's start with how **not** to define a *unit of work*. A unit of work is *absolutely not* based on time. Making commits every X number of minutes, hours, or days is ridiculous and would never result in a *version history* that provides any value outside of a chronicling system. Yes, *WIP* commits are fine. But if they appear in the history of your *master* branch I'm coming for you! A unit of work is *not* based on the type of change. Making commits for *new files* separate from *modified files* rarely makes sense. Neither does any other *type* abstraction: code (e.g. JavaScript vs HTML), layer (e.g. Client vs API), or location (e.g. file system). So if a *unit of work* is **not** based on *time* or *type*, then what? I think it's based by *feature*. A feature provides more context. Therein making it a far better measurement for a *unit of work*. Often, implicit in this context are things like *time* and *type*, as well as the *nature* of the change. Said another way, by basing a *unit of work* by feature will guide you to make commits that tell a story. So, why not just make the first rule: *I make a commit when I complete a feature*? Well, I think this a case where the *journey* matters. A *feature* can mean different things, even within the context of the same repository. A feature can also vary in size. With *unit of work*, you keep the flexibility to control the *size* of the *unit*. You just need to know how to *measure*. I've found by *feature* gives you the best commit.
TypeScript
UTF-8
486
2.6875
3
[ "Apache-2.0" ]
permissive
import type { CollectionItem } from '../../types/eleventy.js'; export function firstWithTag(tag: string, items: CollectionItem[]): CollectionItem | undefined { return items?.find(item => { return !!item.data?.tags?.find(itemTag => itemTag === tag); }); } export function findByTag(tag: string, items: CollectionItem[]): CollectionItem[] { const results = items?.filter(item => { return !!item.data?.tags?.find(itemTag => itemTag === tag); }); return [...results]; }
Java
UTF-8
4,283
3.453125
3
[]
no_license
package slutprojekt; import java.util.*; public class Gamble { public static void main(String[] args) { Scanner user_input = new Scanner(System.in); /*Jag skapar strängar för alla kortvalörer och kortvärden.*/ String[] kortvalör = {"Hjärter", "Spader", "Ruter", "Klöver"}; String[] kortvärde = {"Ess", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Knekt", "Dam", "Kung"}; /*Jag har även valt att använda en budget för spelet så att man kan förlora.*/ /*Jag valde att använda double så att budgeten kan ha decimaler.*/ double budget = 100; /*Här har jag valt att skriva regler för spelet.*/ System.out.println("Välkommen till 'Ryker pengarna, ryker du'"); System.out.println("Regler:"); System.out.println("Du kommer att få satsa pengar på vilket kort som kommer att dras."); System.out.println("Det innebär att du kan skriva 'Hjärter Kung' och så skriver programmet vilket kort som dras."); System.out.println("Om du gissar rätt på valör eller värde så får du hela din insats tillbaka, inklusive 50% av insatsen."); System.out.println("Får du full pot och gissar rätt på både valör och värde så får du hela insatsen tillbaka, dubblad."); System.out.println("Var dock försiktig, du har en begränsad startbudget på 100SEK."); System.out.println("Kom ihåg: Ryker pengarna, ryker du"); /*Jag har skapat en while-loop som körs till budgeten är lika med 0*/ /*I while-loopen sker själva satsandet på kortvalör, värde och insats*/ while (budget > 0) { /* Vid själva satsandet så börjar programmet att fråga vilken valör man vill satsa på.*/ System.out.println("Välj valör att satsa på. Hjärter, Spader, Ruter, Klöver."); String spelare_valör = user_input.nextLine(); /*Sedan frågar programmet vilket värde kortet ska ha.*/ System.out.println("Välj värde att satsa på. Ess,2-10, Knekt, Dam, Kung."); String spelare_värde = user_input.nextLine(); /*Till sist frågar programmet hur mycket man ska satsa.*/ System.out.println("Hur mycket vill du satsa?"); String spelare_insats = user_input.nextLine(); double insats = Double.parseDouble(spelare_insats); /*Programmet subtraherar den nuvarande budgeten med insatsen.*/ budget = budget - insats; /*Här använder jag "Random" för att skapa ett slumpmässigt kort.*/ Random slump_kort = new Random(); String slump_valör = (kortvalör[slump_kort.nextInt(kortvalör.length)]); String slump_värde = (kortvärde[slump_kort.nextInt(kortvärde.length)]); /*Här skriver programmet ut det slumpmässiga kortets valör och värde.*/ System.out.println(slump_valör + " " + slump_värde); /*Här skapar jag en if-sats för den slumpmässiga valören på kortet.*/ /*Är valören den samma som den man satsade på så får man 1,25*insatsen tillbaka.*/ if (spelare_valör.equalsIgnoreCase(slump_valör)) { double valör_vinst = insats * 1.25; budget = budget + valör_vinst; System.out.println("Du gissade på rätt valör!"); } else { System.out.println("Det var tyvärr fel valör"); /*Här har jag skapat en till if-sats för det slumpmässiga värdet på kortet.*/ /*Ifall det är samma värde som det man satsar på så får man 1,5*insatsen tillbaka.*/ if (spelare_värde.equalsIgnoreCase(slump_värde)) { double värde_vinst = insats * 1.5; budget = budget + värde_vinst; System.out.println("Du gissade rätt värde"); } else { System.out.println("Det var tyvärr fel värde"); } /*Här skriver programmet in den nya budgeten efter satsningsprocessen.*/ /*Om budgeten är högre än 0 så startas programmet om.*/ System.out.println("Din budget är nu " + budget); } } } }
Markdown
UTF-8
299
2.6875
3
[]
no_license
# Article R3252-41 Si le créancier transfère son domicile, il en avise le greffe, à moins qu'il n'ait comparu par mandataire. **Liens relatifs à cet article** **Anciens textes**: - Code du travail - art. R145-36 (Ab) **Créé par**: - Décret n°2008-244 du 7 mars 2008 - art. (V)
Java
UTF-8
2,292
1.773438
2
[]
no_license
/* * Copyright &#169; 2007 Manhattan Associates All rights reserved. Do not copy, modify or redistribute this file without specific written permission from Manhattan Associates. */ package com.manh.wmos.services.outbound.service; import com.manh.wmos.services.outbound.data.RFPackFromToteData; public interface TMWIIRFPackToteManagerService extends IRFPackToteManagerService { // getoLpnSize public String getoLpnSize(String cartonNbr) throws com.manh.wm.core.util.WMException; // validate slot against sysCode public boolean validateSlotSysCode(String slot) throws com.manh.wm.core.util.WMException; // validate slot is already assigned to olpn public boolean validateSlotAlreadyAssingnedToOlpn(String slot) throws com.manh.wm.core.util.WMException; // validate PutWall For Olpn public boolean validatePutWallForOlpn(String slot) throws com.manh.wm.core.util.WMException; // update slot to olpn public boolean updateSlotOnLPN(String slot, String cartonNbr) throws com.manh.wm.core.util.WMException; // update LPN ref_field_1 public boolean updateLpnRefField(String userId, String tote) throws com.manh.wm.core.util.WMException; // validate Lpn Ref_Field_1 is Null public String validateLpnRefFieldNull(String cartonNbr) throws com.manh.wm.core.util.WMException; // update packingSatus of C_PACK_WAVE_CHUTE_STAGING public boolean updatePckStatusOfChuteStage(String cartonNbr) throws com.manh.wm.core.util.WMException; /** * Validates all three data before changing the Printer. * @param putwall * @param section * @param printRequester * @return */ public int validateData(String putwall, String section, String printRequester); /** * Updates the Printer based on matched PutWall and Section. * @param putWall * @param section * @param printRequester * @return */ public boolean updatePrintRequester(String putWall, String section, String printRequester); /** * Validates Tote against the current user. * @param tote * @param currentUser * @return */ public boolean validateToteUser(String tote, String currentUser); /** * Validates printer from System Code's misc fields for custom printer validation logic. * @param printerName * @return */ public short validatePrinterFromSysCode(String printerName); }
Java
UTF-8
4,841
1.96875
2
[]
no_license
package com.wso2telco.services.dep.sandbox.servicefactory.walletConfig; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.logging.LogFactory; import com.wso2telco.core.dbutils.exception.ServiceError; import com.wso2telco.dep.oneapivalidation.exceptions.CustomException; import com.wso2telco.dep.oneapivalidation.util.Validation; import com.wso2telco.dep.oneapivalidation.util.ValidationRule; import com.wso2telco.services.dep.sandbox.dao.DaoFactory; import com.wso2telco.services.dep.sandbox.dao.WalletDAO; import com.wso2telco.services.dep.sandbox.dao.model.custom.RetrieveAccountStatusConfigDTO; import com.wso2telco.services.dep.sandbox.servicefactory.AbstractRequestHandler; import com.wso2telco.services.dep.sandbox.servicefactory.Returnable; import com.wso2telco.services.dep.sandbox.util.CommonUtil; import com.wso2telco.services.dep.sandbox.util.RequestType; import com.wso2telco.services.dep.sandbox.util.ServiceName; public class RetrieveAccountStatusConfigRequestHandler extends AbstractRequestHandler<RetrieveAccountStatusConfigRequestWrapper> { RetrieveAccountStatusConfigRequestWrapper requestWrapper; RetrieveAccountStatusConfigResponseWrapper responseWrapper; WalletDAO walletDAO; { LOG = LogFactory.getLog(RetrieveAccountStatusConfigRequestHandler.class); dao = DaoFactory.getGenaricDAO(); walletDAO = DaoFactory.getWalletDAO(); } @Override protected Returnable getResponseDTO() { return responseWrapper; } @Override protected List<String> getAddress() { List<String> address = new ArrayList<String>(); return address; } @Override protected boolean validate(RetrieveAccountStatusConfigRequestWrapper wrapperDTO) throws Exception { String apiType = CommonUtil.getNullOrTrimmedValue(wrapperDTO.getApiType()); String serviceCall = CommonUtil.getNullOrTrimmedValue(wrapperDTO.getServiceCall()); try { ValidationRule[] validationRules = { new ValidationRule(ValidationRule.VALIDATION_TYPE_MANDATORY, "apiType", apiType), new ValidationRule(ValidationRule.VALIDATION_TYPE_MANDATORY, "serviceCall", serviceCall) }; Validation.checkRequestParams(validationRules); } catch (CustomException ex) { LOG.error("###WALLETCONFIG### Error in Validations. ", ex); responseWrapper.setRequestError( constructRequestError(SERVICEEXCEPTION, ex.getErrcode(), ex.getErrmsg(), ex.getErrvar()[0])); return false; } return true; } @Override protected Returnable process(RetrieveAccountStatusConfigRequestWrapper extendedRequestDTO) throws Exception { if (responseWrapper.getRequestError() != null) { responseWrapper.setHttpStatus(Status.BAD_REQUEST); return responseWrapper; } try { String apiType = extendedRequestDTO.getApiType(); String apiTypeRequest = apiType.toLowerCase(); String serviceCall = extendedRequestDTO.getServiceCall(); String serviceCallRequest = serviceCall.toLowerCase(); List<String> accountStatus = new ArrayList<String>(); accountStatus.add(AccountStatus.ACTIVE.toString()); accountStatus.add(AccountStatus.SUSPENDED.toString()); accountStatus.add(AccountStatus.TERMINATED.toString()); // check the valid api type if (!(apiTypeRequest.equals(RequestType.WALLET.toString().toLowerCase()))) { LOG.error("###WALLET### valid api type not provided. "); responseWrapper.setHttpStatus(Status.BAD_REQUEST); responseWrapper.setRequestError(constructRequestError(SERVICEEXCEPTION, ServiceError.SERVICE_ERROR_OCCURED, "valid api type not provided")); return responseWrapper; } if (!(serviceCallRequest.equals(ServiceName.BalanceLookup.toString().toLowerCase()))) { LOG.error("###WALLET### valid service call not provided. "); responseWrapper.setHttpStatus(Status.BAD_REQUEST); responseWrapper.setRequestError(constructRequestError(SERVICEEXCEPTION, ServiceError.SERVICE_ERROR_OCCURED, "valid service call not provided")); return responseWrapper; } RetrieveAccountStatusConfigDTO valueDTO = new RetrieveAccountStatusConfigDTO(); valueDTO.setAccountStatus(accountStatus); responseWrapper.setAccountStatusDTO(valueDTO); responseWrapper.setHttpStatus(Response.Status.OK); } catch (Exception ex) { LOG.error("###WALLETCONFIG### Error Occured in Wallet Service. ", ex); responseWrapper.setHttpStatus(Status.BAD_REQUEST); responseWrapper .setRequestError(constructRequestError(SERVICEEXCEPTION, ServiceError.SERVICE_ERROR_OCCURED, null)); return responseWrapper; } return responseWrapper; } @Override protected void init(RetrieveAccountStatusConfigRequestWrapper extendedRequestDTO) throws Exception { requestWrapper = extendedRequestDTO; responseWrapper = new RetrieveAccountStatusConfigResponseWrapper(); } }
Python
UTF-8
103
3.03125
3
[]
no_license
print('Marcelo', type('Marcelo')) print(10, type(10)) print(2.5, type(2.5)) print(10==10, type(10==10))
Python
UTF-8
1,169
2.875
3
[]
no_license
import pandas as pd import numpy as np import os import sys from sklearn.model_selection import train_test_split from naive_bayes import NaiveBayes from driver_helper import main datafile = 'nuclear_senti_dataset.csv' if __name__ == '__main__': alpha, reduce, word_freq = main(sys.argv[1:]) dataset = pd.read_csv(os.path.join( sys.path[0], datafile), sep=',', index_col=0, header=0) dataset.dropna(how='any', subset=['tweet_text_tokens'], inplace=True) print('----- Data Loaded -----') x_train, x_test, y_train, y_test = train_test_split( dataset['tweet_text_tokens'], dataset['sentiment'], test_size=0.2, random_state=191, stratify=dataset['sentiment']) classes = np.unique(y_train) nb = NaiveBayes(classes, float(alpha), reduce, int(word_freq)) print('----- Training In Progress with alpha = {} -----'.format(nb.alpha)) nb.train(x_train, y_train) print('----- Training Completed with {} words -----'.format( nb.vocab_length)) prob_classes = nb.test(x_test) test_acc = np.sum(prob_classes == y_test)/float(y_test.shape[0]) print('Test Set Accuracy: {:.05%}'.format(test_acc))
JavaScript
UTF-8
275
3.359375
3
[]
no_license
function TriangleArea(num1, num2, num3){ let semiPerimeter = (num1 + num2 + num3) / 2; let area = Math.floor(Math.sqrt(semiPerimeter * (semiPerimeter - num1) * (semiPerimeter - num2) * (semiPerimeter - num3))); return area ; } console.log(TriangleArea(3,4,5));
Python
UTF-8
1,801
3.375
3
[ "BSD-2-Clause" ]
permissive
import re from collections import defaultdict _ASSERTER_CHILD_NAME_PATTERN = re.compile('^[a-zA-Z0-9_]+$') class AsserterNode(object): def __init__(self, parent, on_failure_callback=None): if parent is not None and not isinstance(parent, AsserterNode): raise ValueError( 'Invalid parent {} of type {}'.format( parent, type(parent) ) ) self._parent = parent self._children = defaultdict(lambda: AsserterNode(self)) self._on_failure = on_failure_callback def on_failure(self, *args, **kwargs): if self._on_failure is not None: return self._on_failure(*args, **kwargs) return self._parent.on_failure(*args, **kwargs) def assert_true(self, condition, *args, **kwargs): if condition: return True return self.on_failure(*args, **kwargs) def set_on_failure_callback(self, callback): if not callback is None and not hasattr(callback, '__call__'): raise ValueError( 'The callback {} of type {} is not callable'.format( callback, type(callback) ) ) self._on_failure = callback def get_child(self, name): if not isinstance(name, str) or \ not _ASSERTER_CHILD_NAME_PATTERN.match(name): return ValueError( 'Invalid asserter child name {} of type {}'.format( name, type(name) ) ) return self._children[name] def __repr__(self): normal_repr = super(AsserterNode, self).__repr__() return "<AsserterNode {} with known children {}>".format( normal_repr, self._children.keys() )
Swift
UTF-8
6,516
4.28125
4
[]
no_license
import UIKit //let type: String = "Rectangle" //let description: String = "A quadrilateral with four right angles" // //var width: Int = 5 //var height: Double = 10.5 //var area = Double(width) * (height) // //height += 1 //width += 1 // //area = Double(width) * (height) //// Note how you can "interpolate" variables into Strings using the following syntax //print("The shape is a \(type) or \(description) with an area of \(area)") // //print("The maximum value \(Int32.max)") //print("The minimum value \(Int32.min)") // //print("The maximum value \(UInt32.max)") //print("The minimum value \(UInt32.min)") // //var myInt32: Int32 = 3 //var myNormalInt: Int //// This will not error, because we first convert Int32 to instance of Int Type //myNormalInt = Int(myInt32) // ////For Loops~ loop from 1 to 5 including 5 //for i in 1...5 { // print(i) //} //// loop from 1 to 5 excluding 5 //for i in 1..<5 { // print(i) //} // //var start = 0 //var end = 5 //// loop from start to end including end //for i in start...end { // print(i) //} //// loop from start to end excluding end //for i in start..<end { // print(i) //} // ////while Loops: //var i = 1 //while i < 6 { // print(i) // i = i+1 //} // ////Create a loop (either for or while) that prints all the valiues from 1-225 //for i in 1...225 { // print (i) //} // ////Create a program that prints all of the values from 1-100 that are divisible by 3 or 5 but not both //for i in 1...100{ // if i % 3 == 0 && i % 5 == 0 { // print() // } else { // if i % 3 == 0 || i % 5 == 0 { // print(i) // } // } //} // //Create a program that prints all of the values from 1-100 that are divisible by 3 or 5 but not both //for i in 1...100{ // if i % 3 == 0 && i % 5 == 0 { // print() // } else { // if i % 3 == 0 || i % 5 == 0 { // print(i) // } // } //} ////Now modify that program to print "Fizz" when the number is divisible by 3 and "Buzz" when the number is divisible by 5 as well as "FizzBuzz" when the number is divisible by both! //for i in 1...100{ // if i % 3 == 0 { // print("Fizz") // }; if i % 5 == 0 { // print ("Buzz") // }; if i % 3 == 0 || i % 5 == 0 { // print("FizzBuzz") //} else { // print(i) // } //} //Question 1: Write a program that adds the numbers 1-255 to an array // // //var array = [UInt32]() //for i in 1...255{ // array.append(UInt32(i)) //} // //print (array) // ////print (arc4random_uniform(256)) -> generates a number between the 1 to 256 // ////Question 2: Swap two random values in the array //var length = array.count //var randomOne = Int(arc4random_uniform(UInt32(length))) //var randomTwo = Int(arc4random_uniform(UInt32(length))) // //if randomOne != randomTwo { // swap (&array[randomOne] , &array[randomTwo]) //} //print (array) // //// Question 3: write the code that swaps random values 100 times (You've created a "Shuffle"!) //for i in 1...100{ // var randomOne = Int(arc4random_uniform(UInt32(length))) // var randomTwo = Int(arc4random_uniform(UInt32(length))) // // if randomOne != randomTwo{ // swap (&array[randomOne] , &array[randomTwo]) // } //} //print (array) // //// Question 4: Remove the value "42" from the array and Print "We found the answer to the Ultimate Question of Life, the Universe, and Everything at index __" and print the index of where "42" was before you removed it. // //for i in 0..<array.count{ // if (array[i] == 42) { // array.remove(at: i) // print("We found the answer to the Ultimate Question of Life, the Universe, and Everything at index 42") // break // } //} //print (array) // SUITS //Given the following three variables write a for-in loop that will have the following output in the Assistant Editor. // //let suits = ["Clubs", "Diamonds", "Hearts", "Spades"] //let cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] //var deckOfCards = [String: [Int]]() ////printing cards one at a time ////for suit in suits { // if you are looking to print everything on column at a time //// print ("\(suit)") //// for card in cards{ //// print ("\(card)") //// } ////} //for i in 0..<suits.count{ //ways of working with dictionary is to set the key equals (=) the value // deckOfCards[suits[i]] = cards //} //print(deckOfCards) // HEADS or TAILS //Create a function tossCoin() -> String //Have this function print "Tossing a Coin!" Next have the function randomly pick either "Heads" or "Tails" //func cointoss() -> String{ // let coin = Int(arc4random_uniform(UInt32(2))) // print (coin) // if coin == 0 { // return "Heads" // }else { // return "Tails" // } //} //var toss = cointoss() //print (toss) // ////Now create another function tossMultipleCoins(Int) -> Double ////Have this function call the tossCoin function multiple times based on the Integer input Have the function return a Double that reflects the ratio of head toss to total toss // //func tossMultipleCoins(tosses:Int) -> Double{ // var headsCount = 0 // var tailsCount = 0 // for toss in 0...tosses{ //shows the length of all the tosses coming from the input // if cointoss() == "Heads"{ // headsCount += 1 // }else{ // tailsCount += 1 // } // } // print ("heads count has a total of \(headsCount) out of \(tosses) tosses") // return Double(tosses) / Double(headsCount) // } //tossMultipleCoins(tosses:100) class Person { var species = "H. Sapiens" var name: String init(name: String) { // Note: this function doesn't get called explicitly. It is called // when creating an instance using the initialization syntax -- "Person()" self.name = name // Note the use of "self" here to refer to the name property } func speak() { print("Hello! I am a \(self.species) and my name is \(self.name)") // Note how we refer to the properties using "self" } } class Developer: Person { // Note how we are specifying that Developer will inherit from Person var favoriteLanguage: String init(name: String, favoriteLanguage: String) { self.favoriteLanguage = favoriteLanguage super.init(name: name) } override func speak() { print("Hello! I am a Developer! My name is \(self.name)") } } var myDeveloper: Developer = Developer(name: "Jay", favoriteLanguage: "Swift") myDeveloper.speak()
PHP
UTF-8
2,199
3.140625
3
[]
no_license
<?php namespace bibliovox\models; use Exception; use Illuminate\Database\Eloquent\Model; use PDOException; /** * Modèle MVC de Recueil * @method static orderBy(string $nomColone, string $mode) * @method static where(string $nomColone, string $comparateur, string $valeur) * @property string nomR le nom du recueil * @property string descriptionR la description du receuil */ class Recueil extends Model { public $timestamps = false; protected $primaryKey = 'idR'; protected $table = 'recueil'; /** * Test si un id de recueil existe * * @param int $idR id recueil * @return bool true si recueil existe */ static function exist(int $idR): bool { return (Recueil::where("idR", "=", "$idR")->first() != null); } /** * Récupère un recueil avec son id * @param int $idR l'id * @return object un Recueil */ static function getById(int $idR) { return Recueil::where("idR", "=", "$idR")->first(); } public static function allCheck(int $idU) { return Recueil::where("idU", "=", "$idU"); } /** * Créer un nouveau recueil dans la basse de données * @param string $nom le nom du recueil * @param string $texte le contenu du recueil * @return object Le recueil créé * @throws Exception Erreur creation dans la base de données */ public static function createNew(string $nom, string $texte) { /** @var bool $res si créer dans BBD */ $res = false; $newRecueil = new Recueil(); $newRecueil->nomR = filter_var($nom, FILTER_SANITIZE_STRING); $newRecueil->descriptionR = filter_var($texte, FILTER_SANITIZE_STRING); try { $res = $newRecueil->save(); } catch (PDOException $e) { } if ($res == false) { throw new Exception('Le recueil n\'a pu être créé'); } return $newRecueil; } public static function updateAll($idR, $titre, $contenu) { $rec = Recueil::where("idR", "=", "$idR")->first(); $rec->nomR = $titre; $rec->descriptionR = $contenu; $rec->save(); } }
PHP
UTF-8
3,158
2.6875
3
[]
no_license
<?php /** * @file * This file provides drush integration for hosting_vnodectrl. * It communiciates with the vnodectrl drush backend and provides * it with information it needs. */ /** * Implementation of hook_drush_command(). */ function hosting_vnodectrl_drush_command() { $items = array(); $items['hosting-vnodectrl-register-images'] = array( 'description' => dt('Imports available images throgh vnodectrl.'), ); return $items; } /** * Callback for hosting-vnodectrl-register-images. * Register all available images for drivers that exist. */ function drush_hosting_vnodectrl_register_images() { drush_log("Fetching images", 'status'); drush_shell_exec("vnodectrl list-images --format=json"); $images_output = implode('\n', drush_shell_exec_output()); $images = (array)json_decode($images_output); if (is_array($images)) { // Empty the database db_query("DELETE FROM {hosting_vnodectrl_images}"); foreach ($images as $driver => $images) { foreach ($images as $image) { $image->provider = $driver; drupal_write_record('hosting_vnodectrl_images', $image); } } drush_log("Images updated.", 'ok'); } else { drush_log('Something went wrong: ' . json_last_error(), 'error'); } } function drush_hosting_vnodectrl_pre_hosting_task() { $task =& drush_get_context('HOSTING_TASK'); if ($task->ref->type == 'server' && ($task->task_type == 'create-server' || $task->task_type == 'delete-server' || $task->task_type == 'server-info')) { drush_log(print_r($task->ref, TRUE), 'ok'); $task->options['provider'] = $task->ref->provider; $task->options['image'] = $task->ref->image; $task->options['name'] = $task->ref->title; $task->options['size'] = $task->ref->size; $task->options['instance_id'] = $task->ref->instance_id; $task->options['additional'] = implode('|', $task->ref->additional); } else { drush_log("something went wrong", 'error'); } } function drush_hosting_vnodectrl_post_hosting_task() { $task = & drush_get_context('HOSTING_TASK'); if ($task->ref->type == 'server' && $task->task_type == 'create-server') { $output =& drush_get_context('HOSTING_DRUSH_OUTPUT'); drush_log(print_r($output['object'], TRUE), 'ok'); if (isset($output['object']['node']['id'])) { // Save the machine ID so we can operate on it. $task->ref->instance_id = $output['object']['node']['id']; node_save($task->ref); } } elseif ($task->ref->type == 'server' && $task->task_type == 'delete-server') { // Remove the machine ID since it is now removed. $task->ref->instance_id = ''; $task->ref->ip_addresses = array(); node_save($task->ref); } elseif ($task->ref->type == 'server' && $task->task_type == 'server-info') { // Fill in relevant information about the server. $output =& drush_get_context('HOSTING_DRUSH_OUTPUT'); drush_log(print_r($output['object'], TRUE), 'ok'); if (isset($output['object']['node']['public_ips'])) { drush_log('yeah'); $task->ref->ip_addresses = $output['object']['node']['public_ips']; node_save($task->ref); } } }
Java
UTF-8
2,290
3.359375
3
[]
no_license
package xiancheng; /** * start方法只是使线程进入就绪状态,要想线程结束, * 还要等待获取CPU资源来进入运行状态,运行完后结束线程。 * sleep(1000)使线程挂起1000毫秒,1000毫秒过去重新竞争CPU资源。 * 在一个时间点可以处理一个线程,在一个时间段可以处理多个线程(多核除外)。 * @author Administrator */ public class TestTongbu { public static void main(String[] args) { // final Object someObject = new Object(); TongbuHero h = new TongbuHero(1000); //重点:同步进行 int threadCount = 10; Thread[] beidaThreads = new Thread[threadCount]; Thread[] huifuThreads = new Thread[threadCount]; for(int i=0; i<threadCount; i++) { Thread t = new Thread() { @Override public void run() { // //任何线程要修改hp的值,必须先占用someObject // synchronized(someObject) { // h.beDamage(1); // } h.beDamage(1); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }; beidaThreads[i] = t; t.start(); } for(int i=0; i<threadCount; i++) { Thread t = new Thread() { @Override public void run() { // //任何线程要修改hp的值,必须先占用someObject // synchronized(someObject) { // h.huifu(1); // } h.huifu(1); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }; huifuThreads[i] = t; t.start(); } for(Thread t : beidaThreads) { try { t.join(); }catch(InterruptedException e) { e.printStackTrace(); } } for(Thread t : huifuThreads) { try { t.join(); }catch(InterruptedException e) { e.printStackTrace(); } } } } class TongbuHero{ public int hp; public TongbuHero(int hp) { this.hp = hp; } public void huifu(int num) { synchronized(this) { hp += num; System.out.printf("已回复血量%d,剩余血量%d%n", num, hp); } } public void beDamage(int num) { synchronized(this) { hp -= num; System.out.printf("损耗血量%d,剩余血量%d%n", num, hp); } } }
Python
UTF-8
569
2.671875
3
[]
no_license
class Solution(object): def fourSumCount(self, A, B, C, D): """ :type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int """ ans=0 di={} for i in A: for j in B: if i+j not in di: di[i+j]=1 else: di[i+j]+=1 for i in C: for j in D: if -i-j in di: ans+=di[-i-j] return ans
Markdown
UTF-8
1,004
2.921875
3
[]
no_license
# Applying and Executing a Playbook Now we will "apply" the newly created playbook to our _StackPulse_ account and trigger its execution. Please return to the "Terminal" tab in your environment. ## Applying your playbook into your StackPulse account To apply (upload) your playbook into your StackPulse account, please run: `./stackpulse apply playbook -f first_playbook.yaml`{{execute}} If the operation is successful, a message similar to the below (albeit with a different ID) should be shown: ```bash created "first_playbook" id="b351a757-92cb-44d0-942e-36828f8144ec" ``` ## Executing a playbook To trigger an execution of your playbook, please run: `./stackpulse run playbook first_playbook`{{execute}} If the operation is successful, you will see an output similar to the below: ```bash Running Playbook first_playbook Execution: https://app.stackpulse.io/execution/d5b69ca7-d935-4be4-ba78-d87c09d044fe ``` Do a `Command+Click`/`Ctrl+Click` on the URL to see the execution results.
C#
UTF-8
13,246
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Configuration; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Text; using System.Web.UI.HtmlControls; namespace TechOnline { public partial class _Default : Page { string strConnection = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { addComputers(); addCellPhones(); addGamming(); addTvs(); } } public void addComputers() // Computers & Tables { SqlConnection con = new SqlConnection(strConnection); SqlCommand firstRow = new SqlCommand("select prd.Id, prd.Name, prd.Description, prd.Barcode, prd.Quantity, prd.Price, prd.CategoryId, prd.Image, prd.SellingPrice, prd.CapturedDate, prd.BrandId " + "from Product prd " + "left join ProductCategory pc on pc.Id = prd.CategoryId " + "left join ProductDepartment pd on pd.Id = pc.DepartmentId " + "WHERE pd.Id = @ProdValue", con); firstRow.Parameters.AddWithValue("@ProdValue", "2"); string rowString = ""; int count = 0; string image = ""; string categoryId = ""; try { con.Open(); SqlDataReader reader = firstRow.ExecuteReader(); while (reader.Read()) { try { var base64 = Convert.ToBase64String((byte[])reader["Image"]); var imgsrc = string.Format("data:image/gif;base64,{0}", base64); image = "<img src= '" + imgsrc + "' height = '100' width = '150px' />"; } catch (Exception) { image = "<img src='' alt='Image not available' height = '100' width = '150px' />"; } if (count < 6) { if (Convert.ToDecimal(reader["SellingPrice"]) < Convert.ToDecimal(reader["Price"])) { rowString += "<div class='col-sm-2' > <a style='color: black;' runat='server' href='ProductDetails?Id=" + reader["Id"] + "'> " + image + " <br> <p> " + reader["Description"] + " <br> <strong> R " + reader["SellingPrice"] + " </strong> <br> <del> R " + reader["Price"] + " </del> </p> </a> </div>"; } else { rowString += "<div class='col-sm-2' > <a style='color: black;' runat='server' href='ProductDetails?Id=" + reader["Id"] + "'> " + image + " <br> <p> " + reader["Description"] + " <br> <strong> R " + reader["SellingPrice"] + " </strong> </p> </a> </div>"; } } count++; categoryId = reader["CategoryId"].ToString(); } con.Close(); } catch(Exception) { } divFirstRow.InnerHtml = rowString; firstRowHeader.InnerHtml = "<div class='col-sm-6'> <p><a href='Search?defaultData=2,0' style ='color:black;'> Take a look at our affordable computers</a></p> </div>" + "<div class='col-sm-6' style='text-align: right'> <a href = 'Search?defaultData=2,0' class='btn btn-info' role='button'>View More</a></div>"; } public void addCellPhones() // Cellphones & GPS { SqlConnection con = new SqlConnection(strConnection); SqlCommand firstRow = new SqlCommand("select prd.Id, prd.Name, prd.Description, prd.Barcode, prd.Quantity, prd.Price, prd.CategoryId, prd.Image, prd.SellingPrice, prd.CapturedDate, prd.BrandId " + "from Product prd " + "left join ProductCategory pc on pc.Id = prd.CategoryId " + "left join ProductDepartment pd on pd.Id = pc.DepartmentId " + "WHERE pd.Id = @ProdValue", con); firstRow.Parameters.AddWithValue("@ProdValue", "3"); string rowString = ""; int count = 0; string image = ""; string categoryId = ""; try { con.Open(); SqlDataReader reader = firstRow.ExecuteReader(); while (reader.Read()) { try { var base64 = Convert.ToBase64String((byte[])reader["Image"]); var imgsrc = string.Format("data:image/gif;base64,{0}", base64); image = "<img src= '" + imgsrc + "' height = '100' width = '150px' />"; } catch (Exception) { image = "<img src='' alt='Image not available' height = '100' width = '150px' />"; } if (count < 6) { if (Convert.ToDecimal(reader["SellingPrice"]) < Convert.ToDecimal(reader["Price"])) { rowString += "<div class='col-sm-2' > <a style='color: black;' runat='server' href='ProductDetails?Id=" + reader["Id"] + "'> " + image + " <br> <p> " + reader["Description"] + " <br> <strong> R " + reader["SellingPrice"] + " </strong> <br> <del> R " + reader["Price"] + " </del> </p> </a> </div>"; } else { rowString += "<div class='col-sm-2' > <a style='color: black;' runat='server' href='ProductDetails?Id=" + reader["Id"] + "'> " + image + " <br> <p> " + reader["Description"] + " <br> <strong> R " + reader["SellingPrice"] + " </strong> </p> </a> </div>"; } } count++; categoryId = reader["CategoryId"].ToString(); } con.Close(); } catch (Exception) { } divSecondRow.InnerHtml = rowString; secondRowHeader.InnerHtml = "<div class='col-sm-6'> <p><a href = 'Search?defaultData=3,0' style ='color:black;'> Own a smartphone for upgrade</a></p> </div>" + "<div class='col-sm-6' style='text-align: right'> <a href = 'Search?defaultData=3,0' class='btn btn-info' role='button'>View More</a></div>"; } public void addGamming() // Gamming { SqlConnection con = new SqlConnection(strConnection); SqlCommand firstRow = new SqlCommand("select prd.Id, prd.Name, prd.Description, prd.Barcode, prd.Quantity, prd.Price, prd.CategoryId, prd.Image, prd.SellingPrice, prd.CapturedDate, prd.BrandId " + "from Product prd " + "left join ProductCategory pc on pc.Id = prd.CategoryId " + "left join ProductDepartment pd on pd.Id = pc.DepartmentId " + "WHERE pd.Id = @ProdValue", con); firstRow.Parameters.AddWithValue("@ProdValue", "8"); string rowString = ""; int count = 0; string image = ""; string categoryId = ""; try { con.Open(); SqlDataReader reader = firstRow.ExecuteReader(); while (reader.Read()) { try { var base64 = Convert.ToBase64String((byte[])reader["Image"]); var imgsrc = string.Format("data:image/gif;base64,{0}", base64); image = "<img src= '" + imgsrc + "' height = '100' width = '150px' />"; } catch (Exception) { image = "<img src='' alt='Image not available' height = '100' width = '150px' />"; } if (count < 6) { if (Convert.ToDecimal(reader["SellingPrice"]) < Convert.ToDecimal(reader["Price"])) { rowString += "<div class='col-sm-2' > <a style='color: black;' runat='server' href='ProductDetails?Id=" + reader["Id"] + "'> " + image + " <br> <p> " + reader["Description"] + " <br> <strong> R " + reader["SellingPrice"] + " </strong> <br> <del> R " + reader["Price"] + " </del> </p> </a> </div>"; } else { rowString += "<div class='col-sm-2' > <a style='color: black;' runat='server' href='ProductDetails?Id=" + reader["Id"] + "'> " + image + " <br> <p> " + reader["Description"] + " <br> <strong> R " + reader["SellingPrice"] + " </strong> </p> </a> </div>"; } } count++; categoryId = reader["CategoryId"].ToString(); } con.Close(); } catch (Exception) { } divThirdRow.InnerHtml = rowString; thirdRowHeader.InnerHtml = "<div class='col-sm-6'> <p><a href = 'Search?defaultData=8,0' style ='color:black;'> Gaming is fun, checkout the latest games here</a></p> </div>" + "<div class='col-sm-6' style='text-align: right'> <a href = 'Search?defaultData=8,0' class='btn btn-info' role='button'>View More</a></div>"; } public void addTvs() // TV, Audio & Video { SqlConnection con = new SqlConnection(strConnection); SqlCommand firstRow = new SqlCommand("select prd.Id, prd.Name, prd.Description, prd.Barcode, prd.Quantity, prd.Price, prd.CategoryId, prd.Image, prd.SellingPrice, prd.CapturedDate, prd.BrandId " + "from Product prd " + "left join ProductCategory pc on pc.Id = prd.CategoryId " + "left join ProductDepartment pd on pd.Id = pc.DepartmentId " + "WHERE pd.Id = @ProdValue", con); firstRow.Parameters.AddWithValue("@ProdValue", "4"); string rowString = ""; int count = 0; string image = ""; string categoryId = ""; try { con.Open(); SqlDataReader reader = firstRow.ExecuteReader(); while (reader.Read()) { try { var base64 = Convert.ToBase64String((byte[])reader["Image"]); var imgsrc = string.Format("data:image/gif;base64,{0}", base64); image = "<img src= '" + imgsrc + "' height = '100' width = '150px' />"; } catch (Exception) { image = "<img src='' alt='Image not available' height = '100' width = '150px' />"; } if (count < 6) { if (Convert.ToDecimal(reader["SellingPrice"]) < Convert.ToDecimal(reader["Price"])) { rowString += "<div class='col-sm-2' > <a style='color: black;' runat='server' href='ProductDetails?Id=" + reader["Id"] + "'> "+image+" <br> <p> " + reader["Description"] + " <br> <strong> R " + reader["SellingPrice"] + " </strong> <br> <del> R " + reader["Price"] + " </del> </p> </a> </div>"; } else { rowString += "<div class='col-sm-2' > <a style='color: black;' runat='server' href='ProductDetails?Id=" + reader["Id"] + "'> " + image + " <br> <p> " + reader["Description"] + " <br> <strong> R " + reader["SellingPrice"] + " </strong> </p> </a> </div>"; } } count++; categoryId = reader["CategoryId"].ToString(); } con.Close(); } catch (Exception) { } divFourthRow.InnerHtml = rowString; fourthRowHeader.InnerHtml = "<div class='col-sm-6'> <p><a href = 'Search?defaultData=4,0' style ='color:black;'> Experience the great entertainment at home</a ></p> </div>" + "<div class='col-sm-6' style='text-align: right'> <a href = 'Search?defaultData=4,0' class='btn btn-info' role='button'>View More</a></div>"; } public void addProducts(string depValue, HtmlGenericControl myDiv) { HtmlGenericControl div = new HtmlGenericControl("div"); div.ID = "divFourthRow"; div.InnerHtml = "Hello"; } } }
C++
UTF-8
334
2.734375
3
[]
no_license
#include<iostream> using namespace std; int main(){ int arr[100][100]; int m,n; cin>>m>>n; for(int i=0;i<m;i++){ for(int z=0;z<n;z++){ cin>>arr[i][z]; } } for(int z=0;z<n;z++){ for(int i=m-1;i>=0;i--){ cout<<arr[i][z]<<" "; } cout<<endl; } }
Markdown
UTF-8
3,201
2.953125
3
[]
no_license
# Show and tell - Neural Image Caption Generator This project is to reimplement the show and tell paper (Vinyals et al., 2015). This application helps visually-impaired people by transforming visual signals into proper language, which involves tasks of both image classification as well as natural language processing. Using 500 GPU hours for training, the trainning process managed to improve the performance and the convergence by replacing the pre-trained model to ResNet 152, using Adam optimizer and several other experiments. As a result, the model yields better performance compared to the original paper on the MSCOCO 2014 testing set. ## Implementation - Dataset: MSCOCO dataset (2017), divided into a training set containing 118k images and a validation set containing 5k images. - Data Augmentation: Resize, Ramdon Changes and Normalization. - The image captioning model(CNN+RNN with dropout): detailed model can found at model.py. The encoder is essentially a pretrained ResNet 152 model. Before outputting the image embedding vector, two FC layers and a dropout layer is applied to add non-linear factors and to reduce overfitting. The decoder is essentially a one layer LSTM model, with the initial hidden state being the image embedding produced by the encoder, the initial input of captions being the index of the start token. - Beam Search: With beam search, instead of always selecting the word with highest probability at each time step, we maintain a priority queue that keeps track of BEAM_SIZE sequences with highest probabilities and at each time step we will generate BEAM_SIZE words with highest probabilities for each sequence that we are tracking, then we only keep the top BEAM_SIZE new sequences for the next time step. ## Results - Training procedure of the best model <p align="center"> <img src="https://github.com/xiekt1993/Portfolio/blob/master/Neural_Image_Caption_Generator/examples2.png" width="750"/> </p> - Loss curves <p align="center"> <img src="https://github.com/xiekt1993/Portfolio/blob/master/Neural_Image_Caption_Generator/examples3.png" width="750"/> </p> - A selection of generated captions, randomly sampled from the testing set <p align="center"> <img src="https://github.com/xiekt1993/Portfolio/blob/master/Neural_Image_Caption_Generator/examples.png" width="750"/> </p> ## Conclusion It is not hard to implement it in terms of coding the end-to-end architecture. However, it is difficult to train the model since it suffers from overfitting quite a lot. There are also some ways to improve our results. 1) The first is to try scheduled sampling when training; 2) the second is to use attention mechanism; 3) the third is to train more models using the best architecture. ## Reference - Vinyals, Oriol, et al. "Show and tell: A neural image caption generator." Proceedings of the IEEE conference on computer vision and pattern recognition. 2015. - Chen, Xinlei, et al. "Microsoft COCO captions: Data collection and evaluation server." arXiv preprint arXiv:1504.00325(2015). - Xu, Kelvin, et al. "Show, attend and tell: Neural image caption generation with visual attention." International conference on machine learning. 2015.
SQL
UTF-8
1,295
4.03125
4
[]
no_license
select e.emp_no, e.last_name, e.first_name, e.gender, salaries.salary from employees as e join salaries on e.emp_no = salaries.emp_no; select first_name, last_name, hire_date from employees where hire_date > '1985-12-31' and hire_date < '1987-01-01'; select d.dept_no, d.dept_name, dm.emp_no, e.last_name, e.first_name, dm.from_date, dm.to_date from departments as d join dept_manager as dm on d.dept_no = dm.dept_no join employees as e on dm.emp_no = e.emp_no ; select e.emp_no, e.last_name, e.first_name, d.dept_name from employees as e join dept_emp as dm on e.emp_no = dm.emp_no join departments as d on dm.dept_no = d.dept_no ; select first_name, last_name from employees where first_name = 'Hercules' and last_name like 'B%' ; select dm.emp_no, e.last_name, e.first_name, d.dept_name from dept_emp as dm join departments as d on dm.dept_no = d.dept_no join employees as e on dm.emp_no = e.emp_no where d.dept_name = 'Sales' ; select dm.emp_no, e.last_name, e.first_name, d.dept_name from dept_emp as dm join departments as d on dm.dept_no = d.dept_no join employees as e on dm.emp_no = e.emp_no where d.dept_name = 'Sales' or d.dept_name = 'Development' ; select last_name, count (emp_no) as "Total Employees" from employees group by last_name order by "Total Employees" desc ;
Python
UTF-8
1,404
3.96875
4
[]
no_license
# -*- coding: utf-8 -*- # @property装饰器负责把一个类方法(动词)变成属性(名词) # property 属性优先级高于实例化对象属性 即self.score会优先查找property,没有在查找对象的score class Student(object): def __init__(self, score): # self.__score = score # 这种情况,初始化还是可以输入字符串的, self.score = score # self.score = score 会调用@score.setter def score(self, score) # self.score 会调用@property的def score @property def score(self): return self.__score # 可以看到这里是__score @score.setter # 可以控制实例化时,传入参数的类型和范围 def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer') if value < 0 or value > 100: raise ValueError('score must be in 0~100') self.__score = value # 是__score,所以最终的是结果是: score最终赋给self.__score @score.deleter def score(self): # del self.__score raise Exception("score is permitted delete") p = Student(99) # 把一个getter方法变成属性,只需要加上@property就可以了, # 此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值 print(p.score) p.score = 80 print(p.score) # del p.score
Python
UTF-8
1,393
3.890625
4
[]
no_license
# guess_word = 'mars' count = 0 guessword = 'nigeria' guessword2 = "india" guessword3 = "andriod" print('welcome new user') print() name = input('what will you want me to call you? ') print('sound great ' + name) print("quiz is just for fun, if you get above 2 you passed ") print() question = input('which planet is the best to spend your holiday ? ') if question == guess_word: print('You got it right ') count = count + 1 else: print("Sorry are wrong") print("let move on ") print() question2 = input("what is the name of the authors place of birth ? ") if question2 == guessword: print("That correct ") count = count + 1 print("you have scored " + str(count) + " so far ") else: print("Wrong, you have scored " + str(count) + "so far ") print("That was awesome, scoring " + str(count)) print("3rd question") print() question3 = input("which country has the highest population un the world ") if question3 == guessword2: print("correct! " + name) count = count + 1 else: print("sorry, you missed " + name) print("Good Job! " + name + " you have score " + str(count)) question4 = input("which phone model is mostly used in africa ? ") if question4 == guessword3: print("that cool ") count = count + 1 else: print("lol") print(" we have come to the end of the quizz and you scored " + str(count) + " thanks for playing ") print(" bye ")
Java
UTF-8
159
1.789063
2
[]
no_license
package rasras.feisal.mvp.mvp.view; /** * Created by feisal on 1/28/17. * All rights reserved. */ public interface View { void onError(Throwable e); }
Python
UTF-8
6,441
2.734375
3
[]
no_license
import re import os from requests_html import HTML from file_management import write_dicts_to_file def open_match(number): with open('data/players/' + str(number) + '.json') as f: return f.read() def scrape_pages(path): teams = [] statistics = [] players = [] index = 0 for dirpath, _, names in os.walk(path): for name in filter(lambda n: 'json' in n, names): with open(os.path.join(dirpath, name)) as f: d = scrape_page(f.read()) statistics.extend(d['stats']) if d['team_a'] not in teams: teams.append(d['team_a']) if d['team_b'] not in teams: teams.append(d['team_b']) for p in d['players']: if p not in players: players.append(p) print("Parsed file No. " + str(index)) index += 1 write_dicts_to_file(statistics, os.path.join(path, 'stats.csv')) write_dicts_to_file(teams, os.path.join(path, 'teams.csv')) write_dicts_to_file(players, os.path.join(path, 'players.csv')) def scrape_page(text): html = HTML(html=text) table = html.find('table', first=True) return scrape_table(table) def scrape_table(table): a_xp = ( "//tr[count(preceding-sibling::tr[@class='hdr'])=1 and" "count(following-sibling::tr[@class='ftr'])=2]" ) team_a_rows = table.xpath(a_xp) b_xp = ( "//tr[count(preceding-sibling::tr[@class='hdr'])=2 and" "count(following-sibling::tr[@class='ftr'])=1]" ) team_b_rows = table.xpath(b_xp) team_a_name, team_a_id, team_b_name, team_b_id = scrape_teams(table) m_id = match_id(table) team_a_stats = map(lambda row: stats(row, m_id), team_a_rows) team_b_stats = map(lambda row: stats(row, m_id), team_b_rows) players = scrape_players(team_a_rows, team_a_id) \ + scrape_players(team_b_rows, team_b_id) return { 'players': players, 'stats': list(team_a_stats) + list(team_b_stats), 'team_a': {'id': team_a_id, 'name': team_a_name}, 'team_b': {'id': team_b_id, 'name': team_b_name} } def match_id(table): anchor = table.find('tr > th > span.actions > a', first=True) match_re = re.compile(r'zapas_(\d+)_') match_found = re.search(match_re, anchor.attrs['href']) return match_found[0] def scrape_teams(table): a_xp = "//tr[count(following-sibling::tr[@class='hdr'])=2]" b_xp = ( "//tr[preceding-sibling::tr[@class='empty'] and" "following-sibling::tr[@class='hdr']]" ) team_a_name = team_name(table.xpath(a_xp, first=True)) team_b_name = team_name(table.xpath(b_xp, first=True)) team_a_id = team_id(table.xpath(a_xp, first=True)) team_b_id = team_id(table.xpath(b_xp, first=True)) return (team_a_name, team_a_id, team_b_name, team_b_id) def scrape_players(rows, tm_id): players = [] for row in rows: p = player(row) p['team_id'] = tm_id players.append(p) return players def player(row): cells = row.find('td') number = -1 if cells[0].find('strong', first=True) is not None: number = int_or_default(cells[0].find('strong', first=True).text) else: number = int_or_default(cells[0].text) return { 'id': player_id(row), 'name': cells[1].attrs['title'], 'number': number } def team_name(row): team = row.find('tr > th > a', first=True) return team.text def team_id(row): team = row.find('tr > th > a', first=True) re_id = re.compile(r'detail_(\d+)_') return re.search(re_id, team.attrs['href'])[1] def stats(row, match_id): goals_2p, misses_2p = shots_2p(row) goals_3p, misses_3p = shots_3p(row) goals_free_throw, misses_free_throw = free_throws(row) balls_won, balls_lost = balls(row) fauls_won, fauls_lost = fauls(row) return { 'player_id': player_id(row), 'match_id': match_id, 'time_in_play': time(row), 'goals_2p': goals_2p, 'misses_2p': misses_2p, 'goals_3p': goals_3p, 'misses_3p': misses_3p, 'goals_free_throw': goals_free_throw, 'misses_free_throw': misses_free_throw, 'offensive_rebounds': offensive_rebounds(row), 'deffensive_rebounds': deffensive_rebounds(row), 'blocks': blocks(row), 'assists': assists(row), 'balls_won': balls_won, 'balls_lost': balls_lost, 'fauls_won': fauls_won, 'fauls_lost': fauls_lost, 'value': value(row), 'points': points(row) } def time(row): cells = row.find('td') re_time = re.compile(r'(\d+):(\d+)') time_str = re.search(re_time, cells[2].text) result = -1 if time_str is not None: result = int(time_str[1]) * 60 + int(time_str[2]) return result def player_id(row): p = row.find('td > a', first=True) re_id = re.compile(r'hrac_(\d+)_') result = -1 if p is not None: result = re.search(re_id, p.attrs['href'])[1] return result def shots_2p(row): return extract_throws(row, 4) def shots_3p(row): return extract_throws(row, 5) def free_throws(row): return extract_throws(row, 6) def extract_throws(row, cell_no): cells = row.find('td') digs = re.search(re.compile(r'(\d+)/(\d+)'), cells[cell_no].text) result = (-1, -1) if digs is not None: result = (int(digs[1]), int(digs[2])) return result def offensive_rebounds(row): cells = row.find('td') return int_or_default(cells[9].text) def deffensive_rebounds(row): cells = row.find('td') return int_or_default(cells[10].text) def blocks(row): cells = row.find('td') return int_or_default(cells[11].text) def assists(row): cells = row.find('td') return int_or_default(cells[13].text) def balls(row): cells = row.find('td') return (int_or_default(cells[14].text), int_or_default(cells[15].text)) def fauls(row): cells = row.find('td') return (int_or_default(cells[17].text), int_or_default(cells[18].text)) def value(row): cells = row.find('td') return int_or_default(cells[20].text) def points(row): cells = row.find('td') return int_or_default(cells[21].text) def int_or_default(val): try: return int(val) except ValueError as _: return -111
Python
UTF-8
716
2.640625
3
[]
no_license
# coding=utf-8 """Classe des code de chaque entités""" import re class Code: def __init__(self,car,s1): s=string (s1) self.code=car + s class CodeFranchise: n=1 char="F" def __init__(self): Code.__init__(self,char,n) n=n+1 class CodeReservation: n=1 char="R" def __init__(self): Code.__init__(self,char,n) n=n+1 class CodeVol: n=1 char="V" def __init__(self): Code.__init__(self,char,n) n=n+1 class CodePassager: n=1 char="P" def __init__(self): Code.__init__(self,char,n) n=n+1 class CodeClient: n=1 char="C" def __init__(self): Code.__init__(self,char,n) n=n+1 class CodeAeroport: n=1 char="A" def __init__(self): Code.__init__(self,char,n) n=n+1
Java
UTF-8
2,220
1.804688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.shell.samples.e2e; import org.springframework.context.annotation.Bean; import org.springframework.shell.command.CommandRegistration; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import org.springframework.shell.standard.ShellOption; import org.springframework.stereotype.Component; public class OptionNamingCommands { @ShellComponent public static class OptionNamingCommandsLegacyAnnotation extends BaseE2ECommands { @ShellMethod(key = LEGACY_ANNO + "option-naming-1", group = GROUP) public void testOptionNaming1Annotation( @ShellOption("from_snake") String snake, @ShellOption("fromCamel") String camel, @ShellOption("from-kebab") String kebab, @ShellOption("FromPascal") String pascal ) { } } @Component public static class OptionNamingCommandsRegistration extends BaseE2ECommands { @Bean public CommandRegistration testOptionNaming1Registration(CommandRegistration.BuilderSupplier builder) { return builder.get() .command(REG, "option-naming-1") .group(GROUP) .withOption() .longNames("from_snake") .required() .and() .withOption() .longNames("fromCamel") .required() .and() .withOption() .longNames("from-kebab") .required() .and() .withOption() .longNames("FromPascal") .required() .and() .withOption() .longNames("arg1") .nameModifier(name -> "x" + name) .required() .and() .withTarget() .consumer(ctx -> {}) .and() .build(); } } }
Python
UTF-8
3,136
2.71875
3
[ "MIT" ]
permissive
#!/usr/bin/env python ''' Written by Andreas Hellesnes, Norwegian Naval Academy 2019 Behaviour.py This is the main program behaviour, it gets data from ROS with swarmData and Subscriber then calculates new movement from behave class finally publishes to ROS with talker Questions: anhellesnes@fhs.mil.no ''' import time import rospy from Behaviour_caller import Behave from ROS_operators.Boat_ID import get_ID from ROS_operators.Global_data import swarmData from ROS_operators.Behaviour_sub import Subscriber, NewCommand from ROS_operators.Behaviour_talker import Talker def main(): wait_time = 0.0 BOAT_ID = get_ID() #initialise objects for loop data = swarmData() command = Subscriber() fence = command.get_static_fence() behaviour_out = Talker() rospy.loginfo("INITIALIZING BEHAVIOUR") rospy.loginfo("Waiting for data...") while not data.has_recieved(): #waits to recieve data wait_time += 0.1 time.sleep(0.1) if wait_time in (10.0, 20.0, 30.0, 40.0): rospy.loginfo("Time waited: {}".format(wait_time)) elif wait_time > 60.0: rospy.loginfo("No data recieved in 60 seconds, behaviour timed out") rospy.signal_shutdown('Behaviour timed out') rospy.loginfo("Data recieved after time: {}, starting".format(wait_time)) behaviour = Behave(BOAT_ID, fence, use_behaviour=0) # BOIDS, PSO while not rospy.is_shutdown(): try: command() time.sleep(0.5) #get newest table of data from units in swarm data_full = data() #calculate wanted vector based on current behaviour wanted = behaviour(data_full) #publish wanted vector to autopilot behaviour_out(wanted) except NewCommand: if command.stop() == True: rospy.signal_shutdown('stop command recieved') else: colav = command.get_colavMode() if colav == 1: #new behaviour order new_behaviour = command.get_taskType() try: rospy.loginfo("Initiating new behaviour...") del behaviour behaviour = Behave(BOAT_ID, fence, new_behaviour) except AttributeError as e: rospy.loginfo("could not initiate new behaviour, with error: {} ", format(e)) if colav == 2: #new fence print("trying to set new fence") new_fence = command.get_fence() behaviour.change_fence(new_fence) if colav == 3: #new destination print("trying to set new dest") destination = command.get_wantedPos() behaviour.set_destination(destination) if colav == 4: #new wanted movement pass #not in use for any beahviour pr now except rospy.ROSInterruptException(): pass if __name__=="__main__": main()
Java
UTF-8
296
2.640625
3
[]
no_license
package com.project.ci360; public class Day { private String dayID; private String dayName; public Day(String id, String dayName){ this.dayID = id; this.dayName = dayName; } public String getDayID() { return dayID; } public String getDayName() { return dayName; } }
JavaScript
UTF-8
1,343
2.984375
3
[ "MIT" ]
permissive
/** * Created by MW Toolbox on 10/05/2017. */ function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 3, center: {lat: -28.024, lng: 140.887} }); // Create an array of alphabetical characters used to label the markers. // Add some markers to the map. // Note: The code uses the JavaScript Array.prototype.map() method to // create an array of markers based on a given "locations" array. // The map() method here has nothing to do with the Google Maps API. var markers = locations.map(function(location,i) { return new google.maps.Marker({ position: location, label: labels[i] }); }); // Add a marker clusterer to manage the markers. var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'}); } var locations = [ {lat: -27.561367, lng: 153.026849}, {lat: -27.558921, lng: 153.021109}, {lat:-27.433083,lng:153.042839}, {lat:-27.370172,lng:153.063247}, {lat:-27.930555,lng:153.378857}, {lat:-19.274277,lng:146.767386}, {lat:-23.345288,lng:150.521081} ]; var labels =["Factory Center","Coopers Plains", "Albion", "Virginia","Gold Coast", "Townsville", "Rockhampton"]
Rust
UTF-8
16,848
2.90625
3
[ "MIT" ]
permissive
//! //! MOS 6502 Instruction set //! use std::fmt; use addr::Address; use mem::Addressable; use super::{Mos6502, Operand, IRQ_VECTOR}; use super::{CarryFlag, ZeroFlag, InterruptDisableFlag, DecimalFlag}; use super::{BreakFlag, UnusedAlwaysOnFlag, NegativeFlag, OverflowFlag}; /// Processor instructions #[derive(Debug, PartialEq, Eq)] pub enum Instruction { // Load/store operations LDA, LDX, LDY, STA, STX, STY, // Register transfers TAX, TAY, TXA, TYA, // Stack operations TSX, TXS, PHA, PHP, PLA, PLP, // Logical AND, EOR, ORA, BIT, // Arithmetic ADC, SBC, CMP, CPX, CPY, // Increments & decrements INC, INX, INY, DEC, DEX, DEY, // Shifts ASL, LSR, ROL, ROR, // Jump & calls JMP, JSR, RTS, // Branches BCC, BCS, BEQ, BMI, BNE, BPL, BVC, BVS, // Status flag changes CLC, CLD, CLI, CLV, SEC, SED, SEI, // System functions BRK, NOP, RTI, } impl Instruction { /// Execute an instruction using the given environment pub fn execute<M: Addressable> (&self, cpu: &mut Mos6502<M>, operand: &Operand) { match *self { // Load/store operations Instruction::LDA => { // load accumulator [N,Z] let value = operand.get(cpu); cpu.ac = value; cpu.set_zn(value); }, Instruction::LDX => { // load X register [N,Z] let value = operand.get(cpu); cpu.x = value; cpu.set_zn(value); }, Instruction::LDY => { // load Y register [N,Z] let value = operand.get(cpu); cpu.y = value; cpu.set_zn(value); }, Instruction::STA => { // store accumulator let value = cpu.ac; operand.set(cpu, value); }, Instruction::STX => { // store X register let value = cpu.x; operand.set(cpu, value); }, Instruction::STY => { // store Y register let value = cpu.y; operand.set(cpu, value); }, // Register transfers Instruction::TAX => { // transfer accumulator to X [N,Z] let value = cpu.ac; cpu.x = value; cpu.set_zn(value); }, Instruction::TAY => { // transfer accumulator to Y [N,Z] let value = cpu.ac; cpu.y = value; cpu.set_zn(value); }, Instruction::TXA => { // transfer X to accumulator [N,Z] let value = cpu.x; cpu.ac = value; cpu.set_zn(value); }, Instruction::TYA => { // transfer Y to accumulator [N,Z] let value = cpu.y; cpu.ac = value; cpu.set_zn(value); }, // Stack operations Instruction::TSX => { // transfer stack pointer to X [N,Z] let value = cpu.sp; cpu.x = value; cpu.set_zn(value); }, Instruction::TXS => { // transfer X to stack pointer cpu.sp = cpu.x; }, Instruction::PHA => { // push accumulator on stack let value = cpu.ac; cpu.push(value); }, Instruction::PHP => { // push processor status (SR) on stack let value = cpu.sr.bits; cpu.push(value); }, Instruction::PLA => { // pull accumulator from stack [N,Z] let value = cpu.pop(); cpu.ac = value; cpu.set_zn(value); }, Instruction::PLP => { // pull processor status (SR) from stack [all] cpu.sr.bits = cpu.pop(); cpu.sr.insert(UnusedAlwaysOnFlag); }, // Logical Instruction::AND => { // logical AND [N,Z] let result = cpu.ac & operand.get(cpu); cpu.ac = result; cpu.set_zn(result); }, Instruction::EOR => { // logical exclusive OR [N,Z] let result = cpu.ac ^ operand.get(cpu); cpu.ac = result; cpu.set_zn(result); }, Instruction::ORA => { // logical inclusive OR [N,Z] let result = cpu.ac | operand.get(cpu); cpu.ac = result; cpu.set_zn(result); }, Instruction::BIT => { // bit test [N,V,Z] let value = operand.get(cpu); cpu.sr.set(ZeroFlag, (value & cpu.ac) == 0); cpu.sr.set(NegativeFlag, (value & 0x80) != 0); cpu.sr.set(OverflowFlag, (value & 0x40) != 0); }, // Arithmetic Instruction::ADC => { // add with carry [N,V,Z,C] if cpu.sr.contains(DecimalFlag) { panic!("mos6502: Decimal mode ADC not supported yet :("); } let value = operand.get(cpu); let mut result = (cpu.ac as u16).wrapping_add(value as u16); if cpu.sr.contains(CarryFlag) { result = result.wrapping_add(1); } cpu.sr.set(CarryFlag, (result & 0x100) != 0); let result = result as u8; cpu.sr.set(OverflowFlag, (cpu.ac ^ value) & 0x80 == 0 && (cpu.ac ^ result) & 0x80 == 0x80); cpu.ac = result; cpu.set_zn(result); }, Instruction::SBC => { // subtract with carry [N,V,Z,C] if cpu.sr.contains(DecimalFlag) { panic!("mos6502: Decimal mode ADC not supported yet :("); } let value = operand.get(cpu); let mut result = (cpu.ac as u16).wrapping_sub(value as u16); if !cpu.sr.contains(CarryFlag) { result = result.wrapping_sub(1); } cpu.sr.set(CarryFlag, (result & 0x100) == 0); let result = result as u8; cpu.sr.set(OverflowFlag, (cpu.ac ^ result) & 0x80 != 0 && (cpu.ac ^ value) & 0x80 == 0x80); cpu.ac = result; cpu.set_zn(result); }, Instruction::CMP => { // compare (with accumulator) [N,Z,C] let result = cpu.ac as i16 - operand.get(cpu) as i16; cpu.sr.set(CarryFlag, result >= 0); cpu.set_zn(result as u8); }, Instruction::CPX => { // compare with X register [N,Z,C] let result = cpu.x as i16 - operand.get(cpu) as i16; cpu.sr.set(CarryFlag, result >= 0); cpu.set_zn(result as u8); }, Instruction::CPY => { // compare with Y register [N,Z,C] let result = cpu.y as i16 - operand.get(cpu) as i16; cpu.sr.set(CarryFlag, result >= 0); cpu.set_zn(result as u8); }, // Increments & decrements Instruction::INC => { // increment a memory location [N,Z] let value = operand.get(cpu).wrapping_add(1); operand.set(cpu, value); cpu.set_zn(value); }, Instruction::INX => { // increment X register [N,Z] let value = cpu.x.wrapping_add(1); cpu.x = value; cpu.set_zn(value); }, Instruction::INY => { // increment Y register [N,Z] let value = cpu.y.wrapping_add(1); cpu.y = value; cpu.set_zn(value); }, Instruction::DEC => { // decrement a memory location [N,Z] let value = operand.get(cpu).wrapping_sub(1); operand.set(cpu, value); cpu.set_zn(value); }, Instruction::DEX => { // decrement X register [N,Z] let value = cpu.x.wrapping_sub(1); cpu.x = value; cpu.set_zn(value); }, Instruction::DEY => { // decrement Y register [N,Z] let value = cpu.y.wrapping_sub(1); cpu.y = value; cpu.set_zn(value); }, // Shifts Instruction::ASL => { // arithmetic shift left [N,Z,C] let value = operand.get(cpu); cpu.sr.set(CarryFlag, (value & 0x80) != 0); let result = value << 1; operand.set(cpu, result); cpu.set_zn(result); }, Instruction::LSR => { // logical shift right [N,Z,C] let value = operand.get(cpu); cpu.sr.set(CarryFlag, (value & 0x01) != 0); let result = value >> 1; operand.set(cpu, result); cpu.set_zn(result); }, Instruction::ROL => { // rotate left [N,Z,C] let carry = cpu.sr.contains(CarryFlag); let value = operand.get(cpu); cpu.sr.set(CarryFlag, (value & 0x80) != 0); let mut result = value << 1; if carry { result |= 0x01 } operand.set(cpu, result); cpu.set_zn(result); }, Instruction::ROR => { // rotate right [N,Z,C] let carry = cpu.sr.contains(CarryFlag); let value = operand.get(cpu); cpu.sr.set(CarryFlag, (value & 0x01) != 0); let mut result = value >> 1; if carry { result |= 0x80 } operand.set(cpu, result); cpu.set_zn(result); }, // Jump & calls Instruction::JMP => { // jump to another location cpu.pc = operand.addr(cpu); }, Instruction::JSR => { // jump to a subroutine // Push the address of the last byte of this instruction to the // stack instead of the address of the next instruction. let pc = cpu.pc; cpu.push(pc - 1); cpu.pc = operand.addr(cpu); }, Instruction::RTS => { // return from subroutine cpu.pc = cpu.pop(); // Need to advance the PC by 1 to step to the next instruction cpu.pc += 1; }, // Branches Instruction::BCC => { // branch if carry flag clear if !cpu.sr.contains(CarryFlag) { cpu.pc = operand.addr(cpu); } }, Instruction::BCS => { // branch if carry flag set if cpu.sr.contains(CarryFlag) { cpu.pc = operand.addr(cpu); } }, Instruction::BEQ => { // branch if zero flag set if cpu.sr.contains(ZeroFlag) { cpu.pc = operand.addr(cpu); } }, Instruction::BMI => { // branch if negative flag set if cpu.sr.contains(NegativeFlag) { cpu.pc = operand.addr(cpu); } }, Instruction::BNE => { // branch if zero flag clear if !cpu.sr.contains(ZeroFlag) { cpu.pc = operand.addr(cpu); } }, Instruction::BPL => { // branch if negative flag clear if !cpu.sr.contains(NegativeFlag) { cpu.pc = operand.addr(cpu); } }, Instruction::BVC => { // branch if overflow flag clear if !cpu.sr.contains(OverflowFlag) { cpu.pc = operand.addr(cpu); } }, Instruction::BVS => { // branch if overflow flag set if cpu.sr.contains(OverflowFlag) { cpu.pc = operand.addr(cpu); } }, // Status flag changes Instruction::CLC => { // clear carry flag [C] cpu.sr.remove(CarryFlag); }, Instruction::CLD => { // clear decimal mode flag [D] cpu.sr.remove(DecimalFlag); }, Instruction::CLI => { // clear interrupt disable flag [I] cpu.sr.remove(InterruptDisableFlag); }, Instruction::CLV => { // clear overflow flag [V] cpu.sr.remove(OverflowFlag); }, Instruction::SEC => { // set carry flag [C] cpu.sr.insert(CarryFlag); }, Instruction::SED => { // set decimal mode flag [D] cpu.sr.insert(DecimalFlag); }, Instruction::SEI => { // set interrupt disable flag [I] cpu.sr.insert(InterruptDisableFlag); }, // System functions Instruction::BRK => { // force an interrupt [B] // An IRQ does the same, but clears BreakFlag (before pushing SR). cpu.sr.insert(BreakFlag); // Unlike JSR, interrupts push the address of the next // instruction to the stack. The next byte after BRK is // skipped. It can be used to pass information to the // interrupt handler. let pc = cpu.pc; cpu.push(pc + 1); let sr = cpu.sr.bits; cpu.push(sr); cpu.sr.insert(InterruptDisableFlag); cpu.pc = cpu.mem.get_le(IRQ_VECTOR); debug!("mos6502: BRK - Jumping to ({}) -> {}", IRQ_VECTOR.display(), cpu.pc.display()); }, Instruction::NOP => { // no operation }, Instruction::RTI => { // return from interrupt [all] cpu.sr.bits = cpu.pop(); cpu.pc = cpu.pop(); // Unlike RTS, do not advance the PC since it already points to // the next instruction }, } } } impl fmt::Display for Instruction { fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Instruction::LDA => "LDA", Instruction::LDX => "LDX", Instruction::LDY => "LDY", Instruction::STA => "STA", Instruction::STX => "STX", Instruction::STY => "STY", Instruction::TAX => "TAX", Instruction::TAY => "TAY", Instruction::TXA => "TXA", Instruction::TYA => "TYA", Instruction::TSX => "TSX", Instruction::TXS => "TXS", Instruction::PHA => "PHA", Instruction::PHP => "PHP", Instruction::PLA => "PLA", Instruction::PLP => "PLP", Instruction::AND => "AND", Instruction::EOR => "EOR", Instruction::ORA => "ORA", Instruction::BIT => "BIT", Instruction::ADC => "ADC", Instruction::SBC => "SBC", Instruction::CMP => "CMP", Instruction::CPX => "CPX", Instruction::CPY => "CPY", Instruction::INC => "INC", Instruction::INX => "INX", Instruction::INY => "INY", Instruction::DEC => "DEC", Instruction::DEX => "DEX", Instruction::DEY => "DEY", Instruction::ASL => "ASL", Instruction::LSR => "LSR", Instruction::ROL => "ROL", Instruction::ROR => "ROR", Instruction::JMP => "JMP", Instruction::JSR => "JSR", Instruction::RTS => "RTS", Instruction::BCC => "BCC", Instruction::BCS => "BCS", Instruction::BEQ => "BEQ", Instruction::BMI => "BMI", Instruction::BNE => "BNE", Instruction::BPL => "BPL", Instruction::BVC => "BVC", Instruction::BVS => "BVS", Instruction::CLC => "CLC", Instruction::CLD => "CLD", Instruction::CLI => "CLI", Instruction::CLV => "CLV", Instruction::SEC => "SEC", Instruction::SED => "SED", Instruction::SEI => "SEI", Instruction::BRK => "BRK", Instruction::NOP => "NOP", Instruction::RTI => "RTI", }) } }
JavaScript
UTF-8
2,841
3.78125
4
[]
no_license
const baseURL = 'https://ghibliapi.herokuapp.com'; //no key needed let url; //add the /people to grab the people and films endpoints //Button const submitButton = document.querySelector('.submitButton'); const section = document.querySelector('section'); section.style.display = 'none'; //eventListener submitButton.addEventListener('click', fetchPeople); function fetchPeople(e) { e.preventDefault(); url = baseURL + '/people'; // fetchFilms returns an object, need to grab the .people and feed that into fetchPeople() fetch(url) .then(function(result){ return result.json(); }) .then(function(json){ console.log(json); let randomNumber = Math.round((Math.random()*42)); //0-42 console.log(json[randomNumber]); //grabs people endpoint displayResults(json[randomNumber]); //grabs a random person from the people endpoint }) } function displayResults(json) { while (section.firstChild) { section.removeChild(section.firstChild); } section.style.display = 'block'; let name = document.createElement('h2'); let film = document.createElement('p'); let age = document.createElement('p'); let species = document.createElement('p'); let gender = document.createElement('p'); let eyeColor = document.createElement('p'); /* need to populate a p tag */ if (json.name) { name.textContent = json.name; } else { name.textContent = 'No Name'; } if (json.eye_color) { eyeColor.textContent = `Eye color: ${json.eye_color}`; } else { eyeColor.textContent = `Eye color: None`; } if (json.age) { age.textContent = `Age: ${json.age}`; } else { age.textContent = `Age: Unknown`; } if (json.gender) { gender.textContent = `Gender: ${json.gender}`; } else { gender.textContent = `Gender: Not applicable`; } fetch(json.species) //because the json.species is a URL, need this promise .then(function(result){ return result.json(); }) .then(function(json){ console.log(json.name); species.textContent = `Species: ${json.name}` }) fetch(json.films) .then(function(result){ return result.json(); }) .then(function(json){ if (json.title){ console.log(json.title); film.textContent = `Film: ${json.title}`; } else { film.textContent =`Film: Multiple Films` } }) section.appendChild(name); section.appendChild(age); section.appendChild(gender); section.appendChild(eyeColor); section.appendChild(species); section.appendChild(film); }
Java
UTF-8
2,248
2.1875
2
[]
no_license
package com.zzwl.ias.mapper; import com.zzwl.ias.domain.MessageSysRecord; import org.apache.ibatis.jdbc.SQL; public class MessageSysRecordSqlProvider { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table message_sys * * @mbg.generated */ public String insertSelective(MessageSysRecord record) { SQL sql = new SQL(); sql.INSERT_INTO("message_sys"); if (record.getId() != null) { sql.VALUES("id", "#{id,jdbcType=INTEGER}"); } if (record.getTitle() != null) { sql.VALUES("title", "#{title,jdbcType=VARCHAR}"); } if (record.getType() != null) { sql.VALUES("type", "#{type,jdbcType=TINYINT}"); } if (record.getContent() != null) { sql.VALUES("content", "#{content,jdbcType=VARCHAR}"); } if (record.getUrl() != null) { sql.VALUES("url", "#{url,jdbcType=VARCHAR}"); } if (record.getCreateTime() != null) { sql.VALUES("create_time", "#{createTime,jdbcType=TIMESTAMP}"); } return sql.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table message_sys * * @mbg.generated */ public String updateByPrimaryKeySelective(MessageSysRecord record) { SQL sql = new SQL(); sql.UPDATE("message_sys"); if (record.getTitle() != null) { sql.SET("title = #{title,jdbcType=VARCHAR}"); } if (record.getType() != null) { sql.SET("type = #{type,jdbcType=TINYINT}"); } if (record.getContent() != null) { sql.SET("content = #{content,jdbcType=VARCHAR}"); } if (record.getUrl() != null) { sql.SET("url = #{url,jdbcType=VARCHAR}"); } if (record.getCreateTime() != null) { sql.SET("create_time = #{createTime,jdbcType=TIMESTAMP}"); } sql.WHERE("id = #{id,jdbcType=INTEGER}"); return sql.toString(); } }
C++
UTF-8
1,837
3.03125
3
[]
no_license
#ifndef LOST_IN_SPACE_ #define LOST_IN_SPACE_ #include "splashkit.h" #include "player.h" #include "power_up.h" #include <vector> using namespace std; using std::vector; struct game_data { player_data player; vector<power_up_data> power_ups; }; /** * Creates a new game * * @returns The new game data **/ game_data new_game(); /** * Draws the game to the screen. * * @param game_draw The player to draw to the screen */ void draw_game(const game_data &game_draw); /** * Actions a step update of the game. * * @param game_to_update The game being updated */ void update_game(game_data &game_to_update); /** * Add a power up to the game. * * @param game The game to which power up is to be added */ void add_power_up(game_data &game); /** * Apply the feature of the power up to the player after collision * * @param game The game * @param powerup_kind Power up which has to applied */ void apply_power_up(game_data &game, power_up_data &power_up); /** * Removes the a specific power up from the power ups vector * * @param power_ups vector of all the power ups * @param index Index of the power up which has to be removed */ void remove_power_up(vector<power_up_data> &power_ups, int i); /** * Checks the collision between player's ship and power up * * @param game The game for which collision has to checked */ void check_collision(game_data &game); /** * Draws the heads up display for the game * * @param g The game for which heads up display is to be drawn */ void draw_hud(const game_data &g); /** * Draws the Mini Map of all power ups inside Heads Up Display * * @param game The vector of all power ups for which for which mini map has to be created */ void draw_mini_map(const vector<power_up_data> &power_ups); #endif
Markdown
UTF-8
8,676
2.921875
3
[]
no_license
### 1、技术选型以及理由 - 微信小程序框架 我们选择了微信小程序开发框架作为用户点餐系统的前端框架。小程序框架提供了自己的视图层描述语言 WXML 和 WXSS, 以及基于 JavaScript 的逻辑层框架,容易上手,并在视图层与逻辑层间提供了数据传输和事件系统,支持响应式、双向数据绑定等特性, 可以让数据与视图非常简单地保持同步:当做数据修改的时候,只需要在逻辑层修改数据,视图层就会做相应的更新, 因而能够很好地支持丰富的用户交互体验支持,可以让开发者方便的聚焦于数据与逻辑上; 框架还管理了整个小程序的页面路由,可以做到页面间的无缝切换,并给以页面完整的生命周期, 开发者需要做的只是将页面的数据,方法,生命周期函数注册进框架中,其他的一切复杂的操作都交由框架处理; 此外,框架还提供了微信风格的组件和丰富的api,实现了尽量以简单、高效的方式让开发者可以在微信中开发具有原生 APP 体验的服务。 且4g网络和移动支付的普及推动了微信小程序作为点餐系统的应用发展, 使用微信小程序作为点餐系统对用户更加快捷和便利,因此选择微信小程序作为前端框架对用户和开发者都十分友好。 ### 2、架构设计 - MINA框架 微信团队为小程序提供的框架命名为MINA应用框架,MINA框架让开发者能够非常方便地使用微信客户端提供的各种基础功能与能力,快速构建一个应用。 在页面视图层,MINA的wxml是一套类似html标签的语言以及一系列基础组件。开发者使用wxml文件来搭建页面的基础视图结构,使用wxss文件来控制页面的展现样式。AppService应用逻辑层是MINA的服务中心,由微信客户端页面视图层外启用异步线程单独加载运行,MINA 中所有使用 javascript 编写的交互逻辑、网络请求、数据处理都必须在 AppService 中实现,但AppService中不能使用DOM操作相关的脚本代码。小程序中的各个页面可以通过AppService实现数据管理、网络通信、应用生命周期管理和页面路由管理。 MINA框架还为页面组件提供了bindtap、bindtouchstart等事件监听相关的属性,来与AppService中的事件处理函数绑定在一起,实现面向AppService层同步用户交互数据。MINA框架的核心是一个响应的数据绑定系统,提供了很多方法将AppService中的数据与页面进行单向绑定,让数据与视图非常简单地保持同步,当AppService中的数据变更时,会主动触发对应页面组件的重新渲染。MINA使用virtualdom技术,加快了页面的渲染效率。 MINA程序包含一个描述整体程序的app和多个描述各自页面的page,一个MINA程序主体部分由三个文件组成,必须放在项目的根目录,如下: 文件 | 作用 | ------- |------- | app.js | 小程序逻辑 | app.json | 小程序公共设置| app.wxss | 小程序公共样式表| 一个MINA页面由四个文件组成,分别是: 文件 | 作用 | ------- |------- | js | 页面逻辑 | json | 页面配置 | wxss | 页面样式表| wxml | 页面结构 | MINA框架图如下: ![小程序框架图](http://wx3.sinaimg.cn/mw690/85eb32d8gy1fsx1xhq7dhj20n30irmxr.jpg) ### 3、模块划分 - 微信小程序用户点餐系统前端 根据业务逻辑和UI设计图,将用户点餐系统前端分为5个页面,按照小程序开发要求的文件结构,每个页面内包含js文件、json文件、wxml文件和wxss文件,分别处理逻辑、配置、结构和样式;根据页面的划分,得到页面模块的细分: 五个页面模块包括: - 授权登录,获取用户的信息 - 主菜单,用户浏览上架菜品以及点餐 - 今日推荐, 商家推出的推荐菜单,每个菜单内有不同菜式 - 今日推荐卡片细节,推荐菜单内的菜式介绍 - 购物车,修改购物车内容以及下单和支付 此外还定义了三个复杂的组件,构成组件模块。 三个组件包括: - 今日推荐的卡片,封装了卡片的样式结构以及交互事件 - 滑动框,自动滑动图片,使页面更美观 - 订单item,封装订单和购物车条目的样式结构以及交互事件 加上小程序的全局文件,包括逻辑文件,配置文件,样式文件,构成app模块; 还有资源文件,包括图片,构成资源模块; 最后还有小程序的工具配置模块,和公共代码模块,各个模块关系如下: ![模块](http://wx3.sinaimg.cn/mw690/85eb32d8gy1fsx5ewujcjj20mt0g2zkk.jpg) 最后项目的结构如下: ```txt ├── project.config.json //开发工具配置 ├── app.js //小程序的全局逻辑文件 ├── app.json //小程序的全局配置 ├── app.wxss //小程序的全局样式 ├── images //小程序利用到的图片 | ├── pages //小程序的页面文件存放文件夹 | ├── authorize // 授权登录页面 │ │ ├── authorize.js //授权登录页面的逻辑文件 | | ├── authorize.json //授权登录页面配置文件 │ │ ├── authorize.wxml // 授权登录页面的结构文件 │ │ └── authorize.wxss // 授权登录页面的样式文件 | | │ ├── index //主菜单页面 │ │ ├── index.js //主菜单页面的逻辑文件 | | ├── index.json //主菜单页面配置文件 │ │ ├── index.wxml // 主菜单页面的结构文件 │ │ └── index.wxss // 主菜单页面的样式文件 | | │ ├── recommendation //今日推荐页面 │ | ├── recommendation.js //今日推荐页面的逻辑文件 │ | ├── recommendation.json //今日推荐页面配置文件 │ | ├── recommendation.wxml //今日推荐页面的结构文件 │ | └── recommendation.wxss //今日推荐页面的样式文件 | | │ ├── recommendation-details //今日推荐卡片细节页面 │ | ├── recommendation-details.js //今日推荐卡片细节页面的逻辑文件 │ | ├── recommendation-details.json //今日推荐卡片细节页面配置文件 │ | ├── recommendation-details.wxml //今日推荐卡片细节页面的结构文件 │ | └── recommendation-details.wxss //今日推荐卡片细节页面的样式文件 | | │ ├── cart //购物车页面 │ | ├── cart.js //购物车页面的逻辑文件 │ | ├── cart.json //购物车页面配置文件 │ | ├── cart.wxml //购物车页面的结构文件 │ └── └── cart.wxss //购物车页面的样式文件 | ├── component //自定义组件 │ ├── card //今日推荐卡片组件 │ | ├── card.js //今日推荐卡片组件的逻辑文件 │ | ├── card.json //今日推荐卡片组件的配置文件 │ | ├── card.wxml //今日推荐卡片组件的结构文件 │ | └── card.wxss //今日推荐卡片组件的样式文件 | | | ├── hSwiper //滑动框组件 │ | ├── hSwiper.js //滑动框组件的逻辑文件 │ | ├── hSwiper.json //滑动框组件的配置文件 │ | ├── hSwiper.wxml //滑动框组件的结构文件 │ | └── hSwiper.wxss //今日推荐卡片组件的样式文件 | | | └── orderItem //购物车or订单item组件 │ | ├── orderItem.js //订单item的逻辑文件 │ | ├── orderItem.json //订单item的配置文件 │ | ├── orderItem.wxml //订单item组件的结构文件 │ └── └── orderItem.wxss //订单item组件的样式文件 | └── utils //公共的js代码 └── util.js ``` ### 4、软件设计技术 - MVVM设计模式 MVVM的全称为Model-View-ViewModel,M表示Model,V表示视图View,VM表示数据与模型,当前端View变化时,由于View与VM进行了绑定,VM又与M进行交互,从而使M得到了改变;当M发生变化时,小程序检测到变化并通知VM,由于VM和V进行了绑定,因此V得到改变。 小程序的框架MINA内的设计思想就包含了MVVM,因此小程序内页面和组件模块都自动采用了MVVM设计模式。
PHP
UTF-8
1,517
2.640625
3
[]
no_license
<!-- 03 LEARN --> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="bootstrap.min.css"> <meta charset="UTF-8"> <title>View From Database</title> </head> <body> <div class="container"> <table class="table table-light table-striped border"> <thead class="thead-light text-center">View from Database</thead> <tbody> <tr> <th>ID</th> <th>Employee Name</th> <th>SSN</th> <th>Department</th> <th>Salary</th> <th>Home Address</th> <th>Update</th> <th>Delete</th> </tr> <?php $connection = mysqli_connect('localhost', 'root', '', 'record'); $viewQuery = "SELECT * FROM emp_record"; $execute = mysqli_query($connection, $viewQuery); while ($dataRows = mysqli_fetch_array($execute)){ $ID = $dataRows['id']; $eName = $dataRows['enam']; $SSN = $dataRows['ssn']; $Dept = $dataRows['dept']; $Salary = $dataRows['salary']; $homeAdd = $dataRows['homeaddress']; ?> <tr> <td><?php echo $ID; ?></td> <td><?php echo $eName; ?></td> <td><?php echo $SSN; ?></td> <td><?php echo $Dept; ?></td> <td><?php echo $Salary; ?></td> <td><?php echo $homeAdd; ?></td> <td>Update</td> <td>Delete</td> </tr> </tbody> <?php } ?> </table> </div> </body> </html>
JavaScript
UTF-8
845
3.90625
4
[ "MIT", "ISC" ]
permissive
/** * Eg one */ const { resolve } = require("core-js/es6/promise"); const { reject } = require("core-js/fn/promise"); function doAsyncWork(resolve, reject) { //perform async calls if (success) { resolve(data) } else { reject("Rejected") } } let myPromise = new Promise(doAsyncWork) /** * Eg two */ let myPromise = new Promise((resolve, reject) => { //perform async calls if (success) { resolve(data) } else { reject("Rejected") } }) /** * How to process the result of a promise * will call afunction that returns a promise object */ MethodThatReturnsPromise() .then(data => console.log(data)) //called when promise is resolved .catch(err => console.log(err)) //called when promise is rejected .finally(() => console.log("All done!")) //called in both cases
Java
UTF-8
1,850
3.921875
4
[]
no_license
package com.etc.structure.stack; /** * @Author:zrd * @Description: * @Date:2018-8-19 17:44 * 队列 底层也是 数组 特点是 先进先出 , 跟在火车站买票情景相似 */ public class MyQueue { private long[] arry; //有效数据大小 private int elements; //对头 private int front; //对尾 private int end ; public MyQueue(){ arry = new long[10]; elements = 0 ; front = 0; end = -1 ; } //带参数的构造方法 public MyQueue(int maxSize){ arry = new long[maxSize]; elements = 0 ; front = 0; end = -1 ; } //添加数据 ,从队尾添加数据 public void insert(long value){ arry[++end] = value ; elements++; } //删除数据 从对头删除数据 public long remove(){ elements--; return arry[front++]; } //查看数据 ,从对头查看 public long peek(){ return arry[front]; } //判断是否为空 public boolean isEmpty(){ return elements == 0; } /** * 判断是否满了 */ public boolean isFull() { return elements == arry.length; } public static void main(String[] args) { MyQueue myQueue = new MyQueue(4); myQueue.insert(2); myQueue.insert(8); myQueue.insert(1); myQueue.insert(200); System.out.println("查看队列的头数据"+ myQueue.peek()); System.out.println("查看队列的头数据"+ myQueue.peek()); System.out.println("查看队列的数据是否为空"+ myQueue.isEmpty()); while(!myQueue.isEmpty()){ System.out.print(myQueue.remove()+" "); } myQueue.insert(62); //这一行就会报错 由于没有 重置对头和队尾导致的问题 } }
PHP
UTF-8
2,104
3.40625
3
[]
no_license
<?php // Lege variabelen $name = ""; $email = ""; $nameError = ""; $emailError = ""; if ($_SERVER["REQUEST_METHOD"] == "POST"){ if(empty($_POST["name"])){ $nameError = "Name is required"; } else { $name = test_input($_POST["name"]); } if(empty($_POST["email"])){ $emailError = "Email is required"; } else { $email = test_input($_POST["email"]); } } // test_input is een functie die voor je de code checkt op speciale tekens function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <title>Form</title> </head> <body> <h1>Form</h1> <div class="block"> <div class="inputs"> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <!-- htmlspecialchars function zorgt ervoor dat special characters omgezet worden naar HTML entities. $_SERVER["PHP_SELF"] is een super global variable --> <label>Name:</label> <input type="text" id="name" name="name" value="<?php echo $name ?>"> <span class="error">* <?php echo $nameError;?></span> <br> <label>Email:</label> <input type="email" id="email" name="email" placeholder="@" value="<?php echo $email ?>"> <span class="error">* <?php echo $emailError;?></span> <br> <input type="submit" id="submit" name="submit" value="Submit"> </form> </div> </div> <div class="input"> <h2>Je gegevens:</h2> <?php if($nameError || $emailError == true){ ""; } else{ echo $name; echo "<br>"; echo $email; } ?> </div> </body> </html>
C#
UTF-8
1,933
2.859375
3
[]
no_license
using Data_Access_Layer.models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace CASM.Controllers { public class PilotApiController : ApiController { CasmContext db = new CasmContext(); // GET api/pilotapi public IEnumerable<PilotsDetail> Get() { //var names = from o in db.PassengersDetails select o.FirstName; //foreach (var o in names) //{ // Console.WriteLine(o); //} return db.PilotsDetails; } // GET api/pilotapi/5 public PilotsDetail Get(int id) { return db.PilotsDetails.Find(id); } // POST api/pilotapi public void Post(PilotsDetail pilots) { db.PilotsDetails.Add(pilots); db.SaveChanges(); } // PUT api/pilotapi/5 public HttpResponseMessage Put(PilotsDetail pilot) { if (ModelState.IsValid) { db.Entry(pilot).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, pilot); return response; } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } } // DELETE api/pilotapi/5 public HttpResponseMessage Delete(int id) { PilotsDetail pilot = db.PilotsDetails.Find(id); if (pilot == null) { return Request.CreateResponse(HttpStatusCode.NotFound); } db.PilotsDetails.Remove(pilot); db.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK, pilot); } } }
Shell
UTF-8
269
2.796875
3
[ "PHP-3.01" ]
permissive
#!/bin/sh extdir=`php -r "echo ini_get('extension_dir');" 2> /dev/null` if [ ! -d "$extdir" ] ; then mkdir "$extdir" fi cp modules/qb.so "$extdir/qb.so" inidir="/etc/php5/mods-available" if [ ! -f $inidir/qb.ini ] ; then cp qb.ini $inidir/qb.ini fi php5enmod qb
Python
UTF-8
436
2.84375
3
[]
no_license
def solution(A): answer = 0 N = len(A) Chk = [0]*(N+1) for n in A: Chk[n] += 1 for i in range(1, N): if Chk[i] > 1: answer += Chk[i]-1 Chk[i+1] += Chk[i]-1 elif Chk[i] < 1: answer += 1-Chk[i] Chk[i+1] -= 1-Chk[i] if answer > 10**12: return -1 Chk[i] = 1 print(answer) return answer solution([4, 4, 4, 4] )
PHP
UTF-8
497
3.09375
3
[]
no_license
<?php require_once __DIR__ . '/User.php'; /** * Employee Class * Classe Figlia Employee */ class Employee extends User { // Propietà protected $prezzo; // Costruttore public function __construct($_name, $_lastName, $_age, $_prezzo = '85$') { parent::__construct($_name, $_lastName, $_age, $_prezzo, ); $this->prezzo = $_prezzo; } // Metodi public function getPrezzo() { return $this->prezzo; } }
Java
UTF-8
4,942
2.375
2
[]
no_license
package com.firstlab.migration; import com.firstlab.jpa.Expenditure; import com.firstlab.jpa.Firm; import com.firstlab.jpa.Realm; import com.firstlab.jpa.Staff; import com.firstlab.jpa.sql.ExpenditureSql; import com.firstlab.jpa.sql.FirmSql; import com.firstlab.jpa.sql.RealmSql; import com.firstlab.jpa.sql.StaffSql; import com.firstlab.repository.ExpenditureRepository; import com.firstlab.repository.FirmRepository; import com.firstlab.repository.RealmRepository; import com.firstlab.repository.StaffRepository; import com.firstlab.repositorySQL.ExpenditureRepositorySql; import com.firstlab.repositorySQL.FirmRepositorySql; import com.firstlab.repositorySQL.RealmRepositorySql; import com.firstlab.repositorySQL.StaffRepositorySql; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; import java.util.Optional; public class MongoSql { private FirmRepository firmRepository; private RealmRepository realmRepository; private ExpenditureRepository expenditureRepository; private StaffRepository staffRepository; private FirmRepositorySql firmRepositorySql; private ExpenditureRepositorySql expenditureRepositorySql; private RealmRepositorySql realmRepositorySql; private StaffRepositorySql staffRepositorySql; public MongoSql(FirmRepository firmRepository, RealmRepository realmRepository, ExpenditureRepository expenditureRepository, StaffRepository staffRepository, FirmRepositorySql firmRepositorySql, ExpenditureRepositorySql expenditureRepositorySql, RealmRepositorySql realmRepositorySql, StaffRepositorySql staffRepositorySql) { this.firmRepository = firmRepository; this.realmRepository = realmRepository; this.expenditureRepository = expenditureRepository; this.staffRepository = staffRepository; this.firmRepositorySql = firmRepositorySql; this.expenditureRepositorySql = expenditureRepositorySql; this.realmRepositorySql = realmRepositorySql; this.staffRepositorySql = staffRepositorySql; } public void convertMongoToSql(MongoRepository mongoRepositories[]) { for(int i =0;i<mongoRepositories.length;i++){ List<Object> data=mongoRepositories[i].findAll(); for(int j=0;j<data.size();j++){ convertEntityMongoToSql(data.get(j)); } } } public void convertEntityMongoToSql(Object mongo){ if(mongo instanceof Expenditure){ Optional<ExpenditureSql> exp=expenditureRepositorySql.findByTittle(((Expenditure) mongo).getTittle()); if(exp.isEmpty()){ expenditureRepositorySql.save(convertExpenditure((Expenditure) mongo)); } } else if(mongo instanceof Firm){ Optional<FirmSql> f=firmRepositorySql.findByName(((Firm) mongo).getName()); if(f.isEmpty()){ firmRepositorySql.save( convertFirm((Firm) mongo)); } } else if(mongo instanceof Realm){ Optional<RealmSql> r=realmRepositorySql.findByTittle(((Realm) mongo).getTittle()); if(r.isEmpty()){ realmRepositorySql.save( convertRealm((Realm) mongo)); } } else if(mongo instanceof Staff){ Optional<StaffSql> s=staffRepositorySql.findByName(((Staff) mongo).getName()); if(s.isEmpty()){ staffRepositorySql.save( convertStaff((Staff) mongo)); } } } public ExpenditureSql convertExpenditure(Expenditure mongo){ Optional<FirmSql> f=firmRepositorySql.findByName((mongo.getFirm()).getName()); if(f.isEmpty()){ f= Optional.ofNullable(convertFirm(mongo.getFirm())); } Optional<RealmSql> r=realmRepositorySql.findByTittle((mongo.getRealm()).getTittle()); if(r.isEmpty()){ r= Optional.ofNullable(convertRealm(mongo.getRealm())); } return new ExpenditureSql(mongo.getTittle(), mongo.getMoney(),mongo.getDescription(),f.get(),r.get()); } public FirmSql convertFirm(Firm mongo){ FirmSql f = new FirmSql(mongo.getName(),mongo.getAddress(),mongo.getContactNumber(), mongo.getManager(),mongo.getYear(),mongo.getIn()); firmRepositorySql.save(f); return f; } public RealmSql convertRealm(Realm mongo){ RealmSql r= new RealmSql(mongo.getTittle(),mongo.getDescription()); realmRepositorySql.save(r); return r; } public StaffSql convertStaff(Staff mongo){ Optional<FirmSql> f=firmRepositorySql.findByName((mongo.getFirm()).getName()); if(f.isEmpty()){ f= Optional.ofNullable(convertFirm(mongo.getFirm())); } return new StaffSql(mongo.getName(),mongo.getOccupation(),mongo.getEmail(), mongo.getPhone(),mongo.getSalary(),mongo.getDescription(),f.get()); } }
Markdown
UTF-8
2,240
2.890625
3
[ "BSD-3-Clause" ]
permissive
These files represent the initial version of a proposed spec for automating a datacenter migration. Note that there are no tools built around this yet. Imagine something like ``` commcare-cloud icds migration 2017-12-01-initial run postgresql ``` which would look at the mapping you'd specified of postgresql machines and initiate pairwise rsyncs. And then maybe ``` commcare-cloud icds migration 2017-12-01-initial check postgresql ``` would show you some progress information about the ongoing migration, as well as useful information like what logfiles to check to see the raw output of rsync commands, etc. for debugging. Anyway, that's the dream. ## The format - the big file `couchdb2-cluster-plan.yml` is just the plan file from `couchdb-cluster-admin` converted to YAML. This outlines the sharding plan that `couchdb-cluster-admin` will eventually commit, and thus also which data needs to be copied to which machine. - the `role-mapping.yml` file is really the payload here. It outlines for each data service which machine-to-machine data transfers need to happen. You can read it as saying "for the purposes of `postgresql`, `icds` `pg1` corresponds to `icds-new` `pgmain`", "for the purposes of `riackcs`, `icds` `pg1` corresponds to `icds-new` `riak0`", etc. ## The rationale Thinking back to the data-migration part of the migration, I'm pretty sure that this right here captures most if not all of what a computer would need to know about the particulars of that migration in order to run it automatically, or at least run parts of it automatically though commands like the ones above. The other nice thing is that even before we add any super-sophisticated automation, having this down in a spec can: - let people manually verify that they're migrating to and from the right IPs—it's right here in the spec what's supposed to go where - let people write scripts that generate the rsync commands that they should manually run (instead of manually copying and pasting IP addresses to form the commands themselves) - leave a simple formal record of what was supposed to happen in each migration. - serve as a focal point for building simple tools around that will eventually snowball into something super useful
Markdown
UTF-8
6,374
3.515625
4
[]
no_license
### 一.父组件像子组件传数据 #### 传递数据注意: 1.props只用于父组件像子组件传值 2.如果要像非子组件传递数据,必须逐层传递 3兄弟组件传值需借助父组件 #### 1.1传值 1.在父组件进行绑定 ```vue //父组件 //引入的child组件 //使用 v-bind 的缩写语法通常更简单: <child :msg-val="msg"> //这里必须要用 - 代替驼峰 // HTML 特性是不区分大小写的。所以,当使用的不是字符串模板,camelCased (驼峰式) 命名的 prop 需要转换为相对应的 kebab-case (短横线隔开式) 命名,当你使用的是字符串模板的时候,则没有这些限制 </child> data(){ return { msg: [1,2,3] }; } ``` 2.子组件props接受 ```vue //子组件通过props来接收数据: //方式1: props: ['msgVal'] //在menthod中可以this.magVal调用,相当于在data中定义的全局变量 //方式2 : props: { msgVal: Array //这样可以指定传入的类型,如果类型不对,会警告 } //方式3: props: { msgVal: { type: Array, //指定传入的类型 //type 也可以是一个自定义构造器函数,使用 instanceof 检测。 default: [0,0,0] //这样可以指定默认的值 } } //注意 props 会在组件实例创建之前进行校验,所以在 default 或 validator 函数里,诸如 data、computed 或 methods 等实例属性还无法使用 ``` #### 1.2传递函数 1.在父组件中声明的函数绑定到子组件 ```vue <Child :deletd="delted" :index="index"></Child> methods:{ deleted(index){ this.arr.splice(index,1); } ``` 2.在子组件中接受 ```vue <a @click="deletedTemp">删除</a> props:['deletd'], methods:{ deletedTemp(){ this.deleted(this.index) } } ``` 方法二:自定义事件(子组可以向父组件传值) 在父组件中定义事件监听函数,并引用子组件v-on绑定事件监听 ```vue <Child @deleted_hobby="deletdHobby"></Child> //触发deleted_hobby来调用deletedHobby methods:{ deletdHobby(index){ this.arr.splice(index,1); } ``` 在子组件中触发监听事件函数执行 ```vue <a @click="deletedTemp(index)">删除</a> props:['deletd'], methods:{ deletedTemp(index){ //触发父组件deleted_hobby this.$emit('deleted_hobby',index) } } ``` #### 1.3父组件调用子组件的方法 1.子组件 ```vue <template> <div> child </div> </template> <script> export default { name: "child", props: "someprops", methods: { parentHandleclick(e) { console.log(e) } } } </script> ``` 2.父组件 ```vue <template> <div> <button @click="clickParent">点击</button> <child ref="mychild"></child> </div> </template> <script> import Child from './child'; export default { name: "parent", components: { child: Child }, methods: { clickParent() { this.$refs.mychild.parentHandleclick("嘿嘿嘿"); } } } </script> ``` #### 1.4 slot插槽(主要用于父组件向子组件传递标签+数据) 1.在子组件定义插槽 ```vue <slot name="dashboard"></slot> ``` 2.父组件中使用 ```vue <child> <!--slot属性值对应子组件中的插槽的name属性值--> <h1 slot="dashboard" class="page-header">{{title}}</h1> </child> ``` ### 二.子组件向父组件传值 1.子组件通过this.$emit()的方式将值传递给父组件 ```vue <template>     <div class="app">        <input @click="sendMsg" type="button" value="给父组件传递值">     </div> </template> <script> export default {       data () {         return { //将msg传递给父组件             msg: "我是子组件的msg",         }     }, methods:{ sendMsg(){ //func: 是父组件指定的传数据绑定的函数,this.msg:子组件给父组件传递的数据 this.$emit('func',this.msg) } } } </script> ``` 2.父组件, 这里的func是父组件中绑定的函数名 ```vue <template> <div class="app"> <child @func="getMsgFormSon"></child> </div> </template> <script> import child from './child.vue' export default { data () { return { msgFormSon: "this is msg" } }, components:{ child, }, methods:{ getMsgFormSon(data){ this.msgFormSon = data console.log(this.msgFormSon) } } } </script> ``` ### 三.兄弟组件传值 第三方插件 pubsubjs 发布-订阅 下载:`npm i pubsub-js -S` 在需要使用的组件中引用`import PubSub from 'pubsub-js'` pub-sub库的使用。 发布: ```js PubSub.publish("事件名",data); ``` 订阅: ```js PubSub.subscribe('事件名',function(event,data){ //event 接受的是消息名称 data是传递的数据 //事件回调处理 }) ``` 案列: 项目中我们头部header需要向后台发送关键字,后台根据得到的关键字进行相应的操作,返回项目需要的数据。main主体区域中需要利用后台返回的数据,进行页面的渲染,main区域中必定会利用header中提供的关键字发送ajax请求,所以这就牵扯到组件之间的通信问题,pubsub-js就是用来实现组件之间通信的。兄弟组件之间通信如果利用props属性,需要借助父组件来实现,pubsub跨越组件之间的关系阶层进行通信。pubsub-js也就是我们所说的订阅消息和发布消息,订阅消息可以理解为事件的监听,发布消息可以理解为触发事件。 我们在header中点击搜索会通知main区域向后台发送Ajax请求,所以我们在header中发布消息,main中订阅消息 header中: ```vue import PubSub from 'pubsub-js' export default{ name:'header', data(){ return{ searchName:'', } }, methods:{ search(){ //发布消息 const searchName = this.searchName.trim(); if(serachName){ PubSub.publish('search',searchName); } } } } ``` main.vue ```vue mounted(){ PubSub.subscribe('search',(event,searchName)=>{ console.log(searchName); ...... }) } ```
Java
UTF-8
1,139
2.5
2
[]
no_license
package preschool2me; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Login_Admin { public static void main(String[] args) { String baseUrl="https://staging.daycare2me.com/index.html"; System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get(baseUrl); driver.manage().window().maximize(); login(driver); // TODO Auto-generated method stub } public static void login(WebDriver driver) { WebElement usrname=driver.findElement(By.id("user_name")); WebElement pwd=driver.findElement(By.id("user_password")); WebElement login=driver.findElement(By.id("login_form_btn")); usrname.sendKeys("arunrajan@qburst.com"); pwd.sendKeys("123456"); login.click(); if(driver.findElement(By.xpath("//*[@id=\"wrap-nav\"]/ul[1]/li[1]/a/button")).isDisplayed()) { System.out.println("Login verified sucessfully"); } else { System.out.println("Login case failed"); } driver.close(); } }
Markdown
UTF-8
2,296
2.734375
3
[]
no_license
--- layout: layouts/post.njk title: > MRS 022: Allison McMillan date: 2017-09-27 04:00:54 episode_number: 022 duration: 33:02 audio_url: https://media.devchat.tv/my-ruby-story/MRS_022__Allison_McMillan.mp3 podcast: ruby-rogues tags: - ruby_rogues - podcast --- This week on My Ruby Story, Charles speaks with Allison McMillan. Allison is a software developer at [Collective Idea](https://collectiveidea.com), a software consulting company that solves real-world software problems. Allison is very excited about working on a number of projects and learning new things in the development world. Allison was a recent guest on Ruby Rogues and will be a speaker at Ruby Dev Summit coming up on October 16-21, 2017. In this episode we learn more about Allison’s journey as a startup founder, to make a career change to a developer, all while and making a name in the dev community and gaining a dev job. Allison talks about her involvement and contributions to the Ruby community. **In particular, we dive pretty deep on:** - Allison got into programming working as a non-profit executive and dealing with change in the organization. - Getting in involve&nbsp; in the[DC Tech Community&nbsp;](https://www.meetup.com/DC-Tech-Meetup/?_cookie-check=J-9UEiLc24IWLTaK) - Joining the [Rails Girls](https://railsgirls.com) Workshop - Got her first job by attending the Ruby Conf. at the Scholar Guide Program - Working Remotely as a junior developer - Doing light talks at Ruby Conf. to gain authority - Allison mentions doing conference speaking and organizing as apart of contributing to the Ruby community - Allison’s favorite thing to speak about at conferences involves writing interactive workshops. **Links:** - [DC Tech Community&nbsp;](https://www.meetup.com/DC-Tech-Meetup/?_cookie-check=J-9UEiLc24IWLTaK) - [Rails Girls](https://railsgirls.com) - [https://rubyconf.org/scholarships](https://rubyconf.org/scholarships) - Blog site - [DayDreams In Ruby](https://daydreamsinruby.com) - @allie_p - [Ruby Dev Summit&nbsp;](https://rubydevsummit.com) - Free **Picks:&nbsp;** Allison - [Hello Ruby](https://www.helloruby.com) by Linda Liukas - Baking - [SmittenKitchen](https://smittenkitchen.com) Charles - [GitLab Server](https://about.gitlab.com) - [MatterMost](https://about.mattermost.com) - ### Transcript
C++
UTF-8
838
2.75
3
[]
no_license
#include<iostream> #include<algorithm> #include<map> #include<vector> #include<queue> using namespace std; int arr[30001]; bool reached[30001] = {0}; int main(){ int n, t; cin >> n >> t; map<int, vector<int> > mp; int m; for(int i = 0; i < n-1; i++){ cin >> m; arr[i+1] = i+1+m; } int pos = 1; arr[n] = 1; //bool flag = false; while(reached[pos] != 1){ reached[pos] = 1; //cout << "pos " << pos << " " << t << endl; if(pos == t){ cout << "YES"; return 0; } else pos = arr[pos]; } cout << "NO"; return 0; /*queue<int> q; q.push(1); discovered[n] = {0} while(!q.empty()){ int cur = q.front() for(int j = 0; j < mp[cur].size(); j++){ if(cur == t){ cout << "YES"; return 0;n } if(discovered[mp[cur][j]] == 0){ q.push(mp[cur][j]); discovered[mp[cur][j]] = 1; } } }*/ }
C++
UTF-8
957
3.109375
3
[]
no_license
/* Written by: Nicholas Cockcroft Date: August 12, 2018 Description: The "AI" class is responsible for the AI of the tic tac toe game. Everything needed for the AI to perform properly will be stored in this class. */ #ifndef AI_H #define AI_H #include <iostream> #include <string> #include <sstream> #include <cstdlib> #include <ctime> using namespace std; class AI { public: // Pubic functions AI(); void CreatePiece(char playerPiece); void MakeMove(string board); void MakeAIBoard(string board); // Getters char GetPiece(); char GetCurrentMove1(); char GetCurrentMove2(); private: // Private variables char AIPiece; char enemysPiece; char AIBoard[3][3]; char currentMove1; char currentMove2; int lastEducatedMove; // Private functions bool CheckHorizontal(); bool CheckVerticle(); bool CheckLeftDiagnol(); bool CheckRightDiagnol(); bool MiddleSpot(); int EducatedMove(); }; #endif
Python
UTF-8
2,730
2.515625
3
[]
no_license
#******************************************************** #@author: Pam Vinco #@summary: ScenarioBox handles all Scenario Box functions #******************************************************** from API.SquishSyntax import SquishSyntax from API.UserCreatedPacketWindow.ScenarioBoxConst import ScenarioBoxConst from API.Utility import UtilConst from API.Utility.Util import Util util = Util() class ScenarioBox: def __init__(self): self.util = Util() self.check = ScenarioBoxCheck() #@summary: Selects a scenario from the scenario dropdown list #@param p_item: Name of scenario to select #@note: p_item is not a constant, p_item is the EXACT name of the scenario in quotation marks (Scenario 1 = "Scenario 1") def selectScenario(self, p_scenario): Util().clickItem(ScenarioBoxConst.SCENARIO_DROPDOWN, p_scenario) def deleteButton(self): Util().clickButton(ScenarioBoxConst.DELETE_SCENARIO) def newButton(self): Util().clickButton(ScenarioBoxConst.NEW_SCENARIO) def deleteScenario(self, scenario): self.selectScenario(scenario) self.deleteButton() def addScenarioDescription(self, p_scenario, p_description): self.selectScenario(p_scenario) self.commonAddScenarioDescription(p_scenario, p_description) def changeScenarioName(self, p_scenario, p_name): self.selectScenario(p_scenario) self.commonChangeScenarioName(p_name) def createNewScenario(self, p_description, p_name): Util().clickButton(ScenarioBoxConst.NEW_SCENARIO) self.commonChangeScenarioName(p_name) self.commonAddScenarioDescription(p_name, p_description) def commonAddScenarioDescription(self, p_scenario, p_description): Util().clickButton(ScenarioBoxConst.SCENARIO_DESCRIPTION) for i in range(1,3): Util().click(ScenarioBoxConst.SCENARIO_DESCRIPTION_TEXT_FIRST_PART + p_scenario + ScenarioBoxConst.SCENARIO_DESCRIPTION_TEXT_LAST_PART) Util().snooze(1) Util().setText(ScenarioBoxConst.SCENARIO_DESCRIPTION_TEXT, p_description) Util().close(ScenarioBoxConst.SCENARIO_DESCRIPTION_WINDOW) def commonChangeScenarioName(self, p_name): Util().setText(ScenarioBoxConst.SCENARIO_NAME_TEXT, p_name) Util().typeText(ScenarioBoxConst.SCENARIO_NAME_TEXT, "\r") def expandScenarioToggle(self): Util().clickButton(ScenarioBoxConst.SCENARIO_BOX_EXPANDER) class ScenarioBoxCheck: def __init__(self): self.util = Util() def scenarioName(self, scenarioName): Util().textCheckPoint(ScenarioBoxConst.SCENARIO_NAME_TEXT, scenarioName)
Markdown
UTF-8
814
2.515625
3
[]
no_license
# Finanças - Modelo Analítico para Análise de Portfólio ### https://www.datascienceacademy.com.br Esse é aplicativo RStudio Shiny que constrói eficientes portfólios com base em um modelo de média-variância simples e um modelo Black-Litterman (módulo não concluído). O aplicativo exibe porcentagens a serem alocadas para cada classe de ativos (assets). O Modelo Black-Litterman combina a opinião dos investidores sobre classes de ativos no modelo de otimização de portfólio, sendo muito utilizado em Fundos Hedge, com carteiras de bilhões de dólares. Esse aplicativo foi construído em módulos. Você pode expandi-lo e agregar mais módulos e outros tipos de análises. Para esse aplicativo, consideramos ativos americanos, por ser mais fácil encontrar documentação sobre tais ativos.
Swift
UTF-8
1,186
3.109375
3
[]
no_license
// // main.swift // SwiftNN // // Created by Dan See on 1/6/16. // Copyright © 2016 Dan See. All rights reserved. // // Process.arguments[1] changes the execution directory into the specified directory // Process.arguments[2] opens the given file for analysis import Foundation let featuresVector: [UInt32] = [UInt32](count: 3, repeatedValue: 1) let sNN = Network(ls: 3, numLayers: 1, lr: 1, featuresVector: featuresVector) let nsf: NSFileManager = NSFileManager() //print(nsf.currentDirectoryPath) //print("") // nsf.changeCurrentDirectoryPath(Process.arguments[1]) // ^^^ enable this line when the code is run from the command line func initializeWorkingDirectory(defaultDirectory:String = "/Users/dansee/sNN_testing") { print("Process arg count has \(Process.arguments.count) items") if(Process.arguments.count > 2) { nsf.changeCurrentDirectoryPath(Process.arguments[1]) } else { nsf.changeCurrentDirectoryPath(defaultDirectory) } print("Changed directory to \(nsf.currentDirectoryPath)") do{ try print(nsf.contentsOfDirectoryAtPath(nsf.currentDirectoryPath)) } catch { print("Couldn't open that directory path.") } } initializeWorkingDirectory()
Python
UTF-8
3,082
4.0625
4
[]
no_license
""" Procedure: Create a Trie data structure with insert (for the available words), startswith (to perform dfs) and DFS (to find all words). Use DFS on every value of the matrix and every complete iteration will have a seen set because we are starting from new at every cell, also we need to backtrack at each iteration to clear nodes we seen that were reached from other cells. Use startswith so that we dont check irrelevant cells and only check prefixes that are in the Trie. Complexity: n -> number of rows, m -> number of cols, s -> length of average word, l -> number of words Time: O(n * m * 4^s) Space: O(max(s * l, 4^s)) """ class TrieNode: def __init__(self): self.children = {} self.leaf = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: if char not in node.children: nextNode = TrieNode() node.children[char] = nextNode node = nextNode else: node = node.children[char] node.leaf = True def startsWith(self, prefix): node = self.root for char in prefix: if char not in node.children: return False node = node.children[char] return True def DFS(self, board, words, m, n): result = set() directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] for x in range(m): for y in range(n): prefix = board[x][y] stack = [(x, y, prefix, False)] seen = set() while stack: i, j, s, backtrack = stack.pop() if s in words: result.add(s) if backtrack: seen.remove((i, j)) continue seen.add((i, j)) stack.append((i, j, s, True)) if self.startsWith(s): for x2, y2 in directions: newX, newY = i + x2, j + y2 if 0 <= newX < m and 0 <= newY < n and (newX, newY) not in seen: temp = s + board[newX][newY] if self.startsWith(temp): stack.append((newX, newY, temp, False)) return result class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: if not board or len(board[0]) == 0 or not words: return [] rowNum, colNum = len(board), len(board[0]) root = Trie() setWords = set(words) for word in words: root.insert(word) return root.DFS(board, setWords, rowNum, colNum)
Markdown
UTF-8
2,655
2.765625
3
[]
no_license
# About Comparing 3D structures of homologous RNA molecules yields information about sequence and structural variability. To compare large RNA 3D structures, accurate automatic comparison tools are needed. In this article, we introduce a new algorithm and web server to align large homologous RNA structures nucleotide by nucleotide using local superpositions that accommodate the flexibility of RNA molecules. Local alignments are merged to form a global alignment by employing a maximum clique algorithm on a specially defined graph that we call the ‘local alignment’ graph. The algorithm is implemented in a program suite and web server called ‘R3D Align’. The R3D Align alignment of homologous 3D structures of 5S, 16S and 23S rRNA was compared to a high-quality hand alignment. A full comparison of the 16S alignment with the other state-of-the-art methods is also provided. The R3D Align program suite includes new diagnostic tools for the structural evaluation of RNA alignments. The R3D Align alignments were compared to those produced by other programs and were found to be the most accurate, in comparison with a high quality hand-crafted alignment and in conjunction with a series of other diagnostics presented. The number of aligned base pairs as well as measures of geometric similarity are used to evaluate the accuracy of the alignments. # Installation From the command line. Skip the first line if FR3D is already installed. git clone git@github.com:BGSU-RNA/FR3D.git git clone git@github.com:BGSU-RNA/R3DAlign.git # Usage The main program is _R3DAlign.m_. After starting Matlab or Octave: cd FR3D; addpath FR3DSource PrecomputedData PDBFiles SearchSaveFiles; cd R3DAlign; addpath(genpath(pwd)); % test alignment of two 5S rRNAs [a1,a2] = R3DAlign('2AW4',{'A'},{'all'},'2J01',{'B'},{'all'},0.5,9,50,'greedy'); Alternatively, manually set the Matlab path to include the FR3D folders listed above. This will allow R3D Align to use binary .mat files for structures already downloaded and annoted by FR3D. However, any new .mat files will be stored in the R3DAlign folder, not back in the FR3D folder. To produce pdb files, use the following commands: Query.Type = 'local'; Query.Name = 'output_file'; % will produce output_file.pdb in the current working directory [a1,a2] = R3DAlign('2AW4',{'A'},{'all'},'2J01',{'B'},{'all'},0.5,9,50,'greedy',Query); # Credits Developed by Ryan Rahrig. Transferred to Github by Anton Petrov. Updated by Craig Zirbel Tested on Matlab R2007b, R2019b, and Octave 3.6.3, at various times. We try to maintain backward compatibility, but it cannot be assured.
C++
UTF-8
264
3.234375
3
[]
no_license
#include <iostream> #include<cmath> //for round function using namespace std; float roundoff(float var,unsigned char prec){ float pow_10=pow(10.0f,(float)prec); return round(var*pow_10)/pow_10; } int main() { cout<<roundoff(234.5618,3); }
C#
UTF-8
788
2.5625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class simpleController : MonoBehaviour { public bool turn; public Rigidbody2D myRigidBody; public float moveSpeed; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (turn == true) { myRigidBody.velocity = new Vector2(0, moveSpeed); } if (turn == false) { myRigidBody.velocity = new Vector2(-moveSpeed, 0); } } public void turnbird() { if (turn == true) { turn = false; } else if (turn == false) { turn = true; } } }
C++
UTF-8
1,003
2.8125
3
[]
no_license
#include <QCoreApplication> #include <iostream> #include <hello.h> using namespace std; void imprime(int value) { std::cout << "Value = " << value << '\n'; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyObject obj; // conecta o sinal valueChanged a função imprime QCoreApplication::connect( &obj, &MyObject::valueChanged, &imprime ); // faz o mesmo usando funções lambda QCoreApplication::connect( &obj, &MyObject::valueChanged, [] (int value) { std::cout << "lambda-" << value << '\n'; }); obj.setValue(15); MyObject obj2; // conecta o signal de obj2 com o slot de obj QCoreApplication::connect( &obj2, SIGNAL(valueChanged(int)), &obj, SLOT(setValue(int)) ); obj2.setValue(18); return a.exec(); }
Python
UTF-8
1,479
3.125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue May 22 21:23:39 2018 @author: XIN """ class rollingHash(object): def __init__(self): self.value = 0 self.base = 26 self.p = 10529 self.size = 0 def append(self, char): self.value = (self.value*self.base + (ord(char)-ord('a'))) % self.p self.size += 1 def skip(self, char): self.value = (self.value - (ord(char)-ord('a'))*(self.base**(self.size-1) % self.p)) % self.p self.size -= 1 def Karp_Rabin(s, t): rs = rollingHash() rt = rollingHash() res = [] for c in s: rs.append(c) # print(rs.value) for c in t[:len(s)]: rt.append(c) # print(rt.value) if rs.value == rt.value: # print(rt.value) res.append(0) for i in range(len(s), len(t)): rt.skip(t[i-len(s)]) rt.append(t[i]) # print(rt.value) if rs.value == rt.value: res.append(i-len(s)+1) return res import random import string import re if __name__ == '__main__': s = 'aab' t = ''.join(random.choice(string.ascii_lowercase) for _ in range(1000000)) ans = Karp_Rabin(s,t) a = [] for x in ans: a.append(t[x:x+len(s)]) count = 0 for x in a: if x == s: count += 1 b = re.findall(s,t) print(len(b)-count)
Java
UTF-8
3,314
1.664063
2
[]
no_license
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package com.tencent.mm.modelqrcode; import a.h; import android.os.*; // Referenced classes of package com.tencent.mm.modelqrcode: // DecodeThread, CameraManager, ScreenManager public final class CaptureHandler extends Handler { public CaptureHandler(CameraManager cameramanager, ScreenManager screenmanager, OnResetPreviewListener onresetpreviewlistener, OnSuccessListener onsuccesslistener) { b = null; c = null; d = null; a = State.b; c = onresetpreviewlistener; d = onsuccesslistener; e = cameramanager; b = new DecodeThread(cameramanager, screenmanager, this); b.start(); b(); } private void b() { if(a == State.b) { a = State.a; e.a(b.a()); e.b(this); } } public final void a() { a = State.c; Message.obtain(b.a(), 0x12345006).sendToTarget(); try { b.join(); } catch(InterruptedException interruptedexception) { } removeMessages(0x12345004); removeMessages(0x12345005); } public final void handleMessage(Message message) { message.what; JVM INSTR tableswitch 305418241 305418245: default 40 // 305418241 41 // 305418242 62 // 305418243 40 // 305418244 69 // 305418245 121; goto _L1 _L2 _L3 _L1 _L4 _L5 _L1: return; _L2: if(a == State.a) e.b(this); continue; /* Loop/switch isn't completed */ _L3: b(); continue; /* Loop/switch isn't completed */ _L4: a = State.b; Bundle bundle = message.getData(); if(bundle != null) bundle.getParcelable("barcode_bitmap"); if(d != null) d.a(((h)message.obj).a()); continue; /* Loop/switch isn't completed */ _L5: a = State.a; e.a(b.a()); if(true) goto _L1; else goto _L6 _L6: } private State a; private DecodeThread b; private OnResetPreviewListener c; private OnSuccessListener d; private CameraManager e; private class State extends Enum { public static State valueOf(String s) { return (State)Enum.valueOf(com/tencent/mm/modelqrcode/CaptureHandler$State, s); } public static State[] values() { return (State[])d.clone(); } public static final State a; public static final State b; public static final State c; private static final State d[]; static { a = new State("PREVIEW", 0); b = new State("SUCCESS", 1); c = new State("DONE", 2); State astate[] = new State[3]; astate[0] = a; astate[1] = b; astate[2] = c; d = astate; } private State(String s, int i) { super(s, i); } } private class OnSuccessListener { public abstract void a(String s); } }
Python
UTF-8
166
3.828125
4
[]
no_license
def square(x): return x * x def main(num): for num in range(10): print( "The square of {} is {}".format( num, square(num))) if __name__ == "__main__": main()
Ruby
UTF-8
212
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Post def initialize(title) @title = title Author.post_count += 1 end attr_accessor :author attr_reader :title def author_name self.author ? self.author.name : self.author end end
C
UTF-8
305
2.875
3
[]
no_license
/* ** EPITECH PROJECT, 2018 ** LibString ** File description: ** putchar, putstr - Output of characters and strings */ #include <unistd.h> size_t my_strlen(char const *str); int my_putchar(char c) { return (write(1, &c, 1)); } int my_puts(char const *str) { return (write(1, str, my_strlen(str))); }
JavaScript
UTF-8
2,271
3.109375
3
[]
no_license
//Não funfa mais function daCrawl () { lojas = []; $(".icon").each(function( index ) { if($(this).attr("height") != "21") { if(!lojas.includes($(this).attr("title"))) { lojas.push($(this).attr("title")); } } }); resultado = lojas.join(); console.log(resultado); } //só funfa o nome. Vai pegar precos repetidos function crawler2 () { lojas = []; precos = []; $(".e-col1").each(function() { nome = $(this).children().children().attr("title"); if(!lojas.includes(nome)) { lojas.push(nome); } }); $(".e-col3").each(function() { valor = $(this).text(); //se ela for grande tem desconto if(valor.length == 5) { valor = valor.slice(3).replace(',','.'); } else { valor = valor.slice(11).replace(',','.'); } if(!precos.includes(valor)) { precos.push(valor); } }); resultado = lojas.join() + '\n\n' + precos.join(); console.log(resultado); } function nome_e_preco () { lojas = []; precos = []; $(".estoque-linha primeiro,.estoque-linha").each(function() { nome = $(this).find("img").attr("title"); if(!lojas.includes(nome)) { lojas.push(nome); valor = $(this).children(".e-col3").text() if(valor.length == 8) { //NORMAL precos.push(valor.slice(3).replace(',','.')); } else if(valor.length == 16) {//PROMOCAO precos.push(valor.slice(11).replace(',','.')); } else { precos.push("[Erro no tamanho do preço :(]"); } } }); resultado = lojas.join() + '\n\n' + precos.join(); console.log(resultado); } nome_e_preco(); function nome_e_preco () { lojas = []; precos = []; //Limpa as Promocoes $(".estoque-linha primeiro,.estoque-linha").find(".e-col3").children('font').text("") $(".estoque-linha primeiro,.estoque-linha").each(function() { nome = $(this).find("img").attr("title"); if(!lojas.includes(nome)) { lojas.push(nome); valor = $(this).children(".e-col3").text() valor = valor.slice(3); precos.push(valor); } }); resultado = lojas.join() + '\n\n' + precos.join(); console.log(resultado); } nome_e_preco();
C++
UTF-8
841
3.015625
3
[]
no_license
#ifndef USER_H #define USER_H #include <iostream> #include <string> /** * Implements User functionality and information storage * You should not need to derive anything from User at this time */ class User { public: User(); User(std::string name, double balance, int type, unsigned long long hash_password); virtual ~User(); double getBalance() const; std::string getName() const; void deductAmount(double amt); virtual void dump(std::ostream& os); unsigned long long getPassword(); bool check_password(unsigned long long password); User* get_pred(); double get_dist(); void set_pred(User* pred); void set_dist(double dist); private: std::string name_; double balance_; int type_; unsigned long long hash_password_; User* pred_; double dist_; }; #endif
C#
UTF-8
896
3.46875
3
[]
no_license
using System; using System.Linq; using Xunit; namespace Kata { public class UnitTest1 { [Theory] [InlineData("atl","ieer",true)] [InlineData("atl",null,false)] public void MatchTest(string firstWord, string secondWord, bool expectedResult) { var baseString = "Atelier"; var result = Match(baseString, firstWord, secondWord); Assert.Equal(result, expectedResult); } private bool Match(string baseString, string firstWord, string secondWord) { var wordsConcatened = (firstWord + secondWord).ToLower(); var orderedWords = new string(wordsConcatened.OrderBy(ch => ch).ToArray()); var findWord = new string(baseString.ToLower().OrderBy(ch => ch).ToArray()); return findWord == orderedWords; } } }
Ruby
UTF-8
748
2.640625
3
[]
no_license
# == Schema Information # # Table name: benches # # id :bigint not null, primary key # description :string not null # lat :float not null # lng :float not null # created_at :datetime not null # updated_at :datetime not null # class Bench < ApplicationRecord validates :description, :lat, :lng, presence: true def self.in_bounds(bounds) # bounds = {lng: [long_start, long_end], lat: [lat_start,lat_end]} if bounds Bench.where('lng BETWEEN ? AND ?', bounds[:lng][0], bounds[:lng][1]) .where('lat BETWEEN ? AND ?', bounds[:lat][0], bounds[:lat][1]) else Bench.all end end end
Java
UTF-8
1,984
1.632813
2
[]
no_license
package com.hp.it.perf.ac.app.hpsc.search.service; import java.util.List; import org.springframework.jdbc.core.RowCallbackHandler; import com.hp.it.perf.ac.app.hpsc.search.bean.ConsumerDetailReport; import com.hp.it.perf.ac.app.hpsc.search.bean.ConsumerHomeInfo; import com.hp.it.perf.ac.app.hpsc.search.bean.ConsumerRequestReport; import com.hp.it.perf.ac.app.hpsc.search.bean.ProducerHomeInfo; import com.hp.it.perf.ac.app.hpsc.search.bean.ProducerReport; import com.hp.it.perf.ac.app.hpsc.search.bean.QueryCondition; import com.hp.it.perf.ac.common.model.AcCommonDataWithPayLoad; import com.hp.it.perf.ac.core.AcService; public interface HpscQueryService extends AcService { // condition: time window. public ConsumerHomeInfo getConsumerHomeInfo(QueryCondition queryCondition); // condition: time window. public List<ProducerHomeInfo> getProducerHomeInfo(QueryCondition queryCondition); // condition: time window. public List<ConsumerRequestReport> getConsumerRequestReport(QueryCondition queryCondition); // condition: time window, request name. public List<ConsumerRequestReport> getConsumerRequestDetailReport(QueryCondition queryCondition); // condition: time window. public List<ConsumerDetailReport> getConsumerDetailReport(QueryCondition queryCondition); // condition: time window. public List<ProducerReport> getProducerReport(QueryCondition queryCondition); // condition: time window, portletName+phaseName(part). public List<ProducerReport> getProducerDetailReoprt(QueryCondition queryCondition); // condition: acid list. public List<AcCommonDataWithPayLoad> getLogDetail(QueryCondition queryCondition); // condition: time window // condition: deleteAll is a flag for deleting all data in database public void deleteDataInDB(QueryCondition queryCondition, boolean deleteAll); // condition: sql, prepared argurment objects, RowCallbackHandler public void handledBySql(String sql, Object[] args, RowCallbackHandler rch); }
Java
UTF-8
1,177
2.890625
3
[]
no_license
package lars.wittenbrink.halligalli.game.cards; import java.util.Collections; import java.util.LinkedList; import java.util.List; import lars.wittenbrink.halligalli.game.user.User; public final class Cards { public Cards(){ } public static List<Card> createCards() { List<Card> cards = new LinkedList<>(); for (FruitIcon fruitIcon : FruitIcon.values()) { for (FruitNumber fruitNumber : FruitNumber.values()) { for (int i = 0; i < fruitNumber.getNumber(); i++) { cards.add(new Card(fruitIcon, fruitNumber)); } } } return cards; } public static List<Card> mixCards(List<Card> cards) { Collections.shuffle(cards); return cards; } public static void distributeCards(List<Card> cards, List<User> users) { while (!cards.isEmpty()) { for (User user : users) { if (!cards.isEmpty()) { user.getClosedCards().addLast(cards.get(0)); cards.remove(0); } else { return; } } } } }
Go
UTF-8
487
2.828125
3
[ "MIT" ]
permissive
package y2021m01 // 每日一题 20210126 // // 1128. 等价多米诺骨牌对的数量 // Link: https://leetcode-cn.com/problems/number-of-equivalent-domino-pairs/ func numEquivDominoPairs(dominoes [][]int) int { getIndex := func(arr []int) int { if arr[0] > arr[1] { return arr[1]*10 + arr[0] } return arr[0]*10 + arr[1] } ret := 0 counter := make([]int, 100) for _, v := range dominoes { key := getIndex(v) ret += counter[key] counter[key] += 1 } return ret }
Ruby
UTF-8
1,078
3.75
4
[]
no_license
#!/usr/bin/env ruby # frozen_string_literal: true def speak(numbers, turns) tally = Hash[numbers[0..-2].map.with_index { |n, i| [n, i + 1] }] (numbers.length..(turns - 1)).each do |i| prev = tally[numbers.last] prev = prev.nil? ? 0 : i - prev tally[numbers.last] = i numbers << prev end numbers.last end # Part one # puts speak([0, 3, 6], 10) # => 436 puts speak([0, 3, 6], 2020) # => 436 puts speak([1, 3, 2], 2020) # => 1 puts speak([2, 1, 3], 2020) # => 10 puts speak([1, 2, 3], 2020) # => 27 puts speak([2, 3, 1], 2020) # => 78 puts speak([3, 2, 1], 2020) # => 438 puts speak([3, 1, 2], 2020) # => 1836 puts speak([0, 5, 4, 1, 10, 14, 7], 2020) # => 203 # Part two puts speak([0, 3, 6], 30_000_000) # => 175594 puts speak([1, 3, 2], 30_000_000) # => 2578 puts speak([2, 1, 3], 30_000_000) # => 3544142 puts speak([1, 2, 3], 30_000_000) # => 261214 puts speak([2, 3, 1], 30_000_000) # => 6895259 puts speak([3, 2, 1], 30_000_000) # => 18 puts speak([3, 1, 2], 30_000_000) # => 362 puts speak([0, 5, 4, 1, 10, 14, 7], 30_000_000) # => 9007186
C
UTF-8
1,643
3.078125
3
[]
no_license
#include <stdio.h> typedef struct point{ int x; int y; } point; point Point_Default = {0,0}; int contains(point* visited,int size,point item) { for(int i =0;i <size;i++) if(visited[i].x==item.x&&visited[i].y==item.y)return 1; return 0; } int main() { FILE* fp = fopen("maze_ai.in","r"); int length; int width; fscanf(fp,"%i %i",&width,&length); char buff[500]; fgets(buff,500,fp); int map[length][width]; point position = Point_Default; point target = Point_Default; for(int row = 0;row<length;row++) { fgets(buff, width+2, fp); for(int i = 0;i<width;i++) { if(buff[i] == 'S') { position.x = i; position.y = row; } if(buff[i] == 'E') { target.x = i; target.y = row; } map[row][i] = buff[i] == '#'; } } point stack[length*width]; point* item = stack; *item = position; point visited[length*width]; point* v = visited; *(v++) = position; while(item >= stack) { int dx; int dy; for(dx=-1;dx<=2;dx++) { if(dx==2)break; for(dy=-1;dy<=1;dy++) { if(dx==dy||dx*dy!=0)continue; point next = {item->x+dx,item->y+dy}; if(!map[next.y][next.x] && !contains(visited,v-visited,next)) { *(++item) = next; *(v++) = next; goto done; } } } done: if(dx==2) { item--; }else{ if(item->x==target.x&&item->y==target.y)break; } } printf("%i,%i\n",item->x,item->y); for(;item>stack;item--) { map[item->y][item->x]=2; } map[item->y][item->x] = 2; char* pieces = " #*"; for(int row=0;row<length;row++) { for(int col=0;col<width;col++) printf("%c",pieces[map[row][col]]); puts(""); } return 0; }
C#
UTF-8
1,574
4.1875
4
[]
no_license
using System; using System.Collections.Generic; namespace ADT_Stack { class Program { static void Main(string[] args) { // stack usage example Stack<string> stack = new Stack<string>(); stack.Push("1. John Jackson"); stack.Push("2. Nicolas Cage"); stack.Push("3. Marry Poppins"); stack.Push("4. Daniel Sadcliff"); Console.WriteLine("Top = " + stack.Peek()); while (stack.Count > 0) { string personName = stack.Pop(); Console.WriteLine(personName); } Console.WriteLine(); // Correct brackets check string expression = "1 + ( 3 + 2 - (2+3)*4 - ((3+1*(4-2)))"; Stack<int> bracketStack = new Stack<int>(); bool correctBrackets = true; for (int index = 0; index < expression.Length; index++) { char ch = expression[index]; if (ch == '(') { bracketStack.Push(index); } else if (ch == ')') { if (stack.Count == 0) { correctBrackets = false; break; } stack.Pop(); } } if (stack.Count != 0) { correctBrackets = false; } Console.WriteLine("Are the brackets correct? " + correctBrackets); } } }
C
UTF-8
446
4.0625
4
[]
no_license
#include "holberton.h" /** * create_array - creates an array of chars, and initializes * it with a specific char. * @size: lenght. * @c: array. * Return: NULL or array. */ char *create_array(unsigned int size, char c) { char *pointer; unsigned int index; pointer = malloc(size * sizeof(c)); if (size == 0 || pointer == NULL) return (NULL); for (index = 0; index < size; index++) *(pointer + index) = c; return (pointer); }
Swift
UTF-8
4,584
2.796875
3
[]
no_license
// // FirestoreService.swift // Messenger // // Created by Леонид on 19.08.2020. // Copyright © 2020 LSDevStudy. All rights reserved. // import Firebase import FirebaseFirestore class FirestoreService { static let shared = FirestoreService() let db = Firestore.firestore() private var usersRef: CollectionReference { return db.collection("users") } var currentUser: MUser! func saveProfileWith (id: String, email: String, username: String, completion: @escaping (Result<MUser, Error>) -> Void) { guard Validators.isFilled(email: email, name: username) else { completion(.failure(AuthError.notFilled)) //В связи с тем, что в той реализации, которую я видел, этот процесс был вынесен на отдельный экран - то и ошибки у него были отдельные. В моей реализации оно делается на одном экране и использует один лог ошибок. return } let muser = MUser(username: username, email: email, id: id) self.usersRef.document(muser.id).setData(muser.representation) { (error) in if let error = error { completion(.failure(error)) } else { completion(.success(muser)) } } } func getUserData (user: User, completion: @escaping (Result<MUser, Error>) -> Void) { let docReference = usersRef.document(user.uid) docReference.getDocument { (document, error) in if let document = document, document.exists { guard let muser = MUser(document: document) else { completion(.failure(AuthError.cannorUnwrapUser)) return } self.currentUser = muser completion(.success(muser)) } else { completion(.failure(AuthError.cannotGetUser)) } } } func searchUser (searchingUser: String, completion: @escaping (Result<MUser, Error>) -> Void) { usersRef.whereField("username", isEqualTo: searchingUser).getDocuments { (querySnapshot, error) in if let error = error { completion(.failure(error)) return } guard let resultUser = querySnapshot?.documents.first else { completion(.failure(AuthError.cannotGetUser)) return } let muser = MUser(document: resultUser)! completion(.success(muser)) } } func createChat (reciever: MUser, completion: @escaping (Result<MChat, Error>) -> Void) { let recieverRef = db.collection(["users", reciever.id, "activeChats"].joined(separator: "/")) let currentUserRef = db.collection(["users", currentUser.id, "activeChats"].joined(separator: "/")) let messageRef = recieverRef.document(self.currentUser.id).collection("messages") let currentUserMessRef = currentUserRef.document(reciever.id).collection("messages") let message = MMessage(user: currentUser, content: "") let recieverChat = MChat(username: currentUser.username, lastMessage: nil, id: currentUser.id) recieverRef.document(currentUser.id).setData(recieverChat.representation) { (error) in if let error = error { completion(.failure(error)) return } messageRef.addDocument(data: message.representation) { (error) in if let error = error { completion(.failure(error)) return } } } let currentUserChat = MChat(username: reciever.username, lastMessage: nil, id: reciever.id) currentUserRef.document(reciever.id).setData(currentUserChat.representation) { (error) in if let error = error { completion(.failure(error)) return } currentUserMessRef.addDocument(data: message.representation) { (error) in if let error = error { completion(.failure(error)) return } completion(.success(currentUserChat)) } } } }
Java
UTF-8
5,484
2.203125
2
[]
no_license
package com.example.yash.weatherapi; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private String TAG = "MainActivity"; private ListView listView; private ProgressDialog progressDialog; private static String url = "https://weatherforcast.000webhostapp.com/city_list.json"; ArrayList<HashMap<String,String >> cityList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cityList = new ArrayList<>(); listView = (ListView)findViewById(R.id.listView); new GetContacts().execute(); } //onPreExecute--> doInBackground--> onPostExecute private class GetContacts extends AsyncTask<Void, Void, Void>{ @Override protected void onPreExecute(){ super.onPreExecute(); progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Please wait"); progressDialog.setCancelable(false); progressDialog.show(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler httpHandler = new HttpHandler(); String jsonString = httpHandler.makeServiceCall(url); Log.e(TAG,"Response from url: " +jsonString); if(jsonString!=null){ try{ JSONObject jsonObject = new JSONObject(jsonString); JSONArray city = jsonObject.getJSONArray("City"); for(int i=0; i<city.length();i++){ JSONObject c = city.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String country = c.getString("country"); //Phone node is json object JSONObject coord = c.getJSONObject("coord"); String lon = coord.getString("lon"); String lat = coord.getString("lat"); // tmp hash map for single contact HashMap<String, String> eachcity = new HashMap<>(); // adding each child node to HashMap key => value eachcity.put("id", id); eachcity.put("name", name); eachcity.put("country", country); eachcity.put("lon", lon); eachcity.put("lat", lat); // adding contact to contact list cityList.add(eachcity); } } catch (final JSONException e) { //e.printStackTrace(); Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server.", Toast.LENGTH_LONG) .show(); } }); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (progressDialog.isShowing()) progressDialog.dismiss(); ListAdapter adapter = new SimpleAdapter( MainActivity.this, cityList, R.layout.list_item, new String[]{"name"}, new int[]{R.id.name}); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String city_id = cityList.get(position).get("id"); String city_name = cityList.get(position).get("name"); Intent intent = new Intent(MainActivity.this,weather.class); intent.putExtra("city",city_id); intent.putExtra("name",city_name); startActivity(intent); } }); } } }
PHP
UTF-8
10,555
2.703125
3
[]
no_license
<?php // 'edit.php' require_once "pdo.php"; require_once "util.php"; session_start(); // If the user is not logged-in if ( ! isset($_SESSION['user_id'])) { die('ACCESS DENIED'); return; } // If the user requested cancel, go back to index.php if ( isset($_POST['cancel']) ) { header('Location: index.php'); return; } // Make sure the REQUEST parameter is present if ( ! isset($_REQUEST['profile_id']) ) { $_SESSION['error'] = "Missing profile_id"; header('Location: index.php'); return; } if ( isset($_GET['profile_id']) && strlen($_GET['profile_id'] > 0)) { $_SESSION['profile_id'] = $_GET['profile_id']; } $uid = $_SESSION['user_id']; $profileid = $_SESSION['profile_id']; $posCount = get_position_count($pdo); $_SESSION['posCount'] = $posCount; // Get profile from database $profile = get_profile_information($pdo, $profileid, $uid); if($profile===false){ $_SESSION['error'] = 'Could not load profile'; header('Location: index.php'); return; } $fn = htmlentities($profile['first_name']); $ln = htmlentities($profile['last_name']); $em = htmlentities($profile['email']); $hl = htmlentities($profile['headline']); $sum = htmlentities($profile['summary']); // Get educations and positions from database $educations = loadEdu($pdo, $_SESSION['profile_id']); $positions = loadPos($pdo, $_SESSION['profile_id']); // Validation Data if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email']) && isset($_POST['headline']) && isset($_POST['summary'])) { $msg = validateProfile(); if (is_string($msg) ) { $_SESSION['error'] = $msg; header('Location: edit.php?profile_id='.$_REQUEST['profile_id']); return; } //Validate position entries when present. $msg = validatePos(); if (is_string($msg) ) { $_SESSION['error'] = $msg; header('Location: edit.php?profile_id='.$_REQUEST['profile_id']); return; } $msg = validateEducation(); if (is_string($msg) ) { $_SESSION['error'] = $msg; header('Location: edit.php?profile_id='.$_REQUEST['profile_id']); return; } $msg = validateInstitution(); if (is_string($msg) ) { $_SESSION['error'] = $msg; header('Location: edit.php?profile_id='.$_REQUEST['profile_id']); return; } // Update profiles $sql = "UPDATE Profile SET first_name = :fn, last_name = :lnm, email = :em, headline = :hl, summary = :sum WHERE profile_id = :prof_id "; $stmt = $pdo->prepare($sql); $stmt->execute(array(':fn' => $_POST['first_name'], ':lnm' => $_POST['last_name'], ':em' => $_POST['email'], ':hl' => $_POST['headline'], ':sum' => $_POST['summary'], ':prof_id' => $_GET['profile_id']) ); // Delete old education entries; recreate new list $stmt = $pdo->prepare('DELETE FROM Education WHERE profile_id = :pid'); $stmt->execute(array(':pid' => $_REQUEST['profile_id'])); // Clear old position entries; recreate new list $stmt = $pdo->prepare('DELETE FROM Position WHERE profile_id = :pid'); $stmt->execute(array(':pid' => $_REQUEST['profile_id'])); //Insert new position entries; create replacement list insertPositions($pdo, $_REQUEST['profile_id']); $posCount = get_position_count($pdo); $_SESSION['posCount'] = $posCount; $_SESSION["success"] = 'Record edited: there are now '.$posCount.' positions.'; insertEducations($pdo, $_REQUEST['profile_id']); $_SESSION['success'] = "Position added"; header("Location: index.php"); return; } ?> <!-- ---------------------------- VIEW ------------------------------------> <!DOCTYPE html> <html> <head> <title>Marcel Merchat's Resume Registry</title> <?php require_once 'jquery.php'; if(isMobile()==1) { require_once 'mobile.php'; } else { echo '<link rel="stylesheet" type="text/css" href="styleDesktop.css">'; } ?> <script src="script.js"></script> </head> <body> <div id="main"> <h2>Editing profile: by <?= $_SESSION['full_name'] ?></h2> <?php flashMessages(); if( $_SESSION['posCount'] === 9 ){ $_SESSION['error'] = 'The number of position entries is at the limit of nine.'; unset($_SESSION['error']); echo '<br>'; } ?> <form method="post"> <p><input type='hidden' name='profile_id' value='<?= $profileid ?>' ></p> <p><input type="hidden" name="user_id" value='<?= $uid ?>' ></p> <p>First Name: <input class="text-box" type="text" name="first_name" value='<?= $fn ?>' id="fn" size="30"></p> <p>Last Name: <input class="text-box" type="text" name="last_name" value='<?= $ln ?>' id="ln" size="30"></p> <p class="small-bottom-pad">E-mail:</p> <input class="emale-entry-box" type="text" name="email" value='<?= $em ?>' id="em"> <p class="small-bottom-pad"> Headline:</p> <input class="big headline-box" type="text" name="headline" value='<?= $hl ?>' id="he"> <p class="small-bottom-pad"> Summary:</p> <textarea class="big" name="summary" rows="8" cols="80" id="su"> <?= $sum ?> </textarea> <p>Add Education: <button class="click-plus" id="addEdu" >+</button></p> <div id="edu_fields"> <?php $countEdu = 1; foreach($educations as $education){ $_SESSION['education_count'] = $countEdu; echo '<div id=\"edu'.$countEdu.'\">'."\n"; echo '<p>Year: <input class="year-entry-box" type="text" name="edu_year'.$countEdu.'"'; echo ' value="'.$education['year'].'">'."\n"; echo '<input class="click-plus" type="button" value="-" '; echo 'onclick="$(\'#edu'.$countEdu.'\').remove(); return false;">'."\n"; echo "</p>\n"; echo '<p>School: <input class="text-box" type="text" name="edu_school'.$countEdu.'" value="'.htmlentities($education['name']).'" rows="8" cols="80"></p>'; $countEdu++; echo "</div></p>\n"; } echo "</div>"; //Grab some HTML with hot spots and insert in the DOM ?> <script id="edu-template" type="text"> <div id="edu@COUNT@"> <p>Year: <input class="year-entry-box" type="text" name="edu_year@COUNT@" value="" /> <input class="click-plus" type="button" value="-" onclick="$('#edu@COUNT@').remove(); return false;"/><p> <p>School: <input class="school" type="text" size="80" name="edu_school@COUNT@" value="" id="school@COUNT@" /></p> </script> <!--<p>Position: <input type="submit" id="addPos" value="+">;--> <p>Add Position: <button class="click-plus" id="addPos" >+</button></p> <div id="position_fields"> <?php $pos = 1; foreach($positions as $position){ $_SESSION['position_count'] = $pos; echo '<div id="position'.$pos.'">'."\n"; echo '<p>Year: <input class="year-entry-box" type="text" name="year'.$pos.'"'; echo ' value="'.$position['year'].'">'."\n"; echo '<input class="click-plus" type="button" value="-" '; echo 'onclick="$(\'#position'.$pos.'\').remove(); return false;">'."\n"; echo "</p>\n"; echo '<textarea name="desc'.$pos.'" rows="8" cols="80">'.htmlentities($position['description']).'</textarea>'; $pos++; echo "</div></p>\n"; } ?> </div> <div> <p> <input class="button-submit" type="submit" onclick="return doValidate();" value="Save"> <input class="button-submit" type="submit" name="cancel" value="Cancel" size="40"> </p> </div> </form> </div> <script> $(document).ready(function() { window.console && console.log('Document ready called'); var temp = "<?php echo $pos ?>"; $(document).ready(function() { window.console && console.log('Document ready called'); countPos = 9; countphp = 1; var temp = "<?php echo $pos ?>"; window.console && console.log('Document ready called'); var positionCount = Number("<?php echo $pos ?>"); var countEdu = Number("<?php echo $countEdu ?>"); $('#addPos').click(function(event){ event.preventDefault(); if( positionCount > 9){ alert('Maximum of nine position entries exceeded'); return; } window.console && console.log("Adding position "+positionCount); $('#position_fields').append( '<div id=\"position'+positionCount+'\"><p>Year: <input class="year-entry-box" type="text" name="year'+positionCount+'" size="10" id="yr"/> <input \ class="click-plus" type="button" value="-" onclick="$(\'#position'+positionCount+'\').remove(); return false;"/></p> \ <p>Description: </p> \ <textarea name=\"desc'+positionCount+'\" rows = "8" cols="80" id="de" ></textarea> \ </div>'); positionCount++; }); $('#addEdu').click(function(event) { event.preventDefault(); if(countEdu >= 9){ alert('Maximum of nine education entries exceeded'); return; } window.console && console.log("Adding education "+countEdu); var source = $('#edu-template').html(); //window.console && console.log('Adding education '.$countEdu); $('#edu_fields').append(source.replace(/@COUNT@/g, countEdu)); countEdu++; // auto-completion handler for new additions window.console && console.log("Appending to education"); var y = "school.php"; $(document).on('click', '.school', 'input[type="text"]', function(){ eyedee = $(this).attr("id"); term = document.getElementById(id=eyedee).value; window.console && console.log('preparing json for '+term); $.getJSON('school.php?ter'+'m='+term, function(data) { var y = data; $('.school').autocomplete({ source: y }); }); }); }); //end of addedu $(document).on('click', '.school', 'input[type="text"]', function(){ eyedee = $(this).attr("id"); term = document.getElementById(id=eyedee).value; $.getJSON('school.php?ter'+'m='+term, function(data) { var y = data.Result; var y =data; $('.school').autocomplete({ source: y }); }); }); }); }); </script> </body> </html>
C#
UTF-8
1,309
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ex03.GarageLogic { public static class VehicleCreator { public static string[] s_VehicleTypesMenu = {"Electric car", "Fuel car", "Electric motorcycle", "Fuel motorcycle", "Truck"}; public static Vehicle CreateVehicle(int i_VehicleType) { Vehicle vehicle = null; switch (i_VehicleType) { case 0: { vehicle = new ElectricCar(); break; } case 1: { vehicle = new FuelCar(); break; } case 2: { vehicle = new ElectricMotorcycle(); break; } case 3: { vehicle = new FuelMotorcycle(); break; } case 4: { vehicle = new Truck(); break; } } return vehicle; } } }
Java
UTF-8
191
2.390625
2
[]
no_license
package operational.interpreter; public class KeyExpression implements Expression<String> { @Override public String interpret(Context context) { return context.nextToken().trim(); } }