code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment -*- coding: utf-8 -*- string :mod:`test` module : Test module for bloomfilter analysis :author: Léane TEXIER & Antonio Viana SIMONE JUNIOR & `FIL - IEEA - Univ. Lille1.fr <http://portail.fil.univ-lille1.fr>`_ :date: 2016, january import random import bloomfilter set nb_hash_functions = 8 set random_tab = list c...
# -*- coding: utf-8 -*- """:mod:`test` module : Test module for bloomfilter analysis :author: Léane TEXIER & Antonio Viana SIMONE JUNIOR & `FIL - IEEA - Univ. Lille1.fr <http://portail.fil.univ-lille1.fr>`_ :date: 2016, january """ import random import bloomfilter nb_hash_functions = 8 random_tab = [ 0 for i in ra...
Python
zaydzuhri_stack_edu_python
function calc_boxplots dots begin set tuple low_box_Q1 median high_box_Q3 = call percentile dots percents comment calc borders set IQR = high_box_Q3 - low_box_Q1 set Q1_15 = low_box_Q1 - 1.5 * IQR set Q3_15 = high_box_Q3 + 1.5 * IQR set tuple high_whisker low_whisker = tuple high_box_Q3 low_box_Q1 for dot in dots begin...
def calc_boxplots(dots): low_box_Q1, median, high_box_Q3 = np.percentile(dots, percents) # calc borders IQR = high_box_Q3 - low_box_Q1 Q1_15 = low_box_Q1 - 1.5 * IQR Q3_15 = high_box_Q3 + 1.5 * IQR high_whisker, low_whisker = high_box_Q3, low_box_Q1, for dot in dots: if high_box_Q3 < dot <= Q3_15 and dot > h...
Python
nomic_cornstack_python_v1
function parse_refs_json data begin comment docs contains annotation, fileName, details, id generated by Solr set docs = data at string response at string docs comment Create a list object for the results with annotation and details. Details is a list of comment a single string, flatten it: remove the string from the l...
def parse_refs_json(data): # docs contains annotation, fileName, details, id generated by Solr docs = data['response']['docs'] # Create a list object for the results with annotation and details. Details is a list of # a single string, flatten it: remove the string from the list. results = [[docs[i]...
Python
nomic_cornstack_python_v1
function fullLine n c begin set s = string return s end function comment Empty line, Rectangle, Empty Rectangle, Triangle à gauche, Triangle à droite, Triangle centré, Triangle vide à gauche, Triangle vide à droite, Triangle vide centré, Pacman, Sablier, Plus, Multiplier, Serpent horizontal, Serpent Vertical, Damier, ...
def fullLine(n,c): s = "" return s # Empty line, Rectangle, Empty Rectangle, Triangle à gauche, Triangle à droite, Triangle centré, Triangle vide à gauche, Triangle vide à droite, Triangle vide centré, Pacman, Sablier, Plus, Multiplier, Serpent horizontal, Serpent Vertical, Damier, Diagonale /, Diagonale \ def emp...
Python
zaydzuhri_stack_edu_python
function set self value begin if value == value begin return false end set value = value return true end function
def set(self, value): if value == self.value: return False self.value = value return True
Python
nomic_cornstack_python_v1
function on_buttonBox_accepted self begin call newtelnetconsole end function
def on_buttonBox_accepted(self): self.newtelnetconsole()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from __future__ import print_function from nltk.corpus import sentiwordnet as swn class SentiWordNet extends object begin string 正/负向情感极性评分均为 0 ~ 1 decorator classmethod function get cls word pos=none begin set synsets = call senti_synsets string=word pos=pos return synsets end function en...
# -*- coding: utf-8 -*- from __future__ import print_function from nltk.corpus import sentiwordnet as swn class SentiWordNet(object): """ 正/负向情感极性评分均为 0 ~ 1 """ @classmethod def get(cls, word, pos=None): synsets = swn.senti_synsets(string=word, pos=pos) return synsets senti_wordn...
Python
zaydzuhri_stack_edu_python
import sys import socket import time import BaseHTTPServer import os import json comment print socket.gethostname() set HOST_NAME = call gethostname set PORT_NUMBER = integer 7777 set CID = call gethostname set data = dict string cid CID set json_data = dumps data class MyHandler extends BaseHTTPRequestHandler begin fu...
import sys import socket import time import BaseHTTPServer import os import json #print socket.gethostname() HOST_NAME = socket.gethostname() PORT_NUMBER = int(7777) CID = socket.gethostname() data = { 'cid' : CID, } json_data = json.dumps(data) class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def d...
Python
zaydzuhri_stack_edu_python
function ip_address self ip_address begin set _ip_address = ip_address end function
def ip_address(self, ip_address): self._ip_address = ip_address
Python
nomic_cornstack_python_v1
comment Escreva uma classe Python que contenha um método que faça a validação da força da senha fornecida pelo usuário. comment Uma senha forte deve atender aos seguintes critérios: comment Possuir ao menos 1 caractere numérico; comment Possuir ao menos 1 caractere especial; comment Ao chamar o método o programa deve r...
#Escreva uma classe Python que contenha um método que faça a validação da força da senha fornecida pelo usuário. # Uma senha forte deve atender aos seguintes critérios: #Possuir ao menos 1 caractere numérico; #Possuir ao menos 1 caractere especial; #Ao chamar o método o programa deve retornar se a senha é valida ou nã...
Python
zaydzuhri_stack_edu_python
function generate_combinations s begin set result = list for i in range length s begin for j in range i + 1 length s + 1 begin append result s at slice i : j : end end return result end function
def generate_combinations(s): result = [] for i in range(len(s)): for j in range(i+1, len(s)+1): result.append(s[i:j]) return result
Python
jtatman_500k
function get_transcript self transcript_format=string srt begin set lang = transcript_language if lang == string en begin comment HTML5 case and (Youtube case for new style videos) if sub begin set transcript_name = sub end else comment old courses if youtube_id_1_0 begin set transcript_name = youtube_id_1_0 end else b...
def get_transcript(self, transcript_format='srt'): lang = self.transcript_language if lang == 'en': if self.sub: # HTML5 case and (Youtube case for new style videos) transcript_name = self.sub elif self.youtube_id_1_0: # old courses trans...
Python
nomic_cornstack_python_v1
function test_image_returned self begin set array_no_filename = call gradient_magnitude bw assert true is instance array_no_filename ndarray set array_filename = call gradient_magnitude bw valid_output_filename assert true is instance array_filename ndarray end function
def test_image_returned(self): array_no_filename = self.gt.gradient_magnitude(self.bw) self.assertTrue(isinstance(array_no_filename, np.ndarray)) array_filename = self.gt.gradient_magnitude( self.bw, self.valid_output_filename) self.assertTrue(isinstance(array_filename, np.nd...
Python
nomic_cornstack_python_v1
function harvest p4Mol orca_out **largs begin comment Split into lines as it is much easier to find what is needed set out_lines = split orca_out string set mol = call harvest_molecule_from_outfile out_lines set file_name = string NONE set grad = call harvest_engrad file_name comment Harvest energies and properties fro...
def harvest(p4Mol, orca_out, **largs): # Split into lines as it is much easier to find what is needed out_lines = orca_out.split('\n') mol = harvest_molecule_from_outfile(out_lines) file_name = "NONE" grad = harvest_engrad(file_name) # Harvest energies and properties from the output file ...
Python
nomic_cornstack_python_v1
function two_arrow_circle render=MGL_LINE_STRIP begin call glBegin render call glVertex3f 3.8742999999999997e-07 0.0 - 0.999999 call glVertex3f 0.195091 0.0 - 0.980785 call glVertex3f 0.382683 0.0 - 0.923879 call glVertex3f 0.55557 0.0 - 0.831469 call glVertex3f 0.707106 0.0 - 0.707106 call glVertex3f 0.831469 0.0 - 0....
def two_arrow_circle(render=OpenMayaRender.MGL_LINE_STRIP): gl_ft.glBegin(render) gl_ft.glVertex3f(3.8742999999999997e-07, 0.0, -0.999999) gl_ft.glVertex3f(0.195091, 0.0, -0.980785) gl_ft.glVertex3f(0.382683, 0.0, -0.923879) gl_ft.glVertex3f(0.55557, 0.0, -0.831469) gl_ft.glVertex3f(0.707106, 0....
Python
nomic_cornstack_python_v1
async function _update_flow_setting flow_id key value begin if flow_id is none begin raise call ValueError string Invalid flow ID end comment retrieve current settings so that we only update provided keys set flow = await first where id=flow_id set literal string settings comment if we don't have permission to view the...
async def _update_flow_setting(flow_id: str, key: str, value: any) -> bool: if flow_id is None: raise ValueError("Invalid flow ID") # retrieve current settings so that we only update provided keys flow = await models.Flow.where(id=flow_id).first({"settings"}) # if we don't have permission to v...
Python
nomic_cornstack_python_v1
comment Add our dependencies. import csv import os comment Assign a variable to load a file from a path. set file_to_load = join path string Resources string election_results.csv comment Assign a variable to save the file to a path. set file_to_save = join path string analysis string election_analysis.txt comment Initi...
# Add our dependencies. import csv import os # Assign a variable to load a file from a path. file_to_load = os.path.join("Resources", "election_results.csv") # Assign a variable to save the file to a path. file_to_save = os.path.join("analysis", "election_analysis.txt") # Initialize variables total_votes = 0 #candida...
Python
zaydzuhri_stack_edu_python
class HttpResponse extends object begin function __init__ self response begin set http_version = none set code = none set message = none set headers_list = list set headers_dict = dict set body_str = none set body_bytes = none call __make_response response end function function __make_response self response begin str...
class HttpResponse(object): def __init__(self, response: bytes) -> None: self.http_version = None self.code = None self.message = None self.headers_list = [] self.headers_dict = {} self.body_str = None self.body_bytes = None self.__make_...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render , get_object_or_404 from django.utils import timezone comment . = a dossier en cours from models import Post comment A view is a place where we put the "logic" of our application. comment It will request information from the model you created before and pass it to a template function...
from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post # . = a dossier en cours # A view is a place where we put the "logic" of our application. #It will request information from the model you created before and pass it to a template def post_list(request): ...
Python
zaydzuhri_stack_edu_python
function invalid self begin set authorized_keys_files = call scan_authorized_keys set invalid_pub_key = call get_invalid_hosts for file in authorized_keys_files begin set ak = call AuthorizedKeys file for pub_key in data begin if pub_key in invalid_pub_key begin call invalid pub_key info format string invalid host {} p...
def invalid(self): authorized_keys_files = scan_authorized_keys() invalid_pub_key = self.get_invalid_hosts() for file in authorized_keys_files: ak = AuthorizedKeys(file) for pub_key in ak.data: if pub_key in invalid_pub_key: ak.invalid(...
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode(object): comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution extends object begin function minDiffInBST self root begin string :type root: TreeNode :rtype: int set arr = list set min = 10...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDiffInBST(self, root): """ :type root: TreeNode :rtype: int """ arr = ...
Python
zaydzuhri_stack_edu_python
import unittest from tests.base_test import BaseTest from pages.home_page import HomePage from pages.basket_page import BasketPage from variables import Variables from time import sleep class BasketTest extends BaseTest begin function test_add_2_different_products self begin set home_page = call HomePage driver call ad...
import unittest from tests.base_test import BaseTest from pages.home_page import HomePage from pages.basket_page import BasketPage from variables import Variables from time import sleep class BasketTest(BaseTest): def test_add_2_different_products(self): home_page = HomePage(self.driver) home_page...
Python
zaydzuhri_stack_edu_python
function part2 lines begin set digits = list map int list comprehension c for c in lines at 0 * 10000 set skip = integer lines at 0 at slice : 7 : if skip < length digits / 2 begin print string ERROR: can't use fast method, not skipping enough digits exit 1 end set digits = digits at slice skip : : for _ in range 10...
def part2(lines): digits = list(map(int, [c for c in lines[0]])) * 10000 skip = int(lines[0][:7]) if skip < len(digits) / 2: print("ERROR: can't use fast method, not skipping enough digits") exit(1) digits = digits[skip:] for _ in range(100): for i in range(len(digits) - 2, -...
Python
nomic_cornstack_python_v1
class Solution begin function totalFruit self tree begin if length set tree == 2 begin return length tree end set ans = list set i = 0 set tmp = list set j = list while i < length tree begin if tree at i not in tmp begin append j i end append tmp tree at i set i = i + 1 if length set tmp == 3 begin append ans length...
class Solution: def totalFruit(self, tree): if len(set(tree)) == 2: return len(tree) ans = [] i = 0 tmp = [] j = [] while i < len(tree): if tree[i] not in tmp: j.append(i) tmp.append(tree[i]) i += 1 ...
Python
zaydzuhri_stack_edu_python
function _is_close_tag self tokenized_line begin if tokenized_line at 0 == string </ begin return true end else begin return false end end function
def _is_close_tag(self, tokenized_line): if tokenized_line[0] == '</': return True else: return False
Python
nomic_cornstack_python_v1
function get_guild self idOrName begin if is instance idOrName int begin return call get_guild idOrName end else begin for guild in guilds begin if name == idOrName begin return guild end end end return none end function
def get_guild(self, idOrName: Union[int, str]) -> Optional[Guild]: if isinstance(idOrName, int): return self.bot.get_guild(idOrName) else: for guild in self.bot.guilds: if guild.name == idOrName: return guild return None
Python
nomic_cornstack_python_v1
function extract_feat self img img_metas begin set img_feats = call extract_img_feat img img_metas return img_feats end function
def extract_feat(self, img, img_metas): img_feats = self.extract_img_feat(img, img_metas) return img_feats
Python
nomic_cornstack_python_v1
function initial_population begin comment [OBS, MOVES] set training_data = list comment all scores: set scores = list comment just the scores that met our threshold: set accepted_scores = list comment iterate through however many games we want: for _ in range initial_games begin set score = 0 comment moves specifica...
def initial_population(): # [OBS, MOVES] training_data = [] # all scores: scores = [] # just the scores that met our threshold: accepted_scores = [] # iterate through however many games we want: for _ in range(initial_games): score = 0 # moves specifically from this envir...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 string Write a script that deletes all State objects with a name containing the letter a from the database hbtn_0e_6_usa Your script should take 3 arguments: mysql username, mysql password and database name You must use the module SQLAlchemy You must import State and Base from model_state - fr...
#!/usr/bin/python3 """ Write a script that deletes all State objects with a name containing the letter a from the database hbtn_0e_6_usa Your script should take 3 arguments: mysql username, mysql password and database name You must use the module SQLAlchemy You must import State and Base from model_state - from model...
Python
zaydzuhri_stack_edu_python
comment !usr/bin/python3 comment Last Update : December 10, 2017 comment Author : Dhaval R Niphade comment Course : CSCI B551 Elements of Artificial Intelligence comment Assignment 4 - Question 2 import random , math import numpy as np from json import load , dump from copy import deepcopy class AdaBoost begin function...
#!usr/bin/python3 # Last Update : December 10, 2017 # Author : Dhaval R Niphade # Course : CSCI B551 Elements of Artificial Intelligence # Assignment 4 - Question 2 import random, math import numpy as np from json import load, dump from copy import deepcopy class AdaBoost(): def __init__(self,trai...
Python
zaydzuhri_stack_edu_python
import numpy as np from numpy import linalg as alglin from scipy.special import lambertw as W import matplotlib from params import * from spline import * import matplotlib.pyplot as plt set tn = 0 set tn1 = 0 set Un = 0 set h = 0 function f t U begin set diff = call V t - U return call k * norm call dV t * diff / norm ...
import numpy as np from numpy import linalg as alglin from scipy.special import lambertw as W import matplotlib from params import * from spline import * import matplotlib.pyplot as plt tn = tn1 = Un = h = 0 def f(t, U): diff = V(t) - U return k() * alglin.norm(dV(t)) * diff/alglin.norm(diff) def g(U): return Un ...
Python
zaydzuhri_stack_edu_python
function twitter_v2s self begin return get pulumi self string twitter_v2s end function
def twitter_v2s(self) -> Sequence['outputs.GetLinuxFunctionAppAuthSettingsV2TwitterV2Result']: return pulumi.get(self, "twitter_v2s")
Python
nomic_cornstack_python_v1
function write_dialogue condition cond_line write_line file begin if condition cond_line begin write file strip write_line + string end else begin write file strip write_line + string end end function
def write_dialogue(condition, cond_line, write_line, file): if condition(cond_line): file.write(write_line.strip() + "\n") else: file.write(write_line.strip() + " ")
Python
nomic_cornstack_python_v1
function _get_description_str epoch_idx begin set total_digits = length string epochs set cur_digits = length string epoch_idx set sup_digits = total_digits - cur_digits set desc_str = string Epoch { string 0 * sup_digits + string epoch_idx + 1 } / { epochs } return desc_str end function
def _get_description_str(epoch_idx): total_digits = len(str(cfg.epochs)) cur_digits = len(str(epoch_idx)) sup_digits = total_digits - cur_digits desc_str = f"Epoch {'0' * (sup_digits) + str(epoch_idx + 1)}/{cfg.epochs}" return desc_str
Python
nomic_cornstack_python_v1
import numpy as np from keras.models import Sequential from keras.layers import Dense , Dropout , Flatten from keras.layers import Conv2D , MaxPooling2D comment create model set model = sequential add model conv 2d 32 kernel_size=tuple 3 3 activation=string relu input_shape=tuple 224 224 3 add model max pooling 2d tupl...
import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D # create model model = Sequential() model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', input_shape=(224, 224, 3))) model.add(MaxPooling2D((2, 2))) model.add(D...
Python
jtatman_500k
function make_sql self tbl ev begin comment parse data set data = call db_urldecode data comment parse tbl info if find type string : > 0 begin set tuple op keys = split type string : end else begin set op = type set keys = extra2 end set key_list = keys set key_list = split keys string , if keep_latest and length key_...
def make_sql(self, tbl, ev): # parse data data = skytools.db_urldecode(ev.data) # parse tbl info if ev.type.find(':') > 0: op, keys = ev.type.split(':') else: op = ev.type keys = ev.extra2 ev.key_list = ...
Python
nomic_cornstack_python_v1
function _has_can self begin return random < can_density end function
def _has_can(self): return random.random() < self.can_density
Python
nomic_cornstack_python_v1
function exit_program cls return_code begin print string Exiting due to: %s % call verbose return_code exit return_code end function
def exit_program(cls, return_code): print("Exiting due to: %s" % (ErrorMessages.verbose(return_code))) sys.exit(return_code)
Python
nomic_cornstack_python_v1
function start update context begin set bot : Bot = bot call send_message chat_id=id text=string Hi there, how can I help you? Use <b>/help</b> command to explore all command options. parse_mode=HTML end function
def start(update: Update, context: CallbackContext): bot: Bot = context.bot bot.send_message( chat_id=update.effective_chat.id, text= """Hi there, how can I help you? Use <b>/help</b> command to explore all command options. """, parse_mode=ParseMode.HTML, )
Python
nomic_cornstack_python_v1
function write data location begin with open location string a+ as text_file begin write text_file data end end function function format_data data begin return string { data at string close_time } | { data at string item } | { data at string user_id } | { data at string status } | { data at string price_paid } | { data...
def write(data, location): with open(location, 'a+') as text_file: text_file.write(data) def format_data(data): return f"{data['close_time']}|{data['item']}|{data['user_id']}|{data['status']}|{data['price_paid']:.2f}|{data['total_bid_count']}|{data['highest_bid']:.2f}|{data['lowest_bid']:.2f}\n"
Python
zaydzuhri_stack_edu_python
string test.py This file contains tests using the unittest framework import unittest import os from kafka_objects.producer import Producer from kafka_objects.consumer import Consumer class TestAccountOperations extends TestCase begin function setUp self begin comment Initialize db connection set db_config = dict string...
''' test.py This file contains tests using the unittest framework ''' import unittest import os from kafka_objects.producer import Producer from kafka_objects.consumer import Consumer class TestAccountOperations(unittest.TestCase): def setUp(self): # Initialize db connection db_config = { ...
Python
zaydzuhri_stack_edu_python
function dirty_cols model begin set cols = join string , dirty_fields return cols or none end function
def dirty_cols(model): cols = ', '.join(model.dirty_fields) return cols or None
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- from Queue import PriorityQueue comment Problem 1 function heapsort array begin set size = length array - 1 for i in range size / 2 - 1 - 1 begin call heapify array i size end for i in range size 0 - 1 begin set tuple array at 0 array at i = tuple array at i array ...
#!/usr/bin/python # -*- coding: utf-8 -*- from Queue import PriorityQueue # Problem 1 def heapsort(array): size = len(array) - 1 for i in range(size / 2, -1, -1): heapify(array, i, size) for i in range(size, 0, -1): array[0], array[i] = array[i], array[0] size -= 1 heapi...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict from nltk.corpus import wordnet as wn from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from portmanteau import Portmanteau from rhyme import Rhyme from global_constants import MAX_NEIGHBORS , NEAR_MISS_VOWELS , NEAR_MISS_CONSONANTS import io function...
from collections import defaultdict from nltk.corpus import wordnet as wn from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from portmanteau import Portmanteau from rhyme import Rhyme from global_constants import MAX_NEIGHBORS, NEAR_MISS_VOWELS, NEAR_MISS_CONSONANTS import io def parse...
Python
zaydzuhri_stack_edu_python
function _start_auto_refresh_thread self begin string Start the background thread that auto refreshes all clients according to `self.status_interval`. function run begin while true begin sleep status_interval call invalidate end end function set t = thread target=run set daemon = true start t end function
def _start_auto_refresh_thread(self): """ Start the background thread that auto refreshes all clients according to `self.status_interval`. """ def run(): while True: time.sleep(self.status_interval) self.invalidate() t = thread...
Python
jtatman_500k
function f_to_c f_temp begin set c_temp = f_temp - 32 * 5 / 9 return c_temp end function set f100_in_celsius = call f_to_c 100 function c_to_f c_temp begin set f_temp = c_temp * 9 / 5 + 32 return f_temp end function set c0_in_fahrenheit = call c_to_f 0 function get_force mass acceleration begin return mass * accelerati...
def f_to_c(f_temp): c_temp = (f_temp - 32) * 5/9 return c_temp f100_in_celsius = f_to_c(100) def c_to_f(c_temp): f_temp = c_temp * (9/5) + 32 return f_temp c0_in_fahrenheit = c_to_f(0) def get_force(mass, acceleration): return mass * acceleration train_mass = 22680 train_acceleration = 10 train...
Python
zaydzuhri_stack_edu_python
function to_timedelta value strict=true begin string converts duration string to timedelta strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration string exceed allowed values if is instance value int begin comment assuming it's seconds return time delta seconds=value end else if...
def to_timedelta(value, strict=True): """ converts duration string to timedelta strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration string exceed allowed values """ if isinstance(value, int): return timedelta(seconds=value) # assuming it's se...
Python
jtatman_500k
function get_all_function_def_arguments self begin set args = list self set args = args + list comprehension call FunctionDefArgument size for size in shape set args = args + list comprehension call FunctionDefArgument stride for stride in strides return args end function
def get_all_function_def_arguments(self): args = [self] args += [FunctionDefArgument(size) for size in self.shape] args += [FunctionDefArgument(stride) for stride in self.strides] return args
Python
nomic_cornstack_python_v1
function load_arquivo_eventos self file begin set tuple validfile mensagem = call valid_file file extensions=list string json string bson string zip if not validfile begin raise exception mensagem end if string zip in filename begin set file = zip file file end set content = read file set content = decode content strin...
def load_arquivo_eventos(self, file): validfile, mensagem = self.valid_file(file, extensions=['json', 'bson', 'zip']) if not validfile: raise Exception(mensagem) if 'zip' in file.filename: file = ZipFile(file) content ...
Python
nomic_cornstack_python_v1
comment Python code comment start HTML tag set html = string <html> comment start table set html = html + string <table style="background: linear-gradient(90deg, #feedba, #fffd, #abdefa, #247ba0);"> comment loop for 10 rows for i in range 10 begin comment start table row set html = html + string <tr> comment loop for 4...
# Python code # start HTML tag html = '<html>\n' # start table html += '<table style="background: linear-gradient(90deg, #feedba, #fffd, #abdefa, #247ba0);">\n' # loop for 10 rows for i in range(10): # start table row html += ' <tr>\n' # loop for 4 columns for j in range(4): # add table cell with index ht...
Python
flytech_python_25k
import math import random from itertools import accumulate seed 12345 function get_uniform a=0 b=1 begin return uniform a b end function function get_exp alpha begin return - log call get_uniform / alpha end function function get_poisson_sample rate n=1 begin return list accumulate list comprehension call get_exp rate ...
import math import random from itertools import accumulate random.seed(12345) def get_uniform(a=0, b=1): return random.uniform(a, b) def get_exp(alpha): return -math.log(get_uniform()) / alpha def get_poisson_sample(rate, n=1): return list(accumulate([get_exp(rate) for i in range(n)])) def get_bern...
Python
zaydzuhri_stack_edu_python
function confirm_drill_mstone request begin if not string ms in GET and call has_perm string shipping.can_ship begin return call HttpResponseRedirect reverse string shipping.views.milestones end try begin set mstone = get objects code=GET at string ms end except any begin return call HttpResponseRedirect reverse string...
def confirm_drill_mstone(request): if not ("ms" in request.GET and request.user.has_perm('shipping.can_ship')): return HttpResponseRedirect(reverse('shipping.views.milestones')) try: mstone = Milestone.objects.get(code=request.GET['ms']) except: return HttpResponseRedirec...
Python
nomic_cornstack_python_v1
function log_type self begin return get pulumi self string log_type end function
def log_type(self) -> str: return pulumi.get(self, "log_type")
Python
nomic_cornstack_python_v1
import MathAndStats as ms import copy import random class PAM begin function __init__ self data k uses_regression min_examples_in_cluster begin print string Finding medoids comment appended to using deep copy, holds the medoids set medoids = list comment appended to using shallow copy, holds the items clustered around...
import MathAndStats as ms import copy import random class PAM: def __init__(self, data, k, uses_regression, min_examples_in_cluster): print("Finding medoids") # appended to using deep copy, holds the medoids self.medoids = [] # appended to using shallow copy, holds the ...
Python
zaydzuhri_stack_edu_python
function is_valid_ip_address ip_addr begin try begin call ip_address ip_addr end except ValueError begin return false end return true end function
def is_valid_ip_address(ip_addr: str) -> bool: try: ip_address(ip_addr) except ValueError: return False return True
Python
nomic_cornstack_python_v1
function visit_Assert self node begin set test = call visit test if msg is not none begin write self string raise %s unless %s % tuple call visit msg test end else begin write self string raise unless %s % test end end function
def visit_Assert(self, node): test = self.visit(node.test) if node.msg is not None: self.write("raise %s unless %s" % (self.visit(node.msg), test)) else: self.write("raise unless %s" % test)
Python
nomic_cornstack_python_v1
import numpy as np import pdb comment Function to create point cloud file function create_output vertices colors filename begin set colors = reshape colors - 1 3 set vertices = horizontal stack list reshape vertices - 1 3 colors comment 必须先写入,然后利用write()在头部插入ply header call savetxt filename vertices fmt=string %f %f %f...
import numpy as np import pdb # Function to create point cloud file def create_output(vertices, colors, filename): colors = colors.reshape(-1, 3) vertices = np.hstack([vertices.reshape(-1, 3), colors]) np.savetxt(filename, vertices, fmt='%f %f %f %d %d %d') # 必须先写入,然后利用write()在头部插入ply header ply_hea...
Python
zaydzuhri_stack_edu_python
function own_app self begin if not _own_app begin update self end return _own_app end function
def own_app(self) -> str: if not self._own_app: self.update() return self._own_app
Python
nomic_cornstack_python_v1
string Details: Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). Examples: "the-stealth-warrior" gets co...
'''Details: Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). Examples: "the-stealth-warrior" gets conv...
Python
zaydzuhri_stack_edu_python
function lifetime begin pass end function
def lifetime(): pass
Python
nomic_cornstack_python_v1
import re import inspect import os from _src.read_conf import ReadConfig class Utilities begin decorator classmethod function get_method_names_from_obj cls var_object begin string This method allows to get all the function/method names from an given object comment methodList = [method for method in dir(object) if calla...
import re import inspect import os from _src.read_conf import ReadConfig class Utilities: @classmethod def get_method_names_from_obj(cls, var_object): """ This method allows to get all the function/method names from an given object """ # methodList = [method for method in...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- ############################################# comment Developed by Maksym Polshcha (maxp@sterch.net) comment All right reserved, 2012 string Activities for test cass for sterch.conveyor set __author__ = string Maxim Polscha (maxp@sterch.net) set __license__ = string ZPL from threading impo...
### -*- coding: utf-8 -*- ############################################# # Developed by Maksym Polshcha (maxp@sterch.net) # All right reserved, 2012 ####################################################################### """ Activities for test cass for sterch.conveyor """ __author__ = "Maxim Polscha (maxp@sterch.net)...
Python
zaydzuhri_stack_edu_python
for i in range integer input begin set tuple r s = split input print join string map lambda x -> x * integer r s end
for i in range(int(input())): r,s = input().split() print("".join(map(lambda x:x*int(r),s)))
Python
zaydzuhri_stack_edu_python
import torch from torch import nn from torchvision import transforms from torchvision.utils import make_grid from torch.utils.data import DataLoader , Dataset import matplotlib.pyplot as plt import os import numpy as np import pandas as pd from skimage import io , transform import torchvision import torchvision.transfo...
import torch from torch import nn from torchvision import transforms from torchvision.utils import make_grid from torch.utils.data import DataLoader, Dataset import matplotlib.pyplot as plt import os import numpy as np import pandas as pd from skimage import io, transform import torchvision import torchvision.transform...
Python
zaydzuhri_stack_edu_python
function map_def_classes self table begin set definition = call MapperDefinition for rc in call get_table_classes table begin set splitted = split rc set abbreviation = join string splitted at slice : - 1 : set course_number = splitted at - 1 add definition abbreviation allowed=list course_number end return definitio...
def map_def_classes(self, table): definition = MapperDefinition() for rc in self.get_table_classes(table): splitted = rc.split() abbreviation = " ".join(splitted[:-1]) course_number = splitted[-1] definition.add(abbreviation, allowed=[course_number]) ...
Python
nomic_cornstack_python_v1
function getDefaultGetter paramId prefix=GETTER_PREFIX begin return prefix + call relative paramId end function
def getDefaultGetter(paramId, prefix=GETTER_PREFIX): return prefix + util.relative(paramId)
Python
nomic_cornstack_python_v1
function delete_business current_user businessId begin set business = call get_in_module string business businessId set name = name delete if not call existing_module string business name begin return tuple call jsonify dict string success string Business Deleted 200 end return tuple call jsonify dict string warning st...
def delete_business(current_user, businessId): business = get_in_module('business', businessId) name = business.name business.delete() if not existing_module('business', name): return jsonify({'success': 'Business Deleted'}), 200 return jsonify({'warning': 'Business Not Deleted'}), 400
Python
nomic_cornstack_python_v1
function Password begin set password_len_temp = get e1 set password_description = get e2 comment Check numeric. if call isnumeric begin set password_len = integer password_len_temp end else begin call showerror string Error string Please insert numbers only! end comment Natural numbers. if password_len > 0 begin pass e...
def Password(): password_len_temp = e1.get() password_description = e2.get() if password_len_temp.isnumeric(): # Check numeric. password_len = int(password_len_temp) else: tkinter.messagebox.showerror("Error", "Please insert numbers only!") ...
Python
nomic_cornstack_python_v1
function type self begin return get pulumi self string type end function
def type(self) -> str: return pulumi.get(self, "type")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment Miscellaneous parts of conditions comment pass can be used as placeholder set number = input string Please input a number: if integer number == 7 begin print string The magic number has been input!!! end print string You input + number print string An equivalent if block but more r...
#!/usr/bin/env python3 # Miscellaneous parts of conditions # pass can be used as placeholder number = input('Please input a number: '); if int(number) == 7: print("The magic number has been input!!!") print("You input " + number) print("An equivalent if block but more readable") if int(number) == 7: print("...
Python
zaydzuhri_stack_edu_python
comment import numpy as np from typing import List import fire import pandas as pd class Chunk begin function __init__ self begin set morphs = list set dst = - 1 set srcs = list end function comment def print_all(self): comment return self.morphs + "\t" + self.dst + ", " + self.srcs function __repr__ self begin if mo...
# import numpy as np from typing import List import fire import pandas as pd class Chunk: def __init__(self): self.morphs = [] self.dst = -1 self.srcs = [] # def print_all(self): # return self.morphs + "\t" + self.dst + ", " + self.srcs def __repr__(self): if self.mor...
Python
zaydzuhri_stack_edu_python
import datetime import errno import os from pathlib import Path from factory_output.printer import Printer class FilePrinter extends Printer begin function __init__ self begin pass end function function print self data begin set path = string { string call home } /Desktop/FindStatsApp call _mkdir_p path set now = now s...
import datetime import errno import os from pathlib import Path from factory_output.printer import Printer class FilePrinter(Printer): def __init__(self): pass def print(self, data): path = f"{str(Path.home())}/Desktop/FindStatsApp" FilePrinter._mkdir_p(path) now = datetime.d...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import getopt import sys
#!/usr/bin/python import getopt import sys
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import matplotlib.pyplot as plt import scipy from scipy import stats from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.m...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import scipy from scipy import stats from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.m...
Python
zaydzuhri_stack_edu_python
string import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A")) string s = 0 for d in range(0, 5, 0.1): s += d print(s) string def f(x = 100, y = 100): return(x+y, x-y) x, y = f(y = 200, x = 100) print(x, y) string class Ex: def __init__(self): self.name="pulkit" def fun1(self,name2): self.name...
"""import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A")) """ """s = 0 for d in range(0, 5, 0.1): s += d print(s)""" """def f(x = 100, y = 100): return(x+y, x-y) x, y = f(y = 200, x = 100) print(x, y)""" """class Ex: def __init__(self): self.name="pulkit" def fun1(self,n...
Python
zaydzuhri_stack_edu_python
function format_uid cls uid begin if uid == UID_NOT_SUPPORTED begin return string UID not supported in this part end if uid == UID_ADDRESS_UNKNOWN begin return string UID address unknown end set swapped_data = list comprehension list comprehension uid at b for b in part for part in UID_SWAP set uid_string = join string...
def format_uid(cls, uid): if uid == cls.UID_NOT_SUPPORTED: return "UID not supported in this part" if uid == cls.UID_ADDRESS_UNKNOWN: return "UID address unknown" swapped_data = [[uid[b] for b in part] for part in Stm32Bootloader.UID_SWAP] uid_string = "-".join("...
Python
nomic_cornstack_python_v1
function turtle_trade self row begin if trades_open_count > 0 begin if low < low_20d begin call sell_all_open_trades low_20d date set trades_open_count = 0 end else if high > next_entry begin for t in array range high_55d high TR_EMA / 2 begin if trades_open_count < 4 and t > next_entry begin call buy date max t open i...
def turtle_trade(self, row): if self.trades_open_count > 0: if row.low < row.low_20d: self.sell_all_open_trades(row.low_20d, row.date) self.trades_open_count = 0 elif row.high > self.next_entry: for t in np.arange(row.high_55d, row.high, ro...
Python
nomic_cornstack_python_v1
function SshCopyFiles srcs host dst begin set command = list string scp srcs host + string : + dst set result = call RunCommand command if result begin raise call ExternalError string Failed to scp "%s" to "%s" (%s) % tuple srcs host + string : + dst result end end function
def SshCopyFiles(srcs, host, dst): command = ['scp', srcs, host + ':' + dst] result = RunCommand(command) if result: raise ExternalError('Failed to scp "%s" to "%s" (%s)' % (srcs, host + ':' + dst, result))
Python
nomic_cornstack_python_v1
function f2 self sample_sets indexes=none windows=none mode=string site span_normalise=true begin return call __k_way_sample_set_stat f2 2 sample_sets indexes=indexes windows=windows mode=mode span_normalise=span_normalise end function
def f2( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): return self.__k_way_sample_set_stat( self._ll_tree_sequence.f2, 2, sample_sets, indexes=indexes, windows=windows, mode=mode, ...
Python
nomic_cornstack_python_v1
import random print string I want you to guess a number between one and ten set NUMB = random integer 1 11 set SEQ_TRY = 0 set MAX_TRY = 5 set USER_INPUT = none set SEQ_TRY = 0 while SEQ_TRY < MAX_TRY begin set SEQ_TRY = SEQ_TRY + 1 set GOOD_TRY = true try begin set USER_INPUT = integer input string try to guess number...
import random print('I want you to guess a number between one and ten') NUMB=random.randint(1,11) SEQ_TRY=0 MAX_TRY =5 USER_INPUT=None SEQ_TRY =0 while SEQ_TRY < MAX_TRY: SEQ_TRY += 1 GOOD_TRY=True try: USER_INPUT =int(input('try to guess number which thinking computer, input the number: \n')) ...
Python
zaydzuhri_stack_edu_python
function remove_stop_words sentence begin set stop_words = call words string english comment Removing punctuation increases accuracy. extend stop_words tuple string , string . set filtered_sent = list comprehension w for w in sentence if lower w not in stop_words return filtered_sent end function
def remove_stop_words(sentence): stop_words = stopwords.words('english') stop_words.extend((',', '.')) # Removing punctuation increases accuracy. filtered_sent = [w for w in sentence if w.lower() not in stop_words] return filtered_sent
Python
nomic_cornstack_python_v1
import psycopg2 from app.api.models.database.connection import connect import psycopg2.extras as extra class QueryMenuTable begin function __init__ self begin set conn = call connect set autocommit = true set cursor = call cursor set dict_cursor = call cursor cursor_factory=DictCursor end function function add_item sel...
import psycopg2 from app.api.models.database.connection import connect import psycopg2.extras as extra class QueryMenuTable(): def __init__(self): self.conn = connect() self.conn.autocommit = True self.cursor = self.conn.cursor() self.dict_cursor = self.conn.cursor( cur...
Python
zaydzuhri_stack_edu_python
comment https://adventofcode.com/2020/day/2 set input_file = open string ../inputs/day-2.txt string r set lines = read lines input_file comment lines = [ comment '1-3 a: abcde', comment '1-3 b: cdefg', comment '2-9 c: ccccccccc' comment ] set valid_passwords = 0 for line in lines begin set password_policy = line set pa...
# https://adventofcode.com/2020/day/2 input_file = open('../inputs/day-2.txt', 'r') lines = input_file.readlines() # lines = [ # '1-3 a: abcde', # '1-3 b: cdefg', # '2-9 c: ccccccccc' # ] valid_passwords = 0 for line in lines: password_policy = line password = password_policy.split(' ')[2] letter...
Python
zaydzuhri_stack_edu_python
class Solution begin function destCity self paths begin set a = set set b = set for p in paths begin add a p at 0 add a p at 1 add b p at 0 end return pop a - b end function end class
class Solution: def destCity(self, paths: List[List[str]]) -> str: a = set() b = set() for p in paths: a.add(p[0]) a.add(p[1]) b.add(p[0]) return (a - b).pop()
Python
zaydzuhri_stack_edu_python
function peak_to_subpeak_list chrom start end begin set num_subpeaks = integer end - integer start // 60 set start_list = list range start end 60 set end_list = start_list at slice 1 : : append end_list start_list at - 1 + 60 set subpeak_lists = list comprehension tuple chrom s e for tuple s e in zip start_list end_l...
def peak_to_subpeak_list(chrom,start,end): num_subpeaks = int(end) - int(start) // 60 start_list = list(range(start,end,60)) end_list = start_list[1:] end_list.append(start_list[-1] + 60) subpeak_lists = [(chrom,s,e) for s,e in zip(start_list,end_list)] return subpeak_lists
Python
nomic_cornstack_python_v1
import numpy as np from numpy import linalg as LA function f1 x a b begin return a * sin x at 0 + b * cos x at 1 end function function f2 x a b begin return x at 0 - a ^ 2 + x at 0 * x at 1 + x at 1 - b ^ 2 end function function df1_1 x a b begin return a * cos x at 0 end function function df1_2 x a b begin return - b ...
import numpy as np from numpy import linalg as LA def f1(x,a,b): return a*np.math.sin(x[0]) + b*np.math.cos(x[1]) def f2(x,a,b): return (x[0] - a)**2 + x[0]*x[1] + (x[1] - b)**2 def df1_1(x,a,b): return a*np.math.cos(x[0]) def df1_2(x,a,b): return -b*np.math.sin(x[1]) def df2_1(x,a,b): return -...
Python
zaydzuhri_stack_edu_python
function accuracy output target topk=tuple 1 begin with no grad begin set maxk = max topk set batch_size = size target 0 set tuple _ pred = call topk maxk 1 true true set pred = t dist set correct = call eq call expand_as pred set res = list for k in topk begin set correct_k = sum 0 keepdim=true append res call mul_ 1...
def accuracy(output, target, topk=(1,)): with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: c...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Aug 9 19:07:08 2017 @author: petur import pandas as pd import time from tpot import TPOTClassifier from sklearn.svm import SVC import petur_functions as petur comment In[Load data and prepare] comment Load data from csv set df_name = string Working_Dataset/MAIN_FULL.c...
# -*- coding: utf-8 -*- """ Created on Wed Aug 9 19:07:08 2017 @author: petur """ import pandas as pd import time from tpot import TPOTClassifier from sklearn.svm import SVC import petur_functions as petur # In[Load data and prepare] # Load data from csv df_name = "Working_Dataset/MAIN_FULL.csv" df = pd.read_cs...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment Trước khi đi vào chương này chúng ta sẽ cùng tìm hiểu các thuật ngữ được đối sánh giữa Tiếng Việt và Tiếng Anh: comment * Học có giám sát: Supervised Learning comment * Học không giám sát: Unsupervised Learning comment * Tập huấn luyện: Tập train comment * Tập ...
#!/usr/bin/env python # coding: utf-8 # Trước khi đi vào chương này chúng ta sẽ cùng tìm hiểu các thuật ngữ được đối sánh giữa Tiếng Việt và Tiếng Anh: # # * Học có giám sát: Supervised Learning # * Học không giám sát: Unsupervised Learning # * Tập huấn luyện: Tập train # * Tập kiểm tra: Tập test # * Hồi qui: Regress...
Python
zaydzuhri_stack_edu_python
string Extended Huckel Theory Compute overlap matrix comment from input_molecule import create_methane import numpy as np from math import factorial as bang comment atoms,positions,basis = create_ammonia() string First we have some short functions to calculate particular quantities in the radial overlap integral below,...
""" Extended Huckel Theory Compute overlap matrix """ #from input_molecule import create_methane import numpy as np from math import factorial as bang #atoms,positions,basis = create_ammonia() """ First we have some short functions to calculate particular quantities in the radial overlap integral below, written sep...
Python
zaydzuhri_stack_edu_python
import pygame , sys from pygame.locals import * import time import random function rcircle size begin set tuple r g b = tuple random integer 0 255 random integer 0 255 random integer 0 255 set rpos = tuple random integer 0 size at 0 random integer 0 size at 1 comment 半径不大于四分之一窗口高度 set rradius = random integer 10 size a...
import pygame,sys from pygame.locals import * import time import random def rcircle(size): r,g,b = random.randint(0,255),random.randint(0,255),random.randint(0,255) rpos = (random.randint(0,size[0]),random.randint(0,size[1])) rradius = random.randint(10,size[1] // 4) # 半径不大于四分之一窗口高度 rwidth = r...
Python
zaydzuhri_stack_edu_python
from django.test import TestCase class TestBase extends TestCase begin string Test base Have assertContent method for easy test multiple contents function assertContents self contents begin for expected_content in contents begin with call subTest begin call assertContains response expected_content end end end function ...
from django.test import TestCase class TestBase(TestCase): """Test base Have assertContent method for easy test multiple contents""" def assertContents(self, contents): for expected_content in contents: with self.subTest(): self.assertContains(self.response, expected_cont...
Python
zaydzuhri_stack_edu_python
function ct_transpile cfg begin if is file path join path config at string SRV_DIR string ignition cfg + string .yaml begin set cfg_file = join path config at string SRV_DIR string ignition cfg + string .yaml end else if is file path join path config at string SRV_DIR string ignition cfg + string .yml begin set cfg_fil...
def ct_transpile(cfg): if path.isfile(path.join(app.config['SRV_DIR'], 'ignition', cfg + '.yaml')): cfg_file = path.join(app.config['SRV_DIR'], 'ignition', cfg + '.yaml') elif path.isfile(path.join(app.config['SRV_DIR'], 'ign...
Python
nomic_cornstack_python_v1
function _delete self managed=true resource_id=none resource_type=string instance criterion=dict begin set context = call elevated set all_tenants = true set edit_managed_records = true update criterion dict string domain_id domain_id if managed begin update criterion dict string managed managed ; string managed_plugin...
def _delete(self, managed=True, resource_id=None, resource_type='instance', criterion={}): context = DesignateContext().elevated() context.all_tenants = True context.edit_managed_records = True criterion.update({'domain_id': cfg.CONF[self.name].domain_id}) if ma...
Python
nomic_cornstack_python_v1
function contact_us_view request begin return call render request string home/contact.html end function
def contact_us_view(request): return render(request, 'home/contact.html')
Python
nomic_cornstack_python_v1
comment Python 3.7.x comment https://projecteuler.net/problem=36 string There is a deliberate logical error in the code. Do you understand Python for a long time to find her. set summ = 0 for x in range 1 1000000 begin if string x at slice : : == string x at slice : : - 1 begin set st = string binary x at slice 2 ...
#Python 3.7.x #https://projecteuler.net/problem=36 """ There is a deliberate logical error in the code. Do you understand Python for a long time to find her. """ summ = 0 for x in range(1,1000000): if str(x)[:] == str(x)[::-1]: st = str(bin(x))[2:] if st[:] != st[::-1]: summ += x print(...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import torch import numpy as np comment 创建tensor的多种方式 set tensor1 = tensor 2 3 print tensor1 string tensor([[-2.2565e+07, 4.5842e-41, -5.3370e+08], [ 4.5842e-41, 4.4842e-44, 0.0000e+00]]) set tensor2 = call rand 2 3 print tensor2 string tensor([[ 0.2535, 0.0926, 0.7768], [ 0.8807, 0.6189, ...
# -*- coding: utf-8 -*- import torch import numpy as np # 创建tensor的多种方式 tensor1 = torch.Tensor(2, 3) print(tensor1) ''' tensor([[-2.2565e+07, 4.5842e-41, -5.3370e+08], [ 4.5842e-41, 4.4842e-44, 0.0000e+00]]) ''' tensor2 = torch.rand(2, 3) print(tensor2) ''' tensor([[ 0.2535, 0.0926, 0.7768], [ 0...
Python
zaydzuhri_stack_edu_python
from pymongo import MongoClient comment estabelecendo a conexao set cliente = call MongoClient string localhost 27017 comment criando um banco set banco = santander comment criando collections set colecao = clientes while true begin print string { string Menu } set op = integer input string 1. Inserir dados 2. Exibir d...
from pymongo import MongoClient # estabelecendo a conexao cliente = MongoClient('localhost',27017) banco = cliente.santander# criando um banco colecao = banco.clientes# criando collections while True: print(f"{' Menu ':^40}") op = int(input(''' 1. Inserir dados 2. Exibir dados 3. Excl...
Python
zaydzuhri_stack_edu_python
function get_n_trials self study_id state=none begin raise NotImplementedError end function
def get_n_trials(self, study_id: int, state: Optional[TrialState] = None) -> int: raise NotImplementedError
Python
nomic_cornstack_python_v1
class PremiumBasePaymentGateway begin function __init__ self retry=3 begin set retry = retry end function function process self data begin while retry > 0 begin if data is not none begin return true end set retry = retry - 1 end return false end function end class
class PremiumBasePaymentGateway: def __init__(self, retry=3): self.retry = retry def process(self, data): while self.retry > 0: if data is not None: return True self.retry -= 1 return False
Python
zaydzuhri_stack_edu_python