code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
print string What is Your Name ? set myName = input print string Hellloo + myName + string Nice to meet you + string length myName print string What is your age ? set nyAge = input print string You will be + string integer nyAge
print('What is Your Name ?') myName = input() print('Hellloo ' + myName + ' Nice to meet you ' + str(len(myName))) print('What is your age ?') nyAge = input(); print('You will be ' +str(int(nyAge)))
Python
zaydzuhri_stack_edu_python
comment Sets / conjuntos set s1 = set comment Requiere llaves para asignar valores set s1 = set literal 1 2 3 4 5 6 7 8 add s1 550 print s1 set s2 = set literal string hola string mundo string hola string mundo string hola string mundo update s1 s2 print s1 set lista_repetidos = list 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 ...
#Sets / conjuntos s1 = set() #Requiere llaves para asignar valores s1= {1,2,3,4,5,6,7,8} s1.add(550) print(s1) s2= {"hola", "mundo", "hola", "mundo","hola", "mundo"} s1.update(s2) print(s1) lista_repetidos=[1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10] conjunto_resultado=set(lista_repetidos) print(conjunto_resulta...
Python
zaydzuhri_stack_edu_python
function generate_voting_ensemble file begin print string -------> Generating voting ensemble report... comment Get file name set file_name = split string file string . at 0 comment Get all files in the directory set results = list directory all_results_path comment Combine all results into one dataframe set list_of_fr...
def generate_voting_ensemble(file): print('-------> Generating voting ensemble report...') file_name = str(file).split('.')[0] # Get file name # Get all files in the directory results = os.listdir(all_results_path) # Combine all results into one dataframe list_of_frames = [] for filenam...
Python
nomic_cornstack_python_v1
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Category , Base , Item , User set engine = call create_engine string sqlite:///catalog.db comment Bind the engine to the metadata of the Base class so that the comment declaratives can be accessed through a DBSession...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Category, Base, Item, User engine = create_engine('sqlite:///catalog.db') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bi...
Python
zaydzuhri_stack_edu_python
function test_api_video_bulk_delete_by_organization_admin self begin set user = call UserFactory set organization = call OrganizationFactory call OrganizationAccessFactory role=ADMINISTRATOR organization=organization user=user set playlist = call PlaylistFactory organization=organization set video1 = call VideoFactory ...
def test_api_video_bulk_delete_by_organization_admin(self): user = factories.UserFactory() organization = factories.OrganizationFactory() factories.OrganizationAccessFactory( role=models.ADMINISTRATOR, organization=organization, user=user ) playlist = factories.Playli...
Python
nomic_cornstack_python_v1
import csv import random function randomMAC begin set mac = list 0 22 62 random integer 0 127 random integer 0 255 random integer 0 255 return join string : map lambda x -> string %02x % x mac end function with open string hostnames.csv string w as host_csvfile begin set fieldnames = list string ip string host set host...
import csv import random # def randomMAC(): mac = [ 0x00, 0x16, 0x3e, random.randint(0x00, 0x7f), random.randint(0x00, 0xff), random.randint(0x00, 0xff) ] return ':'.join(map(lambda x: "%02x" % x, mac)) # with open('hostnames.csv', 'w') as host_csvfile: fieldnames = ['ip', 'host'] host_writer = csv.Dic...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3.7 import os import math function print_pi begin set pi = pi set digits = call getenv string DIGITS if digits begin set digits = integer digits end else begin set digits = 10 end print string %.*f % tuple digits pi end function call print_pi
#!/usr/bin/env python3.7 import os import math def print_pi(): pi = math.pi digits = os.getenv("DIGITS") if digits: digits = int(digits) else: digits = 10 print("%.*f" % (digits, pi)) print_pi()
Python
zaydzuhri_stack_edu_python
set airTemp = decimal input string Please enter an air temperature: set windSpeed = decimal input string Please enter the corresponding wind speed: set WCI = 13.12 + 0.6215 * airTemp - 11.37 * windSpeed ^ 0.16 + 0.3965 * airTemp * windSpeed ^ 0.16 print format string The WCI (Wind Chill Index) is {}. WCI
airTemp = float(input("Please enter an air temperature: ")) windSpeed = float(input("Please enter the corresponding wind speed: ")) WCI = 13.12 + (0.6215*airTemp) - (11.37*(windSpeed**0.16)) + (0.3965*airTemp*(windSpeed**0.16)) print("The WCI (Wind Chill Index) is {}.".format(WCI))
Python
zaydzuhri_stack_edu_python
function edge_exists self id1 id2 begin if id1 in edge_map and id2 in edge_map at id1 begin return true end if id2 in edge_map and id1 in edge_map at id2 begin return true end return false end function
def edge_exists(self, id1, id2): if id1 in self.edge_map and id2 in self.edge_map[id1]: return True if id2 in self.edge_map and id1 in self.edge_map[id2]: return True return False
Python
nomic_cornstack_python_v1
function _parse_json self response exactly_one=true begin string Parse responses as JSON objects. if not length response begin return none end if exactly_one begin return call _format_structured_address response at 0 end else begin return list comprehension call _format_structured_address c for c in response end end fu...
def _parse_json(self, response, exactly_one=True): """ Parse responses as JSON objects. """ if not len(response): return None if exactly_one: return self._format_structured_address(response[0]) else: return [self._format_structured_addr...
Python
jtatman_500k
string Author: Shuhu Hao organization: bingoyes Project: Python Study software: PyCharm comment 用def定义,pass占位 comment 调用函数在函数后面 comment def info(a,b,c): comment print('I am info') comment d = a+ b+c comment return d comment print(info(1,2,3),'aa','bbb') comment def test(): comment pass comment def sum1(*num): comment a...
''' Author: Shuhu Hao organization: bingoyes Project: Python Study software: PyCharm ''' # 用def定义,pass占位 # 调用函数在函数后面 # def info(a,b,c): # print('I am info') # d = a+ b+c # return d # print(info(1,2,3),'aa','bbb') # def test(): # pass # def sum1(*num): # add = 0 # for e in num: # ...
Python
zaydzuhri_stack_edu_python
function get_input_data_tensors reader data_pattern batch_size num_readers=1 begin with call name_scope string input begin set files = glob gfile data_pattern if not files begin raise call IOError string Unable to find input files. data_pattern=' + data_pattern + string ' end info string number of input files: + string...
def get_input_data_tensors(reader, data_pattern, batch_size, num_readers=1): with tf.name_scope("input"): files = gfile.Glob(data_pattern) if not files: raise IOError("Unable to find input files. data_pattern='" + data_pattern + "'") logging.info("number of input files: " + str(l...
Python
nomic_cornstack_python_v1
comment Given 2 sorted arrays merge them into one array comment [1, 3, 4, 6, 7, 8], [2, 5, 9, 12, 15, 25, 99] comment Method 1 : function merge_arrays arr1 arr2 begin comment combine lists set merged_list = arr1 + arr2 comment used pythons built in to sort the list sort merged_list comment returnn the merged sorted lis...
# Given 2 sorted arrays merge them into one array # [1, 3, 4, 6, 7, 8], [2, 5, 9, 12, 15, 25, 99] # Method 1 : def merge_arrays(arr1, arr2): merged_list = (arr1 + arr2) # combine lists merged_list.sort() # used pythons built in to sort the list return merged_list # returnn the merged sorted list # Met...
Python
zaydzuhri_stack_edu_python
import math import random from mesa import Agent , Model from mesa.space import MultiGrid from mesa.time import RandomActivation from mesa.datacollection import DataCollector from collections import namedtuple import typing set Point = named tuple string Point string x y set PotentialMove = named tuple string Potential...
import math import random from mesa import Agent, Model from mesa.space import MultiGrid from mesa.time import RandomActivation from mesa.datacollection import DataCollector from collections import namedtuple import typing Point = namedtuple('Point', 'x y') PotentialMove = namedtuple("PotentialMove", ["pos...
Python
zaydzuhri_stack_edu_python
import sys import time import re import os import shutil import zipfile function findSpecial begin string this function searches whole computers memory to find and print files name and location of files names are from the form - [any combination of symbols]__[any combination of symbols]__ .[any postfix] comment this la...
import sys import time import re import os import shutil import zipfile def findSpecial(): """ this function searches whole computers memory to find and print files name and location of files names are from the form - [any combination of symbols]__[any combination of symbols]__ .[any postfix] """ ...
Python
zaydzuhri_stack_edu_python
function elu x y alpha=1.0 kernel_name=string elu begin set shape_input = get x string shape set dtype_input = get x string dtype set input_dtype = lower dtype_input call check_kernel_name kernel_name call check_shape_rule shape_input call check_shape_size shape_input SHAPE_SIZE_LIMIT set check_list = tuple string floa...
def elu(x, y, alpha=1.0, kernel_name="elu"): shape_input = x.get("shape") dtype_input = x.get("dtype") input_dtype = dtype_input.lower() util.check_kernel_name(kernel_name) util.check_shape_rule(shape_input) util.check_shape_size(shape_input, SHAPE_SIZE_LIMIT) check_list = ("float16", "fl...
Python
nomic_cornstack_python_v1
function can_sum target_sum array memo=dict begin if target_sum in memo begin return memo at target_sum end else if target_sum == 0 begin return true end else if target_sum < 0 begin return false end for num in array begin set remainder = target_sum - num if call can_sum remainder array memo == true begin set memo at t...
def can_sum(target_sum, array, memo={}): if target_sum in memo: return memo[target_sum] elif target_sum == 0: return True elif target_sum < 0: return False for num in array: remainder = target_sum - num if can_sum(remainder, array, memo) == True: memo...
Python
zaydzuhri_stack_edu_python
function update_and_calc_output alpha input_set weights_old theta num_of_iterations begin comment d = 0 for _ in range num_of_iterations begin for iris in input_set begin set d = d set y = call calc_output weights_old iris theta set theta = call update_weights_and_theta d y alpha iris weights_old theta end end return t...
def update_and_calc_output(alpha, input_set, weights_old, theta, num_of_iterations): # d = 0 for _ in range(num_of_iterations): for iris in input_set: d = iris.d y = calc_output(weights_old, iris, theta) theta = update_weights_and_theta(d, y, alpha, iris, weights_old,...
Python
nomic_cornstack_python_v1
string The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? from util.functions import getfactors function run begin set m = 600851475143 return max call getfactors n=m end function if __name__ == string __main__ begin print run end
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ from util.functions import getfactors def run() -> int: m = 600851475143 return max( getfactors( n = m )) if __name__ == '__main__': print( run())
Python
zaydzuhri_stack_edu_python
comment 给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。 comment 示例 1: comment 输入: [2,3,-2,4] comment 输出: 6 comment 解释: 子数组 [2,3] 有最大乘积 6。 comment 示例 2: comment 输入: [-2,0,-1] comment 输出: 0 comment 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 comment Related Topics 数组 动态规划 comment 👍 829 👎 0 comment leetcode submit reg...
# 给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。 # # # # 示例 1: # # 输入: [2,3,-2,4] # 输出: 6 # 解释: 子数组 [2,3] 有最大乘积 6。 # # # 示例 2: # # 输入: [-2,0,-1] # 输出: 0 # 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 # Related Topics 数组 动态规划 # 👍 829 👎 0 # leetcode submit region begin(Prohibit modification and ...
Python
zaydzuhri_stack_edu_python
function _parse_caps_bank bank begin string Parse the <bank> element of the connection capabilities XML. set result = dict string id integer get bank string id ; string level integer get bank string level ; string type get bank string type ; string size format string {} {} get bank string size get bank string unit ; st...
def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': ba...
Python
jtatman_500k
function get_db_table is_admin begin if is_admin begin set db_file = predicted_actions_db end else begin set db_file = dot_t_system_dir + string /actions.json end set db = call TinyDB db_file return call table string scenarios end function
def get_db_table(is_admin): if is_admin: db_file = predicted_actions_db else: db_file = dot_t_system_dir + "/actions.json" db = TinyDB(db_file) return db.table("scenarios")
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment -*- coding: utf-8 -*- function Print msg lvl=- 1 filename=none begin if lvl < 0 begin set res = msg end else if lvl == 0 begin set res = string ---> %s % msg end else begin set res = string ---> for i in call xrange lvl - 1 begin set res = string ---!%s % res end set res = string %...
#! /usr/bin/env python # -*- coding: utf-8 -*- def Print(msg, lvl=-1, filename=None): if lvl < 0: res = msg elif lvl == 0: res = "---> %s" % msg else: res = "--->" for i in xrange(lvl - 1): res = "---!%s" % res res = "%s %s" % (res, msg)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python set divisions = 2 comment it is 3 for part 1 set spaces = 4 function give_combination packets begin set total = 0 set groups = dict set final_groups = dict set weights = dict 1 0 ; 2 0 for p in packets begin set total = total + p set groups at p = 1 set weights at 1 = weights at 1 + p set fin...
#!/usr/bin/python divisions = 2 spaces = 4 # it is 3 for part 1 def give_combination(packets): total = 0 groups = {} final_groups = {} weights = {1: 0, 2: 0} for p in packets: total += p groups[p] = 1 weights[1] += p final_groups[p] = divisions total /= spaces min_packets = 0 no_mor...
Python
zaydzuhri_stack_edu_python
function ub_to_str string begin string converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) if not is instance string str begin if PY2 begin return string string end else begin return decode string end end return string end function
def ub_to_str(string): """ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) """ if not isinstance(string, str): if six.PY2: return str(string) else: return st...
Python
jtatman_500k
function verify self begin return __verify end function
def verify(self): return self.__verify
Python
nomic_cornstack_python_v1
import numpy as np from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib.patches import FancyArrowPatch set fig = figure set ax = call add_subplot 111 projection=string 3d set tuple X Y = mgrid at tuple slice - 1 : 1 : 30j slice - 1 : 1 : 30j set Z = X ^ 2 + Y ^ 2 + 1 call plot_surface...
import numpy as np from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib.patches import FancyArrowPatch fig = plt.figure() ax = fig.add_subplot(111, projection="3d") X, Y = np.mgrid[-1:1:30j, -1:1:30j] Z = X**2+Y**2 + 1 ax.plot_surface(X, Y, Z, cmap="Greens_r", lw=0, rstride=2, cstrid...
Python
zaydzuhri_stack_edu_python
function set_src_dst_tensor self tik_instance begin set src_element_number = call functools_reduce lambda x1 x2 -> x1 * x2 src_shape_ori at slice : : set dst_element_number = call functools_reduce lambda x1 x2 -> x1 * x2 dst_shape at slice : : set src_gm = tensor dtype tuple src_element_number name=string src_gm sc...
def set_src_dst_tensor(self, tik_instance): src_element_number = functools_reduce(lambda x1, x2: x1 * x2, self.src_shape_ori[:]) dst_element_number = functools_reduce(lambda x1, x2: x1 * x2, self.dst_shape[:]) ...
Python
nomic_cornstack_python_v1
import math from collections import deque , defaultdict from sys import stdin , stdout set input = readline comment print = stdout.write set listin = lambda -> list map int split input set mapin = lambda -> map int split input for _ in range integer input begin set tuple a b n s = call mapin set rem = s % n if rem > ...
import math from collections import deque, defaultdict from sys import stdin, stdout input = stdin.readline # print = stdout.write listin = lambda : list(map(int, input().split())) mapin = lambda : map(int, input().split()) for _ in range(int(input())): a, b, n, s = mapin() rem = s%n if rem > b: pri...
Python
zaydzuhri_stack_edu_python
function away_points_against self begin return score at 0 end function
def away_points_against(self) -> int: return self.score[0]
Python
nomic_cornstack_python_v1
import json from datetime import datetime , timedelta import requests import os import html import time as t import random import sys function post url begin set new_url = string http://api.scraperapi.com?api_key=e9da48dcd2ce48e993b1b254c5ae8b94&url= + url try begin set response = get requests new_url end except any be...
import json from datetime import datetime, timedelta import requests import os import html import time as t import random import sys def post(url): new_url = 'http://api.scraperapi.com?api_key=e9da48dcd2ce48e993b1b254c5ae8b94&url=' + url try: response = requests.get(new_url) except: print('Connection error') ...
Python
zaydzuhri_stack_edu_python
function profile begin set record = call person call args 0 set form = call SQLFORM person record deletable=true upload=call URL string download if accepted begin comment response.flash = 'form accepted:' + form.vars.name insert person name=name first_name=first_name birthday=birthday end else if errors begin set flash...
def profile(): record = db.person(request.args(0)) form = SQLFORM(db.person, record, deletable=True, upload=URL('download')) if form.process().accepted: #response.flash = 'form accepted:' + form.vars.name db.person.insert(name=form.vars.name, first_name=form.vars.fi...
Python
nomic_cornstack_python_v1
function create_receipt_rule self parent rule_id receipt_rule retry=DEFAULT timeout=DEFAULT metadata=none begin if string create_receipt_rule not in _inner_api_calls begin set _inner_api_calls at string create_receipt_rule = call wrap_method CreateReceiptRule default_retry=retry default_timeout=timeout client_info=_cli...
def create_receipt_rule(self, parent, rule_id, receipt_rule, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, ...
Python
nomic_cornstack_python_v1
function Open self *args **kwargs begin pass end function
def Open(self, *args, **kwargs): pass
Python
nomic_cornstack_python_v1
function test_template_add self begin set domain = call Domain name=string example.com template=domain_template1 reverse_template=reverse_template save set record_count = count record_set set t1_ns2_record = call RecordTemplateFactory type=string NS name=string {domain-name} content=string ns2.{domain-name} domain_temp...
def test_template_add(self): domain = Domain( name='example.com', template=self.domain_template1, reverse_template=self.reverse_template, ) domain.save() record_count = domain.record_set.count() self.t1_ns2_record = RecordTemplateFactory( type=...
Python
nomic_cornstack_python_v1
function addfunctions2new abunch key begin string add functions to a new bunch/munch object set snames = list string BuildingSurface:Detailed string Wall:Detailed string RoofCeiling:Detailed string Floor:Detailed string FenestrationSurface:Detailed string Shading:Site:Detailed string Shading:Building:Detailed string Sh...
def addfunctions2new(abunch, key): """add functions to a new bunch/munch object""" snames = [ "BuildingSurface:Detailed", "Wall:Detailed", "RoofCeiling:Detailed", "Floor:Detailed", "FenestrationSurface:Detailed", "Shading:Site:Detailed", "Shading:Building:...
Python
jtatman_500k
function get_coins begin call __patch return call get_coins end function
def get_coins(): __patch() return local_api.get_coins()
Python
nomic_cornstack_python_v1
function broadcast_axes data=none axis=_Null size=_Null name=none attr=none out=none **kwargs begin return tuple 0 end function
def broadcast_axes(data=None, axis=_Null, size=_Null, name=None, attr=None, out=None, **kwargs): return (0,)
Python
nomic_cornstack_python_v1
function RefreshDiscLearnedInfo self *args **kwargs begin comment type: (*Any, **Any) -> Union[bool, None] set payload = dict string Arg1 href for i in range length args begin set payload at string Arg%s % i + 2 = args at i end for item in items kwargs begin set payload at item at 0 = item at 1 end return call _execute...
def RefreshDiscLearnedInfo(self, *args, **kwargs): # type: (*Any, **Any) -> Union[bool, None] payload = {"Arg1": self.href} for i in range(len(args)): payload["Arg%s" % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import KFold from scipy.optimize import curve_fit comment Import data set and split into predictor variables (receptors, JAKs, SOCS, etc.) and response variables (STATs) comment pM set IFNg_dose = 1...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import KFold from scipy.optimize import curve_fit # Import data set and split into predictor variables (receptors, JAKs, SOCS, etc.) and response variables (STATs) IFNg_dose = 100 # pM Imm...
Python
zaydzuhri_stack_edu_python
function bisection_root number n tolerance=1e-08 begin if number < 0 begin raise call ValueError string Cannot calculate root of a negative number end set low = 0.0 set high = max number 1.0 while high - low > tolerance begin set mid = low + high / 2.0 if mid ^ n > number begin set high = mid end else begin set low = m...
def bisection_root(number, n, tolerance=1e-8): if number < 0: raise ValueError("Cannot calculate root of a negative number") low = 0.0 high = max(number, 1.0) while high - low > tolerance: mid = (low + high) / 2.0 if mid ** n > number: high = mid else: ...
Python
jtatman_500k
import cv2 import numpy as np from skimage import filters from skimage.io import imread import matplotlib.pyplot as plt from skimage.util.shape import view_as_blocks from scipy.spatial.distance import cdist from scipy.ndimage.filters import convolve from skimage.feature import corner_peaks from scipy import signal comm...
import cv2 import numpy as np from skimage import filters from skimage.io import imread import matplotlib.pyplot as plt from skimage.util.shape import view_as_blocks from scipy.spatial.distance import cdist from scipy.ndimage.filters import convolve from skimage.feature import corner_peaks from scipy import signal plt...
Python
zaydzuhri_stack_edu_python
function which program begin function is_exe fpath begin string Determine if program exists and is executable. return is file path fpath and call access fpath X_OK end function set tuple fpath _fname = split path program if fpath begin if call is_exe program begin return program end end else begin for path in split env...
def which(program): def is_exe(fpath): """Determine if program exists and is executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, _fname = os.path.split(program) if fpath: if is_exe(program): return program ...
Python
nomic_cornstack_python_v1
function calcAverage avg1 avg2 avg3 avg4 avg5 avg6 begin set agerage = average1 + average2 + average3 + average4 + average / 5 return average end function function determineGrade userAverage begin if userAverage < 40 begin return string F end else if userAverage < 50 begin return string D end else if userAverage < 60 b...
def calcAverage( avg1, avg2, avg3, avg4, avg5, avg6): agerage = ( average1 + average2 + average3 + average4 + average )/5 return average def determineGrade( userAverage ): if(userAverage <40 ): return "F" elif( userAverage < 50 ): return "D" elif( userAverage < 60 ): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string In this module, the base class BaseModel string Para asignar el valor del atributo id import uuid string Para crear la fecha from datetime import datetime from models import storage class BaseModel begin string Creating the Base class function __init__ self *args **kwargs begin string I...
#!/usr/bin/python3 """ In this module, the base class BaseModel """ """ Para asignar el valor del atributo id """ import uuid """ Para crear la fecha """ from datetime import datetime from models import storage class BaseModel(): """ Creating the Base class """ def __init__(self, *args, **kwargs): "...
Python
zaydzuhri_stack_edu_python
function usefulFunction begin print call uname end function
def usefulFunction(): print(platform.uname())
Python
nomic_cornstack_python_v1
function station_on_map request station_number begin set data_stations = call stations_with_data set station_number = integer station_number set tuple down problem up = call status_lists set station = call get_object_or_404 Station number=station_number set center = call latest_location if center at string latitude is ...
def station_on_map(request, station_number): data_stations = stations_with_data() station_number = int(station_number) down, problem, up = status_lists() station = get_object_or_404(Station, number=station_number) center = station.latest_location() if center['latitude'] is None and center['lon...
Python
nomic_cornstack_python_v1
function setUp self begin setup call super put put end function
def setUp(self) -> None: super().setUp() user_models.LearnerGoalsModel( id=self.USER_1_ID, topic_ids_to_learn=self.TOPIC_IDS, topic_ids_to_master=[] ).put() user_models.LearnerGoalsModel( id=self.USER_2_ID, topic_ids_to_learn=s...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Apr 17 22:49:35 2022 @author: zhen chen @Email: chen.zhen5526@gmail.com MIT Licence. Python version: 3.8 Description: draw bars for the joint chance results with confidence intervals for different scenario size import matplotlib.pyplot as plt import math import numpy ...
# -*- coding: utf-8 -*- """ Created on Sun Apr 17 22:49:35 2022 @author: zhen chen @Email: chen.zhen5526@gmail.com MIT Licence. Python version: 3.8 Description: draw bars for the joint chance results with confidence intervals for different scenario size """ import matplotlib.pyplot as plt import math import n...
Python
zaydzuhri_stack_edu_python
function validate_email email begin set email = string email or string set ok = false set email = strip email or string set parts = split email string @ set ok = length parts == 2 if ok and not parts at 0 and parts at 1 begin set ok = false end else if length parts > 1 begin call validate_domain parts at 1 end if not ...
def validate_email(email): email = str(email or "") ok = False email = (email.strip() or "") parts = email.split("@") ok = (len(parts) == 2) if ok and not (parts[0] and parts[1]): ok = False elif len(parts) > 1: validate_domain(parts[1]) if not ok: raise Valida...
Python
nomic_cornstack_python_v1
function extend a b begin set res = copy a update res b return res end function
def extend(a, b): res = a.copy() res.update(b) return res
Python
nomic_cornstack_python_v1
import re import pandas as pd function cleanDegree s begin return sub string \s*(\w\w)[\.]?(\w)[\.]? string \1.\2. s end function function cleanTitle s begin return sub string (.*)Professor.* string \1Professor s end function function emailDomain s begin set r = search string @(.*) strip s return call group 1 end funct...
import re import pandas as pd def cleanDegree(s): return re.sub('\s*(\w\w)[\.]?(\w)[\.]?', r' \1.\2.', s) def cleanTitle(s): return re.sub('(.*)Professor.*', r'\1Professor', s) def emailDomain(s): r = re.search('@(.*)', s.strip()) return r.group(1) df = pd.read_csv('faculty.csv') df['degree_clea...
Python
zaydzuhri_stack_edu_python
function __init__ self begin comment the gameState dictionary stores the position of each piece set gameState = dictionary for r in range 1 4 begin for c in range 1 4 begin set gameState at tuple r c = _ablank end end comment the blanks show what's left to choose from set blanks = set comprehension v for v in gameState...
def __init__(self): # the gameState dictionary stores the position of each piece self.gameState = dict() for r in range(1,4): for c in range(1,4): self.gameState[r,c] = self._ablank # the blanks show what's left to choose from self.b...
Python
nomic_cornstack_python_v1
function __init__ self battery_size=75 begin set battery_size = battery_size end function
def __init__(self, battery_size=75): self.battery_size = battery_size
Python
nomic_cornstack_python_v1
function set_feed_permissions self feed_permission feed_id begin string SetFeedPermissions. [Preview API] Update the permissions on a feed. :param [FeedPermission] feed_permission: Permissions to set. :param str feed_id: Name or Id of the feed. :rtype: [FeedPermission] set route_values = dict if feed_id is not none be...
def set_feed_permissions(self, feed_permission, feed_id): """SetFeedPermissions. [Preview API] Update the permissions on a feed. :param [FeedPermission] feed_permission: Permissions to set. :param str feed_id: Name or Id of the feed. :rtype: [FeedPermission] """ r...
Python
jtatman_500k
comment Autor: Victor Cerón comment Calcula la velcidad proedio en un viaje set tiempo = integer input string Teclea el tiempo de viaje en horas enteras set distancia = integer input string Teclea la distancia del viaje en km enteros set Velocidad = distancia / tiempo print string La velocidad promedio es: Velocidad st...
# Autor: Victor Cerón # Calcula la velcidad proedio en un viaje tiempo = int(input("Teclea el tiempo de viaje en horas enteras ")) distancia = int(input("Teclea la distancia del viaje en km enteros ")) Velocidad = distancia / tiempo print("La velocidad promedio es:" , Velocidad , "km/h")
Python
zaydzuhri_stack_edu_python
set height = integer input string 身長を入力して下さい: / 100 set weight = integer input string 体重を入力して下さい: set bmi = weight / height ^ 2 print string あなたのBMIは { bmi } です end=string
height = int(input("身長を入力して下さい: ")) / 100 weight = int(input("体重を入力して下さい: ")) bmi = weight / (height ** 2) print(f"あなたのBMIは{bmi:.1f}です", end="")
Python
zaydzuhri_stack_edu_python
function add_numbers *args begin if not all generator expression is instance arg int for arg in args begin raise call ValueError string All arguments must be integers end if not all generator expression - 100 <= arg <= 100 for arg in args begin raise call ValueError string All arguments must be within the range -100 to...
def add_numbers(*args): if not all(isinstance(arg, int) for arg in args): raise ValueError("All arguments must be integers") if not all(-100 <= arg <= 100 for arg in args): raise ValueError("All arguments must be within the range -100 to 100") try: result = sum(args) except ...
Python
jtatman_500k
function result_from_dict result_dict begin if string variances in keys result_dict begin set variances = result_dict at string variances end else begin set variances = none end if string dof in keys result_dict begin set dof = result_dict at string dof end else begin set dof = none end set evaluations = result_dict at...
def result_from_dict(result_dict): if 'variances' in result_dict.keys(): variances = result_dict['variances'] else: variances = None if 'dof' in result_dict.keys(): dof = result_dict['dof'] else: dof = None evaluations = result_dict['evaluations'] method = result_...
Python
nomic_cornstack_python_v1
function test_generate_comparative_plots_box self begin set fig = call generate_comparative_plots string box ValidTypicalData list 1 4 10 11 list string T0 string T1 string T2 string T3 list string Infants string Children string Teens list string b string g string y string x-axis label string y-axis label string Test s...
def test_generate_comparative_plots_box(self): fig = generate_comparative_plots('box', self.ValidTypicalData, [1, 4, 10, 11], ["T0", "T1", "T2", "T3"], ["Infants", "Children", "Teens"], ['b', 'g', 'y'], "x-axis label", "y-axis label", "Test") ax = fig.get_...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import numpy as np import os import sys from torch.utils import data comment JM: added pickle import pickle from tqdm import tqdm function metrics threshold predictions labels label_unmon begin string Computes a range of metrics. For details on the metrics, see, e.g., https://www.cs.kau.se...
#!/usr/bin/env python3 import numpy as np import os import sys from torch.utils import data import pickle # JM: added pickle from tqdm import tqdm def metrics(threshold, predictions, labels, label_unmon): ''' Computes a range of metrics. For details on the metrics, see, e.g., https://www.cs.kau.se/pulls/hot/ba...
Python
zaydzuhri_stack_edu_python
function solution n begin set answer = string while n > 0 begin set tuple n a = divide mod n 3 if a == 0 begin set n = n - 1 end set answer = numbers at a + answer end return answer end function print call solution 12
def solution(n): answer = "" while n > 0: n, a = divmod(n, 3) if a == 0: n -= 1 answer = numbers[a] + answer return answer print(solution(12))
Python
zaydzuhri_stack_edu_python
function test_list_bookings self begin set request = call HttpRequest set test_user = get objects pk=1 set user = test_user set bookings = call list_bookings request set bookings_id = sorted list call values_list string id flat=true set bookings_id_from_fixture = list 1 2 3 6 assert bookings_id == bookings_id_from_fixt...
def test_list_bookings(self): request = HttpRequest() test_user = User.objects.get(pk=1) request.user = test_user bookings = Services().list_bookings(request) bookings_id = sorted(list(bookings.values_list('id', flat=True))) bookings_id_from_fixture = [1, 2, 3, 6] ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import sys call reload sys call setdefaultencoding string utf8 import csv comment import requests comment import multiprocessing from grab import Grab from bs4 import BeautifulSoup from datetime import datetime comment TODO не авторизируется comment def get_html(url, url1, login, password)...
# -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf8') import csv # import requests # import multiprocessing from grab import Grab from bs4 import BeautifulSoup from datetime import datetime # TODO не авторизируется # def get_html(url, url1, login, password): # r = requests.get(url1, auth=(...
Python
zaydzuhri_stack_edu_python
function GetInitialFile begin set LocalOnList = 0 set StringToPass = call GetFileContent set Dictionary = call Hash for i in StringToPass begin set Temp = call AppliesRE i at 0 comment Remove todas as ocorrencias repetidas de um tweet set Temp = list set Temp set Value = integer i at 1 for Word in Temp begin call Inser...
def GetInitialFile(): LocalOnList = 0 StringToPass = GetFileContent() Dictionary = Hash() for i in StringToPass: Temp = AppliesRE(i[0]) Temp = list(set(Temp)) #Remove todas as ocorrencias repetidas de um tweet Value = int(i[1]) for Word in Temp: InsertOnHash(D...
Python
nomic_cornstack_python_v1
function bounding_ellipsoid points pointvol=0.0 begin string Calculate the bounding ellipsoid containing a collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional The minimum volume occupied by a single point. When provided, used ...
def bounding_ellipsoid(points, pointvol=0.): """ Calculate the bounding ellipsoid containing a collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional The minimum volume occupied by a sing...
Python
jtatman_500k
function encode_message_type_value message_type begin set message_types = dict string m-send-req 128 ; string m-send-conf 129 ; string m-notification-ind 130 ; string m-notifyresp-ind 131 ; string m-retrieve-conf 132 ; string m-acknowledge-ind 133 ; string m-delivery-ind 134 return list get message_types message_type 1...
def encode_message_type_value(message_type): message_types = { 'm-send-req': 0x80, 'm-send-conf': 0x81, 'm-notification-ind': 0x82, 'm-notifyresp-ind': 0x83, 'm-retrieve-conf': 0x84, 'm-acknowledge-ind': 0x85, 'm-delivery-ind': ...
Python
nomic_cornstack_python_v1
comment coding:utf-8 comment http://www.cnblogs.com/whatbeg/p/5155524.html import socket comment 创建socket set client = call socket AF_INET SOCK_STREAM comment 建立连接 call connect tuple string 127.0.0.1 10021 print string 客户端:Nancsy-客户端: print string 客户端IP: 127.0.0.1 print string 学号: 2013011023 print string 姓名: 林鹏珊 end=st...
#coding:utf-8 #http://www.cnblogs.com/whatbeg/p/5155524.html import socket #创建socket client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #建立连接 client.connect(("127.0.0.1",10021)) print("客户端:Nancsy-客户端:") print("客户端IP: 127.0.0.1") print("学号: 2013011023") print("姓名: 林鹏珊",end='\n\n') print("**************通信窗口******...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: import numpy as np import pandas as pd comment In[2]: set dados = read csv string microdados_enem_2019_sp.csv sep=string ; encoding=string iso-8859-1 head dados 3 comment In[3]: set dados1 = drop dados columns=list string CO_MUNICIPIO_RESIDENCIA comment ...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd # In[2]: dados = pd.read_csv('microdados_enem_2019_sp.csv', sep=';', encoding='iso-8859-1') dados.head(3) # In[3]: dados1 = dados.drop(columns=['CO_MUNICIPIO_RESIDENCIA']) # In[4]: dados1.head(3) # In[5]: dados1 = d...
Python
zaydzuhri_stack_edu_python
comment dataset = 'small' set dataset = string large set fin = open string A-%s.in % dataset string r set fout = open string A-%s.out % dataset string w function indexOrSize List Item begin try begin return index List Item end except ValueError begin return length List end end function set ncases = integer read line fi...
#dataset = 'small' dataset = 'large' fin = open('A-%s.in' % dataset, 'r') fout = open('A-%s.out' % dataset, 'w') def indexOrSize(List, Item): try: return List.index(Item) except ValueError: return len(List) ncases = int(fin.readline()) for i in range(ncases): case = i+1 nengines = in...
Python
zaydzuhri_stack_edu_python
function resize self begin return get pulumi self string resize end function
def resize(self) -> Optional[str]: return pulumi.get(self, "resize")
Python
nomic_cornstack_python_v1
function getOrganizationConfigTemplateSwitchProfilePorts self organizationId configTemplateId profileId begin set metadata = dict string tags list string switch string configure string configTemplates string profiles string ports ; string operation string getOrganizationConfigTemplateSwitchProfilePorts set resource = s...
def getOrganizationConfigTemplateSwitchProfilePorts(self, organizationId: str, configTemplateId: str, profileId: str): metadata = { 'tags': ['switch', 'configure', 'configTemplates', 'profiles', 'ports'], 'operation': 'getOrganizationConfigTemplateSwitchProfilePorts', } ...
Python
nomic_cornstack_python_v1
function init_network param_def patterns param item_index remove_blank=false begin comment set item weights set weights = call eval_weights patterns param item_index if remove_blank begin comment remove context units that are zero for all items for connect in list string fc string cf begin for tuple region mat in items...
def init_network(param_def, patterns, param, item_index, remove_blank=False): # set item weights weights = param_def.eval_weights(patterns, param, item_index) if remove_blank: # remove context units that are zero for all items for connect in ['fc', 'cf']: for region, mat in weig...
Python
nomic_cornstack_python_v1
comment load all dependencies import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import statsmodels import patsy import time import random from statsmodels.formula.api import ols print string Run a simple OLS regression comment read in the data set d1 = read csv string mtcars.c...
#load all dependencies import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import statsmodels import patsy import time import random from statsmodels.formula.api import ols print("Run a simple OLS regression") #read in the data d1 = pd.read_csv("mtcars.csv") #look at the s...
Python
zaydzuhri_stack_edu_python
import json set __author__ = string kyedidi class Submission begin function __init__ self submission_tuple begin set id = submission_tuple at 0 set manually_verified = submission_tuple at 1 set manually_marked = submission_tuple at 2 set title = submission_tuple at 3 set self_text = submission_tuple at 4 set current_we...
import json __author__ = 'kyedidi' class Submission: def __init__(self, submission_tuple): self.id = submission_tuple[0] self.manually_verified = submission_tuple[1] self.manually_marked = submission_tuple[2] self.title = submission_tuple[3] self.self_text = submission_tuple[4] self.current...
Python
zaydzuhri_stack_edu_python
function server_type self begin return _server_type end function
def server_type(self): return self._server_type
Python
nomic_cornstack_python_v1
function asalto cholo victima tipo begin if victima == string None or victima == none begin return string Patron, me parece que esa persona no existe. end if victima in prohibido or cholo in prohibido begin return string wow :O chico listo end if cholo == victima begin comment Respuesta en caso de autorobo if cholo == ...
def asalto(cholo,victima,tipo): if victima == 'None' or victima == None: return "Patron, me parece que esa persona no existe." if victima in prohibido or cholo in prohibido: return "wow :O chico listo" if cholo == victima: #Respuesta en caso de autorobo if cholo == "Empl...
Python
nomic_cornstack_python_v1
from urllib.request import urlopen from bs4 import BeautifulSoup function getData begin set url = string https://blogtienao.com/tien-ao/bitcoin/ set conn = url open url set raw_data = read conn set text = decode raw_data string utf8 set soup = call BeautifulSoup text string html.parser comment div = soup.find_all('div'...
from urllib.request import urlopen from bs4 import BeautifulSoup def getData(): url = "https://blogtienao.com/tien-ao/bitcoin/" conn = urlopen(url) raw_data = conn.read() text = raw_data.decode('utf8') soup = BeautifulSoup(text, "html.parser") # div = soup.find_all('div', 'item-details') # ...
Python
zaydzuhri_stack_edu_python
comment Prosze zaimplementowac algorytm QuickSort bez uzycia rekurencji (ale mozna wykorzystac comment własny stos). function partition A left right begin set elem = A at right set i = left for j in range left right begin if A at j <= elem begin set tuple A at j A at i = tuple A at i A at j set i = i + 1 end end set tu...
# Prosze zaimplementowac algorytm QuickSort bez uzycia rekurencji (ale mozna wykorzystac # własny stos). def partition(A, left, right): elem = A[right] i = left for j in range(left, right): if A[j] <= elem: A[j], A[i] = A[i], A[j] i += 1 A[i], A[right] = A[righ...
Python
zaydzuhri_stack_edu_python
function display self begin set rows = list tuple display length views set tuple fig axes = call subplots 1 length views figsize=call _figsize rows squeeze=true for tuple ax view in zip call ravel views begin image show display axis string off call set_visible false call set_visible false set title=id end tight layout ...
def display(self): rows = [(self.views[0].display, len(self.views))] fig, axes = plt.subplots(1, len(self.views), figsize=self._figsize(rows), squeeze=True) for ax, view in zip(axes.ravel(), self.views): ax.imshow(view...
Python
nomic_cornstack_python_v1
function train self optim training_set max_epochs=10 hooks=list l2=0.0 clip=none clip_op=clip_by_value device=string /cpu:0 begin assert is_train msg string Reader has to be created for with is_train=True for training. info string Setting up data and model... with device device begin comment First setup shared resourc...
def train(self, optim, training_set: Sequence[Tuple[QASetting, Answer]], max_epochs=10, hooks=[], l2=0.0, clip=None, clip_op=tf.clip_by_value, device="/cpu:0"): assert self.is_train, "Reader has to be created for with is_train=True for training." ...
Python
nomic_cornstack_python_v1
function callback_extend_list item begin extend fisher_contingency_pval_parallel_insertion item end function
def callback_extend_list(item): fisher_contingency_pval_parallel_insertion.extend(item)
Python
nomic_cornstack_python_v1
function WillRunAction self tab begin call WillRunAction tab call InjectJavaScript tab string seek.js end function
def WillRunAction(self, tab): super(SeekAction, self).WillRunAction(tab) utils.InjectJavaScript(tab, 'seek.js')
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat May 18 20:09:09 2013 @author: ventilator function getsum length begin set summe = 0 comment length = #of quadrat set currentnumber = 1 set summe = summe + currentnumber for x in range 2 length + 1 2 begin comment print x for i in range 0 4 begin set currentnumber = cu...
# -*- coding: utf-8 -*- """ Created on Sat May 18 20:09:09 2013 @author: ventilator """ def getsum(length): summe = 0 #length = #of quadrat currentnumber = 1 summe += currentnumber for x in range(2, length+1, 2): #print x for i in range(0,4): currentnumber += x ...
Python
zaydzuhri_stack_edu_python
import platform import subprocess import re import statistics function run_pingcheck ip count=4 retries=1 begin set pings = list for i in range 0 count begin set res = call check_ping ip if not res at string success and retries > 0 begin return call run_pingcheck ip count retries - 1 end else if not res at string succ...
import platform import subprocess import re import statistics def run_pingcheck(ip, count=4, retries=1): pings = [] for i in range(0, count): res = check_ping(ip) if (not res["success"]) and (retries > 0): return run_pingcheck(ip, count, retries-1) elif not res["success"]: ...
Python
zaydzuhri_stack_edu_python
from PIL import Image import pytesseract import cv2 from dateutil.parser import parse import re from flask import Flask , request , jsonify , render_template import base64 set app = call Flask __name__ decorator call route string / function home begin return call render_template string index.html end function decorator...
from PIL import Image import pytesseract import cv2 from dateutil.parser import parse import re from flask import Flask, request, jsonify, render_template import base64 app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/process',methods=['POST']) ...
Python
zaydzuhri_stack_edu_python
function walk self pattern=none errors=string strict regex=none begin pass end function
def walk(self, pattern=None, errors='strict', regex=None): pass
Python
nomic_cornstack_python_v1
function views self views begin set _views = views end function
def views(self, views): self._views = views
Python
nomic_cornstack_python_v1
function __eq__ self other begin if length table != length table begin return false end for i in range length table begin if table at i != table at i begin return false end end return true end function
def __eq__(self, other): if len(self.table) != len(other.table): return False for i in range(len(self.table)): if self.table[i] != other.table[i]: return False return True
Python
nomic_cornstack_python_v1
function test_last_name_is_optional self begin set updated_data at string last_name = string call update_user assert equal last_name updated_data at string last_name end function
def test_last_name_is_optional(self): self.updated_data['last_name'] = '' self.update_user() self.assertEqual(self.user.last_name, self.updated_data['last_name'])
Python
nomic_cornstack_python_v1
string Train the CNN. import argparse from cnn_model import VideoRecognitionCNN from config import MODEL_DIR , TFRECORD_PATH , TRAIN_STEPS if __name__ == string __main__ begin set parser = call ArgumentParser description=string Train the CNN. call add_argument string -n string --number-steps type=int default=TRAIN_STEP...
""" Train the CNN. """ import argparse from cnn_model import VideoRecognitionCNN from config import (MODEL_DIR, TFRECORD_PATH, TRAIN_STEPS) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Train the CNN.') parser.add_argument('-n', '--number-steps', type=int, default=TRAIN_STEPS, ...
Python
zaydzuhri_stack_edu_python
comment Created by Bogdan Trif on 27-01-2018 , 7:05 PM. string This chapter covers one of Python's strengths: introspection. As you know, everything in Python is an object, and introspection is code looking at other modules and functions in memory as objects, getting information about them, and manipulating them. Along...
# Created by Bogdan Trif on 27-01-2018 , 7:05 PM. ''' This chapter covers one of Python's strengths: introspection. As you know, everything in Python is an object, and introspection is code looking at other modules and functions in memory as objects, getting information about them, and manipulating them. Along the wa...
Python
zaydzuhri_stack_edu_python
function gcd a b begin if b == 0 begin return a end return call gcd b a % b end function function main begin set n = integer input set a = sorted list comprehension integer x for x in split input for i in range n begin for j in range i + 1 n begin if call gcd a at i a at j == 1 begin print a at i a at j sep=string end ...
def gcd(a,b): if(b==0): return a return gcd(b, a%b) def main(): n = int(input()) a = sorted([int(x) for x in input().split()]) for i in range(n): for j in range(i+1,n): if(gcd(a[i],a[j]) == 1): print(a[i] , a[j] , sep=" ") if __name__ == '__ma...
Python
zaydzuhri_stack_edu_python
function getCombinedSpecData self indices=string all begin if indices == string all begin set indices = array range size end set specList = map lambda x -> spec indices set specOut = concatenate list specList axis=1 set descList = map lambda x -> call _convertDescField desc indices set descOut = concatenate list descLi...
def getCombinedSpecData(self, indices='all'): if indices == 'all': indices = np.arange(self.scan.size) specList = map(lambda x: self.scan[x, 0].spec, indices) specOut = np.concatenate(list(specList), axis=1) descList = map(lambda x: self._convertDescField( self.sc...
Python
nomic_cornstack_python_v1
function get_data self n typeCode item_size begin if pos >= num_bytes begin raise call ValueError string All data read from record, pos= + string pos + string >= num_bytes= + string num_bytes end set values = call unpack format string {0}{1} n typeCode data at slice pos : pos + item_size * n : set pos = pos + item_size...
def get_data(self, n, typeCode, item_size): if self.pos >= self.num_bytes: raise ValueError( "All data read from record, pos=" + str(self.pos) + " >= num_bytes=" + str(self.num_bytes) ) values = struct.unpack( ...
Python
nomic_cornstack_python_v1
import os import sys import re import pandas as pd from time import sleep import subprocess from datetime import datetime as dt import argparse , textwrap import cProfile import pstats import io function output_cProfile_to_text filepath begin set s = call StringIO set ps = call sort_stats string tottime call print_stat...
import os import sys import re import pandas as pd from time import sleep import subprocess from datetime import datetime as dt import argparse, textwrap import cProfile import pstats import io def output_cProfile_to_text(filepath): s = io.StringIO() ps = pstats.Stats(filepath, stream=s).sort_stats('tottime') ...
Python
zaydzuhri_stack_edu_python
function weHaveAlreadyRunBackupToday datefile force begin set ret = false set budate = call unix string cat %s % datefile at 1 set today = string format time time string %d-%m-%Y if budate == today begin log string Backup performed today already. set ret = true end if force begin log string Backup performed today alrea...
def weHaveAlreadyRunBackupToday(datefile, force): ret = False budate = unix("cat %s" % datefile)[1] today = time.strftime("%d-%m-%Y") if budate == today: log("Backup performed today already.") ret = True if force: log("Backup performed today already, but doing another one any...
Python
nomic_cornstack_python_v1
import grovepi import os import subprocess import time import math import bandeauLed import captCard comment capteur de température sur le port 4 set capt = 4 comment Bandeau de led sur le port 3 set bandeau = 3 set sleep = 5 call pinMode bandeau string OUTPUT while true begin try begin set list temp humidity = call dh...
import grovepi import os import subprocess import time import math import bandeauLed import captCard capt = 4 # capteur de température sur le port 4 bandeau = 3 #Bandeau de led sur le port 3 sleep = 5 grovepi.pinMode(bandeau,"OUTPUT") while True: try: [temp,humidity] = grovepi.dht(capt,0) wd = os.getcwd() p...
Python
zaydzuhri_stack_edu_python
function resolve begin set n = integer input if n <= 6 begin return print 1 end else if n <= 11 begin return print 2 end else begin set c = n // 11 set MOD = if expression n % 11 > 6 then 2 else 1 if n % 11 == 0 begin set MOD = 0 end end print c * 2 + MOD end function if __name__ == string __main__ begin call resolve e...
def resolve(): n = int(input()) if n <= 6: return print(1) elif n <= 11: return print(2) else: c = n // 11 MOD = 2 if n % 11 > 6 else 1 if n % 11 == 0: MOD = 0 print(c*2+MOD) if __name__ == '__main__': resolve()
Python
zaydzuhri_stack_edu_python
function startup self paramDict begin if string dict not in paramDict begin set dictFname = string /hive/data/inside/pubs/geneDisease/diseaseDictionary/malacards/dictionary.marshal.gz end else begin set dictFname = paramDict at string dict end info string Reading %s % dictFname set lex = call loadLex dictFname end func...
def startup(self, paramDict): if "dict" not in paramDict: dictFname = "/hive/data/inside/pubs/geneDisease/diseaseDictionary/malacards/dictionary.marshal.gz" else: dictFname = paramDict["dict"] logging.info("Reading %s" % dictFname) self.lex = fastFind.loadLex(dict...
Python
nomic_cornstack_python_v1