code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_label value arg
begin
set field = get fields arg string
return if expression field then label else string
end function | def get_label(value, arg):
field = value.fields.get(arg, '')
return field.label if field else '' | Python | nomic_cornstack_python_v1 |
function negate self p1
begin
set tuple x1 y1 z1 = p1
return tuple x1 p - y1 % p z1
end function | def negate(self, p1):
x1, y1, z1 = p1
return (x1, (self.p - y1) % self.p, z1) | Python | nomic_cornstack_python_v1 |
class Pelicula
begin
function __init__ self nombre
begin
set __nombre = nombre
end function
function __str__ self
begin
return __nombre
end function
function set_nombre self nombre
begin
set __nombre = nombre
end function
function get_nombre self
begin
return __nombre
end function
end class | class Pelicula:
def __init__(self, nombre):
self.__nombre=nombre
def __str__(self):
return self.__nombre
def set_nombre (self, nombre):
self.__nombre= nombre
def get_nombre (self):
return self.__nombre | Python | zaydzuhri_stack_edu_python |
function play_video self video_id
begin
if video_id in _videos
begin
if playing == string
begin
if pause == string
begin
set play = _title
print format string Playing video: {} play
set playing = video_id
set pause = string
end
else
begin
set stop = _title
set play = _title
print format string Stopping video: {} sto... | def play_video(self, video_id):
if video_id in self._video_library._videos:
if self.playing=="":
if self.pause=="":
play=self._video_library._videos[video_id]._title
print("Playing video: {}".format(play))
self.playing=video... | Python | nomic_cornstack_python_v1 |
import numpy as np
function choose_action env Q observation epsilon
begin
string Chose a action either random or based on Q-Values :param env: :param Q: :param observation: :param epsilon: :return:
if uniform 0 1 < epsilon
begin
set action = random sample
end
else
begin
set action = argument maximum Q at tuple observat... | import numpy as np
def choose_action(env, Q, observation, epsilon):
"""
Chose a action either random or based on Q-Values
:param env:
:param Q:
:param observation:
:param epsilon:
:return:
"""
if np.random.uniform(0, 1) < epsilon:
action = env.action_space.sample()
else... | Python | zaydzuhri_stack_edu_python |
from libs.graphics import *
from models.Corpse import *
class GoopieUpdateManager
begin
function __init__ self goopie
begin
set goopie = goopie
end function
function updateSkin self
begin
call undraw
set body = call Circle call Point x y radius
call setWidth 1
call setOutline color
call draw win
call setFill string lig... | from libs.graphics import *
from models.Corpse import *
class GoopieUpdateManager:
def __init__(self,goopie):
self.goopie = goopie
def updateSkin(self):
self.goopie.body.undraw()
self.goopie.body = Circle(Point(self.goopie.x, self.goopie.y), self.goopie.radius)
self.goopie.bod... | Python | zaydzuhri_stack_edu_python |
from Numeric import *
set MAX = 30001
set NP = 0
set Prime = list
append Prime 2
set IsP = ones MAX
set IsP at 1 = 0
function Gen
begin
for i in array range 2 MAX / 2
begin
set IsP at 2 * i = 0
end
set n = 3
set NIsP = 1
while n < MAX
begin
if IsP at n == 1
begin
append Prime n
set NIsP = NIsP + 1
for i in array range ... | from Numeric import *;
MAX = 30001; NP = 0; Prime = list();
Prime.append(2); IsP = ones(MAX); IsP[1] = 0;
def Gen():
for i in arange(2,MAX/2):
IsP[2*i] = 0;
n = 3;
NIsP = 1;
while (n < MAX):
if (IsP[n] == 1):
Prime.append(n);
NIs... | Python | zaydzuhri_stack_edu_python |
function wait_start_success self
begin
set _timeout = timeout_ready
if _timeout <= 0
begin
set _timeout = none
end
else
begin
set _timeout = _timeout / 1000.0
end
if wait ready_or_shutdown _timeout
begin
if call is_set
begin
comment return too early and the shutdown is set, means something fails!!
if hide_exc_info
begi... | def wait_start_success(self):
_timeout = self.args.timeout_ready
if _timeout <= 0:
_timeout = None
else:
_timeout /= 1e3
if self.ready_or_shutdown.wait(_timeout):
if self.is_shutdown.is_set():
# return too early and the shutdown is set,... | Python | nomic_cornstack_python_v1 |
function prepare_dir path
begin
set dirname = directory name path path
comment 当前目录直接返回
if not dirname
begin
return none
end
with global_lock
begin
make directories dirname exist_ok=true
end
end function | def prepare_dir(path):
dirname = os.path.dirname(path)
# 当前目录直接返回
if not dirname: return None
with global_lock:
os.makedirs(dirname, exist_ok=True) | Python | nomic_cornstack_python_v1 |
function segment_bf seq score_func
begin
comment necessary for log prob
set maxsc = decimal string -inf
set bestseg = none
for seg in call segment_r seq
begin
comment np.prod([score_func(w) for w in seg])
set score = sum list comprehension call score_func w for w in seg
if score > maxsc
begin
set bestseg = seg
set maxs... | def segment_bf(seq, score_func):
maxsc = float('-inf') # necessary for log prob
bestseg = None
for seg in segment_r(seq):
score = sum([score_func(w) for w in seg]) # np.prod([score_func(w) for w in seg])
if score > maxsc:
bestseg = seg
maxsc = score
return max... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
from urllib.request import urlopen
import pandas as pd
import time
comment Dicionario criado com os dados para cada anuncio
set todos = dict
comment Lista de dicionarios com todos os anuncios
set lista = list
comment Lista com os links de todos os anuncios
set href = list
set ul = list ... | from bs4 import BeautifulSoup
from urllib.request import urlopen
import pandas as pd
import time
todos={} #Dicionario criado com os dados para cada anuncio
lista=[] #Lista de dicionarios com todos os anuncios
href=[] #Lista com os links de todos os anuncios
ul=[]
page = 1 #Contador das páginas
links=[] # todos as tag... | Python | zaydzuhri_stack_edu_python |
function state_machines_set_notification self model prop_name info
begin
string Observe all open state machines and their root states
if info at string method_name == string __setitem__
begin
set state_machine_m = args at 1
call observe_model state_machine_m
end
end function | def state_machines_set_notification(self, model, prop_name, info):
"""Observe all open state machines and their root states
"""
if info['method_name'] == '__setitem__':
state_machine_m = info.args[1]
self.observe_model(state_machine_m) | Python | jtatman_500k |
class Node
begin
function __init__ self data
begin
set data = data
set nextElement = none
end function
end class
class LinkedList
begin
function __init__ self
begin
set headNode = call Node none
end function
comment Insertion at Head
function insertAtHead self dt
begin
comment Create a new node containing your specifie... | class Node:
def __init__(self, data):
self.data = data
self.nextElement = None
class LinkedList:
def __init__(self):
self.headNode = Node(None)
# Insertion at Head
def insertAtHead(self, dt):
tempNode = Node(dt) # Create a new node containing your specified value
... | Python | zaydzuhri_stack_edu_python |
for i in range length NN at 0
begin
for j in range length NN at 1
begin
set curr = NN at i at j
end
end | for i in range(len(NN[0])):
for j in range(len(NN[1])):
curr = NN[i][j] | Python | zaydzuhri_stack_edu_python |
function _parse_docstring docstring
begin
string parses docstring into its help message and params
set params = dict
if not docstring
begin
return tuple none params
end
try
begin
set help_msg = call group
set help_msg = call _strip_lines help_msg
end
except AttributeError
begin
set help_msg = none
end
for param in cal... | def _parse_docstring(docstring):
"""parses docstring into its help message and params"""
params = {}
if not docstring:
return None, params
try:
help_msg = _DOCSTRING_REGEX.search(docstring).group()
help_msg = _strip_lines(help_msg)
except AttributeError:
help_msg = ... | Python | jtatman_500k |
function get_gcd2 a b
begin
set rem = a % b
while rem != 0
begin
set a = b
set b = rem
set rem = a % b
end
print string The GCD of the Number (Method2): b
end function | def get_gcd2(a, b):
rem = a % b
while rem !=0:
a = b
b = rem
rem = a % b
print("The GCD of the Number (Method2): ", b) | Python | nomic_cornstack_python_v1 |
function surface_features self st=string 2000-10-14 en=string 2016-11-12
begin
set fname = join path ds_dir string surf_feat string SEDOO_EdS_Houay Pano.xlsx
set df = call read_excel fname sheet_name=string Soil surface features
set index = call to_datetime pop df string Date
if st
begin
if is instance en int
begin
ass... | def surface_features(
self,
st: Union[str, int, pd.Timestamp] = '2000-10-14',
en: Union[str, int, pd.Timestamp] = '2016-11-12',
)->pd.DataFrame:
fname = os.path.join(
self.ds_dir, "surf_feat", "SEDOO_EdS_Houay Pano.xlsx")
df = pd.read_excel(fname, shee... | Python | nomic_cornstack_python_v1 |
function go_to self x_map y_map yaw_map
begin
call loginfo string Going to pose x = %s, y = %s, yaw = %s. % tuple x_map y_map yaw_map
set goal = call MoveBaseGoal
set header = call Header stamp=now frame_id=string /map
set pose = call _x_y_yaw_to_pose x_map y_map yaw_map
call send_goal goal
call loginfo string Send goa... | def go_to(self, x_map, y_map, yaw_map):
loginfo("Going to pose x = %s, y = %s, yaw = %s." %
(x_map, y_map, yaw_map))
goal = MoveBaseGoal()
goal.target_pose.header = Header(stamp=Time.now(), frame_id = '/map')
goal.target_pose.pose = self._x_y_yaw_to_pose(x_map, y_map, yaw... | Python | nomic_cornstack_python_v1 |
function alphabetical_sorted iterable cmp=none key=lambda x -> lower x reverse=false
begin
return sorted iterable cmp key reverse
end function | def alphabetical_sorted(iterable, cmp=None, key=lambda x: x.lower(),
reverse=False):
return sorted(iterable, cmp, key, reverse) | Python | nomic_cornstack_python_v1 |
function on_session_started session_started_request session
begin
print string on_session_started requestId= + session_started_request at string requestId + string , sessionId= + session at string sessionId
end function | def on_session_started(session_started_request, session):
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId']) | Python | nomic_cornstack_python_v1 |
from tqdm import tqdm , trange
from time import sleep
set bar = call trange 6
for i in bar
begin
comment Print using tqdm class method .write()
sleep 0.1
if not i % 3
begin
write tqdm string Done task %i % i
end
end
print string done! | from tqdm import tqdm, trange
from time import sleep
bar = trange(6)
for i in bar:
# Print using tqdm class method .write()
sleep(0.1)
if not (i % 3):
tqdm.write("Done task %i" % i)
print("done!") | Python | zaydzuhri_stack_edu_python |
string Preprocessing - Step. b : .npy files merge ; Preprocessing step a. 에서 생성된 .npy 파일들을 하나의 .npy 파일로 병합 및 Train/Test set 으로 split 해서 Dataset 완성 1. Partial Data(X) .npy file Merge 2. Partial Target(Y) .npy file Merge 3. Data(X), Target(Y) Merge and Train / Test Split
import numpy as np
from sklearn.model_selection im... | """
Preprocessing
- Step. b : .npy files merge
; Preprocessing step a. 에서 생성된 .npy 파일들을
하나의 .npy 파일로 병합 및 Train/Test set 으로 split 해서 Dataset 완성
1. Partial Data(X) .npy file Merge
2. Partial Target(Y) .npy file Merge
3. Data(X), Target(Y) Merge and Train / Test Split
"""
... | Python | zaydzuhri_stack_edu_python |
function test_fdviolation2_operator agencies
begin
set rhs = list string borough string state
set lhs = string agency
set fd = call fd_violations df=agencies lhs=lhs rhs=rhs
assert length fd == 3
assert shape at 0 == 2
assert shape at 0 == 3
assert string DSNY not in keys fd
end function | def test_fdviolation2_operator(agencies):
rhs = ['borough', 'state']
lhs = 'agency'
fd = fd_violations(df=agencies, lhs=lhs, rhs=rhs)
assert len(fd) == 3
assert fd.get(('NYPD')).shape[0] == 2
assert fd.get(('FDNY')).shape[0] == 3
assert 'DSNY' not in fd.keys() | Python | nomic_cornstack_python_v1 |
function calc_results_metrics self df is_test
begin
set pred = df at string raw_predict
set y = df at string results
set acc_dict = dict string baseline tuple mean y count y ; string acc_proba call accuracy_proba pred y ; string acc_clf call accuracy_classifier pred y ; string prec_20 call precision_metric pred y 0.2 t... | def calc_results_metrics(self, df, is_test):
pred = df['raw_predict']
y = df['results']
acc_dict = {'baseline': (y.mean(), y.count()), 'acc_proba': accuracy_proba(pred, y),
'acc_clf': accuracy_classifier(pred, y),
'prec_20': precision_metric(pred, y, 0.2, ... | Python | nomic_cornstack_python_v1 |
function convert_date date
begin
if call is_str date
begin
if string : in date
begin
set date = date at slice : 10 :
end
return call date
end
else
if is instance date datetime
begin
return call date
end
else
if is instance date date
begin
return date
end
raise call ParamsError string date 必须是datetime.date, datetime.d... | def convert_date(date):
if is_str(date):
if ':' in date:
date = date[:10]
return datetime.datetime.strptime(date, '%Y-%m-%d').date()
elif isinstance(date, datetime.datetime):
return date.date()
elif isinstance(date, datetime.date):
return date
raise ParamsErro... | Python | nomic_cornstack_python_v1 |
function partition arr low high
begin
set pivot = arr at high
set i = low
for j in range low high
begin
if arr at j <= pivot
begin
set tuple arr at i arr at j = tuple arr at j arr at i
set i = i + 1
end
end
set tuple arr at i arr at high = tuple arr at high arr at i
return i
end function
function quickselect arr low hi... | def partition(arr, low, high):
pivot = arr[high]
i = low
for j in range(low, high):
if arr[j] <= pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[high] = arr[high], arr[i]
return i
def quickselect(arr, low, high, k):
if low < high:
pivot_index = ... | Python | jtatman_500k |
from __future__ import division
import numpy as np
import random
set cache_size = 200
set l = list comprehension i for i in range 500
set samples = list
set targets = list
function diff_fun a b
begin
return a - b ^ 2
end function
for ind in range 10000
begin
set contents = random sample l cache_size + 1
set tuple con... | from __future__ import division
import numpy as np
import random
cache_size = 200
l = [i for i in range(500)]
samples = []
targets= []
def diff_fun(a,b):
return (a-b)**2
for ind in range(10000):
contents = random.sample(l,cache_size+1)
contents,key_out = contents[:-1],contents[-1]
noise = random.randi... | Python | zaydzuhri_stack_edu_python |
function get_configured_provider vm_=none
begin
string Return the contextual provider of None if no configured one can be found.
if vm_ is none
begin
set vm_ = dict
end
set tuple dalias driver = split __active_provider_name__ string :
set data = none
set tgt = string unknown
set img_provider = get __opts__ string list... | def get_configured_provider(vm_=None):
'''
Return the contextual provider of None if no configured
one can be found.
'''
if vm_ is None:
vm_ = {}
dalias, driver = __active_provider_name__.split(':')
data = None
tgt = 'unknown'
img_provider = __opts__.get('list_images', '')
... | Python | jtatman_500k |
comment array = [[1, 2], [3, 4]]
set array = list list 0 1 2 3 list 4 5 6 7 list 8 9 10 11 list 12 13 14 15
for i in range 0 length array // 2
begin
set no_of_rows = length array - 1
set no_of_cols = length array - 1 - i
for j in range 0 no_of_cols
begin
set tmp = array at i at j
comment print array
set array at i at j... | #array = [[1, 2], [3, 4]]
array = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
for i in range(0, len(array) // 2):
no_of_rows = len(array) - 1
no_of_cols = len(array) - 1 - i
for j in range(0, no_of_cols):
tmp = array[i][j]
#print array
array[i][j] = array[(no_of_r... | Python | zaydzuhri_stack_edu_python |
string 2020-12-27 兰州 晴 运气,就是机会碰巧撞到了你的努力。 爬取堆图网的萌宠头像的图片。将图片保存到本地
import requests
from pyquery import PyQuery
import logging
import time
call basicConfig level=INFO format=string %(asctime)s - %(levlename)s - %(message)s
comment 请求头
set headers = dict string Accept string text/html,application/xhtml+xml,application/xml;q... | '''
2020-12-27 兰州 晴
运气,就是机会碰巧撞到了你的努力。
爬取堆图网的萌宠头像的图片。将图片保存到本地
'''
import requests
from pyquery import PyQuery
import logging
import time
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levlename)s - %(message)s"
)
#请求头
headers = {
"Accept": "text/html,application/xhtml+xml,application/... | Python | zaydzuhri_stack_edu_python |
function get_task_map_value task
begin
if task at string type == string input
begin
return dict string todo 1 ; string complete 0
end
else
begin
return dict string todo 0 ; string complete 0
end
end function | def get_task_map_value(task):
if task["type"] == "input":
return {"todo": 1, "complete": 0}
else:
return {"todo": 0, "complete": 0} | Python | nomic_cornstack_python_v1 |
function __init__ self model_path config log_path
begin
comment initialize model instance
set model = call MaskRCNN mode=string inference config=config model_dir=log_path
comment load weights
call load_weights model_path by_name=true
end function | def __init__(self, model_path, config, log_path):
# initialize model instance
self.model = modellib.MaskRCNN(mode="inference", config=config,
model_dir=log_path)
# load weights
self.model.load_weights(model_path, by_name=True) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
from __future__ import print_function
import sqlite3
import time
from random import randint
string Can you find the cube root of a number?
class Scores extends object
begin
function __init__ self score e_time
begin
set score = score
set e_time = e_time
set name = string didnotplace
set conn... | #!/usr/bin/env python
from __future__ import print_function
import sqlite3
import time
from random import randint
"""
Can you find the cube root of a number?
"""
class Scores(object):
def __init__(self, score, e_time):
self.score = score
self.e_time = e_time
self.name = "didnotplace"... | Python | zaydzuhri_stack_edu_python |
function replace_fiducials info fiducials
begin
from mne.io import meas_info
set fids = call _make_dig_points keyword fiducials
set info = copy info
set dig = info at string dig
for tuple i d in enumerate dig
begin
if d at string kind == 3
begin
if d at string ident == 3
begin
set dig at i at string r = fids at 2 at st... | def replace_fiducials(info, fiducials):
from mne.io import meas_info
fids = meas_info._make_dig_points(**fiducials)
info = info.copy()
dig = info['dig']
for i, d in enumerate(dig):
if d['kind'] == 3:
if d['ident'] == 3:
dig[i]['r'] = fids[2]['r']
elif ... | Python | nomic_cornstack_python_v1 |
function silly cfg date
begin
call error_prone_distinguish date=date
end function | def silly(cfg, date):
cfg.benji.error_prone_distinguish(date=date) | Python | nomic_cornstack_python_v1 |
function count_read_comp read chrom length comp
begin
set tuple std seq = tuple string + query
if is_reverse
begin
set tuple std seq = tuple string - call revcomp seq
end
call _update_table comp at chrom at string 5p at std seq call xrange 1 length + 1
call _update_table comp at chrom at string 3p at std reversed seq c... | def count_read_comp(read, chrom, length, comp):
std, seq = '+', read.query
if read.is_reverse:
std, seq = '-', mapdamage.seq.revcomp(seq)
_update_table(comp[chrom]['5p'][std], seq, xrange(1, length + 1))
_update_table(comp[chrom]['3p'][std], reversed(seq), xrange(-1, - length - 1, -1)) | Python | nomic_cornstack_python_v1 |
function timestamp2sec timestamp
begin
return integer seconds + 60 * integer minutes + 3600 * integer hours + decimal integer hours / 1000
end function | def timestamp2sec(timestamp):
return (int(timestamp.seconds) + 60 * int(timestamp.minutes) + 3600 * int(timestamp.hours) + float(int(timestamp.hours) / 1000)) | Python | nomic_cornstack_python_v1 |
function get_result self player
begin
string Get the game result from the viewpoint of player.
pass
end function | def get_result(self, player: int) -> float:
""" Get the game result from the viewpoint of player.
"""
pass | Python | nomic_cornstack_python_v1 |
function beautify_file self path
begin
string Beautify bash script file.
set error = false
if path == string -
begin
set data = read stdin
set tuple result error = call beautify_string data string (stdin)
write stdout result
end
else
begin
comment named file
set data = call read_file path
set tuple result error = call ... | def beautify_file(self, path):
"""Beautify bash script file."""
error = False
if(path == '-'):
data = sys.stdin.read()
result, error = self.beautify_string(data, '(stdin)')
sys.stdout.write(result)
else: # named file
data = self.read_file(... | Python | jtatman_500k |
function getTarget self
begin
return call Channel_getTarget self
end function | def getTarget(self):
return _osgAnimation.Channel_getTarget(self) | Python | nomic_cornstack_python_v1 |
function is_vm_waiting_for_answer self
begin
return boolean call call_sdk_function string PrlVmInfo_IsVmWaitingForAnswer handle
end function | def is_vm_waiting_for_answer(self):
return bool(call_sdk_function('PrlVmInfo_IsVmWaitingForAnswer', self.handle)) | Python | nomic_cornstack_python_v1 |
async function test_set_only_target_temp opp
begin
set state = get states ENTITY_CLIMATE
assert 21 == get attributes ATTR_TEMPERATURE
await call async_set_temperature opp 30 ENTITY_CLIMATE
await call async_block_till_done
set state = get states ENTITY_CLIMATE
assert 30.0 == get attributes ATTR_TEMPERATURE
end function | async def test_set_only_target_temp(opp):
state = opp.states.get(ENTITY_CLIMATE)
assert 21 == state.attributes.get(ATTR_TEMPERATURE)
await common.async_set_temperature(opp, 30, ENTITY_CLIMATE)
await opp.async_block_till_done()
state = opp.states.get(ENTITY_CLIMATE)
assert 30.0 == state.attribu... | Python | nomic_cornstack_python_v1 |
function update self dt
begin
comment IMPLEMENT ME
assert type dt == int or type dt == float
if _state == STATE_INACTIVE
begin
call _determineState
if _state == STATE_NEWGAME
begin
call draw
end
end
else
if _state == STATE_NEWGAME
begin
set _game = call Play
call messagePlay
set _state = STATE_COUNTDOWN
end
else
if _st... | def update(self,dt):
# IMPLEMENT ME
assert type(dt)==int or type(dt)==float
if self._state==STATE_INACTIVE:
self._determineState()
if self._state==STATE_NEWGAME:
self.draw()
elif self._state==STATE_NEWGAME:
self._game=Play()
... | Python | nomic_cornstack_python_v1 |
function get_objects_owners obj
begin
set type = call get_type
set owners = list
for user in all
begin
if type == TASK
begin
set relation = get objects user=user task=obj
end
else
if type == EVENT
begin
set relation = get objects user=user event=obj
end
else
if type == PLAN
begin
set relation = get objects user=user p... | def get_objects_owners(obj):
type = obj.get_type()
owners = []
for user in obj.user_set.all():
if type == Entities.TASK:
relation = UserTasks.objects.get(user=user, task=obj)
elif type == Entities.EVENT:
relation = UserEvents.objects.get(user=user, event=obj)
... | Python | nomic_cornstack_python_v1 |
function _get_credentials self method_frame
begin
set tuple auth_type response = call response_for method
if not auth_type
begin
raise call AuthenticationError TYPE
end
call erase_credentials
return tuple auth_type response
end function | def _get_credentials(self, method_frame):
(auth_type,
response) = self.params.credentials.response_for(method_frame.method)
if not auth_type:
raise exceptions.AuthenticationError(self.params.credentials.TYPE)
self.params.credentials.erase_credentials()
return a... | Python | nomic_cornstack_python_v1 |
function conv3x3 in_planes out_planes stride=1 groups=1 dilation=1
begin
return conv 2d in_planes out_planes kernel_size=3 stride=stride padding=dilation groups=groups bias=false dilation=dilation
end function | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation) | Python | nomic_cornstack_python_v1 |
function __data self
begin
set gas_conc = array list
set datetime_array = array list
for tuple index row in enumerate file_data
begin
comment care, there are two date and time columns that may be swtiched
set date = split row at 0 string -
set time = split row at 1 string :
set year = integer date at 0
set month = inte... | def __data(self):
gas_conc = np.array([])
datetime_array = np.array([])
for index, row in enumerate(self.file_data):
#care, there are two date and time columns that may be swtiched
date = row[0].split('-')
time = row[1].split(':')
... | Python | nomic_cornstack_python_v1 |
function to_dict _class
begin
set return_dict = dict string name call identifier ; string description call description
return return_dict
end function | def to_dict(_class):
return_dict = {
'name': _class.identifier(),
'description': _class.description()
}
return return_dict | Python | nomic_cornstack_python_v1 |
comment == is comparing have to use '' because g is a string
if credit == string g
begin
set total_price = price - price / 10
print total_price
end
else
if credit == string b
begin
set total_price = price
print total_price
end
else
begin
print string Invalid input
end | if credit=='g': #== is comparing have to use '' because g is a string
total_price=price-price/10
print(total_price)
elif credit=='b':
total_price=price
print(total_price)
else:
print("Invalid input")
| Python | zaydzuhri_stack_edu_python |
function _unpack_grid self packing_type part
begin
if packing_type == none
begin
set lendat = data_header_length - header_length - 1
if lendat > 1
begin
set buffer_fmt = string { prefmt } { lendat } f
set buffer = call read_struct call Struct buffer_fmt
set grid = zeros ky * kx dtype=float32
set grid at Ellipsis = buff... | def _unpack_grid(self, packing_type, part):
if packing_type == PackingType.none:
lendat = self.data_header_length - part.header_length - 1
if lendat > 1:
buffer_fmt = f'{self.prefmt}{lendat}f'
buffer = self._buffer.read_struct(struct.Struct(buffer_fmt))
... | Python | nomic_cornstack_python_v1 |
from string import *
comment Variables used for finding start codons
set start_codon_index = - 1
set stop_codon_index = - 1
comment Variables used for finding stop codons
set start_codon_count = 0
set stop_codon_count = 0
set seqDNA = string AGGTATGGGCCTTTAAAGTG
set start_codon_index = find seqDNA string ATG
set start_... | from string import *
#Variables used for finding start codons
start_codon_index=-1
stop_codon_index=-1
#Variables used for finding stop codons
start_codon_count=0
stop_codon_count=0
seqDNA='AGGTATGGGCCTTTAAAGTG'
start_codon_index=find(seqDNA,'ATG')
start_codon_count=count(seqDNA,'ATG')
stop_codon_index=find(seqDNA,'... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment @file logger.py
comment @brief Logging system class
comment Daryl Dang - 2021
comment IMPORTS #
import logging
from enum import IntEnum , auto
comment CONSTANTS #
set LOGGING_FILE_NAME = string log.log
comment GLOBALS #
comment Class Definitions #
class VerbosityLevel extends IntEn... | #!/usr/bin/env python3
# @file logger.py
# @brief Logging system class
# Daryl Dang - 2021
###########
# IMPORTS #
###########
import logging
from enum import IntEnum, auto
#############
# CONSTANTS #
#############
LOGGING_FILE_NAME = "log.log"
###########
# GLOBALS #
###########
#####################
# Clas... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string (Compute the volume of a cylinder) Write a program that reads in the radius and length of a cylinder and computes the area and volume using the following formulas: area = radius * radius * π volume = area * length Here is a sample run: Enter the radius and length of a cylinder: 5.5,... | # -*- coding: utf-8 -*-
'''
(Compute the volume of a cylinder) Write a program that
reads in the radius and length of a cylinder and computes the
area and volume using the following formulas:
area = radius * radius * π volume = area * length
Here is a sample run:
Enter the radius and length of a cylinder: ... | Python | zaydzuhri_stack_edu_python |
string Python Program to read the content from File and convert it to a list
with open string C:\Users\nekapoor\git\Python-and-Django\PYTHON PROGRAMS\file_data\word.txt string r encoding=string utf-8 as file1
begin
set linelist = read lines file1
set linelist = list
with open string C:\Users\nekapoor\git\Python-and-Dja... | """Python Program to read the content from File and convert it to a list"""
with open("C:\\Users\\nekapoor\\git\\Python-and-Django\\PYTHON PROGRAMS\\file_data\\word.txt", 'r', encoding='utf-8') as file1:
linelist = file1.readlines()
linelist = list()
with open("C:\\Users\\nekapoor\\git\\Python-and-Django\... | Python | zaydzuhri_stack_edu_python |
import math
function print_integers
begin
set count = 0
set number = 10
while count < 10
begin
if number % 3 != 0
begin
set square_root = square root number
print number square_root
set count = count + 1
end
set number = number - 1
end
end function
call print_integers | import math
def print_integers():
count = 0
number = 10
while count < 10:
if number % 3 != 0:
square_root = math.sqrt(number)
print(number, square_root)
count += 1
number -= 1
print_integers()
| Python | greatdarklord_python_dataset |
comment coding:utf-8
import os
from flask import Flask
from flask_login import LoginManager , login_required , login_user , logout_user , current_user
from sqlalchemy.ext.declarative import declarative_base
from flask import request , render_template
from Model.database import Db
set db = call Db
set app = call Flask _... | #coding:utf-8
import os
from flask import Flask
from flask_login import LoginManager, login_required, login_user, logout_user, current_user
from sqlalchemy.ext.declarative import declarative_base
from flask import request, render_template
from Model.database import Db
db = Db()
app = Flask(__name__)
app.secret... | Python | zaydzuhri_stack_edu_python |
comment Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
comment Importing the dataset
set dataInt = read csv string ./data_set1/input_training_ssnsrY0.csv
set dataTest = read csv string ./data_set1/input_test_cdKcI0e.csv
set dataOut = read csv string ./data_set1/output_tra... | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataInt = pd.read_csv('./data_set1/input_training_ssnsrY0.csv')
dataTest = pd.read_csv('./data_set1/input_test_cdKcI0e.csv')
dataOut = pd.read_csv('./data_set1/output_training_Uf11I9I.csv')
import... | Python | zaydzuhri_stack_edu_python |
comment 导入整个模块
import pizza
comment 使用方法:module_name.function_name()
call make_pizza 16 string pepperoni
call make_pizza 12 string mushrooms string green peppers string extra cheese | # 导入整个模块
import pizza
# 使用方法:module_name.function_name()
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
| Python | zaydzuhri_stack_edu_python |
function test_blank_data self
begin
set form = call PostForm dict
assert false call is_valid
assert equal errors dict string title list string This field is required. ; string intro list string This field is required. ; string text_content list string This field is required.
end function | def test_blank_data(self):
form = forms.PostForm({})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {
'title': ['This field is required.'],
'intro': ['This field is required.'],
'text_content': ['This field is required.'],
}) | Python | nomic_cornstack_python_v1 |
from Fatura import Fatura
set fatura = call Fatura 1 string Livros de programacao 1 80.0
print string Total da fatura = call calcular_valor_fatura | from Fatura import Fatura
fatura = Fatura(1, "Livros de programacao", 1, 80.00)
print("Total da fatura = ",fatura.calcular_valor_fatura()) | Python | zaydzuhri_stack_edu_python |
function reset self
begin
set array at Ellipsis = 0
end function | def reset(self):
self.array[...] = 0 | Python | nomic_cornstack_python_v1 |
for i in reversed range 1 11
begin
print i
end | for i in reversed(range(1,11)):
print(i) | Python | jtatman_500k |
function __traverse_dir self
begin
comment get contents of directory
set contents = list directory __path
comment filter - exclude all but .png files
set contents = filter lambda item -> item at slice - 4 : : == string .png contents
comment check files are present
if not length contents > 0
begin
raise exception form... | def __traverse_dir(self):
# get contents of directory
contents = os.listdir(self.__path)
# filter - exclude all but .png files
contents = filter(lambda item: item[-4:] == ".png", contents)
# check files are present
if not len(contents) > 0:
raise Exception("... | Python | nomic_cornstack_python_v1 |
class TigrCommand
begin
function __init__ self drawer_command args
begin
set drawer_command = drawer_command
set args = args
end function
function execute self drawer
begin
try
begin
return call call __getattribute__ drawer_command *self.args
end
except AttributeError
begin
raise call SyntaxError string Command { drawe... | class TigrCommand:
def __init__(self, drawer_command, args):
self.drawer_command = drawer_command
self.args = args
def execute(self, drawer):
try:
return drawer.__getattribute__(self.drawer_command)(*self.args)
except AttributeError:
raise SyntaxError(f'C... | Python | zaydzuhri_stack_edu_python |
function parent self
begin
return __parent
end function | def parent(self):
return self.__parent | Python | nomic_cornstack_python_v1 |
function cleanup_service self factory svc_registration
begin
comment type: (Any, ServiceRegistration) -> bool
string If this bundle used that factory, releases the reference; else does nothing :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: True if the bundle was usi... | def cleanup_service(self, factory, svc_registration):
# type: (Any, ServiceRegistration) -> bool
"""
If this bundle used that factory, releases the reference; else does
nothing
:param factory: The service factory
:param svc_registration: The ServiceRegistration object
... | Python | jtatman_500k |
class Product
begin
function __init__ self name cost
begin
set name = name
set cost = cost
end function
end class
function calculate_total_cost products quantity
begin
set total_cost = 0
if length products != length quantity
begin
raise call ValueError string Invalid input lengths
end
for i in range length products
beg... | class Product:
def __init__(self, name, cost):
self.name = name
self.cost = cost
def calculate_total_cost(products, quantity):
total_cost = 0
if len(products) != len(quantity):
raise ValueError("Invalid input lengths")
for i in range(len(products)):
if quantity... | Python | jtatman_500k |
function show self window frame
begin
image show window add cv2 frame eyes_frame
end function | def show(self, window, frame):
cv2.imshow(window, cv2.add(frame, self.eyes_frame)) | Python | nomic_cornstack_python_v1 |
comment !user/bin/python
comment -*- coding: UTF-8 -*-
import numpy as np
function numerical_gradient f x
begin
set h = 0.0001
set grad = zeros like x
set it = call nditer x flags=list string multi_index op_flags=list string readwrite
while not finished
begin
set temp_idx = x at multi_index
comment 先算f(x + h)
comment 这... | # !user/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
def numerical_gradient(f, x):
h = 1e-4
grad = np.zeros_like(x)
it = np.nditer(x, flags = ['multi_index'], op_flags = ['readwrite'])
while not it.finished:
temp_idx = x[it.multi_index]
# 先算f(x + h)
# 这... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string Created on Mon Sep 26 08:26:14 2016 @author: rishu
import numpy as np
import bfast as bf
import ewmacd as ew
import landTrendR as ltr
comment for remote desktop:
comment import matplotlib as mpl
comment mpl.use('Agg')
from collections import defaultdict
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 26 08:26:14 2016
@author: rishu
"""
import numpy as np
import bfast as bf
import ewmacd as ew
import landTrendR as ltr
# for remote desktop:
#import matplotlib as mpl
#mpl.use('Agg')
from collections import defaultdict
from matplotlib import pylab... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
comment Jose Antonio Gómez Piñero - P7Ej7 - DAM - "24/11/2019"
comment Escribe un programa que lea una frase, y la pase como parámetro a un procedimiento. El procedimiento contará el
comment número de vocales (de cada una) que aparecen, y lo imprimirá por pantalla.
set frase = input string Escribe ... | # coding=utf-8
# Jose Antonio Gómez Piñero - P7Ej7 - DAM - "24/11/2019"
# Escribe un programa que lea una frase, y la pase como parámetro a un procedimiento. El procedimiento contará el
# número de vocales (de cada una) que aparecen, y lo imprimirá por pantalla.
frase=input("Escribe tu frase aqui: ")
def f(frase):
... | Python | zaydzuhri_stack_edu_python |
import re
from typing import Dict , Any , List , Tuple , Optional , Union
from src.utility import assert_is_experiment
class Parameters
begin
function __init__ self experiment properties
begin
from src.experiment.experiment import Experiment
set _experiment : Experiment = call assert_is_experiment experiment
set _param... | import re
from typing import Dict, Any, List, Tuple, Optional, Union
from src.utility import assert_is_experiment
class Parameters:
def __init__(self, experiment: Any, properties: Dict[str, Any]):
from src.experiment.experiment import Experiment
self._experiment: Experiment = assert_is_experimen... | Python | zaydzuhri_stack_edu_python |
import string
import numpy as np
comment 0
set GRID = list list 1 1 1 1 1 0 1 0 1 1 1 list 1 0 1 0 1 1 1 1 1 0 1 list 1 1 1 1 1 0 1 0 1 0 1 list 1 0 1 0 1 1 1 1 1 1 1 list 1 0 1 0 0 0 1 0 1 0 0 list 1 1 1 1 1 1 1 1 1 1 1 list 0 0 1 0 1 0 0 0 1 0 1 list 1 1 1 1 1 1 1 0 1 0 1 list 1 0 1 0 1 0 1 1 1 1 1 list 1 0 1 1 1 1 1... | import string
import numpy as np
GRID = [[1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1], # 0
[1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1], # 1
[1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1], # 2
[1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1], # 3
[1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0], # 4
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Example 1: Input: [1,3,null,null,2] 1 / 3 2 Output: [3,1,null,null,2] 3 / 1 2 Example 2: Input: [3,1,4,null,null,2] 3 / 1 4 / 2 Output: [2,1,4,null,null,3] 2 / 1 4 / 3... | # -*- coding: utf-8 -*-
"""
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
Example 2:
Input: [3,1,4,null,null,2]
3
/ \
1 4
/
2
... | Python | zaydzuhri_stack_edu_python |
function _get_ssids self
begin
return __ssids
end function | def _get_ssids(self):
return self.__ssids | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from PIL import Image
import time , random , json
import urllib
import urllib.request
import base64
import json
set driver = call Firefox
function driver_init
begin
get driver string http://www.5itest.cn/register
comment 浏览器窗口最大化
call maximize_window
sleep 5
end function
function get_elem... | from selenium import webdriver
from PIL import Image
import time , random , json
import urllib
import urllib.request
import base64
import json
driver = webdriver.Firefox()
def driver_init():
driver.get("http://www.5itest.cn/register")
driver.maximize_window() #浏览器窗口最大化
time.sleep(5)
def get... | Python | zaydzuhri_stack_edu_python |
import sys
import re
from helpers import highlight , applyStartCodes
comment argv is commandline arguments, argv[0] is program name
if length argv == 4
begin
comment Reads line by line
with open argv at - 3 string r as syn
begin
set syntax = call splitlines
close syn
end
with open argv at - 2 string r as them
begin
set... | import sys
import re
from helpers import highlight, applyStartCodes
# argv is commandline arguments, argv[0] is program name
if (len(sys.argv) == 4):
# Reads line by line
with open(sys.argv[-3], "r") as syn:
syntax = syn.read().splitlines()
syn.close()
with open(sys.argv[-2], "r") as them:... | Python | zaydzuhri_stack_edu_python |
import math
set n = integer input string enter a number:
set i = 2
while i <= absolute integer square root n
begin
if n % i == 0
begin
print n string is not a prime number
break
end
set i = i + 1
end
while else
begin
print n string is a prime number
end | import math
n=int(input("enter a number:"))
i=2
while i<=abs(int(math.sqrt(n))):
if(n%i==0):
print(n,"is not a prime number")
break
i+=1
else:
print(n,"is a prime number")
| Python | zaydzuhri_stack_edu_python |
function report_cur_lr self optimizer
begin
for tuple idx group in enumerate param_groups
begin
set updated_lr = group at string lr
info string [Learning Rate] group { idx } : { updated_lr }
end
end function | def report_cur_lr(self, optimizer):
for idx, group in enumerate(optimizer.param_groups):
updated_lr = group["lr"]
logger_.info(f"[Learning Rate] group{idx}: {updated_lr}") | Python | nomic_cornstack_python_v1 |
comment !usr/bin/env python3
comment -*- coding: utf-8 -*-
import numpy as np
import os
function write file value
begin
set file = open file_path string a
if is instance value int
begin
write file
end
end function
string 作用在于: store_resutl(): 进行数据储存; reveal_last(): 定期输出该期间的平均值; write_last(): 定期将平均值结果写入文件,防止数据丢失; write_... | #!usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import os
def write(file, value):
file = open(file_path, 'a')
if isinstance(value, int):
file.write()
'''
作用在于:
store_resutl(): 进行数据储存;
reveal_last(): 定期输出该期间的平均值;
write_last(): 定期将平均值结果写入文件,防止数据丢失;
write_final(): 将每次保存的数据进行写入,不止是平均... | Python | zaydzuhri_stack_edu_python |
function predict_single self observation
begin
if obs_normalizer
begin
set observation = call obs_normalizer observation
end
set action = call predict_target call expand_dims observation axis=0
set action = squeeze np action axis=0
if action_processor
begin
set action = call action_processor action
end
return action
en... | def predict_single(self, observation):
if self.obs_normalizer:
observation = self.obs_normalizer(observation)
action = self.actor.predict_target(np.expand_dims(observation, axis=0))
action = np.squeeze(action,axis=0)
if self.action_processor:
action = self.action_... | Python | nomic_cornstack_python_v1 |
function dimensionality network
begin
return call dimensionality network
end function | def dimensionality(network):
return skgr.tools.dimensionality(network) | Python | nomic_cornstack_python_v1 |
function gcd A B
begin
while B != 0
begin
set C = A % B
set A = B
set B = C
end
return A
end function
comment Example usage
set A = 54
set B = 24
set result = call gcd A B
print string The GCD of A string and B string is: result | def gcd(A, B):
while B != 0:
C = A % B
A = B
B = C
return A
# Example usage
A = 54
B = 24
result = gcd(A, B)
print("The GCD of", A, "and", B, "is:", result)
| Python | jtatman_500k |
import heapq
import numpy as np
string Default query of the weight of a link. We only use the number of cells of a lane in Case 0: no information
function __default_weight_query link
begin
return call get_weight
end function
string Query of the weight of a link based on its long-term stigmergy cost. By default (until u... | import heapq
import numpy as np
"""
Default query of the weight of a link.
We only use the number of cells of a lane in Case 0: no information
"""
def __default_weight_query(link):
return link.get_weight()
"""
Query of the weight of a link based on its long-term stigmergy cost.
By default (until updated), long-term... | Python | zaydzuhri_stack_edu_python |
function transition_evaluation self transition_evaluation
begin
set container at string transition_evaluation = transition_evaluation
end function | def transition_evaluation(self, transition_evaluation):
self.container['transition_evaluation'] = transition_evaluation | Python | nomic_cornstack_python_v1 |
function remove_numbers arr
begin
set new_arr = list
for el in arr
begin
if not is instance el int
begin
append new_arr el
end
end
return new_arr
end function
set a = list 3 1 4 5 6 2
print call remove_numbers a | def remove_numbers(arr):
new_arr = []
for el in arr:
if not isinstance(el, int):
new_arr.append(el)
return new_arr
a = [3, 1, 4, 5, 6, 2]
print(remove_numbers(a)) | Python | jtatman_500k |
function fibonacci num
begin
if fibo_list at num - 1 != 0
begin
return fibo_list at num - 1
end
else
if num == 1 or num == 2
begin
set fibo_list at 0 = 1
set fibo_list at 1 = 1
return 1
end
else
begin
set fibo_list at num - 1 = call fibonacci num - 1 + call fibonacci num - 2
return fibo_list at num - 1
end
end function... | def fibonacci(num):
if fibo_list[num-1]!=0:
return fibo_list[num-1]
else:
if num==1 or num==2:
fibo_list[0]=1
fibo_list[1]=1
return 1
else:
fibo_list[num-1]=fibonacci(num-1)+fibonacci(num-2)
return fibo_list[num-1]
num=int(inpu... | Python | zaydzuhri_stack_edu_python |
function toPathValue self obj
begin
if type obj == list
begin
return quote join string , obj
end
else
begin
return quote string obj
end
end function | def toPathValue(self, obj):
if type(obj) == list:
return urllib.parse.quote(",".join(obj))
else:
return urllib.parse.quote(str(obj)) | Python | nomic_cornstack_python_v1 |
comment coding=gbk
set __author__ = string renfei
set length = 4
set breadth = 5
set area = length * breadth
print string Area is area
print string ܳ 2 * length + breadth | # coding=gbk
__author__ = 'renfei'
length = 4
breadth = 5
area = length * breadth
print("Area is ",area)
print("ܳ",2*(length+breadth))
| Python | zaydzuhri_stack_edu_python |
class TransGenerator extends object
begin
function __init__ self concurrency
begin
set concurrency = concurrency
set dates = list string 2017-11-08
set inputFile = open concurrency + string / + dates at 0 + string sort string r
set inputSQL = read lines inputFile
set inputIndex = - 1
end function
function getNext self
... | class TransGenerator(object):
def __init__(self, concurrency):
self.concurrency = concurrency
self.dates = ['2017-11-08']
self.inputFile = open(self.concurrency + '/' + self.dates[0] + 'sort', 'r')
self.inputSQL = self.inputFile.readlines()
self.inputIndex = -1;
def getNext(self):
try:
self.inputInde... | Python | zaydzuhri_stack_edu_python |
function get_floatingip compute project region ip
begin
set query = string address eq %s % ip
set result = execute list project=project region=region filter=query
if string items in result and length result at string items == 1
begin
return result at string items at 0
end
raise call GceResourceNotFound name=string Floa... | def get_floatingip(compute, project, region, ip):
query = 'address eq %s' % ip
result = compute.addresses().list(project=project, region=region,
filter=query).execute()
if 'items' in result and len(result['items']) == 1:
return result['items'][0]
raise GceR... | Python | nomic_cornstack_python_v1 |
function find_minimum_positive_odd arr
begin
set min_odd = decimal string inf
set found_odd = false
for num in arr
begin
if num > 0 and num % 2 != 0
begin
if num < min_odd
begin
set min_odd = num
end
set found_odd = true
end
end
if not found_odd
begin
return - 1
end
else
begin
return min_odd
end
end function
comment Te... | def find_minimum_positive_odd(arr):
min_odd = float('inf')
found_odd = False
for num in arr:
if num > 0 and num % 2 != 0:
if num < min_odd:
min_odd = num
found_odd = True
if not found_odd:
return -1
else:
return min_odd
# Test the fu... | Python | jtatman_500k |
function pretty self
begin
return name + string - + join string split base name path path string . at slice 0 : - 1 :
end function | def pretty(self):
return self.show.name + ' - ' + \
''.join(os.path.basename(self.path).split('.')[0:-1]) | Python | nomic_cornstack_python_v1 |
function l2_loss var l2_loss_wt
begin
return call multiply decimal l2_loss_wt call l2_loss var
end function | def l2_loss(var, l2_loss_wt):
return tf.multiply(float(l2_loss_wt), tf.nn.l2_loss(var)) | Python | nomic_cornstack_python_v1 |
function __init__ self function line_numbers=none
begin
comment type: (ast.FunctionDef, Tuple[int, int]) -> None
set general_message = string Incorrect indentation
set terse_message = string ~<
call __init__ function line_numbers=line_numbers
end function | def __init__(self, function, line_numbers=None):
# type: (ast.FunctionDef, Tuple[int, int]) -> None
self.general_message = 'Incorrect indentation'
self.terse_message = '~<'
super(IndentError, self).__init__(
function,
line_numbers=line_numbers,
) | Python | nomic_cornstack_python_v1 |
function _clean_email_strings mail
begin
set MAIL_PATTERN = string [A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}
set regex_mail = compile MAIL_PATTERN flags=IGNORECASE
try
begin
return find all mail at 0
end
comment set invalid values (return empty list) to NaN
except IndexError
begin
return NaN
end
comment handle missing valu... | def _clean_email_strings(mail: str) -> str:
MAIL_PATTERN = r"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}"
regex_mail = re.compile(MAIL_PATTERN, flags=re.IGNORECASE)
try:
return regex_mail.findall(mail)[0]
except IndexError: # set invalid values (return empty list) to NaN
return np.NaN
ex... | Python | nomic_cornstack_python_v1 |
function z_algorithm s
begin
set n = length s
if n == 0
begin
return list
end
if type s is str
begin
set s2 = list 0 * n
for tuple i si in enumerate s
begin
set s2 at i = ordinal si
end
set s = s2
end
set z = list 0 * n
set j = 0
for i in range 1 n
begin
set z at i = if expression j + z at j <= i then 0 else min j + z... | def z_algorithm(s):
n = len(s)
if(n == 0):
return []
if(type(s) is str):
s2 = [0] * n
for i, si in enumerate(s):
s2[i] = ord(si)
s = s2
z = [0] * n
j = 0
for i in range(1, n):
z[i] = 0 if (j + z[j] <= i) else min(j + z[j] - i, z[i-j])
w... | Python | zaydzuhri_stack_edu_python |
function is_armed self
begin
return call is_armed_away or call is_armed_home or call is_armed_night or call is_armed_custom_bypass
end function
comment noqa: W504 | def is_armed(self):
return (
self.is_armed_away()
or self.is_armed_home()
or self.is_armed_night() # noqa: W504
or self.is_armed_custom_bypass()
) | Python | nomic_cornstack_python_v1 |
function swapCaseForCharVal v
begin
if v >= 97 and v <= 122
begin
set v = v - 32
end
else
if v >= 65 and v <= 90
begin
set v = v + 32
end
return character v
end function
function swap_case s
begin
return join string list comprehension call swapCaseForCharVal ordinal ch for ch in s
end function
if __name__ == string __... | def swapCaseForCharVal(v):
if v>=97 and v<=122:
v=v-32
elif v>=65 and v<=90:
v=v+32
return chr(v)
def swap_case(s):
return "".join([swapCaseForCharVal(ord(ch)) for ch in s])
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result) | Python | zaydzuhri_stack_edu_python |
string Starts the calibration procedure and creates/removes sensor files
from PyQt5.QtWidgets import QSplitter , QWidget , QVBoxLayout
from PyQt5.QtCore import Qt
from app.gui.panels.calibrationpanel import CalibrationPanel
from app.gui.graphs.gridgraph import GridGraph
class CalibrationTab extends QWidget
begin
string... | """ Starts the calibration procedure and creates/removes sensor files """
from PyQt5.QtWidgets import QSplitter, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
from app.gui.panels.calibrationpanel import CalibrationPanel
from app.gui.graphs.gridgraph import GridGraph
class CalibrationTab(QWidget):
"""
Conta... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.