code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function encrypt_byte_list_in_str bytearray_list public_encryption_key_obj
begin
set encrypted_str_list = list
for bytearray_str in bytearray_list
begin
set message_text_enc = call encrypt string decode bytearray_str string utf-8 16 at 0
append encrypted_str_list message_text_enc
end
set encrypted_message_str = join s... | def encrypt_byte_list_in_str(bytearray_list, public_encryption_key_obj):
encrypted_str_list = []
for bytearray_str in bytearray_list:
message_text_enc = public_encryption_key_obj.encrypt(str(bytearray_str.decode("utf-8")), 16)[0]
encrypted_str_list.append(message_text_enc)
encrypted_message_... | Python | nomic_cornstack_python_v1 |
function write_parameters data run_dir is_parallel
begin
call write_text join run_dir PARAMETERS_PYTHON_FILE call generate_parameters_file data is_parallel
for f in call _simulation_files data
begin
if search string SCRIPT-commandFile f
begin
call chmod string join run_dir f S_IRUSR ? S_IXUSR
end
end
end function | def write_parameters(data, run_dir, is_parallel):
pkio.write_text(
run_dir.join(template_common.PARAMETERS_PYTHON_FILE),
generate_parameters_file(
data,
is_parallel,
),
)
for f in _simulation_files(data):
if re.search(r'SCRIPT-commandFile', f):
... | Python | nomic_cornstack_python_v1 |
function _parse_args_consistent_with_mfd self
begin
set signal_parameters = call translate_keys_to_lal dictionary comprehension key : __dict__ at key for key in signal_parameter_labels if get __dict__ key none is not none
set signal_formats = dictionary comprehension key : get gps_time_and_string_formats_as_LAL key str... | def _parse_args_consistent_with_mfd(self):
self.signal_parameters = self.translate_keys_to_lal(
{
key: self.__dict__[key]
for key in self.signal_parameter_labels
if self.__dict__.get(key, None) is not None
}
)
self.signal_f... | Python | nomic_cornstack_python_v1 |
function default_start self data
begin
set Channel = get pool string sale.channel
set channel = call Channel get context string active_id
return dict string message string This wizard will import all orders and products placed on %s channel(%s). Orders will be imported only which are placed after the Last Order Import ... | def default_start(self, data):
Channel = Pool().get('sale.channel')
channel = Channel(Transaction().context.get('active_id'))
return {
'message':
"This wizard will import all orders and products placed on "
"%s channel(%s). Orders will be imported onl... | Python | nomic_cornstack_python_v1 |
function test_api_score_word self
begin
with client as client
begin
set response = get client string /api/new-game
set key_and_game_board = call get_json
set test_game_id = key_and_game_board at string gameId
set board = list list string O string N string N string E string O list string X string K string E string S str... | def test_api_score_word(self):
with self.client as client:
response = client.get("/api/new-game")
key_and_game_board = response.get_json()
test_game_id = key_and_game_board["gameId"]
games[test_game_id].board = [
["O", "N", "N", "E", "O"],
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Aug 8 09:45:46 2019 @author: 15250
import random
import math
import numpy as np
set data_set_t = list comprehension i * 1.0 / 50 for i in range 0 500
set data_set_x = list comprehension i * 1.0 / 50 for i in range - 500 500
set data_t_x = list
for t in data_set_t
beg... | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 8 09:45:46 2019
@author: 15250
"""
import random
import math
import numpy as np
data_set_t=[i*1.0/50 for i in range(0,500)]
data_set_x=[i*1.0/50 for i in range(-500,500)]
data_t_x=[]
for t in data_set_t:
for x in data_set_x:
data_t_x.append([t,x])
def generat... | Python | zaydzuhri_stack_edu_python |
for brace in sequence
begin
print string DEBUG *Q string + brace
if brace == string ( or brace == string [
begin
append Q brace
end
else
if brace == string ) or brace == string ]
begin
comment А левых открытых-то нет!!!
if length Q == 0
begin
set is_correct = false
comment дальше можно не смотреть
break
end
set left = ... | for brace in sequence:
print('DEBUG', *Q, ' + ', brace)
if brace == '(' or brace == '[':
Q.append(brace)
elif brace == ')' or brace == ']':
if len(Q) == 0: # А левых открытых-то нет!!!
is_correct = False
break # дальше можно не смотреть
left = Q.pop(... | Python | zaydzuhri_stack_edu_python |
function create_database_user self db_user=dict project_id=string
begin
set project_id = if expression project_id != string then project_id else __project_id
info string create_database_user { db_user } { project_id }
set res = post string { value } /groups/ { project_id } /databaseUsers body=db_user
end function | def create_database_user(self,db_user={},project_id=''):
project_id = project_id if project_id != '' else self.__project_id
logger.info(f'create_database_user {db_user} {project_id}')
res = self.post(f'{ApiVersion.A1.value}/groups/{project_id}/databaseUsers',body=db_user) | Python | nomic_cornstack_python_v1 |
function pe43
begin
comment s = 0
set ps = list
for perm in permutations generator expression i for i in range 10 if i != 5
begin
if perm at 3 ? 1
begin
continue
end
set perm = list perm
insert perm 5 5
if not call list_num perm at slice 7 : 10 : % 17 and not call list_num perm at slice 6 : 9 : % 13 and not call list_... | def pe43():
# s = 0
ps = []
for perm in permutations(i for i in range(10) if i != 5):
if perm[3] & 1: continue
perm = list(perm)
perm.insert(5, 5)
if not list_num(perm[7:10]) % 17 and \
not list_num(perm[6: 9]) % 13 and \
not list_num(perm[5: 8]) % 11 an... | Python | nomic_cornstack_python_v1 |
function id_ x
begin
return x
end function | def id_(x: Any) -> Any:
return x | Python | nomic_cornstack_python_v1 |
function cluster_info data paths axes optional_params
begin
set info_s = call DataFrame columns=list string centroid string area string n_nuclei string nuclei_density string eccentricity string ellipticity string rectangularity string compactness string elongation string roundness string convexity string solidity dtype... | def cluster_info(data, paths, axes, optional_params):
info_s = pd.DataFrame(
columns=['centroid', 'area', 'n_nuclei', 'nuclei_density',
'eccentricity', 'ellipticity', 'rectangularity', 'compactness',
'elongation', 'roundness', 'convexity', 'solidity'],
dtype='int64'... | Python | nomic_cornstack_python_v1 |
function sort_nicely l
begin
function tryint s
begin
try
begin
return integer s
end
except any
begin
return s
end
end function
function alphanum_key s
begin
string Turn a string into a list of string and number chunks. "z23a" -> ["z", 23, "a"]
return list comprehension call tryint c for c in split re string ([0-9]+) s
... | def sort_nicely(l):
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [tryint(c) for c in re.split('([0-9]+)', s)]
... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
import time
import os
print string start
function fa_login
begin
set browser = call PhantomJS
call implicitly_wait 10
get browser string https://coinmarketcap.com/currencies/ripple/
sleep 5
print string crawling
set sam = call find_element_by_css_selector string #quote_price
print text
pr... | from selenium import webdriver
import time
import os
print ("start")
def fa_login():
browser=webdriver.PhantomJS()
browser.implicitly_wait(10)
browser.get('https://coinmarketcap.com/currencies/ripple/')
time.sleep(5)
print ("crawling")
sam=browser.find_element_by_css_selector('#quote_price')
print (sam.text)... | Python | zaydzuhri_stack_edu_python |
comment Part 1: Decision Tree for categorical data
import pandas
import numpy
import pprint
from numpy import log2 as log
set csv_path = call raw_input string Enter path to input CSV file:
set dataset = read csv csv_path
comment split data into train data and validation data
set a = split numpy dataset list integer 0.8... | #Part 1: Decision Tree for categorical data
import pandas
import numpy
import pprint
from numpy import log2 as log
csv_path = raw_input("Enter path to input CSV file: ")
dataset = pandas.read_csv(csv_path)
#split data into train data and validation data
a = numpy.split(dataset, [int(.8 * len(dataset.index))])
data =... | Python | zaydzuhri_stack_edu_python |
function retrieve_elements arr
begin
set count_dict = dict
for elem in arr
begin
if elem not in count_dict
begin
set count_dict at elem = 1
end
else
begin
set count_dict at elem = count_dict at elem + 1
end
end
set result = list
for elem in arr
begin
if count_dict at elem == 1
begin
append result elem
end
end
return ... | def retrieve_elements(arr):
count_dict = {}
for elem in arr:
if elem not in count_dict:
count_dict[elem] = 1
else:
count_dict[elem] += 1
result = []
for elem in arr:
if count_dict[elem] == 1:
result.append(elem)
return result
| Python | greatdarklord_python_dataset |
import unittest
import xml.etree.ElementTree as ET
import os , sys
comment Add the directory above this file to the path
set CODE_DIR = directory name path __file__ + string /..
append path CODE_DIR
from version import Version
class VersionTestCase extends TestCase
begin
set file_test_version_1_A = string test_data/tes... | import unittest
import xml.etree.ElementTree as ET
import os, sys
# Add the directory above this file to the path
CODE_DIR = os.path.dirname(__file__)+"/.."
sys.path.append(CODE_DIR)
from version import Version
class VersionTestCase(unittest.TestCase):
file_test_version_1_A = "test_data/test_version_1_A.xml"
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Apr 16 13:26:08 2021 @author: jyaros
import os
import pandas as pd
from matplotlib import pyplot as plt
comment nicer plots
call use string seaborn
from scipy import stats
import numpy as np
import statsmodels.api as sm
import statsmodels.stats as sm_stats
string Load... | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 16 13:26:08 2021
@author: jyaros
"""
import os
import pandas as pd
from matplotlib import pyplot as plt
plt.style.use('seaborn') # nicer plots
from scipy import stats
import numpy as np
import statsmodels.api as sm
import statsmodels.stats as sm_stats
... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime , date , time
import pickle
function savelast t=true
begin
with open string data.pickle string wb as f
begin
dump if expression t then now else call combine call date 1 1 1 time 0 0 f
end
end function
function getlast
begin
try
begin
with open string data.pickle string rb as f
begin
return... | from datetime import datetime, date, time
import pickle
def savelast(t=True):
with open('data.pickle', 'wb') as f:
pickle.dump(datetime.now() if t else datetime.combine(date(1, 1, 1), time(0, 0)), f)
def getlast():
try:
with open('data.pickle', 'rb') as f:
return pickle.load(f)
... | Python | zaydzuhri_stack_edu_python |
function add n1 n2
begin
return n1 + n2
end function
function sub n1 n2
begin
return n1 - n2
end function
function mul n1 n2
begin
return n1 * n2
end function
function div n1 n2
begin
return n1 / n2
end function
if c is string +
begin
print string 計算結果= add a b
end
else
if c is string -
begin
print string 計算結果= sub a b... | def add(n1, n2):
return n1 + n2
def sub(n1,n2):
return n1 -n2
def mul(n1, n2):
return n1*n2
def div(n1, n2):
return n1/n2
if c is "+":
print ("計算結果=",add(a,b))
elif c is "-":
print ("計算結果=",sub(a,b))
elif c is "*":
print ("計算結果=",mul(a,b))
elif c is "/":
print ("計算結果=... | Python | zaydzuhri_stack_edu_python |
import turtle
comment q2
set x = 0
set y = 1
call pensize 1
call speed 1
call pendown
call penup
set range_val = 14
for i in range 1 range_val
begin
call setpos tuple x 0
call pendown
call setpos tuple x y
call setpos tuple - 1 y
call penup
call setpos tuple 0 0
set c = x + y
set x = y
set y = c
end
comment q1
set x = ... | import turtle
#q2
x=0
y=1
turtle.pensize(1)
turtle.speed(1)
turtle.pendown()
turtle.penup()
range_val=14
for i in range(1,range_val):
turtle.setpos((x,0))
turtle.pendown()
turtle.setpos((x,y))
turtle.setpos((-1,y))
turtle.penup()
turtle.setpos((0,0))
c=x+y
x=y
y=c
#q1
x=0
y=1
turtle.pen... | Python | zaydzuhri_stack_edu_python |
function testDescribeMissing self
begin
comment Arrange
set namespace_name = string default
set broker_name = string missing
set return_value = none
comment Act
with assert raises BrokerNotFound
begin
run string events brokers describe missing --platform=gke --cluster=cluster-1 --cluster-location=us-central1-a
end
comm... | def testDescribeMissing(self):
# Arrange
namespace_name = 'default'
broker_name = 'missing'
self.operations.GetBroker.return_value = None
# Act
with self.assertRaises(exceptions.BrokerNotFound):
self.Run('events brokers describe missing '
'--platform=gke --cluster=cluster-1... | Python | nomic_cornstack_python_v1 |
string day: 2020-10-06 url: https://leetcode-cn.com/problems/sum-of-distances-in-tree/ 题目名: 树中距离之和 给定一个无向、连通的树,树中有 N 个标记为 0...N-1 的节点以及 N-1 条边, 第 i 条边连接节点 edges[i][0] 和 edges[i][1], 返回一个表示节点 i 与其他所有节点距离之和的列表 ans, 思路: 我们通过dfs获取所有节点的深度 与 每个节点的子节点数(包括自己) 那么根节点的距离之和就是 所有节点的深度之和 那么根节点的子节点的距离之和,应该是 因为往下走了一层,所以到达其他非自己子节点的节点的距... | """
day: 2020-10-06
url: https://leetcode-cn.com/problems/sum-of-distances-in-tree/
题目名: 树中距离之和
给定一个无向、连通的树,树中有 N 个标记为 0...N-1 的节点以及 N-1 条边,
第 i 条边连接节点 edges[i][0] 和 edges[i][1],
返回一个表示节点 i 与其他所有节点距离之和的列表 ans,
思路:
我们通过dfs获取所有节点的深度 与 每个节点的子节点数(包括自己)
那么根节点的距离之和就是 所有节点的深度之和
那么根节点的子节点的距离之和,应该是
因为往下走了一层,所... | Python | zaydzuhri_stack_edu_python |
import csv
from flask import Flask , render_template , url_for , request
set app = call Flask __name__
decorator call route string /
function my_home
begin
return call render_template string index.html
end function
decorator call route string /<string:page_name>
function html_homepage page_name=string index.html
begin
... | import csv
from flask import Flask, render_template, url_for, request
app = Flask(__name__)
@app.route('/')
def my_home():
return render_template('index.html')
@app.route('/<string:page_name>')
def html_homepage(page_name = 'index.html'):
return render_template(page_name)
def write_to_csv(data):
with ope... | Python | zaydzuhri_stack_edu_python |
function test_logentry_change_message self
begin
set post_data = dict string site pk ; string title string Changed ; string hist string Some content ; string created_0 string 2008-03-12 ; string created_1 string 11:54
set change_url = reverse string admin:admin_utils_article_change args=list quote pk
set response = pos... | def test_logentry_change_message(self):
post_data = {
'site': self.site.pk, 'title': 'Changed', 'hist': 'Some content',
'created_0': '2008-03-12', 'created_1': '11:54',
}
change_url = reverse('admin:admin_utils_article_change', args=[quote(self.a1.pk)])
response =... | Python | nomic_cornstack_python_v1 |
function fit_predict self train_data roles train_features=none cv_iter=none valid_data=none valid_features=none verbose=0 log_file=none
begin
call set_stdout_level call verbosity_to_loglevel verbose
info string Start automl [1mutilizator[0m with listed constraints:
info string - time: { timeout } seconds
info string ... | def fit_predict(
self,
train_data: Any,
roles: dict,
train_features: Optional[Sequence[str]] = None,
cv_iter: Optional[Iterable] = None,
valid_data: Optional[Any] = None,
valid_features: Optional[Sequence[str]] = None,
verbose: int = 0,
log_file: s... | Python | nomic_cornstack_python_v1 |
string ' 給一個四位數的整數,將其循環旋轉兩位數,如下面的測試所示 1234 -> 3412 5678 -> 7856
function problem1 num
begin
set a = num % 100
set b = num // 100
return a * 100 + b
end function
print string { call problem1 1234 } | ''''
給一個四位數的整數,將其循環旋轉兩位數,如下面的測試所示
1234 -> 3412
5678 -> 7856
'''
def problem1(num) :
a =num%100
b =num//100
return a*100+b
print(f"{problem1(1234)}")
| Python | zaydzuhri_stack_edu_python |
function GetCreationDate self
begin
comment https://msdn.microsoft.com/en-us/library/82ab7w69.aspx
comment The DATE type is implemented using an 8-byte floating-point number
return call ToString string o
end function | def GetCreationDate(self):
# https://msdn.microsoft.com/en-us/library/82ab7w69.aspx
# The DATE type is implemented using an 8-byte floating-point number
return self.source.CreationDate.ToString('o') | Python | nomic_cornstack_python_v1 |
function nextTurn self
begin
if not done
begin
raise call ValueError
end
return call __class__ cards hands if expression turn then turn - 1 else none
end function | def nextTurn(self):
if not self.done: raise ValueError()
return self.__class__(self.cards, self.hands, self.turn-1 if self.turn else None) | Python | nomic_cornstack_python_v1 |
function associate x y
begin
comment Stolen from:
comment http://www.indiana.edu/~clcl/holoword/Site/__files/holoword.py
set z = real
return call normalize z
end function | def associate(x, y):
# Stolen from:
# http://www.indiana.edu/~clcl/holoword/Site/__files/holoword.py
z = np.fft.ifft(np.fft.fft(x) * np.fft.fft(y)).real
return normalize(z) | Python | nomic_cornstack_python_v1 |
import smtplib
from email.message import EmailMessage
set x = open string Email.txt string r
set string = string
for i in x
begin
set string = string + i
end
print type string
print encode format string string ã â À encoding=string latin1
set x = encode format string string blerg encoding=string utf-8
print decode x s... | import smtplib
from email.message import EmailMessage
x = open("Email.txt", 'r')
string = ''
for i in x:
string += i
print(type(string))
print(string.format("ã â À").encode(encoding = 'latin1'))
x = string.format("blerg").encode(encoding = 'utf-8')
print(x.decode('utf-8'))
#print(string.encode(encoding='lati... | Python | zaydzuhri_stack_edu_python |
function oauth2callback request
begin
set error = get GET string error
if error
begin
set error_msg = get GET string error_description error
return call HttpTextResponse string The authorization request failed: %s % call _safe_html error_msg
end
else
begin
set user = user
set flow = call _create_flow request
set creden... | def oauth2callback(request):
error = request.GET.get('error')
if error:
error_msg = request.GET.get('error_description', error)
return HttpTextResponse(
'The authorization request failed: %s' % _safe_html(error_msg))
else:
user = request.user
flow = _create_flow(request)
credentials = ... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import requests
class kissmangaapi
begin
function __init__ self query mangaid chapternum
begin
set query = query
set mangaid = mangaid
set chapternum = chapternum
end function
comment returns list of tuples cotaining name of manga and its id [(name1, id1), (name2, id2)]
function get_search... | from bs4 import BeautifulSoup
import requests
class kissmangaapi():
def __init__(self, query, mangaid, chapternum):
self.query = query
self.mangaid = mangaid
self.chapternum = chapternum
def get_search_results(query): # returns list of tuples cotaining name of manga and its i... | Python | zaydzuhri_stack_edu_python |
import asyncio
from unittest import TestCase
import cat
from loop_runner import LoopRunner
class Tests extends TestCase
begin
function setUp self
begin
set runner = call LoopRunner call new_event_loop
start runner
end function
function tearDown self
begin
call stop
join runner
end function
function test_forward self
be... | import asyncio
from unittest import TestCase
import cat
from loop_runner import LoopRunner
class Tests(TestCase):
def setUp(self):
self.runner = LoopRunner(asyncio.new_event_loop())
self.runner.start()
def tearDown(self):
self.runner.stop()
self.runner.join()
def test_f... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import random
import warnings
from collections import Counter
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
set dataSet = read csv string A2_t2_dataset.tsv delimiter=string header=none
call tolist
set data = iloc at tuple ... | import pandas as pd
import numpy as np
import random
import warnings
from collections import Counter
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
dataSet = pd.read_csv("A2_t2_dataset.tsv", delimiter="\t", header=None)
dataSet.astype(float).values.tolist()
da... | Python | zaydzuhri_stack_edu_python |
function least self
begin
set m = min call itervalues
return list comprehension k for tuple k v in call iteritems if v == m
end function | def least(self):
m = min(self.itervalues())
return [k for k, v in self.iteritems() if v == m] | Python | nomic_cornstack_python_v1 |
function change_words self search_path file_type from_str to_str
begin
set numb = 0
for tuple root dirs files in walk call normpath search_path
begin
for filename in files
begin
if ends with filename file_type
begin
set numb = numb + 1
comment finding absolute file path
comment eg: /home/username/tests/findwords/findwo... | def change_words(self, search_path, file_type, from_str, to_str):
numb = 0
for root, dirs, files in os.walk(os.path.normpath(search_path)):
for filename in files:
if filename.endswith(file_type):
numb += 1
# finding absolute file path... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from sklearn import preprocessing
import re
function nearest_neighbors df tgt_make tgt_model tgt_year n_neighbors=20
begin
comment Pass in a target make/model and a full feature vector dataframe get similar models/years
comment Preprocessing happens here, change this function to c... | import pandas as pd
import numpy as np
from sklearn import preprocessing
import re
def nearest_neighbors(df, tgt_make, tgt_model, tgt_year, n_neighbors=20):
# Pass in a target make/model and a full feature vector dataframe get similar models/years
#
# Preprocessing happens here, change this function to change va... | Python | zaydzuhri_stack_edu_python |
function morph_open image kernel_size shape=RECT iterations=1
begin
call _error_if_image_empty image
return call morphologyEx image MORPH_OPEN call getStructuringElement value tuple kernel_size kernel_size iterations=iterations
end function | def morph_open(
image: np.ndarray,
kernel_size: int,
shape: MorphShape = MorphShape.RECT,
iterations=1,
) -> np.ndarray:
_error_if_image_empty(image)
return cv.morphologyEx(
image,
cv.MORPH_OPEN,
cv.getStructuringElement(shape.value, (kernel_size, kernel_size)),
i... | Python | nomic_cornstack_python_v1 |
function __init__ self combo_str msg=string Not a valid combo!
begin
set combo_str = combo_str
set msg = msg
call __init__ msg
end function | def __init__(self, combo_str: str, msg: str = 'Not a valid combo!'):
self.combo_str = combo_str
self.msg = msg
super().__init__(self.msg) | Python | nomic_cornstack_python_v1 |
comment Single Neuron NN with logic that y = 50(x+1)
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
set xs = array list 1.0 2.0 3.0 4.0 5.0 6.0 10.0 11.0 15.0 dtype=float
set ys = array list 100.0 150.0 200.0 250.0 300.0 350.0 550.0 600.0 800.0 dtype=float
set mean = mean np ys
set std =... | # Single Neuron NN with logic that y = 50(x+1)
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
xs = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 10.0, 11.0, 15.0], dtype=float)
ys = np.array([100.0, 150.0, 200.0, 250.0, 300.0, 350.0, 550.0, 600.0, 800.0], dtype=float)
mean = np.mean(ys)
std... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
from bs4 import BeautifulSoup
import re
import os
import sys
function remove_html_tags data
begin
set p = compile string <.*?>
return sub string data
end function
set dir_path = directory name path real path path get current directory
set driver = call Chrome string /Users/ikhwan/capston... | from selenium import webdriver
from bs4 import BeautifulSoup
import re
import os
import sys
def remove_html_tags(data):
p = re.compile(r'<.*?>')
return p.sub('\n', data)
dir_path = os.path.dirname(os.path.realpath(os.getcwd()))
driver = webdriver.Chrome('/Users/ikhwan/capstone/chromedriver')
driver.get('https... | Python | zaydzuhri_stack_edu_python |
string Implement a function that takes as input three variables, and returns the largest of the three. Do this without using the Python max() function! The goal of this exercise is to think about some internals that Python normally takes care of for us. All you need is some variables and if statements!
function get_var... | """
Implement a function that takes as input three variables, and returns the largest of the three. Do this without using the Python max() function!
The goal of this exercise is to think about some internals that Python normally takes care of for us. All you need is some variables and if statements!
"""
def get_var(... | Python | zaydzuhri_stack_edu_python |
function version self
begin
return get environ string http_version string 1.1
end function | def version(self):
return self.environ.get("http_version", "1.1") | Python | nomic_cornstack_python_v1 |
comment check whether word is palindrome or not
set wrd = input string Please enter a word
set rvs = wrd at slice : : - 1
print rvs
if wrd == rvs
begin
print string This word is a palindrome
end
else
begin
print string This word is not a palindrome
end | # check whether word is palindrome or not
wrd=input("Please enter a word")
rvs=wrd[::-1]
print(rvs)
if wrd == rvs:
print("This word is a palindrome")
else:
print("This word is not a palindrome") | Python | zaydzuhri_stack_edu_python |
comment Definition for singly-linked list.
comment class ListNode:
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution
begin
function reverseKGroup self head k
begin
if k == 1
begin
return head
end
set fake = call ListNode 0
set next = head
set head = fake
while true
begin
set ta... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if k == 1:
return head
fake = ListNode(0)
fake.next = head
h... | Python | zaydzuhri_stack_edu_python |
function get_pathname
begin
set path_elems = split path_pkg string / at slice 0 : - 1 :
return join string / path_elems
end function | def get_pathname():
path_elems = path_pkg.split('/')[0:-1]
return '/'.join(path_elems) | Python | nomic_cornstack_python_v1 |
for i in range 0 test_sets_n
begin
set current_set = set map int split call raw_input
if length difference current_set input_set != 0
begin
set is_Super = false
end
end | for i in range(0,test_sets_n):
current_set = set(map(int,raw_input().split()))
if len(current_set.difference(input_set)) !=0:
is_Super = False | Python | zaydzuhri_stack_edu_python |
from collections import deque
from functools import partial
function maybe_int i
begin
try
begin
return integer i
end
except ValueError
begin
return i
end
end function
function move m moves
begin
call *map(maybe_int, m[1:].split('/'))
end function
function exchange dancers i j
begin
set tuple dancers at i dancers at j ... | from collections import deque
from functools import partial
def maybe_int(i):
try:
return int(i)
except ValueError:
return i
def move(m, moves):
moves[m[0]](*map(maybe_int, m[1:].split('/')))
def exchange(dancers, i, j):
dancers[i], dancers[j] = dancers[j], dancers[i]
def partner... | Python | zaydzuhri_stack_edu_python |
string If a runner runs 10 miles in 30 minutes and 30 seconds, What is his/her average speed in kilometers per hour? (Tip: 1 mile = 1.6 km)
set distance_ran_miles = 10
set time_taken_seconds = 30 * 60 + 30
set time_taken_hours = time_taken_seconds / 60 / 60
set speed_in_miles = distance_ran_miles / time_taken_hours
pri... | '''
If a runner runs 10 miles in 30 minutes and 30 seconds,
What is his/her average speed in kilometers per hour? (Tip: 1 mile = 1.6 km)
'''
distance_ran_miles = 10
time_taken_seconds = (30 * 60) + 30
time_taken_hours = (time_taken_seconds/60)/60
speed_in_miles = distance_ran_miles/time_taken_hours
print(speed_in_mil... | Python | zaydzuhri_stack_edu_python |
import pickle
import pandas as pd
import numpy as np
import os
import time
import random
import csv
from os.path import isdir
set prejudged_data_path = string ./results/prejudge/
comment Save Data
function save_data_to_pkl data data_path
begin
print string Saving + data_path + string ...
with open data_path string wb a... | import pickle
import pandas as pd
import numpy as np
import os
import time
import random
import csv
from os.path import isdir
prejudged_data_path = './results/prejudge/'
# Save Data
def save_data_to_pkl(data, data_path):
print('Saving ' + data_path + '...')
with open(data_path, 'wb') as f:
pickle.d... | Python | zaydzuhri_stack_edu_python |
function scrapeRecordIds self
begin
set data = call _getJason SOLD_URL
set stored_records = call _queryScrapedIds string records string sale
set records = list comprehension tuple d at string _id string sale false for d in data if d at string _id not in stored_records
if records
begin
call _storeData records string rec... | def scrapeRecordIds(self):
data = self._getJason(config.SOLD_URL)
stored_records = self._queryScrapedIds('records', 'sale')
records = [(d['_id'], 'sale', False) for d in data
if d['_id'] not in stored_records]
if records:
self._storeData(records, 'records'... | Python | nomic_cornstack_python_v1 |
function recoverTree self root
begin
set tuple list_val list_node = tuple list list
call inorder root list_val list_node
sort list_val
for i in range length list_val
begin
set val = list_val at i
end
return root
end function | def recoverTree(self, root: TreeNode) -> None:
list_val, list_node = [], []
self.inorder(root, list_val, list_node)
list_val.sort()
for i in range(len(list_val)):
list_node[i].val = list_val[i]
return root | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
function main
begin
set dict1 = dict string a 100 ; string b 200
comment Keys should not be same otherwise it will update existing key instead of merging
set dict2 = dict string a 300 ; string y 400
update dict1 dict2
print dict1
end function
if __name__ == string __main__
begin
call main
end | #!/usr/bin/python3
def main():
dict1={'a':100,'b':200}
dict2={'a':300,'y':400} # Keys should not be same otherwise it will update existing key instead of merging
dict1.update(dict2)
print(dict1)
if __name__=='__main__':
main()
| Python | zaydzuhri_stack_edu_python |
function _export_single_project self
begin
string Processes groups and misc options specific for CoIDE, and run generator
set expanded_dic = copy workspace
comment TODO 0xc0170: fix misc , its a list with a dictionary
if string misc in expanded_dic and boolean expanded_dic at string misc
begin
print string Using deprec... | def _export_single_project(self):
""" Processes groups and misc options specific for CoIDE, and run generator """
expanded_dic = self.workspace.copy()
# TODO 0xc0170: fix misc , its a list with a dictionary
if 'misc' in expanded_dic and bool(expanded_dic['misc']):
print ("Us... | Python | jtatman_500k |
function tile_images img_nhwc
begin
string Tile N images into one big PxQ image (P,Q) are chosen to be as close as possible, and if N is square, then P=Q. input: img_nhwc, list or array of images, ndim=4 once turned into array n = batch index, h = height, w = width, c = channel returns: bigim_HWc, ndarray with ndim=3
s... | def tile_images(img_nhwc):
"""
Tile N images into one big PxQ image
(P,Q) are chosen to be as close as possible, and if N
is square, then P=Q.
input: img_nhwc, list or array of images, ndim=4 once turned into array
n = batch index, h = height, w = width, c = channel
returns:
big... | Python | jtatman_500k |
import pandas as pd
import sys
set df = read csv string fercform1electricutilitydata19942019.csv
set alaska_total_energy = df at df at string Utility Name == string Alaska Electric Light and Power Company at list string Total Energy Sales (MWh)
print max
comment print(df[(df['Utility Name']=="Alaska Electric Light and ... | import pandas as pd
import sys
df=pd.read_csv("fercform1electricutilitydata19942019.csv")
alaska_total_energy=df[ (df['Utility Name']=="Alaska Electric Light and Power Company")][['Total Energy Sales (MWh)']]
print(alaska_total_energy.max())
#print(df[(df['Utility Name']=="Alaska Electric Light and Power Company")][[... | Python | zaydzuhri_stack_edu_python |
function test_get_unique_fields_no_unique_fields self
begin
set data_schema = call G DataSchema
call G FieldSchema data_schema=data_schema
call G FieldSchema data_schema=data_schema
call assertEquals call get_unique_fields list
end function | def test_get_unique_fields_no_unique_fields(self):
data_schema = G(DataSchema)
G(FieldSchema, data_schema=data_schema)
G(FieldSchema, data_schema=data_schema)
self.assertEquals(data_schema.get_unique_fields(), []) | Python | nomic_cornstack_python_v1 |
string 5.Singleton(单例) Singleton(单例) 意图: 保证一个类仅有一个实例,并提供一个访问它的全局访问点。 适用性: 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。
class Singleton extends object
begin
function __new__ cls *args **kwargs
begin
if not has attribute cls string _instance
begin
set org = call super Singleton cls
set _i... | """
5.Singleton(单例)
Singleton(单例)
意图:
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
适用性:
当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。
"""
class Singleton(object):
def __new__(cls,*args, **kwargs):
if not hasattr(cls,'_instance'):
org = super(Singleton,cls)
cls._ins... | Python | zaydzuhri_stack_edu_python |
function check_cli_argument
begin
if length argv != NUM_ARGS
begin
error string invalid number of arguments: <deploy.py> <config.json> <system_type> <number_of_instances>
exit ERROR
end
set config = argv at 1
set sys_type = argv at 2
set num_instances = integer argv at 3
with open config as fp
begin
set jconfig = load ... | def check_cli_argument():
if len(sys.argv) != NUM_ARGS:
logging.error(
'invalid number of arguments: <deploy.py> <config.json> <system_type> <number_of_instances>'
)
sys.exit(ERROR)
config = sys.argv[1]
sys_type = sys.argv[2]
num_instances = int(sys.argv[3])
with... | Python | nomic_cornstack_python_v1 |
function test_to_dataframe_raises self
begin
set values = dict string a array list 0 0 1 1 1 1 1 ; string b array range 7 ; string c array range 7
set time = dict string a array list 0 200 200 400 400 600 600 ; string b array list 0 200 200 400 400 600 600 ; string c array list 0 200 200 400 400 600 600
set res = call ... | def test_to_dataframe_raises(self):
values = {'a':np.array([0,0,1,1,1,1,1]),
'b':np.arange(7),
'c':np.arange(7)}
time = { 'a':np.array([0,200,200, 400, 400,600,600]),
'b':np.array([0,200,200,400, 400,600,600 ]),
... | Python | nomic_cornstack_python_v1 |
class Grid
begin
function __init__ self setupString
begin
set setUpLines = split setupString string /
set gridSize = length setUpLines
set cornerPoint = gridSize / 2
set topLeft = list
append topLeft cornerPoint * - 1
append topLeft cornerPoint * - 1
set bottomRight = list cornerPoint cornerPoint
set currentPos = tupl... | class Grid:
def __init__(self, setupString):
setUpLines = setupString.split("/")
gridSize = len(setUpLines)
cornerPoint = gridSize/2
self.topLeft = []
self.topLeft.append(cornerPoint * -1)
self.topLeft.append(cornerPoint * -1)
self.bottomRight = [cornerPoint,... | Python | zaydzuhri_stack_edu_python |
string Klavyeden girilen sayinin pozitif negatif veya 0 olduğunu söyleyen program
set girilenSayi = integer input string Sayi giriniz:
if girilenSayi > 0
begin
print string Girdiğiniz sayi pozitiftir.
end
else
if girilenSayi < 0
begin
print string Girdiğiniz sayi negatiftir.
end
else
begin
print string Girdiğiniz sayi ... | """
Klavyeden girilen sayinin pozitif negatif veya 0 olduğunu söyleyen program
"""
girilenSayi = int(input("Sayi giriniz: "))
if girilenSayi > 0:
print("Girdiğiniz sayi pozitiftir.")
elif girilenSayi < 0:
print("Girdiğiniz sayi negatiftir.")
else:
print("Girdiğiniz sayi 0'dır.")
| Python | zaydzuhri_stack_edu_python |
function max_output_buffer self *args **kwargs
begin
return call ShortPNdetector_sptr_max_output_buffer self *args keyword kwargs
end function | def max_output_buffer(self, *args, **kwargs):
return _ncofdm_swig.ShortPNdetector_sptr_max_output_buffer(self, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
string 5. Harmonic Number Desc -> Prints the Nth harmonic number: 1/1 + 1/2 + ... + 1/N (http://users.encs.concordia.ca/~chvatal/notes/harmonic.html). a. I/P -> The Harmonic Value N. Ensure N != 0 b. Logic -> compute 1/1 + 1/2 + 1/3 + ... + 1/N c. O/P -> Print the Nth Harmonic Value.
comment Using Recursion
function ha... | """
5. Harmonic Number
Desc -> Prints the Nth harmonic number: 1/1 + 1/2 + ... + 1/N
(http://users.encs.concordia.ca/~chvatal/notes/harmonic.html).
a. I/P -> The Harmonic Value N. Ensure N != 0
b. Logic -> compute 1/1 + 1/2 + 1/3 + ... + 1/N
c. O/P -> Print the Nth Harmonic Value.
"""
# Usi... | Python | zaydzuhri_stack_edu_python |
function validate data skiperrors=false fixerrors=true
begin
string Checks that the geojson data is a feature collection, that it contains a proper "features" attribute, and that all features are valid too. Returns True if all goes well. - skiperrors will throw away any features that fail to validate. - fixerrors will ... | def validate(data, skiperrors=False, fixerrors=True):
"""Checks that the geojson data is a feature collection, that it
contains a proper "features" attribute, and that all features are valid too.
Returns True if all goes well.
- skiperrors will throw away any features that fail to validate.
- fixer... | Python | jtatman_500k |
function __check_if_folder_pid self fileName
begin
with open fileName as file
begin
if length split read line file == 1
begin
return true
end
else
begin
return false
end
end
end function | def __check_if_folder_pid(self, fileName):
with open(fileName) as file:
if len(file.readline().split()) == 1:
return True
else:
return False | Python | nomic_cornstack_python_v1 |
function test_composite_pks self connection metadata
begin
set conn = connection
call exec_driver_sql string CREATE TABLE book ( id INTEGER NOT NULL, isbn VARCHAR(50) NOT NULL, title VARCHAR(100) NOT NULL, series INTEGER NOT NULL, series_id INTEGER NOT NULL, UNIQUE(series, series_id), PRIMARY KEY(id, isbn) )
set book =... | def test_composite_pks(self, connection, metadata):
conn = connection
conn.exec_driver_sql(
"""
CREATE TABLE book (
id INTEGER NOT NULL,
isbn VARCHAR(50) NOT NULL,
title VARCHAR(100) NOT NULL,
series INTEGER NOT NUL... | Python | nomic_cornstack_python_v1 |
function test_pkglibexecdir self
begin
call check_argument string pkglibexecdir
end function | def test_pkglibexecdir(self):
self.check_argument('pkglibexecdir') | Python | nomic_cornstack_python_v1 |
function crop_recommendation
begin
comment extract user input information
if method == string POST
begin
set re = call get_json
set city = re at string city
set state = re at string state
comment convert into lower case
set state = lower state
set model_ph = re at string ph
set model_n = re at string n
set model_p = re... | def crop_recommendation():
## extract user input information
if request.method == "POST":
re = request.get_json()
city = re["city"]
state = re["state"]
## convert into lower case
state = state.lower()
model_ph = re["ph"]
model_n = re["n"]
model_p =... | Python | nomic_cornstack_python_v1 |
function sparseVectorDotProduct v1 v2
begin
comment BEGIN_YOUR_CODE (around 5 lines of code expected)
return sum list comprehension v1 at m * v2 at m for m in list v1
end function
comment END_YOUR_CODE | def sparseVectorDotProduct(v1, v2):
# BEGIN_YOUR_CODE (around 5 lines of code expected)
return sum([v1[m] * v2[m] for m in list(v1)])
# END_YOUR_CODE | Python | nomic_cornstack_python_v1 |
string Example text, file.txt: Python aaaa bbbbb aaaa bbbbb aaaa bbbbb CCcc xx y y y y y Z Python program that counts characters in file
comment Open a file.
set f = open string C:\programs\file.txt string r
comment Stores character counts.
set chars = dict
comment Loop over file and increment a key for each char. | """
Example text, file.txt: Python
aaaa
bbbbb
aaaa
bbbbb
aaaa bbbbb
CCcc
xx
y y y y y
Z
Python program that counts characters in file
"""
# Open a file.
f = open(r"C:\programs\file.txt", "r")
# Stores character counts.
chars = {}
# Loop over file and increment a key for each char. | Python | zaydzuhri_stack_edu_python |
with open string input.txt string r as f ; open string output.txt string w as q
begin
set s = strip read line f
set t = strip read line f
set a = string ABCDEFGHIJKLMNOPQRSTUVWXYZ
set i = 0
if not t in s
begin
while i < 25
begin
set t = join string generator expression a at index a x + 1 % 26 for x in t
if t in s
begi... | with open("input.txt", "r") as f, open("output.txt", "w") as q:
s = f.readline().strip()
t = f.readline().strip()
a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
i = 0
if not t in s:
while i < 25:
t = ''.join(a[(a.index(x) + 1) % 26] for x in t)
if t in s:
s = ''.joi... | Python | zaydzuhri_stack_edu_python |
function get_groups self
begin
return list values groups
end function | def get_groups(self):
return list(self.groups.values()) | Python | nomic_cornstack_python_v1 |
function on_post self req resp
begin
string Send a POST request with a docker container ID and it will be deleted. Example input: {'id': "12345"}, {'id': ["123", "456"]}
set content_type = MEDIA_TEXT
set status = HTTP_200
comment verify user input
set payload = dict
if content_length
begin
try
begin
set payload = load... | def on_post(self, req, resp):
"""
Send a POST request with a docker container ID and it will be deleted.
Example input: {'id': "12345"}, {'id': ["123", "456"]}
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# verify user input
pa... | Python | jtatman_500k |
function node_desc self stable_array
begin
set ret_type = list string None * length stable_array
set ret_alias = list stable_array
set ret_desc = list stable_array
set st_map_idxs = list comprehension idx for tuple idx st in enumerate stable_array if not starts with st string unmapped
if st_map_idxs
begin
set vals_arra... | def node_desc(self, stable_array):
ret_type = ["None"] * len(stable_array)
ret_alias = list(stable_array)
ret_desc = list(stable_array)
st_map_idxs = [idx for idx, st in enumerate(stable_array) if not st.startswith('unmapped')]
if st_map_idxs:
vals_array = self.redis_... | Python | nomic_cornstack_python_v1 |
import numpy as np
set a = read lines open string POS1 string r
set a = list comprehension list comprehension y for y in split strip x if y != string for x in a
set cell = list comprehension list comprehension decimal y for y in x for x in a at slice 2 : 5 :
set cell = array cell
set ele = list comprehension x for x ... | import numpy as np
a = open(r'POS1','r').readlines()
a = [[ y for y in x.strip().split() if y != ' ' ] for x in a ]
cell = [[ float(y) for y in x] for x in a[2:5]]
cell = np.array(cell)
ele = [x for x in a[5]]
num = {}
for i in range(len(ele)) :
num[ele[i]]=int(a[6][i])
coord = []
coord_starter = 9
for ii,ij in... | Python | zaydzuhri_stack_edu_python |
function partition nums l r
begin
set p = nums at l
set i = l
set j = r
while i < j
begin
while j > i and nums at j >= p
begin
set j = j - 1
end
set nums at i = nums at j
while i < j and nums at i < p
begin
set i = i + 1
end
set nums at j = nums at i
end
set nums at i = p
return i
end function
function quick_sort nums ... | def partition(nums,l,r):
p = nums[l]
i = l
j = r
while i<j:
while j>i and nums[j] >= p:
j-=1
nums[i] = nums[j]
while i<j and nums[i] < p:
i+=1
nums[j] = nums[i]
nums[i] = p
return i
def quick_sort(nums,l,r):
if(l<r):
p = partiti... | Python | zaydzuhri_stack_edu_python |
import pandas as pda
import numpy as npy
import math as ma
import time
import datetime
import os
comment 这两个是用于的打开文件选择框
from tkinter import Tk
from tkinter.filedialog import askopenfilename
comment 这些是用来读写excel文件的
import xlwt
import xlrd
from xlutils.copy import copy
function GetSectionFileName sourFileName GpsTime tpy... | import pandas as pda
import numpy as npy
import math as ma
import time
import datetime
import os
# 这两个是用于的打开文件选择框
from tkinter import Tk
from tkinter.filedialog import askopenfilename
# 这些是用来读写excel文件的
import xlwt
import xlrd
from xlutils.copy import copy
def GetSectionFileName(sourFileName, GpsTime, tpyeFlag=1):
... | Python | zaydzuhri_stack_edu_python |
function moving self speed_threshold=2 time_threshold=string 30s filter_dict=dictionary compute_gs=3 resample_rule=string 5s
begin
set self = call cast string Flight self
set resampled = call resample resample_rule
if resampled is none or length resampled <= 2
begin
return none
end
set moving = query filter keyword fil... | def moving(
self,
speed_threshold: float = 2,
time_threshold: str = "30s",
filter_dict: Dict[str, int] = dict(compute_gs=3),
resample_rule: str = "5s",
) -> Optional["Flight"]:
self = cast("Flight", self)
resampled = self.resample(resample_rule)
if r... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Jun 2 12:19:58 2020 @author: MOHANA D
comment Please write a program to generate all sentences where subject is in ["I", "You"] and
comment verb is in ["Play", "Love"] and the object is in ["Hockey","Football"].
comment Hints: Use list[index] notation to get a element... | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 2 12:19:58 2020
@author: MOHANA D
"""
#Please write a program to generate all sentences where subject is in ["I", "You"] and
#verb is in ["Play", "Love"] and the object is in ["Hockey","Football"].
#Hints: Use list[index] notation to get a element from a list... | Python | zaydzuhri_stack_edu_python |
string Set custom grains
function some_grain
begin
string Setting some_grain
set grains = dict
set grains at string some_grain = string some_grain_value
return grains
end function | ''' Set custom grains '''
def some_grain():
''' Setting some_grain '''
grains = {}
grains['some_grain'] = 'some_grain_value'
return grains
| Python | zaydzuhri_stack_edu_python |
function valid_year year
begin
if year and is digit year
begin
set year = integer year
if year > 1900 and year < 2020
begin
return year
end
end
end function | def valid_year(year):
if year and year.isdigit():
year = int(year)
if year > 1900 and year < 2020:
return year | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string Module for api reddit
import requests
function number_of_subscribers subreddit
begin
string get the number of suscribers
set url = format string https://www.reddit.com/r/{}/about.json subreddit
set headers = dict string User-Agent string Manu
set response = get requests url headers=head... | #!/usr/bin/python3
""" Module for api reddit """
import requests
def number_of_subscribers(subreddit):
""" get the number of suscribers """
url = 'https://www.reddit.com/r/{}/about.json'.format(subreddit)
headers = {'User-Agent': 'Manu'}
response = requests.get(url, headers=headers, allow_redirects... | Python | zaydzuhri_stack_edu_python |
function _get_unused_port
begin
comment type: () -> int
with call closing call socket AF_INET SOCK_STREAM as s
begin
call bind tuple string 0
return call getsockname at 1
end
end function | def _get_unused_port():
# type: () -> int
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("", 0))
return s.getsockname()[1] | Python | nomic_cornstack_python_v1 |
function he_initializer shape
begin
set tuple fan_in _ = call compute_fans shape
set stddev = square root 2.0 / fan_in
return call truncated_normal_initializer stddev=stddev
end function | def he_initializer(shape):
fan_in, _ = compute_fans(shape)
stddev = np.sqrt(2.0 / fan_in)
return tf.truncated_normal_initializer(stddev=stddev) | Python | nomic_cornstack_python_v1 |
function test_bind_endpoint_to_base_url self
begin
set given_base_url = string https://example.org/api
set given_endpoint = string hello/world
set expected = string https://example.org/api/hello/world
set requester = call Requester
call set_base_url given_base_url
set actual = call bind_endpoint_to_base_url given_endpo... | def test_bind_endpoint_to_base_url(self) -> None:
given_base_url = "https://example.org/api"
given_endpoint = "hello/world"
expected = "https://example.org/api/hello/world"
requester = Requester()
requester.set_base_url(given_base_url)
actual = requester.bind_endpoint_... | Python | nomic_cornstack_python_v1 |
function show_history self user
begin
set header = call connect __path
set curs = call cursor
set encrypted_id = hex digest md5 encode string id + string typicaluser
execute curs string SELECT * FROM users WHERE id = (?) tuple encrypted_id
set data = call fetchall at 0 at 1
return data
end function | def show_history(self, user: TelegramController.User):
header = connect(self.__path)
curs = header.cursor()
encrypted_id = md5((str(user.id) + "typicaluser").encode()).hexdigest()
curs.execute("SELECT * FROM users WHERE id = (?)", (encrypted_id,))
data = curs.fetchall()[0][1]
... | Python | nomic_cornstack_python_v1 |
from pprint import pprint
import openpyxl
class Exexl_handler
begin
function __init__ self excel_file
begin
comment 打开表格
set workbook = open excel_file
end function
function read self sheet_name
begin
comment 获取sheet页
set work_register = workbook at sheet_name
comment 获取所有数据
set data_sheet = list values
set header = da... | from pprint import pprint
import openpyxl
class Exexl_handler:
def __init__(self,excel_file):
self.workbook = openpyxl.open(excel_file) #打开表格
def read(self,sheet_name):
work_register = self.workbook[sheet_name] #获取sheet页
data_sheet = list(work_register.values) #获取所有数据
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Dec 4 12:08:20 2019 @author: carlottaceccacci
function ReadFASTA data_location
begin
if data_location at slice - 4 : : == string .txt
begin
with open data_location as f
begin
return call ParseFASTA f
end
end
end function
function ParseF... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 4 12:08:20 2019
@author: carlottaceccacci
"""
def ReadFASTA(data_location):
if data_location[-4:] == '.txt':
with open(data_location) as f:
return ParseFASTA(f)
def ParseFASTA(f):
... | Python | zaydzuhri_stack_edu_python |
function put self
begin
return call get_health
end function | def put(self):
return self.get_request_handler(request.headers).get_health() | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Задание 9.3 Создать функцию get_int_vlan_map, которая обрабатывает конфигурационный файл коммутатора и возвращает кортеж из двух словарей: * словарь портов в режиме access, где ключи номера портов, а значения access VLAN (числа): {'FastEthernet0/12': 10, 'FastEthernet0/14': 11, 'Fas... | # -*- coding: utf-8 -*-
"""
Задание 9.3
Создать функцию get_int_vlan_map, которая обрабатывает конфигурационный
файл коммутатора и возвращает кортеж из двух словарей:
* словарь портов в режиме access, где ключи номера портов,
а значения access VLAN (числа):
{'FastEthernet0/12': 10,
'FastEthernet0/14': 11,
'FastEth... | Python | zaydzuhri_stack_edu_python |
string Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b - x|, or |a - x| == |b - x| and a < b Example 1: Input: arr = [1,2,3,4,5], k = 4, x = 3 Outp... | """
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
O... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import json
import random
import sys
function main
begin
if length argv != 2
begin
print string Usage: rmap_select.py <routemap json file>
return 1
end
with open argv at 1 as json_file
begin
set data = load json json_file
for elem in data at string map
begin
print string labels: { elem at ... | #!/usr/bin/env python3
import json
import random
import sys
def main():
if len(sys.argv) != 2:
print("Usage: rmap_select.py <routemap json file>")
return 1
with open(sys.argv[1]) as json_file:
data = json.load(json_file)
for elem in data["map"]:
print(f"labels: {e... | Python | zaydzuhri_stack_edu_python |
import sys
set stdin = open string 5097_sample_input.txt string r
set T = integer input
for test_case in range 1 T + 1
begin
set tuple N M = map int split input
set numbers = list map int split input
set index = M % N
print format string #{} {} test_case numbers at index
end | import sys
sys.stdin = open('5097_sample_input.txt', 'r')
T = int(input())
for test_case in range(1, T+1):
N, M = map(int, input().split())
numbers = list(map(int, input().split()))
index = M % N
print('#{} {}'.format(test_case, numbers[index]))
| Python | zaydzuhri_stack_edu_python |
function numIslands4 grid
begin
return list comprehension list comprehension call count_neighbors2 grid i j string 1 for j in range length grid at i for i in range length grid
end function | def numIslands4(grid):
return [[count_neighbors2(grid, i, j, "1") for j in range(len(grid[i]))]
for i in range(len(grid))] | Python | nomic_cornstack_python_v1 |
for i in range first_line
begin
for j in range second_line
begin
set tuple name at i at j marks at i at j = split input
set marks at i at j = decimal marks at i at j
end
end
set list1 = list comprehension second_line for x in range first_line
set counter = 0
while true
begin
if counter >= first_line * second_line
begin... | for i in range(first_line):
for j in range(second_line):
name[i][j], marks[i][j] = input().split()
marks[i][j] = float(marks[i][j])
list1 = [second_line for x in range(first_line)]
counter = 0
while(True):
if counter >= first_line*second_line:
break
for i in range(first_line):
... | Python | zaydzuhri_stack_edu_python |
function optimalSum target nums
begin
set dp = list decimal string inf * target + 1
set dp at 0 = 0
for num in nums
begin
for i in range num target + 1
begin
if dp at i - num + 1 < dp at i
begin
set dp at i = dp at i - num + 1
end
end
end
if dp at target == decimal string inf
begin
return - 1
end
return dp at target
en... | def optimalSum(target, nums):
dp = [float('inf')] * (target + 1)
dp[0] = 0
for num in nums:
for i in range(num, target + 1):
if dp[i - num] + 1 < dp[i]:
dp[i] = dp[i - num] + 1
if dp[target] == float('inf'):
return -1
return dp[target]
target = 10
num... | Python | jtatman_500k |
comment https://leetcode.com/problems/merge-sorted-array/
function merge_sorted_arr_2 nums1 nums2
begin
set result = list
set size_1 = length nums1
set size_2 = length nums2
set tuple i j = tuple 0 0
if size_1 == 0
begin
return nums2
end
if size_2 == 0
begin
return nums1
end
while i < size_1 and j < size_2
begin
if nu... | # https://leetcode.com/problems/merge-sorted-array/
def merge_sorted_arr_2(nums1, nums2):
result = []
size_1 = len(nums1)
size_2 = len(nums2)
i, j = 0, 0
if size_1 == 0:
return nums2
if size_2 == 0:
return nums1
while i < size_1 and j < size_2:
if nums1[i] < nums2[... | Python | zaydzuhri_stack_edu_python |
function test_api_delete_share self
begin
set mock_http_connection = HTTPConnection
set side_effect = list call FakeLoginResponse call FakeGetBasicInfoResponseEs_1_1_3 call FakeLoginResponse call FakeDeleteShareResponse
call _do_setup string http://1.2.3.4:8080 string 1.2.3.4 string admin string qnapadmin string Storag... | def test_api_delete_share(self):
mock_http_connection = http_client.HTTPConnection
mock_http_connection.return_value.getresponse.side_effect = [
fakes.FakeLoginResponse(),
fakes.FakeGetBasicInfoResponseEs_1_1_3(),
fakes.FakeLoginResponse(),
fakes.FakeDelet... | Python | nomic_cornstack_python_v1 |
function create_opencl_context
begin
info string Creating OpenCL context
if string PYOPENCL_CTX in environ
begin
info format string PYOPENCL_CTX is set to "{0}" environ at string PYOPENCL_CTX
info string Using default PyOpenCL context selection
return call create_some_context interactive=false
end
if string X_SGE_CUDA_... | def create_opencl_context():
log.info('Creating OpenCL context')
if 'PYOPENCL_CTX' in os.environ:
log.info('PYOPENCL_CTX is set to "{0}"'.format(os.environ['PYOPENCL_CTX']))
log.info('Using default PyOpenCL context selection')
return cl.create_some_context(interactive=False)
if 'X_... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.