code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import sqlite3
if __name__ == string __main__
begin
set connector = call connect string sqlite_test.db
set sql = string CREATE TABLE uptime1( datetime DATETIME, onemnt DECIMAL, fivemnt DECIMAL, fifteenmnt DECIMAL );
end | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
if __name__ == "__main__":
connector = sqlite3.connect("sqlite_test.db")
sql = """
CREATE TABLE uptime1(
datetime DATETIME,
onemnt DECIMAL,
fivemnt DECIMAL,
fifteenmnt D... | Python | zaydzuhri_stack_edu_python |
function default_parameters self
begin
return dict string x call global_coordinates ; string h call mesh_parameters
end function | def default_parameters(self):
return {'x': self.global_coordinates(),
'h': self.mesh_parameters()} | Python | nomic_cornstack_python_v1 |
import requests
import json
import pandas as pd
function request_stock_data stock_ids start_date=string 20150101 end_date=string 20160101
begin
set stocks_request = get requests string https://www.blackrock.com/tools/hackathon/performance params=dict string identifiers join string , stock_ids ; string startDate start_d... | import requests
import json
import pandas as pd
def request_stock_data(stock_ids, start_date='20150101', end_date='20160101'):
stocks_request= requests.get("https://www.blackrock.com/tools/hackathon/performance",
params= {'identifiers': ','.join(stock_ids),
'startDate': start_date,
'endDate': end_date,
... | Python | zaydzuhri_stack_edu_python |
string Tag: tree Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty. Example: [1,2,3,4,5] 1 / 2 3 / \ 4 5 Output: [[4,5,3],[2],[1]]
from typing import List
class TreeNode
begin
function __init__ self x
begin
set val = x
set left = none
se... | """
Tag: tree
Given a binary tree, collect a tree's nodes as if you were doing this:
Collect and remove all leaves, repeat until the tree is empty.
Example: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: [[4,5,3],[... | Python | zaydzuhri_stack_edu_python |
comment dictionary 字典
set words = dict string ramen string 拉麵 ; string pasta string 義大利麵
comment 增加新的key
set words at string tea = string 茶
print words
comment print(words['ramen'])
comment print(words['pasta']) | # dictionary 字典
words = {
'ramen': '拉麵',
'pasta': '義大利麵'
}
words['tea'] = '茶' # 增加新的key
print(words)
# print(words['ramen'])
# print(words['pasta'])
| Python | zaydzuhri_stack_edu_python |
function ascribe_absites lat
begin
comment first just attempt to load it from lat.lp['meshfn']
set abfn = call prepdir lp at string meshfn + string absites.pkl
if glob glob abfn
begin
with open abfn string r as fn
begin
set abdict = load pickle fn
end
set asites = abdict at string asites
set bsites = abdict at string b... | def ascribe_absites(lat):
# first just attempt to load it from lat.lp['meshfn']
abfn = dio.prepdir(lat.lp['meshfn']) + 'absites.pkl'
if glob.glob(abfn):
with open(abfn, 'r') as fn:
abdict = pickle.load(fn)
asites = abdict['asites']
bsites = abdict['bsites']
else:
... | Python | nomic_cornstack_python_v1 |
function plots_from_files imspaths figsize=tuple 10 5 rows=1 titles=none maintitle=none
begin
set f = figure figsize=figsize
if maintitle is not none
begin
call suptitle maintitle fontsize=10
end
for i in range length imspaths
begin
set sp = call add_subplot rows call ceildiv length imspaths rows i + 1
axis string Off
... | def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None):
f = plt.figure(figsize=figsize)
if maintitle is not None: plt.suptitle(maintitle, fontsize=10)
for i in range(len(imspaths)):
sp = f.add_subplot(rows, ceildiv(len(imspaths), rows), i+1)
sp.axis('Off')
... | Python | nomic_cornstack_python_v1 |
from ui.login_view import LoginView
from ui.todos_view import TodosView
from ui.create_user_view import CreateUserView
class UI
begin
function __init__ self root
begin
set root = root
set current_view = none
end function
function hide_current_view self
begin
if current_view
begin
call destroy
end
set current_view = non... | from ui.login_view import LoginView
from ui.todos_view import TodosView
from ui.create_user_view import CreateUserView
class UI:
def __init__(self, root):
self.root = root
self.current_view = None
def hide_current_view(self):
if self.current_view:
self.current_view.destroy... | Python | zaydzuhri_stack_edu_python |
import socket
import time
import pickle
import numpy as np
import cv2
comment Handles message receiving
function receive_message client_socket HEADER_LENGTH
begin
try
begin
comment Receive our "header" containing message length, it's size is defined and constant
set message_header = call recv HEADER_LENGTH
comment If w... | import socket
import time
import pickle
import numpy as np
import cv2
# Handles message receiving
def receive_message(client_socket, HEADER_LENGTH):
try:
# Receive our "header" containing message length, it's size is defined and constant
message_header = client_socket.recv(HEADER_LENGTH)
# If we received no d... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
comment @Time : 2019/3/31 23:50
comment @Author : LuoJie
comment @Email : 2715053558@qq.com
comment @File : PysparkTest.py
comment @Software: PyCharm
from __future__ import print_function
import sys
from operator import add
import math
from pyspark import SparkCon... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/3/31 23:50
# @Author : LuoJie
# @Email : 2715053558@qq.com
# @File : PysparkTest.py
# @Software: PyCharm
from __future__ import print_function
import sys
from operator import add
import math
from pyspark import SparkConf, SparkContext
def cosine(t):... | Python | zaydzuhri_stack_edu_python |
function release
begin
from secrets import pypi_auth
comment Check that all changes are committed before creating a new version
call git_check
comment Test package
call test
comment Increment version
call inc_version
comment Commit new version, create tag for version and push everything to origin
call git_push
comment ... | def release():
from secrets import pypi_auth
# Check that all changes are committed before creating a new version
git_check()
# Test package
test()
# Increment version
inc_version()
# Commit new version, create tag for version and push everything to origin
git_push()
# Buil... | Python | nomic_cornstack_python_v1 |
import re
import datetime
from pyspark.sql import SparkSession , Row
set spark = call getOrCreate
set apache_access_log_pattern = string ^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+) (\S+)" (\d{3}) (\S+)
set month_map = dict string Jan 1 ; string Feb 2 ; string Mar 3 ; string Apr 4 ; string May 5 ; string J... | import re
import datetime
from pyspark.sql import SparkSession, Row
spark = SparkSession.builder.config("spark.sql.warehouse.dir", "file:///C:/tmp").appName("Weblog").getOrCreate()
apache_access_log_pattern = '^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+) (\S+)" (\d{3}) (\S+)'
month_map = {'Jan': 1, 'Feb... | Python | zaydzuhri_stack_edu_python |
function find_br htmllist
begin
set listoflines = list
for i in range length htmllist
begin
if string <br in htmllist at i
begin
append listoflines i
end
end
if listoflines == list
begin
return string none
end
else
begin
return listoflines
end
end function | def find_br(htmllist):
listoflines = []
for i in range(len(htmllist)):
if "<br" in htmllist[i]:
listoflines.append(i)
if listoflines == []:
return "none"
else:
return listoflines | Python | nomic_cornstack_python_v1 |
function f x
begin
for item in l
begin
if call repr item not in call repr x
begin
return false
end
end
return true
end function
function isPrime x
begin
if x == 1
begin
return false
end
if x == 2
begin
return true
end
for i in call xrange 2 integer x ^ 0.5 + 1
begin
if x % i == 0
begin
return false
end
end
return true
... | def f(x):
for item in l:
if repr(item) not in repr(x): return False
return True
def isPrime(x):
if x ==1: return False
if x== 2: return True
for i in xrange(2,int(x**0.5)+1):
if x%i == 0: return False
return True
l2=[] | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
function draw_one_Liner_Regression_chart data data_name issave=false save_path=string Liner_Regression_chart.png
begin
string 绘制DataFram中单条数据的线性回归图 :param data: 包含所有数据信息的DataFrame :param data_name: DataFrame中某一列的名字 :param issave: 是否保存绘制的图片 :param... | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def draw_one_Liner_Regression_chart(data, data_name, issave=False, save_path="Liner_Regression_chart.png"):
"""
绘制DataFram中单条数据的线性回归图
:param data: 包含所有数据信息的DataFrame
:param data_name: DataFrame中某一列的名字
:param issave: 是否保存绘制的图... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset , DataLoader
class Generator extends Module
begin
function __init__ self latent_dim=5 output_dim=2 hidden_sizes=tuple 10 5
begin
call __i... | import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
class Generator(nn.Module):
def __init__(self, latent_dim=5, output_dim=2, hidden_sizes=(10, 5)):
super().__ini... | Python | zaydzuhri_stack_edu_python |
import tkinter as tk
set win = call Tk
title win string TK GUI
set label = call Label win text=string Hello
call pack
set button = call Button win text=string Press
call pack
set entry = call Entry win text=string Entry
call pack
call mainloop | import tkinter as tk
win = tk.Tk()
win.title("TK GUI")
label = tk.Label(win, text="Hello")
label.pack()
button = tk.Button(win, text="Press")
button.pack()
entry = tk.Entry(win, text="Entry")
entry.pack()
win.mainloop()
| Python | zaydzuhri_stack_edu_python |
function __get__ self parent objtype
begin
return partial __call__ parent
end function | def __get__(self, parent, objtype):
return functools.partial(self.__call__, parent) | Python | nomic_cornstack_python_v1 |
import sys
import nltk
import re
set TERMINALS = string Adj -> "country" | "dreadful" | "enigmatical" | "little" | "moist" | "red" Adv -> "down" | "here" | "never" Conj -> "and" | "until" Det -> "a" | "an" | "his" | "my" | "the" N -> "armchair" | "companion" | "day" | "door" | "hand" | "he" | "himself" N -> "holmes" | ... | import sys
import nltk
import re
TERMINALS = """
Adj -> "country" | "dreadful" | "enigmatical" | "little" | "moist" | "red"
Adv -> "down" | "here" | "never"
Conj -> "and" | "until"
Det -> "a" | "an" | "his" | "my" | "the"
N -> "armchair" | "companion" | "day" | "door" | "hand" | "he" | "himself"
N -> "holmes" | "home"... | Python | zaydzuhri_stack_edu_python |
import unittest
from src.design_patterns.behavioral.registry import RegistryHolder , BaseRegisteredClass
class ClassRegistree extends BaseRegisteredClass
begin
function __init__ self *args **kwargs
begin
pass
end function
end class
class RegistryTest extends TestCase
begin
function setUp self
begin
pass
end function
fu... | import unittest
from src.design_patterns.behavioral.registry import RegistryHolder, BaseRegisteredClass
class ClassRegistree(BaseRegisteredClass):
def __init__(self, *args, **kwargs):
pass
class RegistryTest(unittest.TestCase):
def setUp(self) -> None:
pass
def test_before_subclassing(se... | Python | zaydzuhri_stack_edu_python |
function setData self data
begin
set oldData = call _getData
if oldData is data
begin
return
end
call __resetItem
call _syncScaleToButtonsEnabled
if data is not none
begin
set _data = call ref data _dataAboutToFinalize
set _itemHolder = call _DataRefHolder _data
end
set _dataRange = none
set _histogramData = none
call ... | def setData(self, data):
oldData = self._getData()
if oldData is data:
return
self.__resetItem()
self._syncScaleToButtonsEnabled()
if data is not None:
self._data = weakref.ref(data, self._dataAboutToFinalize)
self._itemHolder = _DataRefHolder... | Python | nomic_cornstack_python_v1 |
function __init__ __self__ accelerators=none advanced_machine_features=none boot_disk_kms_key=none confidential_nodes=none disk_size_gb=none disk_type=none ephemeral_storage_config=none ephemeral_storage_local_ssd_config=none fast_socket=none gcfs_config=none gvnic=none image_type=none kubelet_config=none labels=none l... | def __init__(__self__, *,
accelerators: Optional[pulumi.Input[Sequence[pulumi.Input['AcceleratorConfigArgs']]]] = None,
advanced_machine_features: Optional[pulumi.Input['AdvancedMachineFeaturesArgs']] = None,
boot_disk_kms_key: Optional[pulumi.Input[str]] = None,
... | Python | nomic_cornstack_python_v1 |
function connect_db db_path key decrypt_db=false sqlcipher_exe=string sqlcipher **decryption_pragmas
begin
info string Opening encrypted-db%s: %s db_path if expression decrypt_db then string with { sqlcipher_exe } else string
comment type: ignore[assignment]
set db : Connection = none
set decrypted_file = none
set sql_... | def connect_db(
db_path: Path,
key,
decrypt_db: bool = False,
sqlcipher_exe: PathIsh = "sqlcipher",
**decryption_pragmas: Mapping[str, Any],
) -> Iterator[sqlite3.Connection]:
logger.info(
"Opening encrypted-db%s: %s",
db_path,
f" with {sqlcipher_exe}" if decrypt_db else ... | Python | nomic_cornstack_python_v1 |
function diff_analysis
begin
set lof_xls_file = string { Data_path } /wind/你只是不懂LOF.xlsx
comment close_xls_file = f'{Data_path}/wind/上市封闭式基金.xlsx'
print lof_xls_file
set df_lof = call read_excel lof_xls_file sheet_name=0
print string LOF基金统计 describe df_lof at list string 贴水 string 贴水率
set lof_img_name = string { Data_... | def diff_analysis():
lof_xls_file = f'{Data_path}/wind/你只是不懂LOF.xlsx'
# close_xls_file = f'{Data_path}/wind/上市封闭式基金.xlsx'
print(lof_xls_file)
df_lof = pd.read_excel(lof_xls_file, sheet_name=0)
print('LOF基金统计\n', df_lof[['贴水', '贴水率']].describe())
lof_img_name = f'{Data_path}/wind/LOF(场内)贴水率轴须图.... | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
set __author__ = string jixiuf
comment usage:
comment python get_exportjson_related_files.py a.ExportJson
import json
import sys
function getJson filename
begin
with open filename as data_file
begin
set value = load json data_file
return value
end
end function
if __name__ == string __main__... | # -*- coding:utf-8 -*-
__author__ = 'jixiuf'
# usage:
# python get_exportjson_related_files.py a.ExportJson
import json
import sys
def getJson(filename):
with open(filename) as data_file:
value = json.load(data_file)
return value
if __name__ == '__main__':
if len(sys.argv) != 2:
print... | Python | zaydzuhri_stack_edu_python |
function get_headline_data website_url source
begin
set page = get requests website_url
call raise_for_status
set all_headlines = list
set bs_obj = call BeautifulSoup text string html.parser
set item_list = select bs_obj string item
set printable = set printable
for curr_item in item_list
begin
set item_title = string... | def get_headline_data(website_url, source):
page = requests.get(website_url)
page.raise_for_status()
all_headlines = []
bs_obj = bs4.BeautifulSoup(page.text, 'html.parser')
item_list = bs_obj.select('item')
printable = set(string.printable)
for curr_item in item_list:
item_title = curr_item.title.string
foll... | Python | nomic_cornstack_python_v1 |
function password self
begin
return get pulumi self string password
end function | def password(self) -> Optional[Any]:
return pulumi.get(self, "password") | Python | nomic_cornstack_python_v1 |
function vrand self v
begin
set vtemp = randn size
return reshape vtemp shape
end function | def vrand(self,v):
vtemp = np.random.randn(v.size)
return vtemp.reshape(v.shape) | Python | nomic_cornstack_python_v1 |
function stonith_show stonith_id extra_args=none cibfile=none
begin
return call item_show item=string stonith item_id=stonith_id extra_args=extra_args cibfile=cibfile
end function | def stonith_show(stonith_id, extra_args=None, cibfile=None):
return item_show(
item="stonith", item_id=stonith_id, extra_args=extra_args, cibfile=cibfile
) | Python | nomic_cornstack_python_v1 |
function UseExistingBootDisk disks
begin
return any generator expression get disk string boot false for disk in disks
end function | def UseExistingBootDisk(disks):
return any(disk.get('boot', False) for disk in disks) | Python | nomic_cornstack_python_v1 |
function action_cancel self cr uid ids context=none
begin
return write self cr uid ids dict string state string inprogress context=context
end function | def action_cancel(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state': 'inprogress'}, context=context) | Python | nomic_cornstack_python_v1 |
from abc import abstractmethod , ABC
class Interface
begin
decorator staticmethod
function get_main
begin
print string * * 10
print string Основное меню:
print string 1. Оборудование
print string 2. Доступные остатки на складе
print string 3. Подразделения компании
print string 4. Завершить
print string * * 10
try
begi... | from abc import abstractmethod, ABC
class Interface:
@staticmethod
def get_main():
print('*'*10)
print("Основное меню:")
print("1. Оборудование")
print("2. Доступные остатки на складе")
print("3. Подразделения компании")
print("4. Завершить")
print('*' ... | Python | zaydzuhri_stack_edu_python |
function __init__ self user
begin
set cards = list
set score = 0
set user = user
end function | def __init__(self, user):
self.cards = []
self.score = 0
self.user = user | Python | nomic_cornstack_python_v1 |
from collections import deque
function bfs N M
begin
set queue = deque
append queue tuple N 0
set check = dict
while queue
begin
set tuple item count = call popleft
if get check item 0
begin
continue
end
set check at item = 1
if item == M
begin
return count
end
set count = count + 1
if 0 < item + 1 <= 1000000
begin
ap... | from collections import deque
def bfs(N, M):
queue = deque()
queue.append((N, 0))
check = {}
while queue:
item, count = queue.popleft()
if check.get(item, 0):
continue
check[item] = 1
if item == M:
return count
count += 1
if 0 < it... | Python | zaydzuhri_stack_edu_python |
function test_reset_password self
begin
set dietitian = get query 1
call reset_password string newpass dietitian
assert equal true call check_password string newpass
end function | def test_reset_password(self):
dietitian = Dietitian.query.get(1)
reset_password("newpass", dietitian)
self.assertEqual(True, dietitian.check_password("newpass")) | Python | nomic_cornstack_python_v1 |
function view_project_terms self project_id language_code=none
begin
set data = call _run url_path=string terms/list id=project_id language=language_code
return get data at string result string terms list
end function | def view_project_terms(self, project_id, language_code=None):
data = self._run(
url_path="terms/list",
id=project_id,
language=language_code
)
return data['result'].get('terms', []) | Python | nomic_cornstack_python_v1 |
function buy_coin self base_currency quote_currency amount
begin
set currency_pair = base_currency + string / + quote_currency
set balance_quote_currency = call get_balance quote_currency
comment reserve enough market space
set tuple market_available avg_price price_range = call cal_buy_price currency_pair decimal amou... | def buy_coin(self, base_currency, quote_currency, amount):
currency_pair = base_currency + '/' + quote_currency
balance_quote_currency = self.get_balance(quote_currency)
# reserve enough market space
market_available, avg_price, price_range = self.cal_buy_price(currency_pair, float(am... | Python | nomic_cornstack_python_v1 |
function build_app backend_implementation error_handling=true import_name=__name__
begin
set app = call OpenEoApiApp import_name=import_name
decorator url_defaults
function _add_version endpoint values
begin
string Blueprint.url_defaults handler to automatically add "version" argument in `url_for` calls.
if string vers... | def build_app(
backend_implementation: OpenEoBackendImplementation,
error_handling=True,
import_name=__name__,
) -> OpenEoApiApp:
app = OpenEoApiApp(import_name=import_name)
@app.url_defaults
def _add_version(endpoint, values):
"""Blueprint.url_defaults handler to automatica... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function canMakeArithmeticProgression self arr
begin
if length arr == 2
begin
return true
end
else
if length arr >= 3
begin
sort arr
set d = arr at 1 - arr at 0
for i in range 1 length arr - 1
begin
if arr at i + 1 - arr at i != d
begin
return false
end
end
return true
end
end function
end class | class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
if(len(arr)==2):
return True
elif(len(arr)>=3):
arr.sort()
d=arr[1]-arr[0]
for i in range(1,len(arr)-1):
if(arr[i+1]-arr[i]!=d):
return ... | Python | zaydzuhri_stack_edu_python |
with open string sample.txt as a_file
begin
set count = 0
while read line a_file
begin
set text = read line a_file
for char in strip_char
begin
set text = lower replace text char string
set list_of_words = split text
end
for word in list_of_words
begin
if word in my_Dict
begin
set my_Dict at word = my_Dict at word + 1
... | with open("sample.txt") as a_file:
count = 0
while a_file.readline():
text = a_file.readline()
for char in strip_char:
text=text.replace(char, "").lower()
list_of_words = text.split()
for word in list_of_words:
if word in my_Dict:
my_Di... | Python | zaydzuhri_stack_edu_python |
function equal_sum_partition arr p
begin
set ac = cumulative sum np arr
comment generates the cumulative sums of each part
set cum_part_sums = array range 1 p * ac at - 1 // p
comment finds the indexes where the cumulative sums are sandwiched
return call searchsorted ac cum_part_sums
end function | def equal_sum_partition(arr: np.array, p: int):
ac = np.cumsum(arr)
cum_part_sums = np.array(range(1, p)) * (ac[-1] // p) # generates the cumulative sums of each part
return np.searchsorted(ac, cum_part_sums) # finds the indexes where the cumulative sums are sandwiched | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import requests
set response = get requests string https://finance.naver.com/item/main.nhn?code=005930
set html = text
set soup = call BeautifulSoup html string html5lib
set result = find soup string table dict string class string tb_type1 tb_num
set all_data = select result string tr:nth-... | from bs4 import BeautifulSoup
import requests
response = requests.get("https://finance.naver.com/item/main.nhn?code=005930")
html = response.text
soup = BeautifulSoup(html, 'html5lib')
result = soup.find('table', {'class': 'tb_type1 tb_num'})
all_data = result.select('tr:nth-of-type(11) td')
all_result = []
for i in a... | Python | zaydzuhri_stack_edu_python |
comment String-Methode format()
set string1 = format string Das ist ein Template {} string String
comment wenn neben {} noch ein {} eingefügt wird, kommt fehlermeldung, weil ein Platzhalter leer ist
print string1
comment Template String mit zwei Platzhaltern
set string2 = format string Es sind viele {} {} string natürl... | #String-Methode format()
string1 = "Das ist ein Template {}".format("String")
#wenn neben {} noch ein {} eingefügt wird, kommt fehlermeldung, weil ein Platzhalter leer ist
print(string1)
# Template String mit zwei Platzhaltern
string2 = "Es sind viele {} {}".format("natürlich", "möglich")
print(string2)
# übergebene... | Python | zaydzuhri_stack_edu_python |
function yeardayscalendar self year width
begin
pass
end function | def yeardayscalendar(self, year,width):
pass | Python | nomic_cornstack_python_v1 |
function myfunction
begin
print string a function has been created
end function | def myfunction():
print("a function has been created ") | Python | nomic_cornstack_python_v1 |
function serialize_sk sk
begin
return call hexlify call to_string
end function | def serialize_sk(sk):
return hexlify(sk.to_string()) | Python | nomic_cornstack_python_v1 |
comment python3
import sys
function compute_min_refills distance tank stops
begin
comment write your code here
set capacity = tank
append stops distance
set ans = 0
if distance <= tank
begin
return 0
end
else
begin
for i in range length stops
begin
comment check feasibility
if i == 0 and stops at i > capacity or i > 0 ... | # python3
import sys
def compute_min_refills(distance, tank, stops):
# write your code here
capacity = tank
stops.append(distance)
ans=0
if(distance <= tank):
return 0
else:
for i in range(len(stops)):
#check feasibility
if((i==0 and stops[i] > capacity) or (i>0 and stops... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3.7
comment -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
from vcgencmd import Vcgencmd
comment Vc = Vcgencmd();
import sys , struct , smbus , sys , time , subprocess , threading
global Capacity Volt Temp USV t1 LastCapacity
comment Script settings ###
comment min. Capacity from Battery in p... | #!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
from vcgencmd import Vcgencmd
#Vc = Vcgencmd();
import sys,struct,smbus,sys,time,subprocess,threading
global Capacity, Volt, Temp, USV, t1, LastCapacity
### Script settings ###
minC=75 # min. Capacity from Battery in percent
mAh=560 ... | Python | zaydzuhri_stack_edu_python |
function MagnetPosError_6d magnet_pos_6d Bt sensor_param Measured_data
begin
set Measured_data = reshape Measured_data tuple 16 3
set sensor_pos = sensor_param at tuple slice : : slice 0 : 3 :
set sensor_rotation = sensor_param at tuple slice : : slice 3 : 6 :
set sensor_rotation_matrix = list
for r_v in senso... | def MagnetPosError_6d(magnet_pos_6d, Bt, sensor_param, Measured_data):
Measured_data = Measured_data.reshape((16,3))
sensor_pos = sensor_param[:, 0:3]
sensor_rotation = sensor_param[:, 3:6]
sensor_rotation_matrix = []
for r_v in sensor_rotation:
sensor_rotation_matrix.append( np.dot( yaw_ma... | Python | nomic_cornstack_python_v1 |
from __future__ import division
comment -*- coding: utf-8 -*-
string Created on Thu Feb 28 14:42:15 2013 @author: ttran
from pylab import *
from copy import deepcopy
from scipy import linalg
comment this function, swapRows, was adapted from
comment Numerical Methods Engineering with Python, Jean Kiusalaas
function swap... | from __future__ import division
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 28 14:42:15 2013
@author: ttran
"""
from pylab import *
from copy import deepcopy
from scipy import linalg
# this function, swapRows, was adapted from
# Numerical Methods Engineering with Python, Jean Kiusalaas
def swapRows(v,i,j):
"""Swa... | Python | zaydzuhri_stack_edu_python |
function sendScreenSysex self data line=1
begin
if not data
begin
pass
end
if line == 1
begin
call _send_midi SYSEX_SCREEN_BEGIN_LINE_1 + data + SYSEX_SCREEN_END
end
else
if line == 2
begin
call _send_midi SYSEX_SCREEN_BEGIN_LINE_2 + data + SYSEX_SCREEN_END
end
end function | def sendScreenSysex(self, data, line=1):
if not data:
pass
if(line==1):
self._send_midi(((SYSEX_SCREEN_BEGIN_LINE_1 + data) + SYSEX_SCREEN_END))
else:
if(line==2):
self._send_midi(((SYSEX_SCREEN_BEGIN_LINE_2 + data) + SYSEX_SCREEN_END)) | Python | nomic_cornstack_python_v1 |
from operator import add , sub , mul , gt , eq , and_
from functools import reduce
class Point
begin
comment __init__ function is the constructor
function __init__ self ref=list 0 0
begin
try
begin
set coords = list ref
end
except TypeError
begin
set coords = coords
end
set dim = length coords
end function
decorator st... | from operator import add, sub, mul, gt, eq, and_
from functools import reduce
class Point:
# __init__ function is the constructor
def __init__(self, ref=[0, 0]):
try:
self.coords = list(ref)
except TypeError:
self.coords = ref.coords
self.dim = len(self.coords)
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
import socket
function main
begin
set sock = call socket AF_INET SOCK_STREAM
call connect tuple string localhost 3001
while 1
begin
set receive_data = call recv 1024
set receive_data = string decode receive_data string utf-8
print string server > receive_data
set send_data = input string cl... | # -*- coding:utf-8 -*-
import socket
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 3001))
while (1):
receive_data = sock.recv(1024)
receive_data = str(receive_data.decode('utf-8'))
print("server > ", receive_data)
send_data ... | Python | zaydzuhri_stack_edu_python |
import torch
class EvalCounter
begin
string A counter for loss or metric Attributes: items (dict(str: int)) - the number of items during one stage counter (dict(str: float)) - sum of valid data during one stage items_epoch (dict(str: int)) - the number of items during one epoch counter_epoch (dict(str: float)) - sum of... | import torch
class EvalCounter:
"""A counter for loss or metric
Attributes:
items (dict(str: int)) - the number of items during one stage
counter (dict(str: float)) - sum of valid data during one stage
items_epoch (dict(str: int)) - the number of items during one epoch
counter... | Python | zaydzuhri_stack_edu_python |
from src.refactor_bowling import Game_Score
comment Los casos test en comentario estaban destinados a la construcción individualizada de las funciones y son inviables en su conjunto.
comment def test_strike_score():
comment assert 19 == Game_Score('X36').strike_score()
comment assert 16 == Game_Score('5X422').strike_sc... | from src.refactor_bowling import Game_Score
# Los casos test en comentario estaban destinados a la construcción individualizada de las funciones y son inviables en su conjunto.
# def test_strike_score():
# assert 19 == Game_Score('X36').strike_score()
# assert 16 == Game_Score('5X422').strike_score()
# def... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
from polygon_intersection.polygon import Polygon
from polygon_intersection.convex_intersect import convexIntersect
import sys
function get_intersection poly1 poly2
begin
comment print (poly2.convex())
comment print (poly2.simple())
comment print (poly1.intersect(poly2)... | import matplotlib.pyplot as plt
import numpy as np
from polygon_intersection.polygon import Polygon
from polygon_intersection.convex_intersect import convexIntersect
import sys
def get_intersection(poly1, poly2):
# print (poly2.convex())
# print (poly2.simple())
# print (poly1.intersect(poly2))
interse... | Python | zaydzuhri_stack_edu_python |
from random import seed , uniform , random
from utils import Function , generatePoints , generateY
import numpy as np
import matplotlib.pyplot as plt
from perceptron import Perceptron
function linear_regression X y
begin
set X_pseudo_inverse = call pinv X
set w = dot y
return w
end function
set func = call Function
set... | from random import seed, uniform, random
from utils import Function, generatePoints, generateY
import numpy as np
import matplotlib.pyplot as plt
from perceptron import Perceptron
def linear_regression(X, y):
X_pseudo_inverse = np.linalg.pinv(X)
w = X_pseudo_inverse.dot(y)
return w
func = Function()
x0 = ... | Python | zaydzuhri_stack_edu_python |
function choices self var
begin
return curr_domains or domains at var
end function | def choices(self, var):
return (self.curr_domains or self.domains)[var] | Python | nomic_cornstack_python_v1 |
function split self parent feature threshold
begin
if Left is not none or Right is not none
begin
return tuple none none
end
comment Add left node; it registers with parent
set nleft = call Node parent true
comment Add right node; it registers with parent
set nright = call Node parent false
set feature = feature
set th... | def split(self, parent, feature, threshold):
if parent.Left is not None or parent.Right is not None:
return None, None
nleft = Node(parent, True) # Add left node; it registers with parent
nright = Node(parent, False) # Add right node; it registers with parent
parent.featur... | Python | nomic_cornstack_python_v1 |
function postfixes seq
begin
set n = length seq
for i in call xrange n
begin
yield seq at slice n - i - 1 : :
end
end function | def postfixes(seq):
n = len(seq)
for i in xrange(n):
yield seq[n-i-1:] | Python | nomic_cornstack_python_v1 |
function julian2datetimeindex j tz=UTC
begin
set tuple year month day hour minute second microsecond = call julian2date j
return call DatetimeIndex list comprehension call datetime y m d h mi s ms tz for tuple y m d h mi s ms in zip year month day hour minute second microsecond
end function | def julian2datetimeindex(j, tz=pytz.UTC):
year, month, day, hour, minute, second, microsecond = julian2date(j)
return pd.DatetimeIndex([dt.datetime(y, m, d, h, mi, s, ms, tz)
for y, m, d, h, mi, s, ms in
zip(year, month, day, hour, minute,
... | Python | nomic_cornstack_python_v1 |
import os
import unittest
import piera
try
begin
import StringIO
end
except ImportError
begin
import io as StringIO
end
set tuple current_dirname _ = split path absolute path path __file__
class BaseTestPiera extends TestCase
begin
function setUp self
begin
set base = current_dirname
set hiera = call Hiera join path cu... | import os
import unittest
import piera
try:
import StringIO
except ImportError:
import io as StringIO
current_dirname, _ = os.path.split(os.path.abspath(__file__))
class BaseTestPiera(unittest.TestCase):
def setUp(self):
self.base = current_dirname
self.hiera = piera.Hiera(os.path.join(c... | Python | zaydzuhri_stack_edu_python |
comment Lawrence McAfee
comment ~~~~~~~~ import ~~~~~~~~
from modules.node.HierNode import HierNode
from modules.node.LeafNode import LeafNode
from modules.node.Stage import Stage
from modules.node.block.CodeBlock import CodeBlock as cbk
from modules.node.block.HierBlock import HierBlock as hbk
from modules.node.block.... | # Lawrence McAfee
# ~~~~~~~~ import ~~~~~~~~
from modules.node.HierNode import HierNode
from modules.node.LeafNode import LeafNode
from modules.node.Stage import Stage
from modules.node.block.CodeBlock import CodeBlock as cbk
from modules.node.block.HierBlock import HierBlock as hbk
from modules.node.block.ImageBlock ... | Python | zaydzuhri_stack_edu_python |
comment ans part 1: 3423
comment ans part 2: 7493
from collections import defaultdict
function day18 instructions pid
begin
set registers = default dictionary int
set registers at string p = pid
set pos = 0
set send_queue = list
while pos < length instructions
begin
set tuple command arg1 *opt_arg = split strip instru... | # ans part 1: 3423
# ans part 2: 7493
from collections import defaultdict
def day18(instructions, pid):
registers = defaultdict(int)
registers['p'] = pid
pos = 0
send_queue = []
while pos < len(instructions):
command, arg1, *opt_arg = instructions[pos].strip().split()
if opt_arg:... | Python | zaydzuhri_stack_edu_python |
comment !/usr/local/bin/python3
import os
import sys
set path = input string Enter your directory path:
if exists path path
begin
set df_l = list directory path
end
else
begin
print string Please provide valid path:
exit
end
string p1=os.path.join(path,df_l[0]) p2=os.path.join(path,df_l[1]) #print(os.path.join(path,p1)... | #!/usr/local/bin/python3
import os
import sys
path=input("Enter your directory path: ")
if os.path.exists(path):
df_l=os.listdir(path)
else:
print("Please provide valid path: ")
sys.exit()
"""
p1=os.path.join(path,df_l[0])
p2=os.path.join(path,df_l[1])
#print(os.path.join(path,p1))
if os.path.isfile(p2):
print(... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import urlparse
comment import requests this has to run on python 2.4...
comment import BeautifulSoup # this has to be run on python 2.4...
import urllib
import pprint
import yaml
import glob
import os
from compat import parse_qsl
set sourcecode = strip read open string apikey.txt
function... | # -*- coding: utf-8 -*-
import urlparse
#import requests this has to run on python 2.4...
#import BeautifulSoup # this has to be run on python 2.4...
import urllib
import pprint
import yaml
import glob
import os
from compat import parse_qsl
sourcecode = open('apikey.txt').read().strip()
def get_degree_status(degr... | Python | zaydzuhri_stack_edu_python |
function add num1 num2
begin
print num1 + num2
end function
add 21 67
add 24 98 | def add(num1,num2):
print(num1+num2)
add(21,67)
add(24,98) | Python | zaydzuhri_stack_edu_python |
string # Extract a sample using the code provided in the project notes OSM_FILE = "seattle_washington.osm" SAMPLE_FILE = "sample.osm" k = 200 # Parameter: take every k-th top level element def get_element(osm_file, tags=('node', 'way', 'relation')): context = iter(ET.iterparse(osm_file, events=('start', 'end'))) _, roo... | '''
# Extract a sample using the code provided in the project notes
OSM_FILE = "seattle_washington.osm"
SAMPLE_FILE = "sample.osm"
k = 200 # Parameter: take every k-th top level element
def get_element(osm_file, tags=('node', 'way', 'relation')):
context = iter(ET.iterparse(osm_file, events=('start', 'end')))
... | Python | zaydzuhri_stack_edu_python |
import pyttsx3
import PyPDF2
set book = open string samplebook.pdf string rb
set pdfReader = call PdfFileReader book
set pages = numPages
print pages
set speaker = call init
for x in range pages
begin
set page = call getPage x
set text = call extractText
comment speaker.say("Hare Krishna Hare Krishna Krishna Krishna Ha... | import pyttsx3
import PyPDF2
book = open('samplebook.pdf','rb')
pdfReader = PyPDF2.PdfFileReader(book)
pages = pdfReader.numPages
print(pages)
speaker = pyttsx3.init()
for x in range(pages):
page = pdfReader.getPage(x)
text=page.extractText()
#speaker.say("Hare Krishna Hare Krishna Krishna Krishna Hare Hare Hare ... | Python | zaydzuhri_stack_edu_python |
string #Ordem de precedência: (), **, *,/,//,%, + e - #Programa que recebe o nome nome = input('digite seu nome ') print('prazer em conhecer, {} '.format(nome)) #Programa que lê dois valores n1 = int(input('digite o primeiro num ')) n2 = int(input('digite o segundo num ')) n3 = n1 + n2 print(n3) a = input('Digite algo:... | """
#Ordem de precedência: (), **, *,/,//,%, + e -
#Programa que recebe o nome
nome = input('digite seu nome ')
print('prazer em conhecer, {} '.format(nome))
#Programa que lê dois valores
n1 = int(input('digite o primeiro num '))
n2 = int(input('digite o segundo num '))
n3 = n1 + n2
print(n3)
a = input('Digite algo:... | Python | zaydzuhri_stack_edu_python |
function QuickSort
begin
set less = list
set equal = list
set greater = list
if length A > 1
begin
set pivot = A at 0
for i in A
begin
if i < pivot
begin
append less i
end
else
if i > pivot
begin
append greater i
end
else
begin
append equal i
end
end
return call QuickSort less + equal + call QuickSort greater
end
el... | def QuickSort():
less = []
equal = []
greater = []
if len(A) > 1:
pivot = A[0]
for i in A:
if i < pivot:
less.append(i)
elif i > pivot:
greater.append(i)
else:
equal.append(i)
return QuickSort(le... | Python | zaydzuhri_stack_edu_python |
function configure_database self
begin
from model.meta import create_transaction_manager_aware_dbsession
from model.interfaces import ISQLAlchemySessionFactory
call include string pyramid_retry
call include string pyramid_tm
call include string .model.meta
call registerAdapter factory=create_transaction_manager_aware_d... | def configure_database(self):
from .model.meta import create_transaction_manager_aware_dbsession
from .model.interfaces import ISQLAlchemySessionFactory
self.config.include("pyramid_retry")
self.config.include("pyramid_tm")
self.config.include(".model.meta")
self.config... | Python | nomic_cornstack_python_v1 |
function nitems_written self *args **kwargs
begin
return call lte_random_bit_gen_sptr_nitems_written self *args keyword kwargs
end function | def nitems_written(self, *args, **kwargs):
return _my_lte_swig.lte_random_bit_gen_sptr_nitems_written(self, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
function cast obj
begin
return call itkNoiseImageFilterISS2ISS2_cast obj
end function | def cast(obj: 'itkLightObject') -> "itkNoiseImageFilterISS2ISS2 *":
return _itkNoiseImageFilterPython.itkNoiseImageFilterISS2ISS2_cast(obj) | Python | nomic_cornstack_python_v1 |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler , MinMaxScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score , confusion_matrix
comment Read the dataset
set data = read csv string data.csv
comment Split the dataset
set X ... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix
# Read the dataset
data = pd.read_csv('data.csv')
# Split the dataset
X = data.drop(['label'... | Python | flytech_python_25k |
import scrapy
import pymysql
from bs4 import BeautifulSoup
from scrapyspider.items import Review
import time
comment 继承自scrapy.Spider
class TripadvisorSpider extends Spider
begin
set name = string tripadvisor_co
function start_requests self
begin
set my_sql = call connect host=string 127.0.0.1 port=3306 user=string roo... | import scrapy
import pymysql
from bs4 import BeautifulSoup
from scrapyspider.items import Review
import time
# 继承自scrapy.Spider
class TripadvisorSpider(scrapy.Spider):
name = "tripadvisor_co"
def start_requests(self):
my_sql = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment Date : 2019-11-28
comment Author : Yuanbo Zhao (chaojunction@gmail.com)
from link_list_fun import ListNode , generateNum , printListNode
comment in O(n) time and O(1) space
function isPalindrome head
begin
comment rev records the first half, need to set... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date : 2019-11-28
# Author : Yuanbo Zhao (chaojunction@gmail.com)
from link_list_fun import ListNode, generateNum, printListNode
# in O(n) time and O(1) space
def isPalindrome(head: ListNode) -> bool:
# rev records the first half, need to set the same structure ... | Python | zaydzuhri_stack_edu_python |
function setup_logger level=DEBUG format_str=string [%(levelname)-6s] [%(threadName)-10s] [%(asctime)-24s] %(message)s
begin
set logger = call getLogger
for sh in handlers
begin
call removeHandler sh
end
call setLevel DEBUG
set formatter = call Formatter format_str
set sh = call StreamHandler
call setLevel level
call s... | def setup_logger(level=logging.DEBUG, format_str='[%(levelname)-6s] [%(threadName)-10s] [%(asctime)-24s] %(message)s'):
logger = logging.getLogger()
for sh in logger.handlers:
logger.removeHandler(sh)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(format_str)
sh = logging.Strea... | Python | nomic_cornstack_python_v1 |
function sparse_cross_entropy y_true y_pred
begin
comment Calculate the loss. This outputs a 2 rank tensor of shape [batch_size, seq_length]
set loss = call sparse_softmax_cross_entropy_with_logits labels=y_true logits=y_pred
comment Keras may reduce this across the first axis (the batch) but the semantics are unclear,... | def sparse_cross_entropy(y_true, y_pred):
# Calculate the loss. This outputs a 2 rank tensor of shape [batch_size, seq_length]
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=y_true, logits=y_pred)
# Keras may reduce this across the first axis (the batch) but the semantics are unclea... | Python | nomic_cornstack_python_v1 |
function guess_filepaths_from_filenames dirpath filenames
begin
return generator expression call path_secure join path dirpath record_filename for record_filename in filenames
end function | def guess_filepaths_from_filenames(
dirpath: str,
filenames: Iterable[str]
):
return (path_secure(path.join(dirpath, record_filename))
for record_filename in filenames) | Python | nomic_cornstack_python_v1 |
from google.cloud import texttospeech
import sys
import subprocess
comment Instantiates a client
set client = call TextToSpeechClient
set filename = string output.mp3
function start output_text
begin
call output_mp3 output_text
call speech
end function
function output_mp3 output_text
begin
comment Set the text input to... | from google.cloud import texttospeech
import sys
import subprocess
# Instantiates a client
client = texttospeech.TextToSpeechClient()
filename = 'output.mp3'
def start(output_text):
output_mp3(output_text)
speech()
def output_mp3(output_text):
# Set the text input to be synthesized
synthesis_input = ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import serial
import json
import sys
comment import string
comment import datetime
class sensorComm
begin
function __init__ self
begin
set serialData = call Serial string /dev/ttyAMA0 115200
set pumpPWM = 1500
set hose = 0
set irrigation = 0
set logToDisk = false
set recSerialData = string ... | #!/usr/bin/env python
import serial
import json
import sys
#import string
#import datetime
class sensorComm():
def __init__(self):
self.serialData = serial.Serial('/dev/ttyAMA0', 115200)
self.pumpPWM = 1500
self.hose = 0
self.irrigation = 0
self.logToDisk = False
s... | Python | zaydzuhri_stack_edu_python |
import collections
set g = list comprehension list for _ in range n + 1
set dic = dict
for _ in range m
begin
set tuple u v a b = map int split input
append g at u v
append g at v u
set dic at tuple u v = tuple a b
set dic at tuple v u = tuple a b
end
set arr = list list 0 0 + list comprehension list map int split in... | import collections
g = [[] for _ in range(n+1)]
dic = {}
for _ in range(m):
u,v,a,b = map(int,input().split())
g[u].append(v)
g[v].append(u)
dic[(u,v)]=(a,b)
dic[(v,u)]=(a,b)
arr = [[0,0]]+[list(map(int,input().split())) for _ in range(n)]
cost =[[float('inf')]*2501 for _ in range(n+1)]
for i in ran... | Python | jtatman_500k |
function pprint_contributors contributors
begin
if not contributors
begin
return
end
for c in contributors
begin
print format string {} {} call ljust 50 string _ c at 1
end
end function | def pprint_contributors(contributors: List[Tuple[str, int]]) -> None:
if not contributors:
return
for c in contributors:
print("{} {}".format(c[0].ljust(50, "_"), c[1])) | Python | nomic_cornstack_python_v1 |
function put self new_item item_id
begin
set item = get session Timeseries item_id
if item is none
begin
call abort 404
end
call check_etag item TimeseriesSchema
update call TimeseriesSchema item new_item
add session item
commit session
return item
end function | def put(self, new_item, item_id):
item = db.session.get(Timeseries, item_id)
if item is None:
abort(404)
blp.check_etag(item, TimeseriesSchema)
TimeseriesSchema().update(item, new_item)
db.session.add(item)
db.session.commit()
return item | Python | nomic_cornstack_python_v1 |
import tqdm
import torch
import torchvision
class TrainingClass
begin
function __init__ self model optimizer scheduler config trainloader validloader writer device tokenizer
begin
set config = config
set model = model
set optimizer = optimizer
set scheduler = scheduler
set trainloader = trainloader
set validloader = va... | import tqdm
import torch
import torchvision
class TrainingClass:
def __init__(self, model, optimizer, scheduler, config,
trainloader, validloader, writer, device, tokenizer):
self.config = config
self.model = model
self.optimizer = optimizer
self.scheduler = sched... | Python | zaydzuhri_stack_edu_python |
for counter in range 1 11
begin
print string * * x
set x = x - 1
end | for counter in range(1,11):
print('*'*x)
x=x-1 | Python | zaydzuhri_stack_edu_python |
function format_mpd_status_time v both=false
begin
set arr_v = split v string :
set time_current = call format_time integer arr_v at 0 true
if both
begin
set time_total = call format_time integer arr_v at 1 true
return time_current + string / + time_total
end
else
begin
return time_current
end
end function | def format_mpd_status_time(v, both=False):
arr_v = v.split(':')
time_current = format_time(int(arr_v[0]), True)
if both:
time_total = format_time(int(arr_v[1]), True)
return time_current + '/' + time_total
else:
return time_current | Python | nomic_cornstack_python_v1 |
function trainModel self data attributes class_label
begin
call trainModelOnSubset data attributes class_label
end function | def trainModel(self, data, attributes, class_label):
self.trainModelOnSubset(data, attributes, class_label) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding:utf-8 -*-
string 牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
string 思路: 首先需要写一个reverse函数,把任何输入的字符串完全翻转。然后从前往后依次遍历新字符串,如果遇到空格,就把空格前的字... | # !/usr/bin/env python3
# -*- coding:utf-8 -*-
'牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?'
"""
思路:
首先需要写一个reverse函数,把任何输入的字符串完全翻转。然后从前往后依次遍历新字符串,如果遇到空格,就把空格前的字符串用reverse翻转,添加空格... | Python | zaydzuhri_stack_edu_python |
function from_smiles smi
begin
set rdm = call MolFromSmiles smi
assert rdm is not none
return rdm
end function | def from_smiles(smi):
rdm = _rd_chem.MolFromSmiles(smi)
assert rdm is not None
return rdm | Python | nomic_cornstack_python_v1 |
from src.ashild_grotan_ex.ex01.letter_counts import letter_freq
from math import log2
function entropy message
begin
string takes a string and calculates the message entropy of the string :param message: str :return: float
set msg_freq = call letter_freq message
set total = length message
set msg_entropy = 0
for i in m... | from src.ashild_grotan_ex.ex01.letter_counts import letter_freq
from math import log2
def entropy(message):
"""
takes a string and calculates the message entropy of the string
:param message: str
:return: float
"""
msg_freq = letter_freq(message)
total = len(message)
msg_entropy = 0
... | Python | zaydzuhri_stack_edu_python |
function _get_element self xpath=none selenium_element=none lxml_element=none
begin
comment Get the xpath associated with this element.
if xpath is none and selenium_element is not none
begin
set xpath = call _get_xpath_for_selenium_element selenium_element
end
if xpath is none and lxml_element is not none
begin
set xp... | def _get_element(self, xpath=None, selenium_element=None, lxml_element=None):
# Get the xpath associated with this element.
if xpath is None and selenium_element is not None:
xpath = self._get_xpath_for_selenium_element(selenium_element)
if xpath is None and lxml_element is not None... | Python | nomic_cornstack_python_v1 |
function hailstone n
begin
string append the terms of a hailstone sequence to the list sequence. return sequence
set sequence = list
function path n
begin
string generate a term in a hailstone sequence
append sequence n
if n == 1
begin
return n
end
else
if n % 2 == 0
begin
set n = n / 2
return call path n
end
else
beg... | def hailstone(n):
"""
append the terms of a hailstone sequence to the list sequence.
return sequence
"""
sequence = []
def path(n):
"""
generate a term in a hailstone sequence
"""
sequence.append(n)
if n == 1:
return n
elif n%2 == 0:
n = n/2
return path(n)
else:
n = 3*n + 1
return pa... | Python | zaydzuhri_stack_edu_python |
function _update_resource self context transaction
begin
set nwassn_id = call _get_resource_identifer
set values = call _get_resource_values changes_only=true
set nwassn = call network_assoc_update context nwassn_id values transaction
call _hydrate_all_resource_attributes nwassn
end function | def _update_resource(self, context, transaction):
nwassn_id = self._get_resource_identifer()
values = self._get_resource_values(changes_only=True)
nwassn = db_api.network_assoc_update(context, nwassn_id, values,
transaction)
self._hydrate_all_... | Python | nomic_cornstack_python_v1 |
function get_magic_triangle n
begin
set magic_triangle = list list 1 list 1 1
for r in range 2 n
begin
set current_row = list
for c in range length magic_triangle at - 1 - 1
begin
append current_row magic_triangle at - 1 at c + magic_triangle at - 1 at c + 1
end
insert current_row 0 1
append current_row 1
append magic... | def get_magic_triangle(n):
magic_triangle = [[1], [1, 1]]
for r in range(2, n):
current_row = []
for c in range(len(magic_triangle[-1]) - 1):
current_row.append(magic_triangle[-1][c] + magic_triangle[-1][c + 1])
current_row.insert(0, 1)
current_row.append(1)
m... | Python | zaydzuhri_stack_edu_python |
function status self
begin
return get pulumi self string status
end function | def status(self) -> Optional[str]:
return pulumi.get(self, "status") | Python | nomic_cornstack_python_v1 |
comment 605. Can Place Flowers edge detection
comment three adjancent 0 can place 1 flower
function canPlaceFlowers2 flowerbed n
begin
set s = length flowerbed
set bed = list 0 + flowerbed + list 0
for i in range 1 s + 1
begin
if bed at i == bed at i - 1 == bed at i + 1 == 0
begin
set bed at i = 1
set n = n - 1
end
if ... | # 605. Can Place Flowers edge detection
# three adjancent 0 can place 1 flower
def canPlaceFlowers2(flowerbed, n):
s = len(flowerbed)
bed = [0] + flowerbed + [0]
for i in range(1, s+1):
if bed[i] == bed[i-1] == bed[i+1] == 0:
bed[i] = 1
n -= 1
... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
import random
import math
import numpy as np
import pdb
set EMBED_UNITS = 128
class Embed extends object
begin
function __init__ self trainable=true
begin
string Args: trainable: The embed layers are made ... | import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
import random
import math
import numpy as np
import pdb
EMBED_UNITS = 128
class Embed(object):
def __init__(self, trainable=True):
"""
Args: trainable: The embed lay... | Python | zaydzuhri_stack_edu_python |
function test_blnet_turn self
begin
set blnet = call BLNET ADDRESS password=PASSWORD timeout=10 use_ta=false web_port=port
call turn_on 10
assert equal call get_node string A string 2
call turn_on 9
assert equal call get_node string 9 string 2
call turn_auto 8
assert equal call get_node string 8 string 3
call turn_off ... | def test_blnet_turn(self):
blnet = BLNET(
ADDRESS,
password=PASSWORD,
timeout=10,
use_ta=False,
web_port=self.port)
blnet.turn_on(10)
self.assertEqual(self.server.get_node('A'), '2')
blnet.turn_on(9)
self.assertEqual(sel... | 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.