code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function register cls name begin function inner_wrapper wrapped_class begin if name in registry begin warning string Command %s already exists. name end set registry at name = wrapped_class return wrapped_class end function return inner_wrapper end function
def register(cls, name: str) -> Callable: def inner_wrapper(wrapped_class: CommandBase) -> Callable: if name in cls.registry: logger.warning('Command %s already exists.', name) cls.registry[name] = wrapped_class return wrapped_class return inner_wrap...
Python
nomic_cornstack_python_v1
import pandas import pycountry from pathlib import Path from os.path import realpath set base_path = parent function get_aggregate_ghgs begin set df = read csv base_path / string data_csv / string CW_UNFCCC_GHG_Emissions.csv delimiter=string thousands=string , set df = df at country != string ANNEXI set df = df at cou...
import pandas import pycountry from pathlib import Path from os.path import realpath base_path = Path(realpath(__file__)).parent def get_aggregate_ghgs(): df = pandas.read_csv( base_path / 'data_csv' / 'CW_UNFCCC_GHG_Emissions.csv', delimiter='\t', thousands="," ) df = df[df.country != 'A...
Python
zaydzuhri_stack_edu_python
function test_drawWire self begin set image_name = call filename co_name set tuple result_file reference_file = call get_path image_name string This function is to create an empty image with a specific dimension with white background, and black/white colored set tuple image canvas = call get_image string L tuple 640 48...
def test_drawWire(self): image_name = filename(sys._getframe().f_code.co_name) result_file, reference_file = get_path(image_name) ''' This function is to create an empty image with a specific dimension with white background, and black/white colored ''' image, canvas = get_...
Python
nomic_cornstack_python_v1
function put_drawing_fbx_async self request begin set HttpRequest = call to_http_info configuration return call __make_request_async HttpRequest string PUT string file end function
def put_drawing_fbx_async(self, request): HttpRequest = request.to_http_info(self.api_client.configuration) return self.__make_request_async(HttpRequest, 'PUT', 'file')
Python
nomic_cornstack_python_v1
import urllib.request from os import path , makedirs , listdir , rename from shutil import rmtree , move from glob import glob from files_processing import natural_key , unzip_file , copy_images , copy_labels , move_files , unzip_files , untar_file , ungz_files from image_processing import generate_fov_masks function o...
import urllib.request from os import path, makedirs, listdir, rename from shutil import rmtree, move from glob import glob from .files_processing import natural_key, unzip_file, copy_images, copy_labels, move_files, unzip_files, untar_file, ungz_files from .image_processing import generate_fov_masks def organize_chas...
Python
zaydzuhri_stack_edu_python
function CounterReset self argin begin comment PROTECTED REGION ID(Counter.CounterReset) ENABLED START # set _value = argin if _value == _fire_event_at begin call push_change_event string value _value end return _value end function comment PROTECTED REGION END # // Counter.CounterReset
def CounterReset(self, argin): # PROTECTED REGION ID(Counter.CounterReset) ENABLED START # self._value = argin if self._value == self._fire_event_at: self.push_change_event("value", self._value) return self._value # PROTECTED REGION END # // Counter.CounterReset
Python
nomic_cornstack_python_v1
function find_subsets s begin set subsets = list for i in range length s + 1 begin for subset in call combinations s i begin append subsets subset end end return subsets end function set s = set literal 1 2 3 set result = call find_subsets s print result
def find_subsets(s): subsets = [] for i in range(len(s)+1): for subset in itertools.combinations(s, i): subsets.append(subset) return subsets s = {1,2,3} result = find_subsets(s) print(result)
Python
flytech_python_25k
import math import sys import pygame from pygame.locals import QUIT , MOUSEBUTTONUP import numpy as np import time set xmax = 300 set ymax = 200 set start_x = integer input string Enter x coordinate of start position: set start_y = integer input string Enter y coordinate of start position: set goal_x = integer input st...
import math import sys import pygame from pygame.locals import QUIT, MOUSEBUTTONUP import numpy as np import time xmax = 300 ymax = 200 start_x = int(input("Enter x coordinate of start position: ")) start_y = int(input("Enter y coordinate of start position: ")) goal_x = int(input("Enter x coordinate of go...
Python
zaydzuhri_stack_edu_python
comment -*- coding: UTF-8 -*- string Created on 2014/3/22 @author: rogers from __future__ import print_function from sklearn import datasets from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report from sklearn.svm import SVC im...
# -*- coding: UTF-8 -*- ''' Created on 2014/3/22 @author: rogers ''' from __future__ import print_function from sklearn import datasets from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report from sklearn.svm impo...
Python
zaydzuhri_stack_edu_python
function use_neutron_distances_in_model_in_place model begin set params = call get_current_pdb_interpretation_params set use_neutron_distances = true set log = call null_out process make_restraints=true pdb_interpretation_params=params call set_hydrogen_bond_length show=false end function
def use_neutron_distances_in_model_in_place(model): params = model.get_current_pdb_interpretation_params() params.pdb_interpretation.use_neutron_distances = True model.log=null_out() model.process(make_restraints = True, pdb_interpretation_params = params) model.set_hydrogen_bond_len...
Python
nomic_cornstack_python_v1
with open string outcome.csv string r as f begin set lines = read lines f set s = set for line in lines begin add s line end with open string clean.csv string w as g begin for item in sorted s begin write g item end end end
with open('outcome.csv', 'r') as f: lines = f.readlines() s = set() for line in lines: s.add(line) with open('clean.csv', 'w') as g: for item in sorted(s): g.write(item)
Python
zaydzuhri_stack_edu_python
function setUp self begin set obj = dict string foo string bar end function
def setUp(self): self.obj = {"foo": "bar"}
Python
nomic_cornstack_python_v1
function test_templates_program_detail_meta_description_empty_program_excerpt self begin set program = call ProgramFactory set page = extended_object call publish string en set url = call get_absolute_url set response = get client url assert equal status_code 200 call assertNotContains response string og:description en...
def test_templates_program_detail_meta_description_empty_program_excerpt(self): program = ProgramFactory() page = program.extended_object page.publish("en") url = program.extended_object.get_absolute_url() response = self.client.get(url) self.assertEqual(response.status_...
Python
nomic_cornstack_python_v1
import subprocess import time import pymysql while true begin comment Porta 3306 é padrão, caso a sua seja especifica, Altere set conexao = call connect host=string seu host aqui db=string Nome do DB user=string Usuario passwd=string Senha port=3306 set i = 0 set count = 0 comment Numero de Repetições for i in range 0 ...
import subprocess import time import pymysql while (True): conexao = pymysql.connect(host='seu host aqui', db='Nome do DB', user='Usuario', passwd='Senha', port=3306) #Porta 3306 é padrão, caso a sua seja especifica, Altere i = 0 count = 0 for i in range(0, 10): #Numero de Repetições cursor = c...
Python
zaydzuhri_stack_edu_python
from collections import namedtuple import ipaddr from twisted.python import log class Rule extends object begin function __init__ self conditions action begin set conditions = conditions set action = action end function function _get_list self key begin set value = get conditions key list if not is instance value list ...
from collections import namedtuple import ipaddr from twisted.python import log class Rule(object): def __init__(self, conditions, action): self.conditions = conditions self.action = action def _get_list(self, key): value = self.conditions.get(key, []) if not isinstance(value...
Python
zaydzuhri_stack_edu_python
function json2crf training_data begin from app.nlu.tasks import sentence_tokenize , pos_tag_and_label set labeled_examples = list for example in training_data begin comment POS tag and initialize bio label as 'O' for all the tokens set tagged_example = call pos_tag_and_label get example string text comment find no of ...
def json2crf(training_data): from app.nlu.tasks import sentence_tokenize, pos_tag_and_label labeled_examples = [] for example in training_data: # POS tag and initialize bio label as 'O' for all the tokens tagged_example = pos_tag_and_label(example.get("text")) ...
Python
nomic_cornstack_python_v1
function square number begin if number < 1 or number > 64 begin raise call ValueError string It doesn't make sense to calculate the number of grains given on square { number } of a 64-square chessboard. end return 1 ? number - 1 end function function total begin return 1 ? 64 - 1 end function
def square(number): if number < 1 or number > 64: raise ValueError( f"It doesn't make sense to calculate the number of grains given on square {number} of a 64-square chessboard." ) return 1 << (number - 1) def total(): return (1 << 64) - 1
Python
zaydzuhri_stack_edu_python
function reloadBtnClick begin set t = thread target=reloadBtnAction call setDaemon true start t end function
def reloadBtnClick(): t = threading.Thread(target=reloadBtnAction) t.setDaemon(True) t.start()
Python
nomic_cornstack_python_v1
string class Train: def __init__(self, destinations, expected_time): self.destinations = destinations self.expected_time = expected_time ​ def get_expected_time(self): return self.expected_time ​ def set_expected_time(self, expected_time): self.expected_time = expected_time ​ def manage_delays(self, dest, delay): if de...
""" class Train: def __init__(self, destinations, expected_time): self.destinations = destinations self.expected_time = expected_time ​ def get_expected_time(self): return self.expected_time ​ def set_expected_time(self, expected_time): self.expected_time = expected_time ​ ...
Python
zaydzuhri_stack_edu_python
from numpy import * import numpy from scipy.sparse import lil_matrix , csr_matrix from scipy.io import loadmat from data_config import * comment import h5py function generate_ratings_matrix data begin string Non sparse Matrix format: MAX_USER_ID x MAX_MOVIE_ID Return value: matrix set ratings_file = open data at string...
from numpy import * import numpy from scipy.sparse import lil_matrix, csr_matrix from scipy.io import loadmat from data_config import * # import h5py def generate_ratings_matrix(data): """ Non sparse Matrix format: MAX_USER_ID x MAX_MOVIE_ID Return value: matrix """ ratings_file = open(data['ratings_new'], 'r') ...
Python
zaydzuhri_stack_edu_python
comment @param inorder, a list of integers comment @param postorder, a list of integers comment @return a tree node function subbuildTree self postorder inorder pbegin pend ibegin iend begin if pbegin - pend == 0 begin return none end set val = postorder at pend - 1 set index = index inorder val set lsize = index - ibe...
# @param inorder, a list of integers # @param postorder, a list of integers # @return a tree node def subbuildTree(self, postorder, inorder,pbegin,pend,ibegin,iend): if pbegin-pend==0: return None val = postorder[pend-1] index = inorder.index(val) lsize = index-ibegin cnode = TreeNode(val) ...
Python
zaydzuhri_stack_edu_python
function borealis_array_to_dmap_files filename borealis_filetype slice_id dmap_filename begin set borealis_converter = call BorealisConvert filename borealis_filetype dmap_filename slice_id borealis_file_structure=string array comment overwrite to as generated set dmap_filename = sdarn_filename comment compress (and ad...
def borealis_array_to_dmap_files(filename, borealis_filetype, slice_id, dmap_filename): borealis_converter = BorealisConvert(filename, borealis_filetype, dmap_filename, slice_id, borealis_file_structure='array') dmap_filename = borealis_converter.sdarn_filename # overwrite to as gen...
Python
nomic_cornstack_python_v1
function test_listSnapshot_as_rootadmin_rec_true self begin set apiKey = user_a_apikey set securityKey = user_a_secretkey set snapshotList = list apiclient isrecursive=string true debug string List as ROOT Admin - isrecursive=true %s % snapshotList assert equal length snapshotList == 1 true string Number of items in li...
def test_listSnapshot_as_rootadmin_rec_true(self): self.apiclient.connection.apiKey = self.user_a_apikey self.apiclient.connection.securityKey = self.user_a_secretkey snapshotList = Snapshot.list(self.apiclient, isrecursive="true") self.debug("List as ROOT Admin - isrecursive=true %s" %...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import sys function load begin string load index, words and docs set sIndex = string index.txt set sWord = string words.txt set sDoc = string doc.txt set lIndex = list comment load index set fIndex = open sIndex string r for line in read lines fIndex begin append lIndex list comprehension ...
#!/usr/bin/env python import sys def load(): ''' load index, words and docs ''' sIndex = 'index.txt' sWord = 'words.txt' sDoc = 'doc.txt' lIndex = [] #load index fIndex = open(sIndex, 'r') for line in fIndex.readlines(): lIndex.append( [int(i) for i in line.split()] ) fIndex.close() #load words lWord = ...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torch.nn.functional as F from NegativeSampling import * class TextCNN_NegSamp extends Module begin string CNN text classification model, based on the paper. function __init__ self config begin call __init__ set V = vocab_size set E = embedding_dim set Nf = num_filters set Ks = ...
import torch import torch.nn as nn import torch.nn.functional as F from NegativeSampling import * class TextCNN_NegSamp(nn.Module): """ CNN text classification model, based on the paper. """ def __init__(self, config): super(TextCNN_NegSamp, self).__init__() V = config.vocab_size ...
Python
zaydzuhri_stack_edu_python
function __init__ self file_path begin set file_path = call Path file_path set fname = name set d_stgs = call DisplaySettings set c_stgs = call CalculationSettings info string { self } create end function
def __init__(self, file_path): self.file_path = Path(file_path) self.fname = self.file_path.name self.d_stgs = settings.DisplaySettings() self.c_stgs = settings.CalculationSettings() logger.info(f'{self} create')
Python
nomic_cornstack_python_v1
function best_policy self agent_host begin call clear_inventory set policy = list set current_r = 0 set is_first_action = true set next_a = string comment while next_a != "end_action": comment curr_state = self.get_curr_state() comment possible_actions = self.get_possible_actions(agent_host, is_first_action) comment ...
def best_policy(self, agent_host): self.clear_inventory() policy = [] current_r = 0 is_first_action = True next_a = "" # while next_a != "end_action": # curr_state = self.get_curr_state() # possible_actions = self.get_possible_actions(agent_host, i...
Python
nomic_cornstack_python_v1
function test_pipeline_simple_model x_dict_primary begin set fast_window = 10 set slow_window = 20 set maco = call MovingAverageCrossOverPredictor fast=fast_window slow=slow_window column_name=CLOSE fill_between_crossovers=true set pipeline = call StrategySignalPipeline feature_transformers_primary_model=dict string pr...
def test_pipeline_simple_model(x_dict_primary): fast_window = 10 slow_window = 20 maco = MovingAverageCrossOverPredictor( fast=fast_window, slow=slow_window, column_name=CLOSE, fill_between_crossovers=True, ) pipeline = StrategySignalPipeline( feature_transfor...
Python
nomic_cornstack_python_v1
if length a != length n begin print false end set c = 0 set b = 0 for i in a begin set c = c + ordinal i end for g in a begin set b = b + ordinal g end if c == b begin print true end else begin print false end
if len(a)!= len(n): print (False) c=0 b=0 for i in a: c+=ord(i) for g in a: b+=ord(g) if c==b: print (True) else: print (False)
Python
zaydzuhri_stack_edu_python
function __eq__ self other begin if is instance other Coordinate begin return x == x and y == y end else if is instance other Tuple begin return x == other at 0 and y == other at 1 end else begin return NotImplemented end end function
def __eq__(self, other: Union[Coordinate, Tuple]) -> bool: if isinstance(other, Coordinate): return self.x == other.x and self.y == other.y elif isinstance(other, Tuple): return self.x == other[0] and self.y == other[1] else: return NotImplemented
Python
nomic_cornstack_python_v1
import random set n = 5 comment Generate a random array of unique elements set arr = random sample range 1 10 * n n comment Sort the array in ascending order sort arr print arr
import random n = 5 # Generate a random array of unique elements arr = random.sample(range(1, 10*n), n) # Sort the array in ascending order arr.sort() print(arr)
Python
jtatman_500k
function createFile name begin try begin comment 別名 with open name string w encoding=string utf-8 as f begin write f string 123 end end comment 接 FileNotFoundError 類別的錯誤訊息 except FileNotFoundError as e begin print e print args set name = replace name string / string with open name string w encoding=string utf-8 as f be...
def createFile(name): try: with open(name, 'w', encoding='utf-8') as f: # 別名 f.write('123') except FileNotFoundError as e: # 接 FileNotFoundError 類別的錯誤訊息 print(e) print(e.args) name = name.replace('/', '') with open(name, 'w', encoding='utf-8') as f...
Python
zaydzuhri_stack_edu_python
from flask import Flask , jsonify from flask_restful import Api , Resource , reqparse import time import sqlite3 comment Creating database for the project set connection = call connect string Health_data.db set cursor = call cursor execute cursor string CREATE TABLE IF NOT EXISTS Health_info (row_id INTEGER PRIMARY KEY...
from flask import Flask, jsonify from flask_restful import Api, Resource, reqparse import time import sqlite3 # Creating database for the project connection = sqlite3.connect("Health_data.db") cursor = connection.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS Health_info (row_id INTEGER PRIMARY KEY, patient_id in...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from sklearn import datasets set iris = call load_iris set x_vals = array list comprehension x at slice 0 : 3 : for x in data set y_vals = array list comprehension x at 3 for x in data comment print(y_vals) set sess = call Session set seed = 2 ...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from sklearn import datasets iris = datasets.load_iris() x_vals = np.array([x[0:3] for x in iris.data]) y_vals = np.array([x[3] for x in iris.data]) # print(y_vals) sess = tf.Session() seed = 2 tf.set_random_seed(seed) np.random.seed(seed) ...
Python
zaydzuhri_stack_edu_python
async function modify_ack_deadline self request=none subscription=none ack_ids=none ack_deadline_seconds=none retry=DEFAULT timeout=none metadata=tuple begin comment Create or coerce a protobuf request object. comment Sanity check: If we got a request object, we should *not* have comment gotten any keyword arguments th...
async def modify_ack_deadline( self, request: Union[pubsub.ModifyAckDeadlineRequest, dict] = None, *, subscription: str = None, ack_ids: Sequence[str] = None, ack_deadline_seconds: int = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float ...
Python
nomic_cornstack_python_v1
import numpy as np import torch import torch.nn as nn from torch.distributions import Categorical class TypeModel extends Module begin string Type model (uncoditional) for Attention Induced Program Learning Parameters ---------- max_k: int Maximum number of parts that can be present in an image at once num_parts: int N...
import numpy as np import torch import torch.nn as nn from torch.distributions import Categorical class TypeModel(nn.Module): ''' Type model (uncoditional) for Attention Induced Program Learning Parameters ---------- max_k: int Maximum number of parts that can be present in an image at...
Python
zaydzuhri_stack_edu_python
function predict_api begin set data = call get_json set dataset = call DataFrame data index=list 0 set new_df = call preprocess dataset print type new_df if is instance new_df str begin return string Error! end else begin set result = predict new_df return call jsonify result end end function
def predict_api(): data = request.get_json() dataset = pd.DataFrame(data, index=[0, ]) new_df = preprocess(dataset) print(type(new_df)) if isinstance(new_df, str): return "Error!" else: result = predict(new_df) return jsonify(result)
Python
nomic_cornstack_python_v1
function make_env_file env_string begin with open string .env.example string w as f begin write f env_string end end function
def make_env_file(env_string): with open('.env.example', 'w') as f: f.write(env_string)
Python
nomic_cornstack_python_v1
from keras.layers import Dense , Conv2D , MaxPooling2D , Flatten , Lambda , Input from keras.models import Model , load_model from keras.optimizers import Adam , RMSprop class QNet extends object begin set __slots__ = list string model string optimizer string learningRate string numberOfActions string inputDimensions s...
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Lambda, Input from keras.models import Model, load_model from keras.optimizers import Adam, RMSprop class QNet(object): __slots__ = ["model", "optimizer", "learningRate", "numberOfActions", "inputDimensions", "useMaxPooling"] def __init__(self, l...
Python
zaydzuhri_stack_edu_python
string Advent of Code 2020 By Emet Behrendt Day 7 Section 1 import os set SELF_DIR = directory name path __file__ set INPUT_PATH = join path SELF_DIR string puzzle_input.txt comment Fetch puzzle input with open INPUT_PATH string r as file begin set PUZZLE_INPUT = split read file string end class Bag begin set bag_index...
""" Advent of Code 2020 By Emet Behrendt Day 7 Section 1 """ import os SELF_DIR = os.path.dirname(__file__) INPUT_PATH = os.path.join(SELF_DIR, 'puzzle_input.txt') # Fetch puzzle input with open(INPUT_PATH, 'r') as file: PUZZLE_INPUT = file.read().split('\n') class Bag: bag_index = {} def __init__(self, name, c...
Python
zaydzuhri_stack_edu_python
async function test_program_next_run aresponses authenticated_local_client begin async_with authenticated_local_client begin add authenticated_local_client string { TEST_HOST } : { TEST_PORT } string /api/4/program/nextrun string get response=call json_response loads call load_fixture string program_nextrun_response.js...
async def test_program_next_run( aresponses: ResponsesMockServer, authenticated_local_client: ResponsesMockServer ) -> None: async with authenticated_local_client: authenticated_local_client.add( f"{TEST_HOST}:{TEST_PORT}", "/api/4/program/nextrun", "get", ...
Python
nomic_cornstack_python_v1
function tenant_id self begin return get pulumi self string tenant_id end function
def tenant_id(self) -> pulumi.Input[str]: return pulumi.get(self, "tenant_id")
Python
nomic_cornstack_python_v1
function ensure_valid_file self begin if file_name is none begin raise exception string Must specify file for SVGMobject end if exists path file_name begin set file_path = file_name return end set relative = join path get current directory file_name if exists path relative begin set file_path = relative return end set ...
def ensure_valid_file(self): if self.file_name is None: raise Exception("Must specify file for SVGMobject") if os.path.exists(self.file_name): self.file_path = self.file_name return relative = os.path.join(os.getcwd(), self.file_name) if os.path.exis...
Python
nomic_cornstack_python_v1
function getCorrelation_l self series_id begin comment regard the corrcoef of categorical as 0 if type == categorical begin return 0 end if type == temporal begin set data1 = list comprehension i for i in range tuple_num // series_num end else begin set data1 = X at series_id end set data2 = Y at series_id set log_data...
def getCorrelation_l(self,series_id): if self.fx.type == Type.categorical: # regard the corrcoef of categorical as 0 return 0 if self.fx.type == Type.temporal: data1 = [i for i in range(self.tuple_num // self.series_num)] else: data1 = self.X[series_id] ...
Python
nomic_cornstack_python_v1
function _volume_to_step_position self volume begin comment noinspection PyArgumentEqualDefault set steps = volume * _steps_per_ml return round call m_as string steps + _offset_steps end function
def _volume_to_step_position(self, volume: pint.Quantity) -> int: # noinspection PyArgumentEqualDefault steps = volume * self._steps_per_ml return round(steps.m_as("steps")) + self._offset_steps
Python
nomic_cornstack_python_v1
function format_input_type t id_map begin if call is_required_type t begin set t = of_type set fmt = string %s end else begin set fmt = string Optional[%s] end if call is_list_type t begin return fmt % string list[ { call format_input_type of_type id_map } ] end if call is_custom_scalar_type t and name in id_map begin ...
def format_input_type(t: GraphQLInputType, id_map: IDMap) -> str: if is_required_type(t): t = t.of_type fmt = "%s" else: fmt = "Optional[%s]" if is_list_type(t): return fmt % f"list[{format_input_type(t.of_type, id_map)}]" if is_custom_scalar_type(t) and t.name in id_ma...
Python
nomic_cornstack_python_v1
from gpkit import Variable , Model class FlightState extends Model begin function setup self begin set rho = call Variable string \rho 1.225 string kg/m**3 string air density set rho = call Variable string \rho 1.225 string kg/m**3 string air density set mu = call Variable string \mu 1.789e-05 string kg/m/s string air ...
from gpkit import Variable, Model class FlightState(Model): def setup(self): rho = self.rho = Variable("\\rho", 1.225, "kg/m**3", "air density") mu = self.mu = Variable("\\mu", 1.789e-5, "kg/m/s", "air viscosity") V = self.V = Variable("V", "knots", "speed") constraints = [rho == ...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 _*- string @author:hql @file: Lib @time: 2018/08/{DAY} string 物理基础运算库 from Vector import Vector function VectorCollision m1 v1 m2 v2 begin set m12 = m1 - m2 set mv2 = 2 * m2 * v2 set mv1 = 2 * m1 * v1 set x = m12 * v1 + mv2 // m1 + m2 set y = - m12 * v2 + mv1 // m1 + m2 return tuple x y end fun...
#-*- coding:utf-8 _*- """ @author:hql @file: Lib @time: 2018/08/{DAY} """ """ 物理基础运算库 """ from Vector import Vector def VectorCollision( m1 ,v1 ,m2 ,v2 ): m12 = m1-m2 mv2 = 2*m2*v2 mv1 = 2*m1*v1 x = (m12*v1+mv2)//(m1+m2) y = (-m12 * v2 + mv1) // (m1 + m2) return x,y if __name__ == "__main__":...
Python
zaydzuhri_stack_edu_python
function evaluate_classifier self begin set predictions = predict _model _test_data return call f1_score _test_labels predictions end function
def evaluate_classifier(self): predictions = self._model.predict(self._test_data) return f1_score(self._test_labels, predictions)
Python
nomic_cornstack_python_v1
comment @lc app=leetcode id=96 lang=python3 comment [96] Unique Binary Search Trees comment https://leetcode.com/problems/unique-binary-search-trees/description/ comment algorithms comment Medium (46.83%) comment Total Accepted: 207.8K comment Total Submissions: 443.6K comment Testcase Example: '3' comment Given n, how...
# # @lc app=leetcode id=96 lang=python3 # # [96] Unique Binary Search Trees # # https://leetcode.com/problems/unique-binary-search-trees/description/ # # algorithms # Medium (46.83%) # Total Accepted: 207.8K # Total Submissions: 443.6K # Testcase Example: '3' # # Given n, how many structurally unique BST's (binary ...
Python
zaydzuhri_stack_edu_python
function update self clip_id feature_vec=none is_background=false timeout=none begin with call write_lock timeout begin set clip_id = integer clip_id if feature_vec is not none and not ndim == 1 and length feature_vec == shape at 1 begin raise call ValueError string Given feature vector not compatible (dimensionality o...
def update(self, clip_id, feature_vec=None, is_background=False, timeout=None): with self._rw_lock.write_lock(timeout): clip_id = int(clip_id) if feature_vec is not None and \ not (feature_vec.ndim == 1 and len(feature_vec) == s...
Python
nomic_cornstack_python_v1
function _freeze_layers self begin comment Freeze everything and then unfreeze only the layers we want to train. for model in tuple vae unet text_encoder begin for param in parameters model begin set requires_grad = false end end for param in parameters new_embedding begin set requires_grad = true end end function
def _freeze_layers(self) -> None: # Freeze everything and then unfreeze only the layers we want to train. for model in ( self.vae, self.unet, self.text_encoder, ): for param in model.parameters(): param.requires_grad = False ...
Python
nomic_cornstack_python_v1
string A class within cim v1.5 type system. CIM CODE GENERATOR :: Code generated @ 2012-05-02 12:24:01.321176. comment Module imports. import datetime import simplejson import types import uuid comment Intra/Inter-package imports. from pycim.v1_5.types.software.timing_units import TimingUnits comment Module exports. se...
"""A class within cim v1.5 type system. CIM CODE GENERATOR :: Code generated @ 2012-05-02 12:24:01.321176. """ # Module imports. import datetime import simplejson import types import uuid # Intra/Inter-package imports. from pycim.v1_5.types.software.timing_units import TimingUnits # Module exports. __all__ = ['Ti...
Python
zaydzuhri_stack_edu_python
async function cmd_mmlogs self author channel server auth_id begin if auth_id not in mod_mail_db begin raise call CommandError string ERROR: User ID not found in Mod Mail DB end set quick_switch_dict = dict set quick_switch_dict at auth_id = dict string embed call Embed ; string member_obj await call get_user_info aut...
async def cmd_mmlogs(self, author, channel, server, auth_id): if auth_id not in self.mod_mail_db: raise CommandError('ERROR: User ID not found in Mod Mail DB') quick_switch_dict = {} quick_switch_dict[auth_id] = {'embed': discord.Embed(), 'member_obj': await self.get_user_info(auth_i...
Python
nomic_cornstack_python_v1
function next_possible_moves self is_vamp begin set next_possible_positions = call next_possible_positions is_vamp comment pour chaque groupe, on regarde la répartition de monstres autour de la case de départ set group_repartitions = dict for tuple tuple x_old y_old next_positions in items next_possible_positions begi...
def next_possible_moves(self, is_vamp): next_possible_positions = self.next_possible_positions(is_vamp) group_repartitions = {} # pour chaque groupe, on regarde la répartition de monstres autour de la case de départ for (x_old, y_old), next_positions in next_possible_positions.items(): ...
Python
nomic_cornstack_python_v1
function _keep_row row hits begin if row at 0 in hits begin if decimal row at 3 < decimal hits at row at 0 at string Hit_e-val begin return true end else begin return false end end else begin return true end end function
def _keep_row(row, hits): if row[0] in hits: if float(row[3]) < float(hits[row[0]]["Hit_e-val"]): return True else: return False else: return True
Python
nomic_cornstack_python_v1
function get_viewbox node default=tuple string 0 string 0 string 640 string 480 begin comment Available for: svg, symbol (via use), image, foreignObject comment pylint:disable=invalid-name set viewBox = get node string viewBox if viewBox is none begin return default end comment Fixme: Handle preserveAspectRatio set tup...
def get_viewbox(node, default=('0','0','640','480')): # Available for: svg, symbol (via use), image, foreignObject viewBox = node.get('viewBox') # pylint:disable=invalid-name if viewBox is None: return default # Fixme: Handle preserveAspectRatio x, y, w, h = [v for v in viewBox.split(' ')]...
Python
nomic_cornstack_python_v1
function reward_func self state action Time_matrix begin set reward = 0.0 set trip_time = 0 if action == list 0 0 begin set reward = - 1 * C set trip_time = 1 return tuple reward trip_time end set curr_loc = state at 0 set curr_hour = state at 1 set curr_day = state at 2 set start_loc = action at 0 set end_loc = action...
def reward_func(self, state, action, Time_matrix): reward = 0.0 trip_time = 0 if action == [0,0]: reward = (-1 * C) trip_time = 1 return reward, trip_time curr_loc = state[0] curr_hour = state[1] curr_day = state[2] ...
Python
nomic_cornstack_python_v1
try begin set length = integer input set string = list split input string for i in string begin set check = integer i set k = count string i if k > 1 begin set k = i break end else begin set k = string unique end end print k end except any begin print string Invalid input end
try: length = int(input()) string = list(input().split(" ")) for i in string : check = int(i) k= string.count(i) if(k>1): k=i break else: k="unique" print(k) except: print("Invalid input")
Python
zaydzuhri_stack_edu_python
function _transfer_str self conn tmp name data begin string transfer string to remote file if type data == dict begin set data = call jsonify data end set tuple afd afile = make file temp set afo = call fdopen afd string w try begin write afo encode data string utf8 end except any begin raise call AnsibleError string f...
def _transfer_str(self, conn, tmp, name, data): ''' transfer string to remote file ''' if type(data) == dict: data = utils.jsonify(data) afd, afile = tempfile.mkstemp() afo = os.fdopen(afd, 'w') try: afo.write(data.encode('utf8')) except: ...
Python
jtatman_500k
function init self begin call init set screen = call set_mode tuple width height call set_caption title end function
def init(self): pygame.init() self.screen = pygame.display.set_mode((self.width, self.height)) pygame.display.set_caption(self.title)
Python
nomic_cornstack_python_v1
function test_template_tags_post self begin pass end function
def test_template_tags_post(self): pass
Python
nomic_cornstack_python_v1
comment import the necessary packages from __future__ import print_function from imutils.video import WebcamVideoStream from imutils.video import FPS import argparse import imutils import cv2 comment construct the argument parse and parse the arguments set ap = call ArgumentParser call add_argument string -n string --n...
# import the necessary packages from __future__ import print_function from imutils.video import WebcamVideoStream from imutils.video import FPS import argparse import imutils import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-n", "--num-frames", type=int,...
Python
zaydzuhri_stack_edu_python
for i in range 1 n begin set resposta = resposta * i end print resposta
for i in range(1, n): resposta *= i print(resposta)
Python
zaydzuhri_stack_edu_python
from collections import defaultdict from scrapy import Spider , Selector from scrapy import Request from urlsresolver import PageUri from urlsresolver import UrlsResolver from exceptions import NotExistSiteError from utils import populate_md5 , deepcopy from conf import InitConfigs as _InitConfigs class Collector exten...
from collections import defaultdict from scrapy import Spider, Selector from scrapy import Request from ..urlsresolver import PageUri from ..urlsresolver import UrlsResolver from ..exceptions import NotExistSiteError from ..utils import populate_md5, deepcopy from ..conf import InitConfigs as _InitConfigs class Coll...
Python
zaydzuhri_stack_edu_python
function run self data begin if data and application begin comment Build tuples for embedding index if embeddings begin set data = list comprehension tuple x element none for tuple x element in enumerate data end comment Process workflow with call spinner string Running workflow.... begin set results = list for result...
def run(self, data): if data and self.application: # Build tuples for embedding index if self.application.embeddings: data = [(x, element, None) for x, element in enumerate(data)] # Process workflow with st.spinner("Running workflow...."): ...
Python
nomic_cornstack_python_v1
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data set mnist = call read_data_sets string course/03-Convolutional-Neural-Networks/MNIST_data/ one_hot=true comment Helper functions comment Initialize weights function init_weights shape begin set init_random_dist = call truncated_normal sh...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("course/03-Convolutional-Neural-Networks/MNIST_data/",one_hot=True) ## Helper functions # Initialize weights def init_weights(shape): init_random_dist = tf.truncated_normal(shape,stddev=0.1) re...
Python
zaydzuhri_stack_edu_python
function get_matches_for_StEWI begin set chemicalmatches = read csv output_dir + string ChemicalsByInventorywithSRS_IDS_forStEWI.csv dtype=dict string SRS_ID string str return chemicalmatches end function
def get_matches_for_StEWI(): chemicalmatches = pd.read_csv(output_dir+'ChemicalsByInventorywithSRS_IDS_forStEWI.csv', dtype={"SRS_ID":"str"}) return chemicalmatches
Python
nomic_cornstack_python_v1
class CurrencyBase begin function __init__ self value name begin set value = value set name = name end function function __str__ self begin return string { value } end function function __repr__ self begin return string { value } { name } end function end class class Account extends CurrencyBase begin function __init__...
class CurrencyBase: def __init__(self, value, name): self.value = value self.name = name def __str__(self): return f"{self.value}" def __repr__(self): return f"{self.value} {self.name}" class Account(CurrencyBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def deposit(sel...
Python
zaydzuhri_stack_edu_python
function fluidVoxelInfo *args checkBounds=true inBounds=none objectSpace=true radius=0.0 voxel=none voxelCenter=true xIndex=0 yIndex=0 zIndex=0 **kwargs begin pass end function
def fluidVoxelInfo(*args, checkBounds: bool=True, inBounds: List[int, int, int]=None, objectSpace: bool=True, radius: float=0.0, voxel: List[float, float, float]=None, voxelCenter: bool=True, xIndex: int=0, yIndex: int=0, zIndex: int=0, **kwargs)->None: pass
Python
nomic_cornstack_python_v1
comment coding:iso-8859-9 Trke comment p_30408.py: numpy.array_equal(a,b), numpy.logical_or(a,b) ve numpy.logical_and(a,b) rnei. import numpy as np set A = array list list 11 12 13 list 21 22 23 list 31 32 33 set B = array list list 11 102 13 list 201 22 203 list 31 32 303 print string A ve B matrisleri: A string B se...
# coding:iso-8859-9 Trke # p_30408.py: numpy.array_equal(a,b), numpy.logical_or(a,b) ve numpy.logical_and(a,b) rnei. import numpy as np A = np.array ([ [11, 12, 13], [21, 22, 23], [31, 32, 33] ]) B = np.array ([ [11, 102, 13], [201, 22, 203], [31, 32, 303] ]) print ("A ve B ma...
Python
zaydzuhri_stack_edu_python
import math set Input = string #.#.##..#.###...##.#....##....### ...#..#.#.##.....#..##.#...###..# ####...#..#.##...#.##..####..#.#. ..#.#..#...#..####.##....#..####. ....##...#.##...#.#.#...#.#..##.. .#....#.##.#.##......#..#..#..#.. .#.......#.....#.....#...###..... #.#.#.##..#.#...###.#.###....#..# #.#..........##.....
import math Input="""#.#.##..#.###...##.#....##....### ...#..#.#.##.....#..##.#...###..# ####...#..#.##...#.##..####..#.#. ..#.#..#...#..####.##....#..####. ....##...#.##...#.#.#...#.#..##.. .#....#.##.#.##......#..#..#..#.. .#.......#.....#.....#...###..... #.#.#.##..#.#...###.#.###....#..# #.#..........##..###..........
Python
zaydzuhri_stack_edu_python
if __name__ == string __main__ begin set food = list string rice string beans append food string broccoli extend food list string bread string pizza print food at slice : 2 : print food at - 1 set breakfast_string = string eggs,fruit,orange juice set breakfast = split breakfast_string string , length breakfast set flo...
if __name__ == '__main__': food = ['rice', 'beans'] food.append('broccoli') food.extend(['bread', 'pizza']) print(food[:2]) print(food[-1]) breakfast_string = 'eggs,fruit,orange juice' breakfast = breakfast_string.split(',') len(breakfast) floating_point_list = [] while Tru...
Python
zaydzuhri_stack_edu_python
function get_cpu_info self begin set xml = call getCapabilities set xml = call parseDoc xml set nodes = call xpathEval string //host/cpu if length nodes != 1 begin set reason = call _ string '<cpu>' must be 1, but %d % length nodes set reason = reason + call serialize raise call InvalidCPUInfo reason=reason end set cpu...
def get_cpu_info(self): xml = self._conn.getCapabilities() xml = libxml2.parseDoc(xml) nodes = xml.xpathEval('//host/cpu') if len(nodes) != 1: reason = _("'<cpu>' must be 1, but %d\n") % len(nodes) reason += xml.serialize() raise exception.InvalidCPUI...
Python
nomic_cornstack_python_v1
import os import shutil set source = input string enter the source folder set destination = input string enter the destination folder set source = source + string / set destination = destination + string / set listOfFiles = list directory source for file in listOfFiles begin copy shutil source + file destination end
import os import shutil source=input('enter the source folder') destination = input ('enter the destination folder') source=source+'/' destination=destination+'/' listOfFiles=os.listdir(source) for file in listOfFiles: shutil.copy((source+file),destination)
Python
zaydzuhri_stack_edu_python
import smbus set bus = call SMBus 1 function writeNumber value begin try begin if value > 20 begin call write_byte 4 value end else begin call write_byte 4 0 end end except any begin return false end finally begin return true end end function function writeBlock block begin try begin call write_i2c_block_data 4 0 block...
import smbus bus = smbus.SMBus(1) def writeNumber(value): try: if value > 20: bus.write_byte(0x04, value) else: bus.write_byte(0x04, 0) except: return False finally: return True def writeBlock(block): try: bus.write_i2c_block_data(0x04, ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sun Feb 12 09:13:00 2017 @author: JunTaniguchi comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri Feb 10 21:01:54 2017 @author: JunTaniguchi import requests function get_flicker_dict text begin string flicker se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 12 09:13:00 2017 @author: JunTaniguchi """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 10 21:01:54 2017 @author: JunTaniguchi """ import requests def get_flicker_dict(text): """ flicker serch APIを利用し、テキスト検索でヒットした...
Python
zaydzuhri_stack_edu_python
import numpy as np comment вводим числа set a = integer input string Введите от: set b = integer input string Введите до: comment возможность ввести два любых числа if a > b begin set tuple a b = tuple b a end comment загадали число set number = random integer a b print string Загадано число от a string до b function g...
import numpy as np # вводим числа a = int(input('Введите от: \n')) b = int(input('Введите до: \n')) # возможность ввести два любых числа if a > b: a, b = b, a # загадали число number = np.random.randint(a, b) print('Загадано число от', a, 'до', b) def game_1(number, mid=a+b // 2, low=a, high=b): """бинарный ...
Python
zaydzuhri_stack_edu_python
function get_service_provider_settings self db begin if _service_provider is none begin set _service_provider = call _get_service_provider_settings call get_service_provider db end return _service_provider end function
def get_service_provider_settings(self, db): if self._service_provider is None: self._service_provider = self._get_service_provider_settings(self._configuration.get_service_provider(db)) return self._service_provider
Python
nomic_cornstack_python_v1
function _signature cls apikey encoded_params begin set signature = call hmacnew apikey at string Secret msg=encoded_params digestmod=_sha512 set _post_headers at string Key = apikey at string Key set _post_headers at string Sign = hex digest signature end function
def _signature(cls, apikey, encoded_params): signature = hmacnew(apikey['Secret'], msg=encoded_params, digestmod=_sha512) cls._post_headers['Key'] = apikey['Key'] cls._post_headers['Sign'] = signature.hexdigest()
Python
nomic_cornstack_python_v1
function calculate score interpreted_classes pathogenicity_class_map=default_pathogencity_class_map begin if length pathogenicity_class_map > 2 begin warn string Can't calculate ROC curves for multiclass. return dict end set tuple fpr tpr thresholds = call roc_curve interpreted_classes data return dict string fpr fpr ...
def calculate(score: Score, interpreted_classes: Series, pathogenicity_class_map=default_pathogencity_class_map) -> dict: if len(pathogenicity_class_map) > 2: warn("Can't calculate ROC curves for multiclass.") return {} fpr, tpr, thresholds = roc_curve(interpret...
Python
nomic_cornstack_python_v1
async function async_get_downstream self begin if token is none begin await call async_initialize_token end clear ds_channels set raw = await call _async_ws_get_function CMD_DOWNSTREAM try begin set xml_root = call fromstring raw for downstream in iterate string downstream begin append ds_channels call DownstreamChanne...
async def async_get_downstream(self): if self.token is None: await self.async_initialize_token() self.ds_channels.clear() raw = await self._async_ws_get_function(CMD_DOWNSTREAM) try: xml_root = element_tree.fromstring(raw) for downstream in xml_root....
Python
nomic_cornstack_python_v1
import socket import bin.settings as s function action data begin return encode upper data string utf-8 end function function run begin set sock = call socket call bind tuple IP PORT call listen 1 print string start listen port { PORT } : set tuple conn addr = call accept print string --- conection --- while true begin...
import socket import bin.settings as s def action(data): return data.upper().encode("utf-8") def run(): sock = socket.socket() sock.bind((s.IP, s.PORT)) sock.listen(1) print(f"start listen port {s.PORT}:") conn, addr = sock.accept() print("--- conection ---") while True: ...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 import itertools class KwargsUtils extends object begin decorator staticmethod function get_arg_matrix arg_map begin string Tranform {"a": [1, 2, 3], "b": [1], "c": [1, 2]} to [ {"a": 1, "b": 1, "c": 1}, {"a": 2, "b": 1, "c": 2}, {"a": 3, "b": 1, "c": 1}, {"a": 1, "b": 1, "c": 2}, {"a": 2, "b": 1, ...
# coding=utf-8 import itertools class KwargsUtils(object): @staticmethod def get_arg_matrix(arg_map): """ Tranform {"a": [1, 2, 3], "b": [1], "c": [1, 2]} to [ {"a": 1, "b": 1, "c": 1}, {"a": 2, "b": 1, "c": 2}, {"a": 3, "b...
Python
zaydzuhri_stack_edu_python
function minibatch_k_means X k mbsize iters begin set samples = shape at 0 comment Initialize centers set seed = call argsort call rand samples at slice : k : set centers = X at seed set v = ones k for i in call xrange iters begin set sample = call argsort call rand samples at slice : mbsize : set M = X at sample s...
def minibatch_k_means(X, k, mbsize, iters): samples = X.shape[0] # Initialize centers seed = np.argsort(np.random.rand(samples))[:k] centers = X[seed] v = np.ones(k) # for i in xrange(iters): sample = np.argsort(np.random.rand(samples))[:mbsize] M = X[sample] d = np....
Python
nomic_cornstack_python_v1
function run_multicore args corpus dictionary passes alpha workers pre begin set lda = LdaMulticore set ldamodel = call lda corpus num_topics=num_topics id2word=dictionary passes=passes alpha=alpha workers=workers prefix=pre return model end function
def run_multicore(args, corpus, dictionary, passes, alpha, workers, pre): lda = gensim.models.ldamulticore.LdaMulticore ldamodel = lda(corpus, num_topics=args.num_topics, id2word=dictionary, passes=passes, alpha=alpha, workers=workers, prefix=pre) return model
Python
nomic_cornstack_python_v1
function transform_image img_path begin comment define transformation steps set crop_to_lower_percentage = 50 set output_size = tuple 256 256 set transform = call get_predict_image_transform comment load image set img = decimal comment perform transformation set input = transform img comment single image instead of bat...
def transform_image(img_path: Path) -> torch.Tensor: # define transformation steps crop_to_lower_percentage = 50 output_size = (256, 256) transform = get_predict_image_transform() # load image img = torchvision.io.read_image(str(img_path)).float() # perform transformation input = trans...
Python
nomic_cornstack_python_v1
if A + B > C begin print B + C end else if A + B == C begin print 2 * B + A end else begin print 2 * B + A + 1 end
if A + B > C: print(B + C) elif A + B == C: print(2*B + A) else: print(2*B + A + 1)
Python
zaydzuhri_stack_edu_python
function getLastIndexWithoutHeader filename begin comment subtract 1 since start index=0 return call getCSVLengthWithoutHeader filename - 1 end function
def getLastIndexWithoutHeader(filename): return getCSVLengthWithoutHeader(filename)-1 # subtract 1 since start index=0
Python
nomic_cornstack_python_v1
function get_broadcast_transaction_hashes coin_symbol=string btc api_key=none limit=10 begin string Warning, slow! set transactions = call get_broadcast_transactions coin_symbol=coin_symbol api_key=api_key limit=limit return list comprehension tx at string hash for tx in transactions end function
def get_broadcast_transaction_hashes(coin_symbol='btc', api_key=None, limit=10): ''' Warning, slow! ''' transactions = get_broadcast_transactions( coin_symbol=coin_symbol, api_key=api_key, limit=limit, ) return [tx['hash'] for tx in transactions]
Python
jtatman_500k
function make_mixture_prior latent_size mixture_components begin string Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representing the di...
def make_mixture_prior(latent_size, mixture_components): """Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representin...
Python
jtatman_500k
function delegated_role_definition_ids self begin return get pulumi self string delegated_role_definition_ids end function
def delegated_role_definition_ids(self) -> Optional[Sequence[str]]: return pulumi.get(self, "delegated_role_definition_ids")
Python
nomic_cornstack_python_v1
function write_csv file_path data delimiter=string , begin with open file_path string w encoding=string UTF8 newline=string as file begin set writer = writer file delimiter=delimiter comment write multiple rows write rows writer data return true end end function
def write_csv(file_path, data, delimiter=","): with open(file_path, 'w', encoding='UTF8', newline='') as file: writer = csv.writer(file, delimiter=delimiter) # write multiple rows writer.writerows(data) return True
Python
nomic_cornstack_python_v1
function addParserOptions parser begin comment these options apply globally call add_option string --line-length dest=string lineLength type=string int default=80 help=string Set the length of lines in the file [default: %default] call add_option string --lines-split dest=string splitLines default=true action=string st...
def addParserOptions(parser): #these options apply globally parser.add_option("--line-length",dest="lineLength",type="int",default=80 ,help="Set the length of lines in the file [default: %default]") parser.add_option("--lines-split",dest="splitLines",default=True ,action="store_true" ,help="Separat...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding:utf-8 -*- class Student extends object begin string docstring for student function __init__ self name score begin set name = name set score = score end function function print_score self begin print string %s: %s % tuple name score end function end class set bart = call ...
# !/usr/bin/env python3 # -*- coding:utf-8 -*- class Student(object): """docstring for student""" def __init__(self, name,score): self.name = name self.score = score def print_score(self): print('%s: %s'%(self.name,self.score)) bart = Student('Bart Simpson',59) lisa = Student('Lisa Simpson',87) bart.print_sc...
Python
zaydzuhri_stack_edu_python
function prep_python_creds self begin set creds = dictionary generator expression tuple call rm_prefix lower k at 0 k at 1 for k in call prep_nova_creds if get creds string url begin set creds at string auth_url = pop creds string url end if get creds string tenant_name begin set creds at string project_id = pop creds ...
def prep_python_creds(self): creds = dict((utils.rm_prefix(k[0].lower()), k[1]) for k in self.prep_nova_creds()) if creds.get('url'): creds['auth_url'] = creds.pop('url') if creds.get('tenant_name'): creds['project_id'] = creds.pop('tenant_name'...
Python
nomic_cornstack_python_v1
function parsiraj_upit upit begin set delovi = split upit set saLogickimOperatorom = list set reciUpita = list for deo in delovi begin if upper deo in list string AND string OR string NOT begin append saLogickimOperatorom deo end else begin append reciUpita deo end end comment Ako je duzina veca od jedan znaci da je ...
def parsiraj_upit(upit): delovi = upit.split() saLogickimOperatorom = [] reciUpita = [] for deo in delovi: if deo.upper() in ['AND', 'OR', 'NOT']: saLogickimOperatorom.append(deo) else: reciUpita.append(deo) if len(saLogickimOperatorom) > 1: # Ako je duzina...
Python
zaydzuhri_stack_edu_python
function test_lt self begin comment Test Case 1 set seq1 = string GGCCTAATTACCCAGTGAACCGTAAT set seq2 = string GCTTCTCAGTCTTGGTGCTTCTGAC assert true call Reverse_Primer seq1 0 < call Reverse_Primer seq2 1 comment Test Case 2 set seq1 = string CATCTTCCATAAAATGATTGTGATAGAAATGTCACT set seq2 = string GTGCAGGGGGTTGCAGGAG as...
def test_lt(self): # Test Case 1 seq1 = "GGCCTAATTACCCAGTGAACCGTAAT" seq2 = "GCTTCTCAGTCTTGGTGCTTCTGAC" self.assertTrue(Reverse_Primer(seq1, 0) < Reverse_Primer(seq2, 1)) # Test Case 2 seq1 = "CATCTTCCATAAAATGATTGTGATAGAAATGTCACT" seq2 = "GTGCAGGGGGTTGCAGGAG" ...
Python
nomic_cornstack_python_v1
import tweepy import json from pprint import pprint with open string keys.json as key_file begin set data = load json key_file end set KEY = data at string keys at string consumer at string key set SECRET = data at string keys at string consumer at string secret set TOKEN = data at string keys at string access at strin...
import tweepy import json from pprint import pprint with open('keys.json') as key_file: data = json.load(key_file) KEY = data["keys"]["consumer"]["key"] SECRET = data["keys"]["consumer"]["secret"] TOKEN = data["keys"]["access"]["token"] T_SECRET = data["keys"]["access"]["secret"] AUTH = tweepy.OAuthHandler(KEY, ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment Created for the picoCTF 2018 buffer overflow 3 challenge comment required brute-forcing a static "canary" implementation from pwn import * import struct import itertools import time set buf = string B * 32 set junk = string D * 16 comment win at 0x080486eb set eip = call pack string <I ...
#!/usr/bin/python # Created for the picoCTF 2018 buffer overflow 3 challenge # required brute-forcing a static "canary" implementation from pwn import * import struct import itertools import time buf = "B" * 32 junk = "D" * 16 #win at 0x080486eb eip = struct.pack("<I",0x080486eb) charset = "0123456789ABCDEFGHIJKLM...
Python
zaydzuhri_stack_edu_python