code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment variables set numero = 21 comment constantes set TOPE = 35 while numero <= TOPE begin print numero set numero = numero + 2 end
# variables numero = 21 #constantes TOPE = 35 while numero <= TOPE: print(numero) numero += 2
Python
zaydzuhri_stack_edu_python
from modules.pid import * class Mani begin function __init__ self knots motors setuplist ratiolist wdup limits begin set pidlist = list set gear_ratio_list = ratiolist for i in range knots begin append pidlist call PID setuplist at i motors at i end for i in range 0 length pidlist begin set tuple neg pos = limits at i...
from modules.pid import * class Mani: def __init__(self, knots, motors, setuplist, ratiolist, wdup, limits): self.pidlist = [] self.gear_ratio_list = ratiolist for i in range(knots): self.pidlist.append(PID(setuplist[i], motors[i])) for i in range(0, len(self.pidlist)): ...
Python
zaydzuhri_stack_edu_python
function pack_public x1 x2 begin return x1 + P * x2 end function
def pack_public(x1, x2): return (x1 + P * x2)
Python
nomic_cornstack_python_v1
for i in range 7 begin for j in range 7 begin if i - j == 3 or i + j == 3 and j > 0 or j - i == 3 and j > 3 or i == 5 and j == 4 or i == 4 and j == 5 begin print string * end=string end else begin print end=string end end print end
for i in range(7): for j in range(7): if ((i-j==3)or(i+j==3 and j>0)or(j-i==3 and j>3)or((i==5 and j==4)or(i==4 and j==5))): print("*",end="") else: print(end=" ") print()
Python
zaydzuhri_stack_edu_python
function create_task_id begin return string integer round time * 10 ^ 9 end function
def create_task_id(): return str(int(round(time.time() * 10**9)))
Python
nomic_cornstack_python_v1
comment Create a function for printing triangles of numbers as shown below comment Input: comment 4 comment Output: comment 1 comment 1 2 comment 1 2 3 comment 1 2 3 4 comment 1 2 3 comment 1 2 comment 1 function numbers_print num begin for i in range 1 num + 1 begin print i end=string end end function function first_p...
# Create a function for printing triangles of numbers as shown below # Input: # 4 # # Output: # 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 # 1 2 # 1 def numbers_print(num): for i in range(1, num + 1): print(i, end=" ") def first_part_print(num): for counter in range(1, num + 1): numbers_print(counter...
Python
zaydzuhri_stack_edu_python
function drop_empty_bag_partitions bag begin set bag = call persist function get_len partition begin comment If the bag is the result of bag.filter(), comment then each partition is actually a 'filter' object, comment which has no __len__. comment In that case, we must convert it to a list first. if has attribute parti...
def drop_empty_bag_partitions(bag): bag = bag.persist() def get_len(partition): # If the bag is the result of bag.filter(), # then each partition is actually a 'filter' object, # which has no __len__. # In that case, we must convert it to a list first. if hasattr(partitio...
Python
nomic_cornstack_python_v1
function isWall x y begin if x < 0 or x >= 5 begin return true end if y < 0 or y >= 5 begin return true end end function set val = 0 for y in range 5 begin comment 한 줄에 대해 따로따로 구하라고 했으면 val = 0 이 이 자리에 와야한다. for x in range 5 begin comment 네 방향에 대한 새로운 위치를 정해줌 for i in range 4 begin set nx = x + dx at i set ny = y + dy ...
def isWall(x, y): if x < 0 or x >= 5: return True if y < 0 or y >= 5: return True val = 0 for y in range(5): # 한 줄에 대해 따로따로 구하라고 했으면 val = 0 이 이 자리에 와야한다. for x in range(5): # 네 방향에 대한 새로운 위치를 정해줌 for i in range(4): nx = x + dx[i] ny = y + dy[i] ...
Python
zaydzuhri_stack_edu_python
function remove_property self subject key begin set subject = call _uuid_parse subject if call jack_remove_property _ptr subject encode key != 0 begin raise call ValueError format string Unable to remove property {!r} for subject {!r} key subject end end function
def remove_property(self, subject, key): subject = _uuid_parse(subject) if _lib.jack_remove_property(self._ptr, subject, key.encode()) != 0: raise ValueError('Unable to remove property {!r} for subject {!r}' .format(key, subject))
Python
nomic_cornstack_python_v1
function timeout_wait self begin if _dtr_enabled begin while call __micros - _resume_time < 0 begin if false begin comment TODO: Check for printer status here break end end end else begin while call __micros - _resume_time < 0 begin pass end end end function
def timeout_wait(self): if self._dtr_enabled: while (self.__micros() - self._resume_time) < 0: if False: break # TODO: Check for printer status here else: while (self.__micros() - self._resume_time) < 0: pass
Python
nomic_cornstack_python_v1
function hasNext self begin if tree begin return true end else begin return false end end function
def hasNext(self): if self.tree: return True else: return False
Python
nomic_cornstack_python_v1
function verify self digest begin raise NotImplementedError end function
def verify(self, digest): raise NotImplementedError
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from ExactDate import ExactDate from JieQi import JieQi from NineStar import NineStar from EightChar import EightChar from ShuJiu import ShuJiu from Fu import Fu from Solar import Solar from SolarWeek import SolarWeek from SolarMonth import SolarMonth from SolarSeason import SolarSeason fr...
# -*- coding: utf-8 -*- from .ExactDate import ExactDate from .JieQi import JieQi from .NineStar import NineStar from .EightChar import EightChar from .ShuJiu import ShuJiu from .Fu import Fu from .Solar import Solar from .SolarWeek import SolarWeek from .SolarMonth import SolarMonth from .SolarSeason import SolarSeaso...
Python
jtatman_500k
comment 字符串的搜索和替换 import re from calendar import month_abbr comment change_date是一个替换模式,m是一个match object function change_date m begin set mon_name = month_abbr at integer call group 1 return format string {} {} {} call group 2 mon_name call group 3 end function function search_replace begin set text = string yeah, but n...
#字符串的搜索和替换 import re from calendar import month_abbr def change_date(m): #change_date是一个替换模式,m是一个match object mon_name = month_abbr[int(m.group(1))] return '{} {} {}'.format(m.group(2),mon_name,m.group(3)) def search_replace(): text = 'yeah, but no, but yeah, but no, but yeah' text_rep =...
Python
zaydzuhri_stack_edu_python
function max_difference nums begin set max_diff = 0 set min_num = nums at 0 for num in nums begin if num < min_num begin set min_num = num end set diff = num - min_num if diff > max_diff begin set max_diff = diff end end return max_diff end function
def max_difference(nums): max_diff = 0 min_num = nums[0] for num in nums: if num < min_num: min_num = num diff = num - min_num if diff > max_diff: max_diff = diff return max_diff
Python
jtatman_500k
function convert_service_to_p tot_s_y s_fueltype_tech begin if tot_s_y == 0 begin set _total_service = 0 end else begin set _total_service = 1 / tot_s_y end comment Iterate all technologies and calculate fraction of total service set s_tech_p = dict for tech_services in values s_fueltype_tech begin for tuple tech serv...
def convert_service_to_p(tot_s_y, s_fueltype_tech): if tot_s_y == 0: _total_service = 0 else: _total_service = 1 / tot_s_y # Iterate all technologies and calculate fraction of total service s_tech_p = {} for tech_services in s_fueltype_tech.values(): for tech, service_tech i...
Python
nomic_cornstack_python_v1
function available self available begin set _available = available end function
def available(self, available): self._available = available
Python
nomic_cornstack_python_v1
function assign_sample_to_project sample_name begin if search string Val sample_name begin set project_name = string Validation end else if search string NTC sample_name begin set project_name = string Negative Control (NTC) end else if search string QC sample_name begin set project_name = string Positive Control end e...
def assign_sample_to_project(sample_name): if re.search("Val", sample_name): project_name = "Validation" elif re.search("NTC", sample_name): project_name = "Negative Control (NTC)" elif re.search("QC", sample_name): project_name = "Positive Control" else: project_nam...
Python
nomic_cornstack_python_v1
function delete self model begin pass end function
def delete(self, model): pass
Python
nomic_cornstack_python_v1
function add_db_session_check self session query_cb=none at_least_one_model=none level=1 begin if query_cb is none begin set query_cb = call _at_least_one at_least_one_model end for binding in call _get_bindings session begin set tuple name cb = call _create_db_engine_check session binding query_cb append _checks tuple...
def add_db_session_check( self, session: sqlalchemy.orm.scoping.scoped_session, query_cb: Optional[Callable[[sqlalchemy.orm.scoping.scoped_session], Any]] = None, at_least_one_model: Optional[object] = None, level: int = 1, ) -> None: if query_cb is None: ...
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn import torch.nn.functional as F from neural_networks.GameOfLifeBase import GameOfLifeBase class GameOfLifeReverseOneStep extends GameOfLifeBase begin string This implements the life_step() inverse function as a Neural Network function This model of trying to predict exact inputs plate...
import torch import torch.nn as nn import torch.nn.functional as F from neural_networks.GameOfLifeBase import GameOfLifeBase class GameOfLifeReverseOneStep(GameOfLifeBase): """ This implements the life_step() inverse function as a Neural Network function This model of trying to predict exact inputs plat...
Python
zaydzuhri_stack_edu_python
function obtain_filters_mask model threshold cba_index prune_index begin set num_pruned_bn = 0 set num_total_bn = 0 set num_remain_filters = list set mask_remain_filters = list comment The number of filters reserved must be a multiple of 8 set int_multiple = 8 set filter_switch = list range 0 1024 int_multiple commen...
def obtain_filters_mask(model, threshold, cba_index, prune_index): num_pruned_bn = 0 num_total_bn = 0 num_remain_filters = [] mask_remain_filters = [] # The number of filters reserved must be a multiple of 8 int_multiple = 8 filter_switch = list(range(0, 1024, int_multiple)) # cba_ind...
Python
nomic_cornstack_python_v1
function new_search user begin comment asks the user to choose a category among the categories registered set category = call category_selection set category = call Category name=category comment asks the user to choose among products registered in this category set product = call product_selection category=category se...
def new_search(user): # asks the user to choose a category among the categories registered category = category_selection() category = Category(name=category) # asks the user to choose among products registered in this category product = product_selection(category=category) product = Product(lin...
Python
nomic_cornstack_python_v1
import os import struct import numpy as np import scipy.misc function load_mnist path kind=string train begin string Load MNIST data from `path` set labels_path = join path path string %s-labels.idx1-ubyte % kind set images_path = join path path string %s-images.idx3-ubyte % kind with open labels_path string rb as lbpa...
import os import struct import numpy as np import scipy.misc def load_mnist(path, kind='train'): """Load MNIST data from `path`""" labels_path = os.path.join(path, '%s-labels.idx1-ubyte' % kind) images_path = os.path.join(path, ...
Python
zaydzuhri_stack_edu_python
comment -*-coding:utf-8-*- import sys set input = readline function main begin set N = integer input set p = list comprehension integer i for i in split input set ans = 0 for i in range N - 1 begin if p at i == i + 1 and p at i + 1 == i + 2 begin set tuple p at i p at i + 1 = tuple p at i + 1 p at i set ans = ans + 1 e...
#-*-coding:utf-8-*- import sys input=sys.stdin.readline def main(): N = int(input()) p = [int(i) for i in input().split()] ans = 0 for i in range(N-1): if p[i] == i + 1 and p[i+1] == i+2: p[i], p[i+1] = p[i+1], p[i] ans += 1 for i in range(N-1): if p[i] == i ...
Python
zaydzuhri_stack_edu_python
function get_all_super_names value begin if has attribute value string __class__ begin comment old style class set klass = __class__ set class_name = __name__ set bases = call get_oldstyle_bases klass set bases_names = list comprehension __name__ for x in bases end else begin comment new style set t = type value set cl...
def get_all_super_names(value): if hasattr(value, '__class__'): # old style class klass = value.__class__ class_name = klass.__name__ bases = get_oldstyle_bases(klass) bases_names = [x.__name__ for x in bases] else: # new style t = type(value) clas...
Python
nomic_cornstack_python_v1
function check_credentials self **kwargs begin raise call NotImplementedError string You must implement the 'check_credentials' method on your 'Authentication' class. end function
def check_credentials(self, **kwargs): raise NotImplementedError("You must implement the 'check_credentials' method on your 'Authentication' class.")
Python
nomic_cornstack_python_v1
function format_name name begin comment ajoute le point pour une initiale (lettre seule) set singleletter = compile string \b(?P<letter>[A-Z])(?!\.)\b set name = sub string \g<letter>. name comment passe en minuscule sauf premiere lettre set wordpattern = compile string \b(?P<word>\w+)\b set titlefun = lambda match -> ...
def format_name( name ): # ajoute le point pour une initiale (lettre seule) singleletter = re.compile( r'\b(?P<letter>[A-Z])(?!\.)\b' ) name = singleletter.sub('\g<letter>.', name) # passe en minuscule sauf premiere lettre wordpattern = re.compile( r'\b(?P<word>\w+)\b' ) titlefun = lambda match...
Python
nomic_cornstack_python_v1
import Motor import pigpio import numpy as np import time import os import serial import math from time import sleep import threading comment Motor A set m1DIR = 6 set m1PWM = 13 comment Motor A set m2DIR = 19 set m2PWM = 26 set left = call Motor m1DIR m1PWM set right = call Motor m2DIR m2PWM call Inverse comment motor...
import Motor import pigpio import numpy as np import time import os import serial import math from time import sleep import threading #Motor A m1DIR = 6 m1PWM = 13 #Motor A m2DIR = 19 m2PWM = 26 left = Motor.Motor(m1DIR,m1PWM) right = Motor.Motor(m2DIR,m2PWM) left.Inverse() ########### motor speeds####### # straig...
Python
zaydzuhri_stack_edu_python
import os import time import tensorflow as tf from tensorflow.python.ops import control_flow_ops from tensorflow.python.training import moving_averages function prelu inp name begin with call variable_scope name begin set i = integer call get_shape at - 1 set alpha = call make_var string alpha shape=tuple i set output ...
import os import time import tensorflow as tf from tensorflow.python.ops import control_flow_ops from tensorflow.python.training import moving_averages def prelu(inp, name): with tf.variable_scope(name): i = int(inp.get_shape()[-1]) alpha = make_var('alpha', shape=(i,)) output = tf.nn.relu(...
Python
zaydzuhri_stack_edu_python
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier set data = list list 5 2 4 1 3 list 7 3 5 1 2 list 9 5 4 2 3 set labels = list string iris-setosa string iris-versicolor string iris-virginica set df = call DataFrame data columns=list string sep...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier data = [[5,2,4,1,3], [7,3,5,1,2], [9,5,4,2,3]] labels = ['iris-setosa', 'iris-versicolor', 'iris-virginica'] df = pd.DataFrame(data, columns=['sepal_length', 'sepal_width', 'petal_length', 'pet...
Python
flytech_python_25k
comment -*- coding: utf-8 -*- import nltk set pos_list = list string VB string JJ string NN string RB set pos_NN = list string NN string NNS string NNP string NNPS string PRP string WP set negators = list with open string negators.txt as f begin for line in f begin if strip line begin append negators strip line end en...
# -*- coding: utf-8 -*- import nltk pos_list = ["VB", "JJ", "NN", "RB"] pos_NN = ["NN", "NNS", "NNP", "NNPS", "PRP", "WP"] negators = [] with open("negators.txt") as f: for line in f: if line.strip(): negators.append(line.strip()) # feature functions def unigram_pos_f(y_set): f = lambd...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment There are 100 cars set cars = 100 comment Every car has 4.0 seats set space_in_a_car = 4.0 comment There are total 30 drivers set drivers = 30 comment There are total 90 passengers set passengers = 91 comment how many cars have no driver, cars number substracs the drivers number se...
# -*- coding: utf-8 -*- # There are 100 cars cars = 100 # Every car has 4.0 seats space_in_a_car = 4.0 # There are total 30 drivers drivers = 30 # There are total 90 passengers passengers = 91 # how many cars have no driver, cars number substracs the drivers number cars_not_driven = cars - drivers # how many cars have...
Python
zaydzuhri_stack_edu_python
function __init__ self n init_pdf p_bt_btp kalman_args kalman_class=KalmanFilter begin if not is instance n int or n < 1 begin raise call TypeError string n must be a positive integer end if not is instance init_pdf Pdf or not is instance p_bt_btp CPdf begin raise call TypeError string init_pdf must be a Pdf and p_bt_b...
def __init__(self, n, init_pdf, p_bt_btp, kalman_args, kalman_class = KalmanFilter): if not isinstance(n, int) or n < 1: raise TypeError("n must be a positive integer") if not isinstance(init_pdf, Pdf) or not isinstance(p_bt_btp, CPdf): raise TypeError("init_pdf must be a Pdf and...
Python
nomic_cornstack_python_v1
function test_choose_function begin set c = call ChatBot assert has attribute choose_function string __call__ end function
def test_choose_function(): c = ChatBot() assert hasattr(c.choose_function, '__call__')
Python
nomic_cornstack_python_v1
function fetch_outlet_data phone_number begin set encoded_arg = quote phone_number comment noqa: E501 set endpoint = string https://api.coins.asia/v4/payout-outlets/?language=en&per_page=100&recipient_info= { encoded_arg } &recipient_type=msisdn try begin set resp = call fetch string GET endpoint end except Exception a...
def fetch_outlet_data(phone_number): encoded_arg = urllib.parse.quote(phone_number) endpoint = f'https://api.coins.asia/v4/payout-outlets/?language=en&per_page=100&recipient_info={encoded_arg}&recipient_type=msisdn' # noqa: E501 try: resp = fetch('GET', endpoint) except Exception as e: ...
Python
nomic_cornstack_python_v1
function test_adding_album_twice_forced self begin call add_mp3 filename=string 1.mp3 set tuple added status = call add_album filenames assert equal added true assert equal call get_album_count 1 call add_mp3 filename=string 2.mp3 set tuple added status = call add_album filenames string ep force_update=true assert equa...
def test_adding_album_twice_forced(self): self.add_mp3(filename='1.mp3') (added, status) = self.app.add_album(self.filenames) self.assertEqual(added, True) self.assertEqual(self.get_album_count(), 1) self.add_mp3(filename='2.mp3') (added, status) = self.app.add_album(sel...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from pyeay.dbcac.conexiondb import Ejecutar_SQL from formEAY.constantesCAC.constantesCAC import BasesDeDatos set base_nom_funcion = string dbEmpleados/ class Get_empleados begin decorator staticmethod function lista_basica area_trabajo activo=true begin string Obtiene una lista de los empl...
# -*- coding: utf-8 -*- from pyeay.dbcac.conexiondb import Ejecutar_SQL from formEAY.constantesCAC.constantesCAC import BasesDeDatos base_nom_funcion = 'dbEmpleados/' class Get_empleados(): @staticmethod def lista_basica(area_trabajo, activo=True): """ Obtiene una lista de los empleados, c...
Python
zaydzuhri_stack_edu_python
import numpy as np from matplotlib import pyplot as plt set fig2 = figure set p21 = call add_subplot 111 title=string Mean of all s sets xlabel=string set ylabel=string mean set data = call normal 0 1 10000 set sets = split np data 200 set means = list for i in range 200 begin append means mean np sets at i end scatte...
import numpy as np from matplotlib import pyplot as plt fig2 = plt.figure() p21 = fig2.add_subplot(111,title = 'Mean of all s sets',xlabel='set',ylabel='mean') data = np.random.normal(0,1,10000) sets = np.split(data,200) means = [] for i in range(200): means.append(np.mean(sets[i])) p21.scatter([i for i in range(...
Python
zaydzuhri_stack_edu_python
function handle_error self error begin set handler = get attribute downloader string errorhandler none if not handler begin return end try begin call handler error ep end except Exception as er begin print format string [Crawler] Failed to handle error: {} er end end function
def handle_error(self, error): handler = getattr(self.downloader, "errorhandler", None) if not handler: return try: handler(error, self.ep) except Exception as er: print("[Crawler] Failed to handle error: {}".format(er))
Python
nomic_cornstack_python_v1
function __init__ self begin set isEndOfWord = false set children = list none * 26 end function
def __init__(self): self.isEndOfWord=False self.children=[None]*26
Python
nomic_cornstack_python_v1
function run_from_argv self argv begin set parser = call create_parser argv at 0 argv at 1 set tuple options args = call parse_args argv at slice 2 : : end function
def run_from_argv(self, argv): parser = self.create_parser(argv[0], argv[1]) options, args = parser.parse_args(argv[2:])
Python
nomic_cornstack_python_v1
string Address book challenge import json comment Constants set ADDRESS_BOOK_FILE = string address_book.dat function show_menu begin string Display the menu of available commands and return the selected choice end function
''' Address book challenge ''' import json # Constants ADDRESS_BOOK_FILE = "address_book.dat" def show_menu(): '''Display the menu of available commands and return the selected choice'''
Python
zaydzuhri_stack_edu_python
function cross str1 str2 begin return list comprehension x + y for x in str1 for y in str2 end function print call cross string abc string def
def cross(str1,str2): return [ x+y for x in str1 for y in str2] print(cross('abc','def'))
Python
zaydzuhri_stack_edu_python
function _callback_velocity self uav_velocity_stamped begin comment type: (PoseStamped) -> None set uav_velocity_stamped = uav_velocity_stamped return end function
def _callback_velocity(self, uav_velocity_stamped): # type: (PoseStamped) -> None self.uav_velocity_stamped = uav_velocity_stamped return
Python
nomic_cornstack_python_v1
string 一个句子的分词,所有的3元词组都有组合,每个组合左边,右边的作为统计熵 2-11个字作为的切词,就是在 把这个片段看作词的基础上,看能不能继续组合成词。 string 上一个版本的理论基础,是在已有jieba分词的基础上,进行词语之间的组合,作为新词挖掘; n个词组合为新词的情况; 任意两个词,找出所有的左信息,右信息进行统计; 此次优化:1.如果 任意一个短语切片假定为词语, 看左右信息熵,左右很活跃,此词成立,左右不活跃,进行组合【直接不成立】 【的电影 电影院】,无法计算 内部聚合度 优化方向: 1.过滤掉pmi低于一定阈值的,2.过滤掉 entropy 低于一定阈值的,3. 调节idf权重 import mat...
""" 一个句子的分词,所有的3元词组都有组合,每个组合左边,右边的作为统计熵 2-11个字作为的切词,就是在 把这个片段看作词的基础上,看能不能继续组合成词。 """ """ 上一个版本的理论基础,是在已有jieba分词的基础上,进行词语之间的组合,作为新词挖掘; n个词组合为新词的情况; 任意两个词,找出所有的左信息,右信息进行统计; 此次优化:1.如果 任意一个短语切片假定为词语, 看左右信息熵,左右很活跃,此词成立,左右不活跃,进行组合【直接不成立】 【的电影 电影院】,无法计算 内部聚合度 优化方向: 1.过滤掉pmi低于一定阈值的,2.过滤掉 entropy 低...
Python
zaydzuhri_stack_edu_python
function _try_composite a d n s begin if power a d n == 1 begin return false end for i in range s begin if power a 2 ^ i * d n == n - 1 begin return false end end comment n is definitely composite return true end function
def _try_composite(a, d, n, s): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True # n is definitely composite
Python
nomic_cornstack_python_v1
function province self begin return _province end function
def province(self): return self._province
Python
nomic_cornstack_python_v1
comment ------------------------------------------------------------------------- comment Note: please don't use any additional package except the following packages import numpy as np comment ------------------------------------------------------------------------- string Problem 1: In this problem, you will get famil...
#------------------------------------------------------------------------- # Note: please don't use any additional package except the following packages import numpy as np #------------------------------------------------------------------------- ''' Problem 1: In this problem, you will get familiar with matri...
Python
zaydzuhri_stack_edu_python
function sql_get_oids self where=none begin string Query source database for a distinct list of oids. set table = get lconfig string table set db = get lconfig string db_schema_name or get lconfig string db set _oid = get lconfig string _oid if call is_array _oid begin comment get the db column, not the field alias set...
def sql_get_oids(self, where=None): ''' Query source database for a distinct list of oids. ''' table = self.lconfig.get('table') db = self.lconfig.get('db_schema_name') or self.lconfig.get('db') _oid = self.lconfig.get('_oid') if is_array(_oid): _oid =...
Python
jtatman_500k
import cv2 import boto3 import numpy as np import random import string class ImgReader begin function __init__ self begin set topic_numbers = 7 end function function read_img self image_path begin set img = call imread image_path IMREAD_COLOR return img end function function check_pixel_size self img begin set tuple h ...
import cv2 import boto3 import numpy as np import random import string class ImgReader: def __init__(self): self.topic_numbers = 7 def read_img(self, image_path): img = cv2.imread(image_path, cv2.IMREAD_COLOR) return img def check_pixel_size(self, img): h, w, c = img.shape...
Python
zaydzuhri_stack_edu_python
function goto_assignments request_data begin string Go to assignements worker. set code = request_data at string code set line = request_data at string line + 1 set column = request_data at string column set path = request_data at string path comment encoding = request_data['encoding'] set encoding = string utf-8 set s...
def goto_assignments(request_data): """ Go to assignements worker. """ code = request_data['code'] line = request_data['line'] + 1 column = request_data['column'] path = request_data['path'] # encoding = request_data['encoding'] encoding = 'utf-8' script = jedi.Script(code, line,...
Python
jtatman_500k
function IsTabVisible self tabPage tabOffset dc wnd begin if not dc or not call IsOk begin return false end set page_count = length _pages set button_count = length _buttons call Render dc wnd comment Hasn't been rendered yet assume it's visible if length _tab_close_buttons < page_count begin return true end if _agwFla...
def IsTabVisible(self, tabPage, tabOffset, dc, wnd): if not dc or not dc.IsOk(): return False page_count = len(self._pages) button_count = len(self._buttons) self.Render(dc, wnd) # Hasn't been rendered yet assume it's visible if len(self._...
Python
nomic_cornstack_python_v1
function is_png filename begin return string .png in filename end function
def is_png(filename): return '.png' in filename
Python
nomic_cornstack_python_v1
function compare_states self state_keys begin return all generator expression call compare_state k for k in state_keys end function
def compare_states(self, state_keys): return all(self.compare_state(k) for k in state_keys)
Python
nomic_cornstack_python_v1
function plot_efficiencies self phase file_path size=tuple 12 8 plot_fit=true begin comment Inform the user of the fact that the efficiencies are being calculated and plotted info string Calculating and plotting the efficiencies for the + phase_names at phase + string ... comment Initialize figure with the appropriate ...
def plot_efficiencies(self, phase, file_path, size=(12, 8), plot_fit=True): # Inform the user of the fact that the efficiencies are being calculated and plotted log.info("Calculating and plotting the efficiencies for the " + phase_names[phase] + "...") # Initialize figure with the appropriate ...
Python
nomic_cornstack_python_v1
function for_meters cls meter_x meter_y zoom begin string Creates a tile from X Y meters in Spherical Mercator EPSG:900913 set point = call from_meters meter_x=meter_x meter_y=meter_y set tuple pixel_x pixel_y = call pixels zoom=zoom return call for_pixels pixel_x=pixel_x pixel_y=pixel_y zoom=zoom end function
def for_meters(cls, meter_x, meter_y, zoom): """Creates a tile from X Y meters in Spherical Mercator EPSG:900913""" point = Point.from_meters(meter_x=meter_x, meter_y=meter_y) pixel_x, pixel_y = point.pixels(zoom=zoom) return cls.for_pixels(pixel_x=pixel_x, pixel_y=pixel_y, zoom=zoom)
Python
jtatman_500k
function get_all_children self begin string Returns all unique children (dependencies) for all batches of this Executor. The Taskmaster can recognize when it's already evaluated a Node, so we don't have to make this list unique for its intended canonical use case, but we expect there to be a lot of redundancy (long lis...
def get_all_children(self): """Returns all unique children (dependencies) for all batches of this Executor. The Taskmaster can recognize when it's already evaluated a Node, so we don't have to make this list unique for its intended canonical use case, but we expect there to be a...
Python
jtatman_500k
function __init__ self address port=3000 tls_name=none timeout=5 user=none password=none auth_mode=INTERNAL ssl_context=none consider_alumni=false use_services_alt=false begin set logger = call getLogger string asadm set remote_system_command_prompt = string [#$] call _update_IP address port set port = port comment TOD...
def __init__( self, address, port=3000, tls_name=None, timeout=5, user=None, password=None, auth_mode=constants.AuthMode.INTERNAL, ssl_context=None, consider_alumni=False, use_services_alt=False, ): self.logger = logging...
Python
nomic_cornstack_python_v1
import socket set HEADER_LENGTH = 10 set IP = string 127.0.0.1 set PORT = 2409 set server_socket = call socket AF_INET SOCK_STREAM print string Server Started call connect tuple IP PORT print string Server connected function recive begin set byt = call recv 1240 print byt set stri = input string Please Type Message : s...
import socket HEADER_LENGTH = 10 IP = "127.0.0.1" PORT = 2409 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Server Started") server_socket.connect((IP,PORT)) print("Server connected") def recive(): byt = server_socket.recv(1240) print(byt) stri = input("Please Type Message : ") meg = by...
Python
zaydzuhri_stack_edu_python
function find_financials self begin call get_financials end function
def find_financials(self) -> None: self.builder.get_financials()
Python
nomic_cornstack_python_v1
function writeServerStatus self who avatar_count object_count begin if not udpSock begin debug string Unable to log server Status: no udpSock. return end comment Make who be a string (it might be passed in as an integer) comment who = str(who) set who = string comment Count up the number of bytes in the packet set len...
def writeServerStatus(self, who, avatar_count, object_count): if not self.udpSock: self.notify.debug("Unable to log server Status: no udpSock.") return # Make who be a string (it might be passed in as an integer) #who = str(who) who=""; # Count up the nu...
Python
nomic_cornstack_python_v1
comment first you need to import os module import os from http.server import HTTPServer , CGIHTTPRequestHandler comment The server must be created under the current directory change directory string . comment as an http server it should listen to port 80 or 8080 comment creating object set server_object = call HTTPServ...
# first you need to import os module import os from http.server import HTTPServer, CGIHTTPRequestHandler # The server must be created under the current directory os.chdir('.') # as an http server it should listen to port 80 or 8080 # creating object server_object = HTTPServer(server_address=('', 80), RequestHandlerCla...
Python
zaydzuhri_stack_edu_python
function itkResampleImageFilterIRGBUC3IRGBUC3_cast obj begin return call itkResampleImageFilterIRGBUC3IRGBUC3_cast obj end function
def itkResampleImageFilterIRGBUC3IRGBUC3_cast(obj: 'itkLightObject') -> "itkResampleImageFilterIRGBUC3IRGBUC3 *": return _itkResampleImageFilterPython.itkResampleImageFilterIRGBUC3IRGBUC3_cast(obj)
Python
nomic_cornstack_python_v1
function get_storage self defined linkage symbol_table begin if defined == UNDEFINED or not call is_object begin set storage = none end else if linkage or storage == STATIC begin set storage = STATIC end else begin set storage = AUTOMATIC end return storage end function
def get_storage(self, defined, linkage, symbol_table): if defined == symbol_table.UNDEFINED or not self.ctype.is_object(): storage = None elif linkage or self.storage == self.STATIC: storage = symbol_table.STATIC else: storage = symbol_table.AUTOMATIC ...
Python
nomic_cornstack_python_v1
from Database import Database class Department begin set id = none set name = none function __init__ self tuple_data=none begin if tuple_data begin set id = tuple_data at 0 set name = tuple_data at 1 end end function comment print("Department class is initialized") function save self begin execute _cursor string insert...
from Database import Database class Department: id = None name = None def __init__(self,tuple_data = None): if(tuple_data): self.id = tuple_data[0] self.name = tuple_data[1] #print("Department class is initialized") def save(self): Database._cursor.exe...
Python
zaydzuhri_stack_edu_python
string python包 1.任何有__init__.py文件的目录都可以作为Python的一个包 2.import package.module语句引入package包下的module.py文件 a.该条语句将会在package包下查找__init__.py文件,并执行其顶层的语句 b.然后查找package包下的module.py文件,并执行文件中所有顶层语句,module.py中的变量,函数和类的定义都可以通过pack.module命名空间获取 from foo.main.com.aaron.python.oo.ClassLearn import Student string python算术运算符 1. + 2. - 3...
""" python包 1.任何有__init__.py文件的目录都可以作为Python的一个包 2.import package.module语句引入package包下的module.py文件 a.该条语句将会在package包下查找__init__.py文件,并执行其顶层的语句 b.然后查找package包下的module.py文件,并执行文件中所有顶层语句,module.py中的变量,函数和类的定义都可以通过pack.module命名空间获取 """ from foo.main.com.aaron.python.oo.ClassLearn import Student """...
Python
zaydzuhri_stack_edu_python
function addTB self tb begin set tb_tuple = tuple call getLabel at string text tb if tb_tuple not in _tbMasterList begin append _tbMasterList tb_tuple end end function
def addTB(self, tb): tb_tuple = (tb.getLabel()['text'], tb) if tb_tuple not in self._tbMasterList: self._tbMasterList.append(tb_tuple)
Python
nomic_cornstack_python_v1
comment Copyright (C) 2011 by Brandon Invergo (b.invergo@gmail.com) comment This code is part of the Biopython distribution and governed by its comment license. Please see the LICENSE file that should have been included comment as part of this package. from __future__ import with_statement import os import os.path impo...
# Copyright (C) 2011 by Brandon Invergo (b.invergo@gmail.com) # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. from __future__ import with_statement import os import os.path import subprocess import re...
Python
zaydzuhri_stack_edu_python
import pandas as pd from scipy import stats from helpers.process import get_sub , get_dfs , make_comparison_dataframe , calculate_forecast_errors , inverse_boxcox from prophet import Prophet comment Import the data set tuple df act quizz = call get_dfs comment Format the data set sub_a = call get_sub act from_date=stri...
import pandas as pd from scipy import stats from helpers.process import get_sub, get_dfs, make_comparison_dataframe, calculate_forecast_errors, inverse_boxcox from prophet import Prophet # Import the data df, act, quizz = get_dfs() # Format the data sub_a = get_sub(act, from_date='09/2019') sub_q = get_sub(quizz, fro...
Python
zaydzuhri_stack_edu_python
function end self begin info string MesosExecutor has been asked to end comment Wait for running tasks to all be complete while running or queued_tasks begin call sync info string Waiting for running or queued tasks to complete sleep 10 end call sync call stop end function
def end(self): logging.info("MesosExecutor has been asked to end") # Wait for running tasks to all be complete while self.running or self.queued_tasks: self.sync() logging.info("Waiting for running or queued tasks to complete") time.sleep(10) self.sy...
Python
nomic_cornstack_python_v1
comment 汉诺塔结构 string 规则: 1.n=1:直接把A上的数据放到C上 2.n=2:把A上的数据先放到B上一个,再将A上剩余的一个数据放到C上,再将B上的数据放到C上 2.n=n:把A上的n-1个数据借助C放到B上,再将A上剩余的一个数据放到C上让后再将B上的数据放到C上 function hano n a b c begin if n == 1 begin print a string --> c return none end string if n == 2: print(a,"-->",b) print(a,"-->",c) print(b,"-->",c) return None comment 把n-1个...
#汉诺塔结构 ''' 规则: 1.n=1:直接把A上的数据放到C上 2.n=2:把A上的数据先放到B上一个,再将A上剩余的一个数据放到C上,再将B上的数据放到C上 2.n=n:把A上的n-1个数据借助C放到B上,再将A上剩余的一个数据放到C上让后再将B上的数据放到C上 ''' def hano(n,a,b,c): if n == 1: print(a,"-->",c) return None ''' if n == 2: print(a,"-->",b) print(a,"-->",c) pr...
Python
zaydzuhri_stack_edu_python
import praw import re import time import mysql.connector from timeconvert import timeconvert comment Initialize Reddit instance set reddit = call Reddit client_id=string redacted client_secret=string redacted user_agent=string my user agent username=string SwimConverter password=string redacted comment Specificy the su...
import praw import re import time import mysql.connector from timeconvert import timeconvert # Initialize Reddit instance reddit = praw.Reddit(client_id='redacted', client_secret='redacted', user_agent='my user agent', username='SwimConverter', ...
Python
zaydzuhri_stack_edu_python
string Module to handle Users page and user connections from time import sleep from box import Box import userinterface import userdata function display_no_users_on_page page_num begin string Display on pages with no posts print string - * 50 print string No users on page { page_num } . Please go back a page. print str...
"""Module to handle Users page and user connections""" from time import sleep from box import Box import userinterface import userdata def display_no_users_on_page(page_num): """Display on pages with no posts""" print('-' * 50) print(f'No users on page {page_num}. Please go back a page.') print('-'...
Python
zaydzuhri_stack_edu_python
comment encoding: utf-8 import random from copy import deepcopy from tools import random_player function karasu_point board turn begin set board_flat = sum board list set black = count board_flat 2 set white = count board_flat 1 if turn == 0 begin return black - white end else begin return white - black end end functio...
#encoding: utf-8 import random from copy import deepcopy from tools import random_player def karasu_point(board,turn): board_flat = sum(board.board,[]) black = board_flat.count(2) white = board_flat.count(1) if turn == 0: return black - white else: return white - black def karas...
Python
zaydzuhri_stack_edu_python
string Template-based configuration file import os from UserDict import DictMixin from initools.configparser import ConfigParser , NoOptionError from tempita import Template set __all__ = list string Configuration string asbool string lines class TmplParser extends ConfigParser begin string Parser customized for use wi...
"""Template-based configuration file""" import os from UserDict import DictMixin from initools.configparser import ConfigParser, NoOptionError from tempita import Template __all__ = ['Configuration', 'asbool', 'lines'] class TmplParser(ConfigParser): """Parser customized for use with this configuration""" g...
Python
zaydzuhri_stack_edu_python
function _enrich_commit_with_tags self commits=tuple begin if not commits begin return commits end try begin set tags = call get_tags end except APIException as ex begin error string An error occurred while fetching tags to enrich commit history: HTTP { status_code } - { string ex } raise call NoTagsCouldBeFetchedExcep...
def _enrich_commit_with_tags(self, commits: list = ()): if not commits: return commits try: tags = self.tags_provider.get_tags() except APIException as ex: logger.error( f'An error occurred while fetching tags to enrich commit history: HTTP {e...
Python
nomic_cornstack_python_v1
function GetAllParameters self path service=none begin set param_dict = none set _model_container = none if length _loaded_services == 0 begin return none end else if length _loaded_services == 1 begin set _model_container = call GetObject set param_dict = call GetAllParameters path end comment now that we're done with...
def GetAllParameters(self, path, service=None): param_dict = None _model_container = None if len(self._loaded_services) == 0: return None elif len(self._loaded_services) == 1: _model_container = self._loaded_services[0].GetObject() ...
Python
nomic_cornstack_python_v1
function metric_identifier self metric_identifier begin if metric_identifier is none begin comment noqa: E501 raise call ValueError string Invalid value for `metric_identifier`, must not be `None` end set _metric_identifier = metric_identifier end function
def metric_identifier(self, metric_identifier: str): if metric_identifier is None: raise ValueError('Invalid value for `metric_identifier`, must not be `None`') # noqa: E501 self._metric_identifier = metric_identifier
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider , Rule from items import MaoyanfilmItem class MaoyanSpider extends CrawlSpider begin set name = string maoyan set allowed_domains = list string maoyan.com set start_urls = list string https...
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from ..items import MaoyanfilmItem class MaoyanSpider(CrawlSpider): name = 'maoyan' allowed_domains = ['maoyan.com'] start_urls = ['https://maoyan.com/board/4/'] rules = (...
Python
zaydzuhri_stack_edu_python
import warnings import sklearn as skl import numpy as np from sklearn.base import BaseEstimator , ClassifierMixin , TransformerMixin function crossValidManyClassifiers classifiers X y cv_param=10 begin set listToReturn = list for clf in classifiers begin set scores = cross val score clf X y cv=cv_param set CVscore = m...
import warnings import sklearn as skl import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin def crossValidManyClassifiers(classifiers, X, y, cv_param=10): listToReturn=[] for clf in classifiers: scores = skl.cross_validation.cross_val_score(clf, X, y, cv=cv_param...
Python
zaydzuhri_stack_edu_python
function _move self file begin set ext = lower replace call splitext file at 1 string . string set ftype = false for e in keys cfg at string file_types begin if ext in cfg at string file_types at e begin set ftype = e break end end set dest = join path today_dir ftype try begin move file dest end except any begin set f...
def _move(self, file): ext = os.path.splitext(file)[1].replace('.', '').lower() ftype = False for e in self.cfg['file_types'].keys(): if ext in self.cfg['file_types'][e]: ftype = e break dest = os.path.join(self.today_dir, ftype) try: ...
Python
nomic_cornstack_python_v1
import RPi.GPIO as GPIO import time call setwarnings false call setmode BCM class Step_motor begin function __init__ self IN4A IN3B IN2C IN1D begin set forward_seq = list string 1100 string 0110 string 0011 string 1001 set back_seq = list string 1100 string 1001 string 0011 string 0110 set IN4A = IN4A setup GPIO IN4A O...
import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) class Step_motor: def __init__(self,IN4A,IN3B,IN2C,IN1D): self.forward_seq=['1100','0110','0011','1001'] self.back_seq=['1100','1001','0011','0110'] self.IN4A=IN4A GPIO.setup(self.IN4A,GPIO.OUT) ...
Python
zaydzuhri_stack_edu_python
function sub self value begin set value = call bound value - value minvalue maxvalue call updateSurface end function
def sub(self, value): self.value = bound(self.value - value, self.minvalue, self.maxvalue) self.updateSurface()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment encoding: utf-8 class Solution begin comment @param {integer[]} height comment @return {integer} function largestRectangleArea self height begin set i = 0 set max_a = 0 set s = list set h = height at slice : : append h 0 while i < length h begin if not s or h at i >= h at s at -...
#!/usr/bin/env python # encoding: utf-8 class Solution: # @param {integer[]} height # @return {integer} def largestRectangleArea(self, height): i = 0 max_a = 0 s = [] h = height[:] h.append(0) while i < len(h): if not s or h[i] >= h[s[-1]]: ...
Python
zaydzuhri_stack_edu_python
function Get_AxisOverrun_Value self begin set zor = 0 set yor = 0 set xor = 0 if call __readFromRegister __REG_R_STATUS_REG __MASK_STATUS_REG_ZYXOR == 1 begin set zor = call __readFromRegister __REG_R_STATUS_REG __MASK_STATUS_REG_ZOR set yor = call __readFromRegister __REG_R_STATUS_REG __MASK_STATUS_REG_YOR set xor = c...
def Get_AxisOverrun_Value(self): zor = 0 yor = 0 xor = 0 if self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_ZYXOR) == 0x01: zor = self.__readFromRegister(self.__REG_R_STATUS_REG, self.__MASK_STATUS_REG_ZOR) yor = self.__readFromRegist...
Python
nomic_cornstack_python_v1
function create_path path begin if not exists path path begin try begin make directories path end except OSError as e begin if errno != EEXIST begin raise end end end end function
def create_path(path): if not os.path.exists(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise
Python
nomic_cornstack_python_v1
import requests , json , re , os , sys , shutil from bs4 import BeautifulSoup set loop = 1 set string = string html set soup = call BeautifulSoup string string lxml set links = select soup string a set alreadydone = list for link in links begin try begin set linkhref = get link string href if find all string \d\d\d+ l...
import requests, json, re, os, sys, shutil from bs4 import BeautifulSoup loop = 1 string = """html""" soup = BeautifulSoup(string, "lxml") links = soup.select("a") alreadydone = [] for link in links: try: linkhref = link.get("href") if re.findall("\d\d\d+", linkhref)!=[] and re.findall("classes", linkhref)!=[] a...
Python
zaydzuhri_stack_edu_python
function list_items self shipment_id **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string callback begin return call list_items_with_http_info shipment_id keyword kwargs end else begin set data = call list_items_with_http_info shipment_id keyword kwargs return data end end function
def list_items(self, shipment_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.list_items_with_http_info(shipment_id, **kwargs) else: (data) = self.list_items_with_http_info(shipment_id, **kwargs) return data
Python
nomic_cornstack_python_v1
comment optimiser for a straight line function fit_line data error_func begin comment Generate initial guess for the line model comment slope = 0, inter. = mean(y_values) set l = call float32 list 0 mean np data at tuple slice : : 1 comment Plot initial guess (optional) set x_ends = call float32 list - 5 5 plot x_en...
def fit_line(data, error_func):#optimiser for a straight line #Generate initial guess for the line model l = np.float32([0, np.mean(data[:, 1])]) #slope = 0, inter. = mean(y_values) #Plot initial guess (optional) x_ends = np.float32([-5,5]) plt.plot(x_ends, l[0]*x_ends + l[1], 'm--', linewidth=...
Python
nomic_cornstack_python_v1
function load_new_model self spectral_model begin call calculate_FeH call beginResetModel set spectral_model = spectral_model comment Sort table by Z if spectral_model is not none begin comment First rows in table are fit elems comment Other rows are rt_abundances set num_fit_elems = length elements set elems = keys me...
def load_new_model(self, spectral_model): self.parent.calculate_FeH() self.beginResetModel() self.spectral_model = spectral_model # Sort table by Z if spectral_model is not None: # First rows in table are fit elems # Other rows are rt_abundances ...
Python
nomic_cornstack_python_v1
function _register self identifier constructor qualifier=none kwargs=none scope=none begin set key = call _get_registry_key identifier qualifier if key in _constructor_registry begin raise call ValueError string Ambiguous identifier: { identifier } . end set _constructor_registry at key = tuple constructor kwargs if sc...
def _register( self, identifier: NameOrInterface, constructor: Constructor, qualifier: t.Any = None, kwargs: Kwargs = None, scope: 'Scopes' = None, ): key = Container._get_registry_key(identifier, qualifier) if key in self._constructor_registry: ...
Python
nomic_cornstack_python_v1
import pygame from pygame.math import Vector2 class Player extends object begin function __init__ self game begin set clock = call Clock set minutes = 0 set seconds = 0 set milliseconds = 0 set font = call Font none 32 set last_minutes = 0 set last_seconds = 0 set last_milliseconds = 0 set best_minutes = 10000 set best...
import pygame from pygame.math import Vector2 class Player(object): def __init__(self, game): self.clock = pygame.time.Clock() self.minutes = 0 self.seconds = 0 self.milliseconds = 0 self.font = pygame.font.Font(None, 32) self.last_minutes = 0 self.last_sec...
Python
zaydzuhri_stack_edu_python
import random set carmichael = list 41041 62745 63973 75361 101101 126217 172081 188461 278545 340561 449065 552721 656601 658801 670033 748657 838201 852841 997633 1033669 1082809 1569457 1773289 2100901 2113921 2433601 2455921 comment Unmodified Algorithm function fermat p iterations begin if p == 1 begin return fals...
import random carmichael = [ 41041, 62745, 63973, 75361, 101101, 126217, 172081, 188461, 278545, 340561, 449065, 552721, 656601, 658801, 670033, 748657, 838201, 852841, 997633, 1033669, 1082809, 1569457, 1773289, 2100901, ...
Python
zaydzuhri_stack_edu_python
function size_term land_use destination_choice_coeffs begin set coeffs = destination_choice_coeffs comment first check for missing column in the land_use table set missing = coeffs at ? call isin columns if length missing > 0 begin warn string %s missing columns in land use % length index for v in values begin warn str...
def size_term(land_use, destination_choice_coeffs): coeffs = destination_choice_coeffs # first check for missing column in the land_use table missing = coeffs[~coeffs.index.isin(land_use.columns)] if len(missing) > 0: logger.warn("%s missing columns in land use" % len(missing.index)) ...
Python
nomic_cornstack_python_v1
import random import time try begin comment assert False import torch from transformers import GPT2LMHeadModel , GPT2Tokenizer comment initialize tokenizer and model from pretrained GPT2 model set tokenizer = call from_pretrained string gpt2 set model = call from_pretrained string gpt2 function predict input begin set ...
import random import time try: #assert False import torch from transformers import GPT2LMHeadModel, GPT2Tokenizer # initialize tokenizer and model from pretrained GPT2 model tokenizer = GPT2Tokenizer.from_pretrained('gpt2') model = GPT2LMHeadModel.from_pretrained('gpt2') def predict(input)...
Python
zaydzuhri_stack_edu_python
comment Os motoboys podem ter exclusividade com as lojas, mas as lojas não possuem exclusividade com os motoboys. comment Hoje existem 10 pedidos para serem retirados em 3 lojas. comment Quando eu executar o script passando apenas o motoboy ou não passando nenhum motoboy, preciso ver: comment Quem é o motoboy e quantos...
# Os motoboys podem ter exclusividade com as lojas, mas as lojas não possuem exclusividade com os motoboys. # # Hoje existem 10 pedidos para serem retirados em 3 lojas. # # Quando eu executar o script passando apenas o motoboy ou não passando nenhum motoboy, preciso ver: # Quem é o motoboy e quantos pedidos terá? # De ...
Python
zaydzuhri_stack_edu_python
function execute_total_dataframe_count_strategy dataframe begin debug string >>>>>>>>> Using total count strategy <<<<<<<<<<<< set total_rows = length index return total_rows end function
def execute_total_dataframe_count_strategy(dataframe): logging.debug('>>>>>>>>> Using total count strategy <<<<<<<<<<<<') total_rows = len(dataframe.index) return total_rows
Python
nomic_cornstack_python_v1
function unichr self *args **kwargs begin return character *args keyword kwargs end function
def unichr(self, *args, **kwargs): return chr(*args, **kwargs)
Python
nomic_cornstack_python_v1
comment noqa import pytest from algos import problems decorator call parametrize string string, expected list tuple string [] true tuple string [{()}] true tuple string ()() true tuple string ()[] true tuple string (] false tuple string ] false tuple string ( false tuple string ([)] false function test_balanced_bracket...
import pytest # noqa from algos import problems @pytest.mark.parametrize( "string, expected", [ ("[]", True), ("[{()}]", True), ("()()", True), ("()[]", True), ("(]", False), ("]", False), ("(", False), ("([)]", False), ], ) def test_balance...
Python
zaydzuhri_stack_edu_python