code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_url self
begin
return current_url
end function | def get_url(self):
return self.base_driver.current_url | Python | nomic_cornstack_python_v1 |
import os
import time
import pickle as pk
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
function load_model filename=string ./Data/Setting/model.pk
begin
set fr = open... | import os
import time
import pickle as pk
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
def load_model(filename='./Data/Setting/model.pk'):
fr = open(fil... | Python | zaydzuhri_stack_edu_python |
function stemming self tokens
begin
set ps = call PorterStemmer
set tokens = list comprehension call stem tok for tok in tokens
return tokens
end function | def stemming(self, tokens):
ps = PorterStemmer()
tokens = [ps.stem(tok) for tok in tokens]
return tokens | Python | nomic_cornstack_python_v1 |
function WriteGitmodules submods
begin
set adds = dict
with open string .gitmodules string w as fh
begin
for tuple name tuple os_name url sha1 in sorted call iteritems
begin
if not url
begin
continue
end
if starts with url string svn://
begin
warning string Skipping svn url %s url
continue
end
tuple print ? fh string ... | def WriteGitmodules(submods):
adds = {}
with open('.gitmodules', 'w') as fh:
for name, (os_name, url, sha1) in sorted(submods.iteritems()):
if not url:
continue
if url.startswith('svn://'):
logging.warning('Skipping svn url %s', url)
continue
print >> fh, '[submodule ... | Python | nomic_cornstack_python_v1 |
function audits self page=none per_page=none
begin
set url = format string {0}/{1} call get_url string audits
set params = call get_params tuple string page string per_page locals
return tuple call Request string GET url params parse_json
end function | def audits(self, page=None, per_page=None):
url = '{0}/{1}'.format(self.get_url(), 'audits')
params = base.get_params(('page', 'per_page'), locals())
return http.Request('GET', url, params), parsers.parse_json | Python | nomic_cornstack_python_v1 |
function acc_deltas_bptt self x d y s steps
begin
for t in reversed range length x
begin
if t - steps < 0
begin
set positive_steps = t
end
else
begin
set positive_steps = steps
end
for T in range positive_steps
begin
comment print('-----> '+ str(t-T) + 'd[t - T] : ')
comment print(d[t - T])
comment print(' ')
set d_one... | def acc_deltas_bptt(self, x, d, y, s, steps):
for t in reversed(range(len(x))):
if t - steps < 0:
positive_steps = t
else:
positive_steps = steps
for T in range(positive_steps):
#print('-----> '+ str(t-T) + 'd[t - T] : ')
... | Python | nomic_cornstack_python_v1 |
function extract_data self dataset subset
begin
if pitchwise
begin
set data = list
set targets = list
set lengths = list
set generator = call get_pitchwise_dataset_generator string valid 50 integer n_notes - 1 / 2.0 chunks
for tuple input target len in generator
begin
set data = data + list comprehension squeeze np ... | def extract_data(self,dataset,subset):
if self.pitchwise:
data = []
targets = []
lengths = []
generator = dataset.get_pitchwise_dataset_generator('valid',50,int((self.n_notes-1)/2.0),self.chunks)
for input, target, len in generator:
da... | Python | nomic_cornstack_python_v1 |
function suffix self
begin
raise NotImplementedError
end function | def suffix(self) -> Union[str, Tuple[str, ...]]:
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function get_ast self
begin
if not ast
begin
set ast = call get_ast_from_file filename
end
return ast
end function | def get_ast(self):
if not self.ast:
self.ast = get_ast_from_file(self.filename)
return self.ast | Python | nomic_cornstack_python_v1 |
string Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT
set lines = list
try
beg... | """
Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
Suppose the following input is supplied to the program:
Hello world
Practice makes perfect
Then, the output should be:
HELLO WORLD
PRACTICE MAKES PERFECT
"""
lines = []
try:
w... | Python | zaydzuhri_stack_edu_python |
function xavier_init self shape
begin
set matrix = randn shape at 1 shape at 0 * square root 1 / shape at 0
set new_col = list 0 * length matrix
set matrix = insert np matrix 0 new_col axis=1
return matrix
end function | def xavier_init(self, shape):
matrix = np.random.randn( shape[1], shape[0] ) * np.sqrt(1/shape[0])
new_col = [0]*len(matrix)
matrix = np.insert(matrix, 0, new_col, axis=1)
return matrix | Python | nomic_cornstack_python_v1 |
function get_annotations self
begin
string Get the current annotations.
return dict EVIDENCE evidence ; CITATION copy citation ; ANNOTATIONS copy annotations
end function | def get_annotations(self) -> Dict:
"""Get the current annotations."""
return {
EVIDENCE: self.evidence,
CITATION: self.citation.copy(),
ANNOTATIONS: self.annotations.copy()
} | Python | jtatman_500k |
import sys
set stdin = open string scan_input.txt string r
set hex_dict = dict string 0 string 0000 ; string 1 string 0001 ; string 2 string 0010 ; string 3 string 0011 ; string 4 string 0100 ; string 5 string 0101 ; string 6 string 0110 ; string 7 string 0111 ; string 8 string 1000 ; string 9 string 1001 ; string A st... | import sys
sys.stdin = open('scan_input.txt', 'r')
hex_dict = {
'0': '0000',
'1': '0001',
'2': '0010',
'3': '0011',
'4': '0100',
'5': '0101',
'6': '0110',
'7': '0111',
'8': '1000',
'9': '1001',
'A': '1010',
'B': '1011',
'C': '1100',
'D': '1101',
'E': '1110',... | Python | zaydzuhri_stack_edu_python |
from time import sleep
from module_skills import get_text_beetween , get_enumerate
import datetime
set SECURE = true
function isValid text
begin
set text = lower text
if starts with text string hallo or text == string hi or text == string hey or text == string /start and not string geht in text or string läuft in text
... | from time import sleep
from module_skills import get_text_beetween, get_enumerate
import datetime
SECURE = True
def isValid(text):
text = text.lower()
if (text.startswith(
'hallo') or text == 'hi' or text == 'hey' or text == '/start') and not 'geht' in text or 'läuft' in text:
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
comment Author: wxnacy(wxnacy@gmail.com)
comment Description:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column , Integer , String
from sqlalchemy.orm import sessionmaker
from sqlalchemy im... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
# Description:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy import and_
from sqlalchemy ... | Python | zaydzuhri_stack_edu_python |
function removeVowels string
begin
set vowels = tuple string a string e string i string o string u
set new_string = string
for char in string
begin
if char not in vowels
begin
set new_string = new_string + char
end
end
return new_string
end function
set string = string My name is John
set removeVowelString = call remo... | def removeVowels(string):
vowels = ('a', 'e', 'i', 'o', 'u')
new_string = ''
for char in string:
if char not in vowels:
new_string += char
return new_string
string = 'My name is John'
removeVowelString = removeVowels(string)
print(removeVowelString)
| Python | flytech_python_25k |
function test_handshake_missing_headers tchannel_pair
begin
set tuple server client = tchannel_pair
call initiate_handshake headers=dict
with raises InvalidMessageException
begin
call await_handshake headers=dict
end
end function | def test_handshake_missing_headers(tchannel_pair):
server, client = tchannel_pair
client.initiate_handshake(headers={})
with pytest.raises(InvalidMessageException):
server.await_handshake(headers={}) | Python | nomic_cornstack_python_v1 |
string while num_digit_count != 0: num_digit_count = num_digit_count // 10 i += 1 else: num_digit_count = i
while num > 10
begin
set i = num % 10
set num = num // 10
if i > max_digit
begin
set max_digit = i
end
end
print max_digit | """ while num_digit_count != 0:
num_digit_count = num_digit_count // 10
i += 1
else:
num_digit_count = i """
while num > 10:
i = num % 10
num //= 10
if i > max_digit:
max_digit = i
print(max_digit)
| Python | zaydzuhri_stack_edu_python |
function make_embedding_matrix glove_filepath words
begin
set tuple word_to_idx glove_embeddings = call load_glove_from_file glove_filepath
set embedding_size = shape at 1
set final_embeddings = zeros tuple length words embedding_size
for tuple i word in enumerate words
begin
if word in word_to_idx
begin
set final_embe... | def make_embedding_matrix(glove_filepath, words):
word_to_idx, glove_embeddings = load_glove_from_file(glove_filepath)
embedding_size = glove_embeddings.shape[1]
final_embeddings = np.zeros((len(words), embedding_size))
for i, word in enumerate(words):
if word in word_to_idx:
final... | Python | nomic_cornstack_python_v1 |
function set_comment func comment **repeatable
begin
set fn = call by func
return call set_func_cmt fn comment get repeatable string repeatable 1
end function | def set_comment(func, comment, **repeatable):
fn = by(func)
return idaapi.set_func_cmt(fn, comment, repeatable.get('repeatable', 1)) | Python | nomic_cornstack_python_v1 |
set fruits = dict string mango 100 ; string banana 150 ; string orange 80 ; string apple 158
set key_to_check = lower input string Enter fruit name that you want to buy?
if key_to_check in fruits
begin
print key_to_check string this is available
end
else
begin
print key_to_check string this is not available
end | fruits = {
"mango": 100,
"banana": 150,
"orange": 80,
"apple": 158
}
key_to_check = input("Enter fruit name that you want to buy? ").lower()
if(key_to_check in fruits):
print(key_to_check,"this is available")
else:
print(key_to_check,"this is not available")
| Python | zaydzuhri_stack_edu_python |
import socket
import time
class Server
begin
function __init__ self
begin
set serverhost = string 127.0.0.1
set serverport = 8080
set max_client = 100
set auth_dict = dict
set key_store = dict
end function
function init_authorization self
begin
for i in range 1 max_client + 1
begin
set auth_dict at i = string guest
s... | import socket
import time
class Server():
def __init__(self):
self.serverhost = '127.0.0.1'
self.serverport = 8080
self.max_client = 100
self.auth_dict = {}
self.key_store = {}
def init_authorization(self):
for i in range(1,self.max_client+1):
self.auth_dict[i] = "guest"
self.key_store[i] = {}
... | Python | zaydzuhri_stack_edu_python |
from sys import stdin
set input = readline
set n = integer input
set A = list map int split input
set q = integer input
set m = list map int split input
set set_m = set list
for i in range 2 ^ n
begin
set tmp = 0
for j in range n
begin
if i ? j ? 1
begin
set tmp = tmp + A at j
end
end
add set_m tmp
end
for i in m
begin... | from sys import stdin
input = stdin.readline
n = int(input())
A = list(map(int, input().split()))
q = int(input())
m = list(map(int, input().split()))
set_m = set([])
for i in range(2 ** n):
tmp = 0
for j in range(n):
if (i >> j) & 1:
tmp += A[j]
set_m.add(tmp)
for i in m:
if i... | Python | zaydzuhri_stack_edu_python |
function gen cls feat_mat indexer_type=string hierarchicalkmeans **kwargs
begin
return call gen feat_mat keyword kwargs
end function | def gen(cls, feat_mat, indexer_type="hierarchicalkmeans", **kwargs):
return cls.indexer_dict[indexer_type].gen(feat_mat, **kwargs) | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
import bisect | #-*- coding:utf-8 -*-
import bisect
| Python | zaydzuhri_stack_edu_python |
string Core Protocol Definition classes
set __author__ = string VMware, Inc.
comment pylint: disable=line-too-long
set __copyright__ = string Copyright 2015, 2017 VMware, Inc. All rights reserved. -- VMware Confidential
import abc
import six
decorator call add_metaclass ABCMeta
class ApiProvider extends object
begin
st... | """
Core Protocol Definition classes
"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2015, 2017 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class ApiProvider(object):
"""
The ApiProvider interfac... | Python | zaydzuhri_stack_edu_python |
from __future__ import division
import numpy as np
import pandas as pd
from pandas import Series , DataFrame
import matplotlib as mtp
call use string TkAgg
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as stats
call set_style string whitegrid
from datetime import datetime
import time
set donor_df =... | from __future__ import division
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib as mtp
mtp.use('TkAgg')
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as stats
sns.set_style('whitegrid')
from datetime import datetime
import time
donor_df = pd.read_... | Python | zaydzuhri_stack_edu_python |
from logging import getLogger , Formatter , FileHandler , StreamHandler , INFO , DEBUG
function create_logger exp_version
begin
set log_file = format string ../log/{}.log exp_version
comment logger
set logger_ = call getLogger exp_version
call setLevel DEBUG
comment formatter
set fmr = call Formatter string %(message)s... | from logging import getLogger, Formatter, FileHandler, StreamHandler, INFO, DEBUG
def create_logger(exp_version):
log_file = ("../log/{}.log".format(exp_version))
# logger
logger_ = getLogger(exp_version)
logger_.setLevel(DEBUG)
# formatter
fmr = Formatter("%(message)s \t(%(asctime)s)")
... | Python | zaydzuhri_stack_edu_python |
import time
import tkinter
from PIL import Image , ImageTk
class SimpleApp extends object
begin
function __init__ self master filename **kwargs
begin
set master = master
set filename = filename
set canvas = call Canvas master width=500 height=500 background=string white
call pack
comment Using "next(self.draw())" doesn... | import time
import tkinter
from PIL import Image, ImageTk
class SimpleApp(object):
def __init__(self, master, filename, **kwargs):
self.master = master
self.filename = filename
self.canvas = tkinter.Canvas(master, width=500, height=500,background="white")
self.canvas.pack()
... | Python | zaydzuhri_stack_edu_python |
function scatter3D data labels centers=none save_path=none
begin
set fig = figure figsize=tuple 25 25
set ax = call add_subplot 111 projection=string 3d
call set_proj_type string ortho
call view_init - 22.5 - 45
comment Draw points
scatter ax data at tuple slice : : 0 data at tuple slice : : 1 data at tuple slice... | def scatter3D(data, labels, centers=None, save_path=None):
fig = plt.figure(figsize=(25, 25))
ax = fig.add_subplot(111, projection='3d')
ax.set_proj_type('ortho')
ax.view_init(-22.5, -45)
# Draw points
ax.scatter(
data[:, 0], data[:, 1], data[:, 2],
... | Python | nomic_cornstack_python_v1 |
function CloseSecurityPolicy self request
begin
try
begin
set params = call _serialize
set headers = headers
set body = call string CloseSecurityPolicy params headers=headers
set response = loads body
set model = call CloseSecurityPolicyResponse
call _deserialize response at string Response
return model
end
except Exce... | def CloseSecurityPolicy(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("CloseSecurityPolicy", params, headers=headers)
response = json.loads(body)
model = models.CloseSecurityPolicyResponse()
m... | Python | nomic_cornstack_python_v1 |
function prime a
begin
set i = 2
while a % i != 0
begin
set i = i + 1
end
return i == a
end function
for number in range 2 100
begin
if call prime number == true ? call prime number + 2 == true
begin
print format string ({}, {}) number number + 2
end
end | def prime(a):
i = 2
while a % i != 0:
i += 1
return i == a
for number in range(2,100):
if prime(number) == True & prime(number + 2) == True:
print("({}, {})".format(number, number + 2)) | Python | zaydzuhri_stack_edu_python |
function createByThreePoints self pointOne pointTwo pointThree
begin
return call Circle3D
end function | def createByThreePoints(self, pointOne, pointTwo, pointThree):
return Circle3D() | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python3
set str1 = string My name is Idris
set str2 = replace str1 string string **
print str2 | #! /usr/bin/python3
str1 ="My name is Idris"
str2 = str1.replace(" ", "**")
print(str2)
| Python | zaydzuhri_stack_edu_python |
function _merge x y
begin
for key in x
begin
if key in y
begin
set x at key = call _merge x at key y at key
set y at key = none
end
end
for key in y
begin
if y at key is not none
begin
set x at key = y at key
end
end
return x
end function | def _merge(x, y):
for key in x:
if key in y:
x[key] = _merge(x[key], y[key])
y[key] = None
for key in y:
if y[key] is not None:
x[key] = y[key]
return x | Python | nomic_cornstack_python_v1 |
function _preprocess_data data
begin
comment Convert the json string to a python dictionary object
set feature_vector_dict = loads data
set input_df = call from_dict list feature_vector_dict
comment Column name fixing
set columns = replace str string = string _
set columns = replace str string __ string _
set columns =... | def _preprocess_data(data):
# Convert the json string to a python dictionary object
feature_vector_dict = json.loads(data)
input_df = pd.DataFrame.from_dict([feature_vector_dict])
# Column name fixing
input_df.columns = input_df.columns.str.lower().str.replace(' ', '_').str.replace('-', '_').str.rep... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
from source.ch8.p1.ch8_1_2 import Get_data , Create_model
seed 1
function show_prediction model x_test y_test
begin
set n_show = 96
comment (A)
set y = predict model x_test
figure 2 figsize=tuple 12 8
call gray
for i in range n_show
begin
subplot 8 12 i + 1
set x = x_t... | import numpy as np
import matplotlib.pyplot as plt
from source.ch8.p1.ch8_1_2 import Get_data, Create_model
np.random.seed(1)
def show_prediction(model, x_test, y_test):
n_show = 96
y = model.predict(x_test) # (A)
plt.figure(2, figsize=(12, 8))
plt.gray()
for i in range(n_show):
plt.subplo... | Python | zaydzuhri_stack_edu_python |
function baseVec df cat_name
begin
set sex = SEX_ID at index at 0
if sex == string f
begin
if cat_name == string GENRE_NAME
begin
comment baseline probability for female
set baseProb_seri = baseProb_f_g
end
else
begin
set baseProb_seri = baseProb_f_cap
end
end
else
if cat_name == string GENRE_NAME
begin
set baseProb_se... | def baseVec(df, cat_name):
sex = df.SEX_ID[df.index[0]]
if sex == 'f':
if cat_name == 'GENRE_NAME':
baseProb_seri = baseProb_f_g # baseline probability for female
else:
baseProb_seri = baseProb_f_cap
else:
if cat_name == 'GENRE_NAME':
baseP... | Python | nomic_cornstack_python_v1 |
function two_particle_snapshot_factory device
begin
function make_snapshot particle_types=list string A dimensions=3 d=1 L=20
begin
string Make the snapshot. Args: particle_types: List of particle type names dimensions: Number of dimensions (2 or 3) d: Distance apart to place particles L: Box length The two particles a... | def two_particle_snapshot_factory(device):
def make_snapshot(particle_types=['A'], dimensions=3, d=1, L=20):
"""Make the snapshot.
Args:
particle_types: List of particle type names
dimensions: Number of dimensions (2 or 3)
d: Distance apart to place particles
... | Python | nomic_cornstack_python_v1 |
function list_view request
begin
return call render request context=dict string message string hallo! apa kabar template_name=string content_news/list_view.html
end function | def list_view(request):
return render(request, context={'message': 'hallo! apa kabar'},
template_name='content_news/list_view.html') | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
set df = read csv string output.csv
set ipt_array = list
for num in range 6 length df at string cycles
begin
comment ipt_val = float( df["cycles"][num] ) / float( df["exe_time"][num] )
comment ipt_array.append(ipt_val)
append ipt_array df at string cycles at num / 26.8 * 8
end
pr... | import pandas as pd
import numpy as np
df = pd.read_csv('output.csv')
ipt_array = []
for num in range(6, len(df["cycles"])):
#ipt_val = float( df["cycles"][num] ) / float( df["exe_time"][num] )
# ipt_array.append(ipt_val)
ipt_array.append(df["cycles"][num]/(26.8*8))
print(np.mean(ipt_array)) | Python | zaydzuhri_stack_edu_python |
from engines import Engine
from MCTSCore import *
import multiprocessing
class MCTSEngine extends Engine
begin
function __init__ self
begin
set fixed_potential = call MctsPotentials
end function
function get_move self board color move_num=none time_remaining=none time_opponent=none
begin
set core = call MctsCore board ... | from engines import Engine
from MCTSCore import *
import multiprocessing
class MCTSEngine(Engine):
def __init__(self):
self.fixed_potential = MctsPotentials.MctsPotentials()
def get_move(self, board, color, move_num=None, time_remaining=None, time_opponent=None):
core = MctsCore.Mct... | Python | zaydzuhri_stack_edu_python |
import sys
import time
import deviceModule
set fd = open | import sys
import time
import deviceModule
fd = deviceModule.open()
| Python | zaydzuhri_stack_edu_python |
class Personal_info
begin
function __init__ self name age address ph_num
begin
set __name = name
set __age = age
set __address = address
set __ph_num = ph_num
end function
function set_name self name
begin
set __name = name
end function
function set_age self age
begin
set __age = age
end function
function set_address s... | class Personal_info:
def __init__(self, name, age, address, ph_num):
self.__name = name
self.__age = age
self.__address = address
self.__ph_num = ph_num
def set_name(self, name):
self.__name = name
def set_age(self, age):
self.__age = age
def s... | Python | zaydzuhri_stack_edu_python |
function traductor self text
begin
set text = text
if prova_traduccio == false
begin
return text
end
try
begin
set text_val = integer text
return text
end
except any
begin
pass
end
end function | def traductor(self, text):
text = text
if self.prova_traduccio == False:
return text
try:
text_val = int(text)
return text
except:
pass | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
import time
import socket
from omega_model.common.omega_functions import get_ip_address
set ip_address = call get_ip_address at 0
set start_time = time
set validate_batch = true
set no_sim = false
set bundle_path_root = string
set no_bundle = false
set batch_file = string
set batch_path =... | def __init__(self):
import time
import socket
from omega_model.common.omega_functions import get_ip_address
ip_address = get_ip_address()[0]
self.start_time = time.time()
self.validate_batch = True
self.no_sim = False
self.bundle_path_root = ''
s... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
function red_wine test_frame
begin
comment TRAINING THE MODEL - RED WINE
set red_wine = read csv string winequality-red.csv delimiter=string ;
comment train_X = red_wine.drop(labels='quality',axis=1)
comment train_y = red_wine['q... | import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
def red_wine(test_frame):
# TRAINING THE MODEL - RED WINE
red_wine = pd.read_csv('winequality-red.csv', delimiter=";")
#train_X = red_wine.drop(labels='quality',axis=1)
#train_y = red_wine['quality']
# Spli... | Python | zaydzuhri_stack_edu_python |
import random
function toss i
begin
set head_count = 0
set tail_count = 0
for x in range 1 i
begin
set new_toss = random integer 0 1
if new_toss == 1
begin
set head_count = head_count + 1
set result = string head
end
else
begin
set tail_count = tail_count + 1
set result = string tail
end
end
end function | import random
def toss(i):
head_count = 0
tail_count = 0
for x in range(1, i):
new_toss = random.randint(0,1)
if new_toss == 1:
head_count += 1
result = "head"
else:
tail_count += 1
result = "tail" | Python | zaydzuhri_stack_edu_python |
function _hooks_apply_before_serialize hooks state value
begin
comment type: Optional[Hooks]
comment type: _ProcessorState
comment type: Any
comment type: (...) -> Any
string Apply the before serialize hook.
if hooks and before_serialize
begin
return call before_serialize call ProcessorStateView state value
end
return ... | def _hooks_apply_before_serialize(
hooks, # type: Optional[Hooks]
state, # type: _ProcessorState
value # type: Any
):
# type: (...) -> Any
"""Apply the before serialize hook."""
if hooks and hooks.before_serialize:
return hooks.before_serialize(ProcessorStateView(state), v... | Python | jtatman_500k |
function roman_to_integer roman_numeral
begin
set roman_dict = dict string I 1 ; string V 5 ; string X 10 ; string L 50 ; string C 100 ; string D 500 ; string M 1000
set result = 0
set prev_value = 0
for c in roman_numeral at slice : : - 1
begin
set current_value = roman_dict at c
if current_value >= prev_value
begin... | def roman_to_integer(roman_numeral):
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
prev_value = 0
for c in roman_numeral[::-1]:
current_value = roman_dict[c]
if current_value >= prev_value:
result += current_value
else:
... | Python | jtatman_500k |
function womexam hop
begin
set done = false
while not done
begin
set answer = string y
set tuple wave flux mode = call womwaverange wave flux string none
set indexblue = call womget_element wave wave at 0
set indexred = call womget_element wave wave at - 1
set var = var at slice indexblue : indexred + 1 :
if length wa... | def womexam(hop):
done = False
while (not done):
answer='y'
wave,flux,mode=womwaverange(hop[0].wave,hop[0].flux,'none')
indexblue=womget_element(hop[0].wave,wave[0])
indexred=womget_element(hop[0].wave,wave[-1])
var=hop[0].var[indexblue:indexred+1]
if (len(wave) >... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python -tt
from collections import deque
import sys
import itertools
import operator
import urllib
from urllib import request
from urllib import error
from functools import lru_cache
decorator least recent cache maxsize=32
comment maxsize is better when pow of 2
function get_pep num
begin
try
begin
se... | #!/usr/bin/python -tt
from collections import deque
import sys
import itertools
import operator
import urllib
from urllib import request
from urllib import error
from functools import lru_cache
# maxsize is better when pow of 2
@lru_cache(maxsize=32)
def get_pep(num):
try:
rsrc = 'http://www.... | Python | zaydzuhri_stack_edu_python |
function get_matrix self
begin
return call tolist
end function | def get_matrix(self):
return self.matrix.tolist() | Python | nomic_cornstack_python_v1 |
function _setVals self ref_id=0
begin
set ref_id = ref_id
end function | def _setVals(self, ref_id: int = 0) -> None:
self.ref_id = ref_id | Python | nomic_cornstack_python_v1 |
function set_picture self file_name
begin
comment load the image file
set load = open file_name
comment resize to fit the window
set load = call resize tuple picture_size picture_size ANTIALIAS
comment load the image in a widget
set render = call PhotoImage load
comment remove the old image, if applicable
if has attrib... | def set_picture(self, file_name):
# load the image file
load = Image.open(file_name)
# resize to fit the window
load = load.resize((self.controller.picture_size, self.controller.picture_size), Image.ANTIALIAS)
# load the image in a widget
render = ImageTk.PhotoImage(load... | Python | nomic_cornstack_python_v1 |
function test_helmholtz_single_layer_p1_p0 default_parameters helpers precision device_interface
begin
from bempp.api.operators.boundary.helmholtz import single_layer
from bempp.api import function_space
set grid = call load_grid string sphere
set space0 = call function_space grid string DP 0
set space1 = call function... | def test_helmholtz_single_layer_p1_p0(
default_parameters, helpers, precision, device_interface
):
from bempp.api.operators.boundary.helmholtz import single_layer
from bempp.api import function_space
grid = helpers.load_grid("sphere")
space0 = function_space(grid, "DP", 0)
space1 = function_sp... | Python | nomic_cornstack_python_v1 |
function largestProductofThreeNums nums
begin
sort nums
set lastIndex = length nums - 1
if nums at 0 * nums at 1 >= nums at lastIndex * nums at lastIndex - 1
begin
return nums at 0 * nums at 1 * nums at lastIndex
end
else
begin
return nums at lastIndex * nums at lastIndex - 1 * nums at lastIndex - 2
end
end function
se... | def largestProductofThreeNums(nums):
nums.sort()
lastIndex = len(nums) - 1
if ((nums[0] * nums[1]) >= (nums[lastIndex] * nums[lastIndex - 1])):
return nums[0] * nums[1] * nums[lastIndex]
else:
return nums[lastIndex] * nums[lastIndex - 1] * nums[lastIndex - 2]
list = [-4, -4, 2, 8]
print(largestProductofThre... | Python | zaydzuhri_stack_edu_python |
function generate_additional_files input_qchem work_dir
begin
comment handle custom guess
if mo_coefficients is not none
begin
call store_mo_file work_dir
end
if scf_density is not none
begin
call store_density_file work_dir
end
comment set scf energy if skip_scfman (to not break)
comment TODO: now SCF energy is set to... | def generate_additional_files(input_qchem, work_dir):
# handle custom guess
if input_qchem.mo_coefficients is not None:
input_qchem.store_mo_file(work_dir)
if input_qchem.scf_density is not None:
input_qchem.store_density_file(work_dir)
# set scf energy if skip_scfman (to not break)
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import sys
set matrix = list
set rows = 0
comment Prepare triangle from stdin
set lines = read stdin
for line in call splitlines
begin
set elems = split line string
append matrix list map int elems
set rows = rows + 1
end
comment go up to find a path O((width + height) / 2)
for row in reve... | #!/usr/bin/env python
import sys
matrix = []
rows = 0
# Prepare triangle from stdin
lines = sys.stdin.read()
for line in lines.splitlines():
elems = line.split(" ")
matrix.append(list(map(int, elems)))
rows += 1
# go up to find a path O((width + height) / 2)
for row in reversed(range(rows)):
row_len... | Python | zaydzuhri_stack_edu_python |
function load self
begin
set data = call read_pickle DATE_PKL
set name = DATE_COL
for tuple hname h in items handlers
begin
print string Loading %s % hname
set cur_out = string ../ + out_path
comment make daily and forward fill the values
set df = call ffill
if hname in columns
begin
comment getting to a distinct colum... | def load(self):
self.data = pd.read_pickle(self.DATE_PKL)
self.data.index.name = DATE_COL
for hname, h in self.handlers.items():
print("Loading %s" % hname)
cur_out = '../'+h.out_path
df = pd.read_pickle(cur_out).resample('D').ffill() # make daily and forwar... | Python | nomic_cornstack_python_v1 |
import unittest
import json
from flask import request , jsonify
from myservice.app import app as tested_app
from myservice.classes import quiz
class TestApp extends TestCase
begin
comment allpolls
function test1 self
begin
set allAns = list
set allQuests = list
set ans11 = call Answer string la 1 false
append allAns ... | import unittest
import json
from flask import request, jsonify
from myservice.app import app as tested_app
from myservice.classes import quiz
class TestApp(unittest.TestCase):
def test1(self): # allpolls
allAns = []
allQuests = []
ans11 = quiz.Answer("la 1", False)
allAns.append... | Python | zaydzuhri_stack_edu_python |
string Help speed up preprocessing of some datasets by running jobs on multiple cores
import tqdm
import multiprocessing
function run_job_pool func argsList desc=none cores=none
begin
string Processor pool to use multiple cores, with a progress bar func = function to execute argsList = array of tuples, each tuple is th... | """
Help speed up preprocessing of some datasets by running jobs on multiple cores
"""
import tqdm
import multiprocessing
def run_job_pool(func, argsList, desc=None, cores=None):
"""
Processor pool to use multiple cores, with a progress bar
func = function to execute
argsList = array of tuples, each ... | Python | zaydzuhri_stack_edu_python |
function load self tensor
begin
comment TODO mock for now, load will use worker's store in a future work
if tracing
begin
return call create_from tensor role=self tracing=true
end
else
begin
return tensor
end
end function | def load(self, tensor):
# TODO mock for now, load will use worker's store in a future work
if self.tracing:
return PlaceHolder.create_from(tensor, role=self, tracing=True)
else:
return tensor | Python | nomic_cornstack_python_v1 |
async function test_complex_nft_offer self_hostname two_wallet_nodes trusted royalty_pts
begin
set tuple full_nodes wallets _ = two_wallet_nodes
set full_node_api : FullNodeSimulator = full_nodes at 0
set full_node_server = server
set tuple wallet_node_maker server_0 = wallets at 0
set tuple wallet_node_taker server_1 ... | async def test_complex_nft_offer(
self_hostname: str, two_wallet_nodes: Any, trusted: Any, royalty_pts: Tuple[int, int, int]
) -> None:
full_nodes, wallets, _ = two_wallet_nodes
full_node_api: FullNodeSimulator = full_nodes[0]
full_node_server = full_node_api.server
wallet_node_maker, server_0 = wal... | Python | nomic_cornstack_python_v1 |
function fetch_api path token method=string GET data=dict json=dict files=dict headers=dict params=dict timeout=0 verify=VERIFY **kwargs
begin
set url = API_URL + format path keyword kwargs
set headers = dict none headers ; none call set_headers token
set timeout = timeout or API_DEFAULT_TIMEOUT
set session = call... | def fetch_api(
path, token, method='GET', data={}, json={}, files={}, headers={}, params={},
timeout=0, verify=VERIFY, **kwargs
):
url = settings.API_URL + path.format(**kwargs)
headers = {**headers, **set_headers(token)}
timeout = timeout or config.API_DEFAULT_TIMEOUT
session = Session()
... | Python | nomic_cornstack_python_v1 |
function send_private_message self action json_data
begin
set data = dict string from player_name ; string to json_data at string data at string to ; string message json_data at string data at string message
try
begin
call send_to_spec_user to_player=json_data at string data at string to message=call generate_response ... | def send_private_message(self,
action: str,
json_data: Any
) -> None:
data = {
'from': self.player.player_name,
'to': json_data['data']['to'],
'message': json_data['data']['message']
... | Python | nomic_cornstack_python_v1 |
function testColumnWithZero self
begin
set slot_allocation = 0
put
set user = call seedNDBUser host_for=list program
call loginNDB user
set url = string /gsoc/admin/slots/ + call name
set response = call getListData url 0
call assertEquals response at 0 at string columns at string slot_allocation 0
end function | def testColumnWithZero(self):
self.org.slot_allocation = 0
self.org.put()
user = profile_utils.seedNDBUser(host_for=[self.program])
profile_utils.loginNDB(user)
url = '/gsoc/admin/slots/' + self.gsoc.key().name()
response = self.getListData(url, 0)
self.assertEquals(response[0]['columns'][... | Python | nomic_cornstack_python_v1 |
function CreateGenePool count generator fuzzer **kwargs
begin
set genes = list
for index in range count
begin
set gene = call generator keyword kwargs
append genes call fuzzer gene
end
return genes
end function | def CreateGenePool(count, generator, fuzzer, **kwargs):
genes = []
for index in range(count):
gene = generator(**kwargs)
genes.append(fuzzer(gene))
return genes | Python | nomic_cornstack_python_v1 |
function train model optimizer loss num_steps=1000
begin
comment Autoguide
set guide = call AutoMultivariateNormal model
set svi = call SVI model guide optimizer loss
comment do gradient steps
set losses = list
for _ in range num_steps
begin
append losses step svi
end
return tuple guide losses
end function | def train(model, optimizer, loss, num_steps=1000):
# Autoguide
guide = autoguide.AutoMultivariateNormal(model.model)
svi = SVI(model.model, guide, optimizer, loss)
# do gradient steps
losses = []
for _ in range(num_steps):
losses.append(svi.step())
return guide, losses | Python | nomic_cornstack_python_v1 |
import json
import urllib
comment url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/comments_42.json'
set url = call raw_input string Enter URL:
set data = read url open url
set js = loads data
set total = 0
for comment in js at string comments
begin
set total = total + comment at string count
end | import json
import urllib
#url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/comments_42.json'
url = raw_input('Enter URL: ')
data = urllib.urlopen(url).read()
js = json.loads(data)
total = 0
for comment in js['comments']:
total += comment['count']
| Python | zaydzuhri_stack_edu_python |
set glossary = dict string list string of anything. ; string tupple string can't be change ; string .len string return length of something ; string .title string capitalize the first alphabet
print string list + glossary at string list + string .
print string tupple + glossary at string tupple + string .
print string T... | glossary={'list':'of anything.','tupple':"can't be change",
'.len':'return length of something',
'.title':'capitalize the first alphabet'}
print('list '+glossary['list']+".")
print('tupple '+glossary['tupple']+".")
print('Title '+glossary['.title']+".")
print('Length '+glossary['.len']+".") | Python | zaydzuhri_stack_edu_python |
string input--> p,r,n,ci p--> principle r--> rate of intrest n--> no. of years ci--> compound intrest process ci=p*pow(1+r/100,n)-p
set p = integer input string Enter P:
set r = integer input string Enter r:
set n = integer input string Enter n:
set ci = p * power 1 + r / 100 n - p
print string compound intrest = ci
pr... | """
input--> p,r,n,ci
p--> principle
r--> rate of intrest
n--> no. of years
ci--> compound intrest
process
ci=p*pow(1+r/100,n)-p
"""
p=int(input("Enter P: "))
r=int(input("Enter r: "))
n=int(input("Enter n: "))
ci=p*pow(1+r/100,n)-p
print("compound intrest = ",ci)
print(type(p,n,r))
| Python | zaydzuhri_stack_edu_python |
function latex_tool_name tool
begin
if tool == string a-b-CROWN
begin
set tool = string $\alpha$,$\beta$-CROWN
end
return tool
end function | def latex_tool_name(tool):
if tool == 'a-b-CROWN':
tool = '$\\alpha$,$\\beta$-CROWN'
return tool | Python | nomic_cornstack_python_v1 |
function get_existing_file_hash path
begin
import hashlib
set prefix = call _cache_prefix_for_file path
set md5 = md5
with open path string rb as infile
begin
update md5 prefix + read infile
end
return hex digest md5
end function | def get_existing_file_hash(path: str) -> str:
import hashlib
prefix = _cache_prefix_for_file(path)
md5 = hashlib.md5()
with open(path, 'rb') as infile:
md5.update(prefix + infile.read())
return md5.hexdigest() | Python | nomic_cornstack_python_v1 |
function get_category_by_name name
begin
return first filter name == name
end function | def get_category_by_name(name):
return session.query(Category).filter(Category.name == name).first() | Python | nomic_cornstack_python_v1 |
function video_embed cls
begin
set embed = call embed_msg title=string Now playing description=string ```css { title } ``` field_values=list dict string name string Duration ; string value duration dict string name string Requested by ; string value mention dict string name string URL ; string value string [YouTube]( {... | def video_embed(cls) -> discord.embeds.Embed:
embed = embed_msg(
title="Now playing",
description=f"```css\n{cls.source.title}\n```",
field_values=[
{"name": "Duration", "value": cls.source.duration},
{"name": "Requested by", "value": cls.requester.mention},
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import os
import logging
import math
from margin_lib import Margin
comment Setup Logging Configuration
set logger = call getLogger base name path __file__
if not length handlers
begin
call setLevel DEBUG
set ch = call StreamHandler
call setLevel DEBUG
set formatter = call Formatte... | import numpy as np
import pandas as pd
import os
import logging
import math
from margin_lib import Margin
##############################
# Setup Logging Configuration
##############################
logger = logging.getLogger(os.path.basename(__file__))
if not len(logger.handlers):
logger.setLevel(logging.DEBUG)
... | Python | zaydzuhri_stack_edu_python |
function pt lst title
begin
print title length lst
for item in lst
begin
print item
end
print string
end function
import os
try
begin
remove os string test.db
end
except any
begin
print string remove error
end
import data as d
call sqlInit
comment 1
insert d string p001 string c01 string single string t1 t2 t3 string 3... | def pt(lst,title):
print(title,len(lst))
for item in lst:
print(item)
print('')
import os
try:
os.remove("test.db")
except:
print("remove error")
import data as d
d.sqlInit()
d.insert('p001','c01','single','t1 t2 t3','3')#1
d.insert('p002','c01','single','t1' ,'2')#2
d.insert('p003... | Python | zaydzuhri_stack_edu_python |
function _full_path_patterns patterns rootdir
begin
if rootdir
begin
comment sort for consistency
return sorted list comprehension call FilterPattern type=type pattern=join path rootdir pattern for f in patterns
end
return list patterns
end function | def _full_path_patterns(
patterns: Iterable[FilterPattern], rootdir: Optional[str]
) -> List[FilterPattern]:
if rootdir:
return sorted( # sort for consistency
[
FilterPattern(type=f.type, pattern=os.path.join(rootdir, f.pattern))
f... | Python | nomic_cornstack_python_v1 |
function close self reply_code=0 reply_text=string Normal Shutdown
begin
if not is_open
begin
raise call ChannelClosed
end
info string Channel.close(%s, %s) reply_code reply_text
if _consumers
begin
debug string Cancelling %i consumers length _consumers
for consumer_tag in keys _consumers
begin
call basic_cancel consum... | def close(self, reply_code=0, reply_text="Normal Shutdown"):
if not self.is_open:
raise exceptions.ChannelClosed()
LOGGER.info('Channel.close(%s, %s)', reply_code, reply_text)
if self._consumers:
LOGGER.debug('Cancelling %i consumers', len(self._consumers))
... | Python | nomic_cornstack_python_v1 |
function print_board self
begin
set line = string ---------------------
for tuple i row in enumerate board
begin
set row_string = string
for tuple j col in enumerate row
begin
if j == 3 or j == 6
begin
set row_string = row_string + string |
end
set row_string = row_string + string row at j + string
end
print row_stri... | def print_board(self):
line = "---------------------"
for i, row in enumerate(self.board):
row_string = ""
for j, col in enumerate(row):
if j == 3 or j == 6:
row_string += "| "
row_string += str(row[j]) + " "
print(r... | Python | nomic_cornstack_python_v1 |
string Search contacts.
from functions import open_csv_pop_lst_namedtuple
while true
begin
set contacts = call open_csv_pop_lst_namedtuple
set user_search = input string Search for a contact >
if user_search == string
begin
break
end
if user_search in contacts
begin
print string { user_search } is listed in the contac... | """Search contacts."""
from functions import open_csv_pop_lst_namedtuple
while True:
contacts = open_csv_pop_lst_namedtuple()
user_search = input("\nSearch for a contact\n> ")
if user_search == "":
break
if user_search in contacts:
print(f"{user_search} is listed in the contact databas... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
string asonste 12/Nov.2016 For posting values to emoncms Run with poststing as argument. example: sudo python emoncms.py 'ID1:10' if you vant to post multiple values at the same time, separate with comma: example: sudo python emoncms.py 'ID1:10,ID2:20'
import sys
import urllib2
comment import u... | #!/usr/bin/python
"""
asonste 12/Nov.2016
For posting values to emoncms
Run with poststing as argument.
example: sudo python emoncms.py 'ID1:10'
if you vant to post multiple values at the same time, separate with comma:
example: sudo python emoncms.py 'ID1:10,ID2:20'
"""
import sys
import urllib2
from conf import * # i... | Python | zaydzuhri_stack_edu_python |
function move_robot self target_pos target_orn finger_target=none num_sim_steps=1 max_retries=300
begin
if finger_target is none
begin
set finger_target = finger_target
end
comment Validate input to make sure that pose is attainable. If not, set to attainable pose.
set tuple target_pos target_orn = call validate_pose t... | def move_robot(self,
target_pos,
target_orn,
finger_target=None,
num_sim_steps=1,
max_retries=300):
if finger_target is None:
finger_target = self.finger_target
# Validate input to make sure that pose is attainable. If not, set ... | Python | nomic_cornstack_python_v1 |
function drawdown_dur pnl how=string high
begin
comment Get Drawdown Max Duration
set mark = if expression how == string high then maximum else minimum
set watermark = accumulate fill missing pnl min
set dd = 1 - pnl / call shift 1
set ix at dd < 0 = 0
set drawdown = dd
set sr = as type drawdown at slice 1 : : bool
r... | def drawdown_dur(pnl, how = 'high'):
# Get Drawdown Max Duration
mark = np.maximum if how == 'high' else np.minimum
watermark = mark.accumulate(pnl.fillna(pnl.min()))
dd = 1 - (pnl / watermark.shift(1))
dd.ix[dd < 0] = 0
drawdown = dd
sr = drawdown[1:].astype(bool... | Python | nomic_cornstack_python_v1 |
function delete_task task_id
begin
try
begin
with call TaskTable as table
begin
set result = remove table dict string task_id dict string $eq task_id
if result at string ok != 1 and result at string n == 0
begin
error string Failed to delete task %s task_id
return tuple - 104 string Failed to delete task
end
info strin... | def delete_task(task_id):
try:
with TaskTable() as table:
result = table.remove({"task_id": {"$eq": task_id}})
if result["ok"] != 1 and result['n'] == 0:
log.error("Failed to delete task %s", task_id)
return (-104, "Failed to delete task")
log.info("Task with id %d deleted", task_id)
retu... | Python | nomic_cornstack_python_v1 |
function handle_sentence_simple self sentence ctxinfo
begin
global text_version
global moses_version
global lower_attr
for w in sentence
begin
set attribute w lower_attr lower get attribute w lower_attr
end
call handle_sentence sentence ctxinfo
end function | def handle_sentence_simple(self, sentence, ctxinfo):
global text_version
global moses_version
global lower_attr
for w in sentence :
setattr(w, lower_attr, getattr(w, lower_attr).lower())
self.chain.handle_sentence(sentence, ctxinfo) | Python | nomic_cornstack_python_v1 |
function request_check client exception *msg_parms **kwargs
begin
string Make blocking request to client and raise exception if reply is not ok. Parameters ---------- client : DeviceClient instance exception: Exception class to raise *msg_parms : Message parameters sent to the Message.request() call **kwargs : Keyword ... | def request_check(client, exception, *msg_parms, **kwargs):
"""Make blocking request to client and raise exception if reply is not ok.
Parameters
----------
client : DeviceClient instance
exception: Exception class to raise
*msg_parms : Message parameters sent to the Message.request() call
... | Python | jtatman_500k |
function CreateVars self
begin
set dat_path = call StringVar
set string
set YSF_Version = call StringVar
set string 20170314
set ysf_versions = list string 20170314 string 20150406 string 20130817 string 20120701 string 20110207 string 20100331 string 20090611 string 20080220 string 20070415 string 20060828
end functio... | def CreateVars(self):
self.dat_path = StringVar()
self.dat_path.set("")
self.YSF_Version = StringVar()
self.YSF_Version.set("20170314")
self.ysf_versions = ["20170314","20150406","20130817","20120701",
"20110207","20100331","20090611","20080220",
... | Python | nomic_cornstack_python_v1 |
function deal self
begin
if size self > 0
begin
comment this does not affect the run-time
set decksize = size self - 1
comment efficiency of the size() operation
return pop cards
end
else
begin
return false
end
end function | def deal(self):
if self.size() > 0:
self.decksize = self.size() - 1 # this does not affect the run-time
# efficiency of the size() operation
return self.cards.pop()
else:
return False | Python | nomic_cornstack_python_v1 |
function getargs
begin
set parser = call ArgumentParser
call add_argument string path type=chkpath nargs=string ? default=string . help=string a valid path
call add_argument string -v string --verbosity action=string count default=0 help=string increase output verbosity
return call parse_args
end function | def getargs():
parser = argparse.ArgumentParser()
parser.add_argument(
"path", type=chkpath, nargs="?", default=".", help="a valid path"
)
parser.add_argument(
"-v", "--verbosity", action="count", default=0, help="increase output verbosity"
)
return parser.parse_args() | Python | nomic_cornstack_python_v1 |
comment !/home/liulab/yzhang/python/bin/python
comment zy@jimmy.harvard.edu
import sys , os.path , time
from numpy import *
class Bed extends object
begin
string Bed file object 1) if the bed file is not very large: bed1 = Bed() bed1.readbed(bedfilename) bed1.bedsort() bed1.release_space() 2) if the bed file is very la... | #!/home/liulab/yzhang/python/bin/python
# zy@jimmy.harvard.edu
import sys, os.path, time
from numpy import *
class Bed(object):
""" Bed file object
1) if the bed file is not very large:
bed1 = Bed()
bed1.readbed(bedfilename)
bed1.bedsort()
bed1.release_space()
2) if the bed file is very la... | Python | zaydzuhri_stack_edu_python |
function run self
begin
call request_weather_data
close client
end function | def run(self):
self.request_weather_data()
client.close() | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
set costs = list 1 4 9 16
y label string some numbers
comment plt.plot(costs)
plot list 1 2 3 4 costs
show | import numpy as np
import matplotlib.pyplot as plt
costs = [1,4,9,16]
plt.ylabel('some numbers')
#plt.plot(costs)
plt.plot([1, 2, 3, 4], costs)
plt.show() | Python | zaydzuhri_stack_edu_python |
function split_equal_sum arr
begin
set n = length arr
set leftsum = 0
set rightsum = sum arr
for i in range n
begin
set rightsum = rightsum - arr at i
if leftsum == rightsum
begin
return true
end
set leftsum = leftsum + arr at i
end
return false
end function | def split_equal_sum(arr):
n = len(arr)
leftsum = 0
rightsum = sum(arr)
for i in range(n):
rightsum -= arr[i]
if leftsum == rightsum:
return True
leftsum += arr[i]
return False | Python | jtatman_500k |
function parseline line
begin
string Parse one line of a data file. Parameters ---------- line : string
set tuple id neighbors = split line string ->
set neighbors = split strip neighbors string ,
return tuple id neighbors
end function | def parseline(line):
'''
Parse one line of a data file.
Parameters
----------
line : string
'''
id, neighbors = line.split('->')
neighbors = neighbors.strip().split(',')
return id, neighbors
| Python | zaydzuhri_stack_edu_python |
string Client Colors ========================== Provides functions to fetch and parse data from Kingo's ElasticSearch Data Warehouse to generate a report on client colors. - Create date: 2018-12-11 - Update date: 2018-12-28 - Version: 1.2 Notes: ========================== - v1.0: Initial version - v1.1: Elasticsearch i... | """
Client Colors
==========================
Provides functions to fetch and parse data from Kingo's ElasticSearch Data
Warehouse to generate a report on client colors.
- Create date: 2018-12-11
- Update date: 2018-12-28
- Version: 1.2
Notes:
==========================
- v1.0: Initial version
- v1.1: Elasticse... | Python | zaydzuhri_stack_edu_python |
comment Habituação
print string ********FASE DE HABITUAÇÃO ********
set habituacao = input string O animal está habituado, sim ou não?
comment R2: i
set distancia = 30
if habituacao == string SIM or habituacao == string sim
begin
print string O animal está habituado
set habituado = true
end
else
begin
print string Pros... | #Habituação
print("********FASE DE HABITUAÇÃO ********")
habituacao=input("O animal está habituado, sim ou não?")
distancia=30 #R2: i
if (habituacao=="SIM" or habituacao== "sim"):
print("O animal está habituado")
habituado=True
else:
print("Prossiga com os experimentos até ele está habituado")
print(... | Python | zaydzuhri_stack_edu_python |
function update self data
begin
print data
set table = data
end function | def update(self, data):
print(data)
self.table = data | Python | nomic_cornstack_python_v1 |
function prepare_spec_lib_for_json_storage decoded
begin
set reflib_dict = dictionary
set counter = 1
for spectrum in read mgf call StringIO decode decoded string utf-8 use_index=false
begin
set mz = get spectrum string m/z array
set intensities = get spectrum string intensity array
set metadata = get spectrum string p... | def prepare_spec_lib_for_json_storage(
decoded,
):
reflib_dict = dict()
counter = 1
for spectrum in mgf.read(io.StringIO(
decoded.decode('utf-8')
),
use_index=False,
):
mz = spectrum.get('m/z array')
intensities = spectrum.get('intensity array')
... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.