code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function create_file_node self diff_list fn
begin
set p = call insertAsLastChild
set h = string diff: + strip fn
set b = join string diff_list
return p
end function | def create_file_node(self, diff_list: list[str], fn: str) -> Position:
p = self.root.insertAsLastChild()
p.h = 'diff: ' + fn.strip()
p.b = ''.join(diff_list)
return p | Python | nomic_cornstack_python_v1 |
function find_stkvar self *args
begin
return call lvars_t_find_stkvar self *args
end function | def find_stkvar(self, *args):
return _ida_hexrays.lvars_t_find_stkvar(self, *args) | Python | nomic_cornstack_python_v1 |
function patch_f90_compiler f90_compiler
begin
string Patch up ``f90_compiler.library_dirs``. Updates flags in ``gfortran`` and ignores other compilers. The only modification is the removal of ``-fPIC`` since it is not used on Windows and the build flags turn warnings into errors. Args: f90_compiler (numpy.distutils.fc... | def patch_f90_compiler(f90_compiler):
"""Patch up ``f90_compiler.library_dirs``.
Updates flags in ``gfortran`` and ignores other compilers. The only
modification is the removal of ``-fPIC`` since it is not used on Windows
and the build flags turn warnings into errors.
Args:
f90_compiler (n... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Tue Jan 22 16:48:56 2019 @author: snnch
function iteration f fp x eps n
begin
for i in range 1 n + 1
begin
set y1 = x
set y2 = y1 - f dist y1 / call fp y1
set y3 = y2 - f dist y2 / call fp y2
set x = y1 - y2 - y1 ^ 2 / y3 - 2 * y2 + y1
set fx = absolute f dist x
print str... | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 16:48:56 2019
@author: snnch
"""
def iteration(f, fp, x, eps, n):
for i in range (1,n+1):
y1 = x
y2 = y1-f(y1)/fp(y1)
y3 = y2-f(y2)/fp(y2)
x = y1 - (y2-y1)**2/(y3-2*y2+y1)
fx = abs(f(x))
print('%d it... | Python | zaydzuhri_stack_edu_python |
comment https://www.acmicpc.net/problem/1463
set n = integer input
comment 0번째가 아닌 첫번째부터 최소 계산수를 저장
set l = list 0 0
comment l[4] = (1) l[3] + 1 or (2) l[2] + 1 중 최솟값
comment l[5] = l[4] + 1 -> 5는 2와 3 모두 나누어지지 않기 때문
comment l[6] = (1) l[5] + 1, (2) l[3] + 1 or (3) l[2] + 1 중 최솟값
for i in range 2 n + 1
begin
append l l... | # https://www.acmicpc.net/problem/1463
n = int(input())
l = [0, 0] # 0번째가 아닌 첫번째부터 최소 계산수를 저장
# l[4] = (1) l[3] + 1 or (2) l[2] + 1 중 최솟값
# l[5] = l[4] + 1 -> 5는 2와 3 모두 나누어지지 않기 때문
# l[6] = (1) l[5] + 1, (2) l[3] + 1 or (3) l[2] + 1 중 최솟값
for i in range(2, n + 1):
l.append(l[i - 1] + 1)
if i % 2 == 0:
... | Python | zaydzuhri_stack_edu_python |
string Autor: Pierre Vieira Data da submissão: 22/02/2020 00:20:08
set tuple a b = map int split input
print format string {:.2f} a / b | """
Autor: Pierre Vieira
Data da submissão: 22/02/2020 00:20:08
"""
a, b = map(int, input().split())
print('{:.2f}'.format(a / b))
| Python | zaydzuhri_stack_edu_python |
function toCamelCase s
begin
set s = split s string
return join string generator expression title x for x in s
end function
set s = string this is some random text
print call toCamelCase s | def toCamelCase(s):
s = s.split(' ')
return ''.join(x.title() for x in s)
s = "this is some random text"
print(toCamelCase(s)) | Python | jtatman_500k |
import asyncio
import aiohttp
import os
import csv
from tqdm import tqdm
set code_dirname = directory name path __file__
set sem = semaphore 10
async function http_get session url
begin
async_with sem
begin
print string getting { url }
async_with get session url as resp
begin
set text = await call text encoding=string ... | import asyncio
import aiohttp
import os
import csv
from tqdm import tqdm
code_dirname = os.path.dirname(__file__)
sem = asyncio.Semaphore(10)
async def http_get(session, url):
async with sem:
print(f"getting {url}")
async with session.get(url) as resp:
text = await resp.text(encoding=... | Python | zaydzuhri_stack_edu_python |
function proxy_options_namespaced_node_0 self name path **kwargs
begin
set kwargs at string _return_http_data_only = true
if get kwargs string callback
begin
return call proxy_options_namespaced_node_0_with_http_info name path keyword kwargs
end
else
begin
set data = call proxy_options_namespaced_node_0_with_http_info ... | def proxy_options_namespaced_node_0(self, name, path, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.proxy_options_namespaced_node_0_with_http_info(name, path, **kwargs)
else:
(data) = self.proxy_options_namespaced_node_0_with_ht... | Python | nomic_cornstack_python_v1 |
class Node
begin
function __init__ self data
begin
set data = data
set prev = none
set next = none
end function
end class
function retrieve_delete_insert_nth_mth head n m
begin
if head is none
begin
return head
end
set current = head
set count = 1
comment Find the nth node
while current is not none and count < n
begin
... | class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
def retrieve_delete_insert_nth_mth(head, n, m):
if head is None:
return head
current = head
count = 1
# Find the nth node
while current is not None and count < n:
c... | Python | jtatman_500k |
function outputs self
begin
return get pulumi self string outputs
end function | def outputs(self) -> Optional[Mapping[str, Any]]:
return pulumi.get(self, "outputs") | Python | nomic_cornstack_python_v1 |
function last_updated_by_id self
begin
return __last_updated_by_id
end function | def last_updated_by_id(self) -> str:
return self.__last_updated_by_id | Python | nomic_cornstack_python_v1 |
function from_json data
begin
return call ModelData get data string name get data string type get data string value get data string units
end function | def from_json(data: Dict[str, Any]) -> 'ModelData':
return ModelData(data.get("name"),
data.get("type"),
data.get("value"),
data.get("units")) | Python | nomic_cornstack_python_v1 |
comment -*- coding: UTF-8 -*-
string @version: python2.7 @author: ‘Na‘ @software: PyCharm @file: html_db.py @time: 2017/10/22 23:07
import pymongo
class HtmlDb extends object
begin
function __init__ self
begin
set datas = list
set connection = call MongoClient host=string localhost port=27017
set db = test
end functio... | # -*- coding: UTF-8 -*-
"""
@version: python2.7
@author: ‘Na‘
@software: PyCharm
@file: html_db.py
@time: 2017/10/22 23:07
"""
import pymongo
class HtmlDb(object):
def __init__(self):
self.datas = []
self.connection = pymongo.MongoClient(host="localhost", port=27017)
self.db = self.conne... | Python | zaydzuhri_stack_edu_python |
function remove_character string character
begin
set modified_string = replace string character string
return modified_string
end function
comment Test the function
set mystring = string Hello, World!
set character = string o
set modified_string = call remove_character mystring character
print modified_string
comment O... | def remove_character(string, character):
modified_string = string.replace(character, "")
return modified_string
# Test the function
mystring = "Hello, World!"
character = "o"
modified_string = remove_character(mystring, character)
print(modified_string)
# Output: "Hell, Wrld!"
| Python | jtatman_500k |
import torch
import torch.nn as nn
import torch.nn.functional as F
from config import gamma , sequence_length , device
class QNet extends Module
begin
function __init__ self num_inputs num_outputs
begin
call __init__
comment The inputs are two integers giving the dimensions of the inputs and outputs respectively.
comme... | import torch
import torch.nn as nn
import torch.nn.functional as F
from config import gamma, sequence_length, device
class QNet(nn.Module):
def __init__(self, num_inputs, num_outputs):
super(QNet, self).__init__()
# The inputs are two integers giving the dimensions of the inputs and outputs respect... | Python | zaydzuhri_stack_edu_python |
string import pylab from numpy import * x = arange(0, 8*pi, 0.01) pylab.plot(x, sin(x)) pylab.plot(x, cos(x/2)) pylab.xlabel('x') pylab.title('Oscillation and damped oscillation') pylab.savefig('pylabplot.png') import os curdir = os.getcwd() print 'Plot saved in : ', curdir from math import cos , fabs , pi def g(x): n ... | '''import pylab
from numpy import *
x = arange(0, 8*pi, 0.01)
pylab.plot(x, sin(x))
pylab.plot(x, cos(x/2))
pylab.xlabel('x')
pylab.title('Oscillation and damped oscillation')
pylab.savefig('pylabplot.png')
import os
curdir = os.getcwd()
print 'Plot saved in : ', curdir
from math import cos , fabs , pi
def ... | Python | zaydzuhri_stack_edu_python |
comment find minimum and maximum number in a list without using library function
set a = list 6 4 7 2 1
function min a
begin
set mi = a at 0
for q in a at slice 1 : :
begin
if q < mi
begin
set mi = q
end
end
end function | #find minimum and maximum number in a list without using library function
a=[6,4,7,2,1]
def min(a):
mi=a[0]
for q in a[1:] :
if q < mi :
mi=q | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
set user = call create_user string testuser string testemail@x.com string testpass
save
set response = post login_url dict string username string testuser ; string password string testpass
assert equal 200 status_code
end function | def setUp(self):
self.user = User.objects.create_user('testuser', 'testemail@x.com',
'testpass')
self.user.save()
response = self.client.post(login_url, {
'username': 'testuser',
'password': 'testpass'
})
self.... | Python | nomic_cornstack_python_v1 |
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
from sklearn.preprocessing import StandardScaler
string 归一化
function scaler_demo
begin
comment [[100, 15, 5], [200, 13, 7], [150, 10, 3]]
set data = read csv string D:/DL/scaler_data.txt
set scaler = min max scaler feature_range=tuple 2 3
print data
set... | from sklearn.preprocessing import MinMaxScaler
import pandas as pd
from sklearn.preprocessing import StandardScaler
"""归一化"""
def scaler_demo():
data = pd.read_csv('D:/DL/scaler_data.txt') #[[100, 15, 5], [200, 13, 7], [150, 10, 3]]
scaler = MinMaxScaler(feature_range=(2, 3))
print(data)
data_final = s... | Python | zaydzuhri_stack_edu_python |
string Домашнее задание №1 Функции и структуры данных
function power_numbers *numbers
begin
string функция, которая принимает N целых чисел, и возвращает список квадратов этих чисел
comment Список квадратов целых чисел
set numbers_squared = list comprehension number * number for number in numbers
return numbers_squared... | """
Домашнее задание №1
Функции и структуры данных
"""
def power_numbers(*numbers):
"""
функция, которая принимает N целых чисел,
и возвращает список квадратов этих чисел
"""
# Список квадратов целых чисел
numbers_squared = [number * number for number in numbers]
return numbers_squared
... | Python | zaydzuhri_stack_edu_python |
function get_uci_datasets name split_seed=0 test_fraction=0.1 train_frac=1.0 combine_val_train=false
begin
comment load full dataset
set load_funs = dict string naval _load_naval ; string protein _load_protein ; string crime _load_crime ; string energy _load_app_energy
print format string Loading dataset {}.... name
if... | def get_uci_datasets(
name, split_seed=0, test_fraction=0.10, train_frac=1.0, combine_val_train=False
):
# load full dataset
load_funs = {
"naval": _load_naval,
"protein": _load_protein,
"crime": _load_crime,
"energy": _load_app_energy,
}
print("Loading dataset {}....... | Python | nomic_cornstack_python_v1 |
function transform_batch self raw_images
begin
set transformed_batch = list
for image in enumerate raw_images
begin
set transformed_images = call transform_image image
set transformed_batch = transformed_batch + transformed_images
end
set transformed_batch = stack transformed_batch
return transformed_batch
end functio... | def transform_batch(self, raw_images):
transformed_batch = []
for image in enumerate(raw_images):
transformed_images = self.transform_image(image)
transformed_batch += transformed_images
transformed_batch = torch.stack(transformed_batch)
return transformed_batc... | Python | nomic_cornstack_python_v1 |
comment https://www.hackerrank.com/challenges/gem-stones/problem
comment !/bin/python3
import math
import os
import random
import re
import sys
from functools import reduce
comment Complete the gemstones function below.
function gemstones arr
begin
comment count = 0;
comment for i in set(arr[0]):
comment flag = 1
comme... | #https://www.hackerrank.com/challenges/gem-stones/problem
#!/bin/python3
import math
import os
import random
import re
import sys
from functools import reduce
# Complete the gemstones function below.
def gemstones(arr):
# count = 0;
# for i in set(arr[0]):
# flag = 1
# for j in range(1,len(ar... | Python | zaydzuhri_stack_edu_python |
function __init__ self definition
begin
set definition = definition
set current_value = default_value
set binding = none
end function | def __init__(self, definition):
self.definition = definition
self.current_value = definition.default_value
self.binding = None | Python | nomic_cornstack_python_v1 |
function _get_last_child_with_lineno node
begin
set ignored_fields = set literal string ctx string decorator_list string names string returns
set fields = _fields
comment The fields of ast.Call are in the wrong order.
if is instance node Call
begin
set fields = tuple string func string args string starargs string keywo... | def _get_last_child_with_lineno(node):
ignored_fields = {"ctx", "decorator_list", "names", "returns"}
fields = node._fields
# The fields of ast.Call are in the wrong order.
if isinstance(node, ast.Call):
fields = ("func", "args", "starargs", "keywords", "kwargs")
for name in reversed(fields)... | Python | nomic_cornstack_python_v1 |
function read sock
begin
set raw_message = b''
while true
begin
try
begin
set chunk = call recv 4096
end
except error as err
begin
print string Socket error: string err
break
end
if not chunk
begin
break
end
set raw_message = raw_message + chunk
comment dirty, refactor
if length chunk < 4096
begin
break
end
end
return ... | def read(sock):
raw_message = b''
while True:
try:
chunk = sock.recv(4096)
except socket.error as err:
print('Socket error: ', str(err))
break
if not chunk:
break
raw_message += chunk
if len(chunk) < 4096: # dirty, refactor... | Python | nomic_cornstack_python_v1 |
function _add_lags self X y=none extrapolate=1 update_features_df=false
begin
comment Add lag target to the features if required
comment This will create an additional feature for each sample i.e. the previous value of y
if y is not none and lag_target
begin
set X at string previous_y = call shift 1
if update_features_... | def _add_lags(self, X, y=None, extrapolate=1, update_features_df=False):
# Add lag target to the features if required
# This will create an additional feature for each sample i.e. the previous value of y
if y is not None and self.model.lag_target:
X["previous_y"] = y.shift(1)
... | Python | nomic_cornstack_python_v1 |
function parse_rttm_for_ms_targets self sample
begin
set rttm_lines = read lines open rttm_file
set uniq_id = call get_uniq_id_with_range sample
set rttm_timestamps = call extract_seg_info_from_rttm uniq_id rttm_lines
set fr_level_target = call assign_frame_level_spk_vector rttm_timestamps round_digits frame_per_sec ta... | def parse_rttm_for_ms_targets(self, sample):
rttm_lines = open(sample.rttm_file).readlines()
uniq_id = self.get_uniq_id_with_range(sample)
rttm_timestamps = extract_seg_info_from_rttm(uniq_id, rttm_lines)
fr_level_target = assign_frame_level_spk_vector(
rttm_timestamps, self.... | Python | nomic_cornstack_python_v1 |
function verif_win joueur number_of_ship
begin
if number_of_ship == 3
begin
if etat_bat == string inactif and etat_bat == string inactif and etat_bat == string inactif
begin
return true
end
end
if number_of_ship == 1
begin
if etat_bat == string inactif
begin
return true
end
end
else
if number_of_ship == 5
begin
if etat... | def verif_win(joueur: object, number_of_ship: int):
if number_of_ship == 3:
if joueur.porte_avion.etat_bat == "inactif" and joueur.torpilleur.etat_bat == "inactif" and joueur.croiseur.etat_bat == "inactif":
return True
if number_of_ship == 1:
if joueur.porte_avion.etat_bat == "inacti... | Python | nomic_cornstack_python_v1 |
function getAxes self *args
begin
return call IEncoders_getAxes self *args
end function | def getAxes(self, *args):
return _yarp.IEncoders_getAxes(self, *args) | Python | nomic_cornstack_python_v1 |
class Snek
begin
function __init__ self Color InnerColor Cords Direction
begin
set Color = Color
set InnerColor = InnerColor
set Cords = Cords
set Direction = Direction
set Ready = false
end function
function MoveSnek self
begin
set HEAD = 0
if Direction == string Left
begin
set NewHead = dict string x Cords at HEAD at... | class Snek:
def __init__(self,Color,InnerColor,Cords,Direction):
self.Color = Color
self.InnerColor = InnerColor
self.Cords = Cords
self.Direction = Direction
self.Ready = False
def MoveSnek(self):
HEAD = 0
if self.Direction == "Left":
NewHead... | Python | zaydzuhri_stack_edu_python |
import media , fresh_tomatoes
set hobbs_and_shaw = call Movie string Fast & Furious Presents: Hobbs & Shaw string Ever since hulking lawman Hobbs (Johnson), a loyal agent of America's Diplomatic Security Service, and lawless outcast Shaw (Statham), a former British military elite operative, first faced off in 2015’s Fu... | import media, fresh_tomatoes
hobbs_and_shaw = media.Movie("Fast & Furious Presents: Hobbs & Shaw",
"Ever since hulking lawman Hobbs (Johnson), a loyal agent of America's Diplomatic Security Service, and lawless outcast Shaw (Statham), a former British military elite operative, first faced off in 2015’s Furious 7, ... | Python | zaydzuhri_stack_edu_python |
function catl_model_pred_file_final_path self check_exist=true ext=string hdf5
begin
comment Catalogue output directory
set catl_model_final_path = call catl_model_pred_final_path check_exist=false create_dir=true
comment Catalogue Prefix
set catl_prefix_str = format string {0}_data_model_final_out.{1} sample_Mr ext
co... | def catl_model_pred_file_final_path(self, check_exist=True, ext='hdf5'):
# Catalogue output directory
catl_model_final_path = self.catl_model_pred_final_path(
check_exist=False, create_dir=True)
# Catalogue Prefix
catl_prefix_str = '{0}_data_model_final_out.{1}'.format(
... | Python | nomic_cornstack_python_v1 |
comment import modules
import pandas as pd
import matplotlib.pyplot as plt
comment read file and create dataframe
set df = read csv string pageviews-20160801-000000 sep=string header=none
comment drop missing values and rename columns
drop missing df inplace=true
rename columns=dict 0 string Language ; 1 string Articl... | ##import modules
import pandas as pd
import matplotlib.pyplot as plt
##read file and create dataframe
df = pd.read_csv("pageviews-20160801-000000", sep=" ", header=None)
##drop missing values and rename columns
df.dropna(inplace=True)
df.rename(columns={0: "Language", 1: "Article", 2: "Views", 3: "Size"}, inplace=Tru... | Python | zaydzuhri_stack_edu_python |
function activations_hook self input heatmaps pafs
begin
set batch_ix = _step at 1
if batch_ix % 40 == 0
begin
comment The output of this layer is of shape [batch_size, 16, 32, 32]
comment Take a slice that represents one feature map
print string hook!!!
print data at tuple 0 0
log _step backend_output=data at tuple 0 ... | def activations_hook(self, input, heatmaps, pafs):
batch_ix = self._step[1]
if batch_ix % 40 == 0:
# The output of this layer is of shape [batch_size, 16, 32, 32]
# Take a slice that represents one feature map
print("hook!!!")
print(heatmaps[-1].data... | Python | nomic_cornstack_python_v1 |
comment В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
import random
set SIZE = 10
set a = list comprehension random integer 0 50 for _ in range SIZE
set a_min = 0
set a_max = 0
for i in range SIZE
begin
if a at i < a at a_min
begin
set a_min = i
end
if a at i > a at a_max
begin
s... | # В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
import random
SIZE = 10
a = [random.randint(0, 50) for _ in range(SIZE)]
a_min = 0
a_max = 0
for i in range(SIZE):
if a[i] < a[a_min]:
a_min = i
if a[i] > a[a_max]:
a_max = i
print(a)
spam = a[a_min]
a[a_... | Python | zaydzuhri_stack_edu_python |
function _ssh_master_cmd addr user command local_key=none
begin
set ssh_call = list string ssh string -qNfL%d:127.0.0.1:12042 % call find_port addr user string -o string ControlPath=~/.ssh/unixpipe_%%r@%%h_%d % call find_port addr user string -O command string %s@%s % tuple user addr
if local_key
begin
insert ssh_call ... | def _ssh_master_cmd(addr, user, command, local_key=None):
ssh_call = ['ssh', '-qNfL%d:127.0.0.1:12042' % find_port(addr, user),
'-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % find_port(addr, user),
'-O', command,
'%s@%s' % (user, addr,)
]
if local_key:
ssh_call.insert(1, l... | Python | nomic_cornstack_python_v1 |
function date_to_json date
begin
return string format time date string %Y-%m-%dT%H:%M:%SZ
end function | def date_to_json(date):
return date.strftime('%Y-%m-%dT%H:%M:%SZ') | Python | nomic_cornstack_python_v1 |
function reverse_string s
begin
comment Convert the string to a list of characters
set chars = list s
comment Get the length of the string
set n = length s
comment Swap characters from the beginning and end of the list until reaching the middle
for i in range n // 2
begin
set tuple chars at i chars at n - i - 1 = tuple... | def reverse_string(s):
# Convert the string to a list of characters
chars = list(s)
# Get the length of the string
n = len(s)
# Swap characters from the beginning and end of the list until reaching the middle
for i in range(n // 2):
chars[i], chars[n - i - 1] = chars[n - i - 1]... | Python | jtatman_500k |
function draw_next_piece self
begin
set drop_col = call mouse_x_to_col
call circle surf if expression turn == string R then tuple 255 0 0 else tuple 0 0 255 tuple drop_col * slot_w + pos at 0 + 20 pos at 1 - 30 slot_w // 2 - 7
end function | def draw_next_piece(self):
self.drop_col = self.mouse_x_to_col()
pygame.draw.circle(
self.surf, (255, 0, 0) if self.turn == 'R' else (0, 0, 255),
(
self.drop_col * self.grid.slot_w + self.grid.pos[0] + 20,
self.grid.pos[1] - 30
),
... | Python | nomic_cornstack_python_v1 |
import numpy
from StringIO import StringIO
set test_cases = integer call raw_input
for i in range 0 test_cases
begin
set foundColumn = list
for k in range 0 2
begin
set col = integer call raw_input
set matrix = string
for j in range 0 4
begin
set matrix = matrix + call raw_input + string
end
set mat = call loadtxt c... | import numpy
from StringIO import StringIO
test_cases = int(raw_input())
for i in range(0,test_cases):
foundColumn = []
for k in range(0,2):
col = int(raw_input())
matrix = ''
for j in range(0,4):
matrix+=raw_input()+'\n'
mat = numpy.loadtxt(StringIO(matrix),dtype=... | Python | zaydzuhri_stack_edu_python |
function exported_to_dict filename keep_fields
begin
set result_dict = dict
set keep_set : Set = set keep_fields
assert string Function in keep_set
with open filename string r encoding=string latin-1 as f
begin
set num = 0
for line in f
begin
set num = num + 1
set line = strip line string \
set fields = split line str... | def exported_to_dict(filename: FileName, keep_fields: List) -> Dict:
result_dict = {}
keep_set : Set = set(keep_fields)
assert("Function" in keep_set)
with open(filename, 'r', encoding="latin-1") as f:
num = 0
for line in f:
num = num + 1
line = line.strip("\\\n")... | Python | nomic_cornstack_python_v1 |
comment This class populates hits data and exports final xG model
import pandas as pd
import carball
from concurrent.futures import ProcessPoolExecutor
import pathlib
import glob
import os
import pickle
from sklearn.preprocessing import StandardScaler
from xgboost import XGBClassifier
import json
from util import downl... | # This class populates hits data and exports final xG model
import pandas as pd
import carball
from concurrent.futures import ProcessPoolExecutor
import pathlib
import glob
import os
import pickle
from sklearn.preprocessing import StandardScaler
from xgboost import XGBClassifier
import json
from util import download_ga... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
from board import *
function checkmate board color
begin
if color == string white
begin
set check_fig = white_figures
set ref_fig = black_figures
set check_col = white
set ref_col = black
set ref_king = black_king
end
else
begin
set check_fig = black_figures
set ref_fig = white_figures
set... | #!/usr/bin/env python3
from board import *
def checkmate(board, color):
if color == 'white':
check_fig = board.white_figures
ref_fig = board.black_figures
check_col = Color.white
ref_col = Color.black
ref_king = board.black_king
else:
check_fig = board.blac... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import sys
import getopt
import string
from optparse import OptionParser
function splitByDepth inFile numReads
begin
if inFile == string stdin
begin
set data = stdin
end
else
begin
set data = open inFile string r
end
comment initiate line1 and line2 to BED objects
set line1 = strip read lin... | #!/usr/bin/env python
import sys
import getopt
import string
from optparse import OptionParser
def splitByDepth(inFile,numReads):
if inFile == "stdin":
data = sys.stdin
else:
data = open(inFile, 'r')
# initiate line1 and line2 to BED objects
line1 = data.readline().strip()
if not line1:
return
bed1 = BEDG... | Python | zaydzuhri_stack_edu_python |
function update_state_user self user_dacts
begin
comment re-filtering the dacts
set user_dacts_copy = deep copy user_dacts
set user_dacts = list
for copy_dact in user_dacts_copy
begin
if intent not in list comprehension intent for d in user_dacts
begin
append user_dacts copy_dact
end
else
begin
for user_dact in user_d... | def update_state_user(self, user_dacts):
# re-filtering the dacts
user_dacts_copy = deepcopy(user_dacts)
user_dacts = []
for copy_dact in user_dacts_copy:
if copy_dact.intent not in [d.intent for d in user_dacts]:
user_dacts.append(copy_dact)
else:... | Python | nomic_cornstack_python_v1 |
function randomly_downsample_data array num_downsample seed=none
begin
set num_downsample = integer num_downsample
set input_array_length = call custom_len array
if num_downsample > input_array_length
begin
raise call SyntaxError string Length of the desired downsampling = %i, which exceeds input array length = %i % tu... | def randomly_downsample_data(array, num_downsample, seed=None):
num_downsample = int(num_downsample)
input_array_length = custom_len(array)
if num_downsample > input_array_length:
raise SyntaxError("Length of the desired downsampling = %i, "
"which exceeds input array length = %i " % (n... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import sys
set previousColumn = - 1
set matrixDictionary = dict
set maxBufferSize = 500
set numberOfOverFlows = 0
set intermediateMatrixRow = string
function PrintTemporaryMatrixStrings rowIndex
begin
print format string {0} {1} rowIndex intermediateMatrixRow
end function
for line in stdi... | #!/usr/bin/env python
import sys
previousColumn = -1
matrixDictionary = {}
maxBufferSize = 500
numberOfOverFlows = 0
intermediateMatrixRow = ""
def PrintTemporaryMatrixStrings(rowIndex):
print("{0}\t{1}".format(rowIndex, intermediateMatrixRow))
for line in sys.stdin:
columnNumber, row, value = line.stri... | Python | zaydzuhri_stack_edu_python |
comment bincon_loop.py | iml cwc
comment convert a base 10 number to binary
comment use 191 base 10 equal to 1011 1111 base
comment q(quotient) d(divisor) r(remainder) n(integer input)
set n = integer input string Input an integer less than 256:
set n_og = n
set d = 128
comment create a stirng called binString
set binS... | # bincon_loop.py | iml cwc
# convert a base 10 number to binary
# use 191 base 10 equal to 1011 1111 base
# q(quotient) d(divisor) r(remainder) n(integer input)
n = int(input("Input an integer less than 256: "))
n_og = n
d = 128
binString = "" #create a stirng called binString
for i in range(0, 8):
q =... | Python | zaydzuhri_stack_edu_python |
function mosaic_flat_auto aperture_set_lst max_count name_lst
begin
comment find the brightness order of all aperture sets
string name_satcount_lst = {} for name, aperset in aperture_set_lst.items(): sat_count = 0 for aper, aper_loc in aperset.items(): if aper_loc.nsat > 0: sat_count += 1 name_satcount_lst[name] = sat_... | def mosaic_flat_auto(aperture_set_lst, max_count, name_lst):
# find the brightness order of all aperture sets
'''
name_satcount_lst = {}
for name, aperset in aperture_set_lst.items():
sat_count = 0
for aper, aper_loc in aperset.items():
if aper_loc.nsat > 0:
... | Python | nomic_cornstack_python_v1 |
function register_udp_listener self callback connection_class local_port=none local_host=none
begin
comment If the connection class is not an AbstractListenable, this is an
comment error
if not is subclass connection_class AbstractListenable
begin
raise call SpinnmanInvalidParameterException string connection_class con... | def register_udp_listener(self, callback, connection_class,
local_port=None, local_host=None):
# If the connection class is not an AbstractListenable, this is an
# error
if not issubclass(connection_class, AbstractListenable):
raise exceptions.SpinnmanI... | Python | nomic_cornstack_python_v1 |
async function expire_event self event_id
begin
comment Try to retrieve the event's content from the database or the event cache.
set event = await call get_event event_id
function delete_expired_event_txn txn
begin
comment Delete the expiry timestamp associated with this event from the database.
call _delete_event_exp... | async def expire_event(self, event_id: str) -> None:
# Try to retrieve the event's content from the database or the event cache.
event = await self.get_event(event_id)
def delete_expired_event_txn(txn: LoggingTransaction) -> None:
# Delete the expiry timestamp associated with this e... | Python | nomic_cornstack_python_v1 |
comment LED blink Demo 10
comment Date: 2020-04-18
from machine import Pin
from micropython import const
import utime as time
comment 1=OFF, 0=ON
set LED_OFF = 1
comment use GPIO5 for LED output
set LED_GPIO = 5
set led = call Pin LED_GPIO OUT
async function next_state led delay
begin
set state = 0
try
begin
while true... | ##############################################################
# LED blink Demo 10
# Date: 2020-04-18
#############################################################
from machine import Pin
from micropython import const
import utime as time
LED_OFF = 1 # 1=OFF, 0=ON
LED_GPIO = 5 # use GPIO5 for LED output
... | Python | zaydzuhri_stack_edu_python |
function _child_instantiate_optimiser cls func_caller worker_manager options=none reporter=none
begin
if options is none
begin
set opt_args = call get_all_gp_bandit_args euclidean_gp_args
set options = call load_options opt_args
end
set use_additive_gp = true
return call EuclideanGPBandit func_caller worker_manager is_... | def _child_instantiate_optimiser(cls, func_caller, worker_manager,
options=None, reporter=None):
if options is None:
opt_args = gp_bandit.get_all_gp_bandit_args(euclidean_gp_args)
options = load_options(opt_args)
options.use_additive_gp = True
return gp_bandit.... | Python | nomic_cornstack_python_v1 |
class StackofPlates
begin
function __init__ self capacity
begin
set stacks = list
set capacity = capacity
end function
function push self item
begin
if stacks == list
begin
append stacks list item
end
else
if length stacks at - 1 >= capacity
begin
append stacks list item
end
else
begin
append stacks at - 1 item
end
e... | class StackofPlates:
def __init__(self, capacity):
self.stacks = []
self.capacity = capacity
def push(self, item):
if self.stacks == []:
stacks.append([item])
else:
if len(self.stacks[-1]) >= self.capacity:
self.stacks.append([item])
... | Python | zaydzuhri_stack_edu_python |
function test_get_pathless_raw_file_name_ascii self
begin
set this_pathless_file_name = call _get_pathless_raw_file_name unix_time_sec=VALID_TIME_UNIX_SEC file_extension=ASCII_FILE_EXTENSION
assert true this_pathless_file_name == PATHLESS_ASCII_FILE_NAME
end function | def test_get_pathless_raw_file_name_ascii(self):
this_pathless_file_name = probsevere_io._get_pathless_raw_file_name(
unix_time_sec=VALID_TIME_UNIX_SEC,
file_extension=probsevere_io.ASCII_FILE_EXTENSION)
self.assertTrue(this_pathless_file_name == PATHLESS_ASCII_FILE_NAME) | Python | nomic_cornstack_python_v1 |
function magnitude self matrix
begin
set tuple h w = shape
set dft_magnitude = array list comprehension list comprehension sum list comprehension matrix at i at j * cos 2 * pi / h * u * i + v * j - square root - 1 * sin 2 * pi / h * u * i + v * j for i in range h for j in range w for v in range w for u in range h
retur... | def magnitude(self, matrix):
(h, w) = matrix.shape
dft_magnitude = np.array([[sum([(matrix[i][j] * (math.cos(((2*math.pi)/h) * (u*i + v*j)) - cmath.sqrt(-1)*cmath.sin(((2*math.pi)/h) * (u*i + v*j)))) for i in range(h) for j in range(w)]) for v in range(w)] for u in range(h)])
return dft_magnit... | Python | nomic_cornstack_python_v1 |
function bioinfo_deliveries
begin
pass
end function | def bioinfo_deliveries():
pass | Python | nomic_cornstack_python_v1 |
from django.shortcuts import render , get_object_or_404
from django.http import HttpResponse , HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from django.template import loader
from models import Dish
class IndexView extends ListView
begin
set template_name = string polls/index.ht... | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from django.template import loader
from .models import Dish
class IndexView(generic.ListView):
template_name = 'polls/index.html'
co... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function maxProduct self nums
begin
string :type nums: List[int] :rtype: int
set j = 0
append nums 0
set flag = 0
set maxv = - decimal string inf
for i in range length nums
begin
if flag == 0 and nums at i != 0
begin
set flag = 1
set j = i
end
else
if flag == 1 and nums at i == 0
beg... | class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
j=0
nums.append(0)
flag=0
maxv=-float("inf")
for i in range(len(nums)):
if flag==0 and nums[i]!=0:
flag=1
... | Python | zaydzuhri_stack_edu_python |
function log_meta_info self
begin
set meta_info_df = rename columns=dict string index string col_name
set meta_info_df at string ml_job_id = ml_job_id
set meta_info_df at string operator_id = operator_id
set columns = list comprehension if expression string % not in x then x else replace x string % string for x in colu... | def log_meta_info(self):
meta_info_df = self.dataset.describe().transpose().add_prefix('df_').reset_index().rename(columns={'index':'col_name'})
meta_info_df['ml_job_id'] = self.ml_job_id
meta_info_df['operator_id'] = self.operator_id
meta_info_df.columns = [x if '%' not in x else x.repl... | Python | nomic_cornstack_python_v1 |
function post self request *args **kwargs
begin
try
begin
set qbo_credentials = get objects workspace_id=kwargs at string workspace_id
set qbo_connector = call QBOConnector qbo_credentials workspace_id=kwargs at string workspace_id
set employees = call sync_employees
return call Response data=data status=HTTP_200_OK
en... | def post(self, request, *args, **kwargs):
try:
qbo_credentials = QBOCredential.objects.get(workspace_id=kwargs['workspace_id'])
qbo_connector = QBOConnector(qbo_credentials, workspace_id=kwargs['workspace_id'])
employees = qbo_connector.sync_employees()
return ... | Python | nomic_cornstack_python_v1 |
function load_data
begin
set prefix = string mnist_data/
set train_data = load np prefix + string mnist_train_images.npy
set train_labels = load np prefix + string mnist_train_labels.npy
set val_data = load np prefix + string mnist_validation_images.npy
set val_labels = load np prefix + string mnist_validation_labels.n... | def load_data():
prefix = 'mnist_data/'
train_data = np.load(prefix + 'mnist_train_images.npy')
train_labels = np.load(prefix + 'mnist_train_labels.npy')
val_data = np.load(prefix + 'mnist_validation_images.npy')
val_labels = np.load(prefix + 'mnist_validation_labels.npy')
test_data = np.load(pr... | Python | nomic_cornstack_python_v1 |
function find_stars self data
begin
set star_cutouts = call _find_stars data kernel threshold_eff exclude_border=exclude_border
if length star_cutouts == 0
begin
warn string No sources were found. AstropyUserWarning
return call Table
end
set star_props = list
for star_cutout in star_cutouts
begin
set props = call _DAO... | def find_stars(self, data):
star_cutouts = _find_stars(data, self.kernel, self.threshold_eff,
exclude_border=self.exclude_border)
if len(star_cutouts) == 0:
warnings.warn('No sources were found.', AstropyUserWarning)
return Table()
st... | Python | nomic_cornstack_python_v1 |
import numpy as np
set QAL = call empty dtype=str shape=list 0 2
set data = load np string irqa_data.npy
set counter = 0
function KeyWordsCheck Q
begin
set need = list string 饮食 string 饮用 string 吃 string 食 string 伙食 string 膳食 string 喝 string 菜 string 忌口 string 补品 string 保健品 string 食谱 string 菜谱 string 食用 string 食物 strin... | import numpy as np
QAL = np.empty(dtype=str, shape=[0, 2])
data = np.load('irqa_data.npy')
counter = 0
def KeyWordsCheck(Q):
need = ['饮食', '饮用', '吃', '食', '伙食', '膳食', '喝', '菜' ,'忌口', '补品', '保健品', '食谱', '菜谱', '食用', '食物','补品']
no = ['口吃']
for item in no:
if Q.find(item) != -1:
return Fal... | Python | zaydzuhri_stack_edu_python |
from sklearn.linear_model import LinearRegression
from sklearn.multioutput import MultiOutputRegressor
from sklearn.pipeline import FeatureUnion
from skits.feature_extraction import AutoregressiveTransformer
from skits.pipeline import ForecasterPipeline
from skits.preprocessing import ReversibleImputer , HorizonTransfo... | from sklearn.linear_model import LinearRegression
from sklearn.multioutput import MultiOutputRegressor
from sklearn.pipeline import FeatureUnion
from skits.feature_extraction import AutoregressiveTransformer
from skits.pipeline import ForecasterPipeline
from skits.preprocessing import ReversibleImputer, HorizonTransfo... | Python | zaydzuhri_stack_edu_python |
string 输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 (注意: 在返回值的list中,数组长度大的数组靠前) 递归
import sys
append path string C:\Documents\GitHub\Data-Structure-and-Algorithms
from BST.BinarySearchTree import Tree
class Solution
begin
function findPath self root integer
begin
set result = list
functi... | '''
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
(注意: 在返回值的list中,数组长度大的数组靠前)
递归
'''
import sys
sys.path.append(r"C:\Documents\GitHub\Data-Structure-and-Algorithms")
from BST.BinarySearchTree import Tree
class Solution:
def findPath(self, root, integer):
result = []
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import pandas as pd
import sys
import pickle
import warnings
filter warnings string ignore
append path string ../tools/
from feature_format import featureFormat , targetFeatureSplit
from tester import dump_classifier_and_data
from sklearn.feature_selection import SelectKBest
from sklearn.pipeli... | #!/usr/bin/python
import pandas as pd
import sys
import pickle
import warnings
warnings.filterwarnings("ignore")
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline... | Python | zaydzuhri_stack_edu_python |
import re
set x = call raw_input string Enter filename with extension
set NAME_MSG = string name-msg.txt
set MSG_ONLY = string msg-only.txt
comment Generate log file in name:message format
comment Strip emoticons
function name_msg_filgen filename
begin
set b = open filename string r
set a = open NAME_MSG string w
set y... | import re
x = raw_input('Enter filename with extension')
NAME_MSG = 'name-msg.txt'
MSG_ONLY = 'msg-only.txt'
##Generate log file in name:message format
# Strip emoticons
def name_msg_filgen(filename):
b = open(filename, "r")
a = open(NAME_MSG, "w")
y = b.readline().decode('utf-8-sig').encode('utf-8')
while y:
... | Python | zaydzuhri_stack_edu_python |
function find_supplier
begin
set rfc = args at string rfc
set message = string
try
begin
set supplier = call get_supp dict string _id rfc
end
except Exception as e
begin
set message = string e
set supplier = none
end
if supplier is none
begin
set resp = call make_response dumps dict string status false ; string messag... | def find_supplier():
rfc = request.args["rfc"]
message = ""
try:
supplier = suppliers_service.get_supp({"_id": rfc})
except Exception as e:
message = str(e)
supplier = None
if supplier is None:
resp = make_response(
dumps(
{
... | Python | nomic_cornstack_python_v1 |
function NewRoundingCorrectionPrecedence key_and_percent
begin
set tuple key float_percent = key_and_percent
return list 1 - float_percent - integer float_percent float_percent call SortKeyFeyFromKey key
end function | def NewRoundingCorrectionPrecedence(key_and_percent):
key, float_percent = key_and_percent
return [
1 - (float_percent - int(float_percent)),
float_percent,
SortKeyFeyFromKey(key)] | Python | nomic_cornstack_python_v1 |
function Cmp lhs rhs
begin
return - call cmp length lhs at 1 length rhs at 1 or call cmp lhs at 0 rhs at 0
end function | def Cmp(lhs, rhs):
return -cmp(len(lhs[1]), len(rhs[1])) or cmp(lhs[0], rhs[0]) | Python | nomic_cornstack_python_v1 |
function invert_normal plane
begin
comment flip the normal, and the distance
return - plane
end function | def invert_normal(plane):
# flip the normal, and the distance
return -plane | Python | nomic_cornstack_python_v1 |
function test self
begin
info string No test!
yield
end function | def test(self):
self.logger.info("No test!")
yield | Python | nomic_cornstack_python_v1 |
comment visualizations
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
set height = list 110 140 150 160 170
set weight = list 30 40 50 60 70
set calories_burnt = list 60 70 75 80
plot height weight
title plt string Height Weight Relationship
x label string Height
y label string Weight
show
comme... | #visualizations
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
height = [110,140,150,160,170]
weight = [30,40,50,60,70]
calories_burnt = [60,70,75,80]
plt.plot(height, weight)
plt.title("Height Weight Relationship")
plt.xlabel("Height")
plt.ylabel("Weight")
plt.show()
#add legends
plt.plot(ca... | Python | zaydzuhri_stack_edu_python |
function full_error_results self
begin
return __full_error_results
end function | def full_error_results(self):
return self.__full_error_results | Python | nomic_cornstack_python_v1 |
function TasselliFuoriPosto wmemory
begin
string Calcola il numero di tasselli fuoriposto
from icse.ps.wm.WorkingMemory import WorkingMemory
assert is instance wmemory WorkingMemory
set posizioni = dict 1 tuple 1 1 ; 2 tuple 1 2 ; 3 tuple 1 3 ; 4 tuple 2 3 ; 5 tuple 3 3 ; 6 tuple 3 2 ; 7 tuple 3 1 ; 8 tuple 2 1 ; none ... | def TasselliFuoriPosto(wmemory):
'''
Calcola il numero di tasselli fuoriposto
'''
from icse.ps.wm.WorkingMemory import WorkingMemory
assert isinstance(wmemory, WorkingMemory)
posizioni = {
1: (1,1),
2: (1,2),
3: (1,3),
4: (2,3),
... | Python | zaydzuhri_stack_edu_python |
comment # 매개변수 > 리스트 타입
comment def downheap(i, size):
comment while 2 * i <= size:
comment # k는 왼쪽자식
comment k = 2 * i
comment if k < size and a[k] > a[k + 1]:
comment k += 1
comment if a[i] < a[k]:
comment break
comment a[i], a[k] = a[k], a[i]
comment i = k
comment def create_heap(a):
comment hsize = len(a) - 1
comme... | # # 매개변수 > 리스트 타입
# def downheap(i, size):
# while 2 * i <= size:
# # k는 왼쪽자식
# k = 2 * i
#
# if k < size and a[k] > a[k + 1]:
# k += 1
#
# if a[i] < a[k]:
# break
#
# a[i], a[k] = a[k], a[i]
#
# i = k
#
#
# def create_heap(a):
# hsize = le... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import math
from NN import NN
from Feedforward import Feedforward as ff
from Backpropagate import Backpropagate as bp
from GeneticAlgorithm import GeneticAlgorithm as ga
from DifferentialEvolution import DifferentialEvoluation as de
from PSO import PSO as pso
class NeuralNet
begin
function __init__ ... | import pandas as pd
import math
from NN import NN
from Feedforward import Feedforward as ff
from Backpropagate import Backpropagate as bp
from GeneticAlgorithm import GeneticAlgorithm as ga
from DifferentialEvolution import DifferentialEvoluation as de
from PSO import PSO as pso
class NeuralNet:
def __init__(self... | Python | zaydzuhri_stack_edu_python |
while i <= t
begin
set summation = 0
set tuple base power = map int split input
for k in range power + 1
begin
set summation = summation + power base k
end
print string Result = summation
set i = i + 1
end | while i <= t:
summation = 0
base, power = map(int, input().split())
for k in range(power+1):
summation = summation + pow(base, k)
print("Result =", summation)
i = i + 1
| Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
import layers as ly
import datareader as dr
import utils
string Input image dimension (square)
set INPUT_IMAGE_DIMENSION = 28
string Input image channel (greyscale)
set INPUT_IMAGE_CHANNELS = 1
string Training step size
set STEP_SIZE = 800
string Input batch size
set BATCH_SIZE = 30
string Fully... | import tensorflow as tf
import layers as ly
import datareader as dr
import utils
""" Input image dimension (square) """
INPUT_IMAGE_DIMENSION = 28
""" Input image channel (greyscale) """
INPUT_IMAGE_CHANNELS = 1
""" Training step size """
STEP_SIZE = 800
""" Input batch size"""
BATCH_SIZE = 30
""" Fully connected ... | Python | zaydzuhri_stack_edu_python |
function request_leadership self
begin
set term = term + 1
set election_state = string candidate
set voted_for = _id
set vote_count = 1
call send_to_peers type=string request_votes contents=_id
end function
comment if timer elapses during request for leadership, set to follower | def request_leadership(self):
self.term += 1
self.election_state = 'candidate'
self.voted_for = self._id
self.vote_count = 1
self.send_to_peers(type='request_votes', contents=self._id)
# if timer elapses during request for leadership, set to follower | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import logging
import sqlite3
function _create_products_table con
begin
string Creates the table for consolidated data.
set tb_exists = string SELECT name FROM sqlite_master WHERE type='table' + string AND name='products'
if not call fetchone
begin
info string Table products not detected!
... | # -*- coding: utf-8 -*-
import logging
import sqlite3
#######################################################################
def _create_products_table(con):
"""Creates the table for consolidated data.
"""
tb_exists = "SELECT name FROM sqlite_master WHERE type='table' " + \
"AND name='pr... | Python | zaydzuhri_stack_edu_python |
function test_no_permission self
begin
set item = get objects sms__id=34
call reset
save
set r = get client reverse string legacysms:media kwargs=dict string media_id 34
call assertRedirects r call media_page 34 at string Location fetch_redirect_response=false
call force_login call create username=string spqr1
set r = ... | def test_no_permission(self):
item = mpmodels.MediaItem.objects.get(sms__id=34)
item.view_permission.reset()
item.view_permission.save()
r = self.client.get(reverse('legacysms:media', kwargs={'media_id': 34}))
self.assertRedirects(r, redirect.media_page(34)['Location'],
... | Python | nomic_cornstack_python_v1 |
import codecs
import json
import os
import os.path
import numpy as np
import scrapy
class QuotesSpider extends Spider
begin
set name = string science
set start_urls = list string https://vnexpress.net/khoa-hoc
function parse self response
begin
for post in call css string article.list_news
begin
set link = call re stri... | import codecs
import json
import os
import os.path
import numpy as np
import scrapy
class QuotesSpider(scrapy.Spider):
name = "science"
start_urls = [
'https://vnexpress.net/khoa-hoc',
]
def parse(self, response):
for post in response.css('article.list_news'):
link = post... | Python | zaydzuhri_stack_edu_python |
comment Copyright 2015 Google Inc. All Rights Reserved.
string Compute page for handling tasks related to compute engine.
import logging
import webapp2
import apiauth
from google.appengine.api import app_identity
from google.appengine.api import taskqueue
comment Page actions
comment Get the status of an instance.
set ... | # Copyright 2015 Google Inc. All Rights Reserved.
"""Compute page for handling tasks related to compute engine."""
import logging
import webapp2
import apiauth
from google.appengine.api import app_identity
from google.appengine.api import taskqueue
# Page actions
# Get the status of an instance.
ACTION_STATUS = '... | Python | zaydzuhri_stack_edu_python |
function prime_factors n
begin
set i = 2
set factors = list
while i * i <= n
begin
if n % i
begin
set i = i + 1
end
else
begin
set n = n // i
append factors i
end
end
if n > 1
begin
append factors n
end
return factors
end function
print format string The smallest factors of {} is {}. A call prime_factors A | def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
print("The smallest factors of {} is {}.".format(A, prime_factors(A)))
| Python | zaydzuhri_stack_edu_python |
function cummax self
begin
return call _lift lambda c -> cummax
end function | def cummax(self):
return self._lift(lambda c: c.cummax) | Python | nomic_cornstack_python_v1 |
import re
function nothing_special s
begin
try
begin
return sub string [^a-z0-9\s] string s flags=IGNORECASE
end
except any
begin
return string Not a string!
end
end function | import re
def nothing_special(s):
try:
return re.sub('[^a-z0-9\s]', '', s, flags=re.IGNORECASE)
except:
return 'Not a string!'
| Python | zaydzuhri_stack_edu_python |
comment Complete the variance function to make it return the variance of a list of numbers
set data1 = list 13.04 1.32 22.65 17.44 29.54 23.22 17.65 10.12 26.73 16.43
function mean data
begin
return sum data / length data
end function
function variance data
begin
set mean_data = mean data
set variance_numerator = list ... | #Complete the variance function to make it return the variance of a list of numbers
data1=[13.04, 1.32, 22.65, 17.44, 29.54, 23.22, 17.65, 10.12, 26.73, 16.43]
def mean(data):
return sum(data)/len(data)
def variance(data):
mean_data = mean(data)
variance_numerator = []
for i in data:
variance... | Python | zaydzuhri_stack_edu_python |
import base64
from Crypto.Cipher import AES
import random
import matplotlib.pyplot as plt
string 采用AES对称加密算法ECB
comment str不是32的倍数那就补足为16的倍数
function add_to_32 value
begin
while length value % 32 != 0
begin
set value = value + string
end
comment 返回bytes
return encode str value
end function
comment 加密方法
function encry... | import base64
from Crypto.Cipher import AES
import random
import matplotlib.pyplot as plt
'''
采用AES对称加密算法ECB
'''
# str不是32的倍数那就补足为16的倍数
def add_to_32(value):
while len(value) % 32 != 0:
value += '\0'
return str.encode(value) # 返回bytes
#加密方法
def encrypt_oracle(key):
# 秘钥
text = 'yun school of so... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import getpass
import onetimepass
function get_token cfg
begin
set s = get cfg string auth string secret
if s == string
begin
set t = call getpass string OAuth Token:
end
else
begin
set t = call get_totp s
end
return t
end function
function get_password cfg
begin
set p = get cfg string aut... | #!/usr/bin/env python
import getpass
import onetimepass
def get_token(cfg):
s = cfg.get('auth', 'secret')
if s == '':
t = getpass.getpass('OAuth Token:')
else:
t = onetimepass.get_totp(s)
return t
def get_password(cfg):
p = cfg.get('auth', 'password')
if p == '':
p ... | Python | zaydzuhri_stack_edu_python |
from multiprocessing import Process , Pipe
from collections import namedtuple
from Crypto.Hash import SHA
from set5.utilz import *
set Parameters = named tuple string parameters list string N string g string k string I string P
set p = parameters N 2 3 b'a@a.com' b'passw0rd'
function calc_u A B
begin
set uH = hexadecim... | from multiprocessing import Process, Pipe
from collections import namedtuple
from Crypto.Hash import SHA
from set5.utilz import *
Parameters = namedtuple('parameters', ['N', 'g', 'k', 'I', 'P'])
p = Parameters(N, 2, 3, b'a@a.com', b'passw0rd')
def calc_u(A, B):
uH = hex(A) + hex(B)
uH = sha256_hexdigest(uH.... | Python | zaydzuhri_stack_edu_python |
from components.Text import Text
class Input extends Text
begin
function __init__ self textVal font=string Centaur size=16 color=tuple 255 255 255
begin
call __init__ string font size color
set active = false
end function
function activate self
begin
set active = true
end function
function deactivate self
begin
set ac... | from components.Text import Text
class Input(Text):
def __init__(self, textVal, font='Centaur', size=16, color=(255, 255, 255)):
super().__init__("", font, size, color)
self.active = False
def activate(self):
self.active = True
def deactivate(self):
self.active = False
| Python | zaydzuhri_stack_edu_python |
function freq_word sentence
begin
set words = split sentence
comment make a dictionary to count the occurrance of each word
set d = dict
for word in words
begin
comment if the word is already in the dictionary, increment its count
if word in keys d
begin
set d at word = d at word + 1
end
else
begin
comment else add th... | def freq_word(sentence):
words = sentence.split()
# make a dictionary to count the occurrance of each word
d = {}
for word in words:
# if the word is already in the dictionary, increment its count
if word in d.keys():
d[word] += 1
# else add the word in the dictionary... | Python | jtatman_500k |
function wave_info self raw_output=false
begin
set output = query self string C + channel at - 1 + string :BSWV?
if not raw_output
begin
set info = split split output string at - 1 at slice : - 1 : string ,
set tuple info_tags info_vals = tuple info at slice 0 : : at slice : : 2 info at slice 1 : : at slice : ... | def wave_info(self, raw_output = False):
output = self.query('C' + self.channel[-1] + ':BSWV?')
if not raw_output:
info = output.split(' ')[-1][:-1].split(',')
info_tags, info_vals = info[0:][::2], info[1:][::2]
N = len(info_tags)
output = {}
... | Python | nomic_cornstack_python_v1 |
function test_rider_emails_no_riders_registered self views_class brevet_views_module views_core_module
begin
set request = call get_current_request
update matchdict dict string region string VI ; string distance string 200 ; string date string 03Mar2013 ; string uuid string foo
set gml_patch = call object views_core_mo... | def test_rider_emails_no_riders_registered(
self, views_class, brevet_views_module, views_core_module,
):
request = get_current_request()
request.matchdict.update({
'region': 'VI',
'distance': '200',
'date': '03Mar2013',
'uuid': 'foo',
... | Python | nomic_cornstack_python_v1 |
function find_points self lines
begin
set points = list
for l in lines
begin
set tuple rho theta = l
set a = cos theta
set b = sin theta
set x0 = a * rho
set y0 = b * rho
set x1 = integer x0 + 1000 * - b
set y1 = integer y0 + 1000 * a
set x2 = integer x0 - 1000 * - b
set y2 = integer y0 - 1000 * a
append points list l... | def find_points(self, lines):
points = []
for l in lines:
rho, theta = l
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
... | Python | nomic_cornstack_python_v1 |
if v > 80
begin
set q = v - 80
set multa = format q * 5 string .2f
print format string Multa = {0} multa
end
else
begin
print string Não foi multado
end | if v > 80:
q = v-80
multa = format(q*5, '.2f')
print("Multa = {0}".format(multa))
else:
print("Não foi multado")
| 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.