code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function pre_customer_attachment_create self resource_dict begin pass end function
def pre_customer_attachment_create(self, resource_dict): pass
Python
nomic_cornstack_python_v1
function test_monitoring self begin comment Create runnable script. comment This script is used to create dictionary using cli. set res = run list executable string .test_monitoring.py string --trashesoutput with open string .test_monitoring.txt string r as f begin set kargs = call literal_eval read f end comment Passi...
def test_monitoring(self): # Create runnable script. # This script is used to create dictionary using cli. res = subprocess.run([sys.executable, ".test_monitoring.py", "--trashesoutput"]) with open(".test_monitoring.txt", "r") as f: kargs = ast.literal_eval(f.read()) ...
Python
nomic_cornstack_python_v1
comment Copyright 2003, Google Inc. comment Author: Douglas Greiman comment Formats a human-readable stack trace that includes the values of comment local variables for each stack frame. Useful for log files and comment other places where a bare traceback is inadequate. comment Usage: comment from google3.pyglib import...
# Copyright 2003, Google Inc. # Author: Douglas Greiman # # Formats a human-readable stack trace that includes the values of # local variables for each stack frame. Useful for log files and # other places where a bare traceback is inadequate. # # Usage: # from google3.pyglib import debug_traceback # try: # ......
Python
zaydzuhri_stack_edu_python
import PIL import matplotlib.pyplot as plt comment aspect ratio: width / height function img_width_height img begin set tuple width height = size return tuple width height end function function open_image path begin return open path end function function normal_to_grayscale img begin return call grayscale img end funct...
import PIL import matplotlib.pyplot as plt # aspect ratio: width / height def img_width_height(img): width, height = img.size return width, height def open_image(path): return PIL.Image.open(path) def normal_to_grayscale(img): return PIL.ImageOps.grayscale(img) def grayscale_to_normal(img):...
Python
zaydzuhri_stack_edu_python
function scenario_repl self scenario begin set auto_suggest = call ScenarioAutoSuggest set example_cli = call CommandLineInterface application=call create_application full_layout=false auto_suggest=auto_suggest prompt_prefix=string (scenario) toolbar_hint=string In Scenario Mode: Press [Enter] to execute commands [Ctrl...
def scenario_repl(self, scenario): auto_suggest = ScenarioAutoSuggest() example_cli = CommandLineInterface( application=self.create_application( full_layout=False, auto_suggest=auto_suggest, prompt_prefix='(scenario) ', toolbar_...
Python
nomic_cornstack_python_v1
async function get_execution self request=none name=none retry=DEFAULT timeout=DEFAULT metadata=tuple begin comment Create or coerce a protobuf request object. comment Quick check: If we got a request object, we should *not* have comment gotten any keyword arguments that map to the request. set has_flattened_params = a...
async def get_execution( self, request: Optional[Union[service.GetExecutionRequest, dict]] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str,...
Python
nomic_cornstack_python_v1
function Validate self value **_ begin string Check that value is a valid enum. if value is none begin return end return call RDFBool call Validate value end function
def Validate(self, value, **_): """Check that value is a valid enum.""" if value is None: return return rdfvalue.RDFBool(super(ProtoBoolean, self).Validate(value))
Python
jtatman_500k
function TwoSumSolution array target begin set store = dict for tuple idx item in enumerate array begin set compl = target - item if compl in store begin return list store at compl idx end set store at item = idx end return list end function
def TwoSumSolution(array, target): store = {} for idx, item in enumerate(array): compl = target - item if compl in store: return [store[compl], idx] store[item] = idx return []
Python
zaydzuhri_stack_edu_python
import Functions set file = open string concerts.txt set band = call userInput string Please enter a band: string str
import Functions file = open ('concerts.txt') band = Functions.userInput("Please enter a band: ", "str")
Python
zaydzuhri_stack_edu_python
function cores_per_socket self begin comment type: ignore return integer num_cores_per_socket end function
def cores_per_socket(self): return int(self.num_cores_per_socket) # type: ignore
Python
nomic_cornstack_python_v1
comment coding: utf-8 string In these experiments, we are synthesizing data that has long distant rules of some particular length surrounding an inner conduit which may or may not appear a number of times elsewhere in the corpus. The goal here is to see how the length of the dependency affects model capacity to learn t...
# coding: utf-8 """ In these experiments, we are synthesizing data that has long distant rules of some particular length surrounding an inner conduit which may or may not appear a number of times elsewhere in the corpus. The goal here is to see how the length of the dependency affects model capacity to learn the longe...
Python
zaydzuhri_stack_edu_python
function status_all self **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string callback begin return call status_all_with_http_info keyword kwargs end else begin set data = call status_all_with_http_info keyword kwargs return data end end function
def status_all(self, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.status_all_with_http_info(**kwargs) else: (data) = self.status_all_with_http_info(**kwargs) return data
Python
nomic_cornstack_python_v1
class PlusOne begin function plus_one self digits begin set num = string for d in digits begin set num = num + string d end set result = integer num + 1 set result_digits = list for c in string result begin append result_digits integer c end return result_digits end function end class class Test begin set test = call...
class PlusOne: def plus_one(self, digits): num = "" for d in digits: num += str(d) result = int(num) + 1 result_digits = [] for c in str(result): result_digits.append(int(c)) return result_digits class Test: test = PlusOne() print(test...
Python
zaydzuhri_stack_edu_python
function main begin comment Load all the commands set commands = dict end function
def main(): # Load all the commands commands = {}
Python
nomic_cornstack_python_v1
function import_wikilink self title href **attrs begin string Import a Wiki link and return a :class:`WikiLink` object. :param title: title of the :class:`WikiLink` :param href: href of the :class:`WikiLink` :param attrs: optional attributes for :class:`WikiLink` return call import_ id title href keyword attrs end func...
def import_wikilink(self, title, href, **attrs): """ Import a Wiki link and return a :class:`WikiLink` object. :param title: title of the :class:`WikiLink` :param href: href of the :class:`WikiLink` :param attrs: optional attributes for :class:`WikiLink` """ retu...
Python
jtatman_500k
function process self stream mask begin comment flag = mask[:, :, np.newaxis, :] comment Create a slice that will expand the mask to comment the same dimensions as the weight array set waxis = attrs at string axis set slc = list call slice none * length waxis for tuple ww name in enumerate waxis begin if name not in at...
def process(self, stream, mask): # flag = mask[:, :, np.newaxis, :] # Create a slice that will expand the mask to # the same dimensions as the weight array waxis = stream.weight.attrs["axis"] slc = [slice(None)] * len(waxis) for ww, name in enumerate(waxis): ...
Python
nomic_cornstack_python_v1
from peewee import * from mailroom_donor_report import print_donor_report import time from create_mailroom_db import Donor , Donation function get_first name begin set name_sp = split name if length name_sp == 1 begin return string end else begin return name_sp at 0 end end function function get_last name begin set na...
from peewee import * from mailroom_donor_report import print_donor_report import time from create_mailroom_db import Donor, Donation def get_first(name): name_sp = name.split() if len(name_sp) == 1: return '' else: return name_sp[0] def get_last(name): name_sp = name.split() if l...
Python
zaydzuhri_stack_edu_python
function unassignedCourses self begin set unassigned = list for quarter in courses begin for course in courses at quarter begin comment Ignore courses that are defined as capstone type courses if instructor is none and expertise != string Capstone begin append unassigned course end end end return unassigned end functi...
def unassignedCourses(self): unassigned = [] for quarter in self.courses: for course in self.courses[quarter]: #Ignore courses that are defined as capstone type courses if course.instructor is None and course.expertise != "Capstone": unassi...
Python
nomic_cornstack_python_v1
string Tests for the bot controller actions import pytest from discord.message import Message from disco_dan.controller import Controller from disco_dan import settings class DummyChannel extends object begin string A pretend channel function __init__ self name begin set name = name end function end class class DummyGu...
""" Tests for the bot controller actions """ import pytest from discord.message import Message from disco_dan.controller import Controller from disco_dan import settings class DummyChannel(object): """ A pretend channel """ def __init__(self, name): self.name = name class DummyGuild(object): ...
Python
zaydzuhri_stack_edu_python
from abc import ABC , abstractmethod from typing import Any class CacheBase extends ABC begin decorator abstractmethod async function get self key begin pass end function decorator abstractmethod async function mget self keys begin pass end function decorator abstractmethod async function set self key data begin pass e...
from abc import ABC, abstractmethod from typing import Any class CacheBase(ABC): @abstractmethod async def get(self, key: str): pass @abstractmethod async def mget(self, keys: list[str]) -> list[Any]: pass @abstractmethod async def set(self, key: str, data: Any): pas...
Python
zaydzuhri_stack_edu_python
function navigation parser token begin set args = call split_contents at slice 1 : : set kwargs = dictionary comprehension k : call compile_filter v for tuple k v in list comprehension split a string = 1 for a in args return call NavigationNode kwargs end function
def navigation(parser, token): args = token.split_contents()[1:] kwargs = {k: parser.compile_filter(v) for k, v in [a.split("=", 1) for a in args]} return NavigationNode(kwargs)
Python
nomic_cornstack_python_v1
function unpack_annotations body labels begin if labels is none begin return tuple list list end global remove_default set variables = list set annotations = list for tuple ind row in call iterrows begin if row at string name == string annotation begin append variables tuple row at string var_line row at string var...
def unpack_annotations(body, labels): if labels is None: return [], [] global remove_default variables = [] annotations = [] for ind, row in labels.iterrows(): if row['name'] == "annotation": variables.append(( row['var_line'], row['var_end_line'], row[...
Python
nomic_cornstack_python_v1
async function test_async_plasmawave_on_off begin comment async_plasmawave does not need the device to be turned on with patch string { WinixDriver_TypeName } .plasmawave_on as plasmawave_on ; patch string { WinixDriver_TypeName } .plasmawave_off as plasmawave_off begin set wrapper = call build_mock_wrapper await call ...
async def test_async_plasmawave_on_off(): # async_plasmawave does not need the device to be turned on with patch(f"{WinixDriver_TypeName}.plasmawave_on") as plasmawave_on, patch( f"{WinixDriver_TypeName}.plasmawave_off" ) as plasmawave_off: wrapper = build_mock_wrapper() await wrap...
Python
nomic_cornstack_python_v1
function search_entity_sentences entity_id skip=0 limit=100 db=call Depends get_db begin set db_entity = call get_entity db entity_id=entity_id if not db_entity begin raise call HTTPException status_code=404 detail=string Entity { entity_id } does not exist end set db_entity_sents = call get_entity_sentences db db_enti...
def search_entity_sentences(entity_id: int, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): db_entity = crud.get_entity(db, entity_id=entity_id) if not db_entity: raise HTTPException(status_code=404, detail=f"Entity {entity_id} does not exist") db_entity_sents = crud.get_entity_sent...
Python
nomic_cornstack_python_v1
from InfoString import InfoString from typing import Dict , Tuple set info : Dict at tuple Tuple at tuple str str InfoString = dict function complete_info start max_items=none begin set ids = set set items = list set queue = list start while length queue > 0 begin set current_id = pop queue if current_id in ids begin...
from InfoString import InfoString from typing import Dict, Tuple info: Dict[Tuple[str, str], InfoString] = {} def complete_info(start, max_items=None): ids = set() items = [] queue = [start] while len(queue) > 0: current_id = queue.pop() if current_id in ids: continue ...
Python
zaydzuhri_stack_edu_python
function load_jinja_fns self begin comment Function for jinja, to remove duplicates from flashed messages function remove_duplicates msgs begin set uniq_msgs = list for msg in msgs begin if msg not in uniq_msgs begin append uniq_msgs msg end end return uniq_msgs end function update globals remove_duplicates=remove_dup...
def load_jinja_fns(self): # Function for jinja, to remove duplicates from flashed messages def remove_duplicates(msgs): uniq_msgs = [] for msg in msgs: if msg not in uniq_msgs: uniq_msgs.append(msg) return uniq_msgs current_app.jinja_env.globals.update(remove_duplicates=remove_duplicates)
Python
nomic_cornstack_python_v1
function until_not self method message=string begin set end_time = time + _timeout while true begin try begin set value = call method _obj if not value begin return value end end except _ignored_exceptions as exc begin return true end sleep _poll if time > end_time begin break end end raise call TimeoutException string...
def until_not(self, method, message=''): end_time = time.time() + self._timeout while True: try: value = method(self._obj) if not value: return value except self._ignored_exceptions as exc: return True ...
Python
nomic_cornstack_python_v1
string SRM 573 https://community.topcoder.com/tc?module=ProblemDetail&rd=15493&pm=12469 import unittest class SkiResortEasy begin function minCost self arr_list begin set n = length arr_list set total = 0 for i in range n - 1 begin if arr_list at i + 1 > arr_list at i begin set total = total + arr_list at i + 1 - arr_l...
""" SRM 573 https://community.topcoder.com/tc?module=ProblemDetail&rd=15493&pm=12469 """ import unittest class SkiResortEasy: def minCost(self, arr_list): n = len(arr_list) total = 0 for i in range(n-1): if (arr_list[i+1] > arr_list[i]): total += (arr_list[i+1] - arr_list[i]) arr_l...
Python
zaydzuhri_stack_edu_python
comment Condição - True e False if 2 > 1000 begin print string olá mundo end if 1000 > 2 begin print string mundo morreu end
#Condição - True e False if 2 > 1000: print("olá mundo") if 1000 > 2: print("mundo morreu")
Python
zaydzuhri_stack_edu_python
function auto_choose_game self opponent=none begin set game_found = false set chosen_game = none while not game_found begin set available_games_str = call list_games set available_games = list comprehension split strip game for game in available_games_str set indexes_of_desired_opponents = list set indexes_of_offers =...
def auto_choose_game(self, opponent=None): game_found = False chosen_game = None while not game_found: available_games_str = self.imcs_server.list_games() available_games = [game.strip().split() for game in available_games_str] indexes_of_desired_opponents = ...
Python
nomic_cornstack_python_v1
if c <= porcento begin print string O empréstimo pode ser concedido end else begin print string Você não foi aprovado porque o valor a se pagar é maior que 30% do seu salário end
if c <= porcento: print('O empréstimo pode ser concedido') else: print('Você não foi aprovado porque o valor a se pagar é maior que 30% do seu salário')
Python
zaydzuhri_stack_edu_python
string * Copyright 2020, Departamento de sistemas y Computación, * Universidad de Los Andes * * * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the...
""" * Copyright 2020, Departamento de sistemas y Computación, * Universidad de Los Andes * * * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import winreg from pickle import load , dump from Searcher import Searcher class File begin function __init__ self begin set Searcher = call Searcher end function function readfile self path begin with open file=path mode=string r encoding=string UTF-8 as f begin set text = read f end retu...
# -*- coding: utf-8 -*- import winreg from pickle import load, dump from Searcher import Searcher class File: def __init__(self): self.Searcher = Searcher() def readfile(self, path): with open(file=path, mode='r', encoding='UTF-8') as f: text = f.read() return text d...
Python
zaydzuhri_stack_edu_python
function strategy_comps cls begin Ellipsis end function
def strategy_comps(cls) -> Set[str]: ...
Python
nomic_cornstack_python_v1
function check_for_setup_error self begin set api_version = call get_ontapi_version if api_version begin set tuple major minor = api_version if major == 1 and minor < 9 begin set msg = call _ string Unsupported Data ONTAP version. Data ONTAP version 7.3.1 and above is supported. raise call VolumeBackendAPIException dat...
def check_for_setup_error(self): api_version = self.zapi_client.get_ontapi_version() if api_version: major, minor = api_version if major == 1 and minor < 9: msg = _("Unsupported Data ONTAP version." " Data ONTAP version 7.3.1 and above is s...
Python
nomic_cornstack_python_v1
comment 책 목록 선언 set books = list comment 책 목록 만들기 append books dict string 제목 string 개발자의 코드 ; string 출판연도 string 2013.02.28 ; string 출판사 string A출판 ; string 쪽수 200 ; string 추천유무 false append books dict string 제목 string 클린 코드 ; string 출판연도 string 2013.03.24 ; string 출판사 string B출판 ; string 쪽수 584 ; string 추천유무 true app...
# 책 목록 선언 books = list() # 책 목록 만들기 books.append({'제목':'개발자의 코드','출판연도':'2013.02.28','출판사':'A출판','쪽수':200,'추천유무':False}) books.append({'제목':'클린 코드','출판연도':'2013.03.24','출판사':'B출판','쪽수':584,'추천유무':True}) books.append({'제목':'빅데이터 마케팅','출판연도':'2014.07.02','출판사':'A출판','쪽수':296,'추천유무':True}) books.append({'제목':'구글드','출판연도'...
Python
zaydzuhri_stack_edu_python
for number in range 0 101 begin if number % 3 == 0 and number % 5 == 0 begin print string Dedezinha Querida end else if number % 3 == 0 begin print string Dedezinha end else if number % 5 == 0 begin print string Querida end else begin print string { number } end end
for number in range(0,101): if number%3 == 0 and number%5 == 0: print("Dedezinha Querida") elif number%3 == 0: print("Dedezinha") elif number%5 == 0: print("Querida") else: print(f"{number}")
Python
zaydzuhri_stack_edu_python
from tkinter import * import VideoCapture from csv import writer import numpy as np import cv2 import EyeTracking class TrainingApp begin function __init__ self root cols=6 rows=4 radius=50 video_source=0 file_name=string training_data.csv begin set root = root set cols = cols set rows = rows set circle_radius = radius...
from tkinter import * import VideoCapture from csv import writer import numpy as np import cv2 import EyeTracking class TrainingApp: def __init__(self, root, cols = 6, rows = 4, radius = 50, video_source = 0, file_name = "training_data.csv"): self.root = root self.cols = cols self.rows = r...
Python
zaydzuhri_stack_edu_python
import sqlite3 from sqlite3 import Error class Database begin comment Database class using sqlite3 for the purpose of local user data storage on hard drive function __init__ self begin comment Attempt connection to local db file if possible, else creates a new db file in the current working directory try begin set conn...
import sqlite3 from sqlite3 import Error class Database: # Database class using sqlite3 for the purpose of local user data storage on hard drive def __init__(self): # Attempt connection to local db file if possible, else creates a new db file in the current working directory try: ...
Python
zaydzuhri_stack_edu_python
function pose_info_dict pose **custom_data begin set dict_ = dict string name call name ; string length length residues ; string sequence call sequence for tuple k f in custom_data begin set dict_ at k = f dist pose end return dict_ end function
def pose_info_dict(pose, **custom_data): dict_ = { "name": pose.pdb_info().name(), "length": len(pose.residues), "sequence": pose.sequence(), } for k, f in custom_data: dict_[k] = f(pose) return dict_
Python
nomic_cornstack_python_v1
while currentSideSize <= maxSideLength begin print string Cycle: + string cycle for x in range numberOfSides begin for times in range interval begin set n = n + 1 end set n = n + 1 set sum = sum + n print string Side + string x + 1 + string , adding + string n + string , sum is + string sum end print string Sum after c...
while currentSideSize <= maxSideLength: print("Cycle: "+str(cycle)) for x in range(numberOfSides): for times in range (interval): n += 1 n+= 1 sum += n print(" Side "+str(x+1)+", adding "+str(n)+", sum is "+str(sum)) print("Sum after cycle "+str(cycle)+" is "+...
Python
zaydzuhri_stack_edu_python
import numpy as np import cv2 import logging class ImageWriter extends object begin set RENDER_PIXELS_IN_MM = 8 function __init__ self gcode_writer=none begin set gcode = gcode_writer set logger = call getLogger string image set image = none set w = none set h = none set pixel_size = none if gcode is none begin warning...
import numpy as np import cv2 import logging class ImageWriter(object): RENDER_PIXELS_IN_MM = 8 def __init__(self, gcode_writer=None): self.gcode = gcode_writer self.logger = logging.getLogger("image") self.image = None self.w = None self.h = None self.pixel_si...
Python
zaydzuhri_stack_edu_python
comment 91. 0 comment -1 0 1 comment -2 -1 0 1 2 comment -3 -2 -1 0 1 2 3 comment -4 -3 -2 -1 0 1 2 3 4 print string patterns print string ........... set n = integer input string Enter No of Rows :- for i in range 0 n + 1 begin for c in range 1 n - i + 2 begin print end=string end for c in range i - 1 - 1 begin print ...
## 91. 0 ## -1 0 1 ## -2 -1 0 1 2 ## -3 -2 -1 0 1 2 3 ## -4 -3 -2 -1 0 1 2 3 4 print('\n\t patterns') print('\t...........\n') n = int(input("Enter No of Rows :- ")) for i in range(0,n+1): for c in range(1,n-i+2): print(end=' ') for c in range(i,-1,-1): ...
Python
zaydzuhri_stack_edu_python
import re import copy set fInput = 0 function hw4 input output begin global fInput global fInput2 set fInput = open input string r set fInput2 = open string body.txt string r set f = open output string w set stack = list set hm = dict set funHm = dict set line = string for line in call fileRead begin if starts with...
import re import copy fInput = 0 def hw4(input, output): global fInput global fInput2 fInput = open(input,'r') fInput2 = open('body.txt','r') f = open(output,'w') stack = [] hm = {} funHm= {} line="" for line in fileRead(): if line.startswith('let'): stack.ins...
Python
zaydzuhri_stack_edu_python
while number != 0 begin set counter = counter + 1 set sum = sum + number if number > 0 begin set positive_counter = positive_counter + 1 end else begin set negative_counter = negative_counter + 1 end set number = eval input string Enter an integer (0 to exit): end set average = sum / counter print string The average of...
while number != 0: counter += 1 sum += number if number > 0: positive_counter += 1 else: negative_counter += 1 number = eval(input('Enter an integer (0 to exit): ')) average = sum / counter print(f'The average of the numbers is: {average:.2f}') print(f'The number of positive number ...
Python
zaydzuhri_stack_edu_python
function get_linea_siguiente self begin return lineas_fichero at num_fila + 1 end function
def get_linea_siguiente(self): return self.lineas_fichero [ self.num_fila+1 ]
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon Mar 18 15:36:13 2019 @author: manpreet.saluja import pandas as pd import numpy as np from matplotlib import pyplot as plt set dataset = call DataFrame call rand 10 5 columns=list string A string B string C string D string E scatter plot x=string A y=string B
# -*- coding: utf-8 -*- """ Created on Mon Mar 18 15:36:13 2019 @author: manpreet.saluja """ import pandas as pd import numpy as np from matplotlib import pyplot as plt dataset=pd.DataFrame(np.random.rand(10,5),columns=['A','B','C','D','E']) dataset.plot.scatter(x='A',y='B')
Python
zaydzuhri_stack_edu_python
function formatUrlParam paramRaw begin set res = dict set params = split paramRaw string & for param in params begin set keyValueArr = split param string = if length keyValueArr == 1 begin continue end set res at keyValueArr at 0 = keyValueArr at 1 end return res end function
def formatUrlParam(paramRaw): res = {} params = paramRaw.split("&") for param in params: keyValueArr = param.split("=") if (len(keyValueArr) == 1): continue res[keyValueArr[0]] = keyValueArr[1] return res
Python
zaydzuhri_stack_edu_python
function connect_via self begin return get pulumi self string connect_via end function
def connect_via(self) -> Optional['outputs.IntegrationRuntimeReferenceResponse']: return pulumi.get(self, "connect_via")
Python
nomic_cornstack_python_v1
function linkedListCycle head begin string TC: O(n) | SC: O(n) comment visitedNodes = set() comment ptr = head comment while ptr: comment if ptr in visitedNodes: comment return True comment visitedNodes.add(ptr) comment ptr = ptr.next comment return False string TC: O(n) | SC: O(1) set tuple first second = tuple next n...
def linkedListCycle(head): """ TC: O(n) | SC: O(n) """ # visitedNodes = set() # ptr = head # while ptr: # if ptr in visitedNodes: # return True # visitedNodes.add(ptr) # ptr = ptr.next # return False """ TC: O(n) | SC: O(1) """ first,...
Python
zaydzuhri_stack_edu_python
function reconstruct self sess X_test begin set tuple x_rec_mean x_rec_log_sigma_sq = run tuple x_reconstr x_log_sigma_sq feed_dict=dict x X_test return tuple x_rec_mean x_rec_log_sigma_sq end function
def reconstruct(self, sess, X_test): x_rec_mean, x_rec_log_sigma_sq = sess.run((self.x_reconstr, self.x_log_sigma_sq), feed_dict={self.x: X_test}) return x_rec_mean, x_rec_log_sigma_sq
Python
nomic_cornstack_python_v1
function test_metrics_since_aggregate self begin set slugs = list string test-a string test-b set years = 5 set link_type = string aggregate set granularity = string weekly set now = call datetime 2014 7 4 set module = string redis_metrics.templatetags.redis_metric_tags.datetime with patch module as mock_datetime begin...
def test_metrics_since_aggregate(self): slugs = ['test-a', 'test-b'] years = 5 link_type = "aggregate" granularity = "weekly" now = datetime(2014, 7, 4) module = 'redis_metrics.templatetags.redis_metric_tags.datetime' with patch(module) as mock_datetime: ...
Python
nomic_cornstack_python_v1
function __init__ self model_name_or_path=string google/tapas-base-finetuned-wtq model_version=none tokenizer=none use_gpu=true top_k=10 top_k_per_candidate=3 return_no_answer=false max_seq_len=256 use_auth_token=none devices=none begin call check call __init__ set tuple devices _ = call initialize_device_settings devi...
def __init__( self, model_name_or_path: str = "google/tapas-base-finetuned-wtq", model_version: Optional[str] = None, tokenizer: Optional[str] = None, use_gpu: bool = True, top_k: int = 10, top_k_per_candidate: int = 3, return_no_answer: bool = False, ...
Python
nomic_cornstack_python_v1
import ctypes from ctypes import c_char , c_double , pointer as c_pointer_to , POINTER as PointerT from dataclasses import dataclass from typing import List from PGM import PGMImage decorator dataclass class Kernel begin set mask : List at List at int decorator property function rows self begin return length mask end f...
import ctypes from ctypes import c_char, c_double, pointer as c_pointer_to, POINTER as PointerT from dataclasses import dataclass from typing import List from PGM import PGMImage @dataclass class Kernel: mask: List[List[int]] @property def rows(self) -> int: return len(self.mask) @property...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment 四分木による接触判定を作成する。 comment 理論については次を参照: http://marupeke296.com/COL_2D_No8_QuadTree.html comment 実装はいくつかの点で異なるため注意 comment - 双方向リストではなくsetを使っている comment - 非再帰DFSは競プロテクを採用 import logging import random from aabb import Aabb from util import AutoSaveFigure from lqt import LQT from genera...
# -*- coding: utf-8 -*- # 四分木による接触判定を作成する。 # 理論については次を参照: http://marupeke296.com/COL_2D_No8_QuadTree.html # 実装はいくつかの点で異なるため注意 # - 双方向リストではなくsetを使っている # - 非再帰DFSは競プロテクを採用 import logging import random from aabb import Aabb from util import AutoSaveFigure from lqt import LQT from general import display_aabbs, random_aabb ...
Python
zaydzuhri_stack_edu_python
function setvalue self value begin if _value != value begin comment non-blocking if acquire _change_lock 0 begin set _value = value try begin call _notify_subscribers value end finally begin release _change_lock end end else begin raise call RecursionError string Attempted recursion into observable's set method. end en...
def setvalue(self, value): if self._value != value: if self._change_lock.acquire(0): # non-blocking self._value = value try: self._notify_subscribers(value) finally: self._change_l...
Python
nomic_cornstack_python_v1
function test_buffer_overflow_12 self begin set bv = call get_view_of_file string ./bin/Test12/bo set plugin = call get_plugin_instance string PluginBufferOverflow tuple assert is not none plugin string Could not load Plugin Buffer Overflow set args = call ArgParseMock true false run bv args tuple assert is none error ...
def test_buffer_overflow_12(self): bv = binaryninja.BinaryViewType.get_view_of_file("./bin/Test12/bo") plugin = self._plugins.get_plugin_instance('PluginBufferOverflow') self.assertIsNotNone(plugin), 'Could not load Plugin Buffer Overflow' args = ArgParseMock(True, False) plugin....
Python
nomic_cornstack_python_v1
function drs_fitsredmerged_tell_read filin begin comment Read FITS with open filin as hdulist begin comment Headers (0 main, 1 activity ind, 2 low-res chromatic exposure meter spectrograph and barycentric correction) set header0 = header set header1 = header set header2 = header comment Telluric model comment uniform i...
def drs_fitsredmerged_tell_read(filin): # Read FITS with fits.open(filin) as hdulist: # Headers (0 main, 1 activity ind, 2 low-res chromatic exposure meter spectrograph and barycentric correction) header0 = hdulist[0].header header1 = hdulist[1].header header2 = hdulist[2].heade...
Python
nomic_cornstack_python_v1
function itkImageToImageFilterIRGBUS2IRGBUC2_cast *args begin return call itkImageToImageFilterIRGBUS2IRGBUC2_cast *args end function
def itkImageToImageFilterIRGBUS2IRGBUC2_cast(*args): return _itkImageToImageFilterAPython.itkImageToImageFilterIRGBUS2IRGBUC2_cast(*args)
Python
nomic_cornstack_python_v1
function process_encryption_args optional_arg_map begin set _method_name = string __process_encryption_args end function
def process_encryption_args(optional_arg_map): _method_name = '__process_encryption_args'
Python
nomic_cornstack_python_v1
function _get_named_explicit_paths self begin return __named_explicit_paths end function
def _get_named_explicit_paths(self): return self.__named_explicit_paths
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 from functools import reduce print string 调用abs()函数,abs(-10) = absolute - 10 comment 将函数本身赋值给变量 set f = abs print string 将函数本身赋值给变量,f = abs, f(-11) = f dist - 11 comment 函数名也是变量 abs = 10, 那么abs不再指向原来求绝对值函数, abs(-10)出错 comment 如果写了abs = 10 ,重启python交互环境 comment 一个函数可以接收另一个函数作为参数 称为高阶函数 func...
#!/usr/bin/env python3 from functools import reduce print("调用abs()函数,abs(-10) = ", abs(-10)) # 将函数本身赋值给变量 f = abs print("将函数本身赋值给变量,f = abs, f(-11) = ", f(-11)) # 函数名也是变量 abs = 10, 那么abs不再指向原来求绝对值函数, abs(-10)出错 # 如果写了abs = 10 ,重启python交互环境 # 一个函数可以接收另一个函数作为参数 称为高阶函数 def add(x, y, f): return f(x) + f(y) print("...
Python
zaydzuhri_stack_edu_python
function rate self begin return brate / FAC end function
def rate(self): return self.brate / FAC
Python
nomic_cornstack_python_v1
function solution n begin set answer = 0 set num = 0 for i in range 1 n // 2 + 1 begin set a = 0 for j in range i n begin set a = a + j if a == n begin set num = num + 1 break end else if a > n begin break end end end set answer = num + 1 return answer end function
def solution(n): answer = 0 num=0 for i in range(1,n//2+1): a=0 for j in range(i,n): a = a + j if a == n : num=num+1 break elif a>n: break answer = num+1 return answer
Python
zaydzuhri_stack_edu_python
comment Usage: "python cpall.py dir1 dir2". comment Recursive copy of a directory tree. Works like a comment unix "cp -r dirFrom/* dirTo" command, and assumes comment that dirFrom and dirTo are both directories. Was comment written to get around fatal error messages under comment Windows drag-and-drop copies (the first...
######################################################### # Usage: "python cpall.py dir1 dir2". # Recursive copy of a directory tree. Works like a # unix "cp -r dirFrom/* dirTo" command, and assumes # that dirFrom and dirTo are both directories. Was # written to get around fatal error messages under # Windows drag-...
Python
zaydzuhri_stack_edu_python
function reconfigure self control newconf begin raise NotImplementedError end function
def reconfigure(self, control, newconf): raise NotImplementedError
Python
nomic_cornstack_python_v1
function set_used_capacity_pao self pao capacity begin return call _run_query string MATCH (n:PAO {pao:$pao}) SET n.usedCapacity = $capacity keyword dict string pao pao ; string capacity capacity end function
def set_used_capacity_pao(self, pao, capacity): return self._run_query("MATCH (n:PAO {pao:$pao}) SET n.usedCapacity = $capacity", **{'pao': pao, 'capacity': capacity})
Python
nomic_cornstack_python_v1
function desktop_session self begin set user at string desktop_environment = dict string name user at string desktop if user at string desktop is not none begin comment Append required packages if user at string desktop in list 10 11 12 begin set user at string desktop_environment at string requirements = format string...
def desktop_session(self): self.user['desktop_environment'] = {'name': self.user['desktop']} if self.user['desktop'] is not None: # Append required packages if self.user['desktop'] in [10, 11, 12]: self.user['desktop_environment']['requirements'] = \ '{xorg} {xinit} ...
Python
nomic_cornstack_python_v1
function test_command_edit_info_version_1_to_2 begin with named temporary file as tmp begin copy shutil kValid1 name call parse_args list string edit string -i string version:2 name with open name string rb as tmpstream begin set woz = call WozDiskImage tmpstream end assert image_type == kWOZ2 assert info at string ver...
def test_command_edit_info_version_1_to_2(): with tempfile.NamedTemporaryFile() as tmp: shutil.copy(kValid1, tmp.name) wozardry.parse_args(["edit", "-i", "version:2", tmp.name]) with open(tmp.name, "rb") as tmpstream: woz = wozardry.WozDiskImage(tmpstream) assert woz.ima...
Python
nomic_cornstack_python_v1
function api_authenticate username password api_url project_name begin try begin set http_client = call Http set body = dict string username username ; string password password set url = string %s%s % tuple api_url string auth/tokens?auth_method=password set tuple resp content = call request url method=string POST body...
def api_authenticate(username, password, api_url, project_name): try: http_client = httplib2.Http() body = {'username': username, 'password': password} url = "%s%s" % (api_url, 'auth/tokens?auth_method=password') resp, content = http_client.request( url, method="POST", b...
Python
nomic_cornstack_python_v1
from chess.models.players import Player class Round begin function __init__ self players begin set players = players set rounds = list sort players key=lambda player -> elo for player in players begin set score = 0 end set rmatchs = list end function function __str__ self begin set all_match = rmatchs set name_str = ...
from chess.models.players import Player class Round: def __init__(self, players): self.players = players self.rounds = [] self.players.sort(key = lambda player: player.elo) for player in self.players: player.score = 0 self.rmatchs = [] def _...
Python
zaydzuhri_stack_edu_python
import http.server import socketserver set PORT = 8000 comment See: https://docs.python.org/3/library/http.server.html function run Handler begin with call TCPServer tuple string PORT Handler as httpd begin print string serving at port PORT call serve_forever end end function comment HTTPRequestHandler class class tes...
import http.server import socketserver PORT = 8000 # See: https://docs.python.org/3/library/http.server.html def run(Handler): with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever() # HTTPRequestHandler class class testHTTPServer_Request...
Python
zaydzuhri_stack_edu_python
comment python3 string In this class, I did ... Input variables are: example python code use: Author: Phong Nguyen (vietphong.nguyen@gmail.com) Last modified: SEP 2019 import xlrd from read_LC_table_from_file import to_interval , to_sex , to_age , to_race , to_survival function read_distant_cancer_table_from_file file_...
# python3 """ In this class, I did ... Input variables are: example python code use: Author: Phong Nguyen (vietphong.nguyen@gmail.com) Last modified: SEP 2019 """ import xlrd from read_LC_table_from_file import to_interval, to_sex, to_age, to_race, to_survival def read_distant_cancer_table_from_file(file_name...
Python
zaydzuhri_stack_edu_python
function set_cosmology self cosmo_dict redshift=none begin if redshift == none begin set redshift = _redshift end call set_cosmology self cosmo_dict redshift call set_cosmology_object cosmo set _initialized_i_0_4 = false end function
def set_cosmology(self, cosmo_dict, redshift=None): if redshift==None: redshift = self._redshift halo.Halo.set_cosmology(self, cosmo_dict, redshift) self.pert.set_cosmology_object(self.cosmo) self._initialized_i_0_4 = False
Python
nomic_cornstack_python_v1
function run self **func_kwargs begin return call func keyword func_kwargs end function
def run(self, **func_kwargs) -> Any: return self.func(**func_kwargs)
Python
nomic_cornstack_python_v1
function get_duration_sox_n audio_file_path begin global FS_HZ assert FS_HZ is not none set audiometadata = info audio_file_path set num_frames = num_frames set original_fs_hz = sample_rate set duration_n = num_frames comment TODO(theis): probably not exact value set duration_n_resampled = round duration_n * FS_HZ / or...
def get_duration_sox_n(audio_file_path: str) -> float: global FS_HZ assert FS_HZ is not None audiometadata = torchaudio.info(audio_file_path) num_frames = audiometadata.num_frames original_fs_hz = audiometadata.sample_rate duration_n = num_frames # TODO(theis): probably not exact value d...
Python
nomic_cornstack_python_v1
from collections import defaultdict from points import BasePoint class Wiring begin function __init__ self begin set connections = default dictionary set end function function connect self point_a point_b begin assert is instance point_a BasePoint assert is instance point_b BasePoint add connections at point_a point_a ...
from collections import defaultdict from .points import BasePoint ################################################################################ class Wiring: def __init__(self): self.connections = defaultdict(set) def connect(self, point_a, point_b): assert isinstance(point_a, BasePoi...
Python
zaydzuhri_stack_edu_python
import pathlib import csv import json import datetime import argparse from typing import Optional , Dict , Tuple , List function parse_date date_string begin return call date end function function parse_path path begin return call Path path end function class DataRow begin string Stores the individual transaction infor...
import pathlib import csv import json import datetime import argparse from typing import Optional, Dict, Tuple, List def parse_date(date_string: str) -> datetime.date: return datetime.datetime.strptime(date_string, "%Y-%m-%d").date() def parse_path(path: str) -> pathlib.Path: return pathlib.Path(path) cla...
Python
zaydzuhri_stack_edu_python
from Monoid import * class MonoidModP extends Monoid begin set modulus = none function __init__ self value begin call __init__ value end function function addop self rhs begin print string MonoidModP addop: type(self),type(rhs)= type self type rhs set s = v + v % modulus set r = call MonoidModP s return r end function ...
from Monoid import * class MonoidModP(Monoid): modulus=None def __init__(self,value): super().__init__(value) def addop(self,rhs): print("MonoidModP addop: type(self),type(rhs)=",type(self),type(rhs)) s=(self.v+rhs.v) %self.modulus r = MonoidModP(s) retu...
Python
zaydzuhri_stack_edu_python
function maxPoints grid begin set n = length grid at 0 set dp = list comprehension list 0 * n for _ in range 2 set dp at 0 at 0 = grid at 0 at 0 for j in range 1 n begin set dp at 0 at j = dp at 0 at j - 1 + grid at 0 at j end for i in range 1 2 begin set dp at i at 0 = dp at i - 1 at 0 + grid at i at 0 for j in range ...
def maxPoints(grid): n = len(grid[0]) dp = [[0] * n for _ in range(2)] dp[0][0] = grid[0][0] for j in range(1, n): dp[0][j] = dp[0][j-1] + grid[0][j] for i in range(1, 2): dp[i][0] = dp[i-1][0] + grid[i][0] for j in range(1, n): dp[i][j] = max(dp[i-1][j], dp[i][j-...
Python
jtatman_500k
function test_valid_validate_single_file begin set entitylist = list CLIN_ENT set error_string = string set warning_string = string set expected_valid = true set expected_message = string valid message here! set expected_filetype = string clinical with call object GenieValidationHelper string determine_filetype retur...
def test_valid_validate_single_file(): entitylist = [CLIN_ENT] error_string = '' warning_string = '' expected_valid = True expected_message = "valid message here!" expected_filetype = "clinical" with patch.object(validate.GenieValidationHelper, "determine_filetype", ...
Python
nomic_cornstack_python_v1
function create self keys data begin set result = call create data return result end function
def create(self, keys, data): result = super().create(data) return result
Python
nomic_cornstack_python_v1
import os import sys import numpy as np import pandas as pd from tqdm import tqdm import _pickle as pickle import warnings filter warnings string ignore from functions import * string calculating some predictability indicators for several assets 1) Auto-Predictability 2) Efficient Ratio set tuple start_date end_date = ...
import os import sys import numpy as np import pandas as pd from tqdm import tqdm import _pickle as pickle import warnings warnings.filterwarnings('ignore') from functions import * ''' calculating some predictability indicators for several assets 1) Auto-Predictability 2) Efficient Ratio ''' start_date, end_date = N...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- string ┏┛ ┻━━━━━┛ ┻┓ ┃ ┃ ┃ ━ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┃ ┃ ┻ ┃ ┃ ┃ ┗━┓ ┏━━━┛ ┃ ┃ 神兽保佑 ┃ ┃ 代码无BUG! ┃ ┗━━━━━━━━━┓ ┃ ┣┓ ┃ ┏┛ ┗━┓ ┓ ┏━━━┳ ┓ ┏━┛ ┃ ┫ ┫ ┃ ┫ ┫ ┗━┻━┛ ┗━┻━┛ class Solution extends object begin function reverseString self s begin string :type s: List[str] :rtype: None Do not return anything, modi...
# -*- coding:utf-8 -*- """ ┏┛ ┻━━━━━┛ ┻┓ ┃       ┃ ┃   ━   ┃ ┃ ┳┛  ┗┳ ┃ ┃       ┃ ┃   ┻   ┃ ┃       ┃ ┗━┓   ┏━━━┛ ┃   ┃ 神兽保佑 ┃   ┃ 代码无BUG! ┃   ┗━━━━━━━━━┓ ┃        ┣┓ ┃     ┏┛ ┗━┓ ┓ ┏━━━┳ ┓ ┏━┛ ┃ ┫...
Python
zaydzuhri_stack_edu_python
if __name__ == string __main__ begin set n = integer input for _ in range n begin set num = string input set answer = sum list comprehension integer x for x in num print answer end end
if __name__ == "__main__": n = int(input()) for _ in range(n): num = str(input()) answer = sum([int(x) for x in num]) print(answer)
Python
zaydzuhri_stack_edu_python
import pyautogui as pag function HCI r begin print string here set screen = size pag set c = call position set seconds = 1 set clickflag = true set dragflag = true comment info = [0, 1, 0, 0, 0, 0, 0, 1, 0] comment fist = start if r == 1 begin set flag = true end comment if flag: comment info = [failure, fist, up, down...
import pyautogui as pag def HCI(r): print("here") screen = pag.size() c = pag.position() seconds = 1 clickflag = True dragflag = True #info = [0, 1, 0, 0, 0, 0, 0, 1, 0] #fist = start if r == 1: flag = True #if flag: #info = [failure, fist, up, down, left, righ...
Python
zaydzuhri_stack_edu_python
function write_fasta_file pdb_names pdb_sequences filename dump_dir=string begin comment ensure that the pdb_names and pdb_sequences lists are the same length if length pdb_names != length pdb_sequences begin return false end comment add .txt to the filename, if needed if not ends with filename string .txt begin set fi...
def write_fasta_file(pdb_names, pdb_sequences, filename, dump_dir=''): # ensure that the pdb_names and pdb_sequences lists are the same length if len(pdb_names) != len(pdb_sequences): return False # add .txt to the filename, if needed if not filename.endswith(".txt"): filename += ".txt"...
Python
nomic_cornstack_python_v1
string @version:01.00.00 @Author:Shenglong class Solution begin set tuple n k = tuple 0 0 set value = 0 function kthSmallest self root k begin string Solution1: 前序遍历所有节点,最后返回相应index值即可 res = [] def preorder(root): if root: preorder(root.left) res.append(root.val) preorder(root.right) preorder(root) return res[k-1] stri...
""" @version:01.00.00 @Author:Shenglong """ class Solution: n, k = 0, 0 value = 0 def kthSmallest(self, root: TreeNode, k: int) -> int: ''' Solution1: 前序遍历所有节点,最后返回相应index值即可 res = [] def preorder(root): if root: preorder(root.left) ...
Python
zaydzuhri_stack_edu_python
function get_key_field_list self ObjectType begin comment Lower case only. set obj_type = lower ObjectType comment Attempt to get the key field DataFrame from our cached comment dictionary. try begin set key_field_df = _object_key_fields at obj_type end except KeyError begin comment DataFrame isn't cached. Get it. set ...
def get_key_field_list(self, ObjectType: str) -> List[str]: # Lower case only. obj_type = ObjectType.lower() # Attempt to get the key field DataFrame from our cached # dictionary. try: key_field_df = self._object_key_fields[obj_type] except KeyError: ...
Python
nomic_cornstack_python_v1
function __init__ self dates cooks balances schedule begin set dates = dates set cooks = cooks set cooking_balance = balances set schedule = schedule call calc_init end function
def __init__(self, dates, cooks, balances, schedule): self.dates = dates self.cooks = cooks self.cooking_balance = balances self.schedule = schedule self.calc_init()
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter import ttk from openpyxl import * from tkinter import messagebox class Products extends Frame begin function __init__ self *args **kwargs begin call __init__ self *args keyword kwargs set main = none set file = string set workbook = call load_workbook string data.xlsx set sheet = act...
from tkinter import * from tkinter import ttk from openpyxl import * from tkinter import messagebox class Products(Frame): def __init__(self, *args,**kwargs): Frame.__init__(self,*args,**kwargs) self.main = None self.file = '' workbook = load_workbook('data.xlsx') sheet = ...
Python
zaydzuhri_stack_edu_python
function evaluate_model model tokenizer max_length img_to_cap_dict img_features begin set tuple ground_truth_captions generated_captions = tuple list list comment For each image name of the img_to_cap_dict dictionary, comment take the features of the current image and generate a caption. comment Store the generated c...
def evaluate_model(model, tokenizer, max_length, img_to_cap_dict, img_features): ground_truth_captions, generated_captions = [], [] # For each image name of the img_to_cap_dict dictionary, # take the features of the current image and generate a caption. # Store the generated caption and the ground truth caption...
Python
nomic_cornstack_python_v1
function chunks lst n begin for i in range 0 length lst n begin yield lst at slice i : i + n : end end function
def chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n]
Python
nomic_cornstack_python_v1
comment DERIVED FROM GOOGLE'S WEBSOCKET GAE EXAMPLE comment https://cloud.google.com/appengine/docs/flexible/python/using-websockets-and-session-affinity comment git clone https://github.com/GoogleCloudPlatform/python-docs-samples from flask import Flask , request , render_template , redirect , url_for from flask_socke...
# DERIVED FROM GOOGLE'S WEBSOCKET GAE EXAMPLE # https://cloud.google.com/appengine/docs/flexible/python/using-websockets-and-session-affinity # git clone https://github.com/GoogleCloudPlatform/python-docs-samples from flask import Flask, request, render_template, redirect, url_for from flask_sockets i...
Python
zaydzuhri_stack_edu_python
function EllipticCurve curvename=string Ed25519 coordinates=none begin if coordinates is none begin set coordinates = string affine end return call _EllipticCurve curvename coordinates end function
def EllipticCurve(curvename='Ed25519', coordinates=None): if coordinates is None: coordinates = 'affine' return _EllipticCurve(curvename, coordinates)
Python
nomic_cornstack_python_v1
function rotate self matrix begin set tmp = list set _n = length matrix for idx1 in range _n begin set _tmp_list = list for idx2 in range _n - 1 - 1 - 1 begin append _tmp_list matrix at idx2 at idx1 end append tmp _tmp_list end comment matrix = tmp for _idx1 in range _n begin set matrix at _idx1 = tmp at _idx1 end en...
def rotate(self, matrix: List[List[int]]) -> None: tmp = [] _n = len(matrix) for idx1 in range(_n): _tmp_list = [] for idx2 in range(_n - 1, -1, -1): _tmp_list.append(matrix[idx2][idx1]) tmp.append(_tmp_list) #matrix = tmp for ...
Python
nomic_cornstack_python_v1
from django.db import models from users.models import User import datetime class Question extends Model begin set title = call CharField max_length=500 set body = call TextField max_length=none set created_at = call DateTimeField auto_now_add=true set user = call ForeignKey to=User related_name=string users_quesitons o...
from django.db import models from users.models import User import datetime class Question(models.Model): title = models.CharField(max_length= 500) body = models.TextField(max_length=None) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(to=User, related_name='users_quesiton...
Python
zaydzuhri_stack_edu_python
class TreeNode begin function __init__ self key val left=none right=none parent=none begin set key = key set payload = val set left_child = left set right_child = right set parent = parent end function function has_left_child self begin return left_child end function function has_right_child self begin return right_chi...
class TreeNode: def __init__(self,key,val,left=None,right=None, parent=None): self.key = key self.payload = val self.left_child = left self.right_child = right self.parent = parent def has_left_child(self): return self.left_child def has_right_child(self): ...
Python
zaydzuhri_stack_edu_python
function estimate_dt time_array begin if length time_array < 2 begin comment Assume arbitrary value return time delta seconds=0 end set dt = median diff np time_array if not is instance dt timedelta begin set dt = time delta seconds=as type dt float / 1000000000.0 end comment Check if data is all ascending if dt <= tim...
def estimate_dt(time_array): if len(time_array) < 2: # Assume arbitrary value return datetime.timedelta(seconds=0) dt = np.median(np.diff(time_array)) if not isinstance(dt, datetime.timedelta): dt = datetime.timedelta(seconds=dt.astype(float)/1e9) # Check if data is ...
Python
nomic_cornstack_python_v1
string Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] com...
""" Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ ...
Python
zaydzuhri_stack_edu_python