code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment peewee is the object relational mapper.
from peewee import *
set db = call MySQLDatabase host=string localhost user=string root password=string database=string school
class Student extends Model
begin
comment student_id=PrimaryKeyField()
set student_id = call IntegerField
set name = call CharField
set maths = ... | from peewee import * ###peewee is the object relational mapper.
db=MySQLDatabase(host="localhost",user="root",password="",database="school")
class Student(Model):
# student_id=PrimaryKeyField()
student_id=IntegerField()
name=CharField()
maths=IntegerField()
english=IntegerField()
chemistry=Int... | Python | zaydzuhri_stack_edu_python |
function summary self
begin
return _summary
end function | def summary(self):
return self._summary | Python | nomic_cornstack_python_v1 |
function calibrate_chunk chunk_obj
begin
comment Modify weights
set tuple fwhm_min fwhm_max = call modify_weights output ionfactor ntot=ntot trim_start=trim_start
comment Run bbs
call format string calibrate-stand-alone -f {0} {1} {2} > {3}/logs/{4}_peeling_calibrate_timecorr.log 2>&1 output parset skymodel outdir logn... | def calibrate_chunk(chunk_obj):
# Modify weights
fwhm_min, fwhm_max = modify_weights(chunk_obj.output, chunk_obj.ionfactor,
ntot=chunk_obj.ntot, trim_start=chunk_obj.trim_start)
# Run bbs
subprocess.call("calibrate-stand-alone -f {0} {1} {2} > {3}/logs/"
"{4}_peeling_calibrate_timecorr.... | Python | nomic_cornstack_python_v1 |
import sqlite3 as sql
class SqlDb
begin
string Метод, создающий соединение с базой данных, либо новую базу данных(при её отсутствии по пути path_name)
function __init__ self bd_name
begin
set connect = call connect bd_name check_same_thread=false
set cursor = call cursor
set bd_name = bd_name at slice : - 3 :
if stri... | import sqlite3 as sql
class SqlDb:
"""Метод, создающий соединение с базой данных, либо новую базу данных(при её отсутствии по пути path_name)"""
def __init__(self, bd_name):
self.connect = sql.connect(bd_name, check_same_thread=False)
self.cursor = self.connect.cursor()
self.bd_name = ... | Python | zaydzuhri_stack_edu_python |
async function messages self ctx
begin
await call message_leaderboard ctx string messages
end function | async def messages(self, ctx):
await self.message_leaderboard(ctx, "messages") | Python | nomic_cornstack_python_v1 |
function diffusion self param signal noise s t=none
begin
comment B
set bsize = shape at 0
comment [B']
set time = if expression t is none then s else concatenate list s t axis=0
comment [B'] x 4
set tuple _ _ alpha_sq sigma_sq = call snr param at string logsnr time
if t is not none
begin
comment [B]
set tuple alpha_sq... | def diffusion(self,
param: flax.core.frozen_dict.FrozenDict,
signal: jnp.ndarray,
noise: jnp.ndarray,
s: jnp.ndarray,
t: Optional[jnp.ndarray] = None) -> \
Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
# B
... | Python | nomic_cornstack_python_v1 |
function u236
begin
set endf_data = environ at string OPENMC_ENDF_DATA
set filename = join path endf_data string neutrons string n-092_U_236.endf
return call from_endf filename
end function | def u236():
endf_data = os.environ['OPENMC_ENDF_DATA']
filename = os.path.join(endf_data, 'neutrons', 'n-092_U_236.endf')
return openmc.data.IncidentNeutron.from_endf(filename) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string reducer.py
import sys
import random
set current_count = random integer 1 5
set data = list
for line in stdin
begin
set tuple _ id = split strip line string 1
append data id
set current_count = current_count - 1
if current_count == 0
begin
print join string , data
set data = list
set c... | #!/usr/bin/python
"""reducer.py"""
import sys
import random
current_count = random.randint(1, 5)
data = []
for line in sys.stdin:
_, id = line.strip().split('\t', 1)
data.append(id)
current_count -= 1
if current_count == 0:
print(','.join(data))
data = []
current_count = rando... | Python | zaydzuhri_stack_edu_python |
function deletesession
begin
if linuxServerSessionId != none
begin
call linuxServerStopOperations linuxServerSessionId
call linuxServerDeleteSession linuxServerSessionId
set linuxServerSessionId = none
set sessionId = none
end
else
begin
print string There is currently no opened Linux sessions
end
end function | def deletesession():
if middleware.linuxServerSessionId != None:
middleware.ixn.linuxServerStopOperations(middleware.linuxServerSessionId)
middleware.ixn.linuxServerDeleteSession(middleware.linuxServerSessionId)
middleware.linuxServerSessionId = None
middleware.se... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return dumps _config
end function | def __repr__(self) -> str:
return json.dumps(self._config) | Python | nomic_cornstack_python_v1 |
comment MiniProject1
set prompt = string >
print string Please insert 2 verbs
set verb1 = input prompt
set verb2 = input prompt
print string Please enter 2 adjectives
set adjective1 = input prompt
set adjective2 = input prompt
print string Now enter a verb ending with -ed
set verbed = input prompt
print string Now ente... | #MiniProject1
prompt = '> '
print(f"Please insert 2 verbs")
verb1 = input(prompt)
verb2 = input(prompt)
print(f"Please enter 2 adjectives")
adjective1 = input(prompt)
adjective2 = input(prompt)
print(f"Now enter a verb ending with -ed")
verbed = input(prompt)
print(f"Now enter another verb ending wi... | Python | zaydzuhri_stack_edu_python |
function send_mail message_type etype=none ex=none tb=none msg=none
begin
comment Determine subject
if message_type == string critical
begin
set msg = join string call format_exception etype ex tb
set subject = format CRITICAL_SUBJECT etype=__name__ hostname=call gethostname
end
else
if message_type == string error
be... | def send_mail(message_type, etype=None, ex=None, tb=None, msg=None):
# Determine subject
if message_type == "critical":
msg = "".join(traceback.format_exception(etype, ex, tb))
subject = CRITICAL_SUBJECT.format(etype=etype.__name__, hostname=gethostname())
elif message_type == "error":
... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
comment 导入库
import numpy as np
comment 将numpy重新命名为np
set x = linear space 0 3 * pi 100
comment linspace 第一个参数序列起始值, 第二个参数序列结束值,第三个参数为样本数默认100
set y = sin x
comment 定义sin函数
comment 加上这一句就能在图表中显示中文
set rcParams at string font.sans-serif = list string SimHei
comment 用来正常显示负号
set rcParams at... | import matplotlib.pyplot as plt
#导入库
import numpy as np
#将numpy重新命名为np
x=np.linspace(0,3*np.pi,100)
# linspace 第一个参数序列起始值, 第二个参数序列结束值,第三个参数为样本数默认100
y=np.sin(x)
#定义sin函数
plt.rcParams['font.sans-serif']=['SimHei']#加上这一句就能在图表中显示中文
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
plt.subplot(1,2,1)
#是指一个1行2列的... | Python | zaydzuhri_stack_edu_python |
function gm_part2 gm_config kw_search
begin
set wiki_worker_pool = call WikiWorkerPool kw_search get gm_config string requests_per_second get gm_config string number_of_workers
run
end function | def gm_part2(gm_config, kw_search):
wiki_worker_pool = WikiWorkerPool(kw_search, gm_config.get("requests_per_second"), gm_config.get("number_of_workers"))
wiki_worker_pool.run() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import socket
import ast
import secrets
import hashlib
set TCP_IP = string 127.0.0.1
set TCP_PORT = 5003
set BUFFER_SIZE = 1024
set s = call socket AF_INET SOCK_STREAM
call bind tuple TCP_IP TCP_PORT
set users = list
comment ------METHODS----------
function encodeUser info
begin
comment Co... | #!/usr/bin/env python
import socket
import ast
import secrets
import hashlib
TCP_IP = '127.0.0.1'
TCP_PORT = 5003
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
users = [];
#------METHODS----------
def encodeUser(info):
users.append(ast.literal_eval(inf... | Python | zaydzuhri_stack_edu_python |
function tags_join tags
begin
import re
set parts = list
for t in tags
begin
comment if it contains space, place inside [[ .. ]]
if search string \s t
begin
append parts string [[%s]] % t
end
else
begin
append parts t
end
end
return join string parts
end function | def tags_join(tags):
import re
parts = []
for t in tags:
# if it contains space, place inside [[ .. ]]
if re.search(r'\s', t):
parts.append(u'[[%s]]' % t)
else:
parts.append(t)
return u' '.join(parts) | Python | nomic_cornstack_python_v1 |
function main
begin
import argparse
set prs = call ArgumentParser __doc__ formatter_class=ArgumentDefaultsHelpFormatter
call add_argument string --golr_url default=string https://solr.monarchinitiative.org/solr/golr/ type=str help=string Golr URL
call add_argument string -o default=none type=str help=string Specifies t... | def main():
import argparse
prs = argparse.ArgumentParser(__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
prs.add_argument('--golr_url', default='https://solr.monarchinitiative.org/solr/golr/', type=str,
help='Golr URL')
prs.add_ar... | Python | nomic_cornstack_python_v1 |
function load self s
begin
set _filename = s
comment self._isLoaded = True
with open s string r as f
begin
set _dict = load json f
end
end function | def load(self, s):
self._filename = s
# self._isLoaded = True
with open(s, 'r') as f:
self._dict = json.load(f) | Python | nomic_cornstack_python_v1 |
import os
import tempfile
import argparse
import json
function create_key key value storage
begin
if key in keys storage
begin
append storage at key value
end
else
begin
set data = list
append data value
set storage at key = data
end
end function
function get_value key storage
begin
if key in keys storage
begin
print ... | import os
import tempfile
import argparse
import json
def create_key(key, value, storage):
if key in storage.keys():
storage[key].append(value)
else:
data = []
data.append(value)
storage[key] = data
def get_value(key, storage):
if key in storage.keys():
print(*storage[key], sep=', ')
else:
print(None)... | Python | zaydzuhri_stack_edu_python |
comment input : n, arr1, arr2
function solution n arr1 arr2
begin
for tuple idx _ in enumerate arr1
begin
set arr1 at idx = call tentotwo arr1 at idx n
set arr2 at idx = call tentotwo arr2 at idx n
end
print arr1
print arr2
set arr3 = list
for idx in range n
begin
append arr3 string
for jdx in range n
begin
if arr1 at ... | # input : n, arr1, arr2
def solution(n, arr1, arr2):
for idx, _ in enumerate(arr1):
arr1[idx] = tentotwo(arr1[idx], n)
arr2[idx] = tentotwo(arr2[idx], n)
print(arr1)
print(arr2)
arr3 = list()
for idx in range(n):
arr3.append("")
for jdx in range(n):
if arr... | Python | zaydzuhri_stack_edu_python |
function tokenize_and_clean command
begin
set tokens = call word_tokenize command
set tokens = list comprehension lower token for token in tokens
comment Remove punctuations
set table = call maketrans string string replace punctuation string , string
set tokens = list comprehension call translate table for token in t... | def tokenize_and_clean(command):
tokens = word_tokenize(command)
tokens = [token.lower() for token in tokens]
# Remove punctuations
table = str.maketrans('', '', punctuation.replace(',', ''))
tokens = [token.translate(table) for token in tokens]
# Remove useless tokens
stop_words = set(sto... | Python | nomic_cornstack_python_v1 |
function setUp self
begin
delete
delete
delete
set u = call User email=string test@test.com username=string testuser password=string HASHED_PASSWORD
add session u
commit session
set client = call test_client
end function | def setUp(self):
User.query.delete()
Message.query.delete()
Follows.query.delete()
self.u = User(
email="test@test.com",
username="testuser",
password="HASHED_PASSWORD"
)
db.session.add(self.u)
db.session.commit()
se... | Python | nomic_cornstack_python_v1 |
comment Redo with a base 'Character' class, with Hero and Goblin being subclasses of Character
comment Or not???
comment Hero Class
class Hero
begin
function __init__ self hero_health hero_power
begin
set hero_health = hero_health
set hero_power = hero_power
end function
end class
comment Goblin Class
class Goblin
begi... | ##Redo with a base 'Character' class, with Hero and Goblin being subclasses of Character
# Or not???
class Hero: #Hero Class
def __init__(self, hero_health, hero_power):
self.hero_health = hero_health
self.hero_power = hero_power
class Goblin: ... | Python | zaydzuhri_stack_edu_python |
comment Helps to interface with ram np arrays
class Ram extends object
begin
function __init__ self data
begin
set _data = data
end function
function uint8_at_addr self addr
begin
return _data at addr
end function
end class | # Helps to interface with ram np arrays
class Ram(object):
def __init__(self, data):
self._data = data
def uint8_at_addr(self, addr):
return self._data[addr] | Python | zaydzuhri_stack_edu_python |
import time
from sklearn import svm
from sklearn.decomposition import PCA
from sklearn.neural_network import MLPClassifier
set t0 = time
print string Importing data...
from data import *
print string Finished in %.3fs % time - t0
function score a b
begin
assert length a == length b
return sum map lambda x -> integer a ... | import time
from sklearn import svm
from sklearn.decomposition import PCA
from sklearn.neural_network import MLPClassifier
t0 = time.time()
print('Importing data...')
from data import *
print('Finished in %.3fs' % (time.time() - t0))
def score(a, b):
assert len(a) == len(b)
return sum(map(lambda x: int(a[x] ... | Python | zaydzuhri_stack_edu_python |
function minion_game string
begin
set stuscore = 0
set kevscore = 0
set length = length string
for i in range length
begin
if s at i in tuple string A string E string I string O string U
begin
set kevscore = kevscore + length - i
end
else
begin
set stuscore = stuscore + length - i
end
end
print if expression stuscore >... | def minion_game(string):
stuscore = kevscore = 0
length = len(string)
for i in range(length) :
if s[i] in ('A', 'E', 'I', 'O', 'U') :
kevscore += length - i
else :
stuscore += length - i
print ("Stuart " + str(stuscore) if stuscore > kevscore else "Kevin "... | Python | zaydzuhri_stack_edu_python |
function test_clean_with_name_and_path_conflict self
begin
set repository = call Repository name=name path=path tool=tool
with assert raises ValidationError as ctx
begin
with call assertNumQueries 1
begin
call clean
end
end
assert equal message_dict dict string name list string A repository with this name already exist... | def test_clean_with_name_and_path_conflict(self):
repository = Repository(name=self.repository.name, path=self.repository.path, tool=self.repository.tool)
with self.assertRaises(ValidationError) as ctx:
with self.assertNumQueries(1):
repository.clean()
self.assertEqual(ctx.exception.message_dict, {"name": ... | Python | nomic_cornstack_python_v1 |
function _WaitForEmulatorToStart self adb proc timeout
begin
set timeout_error = call DeviceBootTimeoutError _EMULATOR_TIMEOUT_ERROR % dict string timeout timeout
call PollAndWait func=lambda -> poll proc is none and call _IsEmulatorRunning adb expected_return=true timeout_exception=timeout_error timeout_secs=timeout ... | def _WaitForEmulatorToStart(self, adb, proc, timeout):
timeout_error = errors.DeviceBootTimeoutError(_EMULATOR_TIMEOUT_ERROR %
{"timeout": timeout})
utils.PollAndWait(func=lambda: (proc.poll() is None and
self.... | Python | nomic_cornstack_python_v1 |
function calc_spline_coefs self
begin
if not import_all
begin
comment we need to import the quantities
call importAll
end
set rSpline = call SPLINE dict string x es ; string y rmnc ; string kindspec compute_spline_type ; string ixm xm
set lSpline = call SPLINE dict string x es ; string y lmns ; string kindspec compute_... | def calc_spline_coefs(self):
if(not self.import_all):
self.importAll() # we need to import the quantities
self.rSpline = SPLINE.SPLINE({'x':self.es,
'y':self.rmnc,
'kindspec':self.compute_spline_type,
... | Python | nomic_cornstack_python_v1 |
comment abc084 d
import sys
from io import StringIO
import unittest
from unittest.signals import removeHandler
class TestClass extends TestCase
begin
function assertIO self input output
begin
set tuple stdout stdin = tuple stdout stdin
set tuple stdout stdin = tuple call StringIO call StringIO input
call resolve
seek s... | #
# abc084 d
#
import sys
from io import StringIO
import unittest
from unittest.signals import removeHandler
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sy... | Python | zaydzuhri_stack_edu_python |
import math
function get_primes limit
begin
comment sieve of eratosthenes
set primes = set range 2 limit
for i in range integer square root limit
begin
if i in primes
begin
for j in range i ^ 2 limit i
begin
discard primes j
end
end
end
return primes
end function
function problem50
begin
set primes = call get_primes 10... | import math
def get_primes(limit):
# sieve of eratosthenes
primes = set(range(2, limit))
for i in range(int(math.sqrt(limit))):
if i in primes:
for j in range(i**2, limit, i):
primes.discard(j)
return primes
def problem50():
primes = get_primes(1000000)
pri... | Python | zaydzuhri_stack_edu_python |
comment k-nearest neighbor classifiers
import sys , math
set numofclasses = 0
function normalizeDatasets someExamples someAttributes
begin
set normalizedAnyExample = list
set mathsArrays = list
for i in range 0 length someExamples at 0 - 1
begin
set aColumn = call select_column someExamples i
set values = call calcul... | #k-nearest neighbor classifiers
import sys,math
numofclasses = 0
def normalizeDatasets(someExamples,someAttributes):
normalizedAnyExample=[]
mathsArrays=[]
for i in range(0,len(someExamples[0])-1):
aColumn=select_column(someExamples, i)
values=calculateStandardDeviation(aColumn)
ma... | Python | zaydzuhri_stack_edu_python |
function __init__ self dim padding_type norm_layer use_dropout use_bias
begin
call __init__
set conv_block = call build_conv_block dim padding_type norm_layer use_dropout use_bias
end function | def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
super(ResnetBlock, self).__init__()
self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias) | Python | nomic_cornstack_python_v1 |
function makeTabCuts properties panel cuts
begin
call makeCuts properties panel cuts false
end function | def makeTabCuts(properties, panel, cuts):
makeCuts(properties, panel, cuts, False) | Python | nomic_cornstack_python_v1 |
function getCanonicalInfo self dfrm
begin
set canonical_pattern = compile string IsoId=([0-9A-Z-]+); Sequence=Displayed
set dfrm at string canonical_isoform = apply dfrm lambda x -> if expression not is instance x at string Alternative products (isoforms) float then join string , find all x at string Alternative produc... | def getCanonicalInfo(self, dfrm):
canonical_pattern = re.compile(r'IsoId=([0-9A-Z-]+); Sequence=Displayed')
dfrm['canonical_isoform'] = dfrm.apply(lambda x: ','.join(canonical_pattern.findall(x['Alternative products (isoforms)'])) if not isinstance(x['Alternative products (isoforms)'], float) else np.na... | Python | nomic_cornstack_python_v1 |
function find self vport_name=none emulation_host=none **filters
begin
return find call super IxnDhcp6Iana3Emulation self list string topology string deviceGroup string ipv4Loopback string ldpTargetedRouter string ldppwvpls string ipv6Loopback string ldpTargetedRouterV6 string ldpotherpws string ethernet string ipv6 st... | def find(self, vport_name=None, emulation_host=None, **filters):
return super(IxnDhcp6Iana3Emulation, self).find(["topology","deviceGroup","ipv4Loopback","ldpTargetedRouter","ldppwvpls","ipv6Loopback","ldpTargetedRouterV6","ldpotherpws","ethernet","ipv6","greoipv6","ipv4","greoipv4","dhcpv6client","dhcp6Iana3"... | Python | nomic_cornstack_python_v1 |
from datetime import datetime
from StatusMonitor import StatusMonitor
class OneLineStatusMonitor extends StatusMonitor
begin
string A status monitor that keeps itself constrainted to a single line. Good for running in a CLI. During a run, prints: 🤔 7 jobs running, 9 remaining. While the run boots, prints: Starting job... | from datetime import datetime
from .StatusMonitor import StatusMonitor
class OneLineStatusMonitor(StatusMonitor):
"""
A status monitor that keeps itself constrainted to a single line.
Good for running in a CLI.
During a run, prints:
🤔 7 jobs running, 9 remaining.
While the run boots, ... | Python | zaydzuhri_stack_edu_python |
function delete_task
begin
set rows = all
if length rows < 1
begin
print string Nothing to delete!
end
else
begin
print string Choose the number of the task you want to delete:
call print_rows rows 1
try
begin
set task_id = integer input string 0. Cancel
end
except any
begin
print string Invalid Entry
return none
end
i... | def delete_task():
rows = session.query(ToDo).order_by(ToDo.deadline).all()
if len(rows) < 1:
print('Nothing to delete!')
else:
print('Choose the number of the task you want to delete:')
print_rows(rows, 1)
try:
task_id = int(input('0. Cancel\n'))
except: ... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import re , math
comment Subtitle Time
class SubtitleTime extends object
begin
function __init__ self hours minutes seconds milliseconds
begin
set hours = integer hours
set minutes = integer minutes
set seconds = integer seconds
set milliseconds = integer milliseconds
end function
function... | # -*- coding: utf-8 -*-
import re, math
#
# Subtitle Time
#
class SubtitleTime (object):
def __init__(self, hours, minutes, seconds, milliseconds):
self.hours = int(hours)
self.minutes = int(minutes)
self.seconds = int(seconds)
self.milliseconds = int(milliseconds)
def toMilli... | Python | zaydzuhri_stack_edu_python |
import random
from Character import Character
import discord
from discord.ext import commands
class Kyle extends Character
begin
function __init__ self
begin
call __init__ string Kyle title=string The Aloof Alpha Male hp=2000 attack=160 dodge=30 crit=30 defense=25 gender=0 critValue=2 srec=2
set scount = 0
set Atk = 0
... | import random
from Character import Character
import discord
from discord.ext import commands
class Kyle(Character):
def __init__(self):
super().__init__("Kyle", title="The Aloof Alpha Male", hp=2000, attack=160, dodge=30, crit=30, defense=25,
gender=0, critValue=2, srec = 2)
... | Python | zaydzuhri_stack_edu_python |
function _get_id self player
begin
set name_tag = call player string td[data-stat="player"] a
set name = sub string .*/players/./ string string name_tag
return sub string \.html.* string name
end function | def _get_id(self, player):
name_tag = player('td[data-stat="player"] a')
name = re.sub(r'.*/players/./', '', str(name_tag))
return re.sub(r'\.html.*', '', name) | Python | nomic_cornstack_python_v1 |
import re
function binary string
begin
return not search string ^$|[A-Za-z2-9] string
end function
function binary_even string
begin
if call binary string and string at - 1 == string 0
begin
return true
end
else
begin
return false
end
end function
function hex string
begin
return not search string ^$|[G-Zg-z] string
en... | import re
def binary(string):
return not re.search(r'^$|[A-Za-z2-9]', string)
def binary_even(string):
if binary(string) and string[-1] == '0':
return True
else:
return False
def hex(string):
return not re.search(r'^$|[G-Zg-z]', string)
def word(string):
return re.search(r'[a-z]+... | Python | zaydzuhri_stack_edu_python |
for i in range 1 10001
begin
comment 문자로 받아들여서 각각 자리수 나옴
for j in string i
begin
set i = i + integer j
end
comment 비어있는 집합에 추가
add generated_number_set i
end
comment set - set = 차집합
set self_number_set = natural_number_set - generated_number_set
for i in sorted self_number_set
begin
print i
end | for i in range(1, 10001):
for j in str(i): # 문자로 받아들여서 각각 자리수 나옴
i += int(j)
generated_number_set.add(i) # 비어있는 집합에 추가
self_number_set = natural_number_set - generated_number_set #set - set = 차집합
for i in sorted(self_number_set):
prin... | Python | zaydzuhri_stack_edu_python |
function __init__ self num_latents=1024 activation=none layer_param=none **kwargs
begin
set shape_input = list 512 512 3
if layer_param is none
begin
set layer_param = encoder512_architecture
end
if activation is none
begin
set activation = encoder512_activations
end
call __init__ layer_param=layer_param num_latents=nu... | def __init__(self, num_latents=1024, activation=None, layer_param=None, **kwargs):
shape_input = [512,512,3]
if layer_param is None:
layer_param = ap.encoder512_architecture
if activation is None:
activation = ap.encoder512_activations
super().__init__(
layer_param=layer_param,
num_latents=num_late... | Python | nomic_cornstack_python_v1 |
class JustSomeExceptions
begin
function __enter__ self
begin
return none
end function
function __exit__ self exc_type exc_value traceback
begin
if exc_type is KeyError
begin
print string Key Error !
return true
end
if exc_type is IndexError
begin
print string Index Error !
return true
end
end function
end class
set cou... | class JustSomeExceptions:
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is KeyError:
print('Key Error !')
return True
if exc_type is IndexError:
print('Index Error !')
return True
count... | Python | zaydzuhri_stack_edu_python |
function area
begin
set a = pi * radius * radius
print string Area of Circle is : a
end function
function circum
begin
set c = 2 * pi * radius
print string Circumference of a Circle is : c
end function
call area
call circum
string | def area():
a=pi*radius*radius
print("Area of Circle is :",a)
def circum():
c=2*pi*radius
print("Circumference of a Circle is :",c)
area()
circum()
'''
'''
| Python | zaydzuhri_stack_edu_python |
function file_based_input_fn_builder input_file seq_length is_training drop_remainder batch_size buffer_size
begin
set name_to_features = dict string input_ids call FixedLenFeature list seq_length int64 ; string input_mask call FixedLenFeature list seq_length int64 ; string segment_ids call FixedLenFeature list seq_len... | def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder,batch_size,buffer_size):
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.Fixe... | Python | nomic_cornstack_python_v1 |
function created_timestamp_column self
begin
return _created_timestamp_column
end function | def created_timestamp_column(self):
return self._created_timestamp_column | Python | nomic_cornstack_python_v1 |
string Created on Dec 21, 2017 @author: venturf2 --- Day 21: Fractal Art --- You find a program trying to generate some art. It uses a strange process that involves repeatedly enhancing the detail of an image through a set of rules. The image consists of a two-dimensional square grid of pixels that are either on (#) or... | '''
Created on Dec 21, 2017
@author: venturf2
--- Day 21: Fractal Art ---
You find a program trying to generate some art. It uses a strange process that involves repeatedly enhancing the detail of an image through a set of rules.
The image consists of a two-dimensional square grid of pixels that are either on (#) or... | Python | zaydzuhri_stack_edu_python |
comment Copyright (c) 2019 Matthias Rolf, Oxford Brookes University
string
from cozmo.util import Pose , Position
import numpy as np
import math
class Frame2D
begin
function __init__ self
begin
set mat = call matrix list list 1.0 0.0 0.0 list 0.0 1.0 0.0 list 0.0 0.0 1.0
end function
decorator classmethod
function fro... | # Copyright (c) 2019 Matthias Rolf, Oxford Brookes University
'''
'''
from cozmo.util import Pose, Position
import numpy as np
import math
class Frame2D:
def __init__(self):
self.mat = np.matrix([[1., 0.,0.], [0., 1.,0.], [0., 0.,1.]])
@classmethod
def fromMat(cls,m: np.matrix):
f = ... | Python | zaydzuhri_stack_edu_python |
function color_to_words rgbs word2vec
begin
set max_tokens = max list comprehension length split name for name in rgbs
set tuple total_tokens dim = shape
set avg_vec = mean np syn0 axis=0
set empty_vec = zeros dim
set tuple X_train Y_train = tuple list list
set empty_rgb_vec = 3 * list 0
set mask_rgb_vec = 3 * list -... | def color_to_words(rgbs, word2vec):
max_tokens = max([len(name.split()) for name in rgbs])
(total_tokens, dim) = word2vec.syn0.shape
avg_vec = np.mean(word2vec.syn0, axis = 0)
empty_vec = np.zeros(dim)
(X_train, Y_train) = ([], [])
empty_rgb_vec = 3 * [0]
mask_rgb_vec = 3 * [-1]
for nam... | Python | nomic_cornstack_python_v1 |
function decode self file
begin
raise call NotImplementedError
end function | def decode(self, file):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function delete_all_jobs self jobstore=none
begin
call remove_all_jobs jobstore
end function | def delete_all_jobs(self, jobstore=None):
self._scheduler.remove_all_jobs(jobstore) | Python | nomic_cornstack_python_v1 |
import random
set name = input string Hello. What is your name?
print string Well, + name + string , I am thinking of a number from 1 to 20
set secretN = random integer 1 20
for i in range 1 7
begin
set guess = integer input string Take a guess:
if guess < secretN
begin
print string Your guess is too low
end
else
if gu... | import random
name = input('Hello. What is your name? ')
print('Well, ' +name+ ', I am thinking of a number from 1 to 20')
secretN = random.randint(1, 20)
for i in range(1, 7):
guess = int(input('Take a guess: '))
if guess<secretN:
print('Your guess is too low')
elif guess>secretN:
print('Your guess is too hi... | Python | zaydzuhri_stack_edu_python |
function _set_stops loop_data
begin
comment Set the text that contains stops
set loop_data at string stop = 0
set ix at tuple call contains string stop_ string stop = 1
return loop_data
end function | def _set_stops(loop_data):
# Set the text that contains stops
loop_data[u'stop'] = 0
loop_data.ix[loop_data.text.str.contains(u'stop_'),u'stop'] = 1
return loop_data | Python | nomic_cornstack_python_v1 |
string This script is an example on how to use the outputs of CoreML. This will return a dataFrame of predictions.
comment Auxiliar function that will read a folder
comment that contains the pickle files output of
comment CoreML.
import os
import sys
append path string /home/gari/Desktop/master_tesis_v3/MLDiagnosisTool... | """This script is an example
on how to use the outputs of CoreML.
This will return a dataFrame of
predictions.
"""
#Auxiliar function that will read a folder
# that contains the pickle files output of
# CoreML.
import os
import sys
sys.path.append("/home/gari/Desktop/master_tesis_v3/MLDiagnosisTool/")
sys.path.appen... | Python | zaydzuhri_stack_edu_python |
from collections import deque
set cups = deque map int split input
set bottles = deque map int split input
set wasted_water = 0
while cups and bottles
begin
set current_cup = call popleft
set current_bottle = pop bottles
set capacity_difference = current_cup - current_bottle
if capacity_difference > 0
begin
set current... | from collections import deque
cups = deque(map(int, input().split()))
bottles = deque(map(int, input().split()))
wasted_water = 0
while cups and bottles:
current_cup = cups.popleft()
current_bottle = bottles.pop()
capacity_difference = current_cup - current_bottle
if capacity_difference > 0:
... | Python | zaydzuhri_stack_edu_python |
comment Accept two int values from user and return their product.
comment If the product is greater than 1000, then return their sum
function prod num1 num2
begin
set value = num1 * num2
if value < 1000
begin
return value
end
else
begin
return num1 + num2
end
end function
set number1 = integer input string Enter first ... | #Accept two int values from user and return their product.
# If the product is greater than 1000, then return their sum
def prod (num1, num2):
value = num1 * num2
if(value<1000):
return value
else:
return num1+num2
number1 = int(input("Enter first number: "))
number2 = int(input("Enter sec... | Python | zaydzuhri_stack_edu_python |
import re
import collections
function words text
begin
return find all string [a-z]+ lower text
end function
function train features
begin
set model = default dictionary lambda -> 1
for f in features
begin
set model at f = model at f + 1
end
return model
end function
set NWORDS = train call words read open string big.... | import re
import collections
def words(text):
return re.findall('[a-z]+', text.lower())
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
NWORDS = train(words(open('big.txt').read()))
def edits1(word):
s = [(word[:i], word[i:]... | Python | iamtarun_python_18k_alpaca |
function message msgStr
begin
call notify_confirm msgStr editw=1
end function | def message(msgStr):
nps.notify_confirm(msgStr,editw=1) | Python | nomic_cornstack_python_v1 |
function getF *params
begin
set mode_flag = 0
for param in params
begin
if is instance param NDArray
begin
if mode_flag < 0
begin
raise call TypeError string Expect parameters to have consistent running mode, + format string got {} list comprehension type p for p in params
end
set mode_flag = 1
end
else
if is instance ... | def getF(*params):
mode_flag = 0
for param in params:
if isinstance(param, nd.NDArray):
if mode_flag < 0:
raise TypeError("Expect parameters to have consistent running mode," +
" got {}".format([type(p) for p in params]))
mode_flag ... | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
function image_agcwd img a=0.25 truncated_cdf=false
begin
set tuple h w = shape at slice : 2 :
set tuple hist bins = call histogram flatten img 256 list 0 256
set cdf = cumulative sum hist
set cdf_normalized = cdf / max
set prob_normalized = hist / sum
set unique_intensity = unique img
s... | import numpy as np
import cv2
def image_agcwd(img, a=0.25, truncated_cdf=False):
h,w = img.shape[:2]
hist,bins = np.histogram(img.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf / cdf.max()
prob_normalized = hist / hist.sum()
unique_intensity = np.unique(img)
intensity_max... | Python | zaydzuhri_stack_edu_python |
comment here's what we have so far
class User
begin
function __init__ self name email
begin
set name = name
set email = email
set balance = 0
end function
comment adding the deposit method
comment takes an argument that is the amount of the deposit
function make_deposit self amount
begin
comment the specific user's acc... | class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
self.balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.balance += amount # the specific... | Python | zaydzuhri_stack_edu_python |
function full_dependencies self
begin
if not _full_dependencies
begin
set _full_dependencies = call find_full_dependencies
end
return _full_dependencies
end function | def full_dependencies(self):
if not self._full_dependencies:
self._full_dependencies = self.find_full_dependencies()
return self._full_dependencies | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Oct 6 14:33:20 2016 @author: d_floriello Analisi Francia - Svizzera - PUN 2015
import pandas as pd
import numpy as np
comment from collections import OrderedDict
import matplotlib.pyplot as plt
from sklearn import linear_model
import scipy.stats
set fs = call read_exc... | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 6 14:33:20 2016
@author: d_floriello
Analisi Francia - Svizzera - PUN 2015
"""
import pandas as pd
import numpy as np
#from collections import OrderedDict
import matplotlib.pyplot as plt
from sklearn import linear_model
import scipy.stats
fs = pd.read_... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import yaml
function main
begin
with open string datacenter.yaml string r as yammy
begin
set pyyaml_read = read yammy
set pyyaml_load = dumps yammy
end
print pyyaml_read
print string ----------------------------------
print pyyaml_load
end function
call main | #!/usr/bin/python3
import yaml
def main():
with open("datacenter.yaml","r") as yammy:
pyyaml_read = yammy.read()
pyyaml_load = yaml.dumps(yammy)
print(pyyaml_read)
print("----------------------------------")
print(pyyaml_load)
main()
| Python | zaydzuhri_stack_edu_python |
from itertools import combinations
from math import gcd
function calc x1 x2
begin
if x1 > x2
begin
return tuple - 1 1
end
else
if x1 < x2
begin
return tuple 1 - 1
end
else
begin
return tuple 0 0
end
end function
function print_all i moons speeds
begin
print format string After {} steps: i
set ans = 0
for moon in moons
... | from itertools import combinations
from math import gcd
def calc(x1, x2):
if x1 > x2:
return (-1, 1)
elif x1 < x2:
return (1, -1)
else:
return (0, 0)
def print_all(i, moons, speeds):
print("After {} steps:".format(i))
ans = 0
for moon in moons:
print("({}) pos=<... | Python | zaydzuhri_stack_edu_python |
function permutation arr
begin
set res = list
set visited = set
function backtrack temp
begin
if length temp == length arr
begin
append res copy temp
return
end
for i in range length arr
begin
if i not in visited
begin
add visited i
append temp arr at i
call backtrack temp
remove visited i
pop temp
end
end
end functio... | def permutation(arr):
res = []
visited = set()
def backtrack(temp):
if len(temp) == len(arr):
res.append(temp.copy())
return
for i in range(len(arr)):
if i not in visited:
visited.add(i)
temp.append(arr[i])
... | Python | zaydzuhri_stack_edu_python |
import pymssql
comment 数据库服务器名称或IP
set server = string 192.168.0.141
comment 用户名
set user = string sa
comment 密码
set password = string 13486059134Chen
comment 数据库名称
set database = string new_con
set charset = string utf8
set conn = call connect server user password database charset
set cursor = call cursor
execute curs... | import pymssql
server = '192.168.0.141' # 数据库服务器名称或IP
user = 'sa' # 用户名
password = '13486059134Chen' # 密码
database = 'new_con' # 数据库名称
charset = 'utf8'
conn = pymssql.connect(server, user, password, database, charset)
cursor = conn.cursor()
cursor.execute('SELECT * FROM group_tb')
for row in cursor:
print([i... | Python | zaydzuhri_stack_edu_python |
comment To print the PID of thread and process
comment A comparison of using multiprocessing and multithread
import os
import multiprocessing
import threading
import time
function worker sign lock
begin
print string what
acquire lock
print sign call getpid
call doChore
release lock
end function
function doChore
begin
s... | # To print the PID of thread and process
# A comparison of using multiprocessing and multithread
import os
import multiprocessing
import threading
import time
def worker(sign, lock):
print("what")
lock.acquire()
print(sign, os.getpid())
doChore()
lock.release()
def doChore():
time.sleep(3)
... | Python | zaydzuhri_stack_edu_python |
import os
print string hello world, how are you?
set data_file = string MasterQuizHighscoreTest.txt
comment is_file_empty = (os.path.isfile(data_file)==False) or (os.stat(data_file).st_size == 0)
comment if (is_file_empty):
set result = read lines open data_file string r
print string data: + call result 0
open data_fil... | import os
print("hello world, how are you?")
data_file = "MasterQuizHighscoreTest.txt"
#is_file_empty = (os.path.isfile(data_file)==False) or (os.stat(data_file).st_size == 0)
#if (is_file_empty):
result = open(data_file,"r").readlines()
print ("data: "+result(0))
open(data_file,"w")
f.write("9");
data_file.close()
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Dec 28 14:44:18 2018 @author: arpit
comment -*- coding: utf-8 -*-
string Created on Fri Dec 28 14:44:18 2018 @author: arpit
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
set dataset = values
set N = 10000
set d = 10
set ads_selecte... | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 14:44:18 2018
@author: arpit
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 14:44:18 2018
@author: arpit
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
dataset = pd.read_csv('Ads_CTR_Optimisation.csv')... | Python | zaydzuhri_stack_edu_python |
import re
from collections import defaultdict , deque
with open string input.txt string r as f
begin
set tuple no_players last_marble = map int find all string \d+ read f
end
function solve no_players last_marble
begin
set circle = deque list 0 2 1
set players = default dictionary int
set curr_player = 3
for i in range... | import re
from collections import defaultdict, deque
with open('input.txt', 'r') as f:
no_players, last_marble = map(int, re.findall(r'\d+', f.read()))
def solve(no_players, last_marble):
circle = deque([0, 2, 1])
players = defaultdict(int)
curr_player = 3
for i in range(3, last_marble + 1):
... | Python | zaydzuhri_stack_edu_python |
function isSameKindAs self *args
begin
return call CompositeDragger_isSameKindAs self *args
end function | def isSameKindAs(self, *args):
return _osgManipulator.CompositeDragger_isSameKindAs(self, *args) | Python | nomic_cornstack_python_v1 |
function parse self plist
begin
if not is instance plist PacketList
begin
set plist = call PacketList plist
end
for pkt in plist at LLTD
begin
if LLTDQueryLargeTlv in pkt
begin
set key = string %s:%s:%d % tuple real_dst real_src seq
set types_offsets at key = tuple type offset
end
else
if LLTDQueryLargeTlvResp in pkt
b... | def parse(self, plist):
if not isinstance(plist, PacketList):
plist = PacketList(plist)
for pkt in plist[LLTD]:
if LLTDQueryLargeTlv in pkt:
key = "%s:%s:%d" % (pkt.real_dst, pkt.real_src, pkt.seq)
self.types_offsets[key] = (pkt[LLTDQueryLargeTlv].... | Python | nomic_cornstack_python_v1 |
function lmap f xs
begin
return list map f xs
end function | def lmap(f, xs):
return list(map(f, xs)) | Python | nomic_cornstack_python_v1 |
class Node extends object
begin
function __init__ self start end m
begin
set tuple start end m = tuple start end m
set tuple left right = tuple none none
end function
end class
class SegmentTree extends object
begin
function __init__ self A
begin
set A = A
set root = call build_tree 0 length A
end function
function bui... | class Node(object):
def __init__(self, start, end, m):
self.start, self.end, self.m = start, end, m
self.left, self.right = None, None
class SegmentTree(object):
def __init__(self, A):
self.A = A
self.root = self.build_tree(0, len(self.A))
def build_tree(self, s, e):
... | Python | zaydzuhri_stack_edu_python |
function moments img x0 y0 order active=- 1
begin
comment IMPORT STUFF
comment END IMPORT
comment Allows 'external' masking while invoking
if active == - 1
begin
set active = where img == img
end
set xabs = copy active at 1 + x0
set yabs = copy active at 0 + y0
set sumx = sum img at active * xabs
set sumy = sum img at ... | def moments(img,x0,y0,order,active=-1):
# IMPORT STUFF
# END IMPORT
# Allows 'external' masking while invoking
if active == -1 :
active = num.where(img == img)
xabs = active[1].copy() + x0
yabs = active[0].copy() + y0
sumx = num.sum(img[active] * xabs)
sumy ... | Python | nomic_cornstack_python_v1 |
function _AssName self t
begin
call _Name t
end function | def _AssName(self, t):
self._Name(t) | Python | nomic_cornstack_python_v1 |
for i in range n
begin
set tuple r g b w = map int split input
set num = r % 2 + g % 2 + b % 2 + w % 2
set less = min r min g b
if less == 0
begin
if num > 1
begin
print string No
end
else
begin
print string Yes
end
end
else
if num == 2
begin
print string No
end
else
begin
print string Yes
end
end | for i in range(n):
r,g,b,w= map(int,input().split())
num = r%2+g%2+b%2+w%2
less = min(r,min(g,b))
if less == 0:
if num > 1:
print('No')
else:
print('Yes')
else:
if num == 2:
print('No')
else:
print('Yes')
| Python | jtatman_500k |
function relu_backward_hook_function module grad_in grad_out
begin
comment Get last forward output
set corresponding_forward_output = forward_relu_outputs at - 1
set corresponding_forward_output at corresponding_forward_output > 0 = 1
set modified_grad_out = corresponding_forward_output * clamp torch grad_in at 0 min=0... | def relu_backward_hook_function(module, grad_in, grad_out):
# Get last forward output
corresponding_forward_output = self.forward_relu_outputs[-1]
corresponding_forward_output[corresponding_forward_output > 0] = 1
modified_grad_out = corresponding_forward_output * torch.c... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function decode self encoded first
begin
comment ans = [first]
comment for el in encoded:
comment ans.append(el ^ ans[-1])
comment return ans
return list accumulate list first + encoded lambda x y -> x ? y
end function
end class | class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
# ans = [first]
# for el in encoded:
# ans.append(el ^ ans[-1])
# return ans
return list(accumulate([first] + encoded, lambda x, y: x ^ y)) | Python | zaydzuhri_stack_edu_python |
function add_favo self id
begin
if id in fav_list
begin
remove fav_list id
call pickle_write
end
else
if id not in fav_list
begin
append fav_list id
call pickle_write
end
end function | def add_favo(self, id):
if id in self.fav_list:
self.fav_list.remove(id)
self.pickle_write()
elif id not in self.fav_list:
self.fav_list.append(id)
self.pickle_write() | Python | nomic_cornstack_python_v1 |
string this takes a newick string as instr and reads the string and makes the nodes and returns the root node
comment This code will let you walk through a tree
comment and act on nodes that you want to
import sys
from node import Node
comment This takes in the newick and the
comment seq data then puts them in a data
c... | """
this takes a newick string as instr
and reads the string and makes the
nodes and returns the root node
"""
# This code will let you walk through a tree
# and act on nodes that you want to
import sys
from node import Node
# This takes in the newick and the
# seq data then puts them in a data
# structure that can b... | Python | zaydzuhri_stack_edu_python |
function _get_all_sorted_knots x n_inner_knots=none inner_knots=none lower_bound=none upper_bound=none
begin
if lower_bound is none and size == 0
begin
raise call ValueError string Cannot set lower exterior knot location: empty input data and lower_bound not specified.
end
else
if lower_bound is none and size != 0
begi... | def _get_all_sorted_knots(x, n_inner_knots=None, inner_knots=None,
lower_bound=None, upper_bound=None):
if lower_bound is None and x.size == 0:
raise ValueError("Cannot set lower exterior knot location: empty "
"input data and lower_bound not specified.... | Python | nomic_cornstack_python_v1 |
comment ---------------- ####### ---- ## ---- ####### --------------------------------#
comment ---------------- ## ------- ##--## ------- ## ---------------| FAF-161 |--#
comment ---------------- ##### --- ######## --- ##### ---------------| Gore-Polina |--#
comment ---------------- ## ------ ## -- ## ------ ## ------... | ################################################################################
#---------------- ####### ---- ## ---- ####### --------------------------------#
#---------------- ## ------- ##--## ------- ## ---------------| FAF-161 |--#
#---------------- ##### --- ######## --- ##### ---------------| Gore-Polina |... | Python | zaydzuhri_stack_edu_python |
comment Code for stock problem (L01, 6.006 MIT EECS)
string You are given an array A[0..n-1] of stock prices for n consecutive days, and want to pick two days i0 and j0, with 0 <= i0 <= j0 < n such if you buy a share of stock on day i0 and sell it on day j0 you have maximum gain. That is, you want to maximize A[j0] - A... | # Code for stock problem (L01, 6.006 MIT EECS)
"""
You are given an array A[0..n-1] of stock prices for
n consecutive days, and want to pick two days i0 and j0,
with 0 <= i0 <= j0 < n such if you buy a share of stock on day
i0 and sell it on day j0 you have maximum gain. That is,
you want to maximize A[j0] - A[i0].
... | Python | zaydzuhri_stack_edu_python |
class node
begin
function __init__ self data
begin
set data = data
set next = none
end function
end class
class singlylist
begin
function __init__ self
begin
set head = none
end function
function display self
begin
set llist = list
set curNode = head
while curNode
begin
append llist data
set curNode = next
end
print l... | class node:
def __init__(self, data):
self.data = data
self.next = None
class singlylist:
def __init__(self):
self.head = None
def display(self):
llist = []
curNode = self.head
while curNode:
llist.append(curNode.data)
curNode = curNode.next
print(llist)
def append(self, data):
newNode ... | Python | zaydzuhri_stack_edu_python |
function goes_to_xb xa xb val
begin
if norm val - xb < 0.001
begin
return true
end
else
begin
return false
end
end function | def goes_to_xb(xa, xb, val):
if np.linalg.norm(val - xb) < .001:
return True
else:
return False | Python | nomic_cornstack_python_v1 |
string Created on Aug 9, 2018 @author: marcelo
comment Calling a JSON API
comment In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retr... | '''
Created on Aug 9, 2018
@author: marcelo
'''
#Calling a JSON API
#
#In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the f... | Python | zaydzuhri_stack_edu_python |
function cdf self points
begin
if _y_cdf is not none
begin
set x = points at tuple slice : : 0
set y = points at tuple slice : : 1
comment map the y coordinate first.
set y_out = call _y_cdf y
comment select which x quantile curve to use.
set x_curve = y_out - y_min * y_res / y_max - y_min
set x_curve = as type f... | def cdf(self, points):
if self._y_cdf is not None:
x = points[:, 0]
y = points[:, 1]
# map the y coordinate first.
y_out = self._y_cdf(y)
# select which x quantile curve to use.
x_curve = (y_out - self.y_min) * self.y_res / (self.y_max - ... | Python | nomic_cornstack_python_v1 |
import random
set g = 0
set ri = random integer 1 9
while true
begin
set _input = input string Enter Number or Exit:
if _input == string exit or string
begin
break
end
set _input = integer _input
if _input < ri
begin
print string Too low!
set g = g + 1
end
if _input > ri
begin
print string Too high!
set g = g + 1
end
... | import random
g = 0
ri = random.randint(1, 9)
while True:
_input = input("Enter Number or Exit: ")
if _input == "exit" or '':
break
_input = int(_input)
if _input < ri:
print("Too low!\n")
g+=1
if _input > ri:
print("Too high!\n")
g+=1
if _input == ri:
... | Python | zaydzuhri_stack_edu_python |
set number_one = input string Enter first number
set number_two = input string Enter second number
set totel = integer number_one + integer number_two
print string Total + string totel | number_one = input("Enter first number ")
number_two = input("Enter second number ")
totel = int(number_one) + int(number_two)
print("Total" + str(totel))
| Python | zaydzuhri_stack_edu_python |
import os
import numpy as np
import inspect
function get_root_dir
begin
set path_this_file = directory name path real path path __file__
return join string / split path_this_file string / at slice : - 1 :
end function
function get_var_name var
begin
set callers_local_vars = items f_locals
set name = list comprehension... | import os
import numpy as np
import inspect
def get_root_dir():
path_this_file = os.path.dirname(os.path.realpath(__file__))
return ('/').join(path_this_file.split('/')[:-1])
def get_var_name(var):
callers_local_vars = inspect.currentframe().f_back.f_locals.items()
name = [k for k, v in callers_local_va... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
import api
set pkname = string public_key
set skname = string private_key
set param = input string 输入参数文件路径(空路径使用默认参数):
call SM2_init param
while true
begin
set generate_keys = input string 是否需要生成密钥对(y/n):
if generate_keys == string y or generate_keys == string Y
begin
call SM2_key_pair_gen
print s... | #coding=utf-8
import api
pkname = "public_key"
skname = "private_key"
param = input('输入参数文件路径(空路径使用默认参数):')
api.SM2_init(param)
while True:
generate_keys = input("是否需要生成密钥对(y/n):")
if generate_keys == 'y' or generate_keys == 'Y':
api.SM2_key_pair_gen()
print("密钥对生成完毕")
break
elif ... | Python | zaydzuhri_stack_edu_python |
function days_in_gradebook_history_for_this_course self course_id
begin
set path = dict
set data = dict
set params = dict
comment REQUIRED - PATH - course_id
string The id of the contextual course for this API call
set path at string course_id = course_id
debug format string GET /api/v1/courses/{course_id}/gradebook... | def days_in_gradebook_history_for_this_course(self, course_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""The id of the contextual course for this API call"""
path["course_id"] = course_id
self.logger.debug("GET /api/v1/courses/{c... | Python | nomic_cornstack_python_v1 |
import collections
import fileinput
function I operands board
begin
set tuple m n = map int operands
return list comprehension list comprehension string O for _ in range n for _ in range m
end function
function C operands board
begin
set m = length board
set n = length board at 0
for i in range m
begin
for j in range n... | import collections
import fileinput
def I(operands, board):
m, n = map(int, operands)
return [['O' for _ in range(n)] for _ in range(m)]
def C(operands, board):
m = len(board)
n = len(board[0])
for i in range(m):
for j in range(n):
board[i][j] = 'O'
return board
def L(... | Python | zaydzuhri_stack_edu_python |
import face_recognition as fr
import cv2
import sys
import _pickle as pk
string command line args: imgfile, name_of_person_in_image
set tuple s img name = argv
if img == string cam
begin
set cam = call VideoCapture 0
while true
begin
set tuple ret frame = read cam
image show string Presiona A para guardar su rostro fra... | import face_recognition as fr
import cv2
import sys
import _pickle as pk
'''
command line args: imgfile, name_of_person_in_image
'''
s, img, name = sys.argv
if img == "cam":
cam = cv2.VideoCapture(0)
while True:
ret, frame = cam.read()
cv2.imshow('Presiona A para guardar su rostro', frame)
... | Python | zaydzuhri_stack_edu_python |
import os.path , time
from time import localtime , strftime
import shutil
import os
set firsttime = string input string first time ?(y/n)
set Frequency = string input string do you want to sort your files at regular frequency?(y/n)
if Frequency == string y
begin
set wahttime = integer input string What is the frequency... | import os.path, time
from time import localtime, strftime
import shutil
import os
firsttime=str(input("first time ?(y/n)"))
Frequency=str(input("do you want to sort your files at regular frequency?(y/n)"))
if Frequency=="y":
wahttime=int(input("What is the frequency? (in seconds)"))
if firsttime=="y":
... | Python | zaydzuhri_stack_edu_python |
function sentence_segment self doc candidate_pos lower
begin
set sentences = list
for sent in sents
begin
set selected_words = list
for token in sent
begin
comment Store words only with cadidate POS tag
if pos_ in candidate_pos and is_stop is false
begin
if lower is true
begin
append selected_words lower text
end
els... | def sentence_segment(self, doc, candidate_pos, lower):
sentences = []
for sent in doc.sents:
selected_words = []
for token in sent:
# Store words only with cadidate POS tag
if token.pos_ in candidate_pos and token.is_stop is False:
... | 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.