code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import multiprocessing as mp import numpy as np import scipy.stats as sc import matplotlib.pyplot as pl import time , math comment black scholes valuation of call option on non-dividend-paying equity function VanillaCall s x t r v begin set pv = 0.0 comment option value at maturity if t - 0.0 < 1 / 365 begin set pv = m...
import multiprocessing as mp import numpy as np import scipy.stats as sc import matplotlib.pyplot as pl import time, math # black scholes valuation of call option on non-dividend-paying equity def VanillaCall(s, x, t, r, v): pv = 0.0 # option value at maturity if((t - 0.0) < (1 / 365)): pv = max(s ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment The pound sign is used as a comment character in Python. Programmers comment use comment to annotate code. Python ignores everything after the comment comment character on a line comment Notice how the 'print' function has been inserting a newline at the comment end of our scripts print...
#!/usr/bin/python #The pound sign is used as a comment character in Python. Programmers #use comment to annotate code. Python ignores everything after the #comment character on a line # Notice how the 'print' function has been inserting a newline at the #end of our scripts print("The Nobel Prize categories are:") #We...
Python
zaydzuhri_stack_edu_python
import os import sys import getopt import random import csv import subprocess import hashlib set CHAR_LIST = list string ^ string v string > string < set START = 7000 set STOP = 9000 function get_input_name path begin set tuple filename extension = call splitext path set count = 1 while exists path path begin set path ...
import os import sys import getopt import random import csv import subprocess import hashlib CHAR_LIST = ["^", "v", ">", "<"] START = 7000 STOP = 9000 def get_input_name(path): filename, extension = os.path.splitext(path) count = 1 while os.path.exists(path): path = f"{filename}_...
Python
zaydzuhri_stack_edu_python
string Created on Mar 5, 2016 @author: guillaume import draw from game import Game , WIDTH from computer import getComputerBestMove from terminal import getKeywordKey , close , keyboard from random import randint from signal import signal , SIGINT from sys import exit set QUIT_GAME = - 1 function main begin comment ret...
''' Created on Mar 5, 2016 @author: guillaume ''' import draw from game import Game, WIDTH from computer import getComputerBestMove from terminal import getKeywordKey, close, keyboard from random import randint from signal import signal, SIGINT from sys import exit QUIT_GAME = -1 def main(): # return an initi...
Python
zaydzuhri_stack_edu_python
function apply2audio1D self audio1d begin set length = shape at 0 set ans = call empty tuple _n_mic length for i in range _n_mic begin set ans at i = convolve _rir_array at tuple i slice : : audio1d mode=string same end return ans end function
def apply2audio1D(self, audio1d): length = audio1d.shape[0] ans = np.empty((self._n_mic, length)) for i in range(self._n_mic): ans[i] = np.convolve(self._rir_array[i, :], audio1d, mode='same') return ans
Python
nomic_cornstack_python_v1
function container_scatter_kwargs inputs kwargs target_gpus dim=0 begin set inputs = if expression inputs then call container_scatter inputs target_gpus dim else list set kwargs = if expression kwargs then call container_scatter kwargs target_gpus dim else list if length inputs < length kwargs begin extend inputs lis...
def container_scatter_kwargs(inputs, kwargs, target_gpus, dim=0): inputs = container_scatter(inputs, target_gpus, dim) if inputs else [] kwargs = container_scatter(kwargs, target_gpus, dim) if kwargs else [] if len(inputs) < len(kwargs): inputs.extend([() for _ in range(len(kwargs) - len(inputs))])...
Python
nomic_cornstack_python_v1
function vm_stop name begin set vm_info = call vm_status name if vm_info at string power_state == 1 begin comment print "vm_stop: Will stop VM: {0}".format(name) call stop while call vm_status name at string power_state == 1 begin sleep 1 end end return end function
def vm_stop(name): vm_info = vm_status(name) if vm_info['power_state'] == 1: # print "vm_stop: Will stop VM: {0}".format(name) vm_info['server'].stop() while vm_status(name)['power_state'] == 1: time.sleep(1) return
Python
nomic_cornstack_python_v1
from effects import ellipsis from effects import wait from scene import Scene from random import randint class EscapePod extends Scene begin function introduce self begin call ellipsis 4 wait 0.88 print string You enter the escape pod and attempt to initialise it. wait 1.3 print string The pod has an unlock key which i...
from effects import ellipsis from effects import wait from scene import Scene from random import randint class EscapePod(Scene): def introduce(self): ellipsis(4) wait(0.88) print("You enter the escape pod and attempt to initialise it.") wait(1.3) print("The pod has an unlock key which is one digit....
Python
zaydzuhri_stack_edu_python
import csv import os import time import datetime import argparse from solution import print_solution from kidney_exchange import maximize_total_weight from kidney_exchange import maximize_total_transplants from kidney_exchange import maximize_pairwise_exchange from precomputation import CyclePrecomputation from jsonCon...
import csv import os import time import datetime import argparse from solution import print_solution from kidney_exchange import maximize_total_weight from kidney_exchange import maximize_total_transplants from kidney_exchange import maximize_pairwise_exchange from precomputation import CyclePrecomputation from jsonCon...
Python
zaydzuhri_stack_edu_python
function pollute begin global atmospheric_ghg_levels set atmospheric_ghg_levels = atmospheric_ghg_levels + num_of_fossil_fuels end function
def pollute(): global atmospheric_ghg_levels atmospheric_ghg_levels += num_of_fossil_fuels
Python
nomic_cornstack_python_v1
function validate_grant_type self client_id grant_type client request *args **kwargs begin string Ensure the client is authorized to use the grant type requested. It will allow any of the four grant types (`authorization_code`, `password`, `client_credentials`, `refresh_token`) by default. Implemented `allowed_grant_ty...
def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): """Ensure the client is authorized to use the grant type requested. It will allow any of the four grant types (`authorization_code`, `password`, `client_credentials`, `refresh_tok...
Python
jtatman_500k
function __set__ self obj value begin if value is not none and id == value or has attribute value string id and id == id begin raise call ValueError string Can not associate an object with itself! end return call __set__ obj value end function
def __set__(self, obj, value): if value is not None and (obj.id == value or (hasattr(value, "id") and obj.id == value.id)): raise ValueError("Can not associate an object with itself!") return super(ReferenceProperty, self).__set__(obj, value)
Python
nomic_cornstack_python_v1
function _res_to_gm_more_row args begin set tuple tvm_ib param dst data_res data_tail reg reg_addr index res_offset dst_offset total_len = args set reg_count = 8 with call if_scope total_len % get param string cp_align_len > 0 begin with call if_scope total_len > get param string cp_align_len begin set total_len_align ...
def _res_to_gm_more_row(args): tvm_ib, param, dst, data_res, data_tail, reg, reg_addr, index, res_offset,\ dst_offset, total_len = args reg_count = 8 with tvm_ib.if_scope(total_len % param.get("cp_align_len") > 0): with tvm_ib.if_scope(total_len > param.get("cp_align_len")): total_l...
Python
nomic_cornstack_python_v1
function health_percentage self begin if not health_max begin return 0 end return health / health_max end function
def health_percentage(self) -> Union[int, float]: if not self.proto.health_max: return 0 return self.proto.health / self.proto.health_max
Python
nomic_cornstack_python_v1
function is_absolute self begin return is instance _time tuple Timestamp DatetimeIndex end function
def is_absolute(self) -> bool: return isinstance(self._time, (Timestamp, DatetimeIndex))
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- string @author: Pieter Huycke GitHub: phuycke comment %% comment import relevant modules import os import pickle comment %% comment load in the data set location = string full\path\to\cats_dogs.pkl set location = string C:\Users\pieter\Downloads\GitHub\modeling-ma...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ @author: Pieter Huycke GitHub: phuycke """ #%% # import relevant modules import os import pickle #%% # load in the data location = r'full\path\to\cats_dogs.pkl' location = r'C:\Users\pieter\Downloads\GitHub\modeling-master\AY 2019 - 2020\Lesson 10\Practical session...
Python
zaydzuhri_stack_edu_python
function get_number_pikas_x ai_settings pika_width begin set available_space_x = screen_width - 2 * pika_width set number_pikas_x = integer available_space_x / 2 * pika_width return number_pikas_x end function
def get_number_pikas_x(ai_settings, pika_width): available_space_x = ai_settings.screen_width - 2 * pika_width number_pikas_x = int(available_space_x / (2 * pika_width)) return number_pikas_x
Python
nomic_cornstack_python_v1
function longest_ORF_noncoding dna num_trials begin set org = list dna set max_len = 0 set r = string for i in range num_trials begin set l = org shuffle l set orf = call longest_ORF call collapse l if length orf > max_len begin set r = orf set max_len = length orf end end return r end function
def longest_ORF_noncoding(dna, num_trials): org = list(dna) max_len = 0 r = "" for i in range(num_trials): l = org shuffle(l) orf = longest_ORF(collapse(l)) if len(orf) > max_len: r = orf max_len = len(orf) return r
Python
nomic_cornstack_python_v1
import gmpy2 import random from gmpy2 import mpz set random_state = call random_state 42 comment def prime_generator(bits): comment temp = gmpy2.mpz_rrandomb(random_state, 1538) comment return gmpy2.next_prime(temp) print string -----KEY GENERATION----- set bit_size = 1538 string p=0 #Random p and q value generator q=0...
import gmpy2 import random from gmpy2 import mpz random_state = gmpy2.random_state(42) #def prime_generator(bits): # temp = gmpy2.mpz_rrandomb(random_state, 1538) # return gmpy2.next_prime(temp) print("-----KEY GENERATION-----") bit_size=1538 """p=0 #Random p and q value generator q=0 while(p==q...
Python
zaydzuhri_stack_edu_python
import numpy from dataset import TumorTrain , TumorTest import matplotlib.pyplot as plt from utils import get_training_dataloader , get_test_dataloader set tumor_train_dataset = call TumorTrain print length tumor_train_dataset set tumor_training_loader = call get_training_dataloader num_workers=4 batch_size=30 shuffle=...
import numpy from dataset import TumorTrain,TumorTest import matplotlib.pyplot as plt from utils import get_training_dataloader, get_test_dataloader tumor_train_dataset = TumorTrain() print(len(tumor_train_dataset)) tumor_training_loader = get_training_dataloader( num_workers=4, batch_size=30, shuffle=True...
Python
zaydzuhri_stack_edu_python
if 18 <= age < 31 begin print format string Welcome {} , Have a nice holiday name end else begin print format string Sorry {} You do not meet the requirements name end
if 18 <= age < 31 : print("Welcome {} , Have a nice holiday".format(name)) else: print("Sorry {} You do not meet the requirements ".format(name))
Python
zaydzuhri_stack_edu_python
import unittest from forth_kyu.triplets.node import Node class TestNode extends TestCase begin function setUp self begin set test_node = call Node string a set test_node = test_node + call Node string b set test_node = test_node + call Node string c set test_node = test_node end function function test_property_letter s...
import unittest from forth_kyu.triplets.node import Node class TestNode(unittest.TestCase): def setUp(self): test_node = Node('a') test_node += Node('b') test_node += Node('c') self.test_node = test_node def test_property_letter(self): self.assertEqual(self.test_node....
Python
zaydzuhri_stack_edu_python
function setListaGiorniDellAnno self lista=none index=none begin if lista is not none begin set listaGiorniDellAnno = lista if index is not none begin call emit index end end end function
def setListaGiorniDellAnno(self, lista: list=None, index=None): if lista is not None: self.listaGiorniDellAnno = lista if index is not None: self.listaGiorniDellAnnoChanged.emit(index)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 import time from collections import OrderedDict class LRUCacheDecorator begin function __init__ self maxsize ttl begin string :param maxsize: максимальный размер кеша :param ttl: время в млсек, через которое кеш должен исчезнуть comment TODO инициализация декоратора co...
#!/usr/bin/env python # coding: utf-8 import time from collections import OrderedDict class LRUCacheDecorator: def __init__(self, maxsize, ttl): ''' :param maxsize: максимальный размер кеша :param ttl: время в млсек, через которое кеш должен исчезнуть ''' ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import os , sys if length argv != 4 or argv at 1 == string --help begin write stderr string Usage: + base name path argv at 0 + string <in.bed> <in.fai> <chr_to_invert> write stderr string This script inverts the bed locations for a particular chromosome. write stderr string Version: 1.0 ex...
#!/usr/bin/env python import os, sys if len(sys.argv) != 4 or sys.argv[1] == "--help": sys.stderr.write("Usage: "+os.path.basename(sys.argv[0])+" <in.bed> <in.fai> <chr_to_invert>\n") sys.stderr.write("This script inverts the bed locations for a particular chromosome.\n") sys.stderr.write("Version: 1.0\n"...
Python
zaydzuhri_stack_edu_python
comment print(eval(input().replace(' ', '/')))
# print(eval(input().replace(' ', '/')))
Python
zaydzuhri_stack_edu_python
from scipy.optimize import root , minimize from math import cos function eqn x begin return x + cos x end function function eqn2 x begin return x ^ 2 + x + 2 end function set myroot = call root eqn 0 set mymin = minimize eqn2 0 method=string BFGS print mymin
from scipy.optimize import root, minimize from math import cos def eqn(x): return x + cos(x) def eqn2(x): return x**2 + x + 2 myroot = root(eqn, 0) mymin = minimize(eqn2, 0, method='BFGS') print(mymin)
Python
zaydzuhri_stack_edu_python
function test_extended_bodyclass_template_change_form self begin set response = get client reverse string admin:admin_views_section_add call assertContains response string bodyclass_consistency_check end function
def test_extended_bodyclass_template_change_form(self): response = self.client.get(reverse('admin:admin_views_section_add')) self.assertContains(response, 'bodyclass_consistency_check ')
Python
nomic_cornstack_python_v1
from Player import Player from Guessing import Guessing from Word_Search import Word_Search from Crypto import Crypto from Hangman import Hangman from Math import Math from Python import Python from Boolean import Boolean from Number import Number from Shuffle import Shuffle from Quiz import Quiz from Memory import Mem...
from Player import Player from Guessing import Guessing from Word_Search import Word_Search from Crypto import Crypto from Hangman import Hangman from Math import Math from Python import Python from Boolean import Boolean from Number import Number from Shuffle import Shuffle from Quiz import Quiz from Memory import Mem...
Python
zaydzuhri_stack_edu_python
function _asteroid_start_location self begin set x = random integer SCREEN_MIN_X SCREEN_MAX_X set y = random integer SCREEN_MIN_Y SCREEN_MAX_Y while x == call get_x_y_loc at 0 and y == call get_x_y_loc at 1 begin set x = random integer SCREEN_MIN_X SCREEN_MAX_X set y = random integer SCREEN_MIN_Y SCREEN_MAX_Y end retur...
def _asteroid_start_location(self): x = random.randint(Screen.SCREEN_MIN_X, Screen.SCREEN_MAX_X) y = random.randint(Screen.SCREEN_MIN_Y, Screen.SCREEN_MAX_Y) while x == self.__ship.get_x_y_loc()[0] and \ y == self.__ship.get_x_y_loc()[1]: x = random.randint(Screen.SCR...
Python
nomic_cornstack_python_v1
import sys import os.path from os import path from Parser import Parser from Parser import Command_Type from CodeWriter import CodeWriter set USAGE_INSTRUCTION = string Usage: VMTranslator file.vm set FILE_OPEN_ERROR = string Error: Cannot open file set FILE_WRITE_ERROR = string Error: Cannot write to file set VM_EXTEN...
import sys import os.path from os import path from Parser import Parser from Parser import Command_Type from CodeWriter import CodeWriter USAGE_INSTRUCTION = 'Usage: VMTranslator file.vm' FILE_OPEN_ERROR = 'Error: Cannot open file' FILE_WRITE_ERROR = 'Error: Cannot write to file' VM_EXTENSION = 'vm' DOT = '.' POP = '...
Python
zaydzuhri_stack_edu_python
function strip_floatApprox_wrapping field begin if is instance field dict begin return field at string floatApprox end else begin return field end end function
def strip_floatApprox_wrapping(field): if isinstance(field, dict): return field['floatApprox'] else: return field
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- from abc import ABCMeta , abstractmethod string if __name__ == '__main__': # 实例化动物园 z = Zoo('时间动物园') # 实例化一只猫,属性包括名字、类型、体型、性格 cat1 = Cat('大花猫 1', '食肉', '小', '温顺') # 增加一只猫到动物园 z.add_animal(cat1) # 动物园是否有猫这种动物 have_cat = hasattr(z, 'Cat') 具体要求: 定义“动物”、“猫”、“狗”、“动...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod """ if __name__ == '__main__': # 实例化动物园 z = Zoo('时间动物园') # 实例化一只猫,属性包括名字、类型、体型、性格 cat1 = Cat('大花猫 1', '食肉', '小', '温顺') # 增加一只猫到动物园 z.add_animal(cat1) # 动物园是否有猫这种动物 have_cat = hasattr(z, 'Cat') 具体要求: ...
Python
zaydzuhri_stack_edu_python
for top_left in range a b + 1 begin for top_right in range a b + 1 begin for bot_left in range c d + 1 begin for bot_right in range c d + 1 begin set first_diagonal = top_left + bot_right set second_diagonal = top_right + bot_left set are_equal = first_diagonal == second_diagonal set are_top = top_right != top_left set...
for top_left in range(a, b + 1): for top_right in range(a, b + 1): for bot_left in range(c, d + 1): for bot_right in range(c, d + 1): first_diagonal = top_left + bot_right second_diagonal = top_right + bot_left are_equal =first_diagonal == ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import time from itertools import chain from typing import Generator from pyrogram import Chat , ChatMember , Client , Dialog from pyrogram.errors import BadRequest , FloodWait set app = call Client string my_account function get_supergroup begin set self_id = id for dialog in call iter_di...
#!/usr/bin/env python3 import time from itertools import chain from typing import Generator from pyrogram import Chat, ChatMember, Client, Dialog from pyrogram.errors import BadRequest, FloodWait app = Client("my_account") def get_supergroup() -> Generator[Chat, None, None]: self_id = app.get_me().id for di...
Python
zaydzuhri_stack_edu_python
comment put your python code here set first_number = decimal input set second_number = decimal input set math_operation = input set non_zero_operations = tuple string mod string div string / if second_number == 0 and math_operation in non_zero_operations begin print string Division by 0! end else if lower math_operatio...
# put your python code here first_number = float(input()) second_number = float(input()) math_operation = input() non_zero_operations = ('mod', 'div', '/') if second_number == 0 and math_operation in non_zero_operations: print('Division by 0!') elif math_operation.lower() == 'mod': print(first_number % second...
Python
zaydzuhri_stack_edu_python
function getContext self contextName begin for ctxtObj in contexts begin if contextName == contextName begin return ctxtObj end end end function
def getContext(self, contextName): for ctxtObj in self.contexts: if ctxtObj.contextName == contextName: return ctxtObj
Python
nomic_cornstack_python_v1
comment !/bin/python from subprocess import Popen , call from time import sleep import socket from struct import pack set settings = dict string exe_path string bin/gprs ; string port 12345 ; string host string 127.0.0.1 set state = dict string proc none ; string socket call socket AF_INET SOCK_DGRAM set scores = list ...
#!/bin/python from subprocess import Popen, call from time import sleep import socket from struct import pack settings = { 'exe_path' : 'bin/gprs', 'port' : 12345, 'host' : '127.0.0.1' } state = { 'proc' : None, 'socket' : socket.socket(socket.AF_INET, socket.SOCK_DGRAM), } scores = ['correto'...
Python
zaydzuhri_stack_edu_python
function load_model self weight_file device use_half begin comment import pytorch try begin import torch import sparseconvnet as scn end except any begin raise call RuntimeError string could not load pytorch! end comment import model try begin from sparselarflow import SparseLArFlow end except Exception as e begin rais...
def load_model(self,weight_file,device,use_half): # import pytorch try: import torch import sparseconvnet as scn except: raise RuntimeError("could not load pytorch!") # import model try: from sparselarflow import SparseLArFlow ...
Python
nomic_cornstack_python_v1
function get_dataloaders data_dir imsize batch_size eval_size num_workers=1 begin set dataset = call ImageFolder root=data_dir transform=call Compose list call Resize imsize call CenterCrop imsize call ToTensor call Normalize tuple 0.5 0.5 0.5 tuple 0.5 0.5 0.5 set tuple eval_dataset train_dataset = call random_split d...
def get_dataloaders(data_dir, imsize, batch_size, eval_size, num_workers=1): dataset = datasets.ImageFolder( root=data_dir, transform=transforms.Compose( [ transforms.Resize(imsize), transforms.CenterCrop(imsize), transforms.ToTensor(), ...
Python
nomic_cornstack_python_v1
function getAcceleration self begin return call getAcceleration end function
def getAcceleration(self): return self.motion.getAcceleration()
Python
nomic_cornstack_python_v1
comment TASK SIX: HIGHER ORDER FUNCTIONS, GENERATORS, LIST COMPREHENSION AND DECORATOR comment 1. Write a program to Python find the values which is not divisible 3 but is should be a multiple of 7. comment Make sure to use only higher order function. set l = list comprehension i for i in range 1 50 if i % 3 != 0 and i...
#TASK SIX: HIGHER ORDER FUNCTIONS, GENERATORS, LIST COMPREHENSION AND DECORATOR #1. Write a program to Python find the values which is not divisible 3 but is should be a multiple of 7. # Make sure to use only higher order function. l = [i for i in range(1,50) if i%3 != 0 and i%7 == 0] print(l) #2. Write a program i...
Python
zaydzuhri_stack_edu_python
function writeAttribute self *args begin if type args at 1 == type true begin return call XMLOutputStream_writeAttributeBool self *args end return call XMLOutputStream_writeAttribute self *args end function
def writeAttribute(self, *args): if type(args[1]) == type(True): return _libsbml.XMLOutputStream_writeAttributeBool(self, *args) return _libsbml.XMLOutputStream_writeAttribute(self, *args)
Python
nomic_cornstack_python_v1
function TimeDelay delay cancel=none core=none begin return call TimeDelay delay cancel end function
def TimeDelay (delay, cancel = None, core = None): return (core or Core.Instance ()).TimeDelay (delay, cancel)
Python
nomic_cornstack_python_v1
function walk_rancid_subdirs rancid_root config_dirname=CONFIG_DIRNAME fields=none begin set walker = walk rancid_root comment First item is base set tuple baseroot basedirs basefiles = next walker set results = dict for tuple root dirnames filenames in walker begin comment Skip any path with CVS in it if string CVS i...
def walk_rancid_subdirs(rancid_root, config_dirname=CONFIG_DIRNAME, fields=None): walker = os.walk(rancid_root) baseroot, basedirs, basefiles = next(walker) # First item is base results = {} for root, dirnames, filenames in walker: # Skip any path with CVS in it ...
Python
nomic_cornstack_python_v1
import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split set st = none function fill_na df feature avg begin string df: Data you want to process feature: feature that you want to fill avg: What you want to fill in df What it is: Fill null into the df you ...
import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split st = None def fill_na(df, feature, avg): ''' df: Data you want to process feature: feature that you want to fill avg: What you want to fill in df What it is: Fill null ...
Python
zaydzuhri_stack_edu_python
function generate_samples self trainer pl_module begin comment Generate reconstructed images to see if model is training call sample_images trainer pl_module output_type=string rec include_input=true loader_idx=0 comment Generate attentionmaps from "other class" images as well call sample_images trainer pl_module outpu...
def generate_samples(self, trainer, pl_module): # Generate reconstructed images to see if model is training self.sample_images(trainer, pl_module, output_type='rec', include_input=True, loader_idx=0) # Generate attentionmaps from "other class" images as well self.sample_images(trainer, p...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Oct 19 11:15:09 2018 @author: magge import random set N = 100 set head = 0 set tail = 0 for i in range N begin set r = random integer 0 1 if r == 0 begin print string heads set head = head + 1 end else begin print string tails set tail = tail + 1 end end
# -*- coding: utf-8 -*- """ Created on Fri Oct 19 11:15:09 2018 @author: magge """ import random N = 100 head = 0 tail = 0 for i in range(N): r = random.randint(0,1) if r == 0: print('heads') head += 1 else: print('tails') tail += 1
Python
zaydzuhri_stack_edu_python
from typing import List function waterArea heights begin set n = length heights set area = 0 for i in range 1 n - 1 begin set left = heights at i for j in range i begin set left = max left heights at j end set right = heights at i for j in range i + 1 n begin set right = max right heights at j end set area = area + min...
from typing import List def waterArea(heights: List[int]) -> int: n = len(heights) area = 0 for i in range(1, n-1): left = heights[i] for j in range(i): left = max(left, heights[j]) right = heights[i] for j in range(i+1, n): right = max(right, height...
Python
zaydzuhri_stack_edu_python
string 欧拉计划 题目 002 偶数项斐波那契数列之和 斐波那契数列中的每一项都是前两项的和。由1和2开始生成的斐波那契数列前10项为: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, … 计算该斐波那契数列中不超过400万的项,求其中偶数项之和。 分析: 斐波那契数列,可以使用元组元素交换,不断生成;同时设初始值为0的和,不断与偶数项相加,当数列数值大于400万,即停止迭代 function solution begin set ans = 0 comment 数列第1项 set a = 1 comment 数列第2项 set b = 2 while a <= 4000000 begin if b % ...
''' 欧拉计划 题目 002 偶数项斐波那契数列之和 斐波那契数列中的每一项都是前两项的和。由1和2开始生成的斐波那契数列前10项为: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, … 计算该斐波那契数列中不超过400万的项,求其中偶数项之和。 分析: 斐波那契数列,可以使用元组元素交换,不断生成;同时设初始值为0的和,不断与偶数项相加,当数列数值大于400万,即停止迭代 ''' def solution(): ans = 0 a = 1 # 数列第1项 b = 2 # 数列第2项 while a <= 4000000: ...
Python
zaydzuhri_stack_edu_python
comment precio de base de los huevos = 1800 comment precio de base de las arepas = 5000 comment si alguien compra mas de 10 canastas, el precio 1000 comment si alguien compra mas de 10 canastas de huevos y ademas compra mas de 10 paquetes de arepas comment el precio de los huevos es 800 y el de las arepas es 2000 comme...
# precio de base de los huevos = 1800 # precio de base de las arepas = 5000 # si alguien compra mas de 10 canastas, el precio 1000 # si alguien compra mas de 10 canastas de huevos y ademas compra mas de 10 paquetes de arepas # el precio de los huevos es 800 y el de las arepas es 2000 #paso 1: preguntar cuantos huevo...
Python
zaydzuhri_stack_edu_python
function get_activity_for_users self users start_dt end_dt begin set task = call _get_activity_for_users users start_dt end_dt return run task end function
def get_activity_for_users( self, users: List[str], start_dt: datetime, end_dt: datetime, ) -> Dict[str, list]: task = self._get_activity_for_users(users, start_dt, end_dt) return asyncio.run(task)
Python
nomic_cornstack_python_v1
async function test_start_stop hub_app systemdspawner_config pytestconfig begin set username = call getoption string --system-test-user skip=true set unit_name = string jupyter- { username } -singleuser.service set test_config = dict merge test_config set app = await call hub_app systemdspawner_config call add_user db...
async def test_start_stop(hub_app, systemdspawner_config, pytestconfig): username = pytestconfig.getoption("--system-test-user", skip=True) unit_name = f"jupyter-{username}-singleuser.service" test_config = {} systemdspawner_config.merge(test_config) app = await hub_app(systemdspawner_config) ...
Python
nomic_cornstack_python_v1
function test_serializer_failure_because_verified_user_requests_token self begin set user = call create_user username=string test email=string test@mail.com password=string password set is_verified = true save set data = dict string email string test@mail.com ; string username string test ; string callback_url string h...
def test_serializer_failure_because_verified_user_requests_token(self): user = User.objects.create_user(username='test', email='test@mail.com', password='password') user.is_verified = True user.save() data = {'email': 'test@mail.com', 'username': 'test', ...
Python
nomic_cornstack_python_v1
if n < k * k begin set ans = n + n // k - 1 // n // k end else begin set r = n % k if r == 0 begin set ans = k end else begin set ans = k + 1 end end if ans == x begin print string Correct, but it doesn't necessarily mean that you can win the Turing Award. end else begin print string Wrong, don't cheat me, you are too ...
if n<k*k: ans = (n+n//k-1)//(n//k) else: r = n%k if r==0: ans = k else: ans = k+1 if ans==x : print("Correct, but it doesn't necessarily mean that you can win the Turing Award.") else: print("Wrong, don't cheat me, you are too far away from the Turing Award.") if x>ans: ...
Python
zaydzuhri_stack_edu_python
function __init__ self json_data=none begin call __init__ set options = dict string name string ; string rule string ; string action string ; string undefaction string ; string comment string ; string logaction string ; string newname string ; string hits string ; string undefhits string ; string description s...
def __init__(self, json_data=None): super(NSRewritePolicy, self).__init__() self.options = { 'name': '', 'rule': '', 'action': '', 'undefaction': '', 'comment': '', 'logaction': '', 'newname': '', 'hits': '',...
Python
nomic_cornstack_python_v1
function GetRevisionSet self revision_set_name begin return get _revision_sets revision_set_name none end function
def GetRevisionSet(self, revision_set_name): return self._revision_sets.get(revision_set_name, None)
Python
nomic_cornstack_python_v1
import pickle import os import datetime set restaurant_list = list set user_input_list = list string Name: string Flavor: string Hygiene: string Price: string Menu: string Location: string Business hours: set MENU_RETRIEVE = 1 set MENU_ADD = 2 set MENU_UPDATE = 3 set MENU_EDIT = 4 set MENU_DELETE = 5 set MENU_SAVE = 6...
import pickle import os import datetime restaurant_list = [] user_input_list = ["Name:", "Flavor:", "Hygiene:", "Price:", "Menu:", "Location:", "Business hours:"] MENU_RETRIEVE = 1 MENU_ADD = 2 MENU_UPDATE = 3 MENU_EDIT = 4 MENU_DELETE = 5 MENU_SAVE = 6 MENU_LOAD = 7 MENU_QUIT = 8 INDEX_NAME = 0 I...
Python
zaydzuhri_stack_edu_python
set temps = list 25 39 52 68 20 89 set temps_less_50 = list filter lambda x -> x < 50 temps print string Values less than 50 + string temps_less_50
temps = [25,39,52,68,20,89] temps_less_50 = list(filter(lambda x:x <50, temps)) print('Values less than 50 ' +str(temps_less_50))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment 被测类:计算器 class Calculator begin function add self a b begin return a + b end function function div self a b begin if b != 0 begin return a / b end else begin return string error end end function end class
#!/usr/bin/env python # -*- coding: utf-8 -*- # 被测类:计算器 class Calculator: def add(self, a, b): return a + b def div(self, a, b): if b!=0: return a / b else: return "error"
Python
zaydzuhri_stack_edu_python
async function purge self ctx limit flags=string begin await delete if string all in flags begin await call purge limit=limit end else begin await call purge limit=limit check=lambda msg -> not pinned and not attachments end end function
async def purge(self, ctx, limit: int, flags=""): await ctx.message.delete() if "all" in flags: await ctx.message.channel.purge(limit=limit) else: await ctx.message.channel.purge(limit=limit, check=lambda msg: not msg.pinned ...
Python
nomic_cornstack_python_v1
import math class Solution extends object begin function isPalindrome self x begin string :type x: int :rtype: bool set rev = 0 set y = x if x < 0 begin return false end else if x == 0 begin return true end else begin set count = floor log x 10 while x > 0 begin set tuple x rem = divide mod x 10 set rev = rev + rem * p...
import math class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ rev=0 y=x if(x<0): return False elif (x==0): return True else: count= math.floor(math.log(x,10)) wh...
Python
zaydzuhri_stack_edu_python
function mySort L begin set clear = false while not clear begin set clear = true for j in range 1 length L begin if L at j - 1 > L at j begin set clear = false set temp = L at j set L at j = L at j - 1 set L at j - 1 = temp end end end end function
def mySort(L): clear = False while not clear: clear = True for j in range(1, len(L)): if L[j-1] > L[j]: clear = False temp = L[j] L[j] = L[j-1] L[j-1] = temp
Python
nomic_cornstack_python_v1
from django.shortcuts import render , get_object_or_404 from models import MyBlog function all_blogs request begin comment Grab the elements out of the DB set blog = all comment '-date' : the most current ones are going to pop on top comment blog = MyBlog.objects.order_by('-date') comment '-date' => the most current on...
from django.shortcuts import render, get_object_or_404 from .models import MyBlog def all_blogs(request): # Grab the elements out of the DB blog = MyBlog.objects.all() # '-date' : the most current ones are going to pop on top # blog = MyBlog.objects.order_by('-date') # '-date' => the most current...
Python
zaydzuhri_stack_edu_python
function insertElements self units parent=none begin if not units begin return list end comment store spec file separately - assume all elements share same spec call insertWMSpec units at 0 at string WMSpec set newUnitsInserted = list for unit in units begin comment cast to couch if not is instance unit CouchWorkQueu...
def insertElements(self, units, parent=None): if not units: return [] # store spec file separately - assume all elements share same spec self.insertWMSpec(units[0]['WMSpec']) newUnitsInserted = [] for unit in units: # cast to couch if not isins...
Python
nomic_cornstack_python_v1
function get_model point_cloud is_training num_class sigma_init sigma=0.05 bn_decay=none weight_decay=none begin set batch_size = value set num_point = value set end_points = dict comment noisy generate################################ set tuple point_merge sigma_val = call add_noisy_by_point point_cloud sigma_init set...
def get_model(point_cloud, is_training, num_class, sigma_init, sigma=0.05, bn_decay=None, weight_decay = None): batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value end_points = {} #######noisy generate################################ point_merge, sigma_val = a...
Python
nomic_cornstack_python_v1
string Created on 28 nov. 2017 @author: SergiuP from unittest import TestCase , main from Infrastructure.ComplexRepository import Repository from Domain.ComplexNumber import Complex class ComplexRepositoryTests extends TestCase begin function test_addComplex self begin set s = call Repository set c = call Complex 3 4 c...
''' Created on 28 nov. 2017 @author: SergiuP ''' from unittest import TestCase,main from Infrastructure.ComplexRepository import Repository from Domain.ComplexNumber import Complex class ComplexRepositoryTests(TestCase): def test_addComplex(self): s=Repository() c=Complex(3,4) ...
Python
zaydzuhri_stack_edu_python
function on_Off_class_button_clicked self begin call stop clear stu_pic_label_7 clear rec_label_7 clear CWA_Sno_List clear textEdit end function
def on_Off_class_button_clicked(self): self.timer2.stop() self.stu_pic_label_7.clear() self.rec_label_7.clear() self.CWA_Sno_List.clear() self.textEdit.clear()
Python
nomic_cornstack_python_v1
import random from replit import clear from logo import logo comment Number of appemts depending on the difficulty set easy_level_attemps = 10 set hard_level_attemps = 5 comment function to check if the users guess is to high, low or spot on function check_answer users_guess random_number turns begin if users_guess < r...
import random from replit import clear from logo import logo #Number of appemts depending on the difficulty easy_level_attemps = 10 hard_level_attemps = 5 #function to check if the users guess is to high, low or spot on def check_answer(users_guess, random_number, turns): if users_guess < random_number: print...
Python
zaydzuhri_stack_edu_python
async function test_model_description_rgbww_bulb rgbww_bulb begin set bulb_type = await call get_bulbtype assert bulb_type == call BulbType features=call Features color=true color_tmp=true effect=true brightness=true dual_head=false name=string ESP01_SHRGB1C_31 kelvin_range=call KelvinRange max=6500 min=2700 bulb_type=...
async def test_model_description_rgbww_bulb(rgbww_bulb: wizlight) -> None: bulb_type = await rgbww_bulb.get_bulbtype() assert bulb_type == BulbType( features=Features( color=True, color_tmp=True, effect=True, brightness=True, dual_head=False ), name="ESP01_SHRGB1C_31", ...
Python
nomic_cornstack_python_v1
function split_string str begin comment Split the string into words set words = split str comment Remove duplicate words and capitalize them set unique_words = list set words set unique_words = list comprehension capitalize word for word in unique_words comment Sort the words by length in ascending order set sorted_wor...
def split_string(str): # Split the string into words words = str.split() # Remove duplicate words and capitalize them unique_words = list(set(words)) unique_words = [word.capitalize() for word in unique_words] # Sort the words by length in ascending order sorted_words = sorted(uniq...
Python
jtatman_500k
function p_reserved_word self p begin string reserved_word : BREAK | CASE | CATCH | CONTINUE | DEBUGGER | DEFAULT | DELETE | DO | ELSE | FINALLY | FOR | FUNCTION | IF | IN | INSTANCEOF | NEW | RETURN | SWITCH | THIS | THROW | TRY | TYPEOF | VAR | VOID | WHILE | WITH | NULL | TRUE | FALSE | CLASS | CONST | ENUM | EXPORT...
def p_reserved_word(self, p): """reserved_word : BREAK | CASE | CATCH | CONTINUE | DEBUGGER | DEFAULT | DELETE | DO ...
Python
jtatman_500k
function setUp self begin setup call super DIncPartyLineTest self set p2 = call Player game=g save set p3 = call Player game=g save set s = call Share corporation=c player=p turn=current_turn save set s2 = call Share corporation=c2 player=p2 turn=current_turn save set s3 = call Share corporation=c3 player=p3 turn=curre...
def setUp(self): super(DIncPartyLineTest, self).setUp() self.p2 = Player(game=self.g) self.p2.save() self.p3 = Player(game=self.g, ) self.p3.save() self.s = Share( corporation=self.c, player=self.p, turn=self.g.current_turn ) self.s.save() self.s2 = Share( corporation=self.c2, playe...
Python
nomic_cornstack_python_v1
function __init__ self token value **kwargs begin set _token = string token set _value = value set str_fmt = get kwargs string str_fmt string set _sort_key = get kwargs string sort_key string set _rtv_fmt = get kwargs string rtv_fmt string end function
def __init__(self, token, value, **kwargs): self._token = str(token) self._value = value self.str_fmt = kwargs.get('str_fmt', '') self._sort_key = kwargs.get('sort_key', '') self._rtv_fmt = kwargs.get('rtv_fmt', '')
Python
nomic_cornstack_python_v1
function test_list_g_month_day_length_nistxml_sv_iv_list_g_month_day_length_1_5 mode save_output output_format begin call assert_bindings schema=string nistData/list/gMonthDay/Schema+Instance/NISTSchema-SV-IV-list-gMonthDay-length-1.xsd instance=string nistData/list/gMonthDay/Schema+Instance/NISTXML-SV-IV-list-gMonthDa...
def test_list_g_month_day_length_nistxml_sv_iv_list_g_month_day_length_1_5(mode, save_output, output_format): assert_bindings( schema="nistData/list/gMonthDay/Schema+Instance/NISTSchema-SV-IV-list-gMonthDay-length-1.xsd", instance="nistData/list/gMonthDay/Schema+Instance/NISTXML-SV-IV-list-gMonthDay...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 function print_matrix_integer matrix=list list begin for i in matrix begin for y in range 0 length i begin print format string {:d} i at y end=string if y is not length i - 1 begin print string end=string end end print string end end function
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): for i in matrix: for y in range(0, len(i)): print("{:d}".format(i[y]), end="") if (y is not len(i) - 1): print(" ", end="") print("")
Python
zaydzuhri_stack_edu_python
comment This goes and gets the APIs once so the programs run faster print string Getting things set up. . . import requests import json set wookieurl = string https://starwars.fandom.com/api.php set name_file = open string Mandalore_people_list.txt string r set data_file = open string Mandalore_data_list.txt string w c...
# This goes and gets the APIs once so the programs run faster print('Getting things set up. . .') import requests import json wookieurl = 'https://starwars.fandom.com/api.php' name_file = open('Mandalore_people_list.txt','r') data_file = open('Mandalore_data_list.txt', 'w') ### Wookiepedia Page Search page = '' act...
Python
zaydzuhri_stack_edu_python
comment 题目: comment LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3. comment LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4. comment 实现起来比较简单,状态方程: comment LCS F[i,v] = (max{F[i-1,v],F[i,v-1]},F[i-1,v-1] +1)[X[i] == Y[v]] import numpy as np function LCS X Y N V begin comment L =...
# 题目: # LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3. # LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4. # # 实现起来比较简单,状态方程: # LCS F[i,v] = (max{F[i-1,v],F[i,v-1]},F[i-1,v-1] +1)[X[i] == Y[v]] import numpy as np def LCS(X, Y, N, V): # L = [[None]*(n+1) for i ...
Python
zaydzuhri_stack_edu_python
function Detect self request context begin set t1 = performance counter set anypb = any set height = height set width = width set image = call frombuffer image dtype=uint8 comment if image.ndim == 1: comment image = image.reshape([height,width]) if not isRaw begin set image = call imdecode image IMREAD_GRAYSCALE set tu...
def Detect(self, request, context): t1 = time.perf_counter() anypb = Any() height = request.height width = request.width image = np.frombuffer(request.image, dtype=np.uint8) #if image.ndim == 1: # image = image.reshape([height,width]) if not reque...
Python
nomic_cornstack_python_v1
function test_user_not_in_state self begin set tuple user user_key = call message set tuple manager manager_key = call create set reason = call reason set message = call make user_id=user_id new_manager_id=user_id reason=reason metadata=none set tuple _ status = call create signer_keypair=user_key message=message call ...
def test_user_not_in_state(self): user, user_key = self.test.user.message() manager, manager_key = self.test.user.create() reason = self.test.user.reason() message = self.rbac.user.manager.propose.make( user_id=user.user_id, new_manager_id=manager.user_id, ...
Python
nomic_cornstack_python_v1
function send_message self message begin set raw_message = string { username } { delimiter } { message } set socket_state = call state if socket_state != ConnectedState begin call connectToHost recipient port end set datastream = call QDataStream client_socket call writeUInt32 length raw_message call writeQString raw_m...
def send_message(self, message: str): raw_message = f"{self.username}{self.delimiter}{message}" socket_state = self.client_socket.state() if socket_state != QAbstractSocket.ConnectedState: self.client_socket.connectToHost(self.recipient, self.port) self.datastream = QDat...
Python
nomic_cornstack_python_v1
function key_vault self begin return string { key_vault_name_prefix } { _ws_id at slice - 7 : : } end function
def key_vault(self) -> str: return f"{self.key_vault_name_prefix}{self._ws_id[-7:]}"
Python
nomic_cornstack_python_v1
comment 5 % 2 = 1 comment -2 -> 3 % 2 comment -2 -> 1 % 2 comment -> 1 comment 9 % 4 = 1 comment 11 % 6 = 5 comment a = int(input("Enter a number:")) comment b = int(input("Enter a number:")) comment print(a, "%", b,"=", a%b ) if num % 2 == 0 begin print string Number is even end else begin print string Number is odd e...
# 5 % 2 = 1 # -2 -> 3 % 2 # -2 -> 1 % 2 # -> 1 # 9 % 4 = 1 # 11 % 6 = 5 #a = int(input("Enter a number:")) #b = int(input("Enter a number:")) #print(a, "%", b,"=", a%b ) if(num % 2 == 0): print("Number is even") else: print("Number is odd")
Python
zaydzuhri_stack_edu_python
comment requesrs 第三方库 import requests comment get请求 set url = string http://120.78.128.25:8765/Index/login.html comment 返回一个消息实体 set res = get requests url print headers print status_code comment html print text comment 会报错 print json res comment post 请求 带参数 set url = string http://119.23.241.154:8080/futureloan/mvc/ap...
#requesrs 第三方库 import requests #get请求 url = 'http://120.78.128.25:8765/Index/login.html' res = requests.get(url) #返回一个消息实体 print(res.headers) print(res.status_code) print(res.text) #html print(res.json()) #会报错 #post 请求 带参数 url = 'http://119.23.241.154:8080/futureloan/mvc/api/member/login' data = {"mobilephon...
Python
zaydzuhri_stack_edu_python
function values self begin return values attrs end function
def values(self): return self.attrs.values()
Python
nomic_cornstack_python_v1
for i in inputArray begin if i == 1 begin set count = count + 1 end else begin set count = 0 end if count1 < count begin set count1 = count end end print count1
for i in inputArray: if(i == 1): count = count+1 else: count =0 if(count1<count): count1 = count print(count1)
Python
zaydzuhri_stack_edu_python
function tr self message begin comment noinspection PyTypeChecker,PyArgumentList,PyCallByClass return call translate string index_extractor message end function
def tr(self, message): # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('index_extractor', message)
Python
nomic_cornstack_python_v1
from random import randint set s = set list comprehension random integer - 10 10 for _ in range 10 print s comment 要求找到集合中能被2整除的子集 set ret = set comprehension x for x in s if x % 2 == 0 print ret
from random import randint s = set([randint(-10, 10) for _ in range(10)]) print(s) # 要求找到集合中能被2整除的子集 ret = {x for x in s if x % 2 == 0} print(ret)
Python
zaydzuhri_stack_edu_python
function average_radial_intensity_3D IM origin=none dr=1 dt=none begin return call radial_intensity string avg3D IM origin=origin dr=dr dt=dt end function
def average_radial_intensity_3D(IM, origin=None, dr=1, dt=None): return radial_intensity('avg3D', IM, origin=origin, dr=dr, dt=dt)
Python
nomic_cornstack_python_v1
from new_big_square import * function plot_big_square squares axarr jj=0 ii=0 shift_x_between=1 shift_y_between=1 begin comment axarr[ii, jj].plot(squares[:, 0], squares[:, 1]) print string squares: squares for i in range shape at 0 begin for j in range shape at 1 begin comment plt.plot(plot_shape[:, 0], plot_shape[:, ...
from new_big_square import * def plot_big_square(squares, axarr, jj = 0, ii = 0, shift_x_between = 1, shift_y_between = 1): #axarr[ii, jj].plot(squares[:, 0], squares[:, 1]) print('squares: ', squares) for i in range(squares.shape[0]): for j in range(squares.shape[1]): # plt.plot(plot_shape[:, 0], plot_shape[:...
Python
zaydzuhri_stack_edu_python
class Solution begin function reverse self x begin set num = 1 if x < 0 begin set num = - 1 set x = string x at slice 1 : : end else begin set num = 1 set x = string x end return if expression 2 ^ 31 - 1 >= num * integer x at slice : : - 1 >= - 2 ^ 31 then num * integer x at slice : : - 1 else 0 end function end ...
class Solution: def reverse(self, x: int) -> int: num = 1 if x < 0: num = -1 x = str(x)[1:] else: num = 1 x = str(x) return num * int(x[::-1]) if 2**31-1 >= num * int(x[::-1]) >= -2**31 else 0 if __name__ == '__main__': solu = So...
Python
zaydzuhri_stack_edu_python
function test_running_as_module capsys begin with raises SystemExit begin with call object sys string argv list string bogus string --version begin comment F401 is a "Module imported but unused" warning. This import comment emulates how this project would be run as a module. The only thing comment being done by __main_...
def test_running_as_module(capsys): with pytest.raises(SystemExit): with patch.object(sys, "argv", ["bogus", "--version"]): # F401 is a "Module imported but unused" warning. This import # emulates how this project would be run as a module. The only thing # being done by _...
Python
nomic_cornstack_python_v1
string Created on Mar 9, 2013 @author: goof_troop class LoggingError extends Exception begin string General exception raised by Log function __init__ self msg begin set _message = msg call __init__ self string Loging Error: + msg end function function toString self begin return _message end function end class
''' Created on Mar 9, 2013 @author: goof_troop ''' class LoggingError(Exception): """ General exception raised by Log """ def __init__(self, msg): self._message = msg Exception.__init__(self, "Loging Error: " + msg) def toString(self): return self._message
Python
zaydzuhri_stack_edu_python
function paramshuman chrom outdir alpha_inter gamma_inter p_a p_b seed diag filter_high begin call cmd_estimate_params chrom outdir alpha_inter=alpha_inter gamma_inter=gamma_inter p_a=p_a p_b=p_b seed=seed diag=diag filter_high=filter_high plot=true end function
def paramshuman(chrom, outdir, alpha_inter, gamma_inter, p_a, p_b, seed, diag, filter_high): simulatehuman.cmd_estimate_params(chrom, outdir, alpha_inter=alpha_inter, gamma_inter=gamma_inter, p_a=p_a, p_b=p_b, seed=seed, diag=diag, filter_high=filter_high, ...
Python
nomic_cornstack_python_v1
function test_delete_tag_by_id self begin pass end function
def test_delete_tag_by_id(self): pass
Python
nomic_cornstack_python_v1
async function update_from_gateway_response self guild begin async_with acquire db_pool as conn begin set result = await execute conn string UPDATE { table_name } SET name = $1 WHERE id = $2 name id return integer split result at 1 == 1 end end function
async def update_from_gateway_response(self, guild: Guild) -> bool: async with self.db_pool.acquire() as conn: result = await conn.execute( f"UPDATE {self.table_name} SET name = $1 WHERE id = $2", guild.name, guild.id, ) return...
Python
nomic_cornstack_python_v1
import decimal import time import numpy as np class RandomGen begin function __init__ self c=21 * 2 ^ 30 + 3 m=2 ^ 38 seed=integer time % 1 * 10 ^ 16 begin set c = call Decimal c set m = call Decimal m set seed = call Decimal seed end function function change_seed self val begin string Sets seed value equat to val. set...
import decimal import time import numpy as np class RandomGen: def __init__(self, c=21*2**30+3, m=2**38, seed=int((time.time()%1)*10**16)): self.c = decimal.Decimal(c) self.m = decimal.Decimal(m) self.seed = decimal.Decimal(seed) def change_seed(self, val): """Sets seed va...
Python
zaydzuhri_stack_edu_python
function can_edit self can_edit begin set _can_edit = can_edit end function
def can_edit(self, can_edit): self._can_edit = can_edit
Python
nomic_cornstack_python_v1
function chunks seq n begin for i in range 0 length seq n begin yield seq at slice i : i + n : end end function
def chunks(seq: Sequence[T], n: int) -> Iterator[Sequence[T]]: for i in range(0, len(seq), n): yield seq[i:i + n]
Python
nomic_cornstack_python_v1
set x = 2 set y = 2.5 set z = 7 set tuple nombres apellidos direccion = tuple string Ivan string Fonseca string calle falsa 123 print nombres string apellidos string direccion set x = string x set y = integer y print string valor de x: x print string valor de y: y
x = 2 y = 2.5 z = 7 nombres, apellidos, direccion = ('Ivan ', 'Fonseca', 'calle falsa 123') print(nombres,' ', apellidos,' ', direccion ) x = str(x) y = int(y) print('valor de x: ',x) print('valor de y: ',y)
Python
zaydzuhri_stack_edu_python