code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function open_reader self path begin return call _open_reader path end function
def open_reader(self, path): return self._open_reader(path)
Python
nomic_cornstack_python_v1
function showMaximized self begin if image is none begin pass end else begin call hide set width_img = 2000 call setMaximumSize call QSize width_img 16777215 call view_result image set maxi = true end end function
def showMaximized(self): if self.parent.image is None: pass else: self.parent.ui.scrollArea_2.hide() self.parent.width_img = 2000 self.parent.ui.scrollArea_3.setMaximumSize( QtCore.QSize(self.parent.width_img, 16777215)) self.pa...
Python
nomic_cornstack_python_v1
from import key function value_from_bytes encoded_bytes start=0 expected_indicator=b'V' begin string get value from encoded bytes, return (value_bytes, end_index) or (None, None) set value_bytes = none set end = none set nbytes = length encoded_bytes set indicator = encoded_bytes at slice start : start + 1 : if indic...
from . import key def value_from_bytes(encoded_bytes, start=0, expected_indicator=b"V"): "get value from encoded bytes, return (value_bytes, end_index) or (None, None)" value_bytes = end = None nbytes = len(encoded_bytes) indicator = encoded_bytes[start:start + 1] if indicator == expected_indicator...
Python
zaydzuhri_stack_edu_python
string This file contains the Gaussian Discriminany Analysis object class. import numpy as np from numpy.linalg import inv from linear_model import LinearModel class Gaussian_Discriminant_Analysis extends LinearModel begin string Class for using Gaussian Discriminant Analysis to create a linear model for binary classif...
''' This file contains the Gaussian Discriminany Analysis object class. ''' import numpy as np from numpy.linalg import inv from linear_model import LinearModel class Gaussian_Discriminant_Analysis(LinearModel): ''' Class for using Gaussian Discriminant Analysis to create a linear model for binary classif...
Python
zaydzuhri_stack_edu_python
string This program defines several functions that generate arrays of successively larger T-count operators. import numpy as np from time import time import operator_module as opm comment Generates a list of the 15 T1 operators function generate_T1 save=false load=false begin if load begin return call read_operators st...
""" This program defines several functions that generate arrays of successively larger T-count operators. """ import numpy as np from time import time import operator_module as opm # Generates a list of the 15 T1 operators def generate_T1(save=False, load=False): if load: return opm.read_operators('T1.txt...
Python
zaydzuhri_stack_edu_python
function parse_arguments begin set parser = call ArgumentParser description=string Convert NES CHR (graphics) data into a PNG file. formatter_class=ArgumentDefaultsHelpFormatter call add_argument string -p string --palette nargs=4 default=tuple string 000000 string 555555 string aaaaaa string ffffff help=string Output ...
def parse_arguments(): parser = argparse.ArgumentParser( description="Convert NES CHR (graphics) data into a PNG file.", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "-p", "--palette", nargs=4, default=("000000", "555555", "aaaaaa", "ffffff"), ...
Python
nomic_cornstack_python_v1
function prepare_pricing_dataset self work_dict begin set label = string prepare info format string task - {} - start work_dict={} label work_dict set initial_data = none set ticker = TICKER set ticker_id = TICKER_ID set rec = dict string ticker none ; string ticker_id none ; string s3_enabled true ; string redis_enabl...
def prepare_pricing_dataset( self, work_dict): label = 'prepare' log.info( 'task - {} - start ' 'work_dict={}'.format( label, work_dict)) initial_data = None ticker = TICKER ticker_id = TICKER_ID rec = { 'ticker': None, ...
Python
nomic_cornstack_python_v1
function _custom_hook_to_collect_layer_attributes self module _ output begin set output_activation_shape = list size output comment activation dimension for FC layer is (1,1) if is instance module Linear begin comment In cases where batch dimension is 1 if length output_activation_shape == 1 begin set output_activation...
def _custom_hook_to_collect_layer_attributes(self, module, _, output): output_activation_shape = list(output.size()) # activation dimension for FC layer is (1,1) if isinstance(module, torch.nn.Linear): # In cases where batch dimension is 1 if len(output_activation_shape) ...
Python
nomic_cornstack_python_v1
function preunitereads inputFastq args begin global ALLTEMPFILES set alignFile = name append ALLTEMPFILES alignFile set readFile = named temporary file prefix=string uni_ suffix=string .fasta delete=false dir=tempDir append ALLTEMPFILES name set input = call FastqFile inputFastq for read in input begin write readFile s...
def preunitereads(inputFastq, args): global ALLTEMPFILES alignFile = NamedTemporaryFile(prefix="uni_", suffix=".m5", delete=False, dir=args.tempDir).name ALLTEMPFILES.append(alignFile) readFile = NamedTemporaryFile(prefix="uni_", suffix=".fasta", delete=False, dir=args.tempDir) ALLTEMPFILES.append(r...
Python
nomic_cornstack_python_v1
function __init__ self begin set id = string uuid 4 set type = string Sensor set temp = random integer 80 100 set time = call isoformat set object = dict end function
def __init__(self): self.id = str(uuid.uuid4()) self.type = "Sensor" self.temp = random.randint(80, 100) self.time = dt.now().isoformat() self.object = {}
Python
nomic_cornstack_python_v1
function now cls force=false dontDownload=false ticker=true begin set simpleFilename = string jre-version-windows-arch.exe set downloadDir = call userHomeRelative string Downloads set downloadPath = join path downloadDir simpleFilename set semaphorePath = downloadPath + semaphoreExtenstion if exists path downloadPath a...
def now(cls, force=False, dontDownload=False, ticker=True): simpleFilename = "jre-version-windows-arch.exe" downloadDir = ScriptUser.loggedIn.userHomeRelative("Downloads") downloadPath = os.path.join(downloadDir, simpleFilename) semaphorePath = downloa...
Python
nomic_cornstack_python_v1
function fluid_func_doc self label begin set indices = list range 1 num_i + 1 if length indices > 1 begin set indices = join string , generator expression string idx for idx in indices end else begin set indices = string indices at 0 end set latex = string 0=x_{fl\mathrm{,in,}i}-x_{fl\mathrm{,out,}i}\;\forall fl \in\te...
def fluid_func_doc(self, label): indices = list(range(1, self.num_i + 1)) if len(indices) > 1: indices = ', '.join(str(idx) for idx in indices) else: indices = str(indices[0]) latex = ( r'0=x_{fl\mathrm{,in,}i}-x_{fl\mathrm{,out,}i}\;' r'\f...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Oct 25 18:14:45 2017 @author: sonam import numpy as np import seaborn as sb import matplotlib.pyplot as plt comment vertex from string import ascii_lowercase , ascii_uppercase from collections import deque from collections import OrderedDict from qutip import Qobj fro...
# -*- coding: utf-8 -*- """ Created on Wed Oct 25 18:14:45 2017 @author: sonam """ import numpy as np import seaborn as sb import matplotlib.pyplot as plt from string import ascii_lowercase, ascii_uppercase #vertex from collections import deque from collections import OrderedDict from qutip import Qobj ...
Python
zaydzuhri_stack_edu_python
function led_0 self data begin set color = call getRGBFromString data set r = color at string red set g = color at string green set b = color at string blue call _fade_to_rgbn 0 r g b 0 end function
def led_0(self, data): color = self.getRGBFromString(data) r = color [ 'red' ] g = color [ 'green' ] b = color [ 'blue' ] self._fade_to_rgbn(0, r, g, b, 0)
Python
nomic_cornstack_python_v1
function ext_test image message num_bits begin return call decode_ext call encode_ext image message num_bits num_bits == message end function
def ext_test(image,message,num_bits): return decode_ext(encode_ext(image,message,num_bits),num_bits)\ == message
Python
nomic_cornstack_python_v1
function clear self begin set _size = 0 set _items = array DEFAULT_CAPACITY end function
def clear(self): self._size = 0 self._items = Array(ArraySortedList.DEFAULT_CAPACITY)
Python
nomic_cornstack_python_v1
function _compute_eta self P_mat begin set tuple k l = shape set eta_mat = call empty tuple k l for i in range k begin for j in range l begin set eta_mat at tuple i j = sum P_mat at array range i k at tuple slice : : array range j l end end return eta_mat end function
def _compute_eta(self, P_mat): k, l = P_mat.shape eta_mat = np.empty((k, l)) for i in range(k): for j in range(l): eta_mat[i,j] = np.sum(P_mat[np.arange(i, k)][:, np.arange(j, l)]) return eta_mat
Python
nomic_cornstack_python_v1
function load_temperature_data directory=string ./data/ begin set all_stations_temp_dict = dictionary for tuple _ _ files in walk directory begin for file_name in files begin if starts with file_name string mm begin set station_temp_dict = dictionary set file = open directory + file_name string r set station_id = split...
def load_temperature_data(directory='./data/'): all_stations_temp_dict = dict() for _, _, files in walk(directory): for file_name in files: if file_name.startswith('mm'): station_temp_dict = dict() file = open(directory + file_name, 'r') statio...
Python
nomic_cornstack_python_v1
import turtle comment 导入时间包 import time comment 随机包 import random comment 导入pygame资源包 import pygame comment 音乐的路径 set file = string 4_2.mp3 comment 初始化 call init comment 加载音乐文件 set track = load music file comment 开始播放音乐流 call play comment 控制jerry上下左右跑 function up begin call setheading 90 call forward 20 end function fu...
import turtle import time #导入时间包 import random #随机包 import pygame # 导入pygame资源包 file=r'4_2.mp3' # 音乐的路径 pygame.mixer.init() # 初始化 track = pygame.mixer.music.load(file) # 加载音乐文件 pygame.mixer.music.play() # 开始播放音乐流 #控制jerry上下左右跑 def up(): jerry.setheading(90) jerry.forward(20) def down(): j...
Python
zaydzuhri_stack_edu_python
while anio <= numanios begin set principal = principal * 1 + tasa comment salida formateada mejorada 3 print format string {0:3d}{1:20.5f} anio principal set anio = anio + 1 end
while anio <= numanios: principal = principal * (1 + tasa) #salida formateada mejorada 3 print("{0:3d}{1:20.5f}".format(anio, principal)) anio += 1
Python
zaydzuhri_stack_edu_python
import pandas as pd from selenium import webdriver from xpinyin import Pinyin set expand_frame_repr = false function fun_list_to_str list begin set result = string if length list == 1 begin return list at 0 end else begin for i in range length list begin if i == 0 begin set result = list at i end else begin set result...
import pandas as pd from selenium import webdriver from xpinyin import Pinyin pd.options.display.expand_frame_repr=False def fun_list_to_str(list): result = '' if len(list) == 1: return list[0] else: for i in range(len(list)): if i == 0: result = list[i] ...
Python
zaydzuhri_stack_edu_python
function load_data begin set data = list with call Resource string triangle.txt as datafile begin for line in read lines datafile begin insert data 0 map int split strip line end end return data end function
def load_data(): data = [] with euler.Resource('triangle.txt') as datafile: for line in datafile.readlines(): data.insert(0, map(int, line.strip().split())) return data
Python
nomic_cornstack_python_v1
function __init__ __self__ availability_zones=none cloud_provider_profile=none count=none max_count=none max_pods=none min_count=none mode=none name=none node_image_version=none node_labels=none node_taints=none os_type=none vm_size=none begin if availability_zones is not none begin set __self__ string availability_zon...
def __init__(__self__, *, availability_zones: Optional[Sequence[str]] = None, cloud_provider_profile: Optional['outputs.CloudProviderProfileResponse'] = None, count: Optional[int] = None, max_count: Optional[int] = None, max_pods: Opti...
Python
nomic_cornstack_python_v1
comment !/bin/python3 import json import urllib.request import turtle import time comment http://open-notify.org/Open-Notify-API/ set url = string http://api.open-notify.org/astros.json set odpowiedz = url open url set wynik = loads read odpowiedz print string Liczba osób w Kosmosie: wynik at string number set osoby = ...
#!/bin/python3 import json import urllib.request import turtle import time # http://open-notify.org/Open-Notify-API/ url = 'http://api.open-notify.org/astros.json' odpowiedz = urllib.request.urlopen(url) wynik = json.loads(odpowiedz.read()) print('Liczba osób w Kosmosie: ', wynik['number']) osoby = wynik['people'] ...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. class TreeNode begin function __init__ self x begin set val = x set left = none set right = none end function end class class Solution begin function searchBST self root val begin function traverseTree root begin if root begin if val == val begin comment assigns the found root...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def searchBST(self, root, val): def traverseTree(root): if root: if root.val == val: ...
Python
zaydzuhri_stack_edu_python
function parse_chromAlias cpc build f begin set tuple spcode buildnum = call split_build_string build set build = build set bands = has with open f string r as tsvfile begin set reader = reader tsvfile delimiter=string set n = 0 for list name chr srcs in reader begin set id = call get_band_id cpc spcode chr string if i...
def parse_chromAlias(cpc: ChromosomePartCollection, build: GenomeBuildId, f: str): spcode, buildnum = split_build_string(build) cpc.genomes[spcode].build = build bands = cpc.has with open(f, 'r') as tsvfile: reader = csv.reader(tsvfile, delimiter='\t') n = 0 for [name,chr,srcs] i...
Python
nomic_cornstack_python_v1
function macro self macro_name begin pass end function
def macro(self, macro_name): pass
Python
nomic_cornstack_python_v1
string Move class and Pokemon class from random import randint comment DO NOT CHANGE THIS!!! comment ============================================================================= set is_effective_dictionary = dict string bug set literal string dark string grass string psychic ; string dark set literal string ghost stri...
""" Move class and Pokemon class """ from random import randint # DO NOT CHANGE THIS!!! # ============================================================================= is_effective_dictionary = {'bug': {'dark', 'grass', 'psychic'}, 'dark': {'ghost', 'psychic'}, ...
Python
zaydzuhri_stack_edu_python
function restart self begin set pot = 0 set actions = 0 set previous_bet = small_blind call initiate_blind small_blind + big_blind for player in players begin set credits = starting_credits end comment Let the first player begin set active_player = active_player + 1 % length players set active = true call flip_cards ca...
def restart(self): self.pot = 0 self.actions = 0 self.previous_bet = self.small_blind self.initiate_blind(self.small_blind + self.big_blind) for player in self.players: player.credits = self.starting_credits # Let the first player begin s...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string 9-2,3,4 文件访问,文件行数,文件访问2 import os.path , sys function openfile begin set filename = call raw_input string Enter file's name: set number = integer call raw_input string How many lines to print: end function
# -*- coding: utf-8 -*- """ 9-2,3,4 文件访问,文件行数,文件访问2 """ import os.path,sys def openfile(): filename=raw_input("Enter file's name: ") number=int(raw_input("How many lines to print: "))
Python
zaydzuhri_stack_edu_python
function local_cfg_to_string cfg begin set cfg_loc = call BytesIO call write_local_config cfg_loc return call getvalue end function
def local_cfg_to_string(cfg): cfg_loc = io.BytesIO() cfg.write_local_config(cfg_loc) return cfg_loc.getvalue()
Python
nomic_cornstack_python_v1
function delete_field_labels self begin for visual in visual_field_labels begin set parent = none end debug self string .delete_field_labels(): Deleted { length visual_field_labels } color=tuple 255 0 255 force=DebugVisuals set visual_field_labels = list end function
def delete_field_labels(self): for visual in self.visual_field_labels: visual.parent = None Debug( self, f".delete_field_labels(): Deleted {len(self.visual_field_labels)}", color=(255, 0, 255), force=self.DebugVisuals ) self.v...
Python
nomic_cornstack_python_v1
set a = integer input string ENter First NUmber: set b = integer input string ENter Second NUmber: set tuple x y = tuple y x print string First Number: a print string Second Number: b
a=int(input("ENter First NUmber:")) b=int(input("ENter Second NUmber:")) x, y = y, x print("First Number:",a) print("Second Number:",b)
Python
zaydzuhri_stack_edu_python
function delete_source self src_name begin while true begin try begin set response = query genes IndexName=string src_index KeyConditionExpression=call eq value end except ClientError as e begin raise call DatabaseReadException e end set records = response at string Items if not records begin break end with call batch_...
def delete_source(self, src_name: SourceName) -> None: while True: try: response = self.genes.query( IndexName="src_index", KeyConditionExpression=Key("src_name").eq(src_name.value), ) except ClientError as e: ...
Python
nomic_cornstack_python_v1
function double_decorator f begin function wrapper *args **kwargs begin return f dist *args keyword kwargs * 2 end function return wrapper end function function bold_decorator f begin function wrapper *args **kwargs begin return string <strong> { f dist *args keyword kwargs } </strong> end function return wrapper end f...
def double_decorator(f): def wrapper(*args, **kwargs): return f(*args, **kwargs) * 2 return wrapper def bold_decorator(f): def wrapper(*args, **kwargs): return f'<strong>{f(*args, **kwargs)}</strong>' return wrapper def bread(f): def wrapper(): top = '</"""""""\>' ...
Python
zaydzuhri_stack_edu_python
function get_hottest_submissions_last_day self amount=5 begin call refresh set my_subs = list comprehension string x for x in call get_my_subreddits set my_non_defaults = join string + list comprehension x for x in my_subs if x not in defaults set subs = call get_subreddit my_non_defaults set hot = list comprehension x...
def get_hottest_submissions_last_day(self, amount=5): self.o.refresh() my_subs = [str(x) for x in self.r.get_my_subreddits()] my_non_defaults = '+'.join([x for x in my_subs if x not in self.defaults]) subs = self.r.get_subreddit(my_non_defaults) hot = [x for x in subs.get_hot(tim...
Python
nomic_cornstack_python_v1
comment Implementation of the Queue ADT using a singly linked list. class Node begin function __init__ self data next=none begin string Instantiates a Node with default next of None set data = data set next = next end function end class class Queue begin string Link-based queue implementation. function __init__ self be...
# Implementation of the Queue ADT using a singly linked list. class Node: def __init__(self, data, next = None): """Instantiates a Node with default next of None""" self.data = data self.next = next class Queue: """ Link-based queue implementation.""" def __init...
Python
zaydzuhri_stack_edu_python
function solution A E begin global labels global tree set labels = A comment Building a tree for i in range integer length E / 2 begin if E at i * 2 in tree begin append tree at E at i * 2 E at i * 2 + 1 end else begin set tree at E at i * 2 = list E at i * 2 + 1 end end call get_each_node_l_depth E at 0 return max_len...
def solution(A, E): global labels global tree labels = A # Building a tree for i in range(int(len(E) / 2)): if E[i*2] in tree: tree[E[i*2]].append(E[i*2 + 1]) else: tree[E[i*2]] = [E[i*2 + 1]] get_each_node_l_depth(E[0]) return max_len def get_each_node_l_depth(i): global labels global node_l_...
Python
zaydzuhri_stack_edu_python
function __colorToTopLevel self begin call addTopLevelItems values _separatorContainer at string Color call addTopLevelItem _separatorContainer at string Land end function
def __colorToTopLevel(self): self.addTopLevelItems(self._separatorContainer['Color'].values()) self.addTopLevelItem(self._separatorContainer['Land'])
Python
nomic_cornstack_python_v1
for _ in range n begin set data = split input append array tuple data at 0 integer data at 1 end set array = sorted array key=lambda student -> student at 1 for i in array begin print i at 0 end=string end comment print([x[0] for x in d])
for _ in range(n): data = input().split() array.append((data[0], int(data[1]))) array = sorted(array, key = lambda student: student[1]) for i in array: print(i[0], end = ' ') # print([x[0] for x in d])
Python
zaydzuhri_stack_edu_python
from scipy.spatial import distance as dist from imutils import face_utils import numpy as np import imutils import dlib import cv2 import playsound comment calculating eye aspect ratio function eye_aspect_ratio eye begin comment compute the vertical euclidean distances set A = call euclidean eye at 1 eye at 5 set B = c...
from scipy.spatial import distance as dist from imutils import face_utils import numpy as np import imutils import dlib import cv2 import playsound # calculating eye aspect ratio def eye_aspect_ratio(eye): # compute the vertical euclidean distances A = dist.euclidean(eye[1], eye[5]) B = dist.euclidean(ey...
Python
zaydzuhri_stack_edu_python
function zakoduj tekst begin for l in tekst begin if l == string begin print string // end=string end else begin print kody at ordinal lower l - 97 + string / end=string end end print end function function dekoduj kod_morsea begin for k in kod_morsea begin print character index kody k + 97 end print end function funct...
def zakoduj(tekst): for l in tekst: if l == ' ': print('//', end='') else: print(kody[ord(l.lower()) - 97] + '/', end='') print() def dekoduj(kod_morsea): for k in kod_morsea: print(chr(kody.index(k) + 97)) print() def main(): tekst = input('Podaj ...
Python
zaydzuhri_stack_edu_python
function all_products request begin set products = all set query = none set categories = none if GET begin if string category in GET begin set categories = split GET at string category string , set products = filter category__name__in=categories set categories = filter name__in=categories end if string q in GET begin s...
def all_products(request): products = Product.objects.all() query = None categories = None if request.GET: if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Ca...
Python
nomic_cornstack_python_v1
async function join ctx begin set channel = voice_channel if channel is none begin return end if call is_voice_connected server begin await call disconnect end await call join_voice_channel channel end function
async def join(ctx): channel = ctx.message.author.voice_channel if channel is None: return if bot.is_voice_connected(channel.server): await bot.voice.disconnect() await bot.join_voice_channel(channel)
Python
nomic_cornstack_python_v1
function isnot_int s begin try begin integer s return false end except ValueError begin return true end end function function main begin set First = string input string Please enter a fraction: set Second = string input string Pleaes enter another fraction: if not call isnot_int First begin set First = First + string /...
def isnot_int(s): try: int(s) return False except ValueError: return True def main(): First=str(input("Please enter a fraction: ")) Second=str(input("Pleaes enter another fraction: ")) if not(isnot_int(First)): First=First+'/1' if not(isnot_int(Second)): ...
Python
zaydzuhri_stack_edu_python
from typing import List function vizinho_proximo grafo begin set u = 0 set C : List at int = list u set tam = length grafo set Q : List at int = list set v = none for i in range tam begin append Q i end remove Q u while Q != 0 begin set menor = decimal string inf set continua = false for i in range tam begin if grafo ...
from typing import List def vizinho_proximo(grafo) -> List[int]: u = 0 C: List[int] = [u] tam = len(grafo) Q: List[int] = [] v = None for i in range(tam): Q.append(i) Q.remove(u) while (Q != 0): menor = float('inf') continua = False for ...
Python
zaydzuhri_stack_edu_python
function _embed self backgroundStringArr priorEmbeddedThings additionalInfo begin set embeddable = call generateEmbeddable set canEmbed = false set tries = 0 while not canEmbed begin set tries = tries + 1 if is instance backgroundStringArr at 0 list begin set len_bsa = length backgroundStringArr at 0 end else begin set...
def _embed(self, backgroundStringArr, priorEmbeddedThings, additionalInfo): embeddable = self.embeddableGenerator.generateEmbeddable() canEmbed = False tries = 0 while not canEmbed: tries += 1 if isinstance(backgroundStringArr[0], list): len_bsa = ...
Python
nomic_cornstack_python_v1
function decide_if_keeping dE temperature begin if dE <= 0 begin return true end else begin return random < exp - dE / temperature end end function
def decide_if_keeping(dE,temperature): if dE <= 0: return True else: return np.random.random() < math.exp(-dE/temperature)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import urllib import zipfile import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt comment Download data and unzip the data comment urllib.urlretrieve('http://economics.mit.edu/files/397', 'asciiqob.zip') with zip file string asciiqob.zip string r as z begin extra...
#!/usr/bin/env python import urllib import zipfile import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt # Download data and unzip the data # urllib.urlretrieve('http://economics.mit.edu/files/397', 'asciiqob.zip') with zipfile.ZipFile('asciiqob.zip', "r") as z: z.extractall() # Read t...
Python
zaydzuhri_stack_edu_python
class Solution begin function maxProfit self nums begin set tuple left right maxi = tuple 0 1 0 while right < length nums begin if nums at left > nums at right begin set left = right set right = right + 1 end else begin set total = nums at right - nums at left set maxi = max maxi total set right = right + 1 end end ret...
class Solution: def maxProfit(self, nums: List[int]) -> int: left,right,maxi=0,1,0 while right<len(nums): if nums[left]>nums[right]: left=right right+=1 else: total=nums[right]-nums[left] maxi=max(maxi,total) ...
Python
zaydzuhri_stack_edu_python
import json import pandas as pd import spacy import pickle import time comment total: 1796000 papers (all types) set pickle_abstracts = open string keywords_pickles/cs_abstracts.pickle string wb set i = 0 set abstracts = string set nlp = load spacy string en_core_web_sm with open string arxiv-metadata-oai-snapshot.jso...
import json import pandas as pd import spacy import pickle import time # total: 1796000 papers (all types) pickle_abstracts = open('keywords_pickles/cs_abstracts.pickle', 'wb') i = 0 abstracts = '' nlp = spacy.load('en_core_web_sm') with open('arxiv-metadata-oai-snapshot.json', 'r') as f: start_time = time.time(...
Python
zaydzuhri_stack_edu_python
function calculate_hashes self begin string Return hashes of the contents of this MAR file. The hashes depend on the algorithms defined in the MAR file's signature block. Returns: A list of (algorithm_id, hash) tuples set hashers = list if not signatures begin return list end for s in sigs begin set h = call make_has...
def calculate_hashes(self): """Return hashes of the contents of this MAR file. The hashes depend on the algorithms defined in the MAR file's signature block. Returns: A list of (algorithm_id, hash) tuples """ hashers = [] if not self.mardata.signatures: ...
Python
jtatman_500k
class Solution begin function maxArea self height begin set tuple ret front rear = tuple 0 0 length height - 1 while front < rear begin set area = rear - front * min height at front height at rear set ret = if expression area > ret then area else ret if height at front < height at rear begin set front = front + 1 end e...
class Solution: def maxArea(self, height): ret, front, rear = 0, 0, len(height) - 1 while front < rear: area = (rear - front) * min(height[front], height[rear]) ret = area if area > ret else ret if height[front] < height[rear]: front += 1 ...
Python
zaydzuhri_stack_edu_python
function _collect_operation_calls response poll_interval_seconds=3 begin set client = call _from_response response set op = call from_response client response info string Waiting for operation to complete: { op } set request_while_pending = get client endpoint=string /api/versioned/v1/operations/ { resource_id } while ...
def _collect_operation_calls( *, response: Response, poll_interval_seconds: int = 3 ) -> List[Response]: client = utils.client._from_response(response) op = Operation.from_response(client, response) LOGGER.info(f"Waiting for operation to complete: {op}") request_while_pending = client.get(endpoint...
Python
nomic_cornstack_python_v1
function test_plot self begin comment ROOT Based plots comment Get list of versions set versions = call get_all_versions call failUnlessEqual versions list 1 2 comment Get current version set current = call get_current_version call failUnlessEqual current 2 comment Get next version set next = call get_next_version call...
def test_plot(self): # # ROOT Based plots # # Get list of versions versions = self.p1.get_all_versions() self.failUnlessEqual(versions,[1,2]) # Get current version current = self.p1.get_current_version() self.failUnlessEq...
Python
nomic_cornstack_python_v1
from collections import deque from constants import APPLE , SNAKE_BODY , SNAKE_HEAD class Bfs begin set NAME = string Bfs decorator staticmethod function find_path start end graph begin set grid = board set queue = deque list list start set seen = set list start while queue begin set path = call popleft set tuple x y =...
from collections import deque from constants import APPLE, SNAKE_BODY, SNAKE_HEAD class Bfs: NAME = "Bfs" @staticmethod def find_path(start, end, graph): grid = graph.board queue = deque([[start]]) seen = set([start]) while queue: path = queue.popleft() ...
Python
zaydzuhri_stack_edu_python
function relock self lock_doc begin set lock_info = loads lock_doc if string data_connections in lock_info begin for tuple dataset_name dataset_new_details in items lock_info at string data_connections begin set dataset_connection = get attribute tabs_module dataset_name for tuple k v in items dataset_new_details begin...
def relock(self, lock_doc): lock_info = json.loads(lock_doc) if 'data_connections' in lock_info: for dataset_name, dataset_new_details in lock_info['data_connections'].items(): dataset_connection = getattr(self.tabs_module, dataset_name) for k,v in dataset_ne...
Python
nomic_cornstack_python_v1
import requests function CEP message begin set request = json get requests string https://brasilapi.com.br/api/cep/v1/ + replace replace text string @ghostvd_bot string string /cep string if string message not in request begin set cep = get request string cep set cidade = get request string city set uf = get request st...
import requests def CEP(message): request = requests.get('https://brasilapi.com.br/api/cep/v1/' + message.text.replace('@ghostvd_bot', '').replace('/cep ', '')).json() if 'message' not in request: cep = request.get('cep') cidade = request.get('city') uf = r...
Python
zaydzuhri_stack_edu_python
function average df column_name begin set List = list generator expression decimal val for val in df at column_name return mean statistics List end function
def average(df: DataFrame, column_name: str) -> float: List = list(float(val) for val in df[column_name]) return statistics.mean(List)
Python
nomic_cornstack_python_v1
function _record_audio_data_callback self data begin set data = call fromstring data uint8 if first_audio_frame begin set wf = open file_path string wb call setnchannels total_channels call setsampwidth call get_sample_size audio_format call setframerate audio_rate call setnframes chunk_size call writeframes join b'' d...
def _record_audio_data_callback(self, data): data = np.fromstring(data.data, np.uint8) if self.first_audio_frame: self.wf = wave.open(self.file_path, "wb") self.wf.setnchannels(self.total_channels) self.wf.setsampwidth(self.p.get_sample_size(self.audio_format)) ...
Python
nomic_cornstack_python_v1
from pandas import read_csv comment takes in a csv file as a string and outputs an array
from pandas import read_csv # takes in a csv file as a string and outputs an array
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- set arr = list 1 2 3 4 5 for i in range length arr begin if 6 - arr at i in arr at slice i + 1 : : begin print i arr at i print index arr 6 - arr at i 6 - arr at i end end
#!/usr/bin/env python3 # -*- coding: utf-8 -*- arr = [1,2,3,4,5] for i in range(len(arr)): if 6-arr[i] in arr[i+1:]: print(i,arr[i]) print(arr.index(6-arr[i]),(6-arr[i]))
Python
zaydzuhri_stack_edu_python
function connected_with_process self process begin return process in _connected_processes end function
def connected_with_process(self, process): return process in self._connected_processes
Python
nomic_cornstack_python_v1
function __getMinNode self droot begin set m = droot set dnode = droot if droot is not none begin while left != none begin set dnode = left if key < key begin set m = dnode end end end return m end function
def __getMinNode(self, droot): m = droot dnode = droot if droot is not None: while dnode.left != None: dnode = dnode.left if dnode.key < m.key: m = dnode return m
Python
nomic_cornstack_python_v1
from datetime import datetime function has_friday_13 month year begin return string format time call datetime year month 13 string %a == string Fri end function
from datetime import datetime def has_friday_13(month, year): return datetime(year, month, 13).strftime('%a') == 'Fri'
Python
zaydzuhri_stack_edu_python
function display_fps self begin set template = string {} - FPS: {:.2f} set caption = format template CAPTION call get_fps call set_caption caption end function
def display_fps(self): template = "{} - FPS: {:.2f}" caption = template.format(c.CAPTION, self.clock.get_fps()) pg.display.set_caption(caption)
Python
nomic_cornstack_python_v1
function ReadConfigureVars config_filename begin set config_vars = dict with open config_filename string r as config_file begin for line in config_file begin set m = match line if m begin set config_vars at call group 1 = 1 end end end return config_vars end function
def ReadConfigureVars(config_filename): config_vars = {} with open(config_filename, 'r') as config_file: for line in config_file: m = VAR_DEFINITION_PATTERN.match(line) if m: config_vars[m.group(1)] = 1 return config_vars
Python
nomic_cornstack_python_v1
function add_constant self type_ value begin assert type_ in list STR INT DOUBLE msg string Error constant type for tuple idx const in enumerate constants begin if tuple type_ value == tuple type_ value begin return idx end end append constants call Constant type_ value return length constants - 1 end function
def add_constant(self, type_: str, value): assert type_ in [Constant.STR, Constant.INT, Constant.DOUBLE], 'Error constant type' for idx, const in enumerate(self.constants): if (const.type_, const.value) == (type_, value): return idx self.const...
Python
nomic_cornstack_python_v1
class UserData begin function __init__ self begin comment real name of the user set name = string comment real surname of the user set surname = string comment age of the user set age = integer comment telegram user name set tgUserName = string comment telegram user id set tgUserID = integer comment list of links to so...
class UserData: def __init__(self): self.name = str() # real name of the user self.surname = str() # real surname of the user self.age = int() # age of the user self.tgUserName = str() # telegram user name self.tgUserID = int() # telegram user id self.socialNetworkLinks = list() # list of ...
Python
zaydzuhri_stack_edu_python
function init_weights2 net begin for m in call modules begin if is instance m Conv2d begin call xavier_uniform_ weight if bias is not none begin call constant_ bias 0 end end else if is instance m BatchNorm2d begin call constant_ weight 1 call constant_ bias 0 end else if is instance m Linear begin call xavier_uniform_...
def init_weights2(net): for m in net.modules(): if isinstance(m, nn.Conv2d): nn.init.xavier_uniform_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): ...
Python
nomic_cornstack_python_v1
function download_listings self begin call ExecConfigMethod api_session channel_id=channel_id source=source property_name=string DownloadListings function_name=string DownloadListings end function
def download_listings(self): ExecConfigMethod( self.api_session, channel_id=self.channel_id, source=self.source, property_name='DownloadListings', function_name='DownloadListings')
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import boto3 set file = string elb.md set client = call client string elbv2 function main begin string ELBの基本設定を含む一覧を取得し、ELB毎に情報を整理、取得する為の関数を呼び出す。 with open file string w encoding=string utf-8 as f begin write f string # ELB end set get_elbs = call describe_load_balancers at string LoadBal...
# -*- coding: utf-8 -*- import boto3 file = 'elb.md' client = boto3.client('elbv2') def main(): """ ELBの基本設定を含む一覧を取得し、ELB毎に情報を整理、取得する為の関数を呼び出す。 """ with open(file, 'w', encoding='utf-8') as f: f.write('# ELB') get_elbs = client.describe_load_balancers()['LoadBalancers'] for elb in ge...
Python
zaydzuhri_stack_edu_python
import threading import serial import struct import random import time class LLCom extends Thread begin set ESC = 124 set HDR = 125 set FOOT = 126 set WAIT_FOR_HEADER = 1 set IN_MSG = 2 set IN_ESC = 3 function __init__ self comport callback begin set callback = callback call __init__ self comment open serial port set c...
import threading import serial import struct import random import time class LLCom(threading.Thread): ESC = 0x7c HDR = 0x7d FOOT = 0x7e WAIT_FOR_HEADER = 1 IN_MSG = 2 IN_ESC = 3 def __init__(self, comport, callback): self.callback = callback threading.Thread.__init__(self) self.comport = serial.Serial(...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Mar 10 16:18:56 2016 @author: Colin import pandas as pd import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib call use string ggplot close plt string all comment The timezone and UTC offset break our timedate, so just ignore them comment...
# -*- coding: utf-8 -*- """ Created on Thu Mar 10 16:18:56 2016 @author: Colin """ import pandas as pd import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') plt.close("all") #The timezone and UTC offset break our timedate, so just ignore them parser = l...
Python
zaydzuhri_stack_edu_python
async function _async_on_connect begin await call trigger await call target end function
async def _async_on_connect(): await self._watchdog.trigger() await target()
Python
nomic_cornstack_python_v1
function main begin set client = call Elasticsearch list string 152.136.231.113:32000 set search = search using=client index=string mydocument set top_k = 1 set df_path = string ./cmrc_reformatted/cmrc_reformatted.csv comment drop 2 nan question and 8 nan title set df = drop missing read csv df_path sep=string index_c...
def main(): client = Elasticsearch(['152.136.231.113:32000']) search = Search(using=client, index="mydocument") top_k = 1 df_path = './cmrc_reformatted/cmrc_reformatted.csv' df = pd.read_csv(df_path, sep='\t', index_col=0).dropna() # drop 2 nan question and 8 nan title precision_list, recall_li...
Python
nomic_cornstack_python_v1
function __get_submissions self begin comment Query the API and return a generator. return call new limit=1000 end function
def __get_submissions(self) -> Iterator: # Query the API and return a generator. return self.subreddit.new(limit=1000)
Python
nomic_cornstack_python_v1
import mysql.connector from tkinter import messagebox class DBhelper begin function __init__ self begin try begin set _connection = call connect host=string remotemysql.com user=string eULkE4oaue password=string 56pJskwG6X database=string eULkE4oaue set _mycursor = call cursor end except any begin call errorMessage str...
import mysql.connector from tkinter import messagebox class DBhelper: def __init__(self): try: self._connection=mysql.connector.connect(host="remotemysql.com", user="eULkE4oaue", password="56pJskwG6X", database="eULkE4oaue") self._mycursor=self._connection.cursor() ...
Python
zaydzuhri_stack_edu_python
for i in range 1 11 begin set areas = areas + list i * i end print string areas areas set areas2 = list comprehension i * i for i in range 1 11 print string areas2 areas2 set areas3 = list for i in range 1 11 begin if i % 2 == 0 begin set areas3 = areas3 + list i * i end end print string areas3 areas3 set areas4 = lis...
for i in range(1, 11): areas = areas + [i*i] print("areas", areas) areas2 = [ i*i for i in range(1, 11) ] print("areas2", areas2) areas3 = [] for i in range(1, 11): if i%2 == 0: areas3 = areas3 + [i*i] print("areas3", areas3) areas4 = [ i*i for i in range(1, 11) if i%2 == 0 ] print("areas4", area...
Python
zaydzuhri_stack_edu_python
comment -*- coding:Utf-8 -*- comment python 2.7.3 Windows XP : OK comment python 2.7.2 Linux/Ubuntu : OK from Tkinter import * import sys import tkMessageBox class Initiation begin function __init__ self begin comment le flag permet de controler le jeu (arrêt ou marche) set jeu = 1 call lecture_options set taille_carre...
# -*- coding:Utf-8 -*- # python 2.7.3 Windows XP : OK # python 2.7.2 Linux/Ubuntu : OK from Tkinter import * import sys import tkMessageBox class Initiation: def __init__(self): Initiation.jeu = 1 # le flag permet de controler le jeu (arrêt ou marche) self.lecture_options() Initiation.t...
Python
zaydzuhri_stack_edu_python
import requests , time , json , threading , random class test extends object begin set headers = dict string Content-type string application/json function __init__ self login_url userName=string password=string begin set login_url = login_url set userName = userName set password = password set session = call Session s...
import requests ,time,json,threading,random class test (object): headers = { "Content-type":"application/json" } def __init__(self,login_url,userName="",password=""): self.login_url = login_url self.userName = userName self.password = password self.session = request...
Python
zaydzuhri_stack_edu_python
import json import pymongo import re comment Mongo setup from pymongo import MongoClient set client = call MongoClient set db = volans set collection = courses comment JSON setup set json_data = open string all_data_new.json set data = load json json_data comment Get a list of prerequisites for the given course functio...
import json import pymongo import re # Mongo setup from pymongo import MongoClient client = MongoClient() db = client.volans collection = db.courses # JSON setup json_data = open('all_data_new.json') data = json.load(json_data) # Get a list of prerequisites for the given course def get_prereq(prereqstr): prereq_...
Python
zaydzuhri_stack_edu_python
function even_odd number begin if number % 2 == 0 begin print string Even end else begin print string Odd end end function
def even_odd(number): if number % 2 == 0: print("Even") else: print("Odd")
Python
flytech_python_25k
for line in text begin set line = strip line end set bookends = list set start = list set stop = list for i in range length line begin set char = line at i if char == string { begin append start i end if char == string } begin append stop i append bookends tuple pop start pop stop end end for tuple start stop in boo...
for line in text: line = line.strip() bookends = [] start = [] stop = [] for i in range(len(line)): char = line[i] if char == '{': start.append(i) if char == '}': stop.append(i) bookends.append((start.pop(), stop.pop())) for start,stop in bookends: struct = eval(line[start:stop+1])...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2.7 comment -*- coding: utf-8 -*- string :synopsis: Interfaces for gzip compression and decompression using file objects. This module provides a simple interface to compress and decompress files just like the GNU programs :program:`gzip` and :program:`gunzip` would. The data compression is p...
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- """:synopsis: Interfaces for gzip compression and decompression using file objects. This module provides a simple interface to compress and decompress files just like the GNU programs :program:`gzip` and :program:`gunzip` would. The data compression is provided by the ...
Python
zaydzuhri_stack_edu_python
string for letra in text: for letra in text begin if letra == string 1 begin append output string ` end else if letra == string W begin call appnd string Q end else if letra == string S begin append output string A end else if letra == string X begin append output string Z end else if letra == string begin append outp...
"""for letra in text:""" for letra in text: if letra == "1": output.append('`') elif letra == 'W': output.appnd('Q') elif letra == 'S': output.append('A') elif letra == 'X': output.append('Z') elif letra == ' ': output.append(' ') if letra != '1' and letra...
Python
zaydzuhri_stack_edu_python
function correct_rytov_sc_input radius_sc sphere_index_sc medium_index radius_sampling begin string Inverse correction of refractive index and radius for Rytov This method returns the inverse of :func:`correct_rytov_output`. Parameters ---------- radius_sc: float Systematically corrected radius of the sphere [m] sphere...
def correct_rytov_sc_input(radius_sc, sphere_index_sc, medium_index, radius_sampling): """Inverse correction of refractive index and radius for Rytov This method returns the inverse of :func:`correct_rytov_output`. Parameters ---------- radius_sc: float Systemati...
Python
jtatman_500k
from zipfile import ZipFile set zip_name = input string Enter the name of the zip file: set file1 = input string Enter the first file to zip: set file2 = input string Enter the second file to zip: with zip file string { zip_name } .zip string w as zipf begin write zipf file1 write zipf file2 end
from zipfile import ZipFile zip_name = input('Enter the name of the zip file: ') file1 = input('Enter the first file to zip: ') file2 = input('Enter the second file to zip: ') with ZipFile(f'{zip_name}.zip', 'w') as zipf: zipf.write(file1) zipf.write(file2)
Python
flytech_python_25k
function _GetDimensionChanges self begin set width_change = if expression _left then _CHANGE_W_OFFSET else if expression _right then _CHANGE_WO_OFFSET else _NO_CHANGE set height_change = if expression _top then _CHANGE_W_OFFSET else if expression _bottom then _CHANGE_WO_OFFSET else _NO_CHANGE return tuple width_change ...
def _GetDimensionChanges(self): width_change = ( self._CHANGE_W_OFFSET if self._left else self._CHANGE_WO_OFFSET if self._right else self._NO_CHANGE ) height_change = ( sel...
Python
nomic_cornstack_python_v1
function sendingame self room_id packet begin for conn in call ingame_connections room_id begin call send packet end end function
def sendingame(self, room_id, packet): for conn in self.ingame_connections(room_id): conn.send(packet)
Python
nomic_cornstack_python_v1
function esxi_host_count self esxi_host_count begin set _esxi_host_count = esxi_host_count end function
def esxi_host_count(self, esxi_host_count): self._esxi_host_count = esxi_host_count
Python
nomic_cornstack_python_v1
function probability_s self s c begin return sum list comprehension call get_likelihood c w for w in s + prior_probability at c end function
def probability_s(self, s, c): return sum([self.get_likelihood(c, w) for w in s]) + self.prior_probability[c]
Python
nomic_cornstack_python_v1
import sklearn import io from sklearn.model_selection import train_test_split import NB function get_gold_std train_pos_sen train_neg_sen begin set gold_set = dict set test = open train_pos_sen string r encoding=string utf8 for line in read lines test begin set gold_set at string split line none 1 at 0 = tuple strip s...
import sklearn import io from sklearn.model_selection import train_test_split import NB def get_gold_std(train_pos_sen, train_neg_sen): gold_set = {} test = io.open(train_pos_sen, 'r', encoding="utf8") for line in test.readlines(): gold_set[str(line.split(None, 1)[0])] = (str(line.split(None, 1)[1...
Python
zaydzuhri_stack_edu_python
function _test_structure_exist self dataset_path begin call _save_to_instance_folder_paths dataset_path if exists path images_folder_path and exists path annotations_folder_path begin return true end return false end function
def _test_structure_exist(self, dataset_path): self._save_to_instance_folder_paths(dataset_path) if os.path.exists(self.images_folder_path) and os.path.exists(self.annotations_folder_path): return True return False
Python
nomic_cornstack_python_v1
string Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. class Solution extends object begin string idea: 2 index pointers: new_index, points at new ends curr_index, walk throug...
""" Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. """ class Solution(object): """ idea: 2 index pointers: new_index, points at new ends cur...
Python
zaydzuhri_stack_edu_python
function ino begin show string spheres string inorganic comment cmd.set('sphere_scale', '0.25', '(all)') set string sphere_scale string 1 string (all) call color string yellow string inorganic end function
def ino(): cmd.show("spheres", "inorganic") #cmd.set('sphere_scale', '0.25', '(all)') cmd.set('sphere_scale', '1', '(all)') cmd.color("yellow", "inorganic")
Python
nomic_cornstack_python_v1
function dict_to_html dict begin set html = string for key in dict begin set html = html + format string {}: {}<br> key dict at key end return html end function
def dict_to_html(dict): html = '' for key in dict: html += '{}: {}<br>'.format(key, dict[key]) return html
Python
nomic_cornstack_python_v1
import math function calculate_sphere_volume radius begin set volume = 4 / 3 * pi * radius ^ 3 return volume end function comment Example usage set radius = 5 set sphere_volume = call calculate_sphere_volume radius print string The volume of the sphere with radius { radius } is { sphere_volume }
import math def calculate_sphere_volume(radius): volume = (4/3) * math.pi * (radius**3) return volume # Example usage radius = 5 sphere_volume = calculate_sphere_volume(radius) print(f"The volume of the sphere with radius {radius} is {sphere_volume}")
Python
jtatman_500k
function list_ports self begin comment Build a port list set port_list_all = call comports set port_list = list for device in port_list_all begin append port_list device at 0 end print string Available serial ports: for port in port_list begin print format string {0} port end end function
def list_ports(self): # Build a port list port_list_all = comports() port_list = list() for device in port_list_all: port_list.append(device[0]) print('Available serial ports:') for port in port_list: print('\t{0}'.format(port))
Python
nomic_cornstack_python_v1
function submit self application job=none begin set job = call gsub application job return unique_token end function
def submit(self, application, job=None): job = self.mw.gsub(application, job) return job.unique_token
Python
nomic_cornstack_python_v1