code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function end_turn self begin comment Available money set buying_power = 0 set num_buys = 1 set available_actions = 1 set available_potions = 0 for card in durations begin pop played index played card end set discard = played + discard set discard = hand + discard set played = durations set hand = list call draw 5 end ...
def end_turn(self): self.buying_power = 0 # Available money self.num_buys = 1 self.available_actions = 1 self.available_potions = 0 for card in self.durations: self.played.pop(self.played.index(card)) self.discard = self.played + self.discard self.dis...
Python
nomic_cornstack_python_v1
function cross_correlate_2d x h mode=string same real=true get_reusables=false inplace=true workers=- 1 begin comment check if `h` is reusables if not is instance h tuple begin comment fetch shapes, check inputs set tuple xs hs = tuple shape shape set h_not_smaller = all generator expression hs at i >= xs at i for i in...
def cross_correlate_2d(x, h, mode='same', real=True, get_reusables=False, inplace=True, workers=-1): # check if `h` is reusables if not isinstance(h, tuple): # fetch shapes, check inputs xs, hs = x.shape, h.shape h_not_smaller = all(hs[i] >= xs[i] for i in (0, 1)) ...
Python
nomic_cornstack_python_v1
function get_recognition_alphabet self begin set start_time = time print string get text-line recognition alphabet ... set alphabet = list set fid = open alphabet_path_2 string w set search_folder = join path recognition_txt_folder string *.txt set files = glob glob search_folder for file in call tqdm files begin with...
def get_recognition_alphabet(self): start_time = time.time() print("get text-line recognition alphabet ...") alphabet = [] fid = open(self.alphabet_path_2, 'w') search_folder = os.path.join(self.recognition_txt_folder, '*.txt') files = glob.glob(search_folder) for...
Python
nomic_cornstack_python_v1
function simdir night=string mkdir=false begin set dirname = join path call getenv string DESI_SPECTRO_SIM call getenv string PIXPROD night if mkdir and not exists path dirname begin make directories dirname end return dirname end function
def simdir(night='', mkdir=False): dirname = os.path.join(os.getenv('DESI_SPECTRO_SIM'), os.getenv('PIXPROD'), night) if mkdir and not os.path.exists(dirname): os.makedirs(dirname) return dirname
Python
nomic_cornstack_python_v1
function clear_all self begin comment Iterate through the files and call each one's clear_all method for file in files begin call clear_all end end function
def clear_all(self): # Iterate through the files and call each one's clear_all method for file in self.files: file.clear_all()
Python
nomic_cornstack_python_v1
comment Contando emails enviados por uma pessoa comment em um arquivo txt e printando a pessoa que enviou comment mais msgs set arquivo = open string mbox-short2.txt set linha_vetor = list set nome = list set email = dictionary set maior_nome = none set maior_numero = none for linha in arquivo begin set linha_limpa = s...
# Contando emails enviados por uma pessoa # em um arquivo txt e printando a pessoa que enviou # mais msgs arquivo = open('mbox-short2.txt') linha_vetor = list() nome = list() email = dict() maior_nome = None maior_numero = None for linha in arquivo: linha_limpa = linha.strip() if linha_limpa.startswith('Fro...
Python
zaydzuhri_stack_edu_python
import gi call require_version string Gtk string 3.0 from gi.repository import Gtk from gi.repository import Gdk import re set default_list = list tuple string string string string class SearchTool begin function __init__ self mainWindow statusbar configMgr begin set pathFilter = string set suffixFilter = string ...
import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk from gi.repository import Gdk import re default_list = [ ("", "", "", ""), ] class SearchTool: def __init__(self, mainWindow, statusbar, configMgr ): self.pathFilter = "" self.suffixFilter = "" self.textFilter ...
Python
zaydzuhri_stack_edu_python
comment Used to do get of get and post. import urllib.request import urllib.parse comment x = urllib.request.urlopen('https://www.google.com') # To get the sourcecode of a web page. comment print(x.read()) set varUrl = string http://pythonprogramming.net set varValues = dict string s string basic ; string submit string...
import urllib.request # Used to do get of get and post. import urllib.parse # x = urllib.request.urlopen('https://www.google.com') # To get the sourcecode of a web page. # print(x.read()) varUrl = 'http://pythonprogramming.net' varValues = { 's': 'basic', 'submit': 'search' ...
Python
zaydzuhri_stack_edu_python
import sys import stdio set a = integer argv at 1 set k = 1 while k <= a begin for i in range 1 k + 1 begin write stdio string end for i in range k a + 1 begin write stdio string * end set k = k + 1 call writeln end comment Minh hoa: comment ***** comment **** comment *** comment ** comment *
import sys import stdio a=int(sys.argv[1]) k=1 while k <= a: for i in range(1,k+1): stdio.write(' ') for i in range(k,a+1): stdio.write('*') k=k+1 stdio.writeln() #Minh hoa: # ***** # **** # *** # ** # *
Python
zaydzuhri_stack_edu_python
for i in range N begin if X at i == string 0 begin set ans = ans + string 1 end else begin set ans = ans + X at i end end print ans
for i in range(N): if X[i] == "0": ans = ans + "1" else: ans = ans + X[i] print(ans)
Python
zaydzuhri_stack_edu_python
function _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_status_oper_status input_yang_obj translated_yang_obj=none begin if call _changed begin set status = status end if call _changed begin set last_updated = last_updated end return translated_yang_obj end function
def _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_status_oper_status(input_yang_obj, translated_yang_obj=None): if input_yang_obj.status._changed(): input_yang_obj.status = input_yang_obj.status ...
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import matplotlib.pyplot as plt comment preprocessing from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split , cross_val_score , GridSearchCV import pandas_profiling as pp from sklearn import metrics comment NN models import keras from ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt # preprocessing from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV import pandas_profiling as pp from sklearn import metrics # NN models import keras fro...
Python
zaydzuhri_stack_edu_python
function is_substring s1 s2 begin return s1 in s2 end function set substring = call is_substring string foo string foobar comment Output: True print substring
def is_substring(s1, s2): return s1 in s2 substring = is_substring('foo', 'foobar') print(substring) # Output: True
Python
flytech_python_25k
function before_request self begin if call disable_f begin return none end comment Take time when request started set start_time = time set request_date = call utcnow comment after_request, which is used to get the status code, comment is skipped if an error occures, so we set a default comment error code that is used ...
def before_request( self ) -> None: if self.disable_f(): return None # Take time when request started g.start_time = time.time() g.request_date = datetime.datetime.utcnow() # after_request, which is used to get the status code, # is skipped i...
Python
nomic_cornstack_python_v1
comment Results from our survey on how many cigarettes people smoke per day set survey_responses = list string none string some string a lot string none string a few string none string none set survey_scale = list string none string a few string some string a lot set survey_numbers = list comprehension index survey_sca...
# Results from our survey on how many cigarettes people smoke per day survey_responses = ["none", "some", "a lot", "none", "a few", "none", "none"] survey_scale = ["none", "a few", "some", "a lot"] survey_numbers = [survey_scale.index(response) for response in survey_responses] average_smoking = sum(survey_numbers)...
Python
zaydzuhri_stack_edu_python
function log_final_metrics self model_iter total_iters=none begin if total_iters is none begin set total_iters = MAX_ITER end if MULTI_LABEL begin set info = string if DATASET == string ava begin set info = string Box@%.5f % DETECTION_SCORE_THRESH end print format string * {} testing finished #iters [{}|{}]: mAP: {:.3...
def log_final_metrics(self, model_iter, total_iters=None): if total_iters is None: total_iters = cfg.SOLVER.MAX_ITER if cfg.MODEL.MULTI_LABEL: info = '' if cfg.DATASET == 'ava': info = 'Box@%.5f ' % cfg.AVA.DETECTION_SCORE_THRESH print('*...
Python
nomic_cornstack_python_v1
function auto_setup self begin call auto_setup end function
def auto_setup(self): self.mso.auto_setup()
Python
nomic_cornstack_python_v1
function project self win_width win_height fov viewer_distance begin set factor = fov / viewer_distance + z set x = x * factor + win_width / 2 set y = - y * factor + win_height / 2 return call Point3D x y z end function
def project(self, win_width, win_height, fov, viewer_distance): factor = fov / (viewer_distance + self.z) x = self.x * factor + win_width / 2 y = -self.y * factor + win_height / 2 return Point3D(x, y, self.z)
Python
nomic_cornstack_python_v1
function test_missing_required_attribute self datafiles begin with open datafiles / string test_data_adresse_missing_plz.json encoding=string utf-8 as json_file begin set address_test_data = load json json_file end with raises TypeError as excinfo begin set _ = call Adresse ort=address_test_data at string ort strasse=a...
def test_missing_required_attribute(self, datafiles): with open(datafiles / "test_data_adresse_missing_plz.json", encoding="utf-8") as json_file: address_test_data = json.load(json_file) with pytest.raises(TypeError) as excinfo: _ = Adresse( ort=address_test_dat...
Python
nomic_cornstack_python_v1
function merge_sents idx_i idx_j a c begin set si_text = c at idx_i at a at string text set sj_text = c at idx_j at a at string text if is instance si_text tuple list tuple begin set output_list = list si_text end else begin set output_list = list tuple idx_i si_text end if is instance sj_text tuple list tuple begin se...
def merge_sents(idx_i, idx_j, a, c): si_text = c[idx_i][a]['text'] sj_text = c[idx_j][a]['text'] if isinstance(si_text, (list, tuple)): output_list = list(si_text) else: output_list = [(idx_i, si_text)] if isinstance(sj_text, (list, tuple)): output_list += sj_text else: ...
Python
nomic_cornstack_python_v1
import matplotlib.pylab as py import numpy import random comment py.figure(1) comment py.plot([1,2,3,4],[1,7,3,5]) comment py.show() function stdDev X begin set mean = sum X / decimal length X set tor = 0.0 for x in X begin set tor = tor + x - mean ^ 2 end return tor / length x ^ 0.5 end function function throwNeedles ...
import matplotlib.pylab as py import numpy import random #py.figure(1) #py.plot([1,2,3,4],[1,7,3,5]) #py.show() def stdDev(X): mean=sum(X)/float(len(X)) tor=0.0 for x in X: tor+=(x-mean)**2 return (tor/len(x))**0.5 def throwNeedles(numNeedles): inCircle=0 for needles in xrange(1,num...
Python
zaydzuhri_stack_edu_python
function trim53 self start end begin set tuple seq qual = tuple seq at slice start : end : qual at slice start : end : return self end function
def trim53(self, start, end): self.seq, self.qual = self.seq[start:end], self.qual[start:end] return self
Python
nomic_cornstack_python_v1
function __repr__ self begin return data end function
def __repr__(self): return self.data
Python
nomic_cornstack_python_v1
function dfs graph curr prev bridges visited lows ids prev_id begin set visited at curr = true set prev_id = prev_id + 1 set lows at curr = prev_id set ids at curr = prev_id for target in graph at curr begin if target == prev begin continue end if not visited at target begin call dfs graph target curr bridges visited l...
def dfs(graph: [[int]], curr: int, prev: int, bridges: [int], visited: [int], lows: [int], ids: [int], prev_id: int): visited[curr] = True prev_id += 1 lows[curr] = prev_id ids[curr] = prev_id for target in graph[curr]: if target == prev: continue if not visited[target]:...
Python
zaydzuhri_stack_edu_python
from django.db import models comment Create your models here. class User extends Model begin comment 写属性 comment 主键 id django 的orm会自动创建主键 comment id=models.AutoField(primary_key=True) set user_name = call CharField max_length=32 verbose_name=string 用户的名 set age = call IntegerField verbose_name=string 用户的年龄 set phone = ...
from django.db import models # Create your models here. class User(models.Model): ##写属性 ##主键 id django 的orm会自动创建主键 # id=models.AutoField(primary_key=True) user_name=models.CharField(max_length=32,verbose_name='用户的名') age=models.IntegerField(verbose_name='用户的年龄') phone=models.CharField(max_l...
Python
zaydzuhri_stack_edu_python
from Player import Player import random class Computer extends Player begin function __init__ self side depth begin set side = side set depth = depth end function comment returns Card, [piece,x,y], [x,y] function getMove self board myCards oppCards middleCard begin function islegal start end begin if all map lambda x -...
from Player import Player import random class Computer(Player): def __init__(self,side,depth): self.side = side self.depth = depth def getMove(self,board,myCards,oppCards,middleCard): #returns Card, [piece,x,y], [x,y] def islegal(start, end): if all(map(lambda x...
Python
zaydzuhri_stack_edu_python
function add_tso_sources seed_image seed_segmentation_map psf_seeds segmentation_maps lightcurves frametime total_frames exposure_total_frames frames_per_integration number_of_ints resets_bet_ints starting_time=0 starting_frame=0 samples_per_frametime=5 begin set logger = call getLogger string mirage.seed_image.tso.add...
def add_tso_sources(seed_image, seed_segmentation_map, psf_seeds, segmentation_maps, lightcurves, frametime, total_frames, exposure_total_frames, frames_per_integration, number_of_ints, resets_bet_ints, starting_time=0, starting_frame=0, samples_per_frametime=5): logger = log...
Python
nomic_cornstack_python_v1
function binary_to_hex binary begin set hex = string set binary = call zfill length binary // 4 + 1 * 4 for i in range 0 length binary 4 begin set chunk = binary at slice i : i + 4 : set decimal = sum generator expression integer digit * 2 ^ 3 - j for tuple j digit in enumerate chunk if decimal < 10 begin set hex = h...
def binary_to_hex(binary): hex = "" binary = binary.zfill((len(binary) // 4 + 1) * 4) for i in range(0, len(binary), 4): chunk = binary[i:i+4] decimal = sum(int(digit) * 2 ** (3 - j) for j, digit in enumerate(chunk)) if decimal < 10: hex += str(decimal) ...
Python
jtatman_500k
function add_mx self name records ttl=none identifier=none comment=string begin set ttl = ttl or default_ttl set records = call _make_qualified records return call add_record resource_type=string MX name=name value=records ttl=ttl identifier=identifier comment=comment end function
def add_mx(self, name, records, ttl=None, identifier=None, comment=""): ttl = ttl or default_ttl records = self.route53connection._make_qualified(records) return self.add_record(resource_type='MX', name=name, value=records, ...
Python
nomic_cornstack_python_v1
function test_dict_keys_time_err self begin set val = time 12 15 59 111 tzinfo=call timezone string Asia/Shanghai with raises JSONEncodeError begin dumps dict val true option=OPT_NON_STR_KEYS end end function
def test_dict_keys_time_err(self): val = datetime.time(12, 15, 59, 111, tzinfo=pytz.timezone("Asia/Shanghai")) with pytest.raises(orjson.JSONEncodeError): orjson.dumps({val: True}, option=orjson.OPT_NON_STR_KEYS)
Python
nomic_cornstack_python_v1
function _buildAuthorityConstraints request s_type=string public owner=none ownergroup=none begin if s_type == string public or call getUser request is none begin set c = dict string publicSearchVisible true end else begin assert owner or ownergroup msg string Owner information missing set c = if expression ownergroup ...
def _buildAuthorityConstraints(request, s_type="public", owner=None, ownergroup=None): if s_type == "public" or impl.userauth.getUser(request) is None: c = {'publicSearchVisible': True} else: assert owner or ownergroup, "Owner information missing" c = {'owner': owner} if (ownergroup is N...
Python
nomic_cornstack_python_v1
function __get_type_method3 self begin try begin import subprocess set file_process = popen list string file string -b file_path stdout=PIPE return strip read stdout end except any begin return string end end function
def __get_type_method3(self): try: import subprocess file_process = subprocess.Popen( ['file', '-b', self.file_path], stdout=subprocess.PIPE) return file_process.stdout.read().strip() except: return ''
Python
nomic_cornstack_python_v1
function add_notes self notes begin set _need_increment = true if not condense begin call _terminate_notes end for tuple channel notes in enumerate notes begin set new_notes = set set stale_notes = list for note in notes begin set note_state = note_state at channel at pitch add new_notes pitch if not condense or conde...
def add_notes(self, notes): self._need_increment = True if not self.condense: self._terminate_notes() for channel, notes in enumerate(notes): new_notes = set() stale_notes = [] for note in notes: note_state = self.note_state[channe...
Python
nomic_cornstack_python_v1
comment @lc app=leetcode.cn id=1036 lang=python3 comment [1036] 逃离大迷宫 comment https://leetcode-cn.com/problems/escape-a-large-maze/description/ comment algorithms comment Hard (26.39%) comment Likes: 17 comment Dislikes: 0 comment Total Accepted: 1.2K comment Total Submissions: 4.3K comment Testcase Example: '[[0,1],[1...
# # @lc app=leetcode.cn id=1036 lang=python3 # # [1036] 逃离大迷宫 # # https://leetcode-cn.com/problems/escape-a-large-maze/description/ # # algorithms # Hard (26.39%) # Likes: 17 # Dislikes: 0 # Total Accepted: 1.2K # Total Submissions: 4.3K # Testcase Example: '[[0,1],[1,0]]\n[0,0]\n[0,2]' # # 在一个 10^6 x 10^6 的网格中,...
Python
zaydzuhri_stack_edu_python
import pandas as pd from verzoekveld_functies import * function test_opschonen_oplossingen begin set oplossingen_input = call read_excel string ./data/test/Standaardoplossingen_test_1.xlsx set oplossingen_check = call read_excel string ./data/test/Standaardoplossingen_test_1_check.xlsx set oplossingen_input = call opsc...
import pandas as pd from verzoekveld_functies import * def test_opschonen_oplossingen(): oplossingen_input = pd.read_excel("./data/test/Standaardoplossingen_test_1.xlsx") oplossingen_check = pd.read_excel("./data/test/Standaardoplossingen_test_1_check.xlsx") oplossingen_input = opschonen_oplossingen(oplos...
Python
zaydzuhri_stack_edu_python
from lxml.html import parse from pprint import pprint import pickle import json import os string Fetch today's soup from Apostrophe's website Run: daily set outfile = string /tmp/apostrophe.pkl set soupurl = string http://www.apostropheuk.com/php/showtodays.php?location= function fix_text astr begin string Remove undes...
from lxml.html import parse from pprint import pprint import pickle import json import os """ Fetch today's soup from Apostrophe's website Run: daily """ outfile = '/tmp/apostrophe.pkl' soupurl = 'http://www.apostropheuk.com/php/showtodays.php?location=' def fix_text(astr): """Remove undesirable characters and s...
Python
zaydzuhri_stack_edu_python
function checkargs number message begin if length argv != number + 1 begin print message exit 1 end end function
def checkargs(number, message): if len(sys.argv) != number+1: print(message) sys.exit(1)
Python
nomic_cornstack_python_v1
set time_sec = integer input string Введите время в секундах: set time_h = time_sec // 3600 set time_m = time_sec % 3600 // 60 set time_s = time_sec % 3600 % 60 print string %02i:%02i:%02i % tuple time_h time_m time_s
time_sec = int(input("Введите время в секундах: ")) time_h = time_sec//3600 time_m = time_sec%3600//60 time_s = time_sec%3600%60 print("%02i:%02i:%02i" % (time_h, time_m, time_s))
Python
zaydzuhri_stack_edu_python
function SaveOrUpdate self vals begin set listedParts = list set retValues = list for partVals in vals begin set hasSaved = false if get partVals string engineering_code string in listedParts begin continue end if string engineering_code not in partVals begin set partVals at string componentID = false set partVals at...
def SaveOrUpdate(self, vals): listedParts = [] retValues = [] for partVals in vals: hasSaved = False if partVals.get('engineering_code', '') in listedParts: continue if 'engineering_code' not in partVals: partVals['compo...
Python
nomic_cornstack_python_v1
function pointsToAward type begin set res = 0 if type == string up begin set res = 10 end else if type == string va begin set res = 10 end else if type == string di begin set res = 15 end else if type == string re begin set res = 20 end return res end function
def pointsToAward(type): res = 0 if(type == "up"): res = 10 elif(type == "va"): res = 10 elif(type == "di"): res = 15 elif(type == "re"): res = 20 return res
Python
zaydzuhri_stack_edu_python
comment Consider a list of newly registered but unverified users of a website. After comment we verify these users, how can we move them to a separate list of confirmed comment users? One way would be to use a while loop to pull users from the list of comment unconfirmed users as we verify them and then add them to a s...
# Consider a list of newly registered but unverified users of a website. After # we verify these users, how can we move them to a separate list of confirmed # users? One way would be to use a while loop to pull users from the list of # unconfirmed users as we verify them and then add them to a separate list of # confir...
Python
zaydzuhri_stack_edu_python
from abc import ABCMeta , abstractmethod class Validation extends object begin function add_data self instance data begin set instance = instance set data = data end function function valid_data self begin if call not_empty begin return is instance data instance end end function function not_empty self begin if data is...
from abc import ABCMeta, abstractmethod class Validation(object): def add_data(self, instance, data): self.instance = instance self.data = data def valid_data(self): if self.not_empty(): return isinstance(self.data, self.instance) def not_empty(self): if self.d...
Python
zaydzuhri_stack_edu_python
import subprocess import sys function check_code_git_status begin set result = call getstatusoutput string git status if result at 0 != 0 begin print string git status Failed! pls check your git exit 0 end else if string Changes not staged for commit: in result at 1 begin set answer = input string 编译正式软件发现本地代码有差异,是否要过滤...
import subprocess import sys def check_code_git_status(): result = subprocess.getstatusoutput('git status') if result[0] != 0: print('git status Failed! pls check your git') sys.exit(0) elif 'Changes not staged for commit:' in result[1]: answer = input('编译正式软件发现本地代码有差异,是否要过...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC comment initialise the driver set driver = call Chrome comment go to the given URL get driver string https://www.example.com comment wait for the page to load set wait ...
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # initialise the driver driver = webdriver.Chrome() # go to the given URL driver.get("https://www.example.com") # wait for the page to load wait = WebDriverWait(driv...
Python
jtatman_500k
function connectToServer host id mode buff_size custom_recv_port begin set MAIN_SERVER = host set host = split host string : set RECV_ID = id try begin set s = call socket AF_INET SOCK_STREAM call connect tuple host at 0 integer host at 1 if mode == string SEND begin call send encode string S + string id end else if mo...
def connectToServer(host, id, mode, buff_size, custom_recv_port): MAIN_SERVER = host host = host.split(":") RECV_ID = id try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host[0], int(host[1]))) if mode == "SEND": s.send(("S " + str(id)).encode()) ...
Python
nomic_cornstack_python_v1
class SportProfile extends object begin function __init__ self name age height team position begin set name = name set age = age set height = height set team = team set position = position end function function display self name age height team position begin return name end function end class
class SportProfile(object): def __init__(self, name, age, height, team, position): self.name=name self.age=age self.height=height self.team=team self.position=position def display(self, name, age, height, team, position): return self.name
Python
zaydzuhri_stack_edu_python
function main begin comment Gather command-line arguments. call ParseArgs argv at slice 1 : : comment This is needed on Windows bots syncing internal code. if name == string nt begin set environ at string HOME = join path string c:\ string Users string chrome-bot end comment Sync the buildbot code. check call list GCL...
def main(): # Gather command-line arguments. ParseArgs(sys.argv[1:]) # This is needed on Windows bots syncing internal code. if os.name == 'nt': os.environ['HOME'] = os.path.join('c:\\', 'Users', 'chrome-bot') # Sync the buildbot code. subprocess.check_call([GCLIENT, 'sync', '--force', '-j1']) # Ob...
Python
nomic_cornstack_python_v1
string Team Compo: TOP MID JNG AD SUP FLEX FLEX TEAM import csv import copy import strategy class Team begin set players = none function __init__ self val begin set reader = dict reader val set players = list comprehension row for row in reader end function function removeOut self begin set name = string set remlist =...
""" Team Compo: TOP MID JNG AD SUP FLEX FLEX TEAM """ import csv import copy import strategy class Team: players = None def __init__(self, val): reader = csv.DictReader(val) self.players = [row for row in reader] def removeOut(self): name = '' remlist = [] ...
Python
zaydzuhri_stack_edu_python
import numpy as np function calculk k1 k2 k3 begin set coeff = list k1 * k2 * k3 k1 * k2 + k2 * k3 + k1 * k3 k1 + k2 + k3 - 1 set solution = call roots coeff set liste = list solution at 0 solution at 1 if k1 + k2 + k3 > 1 begin set k = decimal round liste at 0 1 return k end else begin set k = decimal round liste at 1...
import numpy as np def calculk(k1,k2,k3): coeff=[k1*k2*k3,k1*k2+k2*k3+k1*k3,k1+k2+k3-1] solution = np.roots(coeff) liste=[solution[0],solution[1]] if k1+k2+k3>1: k=float(round(liste[0],1)) return (k) else: k=float(round(liste[1],1)) return (k)...
Python
zaydzuhri_stack_edu_python
function cmap_xmap function cmap begin set cdict = _segmentdata set function_to_map = lambda x -> tuple call function x at 0 x at 1 x at 2 for key in tuple string red string green string blue begin set cdict at key = map function_to_map cdict at key sort cdict at key assert cdict at key at 0 < 0 or cdict at key at - 1 ...
def cmap_xmap(function,cmap): cdict = cmap._segmentdata function_to_map = lambda x : (function(x[0]), x[1], x[2]) for key in ('red','green','blue'): cdict[key] = map(function_to_map, cdict[key]) cdict[key].sort() assert (cdict[key][0]<0 or cdict[key][-1]>1),\ "Resulting i...
Python
nomic_cornstack_python_v1
function normalize_binlog_name binlog_name begin if binlog_name == string begin return string end set binlog = split binlog_name string _._ at - 1 if string .part.gz == binlog at slice - 8 : : begin return binlog at slice : - 8 : end else if string .gz == binlog at slice - 3 : : begin return binlog at slice : ...
def normalize_binlog_name(binlog_name): if binlog_name == '': return '' binlog = binlog_name.split('_._')[-1] if '.part.gz' == binlog[-8:]: return binlog[:-8] elif '.gz' == binlog[-3:]: return binlog[:-3] return binlog
Python
nomic_cornstack_python_v1
function getAllRoutes begin comment connect to database set tuple conn cursor = call getConnectionAndCursor comment build SQL set sql = string SELECT idNum, name, country,rating FROM climbingroutes comment execute the query execute cursor sql comment get the data from the database: set data = call fetchall comment clea...
def getAllRoutes(): # connect to database conn, cursor = getConnectionAndCursor() # build SQL sql = """ SELECT idNum, name, country,rating FROM climbingroutes """ # execute the query cursor.execute(sql) # get the data from the database: data = cursor.fetchall() # cle...
Python
nomic_cornstack_python_v1
function PC_traj df rep begin comment scale the PCs set xscale = 1 / max PC_means at rep at string PC_1 - min PC_means at rep at string PC_1 set yscale = 1 / max PC_means at rep at string PC_2 - min PC_means at rep at string PC_2 comment okay so now have a summary of each drug for each PC. comment scale and plot the dr...
def PC_traj(df,rep): #scale the PCs xscale = 1/(np.max(PC_means[rep]['PC_1']) - np.min(PC_means[rep]['PC_1'])) yscale = 1/(np.max(PC_means[rep]['PC_2']) - np.min(PC_means[rep]['PC_2'])) #okay so now have a summary of each drug for each PC. #scale and plot the drugs across the PC1 and 2 space ...
Python
nomic_cornstack_python_v1
function tokenize self text as_id=false begin set processed_text = strip text if decompose begin set processed_text = call decompose text end if as_id begin set tokens = call encode_as_ids processed_text end else begin set tokens = call encode_as_pieces processed_text end if decompose and not as_id begin set tokens = l...
def tokenize(self, text, as_id=False): processed_text = text.strip() if self.decompose: processed_text = self.composer.decompose(text) if as_id: tokens = self.spp.encode_as_ids(processed_text) else: tokens = self.spp.encode_as_pieces(processed_text) if self.decompose and not as_...
Python
nomic_cornstack_python_v1
async function transactions self begin async_with acquire engine as conn begin return await call get_transactions conn end end function
async def transactions(self): async with self.engine.acquire() as conn: return await get_transactions(conn)
Python
nomic_cornstack_python_v1
function request_redraw self begin call invalidate_draw call request_redraw return end function
def request_redraw(self): self.component.invalidate_draw() self.component.request_redraw() return
Python
nomic_cornstack_python_v1
class EntityIdGen begin set __global_entity_id : int = 0 decorator staticmethod function gen begin set __global_entity_id = __global_entity_id + 1 return __global_entity_id end function end class class Entity begin function __init__ self begin set __id = call gen end function decorator property function id self begin r...
class EntityIdGen: __global_entity_id: int = 0 @staticmethod def gen(): EntityIdGen.__global_entity_id += 1 return EntityIdGen.__global_entity_id class Entity: def __init__(self): self.__id = EntityIdGen.gen() @property def id(self): return self.__id def ...
Python
zaydzuhri_stack_edu_python
class Solution begin comment def checkValidString(self, s): comment """ comment :type s: str comment :rtype: bool comment """ comment cnt, star_cnt = (0, 0) comment for ch in s: comment if cnt + star_cnt < 0: comment return False comment elif ch == '*': comment star_cnt += 1 comment elif ch == '(': comment cnt += 1 com...
class Solution: # def checkValidString(self, s): # """ # :type s: str # :rtype: bool # """ # cnt, star_cnt = (0, 0) # # for ch in s: # if cnt + star_cnt < 0: # return False # elif ch == '*': # star_cnt += 1 ...
Python
zaydzuhri_stack_edu_python
function work self i begin set tuple n1 n2 = p at i comment initialize the total arrays for this process set sum1 = zeros like sum1g set sum2 = 1.0 if not pts_only begin set sum2 = zeros like sum2g end if compute_mean_coords begin set N = zeros like N set centers_sum = list comprehension zeros like c for c in centers e...
def work(self, i): n1, n2 = self.p[i] # initialize the total arrays for this process sum1 = numpy.zeros_like(self.sum1g) sum2 = 1. if not self.pts_only: sum2 = numpy.zeros_like(self.sum2g) if self.compute_mean_coords: N = numpy.zeros_like(self.N) ...
Python
nomic_cornstack_python_v1
function number_check num begin set base_str = string The number { num } is if num > 0 begin return base_str + string Positive end else if num < 0 begin return base_str + string Negative end else begin return base_str + string Zero end end function
def number_check(num): base_str = f"The number {num} is " if num > 0: return base_str+"Positive" elif num < 0: return base_str+"Negative" else: return base_str+"Zero"
Python
nomic_cornstack_python_v1
function test_remove_avax_blockchain_account rotkehlchen_api_server begin set rotki = rotkehlchen set async_query = random choice list false true get requests call api_url_for rotkehlchen_api_server string blockchainbalancesresource comment to populate balances set response = delete call api_url_for rotkehlchen_api_ser...
def test_remove_avax_blockchain_account(rotkehlchen_api_server: 'APIServer') -> None: rotki = rotkehlchen_api_server.rest_api.rotkehlchen async_query = random.choice([False, True]) requests.get(api_url_for( rotkehlchen_api_server, 'blockchainbalancesresource', )) # to populate balances...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from __future__ import unicode_literals import functools set __all__ = list string memoized_reset comment def memoize_simple(obj): comment # TODO: make sure it's not iterator comment cache = obj.cache = {} comment def memoizer(f, *args, **kwargs): comment key = (args, frozendict2(kwargs)) ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import functools __all__ = [ 'memoized_reset', ] # def memoize_simple(obj): # # TODO: make sure it's not iterator # cache = obj.cache = {} # # def memoizer(f, *args, **kwargs): # key = (args, frozendict2(kwargs)) # if key n...
Python
zaydzuhri_stack_edu_python
function list_bot begin while true begin set results = string for tuple i conn in enumerate all_connections_bot begin try begin set m = dumps list string call send m end except any begin print string The bot : %s disconnected % tuple all_bot at i at 0 del all_connections_bot at i del all_bot at i continue end set resu...
def list_bot(): while True: results = '' for i, conn in enumerate(all_connections_bot): try: m = pickle.dumps([' ']) conn.send(m) except: print("The bot : %s disconnected" % (all_bot[i][0],)) del all_c...
Python
nomic_cornstack_python_v1
function data_handler self data_handler begin set _data_handler = data_handler end function
def data_handler(self, data_handler): self._data_handler = data_handler
Python
nomic_cornstack_python_v1
function update_permission_set_with_http_info self permission_set_id body **kwargs begin set all_params = list string permission_set_id string body append all_params string callback append all_params string _return_http_data_only append all_params string _preload_content append all_params string _request_timeout set pa...
def update_permission_set_with_http_info(self, permission_set_id, body, **kwargs): all_params = ['permission_set_id', 'body'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') ...
Python
nomic_cornstack_python_v1
import taichi as ti decorator data_oriented class CGSolver begin comment 输入的参数依次为,矩阵大小m n function __init__ self m n u v cell_type begin set m = m set n = n set u = u set v = v set cell_type = cell_type comment 右侧的线性系统: set b = call field dtype=f32 shape=tuple m n comment 左侧的线性系统 set Adiag = call field dtype=f32 shape=...
import taichi as ti @ti.data_oriented class CGSolver: #输入的参数依次为,矩阵大小m n def __init__(self, m, n, u, v, cell_type): self.m = m self.n = n self.u = u self.v = v self.cell_type = cell_type # 右侧的线性系统: self.b = ti.field(dtype=ti.f32, shape=(self.m, self.n)) ...
Python
zaydzuhri_stack_edu_python
for _ in range n begin add names_set input end for name in names_set begin print name end
for _ in range(n): names_set.add(input()) for name in names_set: print(name)
Python
zaydzuhri_stack_edu_python
import collections import sys import os class Word extends object begin function __init__ self word begin set word = word set suggestions = list end function function check self begin string will return a boolean in regards to it be spelled correctly end function function suggest self begin string will return a list o...
import collections import sys import os class Word(object): def __init__(self, word): self.word = word self.suggestions = [] def check(self): """will return a boolean in regards to it be spelled correctly""" def suggest(self): """will return a list of strings for po...
Python
zaydzuhri_stack_edu_python
function extract_head data begin set tl = data at string tls at data at string i set br = data at string brs at data at string i set head = call extract_area data tuple tl br return head end function
def extract_head(data): tl = data['tls'][data['i']]; br = data['brs'][data['i']]; head = extract_area(data,(tl,br)); return head;
Python
nomic_cornstack_python_v1
function generate base begin if base == string begin yield base end else begin for character in call dictionary base at 0 begin for rest in call generate base at slice 1 : : begin yield character + rest end end end end function
def generate(base): if base == '': yield base else: for character in JugglerPassGen.dictionary(base[0]): for rest in JugglerPassGen.generate(base[1:]): yield character + rest
Python
nomic_cornstack_python_v1
from datetime import datetime import RPi.GPIO as GPIO import time comment moving the pill pack set stillMoving = true comment comes from user's input data set readyToTakePill = false set powerArduinoPin = 3 set readArduinoPin = 5 call setwarnings true comment Use physical pin numbering call setmode BOARD setup GPIO pow...
# from datetime import datetime import RPi.GPIO as GPIO import time stillMoving = True # moving the pill pack readyToTakePill = False # comes from user's input data powerArduinoPin = 3 readArduinoPin = 5 GPIO.setwarnings(True) GPIO.setmode(GPIO.BOARD) # Use physical pin numbering GPIO.setup(powerArduinoPin, GPIO.OUT...
Python
zaydzuhri_stack_edu_python
function get_stamp_dir tilename begin return join path call get_base_dir string stamps tilename end function
def get_stamp_dir(tilename): return os.path.join( get_base_dir(), 'stamps', tilename, )
Python
nomic_cornstack_python_v1
import requests import os import csv import datetime import pytz class enphaseAPIReading begin string Class to wrap the enphase api function __init__ self user_id key begin string Initialise system_id from api key and user_id. if user_id == string or key == string begin return end set user_id = user_id set key = key ...
import requests import os import csv import datetime import pytz class enphaseAPIReading: ''' Class to wrap the enphase api ''' def __init__(self, user_id, key): ''' Initialise system_id from api key and user_id. ''' if user_id == '' or key == '': return ...
Python
zaydzuhri_stack_edu_python
function concatenate_strings string1 string2 begin set string1 = strip string1 set string2 = strip string2 if string1 == string or string2 == string begin return string Error: Input strings cannot be empty end set concatenated_string = string1 + string2 if any generator expression is digit char for char in concatenat...
def concatenate_strings(string1, string2): string1 = string1.strip() string2 = string2.strip() if string1 == "" or string2 == "": return "Error: Input strings cannot be empty" concatenated_string = string1 + string2 if any(char.isdigit() for char in concatenated_string): return "E...
Python
jtatman_500k
if c in list range min a b max a b begin print string Yes end else begin print string No end
if c in list(range(min(a,b),max(a,b))): print('Yes') else: print('No')
Python
zaydzuhri_stack_edu_python
function lsb_release_codename begin if has attribute lsb_release_codename string _cache begin return _cache end try begin set p = popen list string lsb_release string -c stdout=PIPE end except OSError begin set _cache = none return _cache end set tuple stdout stderr = communicate p if 0 != returncode begin set _cache =...
def lsb_release_codename(): if hasattr(lsb_release_codename, '_cache'): return lsb_release_codename._cache try: p = subprocess.Popen(['lsb_release', '-c'], stdout=subprocess.PIPE) except OSError: lsb_release_codename._cache = None return lsb_release_codename._cache stdout...
Python
nomic_cornstack_python_v1
import pygame import random class Eagle extends Sprite begin function __init__ self eagle_event begin call __init__ comment def l'image associée set image = load image string assets/eagle.png set image = call scale image tuple 150 100 set rect = call get_rect set velocity = random integer 3 8 set x = random integer 20 ...
import pygame import random class Eagle(pygame.sprite.Sprite): def __init__(self, eagle_event): super().__init__() # def l'image associée self.image = pygame.image.load('assets/eagle.png') self.image = pygame.transform.scale(self.image, (150, 100)) self.rect = self.image.g...
Python
zaydzuhri_stack_edu_python
function clean_name self name replace_space_with=none begin comment ref: https://en.wikipedia.org/wiki/Filename comment ref: https://stackoverflow.com/questions/4814040/allowed-characters-in-filename comment No control chars, no: /, \, ?, %, *, :, |, ", <, > comment remove control chars set name = join string generato...
def clean_name(self, name, replace_space_with=None): # ref: https://en.wikipedia.org/wiki/Filename # ref: https://stackoverflow.com/questions/4814040/allowed-characters-in-filename # No control chars, no: /, \, ?, %, *, :, |, ", <, > # remove control chars name = ''.join(ch for...
Python
nomic_cornstack_python_v1
function crop_image img padding=5 begin string Crops an image or slice to its extents if padding < 1 begin return img end set tuple beg_coords end_coords = call crop_coords img padding if length shape == 3 begin set img = call crop_3dimage img beg_coords end_coords end else if length shape == 2 begin set img = call cro...
def crop_image(img, padding=5): "Crops an image or slice to its extents" if padding < 1: return img beg_coords, end_coords = crop_coords(img, padding) if len(img.shape) == 3: img = crop_3dimage(img, beg_coords, end_coords) elif len(img.shape) == 2: img = crop_2dimage(img, ...
Python
jtatman_500k
function read_ontology self node_id begin string Each node_obj has 6 keys: {'alt_id', 'def', 'is_a', 'name', 'relationship', 'subset'} Key mapping: node_obj['alt_id'] -> ontology_dict['secondary_chebi_id'] node_obj['def'] -> ontology_dict['definition'] node_obj['is_a'] -> will be replaced by successors/predecessors/des...
def read_ontology(self, node_id): """ Each node_obj has 6 keys: {'alt_id', 'def', 'is_a', 'name', 'relationship', 'subset'} Key mapping: node_obj['alt_id'] -> ontology_dict['secondary_chebi_id'] node_obj['def'] -> ontology_dict['definition'] ...
Python
nomic_cornstack_python_v1
class remoteControl begin function __init__ self begin set channels = list string HBO string CNN string Star Sports set index = - 1 end function function _iter_ self begin return self end function function _next_ self begin set index = index + 1 if index == length channels begin raise StopIteration end return channels ...
class remoteControl(): def __init__(self): self.channels = ["HBO","CNN","Star Sports"] self.index = -1 def _iter_(self): return self def _next_(self): self.index += 1 if self.index == len(self.channels): raise StopIteration r...
Python
zaydzuhri_stack_edu_python
from tkinter import Tk , Frame , Button , Canvas , Label , StringVar , LEFT , ALL from random import randint , randrange from math import inf from node import Node from obstacle import Obstacle from ellipse import Ellipse set CANVAS_SIZE = list 640 480 set MAX_LOOP = 500000 set ARRIVAL_RADIUS = 20 set MAP_STEP = 10 cla...
from tkinter import Tk, Frame, Button, Canvas, Label, StringVar, LEFT, ALL from random import randint, randrange from math import inf from node import Node from obstacle import Obstacle from ellipse import Ellipse CANVAS_SIZE = [640, 480] MAX_LOOP = 500000 ARRIVAL_RADIUS = 20 MAP_STEP = 10 class RRStarAlgo: def ...
Python
zaydzuhri_stack_edu_python
function _draw_torus self begin call glBindTexture GL_TEXTURE_2D textureObjects at TORUS_TEXTURE call gltDrawTorus 0.35 0.15 61 37 end function
def _draw_torus(self): glBindTexture(GL_TEXTURE_2D, self.textureObjects[self.TORUS_TEXTURE]) gltDrawTorus(0.35, 0.15, 61, 37)
Python
nomic_cornstack_python_v1
import ast import torch from network import network import numpy as np try begin import cPickle as pickle end except any begin import pickle end comment 3 X 2 tensor set X = tensor tuple list 2 9 list 1 5 list 3 6 dtype=float comment 3 X 1 tensor set y = tensor tuple list 92 list 100 list 89 dtype=float comment 1 X 2 t...
import ast import torch from network import network import numpy as np try: import cPickle as pickle except: import pickle X = torch.tensor(([2, 9], [1, 5], [3, 6]), dtype=torch.float) # 3 X 2 tensor y = torch.tensor(([92], [100], [89]), dtype=torch.float) # 3 X 1 tensor xPredicted = torch.tensor(([4, 8]), ...
Python
zaydzuhri_stack_edu_python
function utm_to_latlon utm_x utm_y begin comment Get UTM information from southeast corner of field set SE_utm = call from_latlon 33.07451869 - 111.97477775 set utm_zone = SE_utm at 2 set utm_num = SE_utm at 3 return call to_latlon utm_x utm_y utm_zone utm_num end function
def utm_to_latlon(utm_x, utm_y): # Get UTM information from southeast corner of field SE_utm = utm.from_latlon(33.07451869, -111.97477775) utm_zone = SE_utm[2] utm_num = SE_utm[3] return utm.to_latlon(utm_x, utm_y, utm_zone, utm_num)
Python
nomic_cornstack_python_v1
function get_root self begin if _parent is none begin return self end else begin return call get_root end end function
def get_root(self): if self._parent is None: return self else: return self._parent.get_root()
Python
nomic_cornstack_python_v1
function search h g u=none begin if u != none and not u in fe begin raise ValueError end if not call is_connected begin raise ValueError end comment If we did not require a boundary point we could use comment u = h.fe.pop(), he.fe.add(u) if u == none begin set r = list comprehension a for a in he if e == none comment I...
def search(h,g,u=None): if u != None and not u in h.fe: raise ValueError if not h.is_connected(): raise ValueError # If we did not require a boundary point we could use # u = h.fe.pop(), he.fe.add(u) if u == None: r = [ a for a in h.he if a.e == None ] if r == []: # ...
Python
nomic_cornstack_python_v1
function _incdec_to_add tape begin while true begin set pos = call _find_pattern tape tuple string inc string x tuple string dec string y tuple string jnz string y - 2 if pos < 0 begin break end set tuple inc dec _ = tape at slice pos : pos + 3 : set repl = list call Command string add args at 0 args at 0 call Command...
def _incdec_to_add(tape: Tape) -> None: while True: pos = _find_pattern(tape, ('inc', 'x'), ('dec', 'y'), ('jnz', 'y', -2)) if pos < 0: break inc, dec, _ = tape[pos:pos+3] repl = [Command('add', dec.args[0], inc.args[0]), Command('cpy', 0, dec.args[0])] tape[pos:...
Python
nomic_cornstack_python_v1
from selenium import webdriver set driver = call Chrome string C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe set url = string http://topis.seoul.go.kr/refRoom/openRefRoom_1_3.do get driver url comment 년도 선택 set year = call find_element_by_id string selYear call click set year2017 = call find_element...
from selenium import webdriver driver = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe') url = 'http://topis.seoul.go.kr/refRoom/openRefRoom_1_3.do' driver.get(url) # 년도 선택 year = driver.find_element_by_id('selYear') year.click() year2017 = driver.find_element_by_xpath('//*[@id="s...
Python
zaydzuhri_stack_edu_python
function W self as_float=true begin comment Subtract the death rate parameter from all elements of the main comment diagonal of matrix `M()`. The numbers are all of type Fraction. set w = call M as_float=false set w at call diag_indices n = w at call diag_indices n - d if as_float begin set w = as type w float end retu...
def W(self, as_float=True): # Subtract the death rate parameter from all elements of the main # diagonal of matrix `M()`. The numbers are all of type Fraction. w = self.M(as_float=False) w[np.diag_indices(self.n)] -= self.d if as_float: w = w.astype(float) ret...
Python
nomic_cornstack_python_v1
import asyncio import aiohttp from bs4 import BeautifulSoup set URL = string https://ru.wikipedia.org/w/index.php set a = ordinal string А set LETTERS = dictionary comprehension character i : 0 for i in range a a + 32 async function get_url_text params session begin async_with get session URL params=params as response ...
import asyncio import aiohttp from bs4 import BeautifulSoup URL = "https://ru.wikipedia.org/w/index.php" a = ord("А") LETTERS = {chr(i): 0 for i in range(a, a + 32)} async def get_url_text(params, session): async with session.get(URL, params=params) as response: return await response.text() async def...
Python
zaydzuhri_stack_edu_python
function list_track_ids mpl_data_path n_tracks=100 begin set track_ids_gen = call track_id_generator mpl_data_path set track_ids = set while length track_ids < n_tracks begin add track_ids next track_ids_gen end return list track_ids end function
def list_track_ids(mpl_data_path, n_tracks=100): track_ids_gen = track_id_generator(mpl_data_path) track_ids = set() while len(track_ids) < n_tracks: track_ids.add(next(track_ids_gen)) return list(track_ids)
Python
nomic_cornstack_python_v1
function distance A B begin set AB = intersection A B return max call Volume + call Volume - 2.0 * call Volume 0.0 end function
def distance(A, B): AB = intersection(A, B); return max(A.Volume() + B.Volume() - 2.0 * AB.Volume(), 0.0);
Python
nomic_cornstack_python_v1
import random comment Game Options set ROCK = string rock set PAPER = string paper set SCISSORS = string scissors set game_options = list ROCK PAPER SCISSORS comment Game logic which determines the winner
import random # Game Options ROCK = 'rock' PAPER = 'paper' SCISSORS = 'scissors' game_options = [ROCK, PAPER, SCISSORS] # Game logic which determines the winner
Python
jtatman_500k
function insert_node self node_tup begin set signature = hex digest sha256 encode node_tup at 0 + node_tup at 4 string utf-8 set app_process = call connect string app_process::memory: check_same_thread=false set app_process_cursor = call cursor execute app_process_cursor string INSERT INTO nodes VALUES (:ip, :port, una...
def insert_node(self, node_tup): signature = hashlib.sha256((node_tup[0]+node_tup[4]).encode('utf-8')).hexdigest() app_process = sqlite3.connect('app_process::memory:', check_same_thread=False) app_process_cursor = app_process.cursor() app_process_cursor.execute("INSERT INTO nodes VALUES...
Python
nomic_cornstack_python_v1
comment !/bin/env python3 comment google code jam 2017 round 1B problem 3 comment Daniel Scharstein function solve a d begin set n = length a set t = list - 1 * n set t at 0 = 0 set cd = list 0 * n for i in range n - 1 begin set cd at i + 1 = cd at i + d at i end for i in range n begin set tuple maxd s = a at i set d0 ...
#!/bin/env python3 # google code jam 2017 round 1B problem 3 # Daniel Scharstein def solve(a, d): n = len(a) t = [-1] * n t[0] = 0 cd = [0] * n for i in range(n-1): cd[i+1] = cd[i] + d[i] for i in range(n): maxd, s = a[i] d0 = cd[i] t0 = t[i] for j in ra...
Python
zaydzuhri_stack_edu_python
import numpy as np import math from copy import deepcopy from PIL import Image function mirror img_i axis begin set tmp = deep copy img_i set h = shape at 0 set w = shape at 1 set i = 0 if axis == string y begin while i < h begin set j = 0 while j < w begin set tmp at tuple i j = img_i at tuple h - i - 1 j set j = j + ...
import numpy as np import math from copy import deepcopy from PIL import Image def mirror(img_i, axis): tmp = deepcopy(img_i) h = img_i.shape[0] w = img_i.shape[1] i = 0 if axis == 'y': while i < h: j = 0 while j < w: tmp[i, j] = img_i[h - i - 1, j] ...
Python
zaydzuhri_stack_edu_python
import argparse import firebase_admin import json from firebase_admin import credentials from firebase_admin import firestore function firebase_upload data begin set db = call client set games = call collection string courts for item in data begin set item end end function if __name__ == string __main__ begin set parse...
import argparse import firebase_admin import json from firebase_admin import credentials from firebase_admin import firestore def firebase_upload(data): db = firestore.client() games = db.collection('courts') for item in data: games.document().set(item) if __name__ == "__main__": parser = ...
Python
zaydzuhri_stack_edu_python
function filter self df condition metadata=none begin return select self df cols=call SelectColumns call col string * where=condition metadata=metadata end function
def filter( self, df: DataFrame, condition: ColumnExpr, metadata: Any = None ) -> DataFrame: return self.select( df, cols=SelectColumns(col("*")), where=condition, metadata=metadata )
Python
nomic_cornstack_python_v1
comment 136. Single Number comment Given an array of integers, every element appears comment twice except for one. Find that single one. comment Note: comment Your algorithm should have a linear runtime complexity. comment Could you implement it without using extra memory? class Solution extends object begin function s...
# 136. Single Number # Given an array of integers, every element appears # twice except for one. Find that single one. # Note: # Your algorithm should have a linear runtime complexity. # Could you implement it without using extra memory? class Solution(object): def singleNumber(self, nums): ...
Python
zaydzuhri_stack_edu_python