code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function segment_string_memoized input_string dictionary
begin
set memo = dict
set out = call segment_string input_string dictionary memo
return out
end function | def segment_string_memoized(input_string, dictionary):
memo = {}
out = segment_string(input_string, dictionary, memo)
return out | Python | nomic_cornstack_python_v1 |
comment 1. дефиниция на клас
class Point
begin
comment Конструктор на класа
function __init__ self
begin
print string Point Ctor
comment данни класа
set x = 20
set y = 30
end function
comment Методи на класа
function draw self
begin
print string draw point at: ( { x } , { y } )
end function
end class
if __name__ == str... | # 1. дефиниция на клас
class Point:
# Конструктор на класа
def __init__(self):
print('Point Ctor')
# данни класа
self.x = 20
self.y = 30
# Методи на класа
def draw(self):
print(f'draw point at: ({self.x},{self.y})')
if __name__ == '__main__':
# 2. декла... | Python | zaydzuhri_stack_edu_python |
function test_Alignments_process_reference_annotation_unknown_annotations_three_items_bug_int self
begin
set alignments_store = call Alignments
set output = call process_reference_annotation string UniRef90_W1Q3F0|5000|5000
set expected_output = list string UniRef90_W1Q3F0|5000|5000 0 string unclassified
assert equal e... | def test_Alignments_process_reference_annotation_unknown_annotations_three_items_bug_int(self):
alignments_store=store.Alignments()
output=alignments_store.process_reference_annotation("UniRef90_W1Q3F0|5000|5000")
expected_output=["UniRef90_W1Q3F0|5000|5000",0,"unclass... | Python | nomic_cornstack_python_v1 |
function primesByMaxValue MAX
begin
set primes = list 2 3 5 7 11 13 17 19 23 29 31 37
set root_index = 3
set root = 7
set square = 49
set r = range 1 root_index
for n in range 41 MAX 2
begin
if square <= n
begin
append r root_index
set root_index = root_index + 1
set root = primes at root_index
set square = root * root... | def primesByMaxValue(MAX):
primes = [2,3,5,7,11,13,17,19,23,29,31,37]
root_index = 3
root = 7
square = 49
r = range(1,root_index)
for n in range(41,MAX,2):
if square <= n:
r.append(root_index)
root_index += 1
root = primes[root_index... | Python | zaydzuhri_stack_edu_python |
function validate self
begin
comment reset all entries to make sure None constraints are fulfilled
for entry in values _config_entries
begin
set value = value
end
end function | def validate(self):
# reset all entries to make sure None constraints are fulfilled
for entry in self._config_entries.values():
entry.value = entry.value | Python | nomic_cornstack_python_v1 |
function kmin self
begin
return 2.0 * pi / lside
end function | def kmin(self):
return 2. * np.pi / self.lside | Python | nomic_cornstack_python_v1 |
function complete self message=string Job completed
begin
set complete_time = call add_message message
set state = COMPLETE
end function | def complete(self, message="Job completed"):
self.complete_time = self.add_message(message)
self.state = JobState.COMPLETE | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup as bs
import requests
from multiprocessing import Pool
function crawl param
begin
set tuple url i = param
while true
begin
try
begin
set req = get requests url
break
end
except any
begin
pass
end
end
if not ok
begin
with open string err.txt string a as f
begin
write f url + string
return
e... | from bs4 import BeautifulSoup as bs
import requests
from multiprocessing import Pool
def crawl(param):
url, i = param
while True:
try:
req = requests.get(url)
break
except:
pass
if not req.ok:
with open('err.txt', 'a') as f:
f.write(ur... | Python | zaydzuhri_stack_edu_python |
function check_prime num
begin
set half = num // 2 + 1
set flag = 0
set i = 2
while i <= half
begin
if num % i == 0
begin
set flag = 1
end
set i = i + 1
end
if flag == 1
begin
print string number is not Prime
end
else
begin
print string number is prime
end
end function
set number = integer input string Enter a Number:
... | def check_prime(num):
half = (num//2)+1
flag = 0
i=2
while i<=half:
if num%i==0:
flag =1
i+=1
if flag==1:
print("number is not Prime")
else:
print("number is prime")
number = int(input("Enter a Number: "))
check_prime(number)
| Python | zaydzuhri_stack_edu_python |
import unittest
import random
import red_black_tree
class Test extends TestCase
begin
string
decorator classmethod
function setUpClass cls
begin
set num_element = list
append num_element 200
set tree = call Tree
set list_value = call create_random_tree cls
end function
comment def setUp(self):
comment self.num_elemen... | import unittest
import random
import red_black_tree
class Test(unittest.TestCase):
"""
"""
@classmethod
def setUpClass(cls):
cls.num_element = []
cls.num_element.append(200)
cls.tree = red_black_tree.Tree()
cls.list_value = cls.create_random_tree(cls)
... | Python | zaydzuhri_stack_edu_python |
import nltk
from nltk.collocations import *
from nltk import word_tokenize
import pickle
import pandas as pd
function join_text text1 text2
begin
if type text1 is str
begin
if type text2 is str
begin
return text1 + string . + text2
end
else
begin
return text1
end
end
else
if type text2 is str
begin
return text2
end
ret... | import nltk
from nltk.collocations import *
from nltk import word_tokenize
import pickle
import pandas as pd
def join_text(text1, text2):
if type(text1) is str:
if type(text2) is str:
return text1 + '.' + text2
else:
return text1
else:
if type(text2)... | Python | zaydzuhri_stack_edu_python |
set pattern = compile string \b[abc]+\w*\b | pattern = re.compile(r'\b[abc]+\w*\b') | Python | jtatman_500k |
function location_to_numeric_hash self
begin
set acc = octant
set mult = 8
for level in levels
begin
set acc = acc + mult * level
set mult = mult * 4
end
return acc
end function | def location_to_numeric_hash(self):
acc = self.octant
mult = 8
for level in self.levels:
acc += mult * level
mult *= 4
return acc | Python | nomic_cornstack_python_v1 |
comment Created By: Theodore Tenedorio
comment Date: 10/29/2015
comment Requires: Python2.7 & openpyxl
comment 'https://pypi.python.org/pypi/openpyxl' or 'pip install openpyxl'
from openpyxl import load_workbook
comment Reads the active worksheet of .xlsx (MS Excel 2010) into an array of columns.
comment header variabl... | # Created By: Theodore Tenedorio
# Date: 10/29/2015
# Requires: Python2.7 & openpyxl
# 'https://pypi.python.org/pypi/openpyxl' or 'pip install openpyxl'
from openpyxl import load_workbook
# Reads the active worksheet of .xlsx (MS Excel 2010) into an array of columns.
# header variable skips the first row if true.
# W... | Python | zaydzuhri_stack_edu_python |
comment 计算六种算法的混淆矩阵
import pickle
import os
class TestList
begin
set baseDir = directory name path get current directory
with open join path baseDir string ML string test_shuffle.pkl string rb as fShuffle
begin
set testList = load pickle fShuffle
end
end class
function getLable testList index threshold
begin
return lis... | #计算六种算法的混淆矩阵
import pickle
import os
class TestList:
baseDir = os.path.dirname(os.getcwd())
with open(os.path.join(baseDir, 'ML', 'test_shuffle.pkl'), 'rb') as fShuffle:
testList = pickle.load(fShuffle)
def getLable(testList:list,index:int,threshold:float):
return [ 0 if i[index+1] <threshold els... | Python | zaydzuhri_stack_edu_python |
import cocos
from cocos.director import director
class HelloWorld extends Layer
begin
function __init__ self
begin
call __init__
set shift = 120
comment create a label
comment create intersections
set intersections = list
for x in range 0 + shift 800 + shift 40
begin
for y in range 0 + shift 800 + shift 40
begin
set i... | import cocos
from cocos.director import director
class HelloWorld(cocos.layer.Layer):
def __init__(self):
super(HelloWorld, self).__init__()
shift = 120
# create a label
# create intersections
intersections = []
for x in range(0 + shift,800 + shift, 40):
... | Python | zaydzuhri_stack_edu_python |
class MyClass
begin
function __init__ self
begin
set list = list
set dictionary = dict
end function
end class | class MyClass:
def __init__(self):
self.list = []
self.dictionary = {} | Python | jtatman_500k |
string -Medium- 描述 It's follow up problem for Binary Tree Longest Consecutive Sequence II Given a k-ary tree, find the length of the longest consecutive sequence path. The path could be start and end at any node in the tree 样例 Example 1: Input: 5<6<7<>,5<>,8<>>,4<3<>,5<>,31<>>> Output: 5 Explanation: 5 / 6 4 /|\ /|7 5 ... | '''
-Medium-
描述
It's follow up problem for Binary Tree Longest Consecutive Sequence II
Given a k-ary tree, find the length of the longest consecutive sequence path.
The path could be start and end at any node in the tree
样例
Example 1:
Input:
5<6<7<>,5<>,8<>>,4<3<>,5<>,31<>>>
Output:
5
Explanation:
5
/ \
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set cupcakes = array list 2 0.75 2 1 0.5
set recipes = call genfromtxt string recipes.csv delimiter=string , | import numpy as np
cupcakes = np.array([2,0.75,2,1,0.5])
recipes = np.genfromtxt('recipes.csv',delimiter = ',') | Python | zaydzuhri_stack_edu_python |
comment Nedbank Loan Calculator
print string ---Welcome To Nedbank Loan Console Calculator---
set loan_amount = integer input string Please enter loan amount:
set interest_rate = decimal input string Please enter your interest rate without a percentage sign
comment how long it would take you to repay the loan.
set _num... | #Nedbank Loan Calculator
print("---Welcome To Nedbank Loan Console Calculator---")
loan_amount = int(input("Please enter loan amount: "))
interest_rate = float(input("Please enter your interest rate without a percentage sign"))
_number_of_months = 12 #how long it would take you to repay the loan.
total_repayment = lo... | Python | zaydzuhri_stack_edu_python |
function from_file_line_match self match line
begin
set key = call group string key
set op = call group string operator
try
begin
set tuple directory path = call get_location directory call group string file current=directory name path
with open join FILEBROWSER_ROOT directory path as f
begin
if string + in op
begin
ca... | def from_file_line_match(self, match, line):
key = match.group('key')
op = match.group('operator')
try:
directory, path = get_location(self.directory, match.group('file'),
current=dirname(self.path))
... | Python | nomic_cornstack_python_v1 |
function restore self save
begin
run call global_variables_initializer
set saver = call Saver call global_variables
set ckpt = call get_checkpoint_state save
call restore sess model_checkpoint_path
end function | def restore(self, save):
self.sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(tf.global_variables())
ckpt = tf.train.get_checkpoint_state(save)
saver.restore(self.sess, ckpt.model_checkpoint_path) | Python | nomic_cornstack_python_v1 |
import numpy as np
import tensorflow as tf
import micronet
string Everything here is imported into the __init__.py. It's sufficient to import from micronet.test. Note: is this a useful/correct practice?
comment TODO: why isn't there an exposed way of doing this?
comment I suppose the Backend is exposed. The name is jus... | import numpy as np
import tensorflow as tf
import micronet
"""
Everything here is imported into the __init__.py. It's sufficient to import
from micronet.test.
Note: is this a useful/correct practice?
"""
# TODO: why isn't there an exposed way of doing this?
# I suppose the Backend is exposed. The name is just o... | Python | zaydzuhri_stack_edu_python |
function predict_proba self X
begin
call check_is_fitted self string n_classes_
set n_classes = n_classes_
set X = call _validate_X_predict X
if n_classes == 1
begin
return ones tuple shape at 0 1
end
if algorithm == string SAMME.R
begin
comment The weights are all 1. for SAMME.R
set proba = sum generator expression ca... | def predict_proba(self, X):
check_is_fitted(self, "n_classes_")
n_classes = self.n_classes_
X = self._validate_X_predict(X)
if n_classes == 1:
return np.ones((X.shape[0], 1))
if self.algorithm == 'SAMME.R':
# The weights are all 1. for SAMME.R
... | Python | nomic_cornstack_python_v1 |
function add_poisson_noise self scale=1.0
begin
set noise = scale * square root where data > 0 data 0 * randn *self.data.shape
if upper get hdr string BUNIT string ADU == string ADU
begin
set noise = noise / square root call gain
end
add self noise
end function | def add_poisson_noise(self, scale=1.0):
noise = (scale * np.sqrt(np.where(self.data > 0, self.data, 0)) *
np.random.randn(*self.data.shape))
if self.hdr.get('BUNIT', 'ADU').upper() == 'ADU':
noise /= np.sqrt(self.gain())
self.add(noise) | Python | nomic_cornstack_python_v1 |
function __eq__ self other
begin
if not is instance other Metrics
begin
return false
end
return __dict__ == __dict__
end function | def __eq__(self, other):
if not isinstance(other, Metrics):
return False
return self.__dict__ == other.__dict__ | Python | nomic_cornstack_python_v1 |
function parse_config_string string
begin
set result = dict
for entry in call smart_split string delimiter=string ,
begin
try
begin
set tuple key val = split entry string =
end
except ValueError
begin
raise call ValueError string Error parsing entry %s % entry
end
set val = call _check_boolean val
set val = call _try_... | def parse_config_string(string):
result = {}
for entry in smart_split(string, delimiter=','):
try:
key, val = entry.split('=')
except ValueError:
raise ValueError('Error parsing entry %s' % entry)
val = _check_boolean(val)
val = _try_numeric(val)
result[key] = val
return copy.deepc... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from home_locators import *
import time
import unittest
class ShortReadsTestCase extends TestCase
begin
function setUp self
begin
set driver = call Chrome string ./chromedriver
call set_window_size 414 736
call addCleanup quit
end function
function test_short_reads self
begin
get driver s... | from selenium import webdriver
from home_locators import *
import time
import unittest
class ShortReadsTestCase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome('./chromedriver')
self.driver.set_window_size(414, 736)
self.addCleanup(self.driver.quit)
def test_short_... | Python | zaydzuhri_stack_edu_python |
function show_age_distrib self
begin
set bin_edges = array range 0 110 10
set hist = histogram column=string age bins=bin_edges
set bin_vals = values
return tuple bin_vals bin_edges
end function | def show_age_distrib(self) -> Tuple[np.ndarray, np.ndarray]:
bin_edges = np.arange(0, 110, 10)
hist = self.data.hist(column='age', bins=bin_edges)
bin_vals = pd.cut(self.data['age'], bins=bin_edges, right=False).value_counts().sort_index().values
return bin_vals, bin_edges | Python | nomic_cornstack_python_v1 |
import numpy as np
comment Given the Celsius temperature, convert it to Fahrenheit (celsius * 1.8 = fahrenheit - 32)
comment then check where the temperature in Fahrenheit is more than 75,
comment If yes print "Too hot", otherwise print Celsius and Fahrenheit temperature on the screen.
function CelToFah c
begin
set f =... | import numpy as np
# Given the Celsius temperature, convert it to Fahrenheit (celsius * 1.8 = fahrenheit - 32)
# then check where the temperature in Fahrenheit is more than 75,
# If yes print "Too hot", otherwise print Celsius and Fahrenheit temperature on the screen.
def CelToFah(c):
f = c * 1.8 + 32
if (f... | Python | zaydzuhri_stack_edu_python |
function parameters self
begin
return _parameters
end function | def parameters(self):
return self._parameters | Python | nomic_cornstack_python_v1 |
function reason self
begin
return err
end function | def reason(self) -> L:
return self.err | Python | nomic_cornstack_python_v1 |
function __setattr__ self name value
begin
call assert_valid
set set default __dict__ string _members dict at name = value
return call _swig_setattr self __class__ name value
end function | def __setattr__(self, name, value):
self.assert_valid()
self.__dict__.setdefault("_members",{})[name] = value
return _swig_setattr(self, self.__class__, name, value) | Python | nomic_cornstack_python_v1 |
function append self language site title url data domain File
begin
append results dict string lang language ; string site site ; string title title ; string url url ; string data data ; string domain domain ; string file File
end function | def append(self, language, site, title, url, data, domain, File):
self.results.append({'lang': language, 'site': site, 'title': title, 'url': url, 'data': data, 'domain': domain, 'file': File}) | Python | nomic_cornstack_python_v1 |
function generate_data cls live_env sim_env **kwargs
begin
comment Extract parameters
set symbol : str = kwargs at string symbol
set check_moment : datetime = kwargs at string check_moment
call info_process string Generating breakout1 setup visual for { symbol } at { string format time check_moment DATE_TIME_FORMAT }
c... | def generate_data(cls, live_env: ExecEnv,
sim_env: ExecEnv,
**kwargs) -> 'Breakout1SetupData':
# Extract parameters
symbol: str = kwargs['symbol']
check_moment: datetime = kwargs['check_moment']
live_env.info_process(f'Generating breakout1 se... | Python | nomic_cornstack_python_v1 |
comment PURPOSE: generates dataset (shapefile) of leads for ag sales team
comment NAME: Alex Kappel
comment CONTACT: apkappel@gmail.com
comment ----------------------------------------
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
comment... | #PURPOSE: generates dataset (shapefile) of leads for ag sales team
#NAME: Alex Kappel
#CONTACT: apkappel@gmail.com
#----------------------------------------
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
#sets inputs
silo_path = '../inpu... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string Three philosophers, thinking and eating sushi
string Starvation occurs when a thread is unable to gain access to a necessary resource and is therefore unable to make progress. If another greedy thread is frequently holding a lock on the shared resource, then the starved thread won't... | #!/usr/bin/env python3
""" Three philosophers, thinking and eating sushi """
'''
Starvation occurs when a thread is unable to gain access to a necessary resource and is therefore unable to make progress. If another greedy thread is frequently holding a lock on the shared resource, then the starved thread won't get a ch... | Python | zaydzuhri_stack_edu_python |
function futures_coin_cancel_all_open_orders self **params
begin
return call _request_futures_coin_api string delete string allOpenOrders signed=true data=params
end function | def futures_coin_cancel_all_open_orders(self, **params):
return self._request_futures_coin_api(
"delete", "allOpenOrders", signed=True, data=params
) | Python | nomic_cornstack_python_v1 |
function getXYZ prev_coord prev_gradient
begin
comment Controls the speed the controller outputs change.
set speed = 0.01
comment Controls the null margin for the controller.
set null_zone = 0
set events = call get_gamepad
set gradient = prev_gradient
for event in events
begin
comment print(event.ev_type, event.code, e... | def getXYZ(prev_coord, prev_gradient):
speed = 0.01 # Controls the speed the controller outputs change.
null_zone = 0 # Controls the null margin for the controller.
events = inputs.get_gamepad()
gradient = prev_gradient
for event in events:
# print(event.ev_type, even... | Python | nomic_cornstack_python_v1 |
comment Import modulo.
import turtle
set myTurtle = call Turtle
comment Prompt user for degrees to moved to the left.
function left degrees
begin
call left integer degrees
end function
comment Prompt user for degrees to moved to the right.
function right degrees
begin
call right integer degrees
end function
comment Dra... | # Import modulo.
import turtle
myTurtle = turtle.Turtle()
def left(degrees): # Prompt user for degrees to moved to the left.
myTurtle.left(int(degrees))
def right(degrees): # Prompt user for degrees to moved to the right.
myTurtle.right(int(degrees))
def forward(amount): # Draw a line with a length.
... | Python | zaydzuhri_stack_edu_python |
import random as rd
set list1 = list
set list2 = list
print string Nhap n:
set n = integer input
for i in range n
begin
append list1 random integer 1 100
end
print list1
print string Nhap x:
set x = integer input
for j in list1
begin
if j <= x
begin
append list2 j
end
end
print string Day nho hon hoac bang x la:
prin... | import random as rd
list1 = []
list2 = []
print("Nhap n:")
n = int(input())
for i in range(n):
list1.append(rd.randint(1, 100))
print(list1)
print("Nhap x:")
x = int(input())
for j in list1:
if(j <= x):
list2.append(j)
print("Day nho hon hoac bang x la:")
print(list2)
| Python | zaydzuhri_stack_edu_python |
function read_sudoku file
begin
with open file as sudoku_file
begin
comment Parse file without newline characters
set numbers_in_given_sudoku = replace read sudoku_file string string
end
comment Return a list of the numbers in the file
return list comprehension integer number for number in numbers_in_given_sudoku
end ... | def read_sudoku(file):
with open(file) as sudoku_file:
numbers_in_given_sudoku = sudoku_file.read().replace('\n', '') # Parse file without newline characters
return [int(number) for number in numbers_in_given_sudoku] # Return a list of the numbers in the file | Python | nomic_cornstack_python_v1 |
function test_fma_invalid_param_floatnum_intnum_floatarray_str_375 self
begin
comment This version is expected to pass.
call fma floatarrayx floatnumy floatarrayz floatarrayout
comment This is the actual test.
with assert raises TypeError
begin
call fma floatnumx intnumy floatarrayz strout
end
end function | def test_fma_invalid_param_floatnum_intnum_floatarray_str_375(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatnumy, self.floatarrayz, self.floatarrayout)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.floatnumx, self.intnumy, self.floata... | Python | nomic_cornstack_python_v1 |
function put_state state_id=none
begin
set state = get storage string State state_id
set data = call get_json silent=true
if state is none
begin
call abort 404
end
if data is none
begin
call abort 400 string Not a JSON
end
else
begin
for tuple key value in items data
begin
set attribute state key value
end
end
save
ret... | def put_state(state_id=None):
state = storage.get("State", state_id)
data = request.get_json(silent=True)
if state is None:
abort(404)
if data is None:
abort(400, "Not a JSON")
else:
for key, value in data.items():
setattr(state, key, value)
storage.save()
... | Python | nomic_cornstack_python_v1 |
function shortest_path absolute_path
begin
string Given an absolute pathname that may have . or .. as part of it, return the shortest standardized path. For example, given "/usr/bin/../bin/./scripts/../", return "/usr/bin/".
set units = split absolute_path string /
set stack = list
for unit in units
begin
if unit == s... | def shortest_path(absolute_path):
"""
Given an absolute pathname that may have . or .. as
part of it, return the shortest standardized path.
For example, given "/usr/bin/../bin/./scripts/../",
return "/usr/bin/".
"""
units = absolute_path.split('/')
stack = []
for unit in units:
... | Python | zaydzuhri_stack_edu_python |
set totalPercorrido = integer input
set totalCombustivelGasto = decimal input
set consumo = totalPercorrido / totalCombustivelGasto
print format string {:0.3f} km/l consumo | totalPercorrido = int(input())
totalCombustivelGasto = float(input())
consumo = totalPercorrido / totalCombustivelGasto
print("{:0.3f} km/l".format(consumo))
| Python | zaydzuhri_stack_edu_python |
function onQuitHelp self eventDict=none
begin
call setStatusText string Press %s + shift + Q to quit % call commandKeyName
end function | def onQuitHelp(self, eventDict = None):
self.mainWindow.setStatusText("Press %s + shift + Q to quit" % Naming.commandKeyName()) | Python | nomic_cornstack_python_v1 |
function blitme self
begin
call blit image rect
end function | def blitme(self):
self.screen.blit(self.image, self.rect) | Python | nomic_cornstack_python_v1 |
import csv
import sys
import os
import os.path
import matplotlib.pyplot as plt
import numpy as np
comment For early return
function main
begin
if length argv != 3
begin
print format string Usage: {} [TRAINING_DATA] [LOG_FILE] argv at 0
return
end
set tfilename = argv at 1
set lfilename = argv at 2
set tdata = tuple tup... | import csv
import sys
import os
import os.path
import matplotlib.pyplot as plt
import numpy as np
# For early return
def main():
if len(sys.argv) != 3:
print("Usage: {} [TRAINING_DATA] [LOG_FILE]".format(sys.argv[0]))
return
tfilename = sys.argv[1]
lfilename = sys.argv[2]
tdata = (([... | Python | zaydzuhri_stack_edu_python |
comment 1. Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата
comment «день-месяц-год». В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать
comment число, месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором @s... | # 1. Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата
# «день-месяц-год». В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать
# число, месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, долже... | Python | zaydzuhri_stack_edu_python |
function test_tags_browse_compare_caption_pagination_end_counts self tag_browse_caption_counts tag_browse_pagination_counts
begin
set caption_end = tag_browse_caption_counts at string end
set pagination_end = tag_browse_pagination_counts at string end
set current_url = tag_browse_caption_counts at string url
assert cap... | def test_tags_browse_compare_caption_pagination_end_counts(self,
tag_browse_caption_counts,tag_browse_pagination_counts):
self.caption_end = tag_browse_caption_counts['end']
self.pagination_end = tag_browse_pagination_counts['end']
self.current_url = tag_browse_caption_counts['url']
... | Python | nomic_cornstack_python_v1 |
import csv , sys
import numpy as np
class CsvHandling
begin
function __init__ self
begin
comment Opened file that is being processed.
set file = none
comment Path to processed file.
set path = none
end function
function if_opened self path
begin
try
begin
file
end
except NameError
begin
return false
end
try else
begin
... | import csv, sys
import numpy as np
class CsvHandling:
def __init__(self):
# Opened file that is being processed.
self.file = None
# Path to processed file.
self.path = None
def if_opened(self,path):
try:
self.file
except NameE... | Python | zaydzuhri_stack_edu_python |
string https://www.hackerrank.com/challenges/correctness-invariant
function insertion_sort ar
begin
set L = length ar
set index = 1
set count = 0
while index < L
begin
set pos = index
set V = ar at pos
while pos > 0 and V < ar at pos - 1
begin
set ar at pos = ar at pos - 1
set pos = pos - 1
set count = count + 1
end
se... | """
https://www.hackerrank.com/challenges/correctness-invariant
"""
def insertion_sort(ar):
L = len(ar)
index = 1
count = 0
while index < L :
pos = index
V = ar[pos]
while pos > 0 and V < ar[pos-1] :
ar[pos] = ar[pos-1]
pos-=1
count+=1
... | Python | zaydzuhri_stack_edu_python |
import csv
import sys
from copy import deepcopy
import sqlparse
class Query
begin
function __init__ self query
begin
if length query at 0 < 3
begin
call prError string No query given.
end
set query at 0 = join string split query at 0
set agg = list string max string min string avg string sum
set operators = list strin... | import csv
import sys
from copy import deepcopy
import sqlparse
class Query():
def __init__(self, query):
if len(query[0]) < 3:
self.prError("No query given.")
query[0] = ' '.join(query[0].split())
self.agg = ['max', 'min', 'avg', 'sum']
self.operators = ['>=', '<=', '>'... | Python | zaydzuhri_stack_edu_python |
function add_nodes self nodes
begin
for node in nodes
begin
call add_node node
end
end function | def add_nodes(self, nodes):
for node in nodes:
self.add_node(node) | Python | nomic_cornstack_python_v1 |
import math
import string
class LittleElephantAndIntervalsDiv2
begin
function getNumber self M L R
begin
set s = set
set count = 0
for i in reversed call xrange 0 length L
begin
set is_paint = false
for n in range L at i R at i + 1
begin
if n not in s
begin
set is_paint = true
end
add s n
end
for else
begin
if is_paint... | import math
import string
class LittleElephantAndIntervalsDiv2:
def getNumber(self, M, L, R):
s = set()
count = 0
for i in reversed(xrange(0, len(L))):
is_paint = False
for n in range(L[i], R[i]+1):
if n not in s:
is_paint = True
... | Python | zaydzuhri_stack_edu_python |
async function listen_to_playlist player app sleep_time=1 recache_time=10
begin
set playlist = none
set last_cached_timestamp = now
while true
begin
await sleep sleep_time
set now = now
if call total_seconds > recache_time
begin
call get_playlist
end
set new_playlist = call get_cached_playlist
if new_playlist is not pl... | async def listen_to_playlist(player, app, sleep_time=1, recache_time=10):
playlist = None
last_cached_timestamp = datetime.now()
while True:
await asyncio.sleep(sleep_time)
now = datetime.now()
if (now - last_cached_timestamp).total_seconds() > recache_time:
player.get_pl... | Python | nomic_cornstack_python_v1 |
string 通过对比可以看出,匿名函数lambda x: x * x实际上就是: def f(x): return x * x 关键字lambda表示匿名函数,冒号前面的x表示函数参数。 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。 用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
set f = lambda x -> x * x
print f
print f dist 5
string 同样,也可以把匿名函数作为返回值返回,比如:
function build x y
begin
ret... | '''
通过对比可以看出,匿名函数lambda x: x * x实际上就是:
def f(x):
return x * x
关键字lambda表示匿名函数,冒号前面的x表示函数参数。
匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
'''
f = lambda x: x * x
print(f)
print(f(5))
'''
同样,也可以把匿名函数作为返回值返回,比如:
'''
def build(x, y):
return ... | Python | zaydzuhri_stack_edu_python |
function from_file filepath=none parent_filepath=none
begin
set fullpath = call full_filepath filepath parent_filepath
set tuple raw md_path = call load_any_file filepath parent_filepath
set d = raw
if is instance d list
begin
return call ResultList d fullpath
end
else
if is instance d dict
begin
set lc_keys = call low... | def from_file(filepath: str = None, parent_filepath: str = None):
fullpath = full_filepath(filepath, parent_filepath)
raw, md_path = load_any_file(filepath, parent_filepath)
d = raw
if isinstance(d, list):
return ResultList(d, fullpath)
elif isinstance(d, dict):
... | Python | nomic_cornstack_python_v1 |
import json
set ios_data = list
set gs4_data = list
set win_data = list
set droid_data = list
set droid2_data = list
function extractIOS ios_extract
begin
set ios_split_by_error = list
set ios_string = string
for i in range length ios_extract
begin
if string HOW TO FIX in upper ios_extract at i or string HOW TO ... | import json
ios_data = []
gs4_data = []
win_data = []
droid_data = []
droid2_data = []
def extractIOS(ios_extract):
ios_split_by_error = []
ios_string = ""
for i in range(len(ios_extract)):
if ("HOW TO FIX" in ios_extract[i].upper() or "HOW TO IMPROVE" in ios_extract[i].upper()):
ios... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin python3
comment coding: utf-8
string AUTHOR: bovenson EMAIL: szhkai@qq.com FILE: change_cwd.py DATE: 17-9-6 下午3:02 DESC:
from contextlib import contextmanager
decorator contextmanager
function cwd path
begin
from os import getcwd , chdir
set cwd = get current directory
change directory path
yield
chan... | #!/usr/bin python3
# coding: utf-8
"""
AUTHOR: bovenson
EMAIL: szhkai@qq.com
FILE: change_cwd.py
DATE: 17-9-6 下午3:02
DESC:
"""
from contextlib import contextmanager
@contextmanager
def cwd(path):
from os import getcwd, chdir
cwd = getcwd()
chdir(path)
yield
chdir(cwd)
# >>> os.getcwd()
# '/home... | Python | zaydzuhri_stack_edu_python |
function skewTest skew n
begin
set n = decimal n
set Y = skew * square root n + 1.0 * n + 3.0 / 6.0 / n - 2.0
set b = 3.0 * n ^ 2 + 27.0 * n - 70.0 * n + 1.0 * n + 3.0 / n - 2.0 / n + 5.0 / n + 7.0 / n + 9.0
set w2 = square root 2.0 * b - 1.0 - 1.0
set delta = 1.0 / square root log w2 / 2.0
set alfa = square root 2.0 /... | def skewTest(skew, n):
n = float(n)
Y = skew*np.sqrt((n+1.)*(n+3.)/6./(n-2.))
b = 3.*(n**2+27.*n-70.)*(n+1.)*(n+3.)/(n-2.)/(n+5.)/(n+7.)/(n+9.)
w2 = np.sqrt(2.*(b-1.)) - 1.
delta = 1./np.sqrt(np.log(w2)/2.)
alfa = np.sqrt(2./(w2-1.))
return delta*np.log(Y/alfa + np.sqrt((Y/alfa)**2+1.)) | Python | nomic_cornstack_python_v1 |
comment -*-coding:utf8
set a = 0
set b = 0
comment a와 b를 0으로 초기화
for i in range 1 101
begin
comment i의 제곱
set a = a + i * i
comment i를 b에 더한다
set b = b + i
end
comment 제곱
print a
comment 합의 제곱중
print b * b
comment (합의 제곱)-(제곱의 합)
print b * b - a | # -*-coding:utf8
a =0
b=0
#a와 b를 0으로 초기화
for i in range(1,101):
a +=i*i#i의 제곱
b += i #i를 b에 더한다
print (a) # 제곱
print(b*b) #합의 제곱중
print((b*b)-a) # (합의 제곱)-(제곱의 합) | Python | zaydzuhri_stack_edu_python |
for note in noteList
begin
set countmatrix at pitchClass = countmatrix at pitchClass + 1
end | for note in noteList:
countmatrix[note.pitchClass] +=1 | Python | zaydzuhri_stack_edu_python |
function _list_to_string l s
begin
return join s l
end function | def _list_to_string(l, s):
return s.join(l) | Python | nomic_cornstack_python_v1 |
class Liczby_zespolone
begin
function __init__ self real imag
begin
set real = real
set imag = imag
end function
function liczba self
begin
if imag >= 0
begin
print format string {}+{}i real imag
end
else
begin
print format string {}-{}i real absolute imag
end
end function
function dodawanie z1 z2
begin
print string Su... | class Liczby_zespolone:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def liczba(self):
if self.imag >= 0:
print("{}+{}i".format(self.real, self.imag))
else:
print("{}-{}i".format(self.real, abs(self.imag)))
def dodawan... | Python | zaydzuhri_stack_edu_python |
function test_only_repofolder_addable_when_already_contains_repositories self browser
begin
call login administrator browser
assert true any filter providedBy call objectValues string Expected repositories within branch_repofolder.
open branch_repofolder
call assertEquals list string Repository Folder call addable_type... | def test_only_repofolder_addable_when_already_contains_repositories(self, browser):
self.login(self.administrator, browser)
self.assertTrue(any(filter(IRepositoryFolder.providedBy,
self.branch_repofolder.objectValues())),
'Expected repositories... | Python | nomic_cornstack_python_v1 |
import crowdai
import argparse
from sklearn.svm import SVR
import numpy as np
set parser = call ArgumentParser description=string Submit the result to crowdAI
call add_argument string --api_key dest=string api_key action=string store required=true
set args = call parse_args
comment Create the challenge object by authen... | import crowdai
import argparse
from sklearn.svm import SVR
import numpy as np
parser = argparse.ArgumentParser(description='Submit the result to crowdAI')
parser.add_argument('--api_key', dest='api_key', action='store', required=True)
args = parser.parse_args()
# Create the challenge object by authentication with cro... | Python | zaydzuhri_stack_edu_python |
from sys import exit
import pygame
from pygame.locals import *
from gui_objects import GuiObjects
set SCREEN_SIZE = tuple 800 600
class SpaceInvadersGame extends object
begin
set player_x = SCREEN_SIZE at 0 / 2 - 25
set player_y = SCREEN_SIZE at 1 - 75
set event_num = 0
function __init__ self
begin
set gui_obj = call G... | from sys import exit
import pygame
from pygame.locals import *
from gui_objects import GuiObjects
SCREEN_SIZE = (800, 600)
class SpaceInvadersGame(object):
player_x = SCREEN_SIZE[0] / 2 - 25
player_y = SCREEN_SIZE[1] - 75
event_num = 0
def __init__(self):
self.gui_obj = GuiObjects()
... | Python | zaydzuhri_stack_edu_python |
comment based on the code of https://codeforces.com/profile/pajenegod and https://codeforces.com/profile/conqueror_of_tourist
comment for printing: they use print('\n'.join(map(str, out))) instead of for ...: print(ans)
comment use pypy 3-64
import sys
from collections import defaultdict
set input = readline
set T = in... | # based on the code of https://codeforces.com/profile/pajenegod and https://codeforces.com/profile/conqueror_of_tourist
# for printing: they use print('\n'.join(map(str, out))) instead of for ...: print(ans)
# use pypy 3-64
import sys
from collections import defaultdict
input = sys.stdin.readline
T = int(input())
for ... | Python | zaydzuhri_stack_edu_python |
function calculate_statistics arr
begin
comment Check if input array is empty
if not arr
begin
return string Input array is empty.
end
comment Check if input array contains only positive integers
if not all generator expression is instance num int and num > 0 for num in arr
begin
return string Input array must contain ... | def calculate_statistics(arr):
# Check if input array is empty
if not arr:
return "Input array is empty."
# Check if input array contains only positive integers
if not all(isinstance(num, int) and num > 0 for num in arr):
return "Input array must contain only positive integers."
# ... | Python | greatdarklord_python_dataset |
comment 20-07-07_30
comment tensorflow 1 버전
comment 3 + 4 + 5
comment 4 - 3
comment 3 * 4
comment 4 / 2
import tensorflow as tf
set n0 = call constant 2
set n1 = call constant 3
set n2 = call constant 4
set n3 = call constant 5
set add = call add_n list n1 n2 n3
set sub = call subtract n2 n1
set mul = call multiply n1 ... | # 20-07-07_30
# tensorflow 1 버전
# 3 + 4 + 5
# 4 - 3
# 3 * 4
# 4 / 2
import tensorflow as tf
n0 = tf.constant(2)
n1 = tf.constant(3)
n2 = tf.constant(4)
n3 = tf.constant(5)
add = tf.add_n([n1, n2, n3])
sub = tf.subtract(n2, n1)
mul = tf.multiply(n1, n2)
div = tf.divide(n2, n0)
print('n1 :', n1) # Tensor("Const... | Python | zaydzuhri_stack_edu_python |
comment evaluation.py
comment It executes first_search, and change the color of text in web page.
import Color_elem_extraction as Cee
import Calculate_fitness_value as Cfv
from selenium.webdriver.support.color import Color
import Local_search as ls
import random
import First_search
import change_color
import Second_sea... | # evaluation.py
# It executes first_search, and change the color of text in web page.
import Color_elem_extraction as Cee
import Calculate_fitness_value as Cfv
from selenium.webdriver.support.color import Color
import Local_search as ls
import random
import First_search
import change_color
import Second_search
from se... | Python | zaydzuhri_stack_edu_python |
function _user_status
begin
set rv = dict string messages map unicode call get_flashed_messages
if is_anonymous
begin
update rv dict string logged_id false
end
else
begin
update rv dict string logged_in true ; string name display_name
end
return rv
end function | def _user_status():
rv = {
'messages': map(unicode, get_flashed_messages()),
}
if current_user.is_anonymous:
rv.update({
'logged_id': False
})
else:
rv.update({
'logged_in': True,
'name': curr... | Python | nomic_cornstack_python_v1 |
comment Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print
comment the user name of a given email address. Both user names and company names are composed of letters only.
set email = input
print split email string @ at 0 | # Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print
# the user name of a given email address. Both user names and company names are composed of letters only.
email = input()
print(email.split('@')[0]) | Python | zaydzuhri_stack_edu_python |
function identify_ha self
begin
try
begin
set hdfs_ha = 0
set yarn_ha = 0
set hive_ha = 0
set zookeeper_ha = 0
set data_hdfs = popen format string cat {} | grep dfs.nameservices config_path at string hdfs shell=true stdout=PIPE encoding=string utf-8
set tuple out_1 err = communicate data_hdfs
if length out_1 > 0
begin
... | def identify_ha(self):
try:
hdfs_ha = 0
yarn_ha = 0
hive_ha = 0
zookeeper_ha = 0
data_hdfs = subprocess.Popen(
"cat {} | grep dfs.nameservices".format(self.config_path["hdfs"]),
shell=True,
stdout=subpro... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
set n = integer input
while n > 0
begin
set n = n - 1
set t = integer input
set f = dictionary
for i in range 26
begin
set f at character ordinal string A + i = 0.0
end
comment print(f) result unorder
while t > 0
begin
set t = t - 1
set p = call raw_input
if p at 2 == string 1
begin
set f ... | # -*- coding: utf-8 -*-
n=int(input())
while n>0 :
n=n-1
t=int(input())
f=dict()
for i in range(26):
f[chr(ord('A')+i)]=0.0;
# print(f) result unorder
while t>0 :
t=t-1
p=raw_input()
if p[2] == '1':
f[p[0]]+=1
if p[2] == '-1':
f[p[1]]+=1
if p[2] == '0':
f[p[1]]+=0.5... | Python | zaydzuhri_stack_edu_python |
function _clean_freebayes_output in_file
begin
set out_file = apply format call splitext in_file
if not call file_exists out_file
begin
with open in_file as in_handle
begin
with open out_file string w as out_handle
begin
for line in in_handle
begin
if starts with line string #
begin
set line = replace line string Type=... | def _clean_freebayes_output(in_file):
out_file = apply("{0}-nodups{1}".format, os.path.splitext(in_file))
if not file_exists(out_file):
with open(in_file) as in_handle:
with open(out_file, "w") as out_handle:
for line in in_handle:
if line.startswith("#"):... | Python | nomic_cornstack_python_v1 |
import torch
from torch import optim
function select_action model state
begin
comment Samples an action according to the probability distribution induced by the model
comment Also returns the log_probability
set log_p = call forward tensor state
set action = item call multinomial exp log_p 1
return tuple action log_p a... | import torch
from torch import optim
def select_action(model, state):
# Samples an action according to the probability distribution induced by the model
# Also returns the log_probability
log_p = model.forward(torch.Tensor(state))
action = torch.multinomial(torch.exp(log_p), 1).item()
return action... | Python | zaydzuhri_stack_edu_python |
comment reliably restored by inspect
function connect_data self detailed_signal handler *data **kwargs
begin
pass
end function | def connect_data(self, detailed_signal, handler, *data, **kwargs): # reliably restored by inspect
pass | Python | nomic_cornstack_python_v1 |
class BinarySearchTree
begin
function __init__ self data
begin
set data = data
set left = none
set right = none
end function
function add_child self data
begin
if data == data
begin
return
end
else
if data < data
begin
if left
begin
call add_child data
end
else
begin
set left = call BinarySearchTree data
end
end
else
i... | class BinarySearchTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def add_child(self, data):
if data == self.data:
return
elif data < self.data:
if self.left:
self.left.add_child(data)... | Python | zaydzuhri_stack_edu_python |
import sys
import os
from iv.neural_network.license_plate import LicensePlateNetwork
set LICENSE_PLATE_NN = call LicensePlateNetwork
function config variable namespace=string IV_
begin
comment make case insensitive
set variable = upper variable
set variable_name = format string {}{} namespace variable
set value = call ... | import sys
import os
from iv.neural_network.license_plate import LicensePlateNetwork
LICENSE_PLATE_NN = LicensePlateNetwork()
def config(variable, namespace="IV_"):
# make case insensitive
variable = variable.upper()
variable_name = '{}{}'.format(namespace, variable)
value = os.getenv(variable_name... | Python | zaydzuhri_stack_edu_python |
function mesh_conway_ambo mesh
begin
return call mesh_conway_dual call mesh_conway_join mesh
end function | def mesh_conway_ambo(mesh):
return mesh_conway_dual(mesh_conway_join(mesh)) | Python | nomic_cornstack_python_v1 |
function get_run_start_intro run_call_count fetches feed_dict tensor_filters is_callable_runner=false
begin
set fetch_lines = call get_flattened_names fetches
if not feed_dict
begin
set feed_dict_lines = list call RichLine string (Empty)
end
else
begin
set feed_dict_lines = list
for feed_key in feed_dict
begin
set fee... | def get_run_start_intro(run_call_count,
fetches,
feed_dict,
tensor_filters,
is_callable_runner=False):
fetch_lines = common.get_flattened_names(fetches)
if not feed_dict:
feed_dict_lines = [debugger_cli_common.Rich... | Python | nomic_cornstack_python_v1 |
string 在一个由 'L' , 'R' 和 'X' 三个字符组成的字符串(例如"RXXLRXRXL")中进行移动操作。一次移动操作指用一个"LX"替换一个"XL",或者用一个"XR"替换一个"RX"。 现给定起始字符串start和结束字符串end,请编写代码,当且仅当存在一系列移动操作使得start可以转换成end时, 返回True。 示例 : 输入: start = "RXXLRXRXL", end = "XRLXXRRLX" 输出: True 解释: 我们可以通过以下几步将start转换成end: RXXLRXRXL -> XRXLRXRXL -> XRLXRXRXL -> XRLXXRRXL -> XRLXXRRLX 注意... | """
在一个由 'L' , 'R' 和 'X' 三个字符组成的字符串(例如"RXXLRXRXL")中进行移动操作。一次移动操作指用一个"LX"替换一个"XL",或者用一个"XR"替换一个"RX"。
现给定起始字符串start和结束字符串end,请编写代码,当且仅当存在一系列移动操作使得start可以转换成end时, 返回True。
示例 :
输入: start = "RXXLRXRXL", end = "XRLXXRRLX"
输出: True
解释:
我们可以通过以下几步将start转换成end:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
注意:... | Python | zaydzuhri_stack_edu_python |
from collections import deque
class Node
begin
function __init__ self data left=none right=none
begin
set data = data
set left = left
set right = right
end function
end class
function print_nodes root start end
begin
if root is none
begin
return
end
set queue = deque
append queue root
set level = 0
while length queue >... | from collections import deque
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def print_nodes(root, start, end):
if root is None:
return
queue = deque()
queue.append(root)
level = 0
while len(q... | Python | zaydzuhri_stack_edu_python |
function inspect_query querystring
begin
return call _parse_query querystring
end function | def inspect_query(querystring: str) -> dict:
return _parse_query(querystring) | Python | nomic_cornstack_python_v1 |
function evaluate_model model X_test y_test category_names print_report=false
begin
set score = score model X_test y_test
set y_pred = predict model X_test
set reports = dict
for tuple i col in enumerate category_names
begin
set y_test_col = iloc at tuple slice : : i
comment y_pred is a numpy array
set y_pred_col =... | def evaluate_model(model, X_test, y_test, category_names, print_report=False) -> Tuple[float, dict]:
score = model.score(X_test, y_test)
y_pred = model.predict(X_test)
reports = {}
for i, col in enumerate(category_names):
y_test_col = y_test.iloc[:, i]
# y_pred is a numpy array
... | Python | nomic_cornstack_python_v1 |
function cmd_open_with ensoapi application
begin
set seldict = call get_selection
if get seldict string files
begin
set file = seldict at string files at 0
end
else
if get seldict string text
begin
set file = strip seldict at string text
end
else
begin
set file = none
end
if not file and is file path file or is directo... | def cmd_open_with(ensoapi, application):
seldict = ensoapi.get_selection()
if seldict.get('files'):
file = seldict['files'][0]
elif seldict.get('text'):
file = seldict['text'].strip()
else:
file = None
if not (file and (os.path.isfile(file) or os.path.isdir(file))):
... | Python | nomic_cornstack_python_v1 |
function find_common_elements list1 list2
begin
set common_elements = list
for element in list1
begin
if element in list2
begin
append common_elements element
end
end
return common_elements
end function
comment Create two empty lists
set list1 = list
set list2 = list
comment Add elements to the lists
extend list1 li... | def find_common_elements(list1, list2):
common_elements = []
for element in list1:
if element in list2:
common_elements.append(element)
return common_elements
# Create two empty lists
list1 = []
list2 = []
# Add elements to the lists
list1.extend([1, 2, 3, 4, 5])
list2.extend([4, 5, 6,... | Python | jtatman_500k |
function properties self
begin
if not unpacked
begin
call __unpack
end
comment MVT encodes feature properties as a list of alternating key and
comment value indices. the keys and values themselves are deduplicated
comment in lists at the layer level (which were passed into the Feature
comment constructor).
set properti... | def properties(self):
if not self.unpacked:
self.__unpack()
# MVT encodes feature properties as a list of alternating key and
# value indices. the keys and values themselves are deduplicated
# in lists at the layer level (which were passed into the Feature
# constru... | Python | nomic_cornstack_python_v1 |
import csv , ast , json , argparse , requests , os , string
import pandas as pd
set baseurl = string https://www.thecocktaildb.com/api/json/v1/1/search.php?f=
set alphanumeric_chars = list digits + ascii_uppercase
set df = call DataFrame
for char in alphanumeric_chars
begin
set url_list = baseurl + char
set response = ... | import csv, ast, json, argparse, requests, os, string
import pandas as pd
baseurl = "https://www.thecocktaildb.com/api/json/v1/1/search.php?f="
alphanumeric_chars = list(string.digits + string.ascii_uppercase)
df = pd.DataFrame()
for char in alphanumeric_chars:
url_list = baseurl + char
response = requests.g... | Python | zaydzuhri_stack_edu_python |
comment Here b34.txt file was created externaly
comment To read a file
with open string b34.txt as file_obj
begin
set content = read file_obj
end
print content
comment we can store the file into a variable
set File = string b34.txt
with open File as f
begin
set content = read f
end
print content
comment To show the wri... | #Here b34.txt file was created externaly
#To read a file
with open('b34.txt') as file_obj:
content = file_obj.read()
print(content)
#we can store the file into a variable
File = 'b34.txt'
with open(File) as f:
content = f.read()
print(content)
#To show the write function
with open(File,'w') as... | Python | zaydzuhri_stack_edu_python |
function test_serialize_bulk_user_lists_for_deletion
begin
set userlist = call create
assert list call serialize_bulk_user_lists_for_deletion list id == list dict string _id call gen_user_list_id userlist ; string _op_type string delete
end function | def test_serialize_bulk_user_lists_for_deletion():
userlist = factories.UserListFactory.create()
assert list(serializers.serialize_bulk_user_lists_for_deletion([userlist.id])) == [
{"_id": api.gen_user_list_id(userlist), "_op_type": "delete"}
] | Python | nomic_cornstack_python_v1 |
function parse_file self
begin
set object_list = list
with open filename string r as f
begin
set start = false
for line in f
begin
if string % == line at 0
begin
set start = not start
end
else
if start
begin
set data = split line
if data != list
begin
set shape = call data at slice : - 1 :
if shape is not none
begin... | def parse_file(self):
object_list = []
with open(self.filename, "r") as f:
start = False
for line in f:
if "%" == line[0]:
start = not start
elif start:
data = line.split()
if data != []:... | Python | nomic_cornstack_python_v1 |
function useradd self username expiration=none
begin
set userentry = call get_userentry username
if userentry is not none
begin
info string User {0} already exists, skip useradd username
return
end
if expiration is not none
begin
set cmd = format string useradd -m {0} -e {1} username expiration
end
else
begin
set cmd =... | def useradd(self, username, expiration=None):
userentry = self.get_userentry(username)
if userentry is not None:
logger.info("User {0} already exists, skip useradd", username)
return
if expiration is not None:
cmd = "useradd -m {0} -e {1}".format(username, ex... | Python | nomic_cornstack_python_v1 |
function partitionMedianOf3 A p r x
begin
set i = p - 1
set j = r
while true
begin
while true
begin
set j = j - 1
if A at j <= x
begin
break
end
end
while true
begin
set i = i + 1
if A at i >= x
begin
break
end
end
if i < j
begin
set tuple A at i A at j = tuple A at j A at i
end
else
begin
return j
end
end
end function | def partitionMedianOf3(A:list, p:int, r:int, x:int) -> int:
i = p - 1
j = r
while True:
while True:
j = j - 1
if A[j]<=x:
break
while True:
i = i + 1
if A[i]>=x:
break
if i < j:
A[i], A[j] = A[j], A[i]
else:
return j | Python | nomic_cornstack_python_v1 |
function form_valid self form
begin
set object = save commit=false
set owner = user
save
call set_permissions cleaned_data at string permissions
return call HttpResponseRedirect reverse string document_metadata args=tuple id
end function | def form_valid(self, form):
self.object = form.save(commit=False)
self.object.owner = self.request.user
self.object.save()
self.object.set_permissions(form.cleaned_data['permissions'])
return HttpResponseRedirect(reverse('document_metadata', args=(self.object.id,))) | Python | nomic_cornstack_python_v1 |
comment ********************************** IMPORTS **********************************
from flask import Flask , render_template , request , redirect , url_for , flash , g
from flask_login import login_user , logout_user , login_required , current_user
from werkzeug.security import generate_password_hash , check_passwor... | #********************************** IMPORTS **********************************
from flask import Flask, render_template, request, redirect, url_for, flash, g
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from flas... | Python | zaydzuhri_stack_edu_python |
from flask import Flask , render_template
set app = call Flask __name__
decorator call route string /
function index
begin
return call render_template string index.html
end function
decorator call route string /firstInternship/
function firstInternship
begin
return call render_template string firstInternship.html
end f... | from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/firstInternship/')
def firstInternship():
return render_template('firstInternship.html')
@app.route('/Advice-By-Year=<year>')
def advice_by_year(year):
return render_templa... | 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.