code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/python3
comment NAME
comment weeralarm.py - script which alarms when temperature above a threshold
comment SYNOPSIS
comment weeralarm.py [-v] [-t interval] [-T threshold]
comment -v: verbose
comment -t interval: sample every interval seconds
comment -T threshold: alarm above this value
comment DESCRIP... | #!/usr/bin/python3
#
# NAME
# weeralarm.py - script which alarms when temperature above a threshold
#
# SYNOPSIS
# weeralarm.py [-v] [-t interval] [-T threshold]
# -v: verbose
# -t interval: sample every interval seconds
# -T threshold: alarm above this value
#
# DESCRIPTION
# reads temperature... | Python | zaydzuhri_stack_edu_python |
function average_blur img kernel_size=3
begin
set imgtype = dtype
set tuple h w c = shape
comment Get a valid kernel size
set kernel_size = call valid_kernel h w kernel_size
comment Averaging Filter Blur (Homogeneous filter)
set blurred = call blur img tuple kernel_size kernel_size
return as type blurred imgtype
end fu... | def average_blur(img: np.ndarray, kernel_size: int = 3):
imgtype = img.dtype
h,w,c = img.shape
#Get a valid kernel size
kernel_size = valid_kernel(h,w,kernel_size)
#Averaging Filter Blur (Homogeneous filter)
blurred = cv2.blur(img,(kernel_size,kernel_size))
return blurred.astype(imgty... | Python | nomic_cornstack_python_v1 |
comment if - else 문
set price = 100000
set grade = 70
if grade >= 60
begin
set price = 150000
print string 인상 price
end
else
begin
set price = 70000
print string 기본 price
end
print string 변환 된 값 : price | # if - else 문
price = 100000
grade = 70
if grade >= 60 :
price = 150000
print('인상',price)
else :
price = 70000
print('기본',price)
print('변환 된 값 : ',price) | Python | zaydzuhri_stack_edu_python |
async function vote self ctx title *options
begin
if length title > 256
begin
raise call BadArgument string The title cannot be longer than 256 characters.
end
if length options < 2
begin
raise call BadArgument string Please provide at least 2 options.
end
if length options > 20
begin
raise call BadArgument string I ca... | async def vote(self, ctx: Context, title: clean_content(fix_channel_mentions=True), *options: str) -> None:
if len(title) > 256:
raise BadArgument("The title cannot be longer than 256 characters.")
if len(options) < 2:
raise BadArgument("Please provide at least 2 options.")
... | Python | nomic_cornstack_python_v1 |
function divide_list numbers divisor
begin
return list comprehension i / divisor for i in numbers
end function | def divide_list(numbers, divisor):
return [i/divisor for i in numbers] | Python | jtatman_500k |
comment Введите число. Если это число делиться на 1000 без остатка, то выведите
comment на экран "millennium".
set a = integer input
if a % 1000 == 0
begin
print string millennium
end | # Введите число. Если это число делиться на 1000 без остатка, то выведите
# на экран "millennium".
a = int(input())
if a % 1000 == 0:
print('millennium')
| Python | zaydzuhri_stack_edu_python |
comment Author: Charse
comment 高阶函数 + 函数嵌套 ==> 装饰器
import time
comment tim(hell1) func=hell1
function tim func
begin
function deco
begin
set start_time = time
comment 在这里实际执行的时 hell1
call func
set stop_time = time
print string run time %s % stop_time - start_time
end function
return deco
end function
function timer fun... | # Author: Charse
# 高阶函数 + 函数嵌套 ==> 装饰器
import time
def tim(func): # tim(hell1) func=hell1
def deco():
start_time = time.time()
func() # 在这里实际执行的时 hell1
stop_time = time.time();
print("run time %s" % (stop_time - start_time))
return deco
def timer(func):
# 函数嵌套
def d... | Python | zaydzuhri_stack_edu_python |
function fit self X gt
begin
if not is instance X list
begin
set X = list X
end
set newX = list
for x in X
begin
assert is instance x ndarray and length shape == 2 and shape at 1 == 3 and shape at 0 == length gt
append newX call _sanitize_input x
end
set d = list comprehension gt - x at tuple slice : : 0 for x in n... | def fit(self, X, gt):
if not isinstance(X, list):
X = [X]
newX = []
for x in X:
assert (isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[1] == 3 and x.shape[0] == len(gt))
newX.append(self._sanitize_input(x))
self.d = [gt - x[:, 0] for x in ... | Python | nomic_cornstack_python_v1 |
function forward self o
begin
comment get Q(s,a;\theta)
if __module__ == string numpy
begin
set o = call from_numpy o
end
comment o = torch.unsqueeze(o, 0)
comment print(o.shape)
comment exit()
set o = view o - 1 input_channels height width
if use_cuda
begin
set o = cuda o
end
set q = call get_q_value o
return q
end fu... | def forward(self, o):
# get Q(s,a;\theta)
if type(o).__module__ == "numpy":
o = torch.from_numpy(o)
# o = torch.unsqueeze(o, 0)
# print(o.shape)
# exit()
o = o.view(-1,BrainDQN.input_channels,height,width )
if self.use_cuda:
o = o.cuda()
q = self.get_q_value(o)
return q | Python | nomic_cornstack_python_v1 |
import sqlite3 as sql
from sqlite3.dbapi2 import PrepareProtocol
import persons
from constants import *
import json
function create_table
begin
set create_users_table = string CREATE TABLE IF NOT EXISTS players( id INTEGER PRIMARY KEY, class TEXT, name TEXT, max_hp INTEGER, armor INTEGER, attack INTEGER, level INTEGER,... | import sqlite3 as sql
from sqlite3.dbapi2 import PrepareProtocol
import persons
from constants import *
import json
def create_table():
create_users_table = """
CREATE TABLE IF NOT EXISTS players(
id INTEGER PRIMARY KEY,
class TEXT,
name TEXT,
max_hp INTEGER,
armor ... | Python | zaydzuhri_stack_edu_python |
function encode coordinates precision=5 third_dim=ABSENT third_dim_precision=0
begin
set multiplier_degree = 10 ^ precision
set multiplier_z = 10 ^ third_dim_precision
set last_lat = 0
set last_lng = 0
set last_z = 0
set res = list
set appender = append
call encode_header appender precision third_dim third_dim_precisi... | def encode(coordinates, precision=5, third_dim=ABSENT, third_dim_precision=0):
multiplier_degree = 10 ** precision
multiplier_z = 10 ** third_dim_precision
last_lat = last_lng = last_z = 0
res = []
appender = res.append
encode_header(appender, precision, third_dim, third_dim_precision)
fo... | Python | nomic_cornstack_python_v1 |
function find_connected_devices portshow_aggregated_df npv_ag_connected_devices_df fcr_xd_proxydev_df
begin
comment filter all connected devices in fabrics
set connected_devices_df = call filter_edge_devices portshow_aggregated_df
comment tag NPIV devices with NPIV tag
set connected_devices_df = call tag_npiv_devices c... | def find_connected_devices(portshow_aggregated_df, npv_ag_connected_devices_df, fcr_xd_proxydev_df):
# filter all connected devices in fabrics
connected_devices_df = filter_edge_devices(portshow_aggregated_df)
# tag NPIV devices with NPIV tag
connected_devices_df = tag_npiv_devices(connected_devices_d... | Python | nomic_cornstack_python_v1 |
function buy
begin
comment if user submitted a form
if method == string POST
begin
set symbol = string get form string symbol
set shares = get form string shares
comment check if inputs are filled
if not symbol
begin
return call apology string You must provide a symbol
end
else
if not shares
begin
return call apology s... | def buy():
# if user submitted a form
if request.method == "POST":
symbol = str(request.form.get("symbol"))
shares = request.form.get("shares")
# check if inputs are filled
if not symbol:
return apology("You must provide a symbol")
elif not shares:
... | Python | nomic_cornstack_python_v1 |
function test_can_append_pseudominus self
begin
set results = dict string upper_in_out true ; string lower_in_out true ; string upper_in_out_in true ; string lower_in_out_in true ; string upper_in true ; string lower_in true ; string upper_in_in_in true ; string lower_in_in_in true ; string upper_out_out_out true ; str... | def test_can_append_pseudominus(self):
results = { 'upper_in_out' : True,
'lower_in_out' : True,
'upper_in_out_in' : True,
'lower_in_out_in' : True,
'upper_in' : True,
'lower_in' : True,
... | Python | nomic_cornstack_python_v1 |
function process_real df
begin
set df_c = copy df
set df_c = apply df_c lambda s -> call to_quants s std=1 axis=1
set df_c = df_c > 0
if type index == MultiIndex
begin
set index = map lambda s -> join string _ s index
end
return T
end function | def process_real(df):
df_c = df.copy()
df_c = df_c.apply(lambda s: H.to_quants(s, std=1), axis=1)
df_c = df_c > 0
if type(df.index) == pd.MultiIndex:
df_c.index = map(lambda s: '_'.join(s), df_c.index)
return df_c.T | Python | nomic_cornstack_python_v1 |
class SoccerPlayer extends object
begin
function __init__ self name position back_number=20
begin
comment print('생성자 함수 호출됨')
set name = name
set position = position
set back_number = back_number
end function
comment back_number 속성을 변경하는 메서드
function change_back_number self new_number
begin
print string 선수의 등번호를 변경합니다 ... | class SoccerPlayer(object):
def __init__(self, name, position, back_number=20):
# print('생성자 함수 호출됨')
self.name = name
self.position = position
self.back_number = back_number
# back_number 속성을 변경하는 메서드
def change_back_number(self, new_number):
print("선수의 등번호를 변경합니다 :... | Python | zaydzuhri_stack_edu_python |
function get_dp1 self k **kwargs
begin
set alpha = kwargs at string alpha
set dp1 = alpha / square root k + 0 * 1j
return dp1
end function | def get_dp1(self, k, **kwargs):
alpha = kwargs["alpha"]
dp1 = alpha/np.sqrt(k) + 0*1j
return dp1 | Python | nomic_cornstack_python_v1 |
function about self
begin
return dictionary page=string about
end function | def about(self):
return dict(page='about') | Python | nomic_cornstack_python_v1 |
from WordGuess import WordGuess
function readWords filename
begin
string Read in the list of possible secret words and their corresponding hints
set File = open filename
comment open dictionary
set Dict = dict
for line in File
begin
comment splits the line with space
set temp = split line string
comment setting a dict... | from WordGuess import WordGuess
def readWords(filename):
""" Read in the list of possible secret words and their corresponding hints """
File = open(filename)
Dict = {} #open dictionary
for line in File:
temp = line.split(' ') #splits the line with space
Dict[temp[0]] = temp[1] #setti... | Python | zaydzuhri_stack_edu_python |
function testCaseEvaluateParenExpression self
begin
comment note that or is the weakest operator
set p = call Parser string (false and false or true)
set e = call ParseCommonExpression
set value = evaluate e none
assert true value is true string Expected True
comment should change the result
set p = call Parser string ... | def testCaseEvaluateParenExpression(self):
p=Parser("(false and false or true)") # note that or is the weakest operator
e=p.ParseCommonExpression()
value=e.Evaluate(None)
self.assertTrue(value.value is True,"Expected True")
p=Parser("(false and (false or true))") # should change the result
e=p.ParseCommon... | Python | nomic_cornstack_python_v1 |
import random
set original_ending = string The hero defeats the villain and saves the day. The kingdom rejoices and celebrates their victory.
set endings = list
for i in range 10
begin
set new_ending = replace original_ending string defeats random choice list string captures string outsmarts string banishes
set new_en... | import random
original_ending = "The hero defeats the villain and saves the day. The kingdom rejoices and celebrates their victory."
endings = []
for i in range(10):
new_ending = original_ending.replace("defeats", random.choice(["captures", "outsmarts", "banishes"]))
new_ending = new_ending.replace("saves the d... | Python | jtatman_500k |
comment noqa: E501
function __init__ self replicate_comment_resource_types=none
begin
set openapi_types = dict string replicate_comment_resource_types ConfigNodePropertyArray
set attribute_map = dict string replicate_comment_resource_types string replicate.comment.resourceTypes
set _replicate_comment_resource_types = r... | def __init__(self, replicate_comment_resource_types: ConfigNodePropertyArray=None): # noqa: E501
self.openapi_types = {
'replicate_comment_resource_types': ConfigNodePropertyArray
}
self.attribute_map = {
'replicate_comment_resource_types': 'replicate.comment.resourceTy... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return string Scrambled Words is a text-based word guessing game.
end function | def __repr__(self):
return "Scrambled Words is a text-based word guessing game." | Python | nomic_cornstack_python_v1 |
function f self f
begin
set _ppm = none
set _f = f
end function | def f(self, f):
self._ppm = None
self._f = f | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
set all_list = list list 1 2 3 4 list 4 3 2 1 list 4 5 6 7 list 2 3 4 5
set a = list
set af = call DataFrame all_list columns=list string phone string phone2 string phone3 string phone4 | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
all_list = [[1,2,3,4],[4,3,2,1],[4,5,6,7],[2,3,4,5]]
a=[]
af = pd.DataFrame(all_list,columns=["phone","phone2","phone3","phone4"]) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from models import methods , objects
function combine_attributes new_at prev_at
begin
string Combines the information of the attributes. Parameters ---------- new_at : int[] The list of the attributes identifiers of the new object. prev_at : int[] The list of the attributes identifiers of ... | # -*- coding: utf-8 -*-
from models import methods, objects
def combine_attributes(new_at, prev_at):
"""
Combines the information of the attributes.
Parameters
----------
new_at : int[]
The list of the attributes identifiers of the new object.
prev_at : int[]
The list of the... | Python | zaydzuhri_stack_edu_python |
function interp_test_data data
begin
comment interpolation interval = (1000 / fps) since 1 sec = 1000 ms
set interp_ms = 1000 / fps
comment int(round(float(data[i][0])/interp_ms)*interp_ms)
comment rounding off model times to nearest interp_ms.
set model_time = list comprehension integer interp_ms * round decimal val a... | def interp_test_data(data):
# interpolation interval = (1000 / fps) since 1 sec = 1000 ms
interp_ms = 1000 / fps
####int(round(float(data[i][0])/interp_ms)*interp_ms)
# rounding off model times to nearest interp_ms.
model_time = [int(interp_ms * round(float(val[0])/interp_ms)) for val in data]
... | Python | nomic_cornstack_python_v1 |
from telegram import ParseMode , ReplyKeyboardMarkup , ReplyKeyboardRemove
from telegram.ext import ConversationHandler
from utils import main_keyboard
function form_start update context
begin
call reply_text string What is your name? (including last name) reply_markup=call ReplyKeyboardRemove
return string name
end fu... | from telegram import ParseMode, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import ConversationHandler
from utils import main_keyboard
def form_start(update, context):
update.message.reply_text(
"What is your name? (including last name)",
reply_markup=ReplyKeyboardRemove()
)
... | Python | zaydzuhri_stack_edu_python |
from utility import *
function forced_ext_cylinder
begin
call pr string Churchill-Bernstein - Forced external convection around cyclinder
set p = call get_params list string Re_D string Pr
set num = 0.62 * p at string Re_D ^ 0.5 * p at string Pr ^ 1 / 3
set den = 1 + 0.4 / p at string Pr ^ 2 / 3 ^ 1 / 4
set factor = 1 ... | from utility import *
def forced_ext_cylinder():
pr('Churchill-Bernstein - Forced external convection around cyclinder')
p = get_params(['Re_D', 'Pr'])
num = .62 * p['Re_D'] ** .5 * p['Pr'] ** (1 / 3)
den = (1 + (.4 / p['Pr']) ** (2 / 3)) ** (1 / 4)
factor = (1 + (p['Re_D'] / 282000) ** (5 / 8)) ... | Python | zaydzuhri_stack_edu_python |
function main
begin
comment escribe tu código abajo de esta línea
set palabras = integer input string Dame el número de palabras:
set paginas = palabras // 475 + 1
set costo = paginas * 60 * 0.9
print string El costo de la publicación es: + string costo
pass
end function
if __name__ == string __main__
begin
call main
e... | def main():
#escribe tu código abajo de esta línea
palabras=int(input("Dame el número de palabras: "))
paginas=palabras//475+1
costo=(paginas*60)*.9
print("El costo de la publicación es: " + str(costo))
pass
if __name__ == '__main__':
main()
| Python | zaydzuhri_stack_edu_python |
comment Etap9. Odcinek: MapReduce: Srednia odleglosc lotu
from mrjob.job import MRJob
from mrjob.step import MRStep
class MRFlights extends MRJob
begin
function steps self
begin
return list call MRStep mapper=moje_mapper_month reducer=moje_reducer_month
end function
comment MRStep(mapper=self.mapper,
comment reducer=se... | # Etap9. Odcinek: MapReduce: Srednia odleglosc lotu
from mrjob.job import MRJob
from mrjob.step import MRStep
class MRFlights(MRJob):
def steps(self):
return [
# MRStep(mapper=self.mapper,
# reducer=self.reducer),
# moje stepy
MRStep(mapper=self.moj... | Python | zaydzuhri_stack_edu_python |
function find_augment_path self head end path=list visit=dict string x list ; string y list start_x=true
begin
append path head
if start_x
begin
if end in feasible_labeling_X at head
begin
append path end
return tuple path true
end
else
begin
append visit at string x head
for next_node in feasible_labeling_X at head... | def find_augment_path(self, head, end, path=[], visit={'x': [], 'y': []}, start_x=True):
path.append(head)
if start_x:
if end in self.feasible_labeling_X[head]:
path.append(end)
return path, True
else:
visit['x'].append(head)
... | Python | nomic_cornstack_python_v1 |
class Option
begin
function __init__ self names nargs=1 implicit=none default=none repeated=false required=false type=none metavar=none help=none
begin
if is instance names str
begin
set names = list names
end
set names = names
set nargs = nargs
set implicit = implicit
set default = default
set repeated = repeated
set ... | class Option:
def __init__(self, names, nargs=1, implicit=None, default=None, repeated=False, required=False, type=None, metavar=None, help=None):
if isinstance(names, str): names = [names]
self.names = names
self.nargs = nargs
self.implicit = implicit
self.default = default
self.repeated ... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python3
import math
import os
import random
import re
import sys
string Task: The final grades for a Physics exam taken by a large group of students have a mean of mu = 70 and a standard deviation of 10. If we can approximate the distribution of these grades by a normal distribution, what percentage of th... | #!/bin/python3
import math
import os
import random
import re
import sys
"""
Task:
The final grades for a Physics exam taken by a large group of students have a mean of mu = 70 and a standard
deviation of 10. If we can approximate the distribution of these grades by a normal distribution, what percentage... | Python | zaydzuhri_stack_edu_python |
comment Комнаты бывают треугольные, прямоугольные и круглые. Чтобы быстро вычислять жилплощадь,
comment требуется написать программу, на вход которой подаётся тип фигуры комнаты и соответствующие
comment параметры, которая бы выводила площадь получившейся комнаты.
import math
print string Введите данные
print string Ко... | # Комнаты бывают треугольные, прямоугольные и круглые. Чтобы быстро вычислять жилплощадь,
# требуется написать программу, на вход которой подаётся тип фигуры комнаты и соответствующие
# параметры, которая бы выводила площадь получившейся комнаты.
#
import math
print('Введите данные')
print('Конфигурация комнаты:')
prin... | Python | zaydzuhri_stack_edu_python |
function cross self vector
begin
return x * vector at 1 - y * vector at 0
end function | def cross(self, vector):
return (self.x * vector[1]) - (self.y * vector[0]) | Python | nomic_cornstack_python_v1 |
import os
import csv
import requests
from bs4 import BeautifulSoup
set URL = string https://en.wikipedia.org/wiki/Mammootty_filmography
set output_name = string filmography
function scrape url output_name
begin
set response = get requests URL
set soup = call BeautifulSoup content
set table_classes = dict string class l... | import os
import csv
import requests
from bs4 import BeautifulSoup
URL = "https://en.wikipedia.org/wiki/Mammootty_filmography"
output_name = "filmography"
def scrape(url, output_name):
response = requests.get(URL)
soup = BeautifulSoup(response.content)
table_classes = {"class": ["wikitables", "sortable"... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import torch
function smooth1d y smooth
begin
string Smooth data using hanning filter :param y: input data to be smoothed :type y: numpy.array or list :param smooth: number of window length for smoothing :type smooth: int :return: smoothed data :rtype: numpy.array
if is instance y list
begin
set y = ... | import numpy as np
import torch
def smooth1d(y, smooth):
"""
Smooth data using hanning filter
:param y: input data to be smoothed
:type y: numpy.array or list
:param smooth: number of window length for smoothing
:type smooth: int
:return: smoothed data
:rtype: numpy.array
"""
if isinstance(y, list)... | Python | zaydzuhri_stack_edu_python |
function random_item weightsdict
begin
set keyvals = list comprehension tuple k v for tuple k v in items weightsdict
set vals = list comprehension v for tuple k v in keyvals
return keyvals at call weighted_choice vals at 0
end function | def random_item(weightsdict):
keyvals = [(k, v) for k, v in weightsdict.items()]
vals = [v for k, v in keyvals]
return keyvals[weighted_choice(vals)][0] | Python | nomic_cornstack_python_v1 |
string IR2 - Reproduction of "A Hierarchical Recurrent Encoder-Decoder for Generative Context-Aware Query Suggestion" by Sordoni et al. Group 8
import tensorflow as tf
import numpy as np
class Decoder extends object
begin
function __init__ self input_dim=300 num_hidden_query=1000 num_hidden_session=1500
begin
string Th... | """
IR2 - Reproduction of "A Hierarchical Recurrent
Encoder-Decoder for Generative Context-Aware Query Suggestion"
by Sordoni et al.
Group 8
"""
import tensorflow as tf
import numpy as np
class Decoder(object):
def __init__(self, input_dim=300, num_hidden_query=1000, num_hidden_session=1500):
... | Python | zaydzuhri_stack_edu_python |
function n_queen_bits_1 rowBits ld rd row
begin
global ans n
if rowBits == DONE
begin
for i in range n
begin
for j in range n
begin
print board at i at j end=string
end
print
end
print
set ans = ans + 1
return
end
set safe = DONE ? ? ld ? rd ? rowBits
while safe != 0
begin
set p = safe ? - safe
set bitPos = call bit_po... | def n_queen_bits_1(rowBits,ld,rd,row):
global ans,n
if rowBits == DONE:
for i in range(n):
for j in range(n):
print(board[i][j],end=" ")
print()
print()
ans+=1
return
safe = DONE & (~(ld|rd|rowBits))
while safe!=0:
p = sa... | Python | zaydzuhri_stack_edu_python |
from os import truncate
import boto3
import json
import sagemaker
from deploy_env import DeployEnv
import time
set env = call DeployEnv
print string Attempting to invoke model_name=%s / env=%s... % tuple call setting string model_name call current_env
print call isDeployed string dep
while true
begin
set query = input ... | from os import truncate
import boto3
import json
import sagemaker
from deploy_env import DeployEnv
import time
env = DeployEnv()
print("Attempting to invoke model_name=%s / env=%s..." % (env.setting('model_name'), env.current_env()))
print(env.isDeployed(),'dep')
while True:
query=input('Enter your query: ')
... | Python | zaydzuhri_stack_edu_python |
function update_edge_attr_to_graph self edge_gdf df_attr
begin
for edge in call itertuples
begin
set updates : dict = get attribute edge df_attr
for tuple key value in items updates
begin
set es at get attribute edge name at key = value
end
end
end function | def update_edge_attr_to_graph(self, edge_gdf, df_attr: str):
for edge in edge_gdf.itertuples():
updates: dict = getattr(edge, df_attr)
for key, value in updates.items():
self.graph.es[getattr(edge, E.id_ig.name)][key] = value | Python | nomic_cornstack_python_v1 |
function _get_wavelength_attrs_with_units self attrname units=string AA
begin
set attr = _lick at attrname
if wavelength_unit is not none
begin
if units is none
begin
return attr * unit at wavelength_unit
end
else
begin
return to attr * unit at wavelength_unit units
end
end
else
begin
return attr
end
end function | def _get_wavelength_attrs_with_units(self, attrname, units='AA'):
attr = self._lick[attrname]
if self.wavelength_unit is not None:
if units is None:
return attr * unit[self.wavelength_unit]
else:
return (attr * unit[self.wavelength_unit]).to(units)... | Python | nomic_cornstack_python_v1 |
function frusrum_ray self param_x param_y
begin
set tuple l r b t n f = dim
comment convert normalized into near frustum space
set sm = call ScaleMat x=r - l y=t - b
comment .5 to compensate origin difference between OpenGL space and pane space
set offset = call MoveMat - 0.5 - 0.5 - n
set frustum_point = sm * offset *... | def frusrum_ray(self, param_x, param_y):
l, r, b, t, n, f = self.body.dim
# convert normalized into near frustum space
sm = ScaleMat(x=r - l, y=t - b)
# .5 to compensate origin difference between OpenGL space and pane space
offset = MoveMat(-.5, -.5, -n)
frustum_point = s... | Python | nomic_cornstack_python_v1 |
import sys
set infile = argv at 1
set curtree = string
with open infile as f
begin
set optimized = open infile + string .optimized.txt string w
set unoptimized = open infile + string .unoptimized.txt string w
set curfile = unoptimized
for l in f
begin
if starts with l string 0
begin
set curtree = strip l
write optimiz... | import sys
infile = sys.argv[1]
curtree = ""
with open(infile) as f:
optimized = open(infile + ".optimized.txt", "w")
unoptimized = open(infile + ".unoptimized.txt", "w")
curfile = unoptimized
for l in f:
if l.startswith("0"):
curtree = l.strip()
optimized.write(l)
... | Python | zaydzuhri_stack_edu_python |
function as_ewkb self
begin
return call to_expr
end function | def as_ewkb(self) -> ir.BinaryValue:
return ops.GeoAsEWKB(self).to_expr() | Python | nomic_cornstack_python_v1 |
import random
set li = list
for i in range 10
begin
set ret = random
append li ret
end
print li | import random
li = []
for i in range(10):
ret = random.random()
li.append(ret)
print(li)
| Python | zaydzuhri_stack_edu_python |
comment Importar librerías
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input , Output
import plotly.graph_objs as go
import pandas as pd
comment Carga de datos
set df_temp = call read_excel string C:\Users\ivan_pinar\Dropbox\Creación de MOCs\MOC Dash ... | #Importar librerías
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
#Carga de datos
df_temp = pd.read_excel(r'C:\Users\ivan_pinar\Dropbox\Creación de MOCs\MOC Dash Python\Datasets\5.2\Tempe... | Python | zaydzuhri_stack_edu_python |
function __init__ self **kwargs
begin
pass
end function | def __init__(self, **kwargs):
pass | Python | nomic_cornstack_python_v1 |
import rpyc
import requests as rq
from anytree import Node
from concurrent.futures import *
import time
comment class for the services offered to the server
class EndService extends Service
begin
comment init for the service
function __init__ self r w s
begin
set worker = w
set requester = r
set stop = s
end function
c... | import rpyc
import requests as rq
from anytree import Node
from concurrent.futures import *
import time
##class for the services offered to the server
class EndService(rpyc.Service):
##init for the service
def __init__(self,r,w,s):
self.worker = w
self.requester = r
self.stop = s
#... | Python | zaydzuhri_stack_edu_python |
function configureVIDMVAPhoID_V1 mvaWP
begin
set parameterSet = call PSet idName=call string idName cutFlow=call VPSet call PSet cutName=call string string PhoMVACut mvaCuts=call vdouble call getCutValues mvaValueMapName=call InputTag mvaValueMapName mvaCategoriesMapName=call InputTag mvaCategoriesMapName needsAddition... | def configureVIDMVAPhoID_V1( mvaWP ):
parameterSet = cms.PSet(
#
idName = cms.string( mvaWP.idName ),
cutFlow = cms.VPSet(
cms.PSet( cutName = cms.string("PhoMVACut"),
mvaCuts = cms.vdouble( mvaWP.getCutValues() ),
mvaValueMapName = ... | Python | nomic_cornstack_python_v1 |
async function entrants self ctx
begin
if _race_created
begin
set racer_list = string Race entrants:
for racer in _racer_dict
begin
set ready_status = string
if racer in _racer_ready_dict
begin
set ready_status = string (ready)
end
set racer_list = format string {prev_racers} {racer}{status} prev_racers=racer_list rac... | async def entrants(self, ctx):
if self._race_created:
racer_list = 'Race entrants:\n'
for racer in self._racer_dict:
ready_status = ''
if racer in self._racer_ready_dict:
ready_status = ' (ready)'
racer_list = '{prev_rac... | Python | nomic_cornstack_python_v1 |
function docache minutes=5 content_type=string application/json; charset=utf-8
begin
function fwrap f
begin
decorator wraps f
function wrapped_f *args **kwargs
begin
set r = f dist *args keyword kwargs
set then = now + time delta minutes=minutes
set rsp = call Response r content_type=content_type
add headers string Exp... | def docache(minutes=5, content_type='application/json; charset=utf-8'):
def fwrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
r = f(*args, **kwargs)
then = datetime.now() + timedelta(minutes=minutes)
rsp = Response(r, content_type=content_type)
rsp.h... | Python | nomic_cornstack_python_v1 |
function itkShotNoiseImageFilterIUC3IUC3_cast *args
begin
return call itkShotNoiseImageFilterIUC3IUC3_cast *args
end function | def itkShotNoiseImageFilterIUC3IUC3_cast(*args):
return _itkShotNoiseImageFilterPython.itkShotNoiseImageFilterIUC3IUC3_cast(*args) | Python | nomic_cornstack_python_v1 |
function GetTestManagementId self
begin
set callResult = call _Call string GetTestManagementId
if callResult is none
begin
return none
end
return callResult
end function | def GetTestManagementId(self):
callResult = self._Call("GetTestManagementId", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
import pytest
import unittest
from utilities.teststatus import TestStatus
from page.courses.registercourse_page import RegisterCoursePage
decorator call usefixtures string oneTimeSetUp string setUp
class RegisterCourseTest extends TestCase
begin
decorator fixture autouse=true
function objectsetup self
begin
set courses... | import pytest
import unittest
from utilities.teststatus import TestStatus
from page.courses.registercourse_page import RegisterCoursePage
@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
class RegisterCourseTest(unittest.TestCase):
@pytest.fixture(autouse=True)
def objectsetup(self):
self.courses = ... | Python | zaydzuhri_stack_edu_python |
comment creamos la clase
class Mascota
begin
comment declaramos el metodo __init__
function __init__ self
begin
set nombre = input string Ingrese el nombre:
set edad = integer input string Ingrese la edad:
end function
function mostrar self
begin
print string Nombre: nombre
print string Edad: edad
end function
end clas... | # creamos la clase
class Mascota:
# declaramos el metodo __init__
def __init__(self):
self.nombre=input("Ingrese el nombre: ")
self.edad=int(input("Ingrese la edad: "))
def mostrar(self):
print("Nombre: ",self.nombre)
print("Edad: ",self.edad)
#----------hasta ... | Python | zaydzuhri_stack_edu_python |
import time
import board
import adafruit_sht4x
from conversions import Conversions
class TemperatureAndHumidity
begin
set sht = none
function __init__ self
begin
string Initialize the class by setting sht variable to obtain the I2C pins which contain the SHT40
set sht = call SHT4x call I2C
end function
function getTemp... | import time
import board
import adafruit_sht4x
from conversions import Conversions
class TemperatureAndHumidity:
sht = None
def __init__(self):
"""Initialize the class by setting sht variable to obtain
the I2C pins which contain the SHT40
"""
self.sht = adafruit_sht4x.SHT4x... | Python | zaydzuhri_stack_edu_python |
function ot_ul2_solve_BFGS C a b reg maxiter=100000 tol=1e-14
begin
comment define objective function f
function f G
begin
set G = reshape G tuple shape at 0 shape at 0
return sum G * C + reg * sum sum 1 - a ^ 2 + reg * sum sum 0 - b ^ 2
end function
comment define the gradient of f
function df G
begin
set G = reshape ... | def ot_ul2_solve_BFGS(C, a, b, reg, maxiter=100000, tol=1e-14):
# define objective function f
def f(G):
G = G.reshape((a.shape[0], b.shape[0]))
return np.sum(G * C) + reg * np.sum((G.sum(1) - a) ** 2) + reg * np.sum((G.sum(0) - b) ** 2)
# define the gradient of f
def df(G):
G =... | Python | nomic_cornstack_python_v1 |
async function list_streams self streams_list_request_body=call Body none description=string
begin
set adapter = call _create_low_code_adapter manifest=manifest
set stream_list_read = list
try
begin
for http_stream in call get_http_streams config
begin
append stream_list_read call StreamsListReadStreams name=name url=... | async def list_streams(self, streams_list_request_body: StreamsListRequestBody = Body(None, description="")) -> StreamsListRead:
adapter = self._create_low_code_adapter(manifest=streams_list_request_body.manifest)
stream_list_read = []
try:
for http_stream in adapter.get_http_stream... | Python | nomic_cornstack_python_v1 |
comment Faça um algoritmo que apenas imprima o seu nome na tela e em seguida finalize a aplicação.
print string Bruno
print
comment Faça um algoritmo que solicite ao usuário digitar o seu nome e em seguida envie a seguinte frase para a saída padrão: "O seu nome é: [nome do usuário]".
set nome = input string Digite o se... | #Faça um algoritmo que apenas imprima o seu nome na tela e em seguida finalize a aplicação.
print("Bruno")
print()
#Faça um algoritmo que solicite ao usuário digitar o seu nome e em seguida envie a seguinte frase para a saída padrão: "O seu nome é: [nome do usuário]".
nome = input("Digite o seu nome")
print("O seu ... | Python | zaydzuhri_stack_edu_python |
function total_seconds cls member_id start=min end=max
begin
set total_seconds = 0
set activities = call get_all member_id start end
if length activities == 0
begin
return total_seconds
end
comment Create dummy start/end activities if search interval split first and/or last voice activity intervals
if status == false
b... | def total_seconds(cls, member_id, start=datetime.min, end=datetime.max):
total_seconds = 0
activities = cls.get_all(member_id, start, end)
if len(activities) == 0:
return total_seconds
# Create dummy start/end activities if search interval split first and/or last voice activi... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed Sep 5 14:31:15 2018 @author: wufan # ============================================================================= # Given a column title as appear in an Excel sheet, return its corresponding column number. # # For example: # # A -> 1 # B -> 2 # C -> 3 # ... # Z -> 26... | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 5 14:31:15 2018
@author: wufan
# =============================================================================
# Given a column title as appear in an Excel sheet, return its corresponding column number.
#
# For example:
#
# A -> 1
# B -> 2
# C -> 3
# ..... | Python | zaydzuhri_stack_edu_python |
function predict_with_preprocessing self df confidence_interval=0.6827
begin
comment pragma: no cover
set tuple pred_mean pred_var = call _predict_transformed_output_with_preprocessing df
set s = call call call Shapes df string DF pred_mean string PM pred_var string PV
set pred_std = square root pred_var
comment Calcul... | def predict_with_preprocessing(
self, df: pd.DataFrame, confidence_interval: float = 0.6827
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: # pragma: no cover
pred_mean, pred_var = self._predict_transformed_output_with_preprocessing(df)
s = Shapes(df, "DF")(pred_mean, "PM")(pred_var, "PV")
... | Python | nomic_cornstack_python_v1 |
comment Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz".
comment For numbers which are multiples of both three and five print "FizzBuzz".
for x in range 1 101
begin
if x % 3 == 0 and x % 5 == 0
begin
print ... | #Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz".
#For numbers which are multiples of both three and five print "FizzBuzz".
for x in range(1,101):
if (x%3==0 and x%5==0):
print("multip... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import numpy as np
import utils
import pymc
comment noqa
from params import *
if __name__ == string __main__
begin
comment load a dataset
set dataset = call load_dataset DATASET_PATH
set observed_xs = dataset at tuple slice : : 0
set observed_ys = dataset at... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import utils
import pymc
from params import * # noqa
if __name__ == '__main__':
# load a dataset
dataset = utils.load_dataset(DATASET_PATH)
observed_xs = dataset[:, 0]
observed_ys = dataset[:, 1]
# plot_ground_truth()
# defin... | Python | zaydzuhri_stack_edu_python |
import itertools
import numpy as np
import seaborn as sns
set style=string white color_codes=true
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
import argparse
set parser = call ArgumentParser description=string Multilingual BERT Evaluation Analysis
call add_argument string --data ... | import itertools
import numpy as np
import seaborn as sns; sns.set(style="white", color_codes=True)
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
import argparse
parser = argparse.ArgumentParser(description='Multilingual BERT Evaluation Analysis')
parser.add_argument('--data', ... | Python | zaydzuhri_stack_edu_python |
function clone self destination=none
begin
if destination is not none
begin
set destination = destination
end
end function | def clone(self, destination=None):
if destination is not None:
self.destination = destination
| Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- encoding: utf-8 -*-
from optparse import OptionParser
from menu import Menu
class Main
begin
function __init__ self
begin
set parser = call OptionParser
call add_option string -f string --fix dest=string fix action=string store_true help=string Fix the configuration file if it c... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from optparse import OptionParser
from menu import Menu
class Main:
def __init__(self):
parser = OptionParser()
parser.add_option("-f", "--fix", dest="fix",
action="store_true", help="Fix the configuration file if it contains error.")
parser.add_option("-e",... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
import bs4
import pickle
import urllib.request
function mac_data ipv4 result_list
begin
set header = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586
set url = string http://apps.neu.edu.cn/macquery/?mac= + ipv4
set request = cal... | # coding=utf-8
import bs4
import pickle
import urllib.request
def mac_data(ipv4, result_list):
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586'
}
url = 'http://apps.neu.edu.cn/macquery/?mac=' + ipv4
request = urllib.request.R... | Python | zaydzuhri_stack_edu_python |
function get_data_base arr
begin
set base = arr
while is instance base ndarray
begin
set base = base
end
return base
end function | def get_data_base(arr):
base = arr
while isinstance(base.base, np.ndarray):
base = base.base
return base | Python | nomic_cornstack_python_v1 |
function simulate_movement self x n affine_matrices=none
begin
set tuple c h w = size x
comment Create a Tensor with n affine transformations. random_affine \in (n_frames, 3, 3)
if affine_matrices is none
begin
set affine_matrices = list comprehension call random_affine for _ in range n - 1
set affine_matrices = affine... | def simulate_movement(self, x, n, affine_matrices=None):
c, h, w = x.size()
# Create a Tensor with n affine transformations. random_affine \in (n_frames, 3, 3)
if affine_matrices is None:
affine_matrices = [self.random_affine() for _ in range(n - 1)]
affine_matrices = af... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
class Solution
begin
function countPrimers self n
begin
string :param n: int :return: int
if n < 3
begin
return 0
end
set prime = list true * n
set prime at 0 = false
set prime at 1 = false
for i in range 2 integer n ^ 0.5 + 1
begin
if prime at i == 1
begin
set prime at slice i * i : n : i = list f... | # coding=utf-8
class Solution:
def countPrimers(self, n):
"""
:param n: int
:return: int
"""
if n < 3:
return 0
prime = [True] * n
prime[0] = prime[1] = False
for i in range(2, int(n ** 0.5) +1):
if prime[i] == 1:
... | Python | zaydzuhri_stack_edu_python |
function __init__ self n q_mean=0.5 ada_freq=none q_max=none
begin
assert 0 <= q_mean <= 1.0 msg string Expectation of each query, q_mean, should be in [0.0, 1.0].
set n = n
set q_mean = q_mean
if ada_freq is none
begin
set ada_freq = dict string method string additive ; string method_param 100
end
comment Calculating ... | def __init__(self, n, q_mean=0.5, ada_freq=None, q_max=None):
assert 0 <= q_mean <= 1.0, "Expectation of each query, q_mean, should be in [0.0, 1.0]."
self.n = n
self.q_mean = q_mean
if ada_freq is None:
ada_freq = {"method": "additive", "method_param": 100}
s... | Python | nomic_cornstack_python_v1 |
function stats message
begin
set urls = length message at string urls
set urls_success = length list comprehension u for u in message at string urls if get u string doc
set all_sentences = list chain *(u['sentences'] for u in message['urls'])
set frds = length list comprehension s for s in all_sentences if get s string... | def stats(message):
urls = len(message['urls'])
urls_success = len([u for u in message['urls'] if u.get('doc')])
all_sentences = list(chain(*(u['sentences'] for u in message['urls'])))
frds = len([s for s in all_sentences if s.get('frd') > config.min_frd_prob])
crawl_date = datetime.strptime(message... | Python | nomic_cornstack_python_v1 |
function infer_pattern_nodes self
begin
comment String conversions:
set pos_var = lambda u pos -> string u_%d_%d_%d_%d % tuple u x y i
set pat_pos_var = lambda u pos -> string u_%d_%d % tuple u i
set pat_pos_assigns = dict
for u_obj in nodes
begin
set u = u
set pos_dict = dict
update pat_pos_assigns dict u string
for... | def infer_pattern_nodes(self):
#String conversions:
pos_var = lambda u, pos : "u_%d_%d_%d_%d" % (u, pos.x, pos.y, pos.i)
pat_pos_var = lambda u, pos : "u_%d_%d" % (u, pos.i)
pat_pos_assigns = {}
for u_obj in self.nodes:
u = u_obj.u
pos_dict = {}... | Python | nomic_cornstack_python_v1 |
import shapefile as sh
from pprint import pprint
comment Read ShapeFile Folder to create a Reader Obj
comment sf = sh.Reader("escolas_detim/equipamentos_escolares_novo")
set sf = reader string escolas_wg8/Escolas_novo
print string Equipamentos Escolares -> Fields
call pprint fields
print string Quantidade de Escolas ->... | import shapefile as sh
from pprint import pprint
# Read ShapeFile Folder to create a Reader Obj
# sf = sh.Reader("escolas_detim/equipamentos_escolares_novo")
sf = sh.Reader("escolas_wg8/Escolas_novo")
print("Equipamentos Escolares -> Fields \n")
pprint(sf.fields)
print("\n \n \n Quantidade de Escolas -> Records \n")... | Python | zaydzuhri_stack_edu_python |
function jacobian self t x u w
begin
set a = u at 0
set theta = x at 2
set v = x at 3
set fx = array list list 0 0 0 0 list 0 0 0 0 list - v * sin theta v * cos theta 0 0 list cos theta sin theta 0 0
set fu = array list list 0 0 0 1 list 0 0 1 0
set w = w * w_scale
set fw = array list list cos theta - sin theta 0 0 lis... | def jacobian(self, t, x, u, w):
a= u[0]
theta = x[2]
v = x[3]
fx = np.array([[0, 0, 0, 0],
[0, 0, 0, 0],
[-v*np.sin(theta), v*np.cos(theta), 0, 0],
[np.cos(theta), np.sin(theta), 0, 0]])
fu = np.array([[0, 0, 0,... | Python | nomic_cornstack_python_v1 |
string Given a sorted array arr[] of distinct elements which is rotated at some unknown point, the task is to find the maximum element in it. Examples: Input: arr[] = {3, 4, 5, 1, 2} Output: 5 Input: arr[] = {1, 2, 3} Output: 3 Approach: A simple solution is to traverse the complete array and find maximum. This solutio... | """
Given a sorted array arr[] of distinct elements which is rotated at some unknown point, the task is to find the maximum element in it.
Examples:
Input: arr[] = {3, 4, 5, 1, 2}
Output: 5
Input: arr[] = {1, 2, 3}
Output: 3
Approach: A simple solution is to traverse the complete array and find maximum. This solut... | Python | zaydzuhri_stack_edu_python |
import numpy as np
comment import matplotlib.pyplot as plt
from numbers import Number as _num
function product seq
begin
set ans = 1
for s in seq
begin
set ans = ans * s
end
return ans
end function
function zero_pad seq length
begin
return list seq + list 0 * max 0 length - length seq
end function
function init_poly_va... | import numpy as np
# import matplotlib.pyplot as plt
from numbers import Number as _num
def product(seq):
ans = 1
for s in seq:
ans *= s
return ans
def zero_pad(seq, length):
return list(seq)+[0]*(max(0, length-len(seq)))
def init_poly_vars(variables):
return [Polynomial([v],[(1,[1])])... | Python | zaydzuhri_stack_edu_python |
comment Author - Dr. Steven Novotny, @stevenjnovotny
comment Contributer - C1C Jonathan Nash, @JonathanNash21
comment Last Updated - 20 Apr 2021
comment Brief - Takes in an image(s) or video stream and passes that information to an AI which will look for
comment vehicles and encloses found vehicles in a unique bounding... | #########################################################################################################
# Author - Dr. Steven Novotny, @stevenjnovotny
# Contributer - C1C Jonathan Nash, @JonathanNash21
# Last Updated - 20 Apr 2021
# Brief - Takes in an image(s) or video stream and passes that information to an AI whi... | Python | zaydzuhri_stack_edu_python |
import metr
import unittest
class MetrTest extends TestCase
begin
function testEmpty self
begin
assert equal call Stat 0 0 call metr string class X {}
end function
function testSingleMethod self
begin
set stat = call metr string class X { void x() { return; } }
assert equal call Stat 1 0 stat
end function
function test... | import metr
import unittest
class MetrTest(unittest.TestCase):
def testEmpty(self):
self.assertEqual(metr.Stat(0, 0), metr.metr('class X {}'))
def testSingleMethod(self):
stat = metr.metr('''class X {
void x() {
return;
}
}''')
self.assertEqual(metr.Stat(1,0), stat)
def testI... | Python | zaydzuhri_stack_edu_python |
string Script to handle Zane related Math calculations Arguments for mod: [Death Follows Close, Kill Skill Stacks, Active Action Skills, Movement Speed Over Base] @author Prismatic
function skillsSpec skills mods gear
begin
from utils import calcMain
comment Doubled Agent
set synchronicity = skills at 0
set donnybrook ... | """
Script to handle Zane related Math calculations
Arguments for mod: [Death Follows Close, Kill Skill Stacks, Active Action Skills, Movement Speed Over Base]
@author Prismatic
"""
def skillsSpec(skills, mods, gear):
from utils import calcMain
# Doubled Agent
synchronicity = skills[0]
donnybrook = ... | Python | zaydzuhri_stack_edu_python |
function testAbandonQueuedTasks self
begin
set manager = call TaskManager
set test_tasks = list comprehension call CreateTask _TEST_SESSION_IDENTIFIER for _ in range 2
for task in test_tasks
begin
assert is not none start_time
end
assert equal length _tasks_queued 2
assert equal length _tasks_processing 0
assert equal ... | def testAbandonQueuedTasks(self):
manager = task_manager.TaskManager()
test_tasks = [
manager.CreateTask(self._TEST_SESSION_IDENTIFIER) for _ in range(2)]
for task in test_tasks:
self.assertIsNotNone(task.start_time)
self.assertEqual(len(manager._tasks_queued), 2)
self.assertEqual(l... | Python | nomic_cornstack_python_v1 |
function test_get_file
begin
set tu = call get_tu string int foo();
set f = call get_file string t.c
assert is instance f File
assert name == string t.c
try
begin
set f = call get_file string foobar.cpp
end
except any
begin
pass
end
try else
begin
assert false
end
end function | def test_get_file():
tu = get_tu('int foo();')
f = tu.get_file('t.c')
assert isinstance(f, File)
assert f.name == 't.c'
try:
f = tu.get_file('foobar.cpp')
except:
pass
else:
assert False | Python | nomic_cornstack_python_v1 |
function _adjust_router_list_for_global_router self routers
begin
string Pushes 'Global' routers to the end of the router list, so that deleting default route occurs before deletion of external nw subintf
comment ToDo(Hareesh): Simplify if possible
for r in routers
begin
if r at ROUTER_ROLE_ATTR == ROUTER_ROLE_GLOBAL
b... | def _adjust_router_list_for_global_router(self, routers):
"""
Pushes 'Global' routers to the end of the router list, so that
deleting default route occurs before deletion of external nw subintf
"""
#ToDo(Hareesh): Simplify if possible
for r in routers:
if r[RO... | Python | jtatman_500k |
function is_armstrong_number num
begin
comment Calculate the number of digits
set n = length string num
comment Check whether is an armstrong number
set sum = 0
set temp = num
while temp > 0
begin
set digit = temp % 10
set sum = sum + digit ^ n
set temp = temp // 10
end
if num == sum
begin
return true
end
else
begin
re... | def is_armstrong_number(num):
# Calculate the number of digits
n = len(str(num))
# Check whether is an armstrong number
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
if num == sum:
return True
else:
... | Python | flytech_python_25k |
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import tkinter.ttk as ttk
import pickle
from search_win import search_win
from stats_win import stats_win
from info_win import info_win
import time
from find_student_and_analysis import analysis_finding_win
from find_student_and_analysis... | import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import tkinter.ttk as ttk
import pickle
from search_win import search_win
from stats_win import stats_win
from info_win import info_win
import time
from find_student_and_analysis import analysis_finding_win
from find_student_and_analysis... | Python | zaydzuhri_stack_edu_python |
function load_models self path=none model_name=string read_grains=false mod_list=none n_models=none **kwargs
begin
if mod_list is none
begin
set mod_list = glob format string {0}{1} path model_name + string *.out
if mod_list is not none
begin
set mod_list = mod_list at slice 0 : n_models :
end
set mod_list = list dif... | def load_models(self, path=None, model_name="", read_grains=False, mod_list=None, n_models=None, **kwargs):
if mod_list is None:
mod_list = glob('{0}{1}'.format(path, model_name) + '*.out')
if mod_list is not None:
mod_list = mod_list[0:n_models]
mod_list = l... | Python | nomic_cornstack_python_v1 |
function getValBoxIdxs self sort
begin
set sort_boxes = _sort_boxes_list at sort
return sort_boxes at slice _nTrain : _nTrain + _nValid :
end function | def getValBoxIdxs(self, sort):
sort_boxes = self._sort_boxes_list[sort]
return sort_boxes[self._nTrain:self._nTrain+self._nValid] | Python | nomic_cornstack_python_v1 |
function cli_arguments
begin
set parser = call ArgumentParser formatter_class=RawDescriptionHelpFormatter usage=string { DETAIL } pdforce.py [-p <pdf>] [-w <wordlist>] [-e <encoding>] [-o <output>] [-c] [-h/--help] { END } description=string { EMPHASIS } { TITLE } Lightweight PDF password cracker. USE FOR LEGAL INTENTS... | def cli_arguments():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
usage=f"\n{Color.DETAIL}pdforce.py [-p <pdf>] [-w <wordlist>] [-e <encoding>] [-o <output>] [-c] [-h/--help]{Color.END}",
description=f"{Color.EMPHASIS}{TITLE}\nLightweight PDF passw... | Python | nomic_cornstack_python_v1 |
function service_notifications self
begin
comment Step 1: Look at existing notifications
if length _active_notifications > 0
begin
info string active notifications: %d % length _active_notifications
comment We have active notifications, let's check on their statuses
set my_notif_index = 0
while my_notif_index < length ... | def service_notifications(self):
# Step 1: Look at existing notifications
if len(self._active_notifications) > 0:
logger.info("active notifications: %d" % len(self._active_notifications))
# We have active notifications, let's check on their statuses
my_notif_index = ... | Python | nomic_cornstack_python_v1 |
import os
import sys
import errno
import select
import socket
class Client extends object
begin
function __init__ self my_username IP=string 127.0.0.1 PORT=1234
begin
set my_username = my_username
set HEADER_LENGTH = 10
set client_socket = call socket AF_INET SOCK_STREAM
call connect tuple IP PORT
call setblocking fals... | import os
import sys
import errno
import select
import socket
class Client(object):
def __init__(self, my_username, IP="127.0.0.1", PORT=1234):
self.my_username = my_username
self.HEADER_LENGTH = 10
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client... | Python | zaydzuhri_stack_edu_python |
function join self property_path alias
begin
if not alias != alias and alias not in _join_map
begin
raise call KeyError string The alias of the joined entity must be unique.
end
set _join_map at alias = dict string path property_path ; string class none ; string mapper none
end function | def join(self, property_path, alias):
if not (alias != self.alias and alias not in self._join_map):
raise KeyError('The alias of the joined entity must be unique.')
self._join_map[alias] = {
'path': property_path,
'class': None,
'mapper': None
... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
import pandas as pd
set obj = read csv string e:/Building_Permits.csv low_memory=false
set attr = list
for item in columns
begin
set n = value counts obj at item
if count n < 100
begin
append attr item
print item count n
end
end
set df = obj at attr
to csv df string e:/test.csv index=false header=... | # coding=utf-8
import pandas as pd
obj = pd.read_csv("e:/Building_Permits.csv",low_memory=False)
attr=[]
for item in obj.columns:
n = obj[item].value_counts()
if n.count() < 100:
attr.append(item)
print(item,n.count())
df = obj[attr]
df.to_csv("e:/test.csv",index=False,head... | Python | zaydzuhri_stack_edu_python |
function __init__ self *args **kwargs
begin
set full_image_accessor = call FullImageAccessor self spec
set full_image = full_image_accessor
return call __init__ *args keyword kwargs
end function | def __init__(self, *args, **kwargs):
full_image_accessor = FullImageAccessor(self, self.full_image.spec)
self.full_image = full_image_accessor
return super(ImageBase, self).__init__(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
function _del_item self layer pos
begin
assert layer in keys
del data at layer at pos
end function | def _del_item(self, layer, pos):
assert layer in self.keys
del self.data[layer][pos] | Python | nomic_cornstack_python_v1 |
import base64
import json
import re
from sre_parse import ESCAPES
from google.cloud import secretmanager
from random import choice
import string
from google.cloud.sql.connector import Connector
import sqlalchemy
set PROJECT_ID = string project_id
set SECRET_ID = string secret_id
comment Atualização secret
set tamanho_d... | import base64
import json
import re
from sre_parse import ESCAPES
from google.cloud import secretmanager
from random import choice
import string
from google.cloud.sql.connector import Connector
import sqlalchemy
PROJECT_ID = "project_id"
SECRET_ID = "secret_id"
###Atualização secret
tamanho_da_senha = 10
caractere... | Python | zaydzuhri_stack_edu_python |
while true
begin
set sum = sum + n % 10
set n = n // 10
if not n > 0
begin
break
end
end
print sum | while True:
sum = sum + (n % 10)
n = n // 10
if not n > 0:
break
print(sum)
| 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.