code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function remove self access_control begin try begin set access_list = call _discern_list access_control end except NoAppropriateListError begin raise call TypeError string Cannot remove access control of type %s % t end remove access_list zserv access_control end function
def remove(self, access_control): try: access_list = self._discern_list(access_control) except NoAppropriateListError: raise TypeError("Cannot remove access control of type %s" % (t)) access_list.remove(self.zserv, access_control)
Python
nomic_cornstack_python_v1
function is_palindrome word begin set reversed_word = word at slice : : - 1 if word == reversed_word begin return true end else begin return false end end function set result = call is_palindrome string civic print result
def is_palindrome(word): reversed_word = word[::-1] if word == reversed_word: return True else: return False result = is_palindrome('civic') print(result)
Python
jtatman_500k
function get_union a b begin return list set a ? set b end function
def get_union(a, b): return list(set(a) | set(b))
Python
nomic_cornstack_python_v1
function policy self value begin set _policy = value end function
def policy(self, value): self._policy = value
Python
nomic_cornstack_python_v1
while i < length members begin print members at i set i = i + 1 end
while i < len(members): print(members[i]) i = i + 1
Python
zaydzuhri_stack_edu_python
function positional_encoding tensor num_encoding_functions=6 include_input=true log_sampling=true begin comment TESTED comment Trivially, the input tensor is added to the positional encoding. set encoding = if expression include_input then list tensor else list set frequency_bands = none if log_sampling begin set freq...
def positional_encoding( tensor, num_encoding_functions=6, include_input=True, log_sampling=True ) -> torch.Tensor: # TESTED # Trivially, the input tensor is added to the positional encoding. encoding = [tensor] if include_input else [] frequency_bands = None if log_sampling: frequency_b...
Python
nomic_cornstack_python_v1
import random set seguir = string print string SIMULADOR DE DADOS print input string Para continuar presiona INTRO --> print while seguir == string begin set dado1 = random integer 1 6 set dado2 = random integer 1 6 set suma = dado1 + dado2 print string El primer dado vale --> dado1 print string El segundo dado vale ...
import random seguir = "" print("SIMULADOR DE DADOS") print() input("Para continuar presiona INTRO --> ") print() while seguir == "": dado1= random.randint(1,6) dado2= random.randint(1,6) suma = dado1+dado2 print("El primer dado vale --> ", dado1) print("El segundo dado vale --> ", dado2) p...
Python
zaydzuhri_stack_edu_python
import time function is_leap_year year begin if year % 4 != 0 begin return false end else if year % 100 != 0 begin return true end else if year % 400 != 0 begin return false end else begin return true end end function function get_current_date_time begin comment Calculate the number of seconds since January 1, 1970 set...
import time def is_leap_year(year): if year % 4 != 0: return False elif year % 100 != 0: return True elif year % 400 != 0: return False else: return True def get_current_date_time(): # Calculate the number of seconds since January 1, 1970 current_timestamp = int...
Python
jtatman_500k
from __future__ import division from integration import * import numpy as np import counter import scipy.integrate as integrate
from __future__ import division from integration import * import numpy as np import counter import scipy.integrate as integrate
Python
zaydzuhri_stack_edu_python
comment convert from the .csv file to a single text file of headers comment this text file defines the header used to generate the GOSISS data import yaml import pandas as pd comment load yaml definitions with open string variable-definitions.yaml string r as stream begin try begin set varlist = load yaml stream end ex...
# convert from the .csv file to a single text file of headers # this text file defines the header used to generate the GOSISS data import yaml import pandas as pd # load yaml definitions with open("variable-definitions.yaml", 'r') as stream: try: varlist = yaml.load(stream) except yaml.YAMLError as exc...
Python
zaydzuhri_stack_edu_python
comment Quick command line parser import sys comment takes string "key" class CommandLineParser begin set dict = dict set loose = list function setup self begin for arg in argv at slice 1 : : begin set key_value = split arg string = if length key_value < 2 begin append loose key_value at 0 continue end else begin s...
# Quick command line parser import sys # takes string "key" class CommandLineParser: dict = {} loose = [] def setup(self): for arg in sys.argv[1:]: key_value = arg.split("=") if (len(key_value) < 2): self.loose.append(key_value[0]) continue...
Python
zaydzuhri_stack_edu_python
comment Player class from BayesMarkov import * class Player begin function __init__ self possibleActions begin set name = string Human Player set possibleActions = list comprehension name for a in possibleActions set pastActions = string set numActions = 0 set numWins = 0 set adversaryActions = string set actionList ...
# Player class from BayesMarkov import * class Player: def __init__(self, possibleActions): self.name = "Human Player" self.possibleActions = [a.name for a in possibleActions] self.pastActions = '' self.numActions = 0 self.numWins = 0 self.adversaryActions = '' ...
Python
zaydzuhri_stack_edu_python
function sounding_generator option_dict desired_num_examples=none desired_full_id_strings=none desired_times_unix_sec=none begin set tuple full_storm_id_strings storm_times_unix_sec storm_to_file_indices = call _find_examples_to_read option_dict=option_dict desired_num_examples=desired_num_examples desired_full_id_stri...
def sounding_generator( option_dict, desired_num_examples=None, desired_full_id_strings=None, desired_times_unix_sec=None): full_storm_id_strings, storm_times_unix_sec, storm_to_file_indices = ( _find_examples_to_read( option_dict=option_dict, desired_num_examples=desired_num_ex...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment # Unit 5 - Financial Planning comment In[23]: comment Initial imports import os import requests import pandas as pd from dotenv import load_dotenv import numpy as np import alpaca_trade_api as tradeapi from MCForecastTools import MCSimulation import io call run...
#!/usr/bin/env python # coding: utf-8 # # Unit 5 - Financial Planning # # In[23]: # Initial imports import os import requests import pandas as pd from dotenv import load_dotenv import numpy as np import alpaca_trade_api as tradeapi from MCForecastTools import MCSimulation import io get_ipython().run_line_magic('m...
Python
zaydzuhri_stack_edu_python
comment real signature unknown function __setattr__ self *args **kwargs begin pass end function
def __setattr__(self, *args, **kwargs): # real signature unknown pass
Python
nomic_cornstack_python_v1
string ============================================================ http://projecteuler.net/problem=153 ============================================================ import numpy as np , time from problem005 import gcd from numpy.testing.utils import assert_equal comment ------------------------------- comment Real (rat...
''' ============================================================ http://projecteuler.net/problem=153 ============================================================ ''' import numpy as np, time from problem005 import gcd from numpy.testing.utils import assert_equal #------------------------------- # Real (rational) divi...
Python
zaydzuhri_stack_edu_python
comment Edgar Ruiz comment CS 299 comment Lab 8 comment November 15th, 2016 comment !/usr/bin/python function revString line newLine=string begin if length newLine == length line begin return newLine end else begin set newLine = newLine + line at length line - length newLine - 1 return call revString line newLine end e...
#Edgar Ruiz #CS 299 #Lab 8 #November 15th, 2016 #!/usr/bin/python def revString(line, newLine = ""): if len(newLine) == len(line): return newLine else: newLine += line[len(line) - len(newLine) - 1] return revString(line, newLine) def pattern(num): if num == 0: print(num, e...
Python
zaydzuhri_stack_edu_python
function count_sheep n begin set results = list for num in range 1 n + 1 begin comment 字串放陣列 append results string num + string sheep... end comment 陣列轉字串 return join string results end function comment 測試 comment , "1 sheep..."); print call count_sheep 1 comment , "1 sheep...2 sheep...") print call count_sheep 2 com...
def count_sheep(n): results=[] for num in range(1,n+1): results.append(str(num)+" sheep...") #字串放陣列 return ''.join(results) #陣列轉字串 # 測試 print(count_sheep(1)) #, "1 sheep..."); print(count_sheep(2)) #, "1 sheep...2 sheep...") print(count_sheep(3)) #, "1 sheep...2 sheep...3 sheep...
Python
zaydzuhri_stack_edu_python
import numpy as np from numpy import random as rn import scipy.stats as ss comment This example is about using control variable in simulation to reduce the variance in the estimation. comment here is estimation the price of asian call option that pays (average of s - k)+, comment with using control variable of regular ...
import numpy as np from numpy import random as rn import scipy.stats as ss # This example is about using control variable in simulation to reduce the variance in the estimation. # here is estimation the price of asian call option that pays (average of s - k)+, # with using control variable of regular (vanilla) call op...
Python
zaydzuhri_stack_edu_python
import abjad set instrument_one = call Violin set instrument_one_range = pitch_range set instrument_one_range_lowest = call NumberedPitch start_pitch set instrument_one_range_highest = call NumberedPitch stop_pitch set instrument_two = call Violin set instrument_two_range = pitch_range set instrument_two_range_lowest =...
import abjad instrument_one = abjad.Violin() instrument_one_range = instrument_one.pitch_range instrument_one_range_lowest = abjad.NumberedPitch(instrument_one_range.start_pitch) instrument_one_range_highest = abjad.NumberedPitch(instrument_one_range.stop_pitch) instrument_two = abjad.Violin() instrument_two_range = ...
Python
zaydzuhri_stack_edu_python
import re function Count dict begin set key_count_dict = dict set value_count_dict = dict set value_list = list for key in keys dict begin set key_count_dict at key = length dict at key set value_list = value_list + dict at key end comment print(value_list) for i in value_list begin if i not in keys value_count_dict...
import re def Count(dict): key_count_dict={} value_count_dict = {} value_list=[] for key in dict.keys(): key_count_dict[key]=len(dict[key]) value_list+=dict[key] #print(value_list) for i in value_list: if i not in value_count_dict.keys(): value_count_dict[...
Python
zaydzuhri_stack_edu_python
function __len__ self begin return _size end function
def __len__(self): return self._size
Python
nomic_cornstack_python_v1
function set_not_complete request begin set current_user = get objects user=get objects email=email print string Set not complete: request if current_lesson_set is none begin return false end set current_set = all if exists current_set begin if method == string POST begin print string Not complete call from POST commen...
def set_not_complete(request): current_user = UserInformation.objects.get(user=User.objects.get(email=request.user.email)) print("Set not complete: ", request) if current_user.current_lesson_set is None: return False current_set = current_user.current_lesson_set.lessons.all() if current_set...
Python
nomic_cornstack_python_v1
string Source: https://py.checkio.org/en/mission/pawn-brotherhood/ Description: A pawn is generally a weak unit, but we have 8 of them which we can use to build a pawn defense wall. With this strategy, one pawn defends the others. A pawn is safe if another pawn can capture a unit on that square. We have several white p...
""" Source: https://py.checkio.org/en/mission/pawn-brotherhood/ Description: A pawn is generally a weak unit, but we have 8 of them which we can use to build a pawn defense wall. With this strategy, one pawn defends the others. A pawn is safe if another pawn can capture a unit on that square. We have several white paw...
Python
zaydzuhri_stack_edu_python
function print_msg msg begin if not PY3 begin print call utf8_encode msg end else begin print msg end end function
def print_msg(msg): if not PY3: print(utf8_encode(msg)) else: print(msg)
Python
nomic_cornstack_python_v1
function download_assay_data_by_attr prop_name prop_value study_name=none start=none count=none value_type=none studies=none user=none token_info=none begin comment noqa: E501 return call download_assay_data_by_attr prop_name prop_value study_name start=start count=count value_type=value_type studies=studies user=user ...
def download_assay_data_by_attr(prop_name, prop_value, study_name=None, start=None, count=None, value_type=None, studies=None, user=None, token_info=None): # noqa: E501 return assay_datum_controller.download_assay_data_by_attr(prop_name, ...
Python
nomic_cornstack_python_v1
set fruit = list string apple string banana string cherry print string original fruit list: fruit append fruit string strawberry print string added fruit in new fruit list: fruit
fruit = ["apple", "banana", "cherry"] print("original fruit list:", fruit) fruit.append("strawberry") print("added fruit in new fruit list:", fruit)
Python
zaydzuhri_stack_edu_python
from collections import Counter set _ = input set s = input set s = counter s set ans = 1 for i in values s begin set ans = ans * i + 1 % 10 ^ 9 + 7 end print ans - 1
from collections import Counter _=input() s=input() s=Counter(s) ans=1 for i in s.values(): ans=(ans*(i+1))%(10**9+7) print(ans-1)
Python
zaydzuhri_stack_edu_python
class User begin function __init__ self name score plays begin set __name = name set __score = score set __plays = plays end function function getName self begin return __name end function function setName self name begin set __name = name end function function getScore self begin return __score end function function s...
class User: def __init__(self, name, score, plays): self.__name = name self.__score = score self.__plays = plays def getName(self): return self.__name def setName(self,name): self.__name = name def getScore(self): return self.__score def setScore(s...
Python
zaydzuhri_stack_edu_python
function envs self begin return get pulumi self string envs end function
def envs(self) -> Optional[Sequence['outputs.CSIPowerMaxSpecDriverCommonEnvs']]: return pulumi.get(self, "envs")
Python
nomic_cornstack_python_v1
function SAT_link_transformation_to_table self begin set cnf = list for rule in consider_order begin for v in f2v_direct at rule begin set k = inv at v append cnf v ? call map_merge_table rule table end end comment A merge 'implies' a placement of a merged rule into a table for tuple k v in call viewitems v_merge begi...
def SAT_link_transformation_to_table(self): cnf = [] for rule in self.consider_order: for v in self.f2v_direct[rule]: k = self.v_direct.inv[v] cnf.append( v >> self.map_merge_table(rule, k.place.table)) # A merge 'implies' a placem...
Python
nomic_cornstack_python_v1
function readMembers self begin set f = open string %s/raw_clumpmembers_%s % tuple wd file string rb comment Skip first and last entries from this array. set data = call fromfile f dtype=string i at slice 1 : - 1 : set nclumps = max data set members = dict comment I think we don't want ID==0 as this refers to no clum...
def readMembers(self): f = open('%s/raw_clumpmembers_%s' %(self.wd,self.file), 'rb') #Skip first and last entries from this array. data = np.fromfile(f, dtype='i')[1:-1] self.nclumps = max(data) members = {} # I think we don...
Python
nomic_cornstack_python_v1
comment 'MULTIDIMENSIONAL MODELS' ROOT.RooFit tutorial macro #306 comment Complete example with use of conditional p.d.f. with per-event errors comment 07/2008 - Wouter Verkerke comment / import ROOT function rf306_condpereventerrors begin comment B - p h y s i c s p d f w i t h p e r - e v e n t G a u s s i a n r e s ...
##################################### # # 'MULTIDIMENSIONAL MODELS' ROOT.RooFit tutorial macro #306 # # Complete example with use of conditional p.d.f. with per-event errors # # # # 07/2008 - Wouter Verkerke # # / import ROOT def rf306_condpereventerrors(): # B - p h y s i c s p d f w i t h p e r - e v e ...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function removeDuplicateLetters self s begin string :type s: str :rtype: str set countList = list 0 * 26 set boolList = list false * 26 for c in s begin set countList at ordinal c - ordinal string a = countList at ordinal c - ordinal string a + 1 end set stack = list for c in s begi...
class Solution(object): def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ countList = [0] *26 boolList = [False] * 26 for c in s: countList[ord(c)-ord('a')] +=1 stack = [] for c in s: countList[ord(c)...
Python
zaydzuhri_stack_edu_python
function growing_plant upSpeed downSpeed desiredHeight begin if upSpeed <= desiredHeight or upSpeed >= desiredHeight begin set pesoAhora = 0 set dias = 0 while pesoAhora <= desiredHeight begin set pesoAhora = pesoAhora + upSpeed set dias = dias + 1 if pesoAhora >= desiredHeight begin return dias end else begin set peso...
def growing_plant(upSpeed, downSpeed, desiredHeight): if upSpeed <= desiredHeight or upSpeed >= desiredHeight: pesoAhora = 0 dias = 0 while pesoAhora <= desiredHeight: pesoAhora = pesoAhora + upSpeed dias = dias + 1 if pesoAhora >= desiredHeight: ...
Python
zaydzuhri_stack_edu_python
function vectra_search_detections_command client **kwargs begin set api_response = call search_detections keyword kwargs set count = get api_response string count if count is none begin raise call VectraException string API issue - Response is empty or invalid end set detections_data = list if count == 0 begin set read...
def vectra_search_detections_command(client: Client, **kwargs) -> CommandResults: api_response = client.search_detections(**kwargs) count = api_response.get('count') if count is None: raise VectraException('API issue - Response is empty or invalid') detections_data = list() if count == 0: ...
Python
nomic_cornstack_python_v1
function preprocess query begin set query = split query string open 1 at 1 comment remove punctuations set query = call translate call maketrans string string punctuation set query = split query set s = string for word in query begin if word not in en_stops begin set s = s + word end end return s end function if __n...
def preprocess(query): query=query.split("open",1)[1] query=query.translate(str.maketrans('', '', string.punctuation)) # remove punctuations query= query.split() s="" for word in query: if word not in en_stops: s+=word return s if __name__ == '__main__': # print(preproce...
Python
zaydzuhri_stack_edu_python
function write_i2c_block_data self i2c_address register values begin raise call IOError string Pretending there's no EEPROM to talk to. end function comment self.regs[register:register + len(values)] = values
def write_i2c_block_data(self, i2c_address, register, values): raise IOError("Pretending there's no EEPROM to talk to.") # self.regs[register:register + len(values)] = values
Python
nomic_cornstack_python_v1
set c1 = list string input set c2 = list string input set c3 = list string input print c1 at 0 + c2 at 1 + c3 at 2
c1 = list(str(input())) c2 = list(str(input())) c3 = list(str(input())) print(c1[0]+c2[1]+c3[2])
Python
zaydzuhri_stack_edu_python
function get_pkts_at_macdst self mac_dest begin set sent_pkt = list set recv_pkt = list set drop_pkt = list for line in input_lines begin set send_event_found = search line set recv_event_found = search line set drop_event_found = search line if send_event_found != none begin set tracelvl = search line if tracelvl !...
def get_pkts_at_macdst(self, mac_dest): sent_pkt = [] recv_pkt = [] drop_pkt = [] for line in self.input_lines: send_event_found = find_send_event.search(line) recv_event_found = find_recv_event.search(line) drop_event_found = find_drop_event....
Python
nomic_cornstack_python_v1
function test begin set N = integer input set nums = sorted list map int split input for i in range 1 N begin if nums at i - 1 != i begin append result i return end end append result N end function set result = list for i in range integer input begin call test end for i in result begin print i end
def test(): N = int(input()) nums = sorted(list(map(int, input().split()))) for i in range(1, N): if nums[i-1] != i: result.append(i) return result.append(N) result = [] for i in range(int(input())): test() for i in result: print(i)
Python
zaydzuhri_stack_edu_python
comment linear algebra import numpy as np comment data processing, CSV file I/O import pandas as pd comment Input data files are available in the "../input/" directory. from subprocess import check_output set input_folder = string ../../moviedata comment print(check_output(["ls", input_folder]).decode("utf8")) import o...
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O # Input data files are available in the "../input/" directory. from subprocess import check_output input_folder = "../../moviedata" # print(check_output(["ls", input_folder]).decode("utf8")) import os import pandas as pd from panda...
Python
zaydzuhri_stack_edu_python
function aic_c self begin if has attribute self string _aic_c begin return _aic_c end else begin set k = length params set n = sum set _aic_c = call aic + 2 * k ^ 2 + 2 * k / n - k - 1 return _aic_c end end function
def aic_c(self): if hasattr(self, '_aic_c'): return self._aic_c else: k = len(self.params) n = self.data['n'].sum() self._aic_c = self.aic() + (2*k**2 + 2*k)/(n - k - 1) return self._aic_c
Python
nomic_cornstack_python_v1
function __init__ self output_file dry_run=false begin call __init__ self set output_file = output_file set _dry_run = dry_run end function
def __init__(self, output_file, dry_run=False): _Router.__init__(self) self.output_file = output_file self._dry_run = dry_run
Python
nomic_cornstack_python_v1
function is_brush self begin return length solids > 0 end function
def is_brush(self) -> bool: return len(self.solids) > 0
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import os from pathlib import Path import json import hashlib set CACHE_FILE = expand user call Path string ~/.cache/py_partial_hash.json set partial_hash_cache = dict function load_hash_cache begin global partial_hash_cache try begin with open CACHE_FILE as f begin set partial_hash_cache...
#!/usr/bin/env python3 import os from pathlib import Path import json import hashlib CACHE_FILE = Path('~/.cache/py_partial_hash.json').expanduser() partial_hash_cache = {} def load_hash_cache(): global partial_hash_cache try: with open(CACHE_FILE) as f: partial_hash_cache = json.load(f) except File...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 import copy class Lam begin function reduce sl begin set res = sl while true begin comment print res set tr = step res if tr == none begin break end set res = tr end comment print res return res end function function to_i sl begin set red = call App call App sl call Val string s call Val string z ...
#coding: utf-8 import copy class Lam: def reduce(sl): res = sl while True: #print res tr = res.step() if tr==None: break res = tr #print res return res def to_i(sl): red = App(App(sl,Val("s")),Val("z")) #print red red = red.reduce() #print "red .. ",red res = 0 while True: i...
Python
zaydzuhri_stack_edu_python
import itertools import math import sys from functools import partial from pathlib import Path set debug = partial print file=stderr set p = call Path string input.txt set a = list comprehension integer line for line in call splitlines function part1 begin for x in a begin for y in a at slice 1 : : begin if x + y == ...
import itertools import math import sys from functools import partial from pathlib import Path debug = partial(print, file=sys.stderr) p = Path('input.txt') a = [int(line) for line in p.read_text().splitlines()] def part1(): for x in a: for y in a[1:]: if x + y == 2020: print(...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Dec 15 18:48:47 2020 @author: Javier Martínez import pandas as pd from ast import literal_eval from tqdm import tqdm from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation as LDA import matplotlib.pyplot...
# -*- coding: utf-8 -*- """ Created on Tue Dec 15 18:48:47 2020 @author: Javier Martínez """ import pandas as pd from ast import literal_eval from tqdm import tqdm from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation as LDA import matplotl...
Python
zaydzuhri_stack_edu_python
function simulate self **kwargs begin import msprime as msp set de = list comprehension call PopulationParametersChange time=tt initial_size=Ne_t for tuple tt Ne_t in zip t Ne at slice : - 1 : update kwargs dict string demographic_events de return call simulate keyword kwargs end function
def simulate(self, **kwargs) -> "tskit.TreeSequence": import msprime as msp de = [ msp.PopulationParametersChange(time=tt, initial_size=Ne_t) for tt, Ne_t in zip(self.t, self.Ne[:-1]) ] kwargs.update({"demographic_events": de}) return msp.simulate(**kwarg...
Python
nomic_cornstack_python_v1
string The approach is to iterate through the array of strings and sort each string, add new strings as key and empty list as value to hashmap. When we find a matched string, append the strings to the list values comment Accepted on leetcode comment Time complexity - O(n) as we traverse entire list comment Space omplex...
"""The approach is to iterate through the array of strings and sort each string, add new strings as key and empty list as value to hashmap. When we find a matched string, append the strings to the list values""" #Accepted on leetcode #Time complexity - O(n) as we traverse entire list #Space omplexity - O(1) sinc...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string The ``sncf`` module =================== Get next departures Labège-Innopole -> Toulouse Matabiau. Usage ----- python sncf.py python sncf.py --next 5 import argparse from datetime import datetime import sys import requests from settings import SNCF_API_KE...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The ``sncf`` module =================== Get next departures Labège-Innopole -> Toulouse Matabiau. Usage ----- python sncf.py python sncf.py --next 5 """ import argparse from datetime import datetime import sys import requests from settings import SNCF_API_KEY AP...
Python
zaydzuhri_stack_edu_python
function test_date self real_track tmp_session begin add tmp_session real_track assert query query string 'date: { string date } ' tmp_session assert query query string 'date::.*' tmp_session end function
def test_date(self, real_track, tmp_session): tmp_session.add(real_track) assert query.query(f"'date:{str(real_track.date)}'", tmp_session) assert query.query("'date::.*'", tmp_session)
Python
nomic_cornstack_python_v1
function getDataview self namespace_id dataview_id begin if namespace_id is none begin raise TypeError end if dataview_id is none begin raise TypeError end set response = get requests __url + format __dataviewPath api_version=__apiVersion tenant_id=__tenant namespace_id=namespace_id dataview_id=dataview_id headers=call...
def getDataview(self, namespace_id, dataview_id): if namespace_id is None: raise TypeError if dataview_id is None: raise TypeError response = requests.get( self.__url + self.__dataviewPath.format(api_version=self.__apiVersion, tenant_id=self.__tenant, namespa...
Python
nomic_cornstack_python_v1
function reset self begin start thread target=calc_LUT name=string calc_LUT end function
def reset(self): threading.Thread(target=self.calc_LUT, name="calc_LUT").start()
Python
nomic_cornstack_python_v1
function dis self begin return call nlegomena 2 end function
def dis(self): return self.nlegomena(2)
Python
nomic_cornstack_python_v1
import sys import csv import numpy as np import pandas as pd import retrieveHECData from sklearn.svm import SVC from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifi...
import sys import csv import numpy as np import pandas as pd import retrieveHECData from sklearn.svm import SVC from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifi...
Python
zaydzuhri_stack_edu_python
import palindrome1 function is_palindrome_v2 word begin string (str) -> bool Return True if and only if word is a palindrome. >>> is_palindrome('noon') True >>> is_palindrome('racecar') True >>> is_palindrome('dented') False comment The number of characters in word set n = length word comment Compare the first half of ...
import palindrome1 def is_palindrome_v2(word): """(str) -> bool Return True if and only if word is a palindrome. >>> is_palindrome('noon') True >>> is_palindrome('racecar') True >>> is_palindrome('dented') False """ # The number of characters in word n = l...
Python
zaydzuhri_stack_edu_python
function _kill_process self pid cgroups=none sig=SIGKILL begin string Try to send signal to given process, either directly of with sudo. Because we cannot send signals to the sudo process itself, this method checks whether the target is the sudo process and redirects the signal to sudo's child in this case. if _user is...
def _kill_process(self, pid, cgroups=None, sig=signal.SIGKILL): """ Try to send signal to given process, either directly of with sudo. Because we cannot send signals to the sudo process itself, this method checks whether the target is the sudo process and redirects the signal to ...
Python
jtatman_500k
function cast obj begin return call itkConnectedComponentImageFilterIUC3IUS3_cast obj end function
def cast(obj: 'itkLightObject') -> "itkConnectedComponentImageFilterIUC3IUS3 *": return _itkConnectedComponentImageFilterPython.itkConnectedComponentImageFilterIUC3IUS3_cast(obj)
Python
nomic_cornstack_python_v1
function GrowInstanceDisk r instance disk amount wait_for_sync=false begin string Grows a disk of an instance. More details for parameters can be found in the RAPI documentation. @type instance: string @param instance: Instance name @type disk: integer @param disk: Disk index @type amount: integer @param amount: Grow d...
def GrowInstanceDisk(r, instance, disk, amount, wait_for_sync=False): """ Grows a disk of an instance. More details for parameters can be found in the RAPI documentation. @type instance: string @param instance: Instance name @type disk: integer @param disk: Disk index @type amount: int...
Python
jtatman_500k
import sys import re function main begin comment Read file set file_name = argv at 1 set List = list set done = false with open file_name string r as file begin while not done begin set string = string while true begin set line = read line file if not line begin set done = true break end if line == string begin brea...
import sys import re def main(): # Read file file_name = sys.argv[1] List = [] done = False with open(file_name, 'r') as file: while not done: string = "" while True: line = file.readline() if not line: done = True break if line == "\n": ...
Python
zaydzuhri_stack_edu_python
import json import decimal import boto3 set dynamodb = call resource string dynamodb from boto3.dynamodb.conditions import Key comment Helper class to convert a DynamoDB item to JSON. class DecimalEncoder extends JSONEncoder begin function default self o begin if is instance o Decimal begin if o % 1 > 0 begin return de...
import json import decimal import boto3 dynamodb = boto3.resource('dynamodb') from boto3.dynamodb.conditions import Key # Helper class to convert a DynamoDB item to JSON. class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if o % 1 > 0: ...
Python
zaydzuhri_stack_edu_python
for i in range 0 n begin set rounds = list comprehension integer num for num in split call raw_input set total = rounds at 0 + rounds at 2 set a = integer rounds at 1 set b = integer rounds at 3 if a == total and b == total begin continue end if a == total begin set B = B + 1 end if b == total begin set A = A + 1 end e...
for i in range(0, n): rounds = [int(num) for num in raw_input().split()] total = rounds[0] + rounds[2] a = int(rounds[1]) b = int(rounds[3]) if a == total and b == total: continue if a == total: B += 1 if b == total: A += 1
Python
zaydzuhri_stack_edu_python
function get_all_permissions self begin return set execute get_session join join select name name action resource end function
def get_all_permissions(self) -> set[tuple[str, str]]: return set( self.appbuilder.get_session.execute( select(self.action_model.name, self.resource_model.name) .join(self.permission_model.action) .join(self.permission_model.resource) ) ...
Python
nomic_cornstack_python_v1
import select class Loop extends object begin function __init__ self begin set epoll = call epoll set fd_event_callback_dict = dictionary set running = false end function function unregister self fd begin call unregister fd if get fd_event_callback_dict string fd + string + string EPOLLHUP begin del fd_event_callback_...
import select class Loop(object): def __init__(self): self.epoll = select.epoll() self.fd_event_callback_dict = dict() self.running = False def unregister(self, fd): self.epoll.unregister(fd) if self.fd_event_callback_dict.get(str(fd) + " " + str(select.EPOLLHUP)): ...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment ## 读取Iris数据集细节资料 comment In[1]: comment 从sklearn.datasets导入iris数据集 from sklearn.datasets import load_iris comment In[2]: set iris = call load_iris shape comment In[4]: print DESCR comment ## 对Iris数据集进行分割 comment In[5]: from sklearn.cross_validation import train_test_split comment 使用train_t...
# coding: utf-8 # ## 读取Iris数据集细节资料 # In[1]: # 从sklearn.datasets导入iris数据集 from sklearn.datasets import load_iris # In[2]: iris = load_iris() iris.data.shape # In[4]: print(iris.DESCR) # ## 对Iris数据集进行分割 # In[5]: from sklearn.cross_validation import train_test_split # 使用train_test_split,利用随即种子random_state采样2...
Python
zaydzuhri_stack_edu_python
function update_user_collection_pending args begin call is_parameter_exists list ID args set collection_id = integer args at ID set request_user = args at USER comment Check CollectionUser try begin set collection_user = get objects collection_id=collection_id user_id=id end except ObjectDoesNotExist begin raise call A...
def update_user_collection_pending(args): is_parameter_exists([ constants.ID ], args) collection_id = int(args[constants.ID]) request_user = args[constants.USER] # Check CollectionUser try: collection_user = CollectionUser.objects.get(collection_id=collection_id, user_id=reque...
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt comment loading tips dataset set tips = call load_dataset string tips comment let's called two variable form our dataset through a bar plot for we called seaborn's barllet method comment sns.barplot(x="day",y="tip",data=tips) c...
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt #loading tips dataset tips = sns.load_dataset('tips') #let's called two variable form our dataset through a bar plot for we called seaborn's barllet method #sns.barplot(x="day",y="tip",data=tips) #plt.show() #let's plot bar ...
Python
zaydzuhri_stack_edu_python
import math set angle_elev = 3.8 set shadow_len = 17.5 set tree_height = 0.0 set tree_height = tan angle_elev * shadow_len print string Tree height: tree_height
import math angle_elev = 3.8 shadow_len = 17.5 tree_height = 0.0 tree_height = math.tan(angle_elev) * shadow_len print('Tree height:', tree_height)
Python
zaydzuhri_stack_edu_python
string #sayfa basinda güncelleme with open("newfile.txt","r+",encoding="utf-8") as file: file.write("YENI EKLEME") with open("newfile.txt","r+",encoding="utf-8") as file: print(file.read()) comment sayfa sonuna güncelleme string with open("newfile.txt","a", encoding="utf-8") as file: file.write(" Sercan Celenk") with o...
""" #sayfa basinda güncelleme with open("newfile.txt","r+",encoding="utf-8") as file: file.write("YENI EKLEME") with open("newfile.txt","r+",encoding="utf-8") as file: print(file.read()) """ #sayfa sonuna güncelleme """ with open("newfile.txt","a", encoding="utf-8") as file: file.write("...
Python
zaydzuhri_stack_edu_python
function check_num_arguments num_arguments_expected program_usage begin if length argv > num_arguments_expected begin tuple print ? stderr string Expected fewer arguments. tuple print ? stderr program_usage exit E2BIG end if length argv < num_arguments_expected begin tuple print ? stderr string Expected more arguments....
def check_num_arguments(num_arguments_expected, program_usage): if len(sys.argv) > num_arguments_expected: print >> sys.stderr, "Expected fewer arguments." print >> sys.stderr, program_usage sys.exit(errno.E2BIG) if len(sys.argv) < num_arguments_expected: print >> sys.stderr, "E...
Python
nomic_cornstack_python_v1
string 주소: https://www.hackerrank.com/challenges/drawing-book/problem 내용 - 첫장이 0-1 페이지로 구성된 책이 있다 - 이 책의 페이지수와 찾으려고 하는 페이지가 주어진다 - 책을 맨 앞에서 뒤로 넘기거나, 맨 뒤에서 앞으로 넘겨서 찾으려고 하는 페이지까지 도달하는데 걸리는 페이지 넘김 횟수를 구하라 예제 Sample Input 0 6 2 Sample Output 0 1 Sample Input 1 5 4 Sample Output 1 0 풀이방법 - 단순 구현이니 생략 comment !/bin/python3 i...
""" 주소: https://www.hackerrank.com/challenges/drawing-book/problem 내용 - 첫장이 0-1 페이지로 구성된 책이 있다 - 이 책의 페이지수와 찾으려고 하는 페이지가 주어진다 - 책을 맨 앞에서 뒤로 넘기거나, 맨 뒤에서 앞으로 넘겨서 찾으려고 하는 페이지까지 도달하는데 걸리는 페이지 넘김 횟수를 구하라 예제 Sample Input 0 6 2 Sample Output 0 1 Sample Input 1 5 4 Sample Output 1 0 풀이방법 - 단순 구현이니 생략 """ #!/bin/python3 ...
Python
zaydzuhri_stack_edu_python
function segmentsFromLabels analyzer labels begin set segments = list set offset = 0 for tuple ftype flen in labels begin append segments call TypedSegment analyzer offset flen ftype set offset = offset + flen end return tuple segments end function
def segmentsFromLabels(analyzer, labels) -> Tuple[TypedSegment]: segments = list() offset = 0 for ftype, flen in labels: segments.append(TypedSegment(analyzer, offset, flen, ftype)) offset += flen return tuple(segments)
Python
nomic_cornstack_python_v1
function is_cgc self begin return target_os == string cgc end function
def is_cgc(self): return self.target.target_os == 'cgc'
Python
nomic_cornstack_python_v1
from collections import defaultdict function subset arr s begin comment Using defaultdict to increase value of each element in arr and don't need to check the exist of element in dict set hashtable = default dictionary int set result = 0 for ele in arr begin if s - ele in hashtable and hashtable at s - ele > 0 begin se...
from collections import defaultdict def subset(arr, s): # Using defaultdict to increase value of each element in arr and don't need to check the exist of element in dict hashtable = defaultdict(int) result = 0 for ele in arr: if (s - ele) in hashtable and hashtable[s-ele] > 0: resul...
Python
zaydzuhri_stack_edu_python
function Y_ell_m_ell ell m_ell begin from sympy.functions.special.spherical_harmonics import Ynm set tuple theta phi = tuple call Symbol string theta real=true call Symbol string phi real=true comment return sp.FU['TR8'](Ynm(ell, m_ell, theta, phi).expand(func=True)) comment return Ynm(ell, m_ell, theta, phi) return ca...
def Y_ell_m_ell(ell: int, m_ell: int): from sympy.functions.special.spherical_harmonics import Ynm theta, phi = sp.Symbol("theta", real=True), sp.Symbol("phi", real=True) # return sp.FU['TR8'](Ynm(ell, m_ell, theta, phi).expand(func=True)) # return Ynm(ell, m_ell, theta, phi) ret...
Python
nomic_cornstack_python_v1
comment implementation of the Stack ADT using list class Stack begin comment creates empty stack function __init__ self begin set _theItems = list end function comment Returns true if the stack is empty function isEmpty self begin return length self == 0 end function comment returns the no of items in the stack functio...
#implementation of the Stack ADT using list class Stack: #creates empty stack def __init__(self): self._theItems = list() #Returns true if the stack is empty def isEmpty(self): return len(self) == 0 #returns the no of items in the stack def __len__(self): return len(sel...
Python
zaydzuhri_stack_edu_python
import pickle import random import socket import sys set server_socket = none set client_socket = none set game_end = false set board = none set target_row = 0 set target_col = 0 set hit_last_round = false function get_port begin set port = none if length argv == 1 begin print string Por favor passe a Porta como argume...
import pickle import random import socket import sys server_socket = None client_socket = None game_end = False board = None target_row = 0 target_col = 0 hit_last_round = False def get_port(): port = None if len(sys.argv) == 1: print("Por favor passe a Porta como argumento") exit() elif ...
Python
zaydzuhri_stack_edu_python
import cv2 import copy from collections import deque set lista_1 = deque set numero = 0 set com_furo = 0 function floodfill pixel valor begin global lista_1 im_2 set troca = im_2 at tuple pixel at 0 pixel at 1 append lista_1 pixel set im_2 at tuple pixel at 0 pixel at 1 = valor while not length lista_1 == 0 begin set e...
import cv2 import copy from collections import deque lista_1 = deque() numero = 0 com_furo = 0 def floodfill(pixel,valor): global lista_1, im_2 troca = im_2[pixel[0],pixel[1]] lista_1.append(pixel) im_2[pixel[0],pixel[1]] = valor while not len(lista_1) == 0: elemento = lista_1.pop() ...
Python
zaydzuhri_stack_edu_python
comment Map sources comment SRTM: American mission that released the 90m-30m (3-1 arcsec) DEM (digital elevation model) comment after an interferometric Shuttle mission (STS-99). originally comment 1 arcsec only for USA, now also for the world. Data is available comment through USGS (US geological survey). Only 56 S - ...
# Map sources # SRTM: American mission that released the 90m-30m (3-1 arcsec) DEM (digital elevation model) # after an interferometric Shuttle mission (STS-99). originally # 1 arcsec only for USA, now also for the world. Data is available # through USGS (US geological survey). Only 56 S - 60 N is included # Format: .h...
Python
zaydzuhri_stack_edu_python
import glob import logging import math import os from dataclasses import dataclass import numpy as np import yaml from PIL import Image set log = call getLogger __name__ decorator call dataclass class DataBlock begin comment Sometimes referred to as "Xraw" set images_raw : ndarray set images : ndarray comment Sometimes...
import glob import logging import math import os from dataclasses import dataclass import numpy as np import yaml from PIL import Image log = logging.getLogger(__name__) @dataclass() class DataBlock: images_raw: np.ndarray # Sometimes referred to as "Xraw" images: np.ndarray labels_raw: np.ndarray # S...
Python
zaydzuhri_stack_edu_python
class ConnectFourBoard begin string Game board class for Connect Four function __init__ self row=6 col=7 begin if row <= 0 or col <= 0 begin raise call ValueError format string Invalid row {} or col {} row col end set tuple row col = tuple row col set board = list comprehension list comprehension string * for _ in rang...
class ConnectFourBoard(): """ Game board class for Connect Four """ def __init__(self, row=6, col=7): if row <=0 or col <= 0: raise ValueError("Invalid row {} or col {}".format(row, col)) self.row, self.col = row, col self.board = [['*' for _ in range(col)] for _ in r...
Python
zaydzuhri_stack_edu_python
class Person begin function get_age self begin return get attribute self string _age end function function set_age self value begin if not is instance value int begin raise call ValueError string age must be integer end if value < 0 begin raise call ValueError string age must be positive number end set _age = value end...
class Person: def get_age(self): return getattr(self, '_age') def set_age(self, value): if not isinstance(value, int): raise ValueError('age must be integer') if value < 0: raise ValueError('age must be positive number') self._age = value age = prop...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri Mar 19 23:13:36 2021 @author: Konstantinos import random import tkinter as tk class Window extends Frame begin function __init__ self parent begin call __init__ self parent set parent = parent comment The final password set password = call StringVar set string Here sh...
# -*- coding: utf-8 -*- """ Created on Fri Mar 19 23:13:36 2021 @author: Konstantinos """ import random import tkinter as tk class Window(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.parent = parent # The final password self.pas...
Python
zaydzuhri_stack_edu_python
string 字符串轮转。给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottle是erbottlewat旋转后的字符串)。 示例1: 输入:s1 = "waterbottle", s2 = "erbottlewat" 输出:True 示例2: 输入:s1 = "aa", s2 = "aba" 输出:False 提示: 字符串长度在[0, 100000]范围内。 说明: 你能只调用一次检查子串的方法吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/string-rotation-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商...
""" 字符串轮转。给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottle是erbottlewat旋转后的字符串)。 示例1: 输入:s1 = "waterbottle", s2 = "erbottlewat" 输出:True 示例2: 输入:s1 = "aa", s2 = "aba" 输出:False 提示: 字符串长度在[0, 100000]范围内。 说明: 你能只调用一次检查子串的方法吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/string-rotation-lcci 著作权归领扣网络所有。商业转载请联系...
Python
zaydzuhri_stack_edu_python
comment !usr/bin/python string Exercise 1 http://greenteapress.com/thinkpython2/html/thinkpython2006.html The time module provides a function, also named time, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970....
#!usr/bin/python """ Exercise 1 http://greenteapress.com/thinkpython2/html/thinkpython2006.html The time module provides a function, also named time, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970. >impo...
Python
zaydzuhri_stack_edu_python
import time import os import sys import math function IMU_movement rec_data direction stride begin comment rec_data[0] is turns: 0 -> no turn, 1 ->right, -1 ->left comment rec_data[1] is # of steps taken comment movement[0]: time comment movements[1] = change on x-axis comment movements[2] = change on y-axis set turn =...
import time import os import sys import math def IMU_movement(rec_data, direction, stride): # rec_data[0] is turns: 0 -> no turn, 1 ->right, -1 ->left # rec_data[1] is # of steps taken #movement[0]: time # movements[1] = change on x-axis # movements[2] = change on y-axis turn = rec_data[0] num_steps = rec_da...
Python
zaydzuhri_stack_edu_python
function testRounding self begin set magctrler = call obtain_device call reset set chanctrler = channels at channel_to_test set virt_iout = call Quantity string 20.19 G call eq_ virt_iout call Quantity string 20 G end function
def testRounding(self): magctrler = self.obtain_device() magctrler.reset() chanctrler = magctrler.channels[self.channel_to_test] chanctrler.virt_iout = Quantity('20.19 G') eq_(chanctrler.virt_iout, Quantity('20 G'))
Python
nomic_cornstack_python_v1
function compute_state_trans_cube rg state2int obs2int n_obs n_states begin set cube = zeros tuple n_obs n_states n_states for in_state in states begin set in_state_ind = state2int at name for tran in outgoing begin set obs_ind = obs2int at name set out_state_ind = state2int at name set cube at tuple obs_ind in_state_i...
def compute_state_trans_cube(rg, state2int, obs2int, n_obs, n_states): cube = np.zeros((n_obs, n_states, n_states)) for in_state in rg.states: in_state_ind = state2int[in_state.name] for tran in in_state.outgoing: obs_ind = obs2int[tran.name] out_state_ind = state2i...
Python
nomic_cornstack_python_v1
comment Rock Paper Scissors import random set choice = input string What weapon do you choose? Type 0 for rock, 1 for scissors, and 2 for paper. set computer = list string rock string paper string scissors set comchoice = random choice computer if choice == string 0 and comchoice == string rock begin print string _____...
# Rock Paper Scissors import random choice = input ("What weapon do you choose? Type 0 for rock, 1 for scissors, and 2 for paper. ") computer = ["rock", "paper", "scissors"] comchoice = random.choice(computer) if choice == "0" and comchoice == "rock": print (''' ______ /( )\ \ \ / / \/[]\/ /\ ...
Python
zaydzuhri_stack_edu_python
function dequeue self begin if call is_empty begin return none end else begin set event = deep copy trace_queue at 0 remove trace_queue event return event end end function
def dequeue(self): if self.is_empty(): return None else: event = deepcopy(self.trace_queue[0]) self.trace_queue.remove(event) return event
Python
nomic_cornstack_python_v1
import os import numpy as np import tensorflow as tf function get_file file_dir begin string :param file_dir: 文件保存路径 :return: 文件名, label set cats = list set label_cats = list set dogs = list set label_dogs = list for file in list directory file_dir begin set name = split file sep=string . if name at 0 == string cat...
import os import numpy as np import tensorflow as tf def get_file(file_dir): ''' :param file_dir: 文件保存路径 :return: 文件名, label ''' cats = [] label_cats = [] dogs = [] label_dogs = [] for file in os.listdir(file_dir): name = file.split(sep='.') if name[0] == 'cat': ...
Python
zaydzuhri_stack_edu_python
function run self **kwargs begin call export_to_xml comment Setting tstart here ensures we don't pick up any pre-existing statepoint comment files in the output directory set tstart = time set last_statepoint = none run keyword kwargs comment Get output directory and return the last statepoint written by this run if ou...
def run(self, **kwargs): self.export_to_xml() # Setting tstart here ensures we don't pick up any pre-existing statepoint # files in the output directory tstart = time.time() last_statepoint = None openmc.run(**kwargs) # Get output directory and return the last...
Python
nomic_cornstack_python_v1
function compute_shotgun_pooling_values_qpcr_minvol sample_concs sample_fracs=none floor_vol=100 floor_conc=40 total_nmol=0.01 begin if sample_fracs is none begin set sample_fracs = ones shape / size end comment calculate volumetric fractions including floor val set sample_vols = total_nmol * sample_fracs / sample_conc...
def compute_shotgun_pooling_values_qpcr_minvol(sample_concs, sample_fracs=None, floor_vol=100, floor_conc=40, total_nmol=.01): if sample_fracs is None: sample_fracs = np.ones(sample_concs.shape) / sample_concs.size # c...
Python
nomic_cornstack_python_v1
from math import * set a = 10 set b = 5 set c = 2 set dodawanie = a + b set mnozenie = a * c set dzielenie = a / b set dzielenie_calkowite = b // c set potega = c ^ b print dodawanie print mnozenie dzielenie print dzielenie print dzielenie_calkowite print potega print power 8 2 set a = a + c print a print square root 2...
from math import * a = 10 b = 5 c = 2 dodawanie = a + b mnozenie = a * c dzielenie = a/b dzielenie_calkowite = b // c potega = c ** b print(dodawanie) print(mnozenie, dzielenie) print(dzielenie) print(dzielenie_calkowite) print(potega) print(pow(8, 2)) a += c print(a) print(sqrt(2)) print(pi) print (u'inżynieria s...
Python
zaydzuhri_stack_edu_python
function l1 x1 x2 begin return absolute x1 - x2 end function
def l1(x1, x2): return np.abs(x1 - x2)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import tornado.ioloop import tornado.web import tornado.websocket import tornado.httpserver class MainHandler extends RequestHandler begin decorator asynchronous function get self begin call render string default.html end function end class class WebSocketHandler extends WebSocketHandler be...
#!/usr/bin/env python import tornado.ioloop import tornado.web import tornado.websocket import tornado.httpserver class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): self.render("default.html") class WebSocketHandler(tornado.websocket.WebSocketHandler): waiters...
Python
zaydzuhri_stack_edu_python
function deleteFront self begin if call isEmpty begin return false end set first_idx = first_idx + 1 set size = size - 1 if first_idx == MAX_SIZE begin set first_idx = first_idx - MAX_SIZE end return true end function
def deleteFront(self) -> bool: if self.isEmpty(): return False self.first_idx += 1 self.size -= 1 if self.first_idx == self.MAX_SIZE: self.first_idx -= self.MAX_SIZE return True
Python
nomic_cornstack_python_v1
function determine_win self begin if radiant_win is true and player_slot < 5 begin return true end if radiant_win is false and player_slot > 5 begin return true end return false end function
def determine_win(self): if self.match.radiant_win is True and self.player_slot < 5: return True if self.match.radiant_win is False and self.player_slot > 5: return True return False
Python
nomic_cornstack_python_v1