code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment Tipos de variables [Python] comment Ejercicios de práctica comment Autor: Inove Coding School comment Version: 2.0 comment IMPORTANTE: NO borrar los comentarios comment que aparecen en verde con el hashtag "#" comment Ejemplos variables de texto comment Ingrese tres palabras y arme un acrónimo con ellas comment...
# Tipos de variables [Python] # Ejercicios de práctica # Autor: Inove Coding School # Version: 2.0 # IMPORTANTE: NO borrar los comentarios # que aparecen en verde con el hashtag "#" # Ejemplos variables de texto # Ingrese tres palabras y arme un acrónimo con ellas # Si desea puede modificar el código para ingresar ...
Python
zaydzuhri_stack_edu_python
import argparse import Constants function segment sentence tag begin comment apply segmentation on one single sentence using predicted tags set sentence = list strip sentence set length = length sentence set tag = list map int split strip tag for i in range length - 2 - 1 - 1 begin if tag at i == BEGIN or tag at i == M...
import argparse import Constants def segment(sentence, tag): # apply segmentation on one single sentence using predicted tags sentence = list(sentence.strip()) length = len(sentence) tag = list(map(int, tag.strip().split())) for i in range(length-2, -1, -1): if tag[i] == Constants.BEGIN or...
Python
zaydzuhri_stack_edu_python
function output_results results mvdelim=string output=stdout begin comment We collect all the unique field names, as well as comment convert all multivalue keys to the right form set fields = set for result in results begin for key in keys result begin if is instance result at key list begin set result at string __mv_...
def output_results(results, mvdelim = '\n', output = sys.stdout): # We collect all the unique field names, as well as # convert all multivalue keys to the right form fields = set() for result in results: for key in result.keys(): if(isinstance(result[key], list)): ...
Python
nomic_cornstack_python_v1
function show_people people begin for person in people begin print title person end end function function make_great people begin set great_people = list while people begin set person = pop people set great_person = person + string the Great append great_people great_person end for great_person in great_people begin a...
def show_people(people): for person in people: print(person.title()) def make_great(people): great_people = [] while people: person = people.pop() great_person = person + " the Great" great_people.append(great_person) for great_person in great_people: people.ap...
Python
zaydzuhri_stack_edu_python
function get_user_task self name_user begin set user_tasks = list set scanned_task = list with open path_to_task_file string r as file begin for line in file begin set task = call Task load task line if name_user in admins begin append user_tasks task end else if name_user in members begin append user_tasks task end ...
def get_user_task(self, name_user): user_tasks = [] scanned_task = [] with open(self.path_to_task_file, 'r') as file: for line in file: task = Task() task.load(line) if name_user in task.admins: user_tasks.append(ta...
Python
nomic_cornstack_python_v1
function main begin comment Get stock symbols and name set tickers = read csv string data/symbols.csv set symbols = tickers at string symbol comment Will use 6 months data set tuple s e = call get_date 180 comment To calculate running time set t0 = time comment Run threads set result1 = call get_quotes symbols s e comm...
def main(): # Get stock symbols and name tickers = pd.read_csv("data/symbols.csv") symbols = tickers['symbol'] # Will use 6 months data s, e = get_date(180) # To calculate running time t0 = time.time() # Run threads result1 = get_quotes(symbols, s, e) # Convert result into pa...
Python
nomic_cornstack_python_v1
function _replace_nulls self df begin print string Replacing nulls in the following categories... if string gilded in columns begin print string gilded: changing strings to nums, all to True/False replace df at string gilded to_replace=list string 0 string 1 string 2 value=list 0 1 2 inplace=true set df at string gilde...
def _replace_nulls(self, df): print('Replacing nulls in the following categories...') if 'gilded' in df.columns: print('gilded: changing strings to nums, all to True/False') df['gilded'].replace(to_replace=['0','1','2'], value=[0,1,2], inplace=True) df['gilded'] = df[...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- set ticker = string SWED-A.ST set INDEX = string ^OMX import pandas as pd import pandas_datareader as web import matplotlib.pyplot as plt set startdate = string 2010 set enddate = string 2019-06-23 set df0 = call DataFrame set df0 at string Stock = call DataReader ticker string yahoo start...
# -*- coding: utf-8 -*- ticker= "SWED-A.ST" INDEX = "^OMX" import pandas as pd import pandas_datareader as web import matplotlib.pyplot as plt startdate= "2010"; enddate='2019-06-23' df0 = pd.DataFrame() df0['Stock'] = web.DataReader(ticker, 'yahoo', start = startdate, end=enddate)['Adj Close']; df0['Index']...
Python
zaydzuhri_stack_edu_python
function __netInterface self begin set interface = dict string AssociatePublicIpAddress true ; string DeleteOnTermination true ; string Description string Network adaptor via boto3 api ; string DeviceIndex 0 ; string Groups sg_ids ; string SubnetId subnet_id if nodeType == string c5n.18xlarge begin set interface at str...
def __netInterface(self): interface = { 'AssociatePublicIpAddress': True, 'DeleteOnTermination': True, 'Description': 'Network adaptor via boto3 api', 'DeviceIndex': 0, 'Groups': self.sg_ids, 'SubnetId': self.subnet_id } i...
Python
nomic_cornstack_python_v1
function _get_stretch_parameters self data begin set median = median data set avg_dev = call _get_avg_dev data set c0 = call clip median + shadows_clip * avg_dev 0 1 set m = call _mtf target_bkg median - c0 return dict string c0 c0 ; string c1 1 ; string m m end function
def _get_stretch_parameters(self, data): median = np.median(data) avg_dev = self._get_avg_dev(data) c0 = np.clip(median + (self.shadows_clip * avg_dev), 0, 1) m = self._mtf(self.target_bkg, median - c0) return { "c0": c0, "c1": 1, "m": m ...
Python
nomic_cornstack_python_v1
function camera_grid_generator camera vehicle_params begin set tuple start_x start_y = tuple 0.0 0.0 set tuple end_x end_y = tuple R_x R_y set tuple step_x step_y = tuple end_x / vehicle_params at string x_pixel_steps_per_line end_y / vehicle_params at string y_pixel_steps_per_line set start_heading = 0.0 set orientati...
def camera_grid_generator(camera, vehicle_params): start_x, start_y = 0.0, 0.0 end_x, end_y = camera.R_x, camera.R_y step_x, step_y = end_x/vehicle_params["x_pixel_steps_per_line"], end_y/vehicle_params["y_pixel_steps_per_line"] start_heading = 0.0 orientation_step = vehicle_params["orientation_step...
Python
nomic_cornstack_python_v1
set i = 2 set total = 0 while i < 100 begin set is_prime = true for j in range 2 i begin if i % j == 0 begin set is_prime = false break end end if is_prime begin print i set total = total + i end set i = i + 1 end print string Sum of prime numbers: total
i = 2 total = 0 while i < 100: is_prime = True for j in range(2, i): if i % j == 0: is_prime = False break if is_prime: print(i) total += i i += 1 print("Sum of prime numbers:", total)
Python
jtatman_500k
function _charge_ self begin set netPos = sum generator expression aaComp at aa * 10 ^ a2chargePos at aa / 10 ^ aa2chargePos at aa + 10 ^ pH1 for aa in aa2chargePos set netNeg = sum generator expression aaComp at aa * 10 ^ pH1 / 10 ^ aa2chargeNeg at aa + 10 ^ pH1 for aa in aa2chargeNeg comment used for calculations in ...
def _charge_(self): netPos = sum( self.aaComp[aa] * (10 ** self.a2chargePos[aa] / 10 ** self.aa2chargePos[aa] + (10 ** pH1)) for aa in self.aa2chargePos) netNeg = sum( self.aaComp[aa] * ((10 ** pH1) / (10 ** self.aa2chargeNeg[aa] + (10 ** pH1))) for aa in self.aa2char...
Python
nomic_cornstack_python_v1
comment Author:Xu comment 豆瓣top250,保存记录到movInfo.txt comment !/usr/bin/env python3 comment _*_ coding:utf-8 _*_ import requests from bs4 import BeautifulSoup import re import traceback import sys function GetHtmlText url begin comment 尝试两次 for i in range 0 1 begin try begin set r = get requests url set encoding = string...
## Author:Xu ## 豆瓣top250,保存记录到movInfo.txt #!/usr/bin/env python3 # _*_ coding:utf-8 _*_ import requests from bs4 import BeautifulSoup import re import traceback import sys def GetHtmlText(url): for i in range(0,1): #尝试两次 try: r=requests.get(url) r.encoding = 'utf-8' ...
Python
zaydzuhri_stack_edu_python
function get_filename nothing begin return format string {nothing}.txt nothing=nothing end function
def get_filename(nothing): return '{nothing}.txt'.format(nothing=nothing)
Python
nomic_cornstack_python_v1
import copy function rotate key begin set n = length key set res = list comprehension list 0 * n for _ in range n for r in range n begin for c in range n begin set res at c at n - 1 - r = key at r at c end end return res end function function finding key Lock newLen m n begin for startI in range newLen - m + 1 begin fo...
import copy def rotate(key): n = len(key) res = [[0] * n for _ in range(n)] for r in range(n): for c in range(n): res[c][n-1-r] = key[r][c] return res def finding(key, Lock, newLen, m, n): for startI in range(newLen-m + 1): for startJ in range(newLen-m + 1): ...
Python
zaydzuhri_stack_edu_python
function _has_received_data self begin return not _bytes_received == bytes_received_on_connection end function
def _has_received_data(self): return not self._bytes_received == self.bytes_received_on_connection
Python
nomic_cornstack_python_v1
function _lineage_eval_text_match_rules rules text begin for rule in rules begin if call dict_call rule at string test text rule at string expression begin return true end end return false end function
def _lineage_eval_text_match_rules(rules, text): for rule in rules: if TextMatch.dict_call(rule['test'], text, rule['expression']): return True return False
Python
nomic_cornstack_python_v1
function notFainted self begin set messages = call attemptAfterTurn pkmn assert messages == list message msg string Should receive messages from afterTurn function end function
def notFainted(self): messages = self.effect.attemptAfterTurn(self.pkmn) assert messages == [AfterTurnEffect.message], "Should receive messages from afterTurn function"
Python
nomic_cornstack_python_v1
function simulationDelayedTreatment numTrials begin set pop_list = dict set resistant_pop_list = dict set init_step_list = list 300 150 75 0 for tuple index init_step in enumerate init_step_list begin set pop_list at init_step = call get_pop_list init_step numTrials subplot 2 2 index + 1 histogram pop_list at init_st...
def simulationDelayedTreatment(numTrials): pop_list = {} resistant_pop_list = {} init_step_list = [300, 150, 75, 0] for index, init_step in enumerate(init_step_list): pop_list[init_step] = get_pop_list(init_step, numTrials) pylab.subplot(2, 2, index + 1) pylab.hist(pop_list[init_...
Python
nomic_cornstack_python_v1
function createMaskStep self filterRadius1 sdFactor filterRadius2 maskThreshold begin call runCustomMaskScript filterRadius1 sdFactor filterRadius2 maskThreshold workingDir=call _getPath ext=call getExt inputImage=_params at string inputImage + string @1 outputMask=_params at string outputMask end function
def createMaskStep(self, filterRadius1, sdFactor, filterRadius2, maskThreshold): runCustomMaskScript(filterRadius1, sdFactor, filterRadius2, maskThreshold, workingDir=self._getPath(), ext=self.getExt(), inputImage=self._params['...
Python
nomic_cornstack_python_v1
string Proyecto import copy import numpy as np import random import vrep import sys import time import math import matplotlib.pyplot as plt class Individuo begin function __init__ self solucion begin set solucion = solucion end function end class class Problema begin set MIN_VALUE = 0.02 set MAX_VALUE = 1.0 function __...
''' Proyecto ''' import copy import numpy as np import random import vrep import sys import time import math import matplotlib.pyplot as plt class Individuo: def __init__(self, solucion): self.solucion = solucion class Problema: MIN_VALUE = 0.02 MAX_VALUE = 1.0 def __init__(self, clientID): ...
Python
zaydzuhri_stack_edu_python
function format_record self record begin set feature = dict string type string Feature ; string geometry record at 0 ; string properties dict for tuple col value in enumerate record begin if fields at col != string geometry begin set feature at string properties at fields at col = value end end return dumps feature cl...
def format_record(self, record): feature = { 'type': 'Feature', 'geometry': record[0], 'properties': {} } for col, value in enumerate(record): if self.fields[col] != 'geometry': feature['properties'][self.fields[col]] = value ...
Python
nomic_cornstack_python_v1
function get_func_arg_names func begin return co_varnames end function
def get_func_arg_names(func): return get_func_code(func).co_varnames
Python
nomic_cornstack_python_v1
function append_colums_df self df new_df begin set df = concat list df new_df axis=1 join_axes=list index return df end function
def append_colums_df(self, df, new_df): df = pd.concat([df,new_df], axis=1, join_axes=[df.index]) return df
Python
nomic_cornstack_python_v1
function construct_patch image x y patch_size begin set patch_width = patch_size at 0 set patch_height = patch_size at 1 set start_y = y set end_y = y + patch_height set start_x = x set end_x = x + patch_width set patch = image at tuple slice start_x : end_x : slice start_y : end_y : return patch end function
def construct_patch(image, x, y, patch_size): patch_width = patch_size[0] patch_height = patch_size[1] start_y = y end_y = (y + patch_height) start_x = x end_x = (x + patch_width) patch = image[start_x:end_x, start_y:end_y] return patch
Python
nomic_cornstack_python_v1
import socket import threading set HEADER = 64 set PORT = 5050 set FORMAT = string utf-8 set DISCONNECT_MESSAGE = string !DISCONNECT comment change it if server is changed set SERVER = call gethostbyname call gethostname set ADDR = tuple SERVER PORT set client = call socket AF_INET SOCK_STREAM call connect ADDR comment...
import socket import threading HEADER = 64 PORT = 5050 FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT" # change it if server is changed SERVER = socket.gethostbyname(socket.gethostname()) ADDR = (SERVER, PORT) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) #debug mode allows you t...
Python
zaydzuhri_stack_edu_python
async function expect self watch_for respond_with begin if not process begin raise exception string missing process; was this called inside a with statement? end assert stdin is not none msg string process must be opened with stdin=PIPE comment NOTE: This could be improved to show which responses were sent, and which c...
async def expect( self, watch_for: bytes, respond_with: bytes, ) -> None: if not self.process: raise Exception("missing process; was this called inside a with statement?") assert self.process.stdin is not None, "process must be opened with stdin=PIPE" ...
Python
nomic_cornstack_python_v1
comment @lc app=leetcode id=98 lang=python comment [98] Validate Binary Search Tree comment https://leetcode.com/problems/validate-binary-search-tree/description/ comment algorithms comment Medium (26.55%) comment Likes: 2582 comment Dislikes: 374 comment Total Accepted: 505.2K comment Total Submissions: 1.9M comment T...
# # @lc app=leetcode id=98 lang=python # # [98] Validate Binary Search Tree # # https://leetcode.com/problems/validate-binary-search-tree/description/ # # algorithms # Medium (26.55%) # Likes: 2582 # Dislikes: 374 # Total Accepted: 505.2K # Total Submissions: 1.9M # Testcase Example: '[2,1,3]' # # Given a binary...
Python
zaydzuhri_stack_edu_python
from pythoncalculator import * import testcalculator function print_hi name begin print string Hi, { name } end function comment Press the green button in the gutter to run the script. if __name__ == string __main__ begin call print_hi string Pawan call pythoncalculator call testcalculator end
from pythoncalculator import * import testcalculator def print_hi(name): print(f'Hi, {name}') # Press the green button in the gutter to run the script. if __name__ == '__main__': print_hi('Pawan') pythoncalculator() testcalculator()
Python
zaydzuhri_stack_edu_python
function __init__ self func=none begin function corrector self model y0 beta lims dv0 retit=false maxit=100 begin return none end function end function
def __init__(self, func=None): def corrector(self, model, y0, beta, lims, dv0, retit=False, maxit=100): return None
Python
nomic_cornstack_python_v1
function generate_plat self x y begin set plat = platform append plat_obj plat call draw_platform x y end function
def generate_plat(self, x, y): plat = Platform() self.plat_obj.append(plat) plat.draw_platform(x,y)
Python
nomic_cornstack_python_v1
import serial import sys import time set original = list 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
import serial import sys import time original = [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]
Python
zaydzuhri_stack_edu_python
import pytest import torch as T from lstm_ae import LstmAutoEncoder from ae_wrappers.ae_classification_wrapper import AutoEncoderClassifier set device = if expression call is_available then string cuda:0 else string cpu class Test_AE_Classifier begin decorator fixture function ae self seq_dim latent_size num_layers n_c...
import pytest import torch as T from lstm_ae import LstmAutoEncoder from ae_wrappers.ae_classification_wrapper import AutoEncoderClassifier device = 'cuda:0' if T.cuda.is_available() else 'cpu' class Test_AE_Classifier(): @pytest.fixture() def ae(self, seq_dim, latent_size, num_layers, n_classes): a...
Python
zaydzuhri_stack_edu_python
function _fetch_components_from_dn self dn begin set components = call to_dn dn set tuple non_dc dc = tuple list list for item in components begin if starts with lower item string dc begin append dc item end else begin append non_dc item end end return tuple non_dc dc end function
def _fetch_components_from_dn(self, dn): components = ldap3.utils.dn.to_dn(dn) non_dc, dc = [], [] for item in components: if item.lower().startswith("dc"): dc.append(item) else: non_dc.append(item) return non_dc, dc
Python
nomic_cornstack_python_v1
import os import sys import json class DataProcessor begin function __init__ self *args begin set objs = dict if length *args > 0 begin for tuple i val in enumerate *args begin call push_obj val end end end function function push_obj self src_path begin assert exists path src_path msg string Invalid file path given to...
import os import sys import json class DataProcessor: def __init__(self, *args): self.objs = {} if len(*args) > 0: for i, val in enumerate(*args): self.push_obj(val) def push_obj(self, src_path): assert os.path.exists(src_path), "Invalid file path given to D...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution begin function isSameTree self p q begin string :type p: TreeNode :type q: TreeNode :rtype: bool set same = true call postOrder p q ret...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ self...
Python
zaydzuhri_stack_edu_python
import os import sys import time from dataclasses import dataclass , field from typing import Any , ClassVar import random class TimerError extends Exception begin string A custom exception used to report errors in use of Timer class end class decorator dataclass class Timer begin set timers : ClassVar = dictionary set...
import os import sys import time from dataclasses import dataclass, field from typing import Any, ClassVar import random class TimerError(Exception): """A custom exception used to report errors in use of Timer class""" @dataclass class Timer: timers: ClassVar = dict() name: Any = None text: Any = "...
Python
zaydzuhri_stack_edu_python
comment Test pygame script, just a basic shell of a game. comment Import modules that I need import pygame , pygame.mixer , random , os.path comment Define the color black for font usage set black = tuple 0 0 0 comment Initialize pygame call init comment Setup the pyinstaller resource path detection. Hugely simplifies ...
#Test pygame script, just a basic shell of a game. # Import modules that I need import pygame, pygame.mixer, random, os.path #Define the color black for font usage black = (0, 0, 0) #Initialize pygame pygame.init() #Setup the pyinstaller resource path detection. Hugely simplifies the build def resource_path(relat...
Python
zaydzuhri_stack_edu_python
function all_batches self batch_size=128 begin comment Start index for the current batch. set begin = 0 comment Repeat until all batches have been processed. while begin < num_used begin comment End index for the current batch. set end = begin + batch_size comment Ensure the batch does not exceed the used replay-memory...
def all_batches(self, batch_size=128): # Start index for the current batch. begin = 0 # Repeat until all batches have been processed. while begin < self.num_used: # End index for the current batch. end = begin + batch_size # Ensure the batch does no...
Python
nomic_cornstack_python_v1
function word_tokenizing text begin set word_tokens = call word_tokenize string text return word_tokens end function
def word_tokenizing(text): word_tokens = nltk.word_tokenize(str(text)) return word_tokens
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt class Plotter begin function __init__ self metrics=none begin set losses = none set accuracies = none set nfes = none set epochs = none set legend = none if metrics is not none begin call _setMetrics metrics end end function function _setMetrics self metrics begin set ...
import numpy as np import matplotlib.pyplot as plt class Plotter(): def __init__(self, metrics=None): self.losses = None self.accuracies = None self.nfes = None self.epochs = None self.legend = None if metrics is not None: self._setMetrics(metric...
Python
zaydzuhri_stack_edu_python
comment Imprimir todas las potencias de dos hasta llegar al mil, hasta millon comment Ciclo While function run begin comment una constante se define con las palabras en Mayusculas set LIMITE = 1000000 set contador = 0 comment todo numero elevado a la cero es igual a uno set potencia_2 = 2 ^ contador while potencia_2 < ...
## Imprimir todas las potencias de dos hasta llegar al mil, hasta millon ## Ciclo While def run(): LIMITE = 1000000 # una constante se define con las palabras en Mayusculas contador = 0 potencia_2 = 2**contador #todo numero elevado a la cero es igual a uno while potencia_2 < LIMITE: print('2 elevado a ' + str(c...
Python
zaydzuhri_stack_edu_python
function load_data del_file dup_file non_file seq_length=500 channels_first=true normalize_data=false begin set deletions = call read_pickle del_file set duplications = call read_pickle dup_file set non_sv = call read_pickle non_file comment combine data and create labels set data = concatenate tuple values values valu...
def load_data(del_file, dup_file, non_file, seq_length=500, channels_first=True, normalize_data=False): deletions = pd.read_pickle(del_file) duplications = pd.read_pickle(dup_file) non_sv = pd.read_pickle(non_file) # combine data and create labels data = n...
Python
nomic_cornstack_python_v1
function delete_page self **app_names_and_pages begin set page_location = lambda app_name app_page -> join path _main app_name app_page set css_path = join path folder_location string static string css for tuple app pages in items app_names_and_pages begin for page in pages begin remove tree call page_location app page...
def delete_page(self,**app_names_and_pages): page_location = lambda app_name,app_page : os.path.join(self._main,app_name,app_page) css_path = os.path.join(self.folder_location,"static","css") for app,pages in app_names_and_pages.items(): for page in pages: sh...
Python
nomic_cornstack_python_v1
function of_row cls row begin set obj = call cls set security_id = security_id set underlying_symbol = underlying_symbol set root_symbol = root set expiration_date = expiration set strike = strike set option_type = option_type set quote_date = quote_date set underlying_price = underlyer_price set ask = ask set bid = bi...
def of_row(cls, row): obj = cls() obj.security_id = row.security_id obj.underlying_symbol = row.underlying_symbol obj.root_symbol = row.root obj.expiration_date = row.expiration obj.strike = row.strike obj.option_type = row.option_type obj.quote_date = row...
Python
nomic_cornstack_python_v1
function can_move_up up left right begin if is instance up bool begin return false end if is instance up int begin return true end else begin return false end end function
def can_move_up(up, left, right): if isinstance(up, bool): return False if isinstance(up, int): return True else: return False
Python
nomic_cornstack_python_v1
function set_first_frame self box=none frame=none img=none transformed_box_ct=none begin set first_box = box set first_frame = frame set first_img = img set large_img = img if transformed_box_ct is not none begin set first_box_ct_in_world = transformed_box_ct end end function
def set_first_frame(self, box=None, frame=None, img=None, transformed_box_ct=None): self.first_box = box self.first_frame = frame self.first_img = img self.large_img = img if transformed_box_ct is not None: self.first_box_ct_in_world = transformed_box_ct
Python
nomic_cornstack_python_v1
comment encoding: UTF-8 import pandas as pd from globalVars import * comment 载入数据,支持多品种多周期同时载入 function load_data begin comment 读取分钟数据CSV时的时间列格式 set date_parse = lambda dates -> string parse time dates string %Y/%m/%d %H:%M comment 读取日线数据CSV时的时间列格式 set date_parse_day = lambda dates -> string parse time dates string %Y/...
# encoding: UTF-8 import pandas as pd from globalVars import * def load_data(): # 载入数据,支持多品种多周期同时载入 date_parse = lambda dates: pd.datetime.strptime(dates, '%Y/%m/%d %H:%M') # 读取分钟数据CSV时的时间列格式 date_parse_day = lambda dates: pd.datetime.strptime(dates, '%Y/%m/%d') # 读取日线数据CSV时的时间列格式 for inst in instrumen...
Python
zaydzuhri_stack_edu_python
function sieve n begin set results = list range n set results at 1 = 0 for i in results begin if i begin for j in range 2 * i n i begin set results at j = 0 end end end return list comprehension n for n in results if n end function
def sieve(n): results = list(range(n)) results[1] = 0 for i in results: if (i): for j in range(2 * i, n, i): results[j] = 0 return [n for n in results if n]
Python
zaydzuhri_stack_edu_python
function place_beepers_on_row begin comment A check for the smallest world (1x1). if call front_is_blocked begin call put_beeper end else begin comment keep putting beepers on all corners until front_is_blocked(). while call front_is_clear begin call put_beeper move end comment when Karel stops, we know he's reached th...
def place_beepers_on_row(): if front_is_blocked(): # A check for the smallest world (1x1). put_beeper() else: while front_is_clear(): # keep putting beepers on all corners until front_is_blocked(). put_beeper() move() reverse_direction() # when Karel stops, we ...
Python
nomic_cornstack_python_v1
function are_segments_compatible self seg0 seg1 begin if h1 != h0 begin print string Warning: seg0 h1 and seg1 h0 are not the same print h1 print h0 end return call check_tolerance h0 h1 h1 end function
def are_segments_compatible(self, seg0, seg1): if seg0.h1 != seg1.h0: print("Warning: seg0 h1 and seg1 h0 are not the same") print(seg0.h1) print(seg1.h0) return self.check_tolerance(seg0.h0, seg0.h1, seg1.h1)
Python
nomic_cornstack_python_v1
function __init__ self patterns begin set patterns = patterns set edges = list set deBruijnDict = dictionary end function
def __init__(self, patterns): self.patterns = patterns self.edges = [] self.deBruijnDict = dict()
Python
nomic_cornstack_python_v1
function index_rows self begin set _index = dict for tuple i r in enumerate row begin set _index at call _cf call idtag r = i end end function
def index_rows(self): self._index = {} for i,r in enumerate(self._table.row): self._index[self._cf(self.idtag(r))] = i
Python
nomic_cornstack_python_v1
import cv2 import numpy as np import csv set train_start_index = 1 set train_last_index = 42 set test_start_index = train_last_index set test_last_index = 53 set num_in_line = 0 function calculate_num input_x label_y hundred begin if hundred == true begin set input_num = input_x at 0 * 100 + input_x at 1 * 10 + input_x...
import cv2 import numpy as np import csv train_start_index = 1 train_last_index = 42 test_start_index = train_last_index test_last_index = 53 num_in_line = 0 def calculate_num(input_x, label_y, hundred): if hundred == True: input_num = input_x[0] * 100 + input_x[1] * 10 + input_x[2] num_in_line...
Python
zaydzuhri_stack_edu_python
function install self begin set cwd = get current directory change directory depenedncy_dir comment Unzipping the dependency set zipf = zip file zip extract all zipf string . change directory extracted_dir comment Installsstalling the dependency set p = call setup_py set tuple out err = communicate p change directory c...
def install(self): cwd = os.getcwd() os.chdir(self.depenedncy_dir) # Unzipping the dependency zipf = zipfile.ZipFile(self.zip) zipf.extractall('.') os.chdir(self.extracted_dir) # Installsstalling the dependency p = setup_py() out, err = p.commun...
Python
nomic_cornstack_python_v1
function listAttributes self begin if not scope begin call promptScope end execute dbCursor string SELECT * FROM ( SELECT ea.attribute_id, ea.attribute_code, ea.is_required AS required FROM catalog_%s_entity AS ce LEFT JOIN eav_attribute AS ea ON ce.entity_type_id = ea.entity_type_id LEFT JOIN catalog_%s_entity_varchar...
def listAttributes(self): if not self.scope: self.promptScope() self.dbCursor.execute("""SELECT * FROM ( SELECT ea.attribute_id, ea.attribute_code, ea.is_required AS required FROM catalog_%s_entity AS ce LEFT JOIN eav_attribute AS ea ON ce.entity_type_id = ea.entity_type_id ...
Python
nomic_cornstack_python_v1
from numpy import * set cont = zeros 3 dtype=int set vn = array eval input string Insira as medias finais de cada aluno: set vp = array eval input string Insira o numero de horas de cada aluno: set ch = decimal input string Insira a carga horaria da disciplina: set f = ch * 0.75 for i in range size vn and range size vp...
from numpy import* cont= zeros(3, dtype=int) vn= array(eval(input("Insira as medias finais de cada aluno:"))) vp= array(eval(input("Insira o numero de horas de cada aluno:"))) ch= float(input("Insira a carga horaria da disciplina:")) f= ch * 0.75 for i in range(size(vn)) and range(size(vp)): if(vn[i]>=5 and vp[i]>=f...
Python
zaydzuhri_stack_edu_python
function SetClassOfDevice self device_type begin if device_type in CLASS_OF_DEVICE begin return call _SetClassOfDevice get CLASS_OF_DEVICE device_type end else begin set error_msg = string device type is not supported: %s % device_type error error_msg raise call RN42Exception error_msg end end function
def SetClassOfDevice(self, device_type): if device_type in self.CLASS_OF_DEVICE: return self._SetClassOfDevice(self.CLASS_OF_DEVICE.get(device_type)) else: error_msg = 'device type is not supported: %s' % device_type logging.error(error_msg) raise RN42Exception(error_msg)
Python
nomic_cornstack_python_v1
function genericize val begin if is instance val bool begin return list true false end else if is instance val dict begin set result = dict for tuple k v in call iteritems begin set result at k = call genericize v end return result end else begin return list val end end function
def genericize(val): if isinstance(val, bool): return [True, False] elif isinstance(val, dict): result = {} for k, v in val.iteritems(): result[k] = genericize(v) return result else: return [val]
Python
nomic_cornstack_python_v1
function dilate_contours contours w h begin set black = zeros tuple h w uint8 call drawContours black contours - 1 255 - 1 set tuple contours _ = call findContours call dilate black ones tuple 7 7 uint8 RETR_EXTERNAL CHAIN_APPROX_NONE return contours end function
def dilate_contours(contours: List[np.ndarray], w: int, h: int) -> List[np.ndarray]: black = np.zeros((h, w), np.uint8) cv2.drawContours(black, contours, -1, 255, -1) contours, _ = cv2.findContours( cv2.dilate(black, np.ones((7, 7), np.uint8)), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NON...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from stack import * function matches open close begin set opens = string ([{ set closes = string )]} return index opens open == index closes close end function function parChecker2 str_symbol begin set s = stack 20 set ind = 0 set L = length str_symbol set balanced = true while ind < L and...
# -*- coding: utf-8 -*- from stack import * def matches(open, close): opens = "([{" closes = ")]}" return opens.index(open) == closes.index(close) def parChecker2(str_symbol): s = Stack(20) ind = 0 L = len(str_symbol) balanced = True while ind < L and balanced: symbol = str...
Python
zaydzuhri_stack_edu_python
import os import cv2 import pandas as pd import numpy as np from skimage.util.shape import view_as_blocks from skimage.transform import resize function generate_patches_from_img img patch_size=128 begin string This function divides the image into equally sized patches.base Parameters ---------- img: numpy array of imag...
import os import cv2 import pandas as pd import numpy as np from skimage.util.shape import view_as_blocks from skimage.transform import resize def generate_patches_from_img(img, patch_size=128): """This function divides the image into equally sized patches.base Parameters ---------- img: numpy array ...
Python
zaydzuhri_stack_edu_python
class Cat extends object begin string A Cat object. function __init__ self name img_url begin set name = name set img_url = img_url end function function __repr__ self begin string Convenience method to show information about cat in console. return string <Cat: %s> % name end function end class set alex = call Cat stri...
class Cat(object): """A Cat object.""" def __init__(self, name, img_url): self.name = name self.img_url = img_url def __repr__(self): """Convenience method to show information about cat in console.""" return "<Cat: %s>" %self.name alex = Cat("Alex", "static/img/alex.jpg"...
Python
zaydzuhri_stack_edu_python
function __call__ self function begin call _add_attr function return function end function
def __call__(self, function: FuncSpeechArg): self._add_attr(function) return function
Python
nomic_cornstack_python_v1
comment Fileoperation -- Those operation we ca d on a file..(read,write,append) comment read - r comment write - w comment append - a comment open a file.. comment open() -- it is the function to open a file.. comment file=open('sample.txt','r') comment #read() comment #readline() comment #readlines() comment for i in ...
#Fileoperation -- Those operation we ca d on a file..(read,write,append) #read - r #write - w #append - a #open a file.. # open() -- it is the function to open a file.. # file=open('sample.txt','r') # #read() # #readline() # #readlines() # for i in file.read(): # print(i) # file.close() # with open('C:/Use...
Python
zaydzuhri_stack_edu_python
function get_title self entry begin set title = call _ string %(title)s (%(word_count)i words) % dict string title title ; string word_count word_count return title end function
def get_title(self, entry): title = _('%(title)s (%(word_count)i words)') % \ {'title': entry.title, 'word_count': entry.word_count} return title
Python
nomic_cornstack_python_v1
function writeShiftFile stream residues shiftList minShiftQuality=0.0 atomNames=tuple string H string N string C string CA string CB string HA string HA2 string HA3 begin set formatObj = call TalosShiftFormat call addSequence residues call startTable colNames=shiftColumns formats=shiftFormats for tuple ii res in enumer...
def writeShiftFile(stream, residues, shiftList, minShiftQuality=0.0, atomNames = ('H','N','C','CA','CB','HA','HA2','HA3')): formatObj = TalosShiftFormat() formatObj.addSequence(residues) formatObj.startTable(colNames=shiftColumns, formats=shiftFormats) for ii,res in enumerate(residues)...
Python
nomic_cornstack_python_v1
import string set punSet = set punctuation set sett = set literal string . string % string & string " string ! string , string [ string = string : string ; string ` string \ string ? string ( set punSet = punSet - sett print punSet
import string punSet = set(string.punctuation) sett = {'.', '%', '&', '"', '!', ',', '[', '=', ':', ';', '`', '\\', '?', '('} punSet = punSet - sett print(punSet)
Python
zaydzuhri_stack_edu_python
comment Problem statement: https://open.kattis.com/problems/anothercandies for i in range integer input begin input set l = integer input set s = 0 for j in range l begin set s = s + integer input end if not s % l begin print string YES end else begin print string NO end end
# Problem statement: https://open.kattis.com/problems/anothercandies for i in range(int(input())): input() l = int(input()) s = 0 for j in range(l): s += int(input()) if not s%l: print('YES') else: print('NO')
Python
zaydzuhri_stack_edu_python
from common import * from plotting import * comment Divergence of schemes for declining dx set N = 20000 set T = 1.0 comment N_values = np.linspace(5,100,94) set n_values = linear space 10 100 91 comment N_values = np.array([5,6,7,8,9,10,15,20,25,30,40,50,60,70,80,90,100,200,300,400,500,1000,1500,2000]) set FE_error = ...
from common import * from plotting import * # Divergence of schemes for declining dx N = 20000 T = 1.0 # N_values = np.linspace(5,100,94) n_values = np.linspace(10,100,91) # N_values = np.array([5,6,7,8,9,10,15,20,25,30,40,50,60,70,80,90,100,200,300,400,500,1000,1500,2000]) FE_error = np.zeros(len(n_values)) BE_err...
Python
zaydzuhri_stack_edu_python
comment Author: Simon Carlson import argparse import os class Parser begin set parsed_lines = list set address = 0 function __init__ self file begin with open file as f begin for line in f begin set l = parse self line if length l > 0 begin append parsed_lines l end end end end function function parse self line begin ...
# Author: Simon Carlson import argparse import os class Parser(): parsed_lines = [] address = 0 def __init__(self, file): with open(file) as f: for line in f: l = self.parse(line) if len(l) > 0: self.parsed_lines.append(l) def p...
Python
zaydzuhri_stack_edu_python
import random , math from statistics import mean , stdev import pylab as plt function illustrateRegressionToMean numTrials numStdDevsToQualityAsExtreme=2 begin set l = list string H string T set extreme = lambda p_hat n -> if expression p_hat > 0.5 + numStdDevsToQualityAsExtreme * square root 0.25 / n or p_hat < 0.5 - ...
import random, math from statistics import mean, stdev import pylab as plt def illustrateRegressionToMean(numTrials, numStdDevsToQualityAsExtreme = 2): l = ["H", "T"] extreme = lambda p_hat, n:True if (p_hat>0.5+numStdDevsToQualityAsExtreme*math.sqrt(0.25/n) or p_hat<0.5-numStdDevsToQualityAsExtreme*math.sqrt(...
Python
zaydzuhri_stack_edu_python
function _buildAspectSettingsWidget self begin set aspectSettingsGroupBox = call QGroupBox string Planet aspect settings: set formLayoutAbove = call QFormLayout call setLabelAlignment AlignLeft set formLayoutBelow = call QFormLayout call setLabelAlignment AlignLeft comment Aspects enabled on Astrology Chart 1. set aspe...
def _buildAspectSettingsWidget(self): self.aspectSettingsGroupBox = QGroupBox("Planet aspect settings:") formLayoutAbove = QFormLayout() formLayoutAbove.setLabelAlignment(Qt.AlignLeft) formLayoutBelow = QFormLayout() formLayoutBelow.setLabelAlignment(Qt.AlignLeft) ...
Python
nomic_cornstack_python_v1
import json import re function load_products file_name begin string Loads a list of products from a file. Args: file_name: the file to load data from, should be a single json encoded product per line. Returns: A list of dicts corresponding to the file lines. Raises: Exception: An exception if there is an error on readi...
import json import re def load_products(file_name): """Loads a list of products from a file. Args: file_name: the file to load data from, should be a single json encoded product per line. Returns: A list of dicts corresponding to the file lines. Raises: Exception:...
Python
zaydzuhri_stack_edu_python
comment set is a collection of non repeatative elements. string set = {1,2,3,4,5,"vikash","1",1,2} print(set) #it cannot print the repeat value of element print(type(set)) comment empty set string set1 = {} # dictionary set2 = () # tuple set3 = [] # list set4 = set() # empty set print(type(set1)) print(type(set2)) prin...
# set is a collection of non repeatative elements. '''set = {1,2,3,4,5,"vikash","1",1,2} print(set) #it cannot print the repeat value of element print(type(set))''' #empty set '''set1 = {} # dictionary set2 = () # tuple set3 = [] # list set4 = set() # empty set print(type(set1)) print(type(set2)) print(type(set3)) ...
Python
zaydzuhri_stack_edu_python
function r2 self data target begin return 1 - call rss data target / call sst target end function
def r2(self, data, target): return 1 - self.rss(data, target) / self.sst(target)
Python
nomic_cornstack_python_v1
string 给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。 找到所有在 [1, n] 范围之间没有出现在数组中的数字。 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。 示例: 输入: [4,3,2,7,8,2,3,1] 输出: [5,6] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ...
''' 给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。 找到所有在 [1, n] 范围之间没有出现在数组中的数字。 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。 示例: 输入: [4,3,2,7,8,2,3,1] 输出: [5,6] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明...
Python
zaydzuhri_stack_edu_python
import random as rnd comment Dimensão inicial set dim = 2 comment Numero de atributos a serem gerados set nDM = 2 comment Numero de datasets a serem gerados set nDS = 200 comment Numero de instancias por dataset set nEX = 1000 print string Generating 200 exponential datasets with 1000 instances each one: for n in range...
import random as rnd dim = 2 # Dimensão inicial nDM = 2 # Numero de atributos a serem gerados nDS = 200 # Numero de datasets a serem gerados nEX = 1000 # Numero de instancias por dataset print("Generating 200 exponential datasets with 1000 instances each one:") for n in range(nDS): n += 1 with ope...
Python
zaydzuhri_stack_edu_python
async function test_no_hb self begin await call async_setup set HB_CHECK_BUFFER = 1 set _hb_mgr = call HeartbeatManager _address _group 0 await sleep 1.1 assert _heartbeat end function
async def test_no_hb(self): await self.async_setup() pyinsteon.managers.heartbeat_manager.HB_CHECK_BUFFER = 1 self._hb_mgr = pyinsteon.managers.heartbeat_manager.HeartbeatManager( self._address, self._group, 0 ) await asyncio.sleep(1.1) assert self._heartbeat
Python
nomic_cornstack_python_v1
function failure_response self begin return get pulumi self string failure_response end function
def failure_response(self) -> Optional[pulumi.Input['BotResponseSpecificationArgs']]: return pulumi.get(self, "failure_response")
Python
nomic_cornstack_python_v1
class Solution begin function uniqueMorseRepresentations self words begin set codes = list string .- string -... string -.-. string -.. string . string ..-. string --. string .... string .. string .--- string -.- string .-.. string -- string -. string --- string .--. string --.- string .-. string ... string - string .....
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: codes = [ ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.", "...","-","..-","...-",".--","-..-","-.--","--.." ] d = lambda x: codes[ord(x) - ord("a")] ...
Python
zaydzuhri_stack_edu_python
function name self begin return get pulumi self string name end function
def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
import sys , os , numpy , re set rawdata = argv at 1 set outfolder = string resources comment READ THE SPECIFIED COLUMNS FROM THE RAW TEXT FILE comment THEY ARE THE CHROMOSOME, FEATURE, START, AND END set table = call loadtxt rawdata unpack=false dtype=string str usecols=tuple 0 2 3 4 comment GENERATE THE CORRECT PATH ...
import sys, os, numpy, re rawdata=sys.argv[1] outfolder="resources" #READ THE SPECIFIED COLUMNS FROM THE RAW TEXT FILE #THEY ARE THE CHROMOSOME, FEATURE, START, AND END table=numpy.loadtxt(rawdata, unpack=False, dtype='str', usecols = (0,2,3,4)) #GENERATE THE CORRECT PATH tableout=os.path.join(outfolder, "TEMP.gen...
Python
zaydzuhri_stack_edu_python
comment to solve quadratic equation import cmath set a = 1 set b = 5 set c = 6 set x = b ^ 2 - 4 * a * c set sol1 = - b - square root x / 2 * a set sol2 = - b + square root x / 2 * a print format string the solutions are {} and{} sol1 sol2
#to solve quadratic equation import cmath a=1 b=5 c=6 x=(b**2)-(4*a*c) sol1=(-b-cmath.sqrt(x))/(2*a) sol2=(-b+cmath.sqrt(x))/(2*a) print("the solutions are {} and{}".format(sol1,sol2) )
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import numpy as np from tqdm import tqdm import gzip class CollapseAF extends object begin string Collapse stacked allele frequency tables based with non unique genomics positions Parameters ---------- **kwargs : type keyword specific updates Attributes ---------- skip_header : type skips ...
#!/usr/bin/env python3 import numpy as np from tqdm import tqdm import gzip class CollapseAF(object): """ Collapse stacked allele frequency tables based with non unique genomics positions Parameters ---------- **kwargs : type keyword specific updates Attributes ---------- ...
Python
zaydzuhri_stack_edu_python
function check_errors self document_tree filename begin for tuple i report in enumerate document_tree at string lab_reports begin if string error in keys report begin print format string {}: {} string file_path + filename report at string error append errors format string {} ERROR: {} FILENAME: {} string now report at ...
def check_errors(self, document_tree, filename): for i, report in enumerate(document_tree['lab_reports']): if 'error' in report.keys(): print('{}: {}'.format(str(self.file_path)+filename, report['error'])) self.errors.append("{} ERROR: {} FILENAME: {}".format(str(date...
Python
nomic_cornstack_python_v1
comment Gamma it's like a gamma bomb, which pretty complicated for most people, but this is what made the Hunk import logging comment TODO: check for debug flag and update logger call basicConfig level=DEBUG set log = call getLogger string Gamma import tokenize , token import codecs , cStringIO , encodings , re from en...
#Gamma it's like a gamma bomb, which pretty complicated for most people, but this is what made the Hunk import logging #TODO: check for debug flag and update logger logging.basicConfig(level=logging.DEBUG) log = logging.getLogger("Gamma") import tokenize, token import codecs, cStringIO, encodings, re from encodings ...
Python
zaydzuhri_stack_edu_python
from Engine.geometry import Vec2d from Engine.config import get_path from Engine.config import DEBUG import pygame import os from math import ceil function load_sound path volume=1 ext=string ogg begin set fp = call get_path path + string . + ext set s = call Sound fp call set_volume volume return s end function functi...
from Engine.geometry import Vec2d from Engine.config import get_path from Engine.config import DEBUG import pygame import os from math import ceil def load_sound(path, volume=1, ext='ogg'): fp = get_path(path + '.' + ext) s = pygame.mixer.Sound(fp) s.set_volume(volume) return s def load_image(path...
Python
zaydzuhri_stack_edu_python
function _test_apply_in_pandas_returning_empty_dataframe self empty_df begin set df = data function stats key pdf begin if key at 0 % 2 == 0 begin return call stats_with_no_column_names key pdf end return empty_df end function set result = call collect set actual_ids = set comprehension row at 0 for row in result set e...
def _test_apply_in_pandas_returning_empty_dataframe(self, empty_df): df = self.data def stats(key, pdf): if key[0] % 2 == 0: return GroupedApplyInPandasTestsMixin.stats_with_no_column_names(key, pdf) return empty_df result = ( df.groupby("id"...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import recall_score , precision_score , accuracy_score from sklearn.cross_validation import train_test_split from sklearn.metrics import classification_report , confusion_matri...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import recall_score, precision_score, accuracy_score from sklearn.cross_validation import train_test_split from sklearn.metrics import classification_report, confusion_matrix ...
Python
zaydzuhri_stack_edu_python
comment Read IoT database and plot any one variable from config import * import sys import pymysql import json import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates comment Note how the double quotes can be retained all the way upto the SQL statement set SQL1 = string select SlNo, GroupId...
# Read IoT database and plot any one variable from config import * import sys import pymysql import json import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates # Note how the double quotes can be retained all the way upto the SQL statement SQL1 = ('select SlNo, GroupId, Devi...
Python
zaydzuhri_stack_edu_python
function iexecute self job jobs_args progress=false begin return none end function
def iexecute ( self , job , jobs_args , progress = False ) : return None
Python
nomic_cornstack_python_v1
function exit self begin if not closed begin try begin call send_json dict string tag string exit flags=NOBLOCK call recv_json flags=NOBLOCK end except Again begin pass end close __req end end function
def exit(self): if not self.__req.closed: try: self.__req.send_json({'tag': 'exit'}, flags=zmq.NOBLOCK) self.__req.recv_json(flags=zmq.NOBLOCK) except zmq.error.Again: pass self.__req.close()
Python
nomic_cornstack_python_v1
function get_win_prob elos begin comment based on https://stats.stackexchange.com/q/66398 set q = list for elo in elos begin append q 10 ^ elo / 400 end set expected_scores = list for i in range length elos begin append expected_scores q at i / sum q end return expected_scores end function
def get_win_prob(elos): #based on https://stats.stackexchange.com/q/66398 q = [] for elo in elos: q.append(10 ** (elo / 400)) expected_scores = [] for i in range(len(elos)): expected_scores.append(q[i]/sum(q)) return expected_scores
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from skimage.io import imread , imsave set img = call imread string ./catG.png image show img cmap=string Greys_r comment breite und höhe print string x und y shape comment anzahl der pixel print call prod sha...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from skimage.io import imread, imsave img = imread("./catG.png") plt.imshow(img, cmap="Greys_r") print("x und y",img.shape) # breite und höhe print(np.prod(img.shape)) # anzahl der pixel print(np.amin(img)) # minimum pri...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np comment 정규분호 normal_dist from scipy.stats import norm comment 평균 얘가 2가되면 가운데가 2가 된다. 3이되면 가운데가 3 ... set mu = 0 comment 표준편차. 얘가 커질수록 좌우로 넓어진다. set sigma = 1 set num_sample = 100000 set s = call normal mu sigma num_sample comment 평균mu, 표준편차sigma인 정규분포를 따르는 랜덤 변수 num_sa...
import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm #정규분호 normal_dist mu = 0 #평균 얘가 2가되면 가운데가 2가 된다. 3이되면 가운데가 3 ... sigma = 1 #표준편차. 얘가 커질수록 좌우로 넓어진다. num_sample = 100000 s = np.random.normal(mu, sigma, num_sample) #평균mu, 표준편차sigma인 정규분포를 따르는 랜덤 변수 num_sample개를 생성하시오 cnt, bins, ignored =...
Python
zaydzuhri_stack_edu_python
import re set text = string The rain in Spain set x = sub string in string ** text set x = sub string \s+ string text print x
import re text = "The rain in Spain" x = re.sub("in", "**", text) x = re.sub("\s+", " ", text) print(x)
Python
zaydzuhri_stack_edu_python
while true begin set tuple n p = map int split input if n == 0 begin break end set lst = list 0 * n set ind = 0 set rest = p while true begin if rest == 0 begin set rest = lst at ind set lst at ind = 0 end else begin set lst at ind = lst at ind + 1 set rest = rest - 1 if lst at ind == p begin print ind break end end se...
while True: n, p = map(int, input().split()) if n == 0: break lst = [0] * n ind = 0 rest = p while True: if rest == 0: rest = lst[ind] lst[ind] = 0 else: lst[ind] += 1 rest -= 1 if lst[ind] == p: print(ind) break ind = (ind + 1) % n
Python
jtatman_500k
function find_file name open_mode begin comment All useful files have already been hashed. So just check the hash. if get __file_hash name begin return open __file_hash at name open_mode end else comment This elif clause checks if the user passed in the file path instead of just the file name if name in iterate values ...
def find_file(name, open_mode): # All useful files have already been hashed. So just check the hash. if __file_hash.get(name): return open(__file_hash[name], open_mode) # This elif clause checks if the user passed in the file path instead of just the file name elif name in iter(__file_hash....
Python
nomic_cornstack_python_v1