code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_short_upload_options self
begin
set gt = call GeneTorrentInstance resourcedir + string -u instance_type=GT_UPLOAD add_defaults=false
set tuple sout serr = communicate gt
assert in string required serr
assert in string missing serr
assert in string upload serr
assert equal returncode 9
set gt = call GeneTo... | def test_short_upload_options(self):
gt = GeneTorrentInstance(self.resourcedir + "-u",
instance_type=InstanceType.GT_UPLOAD, add_defaults=False)
(sout, serr) = gt.communicate()
self.assertIn("required", serr)
self.assertIn("missing", serr)
self.assertIn("upload", serr... | Python | nomic_cornstack_python_v1 |
while number != 0
begin
set number = integer input string Geef een getal:
set count = count + 1
set total = total + number
end
print string Er zijn + string count + string getallen ingevoerd, de som is: + string total | while number != 0:
number = int(input("Geef een getal: "))
count += 1
total = total + number
print("Er zijn "+str(count)+" getallen ingevoerd, de som is: "+ str(total)) | Python | zaydzuhri_stack_edu_python |
function require_instance obj types=none name=none type_name=none truncate_at=80
begin
string Raise an exception if obj is not an instance of one of the specified types. Similarly to isinstance, 'types' may be either a single type or a tuple of types. If name or type_name is provided, it is used in the exception messag... | def require_instance(obj, types=None, name=None, type_name=None, truncate_at=80):
"""
Raise an exception if obj is not an instance of one of the specified types.
Similarly to isinstance, 'types' may be either a single type or a tuple of
types.
If name or type_name is provided, it is used in the ex... | Python | jtatman_500k |
from __future__ import annotations
import string
import re
set EOL_PUNCTUATION = string .!?
class Document
begin
function __init__ self
begin
comment it is up to you how to implement this method
comment feel free to alter this method and its parameters to your liking
set lines = list
end function
function add_line sel... | from __future__ import annotations
import string
import re
EOL_PUNCTUATION = ".!?"
class Document:
def __init__(self) -> None:
# it is up to you how to implement this method
# feel free to alter this method and its parameters to your liking
self.lines = []
def add_line(self, line: st... | Python | zaydzuhri_stack_edu_python |
function parameters self
begin
raise NotImplementedError
end function | def parameters(self):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function check_list source value
begin
try
begin
return value in loads source
end
except any
begin
return false
end
end function | def check_list(source, value):
try:
return value in json.loads(source)
except:
return False | Python | nomic_cornstack_python_v1 |
for x in range 1 n + 1
begin
set sum = sum + x
end
print string Sum of first n string natural numbers is sum | for x in range (1, n + 1):
sum += x
print ("Sum of first", n, "natural numbers is" , sum)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string First element of a sequence The types of the elements of the input are not know
from typing import Union , Sequence , Any
function safe_first_element lst
begin
string Using Sequence and union to declare a set of possible inputs [Any]
if lst
begin
return lst at 0
end
else
begin
retur... | #!/usr/bin/env python3
'''
First element of a sequence
The types of the elements of the
input are not know
'''
from typing import Union, Sequence, Any
def safe_first_element(lst: Sequence[Any]) -> Union[Any, None]:
'''
Using Sequence and union
to declare a set of possible inputs [Any]
'''
if lst:
... | Python | zaydzuhri_stack_edu_python |
comment Install the driver file for the Five_poke (see
comment https://pycontrol.readthedocs.io/en/latest/user-guide/hardware/#more-devices).
comment Connect breakout board 1.2 to the computer, plug in the 12V power supply.
comment Connect port 1 on the Five poke board to port 1 on the breakout board.
comment Connect p... | # Install the driver file for the Five_poke (see
# https://pycontrol.readthedocs.io/en/latest/user-guide/hardware/#more-devices).
# Connect breakout board 1.2 to the computer, plug in the 12V power supply.
# Connect port 1 on the Five poke board to port 1 on the breakout board.
# Connect port 2 on the Five poke board... | Python | zaydzuhri_stack_edu_python |
function run_training config n_classes train_loader valid_loader width=1 mb_version=1
begin
comment defining model
if width > 1
begin
set model = call resnet18 num_classes=n_classes
end
else
if mb_version == 1
begin
set model = call MobileNet n_classes=n_classes width_mult=width
end
else
begin
set model = call MobileNe... | def run_training(config, n_classes, train_loader, valid_loader, width=1, mb_version=1):
# defining model
if width > 1:
model = tvm.resnet18(num_classes=n_classes)
else:
if mb_version == 1:
model = MobileNet(n_classes=n_classes, width_mult=width)
else:
model = ... | Python | nomic_cornstack_python_v1 |
comment -*-encoding:utf-8 -*-
string 字符串应用实例:密码的加密解密 和 密码强度判断实例
from itertools import cycle
function crypt source key
begin
string 编写函数实现字符串加密和解密,循环使用指定密钥,采用简单的异或算法
set result = string
comment itertool提供用于循环操作迭代对象的函数,返回的是一个迭代器对象,惰性求值,用到的时候才会返回一个值
set temp = cycle key
print type temp
for ch in source
begin
set result =... | # -*-encoding:utf-8 -*-
"""
字符串应用实例:密码的加密解密 和 密码强度判断实例
"""
from itertools import cycle
def crypt(source, key):
"""编写函数实现字符串加密和解密,循环使用指定密钥,采用简单的异或算法"""
result = ''
temp = cycle(key) # itertool提供用于循环操作迭代对象的函数,返回的是一个迭代器对象,惰性求值,用到的时候才会返回一个值
print(type(temp))
for ch in source:
result = result... | Python | zaydzuhri_stack_edu_python |
function main
begin
set store = call Storage string token.json
set creds = get store
if not creds or invalid
begin
set flow = call flow_from_clientsecrets string credentials.json SCOPES
set creds = call run_flow flow store
end
set service = call build string calendar string v3 http=call authorize call Http
comment Call... | def main():
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))
# Call the Calendar... | Python | nomic_cornstack_python_v1 |
import math , time
from datetime import timedelta , datetime
function get_track_wise_talk_details test_input output_file
begin
string function to get track wise details for all the talks 1. first setting the variables as needed 2. calling function for getting the total count , index wise dictionary, time wise dict of d... | import math, time
from datetime import timedelta, datetime
def get_track_wise_talk_details(test_input, output_file):
"""
function to get track wise details for all the talks
1. first setting the variables as needed
2. calling function for getting the total count , index wise dictionary, time wise dict... | Python | zaydzuhri_stack_edu_python |
comment Первая строка содержит число 1 <= n <= 10**5. Вторая — массив A[1 ... n], содержащий натуральные числа, не превосходящие 10**9.
comment Необходимо посчитать число пар индексов i <= i < j <= n, для которых A[i] > a[j]. . (Такая пара элементов называется инверсией массива.
comment Количество инверсий в массиве яв... | # Первая строка содержит число 1 <= n <= 10**5. Вторая — массив A[1 ... n], содержащий натуральные числа, не превосходящие 10**9.
# Необходимо посчитать число пар индексов i <= i < j <= n, для которых A[i] > a[j]. . (Такая пара элементов называется инверсией массива.
# Количество инверсий в массиве является в некотор... | Python | zaydzuhri_stack_edu_python |
class Node extends object
begin
function __init__ self item
begin
set item = item
set next = none
end function
end class
class SingleLinkList extends object
begin
function __init__ self
begin
set _head = none
end function
function is_empty self
begin
return _head is none
end function
function length self
begin
set cur ... | class Node(object):
def __init__(self, item):
self.item = item
self.next = None
class SingleLinkList(object):
def __init__(self):
self._head = None
def is_empty(self):
return self._head is None
def length(self):
cur = self._head
count = 0
while ... | Python | zaydzuhri_stack_edu_python |
function get_rotation_matrix_between_two_vectors a b
begin
set tuple a b = tuple norm a norm b
if all a == b
begin
return call identity 3
end
else
if all a == - b
begin
comment When a and b are complete opposite to each other, there is no unique rotation matrix in 3D!
comment Also, note that -np.identity(3) is not unit... | def get_rotation_matrix_between_two_vectors(a, b):
a, b = vec.norm(a), vec.norm(b)
if all(a == b):
return np.identity(3)
elif all(a == -b):
# When a and b are complete opposite to each other, there is no unique rotation matrix in 3D!
## Also, note that -np.ide... | Python | nomic_cornstack_python_v1 |
function timestamp2str t fmt=string %Y-%m-%d %H:%M:%S.000
begin
return string format time call fromtimestamp t fmt
end function | def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'):
return datetime.fromtimestamp(t).strftime(fmt) | Python | nomic_cornstack_python_v1 |
function on_lOrthography_editingFinished self
begin
if call isChecked
begin
set string = call text
set IPA = call toIPA string
set lexNode = lexDict at currentCard
try
begin
set text = IPA
end
except AttributeError
begin
set elemList = list lexNode
reverse elemList
for tuple i item in enumerate elemList
begin
if tag ==... | def on_lOrthography_editingFinished(self):
if self.lAutoBtn.isChecked():
string = self.lOrthography.text()
IPA = Orthographies.toIPA(string)
lexNode = dataIndex.lexDict[dataIndex.currentCard]
try:
lexNode.find('IPA').text = IPA
except A... | Python | nomic_cornstack_python_v1 |
function newCalFileName self type runBegin runEnd=string end
begin
set path = join path cdir
if not exists path path
begin
make directory os path
end
set path = join path cdir calibgroup
if not exists path path
begin
make directory os path
end
set path = join path cdir calibgroup src
if not exists path path
begin
make ... | def newCalFileName(self, type, runBegin, runEnd='end'):
path=os.path.join(self.cdir)
if not os.path.exists(path):
os.mkdir(path)
path=os.path.join(self.cdir,self.calibgroup)
if not os.path.exists(path):
os.mkdir(path)
path=os.path.join(self.cdir... | Python | nomic_cornstack_python_v1 |
function new_position self direction
begin
set tuple x y = call get_position
set tuple dx dy = DIRECTIONS at direction
return tuple x + dx y + dy
end function | def new_position(self, direction):
x, y = self.get_player().get_position()
dx, dy = DIRECTIONS[direction]
return x + dx, y + dy | Python | nomic_cornstack_python_v1 |
import random
comment Did they tie?
function didTie board
begin
for i in board at 0
begin
if i == string o
begin
return false
end
end
return true
end function
comment checks rows if someone won
function checkRows board color
begin
for row in board
begin
set currentStreak = 0
for col in row
begin
if col == color
begin
s... | import random
# Did they tie?
def didTie(board):
for i in board[0]:
if i == "o":
return False
return True
#checks rows if someone won
def checkRows(board, color):
for row in board:
currentStreak = 0
for col in row:
if col == color:
curre... | Python | zaydzuhri_stack_edu_python |
set a = integer input string Enter First Number:
set b = integer input string Enter Second Number:
print string ** PERFORMING EUCLIDEAN ALGORITHM **
set r1 = a
set r2 = b
set q = 0
set r = r1
print string q r1 r2 r
print string _____________ * 5
while r2 > 0
begin
print string q string | r1 string | r2 string | r
set ... | a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
print("\n** PERFORMING EUCLIDEAN ALGORITHM **\n")
r1 = a
r2 = b
q = 0
r = r1
print("\t q \t\t r1 \t\t r2 \t\t r")
print("_____________" * 5)
while(r2 > 0):
print("\t", q , "\t|\t" , r1 , "\t|\t" , r2 , "\t|\t" , r)
q = int(r1 / r2)
... | Python | zaydzuhri_stack_edu_python |
function post self request
begin
set serializer = call get_serializer data=data
call is_valid raise_exception=true
save
set user_serializer = call UserSerializer instance=instance
return call Response data status=HTTP_201_CREATED
end function | def post(self, request: Request) -> Response:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
user_serializer = UserSerializer(instance=serializer.instance)
return Response(user_serializer.data, status=status.HTTP_20... | Python | nomic_cornstack_python_v1 |
import unittest
import mock
import events
class decoratorTests extends TestCase
begin
function test_isMeDecorator self
begin
set me = call Mock
set args = call Mock
set player = me
set inner = call Mock
end function
end class | import unittest
import mock
import events
class decoratorTests(unittest.TestCase):
def test_isMeDecorator(self):
me = mock.Mock()
args = mock.Mock()
args.player = me
inner = mock.Mock() | Python | zaydzuhri_stack_edu_python |
import talib
import numpy as np
import math
import pandas
import time
import datetime
from functools import reduce
comment init方法是您的初始化逻辑,context对象可以在任何函数之间传递
function init context
begin
comment 滑点默认值为2‰
call set_slippage 0.002
comment 交易费默认值为0.25‰
call set_commission 0.00025
comment 基准默认为沪深300
call set_benchmark strin... | import talib
import numpy as np
import math
import pandas
import time
import datetime
from functools import reduce
#init方法是您的初始化逻辑,context对象可以在任何函数之间传递
def init(context):
#滑点默认值为2‰
context.set_slippage(0.002)
#交易费默认值为0.25‰
context.set_commission(0.00025)
#基准默认为沪深300
context.set_benchmark("0... | Python | zaydzuhri_stack_edu_python |
function materialise value
begin
return call get_variable replace name string : string __ + string _materialised shape=shape dtype=dtype trainable=false
end function | def materialise(value):
return tf.get_variable(value.name.replace(':', '__') + '_materialised',
shape=value.shape,
dtype=value.dtype,
trainable=False) | Python | nomic_cornstack_python_v1 |
for string in listOfWords
begin
print string { indexRow } . { string at slice 0 : 10 : 1 }
set indexRow = indexRow + 1
end | for string in listOfWords:
print(f"{indexRow}. {string[0:10:1]}")
indexRow += 1
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Jun 23 12:27:08 2020 @author: Cristhian
set disp = list string * string * string * string * string *
for item in disp
begin
print item * 5
end | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 12:27:08 2020
@author: Cristhian
"""
disp=["*","*","*","*","*"]
for item in disp:
print(item*5) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import re
from plotnine import *
set pre = read csv string ../data/전국_평균_분양가격_2018.6월_.csv string , encoding=string euc-kr
print string =============================
print head pre
print string =============================
print tail pre
print string... | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import re
from plotnine import *
pre = pd.read_csv('../data/전국_평균_분양가격_2018.6월_.csv',',',encoding='euc-kr')
print("=============================")
print(pre.head())
print("=============================")
print(pre.tail())
print("클래스 정보===================... | Python | zaydzuhri_stack_edu_python |
function process_genes data_list
begin
set data_list2float = list
pop data_list 0
set size = length data_list
for i in range size
begin
pop data_list at i 0
append data_list2float array list map float data_list at i
end
set data_list2float2np = transpose np array data_list2float
print shape
call savetxt string ./data/... | def process_genes(data_list):
data_list2float = []
data_list.pop(0)
size = len(data_list)
for i in range(size):
data_list[i].pop(0)
data_list2float.append(np.array(list(map(float, data_list[i]))))
data_list2float2np = np.transpose(np.array(data_list2float))
print(data_list2float2... | Python | nomic_cornstack_python_v1 |
function sto
begin
for i in range 1 101
begin
if i % 3 == 0 and i % 5 == 0
begin
set i = string FooBar
end
else
if i % 5 == 0
begin
set i = string Bar
end
else
if i % 3 == 0
begin
set i = string Foo
end
print i
end
end function
call sto | def sto():
for i in range(1, 101):
if (i % 3) == 0 and (i % 5) == 0:
i = 'FooBar'
elif (i % 5) == 0:
i = 'Bar'
elif (i % 3) == 0:
i = 'Foo'
print(i)
sto()
| Python | zaydzuhri_stack_edu_python |
function associate_floating_ip self vm_id floating_ip
begin
set my_url = string %s/%s/%s/%s % tuple url_openstack string servers vm_id string action
set payload = string { "addFloatingIp": {"address": " + floating_ip + string " } }
call set_info_log my_url
set response = post my_url header payload
call set_info_log rea... | def associate_floating_ip(self, vm_id, floating_ip):
my_url = "%s/%s/%s/%s" % (
self.url_openstack, "servers", vm_id, "action")
payload = '{ "addFloatingIp": {"address": "' + floating_ip + '" } }'
loggers.set_info_log(my_url)
response = http.post(my_url, self.header, payload)... | Python | nomic_cornstack_python_v1 |
function delete_prediction id_prediction
begin
if call delete_prediction id_prediction is none
begin
call abort 404
end
else
begin
return tuple string 200
end
end function | def delete_prediction(id_prediction):
if dbManager.delete_prediction(id_prediction) is None:
abort(404)
else:
return '', 200 | Python | nomic_cornstack_python_v1 |
function __init__ self parent_rat=none up=false
begin
if none is parent_rat
begin
comment If there is no parent RAT, initialize to level 0
set level = 0
set tuple d1 d2 d3 d4 = tuple 0 1 1 1
end
else
begin
comment Else initialize to one level beyond parent ...
set level = level + 1
set tuple d1 d2 d3 d4 = call get_ds
c... | def __init__(self,parent_rat=None,up=False):
if None is parent_rat:
### If there is no parent RAT, initialize to level 0
self.level = 0
self.d1,self.d2,self.d3,self.d4 = 0,1,1,1
else:
### Else initialize to one level beyond parent ...
self.level = parent_rat.level + 1
self.d... | Python | nomic_cornstack_python_v1 |
function _get_feature_attributes self
begin
set srs = call Series directory self
set srs = srs at ? starts with str string _ ? ? call contains string as_ ? srs != string putin ? srs != string takeout ? srs != string intermediate_accesses ? srs != string geometry ? srs != string has_a_point ? srs != string centroid
set ... | def _get_feature_attributes(self) -> dict:
srs = pd.Series(dir(self))
srs = srs[
(~srs.str.startswith('_'))
& (~srs.str.contains('as_'))
& (srs != 'putin')
& (srs != 'takeout')
& (srs != 'intermediate_accesses')
& (srs != 'geometry'... | Python | nomic_cornstack_python_v1 |
function shift_tokens_right self input_ids decoder_start_token_id
begin
set shifted_input_ids = call new_zeros shape
set shifted_input_ids at tuple slice : : slice 1 : : = clone input_ids at tuple slice : : slice : - 1 :
set shifted_input_ids at tuple slice : : 0 = decoder_start_token_id
return shifted_inpu... | def shift_tokens_right(self, input_ids: torch.Tensor, decoder_start_token_id: int):
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
shifted_input_ids[:, 0] = decoder_start_token_id
return shifted_input_ids | Python | nomic_cornstack_python_v1 |
with open string game_instructions.txt as intro
begin
set intro = read intro
end
with open string map.txt as map
begin
set map = read map
end
print intro
set player = dict string inventory list string strength ; string location string foyer
set monster = dict string health list string 100 ; string sanity list string 10... | with open('game_instructions.txt') as intro:
intro = intro.read()
with open('map.txt') as map:
map = map.read()
print(intro)
player = {
'inventory': ['strength'],
'location': 'foyer'
}
monster = {
'health': ['100'],
'sanity': ['100'],
}
monster_alive = True
actions = [
'enter foyer', ... | Python | zaydzuhri_stack_edu_python |
comment nested for loop
set listku = list list string a string b string c list string d string e string f list string g string h string i
for baris in listku
begin
for elemen in baris
begin
print elemen
end
end
set data = list list list string Andi string Budi string Caca list string Deni string Euis string Fafa list s... | # nested for loop
listku=[
['a','b','c'],
['d','e','f'],
['g','h','i']
]
for baris in listku:
for elemen in baris:
print(elemen)
data=[
[
['Andi','Budi','Caca'],
['Deni','Euis','Fafa'],
['Gigi','Hani','Inne']
],
[
['Janu','Koko','Lani'],
['M... | Python | zaydzuhri_stack_edu_python |
function prepare_board self
begin
call pack expand=YES fill=BOTH
call pack expand=YES fill=BOTH
call pack_forget
call place relx=0.2 rely=0.5 anchor=CENTER
call place relx=0.5 rely=0.5 anchor=CENTER
call place relx=0.8 rely=0.5 anchor=CENTER
end function | def prepare_board(self):
self.turn_manager.pack(expand=YES, fill=BOTH)
self.board_canvas.pack(expand=YES, fill=BOTH)
self.title.pack_forget()
self.player_1_title.place(relx=0.2, rely=0.5,anchor=CENTER)
self.turn_message.place(relx=0.5, rely=0.5,anchor=CENTER)
self.player_... | Python | nomic_cornstack_python_v1 |
function delete self key
begin
raise NotImplementedError
end function | def delete(self, key):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function make_local_from_timestamp timestamp timezone
begin
set utc = get arrow timestamp
set local_time = to utc timezone
return string format time local_time string %a %I:%M %p
end function | def make_local_from_timestamp(timestamp, timezone):
utc = arrow.get(timestamp)
local_time = utc.to(timezone)
return local_time.strftime('%a %I:%M %p') | Python | nomic_cornstack_python_v1 |
function values self
begin
return call mapVertexInfluence_values self
end function | def values(self):
return _osgAnimation.mapVertexInfluence_values(self) | Python | nomic_cornstack_python_v1 |
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
comment Create your views here.
from rest_framework.views import APIView
from userapp.models import Employee
from userapp.serializers import EmployeeSerializer , EmployeeDeSerializer
class EmployeeAPIView ... | from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
# Create your views here.
from rest_framework.views import APIView
from userapp.models import Employee
from userapp.serializers import EmployeeSerializer,EmployeeDeSerializer
class EmployeeAPIView(APIVi... | Python | zaydzuhri_stack_edu_python |
function _get_template_from_spikes self spike_ids
begin
comment We get the original template ids for the spikes.
set st = spike_templates at spike_ids
comment We find the template with the largest number of spikes from the spike selection.
set tuple template_ids counts = unique st return_counts=true
set ind = argument ... | def _get_template_from_spikes(self, spike_ids):
# We get the original template ids for the spikes.
st = self.spike_templates[spike_ids]
# We find the template with the largest number of spikes from the spike selection.
template_ids, counts = np.unique(st, return_counts=True)
ind ... | Python | nomic_cornstack_python_v1 |
function check_special num
begin
set sum_of_cubes = 0
for i in num
begin
set sum_of_cubes = sum_of_cubes + integer i ^ 3
end
if sum_of_cubes == integer num
begin
return true
end
else
begin
return false
end
end function
if __name__ == string __main__
begin
set num = input string Enter your number:
if call check_special ... | def check_special(num):
sum_of_cubes = 0
for i in num:
sum_of_cubes += int(i)**3
if sum_of_cubes == int(num):
return True
else:
return False
if __name__ == "__main__":
num = input("Enter your number: ")
if check_special(num):
print("Your number {} is special... | Python | zaydzuhri_stack_edu_python |
function set_cash self cash
begin
set portfolio = call get_portfolio_object
if portfolio is not none
begin
set cash = cash + cash
set initial_cash = initial_cash + cash
end
end function | def set_cash(self, cash):
portfolio = self.get_portfolio_object()
if portfolio is not None:
portfolio.cash += cash
portfolio.initial_cash += cash | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
set stack = list
set min_stack = list
end function | def __init__(self):
self.stack = []
self.min_stack = [] | Python | nomic_cornstack_python_v1 |
from simulator import strong_bisimulation , weak_bisimulation
from simulator import StateGraph
from tkinter import filedialog
from tkinter import ttk
from tkinter import *
import pickle
import time
import os
class UI
begin
comment Auxiliary functions #
function nonsense self
begin
call print_log string Sorry, + name + ... | from simulator import strong_bisimulation, weak_bisimulation
from simulator import StateGraph
from tkinter import filedialog
from tkinter import ttk
from tkinter import *
import pickle
import time
import os
class UI:
#################################
# Auxiliary functions #
#####################... | Python | zaydzuhri_stack_edu_python |
function _UpdateCubeColorWhite self data
begin
for list r c ch in data
begin
set tuple x y = call RowColToXY r c
call _DrawCubeXYWhite x y
end
end function | def _UpdateCubeColorWhite(self, data):
for [r, c, ch] in data:
(x, y) = self.RowColToXY(r, c)
self._DrawCubeXYWhite(x, y) | Python | nomic_cornstack_python_v1 |
import re
function correct_int string
begin
while true
begin
try
begin
set point = integer input format string {} string
end
except ValueError
begin
print string Value error! Try again!
end
try else
begin
if point == 0 or point == 1
begin
return point
end
print string Range error! Try again!
end
end
end function
set st... | import re
def correct_int(string):
while True:
try:
point = int(input("{}".format(string)))
except ValueError:
print("Value error! Try again!\n")
else:
if point == 0 or point == 1:
return point
print("Range error! Try again!\n"... | Python | zaydzuhri_stack_edu_python |
function from_gitlab klass repository labor_hours=true
begin
string Create CodeGovProject object from GitLab Repository
if not is instance repository Project
begin
raise call TypeError string Repository must be a gitlab Repository object
end
set project = call klass
debug string GitLab: repository_id=%d path_with_names... | def from_gitlab(klass, repository, labor_hours=True):
"""
Create CodeGovProject object from GitLab Repository
"""
if not isinstance(repository, gitlab.v4.objects.Project):
raise TypeError('Repository must be a gitlab Repository object')
project = klass()
log... | Python | jtatman_500k |
function parse_file_path file_path
begin
set file_name = base name path file_path
set cutoff = length file_path - length file_name
set folder_path = file_path at slice : cutoff :
return tuple folder_path file_name
end function | def parse_file_path(file_path):
file_name = os.path.basename(file_path)
cutoff = len(file_path) - len(file_name)
folder_path = file_path[:cutoff]
return folder_path, file_name | Python | nomic_cornstack_python_v1 |
comment message_after_replacement = message.format(name,address)
print message | #message_after_replacement = message.format(name,address)
print(message) | Python | zaydzuhri_stack_edu_python |
function resolveAmbiguity self
begin
comment TODO: This removes arguments for which there was no consecutive span found
comment Part of these are non-consecutive arguments,
comment but other could be a bug in recognizing some punctuation marks
set elements = list pred + list comprehension tuple s indices for tuple s in... | def resolveAmbiguity(self):
## TODO: This removes arguments for which there was no consecutive span found
## Part of these are non-consecutive arguments,
## but other could be a bug in recognizing some punctuation marks
elements = [self.pred] \
+ [(s, indices)
... | Python | nomic_cornstack_python_v1 |
string Quick select
from functools import reduce
comment quickselect :: Ord a => Int -> [a] -> a
function quickSelect k
begin
string The kth smallest element in the unordered list xs.
function go k xs
begin
set x = xs at 0
function ltx y
begin
return y < x
end function
set tuple ys zs = call call partition ltx xs at sl... | '''Quick select'''
from functools import reduce
# quickselect :: Ord a => Int -> [a] -> a
def quickSelect(k):
'''The kth smallest element
in the unordered list xs.'''
def go(k, xs):
x = xs[0]
def ltx(y):
return y < x
ys, zs = partition(ltx)(xs[1:])
n = len(... | Python | zaydzuhri_stack_edu_python |
function cleanup self
begin
try
begin
call _closeFTP
set ftp = none
call _closeTelnet
set tn = none
end
except Exception
begin
comment Connection Broken, don't do anything
pass
end
end function | def cleanup(self):
try:
self._closeFTP()
self.ftp=None
self._closeTelnet()
self.tn=None
except Exception:
# Connection Broken, don't do anything
pass | Python | nomic_cornstack_python_v1 |
import re
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import janitor
function requests_retry_session retries=5 backoff_factor=0.3 status_forcelist=tuple 500 502 504 session=none
begin
string Ge... | import re
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import janitor
def requests_retry_session(retries=5, backoff_factor=0.3,
status_forcelist=(500, 502, 504), se... | Python | zaydzuhri_stack_edu_python |
import re
import glob
import os
function degistir basla bitir sayfa veri
begin
string TODO: Docstring for degistir. :returns: TODO
set f = open sayfa string r+
set lines = read lines f
seek f 0
set wlines = list
set c = 0
set flag = false
comment print(veri)
for line in lines
begin
set end = search bitir line
set begi... | import re
import glob
import os
def degistir(basla,bitir,sayfa,veri):
"""TODO: Docstring for degistir.
:returns: TODO
"""
f=open(sayfa,"r+")
lines=f.readlines()
f.seek(0)
wlines=[]
c=0
flag=False
# print(veri)
for line in lines:
end=re.search(bitir,line)
begin... | Python | zaydzuhri_stack_edu_python |
function int_func words
begin
set result = string
for i in words
begin
set i = upper i at 0 + i at slice 1 : :
set result = result + i + string
end
return join string result
end function
set words_list = split input string Введите слова через пробел:
print call int_func words_list
function int_func words
begin
ret... | def int_func(words):
result = ''
for i in words:
i = i[0].upper() + i[1:]
result += i + ' '
return ''.join(result)
words_list = input('Введите слова через пробел: ').split()
print(int_func(words_list))
def int_func(words):
return words.title()
words_list = ' '.join(input('Введите с... | Python | zaydzuhri_stack_edu_python |
from pathlib import Path
from predictor.models import TFAkiBase , TFAkiLstm , TFAkiGpt2
import fire
import logging
import numpy as np
import tensorflow as tf
comment set random seed (for reproducibility)
seed 7
call set_seed 7
comment constants
set TIMESTEPS = 8
set N_FEATURES = 16
function train_models epochs=1 batch_... | from pathlib import Path
from predictor.models import TFAkiBase, TFAkiLstm, TFAkiGpt2
import fire
import logging
import numpy as np
import tensorflow as tf
# set random seed (for reproducibility)
np.random.seed(7)
tf.random.set_seed(7)
# constants
TIMESTEPS = 8
N_FEATURES = 16
def train_models(
epochs: int = ... | Python | zaydzuhri_stack_edu_python |
from nltk.corpus import twitter_samples
import _pickle as CP
set negative_file = call strings string negative_tweets.json
set trainer = list comprehension tuple x string neg for x in negative_file at slice 4000 : 5000 :
set positive_file = call strings string positive_tweets.json
extend trainer list comprehension tupl... | from nltk.corpus import twitter_samples
import _pickle as CP
negative_file = twitter_samples.strings("negative_tweets.json")
trainer = [(x, 'neg') for x in negative_file[4000:5000]]
positive_file = twitter_samples.strings("positive_tweets.json")
trainer.extend([(x, 'pos') for x in positive_file[4000:5000]])
correct =... | Python | zaydzuhri_stack_edu_python |
function __init__ self score_func=mean_squared_error coverage=0.95 null_model_params=none
begin
set score_func = score_func
set coverage = coverage
set null_model_params = null_model_params
comment initializes attributes defined in fit
set null_model = none
set time_col_ = none
set value_col_ = none
comment initializes... | def __init__(self, score_func=mean_squared_error, coverage=0.95, null_model_params=None):
self.score_func = score_func
self.coverage = coverage
self.null_model_params = null_model_params
# initializes attributes defined in fit
self.null_model = None
self.time_col_ = None... | Python | nomic_cornstack_python_v1 |
comment challenge 1: send a random quote on Wednesday
import datetime as dt
import random as rd
import smtplib
comment import sys
comment import os
comment sys.path.append(os.path.dirname(os.getcwd()))
comment import config
comment gmail = config.gmail
comment gmail_pw = config.gmail_pw
comment yahoo = config.yahoo
com... | # challenge 1: send a random quote on Wednesday
import datetime as dt
import random as rd
import smtplib
# import sys
# import os
# sys.path.append(os.path.dirname(os.getcwd()))
# import config
# gmail = config.gmail
# gmail_pw = config.gmail_pw
# yahoo = config.yahoo
gmail = "" # sender email
gmail_pw = "" # se... | Python | zaydzuhri_stack_edu_python |
function _parse_location self row
begin
return dict string name string ; string address format string {} {} row at ADDRESS row at ZIP ; string neighborhood row at COMMUNITY_AREA
end function | def _parse_location(self, row):
return {
'name': '',
'address': "{} {}".format(row[Row.ADDRESS], row[Row.ZIP]),
'neighborhood': row[Row.COMMUNITY_AREA]
} | Python | nomic_cornstack_python_v1 |
function remove_from_system_path self path
begin
set path = call expandvars path product
call remove_from_system_path path
end function | def remove_from_system_path(self, path):
path = self.core.expandvars(path, self.product)
self.core.api.os.registry.remove_from_system_path(path) | Python | nomic_cornstack_python_v1 |
function g_sebal_func ts albedo_sur ndvi
begin
set g = as type copy np ndvi float64
call power g 4 out=g
set g = g * - 0.98
set g = g + 1
set g = g * ts
set g = g * albedo_sur * 0.0074 + 0.0038
return g
end function | def g_sebal_func(ts, albedo_sur, ndvi):
g = np.copy(ndvi).astype(np.float64)
np.power(g, 4, out=g)
g *= -0.98
g += 1
g *= ts
g *= (albedo_sur * 0.0074 + 0.0038)
return g | Python | nomic_cornstack_python_v1 |
from tkinter import *
import requests
import json
set root = call Tk
title root string Using SQLlite3 Databases
call iconbitmap string images/tkinter.ico
call geometry string 600x100
call configure background=string #2d3436
comment https://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCod... | from tkinter import *
import requests
import json
root = Tk()
root.title("Using SQLlite3 Databases")
root.iconbitmap("images/tkinter.ico")
root.geometry("600x100")
root.configure(background="#2d3436")
# https://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=89129&distance=10&API_KEY... | Python | zaydzuhri_stack_edu_python |
function entries_publish self unused_request
begin
return call VoidMessage
end function | def entries_publish(self, unused_request):
return message_types.VoidMessage() | Python | nomic_cornstack_python_v1 |
comment !/home/chaofan/anaconda3/bin/python
comment -*- encoding: utf-8 -*-
string @Description: : @Date :2021/02/05 14:57:09 @Author :chaofan @version :1.0
import torch
import torch.nn as nn
import torch.nn.functional as F
comment 单层线性网络
class SingleLayerModel extends Module
begin
function __init__ self input_dim outp... | #!/home/chaofan/anaconda3/bin/python
# -*- encoding: utf-8 -*-
'''
@Description: :
@Date :2021/02/05 14:57:09
@Author :chaofan
@version :1.0
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
# 单层线性网络
class SingleLayerModel(nn.Module):
def __init__(self, input_dim, output_d... | Python | zaydzuhri_stack_edu_python |
function columns self
begin
string Return column information from the schema or from an upstreram package
try
begin
comment For resources that are metapack packages.
set r = call columns
return list r
end
except AttributeError as e
begin
pass
end
return schema_columns
end function | def columns(self):
"""Return column information from the schema or from an upstreram package"""
try:
# For resources that are metapack packages.
r = self.expanded_url.resource.columns()
return list(r)
except AttributeError as e:
pass
ret... | Python | jtatman_500k |
from configparser import ConfigParser
comment import pyodbc
import psycopg2
import pandas as pd
function convert_excel_to_csv input_file_name sheet_name output_file_name
begin
set df = call read_excel input_file_name sheet_name=sheet_name
print head df 5
to csv df output_file_name index=false header=true
end function
f... | from configparser import ConfigParser
# import pyodbc
import psycopg2
import pandas as pd
def convert_excel_to_csv(input_file_name, sheet_name, output_file_name):
df = pd.read_excel(input_file_name, sheet_name=sheet_name)
print(df.head(5))
df.to_csv(output_file_name, index=False, header=True)
... | Python | zaydzuhri_stack_edu_python |
function challenge_post self environ start_response
begin
set query = environ at string tiddlyweb.query
set redirect = get query string tiddlyweb_redirect list string / at 0
try
begin
set username = query at string username at 0
set password = query at string password at 0
return call _validate_and_redirect environ sta... | def challenge_post(self, environ, start_response):
query = environ['tiddlyweb.query']
redirect = query.get('tiddlyweb_redirect', ['/'])[0]
try:
username = query['username'][0]
password = query['password'][0]
return self._validate_and_redirect(environ, start_r... | Python | nomic_cornstack_python_v1 |
import pudb
function parse_hive infile num_tables
begin
set inlog = open infile string rt
comment preallocate memory
comment holds table names
set tables = list comprehension string for i in call xrange num_tables
comment table_meta = [Partition, Database, Owner, CreateTime, Location, Type]
comment six fields (see abo... | import pudb
def parse_hive(infile, num_tables):
inlog = open(infile, 'rt')
#preallocate memory
tables = ['' for i in xrange(num_tables)] #holds table names
#table_meta = [Partition, Database, Owner, CreateTime, Location, Type]
inner_list = ['' for i in xrange(6)] #six fields (see above)
table... | Python | zaydzuhri_stack_edu_python |
function getfile root path remote
begin
set local_file = join path root path
if not exists path local_file
begin
debug format string Downloading {} from {} path remote
try
begin
if not call download remote + path local_file
begin
debug string Download failed
return none
end
end
except Exception as e
begin
exception str... | def getfile(root,path,remote):
local_file = os.path.join(root,path)
if not os.path.exists(local_file):
logger.debug('Downloading {} from {}'.format(path,remote))
try:
if not download(remote + path, local_file):
logger.debug('Download failed')
return N... | Python | nomic_cornstack_python_v1 |
import MalmoPython
import os
import random
import numpy as np
import warnings
import xml.etree.ElementTree as ET
import json
set TRAIN_ENV_PATH = join path string . string train_env.xml
set TEST_ENV_PATH = join path string . string test_env.xml
set INSTRUCTIONS = list string Find string Get string Put string Stack
set ... | import MalmoPython
import os
import random
import numpy as np
import warnings
import xml.etree.ElementTree as ET
import json
TRAIN_ENV_PATH = os.path.join(".", "train_env.xml")
TEST_ENV_PATH = os.path.join(".", "test_env.xml")
INSTRUCTIONS = ["Find", "Get", "Put", "Stack"]
OBJECTS = ["Red", "Blue", "Green", "White", ... | Python | zaydzuhri_stack_edu_python |
function display_board self
begin
for row in _board
begin
print string row + string
end
end function | def display_board(self):
for row in self._board:
print(str(row) + '\n') | Python | nomic_cornstack_python_v1 |
function peer_config_set host_id status peer_config_fields peer_config_param time_slot_param user_name
begin
global sqlalche_obj
call sql_alchemy_db_connection_open
if status == 1
begin
set result = string Timeslot is smaller than the number of slaves you want to fill
return result
end
else
begin
set peer_config_table ... | def peer_config_set(host_id, status, peer_config_fields, peer_config_param, time_slot_param, user_name):
global sqlalche_obj
sqlalche_obj.sql_alchemy_db_connection_open()
if status == 1:
result = 'Timeslot is smaller than the number of slaves you want to fill'
return result
else:
... | Python | nomic_cornstack_python_v1 |
function clear_config
begin
call clear_config
end function | def clear_config():
client.YoloClient().clear_config() | Python | nomic_cornstack_python_v1 |
function thirteen
begin
set numbers = list 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 8926167069662363382013... | def thirteen():
numbers = [37107287533902102798797998220837590246510135740250,
46376937677490009712648124896970078050417018260538,
74324986199524741059474233309513058123726617309629,
91942213363574161572522430563301811072406154908250,
2306758820... | Python | nomic_cornstack_python_v1 |
function DrawIcon self dc
begin
set rect = call Rect *self.GetClientRect()
set point = call Point
set length = 0
call Deflate 4 4
call SetPen call Pen colourIconBorder
call SetBrush call Brush colourIconBackground
call DrawRectangleRect rect
set right1 = call GetRight + 1
set bottom1 = call GetBottom + 1
call SetPen ca... | def DrawIcon(self, dc):
rect = wx.Rect(*self.GetClientRect())
point = wx.Point()
length = 0
rect.Deflate(4, 4)
dc.SetPen(wx.Pen(colourIconBorder))
dc.SetBrush(wx.Brush(colourIconBackground))
dc.DrawRectangleRect(rect)
right1 = rect.GetRight()... | Python | nomic_cornstack_python_v1 |
function datagen u=1
begin
while u > - 1
begin
set u = u - 0.05
yield u
end
end function | def datagen(u=1):
while u > -1:
u -= 0.05
yield u | Python | nomic_cornstack_python_v1 |
comment CS 124: Machine Learning in Genetics
comment Project: Haplotype Phaser
import numpy as np
import pandas as pd
import itertools as it
comment Packages needed
comment some helpers
function fillna col
begin
comment fills in NAs in a given column w most frequent value between 0 and 2
if index at 0 == string 1
begin... | # CS 124: Machine Learning in Genetics
# Project: Haplotype Phaser
import numpy as np
import pandas as pd
import itertools as it
# Packages needed
# some helpers
def fillna(col):
# fills in NAs in a given column w most frequent value between 0 and 2
if col.value_counts().index[0] == '1':
col.fillna(co... | Python | zaydzuhri_stack_edu_python |
function _get_selenium_parent parent
begin
if is instance parent element_class
begin
return selenium_webelement
end
return selenium_webdriver
end function | def _get_selenium_parent(parent):
if isinstance(parent, parent.element_class):
return parent.selenium_webelement
return parent.selenium_webdriver | Python | nomic_cornstack_python_v1 |
function test_edge_label_string_traversal_types self
begin
call create v1 v2
call create v1 v3
call create v1 v4
set out = call outV call get_label call get_label
assert length out == 2
assert vid in list comprehension vid for v in out
assert vid in list comprehension vid for v in out
set out = call outV call get_label... | def test_edge_label_string_traversal_types(self):
TestEdge.create(self.v1, self.v2)
OtherTestEdge.create(self.v1, self.v3)
YetAnotherTestEdge.create(self.v1, self.v4)
out = self.v1.outV(TestEdge.get_label(), OtherTestEdge.get_label())
assert len(out) == 2
assert s... | Python | nomic_cornstack_python_v1 |
function _timer_callback self timer libev_events
begin
if timer in _active_timers
begin
set tuple callback_method callback_timeout kwargs = _active_timers at timer
if callback_timeout
begin
call callback_method timeout=timer keyword kwargs
end
else
begin
call callback_method keyword kwargs
end
call remove_timeout timer... | def _timer_callback(self, timer, libev_events):
if timer in self._active_timers:
(callback_method,
callback_timeout,
kwargs) = self._active_timers[timer]
if callback_timeout:
callback_method(timeout=timer, **kwargs)
else:
... | Python | nomic_cornstack_python_v1 |
function _swap_query_and_sbjct self
begin
comment swap strings
set tuple query sbjct = tuple sbjct query
set tuple query_protein sbjct_protein = tuple sbjct_protein query_protein
comment swap coordinates
set tuple a b c = tuple query_start query_end query_length
set tuple d e f = tuple sbjct_start sbjct_end sbjct_lengt... | def _swap_query_and_sbjct(self):
# swap strings
self.query, self.sbjct = self.sbjct, self.query
self.query_protein, self.sbjct_protein =\
self.sbjct_protein, self.query_protein
# swap coordinates
(a,b,c) = (self.query_start, self.query_end, self.query_length)
... | Python | nomic_cornstack_python_v1 |
function makeOperatorCommand self buttonText
begin
function applyOperator
begin
set number = mainLabel at string text
if string . in number
begin
set number = decimal number
end
else
begin
set number = integer number
end
call applyOperator buttonText number
set mainLabel at string text = string calculator
set operatorE... | def makeOperatorCommand(self, buttonText):
def applyOperator():
number = self.mainLabel["text"]
if "." in number:
number = float(number)
else:
number = int(number)
self.calculator.applyOperator(buttonText, number)
self.m... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string Calculates the shape of a matrix
function matrix_shape matrix size=list
begin
string Calculates the shape of a matrix using tail recursion Seee alternate way in the 2-main file matrix: is the array to calculate the shape of size: is the shape of the matrix Return: size of matrix whi... | #!/usr/bin/env python3
"""Calculates the shape of a matrix"""
def matrix_shape(matrix, size=[]):
"""
Calculates the shape of a matrix using tail recursion
Seee alternate way in the 2-main file
matrix: is the array to calculate the shape of
size: is the shape of the matrix
R... | Python | zaydzuhri_stack_edu_python |
function nflschedule self irc msg args optlist optteam
begin
set fullSchedule = false
for tuple option arg in optlist
begin
if option == string full
begin
set fullSchedule = true
end
end
set optteam = upper optteam
if optteam not in call _validteams
begin
call reply string Team not found. Must be one of: %s % call _val... | def nflschedule(self, irc, msg, args, optlist, optteam):
fullSchedule = False
for (option, arg) in optlist:
if option == 'full':
fullSchedule = True
optteam = optteam.upper()
if optteam not in self._validteams():
irc.repl... | Python | nomic_cornstack_python_v1 |
function isprime n
begin
string Returns True if n is prime
if n == 2
begin
return true
end
if n == 3
begin
return true
end
if n % 2 == 0
begin
return false
end
if n % 3 == 0
begin
return false
end
set i = 5
set w = 2
while i * i <= n
begin
if n % i == 0
begin
return false
end
set i = i + w
set w = 6 - w
end
return true... | def isprime(n):
"""Returns True if n is prime"""
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import re
import scrapy
from scrapy.selector import Selector
from product_extract.items import OutItem
comment 入力データのクラス
class Input_data
begin
function __init__ self top_url product_url product_xpath product_summary_xpath
begin
set top_url = top_url
set product_url = product_url
set produ... | # -*- coding: utf-8 -*-
import re
import scrapy
from scrapy.selector import Selector
from product_extract.items import OutItem
# 入力データのクラス
class Input_data:
def __init__(self, top_url, product_url, product_xpath, product_summary_xpath):
self.top_url = top_url
self.product_url = product_url
... | Python | zaydzuhri_stack_edu_python |
function longest_common_substring s1 s2
begin
comment Convert the strings to lowercase and normalize special characters
set s1 = lower s1
set s2 = lower s2
set s1 = call normalize_special_chars s1
set s2 = call normalize_special_chars s2
comment Initialize a 2D matrix to store intermediate results
set dp = list compreh... | def longest_common_substring(s1, s2):
# Convert the strings to lowercase and normalize special characters
s1 = s1.lower()
s2 = s2.lower()
s1 = normalize_special_chars(s1)
s2 = normalize_special_chars(s2)
# Initialize a 2D matrix to store intermediate results
dp = [[0] * (len(s2) + 1) for _ ... | Python | greatdarklord_python_dataset |
function ternary n
begin
if n == 0
begin
return list 0
end
set nums = list
while n
begin
set tuple n r = divide mod n 3
append nums integer r
end
return list reversed nums
end function
function func elements k
begin
set result = 0
for element in elements
begin
set e = call ternary element
set n = count e 2
if n < k
be... | def ternary (n):
if n == 0:
return [0]
nums = []
while n:
n, r = divmod(n, 3)
nums.append(int(r))
return list(reversed(nums))
def func(elements, k):
result = 0
for element in elements:
e = ternary(element)
n = e.count(2)
if n < k:
print(element)
result += n
return ... | Python | zaydzuhri_stack_edu_python |
import random
import numpy
from firm import Firm
comment from firm_result import FirmResult
from firm_labormarket_result import FirmLaborMarketResult
from firm_goodmarket_result import FirmGoodMarketResult
from worker import Worker
from world import World
function invert x
begin
if x != 0
begin
return 1 / x
end
else
be... | import random
import numpy
from firm import Firm
#from firm_result import FirmResult
from firm_labormarket_result import FirmLaborMarketResult
from firm_goodmarket_result import FirmGoodMarketResult
from worker import Worker
from world import World
def invert(x):
if x != 0:
return 1 / x
else:
... | Python | zaydzuhri_stack_edu_python |
function _draw_stats self
begin
set on_time = 0
set delayed = 0
for s in schedules
begin
set on_time = on_time + on_time
set delayed = delayed + delayed
end
set total = on_time + delayed
if total != 0
begin
set on_time_percent = round on_time / total * 100 1
set delayed_percent = round delayed / total * 100 1
end
else
... | def _draw_stats(self):
on_time = 0
delayed = 0
for s in self.schedules:
on_time += s.on_time
delayed += s.delayed
total = on_time + delayed
if total != 0:
on_time_percent = round(on_time / total * 100, 1)
delayed_percent = round(... | Python | nomic_cornstack_python_v1 |
import pandas as pd
set data = string /Users/brendamaldonado/Desktop/election_data.csv
set df = read csv data
print head df
shape
comment Votes by Candidate
set results = group by df list string Candidate
set x = count results
print x
sum
set per = count df at string Voter ID
comment Percent of Votes
set x at string Pe... | import pandas as pd
data = '/Users/brendamaldonado/Desktop/election_data.csv'
df= pd.read_csv(data)
print(df.head())
df.shape
#Votes by Candidate
results= df.groupby(['Candidate'])
x= results.count()
print(x)
df["Voter ID"].sum
per= df["Voter ID"].count()
#Percent of Votes
x["Percent_of_Votes"]= x["Voter ID"]/per*10... | Python | zaydzuhri_stack_edu_python |
function _connect_to_db self
begin
comment os.path.join('data','db') #os.path.dirname(os.path.abspath(__file__)) self.db_path
set path = db_path
if debug
begin
set path = directory name path absolute path path __file__
end
try
begin
print path
set con = call connect join path path _data_db_name detect_types=PARSE_DECLT... | def _connect_to_db(self):
# os.path.join('data','db') #os.path.dirname(os.path.abspath(__file__)) self.db_path
path = self.db_path
if self.debug:
path = os.path.dirname(os.path.abspath(__file__))
try:
print(path)
con = sqlite3.connect(os.path.join(path... | Python | nomic_cornstack_python_v1 |
async function users_password
begin
set data = await call get_json
set user_email = data at string email
async_with acquire pool as connection
begin
set passwd_data = await call fetchrow string SELECT "password", email, userid FROM users WHERE email = $1 user_email
end
if passwd_data is not none
begin
return call jsoni... | async def users_password():
data = await request.get_json()
user_email = data['email']
async with current_app.pool.acquire() as connection:
passwd_data = await connection.fetchrow(
"""SELECT "password", email, userid
FROM users
WHERE email = $1""",
... | Python | nomic_cornstack_python_v1 |
function pct_between s low high
begin
return mean call between low high
end function | def pct_between(s, low, high):
return s.between(low, high).mean() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import sys
from inotify_simple import INotify , flags
if length argv != 2
begin
print string Usage: wait-for-no-more-writes <file-to-watch>
exit 1
end
set event_timeout_ms = 2 * 1000
set writes_timeout_ms = 5 * 60 * 1000
set no_writes_for_ms = 0
set seen_writes = false
set inotify = call I... | #!/usr/bin/env python3
import sys
from inotify_simple import INotify, flags
if len(sys.argv) != 2:
print('Usage: wait-for-no-more-writes <file-to-watch>')
sys.exit(1)
event_timeout_ms = 2 * 1000
writes_timeout_ms = 5 * 60 * 1000
no_writes_for_ms = 0
seen_writes = False
inotify = INotify()
wd = inotify.add_w... | 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.