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
Python
UTF-8
3,243
2.65625
3
[]
no_license
from __future__ import print_function from keras.models import Model from keras.layers import Input, LSTM, Dense import numpy as np import seq2seq import utils import sklearn import numpy as np import sys from itertools import chain import time def hamming_dist(s1, s2): assert len(s1) == len(s2) return sum(c1 != c2 for c1, c2 in zip(s1, s2)) def precision(top100, query_class): count = 0 for _, c in top100: if c == query_class: count+=1 a_precision = float(count)/100 print ("Average precision, ", a_precision) return a_precision if __name__ == "__main__": print("\n\nLoading pre-trained model weights...") time.sleep(6) data_path = '20news-bydate-train' utils.DataUtils.get_20news_dataset(data_path) batch_size = 64 # Batch size for training. epochs = 100 # Number of epochs to train for. latent_dim = 256 # Latent dimensionality of the encoding space. num_samples = 10000 # Number of samples to train on. # Path to the data txt file on disk. encoder_input_data, decoder_input_data, decoder_target_data, num_encoder_tokens, num_decoder_tokens = utils.DataUtils.prep_train_data(0, 1000) seq_model = seq2seq.seq2seq(latent_dim, num_encoder_tokens, num_decoder_tokens) seq_model.load_existing() #enc_test, _, _, _, _= utils.DataUtils.prep_train_data(1000, 1100) for seq_index in range(1): print("\nSelecting document...") time.sleep(5) print("\nHashing document\n") input_seq = encoder_input_data[seq_index: seq_index + 1] states_value = np.array(seq_model.hash(input_seq)) hash_code = utils.hash(states_value) hash_class = utils.DataUtils.Y_train[seq_index].split(".")[0].strip(",") h = '' for val in hash_code: h+=str(val) print("Hash value of document: \n", h) print ("\nClass of hashed document: ", hash_class) print("\n") time.sleep(5) input_path = "hashed_documents/all_hash_values.txt" hash_dict = {} sim_dict = {} precisions = [] print("Getting hash values of other documents...\n") time.sleep(5) with open(input_path, "r") as f: classes = {} for line in f.readlines(): hash, c = line.split("]") c = c.split(".")[0].strip(",") if c in classes: classes[c]+=1 else: classes[c] = 1 hash_string = '' for val in hash: if val == '1' or val == '0': hash_string+=val hash_dict[hash_string] = c query = h query_class = hash_class top100 = [] print("\nComparing hash values, finding 100 most similar\n") for key, key_class in hash_dict.items(): sim = hamming_dist(query, key) top100.append([sim, key_class]) top100 = sorted(top100, key=lambda x: x[0], reverse=True) print("\nClasses of most relevant documents:\n") for i, v in enumerate(top100): print(str(i) + ". " + "sim: " + str(v[0]) + " class: " + str(v[1])) if (i == 100): break precisions.append(precision(top100[:100], query_class)) avg_precisions = np.array(precisions)
Java
UTF-8
5,133
1.851563
2
[]
no_license
package com.ooyala.sample.lists; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import com.ooyala.sample.R; import com.ooyala.sample.players.NPAWDefaultPlayerActivity; import com.ooyala.sample.utils.PlayerSelectionOption; import com.ooyala.sample.utils.youbora.YouboraConfigManager; import java.util.LinkedHashMap; import java.util.Map; public class NPAWYouboraListActivity extends Activity implements OnItemClickListener { public final static String getName() { return "NPAW Youbura Integration"; } private static Map<String, PlayerSelectionOption> selectionMap; ArrayAdapter<String> selectionAdapter; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getName()); selectionMap = new LinkedHashMap<String, PlayerSelectionOption>(); //Populate the embed map selectionMap.put("4:3 Aspect Ratio", new PlayerSelectionOption("FwaXZjcjrkydIftLal2cq9ymQMuvjvD8", "c0cTkxOqALQviQIGAHWY5hP0q9gU", "http://www.ooyala.com", NPAWDefaultPlayerActivity.class)); selectionMap.put("MP4 Video", new PlayerSelectionOption("h4aHB1ZDqV7hbmLEv4xSOx3FdUUuephx", "c0cTkxOqALQviQIGAHWY5hP0q9gU", "http://www.ooyala.com", NPAWDefaultPlayerActivity.class)); selectionMap.put("HLS Video", new PlayerSelectionOption("Y1ZHB1ZDqfhCPjYYRbCEOz0GR8IsVRm1", "c0cTkxOqALQviQIGAHWY5hP0q9gU", "http://www.ooyala.com", NPAWDefaultPlayerActivity.class)); selectionMap.put("VOD with CCs", new PlayerSelectionOption("92cWp0ZDpDm4Q8rzHfVK6q9m6OtFP-ww", "c0cTkxOqALQviQIGAHWY5hP0q9gU", "http://www.ooyala.com", NPAWDefaultPlayerActivity.class)); selectionMap.put("VAST2 Ad Pre-roll", new PlayerSelectionOption("Zlcmp0ZDrpHlAFWFsOBsgEXFepeSXY4c", "BidTQxOqebpNk1rVsjs2sUJSTOZc", "http://www.ooyala.com", NPAWDefaultPlayerActivity.class)); selectionMap.put("VAST2 Ad Mid-roll", new PlayerSelectionOption("pncmp0ZDp7OKlwTPJlMZzrI59j8Imefa", "BidTQxOqebpNk1rVsjs2sUJSTOZc", "http://www.ooyala.com", NPAWDefaultPlayerActivity.class)); selectionMap.put("VAST2 Ad Post-roll", new PlayerSelectionOption("Zpcmp0ZDpaB-90xK8MIV9QF973r1ZdUf", "BidTQxOqebpNk1rVsjs2sUJSTOZc", "http://www.ooyala.com", NPAWDefaultPlayerActivity.class)); setContentView(R.layout.list_activity_layout); //Create the adapter for the ListView selectionAdapter = new ArrayAdapter<String>(this, R.layout.list_activity_list_item); for (String key : selectionMap.keySet()) { selectionAdapter.add(key); } selectionAdapter.notifyDataSetChanged(); //Load the data into the ListView ListView selectionListView = (ListView) findViewById(R.id.mainActivityListView); selectionListView.setAdapter(selectionAdapter); selectionListView.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> l, View v, int pos, long id) { PlayerSelectionOption selection = selectionMap.get(selectionAdapter.getItem(pos)); Class<? extends Activity> selectedClass = selection.getActivity(); //Launch the correct activity with the embed code as an extra Intent intent = new Intent(this, selectedClass); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); intent.putExtra("embed_code", selection.getEmbedCode()); intent.putExtra("pcode", selection.getPcode()); intent.putExtra("domain", selection.getDomain()); intent.putExtra("selection_name", selectionAdapter.getItem(pos)); startActivity(intent); return; } /* * Create the Options menu, which you can use to configure all Youbora configuration in the app */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } /* * Handle the display of YouboraConfigActivity and resetting the configuration */ @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.youbora_config_show: YouboraConfigManager.showConfig(getApplicationContext()); return true; case R.id.youbora_config_reset: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { YouboraConfigManager.resetPreferences(getApplicationContext()); } }); builder.setNegativeButton("No", null); builder.setMessage("Do you want to restore the default Youbora config?"); builder.setTitle("Restore defaults"); AlertDialog dialog = builder.create(); dialog.show(); return true; default: return super.onOptionsItemSelected(item); } } }
Shell
UTF-8
742
3.015625
3
[]
no_license
# grc overides for ls # Made possible through contributions from generous benefactors like # `brew install coreutils` if $(gls &>/dev/null) then alias ls="gls -F --color" alias l="gls -lAh --color" alias ll="gls -l --color" alias la='gls -A --color' fi # Always enable colored `grep` output # Note: `GREP_OPTIONS="--color=auto"` is deprecated, hence the alias usage. alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' # Google Chrome alias chrome='/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome' # Flush Directory Service cache alias flush="dscacheutil -flushcache && killall -HUP mDNSResponder" # Lock the screen (when going AFK) alias afk="pmset displaysleepnow"
Python
UTF-8
23,387
2.65625
3
[ "BSD-3-Clause", "MIT" ]
permissive
# This script imports the .dac index file. It is modified from # the slycat-csv-parser. # # S. Martin # 4/4/2017 import csv import numpy import slycat.web.server # zip file manipulation import io import zipfile import os # background thread does all the work on the server import threading import traceback # for dac_compute_coords.py and dac_upload_model.py import imp # for error logging import cherrypy # note this version assumes the first row is a header row, and keeps only the header # and data (called by the generic zip parser) def parse_table_file(file): """ parses out a csv file into numpy array by column (data), the dimension meta data(dimensions), and sets attributes (attributes) :param file: csv file to be parsed :returns: attributes, data """ rows = [row for row in csv.reader(file.decode().splitlines(), delimiter=",", doublequote=True, escapechar=None, quotechar='"', quoting=csv.QUOTE_MINIMAL, skipinitialspace=True)] if len(rows) < 2: raise Exception("File must contain at least two rows.") # get header attributes = rows[0] # go through the csv by row data = [] for row in rows[1:]: data.append(row) if len(attributes) < 1: raise Exception("File must contain at least one column.") return attributes, data # note this version assumes the first row is a header row, and saves the header values # as attributes (obfuscated, but leaving here to preserve backwards compatibility) def parse_file(file): """ parses out a csv file into numpy array by column (data), the dimension meta data(dimensions), and sets attributes (attributes) :param file: csv file to be parsed :returns: attributes, dimensions, data """ def isfloat(value): try: float(value) return True except ValueError: return False rows = [row for row in csv.reader(file.splitlines(), delimiter=",", doublequote=True, escapechar=None, quotechar='"', quoting=csv.QUOTE_MINIMAL, skipinitialspace=True)] if len(rows) < 2: raise Exception("File must contain at least two rows.") attributes = [] dimensions = [{"name":"row", "type":"int64", "begin":0, "end":len(rows[1:])}] data = [] # go through the csv by column for column in zip(*rows): column_has_floats = False # start from 1 to avoid the column name for value in column[1:]: if isfloat(value): column_has_floats = True try:# note NaN's are floats output_list = ['NaN' if x=='' else x for x in column[1:]] data.append(numpy.array(output_list).astype("float64")) attributes.append({"name":column[0], "type":"float64"}) # could not convert something to a float defaulting to string except Exception as e: column_has_floats = False break if not column_has_floats: data.append(numpy.array(column[1:])) attributes.append({"name":column[0], "type":"string"}) if len(attributes) < 1: raise Exception("File must contain at least one column.") return attributes, dimensions, data # note this version assumes there is no header row and the file is a matrix # note that we are assuming floats in our matrices def parse_mat_file(file): """ parses out a csv file into numpy array by column (data), the dimension meta data(dimensions), and sets attributes (attributes) :param file: csv file to be parsed :returns: attributes, dimensions, data """ # parse file using comma delimiter rows = [row for row in csv.reader(file.decode().splitlines(), delimiter=",", doublequote=True, escapechar=None, quotechar='"', quoting=csv.QUOTE_MINIMAL, skipinitialspace=True)] # check that we have a matrix num_rows = len(rows) num_cols = len(rows[0]) is_a_matrix = True for i in range(0, num_rows): if len(rows[i]) != num_cols: is_a_matrix = False # fill a numpy matrix with matrix from file (assumes floats, fails otherwise) data = numpy.zeros((len(rows[0:]), len(rows[0]))) for j in range(len(rows[0:])): try: data[j,:] = numpy.array([float(name) for name in rows[j]]) except: is_a_matrix = False # for a vector we strip off the outer python array [] if int(data.shape[0]) == 1: data = data[0] dimensions = [dict(name="row", end=len(data))] else: # for a matrix we need the number of columns too dimensions = [dict(name="row", end=int(data.shape[0])), dict(name="column", end=int(data.shape[1]))] # attributes are the same for matrices and vectors attributes = [dict(name="value", type="float64")] # return matrix, if found if is_a_matrix: return attributes, dimensions, data else: return [], [], [] def parse_list_file(file): """ parses a text file with a list, one string per row :param file: list file to be parsed (strings, one per row) :return: a list of strings """ # get rows of file rows = [row.strip() for row in file.splitlines()] # remove any empty rows rows = [_f for _f in rows if _f] # return only unique rows rows = list(set(rows)) return rows def parse(database, model, input, files, aids, **kwargs): """ parses a file as a csv and then uploads the parsed data to associated storage for a model :param database: slycat.web.server.database.couchdb.connect() :param model: database.get("model", self._mid) :param input: boolean :param files: files to be parsed :param aids: artifact ID :param kwargs: """ # this version of parse is designed to pass in the column of the aid as the second # part of the aids array, so aids: ["variable", "0"] is the previous behavior. # if nothing extra is passed in, the array column defaults to 0. # also passed in via the aids array is a third variable, which indicates # whether or not the file is a table or a matrix, "table" for table and # "matrix" for matrix. for example, aids: ["variable", "0", "table"] is # the default, while aids: ["variable", "1", "mat"] indicates that the # file is the 2nd matrix in the aid and should be parsed with no header row. # ["variable", "0", "list"] indicates a text file with a list, one per row. # set defaults (table, array 0) table = True list_file = False array_col = 0 # change defaults for three parameters if len(aids) == 3: table = (aids[2] == "table") list_file = (aids[2] == "list") array_col = int(aids[1]) # change defaults for two parameters if len(aids) == 2: array_col = int(aids[1]) # revert aids to what is expected in original code aids = [aids[0]] if len(files) != len(aids): raise Exception("Number of files and artifact ids must match.") # parse file as either table or matrix if table: # table parser (original csv parser) parsed = [parse_file(file) for file in files] for (attributes, dimensions, data), aid in zip(parsed, aids): slycat.web.server.put_model_arrayset(database, model, aid, input) slycat.web.server.put_model_array(database, model, aid, array_col, attributes, dimensions) slycat.web.server.put_model_arrayset_data(database, model, aid, "%s/.../..." % array_col, data) elif list_file: # list file (one string per row) # get strings in list list_data = parse_list_file(files[0]) # put list in slycat database as a model parameter slycat.web.server.put_model_parameter(database, model, aids[0], list_data, input) else: # matrix parser (newer parser) attributes, dimensions, data = parse_mat_file(files[0]) aid = aids[0] if (array_col == 0): slycat.web.server.put_model_arrayset(database, model, aid, input) slycat.web.server.put_model_array(database, model, aid, array_col, attributes, dimensions) slycat.web.server.put_model_arrayset_data(database, model, aid, "%s/0/..." % array_col, [data]) # DAC generic .zip file parser def parse_gen_zip(database, model, input, files, aids, **kwargs): # import error handling from source dac_error = imp.load_source('dac_error_handling', os.path.join(os.path.dirname(__file__), 'py/dac_error_handling.py')) dac_error.log_dac_msg("Gen Zip parser started.") # push progress for wizard polling to database slycat.web.server.put_model_parameter(database, model, "dac-polling-progress", ["Extracting ...", 10.0]) # keep a parsing error log to help user correct input data # (each array entry is a string) parse_error_log = dac_error.update_parse_log (database, model, [], "Progress", "Notes:") # treat uploaded file as bitstream try: file_like_object = io.BytesIO(files[0]) zip_ref = zipfile.ZipFile(file_like_object) zip_files = zip_ref.namelist() except Exception as e: dac_error.quit_raise_exception(database, model, parse_error_log, "Couldn't read zip file (too large or corrupted).") # look for one occurrence (only) of .dac file and var, dist, and time directories dac_file = "" landmarks_file = "" pca_file = "" var_meta_file = "" var_files = [] dist_files = [] time_files = [] for zip_file in zip_files: # parse into directory and/or file head, tail = os.path.split(zip_file) # found a file if head == "": # is it .dac file? ext = tail.split(".")[-1] if ext == "dac": dac_file = zip_file # is it "landmarks.csv"? if zip_file == "landmarks.csv": landmarks_file = zip_file # is is "pca.csv"? if zip_file == "pca.csv": pca_file = zip_file # found a directory -- is it "var/"? elif head == "var": # check for variables.meta file if tail == "variables.meta": var_meta_file = zip_file # check for .var extension elif tail != "": ext = tail.split(".")[-1] if ext == "var": var_files.append(zip_file) else: dac_error.quit_raise_exception(database, model, parse_error_log, "Variable files must have .var extension.") # is it "time/" directory? elif head == "time": # ignore directory if tail != "": ext = tail.split(".")[-1] if ext == "time": time_files.append(zip_file) else: dac_error.quit_raise_exception(database, model, parse_error_log, "Time series files must have .time extension.") # is it "dist/" directory? elif head == "dist": # ignore directory if tail != "": ext = tail.split(".")[-1] if ext == "dist": dist_files.append(zip_file) else: dac_error.quit_raise_exception(database, model, parse_error_log, "Distance matrix files must have .dist extension.") parse_error_log = dac_error.update_parse_log(database, model, parse_error_log, "Progress", "Successfully identified DAC generic format files.") # prepare to upload data meta_var_col_names = [] meta_vars = [] # load variables.meta file if var_meta_file != "": # push progress for wizard polling to database model = database.get('model', model["_id"]) slycat.web.server.put_model_parameter(database, model, "dac-polling-progress", ["Extracting ...", 20.0]) # parse variables.meta file meta_var_col_names, meta_vars = parse_table_file(zip_ref.read(var_meta_file)) # check variable meta data header headers_OK = True if len(meta_var_col_names) == 4: if meta_var_col_names[0] != "Name": headers_OK = False if meta_var_col_names[1] != "Time Units": headers_OK = False if meta_var_col_names[2] != "Units": headers_OK = False if meta_var_col_names[3] != "Plot Type": headers_OK = False else: headers_OK = False # quit if headers are un-recognized if not headers_OK: dac_error.quit_raise_exception(database, model, parse_error_log, "Variables.meta file has incorrect headers.") # check var file names num_vars = len(meta_vars) check_file_names(database, model, dac_error, parse_error_log, "var/variable_", ".var", num_vars, var_files, "missing variable_*.var file(s).") parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Checked DAC variable file names.") # check time file names check_file_names(database, model, dac_error, parse_error_log, "time/variable_", ".time", num_vars, time_files, "missing variable_*.time file(s).") parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Checked DAC time file names.") # check dist file names check_file_names(database, model, dac_error, parse_error_log, "dist/variable_", ".dist", num_vars, dist_files, "missing variable_*.dist file(s).") parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Checked DAC distance file names.") else: dac_error.quit_raise_exception(database, model, parse_error_log, "Variables.meta file not found.") # load landmarks file landmarks = None if landmarks_file != "": # parse landmarks.csv file attr, dim, landmarks = parse_mat_file(zip_ref.read(landmarks_file)) else: parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "No landmarks.csv file found, using all data points.") # load pca-comps file pca_comps = None if pca_file != "": # parse pca.csv file attr, dim, pca_comps = parse_mat_file(zip_ref.read(pca_file)) else: parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "No pca.csv file found, using MDS algorithm.") # now start thread to prevent timing out on large files stop_event = threading.Event() thread = threading.Thread(target=parse_gen_zip_thread, args=(database, model, zip_ref, dac_error, parse_error_log, meta_var_col_names, meta_vars, landmarks, pca_comps, dac_file, stop_event)) thread.start() # helper function which checks file names # note error message shouldn't end with a "." def check_file_names (database, model, dac_error, parse_error_log, root, ext, num_files, files, error_msg): files_found = True for i in range(0, num_files): file_i = root + str(i + 1) + ext if not file_i in files: files_found = False # quit if files do not match if not files_found: dac_error.quit_raise_exception(database, model, parse_error_log, error_msg) # gen zip parsing thread to prevent time outs by browser def parse_gen_zip_thread(database, model, zip_ref, dac_error, parse_error_log, meta_var_col_names, meta_vars, landmarks, pca_comps, dac_file, stop_event): # put entire thread into a try-except block in order report errors try: # import dac_upload_model from source push = imp.load_source('dac_upload_model', os.path.join(os.path.dirname(__file__), 'py/dac_upload_model.py')) num_vars = len(meta_vars) # parse meta file meta_column_names, meta_rows = parse_table_file(zip_ref.read(dac_file)) # number of data points num_datapoints = len(meta_rows) # do pca check (pca over-rides landmarks) use_coordinates=False if pca_comps is not None: num_pca_comps = int(numpy.round(pca_comps[0])) # check that pca comps is at least two if num_pca_comps < 2: dac_error.quit_raise_exception(database, model, parse_error_log, 'Number of PCA components must be at least two.') # set as number of landmarks num_landmarks = num_pca_comps use_coordinates = True parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Using " + str(num_pca_comps) + " PCA components.") # do landmark checks elif landmarks is not None: num_landmarks = len(landmarks) # check that number of landmarks is at least three if num_landmarks < 3: dac_error.quit_raise_exception(database, model, parse_error_log, 'Number of landmarks must be at least three.') # make landmarks integer by rounding landmarks = numpy.around(landmarks) # check that landmarks in are correct range if numpy.amin(landmarks) < 1 or numpy.amax(landmarks) > num_datapoints: dac_error.quit_raise_exception(database, model, parse_error_log, 'Landmarks are out of range of data points.') parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Read " + str(num_landmarks) + " landmarks.") # if no landmarks, it's the same as all landmarks, # at least for the purposes of check dist matrix size else: num_landmarks = num_datapoints parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Read " + str(num_datapoints) + " datapoints.") # push progress for wizard polling to database slycat.web.server.put_model_parameter(database, model, "dac-polling-progress", ["Extracting ...", 30.0]) # parse var files variable = [] for i in range(0, num_vars): attr, dim, data = parse_mat_file(zip_ref.read("var/variable_" + str(i+1) + ".var")) variable.append(numpy.array(data)) parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Parsed " + str(num_vars) + " DAC variable files.") # push progress for wizard polling to database model = database.get('model', model["_id"]) slycat.web.server.put_model_parameter(database, model, "dac-polling-progress", ["Extracting ...", 45.0]) # parse time files time_steps = [] for i in range(0, num_vars): attr, dim, data = parse_mat_file(zip_ref.read("time/variable_" + str(i + 1) + ".time")) # check that time steps match variable length if len(variable[i][0]) != len(data): dac_error.quit_raise_exception(database, model, parse_error_log, 'Time steps do not match variable data for variable ' + str(i+1) + ".") time_steps.append(list(data)) parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Parsed " + str(num_vars) + " DAC time files.") # push progress for wizard polling to database model = database.get('model', model["_id"]) slycat.web.server.put_model_parameter(database, model, "dac-polling-progress", ["Extracting ...", 60.0]) # parse distance files var_dist = [] for i in range(0, num_vars): attr, dim, data = parse_mat_file(zip_ref.read("dist/variable_" + str(i + 1) + ".dist")) # check that distance matrix is (num_datapoint, num_landmarks) if data.shape[0] != num_datapoints or data.shape[1] != num_landmarks: dac_error.quit_raise_exception(database, model, parse_error_log, 'Distance matrix is incorrect shape for variable ' + str(i + 1) + '.') # check that distance matrix matches number of datapoints if len(data) != num_datapoints: dac_error.quit_raise_exception(database, model, parse_error_log, 'Distance matrix size does not match number of datapoints for variable ' \ + str(i + 1) + '.') var_dist.append(numpy.array(data)) parse_error_log = dac_error.update_parse_log (database, model, parse_error_log, "Progress", "Parsed " + str(num_vars) + " DAC distance files.") # summarize results for user parse_error_log.insert(0, "Summary:") # list out final statistics num_tests = len(meta_rows) parse_error_log.insert(1, "Total number of tests: " + str(num_tests) + ".") parse_error_log.insert(2, "Each test has " + str(num_vars) + " digitizer time series.\n") slycat.web.server.put_model_parameter(database, model, "dac-parse-log", ["Progress", "\n".join(parse_error_log)]) # upload model to slycat database push.init_upload_model(database, model, dac_error, parse_error_log, meta_column_names, meta_rows, meta_var_col_names, meta_vars, variable, time_steps, var_dist, landmarks=landmarks, use_coordinates=use_coordinates) # done -- destroy the thread stop_event.set() except Exception as e: dac_error.log_dac_msg(traceback.format_exc()) stop_event.set() # register all generic file parsers (really just the same csv parser), so that they # appear with different labels in the file picker. def register_slycat_plugin(context): context.register_parser("dac-gen-zip-parser", "DAC generic .zip file", ["dac-gen-zip-file"], parse_gen_zip) context.register_parser("dac-category-file-parser", "DAC category list (text file, one category per line)", ["dac-cat-file"], parse)
C
UTF-8
1,429
2.875
3
[]
no_license
/* DDRB = 0b00001111; //0->Input,1->Output (PB7,PB6,PB5,PB4,PB3,PB2,PB1,PB0) //Both are Same DDRB &= ~((1<<PINB7) | (1<<PB6) | (1<<PB5) | (1<<PB4)); //Setting as input DDRB |= ( (1<<PB3) | (1<<PB2) |(1<<PB1) |(1<<PB0) ); //setting as Output PORTB &= ~((1<<PB3) | (1<<PB2) | (1<<PB1) | (1<<PB0)); //clearing the Output Pins initially If we want to enable pullups for Input pins PORTB |= ( (1<<PB7) | (1<<PB6) |(1<<PB5) |(1<<PB4) ); #include <util/delay.h> #include "digitalInputOutput.h" #define LED1 PC0 #define LED2 PC1 #define SW1 PC2 #define SW2 PC3 #define INDDR DDRC #define OUTDDR DDRC #define INPORT PORTC #define OUTPORT PORTC #define INPIN PINC int main() { //Set Pin as Output setPinMode(&OUTDDR, LED1, OUTPUT); setPinMode(&OUTDDR, LED2, OUTPUT); //Set pin as Input setPinMode(&INDDR, SW1, INPUT); setPinMode(&INDDR, SW2, INPUT); //Initially turn output to zero state turnBit(&OUTPORT, LED1, LOW); turnBit(&OUTPORT, LED2, LOW); while(1) { if(checkBitValue(&INPIN,SW1)){ turnBit(&OUTPORT, LED1, HIGH); turnBit(&OUTPORT, LED2, LOW); } else{ turnBit(&OUTPORT, LED1, LOW); turnBit(&OUTPORT, LED2, LOW); } if(checkBitValue(&INPIN,SW2)){ turnBit(&OUTPORT, LED1, LOW); turnBit(&OUTPORT, LED2, HIGH); } else{ turnBit(&OUTPORT, LED1, LOW); turnBit(&OUTPORT, LED2, LOW); } } return 0; } */
Markdown
UTF-8
1,512
2.921875
3
[]
no_license
# vscode-pylint-wrapper Wrapper for executing pylint in vscode to avoid hung processes and runaway memory usage When using pylint with vscode, it seems to suffer from two problems: - the pylint processes never exit, leading to hundreds or thousands of pylint processes after a few hours - the pylint processes themselves, or else the vscode javascript extension which is executing them, consumes more and more memory, leading to an eventual hang as the linux out of memory handler kicks in to kill every *other* process running on the system, for the sake of the pylint processes. This repo provides a simple wrapper script which does two things: - close all file descriptors except useful ones (stdin,stderr,stdout) immediately - execute the 'real' pylint3 process, with a timeout, so that it will be killed if it does not exit in a timely manner. To use this wrapper with vscode: - Save the pylint-3-wrapper.py file somewhere on your system - Run chmod +rx pylint-3-wrapper.py - Check that the setting within the script ('REAL_EXEC=/usr/bin/pylint-3') is the correct path for your system. - In your VSCode user settings, set property 'python.linting.pylintPath' to the path of the wrapper script. - Modify the timeout value if you want ('MAX_LIFE_SECONDS=120') at the top of the script. - The linting can take some time so don't set it too low # Example vscode settings for pylint-3 { "python.linting.pylintPath":"/home/example/bin/pylint-3-wrapper.py", }
Java
UTF-8
2,458
2.28125
2
[]
no_license
package com.edisoninteractive.inrideads.Receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.util.Log; import com.edisoninteractive.inrideads.Entities.WifiConnectionPoint; import com.edisoninteractive.inrideads.Services.GlGeoLocationApiService; import com.edisoninteractive.inrideads.Utils.NetworkUtils; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; import static com.edisoninteractive.inrideads.Entities.GlobalConstants.APP_LOG_TAG; /** * Created by Creator on 4/6/2018. */ public class WifiAPdataReceiver extends BroadcastReceiver { private String className = getClass().getSimpleName(); @Override public void onReceive(Context context, Intent intent) { WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { List<ScanResult> wifiList = wifiManager.getScanResults(); ArrayList<WifiConnectionPoint> al_WifiConnectionPoints = new ArrayList<>(); for (int i = 0; i < wifiList.size(); i++) { ScanResult scanResult = wifiList.get(i); WifiConnectionPoint bean = new WifiConnectionPoint(); bean.macAddress = (scanResult.BSSID); bean.signalStrength = (scanResult.level); al_WifiConnectionPoints.add(bean); } Gson gson = new Gson(); String jsonArray_WifiConnectionPoints = gson.toJson(al_WifiConnectionPoints); Log.i(APP_LOG_TAG, className + ": wifi points quantity: " + al_WifiConnectionPoints.size()); Intent intentServiceStart = new Intent(context, GlGeoLocationApiService.class); intentServiceStart.setAction("com.edisoninteractive.inrideads.Services.action.GetGlGeoLocation"); intentServiceStart.putExtra("wifiAccessPoints", jsonArray_WifiConnectionPoints); context.startService(intentServiceStart); } try { context.unregisterReceiver(this); } catch (Exception e) { e.printStackTrace(); NetworkUtils.getInstance().showAndUploadLogEvent(className , 2, ": unregisterReceiver threw an exception, " + e.getMessage()); } } }
Markdown
UTF-8
2,836
3.703125
4
[]
no_license
# 196. 删除重复的电子邮箱 https://leetcode-cn.com/problems/delete-duplicate-emails/ <br/> ```wiki 编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。 +----+------------------+ | Id | Email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | | 3 | john@example.com | +----+------------------+ Id 是这个表的主键。 例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行: +----+------------------+ | Id | Email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | +----+------------------+ ``` ### 知识点 ##### DELETE ```wiki 1. DELETE 语句用于删除表中的行。 2. 如果WHERE条件没有匹配到任何记录,DELETE语句不会报错,也不会有任何记录被删除。 3. 不带WHERE条件的DELETE语句会删除整个表的数据(删除的是表的数据不是表) 4. 在使用oracle这类关系数据库时,DELETE语句会返回删除的行数以及WHERE条件匹配的行数。 5. 如果要进行删除的这条数据在其他表中使用,并且建立了约束的话,是不能直接进行删除的。 ``` ```mysql 1. DELETE FROM 表名称 WHERE 列名称 = 值 3. DELETE FROM table_name; 或者 DELETE * FROM table_name; ``` #### 方法:使用 `DELETE` 和 `WHERE` 子句 可以使用以下代码,将此表与它自身在*电子邮箱*列中连接起来。<br/> ```mysql SELECT p1.* FROM Person p1, Person p2 WHERE p1.Email = p2.Email ; ``` ```wiki +----+------------------+ +----+------------------+ | Id | Email | | Id | Email | +----+------------------+ +----+------------------+ | 1 | john@example.com | | 1 | john@example.com | | 3 | john@example.com | | 2 | bob@example.com | | 2 | bob@example.com | | 3 | john@example.com | | 1 | john@example.com | +----+------------------+ | 3 | john@example.com | ``` 然后需要找到其他记录中具有相同电子邮件地址的更大 ID。所以我们可以像这样给 `WHERE` 子句添加一个新的条件。<br/> ```mysql SELECT p1.* FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id ; ``` ```wiki +----+------------------+ +----+------------------+ | Id | Email | | Id | Email | +----+------------------+ +----+------------------+ | 3 | john@example.com | | 1 | john@example.com | ``` 已经得到了要删除的记录,所以最终可以将该语句更改为 `DELETE`。 <br/> ```mysql DELETE p1 FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id ``` **分析题目:** <br/> ```wiki 当一个表要与本身数据作比较时,通常要通过FROM引用两次,为了区分分别定义别名。 此题,只保留id最小,因此要比较id的大小。 ```
Java
UTF-8
1,883
2.53125
3
[ "Apache-2.0" ]
permissive
package com.bigboxer23.garage; import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.info.Contact; import io.swagger.v3.oas.annotations.info.Info; import java.io.IOException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; @SpringBootApplication @EnableScheduling @OpenAPIDefinition( info = @Info( title = "Garage Opener", version = "1", description = "Allows rPi to control a garage door, including returning status" + " about open/close state, when last opened, when house door" + " was opened, temp, & humidity", contact = @Contact( name = "bigboxer23@gmail.com", url = "https://github.com/bigboxer23/PiGarage2"))) public class GarageOpenerApplication implements SchedulingConfigurer { public static void main(String[] args) { SpringApplication.run(GarageOpenerApplication.class, args); } public GarageOpenerApplication() throws IOException {} @Override public void configureTasks(ScheduledTaskRegistrar theTaskRegistrar) { theTaskRegistrar.setScheduler(taskExecutor()); } @Bean(destroyMethod = "shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(10, new NamedThreadFactory()); } private class NamedThreadFactory implements ThreadFactory { public Thread newThread(Runnable theRunnable) { return new Thread(theRunnable, "Thread-" + System.currentTimeMillis()); } } }
C
UTF-8
238
2.765625
3
[]
no_license
#include "../include/lexer.h" struct Token* lex(FILE *file) { struct Token * tokens = calloc(10, sizeof(struct Token)); tokens[0].type = INT; strcpy(tokens[0].string, "main"); printf("%d\n", tokens[0].type); return tokens; }
Python
UTF-8
330
3.828125
4
[ "MIT" ]
permissive
''' Probem Task: Create a function that takes a list and finds the integer which appears an odd number of times. Problem Link: https://edabit.com/challenge/9TcXrWEGH3DaCgPBs ''' def oddInteger(intList): xoredValue = intList[0] for ele in intList[1:]: xoredValue = (xoredValue ^ ele) return xoredValue
C++
UTF-8
1,428
2.875
3
[]
no_license
#include<stdio.h> #include<cstring> #include<fstream> #include<string> #include<iostream> using namespace std; int H, W; const int coverType[4][3][2] = { {{0,0},{1,0},{0,1}}, {{0,0},{0,1},{1,1}}, {{0,0},{1,0},{1,1}}, {{0,0},{1,0},{1,-1}} }; int board[20][20]; void getinfo() { string temp; memset(board, 0, sizeof(board)); scanf("%d %d", &H, &W); for(int i = 0; i < H; i++) { cin >> temp; for(int j = 0; j < W; j++) { if(temp[j] == '#') board[i][j] = 1; } } return; } bool set(int y, int x, int type, int delta) { bool ok = true; for(int i = 0; i < 3; i++) { const int ny = y + coverType[type][i][0]; const int nx = x + coverType[type][i][1]; if(ny < 0 || ny >= H || nx < 0 || nx >= W) ok = false; else if((board[ny][nx] += delta) > 1) ok = false; } return ok; } int cover() { int y = -1, x = -1; for(int i = 0; i < H; i++) { for(int j = 0; j< W; j++) { if(board[i][j] == 0) { y = i; x = j; break; } } if(y != -1) break; } if(y == -1) return 1; int ret = 0; for(int type = 0; type < 4; type++) { if(set(y, x, type, 1)) ret += cover(); set(y, x, type, -1); } return ret; } int solution() { int count = 0; for(int i = 0; i < H; i++) { for(int j = 0; j < W; j++) { count += cover(); } } return count; } int main() { int C; freopen("input.txt", "r", stdin); scanf("%d", &C); while(C--) { getinfo(); printf("%d\n", cover()); } }
C++
UTF-8
1,122
2.71875
3
[]
no_license
#ifndef __ZDNN_SOFTMAX__ #define __ZDNN_SOFTMAX__ #include "activate.h" namespace zdnn { class Softmax: public Activation { public: virtual void Activate(Node* node) { for (int col=0; col < node->batch_; col++) { // sum = sigma(exp(-x)) double sum = 0; double* temp_value = new double[node->dimension_]; for (int row=0; row < node->dimension_; row++) { int index = col * node->dimension_ + row; temp_value[row] = exp(-node->in_value_[index]); sum += temp_value[row]; } // exp(-x) / sum for (int row=0; row < node->dimension_; row++) { int index = col * node->dimension_ + row; node->out_value_[index] = temp_value[row] / sum; } delete [] temp_value; } } virtual void BackProp(Node* node) { for (int col=0; col < node->batch_; col++) { for (int row=0; row < node->dimension_; row++) { } } } protected: virtual void act_impl(Node* node, int index) { } virtual void backprop_impl(Node* node, int index) { } }; } #endif
Java
UTF-8
2,740
2.984375
3
[]
no_license
package parkinsonbenjamin.doglibrary.processor; import org.json.simple.JSONArray; import parkinsonbenjamin.doglibrary.dal.DoggoDal; import parkinsonbenjamin.doglibrary.dataobjects.Dog; import parkinsonbenjamin.doglibrary.dataobjects.User; import parkinsonbenjamin.doglibrary.dataobjects.Withdrawal; import parkinsonbenjamin.doglibrary.exceptions.DogException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class WithdrawalProcessor implements Processor { private DoggoDal dal; private final Map<Integer, User> usersById = new HashMap<>(); private final Map<Integer, Dog> dogsById = new HashMap<>(); public WithdrawalProcessor() { } @Override public void initialise(DoggoDal dal) throws DogException { this.dal = dal; initUserMap(); initDogMap(); initWithdrawals(); } private void initUserMap() throws DogException { usersById.clear(); List<User> allUsers = dal.getAllUsers(); for (User u : allUsers) { usersById.put(u.getUserId(), u); } } private void initDogMap() throws DogException { usersById.clear(); List<Dog> allDogs = dal.getAllDogs(); for (Dog d : allDogs) { dogsById.put(d.getDogId(), d); } } private void initWithdrawals() throws DogException { List<Withdrawal> currentWithdrawals = dal.getCurrentWithdrawals(); for (Withdrawal withdrawal : currentWithdrawals) { User user = getUser(withdrawal.getUserId()); user.withdrawDog(withdrawal.getDogId()); Dog dog = getDog(withdrawal.getDogId()); dog.withdraw(); } } private User getUser(int userId) throws DogException { User user = usersById.get(userId); if (user != null) return user; initUserMap(); user = usersById.get(userId); if (user == null) { throw new DogException(String.format("Unable to find User with Id: %d", userId)); } return user; } private Dog getDog(int dogId) throws DogException { Dog dog = dogsById.get(dogId); if (dog != null) return dog; initDogMap(); dog = dogsById.get(dogId); if (dog == null) { throw new DogException(String.format("Unable to find Dog with Id: %d", dogId)); } return dog; } public String getAllDogs() { Collection<Dog> dogs = dogsById.values(); JSONArray array = new JSONArray(); for (Dog d : dogs) { array.add(d.toJSONObject().toJSONString()); } return array.toJSONString(); } }
Java
UTF-8
2,081
2.78125
3
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.viajes.ejb; import co.edu.uniandes.csw.viajes.entities.OficinaEntity; import co.edu.uniandes.csw.viajes.persistence.OficinaPersistence; import java.util.List; import javax.inject.Inject; /** * * @author m.rodriguez21 */ public class OficinaLogic { /** * Variable para acceder a la persistencia de la aplicación. Es una * inyección de dependencias. */ @Inject private OficinaPersistence persistence; /** * Crear una nueva oficina * * @param entity Oficina que se quiere crear * @return La oficina creada */ public OficinaEntity createOficina(OficinaEntity entity) { persistence.create(entity); return entity; } /** * * Obtener todas las oficinas existentes en la base de datos. * * @return una lista de oficinas. */ public List<OficinaEntity> getOficinas() { List<OficinaEntity> oficinas = persistence.findAll(); return oficinas; } /** * * Obtener una oficina por medio de su id. * * @param id: id de la oficina para ser buscada. * @return la oficina solicitada por medio de su id. */ public OficinaEntity getOficina(Long id) { OficinaEntity oficina = persistence.find(id); return oficina; } /** * * Actualizar una oficina. * * * @param entity: oficina con los cambios para ser actualizada, por ejemplo * el nombre. * @return la oficina con los cambios actualizados en la base de datos. */ public OficinaEntity updateOficina(OficinaEntity entity) { OficinaEntity newEntity = persistence.update(entity); return newEntity; } /** * Borrar una oficina * * @param id: id de la oficina a borrar */ public void deleteOficina(Long id) { persistence.delete(id); } }
C++
UTF-8
2,414
2.859375
3
[]
no_license
#include "vex.h" using namespace vex; using namespace std; // defining variables float pi = 3.14159265359; const double wheelDiameter = 3.25; const float wheelCircumference = wheelDiameter * pi; const float turningDiameter = 18.0; // distance (in inches) from top-left wheel to bottom-right wheel const float gearRatio = 1; // 1 turn of the motor = 1 turn of the wheel const int AUTON_DRIVE_PCT = 50; //motor set to 50% power double kP = 0; double kI = 0; double kD = 0; double error; double prevError = 0; double totalError = 0; double derivative; void driveForward(float inches) { float inchesPerDegree = wheelCircumference / 360; float degrees = inches / inchesPerDegree; l.rotateFor(degrees * gearRatio, vex::rotationUnits::deg, AUTON_DRIVE_PCT, vex::velocityUnits::pct, false); // doesnt wait for completion (async) r.rotateFor(degrees * gearRatio, vex::rotationUnits::deg, AUTON_DRIVE_PCT, vex::velocityUnits::pct); // both functions run parallel } void Turn(float degrees) { // Note: +90 degrees is a right turn; -90 is a left turn float turningRatio = turningDiameter / wheelDiameter; float wheelDegrees = turningRatio * degrees; // Divide by two because each wheel provides half the rotation l.rotateFor(wheelDegrees * gearRatio / 2, vex::rotationUnits::deg, AUTON_DRIVE_PCT, vex::velocityUnits::pct); r.rotateFor(wheelDegrees * gearRatio / 2, vex::rotationUnits::deg, AUTON_DRIVE_PCT, vex::velocityUnits::pct); } void drivePID(double desiredValue, bool resetSensors) { while (true) { if (resetSensors == true) { resetSensors = false; l.setPosition(0, degrees); r.setPosition(0, degrees); } int RightFront = RightFrontMotor.position(degrees); int LeftFront = LeftFrontMotor.position(degrees); int RightRear = RightRearMotor.position(degrees); int LeftRear = LeftRearMotor.position(degrees); double averagePosition = (RightFront + LeftFront + RightRear + LeftRear)/2; error = averagePosition - desiredValue; derivative = error - prevError; totalError += error; double linearMotorPower = (error * kP + derivative * kD + totalError * kI); l.spin(fwd, linearMotorPower, voltageUnits::volt); r.spin(fwd, linearMotorPower, voltageUnits::volt); prevError = error; vex::task::sleep(20); } } void resetSensors() { l.setPosition(0, degrees); r.setPosition(0, degrees); }
C++
UTF-8
296
2.609375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ string str; cin>>str; char s=str[0]; int ans = 0, temp = 0; for(auto x: str){ if(s==x){ temp++; } else if(x!=s){ ans = max(ans, temp); temp = 1; s = x; } } ans = max(ans, temp); cout<<ans; return 0; }
Markdown
UTF-8
538
2.5625
3
[]
no_license
# MEAN-stack-and-Fusioncharts-MVC-application Simple MVC application using MEAN stack framework and Fusioncharts showing how we can visualize data by reading values from database. Make sure that you have following modules installed in the local node-modules folder: 1.body-parser 2.express 3.mongojs Values to be put in the database are provided in the .txt file present.you can use your values and change the code accordingly. Be sure that you have required modules in the node-modules folder. Make sure mongo mongod is running.
Java
UTF-8
512
1.789063
2
[]
no_license
package com.maz.store.model.delivery; import com.maz.store.model.customer.CustomerDto; import com.maz.store.model.order.OrderDto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor @Builder public class DeliveryDto implements Serializable { private static final long serialVersionUID = -975568898983791865L; private CustomerDto user; private OrderDto order; }
Python
UTF-8
6,374
2.765625
3
[ "MIT" ]
permissive
import pandas as pd import pyexcel_ods from datetime import datetime import math import numpy import utils import pathlib import sys import os def read_data(path): try: data = pd.read_excel(path, engine='odf') return data except Exception as excep: sys.stderr.write("'Não foi possível ler o arquivo: " + path + '. O seguinte erro foi gerado: ' + excep) os._exit(1) def parse_employees(file_name): rows = read_data(file_name).to_numpy() emps_clean = utils.treat_rows(rows) employees = {} curr_row = 0 for row in emps_clean: matricula = str(row[0]) nome = str(row[1]) cargo = str(row[2]) workplace = str(row[3]) remuneracao = row[4]+row[5] # REMUNERAÇÃO BÁSICA = Remuneração Cargo Efetivo + Outras Verbas Remuneratórias, Legais ou Judiciais total_indenizacao = row[11] cargo_confianca = row[6] grat_natalina = row[7] ferias = row[8] abono_permanencia = row[9] total_temporario = cargo_confianca + grat_natalina + ferias + abono_permanencia previdencia = abs(row[13]) teto_constitucional = abs(row[15]) imposto_de_renda = abs(row[14]) total_descontos = previdencia + teto_constitucional + imposto_de_renda total_bruto = total_indenizacao + total_temporario + remuneracao employees[row[0]] = { 'reg': matricula, 'name': nome, 'role': cargo, 'type': "membro", 'workplace': workplace, 'active': True, "income": { #Soma de todos os recebidos do funcionário 'total': round(total_bruto, 2), 'wage': round(remuneracao, 2), 'perks': { 'total': total_indenizacao, }, 'other': { # Gratificações e remuneraçoes temporárias 'total': round(total_temporario, 2), 'trust_position': cargo_confianca, 'others_total': round(grat_natalina + ferias + abono_permanencia, 2), 'others': { 'Gratificação Natalina': grat_natalina, 'Férias (1/3 constitucional)': ferias, 'Abono de Permanência': abono_permanencia, } }, }, 'discounts': { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts). 'total':round(total_descontos, 2), 'prev_contribution': previdencia , 'ceil_retention': teto_constitucional, 'income_tax': imposto_de_renda , } } return employees def update_employee_indemnity(file_name, employees): rows = read_data(file_name).to_numpy() emp_idemnity = utils.treat_rows(rows) for row in emp_idemnity: exists_employee = employees.get(row[0]) if exists_employee: ferias = row[4] alimentacao = row[5] creche = row[6] transporte = row[7] transporte_mobiliario = row[8] natalidade = row[9] ajuda_custo = row[10] moradia = row[11] pecunia = row[12] lp_pecunia = row[13] pericia_projeto = row[15] grat_exercicio_cumulativo = row[16] encargo_de_curso_concurso = row[17] grat_local_de_trabalho = row[18] hora_extra = row[20] adic_noturno = row[22] adic_atividade_penosa = row[23] adic_insalubridade = row[24] outras_verbas_remuneratorias = row[25] outras_verbas_retroativas = row[26] total_temporario = pericia_projeto + grat_exercicio_cumulativo + encargo_de_curso_concurso + grat_local_de_trabalho + hora_extra + adic_noturno + adic_atividade_penosa + adic_insalubridade + outras_verbas_remuneratorias + outras_verbas_retroativas emp = employees[row[0]] emp['income'].update({ 'total': round(emp['income']['total'] + total_temporario,2) }) emp['income']['perks'].update({ 'total': round(sum(row[4:14]),2), 'vacation': ferias, 'food': alimentacao, 'pre_school': creche, 'transportation': transporte, 'furniture_transport': transporte_mobiliario, 'birth_aid': natalidade, 'subsistence': ajuda_custo , 'housing_aid': moradia , 'pecuniary': pecunia, 'premium_license_pecuniary': lp_pecunia, }) emp['income']['other'].update({ 'total': round(emp['income']['other']['total'] + total_temporario, 2), 'others_total': round(emp['income']['other']['others_total'] + total_temporario, 2), }) emp['income']['other']['others'].update({ 'Gratificação de Perícia e Projeto':pericia_projeto, 'Gratificação Exercício Cumulativo de Ofício': grat_exercicio_cumulativo, 'Gratificação Encargo de Curso e Concurso': encargo_de_curso_concurso, 'Gratificação Local de Trabalho': grat_local_de_trabalho, 'Hora Extra': hora_extra, 'Adicional Noturno': adic_noturno, 'Adicional Atividade Penosa': adic_atividade_penosa, 'Adicional Insalubridade': adic_insalubridade, 'Outras Verbas Remuneratórias': outras_verbas_remuneratorias, 'Outras Verbas Remuneratórias Retroativas/Temporárias': outras_verbas_retroativas, }) employees[row[0]] = emp else: continue return employees def parse(file_names): employees = {} for fn in file_names: if 'Verbas Indenizatorias' not in fn: # Puts all parsed employees in the big map employees.update(parse_employees(fn)) for fn in file_names: if 'Verbas Indenizatorias' in fn: update_employee_indemnity(fn, employees) return list(employees.values())
Java
UTF-8
2,133
2.265625
2
[]
no_license
package com.chanjet.ccs.ccp.base.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import com.chanjet.ccs.base.entity.BaseEntity; //TODO MEMO 修改了createTime,原先是time,及表中的create_time @Entity @Table(name = "t_report") public class Report extends BaseEntity { private int specialNo; // 特服号码 private String tel; // 手机号 private String identifier; // 唯一标识 private String state; // 状态(接收成功:返回DELIVRD或者0 接收失败:其他值) private String createTime; // 创建时间 private int num; // 编号 private int proxyId; // 代理通道id public Report(int id, int specialNo, String tel, String identifier, String state, String createTime, int num, int proxyId) { this.id = id; this.specialNo = specialNo; this.tel = tel; this.identifier = identifier; this.state = state; this.createTime = createTime; this.num = num; this.proxyId = proxyId; } public Report() { } @Column(name = "special_no") public int getSpecialNo() { return specialNo; } public void setSpecialNo(int specialNo) { this.specialNo = specialNo; } @Column(name = "tel") public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } @Column(name = "identifier") public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } @Column(name = "state") public String getState() { return state; } public void setState(String state) { this.state = state; } @Column(name = "create_time") public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } @Column(name = "num") public int getNum() { return num; } public void setNum(int num) { this.num = num; } @Column(name = "proxy_id") public int getProxyId() { return proxyId; } public void setProxyId(int proxyId) { this.proxyId = proxyId; } }
Java
UTF-8
8,391
2.3125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package autores.controladores; import autores.modelos.Alumno; import interfaces.IControladorAMAlumno; import autores.modelos.GestorAutores; import autores.modelos.ModeloTablaGrupos; import autores.vistas.VentanaAAlumno; import autores.vistas.VentanaMAlumno; import auxiliares.Apariencia; import interfaces.IGestorAutores; import java.awt.Dialog; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import javax.swing.JOptionPane; import javax.swing.JTable; public class ControladorMAlumno implements IControladorAMAlumno { private VentanaMAlumno ventana; // private VentanaAAlumno ventanaAlta; private Alumno alumno; /** * Constructor * @param ventanaPadre (VentanaAutores en este caso) */ // public ControladorMAlumno(Dialog ventanaPadre) { // this(ventanaPadre, null); // } /** * Constructor * @param ventanaPadre (VentanaAutores en este caso) * @param alumno alumno a modificar */ public ControladorMAlumno(Dialog ventanaPadre, Alumno alumno) { this.alumno = alumno; // this.ventana = new VentanaMAlumno(this, ventanaPadre); // this.ventana.setTitle(this.alumno == null ? TITULO_NUEVO : TITULO_MODIFICAR); // this.ventana.setLocationRelativeTo(null); // Apariencia.asignarNimbusLookAndFeel("Nimbus"); // if (this.alumno == null) { //nuevo alumno // this.ventanaAlta = new VentanaAAlumno(this, ventanaPadre); // this.ventanaAlta.setTitle(TITULO_NUEVO); // this.ventanaAlta.setLocationRelativeTo(null); // this.configurarTabla(new ModeloTablaGrupos()); //// this.ventana.verTablaGrupos().setEnabled(false); // this.ventanaAlta.setVisible(true); // } // else { //modificación de alumno this.ventana = new VentanaMAlumno(this, ventanaPadre); this.ventana.setTitle(TITULO_MODIFICAR); this.ventana.setLocationRelativeTo(null); this.ventana.verTxtDNI().setText(Integer.toString(this.alumno.verDNI())); this.ventana.verTxtDNI().setEditable(false); this.ventana.verTxtApellidos().setText(this.alumno.verApellidos()); this.ventana.verTxtApellidos().requestFocus(); this.ventana.verTxtApellidos().selectAll(); // no funciona this.ventana.verTxtNombres().setText(this.alumno.verNombres()); this.ventana.verTxtCX().setText(this.alumno.verCX()); this.ventana.verPassClave().setText(this.alumno.verClave()); this.ventana.verPassRepetirClave().setText(this.alumno.verClave()); this.configurarTabla(new ModeloTablaGrupos(this.alumno)); this.ventana.setVisible(true); // } // this.ventana.setVisible(true); } /** * Configura la tabla de grupos asignándole un modelo y seleccionando la primera fila (si hay filas) * @param mtg modelo para la tabla de grupos */ private void configurarTabla(ModeloTablaGrupos mtg) { JTable tablaGrupos = this.ventana.verTablaGrupos(); tablaGrupos.setModel(mtg); } @Override public void btnGuardarClic(ActionEvent evt) { int dni = 0; if (!this.ventana.verTxtDNI().getText().trim().isEmpty()) dni = Integer.parseInt(this.ventana.verTxtDNI().getText().trim()); String apellidos = this.ventana.verTxtApellidos().getText().trim(); String nombres = this.ventana.verTxtNombres().getText().trim(); String cx = this.ventana.verTxtCX().getText().trim(); String clave = new String(this.ventana.verPassClave().getPassword()); String claveRepetida = new String(this.ventana.verPassRepetirClave().getPassword()); // if (this.alumno == null) //nuevo alumno // this.nuevoAlumno(dni, apellidos, nombres, cx, clave, claveRepetida); // else //modificar alumno this.modificarAlumno(apellidos, nombres, cx, clave, claveRepetida); } /** * Se encarga de la creación de un alumno * @param dni dni del alumno * @param apellidos apellidos del alumno * @param nombres nombres del alumno * @param cx cx del alumno * @param clave clave del alumno * @param claveRepetida clave (repetida) del alumno */ // private void nuevoAlumno(int dni, String apellidos, String nombres, String cx, String clave, String claveRepetida) { // IGestorAutores ga = GestorAutores.instanciar(); // String resultado = ga.nuevoAutor(dni, apellidos, nombres, cx, clave, claveRepetida); // if (!resultado.equals(IGestorAutores.EXITO)) // JOptionPane.showMessageDialog(null, resultado, TITULO_NUEVO, JOptionPane.ERROR_MESSAGE); // else // this.ventana.dispose(); // } /** * Se encarga de la modificación del alumno * @param apellidos apellidos del alumno * @param nombres nombres del alumno * @param cx cx del alumno * @param clave clave del alumno * @param claveRepetida clave (repetida) del alumno */ private void modificarAlumno(String apellidos, String nombres, String cx, String clave, String claveRepetida) { IGestorAutores ga = GestorAutores.instanciar(); String resultado = ga.modificarAutor(this.alumno, apellidos, nombres, cx, clave, claveRepetida); if (!resultado.equals(IGestorAutores.EXITO)) JOptionPane.showMessageDialog(null, resultado, TITULO_MODIFICAR, JOptionPane.ERROR_MESSAGE); else this.ventana.dispose(); } @Override public void btnCancelarClic(ActionEvent evt) { this.ventana.dispose(); } @Override public void txtDocumentoPresionarTecla(KeyEvent evt) { char c = evt.getKeyChar(); if (!Character.isDigit(c)) { //sólo se aceptan los dígitos del 0-9, Enter, Del y Backspace switch(c) { case KeyEvent.VK_ENTER: this.btnGuardarClic(null); //no importa el evento en este caso break; case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: break; default: evt.consume(); //consume el evento para que no sea procesado por la fuente } } } @Override public void txtCXPresionarTecla(KeyEvent evt) { this.txtDocumentoPresionarTecla(evt); } @Override public void txtNombresPresionarTecla(KeyEvent evt) { this.txtApellidosPresionarTecla(evt); } @Override public void txtApellidosPresionarTecla(KeyEvent evt) { char c = evt.getKeyChar(); if (!Character.isLetter(c)) { //sólo se aceptan letras, Enter, Del, Backspace y espacio switch(c) { case KeyEvent.VK_ENTER: this.btnGuardarClic(null); //no importa el evento en este caso break; case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: case KeyEvent.VK_SPACE: break; default: evt.consume(); //consume el evento para que no sea procesado por la fuente } } } @Override public void passClavePresionarTecla(KeyEvent evt) { if (evt.getKeyChar() == KeyEvent.VK_ENTER) this.btnGuardarClic(null); } @Override public void passRepetirClavePresionarTecla(KeyEvent evt) { this.passClavePresionarTecla(evt); } @Override public void ventanaObtenerFoco(WindowEvent evt) { if (this.alumno != null) { this.configurarTabla(new ModeloTablaGrupos(this.alumno)); //se refrezca la tabla } //se hace esta comprobación para actualizar la tabla sólo en el caso que se esté modificando un alumno //y se esté volviendo de la ventana para agregar grupos } }
C#
UTF-8
7,831
2.515625
3
[ "MIT" ]
permissive
// This file is part of SharpNEAT; Copyright Colin D. Green. // See LICENSE.txt for details. namespace SharpNeat.Neat.Reproduction.Asexual.Strategy; /// <summary> /// A NEAT genome asexual reproduction strategy based on deletion of a single connection. /// </summary> /// <typeparam name="T">Connection weight data type.</typeparam> /// <remarks> /// Offspring genomes are created by taking a clone of a single parent genome and deleting a single /// connection, if possible. /// </remarks> public sealed class DeleteConnectionStrategy<T> : IAsexualReproductionStrategy<T> where T : struct { readonly INeatGenomeBuilder<T> _genomeBuilder; readonly Int32Sequence _genomeIdSeq; readonly Int32Sequence _generationSeq; #region Constructor /// <summary> /// Construct a new instance. /// </summary> /// <param name="genomeBuilder">NeatGenome builder.</param> /// <param name="genomeIdSeq">Genome ID sequence; for obtaining new genome IDs.</param> /// <param name="generationSeq">Generation sequence; for obtaining the current generation number.</param> public DeleteConnectionStrategy( INeatGenomeBuilder<T> genomeBuilder, Int32Sequence genomeIdSeq, Int32Sequence generationSeq) { _genomeBuilder = genomeBuilder; _genomeIdSeq = genomeIdSeq; _generationSeq = generationSeq; } #endregion #region Public Methods /// <inheritdoc/> public NeatGenome<T>? CreateChildGenome(NeatGenome<T> parent, IRandomSource rng) { // We require at least two connections in the parent, i.e. we avoid creating genomes with // no connections, which would be pointless. if(parent.ConnectionGenes.Length < 2) return null; // Select a gene at random to delete. var parentConnArr = parent.ConnectionGenes._connArr; var parentWeightArr = parent.ConnectionGenes._weightArr; int parentLen = parentConnArr.Length; int deleteIdx = rng.Next(parentLen); // Create the child genome's ConnectionGenes object. int childLen = parentLen - 1; var connGenes = new ConnectionGenes<T>(childLen); var connArr = connGenes._connArr; var weightArr = connGenes._weightArr; // Copy genes up to deleteIdx. Array.Copy(parentConnArr, connArr, deleteIdx); Array.Copy(parentWeightArr, weightArr, deleteIdx); // Copy remaining genes (if any). Array.Copy(parentConnArr, deleteIdx+1, connArr, deleteIdx, childLen-deleteIdx); Array.Copy(parentWeightArr, deleteIdx+1, weightArr, deleteIdx, childLen-deleteIdx); // Get an array of hidden node IDs. var hiddenNodeIdArr = GetHiddenNodeIdArray(parent, deleteIdx, connArr); // Create and return a new genome. return _genomeBuilder.Create( _genomeIdSeq.Next(), _generationSeq.Peek, connGenes, hiddenNodeIdArr); } #endregion #region Private Static Methods /// <summary> /// Get an array of hidden node IDs in the child genome. /// </summary> private static int[] GetHiddenNodeIdArray( NeatGenome<T> parent, int deleteIdx, DirectedConnection[] childConnArr) { // Determine which hidden nodes in the parent have been deleted, i.e. are not in the child. (int? nodeId1, int? nodeId2) = GetDeletedNodeIds(parent, deleteIdx, childConnArr); if(!nodeId1.HasValue && !nodeId2.HasValue) { // The connection deletion resulted in no hidden nodes being deleted, therefore we can re-use // the parent's hidden node ID array. return parent.HiddenNodeIdArray; } // Determine the length of the new ID array, and allocate memory. int childLen = parent.HiddenNodeIdArray.Length; if(nodeId1.HasValue && nodeId2.HasValue) childLen -= 2; else childLen--; int[] childIdArr = new int[childLen]; // Copy the parent's hidden node IDs, except the removed IDs. int[] parentIdArr = parent.HiddenNodeIdArray; for(int parentIdx=0, childIdx=0; parentIdx < parentIdArr.Length; parentIdx++) { int nodeId = parentIdArr[parentIdx]; if(nodeId != nodeId1 && nodeId != nodeId2) childIdArr[childIdx++] = parentIdArr[parentIdx]; } return childIdArr; } /// <summary> /// Determine the set of hidden node IDs that have been deleted as a result of a connection deletion. /// I.e. a node only exists if a connection connects to it, therefore if there are no other connections /// referring to a node then it has been deleted, with the exception of input and output nodes that /// always exist. /// </summary> private static (int? nodeId1, int? nodeId2) GetDeletedNodeIds( NeatGenome<T> parent, int deleteIdx, DirectedConnection[] childConnArr) { // Get the two node IDs referred to by the deleted connection. int? nodeId1 = parent.ConnectionGenes._connArr[deleteIdx].SourceId; int? nodeId2 = parent.ConnectionGenes._connArr[deleteIdx].TargetId; // Set IDs to null for input/output nodes (these nodes are fixed and therefore cannot be deleted). // Also, for cyclic networks nodeId1 and 2 could refer to the same node (a cyclic connection on the same node), if // so then we don't need to set nodeId2. if(nodeId1.Value < parent.MetaNeatGenome.InputOutputNodeCount) nodeId1 = null; if(nodeId2.Value < parent.MetaNeatGenome.InputOutputNodeCount || nodeId1 == nodeId2) nodeId2 = null; if(!nodeId1.HasValue && !nodeId2.HasValue) return (null, null); if(!nodeId1.HasValue) { // 'Shuffle up' nodeId2 into nodeId1. nodeId1 = nodeId2; nodeId2 = null; } if(!nodeId2.HasValue) { if(!IsNodeConnectedTo(childConnArr, nodeId1!.Value)) return (nodeId1.Value, null); return (null, null); } (bool,bool) isConnectedTuple = AreNodesConnectedTo(childConnArr, nodeId1!.Value, nodeId2.Value); if(!isConnectedTuple.Item1 && !isConnectedTuple.Item2) return (nodeId1.Value, nodeId2.Value); if(!isConnectedTuple.Item1) return (nodeId1.Value, null); if(!isConnectedTuple.Item2) return (nodeId2.Value, null); return (null, null); } /// <summary> /// Is nodeId referred to by any of the connections in connArr. /// </summary> private static bool IsNodeConnectedTo(DirectedConnection[] connArr, int nodeId) { // Is nodeId referred to by any of the connections in connArr. foreach(var conn in connArr) { if(conn.SourceId == nodeId || conn.TargetId == nodeId) return true; } return false; } /// <summary> /// Are nodeId1 and nodeId2 connected to by any of the connections in connArr. /// </summary> private static (bool isNode1Connected, bool isNode2Connected) AreNodesConnectedTo(DirectedConnection[] connArr, int nodeId1, int nodeId2) { bool id1Used = false; bool id2Used = false; foreach(var conn in connArr) { if(conn.SourceId == nodeId1 || conn.TargetId == nodeId1) { id1Used = true; if(id2Used) break; } if(conn.SourceId == nodeId2 || conn.TargetId == nodeId2) { id2Used = true; if(id1Used) break; } } return (id1Used, id2Used); } #endregion }
PHP
UTF-8
1,062
2.8125
3
[]
no_license
<?php // Variables $from = htmlspecialchars($_POST["email"]); $to = "solen-jini@hotmail.fr"; $subject = htmlspecialchars($_POST["subject"]); $message = htmlspecialchars($_POST["message"]); // Saut de ligne if (!preg_match("#^[a-z0-9._-]+@(hotmail|live|msn).[a-z]{2,4}$#", $to)) { $br = "\r\n"; } else { $br = "\n"; } // Boundary $boundary = "-----=".md5(rand()); // En-tête $header = 'From:'.$from.$br; $header.= 'Reply-to:'.$from.$br; $header.= "MIME-Version: 1.0".$br; $header.= 'Content-Type: multipart/alternative;'.$br.' boundary='.$br; // Corps du message $mail = $br."--".$boundary.$br; // ouverture du boundary $mail.= "Content-Type: text/plain; charset=\"ISO-8859-1\"".$br; // message en texte et non HTML $mail.= "Content-Transfer-Encoding: 8bit".$br; // encodé en 8 bits, donc avec les accents $mail.= $br.$message.$br; // message lui-même $mail.= $br."--".$boundary."--".$br; // fermeture du boundary // Envoi du mail $bool = mail($to,$subject,$message,$header); ?> <meta http-equiv="refresh" content="0;<?php echo 'home.php?bool='.$bool; ?>'" />
Java
UTF-8
360
1.9375
2
[]
no_license
package com.WiltonZhan.leetcode.l657RobotReturnToOrigin; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class SolutionTest { private final Solution solution = new Solution(); @Test void judgeCircle() { assertTrue(solution.judgeCircle("UD")); assertFalse(solution.judgeCircle("LL")); } }
C++
UTF-8
968
3.296875
3
[]
no_license
#include <iostream> using namespace std; int main() { char respuesta; int cont_A=0, cont_B=0, cont_C=0; cout<<"PARTIDOS CANDIDATOS\n" <<" A. Partido A.\n" <<" B. Partido B.\n" <<" C. Partido C.\n" <<"Voto (fin -> F): "; cin>>respuesta; cout<<endl; while(respuesta!='F' && respuesta!='f') { switch(respuesta) { case 'a': case 'A': cont_A++;break; case 'b': case 'B': cont_B++;break; case 'c': case 'C': cont_C++;break; default:cout<<"Voto nulo.\n"<<endl; } cout<<"PARTIDOS CANDIDATOS\n" <<" A. Partido A.\n" <<" B. Partido B.\n" <<" C. Partido C.\n" <<"Voto (fin -> F): "; cin>>respuesta; cout<<endl; } cout<<"Votos para el partido A: "<<cont_A<<endl; cout<<"Votos para el partido B: "<<cont_B<<endl; cout<<"Votos para el partido C: "<<cont_C<<endl; }
JavaScript
UTF-8
2,712
2.515625
3
[]
no_license
import "./ProjectItem.css"; import DemoModal from "./DemoModal"; import { useState } from "react"; function ProjectItem(props){ const [showDemoModal, setShowDemoModal] = useState(false); const [demoIframe, setDemoIframe] = useState("<iframe></iframe>"); function handleMouseEnter(e){ let element = e.target.querySelector(".projectDetails"); element.style.visibility = "visible"; element.style.opacity = 1; } function handleMouseLeave(e){ hideProjectHovers(); } function hideProjectHovers(){ document.querySelectorAll(".projectDetails").forEach((element) => { element.style.visibility = "hidden"; element.style.opacity = 0; }) } function handleVideoClick(url){ setShowDemoModal(true); setDemoIframe(url); } function handleLiveClick(url){ setShowDemoModal(true); setDemoIframe(url); } function handleNewTabClick(url){ window.open(url, '_blank').focus(); } function handleModalClose(){ setShowDemoModal(false) hideProjectHovers(); } return <div onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} className="projectItem"> <img alt="Project thumbnail" className="thumbnail" src={props.projectObject.cover}></img> <div className="projectDetails"> <div className="description">{props.projectObject.description}</div> <div className="demo"> { props.projectObject.demos.find((item) => item.name == "video") ? <div className="video" onClick={() => { handleVideoClick(props.projectObject.demos.find((item) => item.name == "video").link) }}>Video</div> : null } { props.projectObject.demos.find((item) => item.name == "live") ? <> <div className="live" onClick={() => { handleLiveClick(props.projectObject.demos.find((item) => item.name == "live").link) }}>Live</div> <div className="newTab" onClick={() => { handleNewTabClick(props.projectObject.demos.find((item) => item.name == "live").link) }}>New Tab</div> </> : null } </div> </div> { showDemoModal ? <DemoModal onClose={() => { handleModalClose() }} iframe={demoIframe} /> : null } </div> } export default ProjectItem;
C++
UTF-8
1,028
3.21875
3
[]
no_license
#include <iostream> #include <cstdlib> #include "mylist.h" using namespace std; #define TAB "\t" List<int>* make_list(int amount) { List<int> *l = new List<int>(amount+1); for(int i = 0; i < amount; i++){ l->insert(rand()); } return l; } int main(int argc, char **argv){ List<int> *l; int repeats; int num_search, num_insert, num_delete; cout << "Amount" TAB "Search" TAB "Insert" TAB "Delete" << endl; for (int i = 100; i <= 10000; i+=100) { l = make_list(i); repeats = 100 + rand() % 100; num_search = num_insert = num_delete = 0; for(int j=0; j < repeats; j++) { l->has_value(rand()); num_search+= l->get_seek_num(); l->insert(rand() % i, 0); num_insert+= l->get_seek_num(); l->delete_by_number(rand() % i); num_delete+= l->get_seek_num(); } num_search = num_search / repeats; num_insert = num_insert / repeats; num_delete = num_delete / repeats; cout << i << TAB << num_search << TAB << num_insert << TAB << num_delete << endl; } return 0; }
Markdown
UTF-8
8,249
2.53125
3
[ "MIT" ]
permissive
# trailpack [![Gitter][gitter-image]][gitter-url] [![NPM version][npm-image]][npm-url] [![Build status][ci-image]][ci-url] [![Dependency Status][daviddm-image]][daviddm-url] [![Code Climate][codeclimate-image]][codeclimate-url] [![Follow @trailsjs on Twitter][twitter-image]][twitter-url] Trailpack Interface. Trailpacks extend the capability of the Trails framework. (**Application functionality** should be extended using Services). ## Usage This class should be extended by all trailpacks. Override the trailpack API methods. ```js const Trailpack = require('trailpack') class ExampleTrailpack extends Trailpack { /** * Configure the lifecycle of this trailpacks. */ get lifecycle () { return { initialize: { /** * Only initialize this trailpack after trailpack-router has been * initialized. */ listen: [ 'trailpack:router:initialize' ] } } } validate () { if (!this.app.config.example) throw new Error('config.example not set!') } configure () { this.app.config.example.happy = true } async initialize () { this.interval = setInterval(() => { this.log.debug('happy?', this.app.config.example.happy) }, 1000) } async unload () { clearInterval(this.interval) } constructor (app) { super(app, { config: require('./config'), api: require('./api'), pkg: require('./package') }) } } ``` ## API ### Boot Lifecycle 0. [`trails:start`](https://github.com/trailsjs/trails/blob/master/index.js#L72) (event) 1. [`validate()`](https://github.com/trailsjs/trailpack/blob/master/index.js#L54-L61) 2. [`configure()`](https://github.com/trailsjs/trailpack/blob/master/index.js#L63-L70) 3. [`initialize()`](https://github.com/trailsjs/trailpack/blob/master/index.js#L72-L78) 4. [`trails:ready`](https://github.com/trailsjs/trails/blob/master/lib/trailpack.js#L38) ### Properties #### `log` Provides convenient access to the Trails logger. (e.g. `this.log.debug('hello')`) #### `packs` Access the application's loaded Trailpacks. This is a mapping of name -> Trailpack. (e.g. `this.packs.core`) #### `on`, `once`, `emit`, `after` Emit/Listen for events on the Trails EventEmitter. Convenience methods for `this.app.on`, `this.app.once`, etc. (e.g. `this.emit('custom:event')`) ### Methods #### `constructor(app, definition)` Instantiate the Trailpack. `definition` is an object which contains three optional properties: `config`, `api`, `pkg`. Trailpack configuration is merged into the application configuration. #### `validate()` Validate the preconditions for proper functioning of this trailpack. For example, if this trailpack requires that a database is configured in `config/database.js`, this method should validate this. This method should incur no side-effects. *Do not alter any extant configuration.* #### `configure()` Alter/Extend the configuration (`app.config`) of the application, or add new sections to the config object for the trailpack. This method is run before the application is loaded -- after validate, and before initialize. Trails does not allow further configuration changes after this lifecycle stage is complete. #### `initialize()` If you need to bind any event listeners, start servers, connect to databases, all of that should be done in initialize. The app's configuration is guaranteed to be loaded and finalized before this stage. #### `unload()` Cleaup any resources/daemons started by this Trailpack. Used by [trailpack-autoreload](https://github.com/trailsjs/trailpack-autoreload) and other system tools to cleanly release resources in order to shutdown/restart the Trails application. ### Types The trailpack `type` is used to distinguish between Trailpacks by the role they perform in the application. It is also used by developer tools such as [Trailmix](https://github.com/trailsjs/trailsmix) #### `system` These trailpacks provide critical framework-level functionality that most/all other trailpacks will depend on, such as [`core`](https://github.com/trailsjs/trailpack-core) and [`router`](https://github.com/trailsjs/trailpack-router). ```js const SystemTrailpack = require('trailpack/system') module.exports = class HapiTrailpack extends SystemTrailpack { } ``` #### `server` These allow you to use various node.js web server frameworks with Trails, such as [`express`](https://github.com/trailsjs/trailpack-express4), [`hapi`](https://github.com/trailsjs/trailpack-hapi), and [`koa`](https://github.com/trailsjs/trailpack-koa). Typically, only one server pack will be installed in a Trails Application. ```js const ServerTrailpack = require('trailpack/server') module.exports = class HapiTrailpack extends ServerTrailpack { } ``` #### `datastore` Datastore trailpacks provide a unified way to configure various persistence stores. These may be ORMs, query builders, or database drivers. Examples include [`knex`](https://github.com/trailsjs/trailpack-knex), [`graphql`](https://github.com/trailsjs/trailpack-graphql) and [`waterline`](https://github.com/trailsjs/trailpack-waterline). Typically, only one datastore pack will be installed in a Trails Application. ```js const DatastoreTrailpack = require('trailpack/datastore') module.exports = class KnexTrailpack extends DatastoreTrailpack { } ``` #### `tool` Every application needs a suite of tools for development, debugging, monitoring, etc. These trailpacks integrate various modules with Trails to provide a richer developer experience. Some tool packs include [`autoreload`](https://github.com/trailsjs/trailpack-autoreload), [`webpack`](https://github.com/trailsjs/trailpack-webpack), [`repl`](https://github.com/trailsjs/trailpack-repl). Trails Application logic will typically not rely on these trailpacks directly. ```js const ToolTrailpack = require('trailpack/tool') module.exports = class WebpackTrailpack extends ToolTrailpack { } ``` #### `extension` Extension packs exist to augment, or extend, the functionality of other trailpacks or existing framework logic. For example, [`footprints`](https://github.com/trailsjs/trailpack-footprints) provides a standard interface between `server` and `datastore` trailpacks. [`realtime`](https://github.com/trailsjs/trailpack-realtime) adds additional functionality to a server. [`sails`](https://github.com/trailsjs/trailpack-sails) lets you plugin an entire sails project directly into a Trails Application. [`bootstrap`](https://github.com/trailsjs/trailpack-bootstrap) extends the Trails boot process so that a custom method can be run during application startup. ```js const ExtensionTrailpack = require('trailpack/extension') module.exports = class FootprintsTrailpack extends ExtensionTrailpack { } ``` #### `misc` All trailpacks that don't fit previous types. ```js const Trailpack = require('trailpack') module.exports = class ExampleTrailpack extends Trailpack { } ``` ### Documentation - [**Trailpack Implementation Guide**](https://trailsjs.io/doc/en/ref/trailpack) - [**API Reference**](https://trailsjs.io/doc/en/extend/trailpack) ## Contributing We love contributions! Please see our [Contribution Guide](https://github.com/trailsjs/trails/blob/master/.github/CONTRIBUTING.md) for more information. ## License [MIT](https://github.com/trailsjs/trailpack/blob/master/LICENSE) <img src="http://i.imgur.com/dCjNisP.png"> [npm-image]: https://img.shields.io/npm/v/trailpack.svg?style=flat-square [npm-url]: https://npmjs.org/package/trailpack [ci-image]: https://img.shields.io/travis/trailsjs/trailpack/master.svg?style=flat-square [ci-url]: https://travis-ci.org/trailsjs/trailpack [daviddm-image]: http://img.shields.io/david/trailsjs/trailpack.svg?style=flat-square [daviddm-url]: https://david-dm.org/trailsjs/trailpack [codeclimate-image]: https://img.shields.io/codeclimate/github/trailsjs/trailpack.svg?style=flat-square [codeclimate-url]: https://codeclimate.com/github/trailsjs/trailpack [gitter-image]: http://img.shields.io/badge/+%20GITTER-JOIN%20CHAT%20%E2%86%92-1DCE73.svg?style=flat-square [gitter-url]: https://gitter.im/trailsjs/trails [twitter-image]: https://img.shields.io/twitter/follow/trailsjs.svg?style=social [twitter-url]: https://twitter.com/trailsjs
Markdown
UTF-8
4,620
2.90625
3
[]
no_license
### 统一配置管理 > 思路: zk 节点存储配置信息, 配置信息修改,通知客户端更新配置. > 实现: spring 可通过自定义 ConfigurableEnvironment 接口实现, 自定义propertySource接口实现 ### 同步互斥功能. - barrier > 多个进程需要等到某一条件满足时,才能开始执行. 如两个任务之间有先后关系,可以考虑使用 实现流程: 1. 首先有个/barrier 的根节点.每个需要同步协同的进程都监听这个根节点 2. 每个进程都创建子节点然后 同步等待 (Object.wait), 3. 因为其他的进程也是同样的操作(创建子节点), 故每个进程会接收到通知, 收到通知后判断/barrier 下的子节点是否满足了固定数目 4. 如果满足,则 notify 开始执行. 执行完删除自己之前创建的子节点. 应用实例: 1. 假想实例: 机器a,b,c 分别部署了三个服务ServiceA, ServiceB, ServiceC. ServiceA 需要 ServiceB, ServiceC 都完成后才能进行. 这个时候就可以使用 barrier. - double barrier > 可以想象 双重barrier 就是在barrier 4 步的基础上, 再加个相似的步骤,如下 实现流程: 1. 首先有个/barrier 的根节点.每个需要同步协同的进程都监听这个根节点 2. 每个进程都创建子节点然后 同步等待 (Object.wait), 3. 因为其他的进程也是同样的操作(创建子节点), 故每个进程会接收到通知, 收到通知后判断/barrier 下的子节点是否满足了固定数目 4. 如果满足,则 notify 开始执行. 执行完删除自己之前创建的子节点. 5. 删除完节点后,每个process 继续 wait. 6. 删除节点会收到监听, 如果根节点下的子节点都没了,那就代表全部进程都执行完毕了, 这时再notify ### lock zk lock 实现流程: 1. 各个process 创建序列化临时节点.返回序列号名 2. 获取根节点下所有子节点及其序列号 3. 如自己的序列号是最小的及获得锁. 否则wait.并再之前序列最小的节点上添加监听. 监听节点删除,则notifyAll 4. 释放锁,删除掉锁节点即可. 注意点: 1. 锁应该具有超时时间, 如果长时间未被解锁应该自动解锁. 2. 锁应该是可重入的, 避免死锁. 故获取锁时应该保留当前线程信息 其他方式 - 基于数据库 mysql for update. - 基于缓存 redis.setnx ### TX ### 选举 方法一 1. 初始化节点 比如 (/election) 2. 每个服务节点 在 /election 路径下添加监听 3. 每个服务节点乐观的 同时在 /election 根节点下创建同名的 数据临时节点. 如 /leader(noden.example.com) 4. 因为 节点名是相同的 故 同一时刻只有一个节点能够创建成功. 创建成功的即为 leader 节点. 5. 因为都已经添加了监听. leader 节点创建后,每个子节点都会收到 创建的 leader节点信息. 并各自保存. 6. 如果leader挂掉了, zk与leader节点的session断掉, 那对应的临时节点也就被zk删掉了.其他节点收到通知,重新执行3步骤(重新争夺leader节点),5步骤(更新leader节点信息) > 缺点: 乐观争夺创建leader节点,容易造成竞争. 不适用于节点多的情况. 方法二 > 改进思路: 不在每次 leader 挂掉的时候通知所有节点竞争成为leader,而是必要的时候再重新选举,减少竞争 1. 初始化节点 比如 (/election) 2. 每个服务节点 在 /election 路径下添加监听 3. 每个服务节点 在 /election 路劲下添加 **临时序列** 类型节点, 如(/leader-00001, /leader-00002) 4. 节点通过查询命令, 查询/election 下序列最小的节点即为leader 节点. 5. leader 挂掉的时候,节点接收通知依次获取当前最小的节点 为 leader 节点. 如 /leader-00001挂掉, 那个接下来就是/leader-00002 为leader节点 6. 如果所有都挂掉的话(即查询根节点, 没有/leader-000x节点),则重新 执行 **步骤3** ### HA部署 其实也是 选举 功能的一种运用, 多个服务实例再zk里面注册一下, 断掉的话,临时节点被删除,监听到删除后. 新的服务实例重新作为服务节点. ### zk 的其他问题 1. 为何需要奇数节点而不是优选偶数节点 相近奇数节点树和偶数节点数的稳定性是一样的.主要考虑到资源节省. zk有个半数存活特点,即zk集群半数以上机器可用时,这个集群就是稳定的. ### A&Q A: 获取锁后如果连接丢失,curator 如何处理锁的. Q: 丢失连接是添加监听,自己处理. 类似于java 的 interrupted 机制. 这种情况是需要引用端代码考虑的
C++
UTF-8
986
3.234375
3
[]
no_license
// https://leetcode.com/problems/path-sum-iii/ // 437. Path Sum III #include <bits/stdc++.h> using namespace std; #include "../utils/BinaryTree.h" #include "../utils/Graph.h" #include "../utils/LinkedList.h" #include "../utils/Util.h" class Solution { public: int pathSum(TreeNode *root, int sum) { if (!root) return 0; map<int, int> cnt = {{0, 1}}; int ret = 0; dfs(root, sum, cnt, 0, ret); return ret; } void dfs(TreeNode *root, int sum, map<int, int> &cnt, int ps, int &ret) { ps += root->val; if (cnt.count(ps-sum) > 0) { ret += cnt.at(ps-sum); } cnt[ps]++; if (root->left) dfs(root->left, sum, cnt, ps, ret); if (root->right) dfs(root->right, sum, cnt, ps, ret); cnt[ps]--; } }; int main() { int s; cin >> s; TreeNode *root; cin >> root; Solution solution; cout << solution.pathSum(root, s) << endl; return 0; }
Python
UTF-8
1,538
3.84375
4
[]
no_license
''' Exercise: Write a module bag.py that defines a class named bag. A bag (also called a multiset) is a collection without order (like a set) but with repetition (unlike a set) --- an element can appear one or more times in a bag. Implement bag as a subclass of dictionary where each bag element is a key and its value is an integer that represents its multiplicity (the number of repetitions). For example in b1 = bag({'a':2, 'b':3}), b1 is a bag where 'a' occurs twice (has multiplicity 2) and 'b' occurs three times. Provide a bag union operator + (plus sign) that operates on two bags and returns a third bag, their union. The bag union contains all of the elements of both bags, with their multiplicities added. For example, after b2 = bag({'b':1, 'c':2}), then b1 + b2 == bag({'a':2, 'b':4', 'c':2}) Created on Nov 22, 2011 @author: mark ''' import copy class bag(dict): def __add__ (self, otherBag): newBag = copy.deepcopy(self) for x in otherBag : if x not in newBag: newBag[x] = otherBag[x] else: newBag[x] += otherBag[x] return newBag ''' newBag = {} for x in set(self) + set(otherBag) : newBag[x] = self.get(x,0) + otherBag.get(x,0) return newBag ''' if __name__ == '__main__': b2 = bag({'b':1, 'c':2}) b1 = bag({'a':2, 'b':3}) b3 = bag() b4 = bag({(1,2):1, 'what':3, 2:3, 'zero':0}) b5 = bag({'zero':3}) r1 = b2 + b1 + b3 + b4 + b5 print r1 pass
Shell
UTF-8
526
2.625
3
[]
no_license
#!/bin/bash for nombre in "Ada" "background" "c++" "deadpool"; do mkdir Corrida-$nombre-compresion mkdir Corrida-$nombre-descompresion g++ -g ../../HuffmanModificado/*.cpp -fpermissive -o HuffmanCompressor cp ../../../ArchivosDePrueba/* ./ sleep 2 valgrind --leak-check=full --log-file=./Resultados$nombre-compresion.txt -v ./HuffmanCompressor comprimir "$nombre.jpg" sleep 2 valgrind --leak-check=full --log-file=./Resultados$nombre-descomprimir.txt -v ./HuffmanCompressor descomprimir "$nombre.cmp" sleep 2 done
PHP
UTF-8
1,354
2.640625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Bright * Date: 5/22/2016 * Time: 12:26 PM */ namespace Aforance\Http\Controllers\Policy\Funeral; use Aforance\Aforance\Contracts\Repository\FuneralPolicyRepositoryInterface; use Aforance\Aforance\Repository\CustomerRepository; use Aforance\Http\Controllers\Controller; class FuneralController extends Controller { /** * @var CustomerRepository */ private $customers; /** * @var FuneralPolicyRepositoryInterface */ private $policies; public function __construct(CustomerRepository $customers) { $this->customers = $customers; $this->policies = app('funeral.repository_contract'); } public function index(){ return view('policies.funeral.index'); } /** * Gets the form for creating new funeral * policies * * @param $customerId * @return mixed */ public function getCreationScreen($customerId){ return view('policies.funeral.create', ['customer' => $this->customers->findOrFail(e($customerId))]); } public function getViewScreen($policyNumber){ $policy = $this->policies->getPolicyByNumber(e($policyNumber)); if($policy) return view('policies.funeral.view', ['policy' => $policy]); else return abort(404); } }
Python
UTF-8
3,476
2.546875
3
[]
no_license
import cv2 import numpy as np def get_rigid_transform(tra, rot): tra = np.reshape(tra, (3,1)) rigid_transformation = np.append(rot, tra, axis=1) return rigid_transformation def get_rottra_from_rigid(rigid): rot = rigid[0:3,0:3] tra = rigid.T[3,0:3] return rot, tra def fill_holes(mask): kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) inv_mask = ~mask if mask[0][0]==0: cv2.floodFill(mask, None, (0,0), 255) else: size = mask.shape cv2.floodFill(mask, None, (size[1]-1, size[0]-1), 255) filled_mask = ~(inv_mask & mask) return filled_mask def get_homo_coord(pt_cld): ones = np.ones((pt_cld.shape[0],1)) homo_coord = np.append(pt_cld, ones, axis=1) return homo_coord def project_to_image(pt_cld, intrinsics, tra, rot): homo_coord = get_homo_coord(pt_cld) rigid = get_rigid_transform(tra,rot) homo_coord = intrinsics @ (rigid @ homo_coord.T) coord_2D = homo_coord[:2, :] / homo_coord[2, :] coord_2D = ((np.floor(coord_2D)).T).astype(int) return coord_2D def create_gt_mask(pt_cld, intrinsics, tra, rot, label, image_shape=(480,640)): coord_2D = project_to_image(pt_cld, intrinsics, tra, rot) ID_mask = np.zeros((image_shape[0], image_shape[1]), dtype=np.uint8) x_2d = np.clip(coord_2D[:, 0], 0, image_shape[1]-1) y_2d = np.clip(coord_2D[:, 1], 0, image_shape[0]-1) ID_mask[y_2d, x_2d] = label return fill_holes(ID_mask) def calc_offset(keypoints, image_size=(480,640)): numkpt = keypoints.shape[0] X,Y = np.meshgrid(np.arange(image_size[0]), np.arange(image_size[1])) offset = np.concatenate((np.expand_dims(Y,axis=2),np.expand_dims(X,axis=2)), axis=2) offset = np.tile(np.expand_dims(np.transpose(offset,(1,0,2)),axis=2), (1,1,numkpt,1)) offset = (keypoints - offset) / (image_size[1], image_size[0]) offset = offset.transpose(2,3,0,1).reshape((len(keypoints)*2,)+image_size) return offset def FPSKeypoints(pt_cld, num_keypoints=8): center = np.mean(pt_cld, axis=0) init_point = pt_cld[np.sum((pt_cld-center)**2,axis=1).argmax()] keypoints = [init_point,] distance = np.sum((pt_cld-init_point)**2,axis=1) for i in range(num_keypoints-1): new_point = pt_cld[distance.argmax()] keypoints.append(new_point) distance = np.minimum(distance, np.sum((pt_cld-new_point)**2,axis=1)) keypoints.append(center) return np.array(keypoints) def get_bounding_box(pt_cld): x_max, x_min = np.max(pt_cld[:,0]), np.min(pt_cld[:,0]) y_max, y_min = np.max(pt_cld[:,1]), np.min(pt_cld[:,1]) z_max, z_min = np.max(pt_cld[:,2]), np.min(pt_cld[:,2]) bounding_box = np.array([ [x_min,y_min,z_min], [x_max,y_min,z_min], [x_max,y_max,z_min], [x_min,y_max,z_min], [x_min,y_min,z_max], [x_max,y_min,z_max], [x_max,y_max,z_max], [x_min,y_max,z_max]]) return bounding_box def draw_bounding_box(bounding_box, image, color=(0,0,0), thickness=2): for i in range(4): image = cv2.line(image, tuple(bounding_box[i]), tuple(bounding_box[(i+1)%4]), color, thickness) image = cv2.line(image, tuple(bounding_box[i+4]), tuple(bounding_box[(i+1)%4+4]), color, thickness) image = cv2.line(image, tuple(bounding_box[i]), tuple(bounding_box[i+4]), color, thickness) return image
Java
UTF-8
2,432
2.0625
2
[]
no_license
/** * */ package edu.iiitb.ebay.action; import java.util.ArrayList; import java.util.Map; import org.apache.log4j.Logger; import com.opensymphony.xwork2.ActionSupport; import edu.iiitb.ebay.dao.DealsDAO; import edu.iiitb.ebay.model.entity.CategoryModel; import edu.iiitb.ebay.model.entity.DealModel; import edu.iiitb.ebay.model.entity.ProductModel; import edu.iiitb.ebay.model.page.CategoryProductsModel; /** * @author Pavan * */ public class DealsAction extends ActionSupport { private static Logger logger = Logger.getLogger(DealsAction.class); private ArrayList<CategoryProductsModel> productGroups = new ArrayList<CategoryProductsModel>(); public ArrayList<CategoryProductsModel> getProductGroups() { return productGroups; } public void setProductGroups(ArrayList<CategoryProductsModel> productGroups) { this.productGroups = productGroups; } // public void getDealsList(){ // //int categoryId = 0; // int sellingPrice; // DealsDAO dao = new DealsDAO(); // DealModel dm = null; // CategoryModel cm = null; // ArrayList<Integer> categoryList = dao.parentCategoryIdList(); // for(int cat:categoryList ){ // ArrayList<Integer> catList= new ArrayList<Integer>(); // recursiveFun(catList,cat); // ArrayList<Integer> productList = null; // for(int subCateg : catList){ // productList = dao.getProductIdList(subCateg); // ArrayList<ProductModel> prodList = new ArrayList<ProductModel>(); // for(int proId : productList){ // dm = dao.getDealModel(proId); // cm = dao.getCategoryModel(subCateg); // if(dm == null){ // continue; // } // else { // productList.add // } // } // //productList.add(XYZDAO.getP roductsForCategory(categ.categoryId); // } // } // // } // public void getDealsList() { // logger.info("Inside getDealsList"); // int sellingPrice; // DealsDAO dao = new DealsDAO(); // setProductGroups(dao.getProductGroups()); // } public void recursiveFun(ArrayList<Integer> catList, int cat) { DealsDAO dao = new DealsDAO(); ArrayList<Integer> tempList; tempList = dao.getCategoryIdList(cat); if (tempList == null) return; else { for (int category : tempList) { catList.add(category); recursiveFun(catList, category); } } } @Override public String execute() throws Exception { DealsDAO dealsDAO = new DealsDAO(); logger.info("Inside execute method"); setProductGroups(dealsDAO.getProductGroups()); return super.execute(); } }
JavaScript
UTF-8
3,802
2.546875
3
[]
no_license
import React, { Component } from "react"; import axios from "axios"; import "./Profile.css"; // import { Route, Link } from "react-router-dom"; class Profile extends Component { constructor(props) { super(props); this.state = { playerImg: [], stats: [] }; } componentDidMount = async () => { const response1 = await axios( //response 1 is the img `https://nba-players.herokuapp.com/players/${this.props.match.params.lastName}/${this.props.match.params.firstName}` ); const response2 = await axios( // response 2 is the stats `https://nba-players.herokuapp.com/players-stats/${this.props.match.params.lastName}/${this.props.match.params.firstName}` ); this.setState({ playerImg: response1.config.url, //image stats: response2.data // stats }); }; // From JSON Data TeamLogoURL; setBackground = teamLogo => { return teamLogo.TeamLogoURL && this.state.stats ? teamLogo.TeamCode.toLowerCase().includes(this.state.stats.team_acronym) : true; }; render() { return ( <div className="container"> <img className="teamLogo" src={this.props.teamLogo .filter(this.setBackground) .map(logo => logo.TeamLogoURL)} /> <div className="player-background"> <div> <img className="player-img" src={this.state.playerImg} /> <p className="text-container">{this.state.stats.name}</p> <p className="text-container"> {this.state.stats.team_name}</p> </div> <section className="player-table-stats"> <table role="grid"> <thead> <tr className="stat-name"> <th> <span> 2017- 2018</span> </th> <th scope="col"> <abbr title="Minutes Per Game">MPG</abbr> </th> <th> <abbr title="Field Goal Percentage">FG%</abbr> </th> <th> <abbr title="Three Point Percentage">3P%</abbr> </th> <th> <abbr title="Free Throw Percentage">FT%</abbr> </th> <th> <abbr title="Points Per Game">PPG</abbr> </th> <th> <abbr title="Rebounds Per Game">RPG</abbr> </th> <th> <abbr title="Assists Per Game">APG</abbr> </th> <th> <abbr title="Blocks Per Game">BPG</abbr> </th> <th> <abbr title="Blocks Per Game">STLS</abbr> </th> </tr> </thead> <tbody> <tr className="stats"> <th className="season" scope="row"> SEASON </th> <td>{this.state.stats.minutes_per_game}</td> <td>{this.state.stats.field_goal_percentage}</td> <td>{this.state.stats.three_point_percentage} </td> <td>{this.state.stats.free_throw_percentage} </td> <td>{this.state.stats.points_per_game} </td> <td>{this.state.stats.rebounds_per_game} </td> <td> {this.state.stats.assists_per_game}</td> <td>{this.state.stats.steals_per_game}</td> <td>{this.state.stats.blocks_per_game}</td> </tr> </tbody> </table> </section> </div> </div> ); } } export default Profile;
TypeScript
UTF-8
6,680
2.625
3
[]
no_license
module trl.backend.vm { export class JSExecutionContexts { public executionContexts: JSExecutionContext[]; public globalEnvironment: JSLexicalEnvironment; public objectPrototypeObject: JSObjectPrototypeObject; public functionPrototypeObject: JSFunctionPrototypeObject; constructor( public global: JSGlobalObject ) { this.executionContexts = []; this.globalEnvironment = JSLexicalEnviromentOperations.newGlobalEnvironment(global); } public createGlobalExecutionContext(): JSExecutionContext { return new JSExecutionContext( this.globalEnvironment, this.globalEnvironment, this.global, JSExecutableCodeType.global ); } public initiateGlobalCode(executionContext: JSExecutionContext, code: frontend.syntax.IJSContextInfo) { executionContext.setCode(code); executionContext.declarationBindingInstantiation(this); } public createFunctionExecutionContext(funcObj: JSFunctionObject, thisArg: IJSValue, argumentsList: JSList): JSExecutionContext { let thisBinding: IJSValue; if() { } } } export enum JSExecutableCodeType { global, eval, function } export class JSExecutionContext { public code: frontend.syntax.IJSContextInfo; constructor( public lexicalEnvironment: JSLexicalEnvironment, public variableEnvironment: JSLexicalEnvironment, public thisBinding: IJSValue, public executionCodeType: JSExecutableCodeType ) { } public setCode(code: frontend.syntax.IJSContextInfo) { this.code = code; } public declarationBindingInstantiation(executionContexts: JSExecutionContexts, funcObj?: JSFunctionObject, args?: JSList) { //10.5 Declaration Binding Instantiation const env = this.variableEnvironment.env; const configurableBindings = this.executionCodeType === JSExecutableCodeType.eval; const strict = this.code.jscontext.strict; //4. If code is function code, then if (this.executionCodeType === JSExecutableCodeType.function) { const names = funcObj.jsFormalParameters; _.each(names, (argName, n) => { const val = n > args.list.length ? JSApi.createUndefined() : args.list[n]; if (!env.hasBinding(argName)) { env.createMutableBinding(argName); } env.setMutableBinding(argName, val, strict); }); } //5. For each FunctionDeclaration f in code, in source text order do _.each(this.code.jscontext.functionDeclarations, (f: frontend.syntax.IFunctionDeclaration) => { const fn = JSApi.createString(f.id.name); const fo = JSEvaluation.instantiateFunctionDeclaration(this, f); const funcAlreadyDeclared = env.hasBinding(fn.getValue()); if (!funcAlreadyDeclared) { env.createMutableBinding(fn.getValue(), configurableBindings); } else if (env === executionContexts.globalEnvironment.env) { const go = executionContexts.global; const existing = go.objGetProperty(fn); if (existing instanceof JSUndefined) { JSApi.throwTypeErrorException(); } const existingProp = existing as JSPropertyDescriptor; if (JSApi.isBooleanWithValue(existingProp.jsconfigurable, true)) { go.objDefineOwnProperty( fn, JSPropertyDescriptor.createDataPropertyDescriptor( JSApi.createUndefined(), JSApi.createBoolean(true), JSApi.createBoolean(true), JSApi.createBoolean(configurableBindings) ), true ); } else if (existingProp.isAccessorDescriptor() || !JSApi.isBooleanWithValue(existingProp.jswritable, true) || !JSApi.isBooleanWithValue(existingProp.jsconfigurable, true) ) { JSApi.throwTypeErrorException(); } } env.setMutableBinding(fn.getValue(), fo, strict); }); const argumentsAlreadyDeclared = env.hasBinding("arguments"); //7. If code is function code and if (this.executionCodeType === JSExecutableCodeType.function && !argumentsAlreadyDeclared ) { const names = funcObj.jsFormalParameters; const argsObj = JSExecutionContext.createArgumentsObject(funcObj, names, args, this.variableEnvironment, strict); if(strict) { (env as JSDeclerativeEnvironmentRecord).createImmutableBinding("arguments"); (env as JSDeclerativeEnvironmentRecord).initializeImmutableBinding("arguments", argsObj); } else { env.createMutableBinding("arguments"); env.setMutableBinding("arguments", argsObj, false); } } //8. For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do _.each(this.code.jscontext.variableDeclarations, (variableDeclaration: frontend.syntax.IVariableDeclaration) => { _.each(variableDeclaration.declarations, (declaratior: frontend.syntax.IVariableDeclarator) => { const dn = declaratior.id.name; if(!env.hasBinding(dn)) { env.createMutableBinding(dn); env.setMutableBinding(dn, JSApi.createUndefined(), strict); } }); }); } public static createArgumentsObject(func: JSFunctionObject, names: string[], args: JSList, env: JSLexicalEnvironment, strict: boolean): JSArgumentsObject { return throwNotImplementedYet(); } } }
Markdown
UTF-8
2,696
2.796875
3
[]
no_license
--- author: name: Topy body: "I have a bunch of alternative glyphs named incorrectly. For example, there is a \"four_onum.alt\". \r\n\r\n-Is the correct way to name this four.onum.alt or maybe four.onum_alt would be better? From what I understand, four.onum1 is preferred, but it is not that descriptive as I would like.\r\n-How big of a problem this kind of naming is and where the problems/compatibility issues would be likely to occur?\r\n\r\nI'm also intersted to hear about possible ways to fix it. I found www.typophile.com/node/80760 where a \"Rename Glyphs by Regex\" script by Adam Twardoch was mentioned. This sounds like a tool for the job if it renames glyphs also in the opentype code and classes? However, I didn't find the actual script from Google. Is it publicly available, or should I just turn to Adam directly?" comments: - author: name: agisaak picture: 115092 body: "Any of four.onum.alt, four.onum_alt, or four.onum1 should be fine. There's no reason why the latter should be preferred AFAIK.\r\n\r\nfour_onum.alt, however is definitely not a good idea. The problem will arise in situations where a file is converted to postscript in the middle of a workflow (e.g. when using Acrobat Distiller) in which case unicode values will be lost and those values must be reconstructed from the glyph names.\r\n\r\nIn such cases, the unicode value is determined from the base name ignoring all dot suffixes. The base name must be either a legitimate postscript name (either a name from the Adobe Glyph List or a name of the form uniXXXX) or a ligature composed of legitimate names separated by underscores.\r\n\r\nfour_onum.alt would thus be interpreted as a ligature of four and (the non-legitimately named and likely nonexistent glyph) onum.\r\n\r\nAndr\xE9" created: '2012-07-18 17:51:28' - author: name: Topy body: "I see, thanks Andr\xE9. So it's definitely something that I should fix. Damn." created: '2012-07-19 14:30:51' - author: name: agisaak picture: 115092 body: "I'm not familiar with the script Adam mentioned. Unfortunately I know of no easy way to rename all your glyphs all at once within FontLab. It's easy enough to change the final suffix en masse, but anything involving either the base or a non-final suffix must be done manually or via a python script.\r\n\r\nAndr\xE9" created: '2012-07-19 15:08:06' - author: name: Topy body: Yeah, I really would like to learn Python and do it myself. Both options seem a bit daunting tasks. created: '2012-07-20 07:33:50' date: '2012-07-18 12:35:28' node_type: forum title: Bad glyph names and how to fix it ---
Python
UTF-8
395
3.5
4
[]
no_license
# Given a binary tree, return the inorder traversal of its nodes' values. class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: return self.helper(root, []) def helper(self, root, result): if root is None: return result self.helper(root.left, result) result.append(root.val) return self.helper(root.right, result)
C++
UTF-8
2,499
3.5625
4
[]
no_license
#include <iostream> #include <complex> //*for complex #include <tuple> #include <string> #include <functional> //*for ref() int main(int argc, char const *argv[]) { //std::tuple<std::string, int, int, std::complex<double>> t; //*************************Test tuple get value and compare*************************************************** //* t1 std::tuple<int, float, std::string> t1(41, 6.1, "helloworld"); std::cout << std::get<0>(t1) << std::endl; //*41 std::cout << std::get<1>(t1) << std::endl; //*6.1 std::cout << std::get<2>(t1) << std::endl; //*helloworld //* t2 auto t2 = std::make_tuple(42, 44, "nice"); std::get<1>(t1) = std::get<1>(t2); //*assign second valut in t2 to t1 std::cout << std::get<0>(t1) << std::endl; //*41 std::cout << std::get<1>(t1) << std::endl; //*44 std::cout << std::get<2>(t1) << std::endl; //*helloworld if (t1 < t2) { //*compare value for value t1 = t2; //*OK assign value for value std::cout <<"t1 less than t2" << std::endl;//* YES } std::cout << std::get<0>(t1) << std::endl; //*42 std::cout << std::get<1>(t1) << std::endl; //*44 std::cout << std::get<2>(t1) << std::endl; //*nice //**************************************************************** std::string s="world"; auto x = std::make_tuple(s); //* copy s std::get<0>(x)="my value"; //* modifies x but not s std::cout<<"x is "<<std::get<0>(x)<<std::endl; //* x is my value std::cout<<"s is "<<s<<std::endl; //* s is world auto y = std::make_tuple(std::ref(s)); //* reference for s std::get<0>(y) = "hello"; std::cout<<"y is "<<std::get<0>(y)<<std::endl; //* hello std::cout<<"s is "<<s<<std::endl; //* hello //*****************************Extract tuple value******************************************* std::tuple<int,float,std::string> tt(77,1.1,"hell"); int i; float f; std::string mystring; //* way 1 std::make_tuple(std::ref(i),std::ref(f),std::ref(mystring))=tt; std::cout<<i<<" "<<f<<" "<<mystring<<std::endl; //* 77 1.1 hell //* way 2 int ii; float ff; std::string ss; std::tie(ii,ff,ss)=tt; std::cout<<ii<<" "<<ff<<" "<<ss<<std::endl; //* 77 1.1 hell int iii; std::string sss; std::tie(iii,std::ignore,sss) = tt;//* ignore the second element std::cout<<iii<<" "<<sss<<std::endl; //*77 hell return 0; }
C++
UTF-8
1,034
2.8125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; char s[105], t[105]; int schars[26], tchars[26]; int automaton() { int flag2= 0, j = 0; for(int i = 0; i < strlen(s); i++) { if(s[i] == t[j]) j++; } if(j == strlen(t)) flag2 = 1; return flag2; } int suffixarray() { for(int i = 0; i < strlen(s); i++) schars[s[i] - 'a'] += 1; for(int i = 0; i < strlen(t); i++) tchars[t[i] - 'a'] += 1; int flag = 1; for(int i = 0; i < 26; i++) { if(tchars[i] != schars[i]) flag = 0; } return flag; } int both() { for(int i = 0; i < strlen(s); i++) schars[s[i] - 'a'] += 1; for(int i = 0; i < strlen(t); i++) tchars[t[i] - 'a'] += 1; int flag = 1; for(int i = 0; i < 26; i++) { if(tchars[i] > schars[i]) flag = 0; } return flag; } int main() { cin >> s; cin >> t; int flag1 = automaton(); int flag2 = suffixarray(); if(flag1) cout << "automaton\n"; else if(flag2) cout << "array\n"; else { int flag3 = both(); if(flag3) cout << "both\n"; else cout << "need tree\n"; } return 0; }
C
UTF-8
678
4.65625
5
[]
no_license
/* * C言語のサンプルプログラム - Webkaru * - 3つの数値から一番大きい数値を探す - */ #include <stdio.h> int main(void) { float a, b, c; printf("異なる3つの数値を入力してください。\n"); printf("1つ目の数値: a = "); scanf("%f", &a); printf("2つ目の数値: b = "); scanf("%f", &b); printf("3つ目の数値: c = "); scanf("%f", &c); if(a>b && a>c) printf("一番大きい数値:a = %.2f\n", a); if (b > a && b > c) printf("一番大きい数値:b = %.2f\n", b); if (c > a && c > b) printf("一番大きい数値:c = %.2f\n", c); return 0; }
Python
UTF-8
1,481
2.546875
3
[]
no_license
""" .. :module:: apps.accounts.tasks.ssh :synopsis: Tasks related to user accounts """ import logging from celery import shared_task from celery.result import AsyncResult # pylint: disable=invalid-name logger = logging.getLogger(__name__) # pylint: enable=invalid-name @shared_task( max_retries=None, time_limit=60*5, # 60s * 5 = 5min track_started=True ) # pylint: disable=too-many-arguments def setup_pub_key( username, password, token, system_id, hostname, port ): """Setup public keys for user""" from portal.apps.accounts.managers import accounts as AccountsManager output = AccountsManager.add_pub_key_to_resource( username, password, token, system_id, hostname, port ) return output @shared_task(bind=True) def monitor_setup_pub_key(self, task_id): """Monitors Setup Pub Key Monitors :func:~setup_pub_key` task. This task should send events to the frontend letting the user know what is going on with setting up the public key """ result = AsyncResult(task_id) if not result.ready(): self.retry( exc=Exception('Monitored task not done yet. Retrying') ) if result.state == 'FAILURE': logger.info('TASK FAILED') logger.debug(result.result) elif result.state == 'SUCCESS': logger.info('TASK SUCCESSFUL') logger.debug(result.result)
C#
UTF-8
5,353
2.59375
3
[]
no_license
using FunBooksAndVideos.Common.Models; using FunBooksAndVideos.Common.Rules; using FunBooksAndVideos.Common.Services; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FunBooksAndVideos.Tests { public class TestFactory { public static Mock<ICustomerService> CreateMockCustomerService() { var mockCustomerService = new Mock<ICustomerService>(); mockCustomerService.Setup(customerService => customerService.ActivateMembershipAsync(It.IsAny<int>(), It.IsAny<int>())).Returns(Task.CompletedTask); return mockCustomerService; } public static Mock<IShippingService> CreateMockShippingService(ShippingSlip shippingSlip) { var mockShippingService = new Mock<IShippingService>(); mockShippingService.Setup(shippingService => shippingService.GenerateShippingSlipAsync(It.IsAny<int>(), It.IsAny<IEnumerable<IPurchaseItem>>())).Returns(Task.FromResult(shippingSlip)); return mockShippingService; } public static Mock<IShippingService> CreateMockShippingService(IEnumerable<PhysicalProduct> products) { var mockShippingService = new Mock<IShippingService>(); ShippingSlip shippingSlip = GetShippingSlip(products); mockShippingService.Setup(shippingService => shippingService.GenerateShippingSlipAsync(It.IsAny<int>(), It.IsAny<IEnumerable<IPurchaseItem>>())).Returns(Task.FromResult(shippingSlip)); return mockShippingService; } public static IRule CreateMembershipActivationRule() { return new MembershipActivationRule(CreateMockCustomerService().Object); } public static IRule CreateMembershipActivationRule(ICustomerService customerService) { return new MembershipActivationRule(customerService); } public static IRule CreatePhysicalProductShippingSlipRule(IEnumerable<PhysicalProduct> products) { return new PhysicalProductShippingSlipRule(CreateMockShippingService(GetShippingSlip(products)).Object); } public static IRule CreatePhysicalProductShippingSlipRule(IShippingService shippingService) { return new PhysicalProductShippingSlipRule(shippingService); } public static RulesProcessor CreateRulesProcessor() { List<IRule> rules = new List<IRule>(); rules.Add(CreateMembershipActivationRule()); rules.Add(CreatePhysicalProductShippingSlipRule(GetPhysicalProducts())); return new RulesProcessor(rules); } public static IEnumerable<PhysicalProduct> GetPhysicalProducts() { return new List<PhysicalProduct>() { new Video() { Id = 1, Name = "Comprehensive First Aid Training", Value = 19.99 }, new Book() { Id = 2, Name = "The Girl on the train", Value = 7.99 } }; } public static IEnumerable<MembershipProduct> GetMembershipProducts() { return new List<MembershipProduct>() { new MembershipProduct() { Id = 3, Name = "Book Club Membership", Value = 29.99, MembershipType = MembershipType.Book } }; } public static IEnumerable<PurchaseItem> GetPurchaseItems() { List<PurchaseItem> purchaseItems = new List<PurchaseItem>(); purchaseItems.AddRange(GetPhysicalProducts().Select(x => new PurchaseItem() { Id = x.Id, Product = x })); purchaseItems.AddRange(GetMembershipProducts().Select(x => new PurchaseItem() { Id = x.Id, Product = x })); return purchaseItems; } public static IEnumerable<PurchaseItem> GetPurchaseItems(IEnumerable<Product> products) { List<PurchaseItem> purchaseItems = new List<PurchaseItem>(); purchaseItems.AddRange(products.Select(x => new PurchaseItem() { Id = x.Id, Product = x })); return purchaseItems; } public static PurchaseOrder GetPurchaseOrder() { PurchaseOrder purchaseOrder = new PurchaseOrder() { Id = 987654321, CustomerId = 987, Items = GetPurchaseItems() }; return purchaseOrder; } public static PurchaseOrder GetPurchaseOrder(IEnumerable<PurchaseItem> purchaseItems) { PurchaseOrder purchaseOrder = new PurchaseOrder() { Id = 987654321, CustomerId = 987, Items = purchaseItems }; return purchaseOrder; } public static ShippingSlip GetShippingSlip(IEnumerable<PhysicalProduct> products) { return new ShippingSlip() { Id = 123456789, Products = products }; } } }
JavaScript
UTF-8
2,308
3.25
3
[]
no_license
function mouseOver(id){ var element = document.getElementById(id); element.style.color='white'; element.style.backgroundColor='orange'; } function mouseOut(id){ var element = document.getElementById(id); element.style.color='orange'; element.style.backgroundColor='white'; } var intervalFlag = false; var intervalNum; function start(id) { if(intervalFlag){ } else{ intervalFlag=true; blink(); intervalNum=setInterval("blink()",500); } } function end(id) { if(intervalFlag){ clearInterval(intervalNum) intervalFlag=false; clear9Sqr(); } else{ } } function blink() { for(var i = 0;i<9;i++){ var e = document.getElementById('s'+(i+1)); e.style.backgroundColor='orange'; } var firstNum, firstSqr, firstColor; var secondNum, secondSqr, secondColor; var thirdNum, thirdSqr, thirdColor; firstNum = Math.round(Math.random() * 8)+1; secondNum = Math.round(Math.random() * 8)+1; thirdNum = Math.round(Math.random() * 8)+1; while (secondNum == firstNum) { secondNum = Math.round(Math.random() * 8)+1; } while (thirdNum == firstNum || thirdNum == secondNum) { thirdNum = Math.round(Math.random() * 8)+1; } firstSqr='s'+(firstNum); secondSqr='s'+(secondNum); thirdSqr='s'+(thirdNum); console.log(firstSqr+" "+secondSqr+" "+thirdSqr); var firstElement = document.getElementById(firstSqr); var secondElement = document.getElementById(secondSqr); var thirdElement = document.getElementById(thirdSqr); var firstRgb = 'rgb('+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+')'; var secondRgb = 'rgb('+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+')'; var thirdRgb = 'rgb('+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+')'; firstElement.style.backgroundColor = firstRgb; secondElement.style.backgroundColor = secondRgb; thirdElement.style.backgroundColor = thirdRgb; } function clear9Sqr() { for(var i = 0;i<9;i++){ var e = document.getElementById('s'+(i+1)); e.style.backgroundColor='orange'; } }
Markdown
UTF-8
3,443
2.59375
3
[]
no_license
--- title: Forrest Bradford's Platform #x subtitle: background-image: url("/assets/images/cover platform.jpg") --- <b>Environment:</b> We must act now to stave off the negative effects Global Warming will have on our children and future generations. <a href="/environment.html"><small>Read More</small></a> <b>Education:</b> Forrest supports having strong public education as the bulwark of a free and wealthy society. He opposes draining resources from public schools into charter schools. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <em>“An investment in Knowledge pays the best interest.” - Benjamin Franklin</em> <b>Unions:</b> We must protect unions and do what we can to re-build public confidence and trust in them. They are crucial to a strong and equitable democracy. <a href="/Unions.html"><small>Read More</small></a> <b>Freedom of the Press:</b> Feeling Patriotic? As one of our basic rights in these United States, Freedom of the Press was designed with the main purpose of informing the citizenry of truths. With these truths, the public is afforded critical tools to use in many ways, which enhances their ability in helping to build a stronger republic. It is critical for a strong democracy to have a well-informed public. If this freedom is used with ill-intent to misinform the public… usually this occurs when protection of self-interest and profit is involved… it is a breach of the public trust and is the opposite of patriotic. <a href="/pressfreedom.html"><small>Read More</small></a> <b>Opioid Epidemic:</b> Families need answers and support when their loved ones suffer from addiction and have entered into the system. They should at least know that their loved ones are safe. Oversight is also needed on those who develop these programs who receive grant monies to ensure they are not misappropriating funds. These persons should also be contactable. <b>Spam Phone Calls:</b> These calls negatively affect our peaceful lives on a daily basis. Telephone companies currently have the ability to block these calls, but demand a monthly fee to do so. If telephone companies can stop this nonsense, they then should, at no additional cost. <b>Corporate Takeover:</b> The middle class is being taken for a ride by banking fees, insurance prices, pharmaceutical price gouging, hospital costs, etc. It is time we turn the tables of fairness to the middle class and elect people who care enough to fight for change. <a href="/corporations.html"><small>Read More</small></a> <b>LGBT Rights:</b> LGBT people are not a separate community; they are part of the families of Agawam, Granville, and Southwick. No person should trump another in rights because they are in the majority. In the United States, we strive for equality for all. <b>Mental Illness:</b> A large number of families in Agawam, Southwick, and Granville have dealt with or are currently dealing with those suffering forms of mental illness. We can come up with better supportive ideas for these families. I have had mental illness affect a brother and other members of my family. My parents spent years volunteering for NAMI. I will be an advocate for those families affected as mine was. <b>Military Veterans and Wounded Vet Concerns:</b> Forrest navigated the VA system for many years while caring for his father, who was wounded in the Battle of the Bulge. Forrest is against privatizing the VA system.
Python
UTF-8
543
3.796875
4
[]
no_license
""" Create a function that returns the determinant of a given square matrix. ### Examples determinant([[3]]) ➞ 3 determinant([[1, 0], [5, 4]]) ➞ 4 determinant([[3, 0], [2, 2]]) ➞ 6 determinant([[4, 8, 6], [2, 4, 3], [6, 2, 1]]) ➞ 0 ### Notes All inputs are square integer matrices. """ def determinant(A): if len(A) == 1: return A[0][0] result = 0 for x in range(len(A)): result += ((-1) ** x) * A[x][0] * determinant([A[y][1:] for y in range(len(A)) if y != x]) return result
Java
UTF-8
3,980
3.25
3
[]
no_license
package com.lf; import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import java.util.Scanner; /** * @ClassName: JdbcLogin * @Description:使用JDBC实现登陆功能 这种情况下存在sql注入问题 ,解决SQL注入问题 * @Author: 李峰 * @Date: 2021 年 03月 02 18:13 * @Version 1.0 */ /* * 1.使用powerDesiginer完成数据库的建模 * */ public class JdbcLogin01 { public static void main(String[] args) { //初始化一个用户登陆界面 Map<String,String> userLoginUi=intUi(); //登陆验证 Boolean loginSuccess= login(userLoginUi); //返回登陆结果 System.out.println(loginSuccess ? "登陆成功" : "登陆失败"); } /* * 用来实现登陆验证的方法 * @return用户名和密码判断的结果 * */ private static Boolean login(Map<String, String> userLoginUi) { //定义表示符号 Boolean flag=false; //单独定义变量 String loginName=userLoginUi.get("loginName"); String loginPwd=userLoginUi.get("loginPwd"); //JDBC的代码 //使用资源绑定器绑定资源文件 ResourceBundle bundle=ResourceBundle.getBundle("db"); String driver=bundle.getString("driver"); String url=bundle.getString("url"); String username=bundle.getString("username"); String password=bundle.getString("password"); Connection connection=null; //preparedStatement叫做预编译的数据库操作对象,使用这个可以防止sql注入 PreparedStatement statement=null; ResultSet rs=null; try { //1.注册驱动 Class.forName(driver); //2.获取连接 connection = DriverManager.getConnection(url, username, password); //3.获取数据库对象 //sql语句的框架,问号表示一个占位符 ,将来一个?接收一个传过来的值 , 注意占位符不能使用''括起来 String sql="select loginName,loginPwd from t_user where loginName=? and loginPwd=?" ; //程序执行到这里会对sql框架发送给DBMS,DBMS对sql预计进行预编译 statement = connection.prepareStatement(sql); //按照下标对占位符进行传值,1表示第一个问号 statement.setString(1,loginName); statement.setString(2,loginPwd); //4.执行sql语句 rs = statement.executeQuery(); //处理结果集 如果登陆成功会返回一条数据 if (rs.next()){ flag=true; } } catch (Exception e) { e.printStackTrace(); }finally { //关闭资源,先关闭statement if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement!=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return flag; } /*初始化界面的方法 * @return 用户输入的用户名密码等登陆信息 * */ private static Map<String, String> intUi() { Scanner scanner = new Scanner(System.in); System.out.println("用户名:"); String loginName = scanner.nextLine(); System.out.println("密码:"); String loginPwd=scanner.nextLine(); Map<String,String> loginMap= new HashMap<>(); loginMap.put("loginName",loginName); loginMap.put("loginPwd",loginPwd); return loginMap; } }
C++
UTF-8
2,537
2.640625
3
[]
no_license
// * Question Link -> https://www.hackerrank.com/challenges/the-quickest-way-up/problem #include <iostream> #include <unordered_map> #include <list> #include <vector> #include <stack> #include <queue> #include <algorithm> #include <string> #include <climits> #include <utility> using namespace std; #define mp make_pair #define pb push_back #define INFI 10e8 #define INF 10e7 #define mod 1000000007 #define sieve_limit 10e6 typedef long long ll; typedef pair<int, int> pi; typedef vector<int> vi; typedef vector<long> vl; typedef vector<long long> vll; typedef vector<long long int> vlli; typedef vector<bool> vb; typedef vector<vector<int> > vvi; typedef vector<vector<long long> > vvll; typedef vector<vector<long long int> > vvlli; typedef vector<vector<bool> > vvb; bool valid(int num, vb &visited){ return num <= 100 && num > 0 && !visited[num] ? true : false; } int get_shortest_path(unordered_map<int, int> &ladders, unordered_map<int, int> &snakes){ queue<pair<int, int> > q; vb visited(101, false); q.push(mp(1, 0)); visited[1] = true; while(!q.empty()){ pair<int, int> front = q.front(); q.pop(); if(front.first == 100) return front.second; for(int i = 1; i <= 6; i++){ if(valid(front.first + i, visited)){ if(ladders.count(front.first + i) > 0){ q.push(mp(ladders[front.first + i], front.second + 1)); visited[front.first + i] = visited[ladders[front.first + i]] = true; } else if(snakes.count(front.first + i) > 0){ q.push(mp(snakes[front.first + i], front.second + 1)); visited[front.first + i] = visited[snakes[front.first + i]] = true; } else{ q.push(mp(front.first + i, front.second + 1)); visited[front.first + i] = true; } } } } return -1; } int main(){ std::ios_base::sync_with_stdio(false); cin.tie(NULL); int tc; cin >> tc; for(int t = 0; t < tc; t++){ unordered_map<int, int> ladders, snakes; int l, s, src, dest; cin >> l; for(int i = 0; i < l; i++){ cin >> src >> dest; ladders[src] = dest; } cin >> s; for(int i = 0; i < s; i++){ cin >> src >> dest; snakes[src] = dest; } cout << get_shortest_path(ladders, snakes) << '\n'; } }
Markdown
UTF-8
3,670
2.625
3
[]
no_license
--- layout: post date: 0014-11-01 name: team-member-nationality-requirements title: "California: Team Member Nationality Requirements" category: california comments: true --- Note: this is the same information as for other jurisdictions in the US. Foreigners wanting to start a business of any type in the U.S. follow the same procedure required for the US resident. US residency (or citizenship) are not necessary to incorporate in the US, so there are no team member nationality requirements. However, non-residents may run into problems in setting up a U.S. business because of visas, or because of opening up a US bank account. ### Visas You can manage your business from outside the US as a non-resident, but you will need a work visa to manage it from within the US. See [this guide](https://www.usa-corporate.com/start-us-company-non-resident/intro-us-business-visas/) for US Business Visas. ### Opening a Bank Account: You should open a U.S. bank account for your business before you start your business. However, it has recently become somewhat difficult for foreigners to open a U.S. Bank Account. [This source](https://www.business.com/articles/what-non-residents-need-to-consider-when-forming-a-company-here-in-the-us/) recommends three possible ways to get a U.S. bank account. * “Get a visitor visa, travel to the U.S., go to your bank of choice, and personally open an account.
 * Go to a U.S. bank with a local branch in your country of origin for identity verification, if their policies allow such an arrangement.
 * Use third-party services to help you set up an account.”
 Also note other small differences for foreigners setting up firms in the U.S., taken from [this guide](https://mollaeilaw.com/start-us-business-for-non-us-foreign-resident/). * A foreign citizen may be a corporate officer and/or director, but may not work in the United States or receive a salary or compensation for services provided in the United States unless the foreign citizen has a work permit. If forming a new company, the foreign citizen would need to also obtain a separate work permit to work for the new company.
 * Under US tax law, a nonresident alien may own shares in a C corporation, but may not own any shares in an S corporation.
 * Foreign citizens will face a slight delay (~30 days) when applying for the EIN (Federal Tax ID).
 * You don’t need a US address to incorporate in a US, but you do need a US mailing address through some provider.
 See guides and lists of common pitfalls for foreigners to set up firms in the U.S. [here](https://www.business.com/articles/what-non-residents-need-to-consider-when-forming-a-company-here-in-the-us/) and [here](http://www.hightechstartupworld.com/2012/09/starting-your-own-us-company-as.html). ### Sources: * [Guide to US Business Visas](https://www.usa-corporate.com/start-us-company-non-resident/intro-us-business-visas/) * [What Non-residents Need To Consider When Forming a Company Here in the US](https://www.business.com/articles/what-non-residents-need-to-consider-when-forming-a-company-here-in-the-us/) * [Start US Business for non-US Foreign Resident](https://mollaeilaw.com/start-us-business-for-non-us-foreign-resident/) * [Starting your own US Company as a Foreigner](http://www.hightechstartupworld.com/2012/09/starting-your-own-us-company-as.html) | **[Previous Section]( https://neo-project.github.io/global-blockchain-compliance-hub//california/california-registry-requirements.html)** | **[Next Section]( https://neo-project.github.io/global-blockchain-compliance-hub//california/california-tax-and-auditing-requirements.html)** |
Java
UTF-8
1,867
2.859375
3
[]
no_license
package yelp; public class ScoreObj { private int S1; private int s2; private int s3; private int s4; private int s5; private int s6; private int s7; private int s8; private int s9; private String name; private String category; public ScoreObj() { S1=-1; s2=-1; s3=-1; s4=-1; s5=-1; s6=-1; s7=-1; s8=-1; s9=-1; } public int getS1(){ return this.S1; } public void setS1(int s1){ this.S1 = s1; } public int getS2(){ return this.s2; } public void setS2(int s2){ this.s2 = s2; } public int getS3(){ return this.s3; } public void setS3(int s3){ this.s3 = s3; } public int getS4(){ return this.s4; } public void setS4(int s4){ this.s4 = s4; } public int getS5(){ return this.s5; } public void setS5(int s5){ this.s5 = s5; } public int getS6(){ return this.s6; } public void setS6(int s6){ this.s6 = s6; } public int getS7(){ return this.s7; } public void setS7(int s7){ this.s7 = s7; } public int getS8(){ return this.s8; } public void setS8(int s8){ this.s8 = s8; } public int getS9(){ return this.s9; } public void setS9(int s9){ this.s9 = s9; } public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public String getCategory() { return category; } public int[] scoresArray() { int[] ret = {S1,s2,s3,s4,s5,s6,s7,s8,s9}; return ret; } public int getScores(int x) { if(x==0) return S1; else if(x==1) return s2; else if(x==2) return s3; else if(x==3) return s4; else if(x==4) return s5; else if(x==5) return s6; else if(x==6) return s7; else if (x==7) return s8; else return s9; } public void setCategory(String category) { this.category = category; } }
C#
UTF-8
3,366
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using LawAgendaApi.Data; using LawAgendaApi.Data.Entities; using LawAgendaApi.Data.Queries.Search; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Internal; namespace LawAgendaApi.Repositories.UserRepo { public class UserRepo : IUserRepo { private readonly DataContext _context; public UserRepo(DataContext context) { _context = context; } public async Task<IEnumerable<User>> GetAll() { return await _context.Users .Include(u => u.Type) .Include(u => u.Avatar.Type) .ToListAsync(); } public async Task<User> GetUserById(long id) { var users = await GetAll(); var user = users.FirstOrDefault(u => u.Id == id); return user; } public async Task<IEnumerable<User>> Search(SearchQuery<UserSearchQueryType> query, bool singleFilter) { if (string.IsNullOrEmpty(query.Query)) { return null; } var users = (await GetAll()).AsQueryable(); if (singleFilter) { switch (query.Filter) { case UserSearchQueryType.Name: users = users.Where(u => EF.Functions.Like(u.Name, $"%{query.Query}%")); break; case UserSearchQueryType.Username: users = users.Where(u => EF.Functions.Like(u.Username, $"%{query.Query}%")); break; case UserSearchQueryType.PhoneNumber: users = users.Where(u => EF.Functions.Like(u.PhoneNumber, $"%{query.Query}%")) ?? users.Where(u => EF.Functions.Like(u.PhoneNumber2, $"%{query.Query}%")); break; default: users = null; break; } return users; } users = users.Where(u => EF.Functions.Like(u.Name, $"%{query.Query}%") || EF.Functions.Like(u.Username, $"%{query.Query}%") || EF.Functions.Like(u.PhoneNumber, $"%{query.Query}%") || EF.Functions.Like(u.PhoneNumber2, $"%{query.Query}%")); return users; } public async Task<SaveChangesToDbResult<User>> EditProfile(User user) { var users = await GetAll(); var userFromDb = users.FirstOrDefault(u => u.Id == user.Id); var result = new SaveChangesToDbResult<User>(); if (userFromDb == null) { result.Message = "Not Found"; return null; } var updateResult = _context.Update(user); var isSaved = await _context.SaveChangesAsync() > 0; if (!isSaved) { result.Message = "Could not Save Changes"; return null; } result.Message = "Success"; result.Entity = updateResult.Entity; return result; } } }
Markdown
UTF-8
1,856
3.625
4
[]
no_license
# Apply Method [![Build Status](https://travis-ci.com/kazztac/apply_method.svg?branch=master)](https://travis-ci.com/kazztac/apply_method) ## Overview Allows you to apply any function given as a parameter to the object. As you are able to connect operations to the object with chains, it allow you to describe the sequence of operations neatly. This is useful, for example, if you want to change the internal state with other method after the object is created. ## Examples ``` #[derive(Debug, PartialEq)] struct Dog { name: String, size: String, } impl Dog { fn new() -> Self { Self { name: "Pochi".to_string(), size: "Middle".to_string(), } } } let mut exact_dog = Dog::new(); exact_dog.size = "Big".to_string(); let dog = Dog::new().apply(|it| it.size = "Big".to_string()); assert_eq!(dog, exact_dog); ``` ``` let mut exact_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); exact_path.push("src/lib.rs"); let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).apply(|it| it.push("src/lib.rs")); assert_eq!(path, exact_path); ``` ``` let mut exact_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); exact_path.push("src/lib.rs"); let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .apply(|it| it.push("src")) .apply(|it| it.push("lib.rs")); assert_eq!(path, exact_path); ``` ``` let mut exact_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); exact_path.push("src/lib.rs"); let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).apply_with_param(PathBuf::push, "src/lib.rs"); assert_eq!(path, exact_path); ``` ``` let mut exact_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); exact_path.push("src"); exact_path.push("lib.rs"); let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .apply_with_params(PathBuf::push, vec!["src", "lib.rs"]); assert_eq!(path, exact_path); ```
Python
UTF-8
15,976
2.546875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Hae-in Lim, haeinous@gmail.com Models and database functions for Hae-in's Hackbright project.""" from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Index db = SQLAlchemy() ##################################################################### # Model definitions class Video(db.Model): """A video on YouTube.""" __tablename__ = 'videos' video_id = db.Column(db.String(11), primary_key=True, unique=True) is_monetized = db.Column(db.Boolean) channel_id = db.Column(db.String(24), db.ForeignKey('channels.channel_id')) video_title = db.Column(db.String(255)) video_description = db.Column(db.Text) published_at = db.Column(db.DateTime(timezone=False)) video_category_id = db.Column(db.Integer, db.ForeignKey('video_categories.video_category_id')) duration = db.Column(db.Interval) thumbnail_url = db.Column(db.String(255), unique=True) video_status = db.Column(db.String(15)) channel = db.relationship('Channel', backref=db.backref('videos')) video_category = db.relationship('VideoCategory', backref=db.backref('videos')) def __repr__(self): return '<Video video_id={} channel={} is_monetized={}>'.format( self.video_id, self.channel_id, self.is_monetized) class VideoCategory(db.Model): __tablename__ = 'video_categories' video_category_id = db.Column(db.Integer, primary_key=True) category_name = db.Column(db.String(24)) def __repr__(self): return '<VideoCategory id={} name={}'.format( self.video_category_id, self.category_name) class VideoStat(db.Model): """Statistics about a particular YouTube video at a point in time.""" __tablename__ = 'video_stats' video_stat_id = db.Column(db.Integer, autoincrement=True, primary_key=True) video_id = db.Column(db.String(11), db.ForeignKey('videos.video_id'), nullable=False) retrieved_at = db.Column(db.DateTime(timezone=False)) views = db.Column(db.Integer) likes = db.Column(db.Integer) dislikes = db.Column(db.Integer) comments = db.Column(db.Integer) video = db.relationship('Video', backref=db.backref('video_stats')) def __repr__(self): return '<VideoStat id={}, retrieved_at={}\nviews={} likes={} dislikes={} comments={}>'.format( self.video_id, self.retrieved_at, self.views, self.likes, self.dislikes, self.comments) class Channel(db.Model): """YouTube channel.""" __tablename__ = 'channels' channel_id = db.Column(db.String(24), primary_key=True) channel_title = db.Column(db.String(255)) channel_description = db.Column(db.Text) created_at = db.Column(db.DateTime(timezone=False)) country_code = db.Column(db.String(2), db.ForeignKey('countries.country_code')) country = db.relationship('Country', backref=db.backref('channels')) def __repr__(self): return "<Channel id={} title={}>".format( self.channel_id, self.channel_title) class ChannelStat(db.Model): __tablename__ = 'channel_stats' channel_stat_id = db.Column(db.Integer, autoincrement=True, primary_key=True) channel_id = db.Column(db.String(24), db.ForeignKey('channels.channel_id'), nullable=False) retrieved_at = db.Column(db.DateTime(timezone=False)) total_subscribers = db.Column(db.Integer) total_views = db.Column(db.BigInteger) total_videos = db.Column(db.Integer) total_comments = db.Column(db.Integer) channel = db.relationship('Channel', backref=db.backref('channel_stats')) def __repr__(self): return '<ChannelStat channel_id={}\ntotal_subs={}, total_views={}\nretrieved_at={}>'.format( self.channel_id, self.total_subscribers, self.total_views, self.retrieved_at) class Country(db.Model): """Countries and two-letter ISO country codes.""" __tablename__ = 'countries' country_code = db.Column(db.String(2), primary_key=True) country_name = db.Column(db.String(255)) has_yt_space = db.Column(db.Boolean) def __repr__(self): return '<Country code={} name={}>'.format(self.country_code, self.country_name) class TextAnalysis(db.Model): __tablename__ = 'text_analyses' __table_args__ = (Index('ix_unique_text_analysis', 'textfield', 'video_id', unique=True),) # Ensures only one analysis per video-textfield pair text_analysis_id = db.Column(db.Integer, autoincrement=True, primary_key=True) video_id = db.Column(db.String(11), db.ForeignKey('videos.video_id')) channel_id = db.Column(db.String(24), db.ForeignKey('channels.channel_id'), unique=True) textfield = db.Column(db.String(255)) sentiment_score = db.Column(db.Float) sentiment_magnitude = db.Column(db.Float) sentiment_score_standard_deviation = db.Column(db.Float) sentiment_max_score = db.Column(db.Float) sentiment_min_score = db.Column(db.Float) language_code = db.Column(db.String(4)) video = db.relationship('Video', backref=db.backref('text_analyses')) channel = db.relationship('Channel', backref=db.backref('text_analyses')) def __repr__(self): return '<TextAnalysis for field {} of {}{}\nscore: {}, magnitude: {}>'.format( self.textfield, self.video_id, self.channel_id, self.sentiment_score, self.sentiment_magnitude) class ImageAnalysis(db.Model): __tablename__ = 'image_analyses' image_analysis_id = db.Column(db.Integer, autoincrement=True, primary_key=True) video_id = db.Column(db.String(11), db.ForeignKey('videos.video_id'), unique=True) nsfw_score = db.Column(db.Integer) # Score is from 0 to 100 video = db.relationship('Video', backref=db.backref('image_analyses')) colors = db.relationship('Color', secondary='colors_images', backref=db.backref('image_analyses')) def __repr__(self): return '<ImageAnalysis id={} video={} nsfw_score={}>'.format( self.image_analysis_id, self.video_id, self.nsfw_score) class Tag(db.Model): """A table containing all the tags from video tags and image tags.""" __tablename__ = 'tags' tag_id = db.Column(db.Integer, autoincrement=True, primary_key=True) tag = db.Column(db.String(255), unique=True) videos = db.relationship('Video', secondary='tags_videos', backref=db.backref('tags')) image_analyses = db.relationship('ImageAnalysis', secondary='tags_images', backref=db.backref('tags')) channels = db.relationship('Channel', secondary='tags_channels', backref=db.backref('channels')) def __repr__(self): return '<Tag tag={} id={}>'.format( self.tag, self.tag_id) class TagVideo(db.Model): """An association table connecting the tags and videos tables.""" __tablename__ = 'tags_videos' tag_video_id = db.Column(db.Integer, autoincrement=True, primary_key=True) tag_id = db.Column(db.Integer, db.ForeignKey('tags.tag_id')) video_id = db.Column(db.String(11), db.ForeignKey('videos.video_id')) def __repr__(self): return '<TagVideo id={}>'.format( self.tag_video_id) class TagChannel(db.Model): """An association table connecting the tags and channels tables.""" __tablename__ = 'tags_channels' tag_channel_id = db.Column(db.Integer, autoincrement=True, primary_key=True) tag_id = db.Column(db.Integer, db.ForeignKey('tags.tag_id')) channel_id = db.Column(db.String(11), db.ForeignKey('channels.channel_id')) def __repr__(self): return '<TagChannel id={}>'.format(self.tag_channel_id) class TagImage(db.Model): """An association table connecting the tags and images tables.""" __tablename__ = 'tags_images' tag_image_id = db.Column(db.Integer, autoincrement=True, primary_key=True) image_analysis_id = db.Column(db.Integer, db.ForeignKey('image_analyses.image_analysis_id')) tag_id = db.Column(db.Integer, db.ForeignKey('tags.tag_id')) def __repr__(self): return '<TagImage id={}>'.format( self.tag_image_id) class ColorImage(db.Model): """An association table connecting the color and image_analyses tables.""" __tablename__ = 'colors_images' color_image_id = db.Column(db.Integer, autoincrement=True, primary_key=True) hex_code = db.Column(db.String(7), db.ForeignKey('colors.hex_code')) image_analysis_id = db.Column(db.Integer, db.ForeignKey('image_analyses.image_analysis_id')) def __repr__(self): return '<ColorImage id={}>'.format( self.color_image_id) class Color(db.Model): __tablename__ = 'colors' hex_code = db.Column(db.String(7), primary_key=True) color_name = db.Column(db.String(255)) def __repr__(self): return '<Color id={}, name={}>'.format( self.hex_code, self.color_name) class Document(db.Model): """Document IDs and details for the inverted index.""" __tablename__ = 'documents' document_id = db.Column(db.Integer, autoincrement=True, primary_key=True) document_type = db.Column(db.String, nullable=False) # channel, video, tag, or category document_primary_key = db.Column(db.String(24)) document_subtype = db.Column(db.String) # title, description, video tags, image tags def __repr__(self): return '<Document: id={}, type={}>'.format(self.document_id, self.document_type) class TagChart(db.Model): """A table with info about which tags users are adding to the chart.""" __tablename__ = 'tagcharts' tag_chart_id = db.Column(db.Integer, autoincrement=True, primary_key=True) tag_id = db.Column(db.Integer, db.ForeignKey('tags.tag_id')) added_on = db.Column(db.DateTime(timezone=False)) tag = db.relationship('Tag', backref=db.backref('tagcharts')) class Addition(db.Model): """A table with info on data updates/additions by users.""" __tablename__ = 'additions' addition_id = db.Column(db.Integer, autoincrement=True, primary_key=True) video_id = db.Column(db.String(11), db.ForeignKey('videos.video_id'), nullable=False) added_on = db.Column(db.DateTime(timezone=False)) is_update = db.Column(db.Boolean) video = db.relationship('Video', backref=db.backref('additions')) def __repr__(self): return '<Addition video_id={}, date={}>'.format( self.addition_id, self.added_on) class Search(db.Model): """Searches on website.""" __tablename__ = 'searches' search_id = db.Column(db.Integer, autoincrement=True, primary_key=True) searched_on = db.Column(db.DateTime(timezone=False)) search_text = db.Column(db.String(255)) class Prediction(db.Model): """Predictions about monetization status.""" __tablename__ = 'predictions' prediction_id = db.Column(db.Integer, autoincrement=True, primary_key=True) channel_id = db.Column(db.String(24), db.ForeignKey('channels.channel_id')) predicted_monetization_status = db.Column(db.Boolean) field1 = db.Column(db.Text) field2 = db.Column(db.Text) field3 = db.Column(db.Text) field4 = db.Column(db.Integer) field5 = db.Column(db.Integer) channel = db.relationship('Channel', backref=db.backref('predictions')) class ChannelPerson(db.Model): """An association table connecting the channels and people tables.""" __tablename__ = 'channels_people' channel_person_id = db.Column(db.Integer, autoincrement=True, primary_key=True) channel_id = db.Column(db.String(24), db.ForeignKey('channels.channel_id'), nullable=False) person_id = db.Column(db.Integer, db.ForeignKey('people.person_id'), nullable=False) def __repr__(self): return '<ChannelPerson id={}>'.format(self.channel_person_id) class Person(db.Model): __tablename__ = 'people' person_id = db.Column(db.Integer, autoincrement=True, primary_key=True) person_name = db.Column(db.String(255), unique=True) field1 = db.Column(db.String(255)) field2 = db.Column(db.String(255)) field3 = db.Column(db.String(255)) field4 = db.Column(db.Integer) field5 = db.Column(db.Text) field6 = db.Column(db.Text) field7 = db.Column(db.String(255)) field8 = db.Column(db.String(255)) channel = db.relationship('Channel', secondary='channels_people', backref=db.backref('people')) def __repr__(self): return '<Person {}, id={}>'.format( self.person_name, self.person_id) ##################################################################### # Helper functions def connect_to_db(app, uri='postgresql:///youtube'): """Connect database to the Flask app.""" # Configure to use PostgreSQL. app.config['SQLALCHEMY_DATABASE_URI'] = uri app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.app = app db.init_app(app) if __name__ == '__main__': from server import app connect_to_db(app) db.create_all() print('Successfully connected to DB.')
PHP
UTF-8
5,789
3
3
[]
no_license
<?php /* * Copyright (C) Phonogram Inc 2012 * Licensed Under the MIT license http://www.opensource.org/licenses/mit-license.php */ /* * class BaseModel * モデルを代表するクラス。主にデータベースのレコードかフォームのデータになります。 */ class BaseModel { private static $IS_INITIALIZED = false; private static $CLASS_MODEL_DEFINITIONS; private $changedFields; private $validationErrors; public function BaseModel($values = null) { $this->changedFields = array(); $modelDefinition = self::getClassModelDefinition(get_class($this)); $modelDefinition->initializeObject($this); if (!is_null($values)) { $modelDefinition->set($this, $values, null, false); } $this->changedFields = array(); $this->validationErrors = array(); } public static function classInitialize() { if (self::$IS_INITIALIZED) { return; } self::$CLASS_MODEL_DEFINITIONS = array(); } public static function initializeSubclass($className) { if (isset(self::$CLASS_MODEL_DEFINITIONS[$className])) { return null; } $reflector = new ReflectionClass($className); if (false !== array_search('MODEL_DEFINITION', $reflector->getStaticProperties())) { return; } $modelDefinition = new ModelDefinition($className); $reflector->setStaticPropertyValue('MODEL_DEFINITION', $modelDefinition); self::$CLASS_MODEL_DEFINITIONS[$className] = $modelDefinition; return $modelDefinition; } public static function getClassModelDefinition($class) { return self::$CLASS_MODEL_DEFINITIONS[$class]; } public function getAll() { $modelDefinition = self::getClassModelDefinition(get_class($this)); return $modelDefinition->getAll($this); } /* * set($key, $value) * ウェブからのデータを内部データ形に変換する */ public function set($key, $value = null, $isChanged = true) { $modelDefinition = self::getClassModelDefinition(get_class($this)); return $modelDefinition->set($this, $key, $value, $isChanged); } /* * get() * 内部のデータ形をウェブようの価値に変換した価値を返す。HTMLに埋め込めるデータ形なる */ public function get($key) { $modelDefinition = self::getClassModelDefinition(get_class($this)); return $modelDefinition->get($this, $key); } public function getDb($key) { $modelDefinition = self::getClassModelDefinition(get_class($this)); return $modelDefinition->getDb($this, $key); } /* * val($key[, $value]) * 内部データ形で(変換せずに)価値を取得・設定する */ public function val($key, $value = null) { if ($value === null) { return $this->{$key}; } else { $this->{$key} = $value; $this->_change($key, $value); } } public function nullVal($key) { if (!is_null($this->{$key})) { $this->{$key} = null; $this->_change($key, null); } } public function getVisibleFieldsList() { $modelDefinition = self::getClassModelDefinition(get_class($this)); return $modelDefinition->getFieldList(false); } public function getFieldsList() { $modelDefinition = self::getClassModelDefinition(get_class($this)); return $modelDefinition->getFieldList(true); } public function getLabel($key) { $modelDefinition = self::getClassModelDefinition(get_class($this)); return $modelDefinition->getLabel($key); } public function getType($key) { $modelDefinition = self::getClassModelDefinition(get_class($this)); return $modelDefinition->getType($key); } public function isChanged($field) { return array_key_exists($field, $this->changedFields); } public function hasChanges() { return count($this->changedFields) !== 0; } //record original value. if changed more than once, do not record the subsequent values public function _change($key, $value) { if (!array_key_exists($key, $this->changedFields)) { $this->changedFields[$key] = $this->{$key}; } } // 作成されてから変わった項目の変更を基準の価値として使う。DBに保存するときに使われる。 public function storeChanges() { $this->changedFields = array(); $this->validationErrors = array(); } // オブジェクトが作成されてから変わった項目を、作成の時の価値へ戻す。バリデーションエラーも空にする public function resetChanges() { foreach ($this->changedFields as $key => $value) { $this->{$key} = $value; } $this->changedFields = array(); $this->validationErrors = array(); } public function getValidationErrors() { return $this->validationErrors; } public function addValidationError($field, $message) { $modelDefinition = self::getClassModelDefinition(get_class($this)); if (!$modelDefinition->hasField($field)) { throw new Exception('BaseModel:addValidationError() -- ' . get_class($this) . 'クラスには' . $field . 'というキーはありません。'); } Logger::trace(get_class($this) . '::addValidationError() -- [' . $field . ']' . $message); $this->validationErrors[$field] = $message; } public function resetValidationErrors() { $this->validationErrors = array(); } public function isValid($field = null) { $modelDefinition = self::getClassModelDefinition(get_class($this)); $modelDefinition->isValid($this, $field); return !$this->hasErrors(); } public function hasErrors() { return count($this->validationErrors) > 0; } public function hasError($key) { return array_key_exists($key, $this->validationErrors); } public function getError($key) { return $this->validationErrors[$key]; } }
JavaScript
UTF-8
2,165
3.046875
3
[ "MIT" ]
permissive
var Toucan = module.exports = function(){ var locked = false; var perms = {} var _permit = function(permission){ if(locked) { throw new Error("Cannot add permissions after token has been locked"); } perms[permission] = true; } var _deny = function(permission){ if(locked) { throw new Error("Cannot add permissions after token has been locked"); } perms[permission] = false; } return { permit: function(permission) { if(permission instanceof Array) { for(var i = 0; i < permission.length; i++) { _permit(permission[i]); } }else{ _permit(permission); } return this; }, deny: function(permission) { if(permission instanceof Array) { for(var i = 0; i < permission.length; i++) { _deny(permission[i]); } }else{ _deny(permission); } return this; }, lock: function(permission) { locked = true; return this; }, can: function(permission) { if(!locked) { throw new Error("Access token is not locked") } // Allow-by-default mode if("*" in perms) { // Allow all on, check for any explicit denies if(permission in perms){ return perms[permission]; } // Or allow by default return true; } // Permission must be explicitly set if(permission in perms) { return perms[permission]; } // Deny by default return false; }, cannot: function(permission) { // Convenience function return !this.can(permission); } } }
Ruby
UTF-8
906
3.78125
4
[]
no_license
def translate(words) many_words = words.split(" ") finally = [] if many_words.length == 1 return pig_latin_one_word(words) else many_words.each do |word| finally << pig_latin_one_word(word) end end return finally.join(" ") end def pig_latin_one_word(word) vowels = "aeiou" translated = "" if word.include?("qu") location = word.index("qu") translated = word[location + 2..-1] + word[0...location] + "quay" return translated else word.each_char.with_index do |char, i| if vowels.include?(char) && (i == 0) translated = word + "ay" return translated elsif vowels.include?(char) translated = word[i..-1] + word[0...i] + "ay" return translated end end end end
Swift
UTF-8
3,185
2.515625
3
[]
no_license
// // AnnounceList.swift // KeepChild // // Created by Clément Martin on 13/09/2019. // Copyright © 2019 Clément Martin. All rights reserved. // import Foundation import FirebaseFirestore import CodableFirebase class AnnounceList { var delegateAnnounceList: AnnounceListDelegate? var announceReference: DocumentReference? fileprivate var query: Query? { didSet { if let listener = listener { listener.remove() // observeQuery() } } } private var listener: ListenerRegistration? var documents: [DocumentSnapshot] = [] var didChangeData: ((AnnounceListData) -> Void)? var announce: Announce! var announceListData = [Announce]() var idUser = String() /* var viewData: AnnounceListData { didSet { didChangeData?(viewData) } }*/ /* init(viewData: AnnounceListData) { self.viewData = viewData query = baseQuery() }*/ func readData() { announceListData = [Announce]() Firestore.firestore().collection("Announce2").getDocuments { (querySnapshot, err) in if let err = err { print("erreur : \(err)") } else { for document in querySnapshot!.documents { let announce = try! FirestoreDecoder().decode(Announce.self, from: document.data()) self.announceListData.append(announce) print(document.documentID, document.data()) } } self.delegateAnnounceList?.updateTableView() } } func addData(announce: Announce) { let docData = try! FirestoreEncoder().encode(announce) Firestore.firestore().collection("Announce2").addDocument(data: docData) { error in if let error = error { print("Error writing document: \(error)") } else { print("Document successfully written!") } } } /* func observeQuery() { /* guard let query = query else { return } stopObserving() listener = query.addSnapshotListener { (snapshot, error) in guard let snapshot = snapshot else { print("Error fetching snapshot results: \(error!)") return } */ Firestore.firestore().collection("Announce").getDocuments { (document, error) in if let document = document { let model = try! FirestoreDecoder().decode(Announce.self, from: document) print(model) self.announceListData = [model] } else { print("document no exist") } } // self.documents = snapshot.documents //} }*/ func stopObserving() { listener?.remove() } fileprivate func baseQuery() -> Query { return Firestore.firestore().collection("Announce").limit(to: 50) } } protocol AnnounceListDelegate { func updateTableView() }
SQL
UTF-8
12,256
2.890625
3
[]
no_license
-- MySQL dump 10.13 Distrib 5.7.17, for Win32 (AMD64) -- -- Host: localhost Database: ihome -- ------------------------------------------------------ -- Server version 5.7.17-log /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `alembic_version` -- DROP TABLE IF EXISTS `alembic_version`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `alembic_version` ( `version_num` varchar(32) NOT NULL, PRIMARY KEY (`version_num`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `alembic_version` -- LOCK TABLES `alembic_version` WRITE; /*!40000 ALTER TABLE `alembic_version` DISABLE KEYS */; INSERT INTO `alembic_version` VALUES ('54a4d2e55ea2'); /*!40000 ALTER TABLE `alembic_version` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `ih_area_info` -- DROP TABLE IF EXISTS `ih_area_info`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ih_area_info` ( `create_time` datetime DEFAULT NULL, `update_time` datetime DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `ih_area_info` -- LOCK TABLES `ih_area_info` WRITE; /*!40000 ALTER TABLE `ih_area_info` DISABLE KEYS */; INSERT INTO `ih_area_info` VALUES (NULL,NULL,1,'黄浦区'),(NULL,NULL,2,'徐汇区'),(NULL,NULL,3,'长宁区'),(NULL,NULL,4,'静安区'),(NULL,NULL,5,'普陀区'),(NULL,NULL,6,'虹口区'),(NULL,NULL,7,'杨浦区'),(NULL,NULL,8,'闵行区'),(NULL,NULL,9,'宝山区'),(NULL,NULL,10,'嘉定区'),(NULL,NULL,11,'浦东新区'),(NULL,NULL,12,'金山区'),(NULL,NULL,13,'松江区'),(NULL,NULL,14,'青浦区'),(NULL,NULL,15,'奉贤区'),(NULL,NULL,16,'崇明区'); /*!40000 ALTER TABLE `ih_area_info` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `ih_facility_info` -- DROP TABLE IF EXISTS `ih_facility_info`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ih_facility_info` ( `create_time` datetime DEFAULT NULL, `update_time` datetime DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `ih_facility_info` -- LOCK TABLES `ih_facility_info` WRITE; /*!40000 ALTER TABLE `ih_facility_info` DISABLE KEYS */; INSERT INTO `ih_facility_info` VALUES (NULL,NULL,1,'无线网络'),(NULL,NULL,2,'热水淋浴'),(NULL,NULL,3,'空调'),(NULL,NULL,4,'暖气'),(NULL,NULL,5,'允许吸烟'),(NULL,NULL,6,'饮水设备'),(NULL,NULL,7,'牙具'),(NULL,NULL,8,'香皂'),(NULL,NULL,9,'拖鞋'),(NULL,NULL,10,'手纸'),(NULL,NULL,11,'毛巾'),(NULL,NULL,12,'沐浴露、洗发露'),(NULL,NULL,13,'冰箱'),(NULL,NULL,14,'洗衣机'),(NULL,NULL,15,'电梯'),(NULL,NULL,16,'允许做饭'),(NULL,NULL,17,'允许带宠物'),(NULL,NULL,18,'允许聚会'),(NULL,NULL,19,'门禁系统'),(NULL,NULL,20,'停车位'),(NULL,NULL,21,'有线网络'),(NULL,NULL,22,'电视'),(NULL,NULL,23,'浴缸'); /*!40000 ALTER TABLE `ih_facility_info` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `ih_house_facility` -- DROP TABLE IF EXISTS `ih_house_facility`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ih_house_facility` ( `house_id` int(11) NOT NULL, `facility_id` int(11) NOT NULL, PRIMARY KEY (`house_id`,`facility_id`), KEY `facility_id` (`facility_id`), CONSTRAINT `ih_house_facility_ibfk_1` FOREIGN KEY (`facility_id`) REFERENCES `ih_facility_info` (`id`), CONSTRAINT `ih_house_facility_ibfk_2` FOREIGN KEY (`house_id`) REFERENCES `ih_house_info` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `ih_house_facility` -- LOCK TABLES `ih_house_facility` WRITE; /*!40000 ALTER TABLE `ih_house_facility` DISABLE KEYS */; INSERT INTO `ih_house_facility` VALUES (2,1),(5,1),(1,2),(3,2),(5,2),(1,3),(5,3),(4,4),(5,4),(5,5),(5,9),(5,10),(5,11),(5,12),(5,13),(5,14),(1,15),(1,19),(1,21); /*!40000 ALTER TABLE `ih_house_facility` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `ih_house_image` -- DROP TABLE IF EXISTS `ih_house_image`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ih_house_image` ( `create_time` datetime DEFAULT NULL, `update_time` datetime DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `url` varchar(256) NOT NULL, `house_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `house_id` (`house_id`), CONSTRAINT `ih_house_image_ibfk_1` FOREIGN KEY (`house_id`) REFERENCES `ih_house_info` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `ih_house_image` -- LOCK TABLES `ih_house_image` WRITE; /*!40000 ALTER TABLE `ih_house_image` DISABLE KEYS */; INSERT INTO `ih_house_image` VALUES ('2018-01-10 16:36:30','2018-01-10 16:36:30',1,'FoZg1QLpRi4vckq_W3tBBQe1wJxn',4),('2018-01-10 16:37:03','2018-01-10 16:37:03',2,'FsHyv4WUHKUCpuIRftvwSO_FJWOG',4),('2018-01-10 16:37:58','2018-01-10 16:37:58',3,'FsxYqPJ-fJtVZZH2LEshL7o9Ivxn',4),('2018-01-10 19:33:30','2018-01-10 19:33:30',4,'FsHyv4WUHKUCpuIRftvwSO_FJWOG',5),('2018-01-10 19:37:43','2018-01-10 19:37:43',5,'FsxYqPJ-fJtVZZH2LEshL7o9Ivxn',5),('2018-01-10 19:38:01','2018-01-10 19:38:01',6,'FoZg1QLpRi4vckq_W3tBBQe1wJxn',5); /*!40000 ALTER TABLE `ih_house_image` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `ih_house_info` -- DROP TABLE IF EXISTS `ih_house_info`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ih_house_info` ( `create_time` datetime DEFAULT NULL, `update_time` datetime DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(64) NOT NULL, `price` int(11) DEFAULT NULL, `address` varchar(512) DEFAULT NULL, `room_count` int(11) DEFAULT NULL, `acreage` int(11) DEFAULT NULL, `unit` varchar(32) DEFAULT NULL, `capacity` int(11) DEFAULT NULL, `beds` varchar(64) DEFAULT NULL, `deposit` int(11) DEFAULT NULL, `min_days` int(11) DEFAULT NULL, `max_days` int(11) DEFAULT NULL, `order_count` int(11) DEFAULT NULL, `index_image_url` varchar(256) DEFAULT NULL, `user_id` int(11) NOT NULL, `area_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `area_id` (`area_id`), KEY `user_id` (`user_id`), CONSTRAINT `ih_house_info_ibfk_1` FOREIGN KEY (`area_id`) REFERENCES `ih_area_info` (`id`), CONSTRAINT `ih_house_info_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `ih_user_profile` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `ih_house_info` -- LOCK TABLES `ih_house_info` WRITE; /*!40000 ALTER TABLE `ih_house_info` DISABLE KEYS */; INSERT INTO `ih_house_info` VALUES ('2018-01-10 12:00:03','2018-01-10 12:00:03',1,'海景房',100000,'航头镇航都路18号',1,10,'一室',2,'双人床:2x1.8x1张',200000,1,1,0,'',4,11),('2018-01-10 16:11:46','2018-01-10 16:11:46',2,'1',100,'1',1,1,'1',1,'1',100,1,1,0,'',4,1),('2018-01-10 16:25:10','2018-01-10 16:25:10',3,'1',100,'1',1,1,'1',1,'1',100,1,1,0,'',4,1),('2018-01-10 16:36:21','2018-01-10 16:36:30',4,'1',100,'1',1,1,'1',1,'1',100,1,1,0,'FoZg1QLpRi4vckq_W3tBBQe1wJxn',4,1),('2018-01-10 19:32:34','2018-01-10 19:33:30',5,'学区房',99900,'航头镇航都路18号',3,30,'两室一厅',4,'2x1.8x1张 1.5x1.8x2张',199900,1,0,0,'FsHyv4WUHKUCpuIRftvwSO_FJWOG',4,11); /*!40000 ALTER TABLE `ih_house_info` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `ih_order_info` -- DROP TABLE IF EXISTS `ih_order_info`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ih_order_info` ( `create_time` datetime DEFAULT NULL, `update_time` datetime DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `house_id` int(11) NOT NULL, `begin_date` datetime NOT NULL, `end_date` datetime NOT NULL, `days` int(11) NOT NULL, `house_price` int(11) NOT NULL, `amount` int(11) NOT NULL, `status` enum('WAIT_ACCEPT','WAIT_PAYMENT','PAID','WAIT_COMMENT','COMPLETE','CANCELED','REJECTED') DEFAULT NULL, `comment` text, PRIMARY KEY (`id`), KEY `house_id` (`house_id`), KEY `user_id` (`user_id`), KEY `ix_ih_order_info_status` (`status`), CONSTRAINT `ih_order_info_ibfk_1` FOREIGN KEY (`house_id`) REFERENCES `ih_house_info` (`id`), CONSTRAINT `ih_order_info_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `ih_user_profile` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `ih_order_info` -- LOCK TABLES `ih_order_info` WRITE; /*!40000 ALTER TABLE `ih_order_info` DISABLE KEYS */; /*!40000 ALTER TABLE `ih_order_info` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `ih_user_profile` -- DROP TABLE IF EXISTS `ih_user_profile`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ih_user_profile` ( `create_time` datetime DEFAULT NULL, `update_time` datetime DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL, `password_hash` varchar(128) NOT NULL, `mobile` varchar(11) NOT NULL, `real_name` varchar(32) DEFAULT NULL, `id_card` varchar(20) DEFAULT NULL, `avatar_url` varchar(128) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `mobile` (`mobile`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `ih_user_profile` -- LOCK TABLES `ih_user_profile` WRITE; /*!40000 ALTER TABLE `ih_user_profile` DISABLE KEYS */; INSERT INTO `ih_user_profile` VALUES ('2018-01-05 17:03:05','2018-01-05 17:03:05',1,'18812345678','pbkdf2:sha256:50000$DC4xZgpk$430a754b40e02fdb8edc3786cb005f08e4c687e3a86772569facc95ddd44104e','18812345678',NULL,NULL,NULL),('2018-01-05 20:05:46','2018-01-05 20:05:46',2,'18811234567','pbkdf2:sha256:50000$WChQFnGO$583d65d6d1e5f1145ceedcd5c980079c3d299c2d21e4e7bf5a8ee3eecd99b75b','18811234567',NULL,NULL,NULL),('2018-01-05 20:12:24','2018-01-06 22:19:10',3,'zsj1','pbkdf2:sha256:50000$BztLKyDA$171f2fcdb2aefa9276bc3fa60682efc4773d8235ec34369bead5c44d950bbb96','18821345678',NULL,NULL,'FvWngEQNM09Ma4Ba08I1hn7OKcTU'),('2018-01-06 22:43:26','2018-01-07 20:12:19',4,'zsj','pbkdf2:sha256:50000$n3qp36ki$289dfaafefa15061facbee456e49647a9dd92b1873c6b2d924a0f76f2f20e27f','18822345678','zsj','123456789','FvWngEQNM09Ma4Ba08I1hn7OKcTU'); /*!40000 ALTER TABLE `ih_user_profile` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-01-11 20:37:51
Ruby
UTF-8
3,652
3.375
3
[ "MIT" ]
permissive
require 'drudge/errors' require 'drudge/parsers' require 'drudge/parsers/types' class Drudge # Describes a command and helps executing it # # The command is defined by a name and a list of arguments (see class Param). # The body of the command is a lambda that accepts exactly the arguments class Command include Parsers # The name of the command attr_reader :name # The list of parameters attr_reader :params # A hash of the keyword parameters attr_reader :keyword_params # The command's body attr_reader :body # An optional short desicription of the command attr_reader :desc # Initializes a new command def initialize(name, params = [], body, desc: "") @name = name.to_sym @params = params.select { |p| Param === p } @keyword_params = Hash[params.select { |p| KeywordParam === p } .map { |p| [p.name, p] }] @body = with_keyword_arg_handling(body) @desc = desc end # runs the command def dispatch(*args, **keyword_args) @body.call(*args, **keyword_args) rescue ArgumentError => e raise CommandArgumentError.new(name), e.message end # creates an argument parser for the command def argument_parser keyword_arguments_parser > plain_arguments_parser end private def keyword_arguments_parser if keyword_params.any? keywords_end = optend.optional keyword_argument_parser = keyword_params.values.map(&:argument_parser).reduce(&:|) keyword_argument_parser.repeats(:*) > keywords_end else success(Empty()) end end def plain_arguments_parser end_of_args = eos("extra command line arguments provided") parser = params.reverse.reduce(end_of_args) do |rest, param| p = param.argument_parser case when param.optional? then ((p > rest) | rest).describe("[#{p}] #{rest}") when param.splatt? then (p.repeats(till: rest) > rest).describe("[#{p} ...] #{rest}") else p > rest end end end def with_keyword_arg_handling(proc) -> *args, **keyword_args do if keyword_args.empty? proc.call(*args) else proc.call(*args, **keyword_args) end end end end class AbstractParam include Parsers # the argument's name attr_reader :name # the argument's type attr_reader :type # initializes the param def initialize(name, type) @name = name.to_sym @type = type.to_sym end # external name of the parameter def external_name to_external(name) end # Converts an internal name to external one for use in the shell def to_external(str) str.to_s.tr('_', '-') end protected :to_external end # Represents a command parameter class Param < AbstractParam attr_reader :optional alias_method :optional?, :optional attr_reader :splatt alias_method :splatt?, :splatt def initialize(name, type, optional: false, splatt: false) super(name, type) @optional = !! optional @splatt = !! splatt end # returns a parser that is able to parse arguments # fitting this parameter def argument_parser arg(external_name, value(type)) end end # represents a keyword parameter class KeywordParam < AbstractParam # returns a parser that is able to parse the keyword argument def argument_parser keyword_arg(external_name, name, value(type)) end end end
C
UTF-8
1,400
2.671875
3
[]
no_license
/* ** EPITECH PROJECT, 2018 ** my_defender ** File description: ** map_load */ #include "defender.h" sfVector2f get_castle_pos(tiles_t *tile_list) { sfVector2f error = {0, 0}; for (tiles_t *tile = tile_list; tile != NULL; tile = tile->next) { if (tile->type == 'G') { return (tile->visual->position); } } return (error); } char **create_map(FILE *map_stream) { size_t len = 1; char **map = malloc(sizeof(char *) * (12)); map[11] = NULL; for (size_t i = 0; i < 11; i++) { map[i] = NULL; getline(&map[i], &len, map_stream); } fclose(map_stream); return (map); } map_t *load_map(char *file_path){ FILE *map_stream = fopen(file_path, "r+"); map_t *map = malloc(sizeof(map_t)); map->map = create_map(map_stream); map->map_correct = sfTrue; map->tile_list = create_tile_list(map->map); get_map_start(map); map->castle = create_castle(map->tile_list); return (map); } void draw_map(map_t *map, sfRenderWindow *window) { for (tiles_t *tmp = map->tile_list; tmp != NULL; tmp = tmp->next) sfRenderWindow_drawSprite(window, tmp->visual->sprite, NULL); draw_castle(window, map->castle); } void destroy_map(map_t *map) { destroy_tile_list(map->tile_list); for (int y = 0; map->map[y] != NULL; y++) free(map->map[y]); free(map->map); free(map); }
Java
UTF-8
295
2.875
3
[ "MIT" ]
permissive
package util; public class AddressRange { public final long start; public final long end; public AddressRange(long startAddress, long endAddress) { start = startAddress; end = endAddress; } public Boolean contains(long address) { return (address >= start && address < end); } }
Java
UTF-8
828
2.4375
2
[]
no_license
package com.hit.server; import com.google.gson.Gson; @SuppressWarnings("serial") public class Request<T> extends java.lang.Object implements java.io.Serializable { private java.util.Map<java.lang.String, java.lang.String> headers; T body; public Request(java.util.Map<java.lang.String,java.lang.String> headers,T body) { this.body = body; this.headers = headers; } public java.util.Map<java.lang.String,java.lang.String> getHeaders() { return headers; } public void setHeaders(java.util.Map<java.lang.String,java.lang.String> headers) { this.headers = headers; } public T getBody() { return this.body; } public void setBody(T body) { this.body = body; } public java.lang.String toString() { return new Gson().toJson(this).toString(); } }
C#
UTF-8
1,711
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace VehicleSimulator { public partial class frmChangeVehicleODO : Form { public double? NewODO { get; private set; } public frmChangeVehicleODO(double dblCurrentODO, string strUnits) { InitializeComponent(); txtNewODO.KeyPress += Program.txtNumericWithDecimal_KeyPress; NewODO = null; lblUnits.Text = strUnits; txtCurrentODO.Text = dblCurrentODO.ToString(); } private void cmdCancel_Click(object sender, EventArgs e) { NewODO = null; this.DialogResult = DialogResult.Cancel; Hide(); Close(); } private void txtNewODO_TextChanged(object sender, EventArgs e) { txtNewODO.Text = txtNewODO.Text.Trim(); cmdOK.Enabled = txtNewODO.Text.Length > 0; } private void cmdOK_Click(object sender, EventArgs e) { try { NewODO = System.Convert.ToDouble(txtNewODO.Text); this.DialogResult = DialogResult.OK; Hide(); Close(); } catch { cmdCancel_Click(sender, e); } } private void frmChangeVehicleODO_Load(object sender, EventArgs e) { txtNewODO.Focus(); } } // public partial class frmChangeVehicleODO : Form } // namespace VehicleSimulator
Java
UTF-8
906
2.859375
3
[]
no_license
package lcwu; public class Solution88 { public void merge(int[] nums1, int m, int[] nums2, int n) { int sum[]=new int[m+n]; int i =0; for(;i<m;i++){ sum[i]=nums1[i]; } for(i =0;i<n;i++){ sum[i+m]=nums2[i]; } int temp=0; for(int j=0;j<m+n-1;j++){ for(int k=0;k<m+n-1;k++){ if(sum[k]>sum[k+1]){ temp = sum[k]; sum[k]=sum[k+1]; sum[k+1]=temp; } } } for(i=0;i<m+n;i++){ nums1[i]=sum[i]; } } public static void main(String args[]){ int nums[]={4,5,6,0,0,0}; int ai[]={1,2,3}; Solution88 s88 = new Solution88(); s88.merge(nums,3,ai,3); for(int i =0;i<6;i++){ System.out.println(nums[i]); } } }
Markdown
UTF-8
7,588
2.546875
3
[ "MIT" ]
permissive
[![npm version](https://badge.fury.io/js/cdk-apig-utility.svg)](https://badge.fury.io/js/cdk-apig-utility) [![Coverage Status](https://coveralls.io/repos/github/A-Kurimoto/cdk-apig-utility/badge.svg?branch=master)](https://coveralls.io/github/A-Kurimoto/cdk-apig-utility?branch=master) cdk-apig-utility ==== Have you ever wished that Swagger could be automatically generated from JSDoc? It auto-generates useful CDK’s objects from TypeScript entity(and its JSDoc) to define swagger easily at API Gateway. # Requirement - aws-cdk-lib@2.51.1 - constructs@10.1.168 - typescript@4.9.3 # Install ```bash $ npm install cdk-apig-utility ``` # Usage At first, please understand the following CDK's document. - [Working with models](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigateway-readme.html#working-with-models) Following is the example of CDK. ```typescript // We define the JSON Schema for the transformed valid response const responseModel = api.addModel('ResponseModel', { contentType: 'application/json', modelName: 'ResponseModel', schema: { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'pollResponse', 'type': 'object', 'properties': { 'state': { 'type': 'string' }, 'greeting': { 'type': 'string' } } } }); ``` ```typescript const integration = new LambdaIntegration(hello, { proxy: false, requestParameters: { // You can define mapping parameters from your method to your integration // - Destination parameters (the key) are the integration parameters (used in mappings) // - Source parameters (the value) are the source request parameters or expressions // @see: https://docs.aws.amazon.com/apigateway/latest/developerguide/request-response-data-mappings.html 'integration.request.querystring.who': 'method.request.querystring.who' }, ... ``` Perhaps you were in pain when you had to write the same contents of the entity in the generation of models and request parameters. Moreover, you must create the [CfnDocumentationPart](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.CfnDocumentationPart.html) object so as to write the description of request parameters. You can auto-generate the above objects from following examples. ## Model ### Example Model can be generated from entity objects. ```typescript:sample-if.ts import {SubIf} from './sub/sub-if'; export interface SampleIf { /** * @desc JSDoc of param1 */ param1: string; /** * @description JSDoc of param2 */ param2: number; /** * ignored comment of param3 */ param3: boolean; param4: string[]; param5: number[]; param6: boolean[]; param7: SubIf; param8: SubIf[]; } ``` ```typescript:sub-if.ts export interface SubIf { subParam1: string; } ``` ### Execution ```typescript import {CdkApigUtility} from 'cdk-apig-utility'; import {ModelOptions} from 'aws-cdk-lib/aws-apigateway'; // You can also use getModelsFromDir method. const modelOptions: ModelOptions[] = new CdkApigUtility().getModelsFromFiles(['sample-if.ts', 'sub/sub-if.ts']); // You can search the model what you want by 'modelName'(It has a class name or interface name). const targetModel = modelOptions.find(modelOption => modelOption.modelName === 'SampleIf') as ModelOptions; ``` ### Result ```json { "contentType": "application/json", "modelName": "SampleIf", "schema": { "schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "param1": {"type": "string", "description": "jsDoc of param1"}, "param2": {"type": "number", "description": "jsDoc of param2"}, "param3": {"type": "boolean", "description": "No description."}, "param4": { "type": "array", "description": "No description.", "items": {"type": "string"} }, "param5": { "type": "array", "description": "No description.", "items": {"type": "number"} }, "param6": { "type": "array", "description": "No description.", "items": {"type": "boolean"} }, "param7": { "type": "object", "description": "No description.", "properties": {"subParam1": {"type": "string", "description": "No description."}} }, "param8": { "type": "array", "description": "No description.", "items": { "type": "object", "properties": {"subParam1": {"type": "string", "description": "No description."}} } } } } } ``` If you have written the JSDoc's `@desc` or `@description` tag at the property, it can be converted to description. ## Request parameters ### Example Request parameters can be generated from method's arguments. ```typescript:sample-dao.ts /** * This is sample method. * * @param limit * @param sort 1:ascending 2:descending * @param word some word * @param isSomeFlg some boolean value1¬ * @param someArray some array */ async getSomething1(limit: number, offset: number, sort: number, word?: string, isSomeFlg?: boolean, someArray?: string[]): Promise<any> { } ``` ### Execution ```typescript const requestParameters = new CdkApigUtility().getRequestQueryStringParams('example/dao/sample-dao.ts', 'getSomething1'); ``` ### Result ```json { "method.request.querystring.limit": true, "method.request.querystring.offset": true, "method.request.querystring.sort": true, "method.request.querystring.word": false, "method.request.querystring.isSomeFlg": false, "method.request.querystring.someArray": false } ``` The values(true or false) can be generated from '?' of arguments. ## Request parameter's documents Request parameters' documents can be generated from method's arguments and JSDoc. ```typescript:sample-dao.ts /** * This is sample method. * * @param limit * @param sort 1:ascending 2:descending * @param word some word * @param isSomeFlg some boolean value1¬ * @param someArray some array */ async getSomething1(limit: number, offset: number, sort: number, word?: string, isSomeFlg?: boolean, someArray?: string[]): Promise<any> { } ``` ### Execution ```typescript const descriptions = new CdkApigUtility().getArgumentDescriptions('example/dao/sample-dao.ts', 'getSomething1'); ``` ### Result ```json [ { "name": "sort", "description": "1:ascending\n2:descending" }, { "name": "word", "description": "some word" }, { "name": "isSomeFlg", "description": "some boolean value1" }, { "name": "someArray", "description": "some array" } ] ``` If you have written the JSDoc's `@param` tag at the method, it can be converted to description. You can use this result when you create the [CfnDocumentationPart](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.CfnDocumentationPart.html). ## How to use with CDK. Please see the following test code. [create cf template](https://github.com/A-Kurimoto/cdk-apig-utility/blob/master/test/test.ts) You can use this model at both request and response. # Licence [MIT](https://github.com/A-Kurimoto/cdk-apig-utility/blob/master/LICENSE) # Author [A-Kurimoto](https://github.com/A-Kurimoto)
Python
UTF-8
6,870
4
4
[ "BSD-3-Clause" ]
permissive
""" Investigation of Euler method for integrating ODE: error vs number of steps. It shows that for unstable cases, increasing the number of steps does not always improve the approximation. """ import numpy as np import matplotlib.pyplot as plt def euler_met_1(f, xa, xb, ya, n, verbose=False, y_ground=None, return_all=True): """ First Order ODE (y' = f(x, y)) Solver using Euler method :param f: input function :param xa: left extreme of the value of independent variable :param xb: left extreme of value of independent variable :param ya: initial value of dependent variable :param n : number of steps :param verbose : :param y_ground : :param return_all : for debug purposes :return : value of y at xb. ans has three or five column: step, x, w, [ground, truncating error] Simplified version: h = (xb - xa) / float(n) x = xa w = ya for i in range(n): w += h * f(x, w) x += h return y """ h = (xb - xa) / float(n) x = xa w = ya if return_all: if y_ground is None: ans = np.zeros([n+1, 3]) else: ans = np.zeros([n+1, 5]) ans[0, 0] = 0 ans[0, 1] = x ans[0, 2] = w if y_ground is not None: ans[0, 3] = y_ground(x) ans[0, 4] = np.abs(w - y_ground(x)) if verbose: print(ans[0, :]) for i in range(1, n+1): w += h * f(x, w) x += h if return_all: ans[i, 0] = i ans[i, 1] = x ans[i, 2] = w if y_ground is not None: ans[i, 3] = y_ground(x) ans[i, 4] = np.abs(w - y_ground(x)) if verbose: print(ans[i, :]) if return_all: return ans else: return w if __name__ == "__main__": # Functions collection: def f1(x, y): return y * np.cos(x) def y1_ground(x): return np.exp(np.sin(x)) # parameter of f2: alpha = 7 # range from 2 to 12 def f2(x, y): return alpha * y - (alpha + 1) * np.exp(-x) def y2_ground(x): return np.exp(-x) def f3(x, y): l = 50 # to be considered within the perturbation on the initial condition return l*y - l def y3_ground(x): return 1.0 # ## Cauchy problem 1 ### if 1: x0 = 0 x1 = 5 y0 = 1 num_steps = [5, 10, 15, 20, 25, 30, 50] # Figure fig, ax = plt.subplots(ncols=2, nrows=1, figsize=(12, 5), dpi=100) fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.1) xx = np.linspace(x0, x1, 10000) yy = [y1_ground(x) for x in xx] ax[0].plot(xx, yy, '-', label='ground', color='g') for num_step in num_steps: ans1 = euler_met_1(f1, x0, x1, y0, num_step, y_ground=y1_ground) ax[0].plot(ans1[:, 1], ans1[:, 2], '--+', label='steps = ' + str(num_step)) # Figure of error versus iteration numbers. ax[1].plot(ans1[:, 0], ans1[:, 4], '--+', label='Error') # Labels, grids legend and titles ax[0].grid(True) ax[0].set_title('Euler method vs ground truth') ax[0].set_xlabel(r'$x$') ax[0].set_ylabel(r'$y$') ax[0].legend(loc='upper right') # add mathematical formula ax[0].text(0.5, 0.5, r'Ground: $y(x)=\exp(\sin(x))$') ax[0].text(0.5, 0.1, r'ODE: $\frac{dy}{dx}=y \cdot \cos(x)$, $y(0)=1$') # Labels, grids legend and titles ax[1].grid(True) ax[1].set_title('Number of steps versus errors') ax[1].set_xlabel(r'Steps') ax[1].set_ylabel(r'Error') # ## Cauchy problem 2 ### if 1: x0 = 0 x1 = 1 y0 = 1 num_steps = [3, 5, 10, 25, 50] # Figure: fig, ax2 = plt.subplots(ncols=2, nrows=1, figsize=(12, 5), dpi=130) fig.subplots_adjust(left=0.075, right=0.80, top=0.9, bottom=0.1) xx = np.linspace(x0, x1, 1000) yy = [y2_ground(x) for x in xx] ax2[0].plot(xx, yy, '-', label='ground', color='g') for num_step in num_steps: ans2 = euler_met_1(f2, x0, x1, y0, num_step, y_ground=y2_ground) ax2[0].plot(ans2[:, 1], ans2[:, 2], '--+', label='step ' + str(num_step)) # Figure of error versus iteration numbers. ax2[1].plot(ans2[:, 0], ans2[:, 4], '--+', label='Error') # Labels, grids legend and titles ax2[0].grid(True) ax2[0].set_title('Euler method vs ground truth') ax2[0].set_xlabel(r'$x$') ax2[0].set_ylabel(r'$y$') ax2[0].legend(loc='lower left') # add mathematical formula fig.text(.82, .8, r'ODE:') fig.text(.82, .72, r'$\frac{dy}{dx}=\alpha y - (\alpha + 1) \exp(-x)$') fig.text(.82, .67, r'$y(0) = 1$') fig.text(.82, .58, r'Ground: ') fig.text(.82, .5, r'$y(x)=\exp(-x)$') fig.text(.82, .38, r'Parameter: ') fig.text(.82, .31, r'$\alpha = $ ' + str(alpha)) # Labels, grids legend and titles ax2[1].grid(True) ax2[1].set_title('Number of steps versus errors') ax2[1].set_xlabel(r'Steps') ax2[1].set_ylabel(r'Error') # ## Cauchy problem 3 ### if 1: x0 = 0 x1 = 1 perturbation = 0.000001 # regulate with the parameter function l y0 = 1 + perturbation num_steps = [3, 5, 7] # Figure: fig, ax2 = plt.subplots(ncols=2, nrows=1, figsize=(12, 5), dpi=100) fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.1) xx = np.linspace(x0, x1, 1000) yy = [y3_ground(x) for x in xx] ax2[0].plot(xx, yy, '-', label='ground', color='g') for num_step in num_steps: ans3 = euler_met_1(f3, x0, x1, y0, num_step, y_ground=y3_ground) ax2[0].plot(ans3[:, 1], ans3[:, 2], '--+', label='step ' + str(num_step)) # Figure of error versus iteration numbers. ax2[1].plot(ans3[:, 0], ans3[:, 4], '--+', label='Error') # Labels, grids legend and titles y_val = ax2[0].get_ylim() ax2[0].set_ylim([0.4, max(y_val[1], 2)]) ax2[0].grid(True) ax2[0].set_title('Euler method vs ground truth') ax2[0].set_xlabel(r'$x$') ax2[0].set_ylabel(r'$y$') ax2[0].legend(loc='lower left') # add mathematical formula #ax2[0].text(0.5, 0.5, r'Ground: $y(x)=\exp(\sin(x))$') #ax2[0].text(0.5, 0.1, r'ODE: $\frac{dy}{dx}=y \cdot \cos(x)$, $y(0)=1$') # Labels, grids legend and titles ax2[1].grid(True) ax2[1].set_title('Number of steps versus errors') ax2[1].set_xlabel(r'Steps') ax2[1].set_ylabel(r'Error') plt.show()
Java
UTF-8
7,211
2
2
[]
no_license
package io.cran.trippy.activities; import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Intent; import android.media.Image; import android.support.v4.app.DialogFragment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SignUpCallback; import io.cran.trippy.R; import io.cran.trippy.fragments.DatePickerFragment; import io.cran.trippy.utils.AppPreferences; public class SignUpActivity extends AppCompatActivity implements DatePickerFragment.DatePickerListener { protected EditText mFirstName; protected EditText mLastName; protected EditText mEmailAddress; protected TextView mBirthDate; protected EditText mPassword; protected EditText mRepeatPass; protected ImageView mSignUpBtn; private ObjectAnimator mAnimator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); mFirstName= (EditText) findViewById(R.id.firstNameET); mLastName=(EditText) findViewById(R.id.lastNameET); mEmailAddress=(EditText) findViewById(R.id.emailAddressET); mBirthDate = (TextView) findViewById(R.id.birthDate); mBirthDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } }); mPassword=(EditText)findViewById(R.id.password); mRepeatPass = (EditText) findViewById(R.id.confirmPassword); mSignUpBtn= (ImageView) findViewById(R.id.signUpBtn); mSignUpBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String firstName = mFirstName.getText().toString().trim(); final String lastName = mLastName.getText().toString().trim(); final String emailAddress = mEmailAddress.getText().toString().trim(); String birthDate= mBirthDate.getText().toString().trim(); String password= mPassword.getText().toString().trim(); String repeatPass = mRepeatPass.getText().toString().trim(); if (password.equals(repeatPass)) { ParseUser newUser= new ParseUser(); newUser.setUsername(emailAddress); newUser.put("firstname",firstName); newUser.put("lastname",lastName); newUser.setEmail(emailAddress); newUser.put("birthdate",birthDate); newUser.setPassword(password); newUser.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { if(e==null){ makeAssetsInvisible(); AppPreferences.instance(getApplication()).saveUsername(firstName + " " + lastName); AppPreferences.instance(getApplication()).saveUserMail(emailAddress); AppPreferences.instance(getApplication()).saveUserImage(""); TextView allsetText = (TextView) findViewById(R.id.allsetText); assert allsetText != null; allsetText.setVisibility(View.VISIBLE); ImageView allsetImage = (ImageView) findViewById(R.id.allset); assert allsetImage != null; allsetImage.setVisibility(View.VISIBLE); allsetImage.setImageResource(R.drawable.allset_animation); mAnimator = ObjectAnimator.ofInt(allsetImage, "ImageLevel", 0, 2); mAnimator.setDuration(500); Animator.AnimatorListener animatorListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { Intent i = new Intent(SignUpActivity.this, MainActivity.class); startActivity(i); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }; mAnimator.addListener(animatorListener); mAnimator.start(); } else{ Toast.makeText(SignUpActivity.this,""+e.getMessage(),Toast.LENGTH_LONG).show(); } } }); } else { Toast.makeText(SignUpActivity.this, "Passwords don't match", Toast.LENGTH_LONG).show(); } } }); } private void makeAssetsInvisible() { mFirstName.setVisibility(View.GONE); mLastName.setVisibility(View.GONE); mEmailAddress.setVisibility(View.GONE); mBirthDate.setVisibility(View.GONE); mPassword.setVisibility(View.GONE); mRepeatPass.setVisibility(View.GONE); mSignUpBtn.setVisibility(View.GONE); ImageView divider1 = (ImageView) findViewById(R.id.divider1); ImageView divider2 = (ImageView) findViewById(R.id.divider2); ImageView divider3 = (ImageView) findViewById(R.id.divider3); ImageView divider4 = (ImageView) findViewById(R.id.divider4); ImageView divider5 = (ImageView) findViewById(R.id.divider5); ImageView divider6 = (ImageView) findViewById(R.id.divider6); assert divider1 != null; divider1.setVisibility(View.GONE); assert divider2 != null; divider2.setVisibility(View.GONE); assert divider3 != null; divider3.setVisibility(View.GONE); assert divider4 != null; divider4.setVisibility(View.GONE); assert divider5 != null; divider5.setVisibility(View.GONE); assert divider6 != null; divider6.setVisibility(View.GONE); } @Override public void selectedDate(int year, int month, int day) { mBirthDate.setText("" + day + "/" + month + "/" + year); } }
Markdown
UTF-8
6,974
3.25
3
[]
no_license
# 15生成数据 ## 15.2绘制简单的折线图 mpl_squares.py `import matplotlib.pyplot as plt`导入matplotlib.pyplot 变量`fig`表示整张图片。变量`ax`表示图片中的各个图表 方法`plot()`,它尝试根据给定的数据以有意义的方式绘制图表 函数`plt.show()`打开Matplotlib查看器并显示绘制的图表 ## 15.2.1修改标签文字和线条粗细 参数`linewidth`决定了`plot()` 绘制的线条粗细。 参数`fontsize`指定图表中各种文字的大小 方法`set_xlabel()` 和`set_ylabel()` 让你能够为每条轴设置标题 方法`tick_params()`设置刻度的样式 其中指定的实参将影响 轴和 轴上的刻度(`axes='both'` ),并将刻度标记的字号设置为14(`labelsize=14` ) ### 15.2.2校正图形 向`plot()`提供一系列数时,它假设第一个数据点对应的x坐标值为0, ### 15.2.3使用内置样式 `plt.style.use()`使用内置主题 ### 15.2.4使用`scatter()`绘制散点图并设置样式 向它传递一对x坐标和y坐标,它将在指定位置绘制一个点 ### 15.2.6自动计算数据 `ax.axis([0, 1100, 0, 1100000])` x坐标最小,最大,y坐标最小,最大范围 ### 15.2.7自定义颜色 `ax.scatter(x_values, y_values, c='red', s=10)` `ax.scatter(x_values, y_values, c=(0, 0.8, 0), s=10)` ### 15.2.8使用颜色映射 `ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10)` ### 15.2.9自动保存图表 `plt.savefig('squares_plot.png', bbox_inches='tight')` 第一个实参指定要以什么文件名保存图表,这个文件将存储到scatter_squares.py所在的目录。 第二个实参指定将图表多余的空白区域裁剪掉。如果要保留图表周围多余的空白区域,只需省略这个实参即可。 ## 15.3随机漫步 ### 15.3.1创建`RandomWalk`类 randomwalk.py ```py from random import choice class RandomWalk: """一个生成随机漫步数据的类。""" def __init__(self, num_points=5000): """初始化随机漫步的属性。""" self.num_points = num_points #所有随机漫步都始于(0, 0)。 self.x_values = [0] self.y_values = [0] ``` ### 15.3.2选择方向 ### 15.3.5设置随机漫步图的样式 1. 给点着色 我们将使用颜色映射来指出漫步中各点的先后顺序,并删除每个点的黑色轮廓,让其颜色更为明显。 2. 重新绘制起点和终点 3. 隐藏坐标轴 `ax.get_xaxis().set_visible(False)` 4. 增加点数 5. 调整尺寸以适合屏幕 `fig, ax = plt.subplots(figsize=(10, 6), dpi=128)` ## 15.4使用Plotly模拟掷骰子 ### 15.4.2创建`Die`类 `from random import randint` `randint(a,b)` 返回a,b之间的任何整数,包括a,b ### 15.4.4分析结果 ### 15.4.5绘制直方图 ### 15.4.6同时掷两个骰子 die.py ### 15.4.7同时掷两个面数不同的骰子 # 16下载数据 ## 16.1`CSV`文件格式 要在文本文件中存储数据,一个简单方式是将数据作为一系列以逗号分隔的值写入文件。这样的文件称为`CSV`文件 ### 16.1.1分析`CSV`文件头 `import csv` `reader`处理文件中以逗号分隔的第一行数据,并将每项数据都作为一个元素存储在列表中 ### 16.1.2打印文件头及其位置 ```py for index, column_header in enumerate(header_row): print(index, column_header) ``` ### 16.1.3提取并读取数据 ### 16.1.4绘制温度图表 ### 16.1.5模块datetime |实参 |含义| |:---|:---| |%A |星期几,如Monday| |%B |月份名,如January| |%m |用数表示的月份(01~12)| |%d |用数表示的月份中的一天(01~31)| |%Y |四位的年份,如2019| |%y |两位的年份,如19| |%H |24小时制的小时数(00~23)| |%I |12小时制的小时数(01~12)| |%p |am或pm| |%M |分钟数(00~59)| |%S |秒数(00~61)| ### 16.1.6在图表中添加日期 `datetime.strptime=(row[], '%Y-%m-%d')` `fig.autofmt_xdate()`绘制倾斜的日期标签 ### 16.1.7涵盖更长的时间 ### 16.1.8再绘制一个数据系列 ### 16.1.9给图表区域着色 使用方法`fill_between()`。它接受一个x值系列和两个y值系列,并填充两个y值系列之间的空间 `ax.plot(dates, highs, c='red', alpha=0.5)` ### 16.1.10错误检查 ### 16.1.11自己动手下载数据 ## 16.2制作全球地震散点图:JSON格式 ### 16.2.1地震数据 ```py import json # 探索数据的结构。 filename = 'data/eq_data_1_day_m1.json' with open(filename) as f: all_eq_data = json.load(f) readable_file = 'data/readable_eq_data.json' with open(readable_file, 'w') as f: json.dump(all_eq_data, f, indent=4) ``` 函数`json.load()`将数据转换为Python能够处理的格式,这里是一个庞大的字典 `json.dump()`接受一个JSON数据对象和一个文件对象,并将数据写入这个文件 参数`indent=4`让`dump()`使用与数据结构匹配的缩进量来设置数据的格式 ### 16.2.3创建地震列表 ### 16.2.4提取震级 ### 16.2.5提取位置数据 ### 16.2.6绘制震级散点图 ### 16.2.7另一种指定图表数据的方式 ```py import pandas as pd data = pd.DataFrame( data=zip(lons, lats, titles, mags), columns=["经度", "纬度", "位置", "震级"]) data.head() ``` ### 16.2.8定制标记的尺寸 ```py fig = px.scatter( data, x="经度", y="纬度", range_x=[-200, 200], range_y=[-90, 90], width=800, height=800, title="全球地震散点图", size="震级", size_max=10, ) fig.write_html("global_earthquakes.html") fig.show() ``` 标记尺寸默认为20像素,还可以通过`size_max=10`将最大显示尺寸缩放到10 ### 16.2.9定制标记的颜色 默认的视觉映射图例渐变色范围是从蓝到红再到黄,数值越小则标记越蓝,而数值越大则标记越黄 ### 16.2.10其他渐变 Plotly Express将渐变存储在模块`colors`中。这些渐变是在列表`px.colors.named_colorscales()` Plotly除了有`px.colors.diverging` 表示连续变量的配色方案, 还有`px.colors.sequential` 和`px.colors.qualitative` 表示离散变量。 ### 16.2.11添加鼠标指向时显示的文本 `hover_name="位置",` *** # 17使用API ## 17.1使用Web API ### 17.1.1Git和GitHub ### 17.1.2使用API调用请求数据 ### 17.1.4处理API响应 ```py import requests # 执行API调用并存储响应。 url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' headers = {'Accept': 'application/vnd.github.v3+json'} r = requests.get(url, headers=headers) print(f"Status code: {r.status_code}") # 将API响应赋给一个变量。 response_dict = r.json() # 处理结果。 print(response_dict.keys()) ``` ### 17.1.5处理响应字典 ### 17.1.6概述最受欢迎的仓库 ### 17.1.7监视API的速率限制 ## 17.2使用Plotly可视化仓库 python_repos_visual.py ### 17.2.3在图表中添加可单击的链接 可使用html语法 ### 17.2.4深入了解Plotly和GitHub API ## 17.3Hacker News API hn_submissions.py
C++
GB18030
1,856
3.25
3
[]
no_license
#include "p532ϰ2_ͷļ.h" #include <cstring> #include <iostream> using namespace std; Cd::Cd(char * s1, char * s2, int n, double x) { performers = new char[strlen(s1) + 1]; strcpy(performers, s1); label = new char[strlen(s2) + 1]; strcpy(label, s2); selections = n; playtime = x; } Cd::Cd(const Cd & d) { performers = new char[strlen(d.performers) + 1]; strcpy(performers, d.performers); label = new char[strlen(d.label) + 1]; strcpy(label, d.label); playtime = d.playtime; selections = d.selections; } Cd::Cd() { performers = nullptr;; label = nullptr; selections = 0; playtime = 0.0; } Cd::~Cd() { delete [] performers; delete [] label; } Cd & Cd::operator= (const Cd & d) { if (&d == this) return *this; delete [] performers; delete [] label; performers = new char[strlen(d.performers) + 1]; strcpy(performers, d.performers); label = new char[strlen(d.label) + 1]; strcpy(label, d.label); playtime = d.playtime; selections = d.selections; return *this; } void Cd::Report() const { cout << "Performers:\n " << performers << endl; cout << "Label:\n " << label << endl; cout << "Selections:\n " << selections << endl; cout << "Playtime:\n " << playtime << endl; } Classic::Classic(char * bes, char * s1, char * s2, int n, double x) : Cd(s1, s2, n, x) { best = new char[strlen(bes) + 1]; strcpy(best, bes); } Classic::Classic() // ԶûĬϹ캯 { best = nullptr; } Classic::~Classic() // ԶûĬ { delete [] best; } void Classic::Report() const { Cd::Report(); cout << "Best: \n " << best << endl; } Classic & Classic::operator=(const Classic & d) { if (this == &d) return *this; Cd::operator=(d); delete [] best; best = new char[strlen(d.best) + 1]; strcpy(best, d.best); return *this; }
Java
UTF-8
3,751
2.5
2
[]
no_license
package org.spinachtree.gist; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.util.*; class Transform { private Map<String,Method> ruleMethod = new HashMap<String,Method>(); private static final Class[] parameterTypes={Object[].class}; private Parser parser; Object listener; Transform(Object listener, Parser parser) { this.listener=listener; this.parser=parser; if (listener==null) return; // find listener transform methods......... Class listenerClass=listener.getClass(); Op_rules ops=parser.rules; for (Op_rule rule:ops.rules) { try { ruleMethod.put(rule.name,listenerClass.getMethod(rule.name,parameterTypes)); } catch (NoSuchMethodException nsme) { // should we check if ruleMethod required for this rule...? //if (rule.defn.equals("=")) // System.out.printf("No public method for: %s%n",rule.name); } } if (ruleMethod.size()==0) System.out.println("No public methods found....%n"); } Object transform(String text, Span tree) { Op_rule rule=parser.span_rule(tree); String ruleName=rule.name; Method method=ruleMethod.get(rule.name); Span[] spans=children(tree.tip,tree.top,0); Object[] args=new Object[spans.length]; for (int i=0; i<spans.length; i++) args[i]=transform(text,spans[i]); if (method==null) { if (rule.mode==1) { // [ ... ] list if (args.length!=0) return args; return new Object[] { text.substring(tree.sot,tree.eot) }; } if (rule.mode==2) { // { ... } => map return mapof(ruleName,text,spans,args); } // defaults.... if (args.length==0) return text.substring(tree.sot,tree.eot); if (args.length==1) return args[0]; return args; } else { // transform method..... if (rule.mode==2) { // { ... } => map Object[] maparg = new Object[] { mapof(ruleName,text,spans,args) }; return applyMethod(ruleName,method,maparg); } if (args.length==0) { // rule : ... terminal rule ... Object[] listarg = new Object[] { text.substring(tree.sot,tree.eot) }; return applyMethod(ruleName,method,listarg); } return applyMethod(ruleName,method,args); } } // transform Object applyMethod(String rule, Method method, Object[] args) { try { return method.invoke(listener,(Object)args); // vararg quirk for Object[] } catch(InvocationTargetException ex) { System.out.printf("Rule method: %s => %s%n",rule,ex.getTargetException()); return null; } catch(Exception ex) { System.out.printf("Rule method: %s => %s%n",rule,ex); return null; } } Map<String,Object> mapof(String rule, String text, Span[] spans, Object[] args) { Map<String,Object> map = new HashMap<String,Object>(); map.put("rule",rule); if (spans.length==0) { Span span = spans[0]; map.put("text",text.substring(span.sot,span.eot)); return map; } Map<String,Integer> keys = new HashMap<String,Integer>(); for (int i=0; i<spans.length; i++) { String key=parser.span_rule(spans[i]).name; Integer hit=keys.get(key); if (hit==null) { keys.put(key,new Integer(1)); map.put(key,args[i]); } else if (hit.intValue()==1) { keys.put(key,new Integer(2)); List<Object> vals = new ArrayList<Object>(); vals.set(0,map.get(key)); vals.set(1,args[i]); map.put(key,vals); } else { List<Object> vals= (List<Object>) map.get(key); map.put(key,vals.add(args[i])); } } return map; } Span[] children(Span tip, Span top, int n) { if (tip==top) return new Span[n]; Span[] spans=children(tip,top.tip,n+1); spans[spans.length-n-1]=top; return spans; } public String toString() { if (listener==null) return "No transform methods.."; return listener.getClass().getName(); } } // Transform
C#
UTF-8
4,374
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using DnDApp.Models; using DnDApp.Models.Data; namespace DnDApp.Controllers { [Produces("application/json")] [Route("api/[controller]")] [ApiController] [EnableCors("ReactPolicy")] public class CharactersController : ControllerBase { private readonly CharRepository _repository; public CharactersController(DnDContext context) { _repository = new CharRepository(context); } // GET: api/Characters [HttpGet] public async Task<ActionResult<IEnumerable<Character>>> GetCharacters() { return await _repository.GetAll(); } // GET: api/Characters/5 [HttpGet("{id}")] public async Task<ActionResult<Character>> GetCharacter(int id) { var character = await _repository.GetById(id); if (character == null) { return NotFound(); } return character; } // PUT: api/Characters/5 [HttpPut("{id}")] public async Task<IActionResult> PutCharacter(int id, [Bind("Id", "CharacterName", "Race", "Class", "Strength", "Dexterity", "Constitution", "Intelligence", "Wisdom", "Charisma")] Character character) { if (id != character.Id) { return BadRequest(); } try { await _repository.Update(character); } catch (DbUpdateConcurrencyException) { if (!CharacterExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Characters [HttpPost] public async Task<ActionResult<Character>> PostCharacter([Bind("Id", "CharacterName", "Race", "Class", "Strength", "Dexterity", "Constitution", "Intelligence", "Wisdom", "Charisma")] Character character) { await _repository.Create(character); return CreatedAtAction("GetCharacter", new { id = character.Id }, character); } // DELETE: api/Characters/5 [HttpDelete("{id}")] public async Task<ActionResult<Character>> DeleteCharacter(int id) { var character = await _repository.GetById(id); if (character == null) { return NotFound(); } await _repository.Delete(character); return character; } private bool CharacterExists(int id) { return _repository.Exists(id); } } }
Markdown
UTF-8
845
2.6875
3
[]
no_license
# Odometry Odometry is the use of data from motion sensors to estimate change in position over time. This ROS node provides position estimates based on the following sources: * [x] wheel velocities (dead reckoning) * [ ] IMU sensor readings * [ ] control inputs and robot dynamics ## Error ### Dead Reckoning The position estimate will accumulate a small error over time, depending on how out of sync the message streams from the two motor controllers are. In the most extreme case, when the two controllers are 90 degrees out of phase and the velocity varies a lot, the error can approach 25%. In the regular case it should however be less than 0.1%. The accuracy can thus be increased by either - decreasing the variation in velocity by increasing the sampling rate, or - decrease the phase shift between the two motor controllers.
Python
UTF-8
1,570
2.75
3
[]
no_license
import logging from telegram.ext import Updater from telegram.ext import CommandHandler, MessageHandler, Filters # creates a variable to store the bot token updater = Updater(token='401734925:AAFDIy_Z48vlnf1p0LDRO7OR_olpz0m3lXc') dispatcher = updater.dispatcher # add logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s', level=logging.INFO ) # function for starting messages by the bot def start(bot, update): bot.send_message(chat_id=update.message.chat_id, text="i am jembebot love me and use me") # display sent messages back to the user def echo(bot, update): bot.send_message(chat_id=update.message.chat_id, text=update.message.text) # this commands sends the message the user has sent back in capital letters def caps(bot, update, args): text_caps = ' '.join(args).upper() bot.send_message(chat_id=update.message.chat_id, text=text_caps) # displays message to the user if wrong command is initiated # warning : should be added last def unknown(bot, update): bot.send_message(chat_id=update.message.chat_id, text="i dont understand but i love you") start_handler = CommandHandler('start', start) echo_handler = MessageHandler(Filters.text, echo) caps_handler = CommandHandler('caps', caps, pass_args=True) unknown_handler = MessageHandler(Filters.command, unknown) # adds all handlers to the dispatcher dispatcher.add_handler(start_handler) dispatcher.add_handler(echo_handler) dispatcher.add_handler(caps_handler) dispatcher.add_handler(unknown_handler) # starts the bot updater.start_polling()
Java
UTF-8
1,004
2.625
3
[]
no_license
package sonhv.com.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "BOOK") public class Book { // member variables @Id @GeneratedValue @Column(name = "BOOK_ID") private int bookId; @Column(name= "BOOK_NAME") private String bookName; @Column(name= "AUTHOR") private String author; @Column(name= "CATEGORY") private String category; // getters & setters public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
PHP
UTF-8
651
2.65625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Renatas Narmontas * Date: 07/04/16 * Time: 00:03 */ namespace Nfq\WeatherBundle\Provider; use Exception; class WeatherProviderException extends Exception { /** * WeatherProviderException constructor. * @param string $message * @param int $code * @param Exception|null $previous */ public function __construct($message, $code = 0, Exception $previous = null) { parent::__construct($message, $code, $previous); } /** * @return string */ public function __toString() { return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; } }
Java
UTF-8
2,295
3.71875
4
[]
no_license
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.stream.Stream; /** * Clase Main * Se encarga de la interacción coon el usuario, coloca el documento txt, lol lee y devuelve el resultado. * * @author Andy Catillo y Abril Palencia * @version 31/01/2019 */ public class Main { /** * Método main * @param args */ public static void main(String[] args){ //para leer el archivo ArrayList<String> cubilete = new ArrayList<String>(); try { Stream<String> lines = Files.lines( Paths.get(System.getProperty("user.dir")+"\\datos.txt"), StandardCharsets.UTF_8 ); lines.forEach(a -> cubilete.add(a)); }catch (IOException e ){ System.out.println("Error!"); } //crear el objeto pila Pila<Integer> pila = new Pila<>(); //crear el objeto calculadora Calculator calculator = new MyCalculator(); for (int a=0; a<cubilete.size();a++) { //ciclo para separar cada fila de la lista es sus caracteres String[] caracteres = cubilete.get(a).split(""); ArrayList<String> operacion = new ArrayList<>(); for (int i = 0; i < caracteres.length; i++) { operacion.add(caracteres[i]); } //ciclo para evaluar si es numero u operando for (int car = 0; car < operacion.size(); car++) { int num; String caracter = operacion.get(car); try { num = Integer.parseInt(caracter); pila.push(num); } catch (Exception e) { //si es operando se calcula el resultado if (!caracter.equals(" ")) { int num1 = pila.pop(); int num2 = pila.pop(); int resultado = calculator.calculate(num2, num1, caracter); pila.push(resultado); } } } //se muestra resultado System.out.println("resultado = " + pila.peek()); } } }
C++
UTF-8
2,093
2.625
3
[ "Apache-2.0" ]
permissive
#pragma once #include <optional> #include <base/types.h> #include <Storages/MergeTree/MergeTreeDataPartType.h> #include <Disks/IDisk.h> #include <Storages/MergeTree/IDataPartStorage.h> namespace DB { class MergeTreeData; /** Various types of mark files are stored in files with various extensions: * .mrk, .mrk2, .mrk3, .cmrk, .cmrk2, .cmrk3. * This helper allows to obtain mark type from file extension and vice versa. */ struct MarkType { MarkType(std::string_view extension); MarkType(bool adaptive_, bool compressed_, MergeTreeDataPartType::Value part_type_); static bool isMarkFileExtension(std::string_view extension); std::string getFileExtension() const; bool adaptive = false; bool compressed = false; MergeTreeDataPartType::Value part_type = MergeTreeDataPartType::Unknown; }; /// Meta information about index granularity struct MergeTreeIndexGranularityInfo { public: MarkType mark_type; /// Fixed size in rows of one granule if index_granularity_bytes is zero size_t fixed_index_granularity = 0; /// Approximate bytes size of one granule size_t index_granularity_bytes = 0; MergeTreeIndexGranularityInfo(const MergeTreeData & storage, MergeTreeDataPartType type_); MergeTreeIndexGranularityInfo(const MergeTreeData & storage, MarkType mark_type_); MergeTreeIndexGranularityInfo(MergeTreeDataPartType type_, bool is_adaptive_, size_t index_granularity_, size_t index_granularity_bytes_); void changeGranularityIfRequired(const IDataPartStorage & data_part_storage); String getMarksFilePath(const String & path_prefix) const { return path_prefix + mark_type.getFileExtension(); } size_t getMarkSizeInBytes(size_t columns_num = 1) const; static std::optional<MarkType> getMarksTypeFromFilesystem(const IDataPartStorage & data_part_storage); }; constexpr inline auto getNonAdaptiveMrkSizeWide() { return sizeof(UInt64) * 2; } constexpr inline auto getAdaptiveMrkSizeWide() { return sizeof(UInt64) * 3; } inline size_t getAdaptiveMrkSizeCompact(size_t columns_num); }
Java
UTF-8
1,037
2.421875
2
[]
no_license
package service; import model.Book; import java.util.List; /** * author:丁雯雯 * time:2019/01/22 * 管理书籍的方法 */ public interface BookManageService { /** * function:根据书籍的ID获得书籍的基本信息 * from tables: book * */ public Book getBookInfoById(String id); /** * function:添加书籍的信息入库 * change tables: book * */ public void addBookInfo(Book newBook); /** * function:借书(用户的ID,书籍的id)---判断一下用户的余额是否>=0,若成立,则可以结束;反之,不可以借书; * change table: book(修改书籍的state),userorder(添加借书的订单) * */ //public void lendBook(String userId, String bookId); /** * function:获取所有书的信息 * from tables:book * */ public List getAllBooksInfo(); /** * function:更新书籍的信息 * from tables:book * */ public void updateBookInfo(Book book); }
Java
UTF-8
4,935
2.40625
2
[ "Apache-2.0" ]
permissive
package io.github.privacystreams.device; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.support.annotation.RequiresApi; import io.github.privacystreams.core.PStreamProvider; import io.github.privacystreams.core.UQI; import static android.content.Context.CONNECTIVITY_SERVICE; /** * provides wifi information through returning a WifiAp * fires while connects to or disconnects from a wifi connection */ public class WifiUpdatesProvider extends PStreamProvider { private WifiAp oldWifiOutput; private WifiUpdatesProvider.WifiUpdatesReceiver wifiUpdatesReceiver; public WifiUpdatesProvider() { this.addRequiredPermissions(Manifest.permission.ACCESS_WIFI_STATE); } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) @Override protected void provide() { oldWifiOutput = null; wifiUpdatesReceiver = new WifiUpdatesProvider.WifiUpdatesReceiver(); IntentFilter filter = new IntentFilter(); //Network State Changed Action has firing problem while device disconnects from wifi //Connectivity Action has problem in telling whether the change is due to wifi connection //or mobile connection. Hence these two actions are combined here. filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); getContext().registerReceiver(wifiUpdatesReceiver, filter); //get connection information if the device is connected to wifi for the first time ConnectivityManager connectivityManager = (ConnectivityManager) getContext() .getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null) { if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { oldWifiOutput = getChangedWifi(); } } } @Override protected void onCancel(UQI uqi) { this.getContext().unregisterReceiver(wifiUpdatesReceiver); } private class WifiUpdatesReceiver extends BroadcastReceiver { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public void onReceive(Context context, Intent intent) { //from disconnected to connected if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (networkInfo != null && wifiManager.getConnectionInfo().getBSSID() != null) { if (networkInfo.isConnected()) { WifiAp wifiOutput = getChangedWifi(); oldWifiOutput = wifiOutput; wifiOutput.setFieldValue(WifiAp.STATUS, WifiAp.STATUS_CONNECTED); WifiUpdatesProvider.this.output(wifiOutput); } } } //from connected to disconnected if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { ConnectivityManager connectivityManager = (ConnectivityManager) getContext() .getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo == null && oldWifiOutput != null) { oldWifiOutput.setFieldValue(WifiAp.STATUS, WifiAp.STATUS_DISCONNECTED); WifiUpdatesProvider.this.output(oldWifiOutput); } if (networkInfo != null) { if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && !networkInfo.isConnected()) { oldWifiOutput.setFieldValue(WifiAp.STATUS, WifiAp.STATUS_DISCONNECTED); WifiUpdatesProvider.this.output(oldWifiOutput); } } } } } /** * this method is used to return the current connection information * * @return wifiAp return the connection information */ @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) private WifiAp getChangedWifi() { WifiManager wifiManager = (WifiManager) getContext().getApplicationContext() .getSystemService(Context.WIFI_SERVICE); return new WifiAp(wifiManager.getConnectionInfo(), WifiAp.STATUS_SCANNED); } }
JavaScript
UTF-8
12,668
2.953125
3
[ "MIT" ]
permissive
/* This module provides the dialogs for managing decision knowledge. The user can * create a new decision knowledge element, * edit an existing decision knowledge element, * delete an existing knowledge element, * create a new link between two knowledge elements, * delete a link between two knowledge elements, * change the documentation location (e.g. from issue comments to single JIRA issues), * set an element to the root element in the knowledge tree. Requires * conDecAPI Is required by * conDecContextMenu */ (function(global) { var ConDecDialog = function ConDecDialog() { }; ConDecDialog.prototype.showCreateDialog = function showCreateDialog(idOfParentElement, documentationLocationOfParentElement) { console.log("conDecDialog showCreateDialog"); // HTML elements var createDialog = document.getElementById("create-dialog"); var inputSummaryField = document.getElementById("create-form-input-summary"); var inputDescriptionField = document.getElementById("create-form-input-description"); var selectTypeField = document.getElementById("create-form-select-type"); var selectLocationField = document.getElementById("create-form-select-location"); var submitButton = document.getElementById("create-dialog-submit-button"); var cancelButton = document.getElementById("create-dialog-cancel-button"); // Fill HTML elements inputSummaryField.value = ""; inputDescriptionField.value = ""; fillSelectTypeField(selectTypeField, "Alternative"); fillSelectLocationField(selectLocationField, documentationLocationOfParentElement); // Set onclick listener on buttons submitButton.onclick = function() { var summary = inputSummaryField.value; var description = inputDescriptionField.value; var type = selectTypeField.value; var documentationLocation = selectLocationField.value; conDecAPI.createDecisionKnowledgeElement(summary, description, type, documentationLocation, idOfParentElement, documentationLocationOfParentElement, function() { conDecObservable.notify(); }); AJS.dialog2(createDialog).hide(); }; cancelButton.onclick = function() { AJS.dialog2(createDialog).hide(); }; // Show dialog AJS.dialog2(createDialog).show(); }; ConDecDialog.prototype.showDeleteDialog = function showDeleteDialog(id, documentationLocation) { console.log("conDecDialog showDeleteDialog"); // HTML elements var deleteDialog = document.getElementById("delete-dialog"); var content = document.getElementById("delete-dialog-content"); var submitButton = document.getElementById("delete-dialog-submit-button"); var cancelButton = document.getElementById("delete-dialog-cancel-button"); // Set onclick listener on buttons submitButton.onclick = function() { conDecAPI.deleteDecisionKnowledgeElement(id, documentationLocation, function() { conDecObservable.notify(); }); AJS.dialog2(deleteDialog).hide(); }; cancelButton.onclick = function() { AJS.dialog2(deleteDialog).hide(); }; // Show dialog AJS.dialog2(deleteDialog).show(); }; ConDecDialog.prototype.showDeleteLinkDialog = function showDeleteLinkDialog(id, documentationLocation) { console.log("conDecDialog showDeleteLinkDialog"); // HTML elements var deleteLinkDialog = document.getElementById("delete-link-dialog"); var content = document.getElementById("delete-link-dialog-content"); var submitButton = document.getElementById("delete-link-dialog-submit-button"); var cancelButton = document.getElementById("delete-link-dialog-cancel-button"); // Set onclick listener on buttons submitButton.onclick = function() { var parentElement = conDecTreant.findParentElement(id); conDecAPI.deleteLink(parentElement["id"], id, parentElement["documentationLocation"], documentationLocation, function() { conDecObservable.notify(); }); AJS.dialog2(deleteLinkDialog).hide(); }; cancelButton.onclick = function() { AJS.dialog2(deleteLinkDialog).hide(); }; // Show dialog AJS.dialog2(deleteLinkDialog).show(); }; ConDecDialog.prototype.showLinkDialog = function showLinkDialog(id, documentationLocation) { console.log("conDecDialog showLinkDialog"); // HTML elements var linkDialog = document.getElementById("link-dialog"); var selectElementField = document.getElementById("link-form-select-element"); var submitButton = document.getElementById("link-dialog-submit-button"); var cancelButton = document.getElementById("link-dialog-cancel-button"); var argumentFieldGroup = document.getElementById("argument-field-group"); var radioPro = document.getElementById("link-form-radio-pro"); var radioCon = document.getElementById("link-form-radio-con"); // Fill HTML elements fillSelectElementField(selectElementField, id, documentationLocation); argumentFieldGroup.style.display = "none"; radioPro.checked = false; radioCon.checked = false; selectElementField.onchange = function() { conDecAPI.getDecisionKnowledgeElement(this.value, "i", function(decisionKnowledgeElement) { if (decisionKnowledgeElement && decisionKnowledgeElement.type === "Argument") { argumentFieldGroup.style.display = "inherit"; radioPro.checked = true; } }); }; // Set onclick listener on buttons submitButton.onclick = function() { var childId = selectElementField.value; var knowledgeTypeOfChild = $('input[name=form-radio-argument]:checked').val(); conDecAPI.createLink(knowledgeTypeOfChild, id, childId, "i", "i", function() { conDecObservable.notify(); }); AJS.dialog2(linkDialog).hide(); }; cancelButton.onclick = function() { AJS.dialog2(linkDialog).hide(); }; // Show dialog AJS.dialog2(linkDialog).show(); }; function fillSelectElementField(selectField, id, documentationLocation) { if (selectField === null) { return; } selectField.innerHTML = ""; conDecAPI.getUnlinkedElements(id, documentationLocation, function(unlinkedElements) { var insertString = ""; var isSelected = "selected"; for (var index = 0; index < unlinkedElements.length; index++) { insertString += "<option " + isSelected + " value='" + unlinkedElements[index].id + "'>" + unlinkedElements[index].type + ' / ' + unlinkedElements[index].summary + "</option>"; isSelected = ""; } selectField.insertAdjacentHTML("afterBegin", insertString); }); AJS.$(selectField).auiSelect2(); } ConDecDialog.prototype.showEditDialog = function showEditDialog(id, documentationLocation, type) { console.log("conDecDialog showEditDialog"); conDecAPI.getDecisionKnowledgeElement(id, documentationLocation, function(decisionKnowledgeElement) { var summary = decisionKnowledgeElement.summary; var description = decisionKnowledgeElement.description; var type = decisionKnowledgeElement.type; var documentationLocation = decisionKnowledgeElement.documentationLocation; if (documentationLocation === "i") { var createEditIssueForm = require('quick-edit/form/factory/edit-issue'); createEditIssueForm({ issueId : id }).asDialog({}).show(); return; } // HTML elements var editDialog = document.getElementById("edit-dialog"); var inputSummaryField = document.getElementById("edit-form-input-summary"); var inputDescriptionField = document.getElementById("edit-form-input-description"); var selectTypeField = document.getElementById("edit-form-select-type"); var selectLocationField = document.getElementById("edit-form-select-location"); var submitButton = document.getElementById("edit-dialog-submit-button"); var cancelButton = document.getElementById("edit-dialog-cancel-button"); // Fill HTML elements inputSummaryField.value = summary; inputDescriptionField.value = description; fillSelectTypeField(selectTypeField, type); fillSelectLocationField(selectLocationField, documentationLocation); if (documentationLocation === "s") { inputSummaryField.disabled = true; selectLocationField.disabled = true; } // Set onclick listener on buttons submitButton.onclick = function() { var summary = inputSummaryField.value; var description = inputDescriptionField.value; var type = selectTypeField.value; conDecAPI.updateDecisionKnowledgeElement(id, summary, description, type, documentationLocation, function() { conDecObservable.notify(); }); AJS.dialog2(editDialog).hide(); }; cancelButton.onclick = function() { AJS.dialog2(editDialog).hide(); }; // Show dialog AJS.dialog2(editDialog).show(); }); }; function fillSelectTypeField(selectField, selectedKnowledgeType) { if (selectField === null) { return; } selectField.innerHTML = ""; var extendedKnowledgeTypes = conDecAPI.extendedKnowledgeTypes; for (var index = 0; index < extendedKnowledgeTypes.length; index++) { var isSelected = ""; if (isKnowledgeTypeLocatedAtIndex(selectedKnowledgeType, extendedKnowledgeTypes, index)) { isSelected = "selected"; } selectField.insertAdjacentHTML("beforeend", "<option " + isSelected + " value='" + extendedKnowledgeTypes[index] + "'>" + extendedKnowledgeTypes[index] + "</option>"); } AJS.$(selectField).auiSelect2(); } function isKnowledgeTypeLocatedAtIndex(knowledgeType, extendedKnowledgeTypes, index) { console.log("conDecDialog isKnowledgeTypeLocatedAtIndex"); return knowledgeType.toLowerCase() === extendedKnowledgeTypes[index].toLowerCase().split("-")[0]; } function fillSelectLocationField(selectField, documentationLocationOfParentElement) { if (selectField === null) { return; } selectField.innerHTML = ""; selectField.insertAdjacentHTML("beforeend", "<option selected value = 'i'>JIRA Issue</option>" + "<option value = 's'>JIRA Issue Comment</option></select></div>"); AJS.$(selectField).auiSelect2(); } ConDecDialog.prototype.showChangeTypeDialog = function showChangeTypeDialog(id, documentationLocation) { console.log("conDecDialog showChangeTypeDialog"); // HTML elements var changeTypeDialog = document.getElementById("change-type-dialog"); var selectTypeField = document.getElementById("change-type-form-select-type"); var submitButton = document.getElementById("change-type-dialog-submit-button"); var cancelButton = document.getElementById("change-type-dialog-cancel-button"); // Fill HTML elements conDecAPI.getDecisionKnowledgeElement(id, documentationLocation, function(decisionKnowledgeElement) { fillSelectTypeField(selectTypeField, decisionKnowledgeElement.type); }); // Set onclick listener on buttons submitButton.onclick = function() { var type = selectTypeField.value; conDecAPI.changeKnowledgeType(id, type, documentationLocation, function() { conDecObservable.notify(); }); AJS.dialog2(changeTypeDialog).hide(); }; cancelButton.onclick = function() { AJS.dialog2(changeTypeDialog).hide(); }; // Show dialog AJS.dialog2(changeTypeDialog).show(); }; ConDecDialog.prototype.showSummarizedDialog = function showSummarizedDialog(id, documentationLocation) { // HTML elements var summarizedDialog = document.getElementById("summarization-dialog"); var cancelButton = document.getElementById("summarization-dialog-cancel-button"); var content = document.getElementById("summarization-dialog-content"); var probabilityOfCorrectness = document.getElementById("summarization-probabilityOfCorrectness").valueAsNumber; var projectId = document.getElementById("summarization-projectId").value; if (projectId === undefined || projectId.length === 0 || projectId === "") { document.getElementById("summarization-projectId").value = id; projectId = id; } conDecAPI.getSummarizedCode(parseInt(projectId, 10), documentationLocation, probabilityOfCorrectness, function(text) { var insertString = "<form class='aui'>" + "<div>" + text + "</div>" + "</form>"; content.innerHTML = insertString; }); cancelButton.onclick = function() { AJS.dialog2(summarizedDialog).hide(); }; // Show dialog AJS.dialog2(summarizedDialog).show(); }; ConDecDialog.prototype.showExportDialog = function showExportDialog(decisionElementKey) { console.log("conDecDialog exportDialog"); // HTML elements var exportDialog = document.getElementById("export-dialog"); var hiddenDiv = document.getElementById("exportQueryFallback"); // set hidden attribute hiddenDiv.setAttribute("data-tree-element-key", decisionElementKey); // open dialog AJS.dialog2(exportDialog).show(); }; // export ConDecDialog global.conDecDialog = new ConDecDialog(); })(window);
Java
UTF-8
83
1.59375
2
[]
no_license
package xyz.lebster.node; public @interface SpecificationURL { String value(); }
PHP
UTF-8
382
3
3
[]
no_license
<?php // get the q parameter from URL $q = $_REQUEST["q"]; //Checks if the URL has "www.linkedin.com" for validation if ($q !== "") { $q = strtolower($q); if (strpos($q, 'www.linkedin.com') !== false) { echo '<span class="col-25" style="color:green;">Valid URL</span>'; }else{ echo '<span class="col-25 "style="color:red;">Invalid URL</span>'; } } ?>
C
UTF-8
2,331
2.578125
3
[]
no_license
/* * file.c * * Created on: May 23, 2021 * Author: cory */ #include "../lib/file.h" #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <linux/fs.h> #include <sys/ioctl.h> #include <stdio.h> #define SET_FLAG(field, flag, attr) field = ((flag & attr) ? 1 : 0) #define SAVE_FLAG(field, flag, attr) attr = ((field == 1) ? (attr | flag) : (attr & (~flag))) void get_file_info(char *file_name, FILEINFO **fi) { int attr; FILEINFO *f; if(*fi == NULL) { *fi = malloc(sizeof(FILEINFO)); } if(*fi == NULL) return; f = *fi; memset(f,0,sizeof(FILEINFO)); f->__fd = open(file_name, O_RDONLY); if (f->__fd == -1) return; if (ioctl(f->__fd, FS_IOC_GETFLAGS, &attr) == -1) return; f->file_name = file_name; SET_FLAG(f->ck_a, FS_APPEND_FL, attr); SET_FLAG(f->ck_A, FS_NOATIME_FL, attr); f->ck_F = -1; //SET_FLAG(f->ck_F, 0, attr); SET_FLAG(f->ck_c, FS_COMPR_FL, attr); SET_FLAG(f->ck_D, FS_DIRSYNC_FL, attr); SET_FLAG(f->ck_d, FS_NODUMP_FL, attr); SET_FLAG(f->ck_e, FS_EXTENT_FL, attr); SET_FLAG(f->ck_i, FS_IMMUTABLE_FL, attr); SET_FLAG(f->ck_C, FS_NOCOW_FL, attr); SET_FLAG(f->ck_s, FS_SECRM_FL, attr); SET_FLAG(f->ck_u, FS_UNRM_FL, attr); SET_FLAG(f->ck_S, FS_SYNC_FL, attr); SET_FLAG(f->ck_t, FS_NOTAIL_FL, attr); SET_FLAG(f->ck_T, FS_TOPDIR_FL, attr); SET_FLAG(f->ck_P, FS_PROJINHERIT_FL, attr); SET_FLAG(f->ck_j, FS_JOURNAL_DATA_FL, attr); } int save_file_attr(FILEINFO *fi) { FILEINFO *f = fi; int attr; if (f->__fd == -1) return -1; if (ioctl(f->__fd, FS_IOC_GETFLAGS, &attr) == -1) return -1; SAVE_FLAG(f->ck_a, FS_APPEND_FL, attr); SAVE_FLAG(f->ck_A, FS_NOATIME_FL, attr); SAVE_FLAG(f->ck_c, FS_COMPR_FL, attr); SAVE_FLAG(f->ck_D, FS_DIRSYNC_FL, attr); SAVE_FLAG(f->ck_d, FS_NODUMP_FL, attr); SAVE_FLAG(f->ck_e, FS_EXTENT_FL, attr); SAVE_FLAG(f->ck_i, FS_IMMUTABLE_FL, attr); SAVE_FLAG(f->ck_C, FS_NOCOW_FL, attr); SAVE_FLAG(f->ck_s, FS_SECRM_FL, attr); SAVE_FLAG(f->ck_u, FS_UNRM_FL, attr); SAVE_FLAG(f->ck_S, FS_SYNC_FL, attr); SAVE_FLAG(f->ck_t, FS_NOTAIL_FL, attr); SAVE_FLAG(f->ck_T, FS_TOPDIR_FL, attr); SAVE_FLAG(f->ck_P, FS_PROJINHERIT_FL, attr); SAVE_FLAG(f->ck_j, FS_JOURNAL_DATA_FL, attr); if (ioctl(f->__fd, FS_IOC_SETFLAGS, &attr) == -1) { errExit("FS_IOC_SETFLAGS\n"); return -1; } close(f->__fd); return 0; }
C#
UTF-8
12,793
2.6875
3
[]
no_license
//********************************************************************************** //* Copyright (C) 2007,2016 Hitachi Solutions,Ltd. //********************************************************************************** #region Apache License // // 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 // // http://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. // #endregion //********************************************************************************** //* クラス名 :CmnMethods //* クラス日本語名 :共通関数クラス //* //* 作成者 :生技 西野 //* 更新履歴 : //* //* 日時 更新者 内容 //* ---------- ---------------- ------------------------------------------------- //* 2008/xx/xx 西野 大介 新規作成 //* 2012/11/21 西野 大介 Entity、DataSet自動生成の対応 //********************************************************************************** using System; using System.Text; using System.Data; using System.Collections; namespace DPQuery_Tool { /// <summary>共通関数クラス</summary> public class CmnMethods { #region スキーマ情報の表示 /// <summary>スキーマ情報の表示</summary> /// <param name="table">スキーマ情報</param> /// <param name="writeLine">線を低か引かないか</param> /// <returns>スキーマ情報</returns> public static string DisplayDataString(DataTable table, bool writeLine) { StringBuilder sb = new StringBuilder(); if (writeLine) { // 行の区切り sb.Append("============================" + Environment.NewLine); } // 行 foreach (System.Data.DataRow row in table.Rows) { // 列 foreach (System.Data.DataColumn col in table.Columns) { // カラム名 = 値 sb.Append(col.ColumnName + " = " + row[col] + Environment.NewLine); } if (writeLine) { // 行の区切り sb.Append("============================" + Environment.NewLine); } } return sb.ToString(); } /// <summary>スキーマ情報の表示</summary> /// <param name="table">スキーマ情報</param> /// <param name="writeLine">線を低か引かないか</param> public static void DisplayDataConsole(DataTable table, bool writeLine) { if (writeLine) { // 行の区切り Console.WriteLine("============================"); } // 行 foreach (System.Data.DataRow row in table.Rows) { // 列 foreach (System.Data.DataColumn col in table.Columns) { // カラム名 = 値 Console.WriteLine("{0} = {1}", col.ColumnName, row[col]); } if (writeLine) { // 行の区切り Console.WriteLine("============================"); } } } #endregion #region カラム ポジションを昇順にソート /// <summary>カラム ポジションを昇順にソートする</summary> /// <param name="htColumns">カラム(ハッシュテーブル)</param> /// <returns>ソート後のポジション情報(アレイリスト)</returns> public static ArrayList sortColumn(Hashtable htColumns) { // アレイリストを使用 // ソート用配列 ArrayList sort = new ArrayList(); // ソート用配列にポジション(Int32)を追加 foreach (string position in htColumns.Keys) { // Int32化 sort.Add(Int32.Parse(position)); } // ソート sort.Sort(); // 結果を返す。 return sort; } #endregion #region Entity、DataSet自動生成の対応 #region DB型情報を.NET型情報に変換する /// <summary>型情報</summary> public static DataTable DataTypes = null; /// <summary>DB型情報を.NET型情報に変換する</summary> /// <param name="db_TypeInfo">DB型情報</param> /// <returns>.NET型情報</returns> public static string ConvertToDotNetTypeInfo(string db_TypeInfo) { // TypeName(DB型情報) → DataType(.NET型情報) foreach (DataRow dr in DataTypes.Rows) { if (dr["TypeName"].ToString().ToUpper() == db_TypeInfo.ToUpper()) { return dr["DataType"].ToString(); } } return null; } #region DB固有ロジック /// <summary>DB型情報を.NET型情報に変換する</summary> /// <param name="db_TypeInfo">DB型情報</param> /// <returns>.NET型情報</returns> public static string ConvertToDotNetTypeInfo_DB2(string db_TypeInfo) { // SQL_TYPE_NAME(DB型情報) → FRAMEWORK_TYPE(.NET型情報) foreach (DataRow dr in DataTypes.Rows) { if (dr["SQL_TYPE_NAME"].ToString().ToUpper() == db_TypeInfo.ToUpper()) { return dr["FRAMEWORK_TYPE"].ToString(); } } return null; } /// <summary>DB型番号をDB型名に変換する(OLEDB)</summary> /// <param name="db_TypeInfo">DB型番号</param> /// <returns>DB型名</returns> public static string ConvertToDBTypeInfo_OLEDB(string db_TypeInfo) { foreach (DataRow dr in DataTypes.Rows) { if (dr["NativeDataType"].ToString() == db_TypeInfo) { return dr["TypeName"].ToString(); } } return null; } #endregion #endregion #region DTO生成用 /// <summary> /// 型名の調整を行う。 /// ・.NETの型名からNullableの型名を返す。 ///  C#とVBで事なるので注意すること。 /// ・VBの場合は、配列表記を []→() へ。 /// </summary> /// <param name="typeName">.NETの型名</param> /// <param name="isVB">VBか?</param> /// <returns>調整後の型名</returns> public static string AdjustTypeName(string typeName, bool isVB) { // ワーク領域へコピー string temp = typeName; // Nullableの付与 switch (temp) { case "System.Byte[]": break; // そのまま case "System.Object": break; // そのまま case "System.String": break; // そのまま default: // Nullableの付与 // VS 2005で新しくなったVisual BasicとC#の新機能を総括 - @IT // http://www.atmarkit.co.jp/fdotnet/special/vs2005_02/vs2005_02_02.html if (isVB) { // VB // Dim i As Nullable(Of Integer) = Nothing temp = string.Format("Nullable(Of {0})", typeName); } else { // C# // ・Nullable<int> i; // ・int? i; temp = typeName + "?"; } break; } // VBの場合は、配列表記を []→() へ。 if (isVB) { // VB temp = temp.Replace("[]", "()"); } else { // C# // なにもしない。 } // 調整後の型名を返す。 return temp; } /// <summary>.NETの型名からデータセットの型名を返す。</summary> /// <param name="typeName">.NETの型名</param> /// <returns>XSDの型名</returns> public static string ToXsTypeName(string typeName) { string temp = ""; switch (typeName) { case "System.Boolean": temp = "boolean"; break; case "System.Byte": temp = "unsignedByte"; break; case "System.Byte[]": temp = "base64Binary"; break; case "System.DateTime": temp = "dateTime"; break; case "System.DateTimeOffset": temp = "anyType"; break; case "System.Decimal": temp = "decimal"; break; case "System.Double": temp = "double"; break; case "System.Guid": temp = "string"; break; case "System.Int16": temp = "short"; break; case "System.Int32": temp = "int"; break; case "System.Int64": temp = "long"; break; case "System.Object": temp = "anyType"; break; case "System.SByte": temp = "byte"; break; case "System.Single": temp = "float"; break; case "System.String": temp = "string"; break; case "System.TimeSpan": temp = "duration"; break; case "System.UInt16": temp = "unsignedShort"; break; case "System.UInt32": temp = "unsignedInt"; break; case "System.UInt64": temp = "unsignedLong"; break; default: throw new Exception("非サポートの型です"); } return temp; //if (typeName == "System.Boolean") { return "boolean"; } //if (typeName == "System.Byte") { return "unsignedByte"; } //if (typeName == "System.Byte[]") { return "base64Binary"; } //if (typeName == "System.DateTime") { return "dateTime"; } //if (typeName == "System.DateTimeOffset") { return "anyType"; } //if (typeName == "System.Decimal") { return "decimal"; } //if (typeName == "System.Double") { return "double"; } //if (typeName == "System.Guid") { return "string"; } //if (typeName == "System.Int16") { return "short"; } //if (typeName == "System.Int32") { return "int"; } //if (typeName == "System.Int64") { return "long"; } //if (typeName == "System.Object") { return "anyType"; } //if (typeName == "System.SByte") { return "byte"; } //if (typeName == "System.Single") { return "float"; } //if (typeName == "System.String") { return "string"; } //if (typeName == "System.TimeSpan") { return "duration"; } //if (typeName == "System.UInt16") { return "unsignedShort"; } //if (typeName == "System.UInt32") { return "unsignedInt"; } //if (typeName == "System.UInt64") { return "unsignedLong"; } //throw new Exception("非サポートの型です"); } #endregion #endregion } }
C++
UTF-8
3,254
3.109375
3
[]
no_license
/** @file LockTable.hpp * LockTable stores all the file locks in system, * and provide fast lookup from filename and it's owner. * * @author PengBo * @date 24 7 2007 * * design notes: <br> * 1. it is a collection data structure supporting fast lookup ability, <br> * such as map/hash_map. <br> * <br> * */ #ifndef _TFSMASTER_LOCKTABLE_HPP #define _TFSMASTER_LOCKTABLE_HPP #include "common/IceGenerated.hpp" #include "common/Types.hpp" #include <map> namespace tfs { //enum LockType {ReadLock, WriteLock}; class LockTable { struct LockInfo{ std::string filename; // // lockCnt value: // -1 means WriteLock, it's a exclusive lock flag // 1...n means ReadLock counter int lockCnt; }; public: /** Constructor * @param [in] * @throws */ LockTable(); ~LockTable(); /** Add a lock of lockType for a given file holded by holder. * Holder can add duplicated lock for one filename, which occurs * when a client open a file multiple times in one process. * lockCnt are designed for this case. * * @param [in] filename: lock on which file * @param [in] holder: owner of the lock * @param [in] lockType: read or write lock * @throws * @return false: when the lock is exist, and parameter lockType is different, or the lockType of the lock is write * @return true: read lock can be added for multiple times, but write lock only once */ bool addItem(const std::string& filename, const std::string& holder, const LockType lockType); /** Delete a lock by filename/holder pair * Actually, only dec lockCnt and do real deletion when lockCnt meets Zero. * * * @param [in] filename * @param holder: owner of the lock * @throws * @return :when the operation is going to delete the lock that didn't exist in the map, it'll return false */ bool deleteItem(const std::string& filename, const std::string& holder); /** Delete all locks hold by holder. * * @param holder: owner of the lock * @throws std::runtime_error when internal data structure inconsistent * @return : number of locks that deleted */ int deleteItem(const std::string& holder); /** * Find a lock info by... * * @param [in] * @throws * @return : */ //void findItem(const LockType lockType); private: std::map<std::string , LockInfo> m_nameIdx; std::multimap<std::string , LockInfo, std::less<std::string> > m_holderIdx; typedef std::map<std::string , LockInfo>::iterator NameIdxIterator; typedef std::multimap<std::string , LockInfo, std::less<std::string> >::iterator HolderIdxIterator; typedef std::map<std::string , LockInfo>::value_type NameValueType; typedef std::multimap<std::string , LockInfo, std::less<std::string> >::value_type HolderValueType; }; } #endif /* _TFSMASTER_LOCKTABLE_HPP */
JavaScript
UTF-8
2,429
2.703125
3
[]
no_license
import React, { Component } from 'react'; class DeviceInfo extends Component { constructor(props) { super(props); this.state = { deviceState: this.props.device_info.state, deviceStateArr:[{ "state": this.props.device_info.type, "timestamp": this.props.device_info.last_updated_at }], deviceCurrentState: "Lock" } } lockUnlockDetails() { let state; if(this.state.deviceCurrentState === "Lock") { this.setState({deviceCurrentState: "Unlock", deviceState: "unlocked"}); state = "Unlocked"; } else { this.setState({deviceCurrentState: "Lock", deviceState: "locked"}); state = "Locked"; } let {deviceStateArr} = this.state, currentTimeStamp = Math.floor(Date.now() / 1000), stateObj = { "state": state, "timestamp": currentTimeStamp }; if(deviceStateArr.length === 10) { deviceStateArr.splice(0, 1); deviceStateArr.push(stateObj); } else { deviceStateArr.push(stateObj); } this.setState({deviceStateArr}) } render() { let {device_info} = this.props, device_name = device_info.slug.split("-"), firstWord = device_name[0], lastWord = device_name[2], firstUpperCaseLetter = firstWord.charAt(0).toUpperCase(), stringWithoutFirstUpperLetter = firstWord.slice(1), secondUpperCaseLetter = lastWord.charAt(0).toUpperCase(), stringWithoutLastUpperLetter = lastWord.slice(1), deviceName = `${firstUpperCaseLetter}${stringWithoutFirstUpperLetter} ${device_name[1]} ${secondUpperCaseLetter}${stringWithoutLastUpperLetter}`, {deviceState} =this.state; if(device_info.type === "lock" || device_info.type === "unlock") { return ( <div> <div>Device {deviceName}</div> <div> <button style={{"margin":"10px"}} onClick={this.lockUnlockDetails.bind(this)}>{this.state.deviceCurrentState}</button> </div> </div> ); } else { return ( <div>We are not supporting this device at the moment</div> ); } } } export default DeviceInfo;
C
UHC
3,319
3.734375
4
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> /* "abcabcdede" , ڸ 2 ڸ ab/ca/bc/de/de̹Ƿ ̸ ϸ "abcabc2de , 3 ڸٸ abc/abc/ded/e̹Ƿ "2abcdede Ǿ 3 ª ˴ϴ. ( ڸ ڵ ״ ٿָ ȴ) ڿ s Ű ־ , 1 ̻ ڿ ߶ Ͽ ǥ ڿ * ª ̸ return *ϵ Լ ϼּ. #1 aabbaccc 7 #2 ababcdcdababcdcd 9 #3 abcabcdede 8 #4 abcabcabcabcdededededede 14 #5 xababcdcdababcdcd 17 #6 aaaaaaaaaa 3 - #1 ڿ 1 ߶ "2a2ba3c" Ǹ ̴ 7 ªϴ. - #2 ڿ 8 ߶ ªϴ. - #3 ڿ 3 ߶ ªϴ. - #4 ڿ 2 ڸ "abcabcabcabc6de ˴ϴ. ڿ 3 ڸ "4abcdededededede ˴ϴ. ڿ 4 ڸ "abcabcabcabc3dede ˴ϴ. ڿ 6 ڸ "2abcabc2dedede Ǹ, ̶ ̰ 14 ªϴ. - #5 ڿ պ ̸ŭ ߶ մϴ. ־ ڿ x / ababcdcd / ababcdcd ڸ Ұ մϴ.  ڿ ߶ Ƿ ª ̴ 17 ˴ϴ. - #6: 1 © 11a ڿ̰ ª. ̴ 3. ( 1-1, 1-2 Ѵ. ߺǴ ȸ 10 ̸ -> ߺ ȸ !) ѻ Ͽ ϴ. s ̴ 1 ̻ 1,000 ̸Դϴ. s ĺ ҹڷθ ̷ ֽϴ. */ char* str_cut(char *s, int idx, int start){ int i; char *cut = (char*)malloc(sizeof(char) * idx); for(i = 0; i < idx; i++) cut[i] = s[i + start]; return cut; } int is_in(char *s, char *key, int start, int idx){ int c = 0; int i, j; int end = strlen(s); for(i = start; i < end; i += idx){ for(j = 0; j < idx != '\0'; j++){ if(key[j] != s[i + j]) return c; } c++; } return c; } int solution(char *s) { int len; int lenght = strlen(s); int min = lenght; int count = 1; int same; char *key; int i; while(count <= lenght){ len = 0; i = 0; while(i < lenght){ key = str_cut(s, count, i); if(strlen(key) < count) len += strlen(key); else{ same = is_in(s, key, i, count); if(same >1) len += (count + (1 + same / 10)); else len += count; } i = i + count * same; } if(len < min) min = len; count++; } return min; } int main(void) { char s[1001]; scanf("%s", s); printf("%d\n", solution(s)); }
Python
UTF-8
1,514
3.640625
4
[]
no_license
import random from bokeh.plotting import figure, show def tirar_dado(numero_de_intentos): secuencia_de_tiros = [] for _ in range(numero_de_tiros): tiro = random.choice([1,2,3,4,5,6]) secuencia_de_tiros.append(tiro) return secuencia_de_tiros def graficar(x,y): grafica = figure(title = 'Lanzamiento de dados', x_axis_label = 'Numero de veces que se corrio la simulacion', y_axis_label = 'Probabilidad de obtener X numero') grafica.line(x, y) show(grafica) def calcular_probabilidad(tiros, numero_intentos_simulacion): tiros_con_1 = 0 for tiro in tiros: if 1 in tiro: tiros_con_1 += 1 return tiros_con_1 / numero_intentos_simulacion def main(numero_de_tiros, numero_de_intentos): prob = [] x_arreglo = [] for n in range(1,numero_de_intentos): tiros = [] for _ in range(n): secuencia_de_tiros = tirar_dado(numero_de_tiros) tiros.append(secuencia_de_tiros) probabilidad_de_tiros_con_1 = calcular_probabilidad(tiros, n) prob.append(probabilidad_de_tiros_con_1) x_arreglo.append(n) graficar(x_arreglo, prob) print(f'Probabilidad de obtener POR LO MENOS un 1 en {numero_de_tiros} tiros = {probabilidad_de_tiros_con_1}') if __name__ == '__main__': numero_de_tiros = int(input('Cuantas veces se va a tirar el dado?: ')) numero_de_intentos = int(input('Cuantas veces se va a correr la simulación?: ')) main(numero_de_tiros, numero_de_intentos)
Python
UTF-8
936
3.546875
4
[]
no_license
#-*- coding:utf8 -*- #author : Lenovo #date: 2018/9/17 a=1 print('a:{}'.format(id(a))) def fun(a): a=2 print('fun_a:{}'.format(id(a))) fun(a) print('a:{}'.format(id(a))) print(a) #上面代码可以看到a的值还是1 说明函数并没有对a起作用 #python中对象有两种 不可变对象 string tuple number 可变对象 list dict set #当函数中对一个不可变对象赋值时 并不会发生改变 b=[] def funb(b): b.append('b') funb(b) print(b) #列表为可变的 对函数内的操作相当于对它进行操作 结果为['b'] #总结 #当一个引用传递给函数的时候,函数会复制一份引用,当值为不可变引用时,不会发生变化,除非在函数内部重新 #定义一个相同名称的变量覆盖 并return 在函数执行的时候接受 其值会发生改变 #而当引用的为可变对象时,对它的操作相当于定位了它的指针 其值会发生改变
Java
UTF-8
308
1.765625
2
[]
no_license
package org.gradle.test.performancenull_173; import static org.junit.Assert.*; public class Testnull_17228 { private final Productionnull_17228 production = new Productionnull_17228("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
Shell
UTF-8
799
3.328125
3
[ "MIT" ]
permissive
#!/bin/bash # simple TODO list using [todoman](https://github.com/pimutils/todoman) and [vdirsyncer](https://github.com/pimutils/vdirsyncer) sync(){ [[ "$failed_sync" ]] && return if ! error="$(vdirsyncer sync calendar 2>&1 > /dev/null)"; then failed_sync="true" notify-send -a todo -u low -i todo "Failed sync" "$(echo "$error" | grep "error" )" fi } sync while : ; do events="$(todo --porcelain | jq -r '.[] | "\(.summary) (\(.id))" ' | sort)" cmd="$(echo "$events" | dmenu -l 20 -p "Add/delete a task:")" [[ "$cmd" ]] || break if [[ "$events" == *"$cmd"* ]]; then event_id="$(echo "$cmd" | grep -Eo '\([0-9]*\)$' | sed 's/[()]//g')" todo "done" "$event_id" else todo new "$cmd" fi done sync # vim: set ft=bash:
Java
UTF-8
1,532
2.34375
2
[]
no_license
package com.youhone.yjsboilingmachine.guide; import com.youhone.yjsboilingmachine.R; import java.util.Arrays; import java.util.List; /** * Created by Glen Luengen on 4/13/2018. */ public class MeattypeStation { public static MeattypeStation get() {return new MeattypeStation();} private MeattypeStation(){} public List<Meattype> getMeattypes(){ return Arrays.asList( new Meattype(Guide.BEEF,"Beef", R.drawable.beef_light, R.drawable.beef), new Meattype(Guide.PORK, "Pork", R.drawable.pork_light, R.drawable.pork), new Meattype(Guide.POULTRY, "Poultry", R.drawable.poultry_light, R.drawable.poultry), new Meattype(Guide.EGGS, "Eggs", R.drawable.eggsy_light, R.drawable.eggsy), new Meattype(Guide.SEAFOOD, "Fish and Seafood", R.drawable.seafood_light, R.drawable.seafood), new Meattype(Guide.LAMB, "Lamb", R.drawable.lamb_light, R.drawable.lamb), new Meattype(Guide.VEGETABLES,"Fruits and Vegetables", R.drawable.vegetable_light, R.drawable.vegetable), new Meattype(Guide.GRAINPASTA, "Grains and Legumes", R.drawable.grains_light, R.drawable.grains), new Meattype(Guide.DESSERTS, "Desserts", R.drawable.dessert_light, R.drawable.dessert), new Meattype(Guide.SAUCES, "Sauces and Syrups", R.drawable.sauces_light, R.drawable.sauces), new Meattype(Guide.INFUSIONS, "Infusions", R.drawable.infusions_light, R.drawable.infusions)); } }
Java
UTF-8
574
2.015625
2
[]
no_license
package com.javaee.fabiola.acoes.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.javaee.fabiola.acoes.repositories.MensagemRepository; import com.javaee.fabiola.acoes.domain.Mensagem; //import com.javaee.fabiola.acoes.repositories.MensagemRepository; @Service public class MensagemServiceImpl implements MensagemService { @Autowired MensagemRepository mensagemRepository; @Override public Mensagem createNew(Mensagem mensagem) { return mensagemRepository.save (mensagem); } }
Shell
UTF-8
136
2.8125
3
[]
no_license
#!/usr/bin/env bash # File: array_sum.sh arr1=(pa ra pa pa) arr2=(beep boop beep boop) sum=$(expr ${#arr1[*]} + ${#arr2[*]}) echo $sum
SQL
UTF-8
796
3.515625
4
[]
no_license
SELECT * FROM kaoqin WHERE ename = '朱伟亮' AND EXTRACT( YEAR_MONTH FROM '2015-8-9' ) = EXTRACT( YEAR_MONTH FROM clock ) ORDER BY clock ASC; SELECT * FROM kaoqin WHERE ename = '朱伟亮' AND clock BETWEEN '2015/08/01' AND '2015/09/01' ORDER BY clock ASC; SELECT dep, ename, ckno FROM kaoqin WHERE clock BETWEEN '2015/08/01' AND '2015/09/01' GROUP BY ename, ckno ORDER BY ckno ASC; SELECT COUNT(g.ename) FROM ( SELECT ename FROM kaoqin WHERE clock BETWEEN '2015/08/01' AND '2015/09/01' GROUP BY ename, ckno ) g;
PHP
UTF-8
2,156
2.625
3
[]
no_license
<?php namespace Arbor\Model\UkDfe; use Arbor\Resource\UkDfe\ResourceType; use Arbor\Query\Query; use Arbor\Model\Collection; use Arbor\Model\Exception; use Arbor\Model\ModelBase; class LocalAuthority extends ModelBase { public const AUTHORITY_CODE = 'authorityCode'; public const AUTHORITY_CODE_PRE2011 = 'authorityCodePre2011'; protected $_resourceType = ResourceType::UK_DFE_LOCAL_AUTHORITY; /** * @param Query $query * @return LocalAuthority[] | Collection * @throws Exception */ public static function query(\Arbor\Query\Query $query = null) { $gateway = self::getDefaultGateway(); if ($gateway === null) { throw new Exception('You must call ModelBase::setDefaultGateway() prior to calling ModelBase::query()'); } if ($query === null) { $query = new Query(); } $query->setResourceType(ResourceType::UK_DFE_LOCAL_AUTHORITY); return $gateway->query($query); } /** * @param int $id * @return LocalAuthority * @throws Exception */ public static function retrieve($id) { $gateway = self::getDefaultGateway(); if ($gateway === null) { throw new Exception('You must call ModelBase::setDefaultGateway() prior to calling ModelBase::retrieve()'); } return $gateway->retrieve(ResourceType::UK_DFE_LOCAL_AUTHORITY, $id); } /** * @return string */ public function getAuthorityCode() { return $this->getProperty('authorityCode'); } /** * @param string $authorityCode */ public function setAuthorityCode(string $authorityCode = null) { $this->setProperty('authorityCode', $authorityCode); } /** * @return string */ public function getAuthorityCodePre2011() { return $this->getProperty('authorityCodePre2011'); } /** * @param string $authorityCodePre2011 */ public function setAuthorityCodePre2011(string $authorityCodePre2011 = null) { $this->setProperty('authorityCodePre2011', $authorityCodePre2011); } }
Java
UTF-8
406
1.789063
2
[]
no_license
package LanchoneteFactory.lanchonetes; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author emers */ public class Main { public static void main(String[] args) { Lanchonete lanch = new LanchoneteCG(); lanch.pedirSanduiche(); } }
JavaScript
UTF-8
613
4.3125
4
[]
no_license
// Is unique /* use hashtable Itterate over characeters add to map if character is in map then we fail else add character to map Sort method sort characters if neighbors are equal return false */ const isUnique = function (str) { if (str.length > 128) { return false; } const charArray = new Array (128).fill(false); for (let char of str) { const asciiValue = char.charCodeAt(0); if (charArray[asciiValue] === true) { return false; } charArray[asciiValue] = true; } return true; } console.log(isUnique("abcz!@~"));