code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
string The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? function digit_num power begin string Returns number of power-length numbers. set count = 0 set i = 1 while true begin set num_...
""" The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ def digit_num(power): """ Returns number of power-length numbers. """ count = 0 i = 1 while True: n...
Python
zaydzuhri_stack_edu_python
function left_riemann self n begin set b = mean self + 4 * standard deviation self set a = log k comment range(n) start from 0 without the last one set x = array list comprehension a + b - a / n * i for i in range n set f1 = call integration x set result = b - a / n * f1 return sum result end function
def left_riemann(self,n): b=self.mean()+4*self.std() a=np.log(self.k) x=np.array([a+(b-a)/n * i for i in range(n)]) # range(n) start from 0 without the last one f1=self.integration(x) result=(b-a)/n*f1 return np.sum(result)
Python
nomic_cornstack_python_v1
from functools import reduce from algorithm.al_read import read_file function aa input begin set m = 0 set max_var = none for string in generator expression string i for i in input begin set cur_max = reduce lambda x y -> integer x + integer y string if m < cur_max begin set tuple m max_var = tuple cur_max integer stri...
from functools import reduce from algorithm.al_read import read_file def aa(input): m = 0 max_var = None for string in (str(i) for i in input): cur_max = reduce(lambda x, y: int(x) + int(y), string) if m < cur_max: m, max_var = cur_max, int(string) return max_var if __n...
Python
zaydzuhri_stack_edu_python
import numpy as np from gcg.sampler.replay_pool import ReplayPool class BootstrapReplayPool extends object begin function __init__ self num_bootstraps **kwargs begin set _num_bootstraps = num_bootstraps set _replay_pools = list comprehension call ReplayPool keyword kwargs for _ in range _num_bootstraps end function fun...
import numpy as np from gcg.sampler.replay_pool import ReplayPool class BootstrapReplayPool(object): def __init__(self, num_bootstraps, **kwargs): self._num_bootstraps = num_bootstraps self._replay_pools = [ReplayPool(**kwargs) for _ in range(self._num_bootstraps)] def __len__(self): ...
Python
zaydzuhri_stack_edu_python
function generate_certificates cls begin set cert_age = call _get_file_age_in_seconds call Path TEST_CERT_NAME set key_age = call _get_file_age_in_seconds call Path TEST_KEY_NAME if cert_age < CERT_EXPIRY_AGE and key_age < CERT_EXPIRY_AGE begin debug string Credentials are up to date... return end debug string Credenti...
def generate_certificates(cls): cert_age = _get_file_age_in_seconds(pathlib.Path(TEST_CERT_NAME)) key_age = _get_file_age_in_seconds(pathlib.Path(TEST_KEY_NAME)) if cert_age < CERT_EXPIRY_AGE and key_age < CERT_EXPIRY_AGE: logging.debug('Credentials are up to date...') re...
Python
nomic_cornstack_python_v1
import requests import json function translate phrase begin comment Set up the URL for the Naver Translation API set url = string https://openapi.naver.com/v1/papago/n2mt comment Set up the headers and payload for the request set headers = dict string Content-Type string application/x-www-form-urlencoded; charset=UTF-8...
import requests import json def translate(phrase): # Set up the URL for the Naver Translation API url = "https://openapi.naver.com/v1/papago/n2mt" # Set up the headers and payload for the request headers = { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "X-Naver-C...
Python
jtatman_500k
import nltk from nltk.corpus import movie_reviews from pylab import plot , show from numpy import array from numpy.random import rand from scipy.cluster.vq import kmeans , vq , whiten import numpy as np import random import collections import time set time_start = time comment 1.数据格式化,转化为([词列表的影评],标签) 二元组 set documents...
import nltk from nltk.corpus import movie_reviews from pylab import plot,show from numpy import array from numpy.random import rand from scipy.cluster.vq import kmeans,vq,whiten import numpy as np import random import collections import time time_start=time.time() # 1.数据格式化,转化为([词列表的影评],标签) 二元组 documents ...
Python
zaydzuhri_stack_edu_python
import func set plan = list list 0 1 12 list 0 2 9 list 0 6 12 list 1 3 10 list 2 4 4 list 3 4 0 list 3 7 8 list 4 5 9 list 5 6 8 list 5 7 5 list 6 7 3 set vertex = 8 set T0 = call getT0 plan vertex print string T0: T0 set S = call getS T0 plan print string S: S set T1 = call getT1 plan vertex T0 print string T1: T1 se...
import func plan = [[0, 1, 12], [0, 2, 9], [0, 6, 12], [1, 3, 10], [2, 4, 4], [3, 4, 0], [3, 7, 8], [4, 5, 9], [5, 6, 8], [5, 7, 5], [6, 7, 3]] vertex = 8 T0 = func.getT0(plan, vertex) print('T0: ', T0) S = func.getS(T0, plan) print('S: ', S) T1 = func.getT1(plan, vertex, T0) print('T1: ', T...
Python
zaydzuhri_stack_edu_python
import os import pandas as pd import numpy as np from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFTextExtractionNotAllowed from pdfminer.pdftypes import resolve1 class Scraper begin string Given a filepath, scrape the contents of all pdfs in the filep...
import os import pandas as pd import numpy as np from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFTextExtractionNotAllowed from pdfminer.pdftypes import resolve1 class Scraper: """ Given a filepath, scrape the contents of all pdfs in the filepath...
Python
zaydzuhri_stack_edu_python
import stanza comment Run a stanza based NLP model function stanza_runner model=string small begin string Description: This function is used to load the data from the dataset and process it to identify the named entities. Output: Inside a file stanza_small.csv, the data is stored in the following format: text, type Mod...
import stanza # Run a stanza based NLP model def stanza_runner(model: str = 'small') -> None: ''' Description: This function is used to load the data from the dataset and process it to identify the named entities. Output: Inside a file stanza_small.csv, the data is stored in the following ...
Python
zaydzuhri_stack_edu_python
function _number_of_calculations self begin set value = integer params at string NUMBER_OF_GROUND_MOTION_FIELDS_CALCULATIONS if value <= 0 begin raise call ValueError string NUMBER_OF_GROUND_MOTION_FIELDS_CALCULATIONS must be grater than zero. end return value end function
def _number_of_calculations(self): value = int(self.job_ctxt.params[ "NUMBER_OF_GROUND_MOTION_FIELDS_CALCULATIONS"]) if value <= 0: raise ValueError("NUMBER_OF_GROUND_MOTION_FIELDS_CALCULATIONS " "must be grater than zero.") return value
Python
nomic_cornstack_python_v1
import numpy as np import mxnet import cv2 as cv import sys import os import random import pickle import imgaug import face_model from collections import defaultdict from imgaug import augmenters as iaa from time import time function sqeuclidean_dist emb_1 emb_2 begin return sum call square emb_1 - emb_2 end function c...
import numpy as np import mxnet import cv2 as cv import sys import os import random import pickle import imgaug import face_model from collections import defaultdict from imgaug import augmenters as iaa from time import time def sqeuclidean_dist(emb_1, emb_2): return np.sum(np.square(emb_1 - emb_2)) class Clas...
Python
zaydzuhri_stack_edu_python
import liblo , time class RemoteOSC extends ServerThread begin string Using OSC to sync with a GUI function __init__ self client_port=8000 server_port=9000 server=false begin string will send message to OSC instance on client_port of local machine, and listen to server_port NB: expect patterns indexed from 0 in input, ...
import liblo, time class RemoteOSC(liblo.ServerThread): """ Using OSC to sync with a GUI """ def __init__(self, client_port=8000, server_port=9000, server=False): """ will send message to OSC instance on client_port of local machine, and listen to server_port NB: expect patterns indexed...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved string File: F.py Author: changhaozhe(changhaozhe@baidu.com) Date: 2014/11/16 15:35:01 comment !/usr/bin/python comment coding=utf-8 import logging from logging import debug class Julian begin comme...
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################## # # Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved # ######################################################################## """ File: F.py Author: changhaozhe(changhaozhe@baidu.com) Date: ...
Python
zaydzuhri_stack_edu_python
import datetime from marshmallow import fields class DatetimeField extends DateTime begin function _serialize self value attr obj **kwargs begin return call _serialize value attr obj keyword kwargs end function function _deserialize self value attr data **kwargs begin comment self.datetime_to_iso(obj["update_at"]) retu...
import datetime from marshmallow import fields class DatetimeField(fields.DateTime): def _serialize(self, value, attr, obj, **kwargs): return super()._serialize(value, attr, obj, **kwargs) def _deserialize(self, value, attr, data, **kwargs): # self.datetime_to_iso(obj["update_at"]) r...
Python
zaydzuhri_stack_edu_python
function __init__ self begin set _callables = dict set _modules = none end function
def __init__(self): self._callables = {} self._modules = None
Python
nomic_cornstack_python_v1
function __init__ self dim=none data=none smoothing=none ties=string average offset=0 begin set ties = ties set _offset = offset set _name = string Empirical set smoothing = smoothing assert dim is not none or data is not none msg string Either dimension or data must be specified set _dim = if expression dim is none th...
def __init__(self, dim: Optional[int] = None, data: Optional[Union[np.ndarray, pd.DataFrame]] = None, smoothing: Optional[Smoothing] = None, ties: Ties = "average", offset: float = 0): self.ties = ties self._offset = offset self._name = "Empirical" self.smoothing = smoot...
Python
nomic_cornstack_python_v1
function get_all_column_names data_dicts begin set column_names = list for frame in data_dicts begin set frame_column_names = keys frame set column_names = column_names + list comprehension col for col in frame_column_names if col not in column_names end set sorted_col_names = sorted column_names comment discard the a...
def get_all_column_names(data_dicts): column_names = [] for frame in data_dicts: frame_column_names = frame.keys() column_names += [col for col in frame_column_names if col not in column_names] sorted_col_names = sorted(column_names) # discard the alphabetically...
Python
nomic_cornstack_python_v1
function vote_on_poll request option_id begin comment Fetch option and raise error if it doesn't exists set option_qs = filter pk=option_id if not exists option_qs begin return call Response status=HTTP_404_NOT_FOUND end set option = first option_qs comment If poll requires user, verify that request has one if requires...
def vote_on_poll(request, option_id): # Fetch option and raise error if it doesn't exists option_qs = Option.objects.filter(pk=option_id) if not option_qs.exists(): return Response(status=status.HTTP_404_NOT_FOUND) option = option_qs.first() # If poll requires user, verify that request has...
Python
nomic_cornstack_python_v1
function get_mse self key begin return mean np call square call subtract predictions at key y at key end function
def get_mse(self, key): return np.mean( np.square(np.subtract(self.predictions[key], self.y[key])) )
Python
nomic_cornstack_python_v1
function __init__ self begin comment better to be a prime number, less collision set key_space = 2069 set hash_table = list comprehension call Bucket for i in range key_space end function
def __init__(self): # better to be a prime number, less collision self.key_space = 2069 self.hash_table = [Bucket() for i in range(self.key_space)]
Python
nomic_cornstack_python_v1
function reverse phone db begin set database = load db set database = dictionary zip values database keys database if phone in database begin print string %s (%s) % tuple database at phone phone end else begin print string no one found with number %r % phone exit - 1 end end function
def reverse(phone, db): database = load(db) database = dict(zip(database.values(), database.keys())) if phone in database: print("%s (%s)" % (database[phone], phone)) else: print("no one found with number %r" % phone) sys.exit(-1)
Python
nomic_cornstack_python_v1
for i in range max a1 b1 a1 * b1 + 1 begin if i % a1 == 0 and i % b1 == 0 begin set ans = i break end end print ans
for i in range(max(a1,b1), a1*b1+1) : if (i%a1 == 0) and (i%b1 == 0) : ans = i break print(ans)
Python
zaydzuhri_stack_edu_python
from routes import Mapper import webob.dec import webob.exc import routes.middleware from src.controller.controller import TestAction from src.controller.controller import Application class MyResourceRouter extends object begin function __init__ self begin set route_name = string resource set route_path = string resor ...
from routes import Mapper import webob.dec import webob.exc import routes.middleware from src.controller.controller import TestAction from src.controller.controller import Application class MyResourceRouter(object): def __init__(self): route_name = 'resource' route_path = 'resor' ...
Python
zaydzuhri_stack_edu_python
comment 개똥벌레 comment 풀이 방법 string 1.H크기의 배열을 만들어 벽을 만날 때마다 해당하는 배열인덱스에 +1 해준 후 가장 작은 인덱스를 찾음 -> 시간초과 2.종유석과 석순을 따로 생각하고 각각의 누적합을 구한 후 더해줘서 min값을 찾으려고 함 -> 비요율적으로 따로 배열을 만들어 시간초과 3.결국 블로그 참고 -> 2번 아이디어는 맞았고, 구하는 심플한 방법이 있었음. comment # # # # # # # # # # # # # # # # # # # 1. import sys set input = readline set tuple N H =...
#개똥벌레 #풀이 방법 ''' 1.H크기의 배열을 만들어 벽을 만날 때마다 해당하는 배열인덱스에 +1 해준 후 가장 작은 인덱스를 찾음 -> 시간초과 2.종유석과 석순을 따로 생각하고 각각의 누적합을 구한 후 더해줘서 min값을 찾으려고 함 -> 비요율적으로 따로 배열을 만들어 시간초과 3.결국 블로그 참고 -> 2번 아이디어는 맞았고, 구하는 심플한 방법이 있었음. ''' # # # # # # # # # # # # # # # # # # # # 1. import sys input = sys.stdin.readline N,H=map(int,input().split...
Python
zaydzuhri_stack_edu_python
function exceed_action self begin return get pulumi self string exceed_action end function
def exceed_action(self) -> pulumi.Input[str]: return pulumi.get(self, "exceed_action")
Python
nomic_cornstack_python_v1
import sys function bracket_calculate brackets begin comment print("현재의 brackets",brackets) if brackets == string () begin comment print(brackets,"계산결과",2) return 2 end else if brackets == string [] begin comment print(brackets,"계산결과",3) return 3 end else if brackets == string begin comment print(brackets,"계산결과",0) re...
import sys def bracket_calculate(brackets): #print("현재의 brackets",brackets) if brackets =="()": #print(brackets,"계산결과",2) return 2 elif brackets =="[]": #print(brackets,"계산결과",3) return 3 elif brackets =="": #print(brackets,"계산결과",0) return 0 elif len(brackets)<=2: print(0) sy...
Python
zaydzuhri_stack_edu_python
function test_str begin assert call asnative str string cow == string cow assert is instance call asnative str string cow str assert call asnative str 42 == string 42 assert call asnative str string cow set literal str == string cow assert is instance call asnative str string cow set literal str str with raises Primiti...
def test_str(): assert asnative(str, "cow") == "cow" assert isinstance(asnative(str, "cow"), str) assert asnative(str, 42) == "42" assert asnative(str, "cow", {str}) == "cow" assert isinstance(asnative(str, "cow", {str}), str) with pytest.raises(PrimitiveMismatchError): asnative(str, 42,...
Python
nomic_cornstack_python_v1
if n1 > n2 begin print format string O primeiro número, de valor {}, é maior que o segundo número, de valor {}. n1 n2 end else if n2 > n1 begin print format string O segundo número, de valor {}, é maior que o primeiro número, de valor {}. n2 n1 end else begin print format string O primeiro e o segundo número são iguais...
if n1>n2: print('O primeiro número, de valor {}, é maior que o segundo número, de valor {}.'.format(n1, n2)) elif n2>n1: print('O segundo número, de valor {}, é maior que o primeiro número, de valor {}.'.format(n2, n1)) else: print('O primeiro e o segundo número são iguais, pois ambos têm o valor {}.'.forma...
Python
zaydzuhri_stack_edu_python
function closeDevice self begin call stopSampling comment Releases the bulk endpoint, which dispose_resources apparently doesn't release. call reset call dispose_resources DEVICE end function
def closeDevice(self): self.stopSampling() self.DEVICE.reset() #Releases the bulk endpoint, which dispose_resources apparently doesn't release. usb.util.dispose_resources(self.DEVICE)
Python
nomic_cornstack_python_v1
import numpy as np import csv function get_data_source data_path begin set cup_of_coffe = list set sleep_hours = list with open data_path as f begin set csv_reader = dict reader f for row in csv_reader begin append cup_of_coffe decimal row at string Coffee in ml append sleep_hours decimal row at string sleep in hours...
import numpy as np import csv def get_data_source(data_path): cup_of_coffe = [] sleep_hours = [] with open (data_path) as f: csv_reader = csv.DictReader(f) for row in csv_reader: cup_of_coffe.append(float(row["Coffee in ml"])) sleep_hours.append(float(row["...
Python
zaydzuhri_stack_edu_python
function conf_room input_lst begin set lst_lines_rooms = read lines open string rooms.txt string r set final_lst = list set final_full_lst = list set ult_lst = list for l in range length lst_lines_rooms begin set il_2 = integer join string split input_lst at 2 string : set il_3 = integer join string split input_ls...
def conf_room(input_lst): lst_lines_rooms = open('rooms.txt', 'r').readlines() final_lst = [] final_full_lst = [] ult_lst = [] for l in range(len(lst_lines_rooms)): il_2 = int(''.join(input_lst[2].split(':'))) ...
Python
zaydzuhri_stack_edu_python
from django.db import models from django.db.models import Q from datetime import date from datetime import timedelta import os set MIN_PRICE = 5 set MAX_DURATION = 20 class BidException extends Exception begin function __init__ self value begin set value = value end function function __str__ self begin return call repr...
from django.db import models from django.db.models import Q from datetime import date from datetime import timedelta import os; MIN_PRICE = 5 MAX_DURATION = 20 class BidException (Exception): def __init__ (self, value): self.value=value def __str__(self): return repr(self.value) class CloseException (Exception...
Python
zaydzuhri_stack_edu_python
function is_turbo_boost_enabled begin string Check whether Turbo Boost (scaling CPU frequency beyond nominal frequency) is active on this system. @return: A bool, or None if Turbo Boost is not supported. try begin if exists path _TURBO_BOOST_FILE begin set boost_enabled = integer call read_file _TURBO_BOOST_FILE if not...
def is_turbo_boost_enabled(): """ Check whether Turbo Boost (scaling CPU frequency beyond nominal frequency) is active on this system. @return: A bool, or None if Turbo Boost is not supported. """ try: if os.path.exists(_TURBO_BOOST_FILE): boost_enabled = int(util.read_file(_...
Python
jtatman_500k
function get_data url begin comment Splits the URL and gets the params set split_url = split url string / if length split_url > 5 or length split_url < 4 begin raise call ValueError string The input URL contains too many params. You sure this is a valid URL? end set name = none set id = none comment If the `name` wasn'...
def get_data(url): # Splits the URL and gets the params split_url = url.split("/") if len(split_url) > 5 or len(split_url) < 4: raise ValueError( "The input URL contains too many params. You sure this is a valid URL?" ) name = None id = None # If the `name` wasn't...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment File Name : eecback.py comment Created By : Thomas Aurel comment Creation Date : July 20th, 2016 comment Version : 0.1 comment Last Change : July 21th, 2016 at 12:56:55 AM comment Last Changed By : Thomas Aurel comment Purpose : Description from models.ecommand import ECommand class ECo...
#!/usr/bin/python ############################################################################### # # File Name : eecback.py # Created By : Thomas Aurel # Creation Date : July 20th, 2016 # Version : 0.1 # Last Change : July 21th, 2016 at 12:56:55 AM # Last Changed By : Thomas Aurel ...
Python
zaydzuhri_stack_edu_python
function _touch_store_cache self begin if has attribute self string _store_tuple begin set mod_info = call getpomtime if mod_info != mod_info begin set mod_info = mod_info call send sender=self path=path end end else begin comment FIXME: do we really need that? call _update_store_cache end end function
def _touch_store_cache(self): if hasattr(self, "_store_tuple"): mod_info = self.getpomtime() if self._store_tuple.mod_info != mod_info: self._store_tuple.mod_info = mod_info translation_file_updated.send(sender=self, path=self.path) else: ...
Python
nomic_cornstack_python_v1
function getRandom self begin if vals begin return vals at random integer 0 length vals - 1 end end function
def getRandom(self): if self.vals: return self.vals[random.randint(0, len(self.vals)-1)]
Python
nomic_cornstack_python_v1
function load_catalog path begin comment type: (object) -> object set catalog = read csv path comment Check if utc_timestamp exists, otherwise create it if string utc_timestamp not in columns begin set utc_timestamp = list for e in values begin append utc_timestamp timestamp end set catalog at string utc_timestamp = u...
def load_catalog(path): # type: (object) -> object catalog = pd.read_csv(path) # Check if utc_timestamp exists, otherwise create it if 'utc_timestamp' not in catalog.columns: utc_timestamp = [] for e in catalog.origintime.values: utc_timestamp.append(UTCDateTime(e).timestamp...
Python
nomic_cornstack_python_v1
function transform self X begin call _check_if_pandas_dataframe X name=string X return loc at tuple slice : : column_slice end function
def transform(self, X): _check_if_pandas_dataframe(X, name='X') return X.loc[:, self.column_slice]
Python
nomic_cornstack_python_v1
function sentences doc begin return list comprehension strip s for s in split doc string . end function
def sentences(doc): return [s.strip() for s in doc.split('. ')]
Python
nomic_cornstack_python_v1
function cutout_data self x1 y1 x2 y2 xstep=1 ystep=1 z=0 astype=float fill_value=NaN begin set t1 = time if astype is none begin set astype = float end if fill_value is none begin set fill_value = NaN end comment coerce to int values, just in case set tuple x1 y1 x2 y2 = call sort_xy x1 y1 x2 y2 set tuple x1 y1 x2 y2 ...
def cutout_data(self, x1, y1, x2, y2, xstep=1, ystep=1, z=0, astype=float, fill_value=np.NaN): t1 = time.time() if astype is None: astype = float if fill_value is None: fill_value = np.NaN # coerce to int values, just in case x1, y1, ...
Python
nomic_cornstack_python_v1
function hdf_obj_init self fhdf=none hdf_path=none fname=none raw=none overwrite=true begin if not fhdf begin set fhdf = call hdf_filename_init fname=fname raw=raw hdf_path=hdf_path end if exists path fhdf and overwrite begin remove os fhdf end comment return pd.HDFStore( fhdf,format='table' ) not usefull with float16 ...
def hdf_obj_init(self,fhdf=None,hdf_path=None,fname=None,raw=None,overwrite=True): if not fhdf : fhdf = self.hdf_filename_init(fname=fname,raw=raw,hdf_path=hdf_path) if ( os.path.exists(fhdf) and overwrite ): os.remove(fhdf) # return pd.HDFStore( fhdf,for...
Python
nomic_cornstack_python_v1
function get_alert self begin return alert end function
def get_alert(self): return self.__web_driver.switch_to.alert
Python
nomic_cornstack_python_v1
with open string test_dir/test_text6 as file begin set file_lines = read lines file for line in file_lines begin set info = split line set hours = 0 for elem in info at slice 1 : : begin if elem != string - begin set num = string 0 for i in elem begin if is digit i begin set num = num + i end else begin break end end...
with open('test_dir/test_text6') as file: file_lines = file.readlines() for line in file_lines: info = line.split() hours = 0 for elem in info[1:]: if elem != '-': num = '0' for i in elem: if i.isdigit(): ...
Python
zaydzuhri_stack_edu_python
function add_prog self params begin call clone_prog load self comment set up params set name = params at string name set cycle = params at string cycle set green = params at string green set offset = params at string offset comment update call update_text progId=num_progs name=name call update_cycle progId=num_progs ne...
def add_prog(self, params): self.clone_prog() self.load() # set up params name = params['name'] cycle = params['cycle'] green = params['green'] offset = params['offset'] # update self.update_text(progId=self.num_progs, name=name) self.upd...
Python
nomic_cornstack_python_v1
function suppress self email begin string Adds email addresses to a client's suppression list set body = dict string EmailAddresses if expression is instance email str then list email else email set response = call _post call uri_for string suppress dumps body end function
def suppress(self, email): """Adds email addresses to a client's suppression list""" body = { "EmailAddresses": [email] if isinstance(email, str) else email} response = self._post(self.uri_for("suppress"), json.dumps(body))
Python
jtatman_500k
from twisted.words.xish import domish from wokkel.xmppim import MessageProtocol , AvailablePresence class EchoBotProtocol extends MessageProtocol begin function __init__ self component=false begin call __init__ self set component = component end function end class
from twisted.words.xish import domish from wokkel.xmppim import MessageProtocol, AvailablePresence class EchoBotProtocol(MessageProtocol): def __init__(self, component=False): MessageProtocol.__init__(self) self.component = component
Python
zaydzuhri_stack_edu_python
function _add_reduction_loops_in_partial_loop_nest_tree kernel tree begin from loopy.symbolic import SubstitutionRuleMappingContext set rule_mapping_context = call SubstitutionRuleMappingContext substitutions call get_var_name_generator set reduction_loop_inserter = call ReductionLoopInserter rule_mapping_context tree ...
def _add_reduction_loops_in_partial_loop_nest_tree(kernel, tree): from loopy.symbolic import SubstitutionRuleMappingContext rule_mapping_context = SubstitutionRuleMappingContext( kernel.substitutions, kernel.get_var_name_generator()) reduction_loop_inserter = ReductionLoopInserter(rule_mapping_conte...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment Script to check free space on file system written to by imgcomp. comment If less then 20% free space, erase the oldest date image directory, but only one directory comment so script should be run more than once a day in case daily usage is higher than it was earlier. comment Crontab en...
#!/usr/bin/python3 # Script to check free space on file system written to by imgcomp. # If less then 20% free space, erase the oldest date image directory, but only one directory # so script should be run more than once a day in case daily usage is higher than it was earlier. # # Crontab entry to run it every 6 hours, ...
Python
zaydzuhri_stack_edu_python
comment !/Users/lacar/anaconda/envs/insight/bin/python comment Notes: comment run in virtual environment (insight) function ModelIt fromUser=string Default births=list begin set in_month = length births print string The number born is %i % in_month set result = in_month if fromUser != string Default begin return result...
#!/Users/lacar/anaconda/envs/insight/bin/python # Notes: # run in virtual environment (insight) def ModelIt(fromUser = 'Default', births = []): in_month = len(births) print('The number born is %i' % in_month) result = in_month if fromUser != 'Default': return result else: return 'check your input...
Python
zaydzuhri_stack_edu_python
function prepare_ocp biorbd_model_path final_time n_shooting ode_solver=call RK4 use_sx=true n_threads=1 begin set bio_model = call BiorbdModel biorbd_model_path comment Add objective functions set objective_functions = call Objective MINIMIZE_CONTROL key=string qddot_joints comment Dynamics set dynamics = call Dynamic...
def prepare_ocp( biorbd_model_path: str, final_time: float, n_shooting: int, ode_solver: OdeSolverBase = OdeSolver.RK4(), use_sx: bool = True, n_threads: int = 1, ) -> OptimalControlProgram: bio_model = BiorbdModel(biorbd_model_path) # Add objective functions objective_functions = ...
Python
nomic_cornstack_python_v1
import random class Skipnode begin function __init__ self data height begin string Initializes node with data and (height+1) front pointers. pass end function function __str__ self begin string Returns a string representation of an object for printing. pass end function function __repr__ self begin string Returns a str...
import random class Skipnode: def __init__(self, data, height): '''Initializes node with data and (height+1) front pointers. ''' pass def __str__(self): '''Returns a string representation of an object for printing. ''' pass def __repr__(self): ...
Python
zaydzuhri_stack_edu_python
function GetOrdinalString self basic=0 truncation=0 ndp=0 zonePrecision=Complete dp=string , tDesignator=string T begin return call GetOrdinalString basic truncation + tDesignator + call GetString basic NoTruncation ndp zonePrecision dp end function
def GetOrdinalString(self,basic=0,truncation=0,ndp=0,zonePrecision=Precision.Complete,dp=",",tDesignator="T"): return self.date.GetOrdinalString(basic,truncation)+tDesignator+\ self.time.GetString(basic,NoTruncation,ndp,zonePrecision,dp)
Python
nomic_cornstack_python_v1
function predict self new_imgs compare_all=false begin set embeddings = call _embed_batch new_imgs set embeddings = call reshape_embedding call numpy comment print(self.embedding_coreset.shape) comment print(embeddings.shape) set knn = call KNN X=embedding_coreset k=n_neighbors device=device set score_patches = call kn...
def predict(self, new_imgs: Tensor, compare_all: bool = False) -> Tensor: embeddings = self._embed_batch(new_imgs) embeddings = reshape_embedding(embeddings.cpu().detach().numpy()) #print(self.embedding_coreset.shape) #print(embeddings.shape) knn =...
Python
nomic_cornstack_python_v1
function test_trivial_one_case self begin set data = call Series list true true false false assert equal call _entropy data 1 end function
def test_trivial_one_case(self): data = Series([True, True, False, False]) self.assertEqual(compare._entropy(data), 1)
Python
nomic_cornstack_python_v1
function most_recent_common_ancestor self *ts begin string Find the MRCA of some tax_ids. Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if no ancestor of the specified tax_ids could be found. if length ts > 200 begin set res = call _large_mrca ts end else begin set res = call _small_mrca ts end if...
def most_recent_common_ancestor(self, *ts): """Find the MRCA of some tax_ids. Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if no ancestor of the specified tax_ids could be found. """ if len(ts) > 200: res = self._large_mrca(ts) else: ...
Python
jtatman_500k
async function _get_events_from_external_cache self events update_metrics=true begin set event_map = dict for event_id in events begin set ret = await call get_external tuple event_id none update_metrics=update_metrics if ret begin set event_map at event_id = ret end end return event_map end function
async def _get_events_from_external_cache( self, events: Iterable[str], update_metrics: bool = True ) -> Dict[str, EventCacheEntry]: event_map = {} for event_id in events: ret = await self._get_event_cache.get_external( (event_id,), None, update_metrics=update_me...
Python
nomic_cornstack_python_v1
function on_shutdown self begin call disconnect end function
def on_shutdown(self): self.disconnect()
Python
nomic_cornstack_python_v1
comment !/usr/local/bin/python3 comment coding:utf-8 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header function send_mail begin set host = string smtp.exmail.qq.com comment 25 为 SMTP 端口号 set port = 25 comment todo 发件人 set sender = string ...
#!/usr/local/bin/python3 # coding:utf-8 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header def send_mail(): host = 'smtp.exmail.qq.com' port = 25 # 25 为 SMTP 端口号 sender = '' # todo 发件人 receivers = [] # todo 接收邮件,可设置为你...
Python
zaydzuhri_stack_edu_python
function is_armstrong_number number begin set arm_number = sum list comprehension integer num ^ length string number for num in string number return if expression arm_number == number then true else false end function
def is_armstrong_number(number): arm_number = sum([int(num) ** len(str(number)) for num in str(number)]) return True if arm_number == number else False
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt comment Q1 b class NormalBandit begin function __init__ self mu sigma begin set mu = mu set sigma = sigma end function function reward self begin return call normal mu sigma 1 at 0 end function end class function softmax_2d x axis=0 begin set e_x = exp x - max x axis=a...
import numpy as np import matplotlib.pyplot as plt ############################################################### # Q1 b ############################################################### class NormalBandit: def __init__(self, mu, sigma): self.mu = mu self.sigma = sigma def reward(self): ...
Python
zaydzuhri_stack_edu_python
function load_submission_schedule begin info string Loading submission window schedule data call load_submission_window_schedule end function
def load_submission_schedule(): logger.info('Loading submission window schedule data') load_submission_window_schedule()
Python
nomic_cornstack_python_v1
function get_auth group **auth_kwargs begin try begin set auth = call load_auth_from_conf_options CONF group keyword auth_kwargs end except MissingRequiredOptions begin error string Failed to load auth plugin from group %s group raise end return auth end function
def get_auth(group, **auth_kwargs): try: auth = ks_loading.load_auth_from_conf_options(CONF, group, **auth_kwargs) except ks_exception.MissingRequiredOptions: LOG.error('Failed to load auth plugin from group %s', group) raise retu...
Python
nomic_cornstack_python_v1
from sqlalchemy import Column , Integer , Sequence , String , Boolean , ForeignKey , DateTime , func , CheckConstraint , UniqueConstraint from sqlalchemy.ext.declarative import declarative_base set Base = call declarative_base class FeedItemModel extends Base begin set __tablename__ = string feed_item set id = call Col...
from sqlalchemy import Column, Integer, Sequence, String, Boolean, ForeignKey, DateTime, func, CheckConstraint, \ UniqueConstraint from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class FeedItemModel(Base): __tablename__ = 'feed_item' id = Column(Integer, Sequence('seq_f...
Python
zaydzuhri_stack_edu_python
function set_lang self newLang begin if newLang in call get_all_langs begin set __lang = newLang end end function
def set_lang(self, newLang: str) -> None: if(newLang in self.get_all_langs()): self.__lang = newLang
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment Patryk Wegrzyn comment Kompilatory - laboratorium - poniedziałek 11:15 import scanner import ply.yacc as yacc import AST set tokens = tokens set error_encountered = false set start = string stmtList set precedence = tuple tuple string left string IF tuple string left string ELSE tuple s...
#!/usr/bin/python # Patryk Wegrzyn # Kompilatory - laboratorium - poniedziałek 11:15 import scanner import ply.yacc as yacc import AST tokens = scanner.tokens error_encountered = False start = 'stmtList' precedence = ( # Dangling-else solution ("left", 'IF'), ("left", 'ELSE'), # ID and LEFTBRACKET ...
Python
zaydzuhri_stack_edu_python
function enable_push self begin return self at ENABLE_PUSH end function
def enable_push(self): return self[SettingsFrame.ENABLE_PUSH]
Python
nomic_cornstack_python_v1
function main file_paths=none begin if file_paths begin for file_path in file_paths begin call move_and_symlink_file file_path end end else begin call create_home_directories call create_home_directory_symbolic_links end end function
def main(file_paths: Optional[List[Path]] = None): if file_paths: for file_path in file_paths: move_and_symlink_file(file_path) else: create_home_directories() create_home_directory_symbolic_links()
Python
nomic_cornstack_python_v1
function sum_of_even numbers begin set even_numbers = list comprehension num for num in numbers if num % 2 == 0 set sum_of_even_numbers = sum even_numbers return sum_of_even_numbers end function set numbers = list 2 4 6 8 10 print string Sum of even numbers: call sum_of_even numbers
def sum_of_even(numbers): even_numbers = [num for num in numbers if num % 2 == 0] sum_of_even_numbers = sum(even_numbers) return sum_of_even_numbers numbers = [2, 4, 6, 8, 10] print("Sum of even numbers:", sum_of_even(numbers))
Python
jtatman_500k
function find_it seq begin return max filter lambda x -> count seq x % 2 != 0 seq end function
def find_it(seq): return max(filter(lambda x: seq.count(x) % 2 != 0, seq))
Python
nomic_cornstack_python_v1
string Connects to arango and performs an authenticated request using JWT. This shows how to use a disk JWT cache, which uses a disk locking and caching strategy to share a single JWT across all instances running on the same machine. from arango_crud import Config , RandomCluster , StepBackOffStrategy , JWTAuth , JWTDi...
"""Connects to arango and performs an authenticated request using JWT. This shows how to use a disk JWT cache, which uses a disk locking and caching strategy to share a single JWT across all instances running on the same machine. """ from arango_crud import ( Config, RandomCluster, StepBackOffStrategy, JWTAut...
Python
zaydzuhri_stack_edu_python
function test_reference_query_conversion_dbref self begin class Member extends Document begin set user_num = call IntField primary_key=true end class class BlogPost extends Document begin set title = call StringField set author = call ReferenceField Member dbref=true end class call drop_collection call drop_collection ...
def test_reference_query_conversion_dbref(self): class Member(Document): user_num = IntField(primary_key=True) class BlogPost(Document): title = StringField() author = ReferenceField(Member, dbref=True) Member.drop_collection() BlogPost.drop_collect...
Python
nomic_cornstack_python_v1
while a >= b begin print b set b = b + 1 end set a = integer input set b = 0 while true begin print b set b = b + 1 if a < b begin break end end
while a >= b: print (b) b += 1 a = int(input()) b = 0 while True: print (b) b += 1 if a < b: break
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment find tips from mids along low intensty import numpy as np import nrrd set Case_num = 64 comment threshold of searching ability set threshold = 15 set nrrdData = read nrrd string Case0%d.nrrd % Case_num set im = nrrdData at 0 comment load mid information set mid = load np string Case_num + ...
# coding: utf-8 ## find tips from mids along low intensty import numpy as np import nrrd Case_num = 64 # threshold of searching ability threshold = 15 nrrdData = nrrd.read('Case0%d.nrrd'%Case_num) im = nrrdData[0] # load mid information mid = np.load(str(Case_num)+'-mid.save') print(mid.shape) # s...
Python
zaydzuhri_stack_edu_python
function scope_reset client args begin set result = call get_scope if is_custom begin print string Proxy is using a custom function to check scope. Cannot set context to scope. return end call set_query filter end function
def scope_reset(client, args): result = client.get_scope() if result.is_custom: print("Proxy is using a custom function to check scope. Cannot set context to scope.") return client.context.set_query(result.filter)
Python
nomic_cornstack_python_v1
comment TO FIND SMALLEST NUMBER function smallest numList begin set n = length numList comment TAKING DUMMY VALUE set smallest_number = numList at 0 set i = 1 while i < n begin if numList at i < smallest_number begin set smallest_number = numList at i set i = i + 1 end end return smallest_number end function comment TO...
def smallest(numList):#TO FIND SMALLEST NUMBER n=len(numList) smallest_number=numList[0]#TAKING DUMMY VALUE i=1 while (i<n): if numList[i]<smallest_number: smallest_number=numList[i] i+=1 return smallest_number def my_sort(list):#TO SORT IT IN ASCENDING ORD...
Python
zaydzuhri_stack_edu_python
for shue in mda begin print shue at 1 end
for shue in mda: print(shue[1])
Python
zaydzuhri_stack_edu_python
comment input comment this will act as rows set no_of_arrays = integer input string Enter the number of arrays: comment this will act as columns set length = integer input string Enter the length of a single array: print string comment A for loop for row entries for i in range no_of_arrays begin set a = list print str...
#input no_of_arrays = int(input("Enter the number of arrays:")) #this will act as rows length = int(input("Enter the length of a single array:")) #this will act as columns print(" \n") for i in range(no_of_arrays): # A for loop for row entries a =[] print("enter the values of array " + str(i+1...
Python
zaydzuhri_stack_edu_python
function get_cenrep_entry_line self entry delta_cenrep=false begin set value = none if crml_type in tuple string string string string8 begin if confml_type is none begin pass end else if orig_value is none begin set value = string "" end else begin set value = string "%s" % orig_value end end else if crml_type == strin...
def get_cenrep_entry_line(self, entry, delta_cenrep=False): value = None if entry.crml_type in ('string', 'string8'): if entry.confml_type is None: pass else: if entry.orig_value is None: value = '""' els...
Python
nomic_cornstack_python_v1
function tree_drag_motion self *args begin pass end function
def tree_drag_motion(self, *args): pass
Python
nomic_cornstack_python_v1
import sys from common import geturl , myid from unum.units import s as _sec , h as _hour , d as _day import unum set VALUE_FORMAT = string %.01f if length argv > 1 begin set aid = argv at 1 end
import sys from common import geturl, myid from unum.units import s as _sec, h as _hour, d as _day import unum unum.Unum.VALUE_FORMAT = "%.01f" if len(sys.argv) > 1: aid = sys.argv[1]
Python
zaydzuhri_stack_edu_python
function method value arg begin try begin return value at arg end except tuple TypeError KeyError IndexError begin pass end try begin return get attribute value string arg end except AttributeError begin pass end return format string [no method {}] arg end function
def method(value, arg): try: return value[arg] except (TypeError, KeyError, IndexError): pass try: return getattr(value, str(arg)) except AttributeError: pass return u'[no method {}]'.format(arg)
Python
nomic_cornstack_python_v1
function restock_book self isbn quantity begin execute cursor string SELECT COUNT(*) FROM book WHERE ISBN=%s tuple isbn if call fetchone at 0 begin execute cursor string UPDATE book set stock=stock+%s WHERE ISBN=%s tuple quantity isbn commit db return true end return false end function
def restock_book(self, isbn, quantity): self.cursor.execute("""SELECT COUNT(*) FROM book WHERE ISBN=%s""", (isbn,)) if self.cursor.fetchone()[0]: self.cursor.execute("""UPDATE book set stock=stock+%s WHERE ISBN=%s""", (quantity, isbn)) self.db.commit() return True ...
Python
nomic_cornstack_python_v1
function dirname self begin raise call NotImplementedError end function
def dirname(self): raise NotImplementedError()
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment Qualcomm DevInfo Parser comment by comment TwizzyIndy comment 9/2018 import os import struct function usage begin print string print string Qualcomm DevInfo Parser print string by TwizzyIndy print string 9/2018 print string usage : python read_devinfo.py devinfo.img print string end fun...
#!/usr/bin/python # Qualcomm DevInfo Parser # by # TwizzyIndy # 9/2018 import os import struct def usage(): print("") print("Qualcomm DevInfo Parser") print("by TwizzyIndy") print("9/2018") print("usage : python read_devinfo.py devinfo.img") print("") def main(): if( len(os.sys....
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- from bs4 import BeautifulSoup import copy import os import shutil import utils import json import sys print string Start json transform function transform source_path target_path platform begin with open source_path as f begin set data = load json f end set new...
#!/usr/bin/env python # -*- coding: utf-8 -*- from bs4 import BeautifulSoup import copy import os import shutil import utils import json import sys print("Start json transform") def transform(source_path, target_path, platform): with open(source_path) as f: data = json.load(f) new_doc = BeautifulSoup("<!DOC...
Python
zaydzuhri_stack_edu_python
function csv_to_mysql load_sql host user password begin try begin set con = call connect host=host user=user password=password autocommit=true local_infile=1 print format string Connected to DB: {} host comment Create cursor and execute Load SQL set cursor = call cursor execute cursor load_sql print string Succuessfull...
def csv_to_mysql(load_sql, host, user, password): try: con = pymysql.connect(host=host, user=user, password=password, autocommit=True, local_infile=1) print('Connected to DB: {}'.f...
Python
nomic_cornstack_python_v1
function convert_to_roman n begin if not is instance n int begin raise call ValueError string Input must be a valid integer end if n < 0 begin set is_negative = true set n = absolute n end else begin set is_negative = false end if n == 0 begin return string Nulla end set roman_numerals = dict 1000 string M ; 900 string...
def convert_to_roman(n): if not isinstance(n, int): raise ValueError("Input must be a valid integer") if n < 0: is_negative = True n = abs(n) else: is_negative = False if n == 0: return "Nulla" roman_numerals = { 1000: 'M', 900: 'CM', ...
Python
jtatman_500k
function get_feature_names self begin Ellipsis end function
def get_feature_names(self): ...
Python
nomic_cornstack_python_v1
comment real signature unknown function __new__ *args **kwargs begin pass end function
def __new__(*args, **kwargs): # real signature unknown pass
Python
nomic_cornstack_python_v1
import serial set ser = call Serial string /dev/ttyUSB1 115200 while 1 begin if in_waiting > 0 begin set number = read line ser end end
import serial ser = serial.Serial('/dev/ttyUSB1', 115200) while 1: if(ser.in_waiting >0): number = ser.readline()
Python
zaydzuhri_stack_edu_python
function find_2nd_last head begin if next is none begin return head end while next is not none begin set n = next end return next end function
def find_2nd_last(head): if head.next is None: return head while n.next.next is not None: n = n.next return n.next
Python
zaydzuhri_stack_edu_python
function isdecimal self begin return call isdecimal self end function
def isdecimal(self): return isdecimal(self)
Python
nomic_cornstack_python_v1
function arn self begin return _tg_data at string TargetGroupArn end function
def arn(self): return self._tg_data['TargetGroupArn']
Python
nomic_cornstack_python_v1
function get_analyzer cls analyzer_name begin return _class_registry at lower analyzer_name end function
def get_analyzer(cls, analyzer_name): return cls._class_registry[analyzer_name.lower()]
Python
nomic_cornstack_python_v1
function get_validation_by_action_id self action_id begin return call get_as_dict_array SELECT_VALIDATION_BY_ACTION_ID action_id=action_id end function
def get_validation_by_action_id(self, action_id): return self.get_as_dict_array( ShipyardDbAccess.SELECT_VALIDATION_BY_ACTION_ID, action_id=action_id)
Python
nomic_cornstack_python_v1
function formata_tamanho tamanho begin set zero = 0 set base = 1024 set kilo = base set mega = base ^ 2 set giga = base ^ 3 set tera = base ^ 4 set peta = base ^ 5 if tamanho <= zero begin set tamanho = zero set texto = string ARQUIVO VAZIO end else if tamanho < kilo begin set tamanho = tamanho set texto = string bytes...
def formata_tamanho(tamanho): zero = 0 base = 1024 kilo = base mega = base ** 2 giga = base ** 3 tera = base ** 4 peta = base ** 5 if tamanho <= zero: tamanho = zero texto = 'ARQUIVO VAZIO' elif tamanho < kilo: tamanho = tamanho texto = 'bytes' el...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- comment @Time : 2020/11/20 18:19 comment @Author : Yong comment @Email : Yong_GJ@163.com comment @File : task_7.3.2_listRemove.py comment @Software: PyCharm comment 删除列表中所有包含特定的值 comment list.remove(): 删除列表中的特定值, 从列表首位开始删除。 set pets = list string dog string cat st...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/20 18:19 # @Author : Yong # @Email : Yong_GJ@163.com # @File : task_7.3.2_listRemove.py # @Software: PyCharm # 删除列表中所有包含特定的值 # list.remove(): 删除列表中的特定值, 从列表首位开始删除。 pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) # 从列表...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function numJewelsInStones self J S begin string :type J: str :type S: str :rtype: int return sum generator expression count S j for j in J end function end class set J = string aA set S = string aAAbbbb print call numJewelsInStones J S
class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ return sum(S.count(j) for j in J) J = "aA" S = "aAAbbbb" print(Solution().numJewelsInStones(J, S))
Python
zaydzuhri_stack_edu_python