code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
class Solution begin function maximumProduct self nums begin set n = length nums if n == 3 begin return nums at 0 * nums at 1 * nums at 2 end sort nums if nums at 0 >= 0 begin return nums at - 1 * nums at - 2 * nums at - 3 end if nums at - 1 <= 0 begin return nums at - 1 * nums at - 2 * nums at - 3 end if nums at 1 <= ...
class Solution: def maximumProduct(self, nums: List[int]) -> int: n = len(nums) if n == 3: return nums[0] * nums[1] * nums[2] nums.sort() if nums[0] >= 0: return nums[-1] * nums[-2] * nums[-3] if nums[-1] <=...
Python
zaydzuhri_stack_edu_python
function __repeat_timer interval function iterations args kwargs begin set count = 0 while iterations <= 0 or count < iterations begin sleep interval call function *args keyword kwargs set count = count + 1 end end function
def __repeat_timer(interval, function, iterations, args, kwargs): count = 0 while iterations <= 0 or count < iterations: sleep(interval) function(*args, **kwargs) count += 1
Python
nomic_cornstack_python_v1
function test_start_of_line self begin set before_b = string first line line 1 line a line b line c last line set after_b = string first line line 1 line a line b line c last line call run_test before_b=before_b after_b=after_b before_sel=tuple string 3.10 string 3.10 after_sel=tuple string 3.4 string 3.4 command_name=...
def test_start_of_line(self): before_b = """\ first line line 1 line a line b line c last line """ after_b = """\ first line line 1 line a line b line c last line """ self.run_test( before_b=before_b, ...
Python
nomic_cornstack_python_v1
class Solution extends object begin function generateParenthesis self n begin string :type n: int :rtype: List[str] set result = list call helper n n string result return result end function function helper self left right tmp result begin if left == 0 and right == 0 begin if tmp begin set result = result + tuple tmp...
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ result = [] self.helper(n, n, '', result) return result def helper(self, left, right, tmp, result): if left == 0 and right == 0: if tmp: ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import rospy , tf2_ros from geometry_msgs.msg import TransformStamped , Pose class Dummy begin function __init__ self begin call init_node string ZYang2_3002_dummy set rate = call Rate 100 set tf_buffer = call Buffer set tf_broadcaster = call TransformBroadcaster set tf_listener = call Tran...
#!/usr/bin/env python import rospy, tf2_ros from geometry_msgs.msg import TransformStamped, Pose class Dummy: def __init__(self): rospy.init_node('ZYang2_3002_dummy') self.rate = rospy.Rate(100) self.tf_buffer = tf2_ros.Buffer() self.tf_broadcaster = tf2_ros.TransformBroadcaste...
Python
zaydzuhri_stack_edu_python
function cross self vec begin if not is instance vec Vector3Array begin raise call TypeError string Cross product operand must be a Vector3Array end if nV != 1 and nV != 1 and nV != nV begin raise call ValueError string Cross product operands must have the same number of elements. end return call Vector3Array call cros...
def cross(self, vec): if not isinstance(vec, Vector3Array): raise TypeError('Cross product operand must be a Vector3Array') if self.nV != 1 and vec.nV != 1 and self.nV != vec.nV: raise ValueError('Cross product operands must have the same ' 'number of...
Python
nomic_cornstack_python_v1
function get self task_id begin string Gets a specific task, by ``task_id`` off the queue & runs it. Using this is not as performant (because it has to search the queue), but can be useful if you need to specifically handle a task *right now*. Ex:: # Tasks were previously added, maybe by a different process or # machin...
def get(self, task_id): """ Gets a specific task, by ``task_id`` off the queue & runs it. Using this is not as performant (because it has to search the queue), but can be useful if you need to specifically handle a task *right now*. Ex:: # Tasks were previously add...
Python
jtatman_500k
comment coding=utf-8 from Sample import * class LearningSet begin function __init__ self begin set samples = list end function function setValues self samples begin set out = dictionary for sample in samples begin if call getClass in out begin append out at call getClass sample end else begin set out at call getClass =...
# coding=utf-8 from Sample import * class LearningSet: def __init__ (self): self.samples = list() def setValues(self, samples): out = dict() for sample in samples: if sample.getClass() in out: out[sample.getClass()].append(sample) else: ...
Python
zaydzuhri_stack_edu_python
function onKeyDown event begin if keysym == string Escape begin call destroy end comment Missile controls (single-command version) if controlMode == BASIC begin if keysym == string Up begin call up end if keysym == string Down begin call down end if keysym == string Left begin call left end if keysym == string Right be...
def onKeyDown(event): if event.keysym == 'Escape': root.destroy() #Missile controls (single-command version) if missile.controlMode == ControlMode.BASIC: if event.keysym == 'Up': missile.up() if event.keysym == 'Down': missile.down() if event.keysym =...
Python
nomic_cornstack_python_v1
import pickle from flask import Flask , request , render_template from sklearn.feature_extraction.text import CountVectorizer from nltk.corpus import stopwords import string function text_process mess begin set nopunc = list comprehension char for char in mess if char not in punctuation set nopunc = join string nopunc...
import pickle from flask import Flask,request,render_template from sklearn.feature_extraction.text import CountVectorizer from nltk.corpus import stopwords import string def text_process(mess): nopunc=[char for char in mess if char not in string.punctuation] nopunc="".join(nopunc) return [word for word in...
Python
zaydzuhri_stack_edu_python
function rotationalCipher input rotation_factor begin comment Write your code here set res = string set lower = ordinal string a set upper = ordinal string A for i in input begin if is alphanumeric str i begin if call isnumeric i begin set res = res + string integer i + rotation_factor % 10 end else if is upper str i ...
def rotationalCipher(input, rotation_factor): # Write your code here res = '' lower = ord('a') upper = ord('A') for i in input: if str.isalnum(i): if str.isnumeric(i): res = res + str((int(i) + rotation_factor) % 10) elif str.isupper(i): ...
Python
zaydzuhri_stack_edu_python
function get_prod_penalty nnet begin assert ocsvm_loss is true set penalty = 0 set layers = trainable_layers comment do not regularize parameters of oc-svm layer set num_layers = length layers - 1 assert num_layers > 0 set W_norm_prod = 1.0 if b is not none begin set penalty = penalty + sum b ^ 2 end for i in range num...
def get_prod_penalty(nnet): assert Cfg.ocsvm_loss is True penalty = 0 layers = nnet.trainable_layers num_layers = len(layers) - 1 # do not regularize parameters of oc-svm layer assert num_layers > 0 W_norm_prod = 1.0 if layers[num_layers-1].b is not None: penalty += T.sum(layers...
Python
nomic_cornstack_python_v1
function stop self timeout=20 begin if not call running begin error string Server on port { port } has already stopped. return end info string Telling the server on port { port } to shut down. try begin communicate process input=string close timeout=timeout info string Server on port { port } has stopped. end except Ti...
def stop(self, timeout=20): if not self.running(): log.error(f'Server on port {self.port} has already stopped.') return log.info(f'Telling the server on port {self.port} to shut down.') try: self.process.communicate(input='close', timeout=timeout) ...
Python
nomic_cornstack_python_v1
function check_actors self actors begin string Performs checks on the actors that are to be used. Raises an exception if invalid setup. :param actors: the actors to check :type actors: list call check_actors actors set actor = first_active if actor is not none and not is instance actor InputConsumer begin raise excepti...
def check_actors(self, actors): """ Performs checks on the actors that are to be used. Raises an exception if invalid setup. :param actors: the actors to check :type actors: list """ super(Sequence, self).check_actors(actors) actor = self.first_active if ...
Python
jtatman_500k
string This file implements the REINFORCE algorithm on the CartPole environment. This starter code was obtained from https://towardsdatascience.com/learning-reinforcement-learning-reinforce-with-pytorch-5e8ad7fc7da0 We modified it significantly to enable parallel training of actors. import numpy as np import matplotlib...
""" This file implements the REINFORCE algorithm on the CartPole environment. This starter code was obtained from https://towardsdatascience.com/learning-reinforcement-learning-reinforce-with-pytorch-5e8ad7fc7da0 We modified it significantly to enable parallel training of actors. """ import numpy as np import matplotl...
Python
zaydzuhri_stack_edu_python
class Account extends object begin set ID_COUNT = 1 function __init__ self name **kwargs begin set id = ID_COUNT set name = name update __dict__ kwargs if has attribute self string value begin set value = 0 end set ID_COUNT = ID_COUNT + 1 end function function transfer self amount begin set value = value + amount end f...
class Account(object): ID_COUNT = 1 def __init__(self, name, **kwargs): self.id = self.ID_COUNT self.name = name self.__dict__.update(kwargs) if hasattr(self, 'value'): self.value = 0 Account.ID_COUNT += 1 def transfer(self, amount): self.value += ...
Python
zaydzuhri_stack_edu_python
from kafka import KafkaConsumer from bs4 import BeautifulSoup import json import re class Product begin function __init__ self title price host begin set title = call clean title set price = price set site = host end function end class function receive begin set consumer = call KafkaConsumer bootstrap_servers=string lo...
from kafka import KafkaConsumer from bs4 import BeautifulSoup import json import re class Product: def __init__(self, title, price, host): self.title = clean(title) self.price = price self.site = host def receive(): consumer = KafkaConsumer(bootstrap_servers='localhost:9092', a...
Python
zaydzuhri_stack_edu_python
function get_string self begin string make a string representation of the general error report set ostr = string set errtotal = deletions at string total + insertions at string total + mismatches set ostr = ostr + string from + string alignment_length + string bp of alignment + string set ostr = ostr + string + stri...
def get_string(self): """make a string representation of the general error report""" ostr = '' errtotal = self.deletions['total']+self.insertions['total']+self.mismatches ostr += 'from '+str(self.alignment_length)+' bp of alignment'+"\n" ostr += ' '+str(float(errtotal)/float(self.alignment_length))...
Python
jtatman_500k
function userLanguage self begin return call UserLanguages end function
def userLanguage(self): return UserLanguages()
Python
nomic_cornstack_python_v1
function gcd a b begin if b == 0 begin return a end return call gcd b a % b end function set a = 10 set b = 25 print string GCD of a string and b string = call gcd a b
def gcd(a, b): if b == 0: return a return gcd(b, a % b) a = 10 b = 25 print ("GCD of", a, "and", b, "=", gcd(a, b))
Python
iamtarun_python_18k_alpaca
function get_environ_value key begin assert key in environ msg string { key } should be set in the environ return environ at key end function
def get_environ_value(key: str) -> str: assert key in os.environ, f"{key} should be set in the environ" return os.environ[key]
Python
nomic_cornstack_python_v1
function vm_end vm_state *args op_bytecode=none **kwargs begin set tuple op_code _ _ _ _ = op_bytecode assert VM_OPERATION_TO_BYTECODE at op_code == string END set last_code_addr = vm_code_pointer set end_pointer = length call read1 set vm_code_pointer = last_code_addr + end_pointer return vm_state end function
def vm_end(vm_state: VmState, *args, op_bytecode=None, **kwargs) -> VmState: op_code, _, _, _, _ = op_bytecode assert VM_OPERATION_TO_BYTECODE[op_code] == "END" last_code_addr = vm_state.vm_code_pointer end_pointer = len(vm_state.vm_code_buffer.read1()) vm_state.vm_code_pointer = last_code_addr ...
Python
nomic_cornstack_python_v1
function get_NetworkEnum begin set networks = call Networks return call NetworkEnum string Network list ids end function
def get_NetworkEnum() -> NetworkEnum: networks = Networks() return NetworkEnum('Network', list(networks.ids))
Python
nomic_cornstack_python_v1
class Student begin string docstring for Student. function __init__ self *info begin set firstname = info at 1 set lastname = info at 2 set __cpf = info at 0 end function function get_cpf self begin return __cpf end function end class class Disciplina begin string docstring for Disciplina. function __init__ self nome *...
class Student(): """docstring for Student.""" def __init__(self, *info): self.firstname = info[1] self.lastname = info[2] self.__cpf = info[0] def get_cpf(self): return self.__cpf class Disciplina(): """docstring for Disciplina.""" def __init__(self, nome, *listaOb...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Dec 9 08:40:45 2020 @author: Kyle Schmidt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import MultinomialNB from sk...
# -*- coding: utf-8 -*- """ Created on Wed Dec 9 08:40:45 2020 @author: Kyle Schmidt """ import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import MultinomialNB from skle...
Python
zaydzuhri_stack_edu_python
import os import pandas as pd comment CSV File Generator function csv_generator path begin for tuple root dirnames filenames in walk path begin for file_name in filenames begin set filepath = join path root file_name set file = read csv filepath yield file end end end function comment Append dataframes function df_from...
import os import pandas as pd # CSV File Generator def csv_generator(path): for root, dirnames, filenames in os.walk(path): for file_name in filenames: filepath = os.path.join(root, file_name) file = pd.read_csv(filepath) yield file # Append dataframes def df_from_di...
Python
zaydzuhri_stack_edu_python
function obj_func_general_parametrisation p data parametrisation A reg_func loss penalty params begin set x = data at string x set y = data at string y set tuple n1 n2 = shape at slice 1 : 3 : set p = tensor p device=device set requires_grad = true if not grad is none begin call zero_ end set tuple S alpha eps = call ...
def obj_func_general_parametrisation(p, data, parametrisation, A, reg_func, loss, penalty, params): x = data['x'] y = data['y'] n1, n2 = x.shape[1:3] p = torch.tensor(p, device=x.device) p.requires_grad = True if not p.grad is None: p.grad.zero_()...
Python
nomic_cornstack_python_v1
function get_matrixS n begin set mat_nxn = zeros list n n dtype=int for row_num in range 1 n + 1 begin set i = row_num - 1 if row_num == 1 begin set mat_nxn at i at i + 1 = 1 set mat_nxn at i at i + 2 = 1 end else if row_num == 2 begin set mat_nxn at i at i - 1 = 1 set mat_nxn at i at i + 2 = 1 end else if row_num == n...
def get_matrixS(n): mat_nxn = np.zeros([n, n], dtype=int) for row_num in range(1, n + 1): i = row_num - 1 if row_num == 1: mat_nxn[i][i + 1] = 1 mat_nxn[i][i + 2] = 1 elif row_num == 2: mat_nxn[i][i - 1] = 1 mat_nxn[i][i + 2] = 1 e...
Python
nomic_cornstack_python_v1
comment Code reference from [1] http://scikit-image.org/docs/dev/auto_examples/xx_applications/plot_thresholding.html comment Otsu's thresholding method: comment Otsu’s method calculates an “optimal” threshold (red line in the histogram) by maximizing the comment variance between two classes of pixels, which are separa...
# Code reference from [1] http://scikit-image.org/docs/dev/auto_examples/xx_applications/plot_thresholding.html ##Otsu's thresholding method: #Otsu’s method calculates an “optimal” threshold (red line in the histogram) by maximizing the # variance between two classes of pixels, which are separated by the threshold. ...
Python
zaydzuhri_stack_edu_python
from functools import partial function P x begin return 10 <= x <= 29 end function function Q x begin return 13 <= x <= 18 end function function checker A begin set diapasone = range 8 32 return all generator expression not call A x or call P x or call Q x for x in diapasone end function function A x left right begin r...
from functools import partial def P(x): return 10 <= x <= 29 def Q(x): return 13 <= x <= 18 def checker(A: "some function from x"): diapasone = range(8, 32) return all(not A(x) or P(x) or Q(x) for x in diapasone) def A(x, left, right): return left <= x <= right max_len = 0 for l...
Python
zaydzuhri_stack_edu_python
function match_td_smiles QCA smitree indices begin set match_entries = list for node in call node_iter_depth_first call root select=string Entry begin if payload not in db begin continue end comment these are the indices of everything that matched in the smiles operation set group_smi_list = db at payload at string dat...
def match_td_smiles(QCA, smitree, indices): match_entries = list() for node in QCA.node_iter_depth_first(QCA.root(), select="Entry"): if node.payload not in smitree.db: continue # these are the indices of everything that matched in the smiles operation group_smi_list = smi...
Python
nomic_cornstack_python_v1
comment file: tf3_4.py comment author: meikerwang comment forward and backward train import tensorflow as tf import numpy as np set BATCH_SIZE = 8 set SEED = 23455 comment 基于SEED产生随机数 set rdm = call RandomState seed=SEED comment 随机生成32个2维的0-1均匀分布的数据 作为输入数据集 set X = call rand 32 2 comment 制作label数据集, label为 x0+x1 <1 为1否...
# file: tf3_4.py # author: meikerwang # forward and backward train import tensorflow as tf import numpy as np BATCH_SIZE = 8 SEED = 23455 # 基于SEED产生随机数 rdm = np.random.RandomState(seed=SEED) # 随机生成32个2维的0-1均匀分布的数据 作为输入数据集 X = rdm.rand(32, 2) # 制作label数据集, label为 x0+x1 <1 为1否则为0 Y_ = [[int(x0 + x1 < 1)] for (x0, x1) ...
Python
zaydzuhri_stack_edu_python
function removeModuleRule self phase module method rule_data begin set unlock_cluster = false set response = string Rule has been deleted successfully set retVal = 0 try begin call lock_cluster_for_update set unlock_cluster = true set version_file_path_s3 = call get_version_path cluster_id set version_data_dict = call ...
def removeModuleRule(self, phase, module, method, rule_data): unlock_cluster = False response = "Rule has been deleted successfully" retVal = 0 try: self.lock_cluster_for_update() unlock_cluster = True version_file_path_s3 = utils.get_version_path(self.cluster_id) version_data_d...
Python
nomic_cornstack_python_v1
function compute_weights self time_scale=300 begin comment Assert that times are offset seconds call time_stamps_to_offset_seconds comment Compute weights from time differences set weights = zeros tuple n_science n_sky for ii in range n_science begin set delta_t = science_time_stamps at ii - sky_time_stamps set weights...
def compute_weights(self, time_scale=300): # Assert that times are offset seconds self.time_stamps_to_offset_seconds() # Compute weights from time differences weights = np.zeros((self.n_science, self.n_sky)) for ii in range(self.n_science): delta_t = self.science_ti...
Python
nomic_cornstack_python_v1
function compute_accel data window begin comment deal with incomplete data if length data at TIME_COL < window * 2 begin error string Error! Not enough data points to compute acceleration. + string Try running with a smaller window setting or a smaller threshold. return none end comment Compute left/right acceleration ...
def compute_accel(data, window): # deal with incomplete data if len(data[TIME_COL]) < window * 2: logger.error( "Error! Not enough data points to compute acceleration. " + "Try running with a smaller window setting or a smaller threshold.", ) ...
Python
nomic_cornstack_python_v1
import selenium from selenium import webdriver import time import os comment chromedriver = "C:\ comment os.environ["PATH"] = chromedriver comment Take input from user or command line comment create browser instance for firefox set browser = call Firefox comment open webpage get browser string https://www.facebook.com/...
import selenium from selenium import webdriver import time import os #chromedriver = "C:\ #os.environ["PATH"] = chromedriver #Take input from user or command line #create browser instance for firefox browser = webdriver.Firefox() browser.get("https://www.facebook.com/") #open webpage #email_element = browser.find_...
Python
zaydzuhri_stack_edu_python
comment Project name : SPOJ: BAISED - Biased Standings comment Author : Wojciech Raszka comment Date created : 2019-03-17 comment Description : comment Status : Accepted (23432596) comment Comment : O(n) set T = integer call raw_input while T > 0 begin call raw_input set N = integer call raw_input set prefered_position...
# Project name : SPOJ: BAISED - Biased Standings # Author : Wojciech Raszka # Date created : 2019-03-17 # Description : # Status : Accepted (23432596) # Comment : O(n) T = int(raw_input()) while (T > 0): raw_input() N = int(raw_input()) prefered_position = [0]*(N + 1) for i in range(N): ...
Python
zaydzuhri_stack_edu_python
comment Modules import numpy as np comment Create a matrix using numpy set mat13 = array list 0 0 0
# Modules import numpy as np # Create a matrix using numpy mat13 = np.array([0, 0, 0])
Python
zaydzuhri_stack_edu_python
string Input: Coordinates as a string.. Output: The equation of the circle as a string. Precondition: All three given points do not lie on one line. 0 < xi, yi, r < 10 from collections import namedtuple from math import sqrt from ast import literal_eval set Point = named tuple string Point string x y function precision...
""" Input: Coordinates as a string.. Output: The equation of the circle as a string. Precondition: All three given points do not lie on one line. 0 < xi, yi, r < 10 """ from collections import namedtuple from math import sqrt from ast import literal_eval Point = namedtuple('Point', 'x y') def precision(value): ...
Python
zaydzuhri_stack_edu_python
function generate_file_name num begin set file_name = string C:/Users/yargr/Desktop/screenshot comment First call if num == 0 begin set file_name = file_name + string .jpg end else begin set file_name = file_name + string num + string .jpg end comment Look for a file by that name try begin load image file_name end comm...
def generate_file_name(num): file_name = 'C:/Users/yargr/Desktop/screenshot' if num == 0: # First call file_name += '.jpg' else: file_name += str(num) + '.jpg' try: # Look for a file by that name pygame.image.load(file_name) except: # File doesn't exist - name is va...
Python
nomic_cornstack_python_v1
function downscale_ls_seed_points_list_driver input_ls_seed_points_list_filename output_ls_seed_points_list_filename factor nlat_fine nlon_fine input_grid_type output_grid_type begin set input_points_list = list set comment_line_pattern = compile string ^ *#.*$ with open input_ls_seed_points_list_filename as f begin i...
def downscale_ls_seed_points_list_driver(input_ls_seed_points_list_filename, output_ls_seed_points_list_filename, factor, nlat_fine, nlon_fine, input_grid_type, ...
Python
nomic_cornstack_python_v1
function records begin set records = call load_file string records set tuple times people = tuple records at string records records at string people set refresh = false if string wca_token in session and string ion_token in session begin set me = call api_call string wca string me at string me set year = call api_call ...
def records() -> dict: records = cube.load_file("records") times, people = records["records"], records["people"] refresh = False if "wca_token" in flask.session and "ion_token" in flask.session: me = cube.api_call("wca", "me")["me"] year = cube.api_call("ion", "profile")["graduation_year...
Python
nomic_cornstack_python_v1
function add_previous_and_next_labels docs begin set docs at 0 at string previous_label_published_date = none set docs at 0 at string previous_label_spl_id = none set docs at 0 at string previous_label_spl_version = none set docs at 0 at string next_label_published_date = none set docs at 0 at string next_label_spl_id ...
def add_previous_and_next_labels(docs): docs[0]["previous_label_published_date"] = None docs[0]["previous_label_spl_id"] = None docs[0]["previous_label_spl_version"] = None docs[0]["next_label_published_date"] = None docs[0]["next_label_spl_id"] = None docs[0]["next_label_spl_version"] = None ...
Python
nomic_cornstack_python_v1
function exitOnClick self begin call getMouse call _close end function
def exitOnClick(self): self.getMouse() self._close()
Python
nomic_cornstack_python_v1
function createNewRule oldict key tempdict begin set newkey = key + string ` set newlist = list for item in oldict at key begin if starts with item key begin set str = replace item key string + string + newkey append newlist strip str end end append newlist string @ set tempdict at newkey = newlist end function funct...
def createNewRule(oldict, key, tempdict): newkey = key + '`' newlist = [] for item in oldict[key]: if item.startswith(key): str = item.replace(key, '')+' '+newkey newlist.append(str.strip()) newlist.append('@') tempdict[newkey] = newlist def editOldRule(aDict, key): ...
Python
zaydzuhri_stack_edu_python
function bound3d decs dcs begin comment small delta to avoid issues with souces exactly at edges set delta = 0.001 if type decs != list begin set decs = list decs set dcs = list dcs end set ramin = 0.0 set ramax = 360.0 set decmin = max min list comprehension min d for d in decs - delta - 90.0 set decmax = min max list...
def bound3d(decs, dcs): delta = 0.001 # small delta to avoid issues with souces exactly at edges if (type(decs)!=list): decs = [decs] dcs = [dcs] ramin = 0. ramax = 360. decmin = max(min([min(d) for d in decs]) - delta, -90.) decmax = min(max([max(d) for d in decs]) + delta,...
Python
nomic_cornstack_python_v1
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import threading class AsyncTask begin function __init__ self begin pass end function function TaskA self begin print string Process A start call Timer 1 TaskA end function function TaskB self begin print string Process B start call Timer 3 Task...
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import threading class AsyncTask: def __init__(self): pass def TaskA(self): print ('Process A') threading.Timer(1,self.TaskA).start() def TaskB(self): print ('Process B') threading.Timer(3,...
Python
zaydzuhri_stack_edu_python
function test_get_rov_sol_too_big dbtransaction global_environ photo_params rover_params camera_params begin set rover = rover_params at string name set sol = photo_params at string sol set photo = call Photo keyword photo_params add DBSession call Rover keyword rover_params add DBSession call Camera keyword camera_par...
def test_get_rov_sol_too_big(dbtransaction, global_environ, photo_params, rover_params, camera_params): rover = rover_params['name'] sol = photo_params['sol'] photo = Photo(**photo_params) DBSession.add(Rover(**rover_params)) DBSession.add(Camera(**camera_params)) DB...
Python
nomic_cornstack_python_v1
function lcm *integers begin if not integers begin raise call ValueError string integers must not be empty end if not call is_integer *integers begin raise call TypeError string invalid integer types found: { integers } end function _lcd a b begin if a == 0 and b == 0 begin raise call RuntimeError string lcm(0, 0) is u...
def lcm(*integers: int) -> int: if not integers: raise ValueError('integers must not be empty') if not is_integer(*integers): raise TypeError(f'invalid integer types found: {integers!r}') def _lcd(a: int, b: int) -> int: if a == 0 and b == 0: raise RuntimeError('lcm(0, ...
Python
nomic_cornstack_python_v1
function reset_current_time_slice self begin set __time_left_for_time_slice = __time_quantum end function
def reset_current_time_slice(self): self.__time_left_for_time_slice = self.__time_quantum
Python
nomic_cornstack_python_v1
function check_type self type begin set tdict = dictionary zip TYPES TYPES set tdict at string line = string lc set tdict at string bar = string bvs set tdict at string pie = string p set tdict at string venn = string v set tdict at string scater = string s assert type in tdict msg string Invalid chart type: %s % type ...
def check_type(self, type): tdict = dict(zip(TYPES,TYPES)) tdict['line'] = 'lc' tdict['bar'] = 'bvs' tdict['pie'] = 'p' tdict['venn'] = 'v' tdict['scater'] = 's' assert(type in tdict), 'Invalid chart type: %s'%type return tdict[type]
Python
nomic_cornstack_python_v1
async function store search_engine source process_param=none store_host=false store_emails=false store_ip=false store_people=false store_links=false store_results=false store_interestingurls=false store_asns=false begin if expression process_param is none then await process use_proxy else await process process_param us...
async def store(search_engine: Any, source: str, process_param: Any = None, store_host: bool = False, store_emails: bool = False, store_ip: bool = False, store_people: bool = False, store_links: bool = False, store_results: bool = False, store_interestingurls:...
Python
nomic_cornstack_python_v1
function leucocitos info begin comment Se accede la información de las cedulas por medio del metodo .keys set cedulas = keys info set resultado = dict comment Se crea el for inicial que tome todas las cedulas for i in cedulas begin set dias = keys info at i at string infoHemograma set leuco = values info at i at strin...
def leucocitos(info:dict)-> tuple: # Se accede la información de las cedulas por medio del metodo .keys cedulas = info.keys() resultado = {} #Se crea el for inicial que tome todas las cedulas for i in cedulas: dias = info[i]["infoHemograma"].keys() leuco = info[i]["infoHemograma...
Python
zaydzuhri_stack_edu_python
function get_dist self begin string Return a pkg_resources.Distribution built from self.egg_info_path set egg_info = right strip call egg_info_path string string / set base_dir = directory name path egg_info set metadata = call PathMetadata base_dir egg_info set dist_name = call splitext base name path egg_info at 0 re...
def get_dist(self): """Return a pkg_resources.Distribution built from self.egg_info_path""" egg_info = self.egg_info_path('').rstrip('/') base_dir = os.path.dirname(egg_info) metadata = pkg_resources.PathMetadata(base_dir, egg_info) dist_name = os.path.splitext(os.path.basename(e...
Python
jtatman_500k
from flask import Flask , request , render_template , redirect , session import random set app = call Flask __name__ static_url_path=string /static set secret_key = string root decorator call route string / function game begin if string rand not in keys session begin set session at string rand = random integer 1 10 end...
from flask import Flask, request, render_template, redirect, session import random app = Flask(__name__, static_url_path='/static') app.secret_key = 'root' @app.route('/') def game(): if 'rand' not in session.keys(): session['rand'] = random.randint(1,10) return render_template('index.html') ...
Python
zaydzuhri_stack_edu_python
from itertools import combinations set arr = list comprehension integer input for _ in range 9 for liter in call combinations arr 7 begin set value = sum liter if value == 100 begin print join string map str sorted liter break end end
from itertools import combinations arr = [int(input()) for _ in range(9)] for liter in combinations(arr, 7): value = sum(liter) if value == 100: print('\n'.join(map(str, sorted(liter)))) break
Python
zaydzuhri_stack_edu_python
if a >= 18 begin print string can vote end else begin print string cannot vote end
if a>=18: print('can vote') else: print('cannot vote')
Python
zaydzuhri_stack_edu_python
class myClass begin set x = 5 end class set myVar = call myClass print x class Time begin string Represents a time of day attributes: hour, minute, second function printTime self begin print format string {:2d}:{:2d}:{:2d} hour minute second end function comment or we can use the __str__() function function __str__ sel...
class myClass: x = 5 myVar = myClass() print(myVar.x) class Time: """ Represents a time of day attributes: hour, minute, second """ def printTime(self): print("{:2d}:{:2d}:{:2d}".format(self.hour, self.minute, self.second)) #or we can use the __str__() function def __str__(self): ...
Python
zaydzuhri_stack_edu_python
function get_vertex_keys self begin return keys vertList end function
def get_vertex_keys( self ): return self.vertList.keys()
Python
nomic_cornstack_python_v1
from math import factorial set args = integer input function tail n begin set count = 0 comment Keep dividing n by comment powers of 5 and comment update Count set i = 5 while n / i >= 1 begin set count = count + integer n / i set i = i * 5 end return integer count end function for i in range args begin set num = integ...
from math import factorial args = int(input()) def tail(n): count = 0 # Keep dividing n by # powers of 5 and # update Count i=5 while (n/i>=1): count += int(n/i) i *= 5 return int(count) for i in range(args): num = int(input()) fact = tail(num) prin...
Python
zaydzuhri_stack_edu_python
function read_input begin set test_input = string 1,0,0,0,99 set test_input = string 2,3,0,3,99 set test_out = string 2,0,0,0,99 set test_input = string 2,4,4,5,99,0 for i in range 100 begin for j in range 100 begin set instruction_start = 0 set opcode = 0 set loc_1 = 0 set loc_2 = 0 set result_loc = 0 set current_loc ...
def read_input(): test_input = "1,0,0,0,99" test_input = "2,3,0,3,99" test_out = "2,0,0,0,99" test_input = "2,4,4,5,99,0" for i in range(100): for j in range(100): instruction_start = 0 opcode = 0 loc_1 = 0 loc_2 = 0 result_lo...
Python
zaydzuhri_stack_edu_python
function visit_dimension self node visited_children begin set entries = split text string set value = call __parse_decimal entries at slice 0 : - 1 : set key = KEY_MAP at entries at - 1 if get attribute dictionary key is none begin set attribute dictionary key call Entry end set value = decimal value set value_text = t...
def visit_dimension(self, node, visited_children): entries = node.text.split(" ") value = self.__parse_decimal(entries[0:-1]) key = WdcParsimoniousNodeVisitor.KEY_MAP[entries[-1]] if getattr(self.dictionary, key) is None: setattr(self.dictionary, key, self.dictionary.Entry()...
Python
nomic_cornstack_python_v1
if name begin print string Hey + name end
if name: print('Hey ' + name)
Python
zaydzuhri_stack_edu_python
function get_minimum_diff_for_against_team self begin set for_goals = integer __data at string F at 0 set against_goals = integer __data at string A at 0 set min_difference = absolute for_goals - against_goals set min_difference_team = __data at string Team at 0 for tuple _ row in call iterrows begin set for_goals = in...
def get_minimum_diff_for_against_team(self): for_goals = int(self.__data["F"][0]) against_goals = int(self.__data["A"][0]) min_difference = abs(for_goals - against_goals) min_difference_team = self.__data["Team"][0] for _, row in self.__data.iterrows(): for_goals = in...
Python
nomic_cornstack_python_v1
function publish_scene_config self scene_id config begin string publish a changed scene configuration set sequence_number = sequence_number + 1 call send_multipart call scene_config sequence_number scene_id config return sequence_number end function
def publish_scene_config(self, scene_id, config): """publish a changed scene configuration""" self.sequence_number += 1 self.publisher.send_multipart(msgs.MessageBuilder.scene_config(self.sequence_number, scene_id, config)) return self.sequence_number
Python
jtatman_500k
comment encoding: utf-8 from six.moves import xrange import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow.contrib.data import Dataset from tensorflow.examples.tutorials.mnist import input_data call set_random_seed 1 seed 1 set BATCH_SIZE = 50 set LR = 0.001 comment data comment the...
# encoding: utf-8 from six.moves import xrange import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow.contrib.data import Dataset from tensorflow.examples.tutorials.mnist import input_data tf.set_random_seed(1) np.random.seed(1) BATCH_SIZE = 50 LR = 0.001 # data mnist = input_da...
Python
zaydzuhri_stack_edu_python
function reset self begin call _write 22 1 3 8 end function
def reset(self): self._write(0x16, 1, 3, 0x08)
Python
nomic_cornstack_python_v1
function _keys_to_lower filters begin set convert_dict = default dictionary list for tuple k v in call lists begin set convert_dict at lower k = convert_dict at lower k + v end set newfilt = call MultiDict convert_dict return newfilt end function
def _keys_to_lower(filters): convert_dict = defaultdict(list) for k, v in filters.lists(): convert_dict[k.lower()] += v newfilt = werkzeug.datastructures.MultiDict(convert_dict) return newfilt
Python
nomic_cornstack_python_v1
function remove cls config begin set node = call get_node_by_id cluster config at string node set id_ = config at string id call shell args=list string ceph string auth string del id_ if get config string remove_admin_keyring begin call exec_command cmd=string rm -rf /etc/ceph/ceph.client.admin.keyring sudo=true end ca...
def remove(cls, config: Dict) -> None: node = get_node_by_id(cls.cluster, config["node"]) id_ = config["id"] cls.shell( args=["ceph", "auth", "del", id_], ) if config.get("remove_admin_keyring"): node.exec_command( cmd="rm -rf /etc/ceph/ceph.client.admin.keyring", ...
Python
nomic_cornstack_python_v1
function scramble string begin return join string list comprehension join string random sample word length word for word in split string end function
def scramble(string): return ' '.join([''.join(random.sample(word, len(word))) for word in string.split()])
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Sep 3 13:34:44 2019 @author: project import struct function recv_one_message sock begin set lengthbuf = call recvall sock 4 try begin set length = call unpack string !I lengthbuf end except Exception begin return none end return call recvall sock length at 0 end funct...
# -*- coding: utf-8 -*- """ Created on Tue Sep 3 13:34:44 2019 @author: project """ import struct def recv_one_message(sock): lengthbuf = recvall(sock, 4) try: length = struct.unpack('!I', lengthbuf) except Exception: return None return recvall(sock, length[0]) def recvall(s...
Python
zaydzuhri_stack_edu_python
function key_encryption_key self begin return get pulumi self string key_encryption_key end function
def key_encryption_key(self) -> Optional[pulumi.Input['KeyEncryptionKeyArgs']]: return pulumi.get(self, "key_encryption_key")
Python
nomic_cornstack_python_v1
function get_provider self provider_prefix spec begin set providers = settings at string repo_providers if provider_prefix not in providers begin raise call HTTPError 404 string No provider found for prefix %s % provider_prefix end return call config=settings at string traitlets_config spec=spec end function
def get_provider(self, provider_prefix, spec): providers = self.settings['repo_providers'] if provider_prefix not in providers: raise web.HTTPError(404, "No provider found for prefix %s" % provider_prefix) return providers[provider_prefix]( config=self.settings['traitlet...
Python
nomic_cornstack_python_v1
function fit self dataset batch_size epochs split_ratio=0.7 begin comment Set the train len based on split ratio set train_len = integer length dataset * split_ratio comment Initialize the train and validation generator set train_generator = call DataGenerator x_set=dataset at slice : train_len : batch_size=batch_siz...
def fit(self, dataset, batch_size, epochs, split_ratio=0.7): # Set the train len based on split ratio train_len = int(len(dataset) * split_ratio) # Initialize the train and validation generator train_generator = DataGenerator(x_set=dataset[:train_len], batch_size=batch_size, name=self.name, condition=self.cond...
Python
nomic_cornstack_python_v1
from kivy.app import App from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout class loginForm extends App begin function build self begin set order = call BoxLayout orientation=string vert...
from kivy.app import App from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout class loginForm(App): def build(self): order = BoxLayout(orientation='vertical') ...
Python
zaydzuhri_stack_edu_python
function __init__ self right=none left=none label=string value=none begin set right = right string right child, taken when a sample[`decisiontree.DecisionTree.label`] > `decisiontree.DecisionTree.value` set left = left string left child, taken when sample[`decisiontree.DecisionTree.label`] <= `decisiontree.DecisionTre...
def __init__(self, right=None, left=None, label='', value=None): self.right = right '''right child, taken when a sample[`decisiontree.DecisionTree.label`] > `decisiontree.DecisionTree.value`''' self.left = left '''left child, taken when sample[`decisiontree.DecisionTree.label`] <= `d...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python set a = list set b = list a a a
#!/usr/bin/env python a = [] b = [a,a,a]
Python
zaydzuhri_stack_edu_python
function op_paths self path_base=none begin comment type: (Union[str, UrlPath]) -> Generator[Tuple[UrlPath, Operation]] string Return all operations stored in containers. if path_base begin set path_base = path_base + path_prefix end else begin set path_base = path_prefix or call UrlPath end for container in containers...
def op_paths(self, path_base=None): # type: (Union[str, UrlPath]) -> Generator[Tuple[UrlPath, Operation]] """ Return all operations stored in containers. """ if path_base: path_base += self.path_prefix else: path_base = self.path_prefix or UrlPath(...
Python
jtatman_500k
import random class StickGame begin function __init__ self sticks player_1_name player_2_name begin set sticks = sticks set turns = dict player_1_name player_2_name ; player_2_name player_1_name set turn = player_1_name set sticks_taken = 0 end function function person_turn self begin while true begin try begin set sti...
import random class StickGame: def __init__(self, sticks, player_1_name, player_2_name): self.sticks = sticks self.turns = {player_1_name: player_2_name, player_2_name: player_1_name} self.turn = player_1_name self.sticks_taken = 0 def person_turn(self): while True: ...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn class AdaptiveConcatPool2d extends Module begin string Concat along the channel dimension of AdaptiveAvgPool2d and AdaptiveMaxPool2d. Args: size: size of pooling, default: (1, 1) function __init__ self size=tuple 1 1 begin call __init__ set size = size set ap = call AdaptiveAvgPool2d ...
import torch import torch.nn as nn class AdaptiveConcatPool2d(nn.Module): """Concat along the channel dimension of AdaptiveAvgPool2d and AdaptiveMaxPool2d. Args: size: size of pooling, default: (1, 1) """ def __init__(self, size=(1, 1)): super().__init__() self.size = size ...
Python
zaydzuhri_stack_edu_python
from sklearn.cross_validation import train_test_split from sklearn.metrics import precision_recall_curve , roc_curve import sklearn.metrics as metrics import matplotlib.pyplot as plt import numpy as np function rfc_model_analysis model X_train Y_train X_test y_test begin comment Model Must be a Random Forest Classifier...
from sklearn.cross_validation import train_test_split from sklearn.metrics import precision_recall_curve, roc_curve import sklearn.metrics as metrics import matplotlib.pyplot as plt import numpy as np def rfc_model_analysis(model,X_train,Y_train,X_test,y_test): # Model Must be a Random Forest Classifier m...
Python
zaydzuhri_stack_edu_python
function find_user self uid=none name=none begin for user in run string enumerate.gather progress=false types=list string user begin if uid is none or id == uid and name is none or name == name begin return user end end end function
def find_user(self, uid=None, name=None): for user in self.run("enumerate.gather", progress=False, types=["user"]): if (uid is None or user.id == uid) and (name is None or user.name == name): return user
Python
nomic_cornstack_python_v1
function is_file_i value begin if not type value is str and is file path value begin return false end else begin return true end end function
def is_file_i(value): if not (type(value) is str and os.path.isfile(value)): return False else: return True
Python
nomic_cornstack_python_v1
async function _auth_cram_md5 self username password begin string Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challen...
async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent ...
Python
jtatman_500k
from bs4 import BeautifulSoup set html_string = string <html> <p class="highlight">This is a highlighted paragraph</p> <div> <span>This is a span</span> <p>This is a regular paragraph</p> <p class="highlight">This is another highlighted paragraph</p> </div> </html> set soup = call BeautifulSoup html_string string html....
from bs4 import BeautifulSoup html_string = ''' <html> <p class="highlight">This is a highlighted paragraph</p> <div> <span>This is a span</span> <p>This is a regular paragraph</p> <p class="highlight">This is another highlighted paragraph</p> </div> </html> ''' soup = BeautifulSoup(html_string, 'ht...
Python
greatdarklord_python_dataset
comment Author: Joshua Campbell comment Python: version 2.7.3 comment Purpose: Experiment with Genetic Algorithms to find solutions to problems, in this case comment to find suitable behaviour buying/selling stocks listed on NASDAQ given 3 months comment historical data. This is for my learning purposes only, so low ex...
#Author: Joshua Campbell #Python: version 2.7.3 #Purpose: Experiment with Genetic Algorithms to find solutions to problems, in this case # to find suitable behaviour buying/selling stocks listed on NASDAQ given 3 months # historical data. This is for my learning purposes only, so low expectations woul...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function mostCommonWord self paragraph banned begin string :type paragraph: str :type banned: List[str] :rtype: str set stopwords = list string ! string ? string , string . string ; string ' string set maxi = 0 set mc = string set wc = dict for x in stopwords begin set paragraph =...
class Solution(object): def mostCommonWord(self, paragraph, banned): """ :type paragraph: str :type banned: List[str] :rtype: str """ stopwords = ["!", "?", ",", ".", ";", "'", " "] maxi = 0 mc = "" wc = {} for x in stopwords: ...
Python
zaydzuhri_stack_edu_python
function demo begin from nodebox_linguistics_extended.parser.nltk_lite.corpora import brown from nodebox_linguistics_extended.parser.nltk_lite import tag import sys print string Training taggers. comment Create a default tagger set t0 = call Default string nn set t1 = call Unigram cutoff=1 backoff=t0 train t1 call tagg...
def demo(): from nodebox_linguistics_extended.parser.nltk_lite.corpora import brown from nodebox_linguistics_extended.parser.nltk_lite import tag import sys print("Training taggers.") # Create a default tagger t0 = tag.Default("nn") t1 = tag.Unigram(cutoff=1, backoff=t0) t1.train(brow...
Python
nomic_cornstack_python_v1
function test_check_metadata_parses begin set check = call CheckTester googlefonts_profile string com.google.fonts/check/metadata/parses set good = call TEST_FILE string merriweather/Merriweather-Regular.ttf call assert_PASS call check good string with a good METADATA.pb file... set skip = call TEST_FILE string slabo/S...
def test_check_metadata_parses(): check = CheckTester(googlefonts_profile, "com.google.fonts/check/metadata/parses") good = TEST_FILE("merriweather/Merriweather-Regular.ttf") assert_PASS(check(good), 'with a good METADATA.pb file...') skip = TEST_FILE("slabo/Sla...
Python
nomic_cornstack_python_v1
function add_star_streamer client_id streamer_id now=none begin set now = call _get_now now try begin comment Get the indexed name of the streaming user. set streamer_indexed_name = indexed_name comment Add the client's star for the streaming user. set starred_streamer = call StarredStreamer user_id=client_id streamer_...
def add_star_streamer(client_id, streamer_id, now=None): now = _get_now(now) try: # Get the indexed name of the streaming user. streamer_indexed_name = session.query(User.indexed_name)\ .filter(User.id == streamer_id)\ .one()\ .indexed_name # Add the client's star for the streaming user. starred_...
Python
nomic_cornstack_python_v1
while i > - 3 begin if i % 2 == 0 and i > 0 begin print string i + string is even end else if i % 2 != 0 and i > 0 begin print string i + string is odd end else begin print string i + string is negative end set i = i - 3 end
while i > -3: if (i % 2) == 0 and i > 0: print(str(i)+ "is even") elif (i % 2 )!= 0 and i > 0: print(str(i)+ "is odd") else: print(str(i)+ "is negative") i = i-3
Python
zaydzuhri_stack_edu_python
set my = input string Enter a char: if my >= string a and my <= string z or my >= string A and my <= string Z begin print my string it is an alphabet end else begin print my string it is not an alphabet end
my = input("Enter a char: ") if((my>='a' and my<= 'z') or (my>='A' and my<='Z')): print(my, "it is an alphabet") else: print(my, "it is not an alphabet")
Python
zaydzuhri_stack_edu_python
function qini_score tau_score y_true treatment_group prob_treatment n_bins=10 begin return NotImplementedError end function
def qini_score(tau_score, y_true, treatment_group, prob_treatment, n_bins=10): return NotImplementedError
Python
nomic_cornstack_python_v1
function log_image tag data global_step walltime=none logger=none begin set logger = logger or call _get_context_logger info call ImageT tag=tag img_tensor=data global_step=global_step walltime=walltime or time end function
def log_image(tag: str, data: str, global_step: int, walltime: Optional[float] = None, logger: Optional[logging.Logger] = None) -> None: logger = logger or _get_context_logger() logger.info(ImageT(tag=tag, img_tensor=data, global_step=global_step, ...
Python
nomic_cornstack_python_v1
function load_subgait robot gait_directory gait_name subgait_name gait_version_map begin if not get gait_version_map gait_name begin raise call GaitNameNotFound gait_name end if not get gait_version_map at gait_name subgait_name begin raise call SubgaitNameNotFound subgait_name end set version = gait_version_map at gai...
def load_subgait(robot, gait_directory, gait_name, subgait_name, gait_version_map): if not gait_version_map.get(gait_name): raise GaitNameNotFound(gait_name) if not gait_version_map[gait_name].get(subgait_name): raise SubgaitNameNotFound(subgait_name) version = gait_vers...
Python
nomic_cornstack_python_v1
string Converts an integer number to an ordinal-type name string Example: int(123456789) -> "123 million 456 thousand 789 units" Input range: signed 32-bit integers 0 .. 2^31 Algorithm: convert positional blocks in the thousands/millions|billions range by using modulus operation by powers of 1000 at each step save the ...
""" Converts an integer number to an ordinal-type name string Example: int(123456789) -> "123 million 456 thousand 789 units" Input range: signed 32-bit integers 0 .. 2^31 Algorithm: convert positional blocks in the thousands/millions|billions range by using modulus operation by powers of 1...
Python
zaydzuhri_stack_edu_python
comment Ejercicio 2 comment Complete el siguiente codigo para recorrer la lista `x` e imprima comment los numeros impares y que pare de imprimir al encontrar un numero mayor a 800 import numpy as np set x = call int_ random 100 * 1000 set dx = length x for i in range dx begin if x at i < 800 begin if x at i % 2 == 1 be...
# Ejercicio 2 # Complete el siguiente codigo para recorrer la lista `x` e imprima # los numeros impares y que pare de imprimir al encontrar un numero mayor a 800 import numpy as np x = np.int_(np.random.random(100)*1000) dx = len(x) for i in range(dx): if(x[i] < 800): if (x[i]%2 == 1): print(x[i])
Python
zaydzuhri_stack_edu_python
function opt_bindzone self filename begin if not exists path filename begin raise call UsageError filename + string : No such file end append bindfiles filename end function
def opt_bindzone(self, filename): if not os.path.exists(filename): raise usage.UsageError(filename + ": No such file") self.bindfiles.append(filename)
Python
nomic_cornstack_python_v1
comment 抓取網頁原始碼 import urllib.request as req set url = string https://www.ptt.cc/bbs/PokeMon/index.html comment 模仿使用者,建立一個request物件 set request = call Request url headers=dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 with...
# 抓取網頁原始碼 import urllib.request as req url="https://www.ptt.cc/bbs/PokeMon/index.html" #模仿使用者,建立一個request物件 request=req.Request(url, headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" }) with req.urlopen(request) as resp...
Python
zaydzuhri_stack_edu_python
comment Importation des modules import serial comment pour la communication avec le port série import serial.tools.list_ports comment initialisation des listes set liste_distance = list comment Fonction pour la récupération des données série venant de la carte Arduino function recup_port_Arduino begin set ports = list...
#Importation des modules import serial import serial.tools.list_ports # pour la communication avec le port série #initialisation des listes liste_distance = [] # Fonction pour la récupération des données série venant de la carte Arduino def recup_port_Arduino() : ports = list(serial.tools.list_ports.comports()...
Python
zaydzuhri_stack_edu_python