code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function arrayFromDataset ds offsetBegin offsetEnd begin set shape = tuple offsetEnd - offsetBegin set a = call ndarray shape=shape dtype=dtype set mspace = call create_simple shape set fspace = call get_space call select_hyperslab tuple offsetBegin shape tuple 1 read id mspace fspace a return a end function
def arrayFromDataset(ds, offsetBegin, offsetEnd): shape = (offsetEnd - offsetBegin,) a = np.ndarray(shape=shape, dtype=ds.dtype) mspace = h5py.h5s.create_simple(shape) fspace = ds.id.get_space() fspace.select_hyperslab((offsetBegin,), shape, (1,)) ds.id.read(mspace, fspace, a) return a
Python
nomic_cornstack_python_v1
comment ! /opt/homebrew/bin/python3.9 set v = integer input set array = list for i in range v begin set input_vaule = integer input append array input_vaule end for i in range 1 length array begin for j in range i 0 - 1 begin if array at j < array at j - 1 begin set tuple array at j array at j - 1 = tuple array at j - ...
#! /opt/homebrew/bin/python3.9 v = int(input()) array = list() for i in range(v): input_vaule = int(input()) array.append(input_vaule) for i in range(1, len(array)): for j in range(i, 0, -1): if array[j] < array[j-1]: array[j], array[j-1] = array[j-1], array[j] else: ...
Python
zaydzuhri_stack_edu_python
function c_array ctype values begin set arr = call set arr at slice : : = values return arr end function
def c_array(ctype, values): arr = (ctype*len(values))() arr[:] = values return arr
Python
nomic_cornstack_python_v1
import gi call require_version string Gtk string 3.0 from gi.repository import Gtk from reportlab.platypus import SimpleDocTemplate , PageBreak , Image , Spacer , Paragraph , TableStyle , Table from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from tablaCliente import TablaCliente from sqlite3 imp...
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from reportlab.platypus import (SimpleDocTemplate, PageBreak, Image, Spacer, Paragraph, TableStyle, Table) from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from tablaCliente import TablaCliente from sqlite3 import dbapi2 cl...
Python
zaydzuhri_stack_edu_python
comment ! usr/bin/python comment -*- coding: ISO-8859-1 -*- comment Spritrl - REALINI Christophe 09/10/2020 - FR import sys import random import string function CreatePassword size numbers special_characters begin set password_length = size set password = string for i in range 0 password_length begin set password = pa...
#! usr/bin/python # -*- coding: ISO-8859-1 -*- # Spritrl - REALINI Christophe 09/10/2020 - FR import sys import random import string def CreatePassword(size, numbers, special_characters): password_length = size password = '' for i in range(0, password_length): password = password + random.choic...
Python
zaydzuhri_stack_edu_python
from flask import Flask , render_template , request , redirect , session set app = call Flask __name__ set secret_key = string is it great really import random decorator call route string / function index begin set session at string computer_num = random integer 1 100 set session at string num_attempts = 0 return call ...
from flask import Flask, render_template, request, redirect, session app = Flask(__name__) app.secret_key = 'is it great really' import random @app.route('/') def index(): session['computer_num'] = random.randint(1, 100) session['num_attempts'] = 0 return render_template('index.html') @app.route('/guess...
Python
zaydzuhri_stack_edu_python
function __exit__ self exc_type exc_val exc_tb begin close self end function
def __exit__(self, exc_type, exc_val, exc_tb): self.close()
Python
nomic_cornstack_python_v1
import datetime function calculate standing walking running cycling swimming stretching begin set hours_on_feet = standing + walking + running set hours_exercising = walking + running + cycling + swimming set stretching_hours = min stretching hours_exercising / 10 set training_points = min hours_on_feet hours_exercisin...
import datetime def calculate( standing, walking, running, cycling, swimming, stretching): hours_on_feet = standing + walking + running hours_exercising = walking + running + cycling + swimming stretching_hours = min(stretching,hours_exercising/10) traini...
Python
zaydzuhri_stack_edu_python
import config as cf import sys import controller from DISClib.ADT import list as lt from DISClib.DataStructures import linkedlistiterator as it assert cf import time from prettytable import PrettyTable string La vista se encarga de la interacción con el usuario Presenta el menu de opciones y por cada seleccion se hace ...
import config as cf import sys import controller from DISClib.ADT import list as lt from DISClib.DataStructures import linkedlistiterator as it assert cf import time from prettytable import PrettyTable """ La vista se encarga de la interacción con el usuario Presenta el menu de opciones y por cada seleccion se hace l...
Python
zaydzuhri_stack_edu_python
function _create_synth_Cityscapes_dataset path_dir begin set non_existing_citites = list string dummy_city_1 string dummy_city_2 set fine_labels_dir = call Path path_dir / string gtFine set images_dir = call Path path_dir / string leftImg8bit set dataset_splits = list string train string val string test for split in da...
def _create_synth_Cityscapes_dataset(path_dir): non_existing_citites = ['dummy_city_1', 'dummy_city_2'] fine_labels_dir = Path(path_dir) / 'gtFine' images_dir = Path(path_dir) / 'leftImg8bit' dataset_splits = ['train', 'val', 'test'] for split in dataset_splits: for city in non_existing_cit...
Python
nomic_cornstack_python_v1
import os import pprint function parse_file df begin set data = list with open df string rb as f begin set header = split read line f string , set counter = 0 for line in f begin if counter == 10 begin break end set fields = split line string , set entry = dict for tuple i value in enumerate fields begin comment prin...
import os import pprint def parse_file(df): data = [] with open(df, "rb") as f: header = f.readline().split(',') counter = 0 for line in f: if counter == 10: break fields = line.split(",") entry = {} for i, value in enumerate(fields): # print list(enumerate(fields)) # print i, value ...
Python
zaydzuhri_stack_edu_python
function select_datarate self begin set DATARATE_CONFIG = LIS302DLTR_ACCL_DR_100 ? LIS302DLTR_ACCL_XAXIS ? LIS302DLTR_ACCL_YAXIS ? LIS302DLTR_ACCL_ZAXIS call write_byte_data LIS302DLTR_DEFAULT_ADDRESS LIS302DLTR_REG_CTRL1 DATARATE_CONFIG end function
def select_datarate(self): DATARATE_CONFIG = (LIS302DLTR_ACCL_DR_100 | LIS302DLTR_ACCL_XAXIS | LIS302DLTR_ACCL_YAXIS | LIS302DLTR_ACCL_ZAXIS) bus.write_byte_data(LIS302DLTR_DEFAULT_ADDRESS, LIS302DLTR_REG_CTRL1, DATARATE_CONFIG)
Python
nomic_cornstack_python_v1
function clean config begin if not exists config begin debug string Wily cache does not exist, skipping return end remove tree cache_path debug string Deleted wily cache end function
def clean(config): if not exists(config): logger.debug("Wily cache does not exist, skipping") return shutil.rmtree(config.cache_path) logger.debug("Deleted wily cache")
Python
nomic_cornstack_python_v1
from customerdb1 import get_db string UPDATE, INSERT, DELETE, GET function insert CustomerName CustomerEmail CustomerPhoneNo CustomerPassword CustomerAddress begin set customerdb1 = call get_db set cursor = call cursor set statement = string INSERT INTO Customer(CustomerName, CustomerEmail, CustomerPhoneNo, CustomerPas...
from customerdb1 import get_db """ UPDATE, INSERT, DELETE, GET""" def insert(CustomerName, CustomerEmail, CustomerPhoneNo, CustomerPassword, CustomerAddress): customerdb1 = get_db() cursor = customerdb1.cursor() statement = "INSERT INTO Customer(CustomerName, CustomerEmail, CustomerPhoneNo, CustomerPassw...
Python
zaydzuhri_stack_edu_python
from cmpTree import * class Sort begin function __init__ self n begin set arr = list set n = n set tree = call Tree n set i = 0 set node = root set side = none set indexes = list comprehension i for i in range n end function function setArr self arr i begin set arr = arr set i = i set node = none set indexes = list co...
from cmpTree import * class Sort: def __init__(self, n): self.arr = [] self.n = n self.tree = Tree(n) self.i = 0 self.node = self.tree.root self.side = None self.indexes = [i for i in range(n)] def setArr(self, arr, i): self.arr = arr self.i = i self.node = None self.indexes = [i for i in rang...
Python
zaydzuhri_stack_edu_python
comment 2023-01-16 00:02:19.026780 comment https://codeforces.com/contest/1225/problem/D from collections import Counter function proc n k a begin function factorize n begin set i = 2 set c = counter while i ^ 2 <= n begin while n % i == 0 begin set c at i = c at i + 1 % k set n = n // i if c at i == 0 begin del c at i...
# 2023-01-16 00:02:19.026780 # https://codeforces.com/contest/1225/problem/D from collections import Counter def proc(n, k, a): def factorize(n): i = 2 c = Counter() while i ** 2 <= n: while n % i == 0: c[i] = (c[i] + 1) % k n //= i ...
Python
zaydzuhri_stack_edu_python
function setup begin size 1400 930 set frog = call loadImage string frog3.jpg for i in range 0 100 begin set x = random width set y = random height set c = get frog integer x integer y call fill c call ellipse x y 14 14 end end function
def setup(): size(1400,930) frog=loadImage("frog3.jpg") for i in range(0,100): x=random(width) y=random(height) c=frog.get(int(x),int(y)) fill(c) ellipse(x,y,14,14)
Python
zaydzuhri_stack_edu_python
function sort self reverse begin comment Checks if the list can be sorted assert length self > 0 msg string The list must have at least one item comment Insertion Sort ### for i in range 1 length self begin comment Saves the current item that is checked set current_item = self at i comment j < i (j will be always be pr...
def sort(self, reverse): assert len(self) > 0, "The list must have at least one item" # Checks if the list can be sorted ### Insertion Sort ### for i in range(1, len(self)): current_item = self[i] # Saves the current item that is checked j = i - 1 # j < i (j will ...
Python
nomic_cornstack_python_v1
import requests import regex import time from youtube import get_yt_comments , get_yt_video_info set MIN_TRACKS = 5 set yt_mobile_regex = string http(?:s?):\/\/(?:www\.)?youtu.be/(\S*) set contains_tracklist_regex = string (?:tracklist|track list|tracks)[^\n]*\n set comment_regexps = dict string single_track_per_line l...
import requests import regex import time from youtube import get_yt_comments, get_yt_video_info MIN_TRACKS = 5 yt_mobile_regex = r"http(?:s?):\/\/(?:www\.)?youtu.be/(\S*)" contains_tracklist_regex = r"(?:tracklist|track list|tracks)[^\n]*\n" comment_regexps = { "single_track_per_line": [ (r"\d{1,2}[\.| -...
Python
zaydzuhri_stack_edu_python
function valid_year year begin if year > 0 begin return true end else begin print string Year must be > 0 return false end end function
def valid_year(year): if year > 0: return True else: print("Year must be > 0") return False
Python
nomic_cornstack_python_v1
import os import zipfile function run filepath begin change directory filepath print string Dir: get current directory for i in range integer 1000000000.0 begin if i ? 63 == 0 begin print i call system string du -a -k tmp with open string tmp/flag.zip string rb as f ; open string tmp/flag { i } .zip string wb as out be...
import os import zipfile def run(filepath: str): os.chdir(filepath) print("Dir:", os.getcwd()) for i in range(int(1e9)): if i & 63 == 0: print(i) os.system("du -a -k tmp") with open("tmp/flag.zip", 'rb') as f, open(f"tmp/flag{i}.zip", 'wb') as out: ...
Python
zaydzuhri_stack_edu_python
comment Define a function that can accept two strings as input and concatenate them and then print it in console. function concat_func s1 s2 begin return s1 + string + s2 end function set tuple str_1 str_2 = split input string , print call concat_func str_1 str_2
# Define a function that can accept two strings as input and concatenate them and then print it in console. def concat_func(s1, s2): return s1 + ' ' + s2 str_1, str_2 = input().split(',') print(concat_func(str_1, str_2))
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/python import pygame , sys , time
#! /usr/bin/python import pygame, sys, time
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import scrapy from Tencent.items import TencentItem class TencentSpider extends Spider begin set name = string tencent set allowed_domains = list string tencent.com set start_urls = list string http://hr.tencent.com/position.php?start=0 function parse self response begin set node_list = ca...
# -*- coding: utf-8 -*- import scrapy from Tencent.items import TencentItem class TencentSpider(scrapy.Spider): name = 'tencent' allowed_domains = ['tencent.com'] start_urls = ["http://hr.tencent.com/position.php?start=0"] def parse(self, response): node_list = response.xpath("//tr[@class=...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Jul 7 17:44:01 2020 @author: Renan de Souza Luiz N°USP:9836120 Como usar o programa: --Ao iniciar e rodar o programa deve-se escolher um dos testes: Digite: a para o teste 'a' do enunciado b para o teste 'b' do enunciado c para o teste 'c' do enunciado d para o teste ...
# -*- coding: utf-8 -*- """ Created on Tue Jul 7 17:44:01 2020 @author: Renan de Souza Luiz N°USP:9836120 Como usar o programa: --Ao iniciar e rodar o programa deve-se escolher um dos testes: Digite: a para o teste 'a' do enunciado b para o teste 'b' do enunciado c para o teste 'c' do enunciado d para o ...
Python
zaydzuhri_stack_edu_python
comment function [x, t] = simulateddetectornoise(DET,T,fs,fmin,fmax,seed) comment % SIMULATEDDETECTORNOISE - Simulate Gaussian colored noise for an IFO. comment % comment % SIMULATEDDETECTORNOISE generates simulated Gaussian noise with spectrum comment % matching the design sensitivity curve for a specified gravitation...
# function [x, t] = simulateddetectornoise(DET,T,fs,fmin,fmax,seed) # % SIMULATEDDETECTORNOISE - Simulate Gaussian colored noise for an IFO. # % # % SIMULATEDDETECTORNOISE generates simulated Gaussian noise with spectrum # % matching the design sensitivity curve for a specified gravitational-wave # % detector, or ma...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- set maxn = 1 ? 30 set L = list set total = 0 for p in range 2 maxn begin set okay = true for i in L begin if p % i == 0 begin set okay = false break end end if okay begin append L p set total = total + 1 if total == 10001 begin print p break end end end
# -*- coding: utf-8 -*- maxn = 1 << 30 L = [] total = 0 for p in range(2, maxn): okay = True for i in L: if p % i == 0: okay = False break if okay: L.append(p) total += 1 if total == 10001: print(p) break
Python
zaydzuhri_stack_edu_python
function py_version_strings_match a b begin if not starts with a b and not starts with b a begin return false end set list_a = split a string . set list_b = split b string . set tuple short long = if expression length list_a < length list_b then tuple list_a list_b else tuple list_b list_a for tuple i s in enumerate sh...
def py_version_strings_match(a: str, b: str) -> bool: if (not a.startswith(b)) and (not b.startswith(a)): return False list_a = a.split(".") list_b = b.split(".") short, long = (list_a, list_b) if len(list_a) < len(list_b) else (list_b, list_a) for (i, s) in enumerate(short): if s !...
Python
nomic_cornstack_python_v1
function _move_closed_order self bo begin return call _move_order_from_to bo string trades string history end function
def _move_closed_order(self, bo): return(self._move_order_from_to(bo, 'trades', 'history'))
Python
nomic_cornstack_python_v1
function attributeClass self attribute begin pass end function
def attributeClass(self, attribute): pass
Python
nomic_cornstack_python_v1
comment _author: "小太阳" comment date: 2018/4/10 import time import unittest from framework.engine import BrowserEngine from pageobjects.page_login import Login import csv class TestLogin extends TestCase begin string 错误登录测试 decorator classmethod function setUpClass cls begin set browse = call BrowserEngine cls set drive...
#_author: "小太阳" #date: 2018/4/10 import time import unittest from framework.engine import BrowserEngine from pageobjects.page_login import Login import csv class TestLogin(unittest.TestCase): '''错误登录测试''' @classmethod def setUpClass(cls): browse = BrowserEngine(cls) cls.driver = browse.o...
Python
zaydzuhri_stack_edu_python
class Solution begin function minCut self s begin set n = length s set res = list set dp = list comprehension list comprehension 0 for x in range n for x in range n for i in range n + 1 begin append res i - 1 end set res at 0 = 0 for i in range n begin for j in range i + 1 begin if s at j == s at i and i - j <= 2 or d...
class Solution: def minCut(self, s: str) -> int: n = len(s) res = [] dp = [[0 for x in range(n)] for x in range(n)] for i in range(n+1): res.append(i-1) res[0] = 0 for i in range(n): for j in range(i+1): if (s[j] == s[i] and (i ...
Python
zaydzuhri_stack_edu_python
function out_degree self vertex_subset=none begin set src_col_name = source_columns set dst_col_name = destination_columns comment select only the vertex columns if not is instance src_col_name list and not is instance dst_col_name list begin set vertex_col_names = list src_col_name + list dst_col_name end set df = inp...
def out_degree(self, vertex_subset=None): src_col_name = self.source_columns dst_col_name = self.destination_columns # select only the vertex columns if not isinstance(src_col_name, list) and not isinstance(dst_col_name, list): vertex_col_names = [src_col_name] + [dst_col_na...
Python
nomic_cornstack_python_v1
function text_from_ebook fin skip_last=false begin set book = call read_epub fin set docs = list call get_items_of_type ITEM_DOCUMENT set n_docs = length docs set texts = list for tuple doc_idx doc in enumerate docs begin if skip_last and doc_idx == n_docs - 1 begin break end set soup = call bs content string lxml set...
def text_from_ebook(fin, *, skip_last=False): book = epub.read_epub(fin) docs = list(book.get_items_of_type(ITEM_DOCUMENT)) n_docs = len(docs) texts = [] for doc_idx, doc in enumerate(docs): if skip_last and doc_idx == n_docs-1: break soup = bs(doc.content, 'lxml') ...
Python
nomic_cornstack_python_v1
function read_geojson filename begin if call validate_geojson filename begin with open filename as data_file begin set data = load json data_file end set feature_collection = call FeatureCollection data return feature_collection end else begin raise call ValueError string Error with the file extension. end end function
def read_geojson(filename : str) -> FeatureCollection: if validate_geojson(filename): with open(filename) as data_file: data = json.load(data_file) feature_collection = FeatureCollection(data) return feature_collection else: raise ValueError("Error with the file extension.")
Python
nomic_cornstack_python_v1
function add_entry_singleYerror3 self data_array tag begin set x = data_array at 0 set y = data_array at 1 set yerr = data_array at 2 call add_tag tag call addx x tag call addy y tag call addyerrl yerr tag end function
def add_entry_singleYerror3(self,data_array,tag): x=data_array[0];y=data_array[1];yerr=data_array[2] self.add_tag(tag) self.addx(x,tag) self.addy(y,tag) self.addyerrl(yerr,tag)
Python
nomic_cornstack_python_v1
from general_graph import GeneralGraph from general_process import GeneralProcess from src.preprocessing import Preprocessing from src.identify_threads import IdentifyThreads from src.classify import Classify from src.analyze_threads import AnalyzeThreads from src.graph import Graph import os class Main begin function ...
from general_graph import GeneralGraph from general_process import GeneralProcess from src.preprocessing import Preprocessing from src.identify_threads import IdentifyThreads from src.classify import Classify from src.analyze_threads import AnalyzeThreads from src.graph import Graph import os class Main: def...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution begin comment 返回从上到下每个节点值列表,例:[1,2,3] function PrintFromTopToBottom self root begin set A = list set result = list if not root begin return result ...
## -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): A = [] result = [] if not root: return result ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import json import logging from flask import Flask , request from cipher import Cipher from pubsub import Topic set app = call Flask __name__ call basicConfig format=string %(asctime)s %(levelname)s %(message)s datefmt=string %Y-%m-%d %H:%M:%S level=DEBUG set logger = call getLogger __file_...
#!/usr/bin/env python import json import logging from flask import Flask, request from cipher import Cipher from pubsub import Topic app = Flask(__name__) logging.basicConfig( format=f"%(asctime)s %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.DEBUG ) logger = logging.getLogger...
Python
zaydzuhri_stack_edu_python
string Tests the reader import numpy as np from modules import reader function test_unendlich begin string Test 1 - Unendlich tiefer set massetest = 2.0 set xmintest = - 2.0 set xmaxtest = 2.0 set npointtest = 1999.0 set firsttest = 1 set lasttest = 5 set interpolationtest = string linear set resttest = array list list...
''' Tests the reader ''' import numpy as np from modules import reader def test_unendlich(): ''' Test 1 - Unendlich tiefer''' massetest = 2.0 xmintest = -2.0 xmaxtest = 2.0 npointtest = 1999.0 firsttest = 1 lasttest = 5 interpolationtest = 'linear' resttest = np.array([[-2.0, 0.0], ...
Python
zaydzuhri_stack_edu_python
function orientation_rank chain begin return call max_rank chain 3 5 end function
def orientation_rank(chain): return max_rank(chain, 3, 5)
Python
nomic_cornstack_python_v1
function twoSum nums target begin set set_dict = dict for tuple index num in enumerate nums begin if target - num in keys set_dict begin return list get set_dict target - num index end set set_dict at num = index end end function if __name__ == string __main__ begin print call twoSum nums=list 2 11 7 15 target=9 end
def twoSum(nums, target): set_dict = {} for index, num in enumerate(nums): if (target - num) in set_dict.keys(): return [set_dict.get(target - num), index] set_dict[num] = index if __name__ == '__main__': print(twoSum(nums = [2, 11, 7, 15], target = 9))
Python
zaydzuhri_stack_edu_python
import math function hoge x y p begin set s = 0 for tuple x_i y_i in zip x y begin set s = s + power call fabs x_i - y_i p end return power s 1 / p end function set _ = input set x = list comprehension integer e for e in split input set y = list comprehension integer e for e in split input print call hoge x y 1 print c...
import math def hoge(x, y, p): s = 0 for x_i, y_i in zip(x, y): s += math.pow(math.fabs(x_i - y_i), p) return math.pow(s, 1/p) _ = input() x = [int(e) for e in input().split()] y = [int(e) for e in input().split()] print (hoge(x, y, 1)) print (hoge(x, y, 2)) print (hoge(x, y, 3)) print (max([math...
Python
zaydzuhri_stack_edu_python
class Project begin comment limit properties comment it has id as well set __slots__ = tuple string name string status string inherit_global string view_status string description comment constructro with optional arguments function __init__ self **kwargs begin set name = get kwargs string name set description = get kwa...
class Project: # limit properties # it has id as well __slots__ = 'name', \ 'status', \ 'inherit_global', \ 'view_status', \ 'description' # constructro with optional arguments def __init__(self, **kwargs): self.name = kwargs.g...
Python
zaydzuhri_stack_edu_python
function make_board begin set board = list for i in range 64 begin if i == 0 begin append board i + 1 end else begin append board board at i - 1 * 2 end end return board end function function on_square num begin set board = call make_board return board at num - 1 end function function total_after num begin set board =...
def make_board(): board = [] for i in range(64): if i == 0: board.append(i+1) else: board.append(board[i-1] * 2) return board def on_square(num): board = make_board() return board[num - 1] def total_after(num): board = make_board() return sum(board[:...
Python
zaydzuhri_stack_edu_python
function iterate_is_first input_list begin call iterate_check_position input_list check_first=true end function
def iterate_is_first(input_list): iterate_check_position(input_list, check_first=True)
Python
nomic_cornstack_python_v1
function get_weather latitude longitude begin comment Get weather forecast for location set request_string = string https://api.openweathermap.org/data/2.5/onecall?lat= { latitude } &lon= { longitude } &units= { weather_unit } &exclude=minutely,hourly&appid= { owm_token } set weather_response = get requests request_str...
def get_weather(latitude: float, longitude: float) -> str: # Get weather forecast for location request_string = f"https://api.openweathermap.org/data/2.5/onecall?lat={latitude}&lon={longitude}&units={settings.weather_unit}&exclude=minutely,hourly&appid={settings.owm_token}" weather_response = requests.get(r...
Python
nomic_cornstack_python_v1
function page_not_found e begin comment pylint: disable=unused-argument return string Flask 404 here, but not the page you requested. end function
def page_not_found(e): #pylint: disable=unused-argument return "Flask 404 here, but not the page you requested."
Python
nomic_cornstack_python_v1
function _build_data_payload self begin if _has_sensor begin set temper = call Temper while true begin set results = read temper if string internal temperature in keys results at 0 begin set degrees = dict string thermometer_data string results end else begin debug string Couldn't read the sensor I am re-trying. end en...
def _build_data_payload(self) -> Dict[str, Any]: if self._has_sensor: temper = Temper() while True: results = temper.read() if "internal temperature" in results[0].keys(): degrees = {"thermometer_data": str(results)} els...
Python
nomic_cornstack_python_v1
function getFeatureDicts self begin pass end function
def getFeatureDicts(self): pass
Python
nomic_cornstack_python_v1
function calc_R g_B_s begin set u_z = g_B_s set u_x = call cross transpose array list 0 1 0 u_z set u_y = call cross u_z u_x set R = array list u_x / norm u_x u_y / norm u_y u_z / norm u_z print R return R end function
def calc_R(g_B_s): u_z = g_B_s u_x = np.cross(np.array([0, 1, 0]).transpose(), u_z) u_y = np.cross(u_z, u_x) R = np.array([(u_x / np.linalg.norm(u_x)), (u_y / np.linalg.norm(u_y)), (u_z / np.linalg.norm(u_z))]) print(R) return R
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- from Sources import Sources from ScraperUtils import ScraperUtils string Main Class Leads.py, by Gullam Hussain, 20 Apr, 2016 comment Main method function main begin set keyphrase = call raw_input string Search Phrase: set keyphrase = call normalize_input keyph...
#!/usr/bin/env python # -*- coding: utf-8 -*- from Sources import Sources from ScraperUtils import ScraperUtils ''' Main Class Leads.py, by Gullam Hussain, 20 Apr, 2016 ''' # Main method def main(): keyphrase = raw_input("Search Phrase: ") keyphrase = ScraperUtils.normalize_input(keyphrase) source = Sou...
Python
zaydzuhri_stack_edu_python
function test_default_permissions app default_permissions test_data search_url test_records indexed_records begin set tuple pid record = test_records at 0 set rec_url = call record_url pid set data = dumps test_data at 0 set h = dict string Content-Type string application/json set hp = dict string Content-Type string a...
def test_default_permissions( app, default_permissions, test_data, search_url, test_records, indexed_records ): pid, record = test_records[0] rec_url = record_url(pid) data = json.dumps(test_data[0]) h = {"Content-Type": "application/json"} hp = {"Content-Type": "application/json-patch+json"} ...
Python
nomic_cornstack_python_v1
function precision y_true y_pred begin set true_positives = sum round call clip y_true * y_pred 0 1 set predicted_positives = sum round call clip y_pred 0 1 set precision = true_positives / predicted_positives + call epsilon return precision end function
def precision(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision
Python
nomic_cornstack_python_v1
function Create2DGaussian SizeX SizeY DistScale=1 ResultScale=1 ResultBias=0 begin set rv = norm set s = call empty tuple SizeX SizeY dtype=string float32 for i in range SizeX begin for j in range SizeY begin set distance = square root i - SizeX / 2 ^ 2 + j - SizeY / 2 ^ 2 * DistScale set s at i at j = call pdf distanc...
def Create2DGaussian(SizeX, SizeY, DistScale=1, ResultScale=1, ResultBias=0): rv = scipy.stats.norm() s = np.empty((SizeX, SizeY), dtype='float32') for i in range(SizeX): for j in range(SizeY): distance = math.sqrt((i-(SizeX/2))**2 + (j-(SizeY/2))**2)*DistScale s[i][j] = rv.pdf(distance)*ResultSca...
Python
nomic_cornstack_python_v1
function shuffle elts pi begin return list comprehension elts at pi at i for i in range length elts end function
def shuffle(elts, pi): return [elts[pi[i]] for i in range(len(elts))]
Python
nomic_cornstack_python_v1
function get_bounding_box self event begin comment bounding box set titlebar = 31 set x1 = call winfo_rootx - 1 set y1 = call winfo_rooty - titlebar set x2 = x1 + call winfo_width + 2 set y2 = y1 + call winfo_height + titlebar + 1 call after_idle save_screenshot list x1 y1 x2 y2 end function
def get_bounding_box(self, event): # bounding box titlebar = 31 x1 = self.root.winfo_rootx() - 1 y1 = self.root.winfo_rooty() - titlebar x2 = x1 + self.root.winfo_width() + 2 y2 = y1 + self.root.winfo_height() + titlebar + 1 self.root.after_idle(self.save_screens...
Python
nomic_cornstack_python_v1
function htmlHeader output path serverName query=none begin string Writes an HTML header. if path and path != string / begin write output string <title>%s - Status: %s</title> % tuple serverName path end else begin write output string <title>%s - Status</title> % serverName end write output string <style> body,td { fon...
def htmlHeader(output, path, serverName, query = None): """Writes an HTML header.""" if path and path != '/': output.write('<title>%s - Status: %s</title>' % (serverName, path)) else: output.write('<title>%s - Status</title>' % serverName) output.write(''' <style> body,td { font-family: monospace } .lev...
Python
jtatman_500k
import sys import math function isPrime N begin for i in range 2 integer square root N + 1 begin if N % i == 0 begin return false end end return true end function set stdin = open string input.txt while true begin try begin set tuple a b = map int split call raw_input end except any begin break end set counter = 0 for ...
import sys import math def isPrime(N): for i in range(2, int(math.sqrt(N) + 1)): if (N % i == 0): return False return True sys.stdin = open('input.txt') while True: try: a, b = map(int, raw_input().split()) except: break counter = 0 for n in range(a, b + 1)...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.contrib.contenttypes import generic class Migration extends SchemaMigration begin function forwards self orm begin comment renaming ExperimentACL to 'ObjectACL' call rename...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.contrib.contenttypes import generic class Migration(SchemaMigration): def forwards(self, orm): # renaming ExperimentACL to 'ObjectACL' db.rename_table('tar...
Python
jtatman_500k
function __ne__ self other begin if not is instance other LeaderboardTeam begin return true end return call to_dict != call to_dict end function
def __ne__(self, other): if not isinstance(other, LeaderboardTeam): return True return self.to_dict() != other.to_dict()
Python
nomic_cornstack_python_v1
function compute_accuracy y_ground_truth y_pred begin set pred = call ravel < 0.5 return mean np pred == y_ground_truth end function
def compute_accuracy(y_ground_truth, y_pred): pred = y_pred.ravel() < 0.5 return np.mean(pred == y_ground_truth)
Python
nomic_cornstack_python_v1
function initialize begin call initialize_gripper assert call is_ready print string Initialized gripper sleep 2.0 call add_constraint string right_wall 0 right_wall_dist 0 4 0.1 4 call add_constraint string left_wall 0 left_wall_dist 0 4 0.1 4 call add_constraint string back_wall back_wall_dist 0 0 0.1 4 4 comment self...
def initialize(): initialize_gripper() assert right_gripper.is_ready() print("Initialized gripper") rospy.sleep(2.0) add_constraint('right_wall', 0, right_wall_dist, 0, 4, 0.1, 4) add_constraint('left_wall', 0, left_wall_dist, 0, 4, 0.1, 4) add_constraint('back_wall', back_wall_dist, 0, 0,...
Python
nomic_cornstack_python_v1
function SUM N begin return integer N / 2 * 1 + N end function function NSUM D N begin set c = N for x in range D begin set c = sum c end return c end function set ANS = list set T = integer strip input string for l in range T begin set tuple D N = map int split strip input string append ANS call NSUM D N end for a in...
def SUM(N): return int((N/2)*(1+N)) def NSUM(D, N): c = N for x in range(D): c = SUM(c) return c ANS = [] T = int(input().strip(' ')) for l in range(T): D, N = map(int, input().strip(' ').split()) ANS.append(NSUM(D, N)) for a in ANS: print(a)
Python
zaydzuhri_stack_edu_python
function get_lines self force=false begin string Return a list of lists or strings, representing the code body. Each list is a block, each string is a statement. force (True or False): if an attribute object cannot be included, it is usually skipped to be processed later. With 'force' set, there will be no waiting: a g...
def get_lines(self, force=False): """ Return a list of lists or strings, representing the code body. Each list is a block, each string is a statement. force (True or False): if an attribute object cannot be included, it is usually skipped to be processed later. With 'force' set,...
Python
jtatman_500k
function arguments self begin return get pulumi self string arguments end function
def arguments(self) -> Optional[Sequence[Any]]: return pulumi.get(self, "arguments")
Python
nomic_cornstack_python_v1
async function async_update self **kwargs begin debug string [Foobar2k] Doing async_update comment Get current status of the FB2K server try begin set response = await call prep_fetch HTTP_GET GET_PLAYER_INFO set _power = POWER_ON debug string [Foobar2k] Doing update() POWER ON end except ValueError begin pass end exce...
async def async_update(self, **kwargs): _LOGGER.debug("[Foobar2k] Doing async_update") # Get current status of the FB2K server try: response = await self.prep_fetch(HTTP_GET, GET_PLAYER_INFO) self._power = POWER_ON _LOGGER.debug("[Foobar2k] Doing update() POW...
Python
nomic_cornstack_python_v1
string input: 3 3 1 3 1 2 1 3 2 3 output: YES 1 3 1 2 3 import sys import threading from math import inf call setrecursionlimit 10 ^ 9 call stack_size 10 ^ 8 function solve begin class Edge begin function __init__ self from_v to_v capacity dist begin set from_v = from_v set to_v = to_v set capacity = capacity set dist ...
""" input: 3 3 1 3 1 2 1 3 2 3 output: YES 1 3 1 2 3 """ import sys import threading from math import inf sys.setrecursionlimit(10 ** 9) threading.stack_size(10 ** 8) def solve(): class Edge: def __init__(self, from_v, to_v, capacity, dist): self.from_v = from_v self.to_v = to_v...
Python
zaydzuhri_stack_edu_python
function get_cloud_config_value name vm_ opts default=none search_global=true begin string Search and return a setting in a known order: 1. In the virtual machine's configuration 2. In the virtual machine's profile configuration 3. In the virtual machine's provider configuration 4. In the salt cloud configuration if gl...
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True): ''' Search and return a setting in a known order: 1. In the virtual machine's configuration 2. In the virtual machine's profile configuration 3. In the virtual machine's provider configuration 4. In t...
Python
jtatman_500k
from aoc_utils import run_with_timer set data = list comprehension integer x for x in split strip read line open string input.txt string , function calc_fuel fun begin return min generator expression min list sum generator expression call fun x y for y in data for x in range max data + 1 end function function part_one ...
from aoc_utils import run_with_timer data = [int(x) for x in open("input.txt").readline().strip().split(",")] def calc_fuel(fun): return min(min([sum(fun(x, y) for y in data)]) for x in range(max(data)+1)) def part_one(): return calc_fuel(lambda x, y: abs(y-x)) def part_two(): return calc_fuel(lambda x, y: (a...
Python
zaydzuhri_stack_edu_python
function inicio begin print string Bem-vindo ao jogo do NIM! Escolha: print string print string 1 - para jogar uma partida isolada set Partida = integer input string 2 - para jogar um campeonato if Partida == 2 begin print string print string Voce escolheu um campeonato! print string call campeonato end else if Partida...
def inicio(): print("Bem-vindo ao jogo do NIM! Escolha:") print("") print("1 - para jogar uma partida isolada") Partida = int(input("2 - para jogar um campeonato ")) if Partida == 2: print("") print("Voce escolheu um campeonato!") print("") campeonato() elif Part...
Python
zaydzuhri_stack_edu_python
function __delitem__ self key begin del _dict at key del _type_converter at key end function
def __delitem__(self, key): del self._dict[key] del self._type_converter[key]
Python
nomic_cornstack_python_v1
import torch.nn as nn class FeedForwardNeuralNetwork extends Module begin string Feed-forward neural network model for binary classification. Supports batch normalisation layers function __init__ self input_dim hidden_dim=64 hidden_layers=3 batch_norm=false begin call __init__ set num_layers = hidden_layers set batch_n...
import torch.nn as nn class FeedForwardNeuralNetwork(nn.Module): """ Feed-forward neural network model for binary classification. Supports batch normalisation layers """ def __init__(self, input_dim, hidden_dim=64, hidden_layers=3, batch_norm=False): super(FeedForwardNeuralNetwork, self).__ini...
Python
zaydzuhri_stack_edu_python
comment убрать минимум, и получится все круто function my_func n1 n2 n3 begin set my_numbers = list n1 n2 n3 try begin remove my_numbers min my_numbers return sum my_numbers end except ValueError begin return string Введите числа! end except TypeError begin return string Введите числа! end end function print call my_fu...
# убрать минимум, и получится все круто def my_func(n1, n2, n3): my_numbers = [n1, n2, n3] try: my_numbers.remove(min(my_numbers)) return sum(my_numbers) except ValueError: return 'Введите числа!' except TypeError: return 'Введите числа!' print(my_func(n1=int(input('1-...
Python
zaydzuhri_stack_edu_python
function __call__ self message maximum begin if not progress_bar_type begin set progress_bar = call _NoProgressBar end else begin set progress_bar = call progress_bar_type message max=maximum suffix=string %(index)d/%(max)d end return self end function
def __call__(self, message, maximum): if not self.progress_bar_type: self.progress_bar = self._NoProgressBar() else: self.progress_bar = self.progress_bar_type( message, max=maximum, suffix="%(index)d/%(max)d" ) return self
Python
nomic_cornstack_python_v1
function find_label_by_id self _id begin set search = true set i = 0 while search begin if i == length labels begin break end if id == _id begin return labels at i set search = false end comment print self.labels[i].id set i = i + 1 end if search begin return none end end function
def find_label_by_id(self, _id): search = True i = 0 while search: if i == len(self.labels): break; if self.labels[i].id == _id: return self.labels[i] search = False #print self.labels[i].id i += 1 ...
Python
nomic_cornstack_python_v1
function create_jobs source dose_report=none begin set arch_source = none set arch_all = none for arch in arches begin if name == string source begin set arch_source = arch end if name == string all begin set arch_all = arch end end if not arch_source or not arch_all begin raise call ValueError string Missing arch:all ...
def create_jobs(source, dose_report=None): arch_source = None arch_all = None for arch in source.group_suite.arches: if arch.name == "source": arch_source = arch if arch.name == "all": arch_all = arch if not arch_source or not arch_all: raise ValueError(...
Python
nomic_cornstack_python_v1
import json set teach = open string C:/Users/Sourav/Downloads/teachers.json string r set a = load json teach close teach print a set lis = a at string data set d = dict for i in lis begin set d at i at 0 = integer i at 3 end set loop = true while loop begin set inp = input string Enter the State: print d at inp set ke...
import json teach = open('C:/Users/Sourav/Downloads/teachers.json','r') a = json.load(teach) teach.close() print(a) lis = a['data'] d = {} for i in lis: d[i[0]] = int(i[3]) loop = True while loop: inp = input('Enter the State: ') print(d[inp]) keep = input('\nWant to know value for ot...
Python
zaydzuhri_stack_edu_python
comment Selection Sort set list_Int = list 8 2 4 6 1 9 0 3 5 7 9 set max_Len = length list_Int set list_Index = 0 set i = 0 while list_Index < max_Len - 1 begin for i in range list_Index + 1 max_Len 1 begin if list_Int at list_Index < list_Int at i begin set list_Int at i = list_Int at i + list_Int at list_Index set li...
#Selection Sort list_Int = [8, 2, 4, 6, 1, 9, 0, 3, 5, 7, 9] max_Len = len(list_Int) list_Index = 0 i = 0 while list_Index < max_Len - 1: for i in range(list_Index + 1, max_Len, 1): if list_Int[list_Index] < list_Int[i]: list_Int[i] = list_Int[i] + list_Int[list_Index] list_Int[lis...
Python
zaydzuhri_stack_edu_python
from logging import info import pandas as pd from pandora.core_fields import MISSING_INDICATOR_SUFFIX from pandora.core_types import Module , Imputation function impute df module begin set df = call mark_missing df module set df = call impute_features df module set df = call reindex sorted columns axis=1 return df end ...
from logging import info import pandas as pd from pandora.core_fields import MISSING_INDICATOR_SUFFIX from pandora.core_types import Module, Imputation def impute(df: pd.DataFrame, module: Module) -> pd.DataFrame: df = mark_missing(df, module) df = impute_features(df, module) df = df.reindex(sorted(df.c...
Python
zaydzuhri_stack_edu_python
function hover_over self id begin set el = call wait_n_get ID id set hover = call move_to_element el call perform end function
def hover_over(self, id): el = self.wait_n_get(By.ID, id) hover = ActionChains(self.driver).move_to_element(el) hover.perform()
Python
nomic_cornstack_python_v1
string Exceptions. class InputError extends Exception begin function __init__ self message code=400 begin set message = string InputError: + message set code = code end function function __str__ self begin return message + string error code: %s. % code end function end class class ClassException extends Exception begin...
""" Exceptions. """ class InputError(Exception): def __init__(self, message, code=400): self.message = "InputError: " + message self.code = code def __str__(self): return self.message + " error code: %s." % self.code class ClassException(Exception): def __init__(self, message, c...
Python
zaydzuhri_stack_edu_python
class myRole extends object begin function __init__ self begin set name = string john set age = 18 end function function getName self begin return name end function function setName self name begin if type name == str begin set name = name end else begin raise call TypeError string '%s' is not right name format! % name...
class myRole(object): def __init__(self): self.name = "john" self.age = 18 def getName(self): return self.name def setName(self, name): if type(name) == str: self.name = name else: raise TypeError(r"'%s' is not right name format!" % ...
Python
zaydzuhri_stack_edu_python
function _get_obj_does_not_exist_redirect self request opts object_id begin set msg = call _ string %(name)s with ID "%(key)s" doesn't exist. Perhaps it was deleted? % dict string name verbose_name ; string key unquote object_id call message_user request msg WARNING set url = reverse string admin:index current_app=name...
def _get_obj_does_not_exist_redirect(self, request, opts, object_id): msg = _("""%(name)s with ID "%(key)s" doesn't exist. Perhaps it was deleted?""") % { 'name': opts.verbose_name, 'key': unquote(object_id), } self.message_user(request, msg, messages.WARNING) url...
Python
nomic_cornstack_python_v1
import cv2 import time import configparser from selenium import webdriver import pytesseract from PIL import Image , ImageEnhance class webDriver begin function __init__ self account password begin set pass_Count = 0 set fail_Count = 0 set Account = account set Password = password set browser = call Chrome string ./chr...
import cv2 import time import configparser from selenium import webdriver import pytesseract from PIL import Image, ImageEnhance class webDriver(): def __init__(self, account, password): self.pass_Count = 0 self.fail_Count = 0 self.Account = account self.Password = password ...
Python
zaydzuhri_stack_edu_python
function range1000 begin global range guesses_made guesses_remaining correct_num victory_condition set range = 1000 set guesses_made = 0 comment calculate_remaining_guesses(range) set guesses_remaining = 10 set correct_num = call randrange range set victory_condition = false end function
def range1000(): global range, guesses_made, guesses_remaining, correct_num, victory_condition range = 1000 guesses_made = 0 guesses_remaining = 10#calculate_remaining_guesses(range) correct_num = random.randrange(range) victory_condition = False
Python
nomic_cornstack_python_v1
import math comment linear algebra import numpy as np comment data processing, CSV file I/O (e.g. pd.read_csv) import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from kutils.analysis import GeneralPlotUtils from functools import partial class Utils extends GeneralPlotUtils begin function __init__...
import math import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import seaborn as sns import matplotlib.pyplot as plt from kutils.analysis import GeneralPlotUtils from functools import partial class Utils(GeneralPlotUtils): def __init__(self, data, figsize=(2...
Python
zaydzuhri_stack_edu_python
function register self category name label _type default **kwargs begin set min_val = get kwargs string min_val none set max_val = get kwargs string max_val none set options = get kwargs string options none set help_str = get kwargs string help_str none set category_label = get kwargs string category_label none set sel...
def register( self, category, name, label, _type, default, **kwargs ): min_val = kwargs.get('min_val', None) max_val = kwargs.get('max_val', None) options = kwargs.get('options', None) help_str = kwargs.get('help_str', None) category_label = kwargs.get('category_l...
Python
nomic_cornstack_python_v1
comment [import libraries] import subprocess import os import sys string importing the Vam_settings from the settings_fun file from setting_fun import Vam_settings comment sys.argv[1] command for asking comment sys.argv[2] command for the set volume comment sys.argv[3] is a wake word comment create a object to the Vam_...
##[import libraries] import subprocess import os import sys ''' importing the Vam_settings from the settings_fun file ''' from setting_fun import Vam_settings ## sys.argv[1] command for asking ## sys.argv[2] command for the set volume ## sys.argv[3] is a wake word ## create a object to the Vam_settings() class for...
Python
zaydzuhri_stack_edu_python
function init_gol_objects master begin set rule = call Rule string B string R string / call try_set_rule INITIAL_RULE comment Original (can be editted) - for reset set board = none comment Animated board set anim_board = none set painter = call Painter call reset IMAGE_MAX_WIDTH IMAGE_MAX_HEIGHT CELL_SIZES BOARD_BG BOA...
def init_gol_objects(master: Tk) -> None: self.rule = Rule('B','R','/') self.rule.try_set_rule(self.INITIAL_RULE) self.board = None # Original (can be editted) - for reset self.anim_board = None # Animated board self.painter = Painter...
Python
nomic_cornstack_python_v1
function get_distroot self root begin set distroot = dict for i in sorted pl begin set distroot at string i = call shortest_path_length gl string root i end return distroot end function
def get_distroot(self, root): distroot = {} for i in sorted(self.pl): distroot[str(i)] = networkx.shortest_path_length(self.gl, str(root), i) return distroot
Python
nomic_cornstack_python_v1
comment s1.add([1, 2, 3, 5, 10]) comment 不会报错,因为tuple不可变 add s1 tuple 1 2 3 print s1 comment 报错,虽然tuple可变,但是其中元素list是可变的 add s1 tuple 1 2 8 list 2 3 5
# s1.add([1, 2, 3, 5, 10]) s1.add((1, 2, 3)) # 不会报错,因为tuple不可变 print(s1) s1.add((1, 2, 8, [2, 3, 5])) # 报错,虽然tuple可变,但是其中元素list是可变的
Python
zaydzuhri_stack_edu_python
set zina = list string Pirmais paragrāfs string otr print string <h1>Virsraksts</h1>
zina = ['Pirmais paragrāfs', 'otr'] print('<h1>Virsraksts</h1>')
Python
zaydzuhri_stack_edu_python
function SVM begin set tuple x1 x2 = call generate_training_data_2D set Y = concatenate list zeros shape at 0 dtype=int32 ones shape at 0 dtype=int32 set X = concatenate list x1 x2 axis=0 set rng = call get_state shuffle random X comment Set the random state back to previous to shuffle X & Y similarly call set_state rn...
def SVM(): x1, x2 = generate_training_data_2D() Y = np.concatenate([np.zeros(x1.shape[0], dtype=np.int32), np.ones(x2.shape[0], dtype=np.int32)]) X = np.concatenate([x1, x2], axis=0) rng = np.random.get_state() np.random.shuffle(X) # Set the random state back to previous to shuffle X...
Python
nomic_cornstack_python_v1
function CascadeLlhVertexFit tray name CascadeLlh Pulses=string TWNFEMergedPulses If=lambda frame -> true begin load icetray string clast false load icetray string cscd-llh false comment Settings from std-processing/releases/11-02-00/scripts/IC79/level2_DoCascadeReco.py set CscdLlhVertexFitter = call module_altconfig s...
def CascadeLlhVertexFit(tray, name, CascadeLlh, Pulses='TWNFEMergedPulses', If=lambda frame: True): icetray.load('clast', False) icetray.load('cscd-llh', False) # Settings from std-processing/releases/11-02-00/scripts/IC79/level2_DoCascadeReco.py CscdLlhVertexFitter = icetray.module_altconfig('I3CscdLlhModul...
Python
nomic_cornstack_python_v1
string Realizar un programa en java que permita presentar un mensaje de: acceso correcto, si el valor ingresaso para la variable ciudad tiene el valor de Loja; caso contrario, presentar un mensaje de acceso incorrecto set ciudad = input string Ingrese la ciudad: set ciudad = lower ciudad if ciudad == string loja or ciu...
""" Realizar un programa en java que permita presentar un mensaje de: acceso correcto, si el valor ingresaso para la variable ciudad tiene el valor de Loja; caso contrario, presentar un mensaje de acceso incorrecto """ ciudad = input("Ingrese la ciudad: ") ciudad = ciudad.lower() if ((ciudad == "loja") or (ciudad =...
Python
zaydzuhri_stack_edu_python
function modify_transforms self keys values first_segment last_segment=none begin if not last_segment begin set last_segment = decimal string inf end for tuple dx segment in enumerate story begin if dx >= first_segment begin if dx <= last_segment begin call modify_transforms keys values end end end end function
def modify_transforms(self, keys, values, first_segment, last_segment = None): if not last_segment: last_segment = float('inf') for dx, segment in enumerate(self.story): if dx >= first_segment: if dx <= last_segment: segment.modify_tra...
Python
nomic_cornstack_python_v1
class Solution begin function lengthOfLIS self nums begin set dp = list 1 * length nums set nlen = length nums if nlen == 0 begin return 0 end set nmax = 1 for i in range nlen - 2 - 1 - 1 begin set tmax = 1 for j in range i + 1 nlen begin if nums at i >= nums at j begin continue end set tmax = max tmax dp at j + 1 end ...
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp = [1] * len(nums) nlen = len(nums) if nlen == 0: return 0 nmax = 1 for i in range(nlen-2, -1, -1): tmax = 1 for j in range(i+1, nlen): if nums[i] >= ...
Python
zaydzuhri_stack_edu_python
function add_user username password email is_admin begin set db = call get_db execute db string INSERT INTO user (username, password, email, is_admin) VALUES (?, ?, ?, ?) tuple username password email is_admin commit db end function
def add_user(username, password, email, is_admin): db = get_db() db.execute( 'INSERT INTO user (username, password, email, is_admin) VALUES (?, ?, ?, ?)', (username, password, email, is_admin) ) db.commit()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment encoding: utf-8 string @author: Wayne @contact: wangye.hope@gmail.com @software: PyCharm @file: Shuffle the Array @time: 2020/06/07 10:30 class Solution begin function shuffle self nums n begin return sum map list zip *[nums[:n], nums[n:]] list end function end class set so = call S...
#!/usr/bin/env python # encoding: utf-8 """ @author: Wayne @contact: wangye.hope@gmail.com @software: PyCharm @file: Shuffle the Array @time: 2020/06/07 10:30 """ class Solution: def shuffle(self, nums: list, n: int) -> list: return sum(map(list, zip(*[nums[:n], nums[n:]])), []) so = Solution() print(s...
Python
zaydzuhri_stack_edu_python