code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import itertools
import random
function qselect k a
begin
if a == list or k > length a or k == 0
begin
return list
end
else
begin
comment i=random.randint(0,len(a)-1)
comment a[0],a[i]=a[i],a[0]
set pivot = a at 0
set left = list comprehension x for x in a if x at 0 + x at 1 < pivot at 0 + pivot at 1
set splitP = len... | import itertools
import random
def qselect(k,a):
if a == [] or k>len(a) or k==0:
return []
else:
#i=random.randint(0,len(a)-1)
#a[0],a[i]=a[i],a[0]
pivot=a[0]
left = [x for x in a if (x[0]+x[1]) < (pivot[0]+pivot[1]) ]
splitP=len(left)
if ... | Python | zaydzuhri_stack_edu_python |
function getRemainingSecs self
begin
if not __valid
begin
return call S_ERROR string No certificate loaded
end
set notAfter = call get_not_after
set remaining = notAfter - call dateTime
return call S_OK max 0 days * 86400 + seconds
end function | def getRemainingSecs( self ):
if not self.__valid:
return S_ERROR( "No certificate loaded" )
notAfter = self.__certObj.get_not_after()
remaining = notAfter - Time.dateTime()
return S_OK( max( 0, remaining.days * 86400 + remaining.seconds ) ) | Python | nomic_cornstack_python_v1 |
string import numpy as np objective=[1,3] constraint1=[10,5,4] constraint2=[(1,2),(1,0),(0,1)] class LPsolver(): def solve(self,a,b,c): lb=len(b) la=len(a) arr=np.array(c) arr=np.concatenate((arr,np.identity(len(b))),1) b=np.array(b) x=[0]*l_a arr=np.insert(arr,len(a)+lb,b,1) B=np.array([0]*lb) C=np.array(a+[0]*lb) d=r... | '''
import numpy as np
objective=[1,3]
constraint1=[10,5,4]
constraint2=[(1,2),(1,0),(0,1)]
class LPsolver():
def solve(self,a,b,c):
lb=len(b)
la=len(a)
arr=np.array(c)
arr=np.concatenate((arr,np.identity(len(b))),1)
b=np.array(b)
x=[0]*l_a
arr=np.insert(a... | Python | zaydzuhri_stack_edu_python |
comment def kbc():
comment def question():
comment question_list = ["1.How many continents are there?",
comment "2.What is the capital of India?",
comment "3.NG mei kaun se course padhaya jaata hai?"]
comment return question_list
comment que=question()
comment def option():
comment options_list = [["1.Four", "2.Nine", ... | # def kbc():
# def question():
# question_list = ["1.How many continents are there?",
# "2.What is the capital of India?",
# "3.NG mei kaun se course padhaya jaata hai?"]
# return question_list
# que=question()
# def option():
# options_list = [["1.Four", "2.Nine"... | Python | zaydzuhri_stack_edu_python |
string I can create a static pygame window using the following code.
import pygame
call init
set window = call set_mode tuple 300 300
function update
begin
update display
end function
function main
begin
set run = true
while run
begin
for event in get event
begin
if type == QUIT
begin
set run = false
end
else
begin
pri... | '''
I can create a static pygame window using the following code.
'''
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
def update():
pygame.display.update()
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
... | Python | zaydzuhri_stack_edu_python |
function xi a
begin
return call xrange length a
end function | def xi(a):
return xrange(len(a)) | Python | nomic_cornstack_python_v1 |
function loadKml self scope name path **kwargs
begin
set geodatabase = call getConfigValue string geodatabase
call logMessage INFO string Loading %s to %s/%s as %s % tuple path geodatabase scope name
comment if no dataset, make one
if not exists arcpy join path geodatabase scope
begin
call CreateFeatureDataset_manageme... | def loadKml(self, scope, name, path, **kwargs):
geodatabase = getConfigValue("geodatabase")
self.logger.logMessage(INFO,"Loading %s to %s/%s as %s\n" % (path, geodatabase, scope, name))
#if no dataset, make one
if not arcpy.Exists(os.path.join(geodatabase,scope)):
arcpy.... | Python | nomic_cornstack_python_v1 |
for a in string casa
begin
append lista a
end
print lista
comment Metodo con comprension de listas
set lista = list comprehension letra for letra in string casa
print lista
comment Metodo tradicional
set lista = list
for numero in range 0 11
begin
append lista numero ^ 2
end
print lista
comment Metodo con compresion d... | for a in "casa":
lista.append(a)
print(lista)
##########################################
# Metodo con comprension de listas
lista = [letra for letra in "casa"]
print(lista)
###############################
# Metodo tradicional
lista = []
for numero in range(0, 11):
lista.append(numero ** 2)
print(lista)
######... | Python | zaydzuhri_stack_edu_python |
function update_graphic self
begin
for i in matrixMAPA
begin
for j in i
begin
comment Capturo el item
set item = call find_withtag j at 1
comment Lo pinto del color necesario
call itemconfigure item fill=colores at j at 0
end
end
call after 60 update_graphic
end function | def update_graphic(self):
for i in self.matrixMAPA:
for j in i:
# Capturo el item
item = self.telaMAPA.find_withtag(j[1])
# Lo pinto del color necesario
self.telaMAPA.itemconfigure(item, fill=self.colores[j[0]])
... | Python | nomic_cornstack_python_v1 |
from __future__ import annotations
class MyInt
begin
function __init__ self int_num
begin
if not is instance int_num int or int_num == 0
begin
raise call ValueError string 0以外の整数でなればなりません
end
set value = int_num
end function
function __str__ self
begin
return string value
end function
function __eq__ self other
begin
r... | from __future__ import annotations
class MyInt:
def __init__(self, int_num: int):
if not isinstance(int_num, int) or int_num == 0:
raise ValueError('0以外の整数でなればなりません')
self.value = int_num
def __str__(self) -> str:
return str(self.value)
def __eq__(self, other: MyInt)... | Python | zaydzuhri_stack_edu_python |
from graphviz import Digraph
from OttoDiff.reverse import *
function createGraph root computationalGraph
begin
comment use dfs to traverse the computational graph
if length parents == 0
begin
return
end
for par in parents
begin
call edge string par string root
call createGraph par computationalGraph
end
end function
fu... | from graphviz import Digraph
from OttoDiff.reverse import *
def createGraph(root, computationalGraph):
# use dfs to traverse the computational graph
if len(root.parents) == 0:
return
for par in root.parents:
computationalGraph.edge(str(par), str(root))
createGraph(par, computationa... | Python | zaydzuhri_stack_edu_python |
function move self dst
begin
raise NotImplementedError
end function | def move(self, dst):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
string Given two binary search trees root1 and root2. Return a list containing all the integers from both trees sorted in ascending order. Example 1: Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4] Example 2: Input: root1 = [0,-10,10], root2 = [5,1,7,0,2] Output: [-10,0,0,1,2,5,7,10]
comment Definition fo... | """
Given two binary search trees root1 and root2.
Return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
Output: [-10,0,0,1,2,5,7,10]
"""
# Definiti... | Python | zaydzuhri_stack_edu_python |
function split self num_or_size_splits shuffle=false
begin
raise NotImplementedError
end function | def split(self, num_or_size_splits, shuffle=False):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function bad_column_positions self x
begin
raise call NotImplementedError string base method called
end function | def bad_column_positions(self, x):
raise NotImplementedError("base method called") | Python | nomic_cornstack_python_v1 |
from math import gcd
class Frac
begin
function __init__ self numerator *denominator
begin
try
begin
assert denominator at 0 != 0
set numerator = integer round numerator
set denominator = integer round denominator at 0
set g = call gcd denominator numerator
if g > 1
begin
set denominator = denominator / g
set numerator ... | from math import gcd
class Frac:
def __init__(self, numerator, *denominator):
try:
assert denominator[0] != 0
self.numerator = int(round(numerator))
self.denominator = int(round(denominator[0]))
g = gcd(self.denominator, self.numerator)
i... | Python | zaydzuhri_stack_edu_python |
function asteriscos n
begin
set y = n * string string *
return y
end function | def asteriscos (n):
y= n*str('*')
return y
| Python | zaydzuhri_stack_edu_python |
function allele_to_structure allele
begin
if allele == string A
begin
set allele_str = string 1
end
else
if allele == string B
begin
set allele_str = string 2
end
else
if allele == string 0
begin
set allele_str = string 9
end
return allele_str at slice : :
end function | def allele_to_structure(allele):
if allele == "A":
allele_str = "1"
elif allele == "B":
allele_str = "2"
elif allele == "0":
allele_str = "9"
return allele_str[:] | Python | nomic_cornstack_python_v1 |
comment URI: 1074
set T = input
set T = integer T
set nums = list
for i in range T
begin
set x = input
append nums integer x
end
for num in nums
begin
if num % 2 == 0 and num != 0
begin
print string EVEN end=string
end
else
if num == 0
begin
print string NULL
end
else
begin
print string ODD end=string
end
if num > 0
b... | # URI: 1074
T = input()
T = int(T)
nums = []
for i in range(T):
x = input()
nums.append(int(x))
for num in nums:
if num % 2 == 0 and num != 0:
print("EVEN", end="")
elif num == 0:
print("NULL")
else:
print("ODD", end="")
if num > 0:
print(" POSITIVE")
e... | Python | zaydzuhri_stack_edu_python |
function format_completed_achievements player_achievements
begin
set completed_achievements = call get_player_completed_achievements player_achievements
set achievements = list
for achievement in completed_achievements
begin
append achievements tuple achievement at string completed_on achievement at string title
end
r... | def format_completed_achievements(player_achievements):
completed_achievements = get_player_completed_achievements(player_achievements)
achievements = []
for achievement in completed_achievements:
achievements.append((achievement['completed_on'], achievement['title']))
return sorted(achievements, key = o... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string Python script that takes your GitHub credentials (username and password) and uses the GitHub API to display your id
import requests
from sys import argv
if __name__ == string __main__
begin
set username = argv at 1
set password = argv at 2
set r = json get requests string https://api.gi... | #!/usr/bin/python3
""" Python script that takes your GitHub credentials (username and password)
and uses the GitHub API to display your id
"""
import requests
from sys import argv
if __name__ == '__main__':
username = argv[1]
password = argv[2]
r = requests.get("https://api.github.com/user", auth=(usern... | Python | zaydzuhri_stack_edu_python |
function check_rows m
begin
for row in m
begin
for item in check_list
begin
if item not in row
begin
return false
end
end
end
return true
end function | def check_rows(m):
for row in m:
for item in check_list:
if item not in row:
return False
return True | Python | nomic_cornstack_python_v1 |
function PLL_EN_LD self value
begin
if value not in list 0 1
begin
raise call ValueError string Value must be [0,1]
end
call _writeReg string PLL_ENABLE_ + string cfgNo string PLL_EN_LD_ + string cfgNo value
end function | def PLL_EN_LD(self, value):
if value not in [0, 1]:
raise ValueError("Value must be [0,1]")
self._writeReg('PLL_ENABLE_'+str(self.cfgNo), 'PLL_EN_LD_'+str(self.cfgNo), value) | Python | nomic_cornstack_python_v1 |
for i in range n + 1
begin
set n2 = string i ^ 2
set i = string i
if i == n2 at slice - length i : :
begin
set num = num + 1
end
end
print num | for i in range(n + 1):
n2 = str(i ** 2)
i=str(i)
if i == n2[-len(i):]:
num += 1
print(num) | Python | zaydzuhri_stack_edu_python |
import numpy as np
import scipy.linalg
import networkx as nx
from column_selection import drop_random
comment Project1 returns the projection of the 1s vector into
comment the column space of the input matrix
function Project1 matrix
begin
comment N (number of machines)
set rows = call shape matrix at 0
comment Reduces... | import numpy as np
import scipy.linalg
import networkx as nx
from column_selection import drop_random
# Project1 returns the projection of the 1s vector into
# the column space of the input matrix
def Project1(matrix):
rows = np.shape(matrix)[0] #N (number of machines)
#Reduces the matrix to set of linea... | Python | zaydzuhri_stack_edu_python |
function test_empty_inmemory_backend
begin
set im = call InMemory
assert list == list
remove im call Cookie string SID string 31d4d96e407aad42 type=server
assert list == list
end function | def test_empty_inmemory_backend():
im = storage.InMemory()
assert im.list() == []
im.remove(
cookie.Cookie(
"SID", "31d4d96e407aad42", type=cookie.CookieType.server
)
)
assert im.list() == [] | Python | nomic_cornstack_python_v1 |
function update_by_name name
begin
pass
end function | def update_by_name(name):
pass | Python | nomic_cornstack_python_v1 |
comment lalalal
import numpy as np
comment test row
import Image
import pandas as pd
import os
import matplotlib.pyplot as plt
set x = read csv string red.csv
set x = array x
comment 删除第一列标号
set x = x at tuple slice : : slice 1 : :
set y = read csv string blue.csv
set y = array y
set y = y at tuple slice : : sl... | #lalalal
import numpy as np
#test row
import Image
import pandas as pd
import os
import matplotlib.pyplot as plt
x=pd.read_csv('red.csv')
x=np.array(x)
#删除第一列标号
x=x[:,1:]
y=pd.read_csv('blue.csv')
y=np.array(y)
y=y[:,1:]
z=np.vstack((x,y))
#随机取样形成train 和 test 并分开train_x 与train_y test_x test_y
np.random.shuffle(z)
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
from scipy import stats
from tabulate import tabulate
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
function compute_list_median x
begin
set x = sort np x
set tmp = round 0.5 * shape at 0
if shape at 0 % 2
begin
set median = x at tmp - 1
end
else
begin
set... | import pandas as pd
import numpy as np
from scipy import stats
from tabulate import tabulate
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
def compute_list_median(x):
x = np.sort(x)
tmp = round(0.5 * x.shape[0])
if x.shape[0] % 2:
median = x[tmp - 1]
else:
median = x[tmp - 1] +... | Python | zaydzuhri_stack_edu_python |
function sortSecond val
begin
return val at 1
end function
comment list1 to demonstrate the use of sorting
comment using using second key
set list1 = list tuple 1 2 tuple 3 3 tuple 1 1
comment sorts the array in ascending according to
comment second element
sort list1 key=sortSecond
print list1
comment sorts the array ... | def sortSecond(val):
return val[1]
# list1 to demonstrate the use of sorting
# using using second key
list1 = [(1,2),(3,3),(1,1)]
# sorts the array in ascending according to
# second element
list1.sort(key=sortSecond)
print(list1)
# sorts the array in descending according to
# second element... | Python | zaydzuhri_stack_edu_python |
for i in tableData
begin
for x in tableData at i
begin
set colwidth at i = colwidth at i + length x
end
end | for i in tableData:
for x in tableData[i]:
colwidth[i] += len(x) | Python | zaydzuhri_stack_edu_python |
function ellswift_create_deterministic seed features
begin
set cnt = 0
while true
begin
set sec = call hkdf_sha256 32 seed call to_bytes 4 string little b'sec'
set xval = x
set cnt = cnt + 1
if features ? 8
begin
set u = 0
if features ? 4
begin
set u = u + SIZE
end
end
else
begin
set udat = call hkdf_sha256 64 seed cal... | def ellswift_create_deterministic(seed, features):
cnt = 0
while True:
sec = hkdf_sha256(32, seed, (cnt).to_bytes(4, 'little'), b"sec")
xval = (int.from_bytes(sec, 'big') * SECP256K1_G).x
cnt += 1
if features & 8:
u = 0
if features & 4:
u ... | Python | nomic_cornstack_python_v1 |
function cluster centroids vectors
begin
comment Clear centroid members
for centroid in centroids
begin
set centroid at string members = list
end
for tuple source vector in items vectors
begin
set i = 0
set min_index = 0
set current_min = 0
for centroid in centroids
begin
set centroid_distance = distance centroid at s... | def cluster(centroids, vectors):
# Clear centroid members
for centroid in centroids:
centroid['members'] = []
for source, vector in vectors.items():
i = 0
min_index = 0
current_min = 0
for centroid in centroids:
centroid_distance = distance(centroid['val... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
string __created__ = '2018/1/19' __author__ = 'zhaohongyang'
from drink import DrinkBase
class AddDecoratorBase extends DrinkBase
begin
function __init__ self drink
begin
set drink = drink
end function
end class
class IceDecorator extends AddDecoratorBase
begin
... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
__created__ = '2018/1/19'
__author__ = 'zhaohongyang'
"""
from .drink import DrinkBase
class AddDecoratorBase(DrinkBase):
def __init__(self, drink: DrinkBase) -> None:
self.drink = drink
class IceDecorator(AddDecoratorBase):
def get_price(self):
... | Python | zaydzuhri_stack_edu_python |
function test_epl_single_year_mtl style_checker
begin
call set_year 2017
set p = call run_style_checker string --config=module_config.yaml string whatever string epl_single_year.mtl
assert equal status 0 image
call assertRunOutputEmpty p
comment Try the same test, but without the --config file.
comment It should fail, ... | def test_epl_single_year_mtl(style_checker):
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml',
'whatever', 'epl_single_year.mtl')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
... | Python | nomic_cornstack_python_v1 |
function lock cfg
begin
run list venv_path / string bin/pip string install string pip-tools check=true
set combined = list
for layer in list none string test string dev
begin
append combined layer
run list venv_path / string bin/pip-compile string --generate-hashes string --output-file call build_requirements_name lay... | def lock(cfg):
subprocess.run([cfg.venv_path / "bin/pip", "install", "pip-tools"], check=True)
combined = []
for layer in [None, 'test', 'dev']:
combined.append(layer)
subprocess.run(
[
cfg.venv_path / "bin/pip-compile",
"--generate-hashes",
... | Python | nomic_cornstack_python_v1 |
from pygame.math import Vector2
from pygame.transform import rotozoom
from utils import load_sprite , wrap_position , decelerate , get_random_position , get_random_velocity
from random import randint , choice
import copy
set UP = call Vector2 0 - 1
class GameObject
begin
function __init__ self position sprite velocity=... | from pygame.math import Vector2
from pygame.transform import rotozoom
from utils import load_sprite, wrap_position, decelerate, get_random_position, get_random_velocity
from random import randint, choice
import copy
UP = Vector2(0, -1)
class GameObject:
def __init__(self, position, sprite, velocity=(0, 0)):
... | Python | zaydzuhri_stack_edu_python |
for i in range 1 ta + 1
begin
set ts = ts * i
end
print ts | for i in range(1,ta+1):
ts=ts*i
print(ts)
| Python | zaydzuhri_stack_edu_python |
from enum import Enum
set __NAMESPACE__ = string http://datex2.eu/schema/2/2_0
class VmsTypeEnum extends Enum
begin
string Type of variable message sign. :cvar COLOUR_GRAPHIC: A colour graphic display. :cvar CONTINUOUS_SIGN: A sign implementing fixed messages which are selected by electromechanical means. :cvar MONOCHR... | from enum import Enum
__NAMESPACE__ = "http://datex2.eu/schema/2/2_0"
class VmsTypeEnum(Enum):
"""
Type of variable message sign.
:cvar COLOUR_GRAPHIC: A colour graphic display.
:cvar CONTINUOUS_SIGN: A sign implementing fixed messages which are
selected by electromechanical means.
:cvar... | Python | zaydzuhri_stack_edu_python |
function entered_by self entered_by
begin
set _entered_by = entered_by
end function | def entered_by(self, entered_by):
self._entered_by = entered_by | Python | nomic_cornstack_python_v1 |
function fibonacci n
begin
set a = 0
set b = 1
for i in range 0 n
begin
set aux = a
set a = b
set b = aux + b
end
return a
end function
for c in range 0 3
begin
print call fibonacci c
end | def fibonacci(n):
a = 0
b = 1
for i in range(0, n):
aux = a
a = b
b = aux + b
return a
for c in range(0, 3):
print(fibonacci(c)) | Python | zaydzuhri_stack_edu_python |
function angle R
begin
set ctheta = call trace R - 1.0 * 0.5
return call acos max min ctheta 1.0 - 1.0
end function | def angle(R : Rotation) -> float:
ctheta = (trace(R) - 1.0)*0.5
return math.acos(max(min(ctheta,1.0),-1.0)) | Python | nomic_cornstack_python_v1 |
function sync_old_sprints
begin
for sprint in all
begin
if bz_url
begin
set bzurl = call BugzillaURL url=bz_url
set bugs = call get_bugs scrum_only=false open_only=false
for bug in bugs
begin
comment at this point project and sprint ids are equal
set project_id = team_id
set backlog_id = team_id
set sprint = sprint
sav... | def sync_old_sprints():
for sprint in Sprint.objects.all():
if sprint.bz_url:
bzurl = BugzillaURL(url=sprint.bz_url)
bugs = bzurl.get_bugs(scrum_only=False, open_only=False)
for bug in bugs:
# at this point project and sprint ids are equal
... | Python | nomic_cornstack_python_v1 |
from utility.emoji_remover import EmojiRemover
import time
import re
import datetime
import sys
from selenium import webdriver
from time_extractor import get_publish_at
import csv
from ElementSelectors import *
class ContentExtractor
begin
decorator classmethod
function get_post_time_stamp cls post
begin
comment Get Da... | from utility.emoji_remover import EmojiRemover
import time
import re
import datetime
import sys
from selenium import webdriver
from time_extractor import get_publish_at
import csv
from ElementSelectors import *
class ContentExtractor:
@classmethod
def get_post_time_stamp(cls,post):
# Get Date
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import os
from utils import ccmraw as raw
import json
from utils import utils as u
function subset_evaluation_dict evaluation_statistics bins subset_property methods evaluation_measure
begin
set ranks = evaluation_statistics at string ranks
set precision_rank = dict
for bin in ra... | import pandas as pd
import numpy as np
import os
from ..utils import ccmraw as raw
import json
from ..utils import utils as u
def subset_evaluation_dict(evaluation_statistics, bins, subset_property, methods, evaluation_measure):
ranks = evaluation_statistics['ranks']
precision_rank = {}
for bin in range(... | Python | zaydzuhri_stack_edu_python |
function generate_5utr_isoform_starts tifs
begin
set ret_p = list
set ret_n = list
for tuple i x in call iterrows
begin
if x at string strand == string +
begin
append ret_p x at string t5
end
else
begin
append ret_n x at string t3
end
end
comment TODO positive_strand_only
set ret = list comprehension tuple x string +... | def generate_5utr_isoform_starts(tifs):
ret_p = []
ret_n = []
for i, x in tifs.iterrows():
if x['strand'] == "+":
ret_p.append(x['t5'])
else:
ret_n.append(x['t3'])
# TODO positive_strand_only
ret = [(x, "+") for x in sorted(list(unique(ret_p)))
] ... | Python | nomic_cornstack_python_v1 |
function __init__ self **kwargs
begin
call __init__ request=kwargs at string request
end function | def __init__(self, **kwargs):
super(BasePermission, self).__init__(request=kwargs['request']) | Python | nomic_cornstack_python_v1 |
function main args
begin
string Function run when called from command line.
set options = dict string -rfft list string resetFFTscale false ; string -r1 list string readOneCoil false ; string -rp list string readPhaseCorInfo false ; string -rn list string readNavigator false ; string -skipts list string readTimeStamp t... | def main(args):
'''Function run when called from command line.'''
options = { '-rfft': ['resetFFTscale',False],
'-r1': ['readOneCoil',False],
'-rp': ['readPhaseCorInfo',False],
'-rn': ['readNavigator',False],
'-skipts': ['readTimeSta... | Python | jtatman_500k |
function train_gcmc data_loader adv_loader args model optimizer optimizer_adv pretrain=false progress=none task=none
begin
set data_itr = enumerate data_loader
for tuple idx p_batch in data_itr
begin
set p_batch = to p_batch device
set p_batch_var = p_batch
set tuple task_loss preds = model p_batch_var
zero grad optimi... | def train_gcmc(
data_loader,
adv_loader,
args,
model,
optimizer,
optimizer_adv,
pretrain=False,
progress=None,
task=None,
):
data_itr = enumerate(data_loader)
for idx, p_batch in data_itr:
p_batch = p_batch.to(args.device)
p_batch_var = p_batch
ta... | Python | nomic_cornstack_python_v1 |
import itertools
from scipy.sparse import lil_matrix
function n_choose_2 n
begin
return n * n - 1 / 2
end function
function make_empty_vector n
begin
return call lil_matrix tuple 1 n dtype=string i
end function
function make_feature_function all_words all_tags is_distance=false
begin
set n_features = length all_words ^... | import itertools
from scipy.sparse import lil_matrix
def n_choose_2(n):
return n * (n-1) / 2
def make_empty_vector(n):
return lil_matrix((1, n), dtype='i')
def make_feature_function(all_words, all_tags, is_distance=False):
n_features = len(all_words)**2 + len(all_tags)**2
if is_distance:
n... | Python | zaydzuhri_stack_edu_python |
function acquire self blocking=true timeout=none
begin
if timeout is none
begin
return acquire __lock blocking
end
else
begin
comment Simulated timeout using progressively longer sleeps.
comment This is the same timeout scheme used in the stdlib Condition
comment class. If there's lots of contention on the lock then th... | def acquire(self,blocking=True,timeout=None):
if timeout is None:
return self.__lock.acquire(blocking)
else:
# Simulated timeout using progressively longer sleeps.
# This is the same timeout scheme used in the stdlib Condition
# class. If there's lots ... | Python | nomic_cornstack_python_v1 |
string Created on 2012. 10. 17. @author: pylatte
import threading
import logging
class service extends Thread
begin
set httpd = string
set version = string
function init self httpd version
begin
set httpd = httpd
set version = version
pass
end function
function run self
begin
string Checking a command from interectiv... | '''
Created on 2012. 10. 17.
@author: pylatte
'''
import threading
import logging
class service(threading.Thread):
httpd = ""
version = ""
def init(self,httpd,version):
self.httpd=httpd
self.version = version
pass
def run(self):
"""
Checking a command from inter... | Python | zaydzuhri_stack_edu_python |
from util import *
import numpy as np
from math import log2
comment Add your import statements here
class Evaluation
begin
function __intersection self list1 list2
begin
set list3 = list comprehension value for value in list1 if value in list2
return length list3
end function
function __getRelevanceAndPositionList self... | from util import *
import numpy as np
from math import log2
# Add your import statements here
class Evaluation():
def __intersection(self,list1,list2):
list3 = [value for value in list1 if value in list2]
return len(list3)
def __getRelevanceAndPositionList(self,query_ids,qrels):
ground_truth = { "pos... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
comment low-pass demo, pl2at
import matplotlib.pyplot as plt
import numpy as np
comment nur als Demo, sonst vle[0] == "first run"
set vle1 = 30.0
set y = vle1
function low_pass vle filtFakt
begin
global vle1 y
set vle1 = vle * filtFakt + vle1 * 1 - filtFakt
set y ... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# low-pass demo, pl2at
import matplotlib.pyplot as plt
import numpy as np
vle1 = 30.0 # nur als Demo, sonst vle[0] == "first run"
y = vle1
def low_pass(vle, filtFakt):
global vle1, y
vle1 = vle * filtFakt + vle1 * ( 1 - filtFakt )
y ... | Python | zaydzuhri_stack_edu_python |
comment This is a function definition. Note the colon (:)
function my_function
begin
comment This line belongs to the function because it's indented
set a = 2
comment This line also belongs to the same function
return a
end function
comment This line is OUTSIDE the function block
print call my_function
comment If block... | def my_function(): # This is a function definition. Note the colon (:)
a = 2 # This line belongs to the function because it's indented
return a # This line also belongs to the same function
print(my_function()) # This line is OUTSIDE the function block
if a > b: # If block starts here
print(a) # Th... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set x = integer input
if x >= 18
begin
print string Sim
end
else
begin
print string Nao
end | # -*- coding: utf-8 -*-
x = int(input())
if x >= 18:
print('Sim')
else:
print('Nao')
| Python | zaydzuhri_stack_edu_python |
function leaving_node_count self
begin
return get pulumi self string leaving_node_count
end function | def leaving_node_count(self) -> int:
return pulumi.get(self, "leaving_node_count") | Python | nomic_cornstack_python_v1 |
function getFittedSpectralModel features nbClusters nbInitialisations=1000
begin
set spectralModel = call SpectralClustering n_clusters=nbClusters n_init=nbInitialisations affinity=string rbf assign_labels=string discretize
fit spectralModel features
return spectralModel
end function | def getFittedSpectralModel ( features, nbClusters, nbInitialisations=1000):
spectralModel = SpectralClustering( n_clusters=nbClusters, n_init=nbInitialisations, affinity="rbf", assign_labels="discretize")
spectralModel.fit( features )
return spectralModel | Python | nomic_cornstack_python_v1 |
function get_field_value instance field_name use_get
begin
if use_get
begin
set field_value = get instance field_name
end
else
begin
set field_value = get attribute instance field_name string
end
return field_value
end function | def get_field_value(instance, field_name, use_get):
if use_get:
field_value = instance.get(field_name)
else:
field_value = getattr(instance, field_name, '')
return field_value | Python | nomic_cornstack_python_v1 |
function get resource_name id opts=none account_name=none account_privilege=none db_cluster_id=none db_names=none
begin
set opts = merge opts call ResourceOptions id=id
set __props__ = call __new__ _AccountPrivilegeState
set __dict__ at string account_name = account_name
set __dict__ at string account_privilege = accou... | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
account_name: Optional[pulumi.Input[str]] = None,
account_privilege: Optional[pulumi.Input[str]] = None,
db_cluster_id: Optional[pulumi.Input[str]] = None,
... | Python | nomic_cornstack_python_v1 |
import sys
import mido
import time
import rtmidi
from mido import MidiFile
from moviepy.editor import *
comment equivalent to 120 bpm
set tempo = 0
function get_tempo midifile
begin
for track in tracks
begin
for msg in track
begin
if type == string set_tempo
begin
return tempo
end
end
end
end function
function get_time... | import sys
import mido
import time
import rtmidi
from mido import MidiFile
from moviepy.editor import *
tempo = 0 # equivalent to 120 bpm
def get_tempo(midifile):
for track in midifile.tracks:
for msg in track:
if msg.type == 'set_tempo':
return msg.tempo
def get_timeline(m... | Python | zaydzuhri_stack_edu_python |
function _parse_clinvar_release_date local_vcf_path
begin
with open local_vcf_path string rt as f
begin
for line in f
begin
if starts with line string ##fileDate=
begin
set clinvar_release_date = strip split line string = at - 1
return clinvar_release_date
end
if not starts with line string #
begin
return none
end
end
... | def _parse_clinvar_release_date(local_vcf_path: str) -> str:
with gzip.open(local_vcf_path, "rt") as f:
for line in f:
if line.startswith("##fileDate="):
clinvar_release_date = line.split("=")[-1].strip()
return clinvar_release_date
if not line.starts... | Python | nomic_cornstack_python_v1 |
from tensorflow.keras.layers import Input , Dense , Reshape , Flatten , Dropout , LeakyReLU , Activation
from tensorflow.keras.layers import BatchNormalization , Activation , ZeroPadding2D
from tensorflow.keras.models import Sequential , Model
from tensorflow.keras.optimizers import Adam
import numpy as np
string This ... | from tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Dropout, LeakyReLU, Activation
from tensorflow.keras.layers import BatchNormalization, Activation, ZeroPadding2D
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import Adam
import numpy as np
'''
This model is th... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
import pandas as pd
comment to print in tabular form
from tabulate import tabulate
class Match
begin
function __init__ self match_id team1 team2 venue start_date season
begin
set match_id = match_id
set team1 = team1
set team2 = team2
set venue = venue
set start_date = start_date
set... | from collections import defaultdict
import pandas as pd
from tabulate import tabulate # to print in tabular form
class Match:
def __init__(self, match_id, team1, team2, venue, start_date, season):
self.match_id = match_id
self.team1 = team1
self.team2 = team2
self.venue = venue
... | Python | zaydzuhri_stack_edu_python |
import turtle
import math
from math import sin
from math import radians
from tkinter import *
set root = call Tk
call shape string turtle
function turtleCircle
begin
for x in range 0 120
begin
call forward 8
call left 3
end
end function
function turtleSquare10
begin
set a = 10
set b = - 5
for y in range 0 10
begin
for ... | import turtle
import math
from math import sin
from math import radians
from tkinter import *
root = Tk()
turtle.shape('turtle')
def turtleCircle():
for x in range(0, 120):
turtle.forward(8)
turtle.left(3)
def turtleSquare10():
a = 10
b = -5
for y in range(0,10):
for x in ra... | Python | zaydzuhri_stack_edu_python |
function test_H2O_4 self
begin
set H2O4 = call read_xyz string ./molfiles/H2O_4.xyz
set bfs = call basisset H2O4 string sto-3g
set hamiltonian = call rhf bfs twoe_factory=libint_twoe_integrals
set iterator = call SCFIterator hamiltonian
call converge
assert true converged
call assertAlmostEqual energy - 299.90978986353... | def test_H2O_4(self):
H2O4 = read_xyz('./molfiles/H2O_4.xyz')
bfs = basisset(H2O4,'sto-3g')
hamiltonian = rhf(bfs, twoe_factory=libint_twoe_integrals)
iterator = SCFIterator(hamiltonian)
iterator.converge()
self.assertTrue(iterator.converged)
self.assertAlmostEqua... | Python | nomic_cornstack_python_v1 |
string # Definition for a Node. class Node: def __init__(self, val, next, random): self.val = val self.next = next self.random = random
class Solution
begin
function copyRandomList self head
begin
set dummy = call Node - 1 none none
set cur = head
set newcur = dummy
set nodemap = dict
while cur
begin
set newNode = cal... | """
# Definition for a Node.
class Node:
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
dummy = Node(-1, None, None)
cur = head
newcur = dummy
... | Python | zaydzuhri_stack_edu_python |
function outer_horizontal_border_bottom self
begin
string The complete outer bottom horizontal border section, including left and right margins. Returns: str: The bottom menu border.
return format string {lm}{lv}{hz}{rv} lm=string * left lv=bottom_left_corner rv=bottom_right_corner hz=call outer_horizontals
end functi... | def outer_horizontal_border_bottom(self):
"""
The complete outer bottom horizontal border section, including left and right margins.
Returns:
str: The bottom menu border.
"""
return u"{lm}{lv}{hz}{rv}".format(lm=' ' * self.margins.left,
... | Python | jtatman_500k |
import numpy as np
set a = array range 12
set shape = tuple 3 4
print string Array a: a
set d = copy a
print string d is a: d is a
print string d.base is a: base is a
set d at tuple 0 0 = 9999
print string Array D : d
print string Array A : a | import numpy as np
a= np.arange(12)
a.shape=3,4
print("Array a: ", a)
d = a.copy()
print("d is a: ", d is a)
print("d.base is a: ", d.base is a)
d[0,0] = 9999
print("Array D : ", d)
print("Array A : ", a) | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
import networkx as nx
try
begin
import simplejson as json
end
except any
begin
import json
end
function oe_ratio n nx ny nxy
begin
return decimal n * decimal nxy / decimal nx * decimal ny
end function
function cooccurrences n nx ny nxy
begin
return decimal nxy
end function
class Bund... | from collections import defaultdict
import networkx as nx
try:
import simplejson as json
except:
import json
def oe_ratio(n, nx, ny, nxy):
return float(n) * float(nxy) / (float(nx) * float(ny))
def cooccurrences(n, nx, ny, nxy):
return float(nxy)
class Bundle():
def __init__(self, li=[], json_p... | Python | zaydzuhri_stack_edu_python |
import os
import re
import time
class Strongswan
begin
string Class Factory for strongswan
function __init__ self linux_handle **kwargs
begin
string :param linux_handle: **REQUIRED** linux handle where strongswan is installed :param kwargs: connection_name: **REQUIRED* ipsec connection name :return class instance EXAMP... | import os
import re
import time
class Strongswan:
"""
Class Factory for strongswan
"""
def __init__(self, linux_handle, **kwargs):
"""
:param linux_handle:
**REQUIRED** linux handle where strongswan is installed
:param kwargs: connection_n... | Python | zaydzuhri_stack_edu_python |
if length string % 2 == 0
begin
set i = length string / 2 - 1
set x = call partition string at integer i
set part1 = x at 0 + x at 1
set part2 = x at 2
set new_str = part2 + part1
print new_str
end
else
begin
set i = length string // 2
set x = call partition string at integer i
set part1 = x at 0 + x at 1
set part2 = x... | if len(string) % 2 == 0:
i = len(string) / 2 - 1
x = string.partition(string[int(i)])
part1 = x[0] + x[1]
part2 = x[2]
new_str = part2 + part1
print(new_str)
else:
i = len(string) // 2
x = string.partition(string[int(i)])
part1 = x[0] + x[1]
part2 = x[2]
new_str = part2 + ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string NOTA: bastante parte del script hace analisis de PCA y termina produciendo data frames. quizas tenga mas sentido hacer eso en un script dedicado al analisis y procesamiento y tener otro script que solo se dedique a importar el csv y el audio y tocarlos. hacer un script que reciba un... | #!/usr/bin/env python3
""" NOTA: bastante parte del script hace analisis de PCA y termina produciendo
data frames. quizas tenga mas sentido hacer eso en un script dedicado al
analisis y procesamiento y tener otro script que solo se dedique a importar el
csv y el audio y tocarlos.
hacer un script que reciba un wav y c... | Python | zaydzuhri_stack_edu_python |
import boto3
import argparse
set parser = call ArgumentParser prog=string Get the Name of the customers from the instances that are running as a particular Product formatter_class=RawDescriptionHelpFormatter description=string This tool will require the region and the application name
call add_argument string -rgn stri... | import boto3
import argparse
parser = argparse.ArgumentParser(
prog='Get the Name of the customers from the instances that are running as a particular Product',
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''This tool will require the region and the application name''')
parser.add_arg... | Python | zaydzuhri_stack_edu_python |
import utils
class TablaSimulacion
begin
function __init__ self cantidad_orden punto_reorden inicial predicciones
begin
set cantidad_orden = cantidad_orden
set punto_reorden = punto_reorden
set inicial = inicial
set predicciones = predicciones
set tabla = list
call simular
end function
function simular self
begin
set ... | import utils
class TablaSimulacion:
def __init__(self, cantidad_orden, punto_reorden, inicial, predicciones):
self.cantidad_orden = cantidad_orden
self.punto_reorden = punto_reorden
self.inicial = inicial
self.predicciones = predicciones
self.tabla = []
self.simula... | Python | zaydzuhri_stack_edu_python |
function preload_views
begin
log string Starting `preload_views`
set modules = set
for pkg in call find_packages ROOT_DIR
begin
set pkgpath = ROOT_DIR + string / + replace pkg string . string /
for info in call iter_modules list pkgpath
begin
if ispkg
begin
continue
end
if name != string views
begin
continue
end
add mo... | def preload_views():
log("Starting `preload_views`")
modules = set()
for pkg in find_packages(ROOT_DIR):
pkgpath = ROOT_DIR + "/" + pkg.replace(".", "/")
for info in pkgutil.iter_modules([pkgpath]):
if info.ispkg:
continue
if info.name != "views":
... | Python | nomic_cornstack_python_v1 |
comment https://www.reddit.com/r/dailyprogrammer/comments/1m1jam/081313_challenge_137_easy_string_transposition/
comment Transpose the list
function transpose lst
begin
comment Finds the maximum number; accounts for the extra space
set len_max = max list comprehension length i for i in lst
set space_added = list compre... | # https://www.reddit.com/r/dailyprogrammer/comments/1m1jam/081313_challenge_137_easy_string_transposition/
#Transpose the list
def transpose(lst):
#Finds the maximum number; accounts for the extra space
len_max = max([len(i) for i in lst])
space_added = [i + ' ' * (len_max - len(i)) for i in lst]
... | Python | zaydzuhri_stack_edu_python |
for j in range N - 3
begin
if dp at j > 0
begin
append dp dp at j + 1
end
else
if dp at j + 2 > 0
begin
append dp dp at j + 2 + 1
end
else
begin
append dp - 1
end
end
print dp at N - 1 | for j in range( N-3) :
if dp[j] >0 :
dp.append(dp[j]+1)
else :
if dp[j+2] > 0 :
dp.append(dp[j+2]+1)
else :
dp.append(-1)
print(dp[N-1])
| Python | zaydzuhri_stack_edu_python |
function add_entity self
begin
set new_id = num_entities * 2 + 1
call AddNode new_id
set num_entities = num_entities + 1
append entities new_id
return new_id
end function | def add_entity(self):
new_id = self.num_entities * 2 + 1
self._G.AddNode(new_id)
self.num_entities += 1
self.entities.append(new_id)
return new_id | Python | nomic_cornstack_python_v1 |
function terminate_program msg=none
begin
if msg
begin
critical msg
end
exit if expression msg then - 1 else 0
end function | def terminate_program(msg=None):
if msg:
LOGGER.critical(msg)
sys.exit(-1 if msg else 0) | Python | nomic_cornstack_python_v1 |
function get_customer self
begin
if customer_id
begin
return customer
end
set name = display_name or name or string
set email = billing_email or email or string
if api_key != string sk_test_xxxx
begin
try
begin
set customer = call create name=name email=email
set customer = call sync_from_stripe_data customer
end
exc... | def get_customer(self) -> djstripe.models.Customer:
if self.customer_id:
return self.customer
name = self.display_name or self.name or ""
email = self.billing_email or self.email or ""
if stripe.api_key != "sk_test_xxxx":
try:
customer = stripe.C... | Python | nomic_cornstack_python_v1 |
function load_entry_points group_name strict=false **kwargs
begin
set loaded_entry_points = dict
for tuple name entry_point in items call get_entry_points group_name strict=strict keyword kwargs
begin
try
begin
set loaded_entry_points at name = load entry_point
end
comment noqa: F841
except Exception as e
begin
set ms... | def load_entry_points(group_name, *, strict=False, **kwargs):
loaded_entry_points = {}
for name, entry_point in get_entry_points(
group_name, strict=strict, **kwargs
).items():
try:
loaded_entry_points[name] = entry_point.load()
except Exception as e: # noqa: F841
... | Python | nomic_cornstack_python_v1 |
function runtime_scale_monitoring_enabled self
begin
return get pulumi self string runtime_scale_monitoring_enabled
end function | def runtime_scale_monitoring_enabled(self) -> Optional[bool]:
return pulumi.get(self, "runtime_scale_monitoring_enabled") | Python | nomic_cornstack_python_v1 |
function delete_old_posts_for_partner partner num_posts_to_keep=20
begin
from partner_feeds.models import Post
set recent_posts = list call values_list string id flat=true at slice : num_posts_to_keep :
delete
end function | def delete_old_posts_for_partner(partner, num_posts_to_keep=20):
from partner_feeds.models import Post
recent_posts = list(Post.objects.filter(
partner=partner).values_list('id', flat=True)[:num_posts_to_keep])
Post.objects.filter(partner=partner).exclude(pk__in=recent_posts).delete() | Python | nomic_cornstack_python_v1 |
from ParallelResister import parallel_resistance
from ConstantTime import constant_time
from VoltageCapacity import voltage_capacity
from math import exp
import matplotlib.pyplot as plt
set x = list 1000 1000 1000 1000
set re = call parallel_resistance x
set c = 5
set t = call constant_time re c
set x = exp 1
print x
s... | from ParallelResister import parallel_resistance
from ConstantTime import constant_time
from VoltageCapacity import voltage_capacity
from math import exp
import matplotlib.pyplot as plt
x = [1000,1000,1000,1000]
re = parallel_resistance(x)
c = 5
t = constant_time(re,c)
x = exp(1)
print(x)
uc = voltage_capacity(51000,50... | Python | zaydzuhri_stack_edu_python |
import json
import functools
function to_json func
begin
decorator wraps func
function wrapper *args **kwargs
begin
set rezult = call func *args keyword kwargs
return dumps rezult
end function
return wrapper
end function | import json
import functools
def to_json(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
rezult = func(*args, **kwargs)
return json.dumps(rezult)
return wrapper
| Python | zaydzuhri_stack_edu_python |
function fit self X y
begin
set X = array X dtype=float32
set y = array y dtype=float32
assert shape at 0 == shape at 0
return tuple X y
end function | def fit(self, X, y):
X = np.array(X, dtype=np.float32)
y = np.array(y, dtype=np.float32)
assert X.shape[0] == y.shape[0]
return X, y | Python | nomic_cornstack_python_v1 |
function delete self
begin
set build = call get_build _id
if exists path join path builds_path _id
begin
remove tree join path builds_path _id
return string Deleted
end
return string Doesn't exist
end function | def delete(self):
build = get_build(self._id)
if os.path.exists(os.path.join(pecan.conf.builds_path, self._id)):
shutil.rmtree(os.path.join(pecan.conf.builds_path, self._id))
return "Deleted"
return "Doesn't exist" | Python | nomic_cornstack_python_v1 |
function __eq__ self other
begin
return point in self and call iscollinear other
end function | def __eq__(self, other):
return other.point in self and self.iscollinear(other) | Python | nomic_cornstack_python_v1 |
function GenerateOptTable self expand_max expand_min size_max size_min
begin
for i in call xrange 0 256
begin
set best_err = 256
for mn in call xrange 0 size_min
begin
for mx in call xrange 0 size_max
begin
set mine = call expand_min mn
set maxe = call expand_max mx
set err = absolute call Lerp13 maxe mine - i
comment ... | def GenerateOptTable(self, expand_max, expand_min, size_max, size_min):
for i in xrange(0, 256):
best_err = 256
for mn in xrange(0, size_min):
for mx in xrange(0, size_max):
mine = expand_min(mn)
maxe = expand_max(mx)
err = abs(Lerp13(maxe, mine) - i)
# D... | Python | nomic_cornstack_python_v1 |
function pop self
begin
try
begin
if length == 0
begin
raise IndexError
end
else
begin
pass
end
end
except any
begin
call error_message string IndexError string pop(): empty DLL
end
set val = data
delete - 1
return val
end function | def pop(self):
try:
if self.length==0:
raise IndexError
else:
pass
except:
error.error_message("IndexError","pop(): empty DLL")
val=self.end.data
self.delete(-1)
return val | Python | nomic_cornstack_python_v1 |
function max_subarray arr k
begin
set max_sum = decimal string -inf
set current_sum = 0
set start_index = 0
set end_index = 0
set curr_len = 0
set max_len = 0
for i in range length arr
begin
set num = arr at i
set current_sum = current_sum + num
set curr_len = curr_len + 1
if current_sum > max_sum
begin
set max_sum = c... | def max_subarray(arr, k):
max_sum = float('-inf')
current_sum = 0
start_index = 0
end_index = 0
curr_len = 0
max_len = 0
for i in range(len(arr)):
num = arr[i]
current_sum += num
curr_len += 1
if current_sum > max_sum:
max_sum = curre... | Python | jtatman_500k |
function run_fitacf_amgeo_clustering args
begin
set db = db scan args
return
end function | def run_fitacf_amgeo_clustering(args):
db = DBScan(args)
return | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
from itertools import chain
import math
set filename = string example.txt
set filename = string example2.txt
set filename = string input.txt
set parts = split read open filename string
set rules = dict
for line in split parts at 0 string
begin
set tuple name values = split line string :
s... | #!/usr/bin/env python3
from itertools import chain
import math
filename = 'example.txt'
filename = 'example2.txt'
filename = 'input.txt'
parts = open(filename).read().split('\n\n')
rules = {}
for line in parts[0].split('\n'):
name, values = line.split(': ')
rules[name] = [list(map(int, v.split('-'))) for v ... | Python | zaydzuhri_stack_edu_python |
function marker_open_cb self
begin
comment @ Better way?
if marker_dialog == none
begin
import VolumePath
set marker_dialog = call volume_path_dialog 1
end
call ImportXML
call enter
call enter
return
end function | def marker_open_cb(self):
# @ Better way?
if self.marker_dialog == None:
import VolumePath
self.marker_dialog = VolumePath.volume_path_dialog(1)
self.marker_dialog.ImportXML()
self.marker_dialog.enter()
self.marker_dialog.open_dialog.enter()
r... | Python | nomic_cornstack_python_v1 |
comment Make sure the servos move the right amount of steps in the right amount of time
import config
from time import sleep
function moveTotalSteps
begin
comment Subdivide the steps to set the steps/time for the servos
set yawDivided = integer decimal yawSteps / totalSteps
set pitchDivided = integer decimal pitchSteps... | # Make sure the servos move the right amount of steps in the right amount of time
import config
from time import sleep
def moveTotalSteps():
# Subdivide the steps to set the steps/time for the servos
yawDivided = int(float(config.yawSteps)/config.totalSteps)
pitchDivided = int(float(config.pitchSteps)/con... | Python | zaydzuhri_stack_edu_python |
string Mode : w = write mode / mode menulis dan menghapus file lama, jika file tidak ada maka akan dibuatkan r = read only / hanya membaca a = appending mode / menambahkan text diakhir file r+ = write and read mode
set path = string 26 - Write, Read and Append File/file.txt
comment Open file
set file = open path mode=s... | """
Mode :
w = write mode / mode menulis dan menghapus file lama, jika
file tidak ada maka akan dibuatkan
r = read only / hanya membaca
a = appending mode / menambahkan text diakhir file
r+ = write and read mode
"""
path = '26 - Write, Read and Append File/file.txt'
# Open file
file = open(path, mode='w')
file.wr... | Python | zaydzuhri_stack_edu_python |
function resolve_format apath
begin
set status = NOT_COMPATIBLE
set handlers = call handlers
for handler in dictionary handlers
begin
set unpacker = handlers at handler
set status = call check apath
if call check apath == ALL_GOOD
begin
return handler
end
end
if status == CORRUPTED
begin
raise call AdvarchsExtractExcep... | def resolve_format(apath):
status = ArchiveStatus.NOT_COMPATIBLE
handlers = HandlersFactory.handlers()
for handler in dict(handlers):
unpacker = handlers[handler]
status = unpacker.check(apath)
if unpacker.check(apath) == ArchiveStatus.ALL_GOOD:
return handler
if s... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
class Credentials extends object
begin
function __init__ self file_path
begin
set file_path = file_path
call get_credentials
end function
function get_credentials self
begin
with open file_path string r as cred_file
begin
set lines = call splitlines
for line in... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Credentials(object):
def __init__(self, file_path):
self.file_path = file_path
self.get_credentials()
def get_credentials(self):
with open(self.file_path, 'r') as cred_file:
lines = cred_file.read().splitlines()
... | Python | zaydzuhri_stack_edu_python |
from sklearn.neighbors import KNeighborsClassifier
import os
import numpy as np
import pandas as np
import matplotlib.pyplot as plt
import cv2
from fastai.imports import *
import tensorflow as tf
from tensorflow import keras
comment Function to normalize series of images (photo_batch) into data and labels within a Cate... | from sklearn.neighbors import KNeighborsClassifier
import os
import numpy as np
import pandas as np
import matplotlib.pyplot as plt
import cv2
from fastai.imports import *
import tensorflow as tf
from tensorflow import keras
#Function to normalize series of images (photo_batch) into data and labels within a Ca... | 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.