code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function multi_raw query params models model_to_fields
begin
string Scoop multiple model instances out of the DB at once, given a query that returns all fields of each. Return an iterable of sequences of model instances parallel to the ``models`` sequence of classes. For example:: [(<User such-and-such>, <Watch such-an... | def multi_raw(query, params, models, model_to_fields):
"""Scoop multiple model instances out of the DB at once, given a query that
returns all fields of each.
Return an iterable of sequences of model instances parallel to the
``models`` sequence of classes. For example::
[(<User such-and-such>... | Python | jtatman_500k |
function computeActionFromValues self state
begin
string *** YOUR CODE HERE ***
set bestAction = none
set best = - decimal string inf
for action in call getPossibleActions state
begin
set Qvalue = call computeQValueFromValues state action
if Qvalue > best
begin
set best = Qvalue
set bestAction = action
end
end
return b... | def computeActionFromValues(self, state):
"*** YOUR CODE HERE ***"
bestAction=None
best=-float('inf')
for action in self.mdp.getPossibleActions(state):
Qvalue=self.computeQValueFromValues(state, action)
if Qvalue>best:
best=Qvalue
... | Python | nomic_cornstack_python_v1 |
function rd obj default_value=0
begin
set hints = get get attribute obj string hints dict string fields list
if length hints > 1
begin
set msg = string Your object { obj } ( { name } . { get attribute obj string dotted_name string } ) has { length hints } items hinted ( { hints } ). We do not know how to pick out a sin... | def rd(obj, *, default_value=0):
hints = getattr(obj, 'hints', {}).get("fields", [])
if len(hints) > 1:
msg = (
f"Your object {obj} ({obj.name}.{getattr(obj, 'dotted_name', '')}) "
f"has {len(hints)} items hinted ({hints}). We do not know how to "
"pick out a single ... | Python | nomic_cornstack_python_v1 |
import sys
import numpy as np
from sklearn.externals import joblib
from Caracteristiques.executables.exe_extracteur import *
import Trainer as Trainer
function selecter values select_stat
begin
string Garde uniquement les indices dans la liste values ou la valeur pour le meme indice dans select_stat est 1 exemple: [10,... | import sys
import numpy as np
from sklearn.externals import joblib
from Caracteristiques.executables.exe_extracteur import *
import Trainer as Trainer
def selecter(values,select_stat):
"""
Garde uniquement les indices dans la liste values ou la valeur pour le meme indice dans select_stat est 1
exemple:
... | Python | zaydzuhri_stack_edu_python |
function copyTiePointGrids sourceProduct targetProduct
begin
call ProductUtils_copyTiePointGrids _obj _obj
return
end function | def copyTiePointGrids(sourceProduct, targetProduct):
ProductUtils_copyTiePointGrids(sourceProduct._obj, targetProduct._obj)
return | Python | nomic_cornstack_python_v1 |
string sort iterables
from utils import title
decorator title
function sort_example
begin
string .sort() alters the object
set v = list 3 1 4 1 5
print v
sort v
print v
sort v reverse=true
print v
end function
decorator title
function sort_by_key
begin
string sort by keys
set v = list list string a 1 2 list string b 2 ... | """ sort iterables """
from utils import title
@title
def sort_example():
""" .sort() alters the object """
v = [3, 1, 4, 1, 5]
print(v)
v.sort()
print(v)
v.sort(reverse=True)
print(v)
@title
def sort_by_key():
""" sort by keys """
v = [['a', 1, 2],
... | Python | zaydzuhri_stack_edu_python |
function sort li
begin
for i in range 8
begin
set minpos = i
for j in range i 9
begin
if li at j < li at minpos
begin
set minpos = j
end
end
set temp = li at i
set li at i = li at minpos
set li at minpos = temp
print li
end
end function
set li = list 1 5 9 2 3 6 8 4 7
set l = length li
sort li
print li | def sort(li):
for i in range(8):
minpos = i
for j in range(i, 9):
if li[j] < li[minpos]:
minpos = j
temp = li[i]
li[i] = li[minpos]
li[minpos] = temp
print(li)
li = [1, 5, 9, 2, 3, 6, 8, 4, 7]
l = len(li)
sort(li)
print(li)
| Python | zaydzuhri_stack_edu_python |
function longest_substring string
begin
comment Stores the last occurrence of each character
set last_occurrence = dict
set result = list 0 1
set start_index = 0
for tuple i char in enumerate string
begin
if char in last_occurrence
begin
set start_index = max start_index last_occurrence at char + 1
end
comment We can ... | def longest_substring(string):
# Stores the last occurrence of each character
last_occurrence = {}
result = [0, 1]
start_index = 0
for i, char in enumerate(string):
if char in last_occurrence:
start_index = max(start_index, last_occurrence[char] + 1)
# We can use result to store... | Python | flytech_python_25k |
from graph_utils import *
from scipy.linalg import fractional_matrix_power
import torch
comment polinomiale di chebyshev
function T k x
begin
if k == 0
begin
return 1
end
else
if k == 1
begin
return x
end
else
if k > 1
begin
return 2 * x * t dist k - 1 x - t dist k - 2 x
end
else
begin
return - 1
end
end function
funct... | from graph_utils import *
from scipy.linalg import fractional_matrix_power
import torch
#polinomiale di chebyshev
def T(k, x):
if k == 0:
return 1
elif k == 1:
return x
elif k > 1:
return 2 * x * T(k - 1, x) - T(k - 2, x)
else:
return -1
def k_hop_neighbors(G, node, k)... | Python | zaydzuhri_stack_edu_python |
comment importing the libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
comment loading the dataset
set df = read csv string... | #importing the libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
#loading the dataset
df = pd.read_csv('wine_data.csv')
#d... | Python | jtatman_500k |
from flask import Flask
set app = call Flask __name__
decorator call route string /
function index
begin
return string Hello, world!
end function
decorator call route string /david
function david
begin
return string Hello, David!
end function
decorator call route string /prasham
function prasham
begin
return string Hel... | from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, world!"
@app.route("/david")
def david():
return "Hello, David!"
@app.route("/prasham")
def prasham():
return "Hello Prasham"
print("Hello Prasham")
@app.route("/bhuta")
def bhuta():
return "Bhuta, Hi!"
... | Python | zaydzuhri_stack_edu_python |
function remove filePath
begin
set files = glob glob filePath
for f in files
begin
remove os f
end
end function | def remove(filePath):
files = glob.glob(filePath)
for f in files:
os.remove(f) | Python | nomic_cornstack_python_v1 |
function __init__ self n_actions
begin
set n_actions = n_actions
set sess = call Session
comment Generate initialized weights once.
set init = call variance_scaling_initializer seed=1234
set inits = run list call init list 8 8 3 16 call init list 4 4 16 32 call init list 17280 256 call init list 256 n_actions
comment W... | def __init__(self, n_actions):
self.n_actions = n_actions
self.sess = tf.Session()
# Generate initialized weights once.
init = tf.contrib.layers.variance_scaling_initializer(seed=1234)
self.inits = self.sess.run([
init([8, 8, 3, 16]),
init([4, 4, 16, 32])... | Python | nomic_cornstack_python_v1 |
function __ge__ self other
begin
if not is instance other OrderedDict
begin
raise call TypeError string Can only compare with other OrderedDicts
end
comment FIXME: efficiency?
comment Generate both item lists for each compare
return items self >= items other
end function | def __ge__(self, other):
if not isinstance(other, OrderedDict):
raise TypeError('Can only compare with other OrderedDicts')
# FIXME: efficiency?
# Generate both item lists for each compare
return (self.items() >= other.items()) | Python | nomic_cornstack_python_v1 |
function depend self task
begin
if type task == str
begin
set task_obj = call get_task task
if task_obj is none
begin
raise call KeyError format string unknown project "{}" task
end
else
begin
set task = task_obj
end
end
else
if _context
begin
call set_context _context
end
append __dependencies task
return self
end fun... | def depend(self, task):
if type(task) == str:
task_obj = TaskManager().get_task(task)
if task_obj is None:
raise KeyError("unknown project \"{}\"".format(task))
else:
task = task_obj
else:
if self._context:
t... | Python | nomic_cornstack_python_v1 |
function mesh_conway_meta mesh
begin
return call mesh_conway_kis call mesh_conway_join mesh
end function | def mesh_conway_meta(mesh):
return mesh_conway_kis(mesh_conway_join(mesh)) | Python | nomic_cornstack_python_v1 |
function _homography self image
begin
comment get matching points
set tuple kp1 des1 = call detectAndCompute image none
set tuple kp2 des2 = call detectAndCompute template none
set bf = call BFMatcher
set matches = call knnMatch des1 des2 k=2
set good = list
comment prune the matching
for tuple m n in matches
begin
if... | def _homography(self, image):
# get matching points
kp1, des1 = sift.detectAndCompute(image, None)
kp2, des2 = sift.detectAndCompute(self.template, None)
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)
good = []
# prune the matching
for m,n in matches:
if m.distance < 0.5 * n.distance:
... | Python | nomic_cornstack_python_v1 |
function move self movement
begin
set tuple leftWheel rightWheel rampUp = movement
comment place the appropriate commands on each controllerQ
clear synchronizer
put tuple leftWheel rampUp
put tuple - rightWheel rampUp
set
return
end function | def move(self, movement):
leftWheel, rightWheel, rampUp = movement
# place the appropriate commands on each controllerQ
synchronizer.clear()
self.leftQ.put((leftWheel, rampUp))
self.rightQ.put((-(rightWheel), rampUp))
synchronizer.set()
return | Python | nomic_cornstack_python_v1 |
set i = 2
set total = 0
while i < 100
begin
set is_prime = true
for j in range 2 i
begin
if i % j == 0
begin
set is_prime = false
break
end
end
if is_prime
begin
print i
set total = total + i
end
set i = i + 1
end
print string Sum of prime numbers: total | i = 2
total = 0
while i < 100:
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime:
print(i)
total += i
i += 1
print("Sum of prime numbers:", total)
| Python | greatdarklord_python_dataset |
function configureApache
begin
set platformConfig = string <VirtualHost *:80> ServerAdmin nasko.js@gmail.com ErrorLog ${APACHE_LOG_DIR}/SmowWeb_error.log CustomLog ${APACHE_LOG_DIR}/SmoWeb_access.log combined LogLevel info ServerName platform.sysmoltd.com ServerAlias platform.sysmoltd.com WSGIScriptAlias / /srv/SmoWeb/... | def configureApache():
platformConfig="""
<VirtualHost *:80>
ServerAdmin nasko.js@gmail.com
ErrorLog ${APACHE_LOG_DIR}/SmowWeb_error.log
CustomLog ${APACHE_LOG_DIR}/SmoWeb_access.log combined
LogLevel info
ServerName platform.sysmoltd.com
ServerAlias platform.sysmoltd.com
WSGIScriptAlias / /srv/SmoWeb/Platform... | Python | nomic_cornstack_python_v1 |
function rgb hex_code
begin
set hex_code = call separate_hex hex_code
set result = dict string r 0 ; string g 0 ; string b 0
for tuple i color in enumerate result
begin
set result at color = integer hex_code at i 16
end
return result
end function
function separate_hex hex_code
begin
string This splits the hex code into... | def rgb(hex_code: str):
hex_code = separate_hex(hex_code)
result = {
'r': 0,
'g': 0,
'b': 0,
}
for i, color in enumerate(result):
result[color] = int(hex_code[i], 16)
return result
def separate_hex(hex_code):
"""This splits the hex code into a list of r, g, b"... | Python | zaydzuhri_stack_edu_python |
function cache_keys self
begin
return iterate keys _cache
end function | def cache_keys(self):
return iter(self._cache.keys()) | Python | nomic_cornstack_python_v1 |
from numpy import *
import matplotlib.pyplot as plt
comment 加载文件,读取数据
function load_data fileName
begin
set dataMat = list
set labelMat = list
set file = open fileName
for line in read lines file
begin
set lineArr = split strip line
append dataMat list 1.0 decimal lineArr at 0 decimal lineArr at 1
append labelMat dec... | from numpy import *
import matplotlib.pyplot as plt
# 加载文件,读取数据
def load_data(fileName):
dataMat = []
labelMat = []
file = open(fileName)
for line in file.readlines():
lineArr = line.strip().split()
dataMat.append([1.0,float(lineArr[0]), float(lineArr[1])])
labelMat.append(float... | Python | zaydzuhri_stack_edu_python |
function get cls name label=none fmt=string {}_%Y-%m-%d_%H%M%S.log
begin
if name not in keys loggers
begin
set loggers at name = call cls name label=label fmt=fmt
end
return loggers at name
end function | def get(cls, name, label=None, fmt="{}_%Y-%m-%d_%H%M%S.log"):
if name not in cls.loggers.keys():
cls.loggers[name] = cls(name, label=label, fmt=fmt)
return cls.loggers[name] | Python | nomic_cornstack_python_v1 |
function k_unit self
begin
set v = array list 0.0 0.0 1.0
return v
end function | def k_unit(self):
v = np.array([0.0, 0.0, 1.0])
return v | Python | nomic_cornstack_python_v1 |
function get_inbound_topics self
begin
return inbound_topics
end function | def get_inbound_topics(self):
return self.inbound_topics | Python | nomic_cornstack_python_v1 |
function act self obs info debug_imgs=false goal=none
begin
set act = dict string camera_config camera_config ; string primitive none
if not obs
begin
return act
end
comment Get heightmap from RGB-D images.
set tuple colormap heightmap = call get_heightmap obs camera_config
if goal is not none
begin
set tuple colormap_... | def act(self, obs, info, debug_imgs=False, goal=None):
act = {'camera_config': self.camera_config, 'primitive': None}
if not obs:
return act
# Get heightmap from RGB-D images.
colormap, heightmap = self.get_heightmap(obs, self.camera_config)
if goal is not None:
... | Python | nomic_cornstack_python_v1 |
function dev n
begin
return integer n / 2
end function
set N = integer input
set li = list map int split input
set flag = true
set an = 0
while true
begin
for i in range N
begin
if li at i % 2 != 0
begin
set flag = false
end
end
if flag
begin
set li = list map dev li
set an = an + 1
end
else
begin
break
end
end
print a... | def dev(n):
return int(n / 2)
N = int(input())
li = list(map(int, input().split()))
flag = True
an = 0
while True:
for i in range(N):
if li[i] % 2 != 0:
flag = False
if flag:
li = list(map(dev, li))
an += 1
else:
break
print(an) | Python | zaydzuhri_stack_edu_python |
function get_instantiation self class_name
begin
set contexts = call _get_context_all class_name
set analyzer = call InstantiationAnalyzer class_name
for i in range 1 length contexts
begin
set code = contexts at i at 0
parse analyzer code
end
return d
end function | def get_instantiation(self, class_name):
contexts = self._get_context_all(class_name)
analyzer = InstantiationAnalyzer(class_name)
for i in range(1, len(contexts)):
code = contexts[i][0]
analyzer.parse(code)
return analyzer.d | Python | nomic_cornstack_python_v1 |
function set_logger args
begin
call cleanup
set stderr = call StreamHandler
if debug
begin
set screen_format = SCREEN_FORMAT
end
else
begin
set screen_format = SCREEN_FORMAT_QUIET
end
set screen_format = call Formatter screen_format datefmt=SMALL_TIMESTAMP
call setFormatter screen_format
set log_file = call RotatingFil... | def set_logger(args):
cleanup()
stderr = logging.StreamHandler()
if args.debug:
screen_format = SCREEN_FORMAT
else:
screen_format = SCREEN_FORMAT_QUIET
screen_format = logging.Formatter(screen_format, datefmt=SMALL_TIMESTAMP)
stderr.setFormatter(screen_format)
log_f... | Python | nomic_cornstack_python_v1 |
function loopcount self
begin
return length loopindices
end function | def loopcount(self):
return len(self.loopindices) | Python | nomic_cornstack_python_v1 |
function Beersong start
begin
for i in range start 0 - 1
begin
print i string bottels of beer on the wall, i string bottles of beer. Take one down, pass it arround i - 1 string bottles of bear on the wall!
end
end function
function main
begin
print string start us off!
set start = integer input
call Beersong start
end ... | def Beersong(start):
for i in range(start, 0, -1):
print(i,"bottels of beer on the wall,", i, "bottles of beer.\nTake one down, pass it arround", (i-1), "bottles of bear on the wall!")
def main():
print("start us off!")
start = int(input())
Beersong(start)
main()
| Python | zaydzuhri_stack_edu_python |
from tests.helpers import login_demo , create_item_demo , update_item_demo
function test_get_item_by_id init_client init_db
begin
string Test getting an item by its id in different scenarios.
set test_id = 1
set resp = get init_client string /items/ { test_id }
assert status_code == 200
assert call get_json at string n... | from tests.helpers import login_demo, create_item_demo, update_item_demo
def test_get_item_by_id(init_client, init_db):
"""Test getting an item by its id in different scenarios."""
test_id = 1
resp = init_client.get(f'/items/{test_id}')
assert resp.status_code == 200
assert resp.get_json()['name']... | Python | zaydzuhri_stack_edu_python |
function removeOuterParentheses S
begin
string :type S: str :rtype: str
set res = string
set ans = string
set cur_stacks = list
for i in range length S
begin
set ans = ans + S at i
if S at i == string (
begin
append cur_stacks string (
end
else
begin
pop cur_stacks
if cur_stacks == list
begin
set res = res + ans at... | def removeOuterParentheses(S):
"""
:type S: str
:rtype: str
"""
res = ""
ans = ""
cur_stacks = []
for i in range(len(S)):
ans += S[i]
if S[i] == "(":
cur_stacks.append('(')
else:
cur_stacks.pop()
if cur_stacks == []:
... | Python | zaydzuhri_stack_edu_python |
function save self session=none
begin
set change_fields = call _get_changed_persistent_fields
call update_from db_model id change_fields session=session
call obj_reset_changes
end function | def save(self, session=None):
change_fields = self._get_changed_persistent_fields()
self.db_repo.update_from(self.db_model, self.id,
change_fields, session=session)
self.obj_reset_changes() | Python | nomic_cornstack_python_v1 |
import tkinter as tk
from tkinter import *
import pymysql
comment Connect to the database
set conn = call connect host=string localhost user=string username password=string password db=string database_name
set cursor = call cursor
comment Create the main window
set root = call Tk
comment Add a title
title root string S... | import tkinter as tk
from tkinter import *
import pymysql
# Connect to the database
conn = pymysql.connect(host="localhost", user="username", password="password", db="database_name")
cursor = conn.cursor()
# Create the main window
root = tk.Tk()
# Add a title
root.title("Student Records")
# Add a label
label = Labe... | Python | flytech_python_25k |
function column_definition table_name col_name
begin
string Get the source of a column function. If a column is a registered Series and not a function then all that is returned is {'type': 'series'}. If the column is a registered function then the JSON returned has keys "type", "filename", "lineno", "text", and "html".... | def column_definition(table_name, col_name):
"""
Get the source of a column function.
If a column is a registered Series and not a function then all that is
returned is {'type': 'series'}.
If the column is a registered function then the JSON returned has keys
"type", "filename", "lineno", "tex... | Python | jtatman_500k |
comment MoonTube (https://www.acmicpc.net/problem/15591)
string (TLE..) 모든 노드들이 연결되어 있는 상태 -> 그래프 처음 생각난 아이디어 : 인접 행렬을 통해 각 지역 간 최소 비용 값을 저장해 둔다. "플로이드 워셜 알고리즘"으로 접근하였는데 TLE 났다...
comment 1부터 N까지 번호가 붙여진 N (1 ≤ N ≤ 5,000)개의 동영상
comment N-1개의 동영상 쌍을 골라서 직접 두 쌍의 USADO를 계산
comment 존은 N-1개의 동영상 쌍을 골라서 어떤 동영상에서 다른 동영상으로 가는 ... | # MoonTube (https://www.acmicpc.net/problem/15591)
'''
(TLE..)
모든 노드들이 연결되어 있는 상태 -> 그래프
처음 생각난 아이디어 : 인접 행렬을 통해 각 지역 간 최소 비용 값을 저장해 둔다.
"플로이드 워셜 알고리즘"으로 접근하였는데 TLE 났다...
'''
# 1부터 N까지 번호가 붙여진 N (1 ≤ N ≤ 5,000)개의 동영상
# N-1개의 동영상 쌍을 골라서 직접 두 쌍의 USADO를 계산
# 존은 N-1개의 동영상 쌍을 골라서 어떤 동영상에서 ... | Python | zaydzuhri_stack_edu_python |
function genetic_algorithm points reference_point
begin
comment define the search space
set search_space = list comprehension random integer - 20 20 for _ in range length points
comment set the initial minimum distance
set min_distance = decimal string inf
comment execute the genetic algorithm
while true
begin
comment ... | def genetic_algorithm(points, reference_point):
# define the search space
search_space = [np.random.randint(-20, 20) for _ in range(len(points))]
# set the initial minimum distance
min_distance = float("inf")
# execute the genetic algorithm
while True:
# evaluate the search space
... | Python | jtatman_500k |
function saltvolume salt temp pres chkbnd=false useext=false
begin
call _chksalbnds salt temp pres chkbnd=chkbnd
comment Treat boundary case separately
if salt == 0
begin
set g1_p = call _sal_g_term 1 0 1 temp pres useext=useext
set v = g1_p
return v
end
set g_p = call sal_g 0 0 1 salt temp pres useext=useext
set vsal ... | def saltvolume(salt,temp,pres,chkbnd=False,useext=False):
_chksalbnds(salt,temp,pres,chkbnd=chkbnd)
# Treat boundary case separately
if salt == 0:
g1_p = _sal_g_term(1,0,1,temp,pres,useext=useext)
v = g1_p
return v
g_p = sal_g(0,0,1,salt,temp,pres,useext=useext)
vsal = g... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string hill -- a micro web framework
import threading
import re
import config
set ctx = call local
class Application extends object
begin
function __init__ self urlmapping
begin
set urlmapping = urlmapping
end function
function run self *middleware
begin
from paste import httpserver
set app = c... | #!/usr/bin/python
"""hill -- a micro web framework"""
import threading
import re
import config
ctx = threading.local()
class Application(object):
def __init__(self, urlmapping):
self.urlmapping = urlmapping
def run(self, *middleware):
from paste import httpserver
app = self.make_app(*... | Python | zaydzuhri_stack_edu_python |
function rot n x y rx ry
begin
if ry == 0
begin
if rx == 1
begin
set x = n - 1 - x
set y = n - 1 - y
end
set t = x
set x = y
set y = t
end
return tuple x y
end function | def rot(n, x, y, rx, ry):
if ry == 0:
if rx == 1:
x = (n-1) - x
y = (n-1) - y
t = x
x = y
y = t
return x, y | Python | nomic_cornstack_python_v1 |
function prepare_greem_tea self green_tea
begin
set hot_water = hot_water - hot_water
set ginger_syrup = ginger_syrup - ginger_syrup
set sugar_syrup = sugar_syrup - sugar_syrup
set green_mixture = green_mixture - green_mixture
if hot_water < 0
begin
print string Sorry, Green tea cannot be prepared beacause not enough w... | def prepare_greem_tea(self, green_tea):
hot_water = self.hot_water - green_tea.hot_water
ginger_syrup = self.ginger_syrup - green_tea.ginger_syrup
sugar_syrup = self.sugar_syrup - green_tea.sugar_syrup
green_mixture = self.green_mixture - green_tea.green_mixture
... | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup
import re
comment 原创申请URL
set url = string http://91.t9m.space/forumdisplay.php?fid=19
comment 获取url对应的soup
function getSoup url
begin
set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
set responses = get reques... | import requests
from bs4 import BeautifulSoup
import re
# 原创申请URL
url = "http://91.t9m.space/forumdisplay.php?fid=19"
# 获取url对应的soup
def getSoup(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'}
responses = requests.get(url, headers=headers)
... | Python | zaydzuhri_stack_edu_python |
function IsNum ci
begin
if ci >= ordinal string 0 and ci <= ordinal string 9
begin
return 1
end
return 0
end function
class Node
begin
function __init__ self freq dict
begin
set freq = freq
set dict = dict
end function
end class
set trie = list
append trie call Node 0 dict
set cttrie = 1
set ctgame = 0
while ctgame < ... | def IsNum(ci):
if (ci>=ord('0') and ci<=ord('9')):
return 1
return 0
class Node:
def __init__(self,freq,dict):
self.freq=freq
self.dict=dict
trie=[]
trie.append(Node(0,{}))
cttrie=1
ctgame=0
while (ctgame<gamelim):
s=rfile.readline()
if (len(s)==0):
break
if (s[0]=='1'):
ctply=... | Python | zaydzuhri_stack_edu_python |
function __init__ self data db_file=none root_directory=none name=string main_partition **kwargs
begin
debug string Initialisation of SQLite indexer.
set data = data
set metadata = dict
if root_directory is none
begin
set root_directory = call gettempdir
end
else
begin
set root_directory = root_directory
end
if db_fil... | def __init__(
self,
data,
db_file=None,
root_directory=None,
name="main_partition",
**kwargs
):
logger.debug("Initialisation of SQLite indexer.")
self.data = data
self.metadata = {}
if root_directory is None:
self.root_direc... | Python | nomic_cornstack_python_v1 |
set cars = list string toyota string mazda string demio
print cars
print cars at 1 | cars = ['toyota','mazda','demio']
print(cars)
print(cars[1]) | Python | zaydzuhri_stack_edu_python |
function solve
begin
import math
set R = integer input
print 2 * R * pi
end function
if __name__ == string __main__
begin
call solve
end | def solve():
import math
R = int(input())
print(2*R*math.pi)
if __name__ == "__main__":
solve() | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment Заполнить все поля в билете на самолет.
comment Создать функцию, принимающую параметры: ФИО, откуда, куда, дата вылета,
comment и заполняющую ими шаблон билета Skillbox Airline.
comment Шаблон взять в файле lesson_013/images/ticket_template.png
comment Пример заполнения lesson_013/... | # -*- coding: utf-8 -*-
# Заполнить все поля в билете на самолет.
# Создать функцию, принимающую параметры: ФИО, откуда, куда, дата вылета,
# и заполняющую ими шаблон билета Skillbox Airline.
# Шаблон взять в файле lesson_013/images/ticket_template.png
# Пример заполнения lesson_013/images/ticket_sample.png
# Подходя... | Python | zaydzuhri_stack_edu_python |
if cal == string +
begin
print call fi se
end
else
if cal == string -
begin
print call fi se
end
else
if cal == string *
begin
print call fi se
end
else
if cal == string /
begin
print string %.1f % call fi se
end | if cal == "+":
print((lambda x, y: x + y)(fi, se))
elif cal == "-":
print((lambda x, y : x-y)(fi,se))
elif cal == "*":
print((lambda x, y : x*y)(fi,se))
elif cal == "/":
print('%.1f' %(lambda x,y : x/y)(fi,se)) | Python | zaydzuhri_stack_edu_python |
for i in range length r
begin
if i % 2 == 0
begin
if i == length r - 1
begin
set ans = ans + r at i ^ 2
end
else
begin
set ans = ans + r at i ^ 2 - r at i + 1 ^ 2
end
end
end
import math
print ans * pi | for i in range(len(r)):
if i % 2 == 0:
if i == len(r) - 1:
ans += r[i] ** 2
else:
ans += r[i] ** 2 - r[i + 1] ** 2
import math
print(ans * math.pi) | Python | zaydzuhri_stack_edu_python |
from helpers import *
from functools import reduce
from itertools import imap , chain
class Event extends object
begin
set E_COM_BREAKDOWN_TIME = 5
set ENCOUNTER_RANGE = tuple 1 8
decorator classmethod
function generateRandom cls random
begin
return call random choice tuple generateRandomEncounter generateRandomIncomin... | from ..helpers import *
from functools import reduce
from itertools import imap, chain
class Event(object):
E_COM_BREAKDOWN_TIME = 5
ENCOUNTER_RANGE = (1,8)
@classmethod
def generateRandom(cls, random):
return random.choice((
cls.generateRandomEncounter,
cls.generateRandomIncomingData,
cls.generateRando... | Python | zaydzuhri_stack_edu_python |
function ReadColorJSON param desc
begin
set current_value = call Color desc at string rgb at 0 desc at string rgb at 1 desc at string rgb at 2
end function | def ReadColorJSON(param, desc):
param.current_value = Color(desc['rgb'][0], desc['rgb'][1], desc['rgb'][2]) | Python | nomic_cornstack_python_v1 |
comment 12.16 Write a test program that prompts the user to enter five strings and
comment displays them in reverse order
class Stack extends list
begin
function __init__ self
begin
call __init__
end function
function isEmpty self
begin
return call __len__ == 0
end function
function peek self
begin
return call __getite... | # 12.16 Write a test program that prompts the user to enter five strings and
# displays them in reverse order
class Stack(list):
def __init__(self):
super().__init__()
def isEmpty(self):
return self.__len__() == 0
def peek(self):
return self.__getitem__(len(self) - 1)
def p... | Python | zaydzuhri_stack_edu_python |
function index_gcis gcis_url es_url index alias dump_dir
begin
set conn = call get_es_conn es_url index alias
set refList = call get_refList dump_dir
set art_path = string %s/article/ % dump_dir
for tuple root dirs files in walk art_path
begin
for f in files
begin
set f = string %s%s % tuple art_path f
print string f: ... | def index_gcis(gcis_url, es_url, index, alias, dump_dir):
conn = get_es_conn(es_url, index, alias)
refList = get_refList(dump_dir)
art_path = "%s/article/"%(dump_dir)
for (root,dirs,files) in os.walk(art_path):
for f in files:
f = "%s%s"%(art_path, f)
print("f: %s" % f)
... | Python | nomic_cornstack_python_v1 |
async function update_payment_extra payment_hash extra outgoing=false conn=none
begin
set amount_clause = if expression outgoing then string AND amount < 0 else string AND amount > 0
set row = await call fetchone string SELECT hash, extra from apipayments WHERE hash = ? { amount_clause } tuple payment_hash
if not row
b... | async def update_payment_extra(
payment_hash: str,
extra: dict,
outgoing: bool = False,
conn: Optional[Connection] = None,
) -> None:
amount_clause = "AND amount < 0" if outgoing else "AND amount > 0"
row = await (conn or db).fetchone(
f"SELECT hash, extra from apipayments WHERE hash =... | Python | nomic_cornstack_python_v1 |
function load_injections_from_mcf self filename
begin
set injections = list
comment load all injections
with open filename encoding=string latin-1 as mcf
begin
for line in mcf
begin
if line at slice : 2 : == string SE
begin
append injections tuple line at slice 3 : 6 : line at slice 7 : 10 :
end
end
end
comment con... | def load_injections_from_mcf(self, filename):
injections = []
# load all injections
with open(filename, encoding="latin-1") as mcf:
for line in mcf:
if line[:2] == "SE":
injections.append((line[3:6], line[7:10]))
# convert to array
... | Python | nomic_cornstack_python_v1 |
function test_translate_retains_annotations self
begin
set grammar = string <A> ::= <B> <C> <B> ::= <C> | @Q <D> <C> ::= "C" <D> ::= "D"
set tree = parse call Parser grammar
set node = call translate tree
set expected = parse call Parser string <A> ::= <B> <C> <B> ::= "C" | @Q "D" <C> ::= "C" <D> ::= "D"
assert true ca... | def test_translate_retains_annotations(self):
grammar = r'''
<A> ::= <B> <C>
<B> ::= <C> | @Q <D>
<C> ::= "C"
<D> ::= "D"
'''
tree = Parser().parse(grammar)
node = Translator().translate(tree)
expected = Parser().parse(r'''
... | Python | nomic_cornstack_python_v1 |
import os
function renameFiles
begin
comment 1 get file names from folder
set fileList = list directory string C:\path\path
comment 2 print(fileList)
set saved_path = get current directory
print string Current working directory is + saved_path
change directory string C:\path\path
comment for each file, rename file
for ... | import os
def renameFiles():
#1 get file names from folder
fileList = os.listdir(r"C:\path\path")
#2 print(fileList)
saved_path = os.getcwd()
print("Current working directory is "+saved_path)
os.chdir(r"C:\path\path")
#for each file, rename file
for file_name in fileList:
os.ren... | Python | zaydzuhri_stack_edu_python |
from collections import deque
function rotate string n
begin
string Rotate characters in a string. Expects string and n (int) for number of characters to move.
set deq = deque string
call rotate - n
return join string deq
end function | from collections import deque
def rotate(string, n):
"""Rotate characters in a string.
Expects string and n (int) for number of characters to move.
"""
deq = deque(string)
deq.rotate(-n)
return "".join(deq)
| Python | zaydzuhri_stack_edu_python |
function sends self tag=none fromdate=none todate=none
begin
string Gets a total count of emails you’ve sent out.
return call string GET string /stats/outbound/sends tag=tag fromdate=fromdate todate=todate
end function | def sends(self, tag=None, fromdate=None, todate=None):
"""
Gets a total count of emails you’ve sent out.
"""
return self.call("GET", "/stats/outbound/sends", tag=tag, fromdate=fromdate, todate=todate) | Python | jtatman_500k |
comment !/usr/bin/env python
import rospy
from std_msgs.msg import String
global press_key
set press_key = string 0
function callback msg
begin
global press_key
set press_key = data
end function
if __name__ == string __main__
begin
call init_node string testKeyboard
call Subscriber string /keys String callback
comment ... | #!/usr/bin/env python
import rospy
from std_msgs.msg import String
global press_key
press_key = "0"
def callback(msg):
global press_key
press_key = msg.data
if __name__ == '__main__':
rospy.init_node("testKeyboard")
rospy.Subscriber("/keys", String, callback)
# Loop rate (in Hz)
rate = r... | Python | zaydzuhri_stack_edu_python |
function report self
begin
from import databases
set _current = current
set data = list
function get_dir_size dirpath
begin
string Modified from http://stackoverflow.com/questions/12480367/how-to-generate-directory-size-recursively-in-python-like-du-does. Does not follow symbolic links
return sum generator expression... | def report(self):
from . import databases
_current = self.current
data = []
def get_dir_size(dirpath):
"""Modified from http://stackoverflow.com/questions/12480367/how-to-generate-directory-size-recursively-in-python-like-du-does.
Does not follow symbolic links... | Python | nomic_cornstack_python_v1 |
from typing import Tuple , List
from pymongo import MongoClient
class TrieNode extends object
begin
function __init__ self char
begin
set char = char
set children = list
set word_finished = false
set words = list
end function
end class
function add root word
begin
string Add word to prefix tree
set node = root
for ch... | from typing import Tuple, List
from pymongo import MongoClient
class TrieNode(object):
def __init__(self, char: str):
self.char = char
self.children = []
self.word_finished = False
self.words = []
def add(root: TrieNode, word: str):
""" Add word to prefix tree """
node ... | Python | zaydzuhri_stack_edu_python |
function calculate_measurement self measurement_name=string current
begin
comment Get the measurement
set exp_name = file_name
if measurement_name == string current
begin
set measurement = current_measurement
end
else
begin
set measurement = call get_measurement measurement_name
end
set params = none
comment End and st... | def calculate_measurement(self, measurement_name="current"):
# Get the measurement
exp_name = self.current_exp.file_name
if measurement_name == "current":
measurement = self.current_measurement
else:
measurement = self.current_exp.get_measurement(measurement_name... | Python | nomic_cornstack_python_v1 |
function time_write fpath time
begin
with open fpath string wb as f
begin
return write f time
end
end function | def time_write(fpath, time):
with open(fpath, 'wb') as f:
return f.write(time) | Python | nomic_cornstack_python_v1 |
function createService self json uid
begin
comment TODO:SHOULD TAKE PARAMETERS DINAMICALLY CHECKING FOR KEYS
comment for key in CREATESERVICEKEYS:
comment if key not in json:
comment return jsonify(Error="Error in credentials from submission: "+ str(key)), 400
try
begin
set websites = call unpackWebsites json=json at s... | def createService(self, json,uid):
# TODO:SHOULD TAKE PARAMETERS DINAMICALLY CHECKING FOR KEYS
# for key in CREATESERVICEKEYS:
# if key not in json:
# return jsonify(Error="Error in credentials from submission: "+ str(key)), 400
... | Python | nomic_cornstack_python_v1 |
function find_address
begin
set street_name = input string Enter your house number and street name:
set city_name = input string Enter your city:
set state_name = input string Enter your state:
set zip_code = input string Enter your zip code:
if length street_name == 0 or length city_name == 0 or length state_name == 0... | def find_address():
street_name = input('Enter your house number and street name: ')
city_name = input('Enter your city: ')
state_name = input('Enter your state: ')
zip_code = input('Enter your zip code: ')
if len(street_name) == 0 or len(city_name) == 0 or len(state_name) == 0 or len(zip_cod... | Python | nomic_cornstack_python_v1 |
function KS n key
begin
set keyp = bytearray KEY_SIZE
for i in range n
begin
set keyp = call lrotate keyp KS_TABLE at i at 1
end
return call PC2 keyp
end function | def KS(n, key):
keyp = bytearray(KEY_SIZE)
for i in range(n):
keyp = lrotate(keyp, KS_TABLE[i][1])
return PC2(keyp) | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
function get_key l
begin
set opp = dict 0 1 ; 1 0 ; 2 4 ; 4 2 ; 3 5 ; 5 3
set front = dict 0 list 3 2 5 4 ; 1 list 3 4 5 2 ; 2 list 0 3 1 5 ; 3 list 2 0 4 1 ; 4 list 0 5 1 3 ; 5 list 2 1 4 0
set i = index l 1
set bottom = l at opp at i
set left = min generator expression l at j for j... | from collections import defaultdict
def get_key(l):
opp = {0: 1, 1: 0, 2: 4, 4: 2, 3: 5, 5: 3}
front = {0: [3, 2, 5, 4], 1: [3, 4, 5, 2],
2: [0, 3, 1, 5], 3: [2, 0, 4, 1],
4: [0, 5, 1, 3], 5: [2, 1, 4, 0]}
i = l.index(1)
bottom = l[opp[i]]
left = min(l[j] for j in range(6... | Python | zaydzuhri_stack_edu_python |
function is_mitochrondial chrom ref alt sample_gt
begin
if alt in sample_gt and chrom == string MT
begin
return true
end
else
begin
return false
end
end function | def is_mitochrondial(chrom, ref, alt, sample_gt):
if alt in sample_gt and chrom == 'MT':
return True
else:
return False | Python | nomic_cornstack_python_v1 |
function range1000
begin
global upper_limit
set upper_limit = 1000
comment button that changes the range to [0,1000) and starts a new game
global secret_number
set secret_number = call randrange 0 1000
call new_game
end function | def range1000():
global upper_limit
upper_limit = 1000
# button that changes the range to [0,1000) and starts a new game
global secret_number
secret_number = random.randrange(0,1000)
new_game() | Python | nomic_cornstack_python_v1 |
comment 문제
comment N명의 사람들은 매일 아침 한 줄로 선다.
comment 이 사람들은 자리를 마음대로 서지 못하고 오민식의 지시대로 선다.
comment 어느 날 사람들은 오민식이 사람들이 줄 서는 위치를 기록해 놓는다는 것을 알았다.
comment 그리고 아침에 자기가 기록해 놓은 것과 사람들이 줄을 선 위치가 맞는지 확인한다.
comment 사람들은 자기보다 큰 사람이 왼쪽에 몇 명 있었는지만을 기억한다.
comment N명의 사람이 있고, 사람들의 키는 1부터 N까지 모두 다르다.
comment 각 사람들이 기억하는 정보가 주어질 때,
comm... | # 문제
# N명의 사람들은 매일 아침 한 줄로 선다.
# 이 사람들은 자리를 마음대로 서지 못하고 오민식의 지시대로 선다.
# 어느 날 사람들은 오민식이 사람들이 줄 서는 위치를 기록해 놓는다는 것을 알았다.
# 그리고 아침에 자기가 기록해 놓은 것과 사람들이 줄을 선 위치가 맞는지 확인한다.
# 사람들은 자기보다 큰 사람이 왼쪽에 몇 명 있었는지만을 기억한다.
# N명의 사람이 있고, 사람들의 키는 1부터 N까지 모두 다르다.
# 각 사람들이 기억하는 정보가 주어질 때,
# 줄을 어떻게 서야 하는지 출력하는 프로그램을 작성하시오.
#
# 입력
# 첫째 줄... | Python | zaydzuhri_stack_edu_python |
string Author: Patrik Holop, Matej Hrabal About: Module that extracts output information from recognized patterns Input sphere vector's shape: {[[T,F,T], [F,F,T], ...} where T means border pixel, F inside of outside pixel
import math
from src.image.detector import Detector
from src.core.io import get_image_vector , wri... | """
Author: Patrik Holop, Matej Hrabal
About: Module that extracts output information from recognized patterns
Input sphere vector's shape:
{[[T,F,T], [F,F,T], ...} where T means border pixel,
F inside of outside pixel
"""
import math
from src.image.detector import ... | Python | zaydzuhri_stack_edu_python |
import sys
set tuple x y = list comprehension integer x for x in split read line stdin
set k = integer read line stdin
set b = integer read line stdin
set xx = list
set yy = list
while x > 0
begin
insert xx 0 x % b
set x = integer x / b
end
while y > 0
begin
insert yy 0 y % b
set y = integer y / b
end
for i in range ... | import sys
x, y = [int(x) for x in sys.stdin.readline().split()]
k = int(sys.stdin.readline())
b = int(sys.stdin.readline())
xx = []
yy = []
while x > 0:
xx.insert(0, x%b)
x = int(x/b)
while y > 0:
yy.insert(0, y%b)
y = int(y/b)
for i in range(len(yy)-len(xx)):
xx.insert(0, 0)
def C(a, b):
x1, x2 = (a, b-a) i... | Python | zaydzuhri_stack_edu_python |
function scrambleBin binary
begin
set scrambled = list string string string string
set n = 0
for i in range length scrambled
begin
while 8 > length scrambled at i
begin
for char in binary
begin
set scrambled at i = scrambled at i + char at n
end
set n = n + 1
end
end
return scrambled
end function | def scrambleBin(binary):
scrambled = ['', '', '', '']
n = 0
for i in range(len(scrambled)):
while 8 > len(scrambled[i]):
for char in binary:
scrambled[i] += char[n]
n += 1
return scrambled | Python | nomic_cornstack_python_v1 |
import psycopg2
set connection = call connect user=string postgres password=string ams253526370 host=string 127.0.0.1 port=string 5432 database=string airport
set cursor = call cursor
function conectar
begin
try
begin
execute cursor string SELECT * FROM flights;
set record = call fetchall
print record
print string Cone... | import psycopg2
connection = psycopg2.connect(user = "postgres", password = "ams253526370", host = "127.0.0.1", port = "5432", database = "airport")
cursor = connection.cursor()
def conectar():
try:
cursor.execute("SELECT * FROM flights;")
record = cursor.fetchall()
print(record)
p... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from flask import Flask , render_template , jsonify
import json
import requests
from random import sample
from models import *
set app = call Flask __name__
decorator call route string /
function index
begin
set artistes = call order_by name
set albums = call order_by title
set genres = ca... | # -*- coding: utf-8 -*-
from flask import Flask, render_template, jsonify
import json
import requests
from random import sample
from models import *
app = Flask(__name__)
@app.route('/')
def index():
artistes = Artists.select().order_by(Artists.name)
albums = Albums.select().order_by(Albums.title)
genres ... | Python | zaydzuhri_stack_edu_python |
from project_utils import *
string read train data from csv file, change some of the names to be readable by further functions. get the important words from file and create a bag of words presentation of the data. learn 3 classification models and save it to files.
function flow
begin
set all_data = read csv string Cla... | from project_utils import *
"""read train data from csv file, change some of the names to be
readable by further functions.
get the important words from file and create a bag of words presentation of the data.
learn 3 classification models and save it to files."""
def flow():
all_data = pd.read_csv('Classified_D... | Python | zaydzuhri_stack_edu_python |
function calculate_cost X cost discount_percentage tax_percentage
begin
comment Calculate the total cost before applying discounts or taxes
set total_cost = X * cost
comment Apply the discount
set discount_amount = total_cost * discount_percentage
set total_cost = total_cost - discount_amount
comment Apply the tax
set ... | def calculate_cost(X, cost, discount_percentage, tax_percentage):
# Calculate the total cost before applying discounts or taxes
total_cost = X * cost
# Apply the discount
discount_amount = total_cost * discount_percentage
total_cost -= discount_amount
# Apply the tax
tax_amount = t... | Python | greatdarklord_python_dataset |
import math
import os
from functools import reduce
import numpy as np
import tensorflow as tf
from layers import RegDense , RegConv2D , RegConv2DTranspose
function l2_norm x
begin
return square root call reduce_sum x ^ 2 axis=list 1 2 3 at tuple Ellipsis none none none
end function
class Base_VAE_GAN extends object
beg... | import math
import os
from functools import reduce
import numpy as np
import tensorflow as tf
from layers import RegDense, RegConv2D, RegConv2DTranspose
def l2_norm(x):
return (tf.sqrt(tf.reduce_sum(x ** 2, axis=[1, 2, 3])))[..., None, None, None]
class Base_VAE_GAN(object):
def __init__(self, logdir, lmd... | Python | zaydzuhri_stack_edu_python |
function radiogaga_db_insert MySQLconnection table element
begin
comment DB connection
set conn = MySQLconnection
comment Write the mysql command to send to the server
comment Note that this follows the new PEP 3101 and PEP 249 (DB-API)
set s = string INSERT INTO {0} (
set s = format s table
set count = 1
set n = lengt... | def radiogaga_db_insert(MySQLconnection, table, element):
# DB connection
conn = MySQLconnection
# Write the mysql command to send to the server
# Note that this follows the new PEP 3101 and PEP 249 (DB-API)
s = "INSERT INTO {0} ("
s = s.format(table)
count = 1
n = len(element)
for ... | Python | nomic_cornstack_python_v1 |
function _onMiddleButtonRelease self object event
begin
debug string _onMiddleButtonRelease( { call GetClassName } , { event } )
set clickPosition = call GetEventPosition
comment Find the closest picked actor that matches one of the supplied actors
comment during construction.
set picker = call vtkPointPicker
call Pick... | def _onMiddleButtonRelease( self, object, event ):
logger.debug( f"_onMiddleButtonRelease( {object.GetClassName()}, {event} )" )
clickPosition = self.GetInteractor().GetEventPosition()
# Find the closest picked actor that matches one of the supplied actors
# during construction.
... | Python | nomic_cornstack_python_v1 |
function __setslice__ self i j sequence
begin
if length x at slice i : j : == length sequence
begin
set x at slice i : j : = sequence
end
else
begin
raise call ValueError string The length is not matched
end
end function | def __setslice__(self,i,j,sequence):
if len(self.x[i:j]) == len(sequence):
self.x[i:j] = sequence
else:
raise ValueError("The length is not matched") | Python | nomic_cornstack_python_v1 |
function regioncounts ribo out experiments upperlength lowerlength title horizontal dump
begin
return call plot_region_counts_wrapper ribo_file=ribo experiment_list=experiments range_lower=lowerlength range_upper=upperlength title=title output_file=out dump_to_file=dump horizontal=horizontal
end function | def regioncounts(ribo, out, experiments,
upperlength, lowerlength, title, horizontal, dump):
return plot_region_counts_wrapper(
ribo_file = ribo,
experiment_list = experiments,
range_lower = lowerlength,
... | Python | nomic_cornstack_python_v1 |
function getMasterIp
begin
return loads read open JOB_FLOW_JSON at string masterPrivateDnsName
end function | def getMasterIp():
return json.loads(open(CC.JOB_FLOW_JSON).read())['masterPrivateDnsName'] | Python | nomic_cornstack_python_v1 |
comment All relatively prime numbers up to n
import sys
function gcd a b
begin
while a % b != 0
begin
set tuple a b = tuple b a % b
end
return b
end function
set n = integer argv at 1
set n = n + 1
for i in range 0 n
begin
print i sep=string end=string
end
print
comment first row is all spaces because i=1
print string... | # All relatively prime numbers up to n
import sys
def gcd(a, b):
while a%b !=0:
a,b=b, a%b
return b
n=int(sys.argv[1])
n += 1
for i in range(0,n):
print(i, sep="", end="")
print()
# first row is all spaces because i=1
print(str(1)+' '*(n-1))
for i in range(2,n):
print(str(i) + ' ', end="") # for j=1, 1st... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string Created on Thu Nov 1 21:56:03 2018 @author: liguo
import networkx as nx
from random import choice
import examples as ex
import numpy as np
import highorder
comment Degree type feature and lowOrder feature:
comment TUNGraphEdgeI
function degreeFeature gr... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 1 21:56:03 2018
@author: liguo
"""
import networkx as nx
from random import choice
import examples as ex
import numpy as np
import highorder
# Degree type feature and lowOrder feature:
def degreeFeature(graph, uGraph, srcNode, dstNode): # TUNGra... | Python | zaydzuhri_stack_edu_python |
function normalize_weights self
begin
comment TODO automatise this
comment demand and production time series names
set prod_ts_with_weight = list comprehension item for item in prod_ts if item in unique level=1
set demand_ts_with_weight = list comprehension item for item in demand_ts if item in unique level=1
comment p... | def normalize_weights(self):
# TODO automatise this
# demand and production time series names
prod_ts_with_weight = [item for item in self.prod_ts if item in self.weights.index.unique(level=1)]
demand_ts_with_weight = [item for item in self.demand_ts if item in self.weights.index.unique(... | Python | nomic_cornstack_python_v1 |
comment The Collatz Sequence
function collatz number
begin
if number % 2 == 0
begin
set number = number // 2
print number
return number
end
else
if number == 0
begin
set number = 1
print number
return number
end
else
begin
set number = 3 * number + 1
print number
return number
end
end function
comment Ask player for nu... | # The Collatz Sequence
def collatz(number):
if number%2 == 0:
number=number//2
print(number)
return number
elif number == 0:
number= 1
print(number)
return number
else:
number=(3*number) +1
print(number)
return number
# Ask player for number
print('Give me a number')
playerNumber = in... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plot
set arrs = list
set x = array range 4 40 / 10.0
set color = list list 1 0 0 list 47 / 255.0 79 / 255.0 47 / 255.0 list 0 0 1 list 173 / 255.0 1 47 / 255.0 list 104 / 255.0 34 / 255.0 139 / 255.0
set a = - 1
for i in range 13 30 4
begin
set a = a + 1
end | import numpy as np
import matplotlib.pyplot as plot
arrs = []
x = np.array(range(4,40))/10.
color = [[1,0,0],[47/255.,79/255.,47/255.],[0,0,1],[173/255.,1,47/255.],[104/255.,34/255.,139/255.]]
a= -1
for i in range(13,30,4):
a+=1 | Python | zaydzuhri_stack_edu_python |
function __get_indices_by_category__ self categories minimum_count
begin
set chosen_indices_by_category = list
for category in categories
begin
set category_indices = index
set random_indices = random choice category_indices minimum_count replace=false
set category_indices_array = array random_indices
append chosen_in... | def __get_indices_by_category__(self, categories, minimum_count):
chosen_indices_by_category = []
for category in categories:
category_indices = self.data_frame[self.data_frame[self.predicting_column] == category].index
random_indices = np.random.choice(category_indices, minimum_... | Python | nomic_cornstack_python_v1 |
for val in aliast
begin
print val
end
for val in range 1 5
begin
print val
end
set adict = dict string chap1 10 ; string chap2 20 ; string chap3 30
for item in keys adict
begin
print string key is item
print string value is adict at item
end
set name = string python programming
for char in name
begin
print char
end | for val in aliast :
print(val)
for val in range(1,5) :
print(val)
adict={"chap1":10,"chap2":20,"chap3":30}
for item in adict.keys() :
print("key is", item)
print("value is", adict[item])
name="python programming"
for char in name :
print(char)
| Python | zaydzuhri_stack_edu_python |
function game_card_poker_winner hand1 hand2
begin
set winner = string Its a tie both players share the pot
set check1 = all generator expression item in deck for item in hand2
set check2 = all generator expression item in deck for item in hand2
if length hand1 == length hand2 and check1 is true and check2 is true
begin... | def game_card_poker_winner(hand1: "List of Cards with Player 1",hand2: "List of Cards with Player 1") -> 'Returns the number of player who won':
winner = 'Its a tie both players share the pot'
check1 = all(item in deck for item in hand2)
check2 = all(item in deck for item in hand2)
if len(hand1) == len... | Python | nomic_cornstack_python_v1 |
function distance_to_dest map
begin
set width = length map at 0
set height = length map
set end = tuple height - 1 width - 1
return call compute_cost map end
end function | def distance_to_dest(map):
width = len(map[0])
height = len(map)
end = (height - 1, width - 1)
return compute_cost(map, end) | Python | nomic_cornstack_python_v1 |
function get_user_filter self
begin
return list comprehension dict string Name string tag: + tag at string Key ; string Values list tag at string Value for tag in user_profile at string tags
end function | def get_user_filter(self):
return [{'Name': 'tag:' + tag['Key'], 'Values': [tag['Value']]} for tag in self.user_profile['tags']] | Python | nomic_cornstack_python_v1 |
comment FUNCTION: DOUBLE INDEX
function double_index lst index
begin
comment print(index)
comment print(len(lst) - 1)
if index <= length lst - 1
begin
return 2 * lst at index
end
else
begin
return lst
end
end function
comment FUNCTION: DOUBLE INDEX
function double_index2 lst index
begin
try
begin
return 2 * lst at inde... | #FUNCTION: DOUBLE INDEX
def double_index(lst, index):
#print(index)
#print(len(lst) - 1)
if (index <= len(lst) - 1):
return 2 * lst[index]
else:
return lst
#FUNCTION: DOUBLE INDEX
def double_index2(lst, index):
try:
return 2 * lst[index]
except IndexError:
return "Except IndexError..."
excep... | Python | zaydzuhri_stack_edu_python |
function get_character_indices string
begin
set character_indices = dict
for tuple index character in enumerate string
begin
if character not in character_indices
begin
set character_indices at character = list index
end
else
begin
append character_indices at character index
end
end
return character_indices
end functi... | def get_character_indices(string):
character_indices = {}
for index, character in enumerate(string):
if character not in character_indices:
character_indices[character] = [index]
else:
character_indices[character].append(index)
return character_indices
| Python | jtatman_500k |
function evaluate self gameState action
begin
set features = call getFeatures gameState action
set weights = call getWeights gameState action
comment print "features: ", features
comment print "weights: ", weights
comment print "action: ", action
comment print "features * weights: ", features*weights
comment print "\n"... | def evaluate(self, gameState, action):
features = self.getFeatures(gameState, action)
weights = self.getWeights(gameState, action)
# print "features: ", features
# print "weights: ", weights
# print "action: ", action
# print "features * weights: ", features*weights
... | Python | nomic_cornstack_python_v1 |
function wait_for_states self timeout=40 *states
begin
set link_state = none
for _ in range timeout
begin
set link_state = call get_attribute string LinkStatus
if link_state in states
begin
return
end
sleep 1
end
raise call TgnError string Port failed to reach state { states } , port state is { link_state } after { tim... | def wait_for_states(self, timeout: Optional[int] = 40, *states: str) -> None:
link_state = None
for _ in range(timeout):
link_state = self.active_phy.get_attribute("LinkStatus")
if link_state in states:
return
time.sleep(1)
raise TgnError(f"Por... | 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.