code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function create_connection self alias=string default **kwargs begin string Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias. set default kwargs string serializer serializer set conn = call Elasticsearch keyword kwargs set _conns at alias = call Elasticsearch keyword kwargs retu...
def create_connection(self, alias='default', **kwargs): """ Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias. """ kwargs.setdefault('serializer', serializer) conn = self._conns[alias] = Elasticsearch(**kwargs) return conn
Python
jtatman_500k
function _enable_os_kit_component self kit comp_name comp_version software_profile begin return call _add_component_to_software_profile kit comp_name comp_version software_profile end function
def _enable_os_kit_component(self, kit, comp_name, comp_version, software_profile): return self._add_component_to_software_profile( kit, comp_name, comp_version, software_profile)
Python
nomic_cornstack_python_v1
comment re.match # 从第0位开始匹配字符串,匹配完成立刻结束,会忽略. 相当于匹配开头 comment re.search # 搜索整个字符串进行匹配, 相当于匹配包含 comment re.findall # 检索整个字符串进行匹配,返回一个列表 import re set result = match string \d[a-z] string ......3d comment None 从第0位开始匹配,一旦失败立刻返回None print result comment 搜索匹配 set result = search string \d[a-z] string .....3d comment <re.Mat...
# re.match # 从第0位开始匹配字符串,匹配完成立刻结束,会忽略. 相当于匹配开头 # re.search # 搜索整个字符串进行匹配, 相当于匹配包含 # re.findall # 检索整个字符串进行匹配,返回一个列表 import re result = re.match(r"\d[a-z]","......3d") print(result) # None 从第0位开始匹配,一旦失败立刻返回None result = re.search(r"\d[a-z]",".....3d") # 搜索匹配 print...
Python
zaydzuhri_stack_edu_python
function start_unstarted_cycles begin set workflows = call _get_unstarted_workflows for workflow in workflows begin set tasks_start_days = list comprehension relative_start_day for tg in task_groups for task in task_group_tasks set tasks_end_days = list comprehension relative_end_day for tg in task_groups for task in t...
def start_unstarted_cycles(): workflows = _get_unstarted_workflows() for workflow in workflows: tasks_start_days = [task.relative_start_day for tg in workflow.task_groups for task in tg.task_group_tasks] tasks_end_days = [task.relative_end_day ...
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math import os import random import re import sys from collections import defaultdict comment Complete the minimumSwaps function below. string https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arra...
#!/bin/python3 import math import os import random import re import sys from collections import defaultdict # Complete the minimumSwaps function below. """ https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays You are ...
Python
zaydzuhri_stack_edu_python
function inradius P x begin if not call contains x begin return call NotImplementedError string The polytope should contain x. end set tuple A a B b C c D d = call dual_representation P set l = call nrows return min generator expression call row j * call vector x + b at j for j in range l end function
def inradius(P, x): if not (P.contains(x)): return NotImplementedError("The polytope should contain x.") (A, a, B, b, C, c, D, d) = dual_representation(P) l = D.nrows() return min(B.row(j)*vector(x)+b[j] for j in range(l))
Python
nomic_cornstack_python_v1
function to_str self begin return call pformat call to_dict end function
def to_str(self): return pprint.pformat(self.to_dict())
Python
nomic_cornstack_python_v1
function __init__ self sigma dim begin set sigma = sigma set dim = dim call __init__ ksize=integer sigma * 8 + 1 end function
def __init__(self, sigma, dim): self.sigma = sigma self.dim = dim super().__init__(ksize=int(sigma*8 + 1))
Python
nomic_cornstack_python_v1
function on_post self req resp begin set password = string body at string password set tuple error account_addr private_key keystore = call create_account password if error is none begin set message = dict string success true ; string account_addr account_addr ; string private_key private_key ; string keystore dumps ke...
def on_post(self, req, resp): password = str(req.body['password']) error, account_addr, private_key, keystore = eth_helper.create_account(password) if error is None: message = { 'success': True, 'account_addr': account_addr, 'private_...
Python
nomic_cornstack_python_v1
comment get_ipython().run_line_magic('matplotlib', 'inline') comment from matplotlib import style comment style.use('fivethirtyeight') comment import matplotlib.pyplot as plt import numpy as np import pandas as pd import datetime as dt import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.or...
# get_ipython().run_line_magic('matplotlib', 'inline') # from matplotlib import style # style.use('fivethirtyeight') # import matplotlib.pyplot as plt import numpy as np import pandas as pd import datetime as dt import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from s...
Python
zaydzuhri_stack_edu_python
for i in my_list begin print i type i end
for i in my_list: print(i, type(i))
Python
zaydzuhri_stack_edu_python
function say_good_morning greeting begin set name = get greeting string name set to = get greeting string to comment If a 'broadcast' message is received, emit it back out w/ the 'broadcast' flag to True comment This will emit to ALL rooms if to == EVERYONE begin call emit string broadcast dict string name name broadca...
def say_good_morning(greeting): name = greeting.get("name") to = greeting.get("to") # If a 'broadcast' message is received, emit it back out w/ the 'broadcast' flag to True # This will emit to ALL rooms if to == EVERYONE: socketio.emit("broadcast", {"name": name}, broadcast=True) else: ...
Python
nomic_cornstack_python_v1
import os , sys import json import pprint , urllib from pull_article_by_pmid import pull_article_by_id function search_by_author author_name=string R result_dir=string losick_pubs return_max=300 begin if not is directory path result_dir begin make directories result_dir end comment parameters for pulling this pubmed ar...
import os, sys import json import pprint, urllib from pull_article_by_pmid import pull_article_by_id def search_by_author(author_name=" R", result_dir='losick_pubs', return_max=300): if not os.path.isdir(result_dir): os.makedirs(result_dir) # parameters for pulling this pubmed article in JSON format ...
Python
zaydzuhri_stack_edu_python
string This is the fifth set of exercises used in the class. This class is somewhat different. You will create two files. First, you will create a class which implements vectors. Second, you will create unittests. unittests establish whether the class works properly or not. Below you find a skeleton for the code. At th...
""" This is the fifth set of exercises used in the class. This class is somewhat different. You will create two files. First, you will create a class which implements vectors. Second, you will create unittests. unittests establish whether the class works properly or not. Below you find a skeleton for the code. At the...
Python
zaydzuhri_stack_edu_python
from sklearn.datasets import make_blobs from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from mglearn import cm2 comment 构造数据 set tuple X _ = call make_blobs n_samples=50 centers=5 random_state=4 cluster_std=2 comment 将其分为训练集和测试集 set tuple X_train X_test = train test split X random_s...
from sklearn.datasets import make_blobs from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from mglearn import cm2 # 构造数据 X,_ = make_blobs(n_samples=50,centers=5,random_state=4,cluster_std=2) # 将其分为训练集和测试集 X_train,X_test=train_test_split(X,random_state=1,test_size=0.1) # 绘制训练集和测试集 fi...
Python
zaydzuhri_stack_edu_python
comment max = 40 set evenTotal = 2 comment print last comment print val while val <= max begin set tmpLast = val set val = val + last set last = tmpLast if val > max begin break end else comment print val if val % 2 == 0 begin comment print val set evenTotal = evenTotal + val end end
# max = 40 evenTotal = 2 # print last # print val while val <= max: tmpLast = val val = val + last last = tmpLast if val > max: break else: # print val if (val % 2 == 0): # print val evenTotal = evenTotal + val
Python
zaydzuhri_stack_edu_python
function load_modelnet40 partition begin return call _load_modelnet string modelnet40 partition end function
def load_modelnet40(partition): return _load_modelnet('modelnet40', partition)
Python
nomic_cornstack_python_v1
function user_command_change_nick self args begin set tuple mess room nick = list string * 3 set tuple command s args = call partition string comment Parsing args if lower command != string nick begin set mess = string What must I change? end else begin set args = strip args string if args and args at 0 in list string...
def user_command_change_nick(self, args): mess, room, nick = ['']*3 command, s, args = args.partition(' ') # Parsing args if command.lower() != 'nick': mess = 'What must I change?' else: args = args.strip(' ') if args and args[0] in ['"', "'"]:...
Python
nomic_cornstack_python_v1
comment 对处理后的新文件进行插值 comment 3-9 列直接进行插值 12列 H 对字母后的数字进行插值 并将H添加回去 comment 2,10,11,13列 同一值 comment 定义插值函数 from scipy import interpolate import numpy as np comment 对数据进行插值 data为进行插值的数据 list function interpolation data n begin set x = linear space 0 length data - 1 length data comment 数据扩充为10倍 linspace(start,stop,numbers...
# 对处理后的新文件进行插值 # 3-9 列直接进行插值 12列 H 对字母后的数字进行插值 并将H添加回去 # 2,10,11,13列 同一值 # 定义插值函数 from scipy import interpolate import numpy as np # 对数据进行插值 data为进行插值的数据 list def interpolation(data,n): x = np.linspace(0,len(data)-1,len(data)) # 数据扩充为10倍 linspace(start,stop,numbers) x_new = np.linspace(0,len(data)-1,n*len...
Python
zaydzuhri_stack_edu_python
import numpy as np from random import randint function displayNumericResults c p d i begin set result = zeros tuple c 2 dtype=float for j in range c begin set a = string j set result at j at 0 = j set result at j at 1 = p at i at d at a end return result at call argsort at slice : : - 1 end function comment see predi...
import numpy as np from random import randint def displayNumericResults(c, p, d, i): result = np.zeros((c, 2), dtype = float) for j in range(c): a = str(j) result[j][0] = j result[j][1] = p[i][d[a]] return (result[result[:, 1].argsort()])[::-1] # see pred...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup as bs import requests import urllib.request import os function get_imgs site begin set source = text set soup = call bs source string lxml set urls = list comprehension string url at string src for url in find all string img if string .jpg in string site + url at string src or string .png ...
from bs4 import BeautifulSoup as bs import requests import urllib.request import os def get_imgs(site): source = requests.get(site).text soup = bs(source, "lxml") urls = [str(url["src"]) for url in soup.findAll("img") if ".jpg" in str(site+url["src"]) or ".png" in str(site+url["src"])] ret...
Python
zaydzuhri_stack_edu_python
import numpy set arr = array split input float set n = integer input print call polyval arr n
import numpy arr = numpy.array(input().split(), float) n = int(input()) print(numpy.polyval(arr, n))
Python
zaydzuhri_stack_edu_python
from operator import attrgetter , itemgetter class Teacher begin function __init__ self name salary age begin set name = name set age = age set salary = salary end function function __repr__ self begin return call repr tuple name age salary end function end class set teachers = list call Teacher string A 1200 30 call T...
from operator import attrgetter, itemgetter class Teacher(): def __init__(self, name, salary, age): self.name = name self.age = age self.salary = salary def __repr__(self): return repr((self.name,self.age,self.salary)) teachers = [Teacher("A",1200,30),Teacher("B",120...
Python
zaydzuhri_stack_edu_python
function full_path self begin set path = file_path if _relative_path begin set path = join path path _relative_path end return path end function
def full_path(self): path = self.file_path if self._relative_path: path = os.path.join(path, self._relative_path) return path
Python
nomic_cornstack_python_v1
string This program prompts the user to pick a number, enter their name, and then generates a password the length of the chosen number from letters in their name. import random print string Let's make a random password together! set user_selected_number = input string Pick any two digit number. This will determine how ...
''' This program prompts the user to pick a number, enter their name, and then generates a password the length of the chosen number from letters in their name. ''' import random print("Let's make a random password together!") user_selected_number = input("Pick any two digit number. This will determine how many charac...
Python
zaydzuhri_stack_edu_python
function get_partition_table_type self begin set process = popen list string parted string -s device string print stdout=PIPE set tuple output error = communicate process set exit_code = returncode if exit_code != 0 begin raise call DeviceError device string Non-zero exit code string error string utf-8 end set result =...
def get_partition_table_type(self): process = subprocess.Popen(["parted", "-s", self.device, "print"], stdout=subprocess.PIPE) output, error = process.communicate() exit_code = process.returncode if exit_code != 0: raise weresync.exception.DeviceError(self.device, "Non-zero ...
Python
nomic_cornstack_python_v1
comment Author: Alex Gezerlis comment Numerical Methods in Physics with Python (2nd ed., CUP, 2023) comment Solution to chapter 5, problem 25 comment NOTE TO INSTRUCTORS: this solution is made available to all readers (i.e., not locked) from math import sqrt , exp function f x begin comment following line is there for ...
# Author: Alex Gezerlis # Numerical Methods in Physics with Python (2nd ed., CUP, 2023) # Solution to chapter 5, problem 25 # NOTE TO INSTRUCTORS: this solution is made available to all readers (i.e., not locked) from math import sqrt, exp def f(x): # following line is there for development/debugging purposes ...
Python
zaydzuhri_stack_edu_python
function main self frame begin debug string QR/main: Started set codes = list call get_qr_codes frame debug string QR/main: Finished return call draw_qr_codes frame end function
def main(self, frame): self.__logger.debug("QR/main: Started") self.codes = [] self.get_qr_codes(frame) self.__logger.debug("QR/main: Finished") return self.draw_qr_codes(frame)
Python
nomic_cornstack_python_v1
import requests import json import hashlib set isbn = string 9780062380661 set isbn2 = string 9780451474575 set response = get requests format string https://www.googleapis.com/books/v1/volumes?q=isbn:{} isbn set ret = loads text comment parse = json.dumps(ret) comment print(type(parse)) print ret at string items at 0 ...
import requests import json import hashlib isbn = '9780062380661' isbn2 = '9780451474575' response = requests.get('https://www.googleapis.com/books/v1/volumes?q=isbn:{}'.format(isbn)) ret = json.loads(response.text) # parse = json.dumps(ret) # print(type(parse)) print(ret['items'][0]['volumeInfo']['title']) title =...
Python
zaydzuhri_stack_edu_python
function extent self begin set first = next iterate self set minx = reduce lambda v c -> if expression v < x then v else x self x set maxx = reduce lambda v c -> if expression v > x then v else x self x set miny = reduce lambda v c -> if expression v < y then v else y self y set maxy = reduce lambda v c -> if expressio...
def extent(self): first = next(iter(self)) minx = reduce(lambda v, c: v if v < c.x else c.x, self, first.x) maxx = reduce(lambda v, c: v if v > c.x else c.x, self, first.x) miny = reduce(lambda v, c: v if v < c.y else c.y, self, first.y) maxy = reduce(lambda v, c: v if v > c.y el...
Python
nomic_cornstack_python_v1
function load_CIFAR100 batch_dir begin set tuple ims coarse_labels fine_labels = call load_CIFAR_batch batch_dir + string /train set tuple ims_t c_labels f_labels = call load_CIFAR_batch batch_dir + string /test set ims = concatenate tuple ims ims_t set coarse_labels = concatenate tuple coarse_labels c_labels set fine_...
def load_CIFAR100(batch_dir): ims, coarse_labels, fine_labels = load_CIFAR_batch(batch_dir + '/train') ims_t, c_labels, f_labels = load_CIFAR_batch(batch_dir + '/test') ims = np.concatenate((ims, ims_t)) coarse_labels = np.concatenate((coarse_labels, c_labels)) fine_labels = np.concatenate((fin...
Python
nomic_cornstack_python_v1
comment pylint: disable=unused-argument function target_log_prob_fn self *args **kwargs begin comment pylint: disable=unused-argument function log_joint_fn *args **kwargs begin set states = dictionary zip keys unobserved args update states observed set interceptor = call CollectLogProb states with call interception int...
def target_log_prob_fn(self, *args, **kwargs): # pylint: disable=unused-argument def log_joint_fn(*args, **kwargs): # pylint: disable=unused-argument states = dict(zip(self.unobserved.keys(), args)) states.update(self.observed) interceptor = interceptors.CollectLogProb(sta...
Python
nomic_cornstack_python_v1
import os import sys import json import math from autoallocation import AutoAllocation class allocation begin function __init__ self allocation_logic latitude longitude begin set allocation_logic = allocation_logic set latitude = latitude set longitude = longitude call autoallocation_execution end function function aut...
import os import sys import json import math from autoallocation import AutoAllocation class allocation: def __init__(self,allocation_logic,latitude,longitude): self.allocation_logic = allocation_logic self.latitude = latitude self.longitude = longitude self.autoallocation_execution() def autoallocat...
Python
zaydzuhri_stack_edu_python
function __all_penguins self begin set ret = list for p in players begin set ret = ret + call get_penguins end return ret end function
def __all_penguins(self): ret = [] for p in self.players: ret += p.get_penguins() return ret
Python
nomic_cornstack_python_v1
comment noqa: N802 function assertOnPaymentErrorPage self response mock_send_email begin call assertContains response string We are experiencing technical problems call assertContains response upper ref at slice : 8 : call assert_not_called for key in complete_session_keys begin assert not in key session end end funct...
def assertOnPaymentErrorPage(self, response, mock_send_email): # noqa: N802 self.assertContains(response, 'We are experiencing technical problems') self.assertContains(response, self.ref[:8].upper()) mock_send_email.assert_not_called() for key in self.complete_session_keys: ...
Python
nomic_cornstack_python_v1
function format_multiple_files args file_names begin set account_owners = call read_account_owners owners_file for file in file_names begin set input_path = join path input_dir file set output_path = join path output_dir file if reverse find file string . == - 1 begin set output_path = output_path + string .html end el...
def format_multiple_files(args, file_names): account_owners = read_account_owners(args.owners_file) for file in file_names: input_path = os.path.join(args.input_dir, file) output_path = os.path.join(args.output_dir, file) if file.rfind(".") == -1: output_path += ".html" ...
Python
nomic_cornstack_python_v1
function init_memory g nf current_priorities begin return tuple nf tuple list comprehension nodes at nf at i + 1 >= current_priorities at i for i in range call get_nbr_priority_functions end function
def init_memory(g, nf, current_priorities): return (nf, tuple([g.nodes[nf][i + 1] >= current_priorities[i] for i in range(g.get_nbr_priority_functions())]))
Python
nomic_cornstack_python_v1
string Given a list of employees, write the code to extract the second to last employee from the list? Assume that you do not know how long the list initially is. E.g. employees = [“John Smith”, “Frank Jacobs”, “Scott Anderson”, “Mary Smith”, “Jim Bates”] You code should print out : Mary Smith On the output console set...
''' Given a list of employees, write the code to extract the second to last employee from the list? Assume that you do not know how long the list initially is. E.g. employees = [“John Smith”, “Frank Jacobs”, “Scott Anderson”, “Mary Smith”, “Jim Bates”] You code should print out : Mary Smith On the output console '''...
Python
zaydzuhri_stack_edu_python
function author_view self context begin string Display a the studio editor when the user has clicked "View" to see the container view, otherwise just show the normal 'author_preview_view' or 'student_view' preview. set root_xblock = get context string root_xblock if root_xblock and location == location begin comment Us...
def author_view(self, context): """ Display a the studio editor when the user has clicked "View" to see the container view, otherwise just show the normal 'author_preview_view' or 'student_view' preview. """ root_xblock = context.get('root_xblock') if root_xblock and roo...
Python
jtatman_500k
function account_enabled self begin if string accountEnabled in _prop_dict begin return _prop_dict at string accountEnabled end else begin return none end end function
def account_enabled(self): if "accountEnabled" in self._prop_dict: return self._prop_dict["accountEnabled"] else: return None
Python
nomic_cornstack_python_v1
import MySQLdb import time import numpy as np import fastcluster import scipy function cluster_by_ingred cursor ingred metric data_dir=string /Users/amorten/Projects/RecipeSearch/Database/HClusters/ begin set time_before = time set rec_ids = call get_rec_ids_for_ingred cursor ingred save data_dir + metric + string /rec...
import MySQLdb import time import numpy as np import fastcluster import scipy def cluster_by_ingred(cursor,ingred,metric, data_dir="/Users/amorten/Projects/" "RecipeSearch/Database/HClusters/"): time_before = time.time() rec_ids = get_rec_ids_for_ingred(c...
Python
zaydzuhri_stack_edu_python
import socket function http_get url begin comment Extract hostname and path from the URL set tuple hostname path = call extract_hostname_path url comment Create a TCP socket set sock = call socket AF_INET SOCK_STREAM comment Connect to the server using port 80 (default for HTTP) set server_address = tuple hostname 80 c...
import socket def http_get(url): # Extract hostname and path from the URL hostname, path = extract_hostname_path(url) # Create a TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to the server using port 80 (default for HTTP) server_address = (hostname, 80)...
Python
jtatman_500k
function stop_shoot self begin if recording begin call stop_recording end call stop_recording comment Todo: This is disgusting way to merging audio and silent video. Fix this. call merge_audio_and_video end function
def stop_shoot(self): if self.camera.recording: self.camera.stop_recording() self.hearer.stop_recording() # Todo: This is disgusting way to merging audio and silent video. Fix this. self.merge_audio_and_video()
Python
nomic_cornstack_python_v1
function test_profile_transformer deepcopy_mock process_mock begin comment Setup set transformer_mock = call Mock spec_set=NumericalTransformer set dataset_gen_mock = call Mock spec_set=RandomNumericalGenerator set return_value = zeros 100 set return_value = ones 100 set return_value = return_value comment Run set prof...
def test_profile_transformer(deepcopy_mock, process_mock): # Setup transformer_mock = Mock(spec_set=NumericalTransformer) dataset_gen_mock = Mock(spec_set=RandomNumericalGenerator) transformer_mock.return_value.transform.return_value = np.zeros(100) dataset_gen_mock.generate.return_value = np.ones(1...
Python
nomic_cornstack_python_v1
function addPlayer settings begin string define a new PlayerRecord setting and save to disk file call _validate settings set player = call PlayerRecord settings save set call getKnownPlayers at name = player return player end function
def addPlayer(settings): """define a new PlayerRecord setting and save to disk file""" _validate(settings) player = PlayerRecord(settings) player.save() getKnownPlayers()[player.name] = player return player
Python
jtatman_500k
function ensure_chambers begin string Ensures chambers are created set france = get objects name=string France for key in tuple string AN string SEN begin set variant = FranceDataVariants at key call get_or_create name=variant at string chamber abbreviation=variant at string abbreviation country=france end end function
def ensure_chambers(): """ Ensures chambers are created """ france = Country.objects.get(name="France") for key in ('AN', 'SEN'): variant = FranceDataVariants[key] Chamber.objects.get_or_create(name=variant['chamber'], abbreviation=variant['abbre...
Python
jtatman_500k
function test_main driver begin comment Test Parameters comment Auto generated application URL parameter set ApplicationURL = string https://epitest-demo.bloomstack.io/ set ExpectedCust = string set ActualCustNameOnScreen = string set ExpectedCompany = string set ActtualCustOnSave = string set username = string tes...
def test_main(driver): # Test Parameters # Auto generated application URL parameter ApplicationURL = "https://epitest-demo.bloomstack.io/" ExpectedCust = "" ActualCustNameOnScreen = "" ExpectedCompany = "" ActtualCustOnSave = "" username = "testautomationuser@bloomstack.com" pwd = "e...
Python
nomic_cornstack_python_v1
function sitemetricexchange self begin try begin return _sitemetricexchange end except Exception as e begin raise e end end function
def sitemetricexchange(self) : try : return self._sitemetricexchange except Exception as e: raise e
Python
nomic_cornstack_python_v1
function decimal2bin number precision begin assert number > 0 set binary_str = binary integer number set frac = number - integer number for i in range precision begin set frac = frac * 2 set frac_bit = integer frac if frac_bit == 1 begin set frac = frac - frac_bit set binary_str = binary_str + string 1 end else begin s...
def decimal2bin(number, precision): assert number > 0 binary_str = bin(int(number)) frac = number - int(number) for i in range(precision): frac *= 2 frac_bit = int(frac) if frac_bit == 1: frac -= frac_bit binary_str += '...
Python
nomic_cornstack_python_v1
comment Load and prepare CIFAR-10 data. For a detailed description of the CIFAR-10 comment file format, see: https://www.cs.toronto.edu/~kriz/cifar.html import numpy as np set CIFAR_DIRECTORY = string ../data/cifar-10-batches-py/ comment Read a CIFAR-10 dictionary. Amongst others, the dictionary includes a "data" comme...
# Load and prepare CIFAR-10 data. For a detailed description of the CIFAR-10 # file format, see: https://www.cs.toronto.edu/~kriz/cifar.html import numpy as np CIFAR_DIRECTORY = '../data/cifar-10-batches-py/' # Read a CIFAR-10 dictionary. Amongst others, the dictionary includes a "data" # entry and a "labels" entry....
Python
zaydzuhri_stack_edu_python
string Except for one test, this file tests with auto-creation of topics disabled, as it is more rigorous for testing purposes. :copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved. :license: BSD, see LICENSE.txt for details. import gc import pytest import pubsub.core.topicargspec from pubsub impo...
""" Except for one test, this file tests with auto-creation of topics disabled, as it is more rigorous for testing purposes. :copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved. :license: BSD, see LICENSE.txt for details. """ import gc import pytest import pubsub.core.topicargspec from pubsu...
Python
zaydzuhri_stack_edu_python
function enable_onnx_compatible_models self begin return get pulumi self string enable_onnx_compatible_models end function
def enable_onnx_compatible_models(self) -> Optional[bool]: return pulumi.get(self, "enable_onnx_compatible_models")
Python
nomic_cornstack_python_v1
function test_fma_nan_param_nanarray_nannum_ninfnum_none_a_183 self begin comment This version is expected to pass. call fma okarrayx oknumy oknumz matherrors=true comment This should raise an error. with assert raises ArithmeticError begin call fma nanarrayx nannumy ninfnumz end end function
def test_fma_nan_param_nanarray_nannum_ninfnum_none_a_183(self): # This version is expected to pass. arrayfunc.fma(self.okarrayx, self.oknumy, self.oknumz, matherrors=True) # This should raise an error. with self.assertRaises(ArithmeticError): arrayfunc.fma(self.nanarrayx, self.nannumy, self.ninfnumz)
Python
nomic_cornstack_python_v1
from typing import Tuple import pandas as pd import numpy as np from pandas.core.frame import DataFrame class MarketDataProvider begin set assets : array set data : DataFrame set min_fill_time : int function __init__ self merged_csv_path begin comment Load in CSV and convert time to DatetimeIndex set expected_dtypes = ...
from typing import Tuple import pandas as pd import numpy as np from pandas.core.frame import DataFrame class MarketDataProvider: assets: np.array data: DataFrame min_fill_time: int def __init__(self, merged_csv_path: str) -> None: # Load in CSV and convert time to DatetimeIndex expec...
Python
zaydzuhri_stack_edu_python
function is_integrity_error cls exception begin return is instance exception IntegrityError end function
def is_integrity_error(cls, exception): return isinstance(exception, IntegrityError)
Python
nomic_cornstack_python_v1
if hoge begin set fuga = pop hoge print fuga end print hoge
if hoge : fuga = hoge.pop() print(fuga) print(hoge)
Python
zaydzuhri_stack_edu_python
comment This module should work as a template whenever there are or not students import tkinter as tk import Cruz_Elian_Practica_12_styles as st from PIL import ImageTk , Image from Cruz_Elian_Practica_12_studentDataTemplate import * from Cruz_Elian_Practica_12_AddStudent import * from addFolder import * set mainRoot =...
#This module should work as a template whenever there are or not students import tkinter as tk import Cruz_Elian_Practica_12_styles as st from PIL import ImageTk, Image from Cruz_Elian_Practica_12_studentDataTemplate import * from Cruz_Elian_Practica_12_AddStudent import * from addFolder import * mainRoot=None mainC...
Python
zaydzuhri_stack_edu_python
import cv2 from pyzbar import pyzbar import json import requests import time async function postRequestAPI url body begin return await post url data=body end function function read_barcodes frame begin set barcodes = decode pyzbar frame set url = string http://localhost:8000/item for barcode in barcodes begin set tuple...
import cv2 from pyzbar import pyzbar import json import requests import time async def postRequestAPI(url, body) : return await requests.post(url, data=body) def read_barcodes(frame): barcodes = pyzbar.decode(frame) url = 'http://localhost:8000/item' for barcode in barcodes: x, y...
Python
zaydzuhri_stack_edu_python
function add_tags_to_bookmark self bookmark_id tags begin string Add tags to to a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. :param tags: Comma separated tags to be applied. set url = call _generate_url format string bookmarks/{0}/tags bookmark_i...
def add_tags_to_bookmark(self, bookmark_id, tags): """ Add tags to to a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. :param tags: Comma separated tags to be applied. """ url = self._generate...
Python
jtatman_500k
function _failed_tests self metric_source_id begin return call __test_count metric_source_id string fail end function
def _failed_tests(self, metric_source_id: str) -> int: return self.__test_count(metric_source_id, "fail")
Python
nomic_cornstack_python_v1
if __name__ == string __main__ begin while 1 begin set user_number = input string Choose a number: if is digit user_number begin set user_number = integer user_number break end else begin print format string {} is not a valid number user_number end end if user_number > 100 begin print user_number ^ 2 end else begin pri...
if __name__ == '__main__': while 1: user_number = input("Choose a number: \n") if user_number.isdigit(): user_number = int(user_number) break else: print("{} is not a valid number".format(user_number)) if user_number > 100: print(user_number*...
Python
zaydzuhri_stack_edu_python
function query self query bindings=tuple results=string * begin try begin if closed begin call make_connection end call set_cursor with _cursor as cursor begin if is instance query list and not _dry begin for q in query begin call statement q tuple end return end set query = replace query string '?' string %s call sta...
def query(self, query, bindings=(), results="*"): try: if self._connection.closed: self.make_connection() self.set_cursor() with self._cursor as cursor: if isinstance(query, list) and not self._dry: for q in query: ...
Python
nomic_cornstack_python_v1
function set_machine_status_handler self handler begin set _status_handler = handler end function
def set_machine_status_handler(self, handler): self._status_handler = handler
Python
nomic_cornstack_python_v1
function deposit begin comment Get user balance set user_balance = call get_balance db if method == string POST begin if not get form string amount begin return call apology string Missing amount end else if decimal get form string amount <= 0 begin return call apology string Amount must be a positive number end set de...
def deposit(): # Get user balance user_balance = get_balance(db) if request.method == "POST": if not request.form.get('amount'): return apology("Missing amount") elif float(request.form.get('amount')) <= 0: return apology("Amount must be a positive number") ...
Python
nomic_cornstack_python_v1
function num_temp_HBNB n begin return call render_template string 5-number.html n=n end function
def num_temp_HBNB(n): return render_template('5-number.html', n=n)
Python
nomic_cornstack_python_v1
import os import itertools import distutils.dir_util import pynini from pynini import * class AttributeGrammarFST begin function __init__ self begin set path = join path directory name path __file__ + string /bin_files/ set digits = list string 1 string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9 s...
import os import itertools import distutils.dir_util import pynini from pynini import * class AttributeGrammarFST: def __init__(self): self.path = os.path.join(os.path.dirname(__file__) + '/bin_files/') digits = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] splitters = ['x', 'X', ...
Python
zaydzuhri_stack_edu_python
comment Fonte: https://www.trustedsec.com/2010/03/generate-an-ntlm-hash-in-3-lines-of-python import hashlib , binascii set hash = call digest
#Fonte: https://www.trustedsec.com/2010/03/generate-an-ntlm-hash-in-3-lines-of-python import hashlib,binascii hash = hashlib.new('md4', "moreno".encode('utf-16le')).digest()
Python
zaydzuhri_stack_edu_python
import random function random_exercise difficulty_level begin if difficulty_level == 0 begin set operando_1 = call randrange 1 10 set operando_2 = call randrange 1 10 set operador = random choice list string + string - string * set exercise_list = list operando_1 operando_2 operador end if difficulty_level == 1 begin s...
import random def random_exercise(difficulty_level): if difficulty_level == 0: operando_1 = random.randrange(1, 10) operando_2 = random.randrange(1, 10) operador = random.choice(['+', '-', '*']) exercise_list = [ operando_1, operando_2, operador ...
Python
zaydzuhri_stack_edu_python
comment Binary Beats comment Import required libraries import sys from matplotlib import pyplot as plt from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import Dropout , Flatten , Dense , BatchNormalization from tensorflow.keras.callbacks import EarlyStopping , ModelCheckp...
# Binary Beats # Import required libraries import sys from matplotlib import pyplot as plt from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import Dropout, Flatten, Dense, BatchNormalization from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint from tensor...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python class dsDNA_pos begin string Starts from position 0 function __init__ self size begin set size = size end function function set_plus_pos self pos_p begin set pos_p = pos_p end function function set_minus_pos self pos_m begin set pos_p = size - pos_m - 1 end function function posp self begin...
#!/usr/bin/env python class dsDNA_pos: """ Starts from position 0 """ def __init__(self, size): self.size = size def set_plus_pos(self, pos_p): self.pos_p = pos_p def set_minus_pos(self, pos_m): self.pos_p = self.size - pos_m - 1 def posp(self): return self.pos_p ...
Python
zaydzuhri_stack_edu_python
function convert self delta_multiplier begin set delta_multiplier = delta_multiplier end function
def convert(self, delta_multiplier): self.delta_multiplier = delta_multiplier
Python
nomic_cornstack_python_v1
import socket import string set HOST = string 140.122.185.174 set port = 8081 comment Normally 1024, the lower the number is, the response is faster set BUFFER_SIZE = 1024 comment How many bytes you want to try (Final bytes "char_bytes = 16") set char_bytes = 16 set SECRET = string set s = call socket AF_INET SOCK_STR...
import socket import string HOST = '140.122.185.174' port = 8081 BUFFER_SIZE = 1024 # Normally 1024, the lower the number is, the response is faster char_bytes = 16 # How many bytes you want to try (Final bytes "char_bytes = 16") SECRET = '' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, por...
Python
zaydzuhri_stack_edu_python
from hash_stats import HashStats class RoboHash begin string RoboHash is a HashTable implementation that provides constant time lookups and O(N) insertion time. It uses Open Addressing with linear probing for Hash collision resolution string Initializes RoboHash array_size -- the size of the table to start with, will d...
from hash_stats import HashStats class RoboHash: """ RoboHash is a HashTable implementation that provides constant time lookups and O(N) insertion time. It uses Open Addressing with linear probing for Hash collision resolution """ """Initializes RoboHash array_size -- the size of the table t...
Python
zaydzuhri_stack_edu_python
function workflow_2 sentences keep_prob=0.5 mask_prob=0.4 replace_prob=0.1 begin if length sentences < 0 begin return list end comment Extract entity and pattern for each sentence set all_docs = call pipe sentences set all_ents = list for doc in all_docs begin set ents = list for ent in ents begin append ents tuple ...
def workflow_2(sentences: List[str], keep_prob=0.5, mask_prob=0.4, replace_prob=0.1): if len(sentences) < 0: return [] # Extract entity and pattern for each sentence all_docs = nlp.pipe(sentences) all_ents = [] for doc in all_docs: ents = [] for ent in doc.ents:...
Python
nomic_cornstack_python_v1
function test_delete_server_fails self nova_mock begin set return_value = list call FakeServer string 1212 string speedy string ACTIVE for fail in novaclient_exceptions begin function _raise_fail server begin raise call fail code=http_status end function set side_effect = _raise_fail set exc = assert raises OpenStackCl...
def test_delete_server_fails(self, nova_mock): nova_mock.servers.list.return_value = [fakes.FakeServer('1212', 'speedy', 'ACTIVE')] for fail in self.novaclient_exceptions: ...
Python
nomic_cornstack_python_v1
string Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. In des First line contain integer N,denotes size of array. Second line contain N space separated integers,denotes array elements. Ot des Print the sum 4...
""" Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. In des First line contain integer N,denotes size of array. Second line contain N space separated integers,denotes array elements. Ot des Print th...
Python
zaydzuhri_stack_edu_python
function ls_diff_2 up_to=1750 precision=1000 begin set prec = precision set dec_2 = call Decimal 2 set dec_1_5 = call Decimal 1.5 return list comprehension integer dec_1_5 ^ i / dec_1_5 ^ i - 1 - dec_1_5 ^ - i / 1 - dec_2 ^ - i for i in range 2 up_to end function
def ls_diff_2(up_to=1750, precision=1000): getcontext().prec = precision dec_2 = Decimal(2) dec_1_5 = Decimal(1.5) return [int(dec_1_5**i) / (dec_1_5**i) - (1 - dec_1_5**(-i)) / (1 - dec_2**(-i)) for i in range(2, up_to)]
Python
nomic_cornstack_python_v1
from flask import Flask , render_template , redirect , url_for , request from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms import StringField , SubmitField from wtforms.validators import DataRequired import requests import os set API_KEY = get env...
from flask import Flask, render_template, redirect, url_for, request from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired import requests import os API_KEY = os.environ.get(...
Python
zaydzuhri_stack_edu_python
function test_amplitude self begin comment 1 + i, 1-i and i set x = call as_tensor list list 1 1 list 1 - 1 list 0 1 set y = call as_tensor list 2 2 1 set passcomplex = item call sumsqr_diff y call amplitude x < 1e-07 comment 1,2,4 (test function for real numbers) set x = call as_tensor list 1 2 4 set y = call as_tenso...
def test_amplitude(self): # 1 + i, 1-i and i x = torch.as_tensor([[1, 1], [1, -1], [0, 1]]) y = torch.as_tensor([2, 2, 1]) passcomplex = sumsqr_diff(y, pyms.utils.amplitude(x)).item() < 1e-7 # 1,2,4 (test function for real numbers) x = torch.as_tensor([1, 2, 4]) y...
Python
nomic_cornstack_python_v1
comment Write a bizz and zzuu game ##project set user_number = integer input string please enter a number for i in range 1 user_number + 1 begin print i end while true begin user_number end set play = input string Do you want to play BIZZZUUUU? if play == string yes begin set user_input = integer input string what numb...
# Write a bizz and zzuu game ##project user_number= (int(input("please enter a number"))) for i in range(1, user_number + 1): print(i) while True: user_number play = input('Do you want to play BIZZZUUUU?\n') if play == 'yes': user_input = int(input('what number would you like to play to?\n')) for num ...
Python
zaydzuhri_stack_edu_python
function sub_val self value_to_sub **kwargs begin return call set_val call _on_sub call get_val value_to_sub keyword kwargs keyword kwargs end function
def sub_val(self, value_to_sub, **kwargs): return self.set_val(self._on_sub(self.get_val(), value_to_sub, **kwargs), **kwargs)
Python
nomic_cornstack_python_v1
function get_template self begin if get_website begin return call get_template end else begin return call get_template end end function
def get_template(self): if self.get_website: return self.get_website.get_template() else: return default_entity.get_website.get_template()
Python
nomic_cornstack_python_v1
from flask import Flask from flask_restful import Resource , Api comment Resources is thing that api can return , create, delete and so on comment Resource are usually mapped into databases tables as well. comment Config the api set app = call Flask __name__ set api = call Api app comment Every resource has to be a cla...
from flask import Flask from flask_restful import Resource, Api # Resources is thing that api can return , create, delete and so on # Resource are usually mapped into databases tables as well. #Config the api app = Flask(__name__) api = Api(app) #Every resource has to be a class items = [] #Defining our resource ...
Python
zaydzuhri_stack_edu_python
string 求最大公约数和最小公倍数 version:0.1 author:小雨 date:2019..09.19 function gcd x y begin set tuple x y = if expression x > y then tuple x y else tuple y x for factor in range y 0 - 1 begin if x % factor == 0 and y % factor == 0 begin return factor end end end function function lcm x y begin return x * y / call gcd x y end fun...
''' 求最大公约数和最小公倍数 version:0.1 author:小雨 date:2019..09.19 ''' def gcd(x, y): (x, y) = (x, y) if (x > y) else (y, x) for factor in range(y, 0, -1): if x % factor == 0 and y % factor == 0: return factor def lcm(x,y): return x * y / gcd(x, y)
Python
zaydzuhri_stack_edu_python
import Tkinter as tk from PIL import Image , ImageTk class App begin function __init__ self root images begin set index = 0 set images = images set points = list for i in range length images begin set images at i = call PhotoImage images at i end set w = call width set h = call height set x = 0 set y = 0 set panel1 = ...
import Tkinter as tk from PIL import Image, ImageTk class App: def __init__(self, root, images): self.index = 0 self.images = images self.points = [] for i in range(len(self.images)): self.images[i] = ImageTk.PhotoImage(self.images[i]) w = images[0].width() h = images[0].height() x = 0 y = 0 ...
Python
zaydzuhri_stack_edu_python
function dump_jsonl self data output_path append=false begin set mode = if expression append then string a+ else string w with open output_path mode encoding=string utf-8 as f begin for line in data begin set json_record = dumps line ensure_ascii=false write f json_record + string end end print format string Wrote {} r...
def dump_jsonl(self, data, output_path, append=False): mode = 'a+' if append else 'w' with open(output_path, mode, encoding='utf-8') as f: for line in data: json_record = json.dumps(line, ensure_ascii=False) f.write(json_record + '\n') print('Wrote {} ...
Python
nomic_cornstack_python_v1
import numpy as np function generate_unique_array rows cols begin set array = zeros tuple rows cols dtype=int for i in range rows begin for j in range cols begin while true begin set value = random integer 1 101 if value not in array at tuple i slice : : and value not in array at tuple slice : : j begin set array...
import numpy as np def generate_unique_array(rows, cols): array = np.zeros((rows, cols), dtype=int) for i in range(rows): for j in range(cols): while True: value = np.random.randint(1, 101) if value not in array[i, :] and value not in array[:, j]: ...
Python
jtatman_500k
import numpy as np function feat_calc feat_array index_1 index_2 calc_type dst_index=- 1 begin string Function: Band math for two feature array, generate new feature array (Currently only supports binocular operations) Input: feat_array: np.array, original feature array, shape is ((sample number), (feature nmber + labe...
import numpy as np def feat_calc( feat_array: np.array, index_1: int, index_2: int, calc_type: str, *, dst_index: int = -1, ) -> np.ndarray: """ Function: Band math for two feature array, generate new feature array (Currently only supports binocular operations) Inpu...
Python
zaydzuhri_stack_edu_python
set cars = list dict string brand string Toyota ; string year 2005 ; string color string blue dict string brand string Ford ; string year 2012 ; string color string red dict string brand string Toyota ; string year 2015 ; string color string red dict string brand string Honda ; string year 2009 ; string color string gr...
cars = [ {'brand': 'Toyota', 'year': 2005, 'color': 'blue'}, {'brand': 'Ford', 'year': 2012, 'color': 'red'}, {'brand': 'Toyota', 'year': 2015, 'color': 'red'}, {'brand': 'Honda', 'year': 2009, 'color': 'green'}, {'brand': 'Toyota', 'year': 2018, 'color': 'black'}, {'brand': 'Ford', 'year'...
Python
jtatman_500k
function cosmic_correction sx spe fx ic weights cpt cosmic_sigcut cosmic_threshold begin comment define the critical pixel values? set crit = sx - spe at ic * fx comment re-cast the sigcut parameters comment 25% of the flux set sigcut = cosmic_sigcut comment start the loop counter set nbloop = 0 comment loop around unt...
def cosmic_correction(sx, spe, fx, ic, weights, cpt, cosmic_sigcut, cosmic_threshold): # define the critical pixel values? crit = (sx - spe[ic] * fx) # re-cast the sigcut parameters sigcut = cosmic_sigcut # 25% of the flux # start the loop counter nbloop = 0 # loop aro...
Python
nomic_cornstack_python_v1
function update_db_version begin print string Checking Database states... set default environ string DJANGO_SETTINGS_MODULE string ADSM.settings try begin call call_command string migrate database=string scenario_db interactive=false fake_initial=true call call_command string migrate database=string default interactive...
def update_db_version(): print("Checking Database states...") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ADSM.settings") try: call_command('migrate', database='scenario_db', interactive=False, fake_initial=True) call_command('migrate', database='default', interactive=False, fake_initia...
Python
nomic_cornstack_python_v1
function get_tag_values self data tag_name begin try begin set tree = call fromstring data set xml_namespace = dict string wprt string http://schemas.microsoft.com/windows/2006/08/wdp/print ; string wsa string http://schemas.xmlsoap.org/ws/2004/08/addressing ; string SOAP-ENV string http://www.w3.org/2003/05/soap-envel...
def get_tag_values(self, data, tag_name): try: tree = et.fromstring(data) xml_namespace = {"wprt": "http://schemas.microsoft.com/windows/2006/08/wdp/print", "wsa": "http://schemas.xmlsoap.org/ws/2004/08/addressing", "SOAP-ENV": "http://www.w3.or...
Python
nomic_cornstack_python_v1
function ra_reply_callback req iface begin set src = src call sendp ra iface=iface verbose=0 print string Fake RA sent in response to RS from %s % src end function
def ra_reply_callback(req, iface): src = req[IPv6].src sendp(ra, iface=iface, verbose=0) print("Fake RA sent in response to RS from %s" % src)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import os import re import json import pytz import pydicom import string import tzlocal import logging import zipfile import datetime import classification_from_label from fnmatch import fnmatch from pprint import pprint call basicConfig set log = call getLogger string dicom-mr-classifier s...
#!/usr/bin/env python import os import re import json import pytz import pydicom import string import tzlocal import logging import zipfile import datetime import classification_from_label from fnmatch import fnmatch from pprint import pprint logging.basicConfig() log = logging.getLogger("dicom-mr-classifier") DEFAU...
Python
zaydzuhri_stack_edu_python
function get_red_volume self begin set cumulative_volume = 0 comment If there is no hyperrectangle in the unsat space if not rectangles_unsat begin return 0.0 end for rectangle in rectangles_unsat begin set cumulative_volume = cumulative_volume + call get_rectangle_volume rectangle end return cumulative_volume end func...
def get_red_volume(self): cumulative_volume = 0 ## If there is no hyperrectangle in the unsat space if not self.rectangles_unsat: return 0.0 for rectangle in self.rectangles_unsat: cumulative_volume = cumulative_volume + get_rectangle_volume(rectangle) r...
Python
nomic_cornstack_python_v1
function currentosPaths filenames begin set nativeSep = vars at string DIRSEP if nativeSep == sep begin return filenames end else begin return call substitute filenames lambda x -> replace x nativeSep sep string FILENAMES caller=string currentosPaths end end function
def currentosPaths(filenames): nativeSep = mk.vars['DIRSEP'] if nativeSep == os.sep: return filenames else: return substitute(filenames, lambda x: x.replace(nativeSep, os.sep), 'FILENAMES', caller='currentosPaths')
Python
nomic_cornstack_python_v1
function open url backend_args=none begin set backend = call new_backend url backend_args comment Make sure the database already exists. set root = call get_root if string SCHEVO not in root begin close backend raise call DatabaseDoesNotExist url end comment Determine the version of the database. set schevo = root at s...
def open(url, backend_args=None): backend = new_backend(url, backend_args) # Make sure the database already exists. root = backend.get_root() if 'SCHEVO' not in root: backend.close() raise DatabaseDoesNotExist(url) # Determine the version of the database. schevo = root['SCHEVO'] ...
Python
nomic_cornstack_python_v1
function SizeOnStore self begin return call SizeOnStore end function
def SizeOnStore (self): return self.provider.SizeOnStore ()
Python
nomic_cornstack_python_v1
comment 15. 3Sum comment https://leetcode.com/problems/3sum/ class Solution extends object begin function threeSum self nums begin string :type nums: List[int] :rtype: List[List[int]] return call threeSum_withtarget nums 0 end function function threeSum_withtarget self nums target begin set res = list set N = length n...
# 15. 3Sum # https://leetcode.com/problems/3sum/ class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ return self.threeSum_withtarget(nums, 0) def threeSum_withtarget(self, nums, target): res = [] ...
Python
zaydzuhri_stack_edu_python
function mergeDictionaries dict1 dict2 begin string This function takes two python dictionaries as inputs and returns a single merged dictionary. comment Create a new empty dictionary set merged_dict = dict comment Iterate over the two argument dictionaries and add the key-value pairs to the new dictionary for tuple k...
def mergeDictionaries(dict1, dict2): '''This function takes two python dictionaries as inputs and returns a single merged dictionary.''' # Create a new empty dictionary merged_dict = {} # Iterate over the two argument dictionaries and add the key-value pairs to the new dictionary for key, value in...
Python
flytech_python_25k