code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_search_multiple self
begin
comment Create tree
call test_insert_multiple
comment Search for existent values
assert equal search 2 true
assert equal search 3 true
assert equal search 3.5 true
assert equal search 4 true
assert equal search 4.5 true
assert equal search 5 true
assert equal search 5.5 true
ass... | def test_search_multiple(self):
# Create tree
self.test_insert_multiple()
# Search for existent values
self.assertEqual(self.btree.search(2), True)
self.assertEqual(self.btree.search(3), True)
self.assertEqual(self.btree.search(3.5), True)
self.assertEqua... | Python | nomic_cornstack_python_v1 |
string Aliasing of Tuple Objects: = ------------------------ => The process of giving another reference variable to the existing tuple is called aliasing. => The problem in this approach is by using one reference variable if we are changing content, then those changes will be reflected to the other reference variable. ... | """
Aliasing of Tuple Objects: =
------------------------
=> The process of giving another reference variable to the existing tuple is called aliasing.
=> The problem in this approach is by using one reference variable if we are changing
content, then those changes will be reflected to the other reference variabl... | Python | zaydzuhri_stack_edu_python |
function cur_epoch self epoch
begin
comment allow setter for training resumption
set _cur_epoch = epoch
end function | def cur_epoch(self, epoch: int):
# allow setter for training resumption
self._cur_epoch = epoch | Python | nomic_cornstack_python_v1 |
function run self x
begin
string *** YOUR CODE HERE ***
comment the function of three-layer net:f(x) = relu( relu(x ⋅ W1 + b1) ⋅ W2 + b2) ⋅ W3 + b3
comment the first hidden dimension
comment first layer function: relu(x ⋅ W1 + b1)
set t1 = linear x w1
set tb1 = call AddBias t1 b1
set dimension1 = relu tb1
comment the s... | def run(self, x):
"*** YOUR CODE HERE ***"
# the function of three-layer net:f(x) = relu( relu(x ⋅ W1 + b1) ⋅ W2 + b2) ⋅ W3 + b3
# the first hidden dimension
# first layer function: relu(x ⋅ W1 + b1)
t1 = nn.Linear(x, self.w1)
tb1 = nn.AddBias(t1, self.b1)
... | Python | nomic_cornstack_python_v1 |
function swap_items lst item1 item2
begin
set idx1 = index lst item1
set idx2 = index lst item2
set tuple lst at idx1 lst at idx2 = tuple lst at idx2 lst at idx1
return lst
end function | def swap_items(lst, item1, item2):
idx1 = lst.index(item1)
idx2 = lst.index(item2)
lst[idx1], lst[idx2] = lst[idx2], lst[idx1]
return lst | Python | iamtarun_python_18k_alpaca |
function savepoints fn
begin
return call _chain_decorators_on fn call emits_warning_on string mssql string Savepoint support in mssql is experimental and may lead to data loss. call no_support string access string not supported by database call no_support string sqlite string not supported by database call no_support s... | def savepoints(fn):
return _chain_decorators_on(
fn,
emits_warning_on('mssql', 'Savepoint support in mssql is experimental and may lead to data loss.'),
no_support('access', 'not supported by database'),
no_support('sqlite', 'not supported by database'),
no_support('sybase', ... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interpn
import os
comment Credit to Guillaume for density_scatter https://stackoverflow.com/a/53865762/12056557
function density_scatter x y label sort=true bins=20 **kwargs
begin
string Scatter plot colored by 2d histo... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interpn
import os
# Credit to Guillaume for density_scatter https://stackoverflow.com/a/53865762/12056557
def density_scatter(x, y, label, sort=True, bins=20, **kwargs):
"""
Scatter plot colored by 2d histogra... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import qutip as qt
function d2op N delta
begin
string Second derivative operator. This function returns a discretized second derivative operator using the central difference method. Args: N (int): The system dimention is given by `2*N + 1` delta (float): The step size ... | import numpy as np
import matplotlib.pyplot as plt
import qutip as qt
def d2op(N, delta):
"""Second derivative operator.
This function returns a discretized second derivative operator using the
central difference method.
Args:
N (int): The system dimention is given by `2*N + 1`
delt... | Python | zaydzuhri_stack_edu_python |
from Texto import obtener_texto
function palabras_validas texto_a_procesar
begin
set lista_palabra_valida = list
for palabra in split texto_a_procesar
begin
set palabra_sin = string
for letra in palabra
begin
if is alpha letra
begin
set palabra_sin = palabra_sin + letra
end
end
if length palabra_sin >= 5
begin
append... | from Texto import obtener_texto
def palabras_validas(texto_a_procesar):
lista_palabra_valida = []
for palabra in texto_a_procesar.split():
palabra_sin = ''
for letra in palabra:
if (letra.isalpha()):
palabra_sin += letra
if (len(palabra... | Python | zaydzuhri_stack_edu_python |
function _ _ visitor
begin
return call visit_false
end function | def _(_: AlwaysFalse, visitor: BooleanExpressionVisitor[T]) -> T:
return visitor.visit_false() | Python | nomic_cornstack_python_v1 |
function calculate_quantiles self levels
begin
comment quantiles = numpy.quantile(self.matrix, levels, axis=0)
set n_samples = shape at 1
set quantiles = zeros tuple length levels n_samples
for sample in range n_samples
begin
set values = matrix at tuple slice : : sample
set values = values at values != 0
set sample... | def calculate_quantiles(self, levels):
#quantiles = numpy.quantile(self.matrix, levels, axis=0)
n_samples = self.matrix.shape[1]
quantiles = numpy.zeros((len(levels), n_samples))
for sample in range(n_samples):
values = self.matrix[:, sample]
values = values[value... | Python | nomic_cornstack_python_v1 |
function reduce string
begin
for i in range length alphabet
begin
set letter = alphabet at i
set value1 = letter + capitalize letter
set value2 = capitalize letter + letter
set string = replace string value1 string
set string = replace string value2 string
end
return string
end function
set input = string
try
begin
wh... | def reduce(string):
for i in range(len(alphabet)):
letter = alphabet[i]
value1 = letter + letter.capitalize()
value2 = letter.capitalize() + letter
string = string.replace(value1, "")
string = string.replace(value2, "")
return string
input = ""
try:
while True:
... | Python | zaydzuhri_stack_edu_python |
import requests
import json
from constants import hue_username , bridge_ip , light_settings_path
class Light
begin
function __init__ self
begin
pass
end function
function get_light_settings self mood
begin
with open light_settings_path string r as f
begin
set data = load json f
return data at mood
end
end function
func... | import requests
import json
from constants import hue_username, bridge_ip, light_settings_path
class Light:
def __init__(self):
pass
def get_light_settings(self, mood):
with open(light_settings_path, 'r') as f:
data = json.load(f)
return data[mood]
def op... | Python | zaydzuhri_stack_edu_python |
function addRecipe self recipe
begin
set toAdd = none
if is instance recipe tuple CraftRecipe
begin
set toAdd = recipe
end
else
if is instance recipe tuple ShapedRecipe
begin
set toAdd = call fromBukkitRecipe recipe
end
else
if is instance recipe tuple ShapelessRecipe
begin
set toAdd = call fromBukkitRecipe recipe
end
... | def addRecipe(self, recipe):
toAdd = None
if isinstance(recipe, (CraftRecipe, )):
toAdd = recipe
else:
if isinstance(recipe, (ShapedRecipe, )):
toAdd = CraftShapedRecipe.fromBukkitRecipe(recipe)
elif isinstance(recipe, (ShapelessRecipe, )):
... | Python | nomic_cornstack_python_v1 |
from sklearn.datasets import load_iris
import tensorflow as tf
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
comment plt.switch_backend('agg')
comment 导入数据
set tuple data label = call load_iris true
comment 将样本标签转为独热编码的形式
with call Session as sess
begin
set label = run call one_ho... | from sklearn.datasets import load_iris
import tensorflow as tf
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# plt.switch_backend('agg')
data, label = load_iris(True) # 导入数据
with tf.Session() as sess: # 将样本标签转为独热编码的形式
label = sess.run(tf.one_hot(label, 3))
global_step = t... | Python | zaydzuhri_stack_edu_python |
function get_earliest_hash
begin
set earliest_hash = string
if is file path file_name
begin
set hash_list = call get_list_from_file string hash
if hash_list != false
begin
set length = length hash_list
set earliest_hash = hash_list at length - 1
end
else
begin
set earliest_hash = false
end
end
return earliest_hash
end... | def get_earliest_hash():
earliest_hash = ""
if (os.path.isfile(file_name)):
hash_list = get_list_from_file("hash")
if (hash_list != False):
length = len(hash_list)
earliest_hash = hash_list[length - 1]
else:
earliest_hash = False
return earliest_ha... | Python | nomic_cornstack_python_v1 |
function check_metrics self a
begin
if all list comprehension x in __all_metrics for x in a
begin
set metrics = a
end
else
begin
warning string metric a is not in the list of possible metrics, trying all metrics
set metrics = copy __all_metrics
end
end function | def check_metrics(self, a):
if all([x in self.__all_metrics for x in a]):
self.metrics = a
else:
self.logger.warning("metric a is not in the list of possible metrics, trying all metrics")
self.metrics = self.__all_metrics.copy() | Python | nomic_cornstack_python_v1 |
function fix_addresses start=none end=none
begin
if start in tuple none BADADDR
begin
set start = minEA
end
if end in tuple none BADADDR
begin
set end = maxEA
end
return tuple start end
end function | def fix_addresses(start=None, end=None):
if start in (None, idaapi.BADADDR):
start = idaapi.cvar.inf.minEA
if end in (None, idaapi.BADADDR):
end = idaapi.cvar.inf.maxEA
return start, end | Python | nomic_cornstack_python_v1 |
import copy
class DataSet extends object
begin
function __init__ self data_builder split_test_size
begin
set data_builder = data_builder
comment read!!
read data_builder
set data_builder_trn = deep copy data_builder
set data_builder_test = deep copy data_builder
set images = images at slice 0 : - split_test_size :
set... | import copy
class DataSet(object):
def __init__(self, data_builder, split_test_size):
self.data_builder = data_builder
self.data_builder.read() # read!!
self.data_builder_trn = copy.deepcopy(self.data_builder)
self.data_builder_test = copy.deepcopy(self.data_builder)
... | Python | zaydzuhri_stack_edu_python |
function rushdown self
begin
return _rushdown
end function | def rushdown(self):
return self._rushdown | Python | nomic_cornstack_python_v1 |
function test_one_way_om_cost self
begin
set m = call build_model dict string techs.test_transmission_elec.costs.monetary.om_prod 1 ; string links.a,b.techs.test_transmission_elec.switches.one_way true string simple_supply,two_hours
run build_only=true
set arg1 = _backend_model
set arg2 = string cost_var
set arg3 = lis... | def test_one_way_om_cost(self):
m = build_model(
{
"techs.test_transmission_elec.costs.monetary.om_prod": 1,
"links.a,b.techs.test_transmission_elec.switches.one_way": True,
},
"simple_supply,two_hours",
)
m.run(build_only=True)... | Python | nomic_cornstack_python_v1 |
string Created on Oct 20, 2020 @author: david Compare bayesian optimization on an eggholder function. Number of epochs: 200 Number of experiments: 10 Return: - (mean, variance) values for each epoch - time logs for each epoch - graph representing function space
import math
from skopt.space import Real
import matplotlib... | '''
Created on Oct 20, 2020
@author: david
Compare bayesian optimization on an eggholder function.
Number of epochs: 200
Number of experiments: 10
Return:
- (mean, variance) values for each epoch
- time logs for each epoch
- graph representing function space
'''
import math
from skopt.spac... | Python | zaydzuhri_stack_edu_python |
function map_constructor self loader node deep=false
begin
string Walk the mapping, recording any duplicate keys.
set mapping = dict
for tuple key_node value_node in value
begin
set key = call construct_object key_node deep=deep
set value = call construct_object value_node deep=deep
if key in mapping
begin
raise call ... | def map_constructor(self, loader, node, deep=False):
""" Walk the mapping, recording any duplicate keys.
"""
mapping = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
value = loader.construct_object(value_node, deep=... | Python | jtatman_500k |
function dstate wavefunc bosonic dbosonic dfermionic
begin
set batch_size = integer shape at 0
comment tensorflow bugs in gradients if s = 0 here
set s = 1e-08 * ones list batch_size
set tuple log_norm state = call wavefunc bosonic - reshape tf call cast s complex64 list batch_size + list 1 * 3 * dbosonic
if dfermionic... | def dstate(wavefunc, bosonic, dbosonic, dfermionic):
batch_size = int(bosonic.shape[0])
s = 1e-8 * tf.ones([batch_size]) # tensorflow bugs in gradients if s = 0 here
log_norm, state = wavefunc(bosonic - tf.reshape(tf.cast(s, tf.complex64), [batch_size] + [1] * 3) * dbosonic)
if dfermionic is not None:
... | Python | nomic_cornstack_python_v1 |
function enable_audio_video_cmd param enable
begin
string Return command to enable/disable all audio/video streams.
set cmd = string configManager.cgi?action=setConfig
set formats = list tuple string Extra 3 tuple string Main 4
if param == string Video
begin
append formats tuple string Snap 3
end
for tuple fmt num in f... | def enable_audio_video_cmd(param, enable):
"""Return command to enable/disable all audio/video streams."""
cmd = 'configManager.cgi?action=setConfig'
formats = [('Extra', 3), ('Main', 4)]
if param == 'Video':
formats.append(('Snap', 3))
for fmt, num in formats:
for i in range(num):
... | Python | jtatman_500k |
comment !usr/bin/python3
comment Password Generator
import string
from random import choice , randint
set characters = ascii_letters + punctuation + digits
set password = join string generator expression random choice characters for _ in range random integer 8 16
print password | #!usr/bin/python3
#Password Generator
import string
from random import choice, randint
characters = string.ascii_letters +string.punctuation +string.digits
password = ''.join(choice(characters) for _ in range(randint(8, 16)))
print(password) | Python | zaydzuhri_stack_edu_python |
comment Description of the problem can be found at http://codeforces.com/problemset/problem/714/B
set n = integer input
set l_n = list map int split input
set h = max l_n
set l = min l_n
for n in l_n
begin
if n != h and n != l
begin
if absolute n - h != absolute n - l
begin
print string NO
call quit
end
end
end
print s... | # Description of the problem can be found at http://codeforces.com/problemset/problem/714/B
n = int(input())
l_n = list(map(int, input().split()))
h = max(l_n)
l = min(l_n)
for n in l_n:
if n != h and n!= l:
if abs(n - h) != abs(n - l):
print("NO")
quit()
print("YES") | Python | zaydzuhri_stack_edu_python |
import math
set MODE_ZERO_2PI = 0
set MODE_MINUSPI_PI = 1
function fit angle mode
begin
if angle > 2 * pi
begin
set angle = angle - floor angle / 2 * pi * 2 * pi
end
else
if angle < 0
begin
set angle = angle - ceil angle / 2 * pi * 2 * pi
end
if mode == MODE_ZERO_2PI
begin
return angle
end
if mode == MODE_MINUSPI_PI an... | import math
MODE_ZERO_2PI = 0
MODE_MINUSPI_PI = 1
def fit(angle: float, mode: int) -> float:
if angle > 2 * math.pi:
angle -= math.floor(angle / (2 * math.pi)) * 2 * math.pi
elif angle < 0:
angle -= math.ceil(angle / (2 * math.pi)) * 2 * math.pi
if mode == MODE_ZERO_2PI:
return a... | Python | zaydzuhri_stack_edu_python |
function create_an_ipv4_object_from_a_cumulus_output_command context
begin
set object_03 = call _cumulus_ipv4_converter hostname=string leaf01 plateform=string linux cmd_output=call open_file path=string { FEATURES_OUTPUT_PATH } cumulus_show_interface.json filters=dict string get_loopback false ; string get_physical tr... | def create_an_ipv4_object_from_a_cumulus_output_command(context) -> None:
context.object_03 = _cumulus_ipv4_converter(
hostname="leaf01",
plateform="linux",
cmd_output=open_file(
path=f"{FEATURES_OUTPUT_PATH}cumulus_show_interface.json"
),
filters={
"... | Python | nomic_cornstack_python_v1 |
function traffic_limit_config self
begin
return get pulumi self string traffic_limit_config
end function | def traffic_limit_config(self) -> Optional['outputs.RuleRuleActionTrafficLimitConfig']:
return pulumi.get(self, "traffic_limit_config") | Python | nomic_cornstack_python_v1 |
function distance self *args
begin
return call Position2D_distance self *args
end function | def distance(self, *args):
return _almathswig.Position2D_distance(self, *args) | Python | nomic_cornstack_python_v1 |
function step4 self
begin
if b at k - 1 == string a
begin
if call ends string al
begin
pass
end
else
begin
return
end
end
else
if b at k - 1 == string c
begin
if call ends string ance
begin
pass
end
else
if call ends string ence
begin
pass
end
else
begin
return
end
end
else
if b at k - 1 == string e
begin
if call ends ... | def step4(self):
if self.b[self.k - 1] == 'a':
if self.ends("al"): pass
else: return
elif self.b[self.k - 1] == 'c':
if self.ends("ance"): pass
elif self.ends("ence"): pass
else: return
elif self.b[self.k - 1] == 'e':
if self.ends("er"): pass... | Python | nomic_cornstack_python_v1 |
import tkinter as tk
set win = call Tk
title win string Python GUI
call resizable 0 0
call mainloop | import tkinter as tk
win = tk.Tk()
win.title("Python GUI")
win.resizable(0, 0)
win.mainloop() | Python | zaydzuhri_stack_edu_python |
function do_hackedemails self arg
begin
set result = call submit session string hackedemails arg
call pp_json result
end function | def do_hackedemails(self, arg):
result = self.dispatch.submit(self.session, 'hackedemails', arg)
pp_json(result) | Python | nomic_cornstack_python_v1 |
function get_trackpoints self file_path activities
begin
set trackpoints = list
set activity_pointer = 0
set current_activity = activities at activity_pointer
set collecting_trackpoints = false
with open file_path as file
begin
set records = read lines file at slice 6 : :
if length records > 2500
begin
return trackp... | def get_trackpoints(self, file_path, activities):
trackpoints = []
activity_pointer = 0
current_activity = activities[activity_pointer]
collecting_trackpoints = False
with open(file_path) as file:
records = file.readlines()[6:]
if len(records) > 2500:
... | Python | nomic_cornstack_python_v1 |
function gender data
begin
set males = 0
set females = 0
for i in range length data
begin
if data at i at 1 == string M
begin
set males = males + 1
end
if data at i at 1 == string F
begin
set females = females + 1
end
end
return tuple males females
end function | def gender(data):
males=0
females = 0
for i in range(len(data)):
if (data[i][1]=='M'):
males += 1
if (data[i][1]=='F'):
females += 1
return males, females | Python | nomic_cornstack_python_v1 |
function _getData self data
begin
string Check that data is acceptable and return it. Default behavior is that the data has to be of type `dict`. In derived classes this method could for example allow `None` or empty strings and just return empty dictionary. :raises: ``ValidationError`` if data is missing or wrong type... | def _getData(self, data):
""" Check that data is acceptable and return it.
Default behavior is that the data has to be of type `dict`. In derived
classes this method could for example allow `None` or empty strings and
just return empty dictionary.
:raises: ``ValidationError`` i... | Python | jtatman_500k |
function handler self handler
begin
comment noqa: E501
if client_side_validation and handler is none
begin
comment noqa: E501
raise call ValueError string Invalid value for `handler`, must not be `None`
end
set _handler = handler
end function | def handler(self, handler):
if self.local_vars_configuration.client_side_validation and handler is None: # noqa: E501
raise ValueError("Invalid value for `handler`, must not be `None`") # noqa: E501
self._handler = handler | Python | nomic_cornstack_python_v1 |
function two_tailed_ztest success1 success2 total1 total2
begin
set p1 = success1 / decimal total1
set p2 = success2 / decimal total2
set p_pooled = success1 + success2 / decimal total1 + total2
set obs_ratio = 1.0 / total1 + 1.0 / total2
set var = p_pooled * 1 - p_pooled * obs_ratio
comment calculate z-score using for... | def two_tailed_ztest(success1, success2, total1, total2):
p1 = success1 / float(total1)
p2 = success2 / float(total2)
p_pooled = (success1 + success2) / float(total1 + total2)
obs_ratio = (1. / total1 + 1. / total2)
var = p_pooled * (1 - p_pooled) * obs_ratio
# calculate z-score using foregoin... | Python | nomic_cornstack_python_v1 |
function write_metadata self fp
begin
string Adds data to the metadata that's written. Parameters ---------- fp : pycbc.inference.io.BaseInferenceFile instance The inference file to write to.
call write_metadata fp
call write_stilde data
end function | def write_metadata(self, fp):
"""Adds data to the metadata that's written.
Parameters
----------
fp : pycbc.inference.io.BaseInferenceFile instance
The inference file to write to.
"""
super(BaseDataModel, self).write_metadata(fp)
fp.write_stilde(self.... | Python | jtatman_500k |
function BubbleSort aList
begin
for i in range length aList
begin
for j in range length aList - 1 - i
begin
if aList at j > aList at j + 1
begin
set tmp = aList at j
set aList at j = aList at j + 1
set aList at j + 1 = tmp
end
end
end
print aList
end function | def BubbleSort(aList):
for i in range(len(aList)):
for j in range(len(aList)-1-i):
if aList[j]>aList[j+1]:
tmp = aList[j]
aList[j] = aList[j+1]
aList[j+1]=tmp
print(aList)
| Python | zaydzuhri_stack_edu_python |
from flask import Flask , render_template , request
from datetime import datetime
set app = call Flask __name__
decorator call route string /
function idk
begin
return call render_template string index1.html now
end function
decorator call route string /dada
function hello
begin
print args
set naam = string manan
set d... | from flask import Flask,render_template, request
from datetime import datetime
app = Flask(__name__)
@app.route("/")
def idk():
return render_template("index1.html",now)
@app.route("/dada")
def hello():
print(request.args)
naam = 'manan'
data = [['Name','isAwesome','Spreadingfrom'],
['Manan',True,2002],
['... | Python | zaydzuhri_stack_edu_python |
comment Install required modules
import os
import sys
import time
call system string python -m pip install --upgrade -r requirements.txt
from chat import speech
from multiprocessing import Process , Manager
from user_interface import console
change directory directory name path real path path __file__
if __name__ == st... | # Install required modules
import os
import sys
import time
os.system('python -m pip install --upgrade -r requirements.txt')
from chat import speech
from multiprocessing import Process, Manager
from user_interface import console
os.chdir(os.path.dirname(os.path.realpath(__file__)))
if __name__ == '__main__':
w... | Python | zaydzuhri_stack_edu_python |
function convertTimeAndExtent self
begin
return call Submodel_convertTimeAndExtent self
end function | def convertTimeAndExtent(self):
return _libsbml.Submodel_convertTimeAndExtent(self) | Python | nomic_cornstack_python_v1 |
function setUp self
begin
set reporter = call Reporter
set loader = call TestLoader
end function | def setUp(self):
self.reporter = reporter.Reporter()
self.loader = pyunit.TestLoader() | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import sys
import io
from configparser import ConfigParser , MissingSectionHeaderError
class BotConfig extends object
begin
string Contains configuration for bot
set voice_dir = none
decorator classmethod
function __init__ cls path
begin
string Initialize bot. @param path (string): Path to... | # -*- coding: utf-8 -*-
import sys
import io
from configparser import ConfigParser, MissingSectionHeaderError
class BotConfig(object):
'''Contains configuration for bot'''
voice_dir = None
@classmethod
def __init__(cls, path):
'''Initialize bot.
@param path (string): Path to con... | Python | zaydzuhri_stack_edu_python |
function spline_branch self branch interval=1.0
begin
set number_of_points = integer round call branchLength branch / interval 0 + 1
set line = call LineString list comprehension tuple point at slice : 3 : for point in branch
set splitter = call MultiPoint list comprehension call interpolate i / number_of_points norma... | def spline_branch(self,branch,interval=1.0):
number_of_points = int(round(self.branchLength(branch)/interval,0))+1
line = LineString([tuple(point[:3]) for point in branch])
splitter = MultiPoint([line.interpolate((i/number_of_points),normalized=True) for i in range(number_of_points+1)])
interp = self.parse_s... | Python | nomic_cornstack_python_v1 |
function _request_features self callback=none
begin
call send call NodeFeaturesRequest mac callback
end function | def _request_features(self, callback=None):
self.stick.send(
NodeFeaturesRequest(self.mac),
callback,
) | Python | nomic_cornstack_python_v1 |
function __init__ self method arg_info resource_arg_info
begin
set method = method
set arg_info = arg_info
set resource_arg_info = call _NormalizeResourceArgInfo resource_arg_info
end function | def __init__(self, method, arg_info, resource_arg_info):
self.method = method
self.arg_info = arg_info
self.resource_arg_info = self._NormalizeResourceArgInfo(resource_arg_info) | Python | nomic_cornstack_python_v1 |
comment real signature unknown; restored from __doc__ with multiple overloads
function markerDefine self *__args
begin
return 0
end function | def markerDefine(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads
return 0 | Python | nomic_cornstack_python_v1 |
function alpha_shape_removed triangulation alpha
begin
set i = call circumradius points simplices > alpha
return i
end function | def alpha_shape_removed(triangulation, alpha):
i = circumradius(triangulation.points, triangulation.simplices) > alpha
return i | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[4]:
comment din = r'p1\samp.txt'
set din = string p1\A-small-attempt0.in
comment din = r'p1\A-large.in'
with open din string r as f
begin
set inputs = read lines f
end
set results = list
set all_digits = set map str range 10
set T = integer inputs at 0
set l = 1
while l < length inputs... | # coding: utf-8
# In[4]:
#din = r'p1\samp.txt'
din = r'p1\A-small-attempt0.in'
#din = r'p1\A-large.in'
with open(din, 'r') as f:
inputs = f.readlines()
results = []
all_digits = set(map(str, range(10)))
T = int(inputs[0])
l = 1
while l < len(inputs):
D, N = map(int, inputs[l].split())
l+=1
maxt ... | Python | zaydzuhri_stack_edu_python |
import socket
import os
import sys
import tkinter as tk
from tkinter import filedialog
set BUFFER_SIZE = 1024
set FILE_BUFFER_SIZE = 100
function catch_sabotage or_address curr_address sock
begin
if not or_address == curr_address
begin
call sendto encode string You have attempted to sabotage the server string ascii cur... | import socket
import os
import sys
import tkinter as tk
from tkinter import filedialog
BUFFER_SIZE = 1024
FILE_BUFFER_SIZE = 100
def catch_sabotage(or_address, curr_address, sock):
if not or_address == curr_address:
sock.sendto('You have attempted to sabotage the server'.encode('ascii'), curr_address)
print('Cl... | Python | zaydzuhri_stack_edu_python |
function block_loc_to_grid_loc i j k blocksize buffer trimrowsup trimcolsleft
begin
set trimup = trimrowsup at k
set trimleft = trimcolsleft at k
set i = integer i * blocksize + buffer / 2 + trimup
set j = integer j * blocksize + buffer / 2 + trimleft
return list i j k
end function | def block_loc_to_grid_loc(i, j, k, blocksize, buffer, trimrowsup,
trimcolsleft):
trimup = trimrowsup[k]
trimleft = trimcolsleft[k]
i = int(i*blocksize + buffer/2 + trimup)
j = int(j*blocksize + buffer/2 + trimleft)
return [i, j, k] | Python | nomic_cornstack_python_v1 |
string Created on 2018. 11. 5. # tuple : List와 유사, 읽기 전용, 수정 X, 검색 속도 빠름.
comment t = 'a', 'b', 'c', 'd'
set t = tuple string a string b string c string d
print t length t count t string a index t string b
print
set p = tuple 1 2 3
comment p[0] = 10 # 'tuple' object does not support item assignment, 튜플은 수정 불가능.
print p... | '''
Created on 2018. 11. 5.
# tuple : List와 유사, 읽기 전용, 수정 X, 검색 속도 빠름.
'''
#t = 'a', 'b', 'c', 'd'
t = ('a', 'b', 'c', 'd')
print(t, len(t), t.count('a'), t.index('b'))
print()
p = (1, 2, 3)
#p[0] = 10 # 'tuple' object does not support item assignment, 튜플은 수정 불가능.
print(p)
q = list(p) # 형변환
q[0] = 10
p = tuple(q)
p... | Python | zaydzuhri_stack_edu_python |
import pyperclip
class Contact
begin
string Class that generates new instances of contacts.
comment Empty contact list
set contact_list = list
function __init__ self first_name last_name number email
begin
comment docstring removed for simplicity
set first_name = first_name
set last_name = last_name
set phone_number =... | import pyperclip
class Contact:
"""
Class that generates new instances of contacts.
"""
contact_list = [] # Empty contact list
def __init__(self,first_name,last_name,number,email):
# docstring removed for simplicity
self.first_name = first_name
self.last_name = la... | Python | zaydzuhri_stack_edu_python |
from PIL import Image
string Image1=Image.open("IMage name1") Image2 = Image.open("image name 2") area (image1/2,image1/2,image2/3/4,image2/e/4) image1.paste(Image2,area of the image1) image1.show() | from PIL import Image
'''
Image1=Image.open("IMage name1")
Image2 = Image.open("image name 2")
area (image1/2,image1/2,image2/3/4,image2/e/4)
image1.paste(Image2,area of the image1)
image1.show()''' | Python | zaydzuhri_stack_edu_python |
function _log_info message
begin
info message
print message
end function | def _log_info(message: Text):
logging.info(message)
print(message) | Python | nomic_cornstack_python_v1 |
function get_structure_summary self
begin
return call get_structure_summary
end function | def get_structure_summary(self):
return self.__root.get_structure_summary() | Python | nomic_cornstack_python_v1 |
comment 고양이 이미지의 H, S, V 값을 변경해서 각각의 이미지를 저장하기
comment Hue:가로(색조), Saturation:세로(채도), Value:커서 상/하(밝기)
import cv2
import numpy as np
set img = call imread string image/cat.jpg
set HSV = call cvtColor img COLOR_BGR2HSV
set tuple h s v = split cv2 HSV
comment 색조는 범위가 180까지 (90을 더하면 반대 색)
set dh = call addWeighted h 1 h 0... | # 고양이 이미지의 H, S, V 값을 변경해서 각각의 이미지를 저장하기
# Hue:가로(색조), Saturation:세로(채도), Value:커서 상/하(밝기)
import cv2
import numpy as np
img = cv2.imread('image/cat.jpg')
HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(HSV)
dh = cv2.addWeighted(h, 1, h, 0, 180//2) # 색조는 범위가 180까지 (90을 더하면 반대 색)
HSV_dh = cv2.merge((... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
call __init__
call geometry string 700x400+250+250
title self string Untitled - Notepad App
call wm_iconbitmap string F:\Notepad - Extra\icon.ico
end function | def __init__(self) -> None:
super().__init__()
self.geometry('700x400+250+250')
self.title('Untitled - Notepad App')
self.wm_iconbitmap(r'F:\Notepad - Extra\icon.ico') | Python | nomic_cornstack_python_v1 |
function assertSampleDataParticle self val
begin
if is instance val SBE16DataParticle
begin
set sample_dict = loads call generate_parsed
end
else
begin
set sample_dict = val
end
assert true sample_dict at STREAM_NAME PARSED
assert true sample_dict at PKT_FORMAT_ID JSON_DATA
assert true sample_dict at PKT_VERSION 1
asse... | def assertSampleDataParticle(self, val):
if (isinstance(val, SBE16DataParticle)):
sample_dict = json.loads(val.generate_parsed())
else:
sample_dict = val
self.assertTrue(sample_dict[DataParticleKey.STREAM_NAME],
DataParticleValue.PARSED)
self... | Python | nomic_cornstack_python_v1 |
comment each test case
for test_case in range 1 num_test_cases + 1
begin
set line = split read line f string
set values = strip line at 1
set level = 0
set cumulative_people = 0
set added_people = 0
for num_persons in values
begin
set num_persons = integer num_persons
if level > cumulative_people
begin
set added_people... | # each test case
for test_case in range(1, num_test_cases + 1):
line = f.readline().split(" ")
values = line[1].strip()
level = 0
cumulative_people = 0
added_people = 0
for num_persons in values:
num_persons = int(num_persons)
if level > cumulative_people:
added_peop... | Python | zaydzuhri_stack_edu_python |
from typing import List
from structures.task import Task
class TasksCrawlerInterface
begin
decorator staticmethod
function get_task link force_update=false
begin
string Get all information about a task from it's page. :param force_update: If it is False, the task will be downloaded from the site only if it doesn't exis... | from typing import List
from structures.task import Task
class TasksCrawlerInterface:
@staticmethod
def get_task(link: str, force_update=False) -> Task:
"""
Get all information about a task from it's page.
:param force_update: If it is False, the task will be downloaded from the site ... | Python | zaydzuhri_stack_edu_python |
function predict self x
begin
set n = length x
set num_class = length unique y
set prediction = zeros tuple n num_class
comment BEGIN_YOUR_CODE
comment calculate naive bayes probability of each class of input x
print string num_class = + string num_class
p
pass
comment END_YOUR_CODE
return prediction
end function | def predict(self, x):
n = len(x)
num_class = len(np.unique(self.y))
prediction = np.zeros((n, num_class))
############################################################
############################################################
# BEGIN_YOUR_CODE
... | Python | nomic_cornstack_python_v1 |
function soft_assert_cannot_add_comment soft_assert obj
begin
set info_page = call open_info_page_of_obj obj
call click_add_button
comment wait until new tab contains info page url
set tuple _ new_tab = call windows
call wait_for lambda -> ends with url INFO
call expect not exists string There should be no input field... | def soft_assert_cannot_add_comment(soft_assert, obj):
info_page = factory.get_cls_webui_service(
objects.get_plural(obj.type))().open_info_page_of_obj(obj)
info_page.comments_panel.click_add_button()
# wait until new tab contains info page url
_, new_tab = browsers.get_browser().windows()
test_utils.wai... | Python | nomic_cornstack_python_v1 |
function test_get_org_iam_policies_malformed_json_error_handled self
begin
set return_value = fake_orgs_bad_iam_db_rows
set LOGGER = call MagicMock
set expected_org = call Organization fake_orgs_bad_iam_db_rows at 0 at string org_id
set expected_iam = loads fake_orgs_bad_iam_db_rows at 0 at string iam_policy
set expect... | def test_get_org_iam_policies_malformed_json_error_handled(self):
self.fetch_mock.return_value = self.fake_orgs_bad_iam_db_rows
organization_dao.LOGGER = mock.MagicMock()
expected_org = organization.Organization(
self.fake_orgs_bad_iam_db_rows[0]['org_id'])
expected_iam = js... | Python | nomic_cornstack_python_v1 |
function close self
begin
pass
end function | def close(self):
pass | Python | nomic_cornstack_python_v1 |
function smallest_total_number
begin
set total = call total_number
set smallest_number = 0
set current_number = total
while call check current_number
begin
if current_number % 2 == 0
begin
set smallest_number = current_number
set current_number = current_number // 2
end
end
return smallest_number
end function | def smallest_total_number():
total = total_number()
smallest_number = 0
current_number = total
while check(current_number):
if current_number % 2 == 0:
smallest_number = current_number
current_number = current_number // 2
return smallest_number | Python | nomic_cornstack_python_v1 |
function get_q_complete obj
begin
comment TODO: Calculate whatever we need to calculate.
comment TODO: Currently, we don't return HSRNUMBER,
comment but we don't currently use it in CR Connect either
if obj is not none and has attribute obj string Q_COMPLETE
begin
if length all > 0
begin
return dict string STATUS STATU... | def get_q_complete(obj):
# TODO: Calculate whatever we need to calculate.
# TODO: Currently, we don't return HSRNUMBER,
# but we don't currently use it in CR Connect either
if obj is not None and hasattr(obj, 'Q_COMPLETE'):
if len(obj.Q_COMPLETE.all()) > 0:
r... | Python | nomic_cornstack_python_v1 |
comment defines the syntax. This is so that if I decide to change the syntax later, I just have to change it here.
comment Defines the type for each lexeme. You can think of this as defining the vocabulary of the language.
comment These should be types instead of just strings.
set generaltypes = dict string ( string le... | # defines the syntax. This is so that if I decide to change the syntax later, I just have to change it here.
# Defines the type for each lexeme. You can think of this as defining the vocabulary of the language.
# These should be types instead of just strings.
generaltypes = {
"(" : "leftparenthesis",
")" : "... | Python | zaydzuhri_stack_edu_python |
import easytrader
import time
import tushare as ts
import datetime
set user = call use string htzq_client
comment 类似 r'C:\htzqzyb2\xiadan.exe'
call connect string D:\Program Files\海通证券委托\xiadan.exe
comment user.prepare(user='张照博', password='379926', comm_password='379926')
comment user.prepare('D:\Program Files\海通证券委托\... | import easytrader
import time
import tushare as ts
import datetime
user = easytrader.use('htzq_client')
user.connect(r'D:\Program Files\海通证券委托\xiadan.exe') # 类似 r'C:\htzqzyb2\xiadan.exe'
# user.prepare(user='张照博', password='379926', comm_password='379926')
# user.prepare('D:\Program Files\海通证券委托\yh_client.json') # 配... | Python | zaydzuhri_stack_edu_python |
import os
import json
import pkgutil
from copy import deepcopy
from importlib import import_module
from collections import Mapping , OrderedDict
from bottle import request
set POSIX = name != string nt
function request_param param_name
begin
if method == string POST
begin
return get forms param_name
end
else
begin
retu... | import os
import json
import pkgutil
from copy import deepcopy
from importlib import import_module
from collections import Mapping, OrderedDict
from bottle import request
POSIX = os.name != 'nt'
def request_param(param_name):
if request.method == 'POST':
return request.forms.get(param_name)
else:
... | Python | zaydzuhri_stack_edu_python |
function get_fulfillment_preview self request response **kw
begin
return call _post_request request kw response
end function | def get_fulfillment_preview(self, request, response, **kw):
return self._post_request(request, kw, response) | Python | nomic_cornstack_python_v1 |
function batch_write client resources batch_size=MAX_DYNAMO_BATCH_SIZE batch_counter_step=MAX_DYNAMO_BATCH_SIZE
begin
set idx = 0
set item_count = 0
set batch = default dictionary list
for tuple idx batch_resources in enumerate call chunk resources batch_size
begin
clear batch
for resource in batch_resources
begin
appe... | def batch_write(client, resources, batch_size=MAX_DYNAMO_BATCH_SIZE, batch_counter_step=MAX_DYNAMO_BATCH_SIZE):
idx = 0
item_count = 0
batch = defaultdict(list)
for idx, batch_resources in enumerate(chunk(resources, batch_size)):
batch.clear()
for resource in batch_resources:
... | Python | nomic_cornstack_python_v1 |
from sklearn.cross_validation import train_test_split
from sklearn.datasets import fetch_lfw_people
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import RandomizedPCA
from sklearn.svm import SVC
clas... | from sklearn.cross_validation import train_test_split
from sklearn.datasets import fetch_lfw_people
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import RandomizedPCA
from sklearn.svm import SVC
cla... | Python | zaydzuhri_stack_edu_python |
function procedures_from_ccam procedure_occurrence visit_occurrence=none codes=none date_from_visit=true additional_filtering=dictionary date_min=none date_max=none
begin
comment noqa: E501
set procedure_columns = dictionary code_source_value=string procedure_source_value code_start_datetime=string procedure_datetime c... | def procedures_from_ccam(
procedure_occurrence: DataFrame,
visit_occurrence: Optional[DataFrame] = None,
codes: Optional[Dict[str, Union[str, List[str]]]] = None,
date_from_visit: bool = True,
additional_filtering=dict(),
date_min: Optional[datetime] = None,
date_max: Optional[datetime] = No... | Python | nomic_cornstack_python_v1 |
function CrossValidateModelParameters self splitTrainSet matricesPL labelsPL trainingPL predictionLayer trainOperation lossFunction savePath saveName numberOfSteps batchSize
begin
comment DEFINE DATA ##########
set dataDirectory = numpyDirectory
set X = numpyFileList
set Y = labels
set folder = call KFold n_splits=5 sh... | def CrossValidateModelParameters(self, splitTrainSet, matricesPL, labelsPL, trainingPL, predictionLayer, trainOperation, lossFunction, savePath, saveName,
numberOfSteps, batchSize):
########## DEFINE DATA ##########
dataDirectory = splitTrainSet.numpyDirectory
... | Python | nomic_cornstack_python_v1 |
function project dict dimensions RANDOMIZATION_TYPE=string gaussian TERNARY_NON_ZERO_PERCENT=none RANDOM_SEED=0
begin
set projection = zeros tuple dimensions
for tuple key value in items dict
begin
set projection = projection + value * call randomrow key dimensions RANDOMIZATION_TYPE TERNARY_NON_ZERO_PERCENT RANDOM_SEE... | def project(dict, dimensions, RANDOMIZATION_TYPE="gaussian", TERNARY_NON_ZERO_PERCENT=None, RANDOM_SEED=0):
projection = numpy.zeros((dimensions,))
for key, value in dict.items():
projection += value * randomrow(key, dimensions, RANDOMIZATION_TYPE, TERNARY_NON_ZERO_PERCENT, RANDOM_SEED)
return pro... | Python | nomic_cornstack_python_v1 |
function get_max_incident_time new_incidents
begin
function incident_to_timestamp incident
begin
set incident_time = call get_incident_time incident
return string parse time incident_time string %Y-%m-%d %H:%M:%S.%f
end function
set incident_with_latest_timestamp = max new_incidents key=lambda inc -> call incident_to_t... | def get_max_incident_time(new_incidents):
def incident_to_timestamp(incident):
incident_time = get_incident_time(incident)
return datetime.strptime(incident_time, '%Y-%m-%d %H:%M:%S.%f')
incident_with_latest_timestamp = max(new_incidents, key=lambda inc: incident_to_timestamp(inc))
return g... | Python | nomic_cornstack_python_v1 |
function test_user_modification_raises_audit_trail self
begin
assert true count objects >= 1
assert equal level LEVEL_INFO
end function | def test_user_modification_raises_audit_trail(self):
self.assertTrue(AuditTrail.objects.count() >= 1)
self.assertEqual(
AuditTrail.objects.last().level, AuditTrail.LEVEL_INFO) | Python | nomic_cornstack_python_v1 |
string 1005. Spell It Right (20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English. Input Specification: Each input file contains one test case. Each case occupies one l... | """
1005. Spell It Right (20)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.
Input Specification:
Each input file contains one test case. Each case occupies one line... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from sklearn import svm
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.metrics import accuracy_score , classification_report , confusion_matrix
from sklea... | import numpy as np
from sklearn import svm
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
from sklearn.f... | Python | zaydzuhri_stack_edu_python |
function read_from_file
begin
with open string graph.txt as f
begin
set data = read line f
end
set graph = dict
set input = split data
set n = call __len__
for i in range 0 n
begin
for j in range 0 n
begin
if input at i at j == string Y
begin
set element = 1
set graph = call add_value graph i j
add vertexes i
add vert... | def read_from_file():
with open('graph.txt') as f:
data = f.readline()
graph = {}
input = data.split()
n = input.__len__()
for i in range(0, n):
for j in range(0, n):
if input[i][j] == 'Y':
element = 1
graph = add_value(graph, i, j)
... | Python | zaydzuhri_stack_edu_python |
function __enter__ self
begin
set stdout = fout
end function | def __enter__(self):
sys.stdout = self.fout | Python | nomic_cornstack_python_v1 |
import random
function randomElement list
begin
return random choice list
end function
print call randomElement list 1 2 3 4 5 | import random
def randomElement(list):
return random.choice(list)
print(randomElement([1,2,3,4,5])) | Python | jtatman_500k |
comment Work with Python 3.8
import asyncio
import discord
import random
import requests
import datetime
import openpyxl
from discord.ext import commands
import os
set intents = all
set game = call Game string ^^도움말을 입력해주세요.
set bot = call Bot command_prefix=string ^^ status=online activity=game help_command=none inten... | # Work with Python 3.8
import asyncio
import discord
import random
import requests
import datetime
import openpyxl
from discord.ext import commands
import os
intents = discord.Intents.all()
game = discord.Game("^^도움말을 입력해주세요.")
bot = commands.Bot(command_prefix='^^', status=discord.Status.online, activity=game, help_c... | Python | zaydzuhri_stack_edu_python |
string 7. Faça um programa que leia 5 números e informe o maior número.
set maior = 0
for _ in range 5
begin
set numero = integer input string Digite um número:
if numero > maior
begin
set maior = numero
end
end
print string O maior número é: { maior } | """7. Faça um programa que leia 5 números e informe o maior número."""
maior = 0
for _ in range(5):
numero = int(input('Digite um número: '))
if numero > maior:
maior = numero
print(f'O maior número é: {maior}') | Python | zaydzuhri_stack_edu_python |
comment https://colab.research.google.com/github/tensorflow/examples/blob/master/community/en/transformer_chatbot.ipynb
from __future__ import absolute_import , division , print_function , unicode_literals
import tensorflow as tf
import os
import re
call set_seed 1234
comment DATASET PATH
set path_to_dataset = string i... | # https://colab.research.google.com/github/tensorflow/examples/blob/master/community/en/transformer_chatbot.ipynb
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import os
import re
tf.random.set_seed(1234)
# DATASET PATH
path_to_dataset = 'input/movie_dialo... | Python | zaydzuhri_stack_edu_python |
comment 在最后添加元素
append chars string d
print length chars
comment 在索引为1的位置插入元素,插入后该元素的索引编程1
insert chars 1 string 0
print chars at 1
comment 删除索引在-1的元素
pop chars
pop chars - 1
print chars
set chars at 1 = string 1
print chars | #在最后添加元素
chars.append('d')
print(len(chars))
#在索引为1的位置插入元素,插入后该元素的索引编程1
chars.insert(1,'0');
print(chars[1])
#删除索引在-1的元素
chars.pop()
chars.pop(-1)
print(chars)
chars[1] = '1'
print(chars)
| Python | zaydzuhri_stack_edu_python |
function parse_uri cls uri storage_args=dict
begin
raise call NotImplementedError format string `parse_uri` is not implemented for {}. __name__
end function | def parse_uri(cls, uri, storage_args={}):
raise NotImplementedError('`parse_uri` is not implemented for {}.'.format(type(cls).__name__)) | Python | nomic_cornstack_python_v1 |
function update self elapsed
begin
set delta = 8 * elapsed
set rest = rest_drive
if active_drive == rest
begin
set activation_level = activation_level + delta
end
else
begin
set activation_level = max 0 activation_level - delta
end
end function | def update(self, elapsed):
delta = 8 * elapsed
rest = self.behavior_system.robot.drive_system.rest_drive
if self.behavior_system.robot.drive_system.active_drive == rest:
self.activation_level = self.activation_level + delta
else:
self.activation_level = max(0, se... | Python | nomic_cornstack_python_v1 |
import urllib.request
comment url = "https://www.gre.ac.uk/"
set url = strip input string Enter an URL for a file:
set infile = url open url
comment Read the content as string
set content = decode read infile
print content
print
input string Press return to continue ... | import urllib.request
#url = "https://www.gre.ac.uk/"
url = input("Enter an URL for a file: ").strip()
infile = urllib.request.urlopen(url)
content = infile.read().decode() # Read the content as string
print(content)
print()
input("Press return to continue ...")
| Python | zaydzuhri_stack_edu_python |
function total initial *positionals **keywords
begin
set count = initial
for n in positionals
begin
set count = count + n
end
for n in keywords
begin
set count = count + keywords at n
end
return count
end function | def total (initial, *positionals, **keywords):
count = initial
for n in positionals:
count += n
for n in keywords:
count += keywords[n]
return count | Python | nomic_cornstack_python_v1 |
from mpi4py import MPI
from ga4py import ga
import numpy as np
import sys
set EPSILON = 0.0001
set HOW_MANY_STEPS_BEFORE_CONVERGENCE_TEST = 2
set DEBUG = false | from mpi4py import MPI
from ga4py import ga
import numpy as np
import sys
EPSILON = .0001
HOW_MANY_STEPS_BEFORE_CONVERGENCE_TEST = 2
DEBUG = False
| Python | zaydzuhri_stack_edu_python |
function __init__ self node_from node_to bandwidth frequency power noise eff
begin
set node_from : str = node_from
set node_to : str = node_to
set bandwidth : float ? none = bandwidth
set frequency : float ? none = frequency
set power : float ? none = power
set noise : float ? none = noise
set eff : float ? none = eff
... | def __init__(self, node_from: str, node_to: str, bandwidth: float, frequency: float,
power: float | None, noise: float | None, eff: float | None):
self.node_from: str = node_from
self.node_to: str = node_to
self.bandwidth: float | None = bandwidth
self.frequency: float |... | Python | nomic_cornstack_python_v1 |
function step_impl_a_bad_request_is_returned context
begin
call assert_equal status_code 400
end function | def step_impl_a_bad_request_is_returned(context):
nose.tools.assert_equal(context.response.status_code, 400) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string access_required.py: a practice project number 2 from: Lesson 14 - Decorators
set __author__ = string Daniel Urtnowski
set __version__ = string 0.1
import authorization
function access_required fun
begin
string This function is a decorator that when applied to a function executes sub... | #!/usr/bin/env python3
"""
access_required.py: a practice project number 2 from:
Lesson 14 - Decorators
"""
__author__ = "Daniel Urtnowski"
__version__ = "0.1"
import authorization
def access_required(fun):
"""
This function is a decorator that when applied to a function executes
subjected function o... | Python | zaydzuhri_stack_edu_python |
comment Определить, какое число в массиве встречается чаще всего.
import random
set lst = list comprehension random integer 1 10 for i in range 50
print lst
set nums = dict
comment в словарь подставляем в пару ключ: значение, число: количество повторов
for item in lst
begin
if item not in keys nums
begin
set nums at i... | # Определить, какое число в массиве встречается чаще всего.
import random
lst = [random.randint(1, 10) for i in range(50)]
print(lst)
nums = {}
# в словарь подставляем в пару ключ: значение, число: количество повторов
for item in lst:
if item not in nums.keys():
nums[item] = 1
elif item in nums.keys... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
import requests
import re
from urllib.request import urlopen , Request
import os
comment import cookielib
import json
class FaceScrapper
begin
function get_soup url header
begin
return call BeautifulSoup url open call Request url headers=header string html.parser
end function
set ROOT_DIR ... | from bs4 import BeautifulSoup
import requests
import re
from urllib.request import urlopen, Request
import os
# import cookielib
import json
class FaceScrapper():
def get_soup(url,header):
return BeautifulSoup( urlopen( Request(url,headers=header)),'html.parser')
ROOT_DIR="reference_images"
header={'User-Age... | 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.