code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function main begin if length argv < 4 begin print string usage: %s <address 1> <address 2> <address 3> <address 4> % argv at 0 return 1 end set tv1 = call Mdc argv at 1 set tv2 = call Mdc argv at 2 set tv3 = call Mdc argv at 3 set tv4 = call Mdc argv at 4 call connect call connect call connect call connect call video_...
def main(): if len(sys.argv) < 4: print("usage: %s <address 1> <address 2> <address 3> <address 4>" % ( sys.argv[0] )) return 1 tv1 = Mdc(sys.argv[1]) tv2 = Mdc(sys.argv[2]) tv3 = Mdc(sys.argv[3]) tv4 = Mdc(sys.argv[4]) tv1.connect() tv2.connect() tv3....
Python
nomic_cornstack_python_v1
function run self verbose=false begin set step_num = 0 while won == 0 begin if length valid_moves == 0 begin return end set status = step self if verbose and step_num % 2 == 1 begin print call table end if status != INVALID_MOVE begin set step_num = step_num + 1 end end print string Player { call remap_char won } won! ...
def run(self, verbose=False): step_num = 0 while self.won == 0: if len(self.board.valid_moves) == 0: return status = self.step() if verbose and step_num % 2 == 1: print(self.board.table()) if status != board.Board.INVALID_MO...
Python
nomic_cornstack_python_v1
function y self begin return self at 1 end function
def y(self): return self[1]
Python
nomic_cornstack_python_v1
function loads self data raw=false nonce=none begin set data = call decrypt data comment simple integrity check to verify that we got meaningful data if not starts with data PICKLE_PAD begin return dict end set data = data at slice length PICKLE_PAD : : if nonce begin set ret_nonce = decode data at slice : 32 : set...
def loads(self, data, raw=False, nonce=None): data = self.decrypt(data) # simple integrity check to verify that we got meaningful data if not data.startswith(self.PICKLE_PAD): return {} data = data[len(self.PICKLE_PAD) :] if nonce: ret_nonce = data[:32].de...
Python
nomic_cornstack_python_v1
function new_file self begin set filename = call getSaveFileName none string Title string string TXT (*.txt) if filename at 0 begin set currentfile = open filename at 0 string w set tuple base_name ext = call splitext filename at 0 call setText filename at 0 end end function
def new_file(self): self.filename = QFileDialog.getSaveFileName( None, 'Title', '', 'TXT (*.txt)' ) if self.filename[0]: self.currentfile = open(self.filename[0], 'w') (self.base_name, self.ext) = os.path.splitext(self.filename[0]) ...
Python
nomic_cornstack_python_v1
import os from sklearn.metrics import roc_curve , auc , average_precision_score , f1_score from scipy.optimize import brentq from scipy.interpolate import interp1d import matplotlib.pyplot as plt from matplotlib import rc import numpy as np function evaluate labels scores metric=string roc save_to=string begin if metri...
import os from sklearn.metrics import roc_curve, auc, average_precision_score, f1_score from scipy.optimize import brentq from scipy.interpolate import interp1d import matplotlib.pyplot as plt from matplotlib import rc import numpy as np def evaluate(labels, scores, metric='roc',save_to=''): if metric == 'roc': ...
Python
zaydzuhri_stack_edu_python
function posterior_predictive_to_xarray self begin string Convert posterior_predictive samples to xarray. set posterior = posterior set posterior_model = posterior_model set posterior_predictive = posterior_predictive set data = call get_draws_stan3 posterior model=posterior_model variables=posterior_predictive return ...
def posterior_predictive_to_xarray(self): """Convert posterior_predictive samples to xarray.""" posterior = self.posterior posterior_model = self.posterior_model posterior_predictive = self.posterior_predictive data = get_draws_stan3(posterior, model=posterior_model, variabl...
Python
jtatman_500k
function answer_call begin comment Start our TwiML response set resp = call VoiceResponse set callednumber = values at string Called if string 2274 in callednumber begin call say string Matched! voice=string alice end else begin comment Read a message aloud to the caller call say string Thank you for calling! Have a gr...
def answer_call(): # Start our TwiML response resp = VoiceResponse() callednumber = request.values['Called'] if "2274" in callednumber: resp.say('Matched!', voice='alice') else: # Read a message aloud to the caller resp.say("Thank you for calling! Have a great day.", voice='...
Python
nomic_cornstack_python_v1
function apply_filters_to_fields fields filters_by_idx=dict verbose=true begin for idx in keys filters_by_idx begin if string fields at idx != filters_by_idx at idx begin return false end end comment If we didn't fail a filter then the data look OK; return True comment Also return True if an empty filters_by_idx dict ...
def apply_filters_to_fields(fields,filters_by_idx={},verbose=True): for idx in filters_by_idx.keys(): if str(fields[idx]) != filters_by_idx[idx]: return False #If we didn't fail a filter then the data look OK; return True #Also return True if an empty filters_by_idx dict was specifi...
Python
nomic_cornstack_python_v1
from itertools import combinations , permutations for _ in call xrange integer call raw_input begin set s = call raw_input set p = list set generator expression join string i for i in permutations s 2 end
from itertools import combinations,permutations for _ in xrange(int(raw_input())): s=raw_input() p=list(set("".join(i) for i in permutations(s,2)))
Python
zaydzuhri_stack_edu_python
function configs self begin return _configs end function
def configs(self): return self._configs
Python
nomic_cornstack_python_v1
function streaming_mean_cosine_distance predictions labels dim weights=none metrics_collections=none updates_collections=none name=none begin set tuple predictions labels = call remove_squeezable_dimensions predictions labels call assert_is_compatible_with call get_shape set radial_diffs = call mul predictions labels s...
def streaming_mean_cosine_distance(predictions, labels, dim, weights=None, metrics_collections=None, updates_collections=None, name=None): predictions, labels = metric_ops_util.remove_squeezable_dimensions( ...
Python
nomic_cornstack_python_v1
comment sorting test script comment logged in as "test2@test.com" "test" comment starting at home screen call click string 1415332642234.png if exists string 1415332705007.png begin print string Sorted Z-A successfully end else begin print string ERROR: Sorted Z-A unsuccessfully end call click string 1415332759178.png ...
#sorting test script #logged in as "test2@test.com" "test" #starting at home screen click("1415332642234.png") if exists("1415332705007.png"): print("Sorted Z-A successfully") else: print("ERROR: Sorted Z-A unsuccessfully") click("1415332759178.png") if exists("1415332804175.png"): print("Sorted A-Z succes...
Python
zaydzuhri_stack_edu_python
function getConfigFile self runArgs filepath begin comment Identify Hfor type from AthenaCommon.Utils.unixtools import FindFile import sys , os try begin set file = open filepath end except any begin set currentError = string Exiting. Configuration file should be in + string filepath error currentError exit 0 end comme...
def getConfigFile(self, runArgs, filepath): #Identify Hfor type from AthenaCommon.Utils.unixtools import FindFile import sys, os try: self.file = open(filepath) except: currentError = "Exiting. Configuration file should be in "+str(filepath) ...
Python
nomic_cornstack_python_v1
function task_six fnam begin set tuple head data = read csv fnam set cols = length head comment get length of longest fields in each column set l = list comprehension 0 for i in head for val in data begin for tuple i v in enumerate l begin if length val at i > v begin set l at i = length val at i end end end comment cr...
def task_six(fnam): head,data=read_csv(fnam) cols=len(head) # get length of longest fields in each column l=[0 for i in head] for val in data: for i,v in enumerate(l): if len(val[i]) > v: l[i]=len(val[i]) # create formats for each column colspace=3 ...
Python
nomic_cornstack_python_v1
function get_volumes self references=none authorization=none x_request_id=none destroyed=none filter=none ids=none limit=none names=none offset=none sort=none total_item_count=none total_only=none async_req=false _return_http_data_only=false _preload_content=true _request_timeout=none begin comment type: List[models.Re...
def get_volumes( self, references=None, # type: List[models.ReferenceType] authorization=None, # type: str x_request_id=None, # type: str destroyed=None, # type: bool filter=None, # type: str ids=None, # type: List[str] limit=None, # type: int ...
Python
nomic_cornstack_python_v1
function extraction_type_check sample_sheet begin comment Initialise variables set contains_rna_extraction = false set contains_dna_extraction = false comment Crawl over bio entities until test_sample for tuple _ entity in items bio_entities begin for tuple _ bio_sample in items bio_samples begin for tuple _ test_sampl...
def extraction_type_check(sample_sheet): # Initialise variables contains_rna_extraction = False contains_dna_extraction = False # Crawl over bio entities until test_sample for _, entity in sample_sheet.bio_entities.items(): for _, bio_sample in entity.bio_samples.ite...
Python
nomic_cornstack_python_v1
comment coding:utf8 class Solution begin function reverse_string self s begin string :param s: List[str] :return: None set n = length s for i in range n // 2 begin set tuple s at i s at n - 1 - i = tuple s at n - 1 - i s at i end end function end class function main begin set s = list string h string e string l string ...
# coding:utf8 class Solution: def reverse_string(self, s): """ :param s: List[str] :return: None """ n = len(s) for i in range(n // 2): s[i], s[n - 1 - i] = s[n - 1 - i], s[i] def main(): s = ["h", "e", "l", "l", "o"] Solution().reverse_string(...
Python
zaydzuhri_stack_edu_python
function current self begin pass end function
def current(self): pass
Python
nomic_cornstack_python_v1
function icdf_choose_exp self begin set exp_icdf_array = exp - icdf_array set rand_num = random set q = rand_num * CDF_RES comment We take the integer part of q because we require i to be an index. comment By taking away the integer part of q we are left with a random comment number i, on the unit interval that is used...
def icdf_choose_exp(self) -> float: exp_icdf_array = np.exp(-self.icdf_array) rand_num = random.random() q = rand_num * self.CDF_RES # We take the integer part of q because we require i to be an index. # By taking away the integer part of q we are left with a random # nu...
Python
nomic_cornstack_python_v1
function start self timeout=15.0 begin assert _pid is none set _endpoint = string http://%s:%d % tuple _host _port set _rpc = call RPCClient _endpoint set cmd = list _executable string -v string --host _host string --port string _port string --noVMErrorsOnRPCResponse if _blocktime is not none begin extend cmd list stri...
def start(self, timeout: float=15.0) -> None: assert self._pid is None self._endpoint = "http://%s:%d" % (self._host, self._port) self._rpc = RPCClient(self._endpoint) cmd = [ self._executable, "-v", "--host", self._host, "--port", str(se...
Python
nomic_cornstack_python_v1
function get_train_test dataframe begin set x_data = list set y_data = list comment Separate features from the target for row in values begin append x_data row at slice : - 1 : append y_data row at - 1 end set tuple x_train x_test y_train y_test = train test split x_data y_data random_state=1 return tuple array x_tr...
def get_train_test(dataframe: pd.DataFrame) -> tuple: x_data = [] y_data = [] # Separate features from the target for row in dataframe.values: x_data.append(row[:-1]) y_data.append(row[-1]) x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, random_state=1) retu...
Python
nomic_cornstack_python_v1
function sample_without_replacement pool out begin comment We sample n_samples elements from the pool set n_samples = shape at 0 set population_size = shape at 0 comment Initialize the pool for i in range population_size begin set pool at i = i end for i in range n_samples begin set j = random integer population_size -...
def sample_without_replacement(pool, out): # We sample n_samples elements from the pool n_samples = out.shape[0] population_size = pool.shape[0] # Initialize the pool for i in range(population_size): pool[i] = i for i in range(n_samples): j = randint(population_size - i) ...
Python
nomic_cornstack_python_v1
import requests import csv from BeautifulSoup import BeautifulSoup set list_of_rows = list set intID = 1 comment while intID < 100000: while intID < 200 begin set url = string http://webcolourdata.com/profile/ + string intID set response = get requests url set html = content set soup = call BeautifulSoup html if find ...
import requests import csv from BeautifulSoup import BeautifulSoup list_of_rows = [] intID = 1 # while intID < 100000: while intID < 200: url = 'http://webcolourdata.com/profile/' +str(intID) response = requests.get(url) html = response.content soup = BeautifulSoup(html) if soup.find("section", attrs={'class'...
Python
zaydzuhri_stack_edu_python
function performGetValue self quant options=dict begin set qname = name set params = call RFParameters call sc5520a_uhfsFetchRfParameters _handle params if qname == string Frequency begin return decimal frequency end else if qname == string Amplitude begin return decimal power_level end else if qname == string Output b...
def performGetValue(self, quant, options={}): qname = quant.name params = RFParameters() self._lib.sc5520a_uhfsFetchRfParameters(self._handle, params) if qname == 'Frequency': return float(params.frequency) elif qname == 'Amplitude': return float(params.po...
Python
nomic_cornstack_python_v1
function register_data_files self *files task=none run=none begin set files = list comprehension call Path f for f in files for file in files begin if suffix not in DATA_EXTENSIONS begin raise call ValueError string Wrong file format of data { suffix } . Valid formats are { DATA_EXTENSIONS } end end set key = string i...
def register_data_files(self, *files, task=None, run=None): files = [Path(f) for f in files] for file in files: if file.suffix not in DATA_EXTENSIONS: raise ValueError(f'Wrong file format of data {file.suffix}. ' f'Valid formats are {DATA_EXT...
Python
nomic_cornstack_python_v1
function test_get_suggestion_compare_interest_suggestion self begin comment Client type Request set client = call Client comment Bob the social aware has no interests in common with Bob the artist comment Bob the social aware selects a selectable item from page 1 post uri_add_selectable + token + string / content_type=...
def test_get_suggestion_compare_interest_suggestion(self): # Client type Request client = Client() # Bob the social aware has no interests in common with Bob the artist # Bob the social aware selects a selectable item from page 1 client.post(self.uri_add_selectable+self.bob_the_socialaware_twin_profile.token+...
Python
nomic_cornstack_python_v1
function test_post_overlapping_timespan_not_allowed_overlaps_exactly self begin set post_data = call _get_default_post_data set response2 = post list_url HTTP_AUTHORIZATION=string Bearer %s % token format=string json data=post_data assert equal status_code HTTP_201_CREATED call assertOutOfHoursRotaCheckResponseKeys res...
def test_post_overlapping_timespan_not_allowed_overlaps_exactly(self): post_data = self._get_default_post_data() response2 = self.client.post( self.list_url, HTTP_AUTHORIZATION="Bearer %s" % self.token, format="json", data=post_data ) self.assertEqual(response2.status_code, ...
Python
nomic_cornstack_python_v1
function test_case_2 size begin set tuple a b = call createArray_2 size set start = performance counter call Gauss_2 a b set end = performance counter return end - start * 1000 end function
def test_case_2(size): a, b = createArray_2(size) start = time.perf_counter() Gauss_2(a, b) end = time.perf_counter() return (end - start) * 1000
Python
nomic_cornstack_python_v1
function user_profile begin if string username in session begin return call redirect string /profile/ + session at string username end return call redirect string / end function
def user_profile() -> object: if "username" in session: return redirect("/profile/" + session["username"]) return redirect("/")
Python
nomic_cornstack_python_v1
import mysql.connector from mysql.connector import errorcode import datetime function write_values category_name link created updated begin try begin set db_connection = call connect host=string 127.0.0.1 user=string root password=string root database=string carrefourdb set cursor = call cursor set add_category = strin...
import mysql.connector from mysql.connector import errorcode import datetime def write_values(category_name, link, created, updated): try: db_connection = mysql.connector.connect( host="127.0.0.1", user="root", password="root", database='carrefourdb' ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Jun 10 11:07:29 2020 @author: David Palecek from exp import Exp set __all__ = list string Static class Static extends Exp begin string Static experiments class function __init__ self dir_save begin call __init__ dir_save set info = string Class instance of { __class__...
# -*- coding: utf-8 -*- """ Created on Wed Jun 10 11:07:29 2020 @author: David Palecek """ from .exp import Exp __all__ = ['Static'] class Static(Exp): ''' Static experiments class ''' def __init__(self, dir_save): super().__init__(dir_save) self.info = f'Class instance of {self.__cla...
Python
zaydzuhri_stack_edu_python
import json import os import glob import cv2 set annotations_info = dict string images list ; string annotations list ; string categories list set CLASS_NAME = tuple string __background__ string plane string baseball-diamond string bridge string ground-track-field string small-vehicle string large-vehicle string shi...
import json import os import glob import cv2 annotations_info = {'images': [], 'annotations': [], 'categories': []} CLASS_NAME = ('__background__','plane', 'baseball-diamond', 'bridge', 'ground-track-field', 'small-vehicle', 'large-vehicle', 'ship', 'tennis-court', 'basketball-court',...
Python
jtatman_500k
function test self pix_ind=none show_plots=true begin if mpi_rank > 0 begin return end if pix_ind is none begin set pix_ind = random integer 0 high=shape at 0 end set other_params = copy parms_dict comment removing duplicates: set _ = pop other_params string freq return call bayesian_inference_on_period h5_main at pix_...
def test(self, pix_ind=None, show_plots=True): if self.mpi_rank > 0: return if pix_ind is None: pix_ind = np.random.randint(0, high=self.h5_main.shape[0]) other_params = self.parms_dict.copy() # removing duplicates: _ = other_params.pop('freq') r...
Python
nomic_cornstack_python_v1
function skip_column self column_property begin set column = columns at 0 if not include_primary_keys and primary_key or foreign_keys begin return true end if _is_polymorphic_discriminator begin return true end if not include_datetimes_with_default and is instance type DateTime and default begin return true end if only...
def skip_column(self, column_property): column = column_property.columns[0] if (not self.meta.include_primary_keys and column.primary_key or column.foreign_keys): return True if column_property._is_polymorphic_discriminator: return True if (not s...
Python
nomic_cornstack_python_v1
function JENKINS self value begin import logging set msg = if expression is instance value tuple then value at 0 else value set level = if expression is instance value tuple and length value > 1 and is instance value at 1 int then value at 1 else none set secured = if expression is instance value tuple and length value...
def JENKINS(self, value): import logging msg = value[0] if isinstance(value, tuple) else value level = value[1] if isinstance(value, tuple) and len(value) > 1 and isinstance(value[1], int) else None secured = value[2] if isinstance(value, tuple) and len(value) > 2 and isinstance(value[2]...
Python
nomic_cornstack_python_v1
function delete_request self endpoint params expected_http_codes=none extra_headers=none begin return call _do_request endpoint params string delete expected_http_codes extra_headers end function
def delete_request(self, endpoint, params, expected_http_codes=None, extra_headers=None): return self._do_request( endpoint, params, 'delete', expected_http_codes, extra_headers, )
Python
nomic_cornstack_python_v1
comment ============================================================================= comment IMPORTS comment ============================================================================= import torch from espaloma.nn.readout.base_readout import BaseReadout comment ======================================================...
# ============================================================================= # IMPORTS # ============================================================================= import torch from espaloma.nn.readout.base_readout import BaseReadout # ===========================================================================...
Python
jtatman_500k
import operacoes_carrinho function por_album conn cur id nome begin print string print string Usuario: nome print string ORDERNAR POR ÁLBUM comment imprime albuns por ordem ascendente execute cur string SELECT id, nome FROM album ORDER BY nome ASC for linha in call fetchall begin print string ID: linha at 0 string | No...
import operacoes_carrinho def por_album(conn,cur, id, nome): print('\n') print('Usuario:', nome) print('ORDERNAR POR ÁLBUM') # imprime albuns por ordem ascendente cur.execute("SELECT id, nome FROM album ORDER BY nome ASC") for linha in cur.fetchall(): print("ID:", linha[0], " | Nome:",...
Python
zaydzuhri_stack_edu_python
comment Python Loops 3 comment For Loop comment The range() Function for x in range 6 begin print x end comment Using the start parameter for x in range 2 6 begin print x end comment Increment the sequence with 3 for x in range 5 40 5 begin print x end comment Else in For Loop for x in range 4 begin print x end for els...
# Python Loops 3 # For Loop #The range() Function for x in range(6): print(x) #Using the start parameter for x in range (2, 6): print (x) #Increment the sequence with 3 for x in range (5, 40, 5): print(x) #Else in For Loop for x in range(4): print(x) else: print("final...
Python
zaydzuhri_stack_edu_python
function daemon_factory path begin string Create a closure which creates a running daemon. We need to create a closure that contains the correct path the daemon should be started with. This is needed as the `Daemonize` library requires a callable function for daemonization and doesn't accept any arguments. This functio...
def daemon_factory(path): """Create a closure which creates a running daemon. We need to create a closure that contains the correct path the daemon should be started with. This is needed as the `Daemonize` library requires a callable function for daemonization and doesn't accept any arguments. This...
Python
jtatman_500k
class Graph begin function __init__ self graph_dict=dict begin set _graph_dict = graph_dict end function function add_vertex self vertex begin if vertex not in _graph_dict begin set _graph_dict at vertex = list end end function function add_edge self edge begin set tuple vertex1 vertex2 = edge if vertex1 in _graph_dic...
class Graph: def __init__(self,graph_dict = {}): self._graph_dict = graph_dict def add_vertex(self,vertex): if vertex not in self._graph_dict: self._graph_dict[vertex] = [] def add_edge(self,edge): (vertex1,vertex2) = edg...
Python
zaydzuhri_stack_edu_python
function _stepadjust self m begin comment Compute values under Laplace approximation. This is the policy comment that the previous samples were actually drawn from under the comment dynamics that were estimated from the previous samples. set tuple prev_laplace_obj prev_laplace_kl = call _estimate_cost traj_distr traj_i...
def _stepadjust(self, m): # Compute values under Laplace approximation. This is the policy # that the previous samples were actually drawn from under the # dynamics that were estimated from the previous samples. prev_laplace_obj, prev_laplace_kl = self._estimate_cost( self.p...
Python
nomic_cornstack_python_v1
function delete_file_systems_policies self members=none policies=none member_ids=none member_names=none policy_ids=none policy_names=none async_req=false _return_http_data_only=false _preload_content=true _request_timeout=none begin comment type: List[models.ReferenceType] comment type: List[models.ReferenceType] comme...
def delete_file_systems_policies( self, members=None, # type: List[models.ReferenceType] policies=None, # type: List[models.ReferenceType] member_ids=None, # type: List[str] member_names=None, # type: List[str] policy_ids=None, # type: List[str] policy_names=...
Python
nomic_cornstack_python_v1
set A = integer input set B = integer input set N = integer input set costOfOne = A * 100 + B set totalCost = costOfOne * N set rub = totalCost // 100 set kop = totalCost % 100 print rub kop
A = int(input()) B = int(input()) N = int(input()) costOfOne = A * 100 + B totalCost = costOfOne * N rub = totalCost // 100 kop = totalCost % 100 print(rub, kop)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Nov 30 11:41:23 2014 @author: Philip figure set abs_diff1 = absolute diff_th1 at tuple slice : : 2 set abs_diff2 = absolute diff_th2 at tuple slice : : 2 set max_diff = max call nanmax abs_diff1 call nanmax abs_diff2 set hist_range = tuple - 1 * max_diff max_dif...
# -*- coding: utf-8 -*- """ Created on Sun Nov 30 11:41:23 2014 @author: Philip """ plt.figure() abs_diff1=np.abs(diff_th1[:,2]) abs_diff2=np.abs(diff_th2[:,2]) max_diff=max(np.nanmax(abs_diff1), np.nanmax(abs_diff2)) hist_range=(-1*max_diff, max_diff) n, bins, patches = plt.hist(diff_th1[:,2], binNum, range=hist_ran...
Python
zaydzuhri_stack_edu_python
import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import CategoricalNB from sklearn.preprocessing import Normalizer from sklearn.pipeline import Pipelin...
import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import CategoricalNB from sklearn.preprocessing import Normalizer from sklearn.pipeline import Pipelin...
Python
zaydzuhri_stack_edu_python
function testcrcpoly begin for a in tuple 69665 98309 66953 22900171 25578747 1613806023 4374732215 begin set a = call BinaryPolynomial a for p in call genprimes begin print boolean a % p end=string if call order * 2 > call order begin break end end print end end function
def testcrcpoly(): for a in (0x11021, 0x18005, 0x10589, 0x15D6DCB, 0x1864CFB, 0x6030B9C7, 0x104C11DB7): a = BinaryPolynomial(a) for p in genprimes(): print(bool(a%p), end=" ") if p.order()*2>a.order(): break print()
Python
nomic_cornstack_python_v1
function classify self a begin assert type a is HandwrittenData comment key: formula_id, value: (dtw, Handwriting) (lowest prefered) set best_by_symbol = dict for dataset in datasets begin set b = dataset at string handwriting set d = call handwritten_data_greedy_matching_distance a b if d < threshold begin if formula...
def classify(self, a): assert type(a) is HandwrittenData.HandwrittenData # key: formula_id, value: (dtw, Handwriting) (lowest prefered) best_by_symbol = {} for dataset in self.datasets: b = dataset['handwriting'] d = distance_metric.handwritten_data_greedy_matc...
Python
nomic_cornstack_python_v1
while spam < 5 begin print string Hello World! set spam = spam + 1 end comment -------------------- comment Programmer humor set name = string while name != string your name begin print string Please type your name. set name = input end print string Thank you! comment --------------------- comment A break ceases the e...
while spam <5: print('Hello World!') spam = spam + 1 #-------------------- name = '' # Programmer humor while name != 'your name': print('Please type your name.') name = input() print('Thank you!') #--------------------- # A break ...
Python
zaydzuhri_stack_edu_python
comment 3shan ne3raf el most common question (including el user) import pandas as pd import numpy as np import math set data = read csv string sample.csv function checkOtherUsers current_problem ids dataset begin set occurrence = 0 for user in ids begin set index = index at dataset at string user_id == user set temp_us...
# 3shan ne3raf el most common question (including el user) import pandas as pd import numpy as np import math data = pd.read_csv("sample.csv") def checkOtherUsers( current_problem, ids, dataset ): occurrence = 0 for user in ids: index = dataset.index[dataset['user_id'] == user] temp_user = dataset.loc[index] ...
Python
zaydzuhri_stack_edu_python
comment coding=UTF8 import sys from converter_printer import ConverterPrinter from query_loader import ConverterQueryLoader from converter_reader import * from converter_normalizer import ConverterNormalizer from query_loader import Query function download_data latitudeSouth longitudeWest latitudeNorth longitudeEast be...
# coding=UTF8 import sys from converter_printer import ConverterPrinter from query_loader import ConverterQueryLoader from converter_reader import * from converter_normalizer import ConverterNormalizer from query_loader import Query def download_data(latitudeSouth, longitudeWest, latitudeNorth, longitudeEast): que...
Python
zaydzuhri_stack_edu_python
import math comment T H E S P I C E M U S T F L O W set m0 = integer input string Launch mass: set mf = integer input string Dry mass: set Ve = integer input string Exaust Velocity: set Isp = integer input string Specific Impulse: set fuelMass = m0 - mf set Δv = Isp * 9.8 * log decimal m0 / mf print string Δv: print Δv...
import math #T H E S P I C E M U S T F L O W m0 = int(input("\n \n Launch mass: ")) mf = int(input("Dry mass: ")) Ve = int(input("Exaust Velocity: ")) Isp = int(input("Specific Impulse: ")) fuelMass = m0 - mf Δv = Isp*9.8*math.log(float(m0/mf)) print("Δv:") print(Δv) print("Fuel Mass:") print(fuel...
Python
zaydzuhri_stack_edu_python
function create cls **dictionary begin if __name__ == string Rectangle begin set temp = call cls width=6 height=9 end if __name__ == string Square begin set temp = call cls size=69 end update temp keyword dictionary return temp end function
def create(cls, **dictionary): if cls.__name__ == "Rectangle": temp = cls(width=6, height=9) if cls.__name__ == "Square": temp = cls(size=69) temp.update(**dictionary) return temp
Python
nomic_cornstack_python_v1
function _displayThemeStateChanged self p_theme p_state begin set l_titleMsg = string Status Thema Gewijzigd set l_msg = string Status is nu %s voor thema %s % tuple p_state string p_theme call information self l_titleMsg l_msg end function
def _displayThemeStateChanged(self, p_theme, p_state): l_titleMsg = "Status Thema Gewijzigd" l_msg = "Status is nu %s voor thema %s" % (p_state, str(p_theme)) QMessageBox.information(self, l_titleMsg, l_msg)
Python
nomic_cornstack_python_v1
from game_engine import game_engine function move board i player begin if board at i == 0 begin set board at i = player end return board end function function rep v begin if v == 0 begin return string end else if v == 1 begin return string X end else begin return string 0 end end function function draw_line one two th...
from game_engine import game_engine def move(board, i, player): if board[i] == 0: board[i] = player return board def rep(v): if v == 0: return " " elif v == 1: return "X" else: return "0" def draw_line(one, two, three): print(" " + rep(one) + " | " + rep(two) + " | " + rep(three)) def draw_board(boa...
Python
zaydzuhri_stack_edu_python
function update_triples self graph_type turtle commit_msg begin comment TODO: make triples works again raise call InterfaceError string update_triples is temporary not avaliable in this version call _check_connection call _validate_graph_type graph_type set params = dict string commit_info call _generate_commit commit_...
def update_triples(self, graph_type: str, turtle, commit_msg: str) -> None: ### TODO: make triples works again raise InterfaceError( "update_triples is temporary not avaliable in this version" ) self._check_connection() self._validate_graph_type(graph_type) p...
Python
nomic_cornstack_python_v1
function multiply num1 num2 begin comment Convert the input strings to lists of integers set num1 = list comprehension integer digit for digit in num1 set num2 = list comprehension integer digit for digit in num2 comment Reverse the lists to start from the least significant digit reverse num1 reverse num2 comment Initi...
def multiply(num1, num2): # Convert the input strings to lists of integers num1 = [int(digit) for digit in num1] num2 = [int(digit) for digit in num2] # Reverse the lists to start from the least significant digit num1.reverse() num2.reverse() # Initialize a result list with zeros resul...
Python
jtatman_500k
function dbconfig user passwd dbname echo_i=false begin comment str1 = ('postgresql+pg8000://' + user +':' + passwd + '@switch-db2.erg.berkeley.edu:5433/' comment + dbname + '?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory') set str1 = string postgresql+psycopg2:// + user + string : + passwd + string @swit...
def dbconfig(user,passwd,dbname, echo_i=False): #str1 = ('postgresql+pg8000://' + user +':' + passwd + '@switch-db2.erg.berkeley.edu:5433/' # + dbname + '?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory') str1 = ('postgresql+psycopg2://'+user+':'+ passwd + '@switch-db2.erg.berkeley....
Python
nomic_cornstack_python_v1
class Map begin function __init__ self width height begin set width = width set height = height set walls = list set weights = dict end function comment creates a list of the wall locations for the new Map comment each item in the walls list is a tuple where the location tuple represents the index in the original arr...
class Map: def __init__(self, width, height): self.width = width self.height = height self.walls = [] self.weights = {} # creates a list of the wall locations for the new Map # each item in the walls list is a tuple where the location tuple represents the index in the origin...
Python
zaydzuhri_stack_edu_python
import sys set stdin = open string 11724.txt string r string 무방향그래프의 연결요소 개수 출력 연결요소란 원그래프 G 가운데 노드와 엣지가 서로 겹치지 않는 부그래프이되, 부그래프 내 모든 노드쌍에 대해 경로가 존재하는 걸 가리킵니다. string for문에 실행될 원소가 없는 경우 cnt도 더해지지 않는다. visited = [False]*100 cnt = 0 a = [] for i in a: print('---', i) print('----for문 안에 있어요-----') cnt += 1 if visited[a] =...
import sys sys.stdin = open('11724.txt', 'r') ''' 무방향그래프의 연결요소 개수 출력 연결요소란 원그래프 G 가운데 노드와 엣지가 서로 겹치지 않는 부그래프이되, 부그래프 내 모든 노드쌍에 대해 경로가 존재하는 걸 가리킵니다. ''' ''' for문에 실행될 원소가 없는 경우 cnt도 더해지지 않는다. visited = [False]*100 cnt = 0 a = [] for i in a: print('---', i) print('----for문 안에 있어요-----') cnt += 1 if vi...
Python
zaydzuhri_stack_edu_python
function _create_dataset self node begin set dataset_node = node set creating = call create_dataset primary=uuid comment Not sure about handling errors and timeout in the same errback. comment How could I handle them differently? function handle_timeout_and_errors failure begin call trap CancelledError raise call Datas...
def _create_dataset(self, node): self.dataset_node = node creating = self.control_service.create_dataset( primary=node.uuid) # Not sure about handling errors and timeout in the same errback. # How could I handle them differently? def handle_timeout_and_errors(failure...
Python
nomic_cornstack_python_v1
function is_prime n begin if n < 2 begin return false end for i in range 2 integer n ^ 0.5 + 1 begin if n % i == 0 begin return false end end return true end function function sum_of_primes arr begin return sum generator expression num for num in arr if call is_prime num end function set arr = list 1 2 3 4 5 6 7 8 9 10...
def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def sum_of_primes(arr): return sum(num for num in arr if is_prime(num)) arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(sum_of_primes(arr)) # Output: 17 (2 + 3 ...
Python
jtatman_500k
comment By: Justin Chase comment Find Test Development/QA job parsing the postings on Coinality import json import urllib2 set keywords = list string test string Test string QA string qa string Qa set coinalityurl = string https://coinality.com/api/jobs
#By: Justin Chase #Find Test Development/QA job parsing the postings on Coinality import json import urllib2 keywords = ['test', 'Test', 'QA', 'qa', 'Qa'] coinalityurl = 'https://coinality.com/api/jobs'
Python
zaydzuhri_stack_edu_python
from crypto import * function test_letter_frequencies begin set alphabet = string abcdefghijklmnopqrstuvwxyz set alph_freqs = call letter_frequencies alphabet for tuple i j in call iteritems begin assert j == 1.0 / 26.0 end end function function test_split begin set alphabet = string abcdefghijklmnopqrstuvwxyz set empt...
from crypto import * def test_letter_frequencies(): alphabet = "abcdefghijklmnopqrstuvwxyz" alph_freqs = letter_frequencies(alphabet) for i, j in alph_freqs.iteritems(): assert j == 1.0/26.0 def test_split(): alphabet = "abcdefghijklmnopqrstuvwxyz" empty = "" assert split(empty, 4) == ...
Python
zaydzuhri_stack_edu_python
from array import array from conjuntos import conjunto from filas import fila from pilhas import pilha from listas import lista_ligada , lista_duplamente_ligada from vetores import vetor from mapas import mapa from arvores import arvore , no_arvore_inteiro comment vetor_inteiros = array('b', [1,2,3]) comment print(veto...
from array import array from conjuntos import conjunto from filas import fila from pilhas import pilha from listas import lista_ligada, lista_duplamente_ligada from vetores import vetor from mapas import mapa from arvores import arvore, no_arvore_inteiro #vetor_inteiros = array('b', [1,2,3]) #print(vetor_inteiros) #v...
Python
zaydzuhri_stack_edu_python
async function on_message_delete message begin if id in users begin pop users id none end end function
async def on_message_delete(message): if message.author.id in users: users.pop(message.author.id, None)
Python
nomic_cornstack_python_v1
class Student begin function __init__ self name begin set name = name end function end class class Graduate extends Student begin function __init__ self name graduation_date begin call __init__ name set graduation_date = graduation_date end function end class
class Student: def __init__(self, name): self.name = name class Graduate(Student): def __init__(self, name, graduation_date): super().__init__(name) self.graduation_date = graduation_date
Python
zaydzuhri_stack_edu_python
from tkinter import * class Table begin string A simple class for representing data (tuples embedded in list) in the form of a table function __init__ self parent data_list begin set parent = parent set data_list = data_list set total_rows = length data_list set total_columns = length data_list at 0 call create_table c...
from tkinter import * class Table: """ A simple class for representing data (tuples embedded in list) in the form of a table """ def __init__(self, parent, data_list: list): self.parent = parent self.data_list = data_list self.total_rows = len(data_list) self.total_...
Python
zaydzuhri_stack_edu_python
function date_to_filename base_path raw_date_string begin set raw_date_string = raw_date_string at slice : - 1 : set tuple month day year = split raw_date_string string / set relative_path = format string {}/{}/{}.md year month day return base_path / relative_path end function
def date_to_filename(base_path, raw_date_string): raw_date_string = raw_date_string[:-1] month, day, year = raw_date_string.split("/") relative_path = "{}/{}/{}.md".format(year, month, day) return base_path / relative_path
Python
nomic_cornstack_python_v1
comment %% import itertools set num = list map int split input set sum_list = list comprehension sum i for i in call combinations num 3 sort sum_list reverse=true print sum_list at 2
#%% import itertools num = list(map(int, input().split())) sum_list = [sum(i) for i in itertools.combinations(num, 3)] sum_list.sort(reverse=True) print(sum_list[2])
Python
zaydzuhri_stack_edu_python
import numpy as np function get_AP df qid k begin string df : pandas df with a 'score' column indicating a score based on some model return: Average Precision for a given query AP = sum(precision(i) * relevancy(i)) / (num of relevant docs) comment consider only the relevant documents set relevant_docs = df at df at str...
import numpy as np def get_AP(df, qid, k): """ df : pandas df with a 'score' column indicating a score based on some model return: Average Precision for a given query AP = sum(precision(i) * relevancy(i)) / (num of relevant docs) """ # consider only the relevant documents relevant_do...
Python
zaydzuhri_stack_edu_python
from __future__ import print_function , unicode_literals from PyInquirer import style_from_dict , Token , prompt class AskOptions begin function __init__ self message choices name begin set message = message set choices = choices set name = name set style = call style_from_dict dict Separator string #cc5454 ; QuestionM...
from __future__ import print_function, unicode_literals from PyInquirer import style_from_dict, Token, prompt class AskOptions: def __init__(self, message, choices, name): self.message = message self.choices = choices self.name = name self.style = style_from_dict({ ...
Python
zaydzuhri_stack_edu_python
string 练习1: index.html 这个网页内容显示在浏览器上 要求,浏览器可以多次访问 from socket import * comment 创建tcp套接字 set s = call socket call bind tuple string 0.0.0.0 8888 call listen 5 while true begin set tuple c addr = call accept comment 浏览器连接 print string Connect from addr comment 接收的是http请求 set data = call recv 4096 comment 请求行 print split ...
""" 练习1: index.html 这个网页内容显示在浏览器上 要求,浏览器可以多次访问 """ from socket import * # 创建tcp套接字 s = socket() s.bind(("0.0.0.0",8888)) s.listen(5) while True: c,addr = s.accept() print("Connect from",addr) # 浏览器连接 data = c.recv(4096) # 接收的是http请求 print(data.decode().split('\n')[0]) # 请求行 # http响应格式 f = o...
Python
zaydzuhri_stack_edu_python
function evaluate self begin set batch_losses = list set all_predictions = list for tuple inputs targets in _test_data begin set inputs = tensor inputs set targets = tensor targets at tuple slice : : _use_testmat_ixs if use_cuda begin set inputs = cuda inputs set targets = cuda targets end with no grad begin set p...
def evaluate(self): batch_losses = [] all_predictions = [] for (inputs, targets) in self._test_data: inputs = torch.Tensor(inputs) targets = torch.Tensor(targets[:, self._use_testmat_ixs]) if self.use_cuda: inputs = inputs.cuda() ...
Python
nomic_cornstack_python_v1
async function snowflake self ctx *snowflakes begin if not snowflakes begin raise call BadArgument string At least one snowflake must be provided. end set embed = call Embed colour=call blue call set_author name=string Snowflake { string s at slice : length snowflakes ? 1 : } icon_url=string https://github.com/twitte...
async def snowflake(self, ctx: Context, *snowflakes: Snowflake) -> None: if not snowflakes: raise BadArgument("At least one snowflake must be provided.") embed = Embed(colour=Colour.blue()) embed.set_author( name=f"Snowflake{'s'[:len(snowflakes)^1]}", # Deals with plura...
Python
nomic_cornstack_python_v1
import os import sys set path = argv at 1 set oldWord = argv at 2 set newWord = argv at 3 set counter = 0 for file in list directory path begin if oldWord in call splitext file at 0 begin set counter = counter + 1 rename path + string \ + file path + string \ + replace file oldWord newWord end end print string counter ...
import os; import sys; path = sys.argv[1] oldWord = sys.argv[2] newWord = sys.argv[3] counter = 0 for file in os.listdir(path): if oldWord in os.path.splitext(file)[0]: counter = counter + 1 os.rename(path + "\\"+file, path + "\\"+file.replace(oldWord, newWord)) print(str(counter)+ " files have ...
Python
zaydzuhri_stack_edu_python
import streamlit as st from PIL import Image import os call set_page_config page_title=string Art page_icon=string 🎭 layout=string centered initial_sidebar_state=string expanded set app_state = call experimental_get_query_params if string region in keys app_state begin set region = app_state at string region at 0 end ...
import streamlit as st from PIL import Image import os st.set_page_config( page_title="Art", page_icon="🎭", layout="centered", initial_sidebar_state="expanded", ) app_state = st.experimental_get_query_params() if 'region' in app_state.keys(): region = app_state['region'][0] else: region = 'du...
Python
zaydzuhri_stack_edu_python
function clean_names infile outfile=DEFAULT_OUTPUT col=string Name all=false begin print string Processing and exporting, please wait... set ROMAN = list string I string II string III string IV string V string VI string VII string VIII string IX string X if outfile begin try begin set of = open outfile string w end exc...
def clean_names(infile, outfile=DEFAULT_OUTPUT, col="Name", all=False): print("Processing and exporting, please wait...") ROMAN = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'] if outfile: try: of = open(outfile, 'w') except: outfile = None with o...
Python
nomic_cornstack_python_v1
import Modules call greeting string Ivan comment Note: When using a function from a module, comment use the syntax: module_name.function_name. set age = person1 at string age print age comment Built-in Modules import platform as pltf set x = call system comment Windows print x comment Using the dir() function set y = d...
import Modules Modules.greeting("Ivan") #Note: When using a function from a module, #use the syntax: module_name.function_name. age = Modules.person1["age"] print(age) # Built-in Modules import platform as pltf x = pltf.system() print(x) #Windows # Using the dir() function y = dir(pltf) #prin...
Python
zaydzuhri_stack_edu_python
import numpy as np import torch import torch.nn as nn import torch.optim as optim import gym class QLearn begin function __init__ self net e=0.2 discount_rate=0.8 alpha=0.1 begin set net = net set actions = list 0.0 1.0 set e = e set discount_rate = discount_rate set alpha = alpha set previous_state = none end function...
import numpy as np import torch import torch.nn as nn import torch.optim as optim import gym class QLearn: def __init__(self, net, e=0.2, discount_rate=0.8, alpha=0.1): self.net = net self.actions = [0.0, 1.0] self.e = e self.discount_rate = discount_rate self.alpha = alpha...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ load_balancer_name resource_group_name backend_address_pool=none backend_port=none enable_floating_ip=none enable_tcp_reset=none frontend_ip_configuration=none frontend_port=none frontend_port_range_end=none frontend_port_range_start=none id=none idle_timeout_in_minutes=none inbound_nat_rule_...
def __init__(__self__, *, load_balancer_name: pulumi.Input[str], resource_group_name: pulumi.Input[str], backend_address_pool: Optional[pulumi.Input['SubResourceArgs']] = None, backend_port: Optional[pulumi.Input[int]] = None, enable_f...
Python
nomic_cornstack_python_v1
import codecs import logging import numpy as np import gensim from sklearn.cluster import KMeans import shelve call basicConfig level=INFO format=string %(asctime)s %(levelname)s %(message)s set logger = call getLogger __name__ class W2VEmbReader begin function __init__ self emb_path vocab emb_dim=none begin info strin...
import codecs import logging import numpy as np import gensim from sklearn.cluster import KMeans import shelve logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') logger = logging.getLogger(__name__) class W2VEmbReader: def __init__(self, emb_path, vocab, ...
Python
zaydzuhri_stack_edu_python
set name = string Eric print upper name print lower name print title name
name ="Eric" print(name.upper()) print(name.lower()) print(name.title())
Python
zaydzuhri_stack_edu_python
from nsepy import get_history import pandas as pd import matplotlib.pyplot as plt import datetime as dt set start_date = call datetime 2018 1 1 set end_date = today comment define each and everything to perform the operation function PPSR data begin set PP = call Series data at string High + data at string Low + data a...
from nsepy import get_history import pandas as pd import matplotlib.pyplot as plt import datetime as dt start_date = dt.datetime(2018, 1, 1) end_date = dt.datetime.today() #define each and everything to perform the operation def PPSR(data): PP = pd.Series((data['High'] + data['Low'] + data['Close']) / 3) R1...
Python
zaydzuhri_stack_edu_python
comment !/bin/python from __future__ import print_function import os import sys comment Complete the getTotalX function below. function getTotalX a b begin comment 1. find LCM of a comment 2. find GCD of b comment 3. count the number of multiples of LCM that evenly divides the GCD comment a_gcd = findGCD(a) comment a_l...
#!/bin/python from __future__ import print_function import os import sys # # Complete the getTotalX function below. # def getTotalX(a, b): # # 1. find LCM of a # 2. find GCD of b # 3. count the number of multiples of LCM that evenly divides the GCD # # a_gcd = findGCD(a) # a_lcm = ...
Python
zaydzuhri_stack_edu_python
function make_album name_musician name_album countyty=string begin set make_alb = dict string name_mus name_musician ; string name_alb name_album if countyty begin set make_alb at string countyty = countyty end return make_alb end function set var1 = call make_album string one string two print var1 set var2 = call make...
def make_album(name_musician, name_album, countyty=''): make_alb = {'name_mus': name_musician, 'name_alb': name_album} if countyty: make_alb['countyty'] = countyty return make_alb var1 = make_album('one', 'two') print(var1) var2 = make_album('three', 'four') print(var2) var3 = make_album('five', 'se...
Python
zaydzuhri_stack_edu_python
function from_int cls i begin string Create a :class:`FilePerms` object from an integer. >>> FilePerms.from_int(0o644) # note the leading zero-oh for octal FilePerms(user='rw', group='r', other='r') set i = i ? FULL_PERMS set key = tuple string string x string w string xw string r string rx string rw string rwx set pa...
def from_int(cls, i): """Create a :class:`FilePerms` object from an integer. >>> FilePerms.from_int(0o644) # note the leading zero-oh for octal FilePerms(user='rw', group='r', other='r') """ i &= FULL_PERMS key = ('', 'x', 'w', 'xw', 'r', 'rx', 'rw', 'rwx') part...
Python
jtatman_500k
while true begin set name = input string Enter name: if name != string Narayan begin continue print string Hello name string enter your password end set pwd = input string Enter password: if pwd == string Family@143 begin print string You entered coorect details print string Congratulation name break end end print stri...
while True: name = input("Enter name:") if name != 'Narayan' : continue print("Hello",name,"enter your password") pwd=input("Enter password:") if pwd == 'Family@143': print("You entered coorect details") print("Congratulation",name) break print("Thank You")
Python
zaydzuhri_stack_edu_python
function del_selector *args begin return call del_selector *args end function
def del_selector(*args): return _ida_segment.del_selector(*args)
Python
nomic_cornstack_python_v1
for D in values begin set Q = list round 2 * C * D / H ^ 0.5 end print Q sep=string ,
for D in values: Q = [round(((2*C*D)/H)**0.5)] print(Q,sep=',')
Python
zaydzuhri_stack_edu_python
function set_property key value replace=false begin set lines = list try begin with open local_properties string r as f begin for l in f begin set k = strip call partition string = at 0 if k == key begin if not replace begin return end else begin continue end end append lines l end end end except any begin pass end wi...
def set_property(key, value, replace=False): lines = [ ] try: with open(local_properties, "r") as f: for l in f: k = l.partition("=")[0].strip() if k == key: if not replace: return else: ...
Python
nomic_cornstack_python_v1
function linear_least_squares x y begin string Takes two arrays which pair into points (x,y) for linearly varying data. Uses linear regression to find the slope and y-intercept of the best fit line. Returns a 4-tuple (slope,intercept,slope uncertainty,intercept uncertainty) import numpy as np set x_avg = sum x * 1.0 / ...
def linear_least_squares(x,y): """ Takes two arrays which pair into points (x,y) for linearly varying data. Uses linear regression to find the slope and y-intercept of the best fit line. Returns a 4-tuple (slope,intercept,slope uncertainty,intercept uncertainty) """ import numpy as np ...
Python
zaydzuhri_stack_edu_python
function getProjectPlatforms self testprojectid devkey=none begin return call _query string tl.getProjectPlatforms devKey=devkey testprojectid=testprojectid end function
def getProjectPlatforms(self, testprojectid, devkey=None): return self._query("tl.getProjectPlatforms",\ devKey=devkey,\ testprojectid=testprojectid)
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math import os import random import re import sys comment Complete the 'timeConversion' function below. comment The function is expected to return a STRING. comment The function accepts STRING s as parameter. function timeConversion s begin comment Write your code here if ends with s string...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'timeConversion' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def timeConversion(s): # Write your code here if s.endswith("AM"): if s.startswith...
Python
zaydzuhri_stack_edu_python
function decode_labels mask num_images=1 num_classes=20 begin set tuple h w c = shape comment assert(n >= num_images), 'Batch size %d should be greater or equal than number of images to save %d.' % (n, num_images) set outputs = zeros tuple h w 3 dtype=uint8 set img = call new string RGB tuple length mask at 0 length ma...
def decode_labels(mask, num_images=1, num_classes=20): h, w, c = mask.shape #assert(n >= num_images), 'Batch size %d should be greater or equal than number of images to save %d.' % (n, num_images) outputs = np.zeros(( h, w, 3), dtype=np.uint8) img = Image.new('RGB', (len(mask[0]), len(mask))) pixel...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python string This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. Use a Naive Bayes Classifier to identify emails by their authors authors and labels: Sara has label 0 Chris has label 1 import sys from time import time append path string ../tools/ from email_preprocess import prepro...
#!/usr/bin/python """ This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. Use a Naive Bayes Classifier to identify emails by their authors authors and labels: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_prepro...
Python
zaydzuhri_stack_edu_python
function _pull self file_name names save=true force=false uri=string docker:// **kwargs begin string pull an image from a docker hub. This is a (less than ideal) workaround that actually does the following: - creates a sandbox folder - adds docker layers, metadata folder, and custom metadata to it - converts to a squas...
def _pull(self, file_name, names, save=True, force=False, uri="docker://", **kwargs): '''pull an image from a docker hub. This is a (less than ideal) workaround that actually does the following: - creates a sandbox folder - add...
Python
jtatman_500k
from tkinter import * from tkinter import ttk from tkinter import filedialog set gui = call Tk call geometry string 400x400 title gui string FC function getFolderPath begin set folder_selected = call askdirectory set folder_selected end function function doStuff begin set folder = get folderPath print string Doing stuf...
from tkinter import * from tkinter import ttk from tkinter import filedialog gui = Tk() gui.geometry("400x400") gui.title("FC") def getFolderPath(): folder_selected = filedialog.askdirectory() folderPath.set(folder_selected) def doStuff(): folder = folderPath.get() print("Doing stuff with folder", f...
Python
zaydzuhri_stack_edu_python
function min_noutput_items self begin return call turbo_encoder_sptr_min_noutput_items self end function
def min_noutput_items(self): return _my_lte_swig.turbo_encoder_sptr_min_noutput_items(self)
Python
nomic_cornstack_python_v1