code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import requests import json import socket class IpRequesst begin function __init__ self num_ip=0 ifnew=true add_ip=true begin set n = ifnew set ai = add_ip set ni = num_ip end function function request_ip self begin try begin if n == true begin print string here set targetUrl = string set resp = get requests targetUrl...
import requests import json import socket class IpRequesst: def __init__(self,num_ip = 0, ifnew=True, add_ip=True): self.n = ifnew self.ai = add_ip self.ni = num_ip def request_ip(self): try: if self.n == True: print('here') targetUr...
Python
zaydzuhri_stack_edu_python
from Modules import * set _Debug = false if _Debug begin import time end class Vm begin function __init__ this defLocation progLocation begin set addresses = list call loadDef defLocation set prog = list call loadProg progLocation set fileLocation = progLocation end function function loadDef this location begin with ...
from Modules import * _Debug = False if _Debug: import time class Vm: def __init__(this, defLocation, progLocation): this.addresses = [] this.loadDef(defLocation) this.prog = [] this.loadProg(progLocation) this.fileLocation = progLocation ...
Python
zaydzuhri_stack_edu_python
function matRotZ th=0.0 begin set v0 = cos th set v1 = sin th set v2 = 0.0 set v3 = 0.0 set v4 = - sin th set v5 = cos th set v6 = 0.0 set v7 = 0.0 set v8 = 0.0 set v9 = 0.0 set v10 = 1.0 set v11 = 0.0 set v12 = 0.0 set v13 = 0.0 set v14 = 0.0 set v15 = 1.0 return call Matrix v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v...
def matRotZ(th=0.0): v0 = math.cos(th) v1 = math.sin(th) v2 = 0.0 v3 = 0.0 v4 = -math.sin(th) v5 = math.cos(th) v6 = 0.0 v7 = 0.0 v8 = 0.0 v9 = 0.0 v10 = 1.0 v11 = 0.0 v12 = 0.0 v13 = 0.0 ...
Python
nomic_cornstack_python_v1
function __ne__ self other begin return not self == other end function
def __ne__(self, other): return not self == other
Python
nomic_cornstack_python_v1
from Tkinter import Tk , Canvas , Frame , BOTH import math as math set PI = 3.1415926 function distance x1 y1 x2 y2 begin return square root x1 - x2 ^ 2 + y1 - y2 ^ 2 end function class Walking extends Frame begin function __init__ self parent begin call __init__ self parent set parent = parent call init call animate e...
from Tkinter import Tk, Canvas, Frame, BOTH import math as math PI = 3.1415926 def distance(x1,y1,x2,y2): return math.sqrt((x1-x2)**2+(y1-y2)**2) class Walking(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.init() self.animate() def init(self): self.parent.ti...
Python
zaydzuhri_stack_edu_python
function make_heatmap self begin call get_selected_categories_and_codes set codes = deep copy codes if length codes > 40 begin set codes = codes at slice : 40 : exec end comment Filters set heatmap_type = call currentText if heatmap_type == string begin return end set title = heatmap_type + string + call _ string H...
def make_heatmap(self): self.get_selected_categories_and_codes() codes = deepcopy(self.codes) if len(codes) > 40: codes = codes[:40] Message(self.app, _("Too many codes"), _("Too many codes for display. Restricted to 40")).exec() # Filters heatmap_type = ...
Python
nomic_cornstack_python_v1
function readKeyPoints row begin set kp = list - 1 * numberOfKeyPoints for i in range numberOfKeyPoints begin if row at i is not none and row at i != string begin set kp at i = decimal row at i end end return kp end function
def readKeyPoints(row): kp = [-1] * numberOfKeyPoints for i in range(numberOfKeyPoints): if row[i] is not None and row[i] != "": kp[i] = float(row[i]) return kp
Python
nomic_cornstack_python_v1
function get_document self begin return _referenced_doc end function
def get_document(self): return self._referenced_doc
Python
nomic_cornstack_python_v1
function level hexagon begin set lev = 0 for coord in hexagon begin if absolute coord > lev begin set lev = absolute coord end end return lev end function
def level(hexagon): lev = 0 for coord in hexagon: if abs(coord) > lev: lev = abs(coord) return lev
Python
nomic_cornstack_python_v1
function main begin set hour = decimal input set minute = decimal input set prove = hour * 5 + minute / 12 comment Compare if prove == minute begin print string True end else if prove > minute and prove - minute < 1 begin print string True end else begin print string False end end function
def main(): hour = float(input()) minute = float(input()) prove = hour * 5 + (minute / 12) #Compare if prove == minute: print('True') elif prove > minute and (prove - minute) < 1: print('True') else: print('False')
Python
nomic_cornstack_python_v1
comment !/usr/bin/evn python comment coding=utf-8 import base64 set s = string 自行车v便不能盲目 set bs = string base64 encode encode s string utf-8 string utf-8 comment 去掉编码结果前的 b print bs set bbs = string base64 decode bs string utf-8 comment 解码 print bbs
#!/usr/bin/evn python # coding=utf-8 import base64 s = "自行车v便不能盲目" bs = str(base64.b64encode(s.encode("utf-8")), "utf-8") print(bs) # 去掉编码结果前的 b bbs = str(base64.b64decode(bs), "utf-8") print(bbs) # 解码
Python
zaydzuhri_stack_edu_python
function evaluate_accuracy data_iter net ctx=list cpu mx begin set acc = array list 0 ctx=ctx set n = 0 for tuple X y in data_iter begin set X = call as_in_context ctx set y = call as_in_context ctx set acc = acc + sum set n = n + size end return call asscalar / n end function
def evaluate_accuracy(data_iter, net, ctx=[mx.cpu()]): acc = nd.array([0], ctx=ctx) n = 0 for X, y in data_iter: X = X.as_in_context(ctx) y = y.astype('float32').as_in_context(ctx) acc += (net(X).argmax(axis=1) == y).sum() n += y.size return acc.asscalar() / n
Python
nomic_cornstack_python_v1
function build_input_data sentences vocabulary begin set x = array list comprehension list comprehension vocabulary at word for word in sentence for sentence in sentences return x end function
def build_input_data(sentences,vocabulary): x = np.array([[vocabulary[word] for word in sentence] for sentence in sentences]) return x
Python
nomic_cornstack_python_v1
import numpy as np from DeepKnockoffs import KnockoffMachine from DeepKnockoffs import GaussianKnockoffs import data import parameters from sklearn.covariance import MinCovDet , LedoitWolf from scipy.linalg import toeplitz , cholesky import datetime set now = now set timestamp = string format time now string %Y-%m-%dT%...
import numpy as np from DeepKnockoffs import KnockoffMachine from DeepKnockoffs import GaussianKnockoffs import data import parameters from sklearn.covariance import MinCovDet, LedoitWolf from scipy.linalg import toeplitz, cholesky import datetime now = datetime.datetime.now() timestamp = now.strftime('%Y-%m-%dT%H:%M...
Python
zaydzuhri_stack_edu_python
function seek_spot_lists self xml_path begin set spot_dict = call get_pixel_cordinate_from_xml xml_path set spot_dict = spot_dict set spot_list = list values spot_dict return spot_list end function
def seek_spot_lists(self, xml_path): spot_dict = self.get_pixel_cordinate_from_xml(xml_path) self.spot_dict = spot_dict spot_list = list(spot_dict.values()) return spot_list
Python
nomic_cornstack_python_v1
string PyTorch trainer module. - Author: Jongkuk Lim, Junghoon Kim - Contact: lim.jeikei@gmail.com, placidus36@gmail.com import wandb import optuna from tqdm import tqdm from sklearn.metrics import f1_score import torch from train_utils import save_model class TorchTrainer begin string Pytorch Trainer. function __init_...
"""PyTorch trainer module. - Author: Jongkuk Lim, Junghoon Kim - Contact: lim.jeikei@gmail.com, placidus36@gmail.com """ import wandb import optuna from tqdm import tqdm from sklearn.metrics import f1_score import torch from .train_utils import save_model class TorchTrainer: """Pytorch Trainer.""" def __i...
Python
zaydzuhri_stack_edu_python
comment 코딩 클럽 2권 계산기의 애플리케이션의 함수 모듈 comment 팩토리얼 함수: function factorial n begin return string factorial (!) end function comment 로마 숫자로 변환하는 함수: function to_roman n begin return string -> roman end function comment 10진수를 2진수로 변환하는 함수: function to_binary n begin return string -> binary end function comment 2진수를 10진수로 변환...
# 코딩 클럽 2권 계산기의 애플리케이션의 함수 모듈 # 팩토리얼 함수: def factorial(n): return "factorial (!)" # 로마 숫자로 변환하는 함수: def to_roman(n): return "-> roman" # 10진수를 2진수로 변환하는 함수: def to_binary(n): return "-> binary" # 2진수를 10진수로 변환하는 함수: def from_binary(n): return "binary -> 10" # 숫자에 대해 제곱급을 찾는 함수: def square(n): ...
Python
zaydzuhri_stack_edu_python
string Created on 25/mag/2015 @author: Riccardo Cappuzzo This function creates the destinations database. Call this only once, if the structure of the db is wrong, delete it and restart. CAREFUL WHEN DELETING import sqlite3 function create_destination_table begin string Creates the database, call this only once. set sq...
''' Created on 25/mag/2015 @author: Riccardo Cappuzzo This function creates the destinations database. Call this only once, if the structure of the db is wrong, delete it and restart. CAREFUL WHEN DELETING ''' import sqlite3 def create_destination_table(): """Creates the database, call this only once.""" s...
Python
zaydzuhri_stack_edu_python
comment TK's Sample Video Add-on #### comment We hope this helps you create #### comment Your own video add-on using #### comment This simple template #### comment Thanks to all the Dev's for #### comment All the work you do #### comment Thanks to Whufclee #### comment Thanks to Trent Bumgarner #### comment Modules Nee...
######################################## #### TK's Sample Video Add-on #### #### We hope this helps you create #### #### Your own video add-on using #### #### This simple template #### #### Thanks to all the Dev's for #### #### All the work you do #### #### Thanks to Whufclee ...
Python
zaydzuhri_stack_edu_python
function build self begin if allowMethods is none or length allowMethods == 0 and denyMethods is none or length denyMethods == 0 begin raise call NameError string No statements defined for the policy end set policy = dict string principalId principalId ; string policyDocument dict string Version version ; string Statem...
def build(self): if ((self.allowMethods is None or len(self.allowMethods) == 0) and (self.denyMethods is None or len(self.denyMethods) == 0)): raise NameError("No statements defined for the policy") policy = { 'principalId': self.principalId, 'policyD...
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import sys append path string ../../../github/module/ from date_function import date_diff function moving_agg method data level index value window periods sort_col=none begin string Explain: 移動平均を求める。リーケージに注意 Args: method(sum|avg): data(DF) : 入力データ level(list) : 集計を行う粒度。最終的に欠損値補完を...
import numpy as np import pandas as pd import sys sys.path.append('../../../github/module/') from date_function import date_diff def moving_agg(method, data, level, index, value, window, periods, sort_col=None): ''' Explain: 移動平均を求める。リーケージに注意 Args: method(sum|avg): data(DF) ...
Python
zaydzuhri_stack_edu_python
function make_dummy_protocol_resource protocol_id begin return call ProtocolResource protocol_id=protocol_id created_at=call datetime year=2021 month=1 day=1 tzinfo=utc source=call ProtocolSource directory=call Path string /dev/null main_file=call Path string /dev/null config=call JsonProtocolConfig schema_version=123 ...
def make_dummy_protocol_resource(protocol_id: str) -> ProtocolResource: return ProtocolResource( protocol_id=protocol_id, created_at=datetime(year=2021, month=1, day=1, tzinfo=timezone.utc), source=ProtocolSource( directory=Path("/dev/null"), main_file=Path("/dev/null...
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup import random import urllib.request import time import lxml import re import threading from fake_useragent import UserAgent set lock = lock set successNum = 1 set ips = list set ipPrevious = string set fp = open string /Users/logan/Desktop/DataFactory/Homework1/Final/Data...
import requests from bs4 import BeautifulSoup import random import urllib.request import time import lxml import re import threading from fake_useragent import UserAgent lock = threading.Lock() successNum = 1 ips = [] ipPrevious = "" fp = open("/Users/logan/Desktop/DataFactory/Homework1/Final/Data.txt", 'w+') fp2 = ope...
Python
zaydzuhri_stack_edu_python
if num1 == num2 begin print string Os dois numeros são iguais end else if num1 > num2 begin print format string {} é maior que {} num1 num2 end else begin print format string {} é maior que {} num2 num1 end
if num1 == num2: print('Os dois numeros são iguais') elif num1 > num2: print('{} é maior que {}'.format(num1, num2)) else: print('{} é maior que {}'.format(num2, num1))
Python
zaydzuhri_stack_edu_python
function accuracy output target topk=tuple 1 begin set maxk = max topk set batch_size = size target 0 set tuple _ pred = call topk maxk 1 true true set pred = t dist set correct = call eq call expand_as pred set res = list for k in topk begin set correct_k = sum 0 keepdim=true append res call mul_ 100.0 / batch_size e...
def accuracy(output, target, topk=(1,)): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=Tru...
Python
nomic_cornstack_python_v1
function test_birthday self begin set data = dict string email format string {}@example.com call words 1 ; string birth_month string Jan call login username=email password=TEST_USER_PASSWORD set response = put url data format=string json assert equal status_code HTTP_400_BAD_REQUEST assert equal json response dict stri...
def test_birthday(self): data = { 'email': '{}@example.com'.format(lorem_ipsum.words(1)), 'birth_month': 'Jan' } self.client.login(username=self.user.email, password=TEST_USER_PASSWORD) response = self.client.put(self.url, data, format='json') self.assertE...
Python
nomic_cornstack_python_v1
function _final_logits self num_channels begin return 2 * num_channels * vocab_size end function
def _final_logits(self, num_channels): return 2 * num_channels * self.vocab_size
Python
nomic_cornstack_python_v1
function test_user_signup self begin set user_signup_test = call signup string signup_test string signup@test.com string HASHED_PASSWORD none commit session assert is instance user_signup_test User call signup string signup_test string signup_invalid@test.com string HASHED_PASSWORD none try begin commit session end exc...
def test_user_signup(self): user_signup_test = User.signup( "signup_test", "signup@test.com", "HASHED_PASSWORD", None ) db.session.commit() self.assertIsInstance(user_signup_test, User) User.signup( "signup_test", ...
Python
nomic_cornstack_python_v1
import socket import threading from log_utils import log_action import protocol import util class ConnectionHandler extends Thread begin function __init__ self sock address node begin call __init__ self name=string TCP Connection Handler daemon=true set socket = sock call settimeout 10 set address = address set node = ...
import socket import threading from log_utils import log_action import protocol import util class ConnectionHandler(threading.Thread): def __init__(self, sock, address, node): threading.Thread.__init__(self, name='TCP Connection Handler', daemon=True) self.socket = sock self.socket.settim...
Python
zaydzuhri_stack_edu_python
while true begin set ps = lower input string Do you want priority shipping? Type Y for Yes or N for No: if ps == string y or ps == string n begin set ps = ps == string y break end end if quantity < 11 begin set pc = decimal quantity * 21 end else if quantity > 10 begin set pc = decimal quantity * 15.58 end if ps == tru...
while True: ps = input("Do you want priority shipping? Type Y for Yes or N for No: ").lower() if ps == "y" or ps == "n": ps = ps == "y" break if quantity < 11: pc = float(quantity) * 21 elif quantity > 10: pc = float(quantity) * 15.58 if ps == True: sc = quantity * 2 + 60...
Python
zaydzuhri_stack_edu_python
comment climbing stairs comment it has n stairs to reach the top, each time you can either climb 1 or 2 steps comment find out the numbers of ways to the top class Solution extends object begin function climbStairs self n begin set a = 1 set b = 1 for _ in range n begin set tuple a b = tuple b a + b end return a end fu...
# climbing stairs # it has n stairs to reach the top, each time you can either climb 1 or 2 steps # find out the numbers of ways to the top class Solution(object): def climbStairs(self, n): a = b = 1 for _ in range(n): a, b = b, a + b return a # basic Fibonacci Sequence ...
Python
zaydzuhri_stack_edu_python
function __create_stimulus self stimulus begin string ! @brief Create stimulus for oscillators in line with stimulus map and parameters. @param[in] stimulus (list): Stimulus for oscillators that is represented by list, number of stimulus should be equal number of oscillators. if length stimulus != _num_osc begin raise ...
def __create_stimulus(self, stimulus): """! @brief Create stimulus for oscillators in line with stimulus map and parameters. @param[in] stimulus (list): Stimulus for oscillators that is represented by list, number of stimulus should be equal number of oscillators. ...
Python
jtatman_500k
function normalize_number number begin string Normalize a phone number str to format 18051234567 set strip_chars = string ()-.+ for char in strip_chars begin set number = replace number char string end if length number == 10 begin set number = format string 1{} number end return number end function
def normalize_number(number): """Normalize a phone number str to format 18051234567""" strip_chars = '()-.+ ' for char in strip_chars: number = number.replace(char, '') if len(number) == 10: number = "1{}".format(number) return number
Python
zaydzuhri_stack_edu_python
function get_recording self begin return tuple __cs_recording __full_recording end function
def get_recording(self): return self.__cs_recording, self.__full_recording
Python
nomic_cornstack_python_v1
for i in range th_ness * 2 + x begin if i in range 0 th_ness begin print string | * i string + string - * 2 * t + l string + string | * i sep=string set t = t - 1 end else if i in range th_ness + x th_ness * 2 + x begin print string | * th_ness * 2 + x - i - 1 string + string - * 2 * j + l + 2 string + string | * th_ne...
for i in range(th_ness*2+x): if(i in range(0,th_ness)): print("|"*i,"+","-"*(2*t+l),"+","|"*i,sep='') t-=1; elif(i in range(th_ness+x, th_ness*2+x)): print("|"*(th_ness*2+x-i-1),"+","-"*(2*j+l+2),"+","|"*(th_ness*2+x-i-1),sep='') j+=1 elif(i in range(th_ness,...
Python
zaydzuhri_stack_edu_python
function addrow self y addlist begin for x in call xrange 0 x begin call store y x call retrieve y x + addlist at x end end function
def addrow(self, y, addlist): for x in xrange(0, self.x): self.store(y,x, self.retrieve(y,x)+addlist[x])
Python
nomic_cornstack_python_v1
function parler self joueur begin if _lock == false begin print string .. .. .. call gagnerEnergie _energie print string + + string _energie + string energies! set _lock = true input end else begin print string Je t'es deja soigne. end end function
def parler(self, joueur): if self._lock == False: print(".. .. ..") joueur.gagnerEnergie(self._energie) print("+ " + str(self._energie) + " energies!") self._lock = True input() else: print("Je t'es deja soigne.")
Python
nomic_cornstack_python_v1
import pandas as pd import matplotlib.pyplot as plt from bokeh.plotting import figure , show from bokeh.models import DatetimeTickFormatter comment lineplot function function clean_lineplot x y fig color=string blue linew=2 begin string it plots clean lineplots with bokeh, but the figure has to be specified before its ...
import pandas as pd import matplotlib.pyplot as plt from bokeh.plotting import figure, show from bokeh.models import DatetimeTickFormatter # lineplot function def clean_lineplot(x, y, fig, color='blue', linew=2): """ it plots clean lineplots with bokeh, but the figure has to be specified before its usage. ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import h5py set sf = string /home/kazu/bsi3n4_m/phono3py_113_fc2_224_sym_monk_shift/noiso_ave_pp/kappa-m8820.ave_pp.hdf5 set gf = string /home/kazu/bge3n4_m/phono3py_113_fc2_224_sym/noiso_ave_pp/kappa-m8820.ave_pp.hdf5 set cf = string /home...
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import h5py sf = "/home/kazu/bsi3n4_m/phono3py_113_fc2_224_sym_monk_shift/noiso_ave_pp/kappa-m8820.ave_pp.hdf5" gf = "/home/kazu/bge3n4_m/phono3py_113_fc2_224_sym/noiso_ave_pp/kappa-m8820.ave_pp.hdf5" cf = "/home/kazu/bc3n4_m/phono3py_113_fc2_22...
Python
zaydzuhri_stack_edu_python
from nltk.tokenize import word_tokenize , sent_tokenize from nltk.tag import pos_tag from nltk.probability import FreqDist from nltk.corpus import stopwords from nltk.stem import PorterStemmer , LancasterStemmer , SnowballStemmer , WordNetLemmatizer from nltk.chunk import ne_chunk set sentences = list string Natural la...
from nltk.tokenize import word_tokenize, sent_tokenize from nltk.tag import pos_tag from nltk.probability import FreqDist from nltk.corpus import stopwords from nltk.stem import PorterStemmer, LancasterStemmer, SnowballStemmer, WordNetLemmatizer from nltk.chunk import ne_chunk sentences = [ 'Natural language p...
Python
zaydzuhri_stack_edu_python
function docurl request begin set project = get GET string project set version = get GET string version LATEST set doc = get GET string doc string index if project is none begin return call Response dict string error string Need project and doc status=HTTP_400_BAD_REQUEST end set project = call get_object_or_404 Projec...
def docurl(request): project = request.GET.get('project') version = request.GET.get('version', LATEST) doc = request.GET.get('doc', 'index') if project is None: return Response({'error': 'Need project and doc'}, status=status.HTTP_400_BAD_REQUEST) project = get_object_or_404(Project, slug=p...
Python
nomic_cornstack_python_v1
import collections from typing import List class Solution begin function maxNumberOfFamilies self n reservedSeats begin set aisleSeatsDict = default dictionary set for tuple row seat in reservedSeats begin add aisleSeatsDict at row - 1 seat - 1 end set left_spot = set literal 1 2 3 4 set right_spot = set literal 5 6 7 ...
import collections from typing import List class Solution: def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int: aisleSeatsDict = collections.defaultdict(set) for row, seat in reservedSeats: aisleSeatsDict[row - 1].add(seat - 1) left_spot = {1, 2, 3, 4} ...
Python
zaydzuhri_stack_edu_python
function check_remote_address remote_address begin if remote_address not in multiple_tested_servers begin append multiple_tested_servers remote_address end end function
def check_remote_address(remote_address): if remote_address not in world.f_cfg.multiple_tested_servers: world.f_cfg.multiple_tested_servers.append(remote_address)
Python
nomic_cornstack_python_v1
function _PostRequest self request request_data begin if not call _ServerIsRunning begin raise call ValueError string Not connected to server end function MakeIncompleteFile name file_data begin return dict string type string full ; string name name ; string text file_data at string contents end function set file_data ...
def _PostRequest( self, request, request_data ): if not self._ServerIsRunning(): raise ValueError( 'Not connected to server' ) def MakeIncompleteFile( name, file_data ): return { 'type': 'full', 'name': name, 'text': file_data[ 'contents' ], } file_data = request...
Python
nomic_cornstack_python_v1
function get_dataset_info self dataset_id frame_count begin set dataset_frames = list set query_pages = integer frame_count / FRAME_QUERY_LIMIT set remainder = frame_count % FRAME_QUERY_LIMIT if remainder begin set query_pages = query_pages + 1 end set var_data = dict string id dataset_id for page_n in range query_pag...
def get_dataset_info(self, dataset_id, frame_count): dataset_frames = [] query_pages = int(frame_count / self.FRAME_QUERY_LIMIT) remainder = frame_count % self.FRAME_QUERY_LIMIT if remainder: query_pages += 1 var_data = {"id": dataset_id} for page_n in range(q...
Python
nomic_cornstack_python_v1
function charge_types self begin return keys charges end function
def charge_types(self): return self.charges.keys()
Python
nomic_cornstack_python_v1
function save self user=none begin set user = user or user set run = save user=user if string suites in changed_data begin comment if this is empty, then don't make any changes, because comment either there are no suites, or this came from the read comment only suite list. delete permanent=true for tuple i suite in enu...
def save(self, user=None): user = user or self.user run = super(RunForm, self).save(user=user) if "suites" in self.changed_data: # if this is empty, then don't make any changes, because # either there are no suites, or this came from the read # only su...
Python
nomic_cornstack_python_v1
import tensorflow as tf comment Load data set mnist = mnist set tuple tuple x_train y_train tuple x_test y_test = call load_data comment Normalize your data set x_train = call normalize x_train 1 set x_test = call normalize x_test 1 comment Reshabe to fit into Convolutional Layers set CHANNELS = 1 set x_train = reshape...
import tensorflow as tf # Load data mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() # Normalize your data x_train = tf.keras.utils.normalize(x_train, 1) x_test = tf.keras.utils.normalize(x_test, 1) # Reshabe to fit into Convolutional Layers CHANNELS = 1 x_train =...
Python
zaydzuhri_stack_edu_python
function increase_age self s begin set age = age + 1 set days = 0 if age >= 35 and sexual_activity == 1 begin set sexual_activity = 0 remove high_sexual_activity identifier end comment exclude age == 65; they will be replaced next timestep if age % 10 == 5 and age < 65 begin set age_group = integer floor age + 5 / 10 -...
def increase_age(self,s): self.age += 1 self.days = 0 if self.age >= 35 and self.sexual_activity == 1: self.sexual_activity = 0 s.high_sexual_activity.remove(self.identifier) #exclude age == 65; they will be replaced next timestep if self.age % 10...
Python
nomic_cornstack_python_v1
from coreapi import Document , Link , Field function get_homepage begin string Return the top level Document object for the API root. return call Document url=string / title=string Home content=dict string new_game call Link action=string post end function function get_game instance begin string Return a Document objec...
from coreapi import Document, Link, Field def get_homepage(): """ Return the top level Document object for the API root. """ return Document( url='/', title='Home', content={ 'new_game': Link(action='post') } ) def get_game(instance): """ Retur...
Python
zaydzuhri_stack_edu_python
function deserialize self data begin if not data begin return none end if data and data at 0 == string # begin return none end set root = call TreeNode data at 0 set rlist = list root set tuple p c = tuple 0 1 while c < length data begin if data at c != string # begin append rlist call TreeNode data at c end else begin...
def deserialize(self, data): if not data: return None if data and data[0] == '#': return None root = TreeNode(data[0]) rlist = [root] p,c = 0,1 while c < len(data): if data[c] != '#': rlist.append(TreeNode(data[c])) else: rlist.append(None) if data[c+1] != '#': ...
Python
nomic_cornstack_python_v1
function main begin set primary = dict for line in open salmonf begin set data = split right strip line string if data at 0 not in primary begin set primary at data at 0 = set list data at 1 end else begin add primary at data at 0 data at 1 end end set part = list set look = call LookupNames stdfil with open outfil s...
def main(): primary = {} for line in open(salmonf): data = line.rstrip().split("\t") if data[0] not in primary: primary[data[0]] = set([data[1]]) else: primary[data[0]].add(data[1]) part = [] look = LookupNames(stdfil) with open(outfil, 'w') as out: ...
Python
nomic_cornstack_python_v1
function my_turn_in_place robot angle speed begin comment #### comment TODO: Implement your version of a rotating in place function using the comment robot.drive_wheels() function. comment #### set normalizedAngle = angle % 360 set turnLeft = normalizedAngle <= 180 set innerAngle = if expression turnLeft then normalize...
def my_turn_in_place(robot, angle, speed): # #### # TODO: Implement your version of a rotating in place function using the # robot.drive_wheels() function. # #### normalizedAngle = angle % 360 turnLeft = normalizedAngle <= 180 innerAngle = normalizedAngle if turnLeft else 360 - normalizedAngle dist = get_dista...
Python
nomic_cornstack_python_v1
async function find_dungeon_from_name self ctx name database difficulty=none begin set dungeons = call get_dungeons_from_nickname lower name if not dungeons begin set dungeons = call get_dungeons_from_name name if length dungeons == 0 begin await call send string No dungeons found! return end if length dungeons > 1 beg...
async def find_dungeon_from_name(self, ctx, name, database: "DungeonContext", difficulty: str = None): dungeons = database.get_dungeons_from_nickname(name.lower()) if not dungeons: dungeons = database.get_dungeons_from_name(name) if len(dungeons) == 0: await ctx.s...
Python
nomic_cornstack_python_v1
function test_gcp_iam_organization_role_permission_add_command client begin set gcp_iam_organization_role_update_request = call Mock return_value=dict set mock_response = call load_mock_response string role/organization_role_get.json set gcp_iam_organization_role_get_request = call Mock return_value=mock_response set r...
def test_gcp_iam_organization_role_permission_add_command(client): client.gcp_iam_organization_role_update_request = Mock(return_value={}) mock_response = load_mock_response('role/organization_role_get.json') client.gcp_iam_organization_role_get_request = Mock(return_value=mock_response) role_name = "o...
Python
nomic_cornstack_python_v1
function sumlist begin set list = tuple 12 3 4 5 6 for i in list begin return i + i end end function print call sumlist function upperLower a begin if i in a == title a begin return i end end function print call upperLower string the Quick Brown fox
def sumlist(): list=(12,3,4,5,6) for i in list: return i +i print(sumlist()) def upperLower(a): if i in a==a.title(): return i print(upperLower("the Quick Brown fox"))
Python
zaydzuhri_stack_edu_python
function create_user connection user begin set sql = string INSERT INTO Users(Username,Email,Password) VALUES(?,?,?) set cursor = call cursor execute cursor sql user commit connection set userID = lastrowid call create_collection connection tuple string userID string All Media return userID end function
def create_user(connection, user): sql = 'INSERT INTO Users(Username,Email,Password) VALUES(?,?,?)' cursor = connection.cursor() cursor.execute(sql,user) connection.commit() userID = cursor.lastrowid create_collection(connection, (str(userID), "All Media")) return userID
Python
nomic_cornstack_python_v1
from story_screen import StoryPage , StoryScreen class StoryInitialiser begin function __init__ self window begin set window = window set pages = list append pages call StoryPage dict string text string Driver: Help the driver collect as many berries as possible so that the alien will spare her another day. ; string i...
from story_screen import StoryPage, StoryScreen class StoryInitialiser: def __init__(self, window): self.window = window self.pages = [] self.pages.append(StoryPage( { "text": "Driver: Help the driver collect as many berries as possible so that " ...
Python
zaydzuhri_stack_edu_python
function saturation self saturation begin string Set the group saturation. :param saturation: Saturation in decimal percent (0.0-1.0). if saturation < 0 or saturation > 1 begin raise call ValueError string Saturation must be a percentage represented as decimal 0-1.0 end set _saturation = saturation call _update_color i...
def saturation(self, saturation): """ Set the group saturation. :param saturation: Saturation in decimal percent (0.0-1.0). """ if saturation < 0 or saturation > 1: raise ValueError("Saturation must be a percentage " "represented as decimal 0-1.0...
Python
jtatman_500k
function test_noobs self begin call main end function
def test_noobs(self): self.main()
Python
nomic_cornstack_python_v1
function get_data self begin raise call NotImplementedError string Missing implementation for get_data end function
def get_data(self): raise NotImplementedError("Missing implementation for get_data")
Python
nomic_cornstack_python_v1
from Vehicle import Vehicle from Person import Person class Microbus extends Vehicle begin function __init__ self carga_util lista_pasajeros max_pasajeros quantity consume capacity begin call __init__ quantity consume capacity set carga_util = carga_util set lista_pasajeros = lista_pasajeros set max_pasajeros = max_pas...
from Vehicle import Vehicle from Person import Person class Microbus(Vehicle): def __init__(self, carga_util, lista_pasajeros: list, max_pasajeros, quantity, consume, capacity): super().__init__(quantity, consume, capacity) self.carga_util = carga_util self.lista_pasajeros = lista_pasajero...
Python
zaydzuhri_stack_edu_python
function test_rolls_back_on_error self monkeypatch begin set copy_foreign_key_to_m2m_field_mock = call Mock wraps=copy_foreign_key_to_m2m_field set attribute string datahub.dbmaintenance.tasks.copy_foreign_key_to_m2m_field copy_foreign_key_to_m2m_field_mock set attribute string datahub.dbmaintenance.tasks.logger.info c...
def test_rolls_back_on_error(self, monkeypatch): copy_foreign_key_to_m2m_field_mock = Mock(wraps=copy_foreign_key_to_m2m_field) monkeypatch.setattr( 'datahub.dbmaintenance.tasks.copy_foreign_key_to_m2m_field', copy_foreign_key_to_m2m_field_mock, ) monkeypatch.set...
Python
nomic_cornstack_python_v1
function DumpAsCSV self separator=string , file=stdout begin string dump as a comma separated value file for row in range 1 maxRow + 1 begin set sep = string for column in range 1 maxColumn + 1 begin write file string %s"%s" % tuple sep call GetCellValue column row string set sep = separator end write file string end ...
def DumpAsCSV (self, separator=",", file=sys.stdout): """dump as a comma separated value file""" for row in range(1, self.maxRow + 1): sep = "" for column in range(1, self.maxColumn + 1): file.write("%s\...
Python
jtatman_500k
function name self begin return get pulumi self string name end function
def name(self) -> str: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
import math function snell_descartes n1 n2 ang1 begin set ang2 = n1 * sin call radians ang1 / n2 return call degrees call asin ang2 end function
import math def snell_descartes(n1,n2,ang1): ang2 = (n1 * (math.sin(math.radians(ang1)))) / n2 return math.degrees(math.asin(ang2))
Python
zaydzuhri_stack_edu_python
comment เก็บค่าน้ำมัน set gas = dict string Gasoline 95 29.16 ; string Gasoline 91 25.3 ; string Gasohol 91 21.68 ; string Gasohol E20 20.2 ; string Gasohol 95 21.2 ; string Diesel 21.1 comment แสดงราคาน้ำมัน for key in range length keys gas begin set k = list keys gas at key print string key + 1 + string . k string : ...
# เก็บค่าน้ำมัน gas = {"Gasoline 95": 29.16,"Gasoline 91":25.30,"Gasohol 91":21.68,"Gasohol E20":20.2,"Gasohol 95":21.2,"Diesel":21.1} # แสดงราคาน้ำมัน for key in range(len(gas.keys())): k = list(gas.keys())[key] print(str(key+1)+".",k, ":", gas[k], "BAHT") # เก็บประเภทน้ำมันเป็นตัวเลขและราคา oil = int(i...
Python
zaydzuhri_stack_edu_python
function setUp self begin set app = app set client = call test_client self set testing = true set order = mock_data at string order set data = dumps mock_data at string admin set response = post string api/v1/login content_type=string application/json data=data set admin_token_dict = loads data set data = dumps mock_da...
def setUp(self): self.app = app self.client = self.app.test_client(self) self.app.testing = True self.order = mock_data['order'] data = json.dumps(mock_data['admin']) response = self.client.post( 'api/v1/login', content_type="application/json", data=data) ...
Python
nomic_cornstack_python_v1
import time import math comment Import dstarlite C module. from algorithm import field_d_star as dstarlite_c from abstract_algorithm import AbstractAlgorithm class DStarLite extends AbstractAlgorithm begin string function __init__ self map_state begin call __init__ self map_state set planner_name = string D* Lite end ...
import time import math from algorithm import field_d_star as dstarlite_c # Import dstarlite C module. from .abstract_algorithm import AbstractAlgorithm class DStarLite(AbstractAlgorithm): """ """ def __init__(self, map_state): AbstractAlgorithm.__init__(self, map_state) self.planner_na...
Python
zaydzuhri_stack_edu_python
function runGame begin comment Game state comment initial location of the player set player = list 2 4 comment initial score set score = 0 comment initial cube locations set cubes = list list 0 0 list 3 0 list 4 0 print string Welcome to cubes! Quit by typing 'quit' call prettyPrint cubes player score comment Main loop...
def runGame(): # Game state player = [2,4] # initial location of the player score = 0 # initial score cubes = [[0,0], [3,0], [4,0]] # initial cube locations print("Welcome to cubes! Quit by typing 'quit'") prettyPrint(cubes, player, score) # Main loop ...
Python
nomic_cornstack_python_v1
import socket import sys set port = 9000 set s = call socket call bind tuple string port call listen 5 comment List of registered servers and there public keys set servers = list dict string serverName string Elam Test Server ; string publicKey string My Server Public Key while true begin set tuple conn addr = call ac...
import socket import sys port = 9000 s = socket.socket() s.bind(('', port)) s.listen(5) # List of registered servers and there public keys servers = [ {'serverName': 'Elam Test Server', 'publicKey': 'My Server Public Key'} ] while True: conn, addr = s.accept() clientData = conn.recv(1024).decode() ...
Python
zaydzuhri_stack_edu_python
function percentFixationScreen duration=1 begin set trialDataDict at string pointsStartTime = Timestamp if trialDataDict at string trialTotal == 0 begin set pointsScreen = call TextStim win=win0 text=string end else begin set percent = round trialDataDict at string points / trialDataDict at string trialTotal * 10 * 100...
def percentFixationScreen(duration=1): trialDataDict['pointsStartTime'] = lt.GetLastResult().Timestamp if trialDataDict['trialTotal'] == 0: pointsScreen = visual.TextStim(win=win0, text='') else: percent = round( trialDataDict['points'] / ((trialDataDict['trialTotal']) * 10) * 10...
Python
nomic_cornstack_python_v1
async function test_active_zone_prefers_smaller_zone_if_same_distance hass begin set latitude = 32.8806 set longitude = - 117.237561 assert await call async_setup_component hass DOMAIN dict string zone list dict string name string Small Zone ; string latitude latitude ; string longitude longitude ; string radius 250 di...
async def test_active_zone_prefers_smaller_zone_if_same_distance( hass: HomeAssistant, ) -> None: latitude = 32.880600 longitude = -117.237561 assert await setup.async_setup_component( hass, zone.DOMAIN, { "zone": [ { "name": "Small...
Python
nomic_cornstack_python_v1
function factorial n begin comment n! can also be defined as n * (n-1)! if n <= 1 begin return 1 end else begin print n / 0 return n * call factorial n - 1 end end function comment hanlding 2 errors instead of crashing the program try begin print call factorial 900 end except tuple RecursionError OverflowError MemoryEr...
def factorial(n): # n! can also be defined as n * (n-1)! if n <= 1: return 1 else: print( n / 0) return n * factorial(n - 1) # hanlding 2 errors instead of crashing the program try: print(factorial(900)) except (RecursionError, OverflowError, MemoryError): print("This prog...
Python
zaydzuhri_stack_edu_python
import tkinter from tkinter import * from tkinter import messagebox from tkinter import filedialog from tkinter.filedialog import asksaveasfile comment import numpy as np comment import matplotlib.pyplot as plt import PIL from PIL import Image , ImageDraw , ImageFont , ImageTk import os , sys set img = string global fu...
import tkinter from tkinter import * from tkinter import messagebox from tkinter import filedialog from tkinter.filedialog import asksaveasfile #import numpy as np #import matplotlib.pyplot as plt import PIL from PIL import Image, ImageDraw, ImageFont, ImageTk import os, sys img= "global" def open_imag(): top.fil...
Python
zaydzuhri_stack_edu_python
function new_formula self frmla begin set formula = frmla set lexer = call Lexer frmla set parser = call Parser lexer set interpreter = call Interpreter parser set vd = none end function
def new_formula(self, frmla): self.formula = frmla self.lexer = ast.Lexer(frmla) self.parser = ast.Parser(self.lexer) self.interpreter = ast.Interpreter(self.parser) self.vd = None
Python
nomic_cornstack_python_v1
from tkinter import font from tkinter.constants import CENTER from PIL import ImageTk , Image import logging import tkinter as tk import sys from objects import Block , Table class View begin function __init__ self master controller begin set controller = controller set master = master call grid_columnconfigure 0 weigh...
from tkinter import font from tkinter.constants import CENTER from PIL import ImageTk, Image import logging import tkinter as tk import sys from objects import Block, Table class View(): def __init__(self, master, controller) -> None: self.controller = controller self.master = master self...
Python
zaydzuhri_stack_edu_python
function get_forced_dtypes self dtypes begin if is instance dtypes list begin if length dtypes != shape at 1 begin raise call ValueError format string Length mismatch: Length of `dtypes` ({}) has to equal the number of columns ({}). length dtypes shape at 1 end set dtypes_forced = dictionary zip columns dtypes end else...
def get_forced_dtypes(self, dtypes: TYPE_DTYPE_INPUT) -> TYPE_DSTR: if isinstance(dtypes, list): if len(dtypes) != self.df.shape[1]: raise ValueError("Length mismatch: Length of `dtypes` ({}) " "has to equal the number of columns ({})." ...
Python
nomic_cornstack_python_v1
comment Find words that are 8 letter long on this text ; set text = string Without, the night was cold and wet, but in the small parlour of Laburnum villa the blinds were drawn and the fire burned brightly. Father and son were at chess; the former, who possessed ideas about the game involving radical chances, putting h...
# Find words that are 8 letter long on this text ; text = """Without, the night was cold and wet, but in the small parlour of Laburnum villa the blinds were drawn and the fire burned brightly. Father and son were at chess; the former, who possessed ideas about the game involving radical chances, putting his king...
Python
zaydzuhri_stack_edu_python
import time from selenium import webdriver comment browser = webdriver.Chrome() set browser = call Firefox get browser string https://opensource-demo.orangehrmlive.com/index.php/auth/login call send_keys string Admin call send_keys string admin123 call click sleep 5 set page_title = title print page_title assert page_t...
import time from selenium import webdriver #browser = webdriver.Chrome() browser = webdriver.Firefox() browser.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login") browser.find_element_by_name("txtUsername").send_keys("Admin") browser.find_element_by_name("txtPassword").send_keys("admin123") br...
Python
zaydzuhri_stack_edu_python
function get_months_of_year year begin string Returns the number of months that have already passed in the given year. This is useful for calculating averages on the year view. For past years, we should divide by 12, but for the current year, we should divide by the current month. set current_year = year if year == cur...
def get_months_of_year(year): """ Returns the number of months that have already passed in the given year. This is useful for calculating averages on the year view. For past years, we should divide by 12, but for the current year, we should divide by the current month. """ current_year = n...
Python
jtatman_500k
function SetDepth *args **kwargs begin return call Bitmap_SetDepth *args keyword kwargs end function
def SetDepth(*args, **kwargs): return _gdi_.Bitmap_SetDepth(*args, **kwargs)
Python
nomic_cornstack_python_v1
function openLogFile fname begin set reopen = false try begin set curstat = call stat fname end except any begin set reopen = true end global getLogDict comment print("top: reopen(%s)=%s" % (fname, reopen)) if not reopen and get getLogDict fname begin comment print("found getLogDict.get(" + fname + ")") set d = getLogD...
def openLogFile(fname): reopen = False try: curstat = os.stat(fname) except: reopen = True global getLogDict # print("top: reopen(%s)=%s" % (fname, reopen)) if not reopen and getLogDict.get(fname): # print("found getLogDict.get(" + fname + ")") d = getLogDict[fnam...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import re function pre_match r begin return string at slice : start r : end function function post_match r begin return string at slice call end : : end function if __name__ == string __main__ begin with open string ./jawiki-country.txt string r as f begin for cat in read lines f begin...
# -*- coding: utf-8 -*- import re def pre_match(r): return r.string[:r.start()] def post_match(r): return r.string[r.end():] if __name__ == '__main__': with open('./jawiki-country.txt', 'r') as f: for cat in f.readlines(): if 'Category' in cat: r = post_match(re.sea...
Python
zaydzuhri_stack_edu_python
class Solution begin function solve self A N X begin if X % 2 != 0 begin return A end else begin pass end end function end class if __name__ == string __main__ begin set S = call Solution set T = integer input for _ in range T begin set tuple N X = map int split input set A = list map int split input print call solve A...
class Solution: def solve(self, A, N, X): if X % 2 != 0: return A else: pass if __name__ == '__main__': S = Solution() T = int(input()) for _ in range(T): N, X = map(int, input().split()) A = list(map(int, input().split())) print(S.solve(A...
Python
zaydzuhri_stack_edu_python
comment Function to calculate the maximum, minimum, and average values function calculate_metrics list begin comment Calculate the maximum value set maximum = max list comment Calculate the minimum value set minimum = min list comment Calculate the average set n = length list set total = 0 for num in list begin set tot...
# Function to calculate the maximum, minimum, and average values def calculate_metrics(list): # Calculate the maximum value maximum = max(list) # Calculate the minimum value minimum = min(list) # Calculate the average n = len(list) total = 0 for num in list: total += num...
Python
jtatman_500k
comment Define a 2-dimensional point object class Point extends object begin comment Constructor Method function __init__ self x y begin set X = x set Y = y end function comment String representation of the object GOES OVER PRINT COMMAND WHERE PRINT IS LOCATION IN MEMORY function __repr__ self begin return format strin...
# Define a 2-dimensional point object class Point(object): # Constructor Method def __init__(self,x,y): self.X = x self.Y = y # String representation of the object GOES OVER PRINT COMMAND WHERE PRINT IS LOCATION IN MEMORY def __repr__(self): return "({0},{1})".format(self.X, se...
Python
zaydzuhri_stack_edu_python
function test_card_bread_cup_player_card_bonus_active self begin set has_bread_cup_bonus = true for tuple enum english in list tuple FAMILY_CUP string Cup tuple FAMILY_BREAD string Bread begin with call subTest family=english begin set card = call new_red_card name=string Red fee=2 game=game family=enum call add_card c...
def test_card_bread_cup_player_card_bonus_active(self): self.player_card.has_bread_cup_bonus = True for (enum, english) in [ (cards.Card.FAMILY_CUP, 'Cup'), (cards.Card.FAMILY_BREAD, 'Bread'), ]: with self.subTest(family=english): ...
Python
nomic_cornstack_python_v1
function company_size_clean s begin if s begin set m = match string (?P<size_low>\d+)-(?P<size_high>\d+) s if m and string size_low in call groupdict and string size_high in call groupdict begin return tuple integer call groupdict at string size_low integer call groupdict at string size_high end comment a tuple of None...
def company_size_clean(s): if s: m = re.match(r"(?P<size_low>\d+)-(?P<size_high>\d+)", s) if m and 'size_low' in m.groupdict() and 'size_high' in m.groupdict(): return (int(m.groupdict()['size_low']), int(m.groupdict()['size_high'])) # a tuple of None to enforce the to_list() lat...
Python
nomic_cornstack_python_v1
comment Anagrams comment Given an array of strings, return all groups of strings that are anagrams. comment Example comment Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"]. comment Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"]. comment All inputs will be in lower-case clas...
# Anagrams # Given an array of strings, return all groups of strings that are anagrams. # # Example # Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"]. # Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"]. # # All inputs will be in lower-case class Solution: # @param strs: ...
Python
zaydzuhri_stack_edu_python
function build_weights group begin set weight_str = string Weight of set weight_str = weight_str + group + string set weight_str = weight_str + string ----------- for comp in weight_store begin if call determine_group group comp at string group begin set weight_str = weight_str + comp at string component set weight_st...
def build_weights(group): weight_str = "Weight of " weight_str = weight_str + group + '\n' weight_str = weight_str + "----------- \n" for comp in weight_store: if determine_group(group, comp['group']): weight_str = weight_str + comp['component'] weight_str = weight_str + ...
Python
nomic_cornstack_python_v1
async function cardDesc ctx message begin set cardName = message set thisInvalidMessage = INVALID_MESSAGE + string Single Term: Knight / Ace / Devil etc. if cardName == string begin await call sendDelimited ctx thisInvalidMessage return end set fullDeck = await call getFullDeck if fullDeck is none begin return end set...
async def cardDesc(ctx: Context, message: str) -> None: cardName = message thisInvalidMessage = INVALID_MESSAGE + "Single Term: Knight / Ace / Devil etc." if cardName == '': await sendDelimited(ctx, thisInvalidMessage) return fullDeck = await getFullDeck() if fullDeck is None: ...
Python
nomic_cornstack_python_v1
from maxSubArrSum import maxAllSubArraySizeK from heapq import merge , heapify , heappop , heappush from collections import deque import itertools import sys from typing import List comment for x in nums1, find number (same index) in nums2 and check if there is any number larger than x comment (say the number is y>x) o...
from maxSubArrSum import maxAllSubArraySizeK from heapq import merge, heapify,heappop,heappush from collections import deque import itertools import sys from typing import List # for x in nums1, find number (same index) in nums2 and check if there is any number larger than x # (say the number is y>x) on its right side ...
Python
zaydzuhri_stack_edu_python
string Task 6. Вводиться число. Якщо це число додатне, знайти його квадрат, якщо від'ємне, збільшити його на 100, якщо дорівнює 0, не змінювати. function my_fun a begin if a > 0 begin set a = a ^ 2 end else if a < 0 begin set a = a + 100 end else begin a end return a end function set x = decimal input string Input nume...
######################################################## '''Task 6. Вводиться число. Якщо це число додатне, знайти його квадрат, якщо від'ємне, збільшити його на 100, якщо дорівнює 0, не змінювати.''' def my_fun(a): if a>0: a=a**2 elif a<0: a+=100 else: a return a ###############...
Python
zaydzuhri_stack_edu_python
for i in range 2 - 1 - 1 begin set n1 = n1 + a at i set n2 = n2 + b at i end if n1 > n2 begin print n1 end else begin print n2 end
for i in range(2,-1,-1): n1+=a[i] n2+=b[i] if(n1>n2): print(n1) else: print(n2)
Python
zaydzuhri_stack_edu_python
import subprocess , re , shutil from Bio import AlignIO from dendropy import * from numpy import * from random import randint class WeightTreeBuilder begin function __init__ self begin string initialization function return end function function killPolytomyDendro self infile begin string Removed polytomies using dendro...
import subprocess, re, shutil from Bio import AlignIO from dendropy import * from numpy import * from random import randint class WeightTreeBuilder: def __init__(self): '''initialization function''' return def killPolytomyDendro(self, infile): '''Removed polytomies using dendropy''' rawtree = Tree(stream=op...
Python
zaydzuhri_stack_edu_python
import pygame import os import random print call get_fonts call init set FPS = 60 set clock = call Clock set WIDTH = 1366 set HEIGHT = 768 set WINDOW = call set_mode tuple WIDTH HEIGHT call set_caption string Space Invaders comment Assets este preluat de pe internet comment Load images set RED_SPACE_SHIP = load image j...
import pygame import os import random print(pygame.font.get_fonts()) pygame.init() FPS = 60 clock = pygame.time.Clock() WIDTH = 1366 HEIGHT = 768 WINDOW = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Space Invaders") #Assets este preluat de pe internet #Load images RED_SPACE_SHIP = pygame...
Python
zaydzuhri_stack_edu_python
comment result = anime_from_dict(json.loads(json_string)) comment result = anime_to_dict(json.loads(json_string)) from dataclasses import dataclass from typing import Optional , List , Any , TypeVar , Callable , Type , cast from src.moonwalk.types.base import from_float , to_float set T = call TypeVar string T function...
# result = anime_from_dict(json.loads(json_string)) # result = anime_to_dict(json.loads(json_string)) from dataclasses import dataclass from typing import Optional, List, Any, TypeVar, Callable, Type, cast from src.moonwalk.types.base import from_float, to_float T = TypeVar("T") def from_int(x: Any) -> int...
Python
zaydzuhri_stack_edu_python
function testDecodeValidInput self begin set knownValues = tuple tuple list list 48 0 tuple list call BERInteger 2 list 48 3 2 1 2 tuple list call BERInteger 3 list 48 3 2 1 3 tuple list call BERInteger 128 list 48 4 2 2 0 128 tuple list call BERInteger 2 call BERInteger 3 call BERInteger 128 list 48 10 + list 2 1 2 +...
def testDecodeValidInput(self): knownValues = ( ([], [0x30, 0x00]), ([pureber.BERInteger(2)], [0x30, 0x03, 0x02, 0x01, 2]), ([pureber.BERInteger(3)], [0x30, 0x03, 0x02, 0x01, 3]), ([pureber.BERInteger(128)], [0x30, 0x04, 0x02, 0x02, 0, 128]), ( ...
Python
nomic_cornstack_python_v1
function line_ends_in_parentheses line in_parentheses begin set in_quotes = false for x in line begin if in_quotes and x != string " begin continue end if x == string " begin set in_quotes = not in_quotes continue end if in_parentheses begin if x == string ) begin set in_parentheses = false end else if x == string ( be...
def line_ends_in_parentheses(line: str, in_parentheses: bool) -> bool: in_quotes = False for x in line: if in_quotes and x != '"': continue if x == '"': in_quotes = not in_quotes continue if in_parentheses: if x == ')': in_...
Python
nomic_cornstack_python_v1