code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import re import os class REPRLoop begin string Основной бесконечный оработчик function __init__ self storage_file begin set PARSE_ERROR = - 1 set storage_file = storage_file set phone_pattern = compile string ^\d\(\d{3}\)-\d{3}-\d{2}-\d{2}$ set FIO_pattern = compile string ^[А-я]+? [А-я]+? [А-я]+?$ end function functi...
import re import os class REPRLoop: """Основной бесконечный оработчик""" def __init__(self, storage_file): self.PARSE_ERROR = -1 self.storage_file = storage_file self.phone_pattern = re.compile(r"^\d\(\d{3}\)-\d{3}-\d{2}-\d{2}$") self.FIO_pattern = re.compile(r"^[А-я]+? [А-я]+? [А-я]+?$") def run(self): ...
Python
zaydzuhri_stack_edu_python
function generate_phantom gtab S0t=50 S0w=100 snr=none dir_sigma=none begin function circular_mask rows cols center radius begin set tuple X Y = ogrid at tuple slice : rows : slice : cols : set dist_from_center = square root X - center at 0 ^ 2 + Y - center at 1 ^ 2 set mask = dist_from_center <= radius return mask...
def generate_phantom(gtab, S0t=50, S0w=100, snr=None, dir_sigma=None): def circular_mask(rows, cols, center, radius): X, Y = np.ogrid[:rows, :cols] dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2) mask = dist_from_center <= radius return mask phantom = np.zeros(...
Python
nomic_cornstack_python_v1
string 本题要求编写程序,根据输入的三角形的三条边a、b、c,计算并输出面积和周长。注意:在一个三角形中, 任意两边之和大于第三边。三角形面积计算公式:area=√ ​s(s−a)(s−b)(s−c),其中s=(a+b+c)/2。 输入格式: 输入为3个正整数,分别代表三角形的3条边a、b、c。 输出格式: 如果输入的边能构成一个三角形,则在一行内,按照area = 面积; perimeter = 周长 的格式输出,保留两位小数。否则,输出These sides do not correspond to a valid triangle set tuple a b c = split input set tuple a b c...
'''本题要求编写程序,根据输入的三角形的三条边a、b、c,计算并输出面积和周长。注意:在一个三角形中, 任意两边之和大于第三边。三角形面积计算公式:area=√ ​s(s−a)(s−b)(s−c),其中s=(a+b+c)/2。 输入格式: 输入为3个正整数,分别代表三角形的3条边a、b、c。 输出格式: 如果输入的边能构成一个三角形,则在一行内,按照area = 面积; perimeter = 周长 的格式输出,保留两位小数。否则,输出These sides do not correspond to a valid triangle''' a, b, c = input().split() a, b, c = int(a), in...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import re set path1 = string E:\dataset\domain_sentiment_data\sorted_data_acl\dvd\negative.review set path2 = string E:\dataset\domain_sentiment_data\sorted_data_acl\dvd\review_text_neg set path3 = string E:\dataset\domain_sentiment_data\sorted_data_acl\dvd\review_score_neg set path4 = stri...
#-*- coding:utf-8 -*- import re path1 = 'E:\\dataset\\domain_sentiment_data\\sorted_data_acl\\dvd\\negative.review' path2 = 'E:\\dataset\\domain_sentiment_data\\sorted_data_acl\\dvd\\review_text_neg' path3 = 'E:\\dataset\\domain_sentiment_data\\sorted_data_acl\\dvd\\review_score_neg' path4 = 'E:\\dataset\\domain_sent...
Python
zaydzuhri_stack_edu_python
comment Author: coderjelly comment Script in Python demonstrating QuickSort function Swap A i j begin if i == j begin return end set temp = A at i set A at i = A at j set A at j = temp end function function QuickSort A p r begin if p >= r begin return end set q = call Partition A p r call QuickSort A p q - 1 call Quick...
# Author: coderjelly # Script in Python demonstrating QuickSort def Swap(A,i,j): if i == j: return temp = A[i] A[i] = A[j] A[j] = temp def QuickSort(A,p,r): if p >= r: return q = Partition(A,p,r) QuickSort(A,p,q-1) QuickSort(A,q+1,r) def Partition(A,p,r): pivot = A[r] i = p - 1 for j in range(p,r): ...
Python
zaydzuhri_stack_edu_python
function solveAndNotify self request begin string Notifies the owner of the current request (so, the user doing the exercise) that they've solved the exercise, and mark it as solved in the database. set remote = remote set withThisIdentifier = identifier == exerciseIdentifier set exercise = call findUnique Exercise wit...
def solveAndNotify(self, request): """Notifies the owner of the current request (so, the user doing the exercise) that they've solved the exercise, and mark it as solved in the database. """ remote = request.transport.remote withThisIdentifier = Exercise.identifier == se...
Python
jtatman_500k
function pad_images samples nmaxpooling=4 begin set tuple nsamples W Z nchannels = shape set nw = nmaxpooling ^ 2 - W % 2 ^ nmaxpooling set nz = nmaxpooling ^ 2 - Z % 2 ^ nmaxpooling if nw == 0 and nz == 0 begin return tuple samples 0 0 end set samples_padded = concatenate tuple samples zeros tuple nsamples W nz nchann...
def pad_images(samples,nmaxpooling = 4): nsamples,W,Z,nchannels = samples.shape nw = nmaxpooling**2-W%(2**nmaxpooling) nz = nmaxpooling**2-Z%(2**nmaxpooling) if nw == 0 and nz ==0: return samples,0,0 samples_padded = np.concatenate((samples,np.zeros((nsamples,W,nz,nchannels))),axis = 2) ...
Python
nomic_cornstack_python_v1
function check_guess random_number user_guess guess_range begin if user_guess == random_number begin return true end else if user_guess < 1 or user_guess > guess_range begin print string Thats not even in the number range!! return false end else if user_guess < random_number begin print string Too Low! return false end...
def check_guess(random_number, user_guess, guess_range): if user_guess == random_number: return True else: if (user_guess < 1) or (user_guess > guess_range): print("Thats not even in the number range!!") return False elif user_guess < random_number: ...
Python
nomic_cornstack_python_v1
function create_gif_from_traj traj_name=string qn.traj path_i=string . image_range=string 0:5 delay=10 rotation=string 0x, 0y, 0z begin comment "all" comment | - create_gif_from_traj comment | - Method Parameters set atoms_file_name = string out_movie set fold_name = string images comment __| comment | - Creating png *...
def create_gif_from_traj( traj_name="qn.traj", path_i=".", image_range="0:5", # "all" delay=10, rotation="0x, 0y, 0z", ): # | - create_gif_from_traj # | - Method Parameters atoms_file_name = "out_movie" fold_name = "images" # __| # | - Creating png *******************...
Python
nomic_cornstack_python_v1
comment Dimension reduction comment ● More efficient storage and computation comment ● Remove less-informative "noise" features comment ● ... which cause problems for prediction tasks, e.g. comment classification, regression comment # Correlated data in nature comment You are given an array grains giving the width and ...
# Dimension reduction # ● More efficient storage and computation # ● Remove less-informative "noise" features # ● ... which cause problems for prediction tasks, e.g. # classification, regression # # Correlated data in nature # You are given an array grains giving the width and length of samples of grain. You suspect t...
Python
zaydzuhri_stack_edu_python
comment @lc app=leetcode id=158 lang=python3 comment [158] Read N Characters Given Read4 II - Call multiple times comment @lc code=start comment The read4 API is already defined for you. comment def read4(buf4: List[str]) -> int: class Solution begin function __init__ self begin set buf4 = list string * 4 comment curr...
# # @lc app=leetcode id=158 lang=python3 # # [158] Read N Characters Given Read4 II - Call multiple times # # @lc code=start # The read4 API is already defined for you. # def read4(buf4: List[str]) -> int: class Solution: def __init__(self): self.buf4 = ['']* 4 # current internal buffer position ...
Python
zaydzuhri_stack_edu_python
function read_file_line_by_line file_name begin set lines = list with open file_name string r as f begin set content = read lines f for line in content begin append lines line end end return lines end function
def read_file_line_by_line(file_name): lines = [] with open(file_name, 'r') as f: content = f.readlines() for line in content: lines.append(line) return lines
Python
nomic_cornstack_python_v1
string This script is inspired by https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/census/tf-keras/trainer/model.py. The input_fn() function is used to take our datasets (which are numpy.array objects) and make them tf.data.Dataset(s). The create_keras_model() function is a nice and simple wrapper to ...
""" This script is inspired by https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/census/tf-keras/trainer/model.py. The input_fn() function is used to take our datasets (which are numpy.array objects) and make them tf.data.Dataset(s). The create_keras_model() function is a nice and simple wrapper to c...
Python
zaydzuhri_stack_edu_python
function move dir begin global x global y if dir == string north begin if y == 0 or y == 9 begin pass end else begin set y = y - 1 end end else if dir == string south begin if y == 0 or y == 9 begin pass end else begin set y = y + 1 end end else if dir == string east begin if x == 0 or x == 9 begin pass end else begin ...
def move(dir:str): global x global y if dir == 'north': if y == 0 or y == 9: pass else: y -= 1 elif dir == 'south': if y == 0 or y == 9: pass else: y +=1 elif dir == 'east': if x == 0 or x == 9: pass else: x += 1 elif dir == 'west': if x == 0 or x == 9: pass else: x -=1 el...
Python
zaydzuhri_stack_edu_python
function prediction_accuracy clf X_train y_train X_test y_test resample_test=true resample_size=1 begin set tuple y_pred csmf_pred = predict fit clf X_train y_train X_test comment All the outputs should be dataframes which can be concatentated and comment saved without the index set preds = concat list y_test y_pred ax...
def prediction_accuracy(clf, X_train, y_train, X_test, y_test, resample_test=True, resample_size=1): y_pred, csmf_pred = clf.fit(X_train, y_train).predict(X_test) # All the outputs should be dataframes which can be concatentated and # saved without the index preds = pd.concat([...
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter.ttk import * from time import strftime set root = call Tk title root string Clock set icon = call PhotoImage file=string D:/Python Project/Clock.png call iconphoto root icon call resizable false false function time begin set string = string format time string %H:%M:%S %p call config t...
from tkinter import * from tkinter.ttk import * from time import strftime root = Tk() root.title("Clock") icon = PhotoImage(file="D:/Python Project/Clock.png") root.iconphoto(root, icon) root.resizable(False, False) def time(): string = strftime('%H:%M:%S %p') label.config(text=string) la...
Python
zaydzuhri_stack_edu_python
import re function slices series length begin if search string \D series begin raise call ValueError string Series must be made up of digits only. end set len_s = length series if length < 1 ? len_s < length begin raise call ValueError string Slice and series lengths must be greater than 0. end return list comprehensio...
import re def slices(series, length): if re.search('\D', series): raise ValueError('Series must be made up of digits only.') len_s = len(series) if (length < 1) | (len_s < length): raise ValueError('Slice and series lengths must be greater than 0.') return [series[i:i+length] for i in r...
Python
zaydzuhri_stack_edu_python
function test_save_base_metadata self begin call save_base_metadata comment cleanup call delete_base_metadata end function
def test_save_base_metadata(self): self.save_base_metadata() # cleanup self.delete_base_metadata()
Python
nomic_cornstack_python_v1
import random function CodeStr requsest begin string 生成一个包含大小写的4位随机验证码 :return: set code_str = string for i in range 4 begin set num = random integer 0 9 comment a-z set low_al = character random integer 97 122 comment 65-91对应字符A-Z set upper_al = character random integer 65 90 set random_one = random choice list num l...
import random def CodeStr(requsest): ''' 生成一个包含大小写的4位随机验证码 :return: ''' code_str = '' for i in range(4): num = random.randint(0,9) low_al = chr(random.randint(97, 122)) # a-z upper_al = chr(random.randint(65, 90)) # 65-91对应字符A-Z random_one = random.choice([num...
Python
zaydzuhri_stack_edu_python
function cmd_not_understood self line begin call respond string 500 Command "%s" not understood. % line end function
def cmd_not_understood(self, line): self.respond('500 Command "%s" not understood.' %line)
Python
nomic_cornstack_python_v1
function trainedLSTMNN begin set n = call buildNetwork 100 50 1 hiddenclass=LSTMLayer outputbias=false recurrent=true end function
def trainedLSTMNN(): n = buildNetwork(100, 50, 1, hiddenclass = LSTMLayer, outputbias=False, recurrent = True)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import os import getpass import paramiko import re from scp import SCPClient call log_to_file string auto_log function ping_check hostname username password begin string Function that does a Ping Check on the hosts string Usually the http_config only runs when the ping check is successful, but ...
#!/usr/bin/python import os import getpass import paramiko import re from scp import SCPClient paramiko.util.log_to_file("auto_log") def ping_check(hostname, username, password): """Function that does a Ping Check on the hosts""" """Usually the http_config only runs when the ping check is successful, but in ...
Python
zaydzuhri_stack_edu_python
function cmd_calc inp begin set allowed_chars = string 0123456789.+-*/() set par = 0 for i in range 0 length inp begin if inp at i not in allowed_chars begin return next string Unknown syntax end end for else begin comment for's else try begin set out = eval inp end except SyntaxError begin return next string Syntax er...
def cmd_calc(inp): allowed_chars = " 0123456789.+-*/()" par = 0; for i in range(0, len(inp)): if inp[i] not in allowed_chars: return state.next("Unknown syntax") else: # for's else try: out = eval(inp) except SyntaxError: return state.next("...
Python
nomic_cornstack_python_v1
function initArtists begin set axArtistsArray = list comprehension list comprehension plot list list for _ in range 4 for _ in range 3 set first_image_lists = list r_list at 0 y_list at 0 g_list at 0 comment 3 rows for i in range 3 begin set tuple bin_centers h_hist s_hist v_hist = call hsv_histograms first_image_list...
def initArtists(): axArtistsArray = [[plt.plot([],[]) for _ in range(4)] for _ in range(3)] first_image_lists = [r_list[0], y_list[0], g_list[0]] for i in range(3): # 3 rows (bin_centers, h_hist, s_hist, v_hist) = hsv_histograms(first_image_lists[i]) ...
Python
nomic_cornstack_python_v1
function _align_face img face begin set centers = call calc_parts_center face set angle = call _calculate_face_z_alignment_angle centers return call rotate_image img angle centers at string nose-center end function
def _align_face(img, face): centers = util.calc_parts_center(face) angle = _calculate_face_z_alignment_angle(centers) return util.rotate_image(img, angle, centers['nose-center'])
Python
nomic_cornstack_python_v1
function parse_presence_model self default=none begin set cfg_presence_model = find cfg_root string presence_model if cfg_presence_model and text in VALID_TEMP_MODEL begin set cfg_presence_model = text end else begin set cfg_presence_model = default end return cfg_presence_model end function
def parse_presence_model(self, default=None): cfg_presence_model = self.cfg_root.find('presence_model') if cfg_presence_model and cfg_presence_model.text in self.VALID_TEMP_MODEL: cfg_presence_model = cfg_presence_model.text else: cfg_presence_model = default return cfg_presence_model
Python
nomic_cornstack_python_v1
function get_view_name view_cls suffix=none begin string Given a view class, return a textual name to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_NAME_FUNCTION` setting. set name = __name__ set name = call remove_trailing_string name s...
def get_view_name(view_cls, suffix=None): """ Given a view class, return a textual name to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_NAME_FUNCTION` setting. """ name = view_cls.__name__ name = formatting....
Python
jtatman_500k
string Users forms. comment Django from django import forms comment Models from django.contrib.auth.models import User from users.models import Profile class SignupForm extends Form begin string Signup form. set username = call CharField min_length=4 max_length=50 label=false widget=call TextInput attrs=dict string pla...
""" Users forms. """ #Django from django import forms #Models from django.contrib.auth.models import User from users.models import Profile class SignupForm(forms.Form): """ Signup form. """ username = forms.CharField( min_length=4, max_length=50, label=False, widget=forms...
Python
zaydzuhri_stack_edu_python
function goto reference_beats estimated_beats goto_threshold=0.35 goto_mu=0.2 goto_sigma=0.2 begin string Calculate Goto's score, a binary 1 or 0 depending on some specific heuristic criteria Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt') >>> reference_beats = mir_eval.beat.trim_beats(...
def goto(reference_beats, estimated_beats, goto_threshold=0.35, goto_mu=0.2, goto_sigma=0.2): """Calculate Goto's score, a binary 1 or 0 depending on some specific heuristic criteria Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt')...
Python
jtatman_500k
function _get_coloured_if_sorting self to_print sort_param=none begin set uncoloured_string = string { to_print } : { get attribute self to_print } if to_print != sort_param begin return uncoloured_string end return LIGHTBLUE_EX + BLACK + string { uncoloured_string } + RESET_ALL end function
def _get_coloured_if_sorting(self, to_print: str, sort_param: str = None): uncoloured_string = f"{to_print}: {getattr(self, to_print)}" if to_print != sort_param: return uncoloured_string return Back.LIGHTBLUE_EX + Fore.BLACK + f"{uncoloured_string} " + Style.RESET_ALL
Python
nomic_cornstack_python_v1
import random comment d = 0 comment while d < 10: comment print(d) comment d += 1 comment num = random.randint(0, 10) comment inp = int(input()) comment while inp != num: comment print("Wrong Number, one more time!") comment inp = int(input()) set name = input while length name < 8 begin print string WRONG PASSWORD! se...
import random # d = 0 # # while d < 10: # print(d) # d += 1 # # num = random.randint(0, 10) # inp = int(input()) # # while inp != num: # print("Wrong Number, one more time!") # inp = int(input()) name = input() while len(name) < 8: print("WRONG PASSWORD!") name = input() print(name)
Python
zaydzuhri_stack_edu_python
comment AUTHOR: Daniel Raymond comment DATE : 2020-04-29 comment ABOUT : Determines the max value in the final layer and returns its index import ChipsClocked as IC import ChipsAsync as asyncIC from tqdm import tqdm class MaxLogitSelector begin function __init__ self begin call _initChips call _initWiring end function ...
# AUTHOR: Daniel Raymond # DATE : 2020-04-29 # ABOUT : Determines the max value in the final layer and returns its index import ChipsClocked as IC import ChipsAsync as asyncIC from tqdm import tqdm class MaxLogitSelector(): def __init__(self): self._initChips() self._initWiring() def _initCh...
Python
zaydzuhri_stack_edu_python
comment program created by Adam Reed comment started on 5-28-2020 comment finished on 7-3-2020 comment for the UI import tkinter comment for the UI from tkinter import ttk comment for reading csv files import csv comment for saving data in json files import json comment for changing the working directory import os comm...
# program created by Adam Reed # started on 5-28-2020 # finished on 7-3-2020 import tkinter # for the UI from tkinter import ttk # for the UI import csv # for reading csv files import json # for saving data in json files import os # for changing the working directory # ___ Functions & Classes ___ ...
Python
zaydzuhri_stack_edu_python
import enum import os import pickle from copy import copy from typing import Tuple import pygame as pg from block import Block from entity import ENTITY_T from entity_factory import entity_factory class Level begin function __init__ self name h=10 w=20 field=none begin set h = h set w = w set name = name comment Init s...
import enum import os import pickle from copy import copy from typing import Tuple import pygame as pg from block import Block from entity import ENTITY_T from entity_factory import entity_factory class Level(): def __init__(self, name, h=10, w=20, field=None): self.h = h self.w = w self...
Python
zaydzuhri_stack_edu_python
function _connect self begin set proxy = get proxies if expression is_secure then string https else string http if proxy begin set sock = call _connect_proxy proxy set proxy_url = proxy end else begin set sock = call _connect_sock host port ssl=is_secure set proxy_url = none end comment The timeout makes the socket non...
def _connect(self): proxy = self.websocket.proxies.get( 'https' if self.websocket.is_secure else 'http' ) if proxy: sock = self._connect_proxy(proxy) proxy_url = proxy else: sock = self._connect_sock( self.websocket.host, ...
Python
nomic_cornstack_python_v1
function employee_data usr_id begin set num_done_t = 0 set total_t = 0 set empl = get requests format string https://jsonplaceholder.typicode.com/users/{} usr_id set name = get json empl string name set todos = get requests string https://jsonplaceholder.typicode.com/todos set list_completed = list for dict_emp in jso...
def employee_data(usr_id): num_done_t = 0 total_t = 0 empl = requests.get("https://jsonplaceholder.typicode.com/users/{}" .format(usr_id)) name = empl.json().get('name') todos = requests.get("https://jsonplaceholder.typicode.com/todos") list_completed = [] for dic...
Python
nomic_cornstack_python_v1
function setSource self url begin set name = call toString if starts with name string http begin call openExtUrl name end else begin call setSource self call QUrl name end end function
def setSource(self, url): name = url.toString() if name.startswith('http'): dataeditors.openExtUrl(name) else: QTextBrowser.setSource(self, QUrl(name))
Python
nomic_cornstack_python_v1
string Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. Example 1: Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]] Output: true Example 2: Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [...
""" Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. Example 1: Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]] Output: true Example 2: Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1...
Python
zaydzuhri_stack_edu_python
function EbN0_to_noise_voltage self EbN0 begin set a = 10 ^ decimal EbN0 / 10 set b = 1.0 / square root call bits_per_symbol * a comment print(b) return b end function
def EbN0_to_noise_voltage(self, EbN0): a = 10**(float(EbN0) / 10) b = 1.0 / math.sqrt(self.const.bits_per_symbol()*a) #print(b) return b
Python
nomic_cornstack_python_v1
function threadpool self executor=none begin if is instance executor str begin set executor = call require_resource Executor executor end return call threadpool executor end function
def threadpool(self, executor: Executor | str | None = None): if isinstance(executor, str): executor = self.require_resource(Executor, executor) return asyncio_extras.threadpool(executor)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment # Juste prix comment In[69]: import random as rd set prix = call randrange 1001 print string Le prix est: prix set cpt = 0 while cpt < 3 begin set valeur = input string Entrez le prix set cpt = cpt + 1 if is digit valeur begin set valeur = integer valeur if val...
#!/usr/bin/env python # coding: utf-8 # # Juste prix # # # In[69]: import random as rd prix = rd.randrange(1001) print("Le prix est: " , prix) cpt = 0 while cpt < 3: valeur = input(" Entrez le prix ") cpt += 1 if valeur.isdigit(): valeur = int(valeur) if valeur < prix: ...
Python
zaydzuhri_stack_edu_python
import math from config import * comment TODO remove dependence import bar import rod , carriage , effector , rail import vertex function points_dist p1 p2 begin return square root sum list comprehension x1 - x2 * x1 - x2 for tuple x1 x2 in zip p1 p2 end function function rotate a fi begin set fi = fi / 180.0 * pi set ...
import math from config import * import bar #TODO remove dependence import rod, carriage, effector, rail import vertex def points_dist(p1, p2): return math.sqrt(sum([(x1 - x2)*(x1 - x2) for x1, x2 in zip(p1, p2)])) def rotate(a, fi): fi = fi/180.0*math.pi x = a[0] * math.cos(fi) - a[1] * math.sin(fi) y = a[0] * ...
Python
zaydzuhri_stack_edu_python
function multi_value_extended_properties self begin return get properties string multiValueExtendedProperties call EntityCollection context MultiValueLegacyExtendedProperty call ResourcePath string multiValueExtendedProperties resource_path end function
def multi_value_extended_properties(self): return self.properties.get('multiValueExtendedProperties', EntityCollection(self.context, MultiValueLegacyExtendedProperty, ResourcePath("multiValueExtendedProperties", self.resource...
Python
nomic_cornstack_python_v1
comment Radar eletrônico set v = decimal input string Qual é a velocidade atual do carro: set m = v - 80 * 7 if v > 80 begin print string Você excedeu o limite permitido de 80km/h Você deve pagar uma multa de R$ { m } ! end else begin print string Tenha um bom dia! Dirija com segurança! end
# Radar eletrônico v = float(input("Qual é a velocidade atual do carro: ")) m = (v-80)*7 if v > 80: print(f"Você excedeu o limite permitido de 80km/h \nVocê deve pagar uma multa de R${m:.2f}!") else: print("Tenha um bom dia! Dirija com segurança!")
Python
zaydzuhri_stack_edu_python
function __init__ self dataset parent=none begin call __init__ parent=parent set dataset = dataset set columnNameList = list dataset print columnNameList end function
def __init__(self, dataset: pd.DataFrame, parent=None): super().__init__(parent=parent) self.dataset = dataset self.columnNameList = list(self.dataset) print(self.columnNameList)
Python
nomic_cornstack_python_v1
function get_pipeline self pipeline_name local_path=string . persist=false begin call try_import_autoai_libs comment note: Show warning if OBM if string auto_ai.obm in string _wml_stored_pipeline_details begin warn string OBM pipeline can be used only for inspection and deployment purposes. Warning stacklevel=2 end com...
def get_pipeline(self, pipeline_name: str, local_path: str = '.', persist: 'bool' = False) -> Tuple['Pipeline', bool]: try_import_autoai_libs() # note: Show warning if OBM if 'auto_ai.obm' in str(self._wml_stored_pipeline_details): warnings.warn("OBM pipeline ca...
Python
nomic_cornstack_python_v1
function sparkwebhook begin if method == string GET begin return string <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Spark Bot served via Flask</title> </head> <body> <p> <strong>Your Flask web server is up and running!</strong> </p> </body> </html> end else if method == string POST begin strin...
def sparkwebhook(): if request.method == 'GET': return ("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Spark Bot served via Flask</title> </head> ...
Python
nomic_cornstack_python_v1
function discriminator_regress img_dim model_name=string Discriminator use_mbd=true begin if call image_dim_ordering == string channels_first begin set bn_axis = 1 end else begin set bn_axis = - 1 end set nb_filters = 64 comment img_dim=(80, 80, 5)##, this should be set nb_conv = integer round log img_dim at 0 / log 2 ...
def discriminator_regress(img_dim, model_name="Discriminator", use_mbd=True): if K.image_dim_ordering() == "channels_first": bn_axis = 1 else: bn_axis = -1 nb_filters = 64 #img_dim=(80, 80, 5)##, this should be nb_conv = int(np.round(np.log(img_dim[0]) / np.log(2))) nb_conv=8...
Python
nomic_cornstack_python_v1
function find_nearest array value begin set array = call asarray array set idx = argument minimum return array at idx end function
def find_nearest(array, value): array = np.asarray(array) idx = (np.abs(array - value)).argmin() return array[idx]
Python
nomic_cornstack_python_v1
import random function read_sudoku filename begin string Прочитать Судоку из указанного файла set digits = list comprehension c for c in read open filename if c in string 123456789. set grid = call group digits 9 return grid end function function group values n begin set l = list comprehension values at slice i : i + n...
import random def read_sudoku(filename): """ Прочитать Судоку из указанного файла """ digits = [c for c in open(filename).read() if c in '123456789.'] grid = group(digits, 9) return grid def group(values, n): l = [values[i:i+n] for i in range(0, len(values), n)] return l def...
Python
zaydzuhri_stack_edu_python
function create_vbd self xenapi_vbd vdi_image_path begin comment self.__vbd_lock__.acquire() comment try: set current_VDIs = call _get_current_VDIs if get xenapi_vbd string VDI string in current_VDIs begin raise call XendError string Invalid binding VDI, already binding: %s % get xenapi_vbd string VDI string end set xe...
def create_vbd(self, xenapi_vbd, vdi_image_path): # self.__vbd_lock__.acquire() # try: current_VDIs = self._get_current_VDIs() if xenapi_vbd.get('VDI', '') in current_VDIs: raise XendError('Invalid binding VDI, already binding: %s' % xenapi_vbd.get('VDI', '')) xenapi_vb...
Python
nomic_cornstack_python_v1
function write_smet filename data metadata nodata_value=- 999 mode=string h check_nan=true begin string writes smet files Parameters ---- filename : filename/loction of output data : data to write as pandas df metadata: header to write input as dict nodata_value: Nodata Value to write/use mode: defines if to write dail...
def write_smet(filename, data, metadata, nodata_value=-999, mode='h', check_nan=True): """writes smet files Parameters ---- filename : filename/loction of output data : data to write as pandas df metadata: header to write input as dict nodata_value: Nodata Value to write/use ...
Python
jtatman_500k
function compute_average numbers begin set total = 0 for num in numbers begin set total = total + num end return total / length numbers end function if __name__ == string __main__ begin set numbers = list 1 5 7 10 comment 6.0 print call compute_average numbers end
def compute_average(numbers): total = 0 for num in numbers: total += num return total / len(numbers) if __name__ == '__main__': numbers = [1, 5, 7, 10] print(compute_average(numbers)) # 6.0
Python
flytech_python_25k
function read self begin try begin set f = open fn string r set lines = split read f string close f set BLOCKED_IPS = list for line in lines begin if length line > 0 and line at 0 != string ! and string = in line begin set tuple arg val = split line string = set arg = strip arg string set val = strip val string set da...
def read(self): try: f = open(self.fn, "r") lines = f.read().split("\n") f.close() self.BLOCKED_IPS = [] for line in lines: if len(line) > 0 and line[0] != "!" and "=" in line: arg, val = line.split("=") arg = arg.strip(' \t\n\r') val = val.strip(' \t\n\r') self.data[arg] = val ...
Python
nomic_cornstack_python_v1
function store_doc_labels self index out_dir begin set reader = reader set doc_ids = list call all_doc_ids comment define doc labels list set doc_labels = list for doc_id in doc_ids begin set label = call stored_fields doc_id at string docno append doc_labels label end comment convert doc labels list into dicts set ix2...
def store_doc_labels(self, index, out_dir): reader = index.reader() doc_ids = list(reader.all_doc_ids()) # define doc labels list doc_labels = list() for doc_id in doc_ids: label = reader.stored_fields(doc_id)['docno'] doc_labels.append(label) ...
Python
nomic_cornstack_python_v1
import numpy as np import math import csv import matplotlib.pyplot as plt from scipy.stats import norm set TRADING_DAYS = 252 set nse_name = list string HDFCBANK.NS string TATAMOTORS.NS string ADANIENT.NS string VOLTAS.NS string BAJAJFINSV.NS string HAVELLS.NS string RELIANCE.NS string BERGEPAINT.NS string ASIANPAINT.N...
import numpy as np import math import csv import matplotlib.pyplot as plt from scipy.stats import norm TRADING_DAYS = 252 nse_name = ['HDFCBANK.NS', 'TATAMOTORS.NS', 'ADANIENT.NS', 'VOLTAS.NS', 'BAJAJFINSV.NS', 'HAVELLS.NS', 'RELIANCE.NS', 'BERGEPAINT.NS', 'ASIANPAINT.NS', 'MUTHOOTFIN.NS'] bse_name = ['ASTRAL.BO', 'J...
Python
zaydzuhri_stack_edu_python
function _resolve_ondemand self macro data begin comment pylint: disable=too-many-locals string Get on demand macro value If the macro cannot be resolved, this function will return 'n/a' rather than an empty string, this to alert the caller of a potential problem. :param macro: macro to parse :type macro: :param data: ...
def _resolve_ondemand(self, macro, data): # pylint: disable=too-many-locals """Get on demand macro value If the macro cannot be resolved, this function will return 'n/a' rather than an empty string, this to alert the caller of a potential problem. :param macro: macro to parse ...
Python
jtatman_500k
comment python3 string mongod.exe --nojournal --dbpath . Author: Tanlin Purpose: 结课作业:使用MongoDB存储平时作业3中生成的随机数,并能从MongoDB中查询数据进行数据筛选。 Created: 2020.6.24 import random import string import pymongo comment 27017是本机端口号 set myclient = call MongoClient string mongodb://localhost:27017/ comment 创建数据库(Mongo打开和创建不分) set mydb = ...
# python3 """ mongod.exe --nojournal --dbpath . Author: Tanlin Purpose: 结课作业:使用MongoDB存储平时作业3中生成的随机数,并能从MongoDB中查询数据进行数据筛选。 Created: 2020.6.24 """ import random import string import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") # 27017是本机端口号 mydb = myclient["RandomDatadb"] # 创建数据库(Mongo...
Python
zaydzuhri_stack_edu_python
for brightness in range 2 response + 1 2 begin print string Beep's brightness level: + string * * brightness print string Bop's brightness level: + string * * brightness end print string Adjustments complete!
for brightness in range (2,response + 1,2): print("\nBeep's brightness level: "+"*"*brightness) print("Bop's brightness level: "+"*"*brightness) print("\nAdjustments complete!")
Python
zaydzuhri_stack_edu_python
import pygame from pygame.locals import * import time class W extends Sprite begin function __init__ self begin string Set up the player on creation. comment Call the parent class (Sprite) constructor call __init__ set image = load image string resources/w.png set rect = call get_rect set tuple x y = tuple x y end func...
import pygame from pygame.locals import * import time class W(pygame.sprite.Sprite): def __init__(self): """ Set up the player on creation. """ # Call the parent class (Sprite) constructor super().__init__() self.image = pygame.image.load("resources/w.png") self.re...
Python
zaydzuhri_stack_edu_python
string aoc_11 https://adventofcode.com/2019/day/11 from libs.aoc_lib import data_input from libs.aoc_11_lib import part_1 , part_2 function main begin set data = call data_input string data/aoc_11_data.txt comment Part 1 set p_1 = call part_1 data print string Part 1: { p_1 } is { p_1 == 329 } comment Part 2 set p_2 = ...
""" aoc_11 https://adventofcode.com/2019/day/11 """ from libs.aoc_lib import data_input from libs.aoc_11_lib import part_1, part_2 def main() -> None: data = data_input("data/aoc_11_data.txt") # Part 1 p_1 = part_1(data) print(f"Part 1: {p_1} is {p_1 == 329}") # Part 2 p_2 = part_2(...
Python
zaydzuhri_stack_edu_python
function gethandle self begin set handle = string for tag in self begin if code in tuple 5 105 begin set handle = value break end end comment check for valid handle integer handle 16 return handle end function
def gethandle(self): handle = '' for tag in self: if tag.code in (5, 105): handle = tag.value break int(handle, 16) # check for valid handle return handle
Python
nomic_cornstack_python_v1
function __ne__ self other begin return not self == other end function
def __ne__(self, other): return not self == other
Python
nomic_cornstack_python_v1
function save_corr_matrix self file_handle begin if column_order begin set corr_matrix = corr_matrix at tuple slice : : column_order at column_order set labels = list comprehension labels at i for i in column_order end set labels = list comprehension call toString x for x in labels write file_handle string ' + join ...
def save_corr_matrix(self, file_handle): if self.column_order: self.corr_matrix = self.corr_matrix[:, self.column_order][self.column_order] self.labels = [self.labels[i] for i in self.column_order] self.labels = [toString(x) for x in self.labels] file_handle.write("\t'" ...
Python
nomic_cornstack_python_v1
comment Simple pyROOT script to plot the "trend" of bytes generated by an 8-bit Linear-Feedback Shift Register (LFSR). comment The "random" sequence repeats after 256 values, fill the histogram to show only the first 4 replicated sequences. comment Luca Pacher - pacher@to.infn.it comment Spring 2020 from ROOT import TH...
# # Simple pyROOT script to plot the "trend" of bytes generated by an 8-bit Linear-Feedback Shift Register (LFSR). # The "random" sequence repeats after 256 values, fill the histogram to show only the first 4 replicated sequences. # # Luca Pacher - pacher@to.infn.it # Spring 2020 # from ROOT import TH1F, gStyle, gPad...
Python
zaydzuhri_stack_edu_python
function F self x begin if is instance x ndarray begin set x = call maximum x _s set nfwvals = zeros like x set inds1 = where x < 1 set inds2 = where x > 1 set inds3 = where x == 1 set nfwvals at inds1 = 1 - x at inds1 ^ 2 ^ - 0.5 * call arctanh 1 - x at inds1 ^ 2 ^ 0.5 set nfwvals at inds2 = x at inds2 ^ 2 - 1 ^ - 0.5...
def F(self, x): if isinstance(x, np.ndarray): x = np.maximum(x, self._s) nfwvals = np.zeros_like(x) inds1 = np.where(x < 1) inds2 = np.where(x > 1) inds3 = np.where(x == 1) nfwvals[inds1] = (1 - x[inds1] ** 2) ** -.5 * np.arctanh((1 - x[in...
Python
nomic_cornstack_python_v1
function output_signature self begin return call pdcch_interleaver_sptr_output_signature self end function
def output_signature(self): return _my_lte_swig.pdcch_interleaver_sptr_output_signature(self)
Python
nomic_cornstack_python_v1
import traceback import logging from fastapi import APIRouter from fastapi.responses import Response from json import dumps from http import HTTPStatus from backend_service.api.operation.roll_operation import RollOperation , RollOperationException from common.redis_helper import RedisHelper from common.logger import Lo...
import traceback import logging from fastapi import APIRouter from fastapi.responses import Response from json import dumps from http import HTTPStatus from backend_service.api.operation.roll_operation import RollOperation, RollOperationException from common.redis_helper import RedisHelper from common.logger import L...
Python
zaydzuhri_stack_edu_python
function _dict_validity_check d valid_d begin if not call _is_in_dict d valid_d begin raise call InvalidSettingError end end function
def _dict_validity_check(d, valid_d): if not Settings._is_in_dict(d, valid_d): raise InvalidSettingError()
Python
nomic_cornstack_python_v1
function answer a b c begin return upper a at 0 + b at 0 + c at 0 end function print call answer a b c
def answer(a: str, b: str, c: str) -> str: return ((a[0] + b[0] + c[0]).upper()) print(answer(a, b, c))
Python
zaydzuhri_stack_edu_python
comment parametric decaying fib spiral import graphics from graphics import * import math import time import moviepy.editor as mpy import glob from PIL import Image set pie = pi set phi = 1.61803398875 set giantlist = list function takepic win i begin set name = string spinpic set maxchars = 6 set chars = length strin...
#parametric decaying fib spiral import graphics from graphics import * import math import time import moviepy.editor as mpy import glob from PIL import Image pie = math.pi phi = 1.61803398875 giantlist = [] def takepic(win,i): name = "spinpic" maxchars = 6 chars = len(str(i)) nzeros...
Python
zaydzuhri_stack_edu_python
function send_training_report_message socket report flags=0 node_name=none **kwargs begin set context = call get_context set name = node_name or get context string node_name or get context string partition_id set metadata = dict set metadata at string nn = name set metadata at string mt = training_report set metadata ...
def send_training_report_message( socket: Socket, report, flags=0, node_name=None, **kwargs ): context = get_context() name = node_name or context.get("node_name") or context.get("partition_id") metadata = {} metadata["nn"] = name metadata["mt"] = MessageTypes.training_report metadata["job...
Python
nomic_cornstack_python_v1
function ls location=string . pattern=string .* begin set file_list = list for tuple dirpaths dirnames filenames in walk location begin for filename in dirnames + filenames begin if match pattern filename begin append file_list filename end end end return file_list end function
def ls(location='.', pattern='.*'): file_list = [] for (dirpaths, dirnames, filenames) in os.walk(location): for filename in dirnames + filenames: if re.match(pattern, filename): file_list.append(filename) return file_list
Python
nomic_cornstack_python_v1
comment Django from django.shortcuts import render from django.views.generic import ListView , DetailView from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin comment Models from models import Sale comment Forms from forms import SalesSearchForm from report...
# Django from django.shortcuts import render from django.views.generic import ListView, DetailView from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin # Models from .models import Sale # Forms from .forms import SalesSearchForm from reports.forms import Re...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Oct 22 09:08:16 2020 @author: Gautam_Pai class Solution begin function rotate self nums k begin string Do not return anything, modify nums in-place instead. if length nums > k begin set nums at slice : : = nums at slice - k : : + nums at slice : - k : end else ...
# -*- coding: utf-8 -*- """ Created on Thu Oct 22 09:08:16 2020 @author: Gautam_Pai """ class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ if len(nums) > k: nums[:] = nums[-k:]+nums[:-k] ...
Python
zaydzuhri_stack_edu_python
function print_name begin set name = input string Please enter your name: print string Hello { name } end function if __name__ == string __main__ begin call print_name end
def print_name(): name = input("Please enter your name: ") print(f"Hello {name}") if __name__ == '__main__': print_name()
Python
zaydzuhri_stack_edu_python
function _create_scan self scan_struct scantype_struct fset_struct extfiles scores subject_eid study_eid assessment_eid begin comment Create the scan set scan_id = scan_struct at string identifier set tuple scan_entity is_created = call _get_or_create_unique_entity rql=format string Any X Where X is Scan, X identifier ...
def _create_scan(self, scan_struct, scantype_struct, fset_struct, extfiles, scores, subject_eid, study_eid, assessment_eid): # Create the scan scan_id = scan_struct["identifier"] scan_entity, is_created = self._get_or_create_unique_entity( rql=("Any X Where X is ...
Python
nomic_cornstack_python_v1
function train self network training_examples learning_rate reg_lambda=0 batch_size=1 passes=1 begin for _ in range passes begin shuffle random training_examples for tuple i example in enumerate training_examples begin set x = example at 0 set y = example at 1 call forward x backward network call cost_gradient y if i +...
def train(self, network, training_examples, learning_rate, reg_lambda=0, batch_size=1, passes=1): for _ in range(passes): random.shuffle(training_examples) for i, example in enumerate(training_examples): x = example[0] y = example[1] ...
Python
nomic_cornstack_python_v1
comment Write a program which accept name from user and display length of its name. comment Input : Marvellous Output : 10 comment Author : Annaso Chavan function main begin set str = input string please enter name : print string String length is : length str end function comment code starter if __name__ == string __ma...
########################################################################################### # Write a program which accept name from user and display length of its name. # Input : Marvellous Output : 10 # Author : Annaso Chavan ########################################################################################### ...
Python
zaydzuhri_stack_edu_python
comment def solution(string, markers): comment for i in markers: comment index = string.find(i) comment while index > -1: comment string = slice_string(string, index) comment index = string.find(i) comment return string comment def slice_string(string, index): comment start = index comment finish = len(string) comment ...
# def solution(string, markers): # for i in markers: # index = string.find(i) # while index > -1: # string = slice_string(string, index) # index = string.find(i) # return string # # # def slice_string(string, index): # start = index # finish = len(string) # fo...
Python
zaydzuhri_stack_edu_python
from main import Sprite function test_spirit_init begin set s = call Sprite list 0 0 list 1 1 string image.png 100 100 assert speed == list 1 1 assert position == list 0 0 assert image_path == string image.png end function function test_get_x begin set s = call Sprite list 0 0 list 1 1 string image.png 100 100 assert x...
from main import Sprite def test_spirit_init(): s = Sprite([0,0], [1,1], 'image.png', 100, 100) assert s.speed == [1,1] assert s.position == [0,0] assert s.image_path == 'image.png' def test_get_x(): s = Sprite([0,0], [1,1], 'image.png', 100, 100) assert s.x == 0 assert s.y == 0 def ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt from skimage.feature import greycomatrix , greycoprops import cv2 import imagehelper string 그래프를 그린다. function show_patches image_path salt_patches non_salt_patches begin set xs = list set ys = list set image = call cvtColor call imread image_path COLOR_BGR2GRAY for patch in non_salt_p...
import matplotlib.pyplot as plt from skimage.feature import greycomatrix, greycoprops import cv2 import imagehelper """ 그래프를 그린다. """ def show_patches(image_path, salt_patches, non_salt_patches): xs = [] ys = [] image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2GRAY) for patch in (non_salt_pa...
Python
zaydzuhri_stack_edu_python
import time , math from typing import Iterable from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.remote.webelement import WebElement from webdriver_manager.chrome import ChromeDriverManager import pyautogui from pyautogui import click , moveTo , press , rightCl...
import time, math from typing import Iterable from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.remote.webelement import WebElement from webdriver_manager.chrome import ChromeDriverManager import pyautogui from pyautogui import click, moveTo, press, rightClick ...
Python
zaydzuhri_stack_edu_python
function new_frame_event self begin string Called by the event loop when a new input or output frame is available. Inputs are correlated by comparing their frame numbers. If there is a complete set of inputs, and all output frame pools are ready, the :py:meth:`process_frame` method is called. If an input frame has a ne...
def new_frame_event(self): """Called by the event loop when a new input or output frame is available. Inputs are correlated by comparing their frame numbers. If there is a complete set of inputs, and all output frame pools are ready, the :py:meth:`process_frame` method is called...
Python
jtatman_500k
function template_en_noun self section label begin set label_s = label set label_p = none for template in templates begin if name == string en-noun begin set tuple hasPlural addAll = tuple false false for tuple key value in call get_named_args template begin if starts with key string pl begin set label_p = value set ha...
def template_en_noun(self, section, label): label_s = label label_p = None for template in section.templates: if template.name == "en-noun": hasPlural, addAll = False, False for key, value in self.get_named_args(template): ...
Python
nomic_cornstack_python_v1
from rl2020.util.util import override from rl2020.agent.q_learning_agent import QLearningAgent import numpy as np from rl2020.activity.activity_context import ActivityContext set __author__ = string bkurniawan string This class represents an Q-learning with traces agent, using replacing traces (instead of accumulating ...
from rl2020.util.util import override from rl2020.agent.q_learning_agent import QLearningAgent import numpy as np from rl2020.activity.activity_context import ActivityContext __author__ = 'bkurniawan' """ This class represents an Q-learning with traces agent, using replacing traces (instead of accumulating traces) As...
Python
zaydzuhri_stack_edu_python
class solution begin function popuNextRight self root begin if not root begin return end set dummy = call Node - 1 set prev = dummy set curr = root while curr begin if left begin set next = left set prev = next end if right begin set next = right set prev = next end set curr = next end call popuNextRight next end funct...
class solution: def popuNextRight(self, root): if not root: return dummy = Node(-1) prev = dummy curr = root while curr: if curr.left: prev.next = curr.left prev = prev.next if curr.right: ...
Python
zaydzuhri_stack_edu_python
function validate_record record begin if not any generator expression k in record for k in tuple string time b'time' begin warn string records should have "time" column to import records properly. category=RuntimeWarning end return true end function
def validate_record(record): if not any(k in record for k in ("time", b"time")): warnings.warn( 'records should have "time" column to import records properly.', category=RuntimeWarning, ) return True
Python
nomic_cornstack_python_v1
function print_status self pkg begin if pkg at string action == string update begin set version = string %s -> %s % tuple pkg at string orig_ver pkg at string version end else begin set version = pkg at string version end set action = string (%s) % pkg at string action set tmpl = string %20s : %-20s %12s [%2d, %d] prin...
def print_status(self, pkg): if pkg['action'] == 'update': version = '%s -> %s' % (pkg['orig_ver'], pkg['version']) else: version = pkg['version'] action = '(%s)' % pkg['action'] tmpl = "%20s : %-20s %12s [%2d, %d]" print(tmpl % (pkg['name'], version, acti...
Python
nomic_cornstack_python_v1
comment 练习:在控制台中循环录入人的信息(姓名,年龄,性别,体重),如果名称为空字符串,停止录入. comment -- 将所有人的信息打印出来(一人一行) comment -- 打印第一个人的信息 comment -- 打印最后一个人的信息 comment 数据结构:列表内嵌字典 comment [ comment {"name":“无忌”,"age":28,"sex":"男","weight":80}, comment {"name":“赵敏”,"age":26,"sex":"女","weight":50}, comment ] string 17:15 总结:存储多个数据,使用什么数据结构? 根据具体需求,结合优缺点,...
# 练习:在控制台中循环录入人的信息(姓名,年龄,性别,体重),如果名称为空字符串,停止录入. # -- 将所有人的信息打印出来(一人一行) # -- 打印第一个人的信息 # -- 打印最后一个人的信息 # 数据结构:列表内嵌字典 # [ # {"name":“无忌”,"age":28,"sex":"男","weight":80}, # {"name":“赵敏”,"age":26,"sex":"女","weight":50}, # ] """ 17:15 总结:存储多个数据,使用什么数据结构? 根据具体需求,结合优缺点,综合考虑(两害相权其轻) 字典:...
Python
zaydzuhri_stack_edu_python
function get_game self request begin set game = call get_by_urlsafe urlsafe_game_key Game if game begin return call to_form end else begin raise call NotFoundException string Game not found! end end function
def get_game(self, request): game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: return game.to_form() else: raise endpoints.NotFoundException('Game not found!')
Python
nomic_cornstack_python_v1
function dgTimerQueryState self begin pass end function
def dgTimerQueryState(self): pass
Python
nomic_cornstack_python_v1
comment _*_coding:utf-8_*_ class Converter extends object begin function __init__ self begin pass end function function convert self line begin raise exception string Converterクラスは継承してconvertクラスをオーバーライドして使用してください end function end class
# _*_coding:utf-8_*_ class Converter(object): def __init__(self): pass def convert(self, line): raise Exception(u"Converterクラスは継承してconvertクラスをオーバーライドして使用してください")
Python
zaydzuhri_stack_edu_python
function clean_legacy es parsed_args begin if dry_run begin print string Dry run, no operations will be performed end for index in call get_indices es parsed_args true begin if suffix in index begin if not dry_run begin delete index end print format string Deleted: {} index end end end function
def clean_legacy(es, parsed_args): if parsed_args.dry_run: print("Dry run, no operations will be performed") for index in get_indices(es, parsed_args, True): if parsed_args.suffix in index: if not parsed_args.dry_run: es.indices.delete(index) print ("Delet...
Python
nomic_cornstack_python_v1
function unlink self fspath begin return end function
def unlink ( self, fspath ): return
Python
nomic_cornstack_python_v1
import torch import numpy as np import pandas as pd from data_preprocessor import DataPreprocessor from dataset import Dataset from utility import Utility from util.data_loader import DataLoader class MovieRecommender extends object begin function __init__ self begin comment loading trained model set model = load torch...
import torch import numpy as np import pandas as pd from data_preprocessor import DataPreprocessor from dataset import Dataset from utility import Utility from util.data_loader import DataLoader class MovieRecommender(object): def __init__(self): #loading trained model self.model = torch.load("tr...
Python
zaydzuhri_stack_edu_python
import codecs import pandas as pd if __name__ == string __main__ begin set data_neg = split read open string data/rt-polarity.neg string r encoding=string utf-8 errors=string ignore string set data_pos = split read open string data/rt-polarity.pos string r encoding=string utf-8 errors=string ignore string set data_neg ...
import codecs import pandas as pd if __name__ == "__main__": data_neg = codecs.open('data/rt-polarity.neg', 'r', encoding='utf-8', errors='ignore').read().split('\n') data_pos = codecs.open('data/rt-polarity.pos', 'r', encoding='utf-8', errors='ignore').read().split('\n') data_neg = data_neg[:-1] dat...
Python
zaydzuhri_stack_edu_python
function is_firewall_enabled begin set filter_table = call Table FILTER set input_chain = next filter lambda c -> name == string INPUT filter_table return not length rules == 0 end function
def is_firewall_enabled(): filter_table = iptc.Table(iptc.Table.FILTER) input_chain = next(filter(lambda c: c.name == 'INPUT', filter_table)) return not len(input_chain.rules) == 0
Python
nomic_cornstack_python_v1
function use_amortized self begin return get pulumi self string use_amortized end function
def use_amortized(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "use_amortized")
Python
nomic_cornstack_python_v1
comment mostra as torres function print_torres torre1 torre2 torre3 d_size begin set ls = d_size * 2 + 2 comment faz uma lista de tuplas com o zip pras torres for line in zip torre1 torre2 torre3 begin set tuple l c r = line comment mostras as filas e centraliza print string |%s|%s|%s| % tuple call center ls call cente...
def print_torres(torre1, torre2, torre3, d_size): #mostra as torres ls = d_size * 2 + 2 for line in zip(torre1, torre2, torre3): #faz uma lista de tuplas com o zip pras torres l , c, r = line print('|%s|%s|%s|' % (l.center(ls), c.center(ls), r.center(ls))) #mostras as filas e cent...
Python
zaydzuhri_stack_edu_python