code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function moveZeroes self nums
begin
comment indexes of element 0
set zidx = list
for tuple idx val in enumerate nums
begin
if val == 0
begin
append zidx idx
end
end
comment pointer for index diffs. reduce by 1 on every pop.
set p = 0
for i in zidx
begin
set idx = i - p
pop nums idx
set p = p + 1
end
comment extend the... | def moveZeroes(self, nums: 'List[int]') -> 'None':
zidx = [] # indexes of element 0
for idx, val in enumerate(nums):
if val == 0:
zidx.append(idx)
p = 0 # pointer for index diffs. reduce by 1 on every pop.
for i in zidx:
idx = i - p
n... | Python | nomic_cornstack_python_v1 |
function bandname self
begin
if _properties at string bandname is none
begin
set _properties at string bandname = if expression string -w1- in filename then string wisew1 else if expression string -w2- in filename then string wisew2 else if expression string -w3- in filename then string wisew3 else if expression string... | def bandname(self):
if self._properties['bandname'] is None:
self._properties['bandname'] = "wisew1" if "-w1-" in self.filename \
else "wisew2" if "-w2-" in self.filename \
else "wisew3" if "-w3-" in self.filename \
... | Python | nomic_cornstack_python_v1 |
function Schalte x y z anaus
begin
if z == 0
begin
set ebene = 24
end
else
if z == 1
begin
set ebene = 23
end
else
if z == 2
begin
set ebene = 26
end
if x == 0
begin
if y == 0
begin
set col = 15
end
else
if y == 1
begin
set col = 16
end
else
if y == 2
begin
set col = 19
end
end
else
if x == 1
begin
if y == 0
begin
set ... | def Schalte(x,y,z,anaus):
if(z==0):
ebene=24
elif(z==1):
ebene=23
elif(z==2):
ebene=26
if(x==0):
if(y==0):
col=15
elif(y==1):
col=16
elif(y==2):
col=19
elif(x==1):
if(y==0):
col=13
elif(y=... | Python | zaydzuhri_stack_edu_python |
from google.cloud import speech_v1
from google.cloud.speech_v1 import enums
import io
import os
from os.path import expanduser
import audio_metadata
import subprocess
function sample_recognize filename
begin
string Transcribe a short audio file using synchronous speech recognition Args: local_file_path Path to local au... | from google.cloud import speech_v1
from google.cloud.speech_v1 import enums
import io
import os
from os.path import expanduser
import audio_metadata
import subprocess
def sample_recognize(filename):
"""
Transcribe a short audio file using synchronous speech recognition
Args:
local_file_path Path to... | Python | zaydzuhri_stack_edu_python |
from graphviz import Source
from graphviz import Graph
from graphviz import Digraph
class Gramatica
begin
function __init__ self id nombre noTerminales terminales So producciones
begin
set id = id
set nombre = nombre
set noTerminales = noTerminales
set terminales = terminales
set So = So
set producciones = producciones... | from graphviz import Source
from graphviz import Graph
from graphviz import Digraph
class Gramatica:
def __init__(self,id,nombre,noTerminales,terminales,So,producciones):
self.id = id
self.nombre = nombre
self.noTerminales = noTerminales
self.terminales = terminales
... | Python | zaydzuhri_stack_edu_python |
function giveBye id
begin
set tuple db cur = call connect
set query = string UPDATE players SET byes = byes + 1 WHERE id = %s;
set data = tuple id
execute cur query data
commit db
close cur
close db
end function | def giveBye(id):
db, cur = connect()
query = "UPDATE players SET byes = byes + 1 WHERE id = %s;"
data = (id,)
cur.execute(query, data)
db.commit()
cur.close()
db.close() | Python | nomic_cornstack_python_v1 |
comment --------------------------------------------------------
comment PYTHON PROGRAM DEFINITION
comment The knowledge a computer has of Python can be specified in 3 levels:
comment (1) Prelude knowledge --> The computer has it by default.
comment (2) Borrowed knowledge --> The computer gets this knowledge from 3rd p... | # --------------------------------------------------------
#
# PYTHON PROGRAM DEFINITION
#
# The knowledge a computer has of Python can be specified in 3 levels:
# (1) Prelude knowledge --> The computer has it by default.
# (2) Borrowed knowledge --> The computer gets this knowledge from 3rd party libraries defin... | Python | zaydzuhri_stack_edu_python |
import math
import nltk
import time
from collections import defaultdict
comment Constants to be used by you when you fill the functions
set START_SYMBOL = string *
set STOP_SYMBOL = string STOP
set MINUS_INFINITY_SENTENCE_LOG_PROB = - 1000
comment TODO: IMPLEMENT THIS FUNCTION
comment Calculates unigram, bigram, and tr... | import math
import nltk
import time
from collections import defaultdict
# Constants to be used by you when you fill the functions
START_SYMBOL = '*'
STOP_SYMBOL = 'STOP'
MINUS_INFINITY_SENTENCE_LOG_PROB = -1000
# TODO: IMPLEMENT THIS FUNCTION
# Calculates unigram, bigram, and trigram probabilities given a training co... | Python | zaydzuhri_stack_edu_python |
function test_grad_fit
begin
set grad = 2
set intercept = 1
set timing = call timing_parameters pix_x=zeros 4 * deg pix_y=array range 4 * deg image=ones 4 peak_time=intercept * ns + grad * array range 4 * ns rotation_angle=0 * deg
comment Test we get the values we put in back out again
call assert_allclose gradient gra... | def test_grad_fit():
grad = 2
intercept = 1
timing = timing_parameters(
pix_x=np.zeros(4) * u.deg,
pix_y=np.arange(4) * u.deg,
image=np.ones(4),
peak_time=intercept * u.ns + grad * np.arange(4) * u.ns,
rotation_angle=0 * u.deg
)
# Test we get the values we p... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For ex. 1 / 2 3 Return 6 This is basically post order traversal
comment Definition for a binary tree node
set max_val = 0
class TreeNode
begin
function __init__ self x
begin
set val = ... | #!/usr/bin/env python
'''
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For ex.
1
/ \
2 3
Return 6
This is basically post order traversal
'''
#Definition for a binary tree node
max_val = 0
class TreeNode:
def __init__(self, x):
... | Python | zaydzuhri_stack_edu_python |
function snake_to_camel string
begin
set camel_case = list
for word in split string string _
begin
append camel_case title word
end
join string camel_case
end function | def snake_to_camel(string):
camel_case = []
for word in string.split("_"):
camel_case.append(word.title())
"".join(camel_case) | Python | nomic_cornstack_python_v1 |
function image_url self
begin
if cover_image
begin
return url
end
return string /static/images/photos/default_image.jpeg
end function | def image_url(self):
if self.cover_image:
return self.cover_image.url
return "/static/images/photos/default_image.jpeg" | Python | nomic_cornstack_python_v1 |
function convert_unit unit to_unit
begin
from core.models import Equivalence
comment Degenerate case
if string unit == string to_unit
begin
return 1.0
end
comment Try to find a direct mapping between units
try
begin
set equivalence = get objects unit__name=unit to_unit__name=to_unit
end
except ObjectDoesNotExist
begin
... | def convert_unit(unit, to_unit):
from core.models import Equivalence
# Degenerate case
if str(unit) == str(to_unit):
return 1.0
# Try to find a direct mapping between units
try:
equivalence = Equivalence.objects.get(unit__name=unit, to_unit__name=to_unit)
except ObjectDoesNotEx... | Python | nomic_cornstack_python_v1 |
string print(a) print(b) print(c) print(d)
set tuple x1 x2 x3 = tuple 10 string hi 2.35
print x1
print x2
print x3
set p = 12
set p = 1.1
set p = string round
comment will print p's latest value
print p
comment concatenate 2 integers or strings but we can't concatenate integers and concatenate together
set y1 = 2
set y... | """print(a)
print(b)
print(c)
print(d)"""
x1, x2, x3 = 10, "hi", 2.35,
print(x1)
print(x2)
print(x3)
p = 12
p = 1.1
p = 'round'
print(p) #will print p's latest value
#concatenate 2 integers or strings but we can't concatenate integers and concatenate together
y1 = 2
y2 = 3
y3 = 'hi\n'
y4 = 'how r u\n'
print(y1 + y2)... | Python | zaydzuhri_stack_edu_python |
import pickle , cv2 , math , timeit , random , time , os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from pathlib import Path
from sklearn.neighbors import KNeighborsClassifier
function nothing x
begin
pass
end function
comment - Find CONTOURS function
function find_contours file... | import pickle, cv2, math, timeit, random, time, os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from pathlib import Path
from sklearn.neighbors import KNeighborsClassifier
def nothing(x):
pass
# - Find CONTOURS function
def find_contours(filename):
picture = cv2.imread... | Python | zaydzuhri_stack_edu_python |
class DamageToken extends object
begin
function __init__ self x y d
begin
set x = x
set y = y
set cur_y = y
set d = d
end function
end class | class DamageToken(object):
def __init__(self,x,y,d):
self.x = x
self.y = y
self.cur_y = y
self.d = d
| Python | zaydzuhri_stack_edu_python |
function get_values d_list k
begin
set acc = list
for dictionaryy in d_list
begin
for x in keys dictionaryy
begin
if x == k and dictionaryy at x not in acc
begin
append acc dictionaryy at x
end
end
end
return acc
end function
function break_out LOD K
begin
set result = dict
set lst = list
for dictionary in LOD
begin... | def get_values(d_list,k):
acc=[]
for dictionaryy in d_list:
for x in dictionaryy.keys():
if x == k and dictionaryy[x] not in acc:
acc.append(dictionaryy[x])
return acc
def break_out(LOD, K):
result = {}
lst = []
for dictionary in LOD:
V=dictionary[K]
result[V]=[]
for V in result... | Python | zaydzuhri_stack_edu_python |
import json
import requests
class RestClient extends object
begin
function __init__ self
begin
pass
end function
function make_post_request self url body_dictionary header_dictionary
begin
return post url data=dumps body_dictionary headers=header_dictionary
end function
function make_get_request self url body_dictionar... | import json
import requests
class RestClient(object):
def __init__(self):
pass
def make_post_request(self, url, body_dictionary, header_dictionary):
return requests.post(url, data=json.dumps(body_dictionary), headers=header_dictionary)
def make_get_request(self, url, body_dictionary):
... | Python | zaydzuhri_stack_edu_python |
function analyseHeaders line
begin
set csvlist = list
for col in line
begin
set found = false
set col = lower col
end
end function | def analyseHeaders(line):
csvlist=[]
for col in line:
found=False
col=col.lower() | Python | nomic_cornstack_python_v1 |
comment fh = opne('logs.txt')
comment print(dir(fh))
comment fh.close()
with open string logs.txt as logi ; open string emails.txt as emaile
begin
print read logi
print read emaile
end
for line in f
begin
print line
end | #fh = opne('logs.txt')
#print(dir(fh))
#fh.close()
with open("logs.txt") as logi, open("emails.txt") as emaile:
print(logi.read())
print(emaile.read())
for line in f:
print(line) | Python | zaydzuhri_stack_edu_python |
import os
import os.path
from os import path
from Crypto import Random
from Crypto.Cipher import AES
from os import listdir
from os.path import isfile , join
class Encryptor
begin
function __init__ self key
begin
set key = key
end function
function pad self s
begin
return s + b'\x00' * block_size - length s % block_siz... | import os
import os.path
from os import path
from Crypto import Random
from Crypto.Cipher import AES
from os import listdir
from os.path import isfile, join
class Encryptor:
def __init__ (self,key):
self.key = key
def pad(self, s):
return s+b"\0" * (AES.block_size - len(s) % AES.block_size)
... | Python | zaydzuhri_stack_edu_python |
from Queue import Queue
function solve armin motes
begin
set motes = sorted motes reverse=true
set q = queue
put dict string armin armin ; string motes motes ; string count 0
while qsize > 0
begin
set state = get q
while length state at string motes > 0 and state at string armin > state at string motes at - 1
begin
set... | from Queue import Queue
def solve(armin, motes):
motes = sorted(motes, reverse=True)
q = Queue()
q.put({'armin': armin, 'motes': motes, 'count': 0})
while q.qsize > 0:
state = q.get()
while len(state['motes']) > 0 and state['armin'] > state['motes'][-1]:
state['armin'] += state['motes'].pop()
... | Python | zaydzuhri_stack_edu_python |
function uniformCostSearch problem start end
begin
return call graphSearch problem start end call PriorityQueueWithFunction lambda x -> path_cost
end function | def uniformCostSearch(problem, start, end):
return graphSearch(problem, start, end, PriorityQueueWithFunction(lambda x: x.path_cost)) | Python | nomic_cornstack_python_v1 |
function make_class_weight_dict train_y_labels return_dict=false
begin
if string type train_y_labels == string <class 'numpy.ndarray'>
begin
set labs = list range shape at 1
set freq = list sum train_y_labels axis=0
set train_class_counts = dictionary zip labs freq
end
else
begin
set train_class_counts = dictionary gen... | def make_class_weight_dict(train_y_labels, return_dict = False):
if str(type(train_y_labels)) == "<class 'numpy.ndarray'>":
labs = list(range(train_y_labels.shape[1]))
freq = list(np.sum(train_y_labels, axis = 0))
train_class_counts = dict(zip(labs, freq))
else:
train_class_... | Python | nomic_cornstack_python_v1 |
function ams_grad self
begin
return call get_ams_grad
end function | def ams_grad(self):
return self._internal.get_ams_grad() | Python | nomic_cornstack_python_v1 |
from ArrayGenerator import ArrayGenerator
import time
import numpy as np
class LinearSearch
begin
decorator staticmethod
function search data target
begin
for tuple index one in enumerate data
begin
if one == target
begin
return index
end
end
return - 1
end function
end class
if __name__ == string __main__
begin
set te... | from ArrayGenerator import ArrayGenerator
import time
import numpy as np
class LinearSearch:
@staticmethod
def search(data, target):
for index, one in enumerate(data):
if one == target:
return index
return -1
if __name__ == '__main__':
test_list = [24, 18, 12, ... | Python | zaydzuhri_stack_edu_python |
function find_prediction_forecast test train_x train_y model bin_means
begin
set prediction_frame = call DataFrame nan index=index columns=range shape at 1
set predictions = call Series index=index
set pred_class = call Series index=index
set iloc at tuple 0 slice 1 : : = values
set iloc at tuple 0 0 = iloc at - 1
co... | def find_prediction_forecast(test, train_x, train_y, model, bin_means):
prediction_frame = pd.DataFrame(
np.nan, index=test.index, columns=range(train_x.shape[1])
)
predictions = pd.Series(index=test.index)
pred_class = pd.Series(index=test.index)
prediction_frame.iloc[0, 1:] = train_x.iloc... | Python | nomic_cornstack_python_v1 |
function bonded self n1 n2 distance
begin
string Return the estimated bond type Arguments: | ``n1`` -- the atom number of the first atom in the bond | ``n2`` -- the atom number of the second atom the bond | ``distance`` -- the distance between the two atoms This method checks whether for the given pair of atom numbers,... | def bonded(self, n1, n2, distance):
"""Return the estimated bond type
Arguments:
| ``n1`` -- the atom number of the first atom in the bond
| ``n2`` -- the atom number of the second atom the bond
| ``distance`` -- the distance between the two atoms
... | Python | jtatman_500k |
function gen_pall_pairs self
begin
comment TODO: Ensure even split of key generation across clients
assert reg_done
set res = dictionary comprehension k : list for k in keys clients
for pair in call combinations keys clients 2
begin
set g = random integer 0 1
set gen_client = pair at g
set rec_client = pair at g ? 1
ap... | def gen_pall_pairs(self):
#TODO: Ensure even split of key generation across clients
assert self.reg_done
res = {k: list() for k in self.clients.keys()}
for pair in itertools.combinations(self.clients.keys(), 2):
g = random.randint(0,1)
gen_client = pair[g]
... | Python | nomic_cornstack_python_v1 |
import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
set d = call read_excel string payment/月度资金预算编制.xlsx sheet_name=string 月度编制上传模版
set columns = strip str
set foo = group by d string 备注
set book = call load_workbook string payment/付款与挂账.xlsx
set detail = call l... | import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
d = pd.read_excel("payment/月度资金预算编制.xlsx", sheet_name='月度编制上传模版')
d.columns = d.columns.str.strip()
foo = d.groupby('备注')
book = load_workbook('payment/付款与挂账.xlsx')
detail = load_workbook('payment/预算分摊表.xlsx'... | Python | zaydzuhri_stack_edu_python |
import os
import argparse
import sys
set parser = call ArgumentParser
call add_argument string --data_dir default=string data/128x128_specs_5.12s help=string Directory containing the dataset
if __name__ == string __main__
begin
set args = call parse_args
set file_dir = data_dir
if not exists path file_dir
begin
print f... | import os
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', default='data/128x128_specs_5.12s', help="Directory containing the dataset")
if __name__ == '__main__':
args = parser.parse_args()
file_dir = args.data_dir
if not os.path.exists(file_dir):
print("Warning:... | Python | zaydzuhri_stack_edu_python |
function query_map_coordinates self
begin
set query_geom = query session call label string coordinates
try
begin
set coordinates = call normalize_coordinates call subquery
end
except any
begin
set coordinates = list string
end
set str_coordinates = join string , coordinates
return str_coordinates
end function | def query_map_coordinates(self):
query_geom = self.session.query(
func.ST_Extent(self.tables.capa.the_geom).label('coordinates')
)
try:
coordinates = self.normalize_coordinates(query_geom.subquery())
except:
coordinates = ['']
str_coordinates =... | Python | nomic_cornstack_python_v1 |
comment 小文件下载
import requests
set image_url = string https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596368924575&di=0b1f52010b213b308b8d917ba7a6b7df&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2015%2F295%2F41%2F0E87XZ5MPO7J_3epECXX_600.jpg
set r = get requests image_url
with ... | ### 小文件下载
import requests
image_url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596368924575&di=0b1f52010b213b308b8d917ba7a6b7df&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2015%2F295%2F41%2F0E87XZ5MPO7J_3epECXX_600.jpg'
r = requests.get(image_url)
with open("beautiful.... | Python | zaydzuhri_stack_edu_python |
if word == word at slice : : - 1
begin
print string 회문
end
else
begin
print string Flase
end | if word == word[::-1]:
print("회문")
else:
print("Flase")
| Python | zaydzuhri_stack_edu_python |
function main
begin
set token = call getenv string BOT_TOKEN
set application = call build
call load_interactions application
print string Simple Media Converter instance started!
call run_polling
end function | def main():
token = os.getenv("BOT_TOKEN")
application = Application.builder().token(token).read_timeout(30).write_timeout(30).build()
load_interactions(application)
print("Simple Media Converter instance started!")
application.run_polling() | Python | nomic_cornstack_python_v1 |
function get_displayed_field_value self field_name *args
begin
try
begin
set tuple field_class x direct x = call get_field_by_name field_name
end
except FieldDoesNotExist
begin
return args
end
if not direct
begin
raise exception format string Cannot handle indirect fields ({}) field_class
end
set raw_value = if express... | def get_displayed_field_value(self, field_name, *args):
try:
field_class, x, direct, x = self._meta.get_field_by_name(field_name)
except FieldDoesNotExist:
return args
if not direct:
raise Exception('Cannot handle indirect fields ({})'.format(field_class))
... | Python | nomic_cornstack_python_v1 |
function test_fields_and_attributes self
begin
set expected_fields = tuple string id string password string last_login string is_superuser string is_staff string is_active string date_joined string email string groups string user_permissions
set excluded_fields = tuple string full_name string short_name
set user_fields... | def test_fields_and_attributes(self):
expected_fields = (
"id",
"password",
"last_login",
"is_superuser",
"is_staff",
"is_active",
"date_joined",
"email",
"groups",
"user_permissions",
... | Python | nomic_cornstack_python_v1 |
function test_google_analytics_snippet_exists self
begin
set response = get call client string /code/source/
call ok_ string RANDOM_KEY_$#$ in data
call ok_ string .google-analytics.com in data
end function | def test_google_analytics_snippet_exists(self):
response = self.client().get('/code/source/')
ok_('RANDOM_KEY_$#$' in response.data)
ok_( '.google-analytics.com' in response.data ) | Python | nomic_cornstack_python_v1 |
function is_in_that list_of_lists test_list
begin
comment contains positive indices
set inds = list
set ind = 0
for current_list in list_of_lists
begin
comment if the current row is equal to the parameter row vector
if false not in test_list == current_list
begin
append inds ind
end
set ind = ind + 1
end
if length ind... | def is_in_that(list_of_lists, test_list):
inds = [] # contains positive indices
ind = 0
for current_list in list_of_lists:
# if the current row is equal to the parameter row vector
if False not in (test_list == current_list):
inds.append(ind)
ind += 1
if len(i... | Python | nomic_cornstack_python_v1 |
function remove_element_from_tuple tup element
begin
set new_tuple = tuple
for item in tup
begin
if item != element
begin
set new_tuple = new_tuple + tuple item
end
end
return new_tuple
end function | def remove_element_from_tuple(tup, element):
new_tuple = ()
for item in tup:
if item != element:
new_tuple += (item,)
return new_tuple
| Python | jtatman_500k |
function get_or_create_group group_id
begin
try
begin
return get Group group_id=group_id
end
except DoesNotExist
begin
return call create group_id=group_id absent=dict string absent list
end
end function | def get_or_create_group(group_id):
try:
return Group.get(group_id=group_id)
except DoesNotExist:
return Group.create(group_id=group_id,
absent={
"absent": []
}) | Python | nomic_cornstack_python_v1 |
import sys
while true
begin
set n = strip read line stdin
if length n == 0
begin
break
end
set startValue = 0
set a = list comprehension list 0 * integer n for i in range integer n
for x in range integer n
begin
for y in range x - 1 - 1
begin
set k = x - y
set startValue = startValue + 1
set a at y at k = startValue
en... | import sys
while True:
n = sys.stdin.readline().strip()
if len(n) == 0:
break
startValue = 0
a = [[0]*int(n) for i in range(int(n))]
for x in range(int(n)):
for y in range(x, -1, -1):
k = x - y
startValue = startValue + 1
a[y][k] = startValue
f... | Python | zaydzuhri_stack_edu_python |
function half_to_full_hermitian_image_filter *args **kwargs
begin
import itk
set instance = call New *args keyword kwargs
return call __internal_call__
end function | def half_to_full_hermitian_image_filter(*args, **kwargs):
import itk
instance = itk.HalfToFullHermitianImageFilter.New(*args, **kwargs)
return instance.__internal_call__() | Python | nomic_cornstack_python_v1 |
set string = string Hello World
comment prints 11
print length string | string = "Hello World"
print(len(string)) # prints 11 | Python | jtatman_500k |
function levels self
begin
return _levels
end function | def levels(self):
return self._levels | Python | nomic_cornstack_python_v1 |
function test_ChangeParticle_wrong_direction
begin
comment 0 is left and 1 is right.
try
begin
call ChangeParticle list 5 2 1 2 3
end
except any
begin
pass
end
try else
begin
raise call AssertionError string wrong direction did not raise an error
end
end function | def test_ChangeParticle_wrong_direction():
try: ChangeParticle([5,2,1],2,3)# 0 is left and 1 is right.
except: pass
else: raise AssertionError("wrong direction did not raise an error") | Python | nomic_cornstack_python_v1 |
function isMoving self
begin
set msg = InstructionSet at string isMoving
call com_write msg
set reply = call com_recv comDefaultReplyLength
if reply at slice : 1 : is string 0
begin
return false
end
else
begin
return true
end
end function | def isMoving(self):
msg = self.InstructionSet["isMoving"]
self.com_write(msg)
reply = self.com_recv(self.comDefaultReplyLength)
if reply[:1] is "0":
return False
else:
return True | Python | nomic_cornstack_python_v1 |
function get_absolute_and_relative_covid19_occurance
begin
set geolocation_data = call load_geolocation_data
set abs_cases = call load_absolute_case_numbers
set abs_cases_aggregated_age_groups = call aggregate_absolute_cases_by_age abs_cases
set abs_cases_aggregated = call aggregate_absolute_cases_by_lk abs_cases_aggre... | def get_absolute_and_relative_covid19_occurance():
geolocation_data = load_geolocation_data()
abs_cases = load_absolute_case_numbers()
abs_cases_aggregated_age_groups = aggregate_absolute_cases_by_age(abs_cases)
abs_cases_aggregated = aggregate_absolute_cases_by_lk(abs_cases_aggregated_age_groups)
l... | Python | nomic_cornstack_python_v1 |
function clear cls
begin
for db_entity in select cls
begin
call delete_instance
end
end function | def clear(cls):
for db_entity in cls.select():
db_entity.delete_instance() | Python | nomic_cornstack_python_v1 |
function check_optional name allowXHTML=false merge_multiple=false
begin
function check n filename
begin
set n = call get_nodes_by_name n name
if length n > 1 and not merge_multiple
begin
raise call ManifestException string Invalid manifest file: must have a single '%s' element % name
end
if n
begin
set values = list
... | def check_optional(name, allowXHTML=False, merge_multiple=False):
def check(n, filename):
n = get_nodes_by_name(n, name)
if len(n) > 1 and not merge_multiple:
raise ManifestException("Invalid manifest file: must have a single '%s' element" % name)
if n:
values = []
... | Python | nomic_cornstack_python_v1 |
function send_notifications
begin
set due_notifications = filter delivery_date <= now utc
for notification in due_notifications
begin
call delay id
end
end function | def send_notifications():
due_notifications = Notification.query.filter(Notification.delivery_date <= datetime.now(timezone.utc))
for notification in due_notifications:
send_notification.delay(notification.id) | Python | nomic_cornstack_python_v1 |
function self_link self
begin
return get pulumi self string self_link
end function | def self_link(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "self_link") | Python | nomic_cornstack_python_v1 |
function test_expiration_date_from_past self
begin
set data = dict string name string some name ; string description string some text ; string expires_at string 12/12/2012 23:00 ; string max_messages 1
set form = call CreateBoxForm data
assert equal call is_valid false
end function | def test_expiration_date_from_past(self):
data = {
"name": "some name",
"description": "some text",
"expires_at": "12/12/2012 23:00",
"max_messages": 1
}
form = CreateBoxForm(data)
self.assertEqual(form.is_valid(), False) | Python | nomic_cornstack_python_v1 |
import RPi.GPIO as gpio
import time
comment (PIN 1 - Motor DC direito A)
set pin1 = 1
comment (PIN 2 - Motor DC direito B)
set pin2 = 2
comment (PIN 3 - Motor DC esquerdo A)
set pin3 = 3
comment (PIN 4 - Motor DC esquerdo B)
set pin4 = 4
comment (PIN 5 - Sensor esquerdo)
set pin5 = 5
comment (PIN 6 - Sensor direito)
se... | import RPi.GPIO as gpio
import time
pin1 = 1 #(PIN 1 - Motor DC direito A)
pin2 = 2 #(PIN 2 - Motor DC direito B)
pin3 = 3 #(PIN 3 - Motor DC esquerdo A)
pin4 = 4 #(PIN 4 - Motor DC esquerdo B)
pin5 = 5 #(PIN 5 - Sensor esquerdo)
pin6 = 6 #(PIN 6 - Sensor direito)
delay = 1
gpio.setmode(gpio.BCM)
gpio.setup(p... | Python | zaydzuhri_stack_edu_python |
function redraw_chatbuffer self color
begin
clear win_chatbuffer
set tuple h w = call getmaxyx
set j = length linebuffer - h
if j < 0
begin
set j = 0
end
for i in range min h length linebuffer
begin
call addstr_safe string c i 1 linebuffer at j call color_pair color
set j = j + 1
end
call refresh
end function | def redraw_chatbuffer(self, color):
self.win_chatbuffer.clear()
h, w = self.win_chatbuffer.getmaxyx()
j = len(self.linebuffer) - h
if j < 0:
j = 0
for i in range(min(h, len(self.linebuffer))):
self.addstr_safe('c', i, 1, self.linebuffer[j], curses.color_pa... | Python | nomic_cornstack_python_v1 |
import sqlite3
set conn = call connect string src\Database\banco.db
class Funcionario
begin
function __init__ self cpf nome cargo terceirizado salario=none
begin
set cpf = cpf
set nome = nome
set cargo = cargo
set salario = salario
set terceirizado = terceirizado
end function
function insertFuncionario self
begin
set p... | import sqlite3
conn = sqlite3.connect("src\\Database\\banco.db")
class Funcionario:
def __init__(self, cpf:str, nome:str, cargo:str, terceirizado:bool, salario=None):
self.cpf = cpf
self.nome = nome
self.cargo = cargo
self.salario = salario
self.terceirizado = terceiriza... | Python | zaydzuhri_stack_edu_python |
function display_name self
begin
return if expression is instance nickname str then nickname else username
end function | def display_name(self) -> str:
return self.nickname if isinstance(self.nickname, str) else self.username | Python | nomic_cornstack_python_v1 |
import argparse
import os
import sys
import threading
import multiprocessing
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.contrib.slim as slim
import scipy.signal
from AC_Network import AC_Network
from Worker import Worker
from random import choice
from time import sleep
... | import argparse
import os
import sys
import threading
import multiprocessing
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.contrib.slim as slim
import scipy.signal
from AC_Network import AC_Network
from Worker import Worker
from random import choice
from time import slee... | Python | zaydzuhri_stack_edu_python |
comment Project Euler - problem 16
comment 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
comment What is the sum of the digits of the number 2^1000?
comment Written by: Ed Karwacki
set x = 2 ^ 1000
set s = string x
set sum = 0
for i in range length s
begin
set sum = sum + integer s at i
end | #Project Euler - problem 16
#2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#What is the sum of the digits of the number 2^1000?
#Written by: Ed Karwacki
x = 2**1000
s = str(x)
sum = 0
for i in range (len(s)):
sum += int(s[i]) | Python | zaydzuhri_stack_edu_python |
function calculate_fuel_mass geometry_obj fuel_density
begin
comment Check the inputs
assert is instance geometry_obj Geometry msg string Please insert a valid Geometry type.
comment Return the output
return call get_fuel_mass fuel_density
end function | def calculate_fuel_mass(geometry_obj, fuel_density):
# Check the inputs
assert isinstance(geometry_obj, Geometry), "Please insert a valid Geometry type. \n"
# Return the output
return geometry_obj.get_fuel_mass(fuel_density) | Python | nomic_cornstack_python_v1 |
function _reshape_batch inputs size batch_size
begin
set batch_inputs = list
for length_id in range size
begin
append batch_inputs array list comprehension inputs at batch_id at length_id for batch_id in range batch_size dtype=int32
end
return batch_inputs
end function | def _reshape_batch(inputs, size, batch_size):
batch_inputs = []
for length_id in range(size):
batch_inputs.append(np.array([inputs[batch_id][length_id]
for batch_id in range(batch_size)], dtype=np.int32))
return batch_inputs | Python | nomic_cornstack_python_v1 |
import argparse
set ap = call ArgumentParser
call add_argument string --input required=true
set args = variables call parse_args
set ball = list 1 0 0
set order_abc = args at string input
for alpha in order_abc
begin
set temp_ball = 0
if alpha == string A or alpha == string a
begin
set tuple ball at 0 ball at 1 = tuple... | import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--input",required=True)
args = vars(ap.parse_args())
ball = [1,0,0]
order_abc = args["input"]
for alpha in order_abc:
temp_ball = 0
if(alpha == "A" or alpha == "a"):
ball[0] , ball[1] = ball[1] , ball[0]
elif(alpha == "B" or alpha ... | Python | zaydzuhri_stack_edu_python |
function test_pycuda_theano
begin
from pycuda.compiler import SourceModule
set mod = call SourceModule string __global__ void multiply_them(float *dest, float *a, float *b) { const int i = threadIdx.x; dest[i] = a[i] * b[i]; }
set multiply_them = call get_function string multiply_them
set a = as type randn 100 float32
... | def test_pycuda_theano():
from pycuda.compiler import SourceModule
mod = SourceModule("""
__global__ void multiply_them(float *dest, float *a, float *b)
{
const int i = threadIdx.x;
dest[i] = a[i] * b[i];
}
""")
multiply_them = mod.get_function("multiply_them")
a = numpy.random.randn(1... | Python | nomic_cornstack_python_v1 |
class Books
begin
function __init__ self
begin
set book = dict
set bookList = list
end function
function add_a_book self name isbn price
begin
try
begin
if call _find name=name isbn=isbn == none
begin
update book Name=name
update book ISBN=isbn
update book Price=price
append bookList book
end
else
begin
raise excepti... | class Books:
def __init__(self):
self.book = {}
self.bookList = []
def add_a_book(self, name, isbn, price):
try:
if self._find(name=name, isbn=isbn) == None:
self.book.update(Name = name)
self.book.update(ISBN = isbn)
self.book... | Python | zaydzuhri_stack_edu_python |
function estimate_stepdown self x y
begin
set crappyfilter = list - 0.25 - 0.75 0.0 0.75 0.25
set cutoff = length crappyfilter // 2
set y_deriv = convolve y crappyfilter mode=string valid
comment make the derivative's peak have the same amplitude as the step
if max y_deriv > 0
begin
set y_deriv = y_deriv * max y / max ... | def estimate_stepdown(self, x, y):
crappyfilter = [-0.25, -0.75, 0.0, 0.75, 0.25]
cutoff = len(crappyfilter) // 2
y_deriv = numpy.convolve(y,
crappyfilter,
mode="valid")
# make the derivative's peak have the same amplitud... | Python | nomic_cornstack_python_v1 |
function upload_file self filepath key
begin
string Uploads a file using the passed S3 key This method uploads a file specified by the filepath to S3 using the provided S3 key. :param filepath: (str) Full path to the file to be uploaded :param key: (str) S3 key to be set for the upload :return: True if upload is succes... | def upload_file(self, filepath, key):
"""Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
... | Python | jtatman_500k |
function test_speech_bubble_dumping data_files
begin
set page = call get_base_panels num_panels=1
set page = call populate_panels page *data_files minimum_speech_bubbles=1
set bubble = speech_bubbles at 0
set data = call dump_data
set data_keys = keys data
assert string texts in data_keys
assert string text_indices in ... | def test_speech_bubble_dumping(data_files):
page = get_base_panels(num_panels=1)
page = populate_panels(page, *data_files, minimum_speech_bubbles=1)
bubble = page.speech_bubbles[0]
data = bubble.dump_data()
data_keys = data.keys()
assert "texts" in data_keys
assert "text_indices" in data_... | Python | nomic_cornstack_python_v1 |
comment -*- encoding: utf-8 -*-
string @File : student.py @Time : 2020/03/29 19:25:50 @Author : xdbcb8 @Version : 1.0 @Contact : xdbcb8@qq.com @WebSite : www.xdbcb8.com
comment here put the import lib
comment 3 从键盘输入5个同学的账号和密码,然后将他们的姓名,账号和密码(密码需要加密)保存到一个文件中;
comment Tom admin XXXXX
comment Jack root XXXXX
import hashli... | # -*- encoding: utf-8 -*-
'''
@File : student.py
@Time : 2020/03/29 19:25:50
@Author : xdbcb8
@Version : 1.0
@Contact : xdbcb8@qq.com
@WebSite : www.xdbcb8.com
'''
# here put the import lib
#3 从键盘输入5个同学的账号和密码,然后将他们的姓名,账号和密码(密码需要加密)保存到一个文件中;
# Tom admin XXXXX
# Jack root XXXXX
import h... | Python | zaydzuhri_stack_edu_python |
function set_coords self x1 y1 x2 y2
begin
set x1 = x1
set y1 = y1
set x2 = x2
set y2 = y2
end function | def set_coords(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2 | Python | nomic_cornstack_python_v1 |
string ---------------------------------------------------------------------------------------- MODULE FSaveVolatility - Defines menu extensions for saving volatility via the trading manager. This module saves or recalculates the implied volatility from the Trading Manager. If the instrument is not defined as benchmark... | """----------------------------------------------------------------------------------------
MODULE
FSaveVolatility - Defines menu extensions for saving volatility via the
trading manager.
This module saves or recalculates the implied volatility from the Trading Manager.
If the in... | Python | zaydzuhri_stack_edu_python |
comment praxis character.py
class Character
begin
function __init__ self
begin
set id = none
set location = none
set name = string default
set health = 100
set maxHealth = 100
set strength = 10
set agility = 10
set intellect = 10
set charisma = 10
set effects = list
set inventory = list
set equipment = dict string he... | # praxis character.py
class Character:
def __init__(self):
self.id = None
self.location = None
self.name = "default"
self.health = 100
self.maxHealth = 100
self.strength = 10
self.agility = 10
self.intellect = 10
self.charisma = 10
se... | Python | zaydzuhri_stack_edu_python |
import matplotlib
call use string TkAgg
import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv2
import gopigo3
comment import pygame
import time
import easygopigo3 as easy
from pylab import *
comment Simple threshold class that takes in a color image
comment and generates a single threshold.
comment Creati... | import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv2
import gopigo3
#import pygame
import time
import easygopigo3 as easy
from pylab import *
# Simple threshold class that takes in a color image
# and generates a single threshold.
dexgp = gopigo3.GoPiGo3() # ... | Python | zaydzuhri_stack_edu_python |
import eulerutils
comment N = 10**2
comment N = 10**3
set N = 10 ^ 6
set primes = call prime_list N
set start = 0
set candidates = dict
comment kind of a BS/empirically derived endpoint but it turned out to be correct in the end
while start <= length primes / 100
begin
print start
set i = start
set next_sum = 0
set ch... | import eulerutils
# N = 10**2
# N = 10**3
N = 10**6
primes = eulerutils.prime_list(N)
start = 0
candidates = {}
# kind of a BS/empirically derived endpoint but it turned out to be correct in the end
while start <= len(primes)/100:
print(start)
i = start
next_sum = 0
check_list = []
while next_sum... | Python | zaydzuhri_stack_edu_python |
function _calc_loss args loss_function local_q_vector local_ctx_vectors local_positive_idxs local_hard_negatives_idxs=none return_scores=false
begin
set distributed_world_size = distributed_world_size or 1
if distributed_world_size > 1
begin
set q_vector_to_send = call detach_
set ctx_vector_to_send = call detach_
set ... | def _calc_loss(args, loss_function, local_q_vector, local_ctx_vectors, local_positive_idxs,
local_hard_negatives_idxs: list = None, return_scores=False
):
distributed_world_size = args.distributed_world_size or 1
if distributed_world_size > 1:
q_vector_to_send = torch.empty... | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function combinationSum self candidates target
begin
set n = length candidates
set ans = list
function backtracking level cur_list target
begin
if target <= 0
begin
if target == 0
begin
append ans cur_list at slice : :
end
return
end
for i in range level n
begin
append cu... | from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
n = len(candidates)
ans = []
def backtracking(level, cur_list, target):
if target <= 0:
if target == 0:
ans.append(cur_l... | Python | zaydzuhri_stack_edu_python |
function ggaus x
begin
return tuple length x mean np x standard deviation np x
end function | def ggaus(x):
return (len(x), np.mean(x), np.std(x)) | Python | nomic_cornstack_python_v1 |
function task_prepare_nodes self req resp json_data
begin
set action = get json_data string action none
if action != string prepare_nodes
begin
error context string Task body ended up in wrong handler: action %s in task_prepare_nodes % action
call return_error resp HTTP_500 message=string Error retry=false
end
try
begi... | def task_prepare_nodes(self, req, resp, json_data):
action = json_data.get('action', None)
if action != 'prepare_nodes':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_prepare_nodes"
% action)
self... | Python | nomic_cornstack_python_v1 |
string This script aims at detecting the fraud transactions from mobile money transfer based on the dataset available at https://www.kaggle.com/ntnu-testimon/paysim1
import random
from collections import Counter
import numpy as np
from numpy import genfromtxt
from sklearn import svm
from sklearn.neural_network import M... | """
This script aims at detecting the fraud transactions from mobile money transfer
based on the dataset available at https://www.kaggle.com/ntnu-testimon/paysim1
"""
import random
from collections import Counter
import numpy as np
from numpy import genfromtxt
from sklearn import svm
from sklear... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment In[10]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import ... | # coding: utf-8
# In[10]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy... | Python | zaydzuhri_stack_edu_python |
function get_ir_reciprocal_mesh mesh bulk is_shift=zeros 3 dtype=int is_time_reversal=true symprec=1e-05
begin
set mapping = zeros call prod mesh dtype=int
set mesh_points = zeros tuple call prod mesh 3 dtype=int
call ir_reciprocal_mesh mesh_points mapping array mesh array is_shift is_time_reversal * 1 copy T copy call... | def get_ir_reciprocal_mesh( mesh,
bulk,
is_shift=np.zeros(3, dtype=int),
is_time_reversal=True,
symprec=1e-5 ):
mapping = np.zeros( np.prod(mesh), dtype=int )
mesh_points = np.zeros( (np.prod(mesh), ... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[103]:
comment Adding additional argument for specifying directory
function Graph x path index=string
begin
set y = index
import pandas as pd
import os
if path == string
begin
set Dir = get current directory
end
else
begin
set Dir = path
end
change directory string Dir
import numpy as n... | # coding: utf-8
# In[103]:
def Graph(x,path,index="" ): ## Adding additional argument for specifying directory
y = index
import pandas as pd
import os
if path == "":
Dir = os.getcwd()
else:
Dir = path
os.chdir(str(Dir))
import numpy as np
import matplotlib.pyplot a... | Python | zaydzuhri_stack_edu_python |
function test_bucket_to_bucket self
begin
comment Create 2 buckets with 1 overlapping object, 1 extra object at root level
comment in each, and 1 extra object 1 level down in each. Make the overlapping
comment objects named the same but with different content, to test that we detect
comment and properly copy in that ca... | def test_bucket_to_bucket(self):
# Create 2 buckets with 1 overlapping object, 1 extra object at root level
# in each, and 1 extra object 1 level down in each. Make the overlapping
# objects named the same but with different content, to test that we detect
# and properly copy in that case.
buck... | Python | nomic_cornstack_python_v1 |
string Write a Python program to remove the duplicates in a list and print the list in ascending order
function remove_duplicates_ascending l
begin
return sorted list set l
end function
if __name__ == string __main__
begin
set l = list 10 7 9 12 11 7 9 10
set res = call remove_duplicates_ascending l
comment [7, 9, 10, ... | """
Write a Python program to remove the duplicates in a list and print the list in ascending order
"""
def remove_duplicates_ascending(l):
return sorted(list(set(l)))
if __name__ == "__main__":
l = [10,7,9,12,11,7,9,10]
res = remove_duplicates_ascending(l)
print(res) # [7, 9, 10, 11, 12] | Python | jtatman_500k |
function float_to_decimal f
begin
string Convert a float to a 38-precision Decimal
set tuple n d = call as_integer_ratio
set tuple numerator denominator = tuple call Decimal n call Decimal d
return call divide numerator denominator
end function | def float_to_decimal(f):
""" Convert a float to a 38-precision Decimal """
n, d = f.as_integer_ratio()
numerator, denominator = Decimal(n), Decimal(d)
return DECIMAL_CONTEXT.divide(numerator, denominator) | Python | jtatman_500k |
function runloop self
begin
set exit = false
info string Event loop '%s' started % name
while not exit
begin
set _Tlast = time
call runall
set runtime = time - _Tlast
set sleeptime = looptime - runtime
if sleeptime <= 0
begin
pass
end
else
if sleeptime < 1.0
begin
sleep looptime - runtime
end
else
begin
for i in range ... | def runloop(self):
self.exit = False
logger.info("Event loop '%s' started" % self.name)
while not self.exit:
self._Tlast = time.time()
self.runall()
self.runtime = time.time() - self._Tlast
sleeptime = self.looptime - self.runtime
if sleeptime <= 0:
pass
elif slee... | Python | nomic_cornstack_python_v1 |
for n in range 11
begin
set n = n * n
print n
end | for n in range(11):
n = n * n
print(n) | Python | jtatman_500k |
function sample_array self X random_state=none sample_weight=none
begin
if random_state is none
begin
set random_state = call check_random_state random_state
end
set X = call check_array X
if sample_weight is none
begin
set sample_weight = ones tuple shape at 0
end
set cdf = cumulative sum sample_weight
set cdf = cdf /... | def sample_array(self, X, random_state=None, sample_weight=None):
if random_state is None:
random_state = check_random_state(random_state)
X = check_array(X)
if sample_weight is None:
sample_weight = np.ones((X.shape[0], ))
cdf = sample_weight.cumsum()
... | Python | nomic_cornstack_python_v1 |
function validate_key key
begin
if key is none or key == string
begin
raise call QuiltException string Invalid key { key } . A package entry key cannot be empty.
end
for part in split key string /
begin
if part in tuple string string . string ..
begin
raise call QuiltException string Invalid key { key } . A package e... | def validate_key(key):
if key is None or key == '':
raise QuiltException(
f"Invalid key {key!r}. A package entry key cannot be empty."
)
for part in key.split('/'):
if part in ('', '.', '..'):
raise QuiltException(
f"Invalid key {key!r}. "
... | Python | nomic_cornstack_python_v1 |
function jsonl_load obj error=true close_fh=true **kwargs
begin
function is_item item
begin
if not is instance item str
begin
return false
end
if not strip item or starts with item string #
begin
return false
end
return true
end function
set fh = none
if call is_existing_file obj
begin
set path = call pathify obj
set f... | def jsonl_load(
obj: t.Union[str, t.List[str], t.IO],
error: bool = True,
close_fh: bool = True,
**kwargs,
) -> t.List[t.Any]:
def is_item(item):
if not isinstance(item, str):
return False
if not item.strip() or item.startswith("#"):
return False
retu... | Python | nomic_cornstack_python_v1 |
function convert_genes_to_regions genes
begin
sort genes key=lambda x -> x at 0
comment stop gene
append genes tuple none none none none none none
set regions = list
set previous_gene = genes at 0
set region_start = previous_gene at 0
set region_end = previous_gene at 1
for gene in genes at slice 1 : :
begin
comment... | def convert_genes_to_regions(genes):
genes.sort(key=lambda x: x[0])
genes.append((None, None, None, None, None, None)) # stop gene
regions = []
previous_gene = genes[0]
region_start = previous_gene[0]
region_end = previous_gene[1]
for gene in genes[1:]:
... | Python | nomic_cornstack_python_v1 |
function ciphertext self
begin
return call hexlify _token at slice CIPHERTEXT_START : CIPHERTEXT_END :
end function | def ciphertext(self):
return binascii.hexlify(self._token[CIPHERTEXT_START:CIPHERTEXT_END]) | Python | nomic_cornstack_python_v1 |
function max_height self max_height
begin
set _max_height = max_height
end function | def max_height(self, max_height):
self._max_height = max_height | Python | nomic_cornstack_python_v1 |
import requests
import re
import urllib
import sys
import datetime
comment Basic e-mail regexp:
comment letter/number/dot/comma @ letter/number/dot/comma . letter/number
set email_re = compile string ([\w\.,]+@[\w\.,]+\.\w+)
comment HTML <a> regexp
comment Matches href="" attribute
set link_re = compile string href="(.... | import requests
import re
import urllib
import sys
import datetime
# Basic e-mail regexp:
# letter/number/dot/comma @ letter/number/dot/comma . letter/number
email_re = re.compile(r'([\w\.,]+@[\w\.,]+\.\w+)')
# HTML <a> regexp
# Matches href="" attribute
link_re = re.compile(r'href="(.*?)"')
def crawl(... | Python | zaydzuhri_stack_edu_python |
function create_session self user_id=none
begin
set session_id = call create_session user_id
if not session_id
begin
return none
end
set new_user = call UserSession user_id=user_id session_id=session_id
save
return session_id
end function | def create_session(self, user_id=None):
session_id = super().create_session(user_id)
if not session_id:
return None
new_user = UserSession(user_id=user_id, session_id=session_id)
new_user.save()
return session_id | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment !/usr/bin/env python3
string this contains the different strategies
import game.common as cm
import random
class SmartRandom extends object
begin
function __init__ self
begin
pass
end function
decorator staticmethod
function smart_random board threshold=200
begin
set count = 0
for ... | # -*- coding: utf-8 -*-
# !/usr/bin/env python3
"""this contains the different strategies"""
import game.common as cm
import random
class SmartRandom(object):
def __init__(self):
pass
@staticmethod
def smart_random(board, threshold=200):
count = 0
for _ in range(threshold):
... | Python | zaydzuhri_stack_edu_python |
function __init__ self colorNames
begin
comment will later be queried from the user
set _lengthOfPattern = 0
comment initials for color choices, e.g., R for red
set _palette = string
for color in colorNames
begin
set _palette = _palette + upper color at 0
end
end function | def __init__(self, colorNames):
self._lengthOfPattern = 0 # will later be queried from the user
self._palette = '' # initials for color choices, e.g., R for red
for color in colorNames:
self._palette += color[0].upper() | Python | nomic_cornstack_python_v1 |
set string = string This is a sample string.
comment Split the string into individual words
set words = split string
comment Track the frequency of each word
set word_freq = dict | string = "This is a sample string."
# Split the string into individual words
words = string.split()
# Track the frequency of each word
word_freq = {} | Python | flytech_python_25k |
comment Tutorial: https://www.w3schools.com/python/default.asp
comment Read CSV file: https://cmdlinetips.com/2011/08/three-ways-to-read-a-text-file-line-by-line-in-python/
comment Make DB connection: http://www.postgresqltutorial.com/postgresql-python/connect/
comment Execute insert statement: http://initd.org/psycopg... | # Tutorial: https://www.w3schools.com/python/default.asp
# Read CSV file: https://cmdlinetips.com/2011/08/three-ways-to-read-a-text-file-line-by-line-in-python/
# Make DB connection: http://www.postgresqltutorial.com/postgresql-python/connect/
# Execute insert statement: http://initd.org/psycopg/docs/usage.html
import ... | Python | zaydzuhri_stack_edu_python |
function from_string cls alg_str
begin
try
begin
return call cls integer alg_str at 1 - 1 ordinal alg_str at 0 - 97
end
except ValueError as e
begin
raise call ValueError format string Location.from_string {} invalid: {} alg_str e
end
end function | def from_string(cls, alg_str):
try:
return cls(int(alg_str[1]) - 1, ord(alg_str[0]) - 97)
except ValueError as e:
raise ValueError("Location.from_string {} invalid: {}".format(alg_str, e)) | Python | nomic_cornstack_python_v1 |
function read_parquet filepath **kwargs
begin
return call read_parquet filepath keyword kwargs
end function | def read_parquet(filepath: Path, **kwargs: Any) -> dd.DataFrame:
return dd.read_parquet(filepath, **kwargs) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.