code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function local_request view method=string GET data=none view_args=none user=none api_key=none meta=none request_id=none
begin
if api_key is not none and user is not none
begin
raise call TypeError string local_request can only take an api_key or a user, not both.
end
if not view_args
begin
set view_args = dict
end
set... | def local_request(
view,
method='GET',
data=None,
view_args=None,
user=None,
api_key=None,
meta=None,
request_id=None,
):
if api_key is not None and user is not None:
raise TypeError(
"local_request can only take an api_key or a user, not both."
)
if ... | Python | nomic_cornstack_python_v1 |
function discretize self a env
begin
if length arities > 0
begin
if control == string conformant
begin
set index = 0
set output = list
for arities in arities
begin
set local_output = list
for arity in arities
begin
set local_output = local_output + list min integer call cdf a at index * arity arity - 1
set index = in... | def discretize(self, a, env):
if len(self.arities) > 0:
if self.control == "conformant":
index = 0
output = []
for arities in self.arities:
local_output = []
for arity in arities:
local_ou... | Python | nomic_cornstack_python_v1 |
function uploadcomptesting self
begin
call printer string *********************************************************************************
call printer string ***************************UPLOAD COMPONENT TESTING******************************
call printer string **********************************************************... | def uploadcomptesting(self):
self.rdmc.ui.printer(
"\n*************************************************"
"********************************\n"
)
self.rdmc.ui.printer(
"***************************UPLOAD "
"COMPONENT TESTING***************************... | Python | nomic_cornstack_python_v1 |
from sys import maxsize , stdin
function solve packages package_index balanced_weight groups stats seen
begin
if stats >= get seen groups tuple maxsize maxsize
begin
return tuple maxsize maxsize
end
set seen at groups = stats
if package_index == length packages
begin
return stats
end
set package_weight = packages at pa... | from sys import maxsize, stdin
def solve(
packages,
package_index,
balanced_weight,
groups,
stats,
seen):
if stats >= seen.get(groups, (maxsize, maxsize)):
return maxsize, maxsize
seen[groups] = stats
if package_index == len(packages):
return stats
package_w... | Python | zaydzuhri_stack_edu_python |
function _generateVarsUpdateConstrained self traj ak gradient varK
begin
set varKPlus = dict
try
begin
set gain = ak at slice : :
end
except tuple TypeError IndexError
begin
comment technically incorrect, but missing ones will be *0 anyway just below here
set gain = list ak * length call getOptVars
end
set gain = c... | def _generateVarsUpdateConstrained(self,traj,ak,gradient,varK):
varKPlus = {}
try:
gain = ak[:]
except (TypeError,IndexError):
gain = [ak]*len(self.getOptVars()) #technically incorrect, but missing ones will be *0 anyway just below here
gain = np.asarray(gain)
for index,var in enumerate(... | Python | nomic_cornstack_python_v1 |
from tkinter import *
function closeapp
begin
global side
set side = integer get e1
comment lancement de la génération
call destroy
end function
set master = call Tk
call geometry string 300x300
title master string LE LABYRINTHIQUE
call place x=85 y=80
set e1 = call Entry master
set e2 = call Button master text=string ... | from tkinter import *
def closeapp():
global side
side = int(e1.get())
master.destroy() #lancement de la génération
master = Tk()
master.geometry("300x300")
master.title("LE LABYRINTHIQUE")
Label(master, text="Nombre de cases de côté").place(x=85, y=80)
e1 = Entry(master)
e2 = Button(mast... | Python | zaydzuhri_stack_edu_python |
function get_rule rule_id
begin
set rule = call fetchone
return rule
end function | def get_rule(rule_id):
rule = get_db().execute('SELECT i.*, c.name as category_name FROM ruleset i JOIN categories c ON i.category_id = c.id WHERE i.id = ?', (rule_id, )).fetchone()
return rule | Python | nomic_cornstack_python_v1 |
function transactionType self
begin
return details at string transactionType
end function | def transactionType(self):
return self.details['transactionType'] | Python | nomic_cornstack_python_v1 |
class Shark
begin
set location = string Ocean
set animal_type = string Fish
function __init__ self name age
begin
set name = name
set age = age
end function
function details self
begin
print string The name is + name + string with age of + string age + string location
end function
function swim_position self
begin
pri... | class Shark:
location = "Ocean"
animal_type = "Fish"
def __init__(self, name, age):
self.name = name
self.age = age
def details(self):
print("The name is "+self.name+" with age of "+str(self.age)+" ",self.location)
def swim_position(self):
print(self.name+"swims fo... | Python | zaydzuhri_stack_edu_python |
from langdetect import detect_langs
function calcIC cipher_text
begin
import collections
comment Calculate the Index of Coincidence of a piece of text. Allows for identification of a cipher encryption method.
comment Removing all non alpha and whitespace and uppercasing
set cipher_flat = join string list comprehension... | from langdetect import detect_langs
def calcIC(cipher_text):
import collections
#Calculate the Index of Coincidence of a piece of text. Allows for identification of a cipher encryption method.
# Removing all non alpha and whitespace and uppercasing
cipher_flat = "".join([x.upper() for x in cipher_text.spli... | Python | zaydzuhri_stack_edu_python |
import networkx as nx
from matching import HEM
from itertools import chain
function contracted_nodes G u v self_loops=true
begin
string Returns the graph that results from contracting ``u`` and ``v``. Node contraction identifies the two nodes as a single node incident to any edge that was incident to the original two n... | import networkx as nx
from matching import HEM
from itertools import chain
def contracted_nodes(G, u, v, self_loops=True):
"""Returns the graph that results from contracting ``u`` and ``v``.
Node contraction identifies the two nodes as a single node incident to any
edge that was incident to the original ... | Python | zaydzuhri_stack_edu_python |
function parse data
begin
assert type data == dict
set obj = parse Cluster data
set data = _unknown
comment future attributes (yet unknown) are not only ignored, but passed through!
set _unknown = dict
for k in data
begin
if k not in list
begin
set _unknown at k = data at k
end
end
set obj = call RouterCluster oid=oi... | def parse(data):
assert type(data) == dict
obj = Cluster.parse(data)
data = obj._unknown
# future attributes (yet unknown) are not only ignored, but passed through!
_unknown = {}
for k in data:
if k not in []:
_unknown[k] = data[k]
o... | Python | nomic_cornstack_python_v1 |
function s2eapp_image node key_image _paren_if_fun paren_if_app
begin
comment `image` is a function.
set tuple key image = key_image
assert key == S2EXP_NODE or key == S2EXP_SRT
set function = node at 0
set arguments = node at 1
set result = string
if paren_if_app
begin
set result = result + string (
end
set result = ... | def s2eapp_image(node, key_image, _paren_if_fun, paren_if_app):
(key, image) = key_image # `image` is a function.
assert key == t.S2EXP_NODE or key == t.S2EXP_SRT
function = node[0]
arguments = node[1]
result = ""
if paren_if_app:
result += "("
result += image(function[key], paren_i... | Python | nomic_cornstack_python_v1 |
function handle_file self queue
begin
set tuple address msg *args = call recv_multipart
try
begin
try
begin
set transfer = active at address
end
except KeyError
begin
set transfer = call new_transfer msg *args
set active at address = transfer
end
try else
begin
call current_transfer transfer msg *args
end
end
except Tr... | def handle_file(self, queue):
address, msg, *args = queue.recv_multipart()
try:
try:
transfer = self.active[address]
except KeyError:
transfer = self.new_transfer(msg, *args)
self.active[address] = transfer
else:
... | Python | nomic_cornstack_python_v1 |
function get_algorithm_module algorithm submodule
begin
return call import_module join string . list string algorithms algorithm submodule
end function | def get_algorithm_module(algorithm, submodule):
return import_module('.'.join(['algorithms', algorithm, submodule])) | Python | nomic_cornstack_python_v1 |
function add_patches self patch_list
begin
if not patch_list
begin
return
end
if all generator expression present_in_specfile for p in patch_list
begin
debug string All patches are present in the spec file, nothing to do here 🚀
return
end
debug string About to add patches { patch_list } to specfile.
if list comprehens... | def add_patches(self, patch_list: List[PatchMetadata]) -> None:
if not patch_list:
return
if all(p.present_in_specfile for p in patch_list):
logger.debug(
"All patches are present in the spec file, nothing to do here 🚀"
)
return
... | Python | nomic_cornstack_python_v1 |
while number > 0
begin
append binary number % 2
set number = number / 2
end
reverse binary
set length = length binary
set mid = length / 2
set k = 0
set flag = true
while k <= mid
begin
if binary at k != binary at length - k - 1
begin
set flag = false
end
end | while number > 0:
binary.append(number % 2)
number /= 2
binary.reverse()
length = len(binary)
mid = length / 2
k = 0
flag = True
while k <= mid:
if binary[k] != binary[length - k - 1]:
flag = False | Python | zaydzuhri_stack_edu_python |
comment !python
import os , shutil , glob
set bad_names = list string __pycache__ string .pytest_cache string .cache
set ignored_dirs = list string venv
function remove_autogenerated_objects dir
begin
set bad_dirs = list
for name in bad_names
begin
extend bad_dirs glob glob string ./**/ + name recursive=true
end
set s... | #!python
import os, shutil, glob
bad_names = ['__pycache__', '.pytest_cache', '.cache']
ignored_dirs = ['venv']
def remove_autogenerated_objects(dir):
bad_dirs = []
for name in bad_names:
bad_dirs.extend(glob.glob('./**/'+name, recursive=True))
skipped = []
print('removing:')
for dir in... | Python | zaydzuhri_stack_edu_python |
import datetime
set dateTimeObj = now
print string Current Date and Time: dateTimeObj | import datetime
dateTimeObj = datetime.datetime.now()
print('Current Date and Time:', dateTimeObj) | Python | iamtarun_python_18k_alpaca |
comment coding: utf-8
comment In[3]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
comment In[4]:
set size = 200
set x = call normal 0 2 size
set y = call normal - 0.5 3 size
comment In[5]:
figure figsize=tuple 8 6
scatter plt x y
call xlim - 8 8
call ylim - 10 10
comment In[11]:
function get_d... | # coding: utf-8
# In[3]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# In[4]:
size = 200
x = np.random.normal(0, 2, size)
y = np.random.normal(-0.5, 3, size)
# In[5]:
plt.figure(figsize=(8,6))
plt.scatter(x, y)
plt.xlim(-8, 8)
plt.ylim(-10, 10);
# In[11]:
def get_distance(p1, p... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import json
from collections import Counter
from pandas.io.json import json_normalize
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
class tweet_anal
begin
comment city to country mapping - to be extended after pooling all tweets and tracking all unique citie... | import pandas as pd
import numpy as np
import json
from collections import Counter
from pandas.io.json import json_normalize
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
class tweet_anal:
# city to country mapping - to be extended after pooling all tweets and tracking all unique cities pr... | Python | zaydzuhri_stack_edu_python |
function test_jsi18n_fallback_language self
begin
with call settings LANGUAGE_CODE=string fr ; call override string fi
begin
set response = get client string /jsi18n/
call assertContains response string il faut le traduire
call assertNotContains response string Untranslated string
end
end function | def test_jsi18n_fallback_language(self):
with self.settings(LANGUAGE_CODE='fr'), override('fi'):
response = self.client.get('/jsi18n/')
self.assertContains(response, 'il faut le traduire')
self.assertNotContains(response, "Untranslated string") | Python | nomic_cornstack_python_v1 |
function flatten_settings settings
begin
function _flatten settings o name=none
begin
for tuple key value in items variables o
begin
comment Remove any leading underscores on keys accessed through
comment properties for reporting.
if starts with key string _
begin
set key = key at slice 1 : :
end
if name
begin
set ke... | def flatten_settings(settings):
def _flatten(settings, o, name=None):
for key, value in vars(o).items():
# Remove any leading underscores on keys accessed through
# properties for reporting.
if key.startswith('_'):
key = key[1:]
if name:
... | Python | nomic_cornstack_python_v1 |
function create_random_policy pre_decision_states_copy post_decision_states
begin
comment Number of pre decision states to iterate over
set n_pre_states = length pre_decision_states_copy
comment initialize policy
set policy_copy = list none * n_pre_states
set counter = 0
for pre_state in range 0 n_pre_states
begin
comm... | def create_random_policy(pre_decision_states_copy, post_decision_states):
# Number of pre decision states to iterate over
n_pre_states = len(pre_decision_states_copy)
# initialize policy
policy_copy = [None] * n_pre_states
counter = 0
for pre_state in range(0, n_pre_states):
# Last ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3.8
comment -*- coding: utf-8 -*-
comment @Time : 2020/5/7 上午11:27
comment @Author: Jtyoui@qq.com
comment @Notes : flask 启动
import json
from flask import Flask , jsonify , request
from pyunit_time import Time
set app = call Flask __name__
function flask_content_type requests
begin
string 根据不同的co... | # !/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time : 2020/5/7 上午11:27
# @Author: Jtyoui@qq.com
# @Notes : flask 启动
import json
from flask import Flask, jsonify, request
from pyunit_time import Time
app = Flask(__name__)
def flask_content_type(requests):
"""根据不同的content_type来解析数据"""
if requests.method ... | Python | zaydzuhri_stack_edu_python |
function predict self X_pred
begin
comment make predictions
set P = call forward_prop X=X_pred W_1=W_1 W_2=W_2 W_3=W_3 f_1=f_1 f_2=f_2 f_3=f_3 mode=string prediction
set y_pred = reshape array list comprehension inverse transform lb p for p in P - 1
return y_pred
end function | def predict(self, X_pred):
# make predictions
P = self.forward_prop(X = X_pred,
W_1 = self.W_1, W_2 = self.W_2, W_3 = self.W_3,
f_1 = self.f_1, f_2 = self.f_2, f_3 = self.f_3,
mode = 'prediction')
y_pred = np.array(... | Python | nomic_cornstack_python_v1 |
from Basics1 import basics1
from Basics2 import basics2
call help basics1
call basics1
print string - * 25
call help basics2
call basics2
comment After functions in Basics2 come here.
comment global_demo = 0
comment def counter():
comment global global_demo
comment global_demo += 1
comment return global_demo
comment co... | from Basics1 import basics1
from Basics2 import basics2
help(basics1)
basics1()
print('-'*25)
help(basics2)
basics2()
# After functions in Basics2 come here.
# global_demo = 0
# def counter():
# global global_demo
# global_demo += 1
# return global_demo
# counter()
# counter()
# counter()
# counter()
# print(... | Python | zaydzuhri_stack_edu_python |
import datetime
import time
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.chart import Chart
from flatlib import const
from flatlib import aspects
comment Build a chart for a date and location
set data = call utcnow
set d = string format time data string %Y/%m/%d
set h = string fo... | import datetime
import time
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.chart import Chart
from flatlib import const
from flatlib import aspects
# Build a chart for a date and location
data = datetime.datetime.utcnow()
d = data.strftime('%Y/%m/%d')
h = data.strftime('%H:%M:%S')... | Python | zaydzuhri_stack_edu_python |
function denoise self inputs params
begin
info string >>> DENOISING
comment TODO move these somewhere else?
set SINGLES_FILT_WINDOW = 7
set SINGLES_FILT_WINDOW_MIN = decimal 2 / SINGLES_FILT_WINDOW
update params dict string window SINGLES_FILT_WINDOW ; string min_fract SINGLES_FILT_WINDOW_MIN
set tuple outputs params =... | def denoise(self, inputs, params):
logging.info(">>> DENOISING")
# TODO move these somewhere else?
SINGLES_FILT_WINDOW = 7
SINGLES_FILT_WINDOW_MIN = float(2) / SINGLES_FILT_WINDOW
params.update({"window": SINGLES_FILT_WINDOW, "min_fract": SINGLES_FILT_WINDOW_MIN})
... | Python | nomic_cornstack_python_v1 |
for i in range length bin_x_rev
begin
if bin_x_rev at i == string 1
begin
set ans = ans + a at i
end
end
print ans | for i in range(len(bin_x_rev)):
if bin_x_rev[i] == '1':
ans += a[i]
print(ans)
| Python | zaydzuhri_stack_edu_python |
class AuthException extends Exception
begin
function __init__ self status_code detail
begin
call __init__ detail
set detail = detail
set status_code = status_code
end function
end class
class RevokedApiKeyError extends AuthException
begin
function __init__ self
begin
set message = string Revoked API key
call __init__ s... | class AuthException(Exception):
def __init__(self, status_code, detail):
super().__init__(detail)
self.detail = detail
self.status_code = status_code
class RevokedApiKeyError(AuthException):
def __init__(self):
message = "Revoked API key"
super().__init__(status_code=40... | Python | zaydzuhri_stack_edu_python |
function _fetch_mrns self limit=none
begin
raise NotImplementedError
end function | def _fetch_mrns(self, limit: Optional[int] = None) -> Set[str]:
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function check_suid_bin self
begin
comment For GUID => find / -perm -g=s -type f 2>/dev/null
set cmd = string find / -perm -u=s -type f 2>/dev/null
set process = popen cmd shell=true stdout=PIPE stderr=PIPE
set tuple out err = communicate process
set suid = list
for file in split decode strip out string
begin
set fm =... | def check_suid_bin(self):
# For GUID => find / -perm -g=s -type f 2>/dev/null
cmd = 'find / -perm -u=s -type f 2>/dev/null'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
suid = []
for file in... | Python | nomic_cornstack_python_v1 |
function test_exists_change_index_success name
begin
set add_mock = call MagicMock return_value=true
set rehash_mock = call MagicMock return_value=true
set dunder_salt = dict string win_path.get_path call MagicMock side_effect=list list string foo string bar string baz name list name string foo string bar string baz ; ... | def test_exists_change_index_success(name):
add_mock = MagicMock(return_value=True)
rehash_mock = MagicMock(return_value=True)
dunder_salt = {
"win_path.get_path": MagicMock(
side_effect=[["foo", "bar", "baz", name], [name, "foo", "bar", "baz"]]
),
"win_path.add": add_moc... | Python | nomic_cornstack_python_v1 |
function test_put_list_new self
begin
save
assert equal count places 0
set put_data = list comprehension place_id for place in filter name=string Logan Square
call login username=username password=password
set uri = string /api/0.1/stories/%s/places/ % story_id
set response = put uri format=string json data=put_data
ca... | def test_put_list_new(self):
self.story.save()
self.assertEqual(self.story.places.count(), 0)
put_data = [place.place_id for place in
Place.objects.filter(name="Logan Square")]
self.api_client.client.login(username=self.username, password=self.password)
uri = ... | Python | nomic_cornstack_python_v1 |
import sys
comment Skeleton code for problem https://uchicago.kattis.com/problems/pet
comment Make sure you read the problem before editing this code.
comment You should focus only on implementing the solve() function.
comment Do not modify any other code.
comment This function takes a single parameters containing a li... | import sys
# Skeleton code for problem https://uchicago.kattis.com/problems/pet
#
# Make sure you read the problem before editing this code.
#
# You should focus only on implementing the solve() function.
# Do not modify any other code.
# This function takes a single parameters containing a list
# with exactly five e... | Python | zaydzuhri_stack_edu_python |
function _update_limits_from_api self
begin
string Call the service's API action to retrieve limit/quota information, and update AwsLimit objects in ``self.limits`` with this information.
debug string Setting DirectoryService limits from API
call connect
set resp = call get_directory_limits
set directory_limits = resp ... | def _update_limits_from_api(self):
"""
Call the service's API action to retrieve limit/quota information, and
update AwsLimit objects in ``self.limits`` with this information.
"""
logger.debug('Setting DirectoryService limits from API')
self.connect()
resp = self.... | Python | jtatman_500k |
from fer import FER
import cv2
import random
import math
import matplotlib.pyplot as plt
set img = call imread string ./images/testing/blurry images/im2.jpg
set detector = call FER mtcnn=true
comment print(detector.detect_emotions(img))
set tuple emotion score = call top_emotion img
print emotion score
if emotion == st... | from fer import FER
import cv2
import random
import math
import matplotlib.pyplot as plt
img = plt.imread("./images/testing/blurry images/im2.jpg")
detector = FER(mtcnn=True)
# print(detector.detect_emotions(img))
emotion, score = detector.top_emotion(img)
print(emotion,score)
if emotion == "... | Python | zaydzuhri_stack_edu_python |
import string
function sentence_count x
begin
set x = join string generator expression chr for chr in x
set x = replace x string string
set x = replace x string ? string .
set x = replace x string ! string .
set x = replace x string : string .
set x = replace x string ; string .
set sentence_file = split x string .
r... | import string
def sentence_count(x):
x = ''.join(chr for chr in x)
x = x.replace(' ', '')
x = x.replace('?','.')
x = x.replace('!','.')
x = x.replace(':','.')
x = x.replace(';','.')
sentence_file = x.split('.')
return len(sentence_file)
def word_count(x):
exclude = set... | Python | zaydzuhri_stack_edu_python |
function test_nested_adjoint_on_function
begin
function my_op
begin
call RX 0.123 wires=0
call RY 2.32 wires=0
call RZ 1.95 wires=0
end function
set dev = device string default.qubit wires=1
decorator call qnode dev
function my_circuit
begin
call call adjoint my_op
call Hadamard wires=0
call call adjoint call adjoint m... | def test_nested_adjoint_on_function():
def my_op():
qml.RX(0.123, wires=0)
qml.RY(2.32, wires=0)
qml.RZ(1.95, wires=0)
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def my_circuit():
adjoint(my_op)()
qml.Hadamard(wires=0)
adjoi... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment Information about all the attributes can be found here:
comment https://www.kaggle.com/c/allstate-claims-severity/data
comment The aim of the challenge is to predict the 'loss' based on the variables in the dataset. Hence, this is a regression problem.
comment In[28]:
comment Read raw data... | # coding: utf-8
# Information about all the attributes can be found here:
#
# https://www.kaggle.com/c/allstate-claims-severity/data
# The aim of the challenge is to predict the 'loss' based on the variables in the dataset. Hence, this is a regression problem.
# In[28]:
# Read raw data from the file
import num... | Python | zaydzuhri_stack_edu_python |
function __mcu_list self output path
begin
comment drop trailing and leading / from path
call eval_func _mcu_list path 0 output=output
end function | def __mcu_list(self, output, path):
# drop trailing and leading / from path
self.eval_func(_mcu_list, path, 0, output=output) | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
set path = string /Users/mhee4/cloud/webdriver/chromedriver
set driver = call Chrome path
get driver string https://www.google.com
print title
set search_box = call find_element_by_name string q
call send_keys string 아마존 웹 서비스
call submit | from selenium import webdriver
path = "/Users/mhee4/cloud/webdriver/chromedriver"
driver = webdriver.Chrome(path)
driver.get("https://www.google.com")
print(driver.title)
search_box = driver.find_element_by_name("q")
search_box.send_keys("아마존 웹 서비스")
search_box.submit() | Python | zaydzuhri_stack_edu_python |
function test_size
begin
assert size == 1
end function | def test_size():
assert Packet11.size == 1 | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
comment sample_code
comment 入力された値を返す
set a = input string コードを入力してください:
print a | # coding:utf-8
# sample_code
# 入力された値を返す
a = input("コードを入力してください:")
print(a)
| Python | zaydzuhri_stack_edu_python |
function remove_organoid self
begin
set org = call value - 1
set folder = call text
set interval = call text
set removed = call text
set start = decimal call text
set tuple time size circularity = call read_data folder interval start
set organoids = call tolist
set to_remove = organoids at org
if removed == string
beg... | def remove_organoid(self):
org = self.sld.value()-1
folder = self.directory.text()
interval = self.interval.text()
removed = self.removed.text()
start = float(self.start.text())
time, size, circularity = functions.read_data(folder, interval, start)
organoid... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string Lists all State objects from the database hbtn_0e_6_usa
import sys
from model_state import Base , State
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
if __name__ == string __main__
begin
string All states via SQLAlchemy
set my_host = string localhost
set m... | #!/usr/bin/python3
""" Lists all State objects from the database hbtn_0e_6_usa
"""
import sys
from model_state import Base, State
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
if __name__ == "__main__":
""" All states via SQLAlchemy
"""
my_host = 'localhost'
my_port = 330... | Python | zaydzuhri_stack_edu_python |
from matplotlib.markers import MarkerStyle
import numpy as np
import matplotlib.pyplot as plt
set tuple fig ax = call subplots figsize=list 7 5
string plt.rcParams.update({ "text.usetex": True, "font.family": "sans-serif", "font.sans-serif": ["Helvetica"]})
set rcParams at string font.size = 12
set data = call genfromt... | from matplotlib.markers import MarkerStyle
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots(figsize=[7,5])
'''
plt.rcParams.update({
"text.usetex": True,
"font.family": "sans-serif",
"font.sans-serif": ["Helvetica"]})
'''
plt.rcParams['font.size'] = 12
data = np.genfromtxt('data/clea... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
import re
from collections import OrderedDict
set url = string https://pt.wikipedia.org/wiki/Lista_de_epis%C3%B3dios_de_Naruto_Shippuden
set regxWord_Naruto = string (:?N|n)aruto
set regxWord_Sasuke = string (:?S|s)asuke
set regexAll_Words = string \w+
function topWords all... | import requests
from bs4 import BeautifulSoup
import re
from collections import OrderedDict
url = "https://pt.wikipedia.org/wiki/Lista_de_epis%C3%B3dios_de_Naruto_Shippuden"
regxWord_Naruto = "(:?N|n)aruto"
regxWord_Sasuke = "(:?S|s)asuke"
regexAll_Words = "\w+"
def topWords(allwords):
dictCountWords = {}
to... | Python | zaydzuhri_stack_edu_python |
function txt_clean word_str min_len stopwords_list
begin
set clean_words = list
comment transforming the string of words into a list
set word_list = split word_str
for word in word_list
begin
set word_l = strip lower word
if is alpha word_l
begin
if length word_l > min_len
begin
if word_l not in stopwords_list
begin
a... | def txt_clean(word_str, min_len, stopwords_list):
clean_words = []
word_list = word_str.split() #transforming the string of words into a list
for word in word_list:
word_l = word.lower().strip()
if word_l.isalpha():
if len(word_l) > min_len:
if word_l not in stopw... | Python | nomic_cornstack_python_v1 |
function test_get_teamschedule self
begin
set msg = string Response status is not 200
set response = call get_teamschedule team_id
assert equal status_code 200 msg
end function | def test_get_teamschedule(self):
msg = "Response status is not 200"
response = self.api.get_teamschedule(self.team_id)
self.assertEqual(response.status_code, 200, msg) | Python | nomic_cornstack_python_v1 |
from django import forms
from django.contrib.auth.models import UnicodeUsernameValidator
from models import User
class UserRegistrationForm extends Form
begin
set full_name = call CharField max_length=100 required=true
set username = call CharField max_length=150 help_text=string REQUIRED validators=list call UnicodeUs... | from django import forms
from django.contrib.auth.models import UnicodeUsernameValidator
from .models import User
class UserRegistrationForm(forms.Form):
full_name = forms.CharField(max_length=100, required=True)
username = forms.CharField(
max_length=150,
help_text='REQUIRED',
vali... | Python | zaydzuhri_stack_edu_python |
function egyptian_multiplication a n
begin
function isodd n
begin
string returns True if n is odd
return n ? 1 == 1
end function
if n == 1
begin
return a
end
if n == 0
begin
return 0
end
if call isodd n
begin
return call egyptian_multiplication a + a n // 2 + a
end
else
begin
return call egyptian_multiplication a + a n... | def egyptian_multiplication(a, n):
def isodd(n):
"""
returns True if n is odd
"""
return n & 0x1 == 1
if n == 1:
return a
if n == 0:
return 0
if isodd(n):
return egyptian_multiplication(a + a, n // 2) + a
else:
return egyptian_multipl... | Python | nomic_cornstack_python_v1 |
for i in b
begin
while a % i == 0
begin
append primes i
set a = a / i
continue
end
end
if primes == list
begin
append primes a
end
primes
function prime_factorization a
begin
set b = range 2 a
set primes = list
for i in b
begin
while a % i == 0
begin
append primes i
set a = a / i
end
end
if primes == list
begin
appe... | for i in b:
while a % i == 0:
primes.append(i)
a = a/i
continue
if primes == []:
primes.append(a)
primes
def prime_factorization(a):
b = range(2,a)
primes = []
for i in b:
while a % i == 0:
primes.append(i)
a = a/i
if primes == []:
... | Python | zaydzuhri_stack_edu_python |
from __future__ import print_function
from IPython.display import clear_output
function display_board
begin
global board
for i in range 9
begin
print string %s % string board at i end=string
if i in list 2 5 8
begin
print
continue
end
print string | end=string
end
end function
function place_marker marker position
begi... | from __future__ import print_function
from IPython.display import clear_output
def display_board():
global board
for i in range(9):
print(" %s "%(str(board[i])),end="")
if(i in [2,5,8]):
print()
continue
print("|",end="")
def place_marker(marker,positio... | Python | zaydzuhri_stack_edu_python |
import socket
import jim
import json
import argparse
set ADDRESS = string 127.0.0.1
set PORT = 7777
function create_parser
begin
set parser = call ArgumentParser description=string Parser
set parser_group = call add_argument_group title=string Parameters
call add_argument string -a string --addr default=ADDRESS help=st... | import socket
import jim
import json
import argparse
ADDRESS = '127.0.0.1'
PORT = 7777
def create_parser():
parser = argparse.ArgumentParser(description='Parser')
parser_group = parser.add_argument_group(title='Parameters')
parser_group.add_argument('-a', '--addr', default=ADDRESS, help='IP... | Python | zaydzuhri_stack_edu_python |
string A package to recover the pose and focal length of a camera given 3D pionts and their corresponding 2D projections. Includes functions that map from 3D to 2D projections and their derivatives (that's the core part). The camera has seven parameters (wx,wy,wz,tx,ty,tz,f). (wx,wy,wz) describe its rotation about the ... | """
A package to recover the pose and focal length of a camera given 3D
pionts and their corresponding 2D projections. Includes functions that
map from 3D to 2D projections and their derivatives (that's the core
part).
The camera has seven parameters (wx,wy,wz,tx,ty,tz,f). (wx,wy,wz)
describe its rotation about the or... | Python | zaydzuhri_stack_edu_python |
string Lists Consider a list (list = []). You can perform the following commands: 1 - insert i e: Insert integer "e" at position "i". 2 - print: Print the list. 3 - remove e: Delete the first occurrence of integer "e". 4 - append e: Insert integer "e" at the end of the list. 5 - sort: Sort the list. 6 - pop: Pop the la... | """Lists
Consider a list (list = []). You can perform the following commands:
1 - insert i e: Insert integer "e" at position "i".
2 - print: Print the list.
3 - remove e: Delete the first occurrence of integer "e".
4 - append e: Insert integer "e" at the end of the list.
5 - sort: Sort the list.
6 - pop: Pop the last ... | Python | zaydzuhri_stack_edu_python |
function display_hours
begin
with open string tiger_den_hours.txt string r as hours ; open string hours.txt string w+ as o
begin
for line in hours
begin
write o line + string
print strip line
end
end
end function | def display_hours():
with open('tiger_den_hours.txt', 'r') as hours, open('hours.txt', 'w+') as o:
for line in hours:
o.write(line + '\n')
print(line.strip()) | Python | nomic_cornstack_python_v1 |
import numpy as np
from collections import Counter
comment for read and save files
function preprocess_input inpt
begin
if string / in inpt or string \ in inpt
begin
set plaintext = call read_file inpt
return replace lower plaintext string string
end
else
begin
return replace lower inpt string string
end
end function... | import numpy as np
from collections import Counter
# for read and save files
def preprocess_input(inpt):
if ('/' in inpt) or ('\\' in inpt):
plaintext = read_file(inpt)
return plaintext.lower().replace(" ", "")
else:
return inpt.lower().replace(" ", "")
def read_file(file_path):
t... | Python | zaydzuhri_stack_edu_python |
string 错误码装饰器,判断错误码重复以及对错误码集合处理
class ErrorCodeValidator
begin
set error_codes = dictionary
set http_codes = dictionary
comment 默认的共有的响应
set default_response = list
comment 只有登录之后才有的响应错误码
set login_response = list
decorator classmethod
function __check_code_repeat cls response_cls
begin
string error_code 为0时,可以重复定义响应类,... | """错误码装饰器,判断错误码重复以及对错误码集合处理
"""
class ErrorCodeValidator:
error_codes = dict()
http_codes = dict()
# 默认的共有的响应
default_response = list()
# 只有登录之后才有的响应错误码
login_response = list()
@classmethod
def __check_code_repeat(cls, response_cls):
"""
error_code 为0时,可以重复定义响应类,每个接口的返... | Python | zaydzuhri_stack_edu_python |
function primes n
begin
set sieve = list true * n
for i in range 3 integer n ^ 0.5 + 1 2
begin
if sieve at i
begin
set sieve at slice i * i : : 2 * i = list false * n - i * i - 1 / 2 * i + 1
end
end
return list 2 + list comprehension i for i in range 3 n 2 if sieve at i
end function | def primes(n):
sieve = [True] * n
for i in range(3, int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in range(3,n,2) if sieve[i]] | Python | nomic_cornstack_python_v1 |
function data_store_folder_zip request res_id=none
begin
set res_id = get POST string res_id res_id
if res_id is none
begin
return call HttpResponse string Bad request - resource id is not included status=HTTP_400_BAD_REQUEST
end
set res_id = strip string res_id
try
begin
set tuple resource _ user = call authorize requ... | def data_store_folder_zip(request, res_id=None):
res_id = request.POST.get('res_id', res_id)
if res_id is None:
return HttpResponse('Bad request - resource id is not included',
status=status.HTTP_400_BAD_REQUEST)
res_id = str(res_id).strip()
try:
resour... | Python | nomic_cornstack_python_v1 |
function pi_archimedes num
begin
set polygon_edge_length_squared = 2.0
set polygon_sides = 4
for i in range num
begin
set polygon_edge_length_squared = 2 - 2 * square root 1 - polygon_edge_length_squared / 4
set polygon_sides = polygon_sides * 2
end
return tuple polygon_sides * square root polygon_edge_length_squared /... | def pi_archimedes(num):
polygon_edge_length_squared = 2.0
polygon_sides = 4
for i in range(num):
polygon_edge_length_squared = 2 - 2 * math.sqrt(1 - polygon_edge_length_squared / 4)
polygon_sides *= 2
return polygon_sides * math.sqrt(polygon_edge_length_squared) / 2, polygon_sides | Python | nomic_cornstack_python_v1 |
function reverse_odd txt
begin
return join string list comprehension if expression length word % 2 != 0 then word at slice : : - 1 else word for word in split txt
end function | def reverse_odd(txt):
return " ".join([word[::-1] if len(word)%2!=0 else word for word in txt.split()])
| Python | zaydzuhri_stack_edu_python |
function get_timeval
begin
return call convert_timeval time
end function | def get_timeval():
return convert_timeval(time.time()) | Python | nomic_cornstack_python_v1 |
import quandl
import pandas as pd
from quandl_data.config import AUTH_TOKEN
from utils.folders import create_dir
set MONTH_TICKERS = list string F string G string H string J string K string M string N string Q string U string V string X string Z
set QUARTER_TICKERS = list string H string M string U string Z
function ge... | import quandl
import pandas as pd
from quandl_data.config import AUTH_TOKEN
from utils.folders import create_dir
MONTH_TICKERS = [
'F',
'G',
'H',
'J',
'K',
'M',
'N',
'Q',
'U',
'V',
'X',
'Z',
]
QUARTER_TICKERS = [
'H',
'M',
'U',
... | Python | zaydzuhri_stack_edu_python |
function write_num x y t pos
begin
call moveturtle x + 0.5 y + 0.5 t
write t pos
call moveturtle x y t
end function | def write_num(x,y,t,pos):
moveturtle(x+0.5,y+0.5,t)
t.write(pos)
moveturtle(x,y,t) | Python | nomic_cornstack_python_v1 |
import BinaryTree
class Solution extends object
begin
function kthSmallest self root k
begin
string Get the kth smallest element from a given BST. Assume 1 <= k <= BST's total element
set dict = dict
call inOrderTraversal root 0 k dict
return dict at k
end function
function inOrderTraversal self node numPreviousElemen... | import BinaryTree
class Solution(object):
def kthSmallest(self, root, k):
'''Get the kth smallest element from a given BST. Assume 1 <= k <= BST's total element'''
dict = {}
self.inOrderTraversal(root, 0, k, dict)
return dict[k]
def inOrderTraversal(self, node, numPreviousElements, k, dict):
if node is Non... | Python | zaydzuhri_stack_edu_python |
function prepare self task node
begin
comment Not implemented. Try to keep as little state in the conductor as
comment possible.
pass
end function | def prepare(self, task, node):
# Not implemented. Try to keep as little state in the conductor as
# possible.
pass | Python | nomic_cornstack_python_v1 |
function build_expanding_path self X depth=3
begin
set feed = X
comment Loop for 4 blocks
for i in range depth
begin
comment Iteration for block i + 1
print num_features at slice : : - 1 at i
comment Deconvolution Layer 1 with stride = 2
set deconv1 = call conv2d_transpose inputs=feed filters=num_features at slice :... | def build_expanding_path(self, X, depth = 3):
feed = X
# Loop for 4 blocks
for i in range(depth):
# Iteration for block i + 1
print(self.num_features[::-1][i])
# Deconvolution Layer 1 with stride = 2
deconv1 = tf.layers.conv2d_transpose(
... | Python | nomic_cornstack_python_v1 |
function _get_info_by_testcase self
begin
set tests_by_testcase = dict
for tests in tuple successes failures errors
begin
for test_info in tests
begin
if not is instance test_info _TestInfo
begin
print string Unexpected test result type: %r % tuple test_info
continue
end
set testcase = type test_method
comment Ignore ... | def _get_info_by_testcase(self):
tests_by_testcase = {}
for tests in (self.successes, self.failures, self.errors):
for test_info in tests:
if not isinstance(test_info, _TestInfo):
print("Unexpected test result type: %r" % (test_info,))
... | Python | nomic_cornstack_python_v1 |
function remove_char s char
begin
set s = replace s char string
return s
end function
call remove_char s string l | def remove_char(s, char):
s = s.replace(char, '')
return s
remove_char(s, 'l')
| Python | flytech_python_25k |
string valued_stock_PER.py Low PER + Low Debt Ratio 전략의 BackTesting
from pykrx import stock
import pandas as pd
from datetime import datetime
from time import sleep
import numpy as np
import math
import json
string Functions
function calc_yield **args
begin
string :param args: dictionary <keys> test_year = "2018" test_... | """
valued_stock_PER.py
Low PER + Low Debt Ratio 전략의 BackTesting
"""
from pykrx import stock
import pandas as pd
from datetime import datetime
from time import sleep
import numpy as np
import math
import json
"""
Functions
"""
def calc_yield(**args):
"""
:param args: dictionary
<key... | Python | zaydzuhri_stack_edu_python |
function close self
begin
pass
end function | def close(self, ):
pass | Python | nomic_cornstack_python_v1 |
function make_operation exclude=none
begin
function get_call func
begin
decorator wraps func
function wrapper data *args **kwargs
begin
comment exclude 'data', by default
set ignore = if expression exclude is none then list string data else exclude
comment grab parameters from `func` by binding signature
set name = __n... | def make_operation(*, exclude=None):
def get_call(func):
@wraps(func)
def wrapper(data, *args, **kwargs):
# exclude 'data', by default
ignore = ['data'] if exclude is None else exclude
# grab parameters from `func` by binding signature
name = func.__... | Python | nomic_cornstack_python_v1 |
function parse_tsv self config_filename
begin
for line in open config_filename
begin
set line = right strip line
if line == string or line at 0 == string #
begin
continue
end
if not barcode_definitions
begin
call _parse_tsv_defline line
set n = 3 + length barcode_definitions
end
else
begin
set fields = split line stri... | def parse_tsv(self, config_filename):
for line in open(config_filename):
line = line.rstrip()
if line == "" or line[0] == "#": continue
if not self.barcode_definitions:
self._parse_tsv_defline(line)
n = 3 + len(self.barcode_definitions)
... | Python | nomic_cornstack_python_v1 |
string .. module:: analysis_tools.experiment :synopsis: Maintains experimentally controlled parameters and derived quantities. Module Level Classes: ---------------------- Experiment : Maintain experimentally controlled parameter regimes and derived quantities. .. moduleauthor:: Riddhi Gupta <riddhi.sw@gmail.com>
from ... | '''
.. module:: analysis_tools.experiment
:synopsis: Maintains experimentally controlled parameters and derived quantities.
Module Level Classes:
----------------------
Experiment : Maintain experimentally controlled parameter regimes and
derived quantities.
.. moduleauthor:: Riddhi... | Python | zaydzuhri_stack_edu_python |
function create_parser self prog_name subcommand
begin
return call OptionParser prog=prog_name usage=call usage subcommand version=__version__ option_list=option_list
end function | def create_parser(self, prog_name, subcommand):
return OptionParser(prog=prog_name,
usage=self.usage(subcommand),
version=djeese.__version__,
option_list=self.option_list) | Python | nomic_cornstack_python_v1 |
function get_state all_data motion state_id
begin
set states = all_data at string motions/workflow at motion at string workflow_id at string states
for state in states
begin
if state at string id == state_id
begin
return state
end
end
raise call ProjectorElementException string motion { motion at string id } can not be... | def get_state(
all_data: AllData, motion: Dict[str, Any], state_id: int
) -> Dict[str, Any]:
states = all_data["motions/workflow"][motion["workflow_id"]]["states"]
for state in states:
if state["id"] == state_id:
return state
raise ProjectorElementException(
f"motion {motion[... | Python | nomic_cornstack_python_v1 |
comment Вводим через пробел наши числа
set a = list comprehension integer el for el in split input
function bubble_sort a
begin
comment Посколько значиние = true, цикл выполниться хотя бы один раз ( вдруг требутеся соврешить лишь одну перестоновку)
set k = true
while k
begin
set k = false
for i in range length a - 1
be... | #Вводим через пробел наши числа
a = [int(el) for el in input().split()]
def bubble_sort(a):
k = True #Посколько значиние = true, цикл выполниться хотя бы один раз ( вдруг требутеся соврешить лишь одну перестоновку)
while k:
k = False
for i in range(len(a) - 1):
if a[i] > a[i+1]: # ... | Python | zaydzuhri_stack_edu_python |
function gas self gas
begin
if gas is none
begin
comment noqa: E501
raise call ValueError string Invalid value for `gas`, must not be `None`
end
comment noqa: E501
if gas is not none and gas < 0
begin
comment noqa: E501
raise call ValueError string Invalid value for `gas`, must be a value greater than or equal to `0`
e... | def gas(self, gas):
if gas is None:
raise ValueError("Invalid value for `gas`, must not be `None`") # noqa: E501
if gas is not None and gas < 0: # noqa: E501
raise ValueError("Invalid value for `gas`, must be a value greater than or equal to `0`") # noqa: E501
self._g... | Python | nomic_cornstack_python_v1 |
function from_name cls name
begin
return call from_type_name none name
end function | def from_name(cls, name):
return cls.from_type_name(None, name) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
import numpy as np
comment In[2]:
comment column
set m = 30
comment rows
set n = 3
set file_name = string OSHD_Accuracy_Result.txt
set output_file = file_name at slice 0 : - 4 : + string .eps
comment In[3]:
comment print(output_file)
comment In[4]:
set ... | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# In[2]:
m= 30 ##column
n= 3 ##rows
file_name='OSHD_Accuracy_Result.txt'
output_file=file_name[0:-4]+".eps"
# In[3]:
#print(output_file)
# In[4]:
file1 = open(file_name, 'r')
Lines = file1.readlines()
count = 1
# Strips the newline charact... | Python | zaydzuhri_stack_edu_python |
string Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.
function bool_to_word boolean
begin
return if expression boolean == true then string Yes else string No
end function
print string Tests:
print call bool_to_word true
print call bool_to_word false | """
Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.
"""
def bool_to_word(boolean):
return 'Yes' if boolean == True else 'No'
print("Tests:")
print(bool_to_word(True))
print(bool_to_word(False)) | Python | zaydzuhri_stack_edu_python |
import torch
import numpy as np
import matplotlib.pyplot as plt
set x = linear space - 10 10 60
set ax = call gca
call set_color string none
call set_color string none
call set_ticks_position string bottom
call set_position tuple string data 0
call set_ticks_position string left
call set_position tuple string data 0
ca... | import torch
import numpy as np
import matplotlib.pyplot as plt
x = torch.linspace(-10, 10, 60)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'... | Python | zaydzuhri_stack_edu_python |
function cl node total l
begin
if node is none
begin
return
end
set bSum = value + total
if left is none and right is none
begin
append l bSum
return
end
call cl left bSum l
call cl right bSum l
end function
function branchSum tree
begin
set total = 0
set l = list
call cl tree total l
return l
end function | def cl(node, total, l):
if node is None:
return
bSum = node.value + total
if node.left is None and node.right is None:
l.append(bSum)
return
cl(node.left, bSum, l)
cl(node.right, bSum, l)
def branchSum(tree):
total = 0
l = []
cl(tree, total, l)
return l
... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set size = 10000
set arr = list - 1 * size
end function | def __init__(self):
self.size = 10000
self.arr = [-1] * self.size | Python | nomic_cornstack_python_v1 |
import sys
import os
import string_gen as STRS
import cracker as CRK
import reduction as RED
set REPS = 10
set ALPH_FILE = string alph_file.txt
set PW_LEN = 3
set NUM_PWS = 10
set WORDS = call all_words_of_len PW_LEN
set WORDSS = call all_words_of_len PW_LEN + 1
comment len: 52
set ALPH_CAPS = call alphabet_ul
comment ... | import sys
import os
import string_gen as STRS
import cracker as CRK
import reduction as RED
REPS = 10
ALPH_FILE = 'alph_file.txt'
PW_LEN = 3
NUM_PWS = 10
WORDS = STRS.all_words_of_len(PW_LEN)
WORDSS = STRS.all_words_of_len(PW_LEN+1)
ALPH_CAPS = STRS.alphabet_ul() #len: 52
ALPH_CAPS_DIGS = STRS.alphabet_uld() #len:... | Python | zaydzuhri_stack_edu_python |
function add_navnodes self
begin
pass
end function | def add_navnodes(self):
pass | Python | nomic_cornstack_python_v1 |
function list self
begin
return dump
end function | def list(self):
return JSONResponse(self.request).data(items=self._get_agenda_items()).dump() | Python | nomic_cornstack_python_v1 |
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution
begin
function zigzagLevelOrder self root
begin
string :type root: TreeNode :rtype: List[List[int]]
if not root
begin
return list
end
... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not roo... | Python | zaydzuhri_stack_edu_python |
string 07. テンプレートによる文生成.
string 引数x, y, zを受け取り 「x時のyはz」という文字列を返す関数を実装せよ. さらに,x=12, y="気温", z=22.4として, 実行結果を確認せよ.
function use_template x y z
begin
string テンプレートによる文の生成を行う.
return format string {0}時の{1}は{2} x y z
end function
print call use_template 12 string 気温 22.4 | """07. テンプレートによる文生成."""
'''引数x, y, zを受け取り
「x時のyはz」という文字列を返す関数を実装せよ.
さらに,x=12, y="気温", z=22.4として,
実行結果を確認せよ.'''
def use_template(x, y, z):
"""テンプレートによる文の生成を行う."""
return "{0}時の{1}は{2}".format(x, y, z)
print(use_template(12, '気温', 22.4))
| Python | zaydzuhri_stack_edu_python |
function calculate_standard_deviation X
begin
comment Calculate the mean of the list
set mean = 0
for x in X
begin
set mean = mean + x
end
set mean = mean / length X
comment Calculate the variance of the list
set variance = 0
for x in X
begin
set variance = variance + x - mean ^ 2
end
set variance = variance / length X... | def calculate_standard_deviation(X):
# Calculate the mean of the list
mean = 0
for x in X:
mean += x
mean = mean/len(X)
# Calculate the variance of the list
variance = 0
for x in X:
variance += (x - mean)**2
variance = variance / len(X)
# Calculate the standard devi... | Python | jtatman_500k |
function is_pandigital n
begin
set lst = list string 1 string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9
set num = string n
set m = 2
while length num < 9
begin
set num = num + string n * m
set m = m + 1
end
if length num != 9
begin
return false
end
else
begin
for i in num
begin
if i in lst
begin
... | def is_pandigital(n):
lst = ['1','2','3','4','5','6','7','8','9']
num = str(n)
m = 2
while len(num)<9:
num+=str(n*m)
m+=1
if len(num)!=9:
return False
else:
for i in num:
if i in lst:
del lst[lst.index(i)]
else:
return False
if len(lst)==0:
return True
return False
def find_pandigital... | Python | zaydzuhri_stack_edu_python |
function has_double_strict pw
begin
set consecutive_runs = list pw at 0
for i in range 1 length pw
begin
if pw at i == consecutive_runs at - 1 at - 1
begin
set consecutive_runs at - 1 = consecutive_runs at - 1 + pw at i
end
else
begin
append consecutive_runs pw at i
end
end
for run in consecutive_runs
begin
if length r... | def has_double_strict(pw):
consecutive_runs = [pw[0]]
for i in range(1, len(pw)):
if pw[i] == consecutive_runs[-1][-1]:
consecutive_runs[-1] += pw[i]
else:
consecutive_runs.append(pw[i])
for run in consecutive_runs:
if len(run) == 2:
return True
return False | Python | nomic_cornstack_python_v1 |
function sumOfSquares x
begin
set summ = 0
for i in range x + 1
begin
set summ = summ + i * i
end
return summ
end function
function squareOfSums x
begin
set square = 0
for i in range x + 1
begin
set square = square + i
end
set square = square * square
return square
end function
print call squareOfSums value - call sumO... | def sumOfSquares(x):
summ = 0
for i in range(x+1):
summ += (i*i)
return summ
def squareOfSums(x):
square = 0
for i in range(x+1):
square += i
square *= square
return square
print (squareOfSums(value) - sumOfSquares(value))
| Python | zaydzuhri_stack_edu_python |
function test_invalid_port device port
begin
with raises ValueError
begin
call set_spi_config port 0 330000.0
end
end function | def test_invalid_port(device, port):
with pytest.raises(ValueError):
device.set_spi_config(port, 0, 330e3) | Python | nomic_cornstack_python_v1 |
function get_metric p_num total_num total_predicted_num
begin
set precision = if expression total_predicted_num != 0 then p_num * 1.0 / total_predicted_num * 100 else 0
set recall = if expression total_num != 0 then p_num * 1.0 / total_num * 100 else 0
set fscore = if expression precision != 0 or recall != 0 then 2.0 *... | def get_metric(p_num: int, total_num: int, total_predicted_num: int) -> Tuple[float, float, float]:
precision = p_num * 1.0 / total_predicted_num * 100 if total_predicted_num != 0 else 0
recall = p_num * 1.0 / total_num * 100 if total_num != 0 else 0
fscore = 2.0 * precision * recall / (precision + recall) ... | Python | nomic_cornstack_python_v1 |
import numpy as np
import random
import copy
import math
function prob dataset
begin
if length dataset == 0
begin
return 0
end
return sum dataset / length dataset
end function
function train_error dataset
begin
string TODO: Calculate the train error of the subdataset and return it. For a dataset with two classes: C(p) ... | import numpy as np
import random
import copy
import math
def prob(dataset):
if len(dataset) == 0:
return 0
return sum(dataset)/len(dataset)
def train_error(dataset):
'''
TODO:
Calculate the train error of the subdataset and return it.
For a dataset with two classes:
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.