code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function lbs self
begin
set lbs_iter = call list_all
comment iterates all paged items into a single list, filtering on current lb names
set lb_list = list comprehension b for b in lbs_iter if name in _lb_names
return lb_list
end function | def lbs(self):
lbs_iter = self.conn.network.application_gateways.list_all()
# iterates all paged items into a single list, filtering on current lb names
lb_list = [b for b in lbs_iter if b.name in self._lb_names]
return lb_list | Python | nomic_cornstack_python_v1 |
import json , poker_hand_evaluator , random_hand_generator
if __name__ == string __main__
begin
with open string card_template.json string r+ as hands
begin
set template = load json hands
set new_hands = call generate_random_hand template
end
set game = call Game new_hands
call print_information
end | import json, poker_hand_evaluator, random_hand_generator
if __name__ == '__main__':
with open('card_template.json', 'r+') as hands:
template = json.load(hands)
new_hands = random_hand_generator.generate_random_hand(template)
game = poker_hand_evaluator.Game(new_hands)
game.print_information... | Python | zaydzuhri_stack_edu_python |
string 匹配APP回溯数据操作指南 V0.1 * APP相关变量可以按月回溯。回溯匹配逻辑为按照贷款申请时间点回溯匹配历史APP标签数据库,选择申请时间点所在月份前最新一次的指标标签,时间分区字段为ds。
string 3.1 匹配手机维度APP相关变量
comment test为测试数据pyspark dataframe,mobile字段为测试数据的主键手机号,date为申请日期字段,默认取前六位代表年月(Type:String; Eg: '201706')以匹配app变量的时间分区ds(Type:String)
set fp_df = drop call sql string SELECT * FROM (SELECT *... | '''
匹配APP回溯数据操作指南 V0.1
* APP相关变量可以按月回溯。回溯匹配逻辑为按照贷款申请时间点回溯匹配历史APP标签数据库,选择申请时间点所在月份前最新一次的指标标签,时间分区字段为ds。
'''
'''3.1 匹配手机维度APP相关变量'''
# test为测试数据pyspark dataframe,mobile字段为测试数据的主键手机号,date为申请日期字段,默认取前六位代表年月(Type:String; Eg: '201706')以匹配app变量的时间分区ds(Type:String)
fp_df = spark.sql(''' SELECT *
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import socket
import os
set HOST = string
set PORT = 8080
comment test = 'index.html'
comment Function that dirwalks recursively and sends content based on if file was found not
function walkSend fileToBeServed
begin
set found = false
change directory string /var/www/html
for tuple root dirs ... | #!/usr/bin/python3
import socket
import os
HOST = ''
PORT = 8080
#test = 'index.html'
#Function that dirwalks recursively and sends content based on if file was found not
def walkSend(fileToBeServed):
found = False
os.chdir("/var/www/html")
for root, dirs, files in os.walk(".", topdown = False):
... | Python | zaydzuhri_stack_edu_python |
function parse_mapping self map_path source=none dotfiles=none
begin
string Do a simple parse of the dotfile mapping, using semicolons to separate source file name from the target file paths.
set include_re = string ^\s*#include\s+(".+"|'.+')
set include_re = compile include_re I
set mapping_re = string ^("[^"]+"|\'[^\... | def parse_mapping(self, map_path, source=None, dotfiles=None):
"""Do a simple parse of the dotfile mapping, using semicolons to
separate source file name from the target file paths."""
include_re = r"""^\s*#include\s+(".+"|'.+')"""
include_re = re.compile(include_re, re.I)
mappin... | Python | jtatman_500k |
comment Licensed to Elasticsearch B.V. under one or more contributor
comment license agreements. See the NOTICE file distributed with
comment this work for additional information regarding copyright
comment ownership. Elasticsearch B.V. licenses this file to you under
comment the Apache License, Version 2.0 (the "Licen... | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... | Python | jtatman_500k |
function override_description self description
begin
return call MatcherWrapper self description=description
end function | def override_description(self, description: str) -> Matcher:
return MatcherWrapper(self, description=description) | Python | nomic_cornstack_python_v1 |
for i in range integer n / 2
begin
set num = max num cattle at i + cattle at - 1 - i
end
print num | for i in range(int(n / 2)):
num = max(num, cattle[i] + cattle[-1 - i])
print(num)
| Python | zaydzuhri_stack_edu_python |
comment Imports
import pandas as pd
import numpy as np
import json
import os
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import string
import glob
from sklearn.model_selection import learning_curve
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import ... | # Imports
import pandas as pd
import numpy as np
import json
import os
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import string
import glob
from sklearn.model_selection import learning_curve
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import Trunc... | Python | zaydzuhri_stack_edu_python |
function time_stats df
begin
print string 1. Calculating The Most Frequent Times of Travel...
set start_time = time
comment TO DO: display the most common month
set most_common_month = mode
print format string The most common month for traveling is: {} title most_common_month at 0
comment TO DO: display the most common... | def time_stats(df):
print('\n1. Calculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
most_common_month = df['month'].mode()
print('The most common month for traveling is: {}\n'.format(most_common_month[0].title()))
# TO DO: displ... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
from selenium import webdriver
import time
comment chromedriver安装&配置添加说明:
comment 1-本机配置环境变量PATH之后仍无法打开chrome/ 则指定chromedriver所在路径做启动
set PATH = string C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe
comment 2-直接将chromedriver.exe添加至Python\Python36\Scripts(python安装目录下)即可
function m... | # coding=utf-8
from selenium import webdriver
import time
# chromedriver安装&配置添加说明:
# 1-本机配置环境变量PATH之后仍无法打开chrome/ 则指定chromedriver所在路径做启动
PATH = r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'
# 2-直接将chromedriver.exe添加至Python\Python36\Scripts(python安装目录下)即可
def main():
# b = webdriver.Chrom... | Python | zaydzuhri_stack_edu_python |
function createState self x y
begin
set tdb = x + 273.15
set punto = call PsyCoolprop P=P tdb=tdb w=y
return punto
end function | def createState(self, x, y):
tdb = x + 273.15
punto = PsyCoolprop(P=P, tdb=tdb, w=y)
return punto | Python | nomic_cornstack_python_v1 |
function main2
begin
comment coding=utf-8
string 所有接口最后只有这个一个main 函数
import time
set start = time
string 输入参数介绍: shuru_database.txt 是输入的数据库,也就是被查询的库 shuru_query.txt 是输入的查询,也就是要被插入数据库的新数据 yuzhi 输入的阈值0到1之间.如果大于这个阈值就表示2个文本相似. 直白的说,yuzhi越大那么去重越弱,填入数据库的新数据越多!
set yuzhi = 0.1
set pathb = string shuru_database.txt
set pathq =... | def main2():
##
# coding=utf-8
'''
所有接口最后只有这个一个main
函数
'''
import time
start=time.time()
'''
输入参数介绍:
shuru_database.txt 是输入的数据库,也就是被查询的库
shuru_query.txt 是输入的查询,也就是要被插入数据库的新数据
yuzhi 输入的阈值0到1之间.如果大于这个阈值就表示2个文本相似.
直白的说,yuzhi越大那么去重越弱,填入数据库的新数据越多!
'''... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Mar 21 08:21:00 2023 @author: chenxy 2469. 温度转换 给你一个四舍五入到两位小数的非负浮点数 celsius 来表示温度,以 摄氏度(Celsius)为单位。 你需要将摄氏度转换为 开氏度(Kelvin)和 华氏度(Fahrenheit),并以数组 ans = [kelvin, fahrenheit] 的形式返回结果。 返回数组 ans 。与实际答案误差不超过 10-5 的会视为正确答案。 注意: 开氏度 = 摄氏度 + 273.15 华氏度 = 摄氏度 * 1.80 + 32.00 示例... | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 21 08:21:00 2023
@author: chenxy
2469. 温度转换
给你一个四舍五入到两位小数的非负浮点数 celsius 来表示温度,以 摄氏度(Celsius)为单位。
你需要将摄氏度转换为 开氏度(Kelvin)和 华氏度(Fahrenheit),并以数组 ans = [kelvin, fahrenheit] 的形式返回结果。
返回数组 ans 。与实际答案误差不超过 10-5 的会视为正确答案。
注意:
开氏度 = 摄氏度 + 273.15
华氏度 = 摄氏度 * 1.80 + 32.00
示例 ... | Python | zaydzuhri_stack_edu_python |
function pyScorePath mol path size atomCodes=none
begin
set codes = list none * size
for i in range size
begin
if i == 0 or i == size - 1
begin
set sub = 1
end
else
begin
set sub = 2
end
if not atomCodes
begin
set codes at i = call GetAtomCode call GetAtomWithIdx path at i sub
end
else
begin
set base = atomCodes at pat... | def pyScorePath(mol, path, size, atomCodes=None):
codes = [None] * size
for i in range(size):
if i == 0 or i == (size - 1):
sub = 1
else:
sub = 2
if not atomCodes:
codes[i] = Utils.GetAtomCode(mol.GetAtomWithIdx(path[i]), sub)
else:
base = atomCodes[path[i]]
codes[i] = ... | Python | nomic_cornstack_python_v1 |
function bend lsb msb channel=string 0
begin
return string E%c %2x %2x % tuple channel lsb msb
end function | def bend(lsb, msb, channel='0'):
return "E%c %2x %2x" % (channel, lsb, msb) | Python | nomic_cornstack_python_v1 |
function display_for_user cls user
begin
set notifications = dict string like dict string count 0 ; string items dict ; string save dict string count 0 ; string items dict ; string follow list ; string comment list ; string mention list ; string invitation list ; string invitations list ; string invitation_reque... | def display_for_user(cls, user):
notifications = { 'like' : {'count' : 0, 'items' : {}},
'save' : {'count' : 0, 'items' : {}},
'follow' : [] ,
'comment' : [],
'mention': [],
'in... | Python | nomic_cornstack_python_v1 |
function countsetbits A
begin
set count = 0
while A != 0
begin
set A = A ? A - 1
set count = count + 1
end
return count
end function
function solution X Y
begin
set fibs = set literal 1 2 3 5 8 13 21 34
set ans = 0
for i in range X + 1 Y + 1
begin
comment print(i)
set setBits = call countsetbits i
print string setBits ... | def countsetbits(A):
count = 0
while (A != 0):
A = A & (A - 1)
count = count + 1
return (count)
def solution(X, Y):
fibs = {1, 2, 3, 5, 8, 13, 21, 34}
ans = 0
for i in range(X+1, Y+1):
# print(i)
setBits = countsetbits(i)
print("setBits in ", i)
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
set data = zeros tuple 1001 3
set data = call DataFrame data
set iloc at tuple slice : : 0 = index / 10
comment sim to PDB
call DelObj string All
set ana_name = string BBR20-Sodium stearate
call LoadSce ana_name + string _water.sce
for i in range... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data=np.zeros((1001,3))
data=pd.DataFrame(data)
data.iloc[:,0]=data.index/10
#sim to PDB
DelObj('All')
ana_name='BBR20-Sodium stearate'
LoadSce(ana_name+'_water.sce')
for i in range (1000):
if i<10:
name=ana_name+'0000'+s... | Python | zaydzuhri_stack_edu_python |
function retrieval_collate data
begin
comment separate source and target sequences
set tuple t2i_batch i2t_batch = list zip *data
comment t2i
function generate_inputs _batch
begin
set tuple sent att_feats img_masks box_feats obj_labels pos_labels img_ids langs = zip *_batch
comment sent = np.array(sent)
set _sent = lis... | def retrieval_collate(data):
# separate source and target sequences
t2i_batch, i2t_batch = list(zip(*data))
# t2i
def generate_inputs(_batch):
sent, att_feats, img_masks, box_feats, obj_labels, pos_labels, img_ids, langs = zip(
*_batch)
# sent = np.array(sent)
_sent ... | Python | nomic_cornstack_python_v1 |
comment Definition for singly-linked list.
import pdb
class ListNode extends object
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
class Solution extends object
begin
function detectCycle self head
begin
string :type head: ListNode :rtype: ListNode
set fast = head
set slow = hea... | # Definition for singly-linked list.
import pdb
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast = head
slow = h... | Python | zaydzuhri_stack_edu_python |
for x in list
begin
if maxnumber < x
begin
set maxnumber = x
end
end
print string maxnumber number in array is maxnumber | for x in list:
if maxnumber < x:
maxnumber = x
print("maxnumber number in array is ",maxnumber)
| Python | zaydzuhri_stack_edu_python |
import lib601.dist as dist
from lib601.markov import HMM , StateEstimator
from simulator import Simulator
comment ideal = [1,8,8,1,1,8,1,8,8]
set ideal = list 1 8 8 1 1
set numStates = length ideal
comment OBSERVATION MODELS
function perfectObsModel state
begin
return call deltaDist ideal at state
end function
function... | import lib601.dist as dist
from lib601.markov import HMM, StateEstimator
from simulator import Simulator
#ideal = [1,8,8,1,1,8,1,8,8]
ideal = [1,8,8,1,1]
numStates = len(ideal)
## OBSERVATION MODELS
def perfectObsModel(state):
return dist.deltaDist(ideal[state])
def obsModelA(state):
zero_dist = dist.unifor... | Python | zaydzuhri_stack_edu_python |
string 3D plots with matplotlib. credits: @clcoding
import numpy as np
import matplotlib.pyplot as plt
function f x y
begin
return sin square root x ^ 2 + y ^ 2
end function
set x = linear space - 6 6 30
set y = linear space - 6 6 30
set tuple x y = call meshgrid x y
set z = f dist x y
comment fig = plt.figure()
set ax... | """
3D plots with matplotlib.
credits: @clcoding
"""
import numpy as np
import matplotlib.pyplot as plt
def f(x,y):
return np.sin(np.sqrt(x**2 + y **2))
x = np.linspace(-6,6,30)
y = np.linspace(-6,6,30)
x,y = np.meshgrid(x,y)
z = f(x,y)
# fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(x,y,z,50, ... | Python | zaydzuhri_stack_edu_python |
function getContour xpts ypts zpts levels
begin
set fig = figure
set x = deep copy xpts
set y = deep copy ypts
set z = deep copy zpts
set hasLevels = false
for l in levels
begin
if max z - l * min z - l < 0
begin
set hasLevels = true
end
end
if not hasLevels
begin
return dict
end
set CS = call tricontour x y z levels=... | def getContour(xpts,ypts,zpts,levels):
fig = plt.figure()
x = copy.deepcopy(xpts)
y = copy.deepcopy(ypts)
z = copy.deepcopy(zpts)
hasLevels = False
for l in levels:
if (max(z)-l)*(min(z)-l) < 0:
hasLevels = True
if not hasLevels:
return {}
CS = plt.tricontou... | Python | nomic_cornstack_python_v1 |
function plot_mensuration map
begin
set fluxtower = tuple 51.153533 - 0.8583
set tuple flux_x flux_y = map fluxtower at 1 fluxtower at 0
plot flux_x flux_y marker=string D color=string k
for x in call xrange length mensuration_plot_dict
begin
set tuple lon lat = call bng2latlon values mensuration_plot_dict at x at 0 va... | def plot_mensuration(map):
fluxtower = (51.153533, -0.8583)
flux_x, flux_y = map(fluxtower[1], fluxtower[0])
map.plot(flux_x, flux_y, marker='D', color='k')
for x in xrange(len(mensuration_plot_dict)):
lon, lat = bng2latlon(mensuration_plot_dict.values()[x][0], mensuration_plot_dict.values()[x][... | Python | nomic_cornstack_python_v1 |
set car1Price = decimal input string Car 1 Price:
set car1milesPerGallon = decimal input string Car 1 miles per Gallon:
set car2Price = decimal input string Car 2 Price
set car2milesPerGallon = decimal input string Car 2 miles per gallon:
set gallonPrice = decimal input string Price of a gallon of fuel:
set milesPerYea... | car1Price = float(input('Car 1 Price:\n'))
car1milesPerGallon = float (input('Car 1 miles per Gallon:\n'))
car2Price = float(input('Car 2 Price\n'))
car2milesPerGallon = float(input('Car 2 miles per gallon:\n'))
gallonPrice = float(input('Price of a gallon of fuel:\n'))
milesPerYear = float(input('how many miles do y... | Python | zaydzuhri_stack_edu_python |
function delete_post self blogname id
begin
string Deletes a post with the given id :param blogname: a string, the url of the blog you want to delete from :param id: an int, the post id that you want to delete :returns: a dict created from the JSON response
set url = format string /v2/blog/{}/post/delete blogname
retur... | def delete_post(self, blogname, id):
"""
Deletes a post with the given id
:param blogname: a string, the url of the blog you want to delete from
:param id: an int, the post id that you want to delete
:returns: a dict created from the JSON response
"""
url = "/v2... | Python | jtatman_500k |
function parseOutputString self output debug=false
begin
if ignore_parsing
begin
return
end
append path call getSetting string Sqlmap path
try
begin
from lib.core.settings import HASHDB_MILESTONE_VALUE
from lib.core.enums import HASHDB_KEYS
from lib.core.settings import UNICODE_ENCODING
end
except any
begin
log string ... | def parseOutputString(self, output, debug=False):
if self.ignore_parsing:
return
sys.path.append(self.getSetting("Sqlmap path"))
try:
from lib.core.settings import HASHDB_MILESTONE_VALUE
from lib.core.enums import HASHDB_KEYS
from lib.core.settin... | Python | nomic_cornstack_python_v1 |
function main_compute_shap_df X_train_df_list model_list speed_up=true
begin
comment Getting dataframes for multiple models
set store_dfs = call interpret_multiple_models model_list=model_list X_train_df_list=X_train_df_list speed_up=speed_up
comment Getting combined dataframes
set combined_df_dict = call combine_shap_... | def main_compute_shap_df(X_train_df_list,
model_list,
speed_up = True,
):
# Getting dataframes for multiple models
store_dfs = interpret_multiple_models(model_list = model_list,
X_train_df_l... | Python | nomic_cornstack_python_v1 |
from discord.ext import commands
import aiohttp
import discord
from io import BytesIO
from PIL import Image
class Images extends Cog
begin
function __init__ self bot
begin
set bot = bot
end function
decorator call command brief=string This person does not exist.
async function thispersondoesnotexist self ctx
begin
asyn... | from discord.ext import commands
import aiohttp
import discord
from io import BytesIO
from PIL import Image
class Images(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(
brief='This person does not exist.'
)
async def thispersondoesnotexist(self, ctx):
... | Python | zaydzuhri_stack_edu_python |
function municipality self municipality
begin
if municipality is none
begin
comment noqa: E501
raise call ValueError string Invalid value for `municipality`, must not be `None`
end
set _municipality = municipality
end function | def municipality(self, municipality):
if municipality is None:
raise ValueError("Invalid value for `municipality`, must not be `None`") # noqa: E501
self._municipality = municipality | Python | nomic_cornstack_python_v1 |
comment 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。
comment 要求不能创建任何新的节点,只能调整树中节点指针的指向。
comment 为了让您更好地理解问题,以下面的二叉搜索树为例:
comment 我们希望将这个二叉搜索树转化为双向循环链表。
comment 链表中的每个节点都有一个前驱和后继指针。
comment 对于双向循环链表,第一个节点的前驱是最后一个节点,最后一个节点的后继是第一个节点。
comment 下图展示了上面的二叉搜索树转化成的链表。
comment “head” 表示指向链表中有最小元素的节点。
comment 特别地,我们希望可以就地完成转换操作。
comment 当转化... | # 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。
# 要求不能创建任何新的节点,只能调整树中节点指针的指向。
#
# 为了让您更好地理解问题,以下面的二叉搜索树为例:
#
#
# 我们希望将这个二叉搜索树转化为双向循环链表。
# 链表中的每个节点都有一个前驱和后继指针。
# 对于双向循环链表,第一个节点的前驱是最后一个节点,最后一个节点的后继是第一个节点。
# 下图展示了上面的二叉搜索树转化成的链表。
# “head” 表示指向链表中有最小元素的节点。
#
# 特别地,我们希望可以就地完成转换操作。
# 当转化完成以后,树中节点的左指针需要指向前驱,树中节点的右指针需要指向后继。
# 还需要返回链表... | Python | zaydzuhri_stack_edu_python |
function _two_col_align_split_col_fp16_new dst data
begin
set tvm_ib = call create
set tuple n_i col_len row_len = shape
set float_size = call get_bit_len dtype // 8
set cp_align_len = BLOCK_REDUCE_INT8 // float_size
set device_core_num = AICORE_NUM
set ub_bytes = UB_SIZE_B - 64
set ub_ele = ub_bytes // 2 // float_size... | def _two_col_align_split_col_fp16_new(dst, data):
tvm_ib = tvm.ir_builder.create()
n_i, col_len, row_len = data.shape
float_size = cce.cce_intrin.get_bit_len(data.dtype) // 8
cp_align_len = cce_params.BLOCK_REDUCE_INT8 // float_size
device_core_num = AICORE_NUM
ub_bytes = UB_SIZE_B - 64
ub... | Python | nomic_cornstack_python_v1 |
comment 如果c是C的实例化,c.x 将触发getSize,c.x = value将触发setSize,size将赋值为1,即c.size=1,del c.x 触发 delSize,使size的值删除
comment 通过使用property使x与size相连
class C
begin
function __init__ self size=10
begin
set size = size
end function
function getSize self
begin
return size
end function
function setSize self value
begin
set size = value
en... | #如果c是C的实例化,c.x 将触发getSize,c.x = value将触发setSize,size将赋值为1,即c.size=1,del c.x 触发 delSize,使size的值删除
#通过使用property使x与size相连
class C:
def __init__(self, size = 10):
self.size = size
def getSize(self):
return self.size
def setSize(self, value):
self.size = value
def delSize(se... | Python | zaydzuhri_stack_edu_python |
comment https://leetcode.com/problems/symmetric-tree/
comment 递归实现,是否左边和右边一样即可
comment Definition for a binary tree node.
class TreeNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end function
end class
class Solution
begin
function isSymmetric self root
begin
if root is none
begi... | # https://leetcode.com/problems/symmetric-tree/
# 递归实现,是否左边和右边一样即可
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
... | Python | zaydzuhri_stack_edu_python |
import argparse
import os
import sys
import pandas as pd
from slacker import Slacker
from slacknalysis.analysis.messages import write_message_analysis
from slacknalysis.analysis.reactions import write_reaction_analysis
from slacknalysis.config import channels , slack_oath
from slacknalysis.data.clean_data import write_... | import argparse
import os
import sys
import pandas as pd
from slacker import Slacker
from slacknalysis.analysis.messages import write_message_analysis
from slacknalysis.analysis.reactions import write_reaction_analysis
from slacknalysis.config import channels, slack_oath
from slacknalysis.data.clean_data import write... | Python | zaydzuhri_stack_edu_python |
function json_options self
begin
return get pulumi self string json_options
end function | def json_options(self) -> Optional['outputs.TableExternalDataConfigurationJsonOptions']:
return pulumi.get(self, "json_options") | Python | nomic_cornstack_python_v1 |
class ZigzagIterator extends object
begin
function __init__ self lists
begin
string Initialize your data structure here. :type lists: List[List[int]]
set i = 0
set k = length lists
set lists = lists
set lens = map len lists
set minlen = min lens
set n = sum lens
set row = 0
set col = minlen
end function
function next s... | class ZigzagIterator(object):
def __init__(self, lists):
"""
Initialize your data structure here.
:type lists: List[List[int]]
"""
self.i = 0
self.k = len(lists)
self.lists = lists
self.lens = map(len, self.lists)
self.minlen = min(self.lens)
... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set svclassifier = support vector classifier kernel=string linear
end function | def __init__(self):
self.svclassifier = SVC(kernel='linear') | Python | nomic_cornstack_python_v1 |
comment 判断回文
function check s
begin
if s == s at slice : : - 1
begin
return true
end
else
begin
return false
end
end function
function solve
begin
set tuple n k = map int split input
set cnt = 0
for i in range k
begin
if call check string n
begin
break
end
set n = n + integer string n at slice : : - 1
set cnt = cnt... | def check(s): #判断回文
if s == s[::-1]:
return True
else:
return False
def solve():
n, k = map(int, input().split())
cnt = 0
for i in range(k):
if check(str(n)):
break
n = n + int(str(n)[::-1])
cnt += 1
print(n)
print(cnt)
if __name__ ==... | Python | zaydzuhri_stack_edu_python |
from level_selection_view import LevelSelectionView
from LevelSelection.level_selection import LevelSelection
from View.Qt.Level.level_controller import LevelController
from nytram.core.game_engine import TheGameEngine
from PySide.QtCore import QCoreApplication , Qt
class LevelSelectionController
begin
string Controlle... | from level_selection_view import LevelSelectionView
from LevelSelection.level_selection import LevelSelection
from View.Qt.Level.level_controller import LevelController
from nytram.core.game_engine import TheGameEngine
from PySide.QtCore import QCoreApplication, Qt
class LevelSelectionController:
""" Controller ... | Python | zaydzuhri_stack_edu_python |
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import matplotlib
call use string TkAgg
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator , FormatStrFormatter
class NetModel
begin
decorator staticmethod
function activation s
begin
return call div... | from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
class NetModel:
@staticmethod
def activation(s: np.matrix):
return ... | Python | zaydzuhri_stack_edu_python |
from typing import Callable
from nmap.nmap import PortScanner
from datetime import datetime
from Repository.NetworkMapperRepository import NetworkMapperRepository
from Application.NMapObj import NMapObj
from Application.Validation.InputValidation import InputValidation
import time
class NetworkMapperApp
begin
function ... | from typing import Callable
from nmap.nmap import PortScanner
from datetime import datetime
from Repository.NetworkMapperRepository import NetworkMapperRepository
from Application.NMapObj import NMapObj
from Application.Validation.InputValidation import InputValidation
import time
class NetworkMapperApp():
def __... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python
string Routine to XXX
import csv
from db_tools import csv_to_sql
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from operator import itemgetter
import os
import sqlite3
function interactive_soils soil_atts_fpath
begin
string
function triangle sand clay
begin
comment see 'AFRI... | #!/bin/python
"""Routine to XXX
"""
import csv
from db_tools import csv_to_sql
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from operator import itemgetter
import os
import sqlite3
def interactive_soils(soil_atts_fpath):
"""
"""
def triangle(sand, clay):
x = (-clay/2.0)... | Python | zaydzuhri_stack_edu_python |
function dtob num
begin
return decode codecs string %08x % num ? 4294967295 string hex
end function | def dtob(num):
return codecs.decode("%08x" % (num & 0xFFFFFFFF), "hex") | Python | nomic_cornstack_python_v1 |
from point import Point
set tuple x1 y1 = split input string ,
set tuple x2 y2 = split input string ,
set x1 = integer x1
set y1 = integer y1
set x2 = integer x2
set y2 = integer y2
set tuple dx dy = split input string ,
set dx = integer dx
set dy = integer dy
set p1 = call Point x1 y1
set p2 = call Point x2 y2
print s... | from point import Point
x1,y1 = input().split(',')
x2,y2 = input().split(',')
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
dx,dy = input().split(',')
dx = int(dx)
dy = int(dy)
p1 = Point(x1, y1)
p2 = Point(x2,y2)
print('p1点的坐标为:',p1)
print('p2点的坐标为:',p2)
p2.move_by(dx, dy)
print('移动后的坐标为:',p2)
print('p1与p2点的... | Python | zaydzuhri_stack_edu_python |
function send self s
begin
delaybeforesend
if logfile is not none
begin
write logfile s
flush logfile
end
if logfile_send is not none
begin
write logfile_send s
flush logfile_send
end
set c = write wtty s
return c
end function | def send(self, s):
(self.delaybeforesend)
if self.logfile is not None:
self.logfile.write (s)
self.logfile.flush()
if self.logfile_send is not None:
self.logfile_send.write (s)
self.logfile_send.flush()
c = self.wtty.write(s)
... | Python | nomic_cornstack_python_v1 |
comment 5.10
function time self cine start count=1
begin
set ans = call self string time {cine:%d, start:%d, cnt:%d} % tuple cine start count
return call get_unit
end function | def time(self, cine, start, count=1): # 5.10
ans = self('time {cine:%d, start:%d, cnt:%d}'
% (cine, start, count))
return self.Parser(ans[5:]).get_unit() | Python | nomic_cornstack_python_v1 |
comment %% codeblock
comment Q1 matplotlib
import matplotlib.pyplot as plt
from matplotlib import ticker
function prettify_graph graph
begin
call set_title string Results of 500 slot machine pulls
comment Make the y-axis begin at 0
call set_ylim bottom=0
comment Label the y-axis
call set_ylabel string Balance
end funct... | # %% codeblock
##Q1 matplotlib
import matplotlib.pyplot as plt
from matplotlib import ticker
def prettify_graph(graph):
plt.set_title("Results of 500 slot machine pulls")
# Make the y-axis begin at 0
plt.set_ylim(bottom=0)
# Label the y-axis
plt.set_ylabel("Balance")
graph = jimmy_slots.get_graph()... | Python | zaydzuhri_stack_edu_python |
function add_two_lists list1 list2
begin
return list map lambda m -> m at 0 + m at 1 list zip list1 list2
end function | def add_two_lists(list1, list2):
return list(map(lambda m: m[0] + m[1], list(zip(list1, list2)))) | Python | nomic_cornstack_python_v1 |
import pygame
from pygame.sprite import Sprite
from enum import Enum
import os
import time
class CharacterStates extends Enum
begin
set IDLE = 0
set MOVE = 1
set ATTACK = 2
set DEAD = 3
set DEFENCE = 4
set JUMP = 5
end class
class GameObjectTypes extends Enum
begin
set STATIC_OBJECT = 0
set MOVING_OBJECT = 1
set ENEMY ... | import pygame
from pygame.sprite import Sprite
from enum import Enum
import os
import time
class CharacterStates(Enum):
IDLE = 0
MOVE = 1
ATTACK = 2
DEAD = 3
DEFENCE = 4
JUMP = 5
class GameObjectTypes(Enum):
STATIC_OBJECT = 0
MOVING_OBJECT = 1
ENEMY = 2
DARK_ANGEL = 3
OTHER... | Python | zaydzuhri_stack_edu_python |
import argparse
import csv
set parser = call ArgumentParser
call add_argument string -b string --busy help=string Only look at busiest hour of each trace action=string store_true
set args = call parse_args
if busy
begin
set result_file = string dsph-busy.dat
with open string busy_hours.dat string r as busy_file
begin
s... | import argparse
import csv
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--busy", help="Only look at busiest hour of each trace", action='store_true')
args = parser.parse_args()
if args.busy:
result_file = "dsph-busy.dat"
with open("busy_hours.dat", "r") as busy_file:
busy_timestamps =... | Python | zaydzuhri_stack_edu_python |
comment noqa
function build_last_image modeladmin request queryset
begin
for app in queryset
begin
set image = call get_or_create_last_image
call delay id get git string name
end
end function | def build_last_image(modeladmin, request, queryset): # noqa
for app in queryset:
image = app.get_or_create_last_image()
app_build_last_image.delay(image.id, app.git.get("name")) | Python | nomic_cornstack_python_v1 |
function ask_user
begin
while true
begin
set user_quest = input string Ваш вопрос:
if user_quest in our_dict
begin
print our_dict at user_quest
end
else
begin
print string Нужен другой вопрос :)
end
end
end function
call ask_user | def ask_user():
while True:
user_quest = input('Ваш вопрос: ')
if user_quest in our_dict:
print(our_dict[user_quest])
else:
print("Нужен другой вопрос :)")
ask_user()
| Python | zaydzuhri_stack_edu_python |
function format_numbers numbers
begin
set formatted_list = list
for num in numbers
begin
if num % 5 == 0
begin
continue
end
set formatted_num = format string {:,.2f} round num 2
append formatted_list formatted_num
end
return formatted_list
end function
set numbers = list 1000 12345.6789 500 9876.54321 250 0 25.6789 77... | def format_numbers(numbers):
formatted_list = []
for num in numbers:
if num % 5 == 0:
continue
formatted_num = "{:,.2f}".format(round(num, 2))
formatted_list.append(formatted_num)
return formatted_list
numbers = [1000, 12345.6789, 500, 9876.54321, 250, 0, 25.6789, 777.7... | Python | greatdarklord_python_dataset |
async function test_switch_change_light_state hass utcnow
begin
set helper = await call setup_test_component hass create_lightbulb_service_with_hs
await call async_call string light string turn_on dict string entity_id string light.testdevice ; string brightness 255 ; string hs_color list 4 5 blocking=true
call async_a... | async def test_switch_change_light_state(hass: HomeAssistant, utcnow) -> None:
helper = await setup_test_component(hass, create_lightbulb_service_with_hs)
await hass.services.async_call(
"light",
"turn_on",
{"entity_id": "light.testdevice", "brightness": 255, "hs_color": [4, 5]},
... | Python | nomic_cornstack_python_v1 |
function forward self emb_indices
begin
set input_shape = shape
set emb_indices = view emb_indices - 1
set max_emd_indices = call full_like emb_indices num_embeddings - 1
set emb_indices = call minimum emb_indices max_emd_indices
comment (*, D)
set embeddings = call embeddings emb_indices
set embeddings = norm embeddin... | def forward(self, emb_indices: Tensor) -> Tensor:
input_shape = emb_indices.shape
emb_indices = emb_indices.view(-1)
max_emd_indices = torch.full_like(emb_indices, self.num_embeddings - 1)
emb_indices = torch.minimum(emb_indices, max_emd_indices)
embeddings = self.embeddings(emb_... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import imutils
comment read image and take first channel only
set bottle_3_channel = call imread string Photo/bottle5.jpg
set bottle_gray = split cv2 bottle_3_channel at 0
comment cv2.imshow("Bottle Gray", bottle_gray)
comment cv2.waitKey(0)
comment blur ima... | import cv2
import numpy as np
import matplotlib.pyplot as plt
import imutils
# read image and take first channel only
bottle_3_channel = cv2.imread("Photo/bottle5.jpg")
bottle_gray = cv2.split(bottle_3_channel)[0]
# cv2.imshow("Bottle Gray", bottle_gray)
# cv2.waitKey(0)
# blur image
bottle_gray = cv2.Gau... | Python | zaydzuhri_stack_edu_python |
from functools import reduce
function main
begin
set input_list = list list string 34587 string Learning Python, Mark Lutz 4 40.95 list string 98762 string Programming Python, Mark Lutz 5 56.8 list string 77226 string Head First Python, Paul Barry 3 32.95 list string 88112 string Einführung in Python3, Bernd Klein 3 24... | from functools import reduce
def main():
input_list= [ ["34587", "Learning Python, Mark Lutz", 4, 40.95],
["98762", "Programming Python, Mark Lutz", 5, 56.80],
["77226", "Head First Python, Paul Barry", 3,32.95],
["88112", "Einführung in Python3, Bernd Klein", 3, 24.99]]
... | Python | zaydzuhri_stack_edu_python |
function pad_lines self lines idx=none c=none default=string
begin
for i in range length lines
begin
set lines at i = lines at i + if expression idx is not none and i == idx then c else default
end
end function | def pad_lines(self, lines, idx=None, c=None, default=" "):
for i in range(len(lines)):
lines[i] += c if idx is not None and i == idx else default | Python | nomic_cornstack_python_v1 |
from flask import Flask , request , render_template
import requests
set app = call Flask __name__
decorator call route string /
function home
begin
return call render_template string home.html
end function
decorator call route string /cryptocalc
function cryptocalc
begin
return call render_template string theform.html
... | from flask import Flask, request, render_template
import requests
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/cryptocalc')
def cryptocalc():
return render_template('theform.html')
@app.route('/result', methods=["POST"])
def result():
currency_1 = request... | Python | zaydzuhri_stack_edu_python |
import sys
import math
set a = integer argv at 1
set b = integer argv at 2
set c = integer argv at 3
set delta = b * b - 4 * a * c
set ilosc = 0
if delta == 0
begin
set x1 = - b / 2 * a
print format string 1 {x11} x11=x1
end
else
if delta > 0
begin
set x1 = - b + square root delta / 2 * a
set x2 = - b - square root del... | import sys
import math
a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
delta = (b*b) - 4*a*c
ilosc = 0
if(delta == 0):
x1 = -b/2*a
print("1 \n{x11}".format(x11 = x1))
elif(delta>0):
x1 = (-b + math.sqrt(delta))/2*a
x2 = (-b - math.sqrt(delta))/2*a
print("2 \n{x11} {... | Python | zaydzuhri_stack_edu_python |
from sys import stdin , stdout
function check flag
begin
for i in range length flag
begin
if flag at i == false
begin
return false
end
end
return true
end function
function minLight a n
begin
set A = list
for i in range n
begin
if a at i > - 1
begin
set tuple start end = tuple max 0 i - a at i min n - 1 i + a at i
set... | from sys import stdin, stdout
def check(flag):
for i in range(len(flag)):
if flag[i] == False:
return False
return True
def minLight(a,n):
A = []
for i in range(n):
if a[i]>-1:
start,end = max(0,i-a[i]), min(n-1,i+a[i])
d = end-start+1
A.... | Python | zaydzuhri_stack_edu_python |
with open string ua.txt string r+ as file
begin
for line in file
begin
print string '%s', % strip line string
end
end | with open('ua.txt', 'r+') as file:
for line in file:
print('\'%s\',' % line.strip('\n')) | Python | zaydzuhri_stack_edu_python |
comment Print all the factors of a given number
function main
begin
set num = integer input string Enter the integer value ::
set factors = list
for i in range 1 integer num / 2 + 1
begin
if num % i is 0
begin
append factors i
end
end
append factors num
print string The factors are : factors
end function
call main
str... | #Print all the factors of a given number
def main():
num = int(input('Enter the integer value :: '))
factors = []
for i in range(1,int(num/2)+1):
if num % i is 0:
factors.append(i)
factors.append(num)
print('The factors are :',factors)
main()
'''
OUTPUT
------
Enter the integer value :: 50
The factors are ... | Python | zaydzuhri_stack_edu_python |
function __init__ self length_preserving=false
begin
call __init__
set length_preserving = length_preserving
end function | def __init__(self, length_preserving=False):
super().__init__()
self.length_preserving = length_preserving | Python | nomic_cornstack_python_v1 |
function order_product_pre_save_receiver sender instance *args **kwargs
begin
set qty = quantity
if qty >= 1
begin
set price = price
set subtotal = qty * price
set price = price
set subtotal = subtotal
end
end function | def order_product_pre_save_receiver(sender, instance, *args, **kwargs):
qty = instance.quantity
if qty >= 1:
price = instance.product.price
subtotal = qty * price
instance.price = price
instance.subtotal = subtotal | Python | nomic_cornstack_python_v1 |
function sample_values cls
begin
set telemetry_values = call cls
set report_request_id = string 123
set baseline_power_kw = 37.1
set current_power_kw = 272.3
return telemetry_values
end function | def sample_values(cls):
telemetry_values = cls()
telemetry_values.report_request_id = '123'
telemetry_values.baseline_power_kw = 37.1
telemetry_values.current_power_kw = 272.3
return telemetry_values | Python | nomic_cornstack_python_v1 |
function factors x
begin
set a = list
set n = x
set i = 2
while i * i <= n
begin
while n % i == 0
begin
append a i
set n = n // i
end
set i = i + 1
end
if n > 1 and n != x
begin
append a n
end
return a
end function
print string Enter natural number more than 1 :
comment 600851475143
set n = integer input
if n > 1
begi... | def factors(x):
a = []
n = x
i = 2
while (i * i) <= n:
while (n % i) == 0:
a.append(i)
n //= i
i += 1
if (n > 1) and (n != x):
a.append(n)
return a
print('Enter natural number more than 1 : ')
n = int(input()) # 600851475143
if n > 1:... | Python | zaydzuhri_stack_edu_python |
import cv2
import mediapipe as mp
comment drawing utility
set mp_drawing = drawing_utils
comment Face detection utility
set mp_face_detection = face_detection
comment model for detecting face
set model_detection = call FaceDetection
set cap = call VideoCapture string vidmp4.mp4
while call isOpened
begin
set tuple flag ... | import cv2
import mediapipe as mp
# drawing utility
mp_drawing = mp.solutions.drawing_utils
# Face detection utility
mp_face_detection = mp.solutions.face_detection
# model for detecting face
model_detection = mp_face_detection.FaceDetection()
cap = cv2.VideoCapture('vidmp4.mp4')
while cap.isOpened():
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on 17.02.2021 This script asks the user to enter their name and age, then prints out a message addressed to them that tells them the year that they will turn 100 years old. @author: Barbora Doslikova
import datetime
comment gather user info
set username = input string what i... | # -*- coding: utf-8 -*-
"""
Created on 17.02.2021
This script asks the user to enter their name and age,
then prints out a message addressed to them
that tells them the year that they will turn 100 years old.
@author: Barbora Doslikova
"""
import datetime
# gather user info
username = input('what is your name? ')
us... | Python | zaydzuhri_stack_edu_python |
comment StickEmUp Functions
comment Walt Nixon
comment 20140226
import math
import arcpy
comment Calcuate the area of a polygon
function AreaOfPolygon polygon
begin
comment print("AreaOfPolygon()")
set area = 0.0
set n = length polygon
for i in range n
begin
set j = i + 1 % n
set area = area + polygon at i at 0 * polyg... | ##StickEmUp Functions
##Walt Nixon
##20140226
import math
import arcpy
#Calcuate the area of a polygon
def AreaOfPolygon(polygon):
# print("AreaOfPolygon()")
area = 0.0
n = len(polygon)
for i in range(n):
j = (i+1)%n
area += polygon[i][0]*polygon[j][1] - polygon[j][0]*polygon[i][1]
... | Python | zaydzuhri_stack_edu_python |
comment i=1
comment while(i<=10):
comment print(i)
comment i=i+1 | # i=1
# while(i<=10):
# print(i)
# i=i+1
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Feb 27 21:35:42 2019 @author: Administrator
import numpy as np
from center_method import *
from line_three import *
from distance_method import *
function get_cen_sqrt data
begin
set k = call shape data at 0
set cen = ones tuple k k * inf
for i in range k
begin
for j ... | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 21:35:42 2019
@author: Administrator
"""
import numpy as np
from center_method import *
from line_three import *
from distance_method import *
def get_cen_sqrt(data):
k = np.shape(data)[0]
cen = np.ones((k, k)) * np.inf
for i in range(k):
... | Python | zaydzuhri_stack_edu_python |
function update_23 db filename_persist snapshots_dir snapshots_reference_dir
begin
set text = string test/test_fadeto.py test/test_draw_elbows2.py
set candidates = call scripts_names_from_text text end_mark=string :
set tuple checked_in unknown move_failed = call update_testrun__pass db filename_persist candidates snap... | def update_23(db, filename_persist, snapshots_dir, snapshots_reference_dir):
text = """
test/test_fadeto.py
test/test_draw_elbows2.py
"""
candidates = doers.scripts_names_from_text(text, end_mark=':')
checked_in, unknown, move_failed = hl.update_testrun__pass(db,
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from string import ascii_uppercase as ABC
from layouts import labels , color , ax_id
set data = read csv string data/assembly_var.csv
set change_trait = sort np list set data at string change
set traits = set data at string trait
set tuple fig ax = ... | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from string import ascii_uppercase as ABC
from layouts import labels, color, ax_id
data = pd.read_csv("data/assembly_var.csv")
change_trait = np.sort(list(set(data["change"])))
traits = set(data["trait"])
fig, ax = plt.subplots(2,3, figsize = (13,... | Python | zaydzuhri_stack_edu_python |
function __init__ self textfile_path batch_size seq_length number_of_lines_in_file=none one_hot_size=none random_state=none
begin
set textfile_path = textfile_path
set random_state = random_state
set batch_size = batch_size
set seq_length = seq_length
if random_state is none
begin
raise call ValueError string Must pass... | def __init__(self, textfile_path, batch_size,
seq_length,
number_of_lines_in_file=None,
one_hot_size=None, random_state=None):
self.textfile_path = textfile_path
self.random_state = random_state
self.batch_size = batch_size
self.seq_len... | Python | nomic_cornstack_python_v1 |
comment n-fold cross-validation
import numpy as np
import os
from sklearn.cross_validation import KFold
import cv2
import matplotlib.pylab as plt
comment path to data
set path2set = string ../dcom/TrainingSet/
set path2numpy = path2set + string numpy/
function concatdata indices npflist
begin
for k in indices
begin
set... | # n-fold cross-validation
import numpy as np
import os
from sklearn.cross_validation import KFold
import cv2
import matplotlib.pylab as plt
# path to data
path2set="../dcom/TrainingSet/"
path2numpy = path2set+"numpy/"
def concatdata(indices,npflist):
for k in indices:
path2npfn=path2numpy+npflist[k] | Python | zaydzuhri_stack_edu_python |
function test_simplest
begin
assert true
end function
function is_empty value
begin
try
begin
return length value == 0
end
except TypeError
begin
return false
end
end function
function test_empty_list
begin
assert call is_empty list is true
end function
function test_empty_dict
begin
assert call is_empty dict is true
e... | def test_simplest():
assert True
def is_empty(value):
try:
return len(value) == 0
except TypeError:
return False
def test_empty_list():
assert is_empty([]) is True
def test_empty_dict():
assert is_empty({}) is True
def test_list_is_not_empty():
assert is_empty([1, 2, 3]) ... | Python | zaydzuhri_stack_edu_python |
function StreamMedia self callback=none finish_callback=none additional_headers=none
begin
string Send this resumable upload in a single request. Args: callback: Progress callback function with inputs (http_wrapper.Response, transfer.Upload) finish_callback: Final callback function with inputs (http_wrapper.Response, t... | def StreamMedia(self, callback=None, finish_callback=None,
additional_headers=None):
"""Send this resumable upload in a single request.
Args:
callback: Progress callback function with inputs
(http_wrapper.Response, transfer.Upload)
finish_callback: ... | Python | jtatman_500k |
import os
import re
import sys
append path absolute path path string anki
from anki.storage import Collection
comment The range is taken from here:
comment https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
set CJK_UNIFIED_RE = compile string [\u4e00-\u9FFF]
function load_collection db_dir db_file
beg... | import os
import re
import sys
sys.path.append(os.path.abspath("anki"))
from anki.storage import Collection
# The range is taken from here:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
CJK_UNIFIED_RE = re.compile(r"[\u4e00-\u9FFF]")
def load_collection(db_dir, db_file):
db_dir = os.path... | Python | zaydzuhri_stack_edu_python |
function _list_networks__cidr_range self network libcloud_network
begin
return
end function | def _list_networks__cidr_range(self, network, libcloud_network):
return | Python | nomic_cornstack_python_v1 |
function build_tale_image task tale_id force=false
begin
info string Building image for Tale %s tale_id
call updateProgress message=string Building image total=BUILD_TALE_IMAGE_STEP_TOTAL current=1 forceFlush=true
set tic = time
set tale = get girder_client string /tale/%s % tale_id
while tale at string status != READY... | def build_tale_image(task, tale_id, force=False):
logging.info('Building image for Tale %s', tale_id)
task.job_manager.updateProgress(
message='Building image', total=BUILD_TALE_IMAGE_STEP_TOTAL,
current=1, forceFlush=True)
tic = time.time()
tale = task.girder_client.get('/tale/%s' % t... | Python | nomic_cornstack_python_v1 |
function getCarOrderForPerRoad road_map
begin
set tuple channel roadLen = shape
set orderList = list
for i in range roadLen - 1 - 1 - 1
begin
for j in range channel
begin
set id = string road_map at tuple j i
if road_map at tuple j i != 0
begin
append orderList id
end
end
end
return orderList
end function | def getCarOrderForPerRoad(road_map):
channel, roadLen = road_map.shape
orderList = []
for i in range(roadLen - 1, -1, -1):
for j in range(channel):
id = str(road_map[j, i])
if road_map[j, i] != 0:
orderList.append(id)
return orderList | Python | nomic_cornstack_python_v1 |
function test_starts_control_amp_service self
begin
set options = call ControlOptions
call parseOptions list b'--agent-port' b'tcp:8001' b'--data-path' call mktemp
set reactor = call MemoryCoreReactor
call main reactor options
set server = tcpServers at 1
set port = server at 0
set protocol = call buildProtocol none
as... | def test_starts_control_amp_service(self):
options = ControlOptions()
options.parseOptions(
[b"--agent-port", b"tcp:8001", b"--data-path", self.mktemp()])
reactor = MemoryCoreReactor()
ControlScript().main(reactor, options)
server = reactor.tcpServers[1]
port ... | Python | nomic_cornstack_python_v1 |
from re import compile , findall
from urlparse import urljoin
from scraperwiki import scrape | from re import compile, findall
from urlparse import urljoin
from scraperwiki import scrape
| Python | zaydzuhri_stack_edu_python |
function isNodeClean self hostname
begin
set tmp = yield call getServicesToStop hostname
if length tmp != 0
begin
call returnValue false
end
set tmp = yield call getServicesToStart hostname
if length tmp != 0
begin
call returnValue false
end
call returnValue true
end function | def isNodeClean(self, hostname):
tmp = yield self.getServicesToStop(hostname)
if len(tmp) != 0:
defer.returnValue(False)
tmp = yield self.getServicesToStart(hostname)
if len(tmp) != 0:
defer.returnValue(False)
defer.returnValue(True) | Python | nomic_cornstack_python_v1 |
function one_away_2 first second
begin
comment Check length of strings to determine which operation is allowed
if length first == length second
begin
comment Only allowed 1 replace operation
set diff = false
for tuple i char in enumerate first
begin
if char != second at i
begin
if diff
begin
return false
end
else
begin... | def one_away_2(first, second):
# Check length of strings to determine which operation is allowed
if len(first) == len(second):
# Only allowed 1 replace operation
diff = False
for i, char in enumerate(first):
if char != second[i]:
if diff:
r... | Python | nomic_cornstack_python_v1 |
function post self
begin
set post = call get_json
set post at string postTime = time
set _id = inserted_id
set blab = call find_one dict string _id call ObjectId _id
set blab at string id = string blab at string _id
del blab at string _id
return tuple blab 201
end function | def post(self):
post = request.get_json()
post["postTime"] = time.time()
_id = blabs.insert_one(post).inserted_id
blab = blabs.find_one({"_id": ObjectId(_id)})
blab["id"] = str(blab["_id"])
del blab["_id"]
return blab, 201 | Python | nomic_cornstack_python_v1 |
function daily_values self
begin
return _daily_values
end function | def daily_values(self) -> List[RecipeObjectNutrientsCalories]:
return self._daily_values | Python | nomic_cornstack_python_v1 |
function read path encoding=string utf-8
begin
with open path string rb as f
begin
return decode read f encoding
end
end function | def read(path, encoding="utf-8"):
with open(path, "rb") as f:
return f.read().decode(encoding) | Python | nomic_cornstack_python_v1 |
import xmltodict , json
from AnnotationTool.settings import MEDIA_ROOT
with open replace MEDIA_ROOT + string /xml/2/csrf/bb.xml string \ string / string r encoding=string utf-8 as f
begin
set str_xml = string read f
end
comment print(str_xml)
comment xml格式不能有"&"符号
set str_xml = replace str_xml string & string &
com... | import xmltodict, json
from AnnotationTool.settings import MEDIA_ROOT
with open((MEDIA_ROOT + '/xml/2/csrf/bb.xml' ).replace("\\", "/"),'r',encoding='utf-8') as f:
str_xml = str(f.read())
# print(str_xml)
str_xml = str_xml.replace('&','&') # xml格式不能有"&"符号
# print('jjjj')
doc = xmltodict.parse(str_xml,enco... | Python | zaydzuhri_stack_edu_python |
comment 定义一个sample list
set sample_list = list 0 1 2 3 4 5 6 7 8 9
comment 对定义过的列表进行翻转
set reversed_list = sample_list at slice : : - 1
print string 列表翻转==> reversed_list
comment 将翻转后的数组拼接成字符串
comment 调用‘’(空字符串) str类型的join方法可以连接列表里的元素 用‘’(空白字符)表示链接的时候不用任何字符隔开
set joined_str = join string list comprehension string i ... | #定义一个sample list
sample_list = [0,1,2,3,4,5,6,7,8,9]
#对定义过的列表进行翻转
reversed_list = sample_list[::-1]
print('列表翻转==>', reversed_list)
#将翻转后的数组拼接成字符串
#调用‘’(空字符串) str类型的join方法可以连接列表里的元素 用‘’(空白字符)表示链接的时候不用任何字符隔开
joined_str = ''.join([str(i) for i in reversed_list])
print('反转后的数组拼成字符串 ==>', joined_str)
#用字符串切片的方式取出第三到第八个字符(... | Python | zaydzuhri_stack_edu_python |
from tools.input import BaseKeyword , BoolKeyword
class KeepSymm extends BoolKeyword
begin
string Switches to keeping symmetries.
set keyword = string keepsymm
function output_map self **kwargs
begin
string Prints to Tape. Does not print if breaksym is False on input.
if get kwargs string breaksym true == false
begin
r... | from ..tools.input import BaseKeyword, BoolKeyword
class KeepSymm(BoolKeyword):
""" Switches to keeping symmetries. """
keyword = "keepsymm"
def output_map(self, **kwargs):
""" Prints to Tape.
Does not print if breaksym is False on input.
"""
if kwargs.get('breaksym', True) == False: return ... | Python | zaydzuhri_stack_edu_python |
print string Hello World! | print("Hello World!") | Python | iamtarun_python_18k_alpaca |
comment quando coloca o [] depois da variável e um numero de 1-9 mostra o intem da lista de acordo a sua posição. | #quando coloca o [] depois da variável e um numero de 1-9 mostra o intem da lista de acordo a sua posição. | Python | zaydzuhri_stack_edu_python |
function getAttributes clazz
begin
return dictionary comprehension name : attr for tuple name attr in items __dict__ if not starts with name string __ and not callable attr and not type attr is staticmethod and not type attr is classmethod
end function | def getAttributes(clazz):
return {name: attr for name, attr in clazz.__dict__.items()
if not name.startswith("__")
and not callable(attr)
and not type(attr) is staticmethod
and not type(attr) is classmethod} | Python | nomic_cornstack_python_v1 |
function _start_thread self queue tid tname
begin
set actorState = actorState
set threads = dict
set threads at tid = thread target=FakeThread name=tname args=list actor queues
set daemon = true
start threads at tid
end function | def _start_thread(self, queue, tid, tname):
actorState = self.actorState
actorState.threads = {}
actorState.threads[tid] = threading.Thread(target=sopTester.FakeThread,
name=tname,
args=[actorS... | Python | nomic_cornstack_python_v1 |
function tx_parse raw_tx blockchain=string bitcoin **blockchain_opts
begin
string Parse a raw transaction, based on the type of blockchain it's from Returns a tx dict on success (see get_virtual_transactions) Raise ValueError for unknown blockchain Raise some other exception for invalid raw_tx (implementation-specific)... | def tx_parse(raw_tx, blockchain='bitcoin', **blockchain_opts):
"""
Parse a raw transaction, based on the type of blockchain it's from
Returns a tx dict on success (see get_virtual_transactions)
Raise ValueError for unknown blockchain
Raise some other exception for invalid raw_tx (implementation-spec... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.