code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _get_state self
begin
return __state
end function | def _get_state(self):
return self.__state | Python | nomic_cornstack_python_v1 |
function test_check_failed_highstate self
begin
assert equal call check_failed_highstate string aw1-php70-qa string 01 false
end function | def test_check_failed_highstate(self):
self.assertEqual(self.checkredis.check_failed_highstate("aw1-php70-qa", "01"), False) | Python | nomic_cornstack_python_v1 |
while count <= k
begin
set total = total + count
set count = count + 1
end
print total | while count <= k:
total = total + count
count += 1
print(total)
| Python | zaydzuhri_stack_edu_python |
import subprocess
run list string cleanmgr | import subprocess
subprocess.run(['cleanmgr'])
| Python | flytech_python_25k |
function to_dict self
begin
set result = dict
for tuple attr _ in call iteritems openapi_types
begin
set value = get attribute self attr
if is instance value list
begin
set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value
end
else
if has attribute value ... | def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
... | Python | nomic_cornstack_python_v1 |
comment so now not needed.
function clean_file filesnames_list file_type
begin
global files_list
set files_list = list
global ft_list
set ft_list = list
for line in filesnames_list
begin
comment split off file_type here
set tuple s fileType = split line string .
print s
append files_list s
append ft_list fileType
end... | def clean_file(filesnames_list, file_type): # so now not needed.
global files_list
files_list = []
global ft_list
ft_list = []
for line in filesnames_list:
s, fileType = line.split('.') # split off file_type here
print(s)
files_list.append(s)
ft_list.append(... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
from collections import defaultdict
set valueTable = dict string 2 2 ; string 3 3 ; string 4 4 ; string 5 5 ; string 6 6 ; string 7 7 ; string 8 8 ; string 9 9 ; string T 10 ; string J 11 ; string Q 12 ; string K 13 ; string A 14
class Card
begin
function __init__ self cardString
begin
set ... | #!/usr/bin/env python
from collections import defaultdict
valueTable = {
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'T': 10,
'J': 11,
'Q': 12,
'K': 13,
'A': 14 }
class Card:
def __init__(self, cardString):
self.value = valueTable[cardStri... | Python | zaydzuhri_stack_edu_python |
function clean_and_split text compiled_pattern=TOKENIZER
begin
set text = strip lower text
if not has attribute compiled_pattern string findall
begin
return split text
end
return find all text
end function | def clean_and_split(text: str, compiled_pattern=TOKENIZER):
text = text.lower().strip()
if not hasattr(compiled_pattern, 'findall'):
return text.split()
return compiled_pattern.findall(text) | Python | nomic_cornstack_python_v1 |
import numpy as np
from numpy import loadtxt
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from agent import output_
import math
import torch
set dataset = call loadtxt string ./HTRU2/HTRU_2.csv delimiter=string ,
set X = dataset at tup... | import numpy as np
from numpy import loadtxt
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from agent import output_
import math
import torch
dataset = loadtxt('./HTRU2/HTRU_2.csv', delimiter=",")
X = dataset[:, 0:8]
Y = d... | Python | zaydzuhri_stack_edu_python |
function create_connector self request connector_id=none
begin
return call go
end function | def create_connector(self, request, connector_id=None):
return self.start().uri('/api/connector') \
.url_segment(connector_id) \
.body_handler(JSONBodyHandler(request)) \
.post() \
.go() | Python | nomic_cornstack_python_v1 |
function __init__ self state_size action_size seed modeltype=string dqn
begin
call __init__
set seed = call manual_seed seed
set modeltype = modeltype
set fc1_units = 128
set fc2_units = 32
if modeltype in list string dqn string double_dqn
begin
set fc1 = linear state_size fc1_units
set fc2 = linear fc1_units fc2_units... | def __init__(self, state_size, action_size, seed, modeltype='dqn'):
super(QNetwork, self).__init__()
self.seed = torch.manual_seed(seed)
self.modeltype = modeltype
fc1_units=128
fc2_units=32
if self.modeltype in ['dqn', 'double_dqn']:
self.fc... | Python | nomic_cornstack_python_v1 |
from sys import stdin
set s = strip read line stdin
set ans = string No
if starts with s string YAKI
begin
set ans = string Yes
end | from sys import stdin
s = stdin.readline().strip()
ans = 'No'
if s.startswith('YAKI'):
ans = 'Yes' | Python | zaydzuhri_stack_edu_python |
function colorize localized_string text_color=DEFAULT
begin
if text_color == DEFAULT
begin
return localized_string
end
if not has attribute text_color string value
begin
return localized_string
end
return call create_localized_string value tokens=tuple localized_string
end function | def colorize(localized_string: LocalizedString, text_color: CommonLocalizedStringColor=CommonLocalizedStringColor.DEFAULT) -> LocalizedString:
if text_color == CommonLocalizedStringColor.DEFAULT:
return localized_string
if not hasattr(text_color, 'value'):
return localized_string... | Python | nomic_cornstack_python_v1 |
from logging import debug , info
from numpy import array , copy
from scipy.io import loadmat , savemat
from scipy.sparse import csr_matrix
class MatrixStore
begin
function __init__ self
begin
set template = lambda season power -> string data/ { season } / { season } _ { power } .mat
end function
function seed self seas... | from logging import debug, info
from numpy import array, copy
from scipy.io import loadmat, savemat
from scipy.sparse import csr_matrix
class MatrixStore:
def __init__(self):
self.template = lambda season, power : f"data/{season}/{season}_{power}.mat"
def seed(self, seasons, steps):
for season in seasons:
tr... | Python | zaydzuhri_stack_edu_python |
function _torpedo_hit_asteroid self asteroid torpedo
begin
comment the position that the new asteroids are going to start - the same
comment position that of the coalition
set new_asteroids_pos = call get_position
set asteroid_hit_speed = call get_speed
set torpedo_hit_speed = call get_speed
if call get_size == BIGGEST... | def _torpedo_hit_asteroid(self, asteroid, torpedo):
# the position that the new asteroids are going to start - the same
# position that of the coalition
new_asteroids_pos = asteroid.get_position()
asteroid_hit_speed = asteroid.get_speed()
torpedo_hit_speed = torpedo.get_speed()
... | Python | nomic_cornstack_python_v1 |
function heading self text id=string size=string 3
begin
comment size needs to be a string, not a number
set size = string size
set text = string <h + size + string id=" + string id + string "> + string text + string </h + size + string >
add self text
end function | def heading(self,text,id="",size='3'):
size=str(size)#size needs to be a string, not a number
text = '\n<h'+size+' id="'+str(id)+'">'+str(text)+'</h'+size+'>\n'
self.add(text) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment This script registers a new user, or tells the user to enter a new username if the username they choose is taken.
import cgi , os
import cgitb
call enable
import sys
import glob
append path string \Python27\Scripts
import MySQLdb as mdb
set logFile = open string registerlog.txt stri... | #!/usr/bin/env python
# This script registers a new user, or tells the user to enter a new username if the username they choose is taken.
import cgi, os
import cgitb; cgitb.enable()
import sys
import glob
sys.path.append('\Python27\Scripts')
import MySQLdb as mdb
logFile = open('registerlog.txt', 'a')
logFile.write(... | Python | zaydzuhri_stack_edu_python |
import math
function calculate_gcf a b
begin
if b > a
begin
comment Swap values if b is greater than a
set tuple a b = tuple b a
end
set gcf = 1
for i in range 1 call isqrt b + 1
begin
if a % i == 0 and b % i == 0
begin
set gcf = i
end
end
return gcf
end function
comment Example usage:
set a = 36
set b = 48
set gcf = c... | import math
def calculate_gcf(a, b):
if b > a:
a, b = b, a # Swap values if b is greater than a
gcf = 1
for i in range(1, math.isqrt(b) + 1):
if a % i == 0 and b % i == 0:
gcf = i
return gcf
# Example usage:
a = 36
b = 48
gcf = calculate_gcf(a, b)
print("Greatest Common... | Python | jtatman_500k |
function get self person_id
begin
set person = dict string id person_id ; string display_name string display name
set a_person = call from_dictionary person
call serialize_model_instance a_person dict string name string delete-person ; string method string DELETE ; string handler PersonHandler ; string args tuple id mo... | def get(self, person_id):
person = {
'id': person_id,
'display_name': 'display name',
}
a_person = Person.from_dictionary(person)
self.serialize_model_instance(
a_person,
{
'name': 'delete-person',
'method':... | Python | nomic_cornstack_python_v1 |
function listing self
begin
return rowlist
end function | def listing(self):
return self.rowlist | Python | nomic_cornstack_python_v1 |
function __init__ self strategies rounds round_player_count
begin
set _participants = list comprehension call Participant strategy for strategy in strategies
set _rounds = rounds
set _round_player_count = round_player_count
set _result_matrix = dict
end function | def __init__(self, strategies, rounds, round_player_count):
self._participants = [Participant(strategy) for strategy in strategies]
self._rounds = rounds
self._round_player_count = round_player_count
self._result_matrix = {} | Python | nomic_cornstack_python_v1 |
function task_runner self
begin
while 1
begin
set tuple task_id command = get task_queue
for tuple pattern callback in task_patterns
begin
set match = match pattern command
if match
begin
comment execute the callback
set ret = call callback keyword call groupdict or string
comment clear the stop flag in the event it w... | def task_runner(self):
while 1:
(task_id, command) = self.task_queue.get()
for pattern, callback in self.task_patterns:
match = re.match(pattern, command)
if match:
# execute the callback
ret = c... | Python | nomic_cornstack_python_v1 |
function spacess number wordd
begin
for i in range number
begin
set wordd = wordd + string
end
return wordd
end function
function addA number wordd
begin
for i in range number
begin
set wordd = wordd + string A
end
return wordd
end function
set line = 1
for i in range 10
begin
set wordd = string
set wordd = call spac... | def spacess(number, wordd):
for i in range(number):
wordd += ' '
return wordd
def addA (number, wordd):
for i in range(number):
wordd += 'A'
return wordd
line = 1
for i in range(10):
wordd = ''
wordd = spacess(10 - i, wordd)
wordd = addA((1 + i) * 2,wordd)
wordd = spacess(10 - i, wordd)
print(wordd... | Python | zaydzuhri_stack_edu_python |
function _saturate_angular_velocity self wtilde_nk
begin
set w_nk = call clip_by_value wtilde_nk w_bounds at 0 w_bounds at 1
return w_nk
end function | def _saturate_angular_velocity(self, wtilde_nk):
w_nk = tf.clip_by_value(wtilde_nk, self.w_bounds[0], self.w_bounds[1])
return w_nk | Python | nomic_cornstack_python_v1 |
comment import depedencies
import os , requests , csv , sys , math
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from bs4 import BeautifulSoup
comment get list of mods from csv
if is file path string ./buildAliases/aliases.csv
begin
set mods = list
with open string ./buildAliases/aliases.csv as csvfile
be... | #import depedencies
import os, requests, csv, sys, math
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from bs4 import BeautifulSoup
#get list of mods from csv
if(os.path.isfile('./buildAliases/aliases.csv')):
mods = []
with open('./buildAliases/aliases.csv') as csvfile:
readCSV = csv.reade... | Python | zaydzuhri_stack_edu_python |
function test_progressbar_kwarg_passed_sftp
begin
set url = string sftp://test.rebex.net/pub/example/pocketftp.png
set downloader = call choose_downloader url progressbar=true
assert progressbar is true
end function | def test_progressbar_kwarg_passed_sftp():
url = "sftp://test.rebex.net/pub/example/pocketftp.png"
downloader = choose_downloader(url, progressbar=True)
assert downloader.progressbar is True | Python | nomic_cornstack_python_v1 |
from itertools import combinations
set tuple S k = split input
set k = integer k
set lst = list S
sort lst
set S = join string lst
comment print(S)
for i in range k
begin
set lst1 = list call combinations S i + 1
comment print(lst1)
for j in range length lst1
begin
set temp = join string lst1 at j
print temp
end
end | from itertools import combinations
S,k=input().split()
k=int(k)
lst=list(S)
lst.sort()
S="".join(lst)
#print(S)
for i in range(k) :
lst1=list(combinations(S,i+1))
#print(lst1)
for j in range(len(lst1)) :
temp="".join(lst1[j])
print(temp) | Python | zaydzuhri_stack_edu_python |
import sqlite3
import json
from flask import render_template , flash , redirect , url_for
from app import app
from app import db
from app.models import Business
function createQuery row
begin
set business_id = get row string business_id
set name = get row string name
set neighborhood = get row string neighborhood
set a... | import sqlite3
import json
from flask import render_template, flash, redirect, url_for
from app import app
from app import db
from app.models import Business
def createQuery(row):
business_id = row.get("business_id")
name = row.get("name")
neighborhood = row.get("neighborhood")
address = row.get("address")
city =... | Python | zaydzuhri_stack_edu_python |
function encode boxes priors variances
begin
set boxes = call xyxy_to_xywha boxes
set locations = call boxes_to_locations boxes priors variances
return locations
end function | def encode(boxes, priors, variances):
boxes = xyxy_to_xywha(boxes)
locations = boxes_to_locations(boxes, priors, variances)
return locations | Python | nomic_cornstack_python_v1 |
function on_success self queue result
begin
clone self delayed_for=240 + random integer 0 120
end function | def on_success(self, queue, result):
self.clone(delayed_for=240 + randint(0, 120)) | Python | nomic_cornstack_python_v1 |
import math
function readfile
begin
with open string input.txt string r as f
begin
set startTime = integer read line f
set timeTable = split read line f string ,
end
return tuple startTime timeTable
end function
set tuple startTime timeTabe = call readfile
function earielstBus startTime arr
begin
set t = startTime
whil... | import math
def readfile():
with open("input.txt", "r") as f:
startTime = int(f.readline())
timeTable = f.readline().split(',')
return (startTime, timeTable)
startTime, timeTabe = readfile()
def earielstBus(startTime, arr):
t = startTime
while True:
for it in arr:
... | Python | zaydzuhri_stack_edu_python |
import csv
import argparse
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
import hypertools as hyp
set parser = call ArgumentParser
call add_argument string fname type=str
call add_argument string k_clusters metavar=string k type=int
call add_argument string export_name type=str
call add_ar... | import csv
import argparse
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
import hypertools as hyp
parser = argparse.ArgumentParser()
parser.add_argument('fname', type=str)
parser.add_argument('k_clusters', metavar='k', type=int)
parser.add_argument('export_name', type=str)
parser.add_argu... | Python | zaydzuhri_stack_edu_python |
function Fib_recursive n
begin
if n <= 1
begin
return n
end
else
begin
return call Fib_recursive n - 1 + call Fib_recursive n - 2
end
end function | def Fib_recursive(n):
if n <= 1:
return n
else:
return Fib_recursive(n - 1) + Fib_recursive(n - 2)
| Python | flytech_python_25k |
from flask import Flask , Response , jsonify
from Flask_PoolMysql import func
comment 实例化flask对象
set app = call Flask __name__
call from_pyfile string config.py
class JsonResponse extends Response
begin
decorator classmethod
function force_type cls response environ=none
begin
string 这个方法只有视图函数返回非字符、非元祖、非Response对象才会调用 ... | from flask import Flask, Response, jsonify
from Flask_PoolMysql import func
# 实例化flask对象
app = Flask(__name__)
app.config.from_pyfile('config.py')
class JsonResponse(Response):
@classmethod
def force_type(cls, response, environ=None):
"""这个方法只有视图函数返回非字符、非元祖、非Response对象才会调用
:param response:
... | Python | zaydzuhri_stack_edu_python |
function time_stats df month day
begin
print string Calculating The Most Frequent Times of Travel...
set start_time = time
comment TO DO: display the most common month
set months = list string January string February string March string April string May string June
if month == string All
begin
set most_common_month = m... | def time_stats(df, month, day):
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
months = ['January', 'February', 'March', 'April', 'May', 'June']
if month == 'All':
most_common_month = df['Start Time'].dt.month.m... | Python | nomic_cornstack_python_v1 |
from gym_torcs import TorcsEnv
from collections import deque
import numpy as np
from keras.layers import Dense , Input , Add , Concatenate
from keras.optimizers import Adam
from keras.models import Model
from keras import backend as K
import tensorflow as tf
import random
function ou_noise x mu theta sigma
begin
return... | from gym_torcs import TorcsEnv
from collections import deque
import numpy as np
from keras.layers import Dense, Input, Add, Concatenate
from keras.optimizers import Adam
from keras.models import Model
from keras import backend as K
import tensorflow as tf
import random
def ou_noise(x, mu, theta, sigma):
return th... | Python | zaydzuhri_stack_edu_python |
function formfield self **kwargs
begin
set defaults = dict
if has attribute remote_field string get_related_field
begin
comment If this is a callable, do not invoke it here. Just pass
comment it in the defaults for when the form class will later be
comment instantiated.
set limit_choices_to = limit_choices_to
update d... | def formfield(self, **kwargs):
defaults = {}
if hasattr(self.remote_field, "get_related_field"):
# If this is a callable, do not invoke it here. Just pass
# it in the defaults for when the form class will later be
# instantiated.
limit_choices_to = self.re... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[1]:
from Queue import Queue
class Node extends object
begin
function __init__ self value left=none right=none
begin
if value < 0
begin
raise call ValueError string value cannot be negative
end
set value = value
set left = left
set right = right
end function
function setValue self value
... | # coding: utf-8
# In[1]:
from Queue import Queue
class Node(object):
def __init__(self, value, left=None, right=None):
if value < 0:
raise ValueError('value cannot be negative')
self.value = value
self.left = left
self.right = right
def setV... | Python | zaydzuhri_stack_edu_python |
function fileno self
begin
return call fileno
end function | def fileno(self):
return self.fileobj.fileno() | Python | nomic_cornstack_python_v1 |
string Problem 5 of Nuria's HW4. Adiabatic exponent gamma3 stuff.
from __future__ import division
import numpy as np
import astropy
import astropy.units as u
import astropy.constants as c
set chi_H = 13.6 * eV
function ionization_fraction_y temperature density
begin
string Ionization fraction 'y' following Clayton's no... | """
Problem 5 of Nuria's HW4. Adiabatic exponent gamma3 stuff.
"""
from __future__ import division
import numpy as np
import astropy
import astropy.units as u
import astropy.constants as c
chi_H = 13.6 * u.eV
def ionization_fraction_y(temperature, density):
"""
Ionization fraction 'y' following Clayton's ... | Python | zaydzuhri_stack_edu_python |
comment pragma: no cover
function register_graph_magics ip=none
begin
if ip is none
begin
from IPython import get_ipython
set ip = call get_ipython
end
call register_magics MagicGraph
end function | def register_graph_magics(ip=None): # pragma: no cover
if ip is None:
from IPython import get_ipython
ip = get_ipython()
ip.register_magics(MagicGraph) | Python | nomic_cornstack_python_v1 |
import os
import glob
import time
call system string modprobe w1-gpio
call system string modprobe w1-therm
class TempSensor
begin
function __init__ self
begin
set __BASE_DIR = string /sys/bus/w1/devices/
set __DEVICE_FOLDER = glob glob __BASE_DIR + string 28* at 0
set __DEVICE_FILE = __DEVICE_FOLDER + string /w1_slave
... | import os
import glob
import time
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
class TempSensor:
def __init__(self):
self.__BASE_DIR = '/sys/bus/w1/devices/'
self.__DEVICE_FOLDER = glob.glob(self.__BASE_DIR + '28*')[0]
self.__DEVICE_FILE = self.__DEVICE_FOLDER ... | Python | zaydzuhri_stack_edu_python |
import sys
from collections import deque
set q = deque
set n = integer right strip read line stdin
set arr = list map int split right strip read line stdin
set beforeidx = list
set idx = list
set ans = list
function lower_bound s e d
begin
while e - s > 0
begin
set m = s + e // 2
if ans at m < d
begin
set s = m + 1
... | import sys
from collections import deque
q=deque()
n=int(sys.stdin.readline().rstrip())
arr=list(map(int, sys.stdin.readline().rstrip().split()))
beforeidx=[]
idx=[]
ans=[]
def lower_bound(s, e, d):
while(e-s>0):
m=(s+e) //2
if(ans[m] <d):
s=m+1
else:
e=m
return ... | Python | zaydzuhri_stack_edu_python |
comment Load data
import pickle
import pprint
with open string review_data.pickle string rb as data_input
begin
set reloaded_review_text = load pickle data_input
end
comment pprint.pprint(reloaded_review_text)
comment print(type(reloaded_review_text))
comment STEP 2
comment Remove punctuations
from unicodedata import c... | ### Load data
import pickle
import pprint
with open("review_data.pickle", "rb") as data_input:
reloaded_review_text = pickle.load(data_input)
# pprint.pprint(reloaded_review_text)
# print(type(reloaded_review_text))
### STEP 2
### Remove punctuations
from unicodedata import category
import sys
def remove_punct(... | Python | zaydzuhri_stack_edu_python |
comment noqa
function post self group_name
begin
set r = call APIResponse
if content_type != string application/json
begin
warning string Invalid request. GROUPVARS POST requests must be in JSON format (application/json)
set tuple status msg = tuple string UNSUPPORTED format string Invalid content-type({}). Use applica... | def post(self, group_name): # noqa
r = APIResponse()
if request.content_type != 'application/json':
logger.warning("Invalid request. GROUPVARS POST requests must be "
"in JSON format (application/json)")
r.status, r.msg = "UNSUPPORTED", \
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
comment 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,
comment 又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
string 1,目前我找到的对递归最恰当的比喻,就是查词典。我们使用的词典,本身就是递归,为了解释一个词,需要使用更多的词。 当你查一个词,发现这个词的解释中某个词仍然不懂,于是你开始查这第二个词,可惜,第二个词里仍然有不懂的词,于是查第三个词, 这样查下去... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,
# 又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
'''
1,目前我找到的对递归最恰当的比喻,就是查词典。我们使用的词典,本身就是递归,为了解释一个词,需要使用更多的词。
当你查一个词,发现这个词的解释中某个词仍然不懂,于是你开始查这第二个词,可惜,第二个词里仍然有不懂的词,于是查第三个词,
这样查下去,直到有一个词的解释是你完全能看懂的,那么递归走到了尽头... | Python | zaydzuhri_stack_edu_python |
function compile_index_notebook self filename=string index save=false recursive=true
begin
set path = absolute_path / call with_suffix string .ipynb
set index_notebook = call LogIndexNotebook path=path log_folder=self name=name index=index parent=parent
if recursive
begin
for log_folder in notebook_folders
begin
call c... | def compile_index_notebook(self,
filename: str = 'index',
save: bool = False,
recursive: bool = True):
path = self.absolute_path / Path(filename).with_suffix('.ipynb')
self.index_notebook = LogIndexNotebook(path... | Python | nomic_cornstack_python_v1 |
function weather temp
begin
if temp > 60 and temp < 90
begin
print string Let's go to the beach
end
else
if temp > 30
begin
print string It's not that cold
end
else
begin
print string It's freezing!!!!
end
end function
call weather 20 | def weather (temp):
if temp > 60 and temp < 90:
print ("Let's go to the beach")
elif temp > 30:
print ("It's not that cold")
else:
print ("It's freezing!!!!")
weather (20) | Python | zaydzuhri_stack_edu_python |
function handle_mouse_event self event **kwargs
begin
for gobj in gobjects
begin
call handle_mouse_event event keyword kwargs
end
end function | def handle_mouse_event(self, event, **kwargs):
for gobj in self.gobjects:
gobj.handle_mouse_event(event, **kwargs) | Python | nomic_cornstack_python_v1 |
function json self
begin
comment Response legacy data: allow for any column to be null.
set document = dict string mhrNumber mhr_number ; string documentType document_type ; string documentRegistrationNumber document_reg_id ; string interimed interimed ; string ownerCrossReference owner_cross_reference ; string interes... | def json(self):
# Response legacy data: allow for any column to be null.
document = {
'mhrNumber': self.mhr_number,
'documentType': self.document_type,
'documentRegistrationNumber': self.document_reg_id,
'interimed': self.interimed,
'ownerCross... | Python | nomic_cornstack_python_v1 |
function init callback=none tty=7
begin
global _initialized
global _displaySize
global _callback
if _initialized
begin
return false
end
set _callback = callback
if useBrlAPIBindings
begin
try
begin
global brlAPI
global brlAPIRunning
global brlAPISourceId
call threads_init
set brlAPI = call Connection
try
begin
import o... | def init(callback=None, tty=7):
global _initialized
global _displaySize
global _callback
if _initialized:
return False
_callback = callback
if useBrlAPIBindings:
try:
global brlAPI
global brlAPIRunning
global brlAPISourceId
gob... | Python | nomic_cornstack_python_v1 |
function _init_copy self **kwargs
begin
set argnames = args
remove argnames string self
for arg in argnames
begin
set value = get attribute self string _ + arg
set default kwargs arg deep copy value
end
return call __class__ keyword kwargs
end function | def _init_copy(self, **kwargs):
argnames = inspect.getfullargspec(self.__init__).args
argnames.remove("self")
for arg in argnames:
value = getattr(self, "_" + arg)
kwargs.setdefault(arg, copy.deepcopy(value))
return self.__class__(**kwargs) | Python | nomic_cornstack_python_v1 |
comment Given: Positive integers n and m with 0 ≤ m ≤ n ≤ 2000
comment Return: Sum of combinations C(n,k) for all k satisfying m≤k≤n, modulo 1,000,000
comment Count total number of subsets having a fixed size k
comment NB order of elements (exons) in set cannot be altered in this instance
from math import factorial
fun... | #Given: Positive integers n and m with 0 ≤ m ≤ n ≤ 2000
#Return: Sum of combinations C(n,k) for all k satisfying m≤k≤n, modulo 1,000,000
#Count total number of subsets having a fixed size k
#NB order of elements (exons) in set cannot be altered in this instance
from math import factorial
def count_subsets(n,... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: UTF-8 -*-
from solapa import *
function test_overlaps
begin
set items = list tuple string First is on the far left tuple 1 2 tuple 8 9 false tuple string First is on the far right tuple 8 9 tuple 1 2 false tuple string Identical tuple 1 9 tuple 1 9 true tuple string Same... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from solapa import *
def test_overlaps():
items = [
('First is on the far left ', (1, 2), (8, 9), False),
('First is on the far right', (8, 9), (1, 2), False),
('Identical ', (1, 9), (1, 9), True),
('Same start ',(1, 5), (1, 9), True),
('... | Python | zaydzuhri_stack_edu_python |
comment This module will ask input from you and assign it to a variable
comment define a variable and collect user input
set your_input = input string Enter the VLAN ID:
comment input collected from user is always of type : string
print format string Your input is {} your_input
print format string Your input is of type... | # This module will ask input from you and assign it to a variable
# define a variable and collect user input
your_input = input("Enter the VLAN ID:")
# input collected from user is always of type : string
print("Your input is {}".format(your_input))
print("Your input is of type {}".format(type(your_input))) | Python | zaydzuhri_stack_edu_python |
comment ! coding=utf-8
comment 使用信号解决zombie问题
import os , time , signal
function chldhandler signum stackframe
begin
while 1
begin
try
begin
set result = call waitpid - 1 WNOHANG
end
except any
begin
break
end
end
call signal SIGCHLD chldhandler
end function
comment 每次收到SIGCHLD信号,就调用chldhandler这个处理函数
call signal SIGCHL... | #! coding=utf-8
#使用信号解决zombie问题
import os, time, signal
def chldhandler(signum ,stackframe):
while 1:
try:
result = os.waitpid(-1, os.WNOHANG)
except:
break
signal.signal(signal.SIGCHLD, chldhandler)
#每次收到SIGCHLD信号,就调用chldhandler这个处理函数
signal.signal(signal.SIGCHLD... | Python | zaydzuhri_stack_edu_python |
function store_tweets tweets filename
begin
set list_tweets = list
for tweet in tweets
begin
set tweet_infos = dict
set tweet_infos at string tweet_id = id
set tweet_infos at string user_name = screen_name
set tweet_infos at string tweet_text = text
set tweet_infos at string tweet_date = string created_at
set tweet_i... | def store_tweets(tweets,filename):
list_tweets = []
for tweet in tweets :
tweet_infos = {}
tweet_infos["tweet_id"] = tweet.id
tweet_infos["user_name"] = tweet.user.screen_name
tweet_infos["tweet_text"] = tweet.text
tweet_infos["tweet_date"] = str(tweet.created_at)
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import os
import pandas as pd
import argparse
import h5py
import librosa
from scipy import signal
import matplotlib.pyplot as plt
import time
from utilities import read_audio , create_folder , pad_or_trunc
import config
class LogMelExtractor
begin
function __init__ self sample_rate window_size overla... | import numpy as np
import os
import pandas as pd
import argparse
import h5py
import librosa
from scipy import signal
import matplotlib.pyplot as plt
import time
from utilities import read_audio, create_folder, pad_or_trunc
import config
class LogMelExtractor():
def __init__(self, sample_rate, window_size, overla... | Python | zaydzuhri_stack_edu_python |
string Custom topology example author: Brandon Heller (brandonh@stanford.edu) Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line... | """Custom topology example
author: Brandon Heller (brandonh@stanford.edu)
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command l... | Python | zaydzuhri_stack_edu_python |
function max_pp level
begin
set base_pp = 6
set level_pp = 2 * level
return base_pp + level_pp - 2
end function | def max_pp(level):
base_pp = 6
level_pp = 2 * level
return base_pp + (level_pp - 2) | Python | nomic_cornstack_python_v1 |
comment %load q01_calculate_statistics/build.py
comment Default Imports
import pandas as pd
import numpy as np
set data = read csv string data/house_prices_multivariate.csv
set sale_price = loc at tuple slice : : string SalePrice
comment Return mean,median & mode for the SalePrice Column
comment Write your code here... | # %load q01_calculate_statistics/build.py
# Default Imports
import pandas as pd
import numpy as np
data = pd.read_csv('data/house_prices_multivariate.csv')
sale_price = data.loc[:, 'SalePrice']
# Return mean,median & mode for the SalePrice Column
# Write your code here
def calculate_statistics():
mean=sale_pri... | Python | zaydzuhri_stack_edu_python |
function _worker_process msg
begin
from imolecule import format_converter
return call get attribute format_converter msg at string method keyword msg at string params
end function | def _worker_process(msg):
from imolecule import format_converter
return getattr(format_converter, msg['method'])(**msg['params']) | Python | nomic_cornstack_python_v1 |
function get_final_cols_names self col_type
begin
set col_names = list
for c_names in values columns_ctx at col_type
begin
for name in c_names
begin
if name not in col_names
begin
append col_names name
end
end
end
return col_names
end function | def get_final_cols_names(self, col_type):
col_names = []
for c_names in self.columns_ctx[col_type].values():
for name in c_names:
if name not in col_names:
col_names.append(name)
return col_names | Python | nomic_cornstack_python_v1 |
function rekey self
begin
set objdict = dictionary
set objinddict = dictionary
for r in call results
begin
if obj is not none
begin
set objdict at objname = r
set objinddict at objind = r
end
set objdict at label = r
end
end function | def rekey(self):
self.objdict = dict()
self.objinddict = dict()
for r in self.results():
if r.obj is not None:
self.objdict[r.obj.objname] = r
self.objinddict[r.obj.objind] = r
self.objdict[r.label] = r | Python | nomic_cornstack_python_v1 |
function highest_power_of_10 num
begin
set power = - 1
while num != 0
begin
set num = num // 10
set power = power + 1
end
return power
end function
function digit_by_power num power
begin
return num // 10 ^ power % 10
end function
comment first power i from the left that satisfies num[i] < num[i - 1]
comment -1 means n... | def highest_power_of_10(num):
power = -1
while (num != 0):
num //= 10
power += 1
return power
def digit_by_power(num, power):
return (num // 10 ** (power)) % 10
# first power i from the left that satisfies num[i] < num[i - 1]
# -1 means no descent
def first_power_of_des... | Python | zaydzuhri_stack_edu_python |
comment Udacity Data Structures and Algorithms
comment Part 2 - Data Structures
comment Project 2 - Problem #1 - LRU Cache
comment Script Params
set MAX_CAPACITY = 1024
set DEFAULT_CAPACITY = 64
class MAP_Node
begin
string Helper class for LRU Cache. It defines the 'value' structure of each register entry
function __in... | # Udacity Data Structures and Algorithms
# Part 2 - Data Structures
# Project 2 - Problem #1 - LRU Cache
# Script Params
MAX_CAPACITY = 1024
DEFAULT_CAPACITY = 64
class MAP_Node:
"""
Helper class for LRU Cache.
It defines the 'value' structure of each register entry
"""
def __init__(self, va... | Python | zaydzuhri_stack_edu_python |
function hotel_filling sorted_rooms clients hotel rooms sing two half lux
begin
set first_date_in = date_in
set last_date_in = date_in
set main_date = split date_in string . at 1 + string . + split date_in string . at 2
for day in range integer split first_date_in string . at 0 integer split last_date_in string . at 0 ... | def hotel_filling(sorted_rooms, clients, hotel, rooms, sing, two, half, lux):
first_date_in = clients[0].date_in
last_date_in = clients[len(clients)-1].date_in
main_date = clients[0].date_in.split('.')[1] + '.' + clients[0].date_in.split('.')[2]
for day in range(int(first_date_in.split('.')[0]), int(las... | Python | nomic_cornstack_python_v1 |
comment x = int(input("Podaj swoją prędkość (km/h): "))
comment #SCENARIUSZ 1
comment # if x >50:
comment # print("Twoja prędkość jest nieprawidłowa")
comment # else:
comment # print("Twoja prędkość jest prawidłowa")
comment #SCENARIUSZ 2
comment if x >50:
comment print("Twoja prędkość jest nieprawidłowa")
comment elif... | # x = int(input("Podaj swoją prędkość (km/h): "))
# #SCENARIUSZ 1
# # if x >50:
# # print("Twoja prędkość jest nieprawidłowa")
# # else:
# # print("Twoja prędkość jest prawidłowa")
# #SCENARIUSZ 2
# if x >50:
# print("Twoja prędkość jest nieprawidłowa")
# elif x == 50:
# print("Twoja prędkość jest aks... | Python | zaydzuhri_stack_edu_python |
string This is a command line tool to run tests using the organization ideological population dynamics model. The variables that should be controllable with this testing tool are: 1. num epochs 2. initial org size, configuration 3. hiring pool size, configuration 4. num candidates during hiring 5. TOPP probability dist... | '''
This is a command line tool to run tests using the organization ideological population dynamics model.
The variables that should be controllable with this testing tool are:
1. num epochs
2. initial org size, configuration
3. hiring pool size, configuration
4. num candidates during hiring
5.... | Python | zaydzuhri_stack_edu_python |
comment print("Programa para digitar 3 numeros e somar")
comment n1 = int(input("Digite um numero:"))
comment n2 = int(input("Digite outro numero:"))
comment n3 = int(input("Digite e mais outro numero:"))
comment soma = n1 + n2 + n3
comment print("A soma dos numeros é:", soma)
print string Programa para digitar 3 numer... | # print("Programa para digitar 3 numeros e somar")
# n1 = int(input("Digite um numero:"))
# n2 = int(input("Digite outro numero:"))
# n3 = int(input("Digite e mais outro numero:"))
# soma = n1 + n2 + n3
# print("A soma dos numeros é:", soma)
print("Programa para digitar 3 numeros e somar")
i = 1
soma = 0
while i <= 3... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
return call _str_indented
end function | def __str__(self) -> str:
return self._str_indented() | Python | nomic_cornstack_python_v1 |
function __getPointXYs self raw_string
begin
try
begin
set pointsRE = compile string ^\((\d*\D*, *\D*\d*)\)\D*\((\d*\D*, *\D*\d*)\)$
set points = call groups
set startPoint = tuple integer strip split points at 0 string , at 0 integer strip split points at 0 string , at 1
set endPoint = tuple integer strip split points... | def __getPointXYs(self, raw_string):
try:
pointsRE = re.compile('^\((\d*\D*, *\D*\d*)\)\D*\((\d*\D*, *\D*\d*)\)$')
points = pointsRE.search(raw_string.strip()).groups()
startPoint = (int(points[0].split(',')[0].strip()), int(points[0].split(',')[1].strip()))
endPo... | Python | nomic_cornstack_python_v1 |
function view_amenity amenity_id=none
begin
if amenity_id is none
begin
set all_amenities = list comprehension to json state for state in values all string Amenity
return call jsonify all_amenities
end
set s = get storage string Amenity amenity_id
if s is none
begin
call abort 404
end
return call jsonify to json s
end ... | def view_amenity(amenity_id=None):
if amenity_id is None:
all_amenities = [state.to_json() for state
in storage.all("Amenity").values()]
return jsonify(all_amenities)
s = storage.get("Amenity", amenity_id)
if s is None:
abort(404)
return jsonify(s.to_json... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Nov 12 15:24:45 2019 @author: pentela.srikrishna
function div a b
begin
return a / b
end function
try
begin
set c = call div 5 0
end
except any
begin
print string b can't be 0
end | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 15:24:45 2019
@author: pentela.srikrishna
"""
def div(a,b):
return a/b
try:
c=div(5,0)
except:
print("b can't be 0") | Python | zaydzuhri_stack_edu_python |
function top_k_rows matrix k
begin
comment Calculate the sum of absolute differences for each row
set diffs = list
for row in matrix
begin
set row_diff = 0
for i in range length row - 1
begin
if row at i is not none and row at i + 1 is not none
begin
set row_diff = row_diff + absolute row at i - row at i + 1
end
end
a... | def top_k_rows(matrix, k):
# Calculate the sum of absolute differences for each row
diffs = []
for row in matrix:
row_diff = 0
for i in range(len(row) - 1):
if row[i] is not None and row[i + 1] is not None:
row_diff += abs(row[i] - row[i + 1])
diffs.append... | Python | greatdarklord_python_dataset |
for c in range 0 6
begin
set inpt = integer input string Insira um numero:
if inpt % 2 == 0
begin
set soma = soma + inpt
end
end
print format string Soma dos numeros pares: {} soma | for c in range(0, 6):
inpt = int(input('Insira um numero: '))
if(inpt % 2 == 0):
soma += inpt
print('Soma dos numeros pares: {}'.format(soma)) | Python | zaydzuhri_stack_edu_python |
import tkinter as tk
from tkinter import font as tkfont
import person_group
class SampleApp extends Tk
begin
function __init__ self *args **kwargs
begin
call __init__ self *args keyword kwargs
set title_font = call Font family=string Helvetica size=18 weight=string bold slant=string italic
set container = call Frame se... | import tkinter as tk
from tkinter import font as tkfont
import person_group
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
container = tk.Frame(self)
cont... | Python | zaydzuhri_stack_edu_python |
function __init__ self table
begin
call __init__ self table
end function | def __init__(self, table):
SudoKiller.__init__(self, table) | Python | nomic_cornstack_python_v1 |
function TwoSum_HashTable lst target
begin
print target
set hashTable = dictionary
for x in lst
begin
set hashTable at x = true
end
for x in lst
begin
set y = target - x
if y in hashTable and x != y
begin
return tuple x y
end
end
return none
end function
function sum_2 lst total
begin
print total
set s = set lst
set te... | def TwoSum_HashTable(lst, target):
print(target)
hashTable = dict()
for x in lst:
hashTable[x] = True
for x in lst:
y = target-x
if y in hashTable and x != y:
return (x, y)
return None
def sum_2(lst, total):
print(tota... | Python | zaydzuhri_stack_edu_python |
function start_pinging self
begin
string Start sending periodic pings to keep the connection alive
assert ping_interval is not none
if ping_interval > 0
begin
set last_ping = time
set last_pong = time
set ping_callback = call PeriodicCallback periodic_ping ping_interval * 1000
start ping_callback
end
end function | def start_pinging(self) -> None:
"""Start sending periodic pings to keep the connection alive"""
assert self.ping_interval is not None
if self.ping_interval > 0:
self.last_ping = self.last_pong = IOLoop.current().time()
self.ping_callback = PeriodicCallback(
... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
from functools import reduce
string def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] def fn(x, y): return x * 10 + y L = map(char2num, '1') print(L) print(map(char2num, '13579')) print(reduce(fn,map(char2num, '2897475286489347'))) ... | # -*- coding: utf-8 -*-
from functools import reduce
'''
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def fn(x, y):
return x * 10 + y
L = map(char2num, '1')
print(L)
print(map(char2num, '13579'))
print(reduce(fn,map(char2num, '289747... | Python | zaydzuhri_stack_edu_python |
set words = string I love coding
for word in split words
begin
print word
end | words = "I love coding"
for word in words.split():
print(word)
| Python | flytech_python_25k |
function read_message_link request room_id message_id
begin
if method == string GET
begin
set message = read DB string dm_messages dict string id message_id ; string room_id room_id
return call Response data=message status=HTTP_200_OK
end
else
begin
return call JsonResponse dict string message string The message does n... | def read_message_link(request, room_id, message_id):
if request.method == 'GET':
message = DB.read("dm_messages", {"id": message_id, "room_id": room_id})
return Response(data=message, status=status.HTTP_200_OK)
else:
return JsonResponse({'message': 'The message does not exist'}, status=... | Python | nomic_cornstack_python_v1 |
import numpy
import scipy.special
class perceptron
begin
comment 初始化函数
function __init__ self inputnodes outputnodes learningrate
begin
comment 内容的初始化
set input_nodes = inputnodes
set output_nodes = outputnodes
comment 学习率
set learning_rate = learningrate
comment 权重,制作一个大小为输入结点*输出结点的权重大小矩阵
set wio = call normal 0.0 pow... | import numpy
import scipy.special
class perceptron:
# 初始化函数
def __init__(self, inputnodes, outputnodes, learningrate):
# 内容的初始化
self.input_nodes = inputnodes
self.output_nodes = outputnodes
# 学习率
self.learning_rate = learningrate
# 权重,制作一个大小为输入结点*输出结点的... | Python | zaydzuhri_stack_edu_python |
function test_set_timeout init_process_group_mock
begin
set test_timedelta = time delta seconds=30
set strategy = call FSDPStrategy timeout=test_timedelta parallel_devices=list device string cpu
set cluster_environment = call LightningEnvironment
set accelerator = call Mock
call setup_environment
set process_group_back... | def test_set_timeout(init_process_group_mock):
test_timedelta = timedelta(seconds=30)
strategy = FSDPStrategy(timeout=test_timedelta, parallel_devices=[torch.device("cpu")])
strategy.cluster_environment = LightningEnvironment()
strategy.accelerator = Mock()
strategy.setup_environment()
process_g... | Python | nomic_cornstack_python_v1 |
function __init__ self env width=84 height=84
begin
call __init__ env
set width = width
set height = height
set observation_space = call Box low=0 high=255 shape=tuple height width 1 dtype=dtype
end function | def __init__(self, env, width=84, height=84):
super().__init__(env)
self.width = width
self.height = height
self.observation_space = gym.spaces.Box(low=0, high=255,
shape=(self.height, self.width, 1),
... | Python | nomic_cornstack_python_v1 |
import re
comment Day 8 assignment 1
function num_chars
begin
set f = open string inputs/inputd81.txt string r
set amount = 0
for line in f
begin
set line = strip line
set amount = amount + length line - length eval line
end
return amount
end function
comment Day 8 assignment 2
function num_chars2
begin
set f = open st... | import re
#Day 8 assignment 1
def num_chars():
f = open('inputs/inputd81.txt', 'r')
amount = 0
for line in f:
line = line.strip()
amount += len(line) - len(eval(line))
return amount
#Day 8 assignment 2
def num_chars2():
f = open('inputs/inputd81.txt', 'r')
amount = 0
for line in f:
line = line.strip()
... | Python | zaydzuhri_stack_edu_python |
import sys
from itertools import permutations
set answer = 9999999
set input1 = input
set input1 = split input1 string
set N = integer input1 at 0
set M = integer input1 at 1
set K = integer input1 at 2
comment print(N,M,K)
set input2 = input
set input2 = split input2 string
set weight_list = list
for i in range lengt... | import sys
from itertools import permutations
answer = 9999999
input1 = input()
input1 = input1.split(" ")
N = int(input1[0])
M = int(input1[1])
K = int(input1[2])
# print(N,M,K)
input2 = input()
input2 = input2.split(" ")
weight_list = []
for i in range(len(input2)):
weight_list.append(int(input2[i]))
# print(... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string numpy_arrays.py - numpy array sample for python training at www.jasaplus.com
import numpy as np
set lis = list 1 2 3
set a = array lis
print a
print string = * 20
set tup = tuple 3 6 9
set a = array tup
print a
print string = * 20
set a = array list list 0 1 2 list 3 4 5 list 6 7 8
p... | #!/usr/bin/env python
'''
numpy_arrays.py - numpy array sample
for python training at www.jasaplus.com
'''
import numpy as np
lis = [1,2,3]
a = np.array(lis)
print(a)
print("=" * 20)
tup = (3, 6, 9)
a = np.array(tup)
print(a)
print("=" * 20)
a = np.array( [[0,1,2], [3,4,5], [6,7,8]])
print(a)
| Python | zaydzuhri_stack_edu_python |
function tags self
begin
return get pulumi self string tags
end function | def tags(self) -> Sequence[str]:
return pulumi.get(self, "tags") | Python | nomic_cornstack_python_v1 |
string SSD1309 demo (images).
from time import sleep
from machine import Pin , SPI
from ssd1309 import Display
function test
begin
string Test code. Andy Pico
set spi = call SPI 0 baudrate=1000000 sck=call Pin 18 mosi=call Pin 19
set display = call Display spi dc=call Pin 17 cs=call Pin 16 rst=call Pin 20 width=132
cal... | """SSD1309 demo (images)."""
from time import sleep
from machine import Pin, SPI
from ssd1309 import Display
def test():
"""Test code. Andy Pico"""
spi = SPI(0, baudrate=1000000, sck=Pin(18), mosi=Pin(19))
display = Display(spi, dc=Pin(17), cs=Pin(16), rst=Pin(20), width=132)
display.clear_buffers()
... | Python | zaydzuhri_stack_edu_python |
function at_least_21 given_date
begin
set today = today
return today - call relativedelta years=21 >= given_date
end function | def at_least_21(given_date):
today = date.today()
return today - relativedelta(years=21) >= given_date | Python | nomic_cornstack_python_v1 |
function withdraw
begin
set total_bal = 10000
set amount = integer input string Enter the amount you want to withdraw :
if amount > total_bal
begin
print string Insufficient balance
end
else
begin
set total_bal = total_bal - amount
print string Remaining Balance is total_bal
end
end function
function bal_enquiry
begin
... | def withdraw():
total_bal = 10000
amount = int(input("Enter the amount you want to withdraw : "))
if amount > total_bal:
print("Insufficient balance")
else:
total_bal = total_bal - amount
print("Remaining Balance is",total_bal)
def bal_enquiry():
pass
# withdraw... | Python | zaydzuhri_stack_edu_python |
function main
begin
set parser = call ArgumentParser
call add_argument string -i string --input dest=string input required=true help=string Output file from mutalyzer
call add_argument string -f string --fasta dest=string fasta_file required=true help=string FASTA file
call add_argument string -o string --out dest=stri... | def main():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input",
dest='input',
required=True,
help="Output file from mutalyzer")
parser.add_argument("-f", "--fasta",
dest='fasta_file',
... | Python | nomic_cornstack_python_v1 |
function get_builtin_date date date_format=string %Y-%m-%dT%H:%M:%S raise_exception=false
begin
string Try to convert a date to a builtin instance of ``datetime.datetime``. The input date can be a ``str``, a ``datetime.datetime``, a ``xmlrpc.client.Datetime`` or a ``xmlrpclib.Datetime`` instance. The returned object is... | def get_builtin_date(date, date_format="%Y-%m-%dT%H:%M:%S", raise_exception=False):
"""
Try to convert a date to a builtin instance of ``datetime.datetime``.
The input date can be a ``str``, a ``datetime.datetime``, a ``xmlrpc.client.Datetime`` or a ``xmlrpclib.Datetime``
instance. The returned object i... | Python | jtatman_500k |
function get_impl_vol self
begin
set ITERATIONS = 100
set ACCURACY = 0.05
set low_vol = 0
set high_vol = 1
comment It will try mid point and then choose new interval
set vol = 0.5
call get_price_delta
for i in range ITERATIONS
begin
if calc_price > price + ACCURACY
begin
set high_vol = vol
end
else
if calc_price < pric... | def get_impl_vol(self):
ITERATIONS = 100
ACCURACY = 0.05
low_vol = 0
high_vol = 1
self.vol = 0.5 ## It will try mid point and then choose new interval
self.get_price_delta()
for i in range(ITERATIONS):
if self.calc_price > self.price + ACCURACY:
... | Python | nomic_cornstack_python_v1 |
import networkx as nx
import pickle
import glob
import numpy as np
from bulid_models import Logist_Reg_K_Fold
from bulid_models import NN_K_Fold
from bulid_models import Random_Forest_K_Fold
from bulid_models import CNN_K_Fold
string This function creates feature vector using the word list
function create_vector doc wo... | import networkx as nx
import pickle
import glob
import numpy as np
from bulid_models import Logist_Reg_K_Fold
from bulid_models import NN_K_Fold
from bulid_models import Random_Forest_K_Fold
from bulid_models import CNN_K_Fold
''' This function creates feature vector using the word list'''
def create_vector(doc,word_li... | Python | zaydzuhri_stack_edu_python |
function qint4 scale
begin
return call create_quantized_dtype _builtin_quant_dtypes at string qint4 scale none
end function | def qint4(scale):
return create_quantized_dtype(_builtin_quant_dtypes["qint4"], scale, None) | Python | nomic_cornstack_python_v1 |
function transfer self address amount priority=NORMAL payment_id=none unlock_time=0 relay=true
begin
string Sends a transfer. Returns a list of resulting transactions. :param address: destination :class:`Address <monero.address.Address>` or subtype :param amount: amount to send :param priority: transaction priority, im... | def transfer(self, address, amount,
priority=prio.NORMAL, payment_id=None, unlock_time=0,
relay=True):
"""
Sends a transfer. Returns a list of resulting transactions.
:param address: destination :class:`Address <monero.address.Address>` or subtype
:param amount: ... | Python | jtatman_500k |
from nose.tools import *
from ex48 import parser
comment word_list = [('stop', 'of'), ('verb', 'go'), ('noun', 'princess'), ('verb', 'am'), ('direction', 'left'), ('verb', 'do'), ('noun', 'dog'), ('stop', 'the'), ]
function test_peek
begin
set word_list = list tuple string stop string of tuple string verb string go
cal... | from nose.tools import *
from ex48 import parser
# word_list = [('stop', 'of'), ('verb', 'go'), ('noun', 'princess'), ('verb', 'am'), ('direction', 'left'), ('verb', 'do'), ('noun', 'dog'), ('stop', 'the'), ]
def test_peek():
word_list = [('stop', 'of'), ('verb', 'go')]
assert_equal(parser.peek(word_list), ... | 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.