code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import numpy as np
import pandas as pd
set PATH_TO_CSV_FOLDER = string ./training/
set dataset_sub1_3m = read csv PATH_TO_CSV_FOLDER + string sub1_3m_straight.csv
print head dataset_sub1_3m
print shape
set dataset_sub1_4m = read csv PATH_TO_CSV_FOLDER + string sub1_4m_straight.csv
print head dataset_sub1_4m
print shape... | import numpy as np
import pandas as pd
PATH_TO_CSV_FOLDER = "./training/"
dataset_sub1_3m = pd.read_csv(PATH_TO_CSV_FOLDER + "sub1_3m_straight.csv")
print(dataset_sub1_3m.head())
print(dataset_sub1_3m.shape)
dataset_sub1_4m = pd.read_csv(PATH_TO_CSV_FOLDER + "sub1_4m_straight.csv")
print(dataset_sub1_4m.head())
print... | Python | zaydzuhri_stack_edu_python |
function group_jerk self group_id jerk=none
begin
if jerk is none
begin
call send string HJ string ? group_id
set jerk = decimal read self
end
else
begin
call send string HJ jerk group_id
end
return jerk
end function | def group_jerk(self, group_id, jerk=None):
if jerk is None:
self.send('HJ', '?', group_id)
jerk = float(self.read())
else:
self.send('HJ', jerk, group_id)
return jerk | Python | nomic_cornstack_python_v1 |
function normalize_volume_size ct_input pet_input locations_CT locations_PET Voxel_size_INPUT Voxel_size_NORM Objective_size
begin
comment Get limits
set locations_PET = sort np locations_PET
set locations_CT = sort np locations_CT
set loc_min = max list locations_CT at 0 locations_PET at 0
set loc_max = min list locat... | def normalize_volume_size(ct_input, pet_input, locations_CT, locations_PET, Voxel_size_INPUT, Voxel_size_NORM, Objective_size):
# Get limits
locations_PET = np.sort(locations_PET)
locations_CT = np.sort(locations_CT)
loc_min = np.max([locations_CT[0],locations_PET[0]])
loc_max = np.min([locati... | Python | nomic_cornstack_python_v1 |
function __init__ self d t n shift=list 0 0
begin
comment assign control point
set control_points = list list d * 0.5 - t * 0.5 0
call __init__ control_points shift
comment specify a hole in the centre of the CHS
set holes = list list 0 0
comment loop through each point of the CHS
for i in range n
begin
comment determi... | def __init__(self, d, t, n, shift=[0, 0]):
# assign control point
control_points = [[d * 0.5 - t * 0.5, 0]]
super().__init__(control_points, shift)
# specify a hole in the centre of the CHS
self.holes = [[0, 0]]
# loop through each point of the CHS
for i in ra... | Python | nomic_cornstack_python_v1 |
import sys
set stdin = open string input.txt string rt
set n = integer input
set a = list map int split input
set m = integer input
set b = list map int split input
sort a
function printYesOrNo num
begin
set tuple lt rt = tuple 0 length a - 1
while lt <= rt
begin
set mid = lt + rt // 2
set midVal = a at mid
if midVal <... | import sys
sys.stdin = open("input.txt","rt")
n=int(input())
a= list(map(int, input().split()))
m=int(input())
b = list(map(int,input().split()))
a.sort()
def printYesOrNo(num) :
lt , rt = 0, len(a) -1
while lt <= rt :
mid = ( lt + rt ) // 2
midVal = a[mid]
if midVal < num :
... | Python | zaydzuhri_stack_edu_python |
function add_filter self filter_config
begin
pass
end function | def add_filter(self, filter_config):
pass | Python | nomic_cornstack_python_v1 |
function get_approx self metric_type interactive=true
begin
info string Metric type " { metric_type } " not found (no exact match). Trying with regex ...
set results = list pattern=metric_type
set matches = list comprehension tuple x at string type split x at string name string / at 1 for x in list results
if length ma... | def get_approx(self, metric_type, interactive=True):
LOGGER.info(f'Metric type "{metric_type}" not found (no exact match). '
f'Trying with regex ...')
results = self.list(pattern=metric_type)
matches = [(x['type'], x['name'].split('/')[1]) for x in list(results)]
if l... | Python | nomic_cornstack_python_v1 |
comment author='zhy'
import threading
import time
function goevent
begin
set e = event
function go
begin
for i in range 10
begin
wait e
print i string go
clear e
end
end function
start thread target=go
return e
end function
set t = call goevent
for i in range 10
begin
sleep 2
set
end | #author='zhy'
import threading
import time
def goevent():
e=threading.Event()
def go():
for i in range(10):
e.wait()
print(i,"go")
e.clear()
threading.Thread(target=go).start()
return e
t=goevent()
for i in range(10):
time.sleep(2)
t.set()
| Python | zaydzuhri_stack_edu_python |
function __git_init self
begin
call init _repository_directory
end function | def __git_init(self):
Repo.init(self._repository_directory) | Python | nomic_cornstack_python_v1 |
function lenstronomy_ID self
begin
return list string TNFW
end function | def lenstronomy_ID(self):
return ['TNFW'] | Python | nomic_cornstack_python_v1 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import gin
function get_pca_xy_angle positions
begin
from sklearn.decomposition import PCA
function get_pca xy
begin
set pca = principal component analysis n_components... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import gin
def get_pca_xy_angle(positions):
from sklearn.decomposition import PCA
def get_pca(xy):
pca = PCA(n_components=1)
xy = xy.numpy()
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment Funciones comunes y utiles en python
set palabra = string Electroencefalografista | # -*- coding: utf-8 -*-
# Funciones comunes y utiles en python
palabra = "Electroencefalografista"
| Python | zaydzuhri_stack_edu_python |
function _get_error_message_from_exception self e
begin
set error_code = AWSSECURITYHUB_ERR_CODE_UNAVAILABLE
set error_msg = AWSSECURITYHUB_ERR_MSG_UNAVAILABLE
try
begin
if args
begin
if length args > 1
begin
set error_code = args at 0
set error_msg = args at 1
end
else
if length args == 1
begin
set error_code = AWSSEC... | def _get_error_message_from_exception(self, e):
error_code = AWSSECURITYHUB_ERR_CODE_UNAVAILABLE
error_msg = AWSSECURITYHUB_ERR_MSG_UNAVAILABLE
try:
if e.args:
if len(e.args) > 1:
error_code = e.args[0]
error_msg = e.args[1]
... | Python | nomic_cornstack_python_v1 |
function dsse_attestation self
begin
return get pulumi self string dsse_attestation
end function | def dsse_attestation(self) -> pulumi.Output['outputs.DSSEAttestationNoteResponse']:
return pulumi.get(self, "dsse_attestation") | Python | nomic_cornstack_python_v1 |
function is_fix_applicable fix ref
begin
set conf = call parse_fix_name __name__
for key in keys conf
begin
if call normalize_identifier get ref key != call normalize_identifier get conf key
begin
if key == string reference
begin
if get conf key
begin
if not match get ref key or string
begin
return false
end
end
else
b... | def is_fix_applicable(fix: types.FunctionType, ref: dict) -> bool:
conf = parse_fix_name(fix.__name__)
for key in conf.keys():
if normalize_identifier(ref.get(key)) != normalize_identifier(conf.get(key)):
if key == 'reference':
if conf.get(key):
if not _re... | Python | nomic_cornstack_python_v1 |
function get_program_research program_id
begin
return call jsonify call get_program_research program_id
end function | def get_program_research(program_id):
return jsonify(firebase.get_program_research(program_id)) | Python | nomic_cornstack_python_v1 |
function hi
begin
return string hi
end function
function fatorial num
begin
set result = 1
if num == 0
begin
return 1
end
else
begin
for i in range 1 num + 1
begin
set result = result * i
end
return result
end
end function
function ehPar num
begin
if num % 2 == 0
begin
return true
end
else
begin
return false
end
end fu... | def hi():
return "hi"
def fatorial(num):
result = 1
if num == 0:
return 1
else:
for i in range(1,num + 1):
result *= i
return result
def ehPar(num):
if num % 2 == 0:
return True
else:
return False
def divideString(st):
return st.split(" ... | Python | zaydzuhri_stack_edu_python |
function _preserve_bonds self sliced_cartesian use_lookup=none
begin
string Is called after cutting geometric shapes. If you want to change the rules how bonds are preserved, when applying e.g. :meth:`Cartesian.cut_sphere` this is the function you have to modify. It is recommended to inherit from the Cartesian class to... | def _preserve_bonds(self, sliced_cartesian,
use_lookup=None):
"""Is called after cutting geometric shapes.
If you want to change the rules how bonds are preserved, when
applying e.g. :meth:`Cartesian.cut_sphere` this is the
function you have to modify.
... | Python | jtatman_500k |
function openid_form context
begin
update context dict string form call OpenIDLoginForm
return context
end function | def openid_form(context):
context.update({
'form': OpenIDLoginForm()
})
return context | Python | nomic_cornstack_python_v1 |
function test_amountscurrent self
begin
assert true debt
assert equal call compute_current_amount amount
end function | def test_amountscurrent(self):
self.assertTrue(self._instance.debt)
self.assertEqual(self.compute_current_amount(), self._instance.amount) | Python | nomic_cornstack_python_v1 |
function get_human_box_detection bbox
begin
comment Create an empty list
set array_boxes = list
for tuple i bbox in enumerate bbox
begin
comment If the class of the detected object is 1 and the confidence of the prediction is > 0.6
if bbox at 5 == 0
begin
set box = array bbox at slice : 4 : dtype=int32
append at tup... | def get_human_box_detection(bbox):
array_boxes = [] # Create an empty list
for i, bbox in enumerate(bbox):
# If the class of the detected object is 1 and the confidence of the prediction is > 0.6
if bbox[5] == 0:
box = np.array(bbox[:4], dtype=np.int32)
array_boxes.appen... | Python | nomic_cornstack_python_v1 |
function cn_unpack_rsp cls rsp_str
begin
return call hk_unpack_rsp rsp_str
end function | def cn_unpack_rsp(cls, rsp_str):
return cls.hk_unpack_rsp(rsp_str) | Python | nomic_cornstack_python_v1 |
function log_out
begin
pop session string logged_in none
call flash string You were logged out.
return call redirect call url_for string blog.show_posts
end function | def log_out():
session.pop('logged_in', None)
flash('You were logged out.')
return redirect(url_for('blog.show_posts')) | Python | nomic_cornstack_python_v1 |
function submit_button
begin
try
begin
comment Opens the file storing the users data and loads it into memory
set file = open string userInfo.txt string r
for line in file
begin
if string : in line
begin
set tuple key value = split line string : 1
set cvalue = length value - 1
set value = value at slice 0 : cvalue :
s... | def submit_button():
try:
# Opens the file storing the users data and loads it into memory
file = open("userInfo.txt", 'r')
for line in file:
if ':' in line:
key,value = line.split(':', 1)
cvalue = len(value)-1
... | Python | nomic_cornstack_python_v1 |
import csv
import datetime
import logging
import os
import os.path
import re
from typing import List
import pandas as pd
import matplotlib.pyplot as plt
from datatypes import NDResult
set languages = dict 611 string english ; 584 string french ; 2253 string german ; 3856 string japanese
function summary_stats_output re... | import csv
import datetime
import logging
import os
import os.path
import re
from typing import List
import pandas as pd
import matplotlib.pyplot as plt
from datatypes import NDResult
languages = {
611: 'english',
584: 'french',
2253: 'german',
3856: 'japanese'
}
def summary_stats_output(results_cs... | Python | zaydzuhri_stack_edu_python |
function ccc self predictions labels
begin
set predictions = view predictions - 1
set labels = view labels - 1
function _get_moments data_tensor
begin
set mean_t = mean torch data_tensor
set var_t = variance torch data_tensor
return tuple mean_t var_t
end function
set tuple labels_mean labels_var = call _get_moments la... | def ccc(self,
predictions:torch.Tensor,
labels:torch.Tensor):
predictions = predictions.view(-1,)
labels = labels.view(-1,)
def _get_moments(data_tensor):
mean_t = torch.mean(data_tensor)
var_t = torch.var(data_tensor)
retur... | Python | nomic_cornstack_python_v1 |
from Equation import Expression
import matplotlib.pyplot as plt
import numpy as np
import random
from mpl_toolkits.mplot3d import Axes3D
class Solver
begin
function __init__ self
begin
set delta = 0.001
set epsilon = 0.001
set step = 0.1
end function
function grad self x foo
begin
set result = list
for i in range leng... | from Equation import Expression
import matplotlib.pyplot as plt
import numpy as np
import random
from mpl_toolkits.mplot3d import Axes3D
class Solver:
def __init__(self):
self.delta = 0.001
self.epsilon = 0.001
self.step = 0.1
def grad(self, x, foo):
result = []
for i ... | Python | zaydzuhri_stack_edu_python |
function refresh_token self
begin
info string Node.refresh_token, start of
assert node_connection is not none msg string NodeConnection.refresh_token, node_connection is None
try
begin
call verify_token
end
except AssertionError as aerr
begin
error format string Node.refresh_token, {} aerr
raise aerr
end
except ErrorMe... | def refresh_token(self):
logger.info("Node.refresh_token, start of")
assert self.node_connection is not None, "NodeConnection.refresh_token, node_connection is None"
try:
self.verify_token()
except AssertionError as aerr:
logger.error("Node.refresh_token, {}".for... | Python | nomic_cornstack_python_v1 |
string 请实现一个函数用来匹配包括'.'和'*'的正则表达式。 1.模式中的字符'.'表示任意一个字符 2.模式中的字符'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配 数据范围: 1.str 只包含从 a-z 的小写字母。 2.pattern 只包含从 a-z 的小写字母以及字符 . 和 *,无连续的 '*'。 3. 0 <=str.length <=26 4. 0 <=pattern.length <=26 c 输入: "aaa","a*a" 返回值: true 说明:... | '''
请实现一个函数用来匹配包括'.'和'*'的正则表达式。
1.模式中的字符'.'表示任意一个字符
2.模式中的字符'*'表示它前面的字符可以出现任意次(包含0次)。
在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
数据范围:
1.str 只包含从 a-z 的小写字母。
2.pattern 只包含从 a-z 的小写字母以及字符 . 和 *,无连续的 '*'。
3. 0 <=str.length <=26
4. 0 <=pattern.length <=26 c
输入:
"aaa","a*a"
返回值:
true
说明:... | Python | zaydzuhri_stack_edu_python |
function set_postwork self postwork
begin
if not postwork
begin
set postwork = none
return
end
if not callable postwork
begin
raise call FunctionsTypeError string The postwork object passed in is not of function type!
end
set postwork = postwork
end function | def set_postwork(self, postwork: types.FunctionType):
if not postwork:
self.postwork = None
return
if not callable(postwork):
raise FunctionsTypeError("The postwork object passed in is not of function type!")
self.postwork = postwork | Python | nomic_cornstack_python_v1 |
function __init__ self corpus
begin
set unigramCounts = default dictionary lambda -> 0
set bigramCounts = default dictionary lambda -> 0
set starts_with = default dictionary lambda -> 0
set ends_with = default dictionary lambda -> 0
train self corpus
set all_words = sum values unigramCounts
set vocabulary_size = le... | def __init__(self, corpus):
self.unigramCounts = collections.defaultdict(lambda: 0)
self.bigramCounts = collections.defaultdict(lambda: 0)
self.starts_with = collections.defaultdict(lambda: 0)
self.ends_with = collections.defaultdict(lambda: 0)
self.train(corpus)
self.all_words = sum(self.unigra... | Python | nomic_cornstack_python_v1 |
from MyTriple import *
import sys
import time
comment def flat_recurseChildren(query, ts):
comment c = filter(lambda x: x.object() == query.subject(), ts)
comment if len(c) == 0: return []
comment else:
comment ret = []
comment for i in c:
comment print query,'->',i;
comment ret.append( (i, recurseChildren(i, ts)) )
co... | from MyTriple import *
import sys
import time
#def flat_recurseChildren(query, ts):
#c = filter(lambda x: x.object() == query.subject(), ts)
#if len(c) == 0: return []
#else:
#ret = []
#for i in c:
#print query,'->',i;
#ret.append( (i, recurseChildren(i, ts)) )
... | Python | zaydzuhri_stack_edu_python |
string Attempts to speed up execution by finding the correct sparsity.
comment pip install -q tensorflow-model-optimization
from tensorflow_model_optimization.sparsity import keras as sparsity
comment Create a pruned model
set epochs = 5
set num_samples = length train_images
comment default size
set batch_size = 32
set... | '''
Attempts to speed up execution by finding the correct sparsity.
'''
# pip install -q tensorflow-model-optimization
from tensorflow_model_optimization.sparsity import keras as sparsity
# Create a pruned model
epochs = 5
num_samples = len(train_images)
batch_size = 32 # default size
end_step = np.ceil(1.0 * num_sam... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
import random
set poprawna = 0
set liczba1 = random integer 1 30
set liczba2 = random integer 1 30
set liczba3 = random integer 1 30
set liczba4 = random integer 1 30
set liczba5 = random integer 1 30
set odpowiedz1 = input string Podaj pierwszą liczbe (1-30):... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
poprawna = 0
liczba1 = random.randint (1,30)
liczba2 = random.randint (1,30)
liczba3 = random.randint (1,30)
liczba4 = random.randint (1,30)
liczba5 = random.randint (1,30)
odpowiedz1 = input ('Podaj pierwszą liczbe (1-30): ')
while int (odpowiedz1) > ... | Python | zaydzuhri_stack_edu_python |
function create_formal_offer payee_creditor_id offer_announcement_id debtor_ids debtor_amounts valid_until_ts description=none reciprocal_payment_debtor_id=none reciprocal_payment_amount=0
begin
call create_formal_offer payee_creditor_id offer_announcement_id debtor_ids debtor_amounts call parse_date valid_until_ts des... | def create_formal_offer(
payee_creditor_id: int,
offer_announcement_id: int,
debtor_ids: List[int],
debtor_amounts: List[int],
valid_until_ts: str,
description: Optional[dict] = None,
reciprocal_payment_debtor_id: Optional[int] = None,
reciprocal_payment_a... | Python | nomic_cornstack_python_v1 |
function cost_function df method include_archival=true overhead=2.0 * 60 lower=3.0 * 60 upper=20.0 * 60
begin
set counts = split method string = at - 1
set nobs = integer decimal split split method string - at 1 string = at - 1
if counts == string ramp
begin
set counts = call exp_ramp df at string vmag c1=125.0 c2=60.0... | def cost_function(df, method, include_archival=True, overhead=2.*60, lower=3.*60, upper=20.*60):
counts = method.split('=')[-1]
nobs = int(float((method.split('-')[1]).split('=')[-1]))
if counts == 'ramp':
counts = exp_ramp(df['vmag'], c1=125., c2=60.)
else:
counts = float(counts)
#... | Python | nomic_cornstack_python_v1 |
function reset self
begin
for index in values self
begin
call reset
end
set objectids = call TreeSet
end function | def reset(self):
for index in self.values():
index.reset()
self.objectids = self.family.IF.TreeSet() | Python | nomic_cornstack_python_v1 |
function QR_algorithm_shift_Givens_int A
begin
set tuple A scale = call scale_64bit_matrix copy A
comment First, tridiagonalize the input matrix to a Hessenberg matrix.
set T = call convert_to_Hessenberg_Givens_int A
set tuple m n = shape
if n != m
begin
raise call LinAlgError string Array must be square.
end
set conve... | def QR_algorithm_shift_Givens_int(A):
A, scale = fp.scale_64bit_matrix(A.copy())
# First, tridiagonalize the input matrix to a Hessenberg matrix.
T = ma.convert_to_Hessenberg_Givens_int(A)
m, n = T.shape
if n != m:
raise np.linalg.LinAlgError("Array must be square.")
convergence_meas... | Python | nomic_cornstack_python_v1 |
function _permute_sparse a dims perm
begin
set tuple perm dims = tuple call asarray perm call asarray dims
comment New dimensions & stride (i.e. product of preceding dimensions)
set new_dims = dims at perm
set odim_stride = accumulate dims at slice : : - 1 at slice : : - 1 // dims
set ndim_stride = accumulate new_d... | def _permute_sparse(a, dims, perm):
perm, dims = np.asarray(perm), np.asarray(dims)
# New dimensions & stride (i.e. product of preceding dimensions)
new_dims = dims[perm]
odim_stride = np.multiply.accumulate(dims[::-1])[::-1] // dims
ndim_stride = np.multiply.accumulate(new_dims[::-1])[::-1] // new... | Python | nomic_cornstack_python_v1 |
function _eagerly_create_optimizer_variables model_variables optimizer
begin
set delta_tensor_spec = call map_structure lambda v -> call from_tensor call read_value trainable
comment Trace the function, which forces eager variable creation.
call get_concrete_function optimizer=optimizer model_variables=model_variables ... | def _eagerly_create_optimizer_variables(
*, model_variables: model_utils.ModelWeights,
optimizer: tf.keras.optimizers.Optimizer) -> List[tf.Variable]:
delta_tensor_spec = tf.nest.map_structure(
lambda v: tf.TensorSpec.from_tensor(v.read_value()),
model_variables.trainable)
# Trace the function, ... | Python | nomic_cornstack_python_v1 |
function dumps_zmq_op dp
begin
assert is instance dp tuple list tuple
set protos = list comprehension call to_tensor_proto arr for arr in dp
return call dump_tensor_protos protos
end function | def dumps_zmq_op(dp):
assert isinstance(dp, (list, tuple))
protos = [to_tensor_proto(arr) for arr in dp]
return dump_tensor_protos(protos) | Python | nomic_cornstack_python_v1 |
comment 한수
comment 어떤 양의 정수 X의 각 자리가 등차수열을 이룬다면, 그 수를 한수라고 한다.
comment 등차수열은 연속된 두 개의 수의 차이가 일정한 수열을 말한다. N이 주어졌을 때, 1보다 크거나 같고,
comment N보다 작거나 같은 한수의 개수를 출력하는 프로그램을 작성하시오.
function solve n
begin
set l = list comprehension integer i for i in string n
for i in range length l - 2
begin
if l at i - l at i + 1 != l at i +... | # 한수
# 어떤 양의 정수 X의 각 자리가 등차수열을 이룬다면, 그 수를 한수라고 한다.
# 등차수열은 연속된 두 개의 수의 차이가 일정한 수열을 말한다. N이 주어졌을 때, 1보다 크거나 같고,
# N보다 작거나 같은 한수의 개수를 출력하는 프로그램을 작성하시오.
def solve(n: int) -> bool:
l=[int(i) for i in str(n)]
for i in range(len(l)-2):
if l[i]-l[i+1] != l[i+1]-l[i+2]:
return False
retur... | Python | zaydzuhri_stack_edu_python |
string 表題: ロギング - Pythonにおけるログレベルのオーダー 1 CRITICAL 2 ERROR 3 WARNING <---WANING、これより下(INFO, DEBUG)は表示されない 4 INFO 5 DEBUG
import logging
comment ロギングのレベルを変更している
comment こうする事で、waning以下も表示する事ができる
call basicConfig filename=string test.log level=INFO
comment logging.critical('critical')
comment logging.error('error')
commen... | """
表題: ロギング
- Pythonにおけるログレベルのオーダー
1 CRITICAL
2 ERROR
3 WARNING <---WANING、これより下(INFO, DEBUG)は表示されない
4 INFO
5 DEBUG
"""
import logging
# ロギングのレベルを変更している
# こうする事で、waning以下も表示する事ができる
logging.basicConfig(filename='test.log', level=logging.INFO)
# logging.critical('critical')
# logging.error('error')
# logging.warnin... | Python | zaydzuhri_stack_edu_python |
function quantize_down_and_shrink_range input input_min input_max out_type name=none
begin
set _ctx = _context or call context
set tld = _thread_local_data
if is_eager
begin
try
begin
set _result = call TFE_Py_FastPathExecute _context_handle device_name string QuantizeDownAndShrinkRange name op_callbacks input input_mi... | def quantize_down_and_shrink_range(input, input_min, input_max, out_type, name=None):
_ctx = _context._context or _context.context()
tld = _ctx._thread_local_data
if tld.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, tld.device_name, "QuantizeDownAndShr... | Python | nomic_cornstack_python_v1 |
function pc_project mt loadings_ht loading_location=string loadings af_location=string pca_af
begin
set mt = call pc_hwe_gt mt loadings_ht loading_location af_location
set mt = call annotate_cols scores=call array_sum pca_loadings * GTN
return select call cols string scores
end function | def pc_project(
mt: hl.MatrixTable,
loadings_ht: hl.Table,
loading_location: str = "loadings",
af_location: str = "pca_af",
) -> hl.Table:
mt = pc_hwe_gt(mt, loadings_ht, loading_location, af_location)
mt = mt.annotate_cols(scores=hl.agg.array_sum(mt.pca_loadings * mt.GTN))
return mt.cols().... | Python | nomic_cornstack_python_v1 |
function get_ents self feasible_set t r
begin
set evaluations = list comprehension call evaluate_combination combination feasible_set t r for combination in codepool
set idx = call argwhere absolute evaluations - call amax evaluations <= 1e-10
return array evaluations
end function | def get_ents(self, feasible_set, t, r):
evaluations = [self.evaluate_combination(combination,
feasible_set, t, r) for combination in self.codepool]
idx = np.argwhere(abs(evaluations -
np.amax(evaluations)) <= 1e-10)
return np.array(evaluations) | Python | nomic_cornstack_python_v1 |
import sys
comment This is meant to hold the different security tests that can be output
comment this takes in a file and outputs the data as a sulley configuration file.
function output_sulley_file fname template outfile
begin
set temp = open template string r
set out = open outfile string w
for temp_line in temp
begi... | import sys
# This is meant to hold the different security tests that can be output
# this takes in a file and outputs the data as a sulley configuration file.
def output_sulley_file(fname,template,outfile):
temp = open(template, "r" )
out = open(outfile, "w" )
for temp_line in temp:
if "# << --... | Python | zaydzuhri_stack_edu_python |
function transform cls
begin
comment figure out the correspounding indexes for the headers
comment describe in PROGRAM_COLUMNS
set topic_index = list comprehension if expression x in hold_data at 0 then index hold_data at 0 x else - 1 for x in PROGRAMS_COLUMNS
comment collect data with specified index and reform them
s... | def transform(cls):
# figure out the correspounding indexes for the headers
# describe in PROGRAM_COLUMNS
topic_index = [
cls.hold_data[0].index(x) if x in cls.hold_data[0] else -1
for x in PROGRAMS_COLUMNS
]
# collect data with specified index and refor... | Python | nomic_cornstack_python_v1 |
function __delete_job_status self job
begin
set keys = call _get_keys string jobstatus: { id } :*
for key in keys
begin
delete key
end
end function | def __delete_job_status(self, job: Job):
keys = self._get_keys(f'jobstatus:{job.id}:*')
for key in keys:
self.redis_client.delete(key) | Python | nomic_cornstack_python_v1 |
comment This is program to find multiple occurrence of sub_String in string
set string1 = input string enter the main string:
set string2 = input string enter the sub_String value:
set flag = false
set index = 0
while index <= length string1
begin
set result = find string1 string2 index length string1
if result != - 1
... | # This is program to find multiple occurrence of sub_String in string
string1 = input('enter the main string: ')
string2 = input('enter the sub_String value: ')
flag = False
index = 0
while index <= len(string1):
result = string1.find(string2, index ,len(string1))
if result != -1:
print('string is fou... | Python | zaydzuhri_stack_edu_python |
function unsupported self unsupported
begin
set _unsupported = unsupported
end function | def unsupported(self, unsupported):
self._unsupported = unsupported | Python | nomic_cornstack_python_v1 |
function SBS A B
begin
if A == 0 or B == 0
begin
return 0
end
else
if set A <= set B or set B <= set A
begin
return 1
end
else
begin
return length set A ? set B / length set A ? set B
end
end function
function StrToList A
begin
set C = list
for i in A
begin
append C i
end
return C
end function
set x = string 双眼病变
set ... | def SBS(A,B):
if A==0 or B ==0:
return 0
elif set(A)<=set(B) or set(B)<=set(A):
return 1
else:
return len(set(A)&set(B)) /len(set(A)|set(B))
def StrToList(A):
C=[]
for i in A:
C.append(i)
return C
x='双眼病变'
a=StrToList(x)
y='双眼发病'
b=StrToList(y)
c=SBS(a,b)
print... | Python | zaydzuhri_stack_edu_python |
function train train_iterator model criterion optimizer
begin
set batch_time = call AverageMeter
set data_time = call AverageMeter
set losses = call AverageMeter
set timers = dictionary comprehension k : call TimerStat for k in list string d2h string fwd string grad string apply
comment switch to train mode
train model... | def train(train_iterator, model, criterion, optimizer):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
timers = {k: TimerStat() for k in ["d2h", "fwd", "grad", "apply"]}
# switch to train mode
model.train()
end = time.time()
for i, (features, target) i... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import re
set lines = split string 1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc string
set lines = split read open string 2.in string
set valid1 = 0
set valid2 = 0
for line in lines
begin
set tuple minr maxr = list comprehension integer x for x in find all string (\d+) line
set l = split spl... | #!/usr/bin/env python3
import re
lines = '''1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc'''.split('\n')
lines = open('2.in').read().split('\n')
valid1 = 0
valid2 = 0
for line in lines:
minr,maxr = [int(x) for x in re.findall('(\d+)', line)]
l = line.split(':')[0].split(' ')[1]
pasw = line.split(': ')[1]
if minr <=... | Python | zaydzuhri_stack_edu_python |
function show_line_profile self nu_min nu_max npoints=100 include_abs=true include_emit=true vs_nu=true
begin
set tuple nu Fline = call calc_line_profile nu_min nu_max npoints=npoints
if include_abs
begin
set Fabs = call calc_line_profile nu_min nu_max npoints=npoints mode=string abs at - 1
end
if include_emit
begin
se... | def show_line_profile(self, nu_min, nu_max, npoints = 100, include_abs = True, include_emit = True, vs_nu = True):
nu, Fline = self.calc_line_profile(nu_min, nu_max, npoints = npoints)
if include_abs:
Fabs = self.calc_line_profile(nu_min, nu_max, npoints = npoints, mode = "abs")[-1]
... | Python | nomic_cornstack_python_v1 |
function statistical_significance_CC method eval_measure datasets learners optims length=500
begin
set runs = set
set result_dict = default dictionary lambda -> list
function search_case_insensitive method
begin
return glob glob string ../results/*- { upper method } -*-500-*-run?.pkl + glob glob string ../results/*- {... | def statistical_significance_CC(method:str, eval_measure:callable, datasets:list, learners:list, optims:list, length=500):
runs = set()
result_dict = defaultdict(lambda: [])
def search_case_insensitive(method):
return glob.glob(f'../results/*-{method.upper()}-*-500-*-run?.pkl') + \
... | Python | nomic_cornstack_python_v1 |
function fetch_usermsgs receiver sender after=none before=none count=20
begin
set usermsgs = filter call Q from_user=receiver to_user=sender ? call Q from_user=sender to_user=receiver
if after
begin
set usermsgs = filter created__gt=after
end
if before
begin
set usermsgs = filter created__lt=before
end
comment This wil... | def fetch_usermsgs(receiver, sender,
after=None, before=None, count=20):
usermsgs = UserMsg.objects.filter(
Q(from_user=receiver, to_user=sender) |
Q(from_user=sender, to_user=receiver))
if after:
usermsgs = usermsgs.filter(created__gt=after)
if before:
use... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string This is a O(n) solution. Might be possible to improve this.
function is_bouncy a
begin
set digits = list string a
return sorted digits != digits and sorted digits != list reversed digits
end function
set bouncy = 0
set nonbouncy = 1
set num = 1
set proportion = 0
while proportion < 0.9
b... | #!/usr/bin/python
'''
This is a O(n) solution. Might be possible to improve this.
'''
def is_bouncy(a):
digits = list(str(a))
return (sorted(digits) != digits and sorted(digits) != list(reversed(digits)))
bouncy = 0
nonbouncy = 1
num = 1
proportion = 0
while (proportion < .90):
num = num + 1
if (is_bouncy(num))... | Python | zaydzuhri_stack_edu_python |
function end_index self
begin
return min start_index + page_size - 1 total_rows
end function | def end_index(self) -> int:
return min(self.start_index + self.page_size - 1, self.total_rows) | Python | nomic_cornstack_python_v1 |
function state self
begin
if breakpoint and pc in _breakpoint_original_bytes
begin
warning string Overwriting current breakpoint in memory so it doesn't trip up angr.
warning string This has the side-effect of disabling this breakpoint. You can re-enable manually.
set orig_bytes = _breakpoint_original_bytes at pc
set b... | def state(self):
if self._thread.breakpoint and self._thread.pc in self._process.threads._breakpoint_original_bytes:
LOGGER.warning("Overwriting current breakpoint in memory so it doesn't trip up angr.")
LOGGER.warning("This has the side-effect of disabling this breakpoint. You can re-e... | Python | nomic_cornstack_python_v1 |
string comparisonFunction.py
from collections import defaultdict
from exemplar.report import calculate_page_percentages
function comparefunction entries expected
begin
string compare the result from the classifier to the expected result
set result = call calculate_page_percentages entries
set comparison_delta = default... | """
comparisonFunction.py
"""
from collections import defaultdict
from exemplar.report import calculate_page_percentages
def comparefunction(entries, expected):
"""
compare the result from the classifier to the expected result
"""
result = calculate_page_percentages(entries)
comparison_delta = ... | Python | zaydzuhri_stack_edu_python |
comment ml_05.py
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
set iris = call load_iris
set tuple X_train X_test y_train y_test = train test split data target random_stat... | # ml_05.py
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
iris = load_iris()
X_train,X_test,y_train,y_test = train_test_split(iris.data,iris.target,random_state=... | Python | zaydzuhri_stack_edu_python |
from sauron import Sauron
from convolution_nn import ConvolutionNN
import cv2
import os
import time
import numpy as np
comment from picamera import PiCamera
set PROJECT_ROOT = directory name path absolute path path __file__
set FACE_CASCADES = call CascadeClassifier join path PROJECT_ROOT string cascades/data/haarcasca... | from sauron import Sauron
from convolution_nn import ConvolutionNN
import cv2
import os
import time
import numpy as np
#from picamera import PiCamera
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
FACE_CASCADES = cv2.CascadeClassifier(os.path.join(PROJECT_ROOT, "cascades/data/haarcascade_frontalface_alt2.x... | Python | zaydzuhri_stack_edu_python |
for i in range 1 5
begin
for j in range 1 5
begin
for m in range 1 5
begin
if i != j and i != m and j != m
begin
print i j m
end
end
end
end | for i in range(1,5):
for j in range(1,5):
for m in range(1,5):
if (i!=j)and(i!=m)and(j!=m):
print (i,j,m) | Python | zaydzuhri_stack_edu_python |
function _configure_addon self
begin
set cfg = none
try
begin
set data_dir = split path data_dir
set cfg = call Configuration jobtype=string Blender data_path=data_dir at 0 log_level=integer log_level name=ini_file datadir=data_dir at 1
end
except tuple InvalidConfigException IndexError as exp
begin
warning string Warn... | def _configure_addon(self):
cfg = None
try:
data_dir = os.path.split(self.props.data_dir)
cfg = Configuration(jobtype='Blender',
data_path=data_dir[0],
log_level=int(self.props.log_level),
... | Python | nomic_cornstack_python_v1 |
function requestDistributedObject self doId
begin
assert call debugCall
set distObj = get doId2do doId
if distObj is not none
begin
comment Already have it
return
end
if doId in distributedObjectRequests
begin
comment Already requested it
return
end
comment todo: add timeout for to remove request
add distributedObjectR... | def requestDistributedObject(self, doId):
assert self.notify.debugCall()
distObj = self.doId2do.get(doId)
if distObj is not None:
# Already have it
return
if doId in self.distributedObjectRequests:
# Already requested it
return
#tod... | Python | nomic_cornstack_python_v1 |
function getOutputPorts interface_kind
begin
return list comprehension list name ports at name for name in ports if call isoutput
end function | def getOutputPorts(interface_kind: InterfaceKind) -> list:
return [[name, interface_kind.ports[name]] for name in interface_kind.ports if interface_kind.ports[name].isoutput()] | Python | nomic_cornstack_python_v1 |
function GetApp self
begin
return get App
end function | def GetApp( self ):
return wx.App.Get() | Python | nomic_cornstack_python_v1 |
function _handle_build_pre_processing self
begin
set stacks = list
if any generator expression call esbuild_configured for stack in stacks
begin
comment esbuild is configured in one of the stacks, will check and update stack metadata accordingly
for stack in stacks
begin
append stacks call set_sourcemap_metadata_from_... | def _handle_build_pre_processing(self) -> List[Stack]:
stacks = []
if any(EsbuildBundlerManager(stack).esbuild_configured() for stack in self.stacks):
# esbuild is configured in one of the stacks, will check and update stack metadata accordingly
for stack in self.stacks:
... | Python | nomic_cornstack_python_v1 |
function dl_data_sets train_dir source_url=DEFAULT_SOURCE_URL
begin
comment empty string check
if not source_url
begin
set source_url = DEFAULT_SOURCE_URL
end
set TRAIN_IMAGES = string train-images-idx3-ubyte.gz
set TRAIN_LABELS = string train-labels-idx1-ubyte.gz
set TEST_IMAGES = string t10k-images-idx3-ubyte.gz
set ... | def dl_data_sets(train_dir, source_url=DEFAULT_SOURCE_URL):
if not source_url: # empty string check
source_url = DEFAULT_SOURCE_URL
TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
TEST_LABELS = 't10k-labels-... | Python | nomic_cornstack_python_v1 |
function _get_maps_get_default_rules self
begin
return __maps_get_default_rules
end function | def _get_maps_get_default_rules(self):
return self.__maps_get_default_rules | Python | nomic_cornstack_python_v1 |
function _validate_language_support self dict_config
begin
from os import stat , listdir
try
begin
set _str_name_language = dict_config at string play at string call_params at string --language
comment for current configuration of Festival
try
begin
set _str_path_dir_share_festival_languages = string /usr/share/festiva... | def _validate_language_support(self, dict_config):
from os import stat, listdir
try:
_str_name_language = dict_config['play']['call_params']['--language']
# for current configuration of Festival
try:
_str_path_dir_share_festival_languages = '/usr/sha... | Python | nomic_cornstack_python_v1 |
function verify_auth_token token
begin
comment In case the token so wrong that it's None
if not token
begin
raise BadSignatureToken
end
set gen_token = call Serializer config at string API_SECRET_KEY
try
begin
set data = loads token
end
except SignatureExpired
begin
comment valid token, but expired
raise call ExpiredTo... | def verify_auth_token(token):
# In case the token so wrong that it's None
if not token:
raise BadSignatureToken
gen_token = Serializer(app.config['API_SECRET_KEY'])
try:
data = gen_token.loads(token)
except SignatureExpired:
raise ExpiredToken... | Python | nomic_cornstack_python_v1 |
function reaching_have_long self sticks conditions
begin
return call reaching_have_long sticks=sticks conditions=conditions
end function | def reaching_have_long(self, sticks: List[Candlestick], conditions: List[InvestCondition]) -> bool:
return self.random_rule.reaching_have_long(sticks = sticks, conditions = conditions) | Python | nomic_cornstack_python_v1 |
from Phidgets.Devices.Stepper import Stepper
from global_constants import TED_STEPPER_INDEX
set controller = call Stepper
call openPhidget
comment Converts a number of steps into the equivalent degrees
function step2deg steps asBearing=false
begin
comment If asBearing is True, this returns the bearing in degrees of the... | from Phidgets.Devices.Stepper import Stepper
from ..global_constants import TED_STEPPER_INDEX
controller = Stepper()
controller.openPhidget()
#Converts a number of steps into the equivalent degrees
def step2deg(steps, asBearing = False):
#If asBearing is True, this returns the bearing in degrees of the given step... | Python | zaydzuhri_stack_edu_python |
import smtplib
from email.mime.text import MIMEText
from collections import defaultdict
function send_email subject message from_addr *to_addrs host=string localhost port=1025 **headers
begin
set headers = if expression headers is none then dict else headers
set email = call MIMEText message
set email at string Subjec... | import smtplib
from email.mime.text import MIMEText
from collections import defaultdict
def send_email(subject, message, from_addr, *to_addrs,
host="localhost", port=1025, **headers):
headers = {} if headers is None else headers
email = MIMEText(message)
email['Subject'] = subject
email['From'] = fr... | Python | zaydzuhri_stack_edu_python |
import nltk
import numpy as np
import sklearn_crfsuite
from sklearn_crfsuite import scorers
from sklearn_crfsuite import metrics
from sklearn.metrics import f1_score
from sklearn.model_selection import RandomizedSearchCV
import scipy
from sklearn.metrics import make_scorer
from nltk.corpus import wordnet as wn
from nlt... | import nltk
import numpy as np
import sklearn_crfsuite
from sklearn_crfsuite import scorers
from sklearn_crfsuite import metrics
from sklearn.metrics import f1_score
from sklearn.model_selection import RandomizedSearchCV
import scipy
from sklearn.metrics import make_scorer
from nltk.corpus import wordnet as wn
from nlt... | Python | zaydzuhri_stack_edu_python |
function call_binana self autodock_path autodock_path_2
begin
import process_binana
set autodock_chain_A = string $MGL/pythonsh $ADT/prepare_receptor4.py -r + complex_name_A + string -A hydrogens -o output/ + complex_name + string _ + chains at 0 + string .pdbqt
set autodock_chain_B = string $MGL/pythonsh $ADT/prepare_... | def call_binana(self, autodock_path, autodock_path_2):
import process_binana
autodock_chain_A = "$MGL/pythonsh $ADT/prepare_receptor4.py -r " + self.complex_name_A \
+ " -A hydrogens -o output/" + self.complex_name + "_" + self.chains[0] + ".pdbqt\n"
autodock_chain_B = "$MGL/pyth... | Python | nomic_cornstack_python_v1 |
function test_mp_fit_columns self
begin
set details = call analyze mp_fit=true
assert equal is instance details DataFrame true string details is a pandas DataFrame
set columns = list string num_spikes string sigma_mp string mp_softrank
for key in columns
begin
assert true key in columns format string {} in details. Col... | def test_mp_fit_columns(self):
details = self.watcher.analyze(mp_fit=True)
self.assertEqual(isinstance(details, pd.DataFrame), True, "details is a pandas DataFrame")
columns = ["num_spikes", "sigma_mp", "mp_softrank"]
for key in columns:
self.assertTrue(key in details.columns, "{} in details. Columns ... | Python | nomic_cornstack_python_v1 |
function test_index_zero self
begin
comment TODO: change as exception is changed
with assert raises Exception
begin
call change_header Path=0 SectionType=1 Value=2
end
end function | def test_index_zero(self):
# TODO: change as exception is changed
with self.assertRaises(Exception):
self.test_table.change_header(Path=0, SectionType=1, Value=2) | Python | nomic_cornstack_python_v1 |
from turtle import Turtle , Screen
import random
set race = false
set screen = call Screen
setup screen width=500 height=400
set bet = call textinput string Make your bet string Which turtle will win the race? Enter a color:
set colors = list string red string orange string yellow string green string blue string purple... | from turtle import Turtle, Screen
import random
race = False
screen = Screen()
screen.setup(width = 500, height = 400)
bet = screen.textinput("Make your bet", 'Which turtle will win the race? Enter a color: ')
colors = ['red','orange','yellow','green','blue','purple']
turtles = []
for num, color in enumerate(colors):... | Python | zaydzuhri_stack_edu_python |
function mag_atom
begin
print string Magnetization (atom):
print string index string element string s string p string d string tot sep=string
for idx in range length magnetization
begin
print idx + 1 atomic_symbols at idx string { magnetization at idx at string s } string { magnetization at idx at string p } string { m... | def mag_atom():
print("Magnetization (atom):\n")
print(
"index",
"element",
"s",
"p",
"d",
"tot",
sep = "\t"
)
for idx in range(len(outcar.magnetization)):
print(
idx+1,
... | Python | nomic_cornstack_python_v1 |
function list_product_sum_diff A B
begin
set sum_ab = sum A + sum B
set diff_ab = max A + B - min A + B
set product = sum_ab * diff_ab
return product
end function
set A = list 3 5 7 9
set B = list 2 4 6 8 10
set result = call list_product_sum_diff A B
print string The product of the sum and difference of { A } and { B ... | def list_product_sum_diff(A, B):
sum_ab = sum(A) + sum(B)
diff_ab = max(A+B) - min(A+B)
product = sum_ab * diff_ab
return product
A = [3, 5, 7, 9]
B = [2, 4, 6, 8, 10]
result = list_product_sum_diff(A, B)
print(f"The product of the sum and difference of {A} and {B} is {result}.")
| Python | jtatman_500k |
function check_xc self
begin
set p = input_params
comment There is no way to correctly guess the desired
comment set of pseudopotentials without 'pp' being set.
comment Usually, 'pp' will be set by 'xc'.
if string pp not in p or p at string pp is none
begin
if string_params at string gga is none
begin
update p dict str... | def check_xc(self):
p = self.input_params
# There is no way to correctly guess the desired
# set of pseudopotentials without 'pp' being set.
# Usually, 'pp' will be set by 'xc'.
if 'pp' not in p or p['pp'] is None:
if self.string_params['gga'] is None:
... | Python | nomic_cornstack_python_v1 |
comment 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу).
comment Сколько рукопожатий было?
comment Примечание. Решите задачу при помощи построения графа.
import numpy as np
set size = integer input string Сколько человек встретилсь?
function create_graph values size
begin
set... | # 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу).
# Сколько рукопожатий было?
# Примечание. Решите задачу при помощи построения графа.
import numpy as np
size = int(input('Сколько человек встретилсь? '))
def create_graph(values, size):
upper = np.zeros((size, size))... | Python | zaydzuhri_stack_edu_python |
function get_country_keyboard
begin
set markup = call InlineKeyboardMarkup
add markup *[types.InlineKeyboardButton(text=i, callback_data='country:' + i) for i in constant.COUNTRIES]
return markup
end function | def get_country_keyboard():
markup = types.InlineKeyboardMarkup()
markup.add(*[types.InlineKeyboardButton(text=i, callback_data='country:' + i) for i in constant.COUNTRIES])
return markup | Python | nomic_cornstack_python_v1 |
function GetRTMPConfig cpCode accountSwitchKey=none
begin
set getRTMPConfigEndpoint = format string /config-media-live/v1/live/rtmp/configuration/{cpcode} cpcode=cpCode
if accountSwitchKey
begin
set params = dict string accountSwitchKey accountSwitchKey
set rtmpConfigInfo = call getResult getRTMPConfigEndpoint params
e... | def GetRTMPConfig(cpCode,accountSwitchKey=None):
getRTMPConfigEndpoint = '/config-media-live/v1/live/rtmp/configuration/{cpcode}'.format(cpcode=cpCode)
if accountSwitchKey:
params = {'accountSwitchKey':accountSwitchKey}
rtmpConfigInfo = prdHttpCaller.getResult(getRTMPConfigEndpoint,params)
e... | Python | nomic_cornstack_python_v1 |
comment 打开文件,返回一个文件对象
set f = open string C:\Users\pan39\Desktop\工具\python3\6\test.txt
comment 调用文件的 readlines()方法方法读取文件内容
set list = read lines f
comment 关闭文件
close f
print list | f = open("C:\\Users\\pan39\\Desktop\\工具\\python3\\6\\test.txt") #打开文件,返回一个文件对象
list= f.readlines() # 调用文件的 readlines()方法方法读取文件内容
f.close() #关闭文件
print(list)
| Python | zaydzuhri_stack_edu_python |
function test_retrieve_header
begin
set stegs = call Steganographer
set test_message = encode string 12345 string utf-8
set test_data_len = length test_message
set test_bits_used = 1
set test_file_name = string test_retrieve_header.txt
set test_file_name_len = length test_file_name
set test_data = bytes b'\x01' * 1000
... | def test_retrieve_header():
stegs = Steganographer()
test_message = "12345".encode('utf-8')
test_data_len = len(test_message)
test_bits_used = 1
test_file_name = "test_retrieve_header.txt"
test_file_name_len = len(test_file_name)
test_data = bytes(b'\x01' * 1000)
test_header = stegs._ge... | Python | nomic_cornstack_python_v1 |
function get_uri_for_pref self target_pref
begin
set prefs = call get_json USER_PREFERENCE_LIST_URI at string results
for pref in prefs
begin
if pref at string user at string id == id and pref at string key == key
begin
return pref at string url
end
end
call fail
end function | def get_uri_for_pref(self, target_pref):
prefs = self.get_json(USER_PREFERENCE_LIST_URI)["results"]
for pref in prefs:
if (pref["user"]["id"] == target_pref.user.id and pref["key"] == target_pref.key):
return pref["url"]
self.fail() | Python | nomic_cornstack_python_v1 |
function create_random_order_text self text global_time
begin
return call _create_text string RANDOM-text text global_time
end function | def create_random_order_text(self, text, global_time):
return self._create_text(u"RANDOM-text", text, global_time) | Python | nomic_cornstack_python_v1 |
function _input_as_parameters self data
begin
comment The list of values which can be passed on a per-run basis
set allowed_values = list string --uc string --output string --log string --sortbylength string --derep_fulllength string --sizeout string --minseqlength string --strand string --wordlength string --maxreject... | def _input_as_parameters(self, data):
# The list of values which can be passed on a per-run basis
allowed_values = ['--uc', '--output', '--log',
'--sortbylength', '--derep_fulllength', '--sizeout',
'--minseqlength', '--strand', '--wordlength',
... | Python | nomic_cornstack_python_v1 |
function rectangle lon0 lat0 lon1 lat1 coordsys=string equ
begin
if lon0 > lon1
begin
set lon1 = lon1 + 360
end
comment Generate CCW rectangle bounded by great circles
comment nsplit = int(round((lon1 - lon0) / 0.1) + 1)
comment lon = np.linspace(lon0, lon1, nsplit)
comment lon = np.concatenate((lon, lon[::-1]))
commen... | def rectangle(lon0, lat0, lon1, lat1, coordsys='equ'):
if lon0 > lon1:
lon1 = lon1 + 360
# Generate CCW rectangle bounded by great circles
#nsplit = int(round((lon1 - lon0) / 0.1) + 1)
#lon = np.linspace(lon0, lon1, nsplit)
#lon = np.concatenate((lon, lon[::-1]))
#lat = [lat0] * nsplit + [lat1]*nsplit
# Gene... | Python | nomic_cornstack_python_v1 |
import sys
for line in stdin
begin
set line = strip line
set first_four = line at slice : 4 :
set last_four = line at slice - 4 : :
print first_four + last_four
end | import sys
for line in sys.stdin:
line = line.strip()
first_four = line[:4]
last_four = line[-4:]
print(first_four + last_four) | Python | zaydzuhri_stack_edu_python |
from sys import exit
from lxml import etree
import sys
import os
function get_file_path filename
begin
set currentdirpath = get current directory
set file_path = join path get current directory filename
return file_path
end function
set path = call get_file_path string error.xml
with open path string rU as xml_file
beg... | from sys import exit
from lxml import etree
import sys
import os
def get_file_path(filename):
currentdirpath = os.getcwd()
file_path = os.path.join(os.getcwd(), filename)
return file_path
path = get_file_path('error.xml')
with open(path, 'rU') as xml_file:
array = ''
for line in xml_file:
... | Python | zaydzuhri_stack_edu_python |
async function fetch_where cls where *values connection=none order_by=none limit=none
begin
set query = call _query_fetch_where where order_by limit
async_with call MaybeAcquire connection as connection
begin
return await call fetch query *values
end
end function | async def fetch_where(cls, where: str, *values, connection: Optional[Connection] = None,
order_by: Optional[str] = None, limit: Optional[int] = None) -> List[Record]:
query = cls._query_fetch_where(where, order_by, limit)
async with MaybeAcquire(connection) as connection:
... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from bs4 import BeautifulSoup , element
from selenium.webdriver.common.keys import Keys
import time
from PIL import Image
from urllib.request import urlretrieve
set options = call ChromeOptions
call add_argument string user-agent="Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KH... | from selenium import webdriver
from bs4 import BeautifulSoup, element
from selenium.webdriver.common.keys import Keys
import time
from PIL import Image
from urllib.request import urlretrieve
options = webdriver.ChromeOptions()
options.add_argument('user-agent="Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KH... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment coding=utf-8
string reference: http://dola.xinfan.org/?p=282
import os
import sys
import zipfile
import chardet
function detect_enc string
begin
set enc = call detect string at string encoding
if lower enc == string gb2312
begin
set enc = string gbk
end
return enc
end function | #!/usr/bin/env python2
# coding=utf-8
""" reference: http://dola.xinfan.org/?p=282 """
import os
import sys
import zipfile
import chardet
def detect_enc(string):
enc = chardet.detect(string)['encoding']
if enc.lower() == 'gb2312':
enc = 'gbk'
return enc
| Python | zaydzuhri_stack_edu_python |
comment main.py
string Assembler - one of the parts of MixMachine, which assemles mix source code ("*.mix") to Mix Assembled code ("*.ma") Main module of assembler. Read two file names (gets by command line arguments): 1) input file (required) 2) output file (default "out.ma")
import sys
from parse_line import parse_li... | # main.py
"""
Assembler - one of the parts of MixMachine, which assemles mix source code
("*.mix") to Mix Assembled code ("*.ma")
Main module of assembler.
Read two file names (gets by command line arguments):
1) input file (required)
2) output file (default "out.ma")
"""
import sys
from parse_line import parse_line... | Python | zaydzuhri_stack_edu_python |
from math import ceil
set n = integer input
set d = 0
set a = 0
set b = 0
set ans = list
for i in range n
begin
set tuple l r = map int split input
if i == 0
begin
set a = r
set b = l
append ans d
continue
end
set p = max l - a b - r
if p > 2 * d
begin
set d = ceil p / 2
end
set a = min a r
set b = max b l
append ans ... | from math import ceil
n = int(input())
d = 0
a = 0
b = 0
ans = []
for i in range(n):
l, r = map(int, input().split())
if i == 0:
a = r
b = l
ans.append(d)
continue
p = max(l-a, b-r)
if p > 2*d:
d = ceil(p/2)
a = min(a, r)
b = max(b, l)
ans.append(d)
pr... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.