code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function custom_initial_email_subject_line self custom_initial_email_subject_line
begin
set _custom_initial_email_subject_line = custom_initial_email_subject_line
end function | def custom_initial_email_subject_line(self, custom_initial_email_subject_line):
self._custom_initial_email_subject_line = custom_initial_email_subject_line | Python | nomic_cornstack_python_v1 |
import argparse
import json
import os
import yaml
set MATCH_DATA = dict
function main
begin
set parser = call ArgumentParser description=string Generate docker-compose yaml definition from running container.
call add_argument string filename nargs=1 type=str default=string docker-compose.yml help=string The name of th... | import argparse
import json
import os
import yaml
MATCH_DATA = {}
def main():
parser = argparse.ArgumentParser(description='Generate docker-compose yaml definition from running container.')
parser.add_argument('filename', nargs=1, type=str, default='docker-compose.yml',
help='The name... | Python | zaydzuhri_stack_edu_python |
comment utils.py This file may be used for all utility functions
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
import math
from PIL import Image
import numpy as np
import cv2
string Create a bijection betweeen int and object. May be used for reverse indexing
class Indexer extends object
begin... | # utils.py This file may be used for all utility functions
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
import math
from PIL import Image
import numpy as np
import cv2
'''
Create a bijection betweeen int and object. May be used for reverse indexing
'''
class Indexer(object):
def __init... | Python | zaydzuhri_stack_edu_python |
function set_rucio_rules config_rule
begin
global RUCIO_RULE
set RUCIO_RULE = config_rule
end function | def set_rucio_rules( config_rule ):
global RUCIO_RULE
RUCIO_RULE = config_rule | Python | nomic_cornstack_python_v1 |
function id self
begin
return get pulumi self string id
end function | def id(self) -> str:
return pulumi.get(self, "id") | Python | nomic_cornstack_python_v1 |
function _own_pods_of_rc pyk_client rc namespace rc_path verbose
begin
if verbose
begin
info string Waiting %d sec before looking for pods of RC %s % tuple PODS_UP_DELAY_IN_SEC rc_path
end
sleep PODS_UP_DELAY_IN_SEC
set pods_list = call _get_pods_of_rc pyk_client json rc namespace
for pod in pods_list
begin
debug strin... | def _own_pods_of_rc(pyk_client, rc, namespace, rc_path, verbose):
if verbose: logging.info("Waiting %d sec before looking for pods of RC %s" %(PODS_UP_DELAY_IN_SEC, rc_path))
sleep(PODS_UP_DELAY_IN_SEC)
pods_list = _get_pods_of_rc(pyk_client, rc.json(), namespace)
for pod in pods_list:
logging.d... | Python | nomic_cornstack_python_v1 |
comment 9° EJERCICIO
import libreria
function blanca
begin
input string Ingrese el nombre de la ciudad:
print string CIUDAD GUARDADA
end function
function amistad
begin
input string Ingrese el nombre de la ciudad:
print string CIUDAD GUARDADA
end function
function capital
begin
input string Ingrese el nombre de la ciud... | #9° EJERCICIO
import libreria
def blanca():
input("Ingrese el nombre de la ciudad:")
print("CIUDAD GUARDADA")
def amistad():
input("Ingrese el nombre de la ciudad:")
print("CIUDAD GUARDADA")
def capital():
input("Ingrese el nombre de la ciudad:")
print("CIUDAD GUARDADA")
def primavera():
... | Python | zaydzuhri_stack_edu_python |
function get_S_O priceClose priceHigh priceLow time_values=none period=14 K=3 D=3 map_time=false
begin
set priceClose = array priceClose
set priceHigh = array priceHigh
set priceLow = array priceLow
set span = length priceClose - period
set stochastic = call get_stochastics priceClose priceHigh priceLow period
set HL_C... | def get_S_O(priceClose, priceHigh, priceLow, time_values=None, period=14, K=3, D=3, map_time=False):
priceClose = np.array(priceClose)
priceHigh = np.array(priceHigh)
priceLow = np.array(priceLow)
span = len(priceClose)-period
stochastic = get_stochastics(priceClose, priceHigh, priceLow, peri... | Python | nomic_cornstack_python_v1 |
comment python3
import tkinter as tk
comment import tkinter.ttk as ttk
import datetime , os
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import matplotlib
call use string TkAgg
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg , Na... | import tkinter as tk # python3
#import tkinter.ttk as ttk
import datetime, os
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToo... | Python | zaydzuhri_stack_edu_python |
function build_cmd infname outfname parameters
begin
set params = list comprehension format string -{0} {1} quote string k quote string v for tuple k v in items call _asdict if v is not none
set cmd = list string swarm *params string -o quote outfname quote infname
return cmd
end function | def build_cmd(infname, outfname, parameters):
params = [
"-{0} {1}".format(shlex.quote(str(k)), shlex.quote(str(v)))
for k, v in parameters._asdict().items()
if v is not None
]
cmd = ["swarm", *params, "-o", shlex.quote(outfname), shlex.quote(infname)]
return cmd | Python | nomic_cornstack_python_v1 |
function get_yesterday
begin
set yesterday = today - time delta days=1
set yesterday_api = string format time yesterday string %Y%m%d
set yesterday_sheets = string format time yesterday string %m-%d-%Y
return tuple yesterday_api yesterday_sheets
end function | def get_yesterday():
yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
yesterday_api = yesterday.strftime('%Y%m%d')
yesterday_sheets = yesterday.strftime("%m-%d-%Y")
return yesterday_api, yesterday_sheets | Python | nomic_cornstack_python_v1 |
string Title: Hamming Distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 2^31. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above ... | """
Title: Hamming Distance
The Hamming distance between two integers is the number of positions
at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 2^31.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
... | Python | zaydzuhri_stack_edu_python |
function chocouBorda self jogo
begin
if x < 0
begin
set x = 0
set vx = - vx
end
else
if x + r > CANVAS_L
begin
set x = CANVAS_L - r
set vx = - vx
end
if y < 0
begin
set vy = - vy
end
end function | def chocouBorda(self, jogo):
if self.x < 0:
self.x = 0
self.vx = -self.vx
elif self.x + self.r > CANVAS_L:
self.x = CANVAS_L - self.r
self.vx = -self.vx
if self.y < 0:
self.vy = -self.vy | Python | nomic_cornstack_python_v1 |
function __generate_sessions self t_max actions_times
begin
set tuple states actions = tuple list list
set total_reward = 0
set s = call reset
for i in range t_max
begin
set probs = call predict_proba list s at 0
set a = actions_space at random choice a=length probs size=1 p=probs at 0
for j in range actions_times
be... | def __generate_sessions(self,t_max,actions_times):
states,actions=[],[]
total_reward=0
s=self.env.reset()
for i in range(t_max):
probs=self.agent.predict_proba([s])[0]
a=self.actions_space[np.random.choice(a=len(probs),size=1,p=probs)[0]]
for j i... | Python | nomic_cornstack_python_v1 |
function replace_md_links md f
begin
set links = call find_md_links md
set newmd = md
for r in links at string regular
begin
set newmd = replace newmd r at 1 f dist r at 1
end
for r in links at string footnotes
begin
set newmd = replace newmd r at 1 f dist r at 1
end
return newmd
end function | def replace_md_links(md, f):
links = find_md_links(md)
newmd = md
for r in links['regular']:
newmd = newmd.replace(r[1], f(r[1]))
for r in links['footnotes']:
newmd = newmd.replace(r[1], f(r[1]))
return newmd | Python | nomic_cornstack_python_v1 |
function get_device_id group_id identifier
begin
return call get_device_id group_id identifier
end function | def get_device_id(group_id: int, identifier: str) -> int:
return Murmur3().get_device_id(group_id, identifier) | Python | nomic_cornstack_python_v1 |
function _collect_type_vars types
begin
set tvars = list
for t in types
begin
if is instance t TypeVar and t not in tvars
begin
append tvars t
end
if has attribute t string __parameters__
begin
extend tvars list comprehension t for t in __parameters__ if t not in tvars
end
end
return tuple tvars
end function | def _collect_type_vars(types: Tuple[TVarOrType, ...]) -> Tuple[TypeVar, ...]:
tvars = []
for t in types:
if isinstance(t, TypeVar) and t not in tvars:
tvars.append(t)
if hasattr(t, "__parameters__"):
tvars.extend([t for t in t.__parameters__ if t not in tvars])
return... | Python | nomic_cornstack_python_v1 |
import read_data as rd
import explore_data as ed
import pre_process as pp
import generate_features as gf
import classify as c
import sys
set f = open string assignment_three_output.txt string w
set stdout = f
comment read data
set df = call read_data string csv string /Users/emmapeterson/machine-learning-for-public-pol... | import read_data as rd
import explore_data as ed
import pre_process as pp
import generate_features as gf
import classify as c
import sys
f = open("assignment_three_output.txt", 'w')
sys.stdout = f
#read data
df = rd.read_data('csv', '/Users/emmapeterson/machine-learning-for-public-policy/assignment_two/credit-data.c... | Python | zaydzuhri_stack_edu_python |
function year n
begin
if n % 4 == 0
begin
if n % 100 == 0
begin
if n % 400 == 0
begin
print true
end
else
begin
print false
end
end
else
begin
print true
end
end
else
begin
print false
end
end function
call year integer input | def year(n):
if n%4==0:
if n%100==0:
if n%400==0:
print(True)
else:
print(False)
else:
print(True)
else:
print(False)
year(int(input()))
| Python | zaydzuhri_stack_edu_python |
import discord
from discord.ext.commands import Bot
import aiohttp
import asyncio
import datetime
import urllib
set BOT_PREFIX = string !
set TOKEN = replace read open string config.txt string r string string
set client = call Bot command_prefix=BOT_PREFIX
comment Remove default help command in favor of our own
call r... | import discord
from discord.ext.commands import Bot
import aiohttp
import asyncio
import datetime
import urllib
BOT_PREFIX = "!"
TOKEN = open("config.txt", 'r').read().replace("\n", '')
client = Bot(command_prefix = BOT_PREFIX)
# Remove default help command in favor of our own
client.remove_command('help')
@client.... | Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self,
other: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> bool:
return not self == other | Python | nomic_cornstack_python_v1 |
function goForward self
begin
string Goes down one level if possible and returns the url at the current level. If it cannot go down, then a blank string will be returned. :return <str>
if not call canGoForward
begin
return string
end
set _blockStack = true
set _index = _index + 1
call emitCurrentChanged
set _blockStac... | def goForward(self):
"""
Goes down one level if possible and returns the url at the current \
level. If it cannot go down, then a blank string will be returned.
:return <str>
"""
if not self.canGoForward():
return ''
self._bloc... | Python | jtatman_500k |
if age > 20
begin
print string Adult
end
else
if age > 15
begin
print string teenage
end
else
begin
print string Kid
end | if age>20:
print("Adult")
elif age>15:
print("teenage")
else:
print("Kid") | Python | zaydzuhri_stack_edu_python |
function _new_obsolete_task self state_name=DEFAULT_INIT_STATE_NAME task_type=TASK_TYPE_HIGH_BOUNCE_RATE exploration_version=1
begin
return call TaskEntry entity_type=TASK_ENTITY_TYPE_EXPLORATION entity_id=EXP_ID entity_version=exploration_version task_type=task_type target_type=TASK_TARGET_TYPE_STATE target_id=state_n... | def _new_obsolete_task(
self,
state_name: str = feconf.DEFAULT_INIT_STATE_NAME,
task_type: str = constants.TASK_TYPE_HIGH_BOUNCE_RATE,
exploration_version: int = 1
) -> improvements_domain.TaskEntry:
return improvements_domain.TaskEntry(
entity_type=constants.TASK... | Python | nomic_cornstack_python_v1 |
function truncate_str str_ maxlen=110 truncmsg=string ~~~TRUNCATED~~~
begin
string Removes the middle part of any string over maxlen characters.
if NO_TRUNCATE
begin
return str_
end
if maxlen is none or maxlen == - 1 or length str_ < maxlen
begin
return str_
end
else
begin
set maxlen_ = maxlen - length truncmsg
set low... | def truncate_str(str_, maxlen=110, truncmsg=' ~~~TRUNCATED~~~ '):
"""
Removes the middle part of any string over maxlen characters.
"""
if NO_TRUNCATE:
return str_
if maxlen is None or maxlen == -1 or len(str_) < maxlen:
return str_
else:
maxlen_ = maxlen - len(truncmsg)
... | Python | jtatman_500k |
import numpy as np
import matplotlib.pyplot as plt
set x = list 4 8 16 24 40
set r_measured = list 1.868381285227245 2.115646482579043 3.415342854957656 5.216265060300032 8.450317833555255
set r_calculated = list 0.5411617550461464 0.9578889516170715 3.3073620969465933 3.7983829834609923 29.525842162803634
set r_std = ... | import numpy as np
import matplotlib.pyplot as plt
x = [4, 8, 16, 24, 40]
r_measured=[1.868381285227245, 2.115646482579043, 3.415342854957656, 5.216265060300032, 8.450317833555255]
r_calculated=[0.5411617550461464, 0.9578889516170715, 3.3073620969465933, 3.7983829834609923, 29.525842162803634]
r_std= [0.00565271996234... | Python | zaydzuhri_stack_edu_python |
function count_correct_propositions
begin
comment List of propositions and their correctness
set propositions = list tuple string A quadrilateral with four equal sides is a rhombus false tuple string A quadrilateral with two pairs of equal opposite sides is a parallelogram false tuple string The sum of the interior ang... | def count_correct_propositions():
# List of propositions and their correctness
propositions = [
("A quadrilateral with four equal sides is a rhombus", False), # Proposition ①
("A quadrilateral with two pairs of equal opposite sides is a parallelogram", False), # Proposition ②
("The su... | Python | dbands_pythonMath |
import math
import os
import random
import re
import sys
comment Complete the sockMerchant function below.
comment logic Starts from here
function sockMerchant n ar
begin
set dict = dict
set se = list set ar
comment Looping and checking the frequency of each item
for i in range 0 length se
begin
set dict at se at i = ... | import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
#logic Starts from here
def sockMerchant(n, ar):
dict = {}
se = list(set(ar))
#Looping and checking the frequency of each item
for i in range(0,len(se)):
dict[se[i]] = 0
for x in range(0... | Python | zaydzuhri_stack_edu_python |
function update self value
begin
debug string update value of field %s with : %s call repr _name value
set wid = _store_widget
call setProperty string python-object value
call emit _sig
end function | def update(self, value):
log_gui.debug("update value of field %s with : %s", repr(self._name), value)
wid = self._store_widget
wid.setProperty("python-object", value)
wid.emit(self._sig) | Python | nomic_cornstack_python_v1 |
function search self case_ref
begin
set driver = driver
comment Click search link and wait for page
comment Link depends upon PUI version
if logged_in in list string new string beta
begin
comment New PUI version
call click
end
else
begin
call click
end
call until lambda driver -> string Case and Application Search in p... | def search(self,case_ref):
driver = self.driver
#Click search link and wait for page
#Link depends upon PUI version
if self.logged_in in ['new','beta']:
#New PUI version
driver.find_element_by_link_text("Cases and Applications").click()
else:
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import dctypes
comment File to import data from HFK or FK output file from geopsy (.max format)
function importHFKdc filename
begin
set f = open filename + string .max string r
set dataStruct = read lines f
close f
comment Extract number of frequency bands (contained in line 9)
set s_id = length stri... | import numpy as np
import dctypes
# File to import data from HFK or FK output file from geopsy (.max format)
def importHFKdc(filename):
f = open(filename+'.max', 'r')
dataStruct = f.readlines()
f.close()
# Extract number of frequency bands (contained in line 9)
s_id = len('# Number... | Python | zaydzuhri_stack_edu_python |
function submit self **kwargs
begin
set pwd = curdir
set wd = directory name logFile
change directory wd
set d = ordered dictionary
end function
comment d['universe'] = 'vanilla'
comment d['executable'] = self.command | def submit(self, **kwargs):
pwd = curdir
wd = dirname(self.logFile)
chdir(wd)
d = OrderedDict()
#d['universe'] = 'vanilla'
#d['executable'] = self.command | Python | nomic_cornstack_python_v1 |
for _ in range integer input
begin
set tuple Xc Xr Yc Yr = split input
set tuple Xc Xr Yc Yr = tuple ordinal Xc - 65 integer Xr - 1 ordinal Yc - 65 integer Yr - 1
if Xc ? Xr ? Yc ? Yr % 2 == 1
begin
print string Impossible
end
else
if Xc == Yc and Xr == Yr
begin
print 0 character 65 + Xc Xr + 1
end
else
if absolute Xc ... | for _ in range(int(input())):
Xc,Xr,Yc,Yr = input().split()
Xc,Xr,Yc,Yr = ord(Xc)-65,int(Xr)-1,ord(Yc)-65,int(Yr)-1
if (Xc^Xr^Yc^Yr)%2 == 1:
print('Impossible')
elif Xc==Yc and Xr==Yr:
print(0, chr(65+Xc), Xr+1)
elif abs(Xc-Yc) == abs(Xr-Yr):
print(1, chr(65+Xc), Xr+1, chr(65+Yc), Yr+1)
else:
for dc,dr in... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function addDigits self num
begin
string :type num: int :rtype: int
if 0 <= num < 10
begin
return num
end
else
begin
set sumnum = 0
for i in range length string num
begin
set sumnum = sumnum + integer string num at i
end
return call addDigits sumnum
end
end function
end class | class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if 0 <= num < 10:
return num
else:
sumnum = 0
for i in range(len(str(num))):
sumnum = sumnum + int(str(num)[i])
return self.add... | Python | zaydzuhri_stack_edu_python |
function _parse_app_spec src_dir
begin
string Returns the parsed contents of dxapp.json. Raises either AppBuilderException or a parser error (exit codes 3 or 2 respectively) if this cannot be done.
if not is directory path src_dir
begin
error string %s is not a directory % src_dir
end
if not exists path join path src_d... | def _parse_app_spec(src_dir):
"""Returns the parsed contents of dxapp.json.
Raises either AppBuilderException or a parser error (exit codes 3 or
2 respectively) if this cannot be done.
"""
if not os.path.isdir(src_dir):
parser.error("%s is not a directory" % src_dir)
if not os.path.exis... | Python | jtatman_500k |
function plot_confusion_matrix cm classes filename=none normalize=false title=string Confusion matrix cmap=Blues
begin
if normalize
begin
set cm = as type cm string float / sum axis=1 at tuple slice : : newaxis
print string Normalized confusion matrix
end
else
begin
print string Confusion matrix, without normalizati... | def plot_confusion_matrix(cm, classes, filename=None, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
thres... | Python | nomic_cornstack_python_v1 |
from torchtext.datasets import Multi30k
from torchtext.data import Field , BucketIterator
from torchtext.data.metrics import bleu_score
import spacy
import torch
import random
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.fu... | from torchtext.datasets import Multi30k
from torchtext.data import Field, BucketIterator
from torchtext.data.metrics import bleu_score
import spacy
import torch
import random
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.f... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
comment LookupRajon.objects.filter(region_id=5)
return format string {0} ({1}) rajons region_id
end function | def __str__(self):
# LookupRajon.objects.filter(region_id=5)
return '{0} ({1})'.format(self.rajons, self.region_id) | Python | nomic_cornstack_python_v1 |
from numbers import Integral
function deep_flatten it
begin
for item in it
begin
if not is instance item tuple Integral str
begin
yield from call deep_flatten item
end
else
begin
yield item
end
end
end function
for i in call deep_flatten list list string apple string pickle list string pear string avocado
begin
print i... | from numbers import Integral
def deep_flatten(it):
for item in it:
if not isinstance(item, (Integral, str)):
yield from deep_flatten(item)
else:
yield item
for i in deep_flatten([['apple', 'pickle'], ['pear', 'avocado']]):
print(i, end=' ')
| Python | zaydzuhri_stack_edu_python |
comment import UI_test
class pair
begin
function __init__ self f=- 1 s=- 1
begin
set i = f
set j = s
end function
function eqal self id
begin
if i == i and j == j
begin
return true
end
return false
end function
function isNull self
begin
if i == 0 and j == 0
begin
return true
end
return false
end function
function prin... | #import UI_test
class pair:
def __init__(self, f = -1, s = -1):
self.i = f
self.j = s
def eqal(self, id):
if self.i == id.i and self.j == id.j:
return True
return False
def isNull(self):
if self.i == 0 and self.j == 0:
return ... | Python | zaydzuhri_stack_edu_python |
import sys
from game.dealer import Dealer
class Director
begin
string The director class will start the game, allows the user to play again, and it gets the choice of the user.
function __init__ self
begin
set keep_playing = true
set dealer = call Dealer
set score = 300
set choice = string
end function
function start_... | import sys
from game.dealer import Dealer
class Director:
'''
The director class will start the game, allows the user to play again,
and it gets the choice of the user.
'''
def __init__(self):
self.keep_playing = True
self.dealer = Dealer()
self.score = 300
se... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment ==== coding:utf-8 ====
set __author__ = string Yi
import sys , random , string
function password x
begin
set pwd = string
comment chuang jian bian liang zhi wei a-zA-Z0-9
set all = ascii_letters + digits
for i in range x
begin
comment da yin sui ji su bin pin jie
set pwd = pwd + ra... | #!/usr/bin/env python
#==== coding:utf-8 ====
__author__ = "Yi"
import sys,random,string
def password(x):
pwd = " "
#chuang jian bian liang zhi wei a-zA-Z0-9
all=string.ascii_letters + string.digits
for i in range(x):
#da yin sui ji su bin pin jie
pwd += random.choice(all)
print... | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
from PyQt5.QtCore import QObject , pyqtSignal
from app.common.modify_song_info import modifySongInfo
from app.common.write_album_cover import writeAlbumCover
class SaveInfoObject extends QObject
begin
set saveAlbumCoverCompleteSig = call pyqtSignal
set saveCompleteSig = call pyqtSignal
comment 返回错误... | # coding:utf-8
from PyQt5.QtCore import QObject, pyqtSignal
from app.common.modify_song_info import modifySongInfo
from app.common.write_album_cover import writeAlbumCover
class SaveInfoObject(QObject):
saveAlbumCoverCompleteSig = pyqtSignal()
saveCompleteSig = pyqtSignal()
saveErrorSig = pyqtSignal(in... | Python | zaydzuhri_stack_edu_python |
comment real signature unknown; restored from __doc__
function close self
begin
pass
end function | def close(self): # real signature unknown; restored from __doc__
pass | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
import sys
set pixelCal = 13.94736842
set timeCal = 300.0
function main
begin
if length argv >= 2
begin
set path = argv at 1
end
else
begin
set path = string /home/kevin/mot/data/exports/batchTest/Glass.Bead.Tests/212.to.250.um/MSBOT-010180000005_Tracking.txt
end
print... | import numpy as np
import matplotlib.pyplot as plt
import sys
pixelCal = 13.94736842
timeCal = 300.
def main():
if len(sys.argv)>=2:
path = sys.argv[1]
else:
path = '/home/kevin/mot/data/exports/batchTest/Glass.Bead.Tests/212.to.250.um/MSBOT-010180000005_Tracking.txt'
print()
print(path... | Python | zaydzuhri_stack_edu_python |
comment https://www.codewars.com/kata/54da5a58ea159efa38000836/train/python
function find_it seq
begin
return list set list comprehension i for i in seq if count seq i % 2 != 0 at 0
end function
function find_it_best_practice seq
begin
for i in seq
begin
if count seq i % 2 != 0
begin
return i
end
end
end function
print... | # https://www.codewars.com/kata/54da5a58ea159efa38000836/train/python
def find_it(seq):
return list(set([i for i in seq if (seq.count(i) % 2) != 0]))[0]
def find_it_best_practice(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
print(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) ==... | Python | zaydzuhri_stack_edu_python |
function __add_mult_events self ev
begin
assert is instance ev Event
if ev_type not in event_dict
begin
set event_dict at ev_type = list
append event_dict at ev_type call __copy__
print string event added
print ev
return true
end
if ev in event_dict at ev_type
begin
return false
end
for event in event_dict at ev_type
... | def __add_mult_events(self, ev):
assert isinstance(ev, Event)
if ev.ev_type not in self.event_dict:
self.event_dict[ev.ev_type] = []
self.event_dict[ev.ev_type].append(ev.__copy__())
print('event added')
print(ev)
return True
if ev in... | Python | nomic_cornstack_python_v1 |
import math
function square_root a x
begin
while true
begin
comment print(x)
set y = x + a / x / 2
if absolute y - x < 1e-13
begin
return x
break
end
set x = y
end
end function
function test_square_root n
begin
set col2 = call square_root n n
set col3 = square root n
set col4 = absolute col2 - col3
print n string col2... | import math
def square_root(a,x):
while True:
#print(x)
y=(x+a/x)/2
if(abs(y-x)<0.0000000000001):
return x
break
x=y
def test_square_root(n):
col2=square_root(n,n)
col3=math.sqrt(n)
col4=abs(col2-col3)
print(n," ",col2," ",col3," ",col4)
x=1
for x in range(1,10):
test_square_root(x)
| Python | zaydzuhri_stack_edu_python |
class sol
begin
function topProd self arr
begin
set maxprod = 0
end function
end class | class sol:
def topProd(self,arr):
maxprod=0 | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy
import os
import matplotlib.pyplot as plt
from tkinter import *
import numpy as np
from PIL import Image , ImageTk
class Application
begin
function __init__ self master imgPath
begin
comment load image database
set imgPath = imgPath
set imgDataset = list
for tuple i tuple dirpath dirnames filen... | import cv2
import numpy
import os
import matplotlib.pyplot as plt
from tkinter import *
import numpy as np
from PIL import Image, ImageTk
class Application():
def __init__(self, master, imgPath):
#load image database
self.imgPath = imgPath
self.imgDataset = []
for i, (dirpath, dirnames, filenames... | Python | zaydzuhri_stack_edu_python |
function debug variable_name variable
begin
print variable_name string = variable string type = type variable
end function
comment 註解 : # 與 '''
comment print("我是第一行")
comment print("我是第二行")
comment print("我是第三行")
comment print("我是第四行")
comment print("我是第五行")
comment 用 \ 來延續多行
comment paragraph1 = '''
comment Most discu... | def debug(variable_name, variable):
print(variable_name, "=", variable, "\n type =", type(variable))
# 註解 : # 與 '''
# print("我是第一行")
# print("我是第二行")
# print("我是第三行")
# print("我是第四行")
# print("我是第五行")
# 用 \ 來延續多行
# paragraph1 = '''
# Most discussions of GraphQL focus on data fetching, but any complete data pl... | Python | zaydzuhri_stack_edu_python |
function K r R r_ani
begin
set u = r / R
if min u < 1
begin
raise call ValueError string 3d radius is smaller than projected radius! Does not make sense.
end
set ua = r_ani / R
if ua == 1
begin
set k = 1 + 1.0 / u * call arccosh u - 1.0 / 6 * 8.0 / u + 7 * square root u - 1.0 / u + 1.0
end
else
if ua > 1
begin
set k = ... | def K(r, R, r_ani):
u = r / R
if np.min(u) < 1:
raise ValueError("3d radius is smaller than projected radius! Does not make sense.")
ua = r_ani / R
if ua == 1:
k = (1 + 1. / u) * np.arccosh(u) - 1. / 6 * (8. / u + 7) * np.sqrt((u - 1.) / (u + 1.))
elif ua ... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
from collections import Counter
import collections
from collections import defaultdict
import os
set cntdo = counter
set cntmake = counter
set cntwork = counter
set cntword = counter
comment make dictionary
set newdic = dict
set dolemmalist = list
set makelemmalist = list
set worklemmal... | from bs4 import BeautifulSoup
from collections import Counter
import collections
from collections import defaultdict
import os
cntdo=Counter()
cntmake=Counter()
cntwork=Counter()
cntword=Counter()
newdic={} #make dictionary
dolemmalist=[]
makelemmalist=[]
worklemmalist=[]
for filename in os.listdir(os.getcwd()):
c... | Python | zaydzuhri_stack_edu_python |
function tanh self x layer
begin
return tanh x / k
end function | def tanh(self, x, layer):
return np.tanh(x / self.k) | Python | nomic_cornstack_python_v1 |
import sys
set stdin = open string test.txt string rt
set n = integer input
set samples = list map int split input
comment print(n, samples)
function isPrime x
begin
set cnt = 0
for i in range 2 x
begin
if x % i == 0
begin
set cnt = cnt + 1
end
end
if cnt != 2
begin
return false
end
else
begin
return true
end
end funct... | import sys
sys.stdin = open('test.txt', 'rt')
n = int(input())
samples = list(map(int, input().split()))
# print(n, samples)
def isPrime(x):
cnt = 0
for i in range(2, x):
if x % i == 0:
cnt += 1
if cnt != 2:
return False
else:
return True
def reverse(x):
s... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import car
import color
set height = 4
set width = 6
set world = zeros tuple height width
set initial_position = list 0 0
set velocity = list 0 1
comment initialize car objects
set carla = call Car initial_position velocity world
move
move
move
call turn_left
call display_world
set position2 = list 2... | import numpy as np
import car
import color
height = 4
width = 6
world = np.zeros((height, width))
initial_position = [0, 0]
velocity = [0, 1]
carla = car.Car(initial_position, velocity, world) #initialize car objects
carla.move()
carla.move()
carla.move()
carla.turn_left()
carla.display_world()
posi... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
import h5py
import seaborn as sns
import plot_format
call set_format
set data_file = call File string figure_6.h5 string r
set key = string foo
set TE_vals = value
set TE_surrogates = value
set TE_shift_surrogates = value
set shifts = value
set mean = mean np TE_vals a... | import matplotlib.pyplot as plt
import numpy as np
import h5py
import seaborn as sns
import plot_format
plot_format.set_format()
data_file = h5py.File("figure_6.h5", "r")
key = "foo"
TE_vals = data_file[key]["TE"].value
TE_surrogates = data_file[key]["TE_surrogate"].value
TE_shift_surrogates = data_file[key]["TE_shi... | Python | zaydzuhri_stack_edu_python |
import os
import discord
import asyncio
from botlogic import *
set client = call Client
function indent level
begin
set indentation = string
for i in range 0 level
begin
set indentation = indentation + string -
end
return indentation
end function
decorator event
async function on_ready
begin
print string Logged in as
... | import os
import discord
import asyncio
from botlogic import *
client = discord.Client()
def indent(level):
indentation = ""
for i in range(0, level):
indentation += "-"
return indentation
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name... | Python | zaydzuhri_stack_edu_python |
string sub-class implementation, inheriting from 'Circle' within circuituous mod
from circuituous import Circle
class Tire extends Circle
begin
string Tires are circles with a corrected perimeter
function perimeter self
begin
string Circumference corrected for the rubber
comment method variable
set ODO_CORRECT = 1.25
r... | """sub-class implementation, inheriting from 'Circle' within circuituous mod"""
from circuituous import Circle
class Tire(Circle):
"Tires are circles with a corrected perimeter"
def perimeter(self):
"Circumference corrected for the rubber"
ODO_CORRECT = 1.25 # method variable
r... | Python | zaydzuhri_stack_edu_python |
function cli ctx
begin
return call get_groups
end function | def cli(ctx):
return ctx.gi.groups.get_groups() | Python | nomic_cornstack_python_v1 |
from django.http import HttpResponse
from django.shortcuts import render
import operator
function home request
begin
return call render request string home.html
end function
function count request
begin
set fullText = GET at string fullText
set wordsList = split fullText
set wordsDictionary = dict
for word in wordsLis... | from django.http import HttpResponse
from django.shortcuts import render
import operator
def home(request):
return render(request,'home.html')
def count(request):
fullText=request.GET['fullText']
wordsList=fullText.split()
wordsDictionary={}
for word in wordsList:
if word in wordsDictionary:... | Python | zaydzuhri_stack_edu_python |
string Defines functions that return connector sentences based on tension level.
from helpers import rand
set CLIMAX_CONNECTORS = list string However, string Nonewithstanding, string Nevertheless, string Finally, string Crucially, string Still,
set CLIMAX_FINALISERS = list string Horrible. string Definitely not cool. s... | '''
Defines functions that return connector sentences based on tension level.
'''
from helpers import rand
CLIMAX_CONNECTORS = [
' However, ',
' Nonewithstanding, ',
' Nevertheless, ',
' Finally, ',
' Crucially, ',
' Still... | Python | zaydzuhri_stack_edu_python |
function terminate self
begin
call raise_exc SystemExit
end function | def terminate(self):
self.raise_exc(SystemExit) | Python | nomic_cornstack_python_v1 |
function setUp self
begin
call create_test_users
call create_test_messages
set tuple alice_inbox _ = call get_or_create user=alice main=true
set tuple bob_inbox _ = call get_or_create user=bob main=true
set tuple carol_inbox _ = call get_or_create user=carol main=true
end function | def setUp(self) -> None:
self.create_test_users()
self.create_test_messages()
self.alice_inbox, _ = Inbox.objects.get_or_create(user=self.alice, main=True)
self.bob_inbox, _ = Inbox.objects.get_or_create(user=self.bob, main=True)
self.carol_inbox, _ = Inbox.objects.get_or_create(... | Python | nomic_cornstack_python_v1 |
function remove_from_playlist self playlist_name video_id
begin
set playlist_exists = false
set video_id_exists = false
set video_exists_in_playlist = false
for playlist in list keys playlists
begin
if upper playlist_name == upper playlist
begin
set playlist_exists = true
set real_playlist_name = playlist
break
end
end... | def remove_from_playlist(self, playlist_name, video_id):
playlist_exists = False
video_id_exists = False
video_exists_in_playlist = False
for playlist in list(self.playlists.keys()):
if playlist_name.upper() == playlist.upper():
playlist_exists = True
... | Python | nomic_cornstack_python_v1 |
comment https://code.google.com/codejam/contest/2974486/dashboard#s=p3
import sys
function readline
begin
return right strip read line stdin
end function
function wins first second
begin
set win_f = 0
set win_s = 0
for chosen_f in first
begin
if any generator expression k > chosen_f for k in second
begin
remove second ... | # https://code.google.com/codejam/contest/2974486/dashboard#s=p3
import sys
def readline():
return sys.stdin.readline().rstrip()
def wins(first, second):
win_f=0
win_s=0
for chosen_f in first:
if any(k > chosen_f for k in second):
second.remove(min(k for k in second if k > chosen_f... | Python | zaydzuhri_stack_edu_python |
from preprocess_image import PreprocessImageAPI
from skeleton import Skeleton
import cv2
import os
import ascii_app.ascii_converter.config as config
import numpy as np
from skimage.morphology import label
from log_system import Log
from pixel_check import PixelCheck
from ascii_replacer import AsciiReplacer
import math
... | from .preprocess_image import PreprocessImageAPI
from .skeleton import Skeleton
import cv2
import os
import ascii_app.ascii_converter.config as config
import numpy as np
from skimage.morphology import label
from .log_system import Log
from .pixel_check import PixelCheck
from .ascii_replacer import AsciiReplacer
import ... | Python | zaydzuhri_stack_edu_python |
function forward self x hx=none
begin
if hx is none
begin
set hx = call new_zeros num_layers shape at 0 hidden_size
end
set h = call x hx at 0
set hidden_lst = list h
for i in range 1 num_layers
begin
set drop_h = call h
set h = call drop_h hx at i
append hidden_lst h
end
set hidden = stack hidden_lst dim=0
return tupl... | def forward(self, x, hx=None):
if hx is None:
hx = x.new_zeros(self.num_layers, x.shape[0], self.hidden_size)
h = self.rnn_cells[0](x, hx[0])
hidden_lst = [h]
for i in range(1, self.num_layers):
drop_h = self.dropout_layers[i - 1](h)
h = self.rnn_cells... | Python | nomic_cornstack_python_v1 |
function pc_output_buffers_full_avg self *args
begin
return call modulation_mapper_sptr_pc_output_buffers_full_avg self *args
end function | def pc_output_buffers_full_avg(self, *args):
return _my_lte_swig.modulation_mapper_sptr_pc_output_buffers_full_avg(self, *args) | Python | nomic_cornstack_python_v1 |
comment For thread sleeping
import time
comment Library for drone control
import ps_drone
comment Computer vision library
import cv2
comment Contains useful math methods
import numpy as np
comment Drone startup
set drone = call Drone
call startup
call reset
comment Some mandatory drone config.
while call getBattery at ... | import time # For thread sleeping
import ps_drone # Library for drone control
import cv2 # Computer vision library
import numpy as np # Contains useful math methods
# Drone startup
drone = ps_drone.Drone()
drone.startup()
drone.reset()
# Some mandatory drone config.
while (drone.... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment gera_lista_cpf.py
comment Marilia Ribeiro da Silva <marilia.ifc@gmail.com>
import gera_cpf
function gera_lista_cpf len_lista_cpf=string 3
begin
return list comprehension call gera_cpf for i in range integer len_lista_cpf
end function
function main
begin... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# gera_lista_cpf.py
#
# Marilia Ribeiro da Silva <marilia.ifc@gmail.com>
import gera_cpf
def gera_lista_cpf(len_lista_cpf='3'):
return [gera_cpf.gera_cpf() for i in range(int(len_lista_cpf))]
def main():
len_lista_cpf = (input('Informe quantos CPFs você... | Python | zaydzuhri_stack_edu_python |
function get_subdir_regex dirs regex verbose=false
begin
comment check inputs
if is instance dirs basestring
begin
set dirs = list dirs
end
end function | def get_subdir_regex(dirs,regex,verbose=False):
# check inputs
if isinstance(dirs,basestring):
dirs=[dirs] | Python | nomic_cornstack_python_v1 |
function create_schema
begin
set connection_handler = get injector ConnectionHandler
with call get_connection_context
begin
with call cursor as cursor
begin
set path = real path path join path get current directory directory name path __file__ string schema.sql
execute cursor read open path string r list
end
end
end fu... | def create_schema() -> None:
connection_handler = injector.get(ConnectionHandler)
with connection_handler.get_connection_context():
with connection_handler.get_current_connection().cursor() as cursor:
path = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__... | Python | nomic_cornstack_python_v1 |
function glob f
begin
set rs = call file f string r
set buff = read lines rs
close rs
return join string buff
end function | def glob(f):
rs = file(f, 'r')
buff = rs.readlines()
rs.close()
return ''.join(buff) | Python | nomic_cornstack_python_v1 |
function test_raster_spacing
begin
set graph = call DualUniformRectilinearGraph tuple 3 4 spacing=tuple 2.0 3.0
call assert_array_equal length_of_link list 3.0 3.0 3.0 2.0 2.0 2.0 2.0 3.0 3.0 3.0 2.0 2.0 2.0 2.0 3.0 3.0 3.0
call assert_array_equal length_of_face list 3.0 3.0 2.0 2.0 2.0 3.0 3.0
end function | def test_raster_spacing():
graph = DualUniformRectilinearGraph((3, 4), spacing=(2.0, 3.0))
assert_array_equal(
graph.length_of_link,
[
3.0,
3.0,
3.0,
2.0,
2.0,
2.0,
2.0,
3.0,
3.0,
... | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
import pandas as pd
import geopandas as gp
function failure_fraction year=2012
begin
comment -- read data
print string reading PIP_InspectionMain.xlsx...
set in_path = join path string ../data string quality_assessment string PIP
set in_name = join path in_path string PIP_InspectionMain.xls... | import os
import numpy as np
import pandas as pd
import geopandas as gp
def failure_fraction(year=2012):
# -- read data
print("reading PIP_InspectionMain.xlsx...")
in_path = os.path.join('../data','quality_assessment','PIP')
in_name = os.path.join(in_path,'PIP_InspectionMain.xlsx')
inspec = pd.r... | Python | zaydzuhri_stack_edu_python |
comment 8/25/2020
comment Making a list from a file
set filename = string movies_line_by_line.txt
with open filename as file_object
begin
set lines = read lines file_object
end
comment Readline() method stores the objects in lists which we can continue to work with after the lines
for line in lines
begin
print strip li... | ### 8/25/2020
### Making a list from a file
#
filename = 'movies_line_by_line.txt'
with open(filename) as file_object:
lines = file_object.readlines()
# Readline() method stores the objects in lists which we can continue to work with after the lines
for line in lines:
print(line.strip())
# We use a simple for l... | Python | zaydzuhri_stack_edu_python |
comment function definition
function mystery n
begin
comment Pass parameters: n=20
comment check is the number is negative
if n <= 0
begin
return 0
end
else
begin
return call mystery n // 2 + 1
end
end function
comment function returns sum of floor division of a number recursively
print call mystery 20
comment Call the... | def mystery(n): # function definition
# Pass parameters: n=20
if n <= 0: # check is the number is negative
return 0
else:
return mystery(n // 2) + 1
# function returns sum of floor division of a number recursively
print(mystery(20))
# Call the function within a print
| Python | zaydzuhri_stack_edu_python |
function sample self n_samples=100 n_burn=10000 thin_factor=100
begin
set n_it = 0
call run_burn_in n_burn
set samples = random sample self n_samples=n_samples n_burn=0 thin_factor=thin_factor
return samples
end function | def sample(self, n_samples: int = 100, n_burn: int = 10000,
thin_factor: int = 100) -> np.array:
self.n_it = 0
self.run_burn_in(n_burn)
samples = ObservedSpaceSampler.sample(self, n_samples=n_samples,
n_burn=0, thin_factor=thin_factor)... | Python | nomic_cornstack_python_v1 |
comment noqa: E501 # noqa: E501
function __init__ self server_hostname=none shared_basepath=none protocol=none proxy_connection=none file_transfer_cipher_type=none credentials=none
begin
set _server_hostname = none
set _shared_basepath = none
set _protocol = none
set _proxy_connection = none
set _file_transfer_cipher_t... | def __init__(self, server_hostname=None, shared_basepath=None, protocol=None, proxy_connection=None, file_transfer_cipher_type=None, credentials=None): # noqa: E501 # noqa: E501
self._server_hostname = None
self._shared_basepath = None
self._protocol = None
self._proxy_connection = Non... | Python | nomic_cornstack_python_v1 |
string # static 메서드 1. 클래스 안에서 self 가 아닌 함수를 만들기위해서 사용 2. 따라서 매서드를 정의할때 self 매개변수를 기술하지 않는다. 3. 메서드 정의 위에 데코레이터 를 기술한다. 4. 객체를 생성하지않고도 매서드를 호출할수있다. 5. 클래스 이름과 객체 이름으로 모두 실행할수있다.
class Payment
begin
comment 객체 생성 숫자세기
set counter = 0
comment 전체적으로 적용되는 내용
set discount = 0.5
function __init__ self price count
begin
set p... | """
# static 메서드
1. 클래스 안에서 self 가 아닌 함수를 만들기위해서 사용
2. 따라서 매서드를 정의할때 self 매개변수를 기술하지 않는다.
3. 메서드 정의 위에 데코레이터 를 기술한다.
4. 객체를 생성하지않고도 매서드를 호출할수있다.
5. 클래스 이름과 객체 이름으로 모두 실행할수있다.
"""
class Payment:
counter = 0 # 객체 생성 숫자세기
discount = 0.5 #전체적으로 적용되는 내용
def __init__(self , price , count):
... | Python | zaydzuhri_stack_edu_python |
import bisect
set N = integer input
set S = input
set X = list list list
set cnt = 0
for i in range N
begin
if S at i == string o
begin
append X at 0 i
end
else
begin
append X at 1 i
end
end
if X at 0 == list or X at 1 == list
begin
print 0
exit
end
for j in range 2
begin
for i in range length X at j
begin
set x = ... | import bisect
N = int(input())
S = input()
X = [[], []]
cnt = 0
for i in range(N):
if S[i] == 'o':
X[0].append(i)
else:
X[1].append(i)
if X[0] == [] or X[1] == []:
print(0)
exit()
for j in range(2):
for i in range(len(X[j])):
x = bisect.bisect(X[1^j], X[j][i])
if x < ... | Python | zaydzuhri_stack_edu_python |
function delete_topic topic_name
begin
set pubsub_client = call Client
set topic = call topic topic_name
delete
print format string Topic {} deleted. name
end function | def delete_topic(topic_name):
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
topic.delete()
print('Topic {} deleted.'.format(topic.name)) | Python | nomic_cornstack_python_v1 |
comment Binary search can only be used when the list is already sorted.
comment The time complexity of binary search is O(log N)
function binary_search_recursive arr target start end
begin
if start > end
begin
return none
end
set mid = start + end // 2
if arr at mid == target
begin
return mid
end
else
if arr at mid > t... | # Binary search can only be used when the list is already sorted.
# The time complexity of binary search is O(log N)
def binary_search_recursive(arr, target, start, end):
if start > end:
return None
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_sea... | Python | zaydzuhri_stack_edu_python |
function data_generator dataset config shuffle=true augment=false augmentation=none random_rois=0 batch_size=1 detection_targets=false
begin
comment batch item index
set b = 0
set image_index = - 1
set image_ids = copy np image_ids
set error_count = 0
comment Anchors
comment [anchor_count, (y1, x1, y2, x2)]
set backbon... | def data_generator(dataset, config, shuffle=True,
augment=False, augmentation=None,
random_rois=0, batch_size=1, detection_targets=False):
b = 0 # batch item index
image_index = -1
image_ids = np.copy(dataset.image_ids)
error_count = 0
# Anchors
# [anchor_... | Python | nomic_cornstack_python_v1 |
for i in range n
begin
append s tmp at i
end
set ind = n
set perenos = 0
for i in range n
begin
if s at i == string .
begin
set nach = i + 1
end
end
for i in range nach n
begin
if integer s at i > 4
begin
set ind = i
break
end
end
if ind == n
begin
print *s sep=string
exit
end
while t > 0 and s at ind != string .
begin... | for i in range(n):
s.append(tmp[i])
ind = n
perenos = 0
for i in range(n):
if (s[i] == '.'):
nach = i + 1
for i in range(nach, n):
if (int(s[i]) > 4):
ind = i
break
if (ind == n):
print(*s, sep="")
exit()
while (t > 0 and s[ind] != '.'):
if (int(s[ind]) > 3):
ind ... | Python | jtatman_500k |
function predict is_train embeddings premise_tensors hypothesis_tensors
begin
with call variable_scope string embed
begin
set premise = call embed_text premise_tensors embeddings
set premise_lens = premise_tensors at string len
end
with call variable_scope string embed reuse=true
begin
set hypothesis = call embed_text ... | def predict(is_train, embeddings, premise_tensors, hypothesis_tensors):
with tf.variable_scope("embed"):
premise = embed_text(premise_tensors, embeddings)
premise_lens = premise_tensors["len"]
with tf.variable_scope("embed", reuse=True):
hypothesis = embed_text(hypothesis_tensors, embeddings)
hypoth... | Python | nomic_cornstack_python_v1 |
import argparse
import os
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
import cutOutPaintings as cop
import pickle
comment size of the images we will compare
set size = 750
set defaultSource = string database.bin
set testImage = string 5.jpg
set ap = call ArgumentParser
call add_argument str... | import argparse
import os
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
import cutOutPaintings as cop
import pickle
size = 750 #size of the images we will compare
defaultSource = 'database.bin'
testImage = "5.jpg"
ap = argparse.ArgumentParser()
ap.add_argument("-s", "--source", required=Fa... | Python | zaydzuhri_stack_edu_python |
function cog name=none **attrs
begin
function wrapper klass
begin
class Cog extends AutoCog klass
begin
function __new__ cls *args **kwargs
begin
set result = call __new__ cls
set __module__ = __module__
set __name__ = name or __name__
for tuple k v in items attrs
begin
set attribute result k v
end
return result
end fu... | def cog(*, name: str=None, **attrs):
def wrapper(klass):
class Cog(AutoCog, klass):
def __new__(cls, *args, **kwargs):
result = super().__new__(cls)
result.__module__ = klass.__module__
result.__name__ = name or klass.__name__
fo... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment coding: utf-8
set CounterDict = dict
class Counter extends object
begin
string 得到长度为N的一个计数器, 一次全局自增1
function __init__ self n
begin
set max_num = n
set cnt = 0
end function
function count self
begin
set cnt = cnt + 1
if length string cnt > max_num
begin
set cnt = 0
end
return self
end ... | #!/usr/bin/python
#coding: utf-8
CounterDict = {}
class Counter(object):
'''
得到长度为N的一个计数器, 一次全局自增1
'''
def __init__(self, n):
self.max_num = n
self.cnt = 0
def count(self):
self.cnt += 1
if len(str(self.cnt)) > self.max_num:
self.cnt = 0
re... | Python | zaydzuhri_stack_edu_python |
function Frame self
begin
set ret = call InvokeTypes 5 LCID 1 tuple 9 0 tuple
if ret is not none
begin
set ret = call Dispatch ret string Frame none
end
return ret
end function | def Frame(self):
ret = self._oleobj_.InvokeTypes(5, LCID, 1, (9, 0), (),)
if ret is not None:
ret = Dispatch(ret, u'Frame', None)
return ret | Python | nomic_cornstack_python_v1 |
function gen_seqs_multitrial self min_trial_len=2 max_trial_len=3 ntrials=2
begin
set xseq = array list
set yseq = array list
set tseq = array list
for trial in range ntrials
begin
set xseq_ = call gen_xseq_singletrial min_trial_len max_trial_len
set yseq_ = call xseq2yseq_singletrial xseq_
set tseq_ = call xseq2tseq_s... | def gen_seqs_multitrial(self,min_trial_len=2,max_trial_len=3,ntrials=2):
xseq = np.array([])
yseq = np.array([])
tseq = np.array([])
for trial in range(ntrials):
xseq_ = self.gen_xseq_singletrial(min_trial_len,max_trial_len)
yseq_ = self.xseq2yseq_singletrial(xseq_)
tseq_ = self.xseq2t... | Python | nomic_cornstack_python_v1 |
if delete not in My_list
begin
print string not exist in the list
end | if delete not in My_list:
print("not exist in the list") | Python | zaydzuhri_stack_edu_python |
comment !usr/bin/env python
comment -*- coding: utf-8 -*-
string @author: Jon Zhang @contact: zj.fly100@gmail.com @site: @version: 1.0 @license: @file: 11111.py @time: 2018-12-24 19:33 the line began to write the explanation and demonstration of this document
import os , sys
import time
import datetime
import logging
i... | #!usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Jon Zhang
@contact: zj.fly100@gmail.com
@site:
@version: 1.0
@license:
@file: 11111.py
@time: 2018-12-24 19:33
the line began to write the explanation and demonstration of this document
"""
import os,sys
import time
import datetime
import logging
import h... | Python | zaydzuhri_stack_edu_python |
string Code by bill 2/10/2018 This is a temporary script file.
set tuple a b = map int split input string Please input a number:
print string The sum of your two numbers is: a + b | """
Code by bill
2/10/2018
This is a temporary script file.
"""
a , b = map(int, input("Please input a number: ").split())
print ("The sum of your two numbers is: ", a + b)
| Python | zaydzuhri_stack_edu_python |
function get_analog_gen_scale itf log=false
begin
set par_idx = call GetParameterIndex string ANALOG string GEN_SCALE
if par_idx == - 1
begin
if log
begin
debug string No ANALOG:GEN_SCALE parameter!
end
return none
end
set n_items = call GetParameterLength par_idx
if n_items < 1
begin
if log
begin
debug string No item ... | def get_analog_gen_scale(itf, log=False):
par_idx = itf.GetParameterIndex('ANALOG', 'GEN_SCALE')
if par_idx == -1:
if log: logger.debug('No ANALOG:GEN_SCALE parameter!')
return None
n_items = itf.GetParameterLength(par_idx)
if n_items < 1:
if log: logger.debug('No item under ANAL... | Python | nomic_cornstack_python_v1 |
function ssf value name=none weight=1.0
begin
set content = call StringContent value
return call StaticField content name weight
end function | def ssf(value, name=None, weight=1.0):
content = StringContent(value)
return StaticField(content, name, weight) | Python | nomic_cornstack_python_v1 |
import io
import json
string Of each manga i need the address, the name, the last chapter read
comment returns a json object dumped, use loads to recover the dictionary
function readFile fileName
begin
set file = open fileName string r
set records = join string read lines file
close file
return records
end function
co... | import io
import json
"""
Of each manga i need the address, the name, the last chapter read
"""
#returns a json object dumped, use loads to recover the dictionary
def readFile(fileName):
file=open(fileName,"r")
records="".join(file.readlines())
file.close()
return records
#records: json object dumped... | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return call __str__
end function | def __repr__(self):
return self.__str__() | Python | nomic_cornstack_python_v1 |
function read_csv csvfilename
begin
set rows = list
with open csvfilename string rU as csvfile
begin
set file_reader = reader csvfile
for row in file_reader
begin
append rows row
end
end
return rows
end function | def read_csv(csvfilename):
rows = []
with open(csvfilename, "rU") as csvfile:
file_reader = csv.reader(csvfile)
for row in file_reader:
rows.append(row)
return rows | 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.