code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment Los doce días de Navidad es una canción repetitiva que describe una lista cada vez más larga de regalos enviados comment al verdadero amor de cada uno de los 12 días. Se envía un único regalo el primer día. comment Se agrega un nuevo regalo a la colección cada día adicional, y luego se envía la colección comple...
#Los doce días de Navidad es una canción repetitiva que describe una lista cada vez más larga de regalos enviados #al verdadero amor de cada uno de los 12 días. Se envía un único regalo el primer día. #Se agrega un nuevo regalo a la colección cada día adicional, y luego se envía la colección completa. #Los primer...
Python
zaydzuhri_stack_edu_python
from tkinter import * from tkinter import messagebox from pingtest import * from speed import * from network_capture import * from traff_analy_qos import * import pingtest import tkinter import network_capture import time import traff_analy_qos class Gui begin function __init__ self root begin comment Interface structu...
from tkinter import * from tkinter import messagebox from pingtest import * from speed import * from network_capture import * from traff_analy_qos import * import pingtest import tkinter import network_capture import time import traff_analy_qos class Gui(): def __init__(self, root): # Interface structure ...
Python
zaydzuhri_stack_edu_python
function solution phone_book begin for tuple i num1 in enumerate phone_book begin for j in range i + 1 length phone_book begin set num2 = phone_book at j if length num1 < length num2 begin set s = num1 set l = num2 end else begin set s = num2 set l = num1 end if starts with l s begin return false end end end return tru...
def solution(phone_book): for i, num1 in enumerate(phone_book): for j in range(i + 1, len(phone_book)): num2 = phone_book[j] if len(num1) < len(num2): s = num1 l = num2 else: s = num2 l = num1 if...
Python
zaydzuhri_stack_edu_python
function _set_avg self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=call RestrictedPrecisionDecimalType precision=2 is_leaf=true yang_name=string avg parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true namespac...
def _set_avg(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=RestrictedPrecisionDecimalType(precision=2), is_leaf=True, yang_name="avg", parent=self, ...
Python
nomic_cornstack_python_v1
function velocityExponential *args begin return call velocityExponential *args end function
def velocityExponential(*args): return _almathswig.velocityExponential(*args)
Python
nomic_cornstack_python_v1
if a at 4 < a at 2 and a at 5 < a at 3 and a at 0 < a at 6 and a at 1 < a at 7 begin set x = sorted list a at 0 a at 4 a at 2 a at 6 set y = sorted list a at 1 a at 5 a at 3 a at 7 set s = s - x at 2 - x at 1 * y at 2 - y at 1 end print s
if a[4] < a[2] and a[5] < a[3] and a[0] < a[6] and a[1] < a[7]: x = sorted([a[0], a[4], a[2], a[6]]) y = sorted([a[1], a[5], a[3], a[7]]) s -= (x[2]-x[1])*(y[2]-y[1]) print(s)
Python
zaydzuhri_stack_edu_python
for a in range 99 1 - 1 begin print string a + string bottles of beer on the wall, + string a + string bottles of beer! Take one down, pass it around, + string a + string bottles of beer on the wall! end set a = 1 print string a + string bottle of beer on the wall, + string a + string bottle of beer! Take it down, pass...
for a in range(99, 1, -1): print(str(a) + " bottles of beer on the wall, " + str(a) + " bottles of beer! Take one down, pass it around, " + str(a) + " bottles of beer on the wall!") a=1 print(str(a) + " bottle of beer on the wall, " + str(a) + " bottle of beer! Take it down, pass it around, " + str(a) + " bottle of...
Python
zaydzuhri_stack_edu_python
function calculate_home_appliance category=string electronic-home-appliances datetime_obj=none page=none category_value=none begin set data_dict = dict while true begin set ads : list = call get_ads category page category_value set status = true for i in ads begin set slug = i at string slug set timestamp = i at strin...
def calculate_home_appliance(category='electronic-home-appliances', datetime_obj=None, page=None, category_value=None) -> dict and int: data_dict = {} while True: ads: list = get_ads(category, page, category_value) status = True for i in ads: slug = i['slug'] t...
Python
nomic_cornstack_python_v1
function trufflehog repo outdir begin if outdir at - 1 != string / begin set outdir = outdir + string / end set repo_name = split repo string / at - 1 try begin set cmd = run list string trufflehog format string file://{} repo stdout=PIPE set outfile = outdir + repo_name + string .trufflehog with open outfile string wb...
def trufflehog(repo, outdir): if outdir[-1] != "/": outdir += "/" repo_name = repo.split("/")[-1] try: cmd = subprocess.run(["trufflehog", "file://{}".format(repo)], stdout=subprocess.PIPE) outfile = outdir + repo_name + ".trufflehog" with open(outfile, 'wb') as f: ...
Python
nomic_cornstack_python_v1
function area_triangle base height begin if base == 0 or height == 0 begin raise call ValueError string Base and height should not be zero. end else begin return 0.5 * base * height end end function
def area_triangle(base,height): if base == 0 or height == 0: raise ValueError("Base and height should not be zero.") else: return 0.5 * base * height
Python
jtatman_500k
comment !/usr/bin/env python3.6 from portablehole import collection , container , inventory , item set inv = call Inventory set tim = call Player name=string Tim capacity=135 set franklin = call Player name=string Franklin capacity=160 set gp = call Collection itm=item item name=string GP weight=0.01 value=1 category=s...
#!/usr/bin/env python3.6 from portablehole import collection, container, inventory, item inv = inventory.Inventory() tim = container.Player(name="Tim", capacity=135) franklin = container.Player(name="Franklin", capacity=160) gp = collection.Collection(itm=item.Item(name='GP', weight=0.01, value=1, category='coin')) ...
Python
zaydzuhri_stack_edu_python
function update_A self begin set tuple rr cc tx dext = call setup_composite_tx _axes set A = call _get_updated_A rr cc tx call set_array self call safe_masked_invalid A copy=true call _scale_norm norm none none call set_extent dext end function
def update_A(self): rr, cc, tx, dext = setup_composite_tx(self._axes) A = self._get_updated_A(rr, cc, tx) cm.ScalarMappable.set_array(self, cbook.safe_masked_invalid(A, copy=True)) self._scale_norm(self.norm, None, None) self.set_extent(dext)
Python
nomic_cornstack_python_v1
function test_wrong_z_segment self begin set msg = call _create_message adt_a01 call add_segment string zin set zin = string ZIN|aa|bb|cc| comment CX_1 is mandatory set zin_4 = call Field string ZIN_4 datatype=string CX version=string 2.6 set value = string ^12 add zin zin_4 assert raises ValidationError validate repor...
def test_wrong_z_segment(self): msg = self._create_message(self.adt_a01) msg.add_segment('zin') msg.zin = 'ZIN|aa|bb|cc|' # CX_1 is mandatory zin_4 = Field('ZIN_4', datatype='CX', version='2.6') zin_4.value = '^12' msg.zin.add(zin_4) self.assertRaises(Vali...
Python
nomic_cornstack_python_v1
function _read_config filename begin set c = dict with open filename string r as f begin for line in f begin set tuple key val = split line string = set key = strip key set val = strip val set c at key = val end end return c end function
def _read_config(filename): c = {} with open(filename, "r") as f: for line in f: key, val = line.split("=") key = key.strip() val = val.strip() c[key] = val return c
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import requests import re comment 讀取網頁 set res = get requests string ****** set soup = call BeautifulSoup text string html.parser comment 抓取資料 set catch = find all find soup string div string side-box ruled-top href=compile string /ep comment 讀入連結 set file = open string ./Links.txt string ...
from bs4 import BeautifulSoup import requests import re # 讀取網頁 res = requests.get('******') soup = BeautifulSoup(res.text, "html.parser") # 抓取資料 catch = soup.find('div', 'side-box ruled-top').find_all(href=re.compile("/ep")) # 讀入連結 file = open( './Links.txt', 'w', encoding='UTF-8') for i in range(len(catch)): li...
Python
zaydzuhri_stack_edu_python
from operator import itemgetter set tuple n m = map int split input set ab = list comprehension list map int split input for _ in range m set cd = sorted ab key=call itemgetter 1 comment print(cd) set removed = - 1 set ans = 0 for tuple a b in cd begin if a > removed begin set removed = b - 1 set ans = ans + 1 end end ...
from operator import itemgetter n, m = map(int, input().split()) ab = [list(map(int, input().split())) for _ in range(m)] cd = sorted(ab, key=itemgetter(1)) #print(cd) removed = -1 ans = 0 for a, b in cd: if a > removed: removed = b - 1 ans += 1 print(ans)
Python
zaydzuhri_stack_edu_python
function start self begin if _flag ? AN_NOTANCHORED begin return _pos at 0 end return 0 end function
def start(self): if self._flag & self.AN_NOTANCHORED: return self._pos[0] return 0
Python
nomic_cornstack_python_v1
for day in days begin print day end
for day in days: print(day)
Python
jtatman_500k
function resource_path relative_path begin try begin comment PyInstaller creates a temp folder and stores path in _MEIPASS set base_path = _MEIPASS end except Exception begin set base_path = absolute path path string . end return join path base_path relative_path end function
def resource_path(relative_path): try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path)
Python
nomic_cornstack_python_v1
comment -*- encoding: utf-8 -*- string @version: python 3.7 @time: 2019/4/30 22:01 @author: YangZhen @editor:LiJiaHe/GaoJiaYang @title: 处理用户移动操作 @file: gameController.py import queue class UserDao begin function __init__ self num_list vector begin string 构造方法 :param num_list: 待移动列表 :param vector: 移动点坐标 set num_list = n...
# -*- encoding: utf-8 -*- """ @version: python 3.7 @time: 2019/4/30 22:01 @author: YangZhen @editor:LiJiaHe/GaoJiaYang @title: 处理用户移动操作 @file: gameController.py """ import queue class UserDao: def __init__(self, num_list, vector): """ 构造方法 :param num_list: 待移动列表 ...
Python
zaydzuhri_stack_edu_python
comment -*-coding:utf-8-*- import queue from FPGrowth.FPNode import FPNode class FPTree begin function __init__ self begin comment init toot node set root = call FPNode comment sotre 1 frequent item by down sequence set headerList = list comment map the item int headerList to the tree node set mapItemNodes = dict com...
# -*-coding:utf-8-*- import queue from FPGrowth.FPNode import FPNode class FPTree: def __init__(self): # init toot node self.root = FPNode() # sotre 1 frequent item by down sequence self.headerList = [] # map the item int headerList to the tree node self.mapItemNo...
Python
zaydzuhri_stack_edu_python
import math set PI = pi function dobraLista lista begin return list comprehension x * 2 for x in lista end function function multi lista begin set r = 1 for i in lista begin set r = r * i end return r end function if __name__ == string __main__ begin set lista = list 1 2 3 4 5 print call dobraLista lista print print ca...
import math PI = math.pi def dobraLista(lista): return [x * 2 for x in lista] def multi(lista): r = 1 for i in lista: r *= i return r if __name__ == '__main__': lista = [1, 2, 3, 4, 5] print(dobraLista(lista)) print() print(multi(lista))
Python
zaydzuhri_stack_edu_python
function get_cron_id self cr uid context begin set cron_obj = get pool string ir.cron comment find the cron that send messages set cron_id = search cr uid list tuple string function string ilike cron at string function tuple string model string ilike cron at string model context=dict string active_test false if cron_id...
def get_cron_id(self, cr, uid, context): cron_obj = self.pool.get('ir.cron') # find the cron that send messages cron_id = cron_obj.search(cr, uid, [('function', 'ilike', self.cron['function']), ('model', 'ilike', self.cron['model'])], ...
Python
nomic_cornstack_python_v1
from binary_search_tree import * function run_test_bst_insert begin set btree = call BST import random set a = list comprehension call randrange 0 300 1 for i in range 30 print a comment test insert for i in a begin insert btree i end call print_tree print string comment test min max find print min print max print find...
from binary_search_tree import * def run_test_bst_insert(): btree = BST() import random a = [random.randrange(0,300,1) for i in range(30)] print(a) # test insert for i in a: btree.insert(i) btree.print_tree() print("\n") # test min max find print(btree.min()) print...
Python
zaydzuhri_stack_edu_python
function message_type self begin return get pulumi self string message_type end function
def message_type(self) -> Optional[str]: return pulumi.get(self, "message_type")
Python
nomic_cornstack_python_v1
function get_queryset self begin if is_staff begin return all end return filter user=user end function
def get_queryset(self): if self.request.user.is_staff: return WaitQueue.objects.all() return WaitQueue.objects.filter(user=self.request.user)
Python
nomic_cornstack_python_v1
import numpy import scipy.special import scipy.misc import scipy.ndimage from time import sleep import RPi.GPIO as GPIO import time call setmode BOARD call setwarnings true set Left_Motor_Forward = 16 set Left_Motor_Backward = 18 set Right_Motor_Forward = 11 set Right_Motor_Backward = 13 setup GPIO Left_Motor_Forward O...
import numpy import scipy.special import scipy.misc import scipy.ndimage from time import sleep import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(True) Left_Motor_Forward = 16 Left_Motor_Backward = 18 Right_Motor_Forward = 11 Right_Motor_Backward = 13 GPIO.setup(Left_Motor_Forward,GPIO.O...
Python
zaydzuhri_stack_edu_python
function predict self x batch_size=1 begin assert model msg string Model was not initialized return predict model x batch_size=batch_size end function
def predict(self, x, batch_size=1): assert self.model, "Model was not initialized" return self.model.predict(x, batch_size=batch_size)
Python
nomic_cornstack_python_v1
function cast *args begin return call itkMultipleValuedCostFunction_cast *args end function
def cast(*args): return _ITKCostFunctionsPython.itkMultipleValuedCostFunction_cast(*args)
Python
nomic_cornstack_python_v1
comment coding:utf-8 import urllib import urllib2 import cookielib comment 通过cookieJar()类创建一个cookieJar()对象,用来保存cookie值 set cookie = call CookieJar comment 通过HTTPCookieProcessor()处理器构建一个处理器对象,用来处理cookie comment 参数就是构建CookieJar()对象 set cookie_handler = call HTTPCookieProcessor cookie comment 构建一个自定义的opener set opener = c...
# coding:utf-8 import urllib import urllib2 import cookielib #通过cookieJar()类创建一个cookieJar()对象,用来保存cookie值 cookie = cookielib.CookieJar() #通过HTTPCookieProcessor()处理器构建一个处理器对象,用来处理cookie #参数就是构建CookieJar()对象 cookie_handler = urllib2.HTTPCookieProcessor(cookie) #构建一个自定义的opener opener = urllib2.build_opener(cookie_hand...
Python
zaydzuhri_stack_edu_python
from thinkdsp import SinSignal , CosSignal , Spectrum , read_wave , decorate import matplotlib.pyplot as plt import wave comment 绘制一个频率400,振幅为1的正弦信号 set sinSignal = call SinSignal freq=400 amp=1.0 comment plt.subplot(2,1,1) comment sinSignal.plot() comment 绘制一个频率600,振幅为0.5的余弦信号 set cosSignal = call CosSignal freq=600 a...
from thinkdsp import SinSignal, CosSignal , Spectrum, read_wave, decorate import matplotlib.pyplot as plt import wave # 绘制一个频率400,振幅为1的正弦信号 sinSignal = SinSignal(freq=400, amp=1.0) # plt.subplot(2,1,1) # sinSignal.plot() # 绘制一个频率600,振幅为0.5的余弦信号 cosSignal = CosSignal(freq=600, amp=0.5) # plt.subplot(2,1,2) # cosSignal...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Nov 5 15:00:57 2019 @author: matth import math function closest2 LIST begin string closest2(LIST) makes a copy of LIST and then sorts it in order to return a tuple containing the two closest values that are passed in the list LIST >>> closest2([ 15.1, -12.1, 5.4, 11.8...
# -*- coding: utf-8 -*- """ Created on Tue Nov 5 15:00:57 2019 @author: matth """ import math def closest2(LIST): ''' closest2(LIST) makes a copy of LIST and then sorts it in order to return a tuple containing the two closest values that are passed in the list LIST >>> closest2([ 15.1,...
Python
zaydzuhri_stack_edu_python
function safe_upload_and_shutdown self image_file begin if instance begin raise exception string Cannot have a running utility instance with Safe upload end call start_ami try begin set snapshot = call file_to_snapshot image_file end finally begin call safe_call terminate_ami tuple log end return snapshot end function
def safe_upload_and_shutdown(self, image_file): if self.instance: raise Exception( "Cannot have a running utility instance with Safe upload") self.start_ami() try: snapshot = self.file_to_snapshot(image_file) finally: safe_call(self.ter...
Python
nomic_cornstack_python_v1
function stopping_rounds self begin return get _parms string stopping_rounds end function
def stopping_rounds(self): return self._parms.get("stopping_rounds")
Python
nomic_cornstack_python_v1
from domain.types import AgedBrie , NormalItem class DB begin set inventario = list list string +5 Dexterity Vest 10 20 list string Aged Brie 2 0 list string Elixir of the Mongoose 5 7 list string Sulfuras, Hand of Ragnaros 0 80 list string Sulfuras, Hand of Ragnaros - 1 80 list string Backstage passes to a TAFKAL80ETC...
from domain.types import AgedBrie, NormalItem class DB(): inventario = [["+5 Dexterity Vest", 10, 20], ["Aged Brie", 2, 0], ["Elixir of the Mongoose", 5, 7], ["Sulfuras, Hand of Ragnaros", 0, 80], ["Sulfuras, Hand of Ragnaros", -1, 80...
Python
zaydzuhri_stack_edu_python
function ctypes_struct_to_dict struct begin set result = dict for tuple field _ in _fields_ begin set value = get attribute struct field if has attribute value string _length_ and has attribute value string _type_ begin comment Probably an array set value = call tolist end else if type value is bytes begin comment Pro...
def ctypes_struct_to_dict(struct): result = {} for field, _ in struct._fields_: value = getattr(struct, field) if hasattr(value, '_length_') and hasattr(value, '_type_'): # Probably an array value = np.ctypeslib.as_array(value).tolist() elif type(value) is by...
Python
nomic_cornstack_python_v1
function get_current_wohnung request begin set wohnung = call get_object_or_404 Wohnung pk=session at string current_wohnung_id comment try: comment wohnung_id = request.session['current_wohnung_id'] comment wohnung = Wohnung.objects.get(pk=wohnung_id) comment except KeyError: comment wohnung = None return wohnung end ...
def get_current_wohnung(request): wohnung = get_object_or_404(Wohnung, pk=request.session['current_wohnung_id']) # try: # wohnung_id = request.session['current_wohnung_id'] # wohnung = Wohnung.objects.get(pk=wohnung_id) # except KeyError: # wohnung = None return wohnung
Python
nomic_cornstack_python_v1
function main begin while true begin try begin for i in range integer input begin set tuple a b = list map str split input if length b > length a begin print string nao encaixa end else begin set ta = length a - length b if a at slice ta : : == b begin print string encaixa end else begin print string nao encaixa end ...
def main(): while True: try: for i in range(int(input())): a, b = list(map(str, input().split())) if len(b) > len(a): print('nao encaixa') else: ta = len(a) - len(b) if a[ta::] == b: ...
Python
zaydzuhri_stack_edu_python
function next self begin string Move to the next token in the token stream. set current_token = next token_stream none if current_token is none begin set token_span = tuple token_span at 1 token_span at 1 raise error string Unexpected end of input end set token_span = span return self end function
def next(self): """Move to the next token in the token stream.""" self.current_token = next(self.token_stream, None) if self.current_token is None: self.token_span = self.token_span[1], self.token_span[1] raise self.error('Unexpected end of input') self.token_span...
Python
jtatman_500k
function model_fn features labels mode params config begin comment Get the last inner layer. set training = mode == TRAIN set outputs = call get_network features training params comment Create the output layer (Head) without the softmax part. set outputs = call reduce_mean outputs axis=1 set logits = dense outputs 6 se...
def model_fn(features, labels, mode, params, config): # Get the last inner layer. training = (mode == tf.estimator.ModeKeys.TRAIN) outputs = get_network(features, training, params) # Create the output layer (Head) without the softmax part. outputs = tf.reduce_mean(outputs, axis=1) logits = tf....
Python
nomic_cornstack_python_v1
function get_output_tensor interpreter index begin set output_details = call get_output_details at index set tensor = squeeze np call get_tensor output_details at string index return tensor end function
def get_output_tensor(interpreter, index): output_details = interpreter.get_output_details()[index] tensor = np.squeeze(interpreter.get_tensor(output_details["index"])) return tensor
Python
nomic_cornstack_python_v1
comment data transformation using Normalization Method import numpy as np from sklearn.preprocessing import Normalizer set X = array list list 4 1 2 2 list 1 3 9 3 list 5 7 5 1 comment normalizing on rows, works on formula Xi/sqrt(Xi**2+Yi**2+Zi**2) comment adding square of all the values of the row after normalization...
# data transformation using Normalization Method import numpy as np from sklearn.preprocessing import Normalizer X = np.array([[4, 1, 2, 2], [1, 3, 9, 3], [5, 7, 5, 1]]) # normalizing on rows, works on formula Xi/sqrt(Xi**2+Yi**2+Zi**2) # adding square of all the values of the row after no...
Python
zaydzuhri_stack_edu_python
function is_in self values begin if call is_str values begin set values = list values end return call ViewExpression dict string $in list self list values end function
def is_in(self, values): if etau.is_str(values): values = [values] return ViewExpression({"$in": [self, list(values)]})
Python
nomic_cornstack_python_v1
comment https://qiita.com/SquidSky/items/90eb450310f1697d03e9 comment DO NOT NAME this file "tkinter.py" import tkinter as tk function bLeftClicked canvas begin comment print(dir(canvas)) delete string all call create_rectangle 80 80 400 250 fill=string green comment canvas.create_rectangle(80, 80, 400, 250, fill = 'gr...
# https://qiita.com/SquidSky/items/90eb450310f1697d03e9 # DO NOT NAME this file "tkinter.py" import tkinter as tk def bLeftClicked(canvas): #print(dir(canvas)) canvas.delete("all") canvas.create_rectangle(80, 80, 400, 250, fill = 'green') #canvas.create_rectangle(80, 80, 400, 250, fill = 'green', stipp...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, right=None): comment self.val = val comment self.left = left comment self.right = right class Solution begin string def countNodes(self, root: TreeNode) -> int: if not root: return 0 leftd = self.getDepth(roo...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: """ def countNodes(self, root: TreeNode) -> int: if not root: return 0 left...
Python
zaydzuhri_stack_edu_python
import csv import json import logging import datetime from collections import defaultdict from config import filemap set __author__ = string jhh283 comment script that loads data from files into a class structure called Stats call basicConfig filename=string loader.log level=DEBUG format=string %(asctime)s - %(name)s -...
import csv import json import logging import datetime from collections import defaultdict from config import filemap __author__ = 'jhh283' # script that loads data from files into a class structure called Stats logging.basicConfig(filename='loader.log', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelnam...
Python
zaydzuhri_stack_edu_python
function _valid link link_as begin if length link == 2 begin set gen = keys link set allels1 = split split gen at 0 string : at 0 string / set allels2 = split split gen at 1 string : at 0 string / if allels1 at 0 != allels2 at 0 and allels1 at 1 != allels2 at 1 and call _snp_veracity link link_as begin return true end ...
def _valid(link, link_as): if len(link) == 2: gen = link.keys() allels1 = gen[0].split(":")[0].split("/") allels2 = gen[1].split(":")[0].split("/") if allels1[0] != allels2[0] and allels1[1] != allels2[1] and _snp_veracity(link, link_as): return True
Python
nomic_cornstack_python_v1
function write_sequence_file self filename begin set f = open filename string w for sid in __seqid begin write f string > + sid + string write f call get_sequence + string end close f del f end function
def write_sequence_file(self,filename): f = open(filename,"w") for sid in self.__seqid: f.write(">"+sid+"\n") f.write(self.__seq[sid].get_sequence()+"\n") f.close() del f
Python
nomic_cornstack_python_v1
function __setattr__ self name0 val begin if call _is_private_property name0 begin set __dict__ at name0 = val return end if name0 in __subst_dict begin set name = __subst_dict at name0 end else begin set name = name0 end comment end comment replace common substitutions for string value if type val is str begin set val...
def __setattr__(self,name0,val): if self._is_private_property(name0): self.__dict__[name0] = val; return if name0 in self.__subst_dict: name = self.__subst_dict[name0] else: name =name0; #end # replace common substitutions for s...
Python
nomic_cornstack_python_v1
import sqlite3 from config import States set BASE = string base_telegram.db set sql_insert = string insert into USER_INFO(USER_ID,{field}) values({user},'{value}'); set sql_update = string update USER_INFO set {field}='{value}' where USER_ID={user}; set sql_get_state = string select STATE_DIALOG from USER_INFO where US...
import sqlite3 from config import States BASE = 'base_telegram.db' sql_insert = ("""insert into USER_INFO(USER_ID,{field}) values({user},'{value}');""") sql_update = ("""update USER_INFO set {field}='{value}' where USER_ID={user};""") sql_get_state = (""" select STATE_DIALOG ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment Generated by the protocol buffer compiler. DO NOT EDIT! comment source: gym.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: gym.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_datab...
Python
jtatman_500k
import ngram_score as ns import caesar_cipher as cc set fitness = call ngram_score string data/english_quadgrams.txt function break_cipher ciphertext keys begin set max_fitness_score = decimal string -inf for key in keys begin set plaintext = call caesar_decipher ciphertext key set fitness_score = score fitness plainte...
import ngram_score as ns import caesar_cipher as cc fitness = ns.ngram_score('data/english_quadgrams.txt') def break_cipher(ciphertext, keys): max_fitness_score = float('-inf') for key in keys: plaintext = cc.caesar_decipher(ciphertext, key) fitness_score = fitness.score(plaintext) i...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- import pandas as pd from Furniture import * from collections import defaultdict import re import threading comment import multiprocessing as mp import time function readdata filename begin set dataset = dict set data = read csv filename usecols=list string url str...
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd from Furniture import * from collections import defaultdict import re import threading #import multiprocessing as mp import time def readdata(filename): dataset={} data = pd.read_csv(filename,usecols=['url', 'label'],dtype={"url": str,'label':int},true_v...
Python
zaydzuhri_stack_edu_python
function test_gshadow_centos_7_7 self begin assert equal parse gshadow centos_7_7_gshadow quiet=true centos_7_7_gshadow_json end function
def test_gshadow_centos_7_7(self): self.assertEqual(jc.parsers.gshadow.parse(self.centos_7_7_gshadow, quiet=True), self.centos_7_7_gshadow_json)
Python
nomic_cornstack_python_v1
function get_off_geometry_from_group group begin set vertices = group at string geometry_group at string vertices at Ellipsis return tuple vertices group at string geometry_group at string faces at Ellipsis group at string geometry_group at string winding_order at Ellipsis end function
def get_off_geometry_from_group(group): vertices = group['geometry_group']['vertices'][...] return vertices, group['geometry_group']['faces'][...], group['geometry_group']['winding_order'][...]
Python
nomic_cornstack_python_v1
function add self side begin set verts = call frozenset side set self at verts = self at verts + call _orientation side end function
def add(self, side): verts = frozenset(side) self[verts] += _orientation(side)
Python
nomic_cornstack_python_v1
function set_data self xs ys data zs=none begin comment block until any previous calls to set_data have been fully processed acquire image at string sem comment set the new x and y data set image at string x = xs set image at string y = ys if zs is not none begin set image at string z = zs end set image at string data ...
def set_data(self, xs, ys, data, zs=None): # block until any previous calls to set_data have been fully processed self.image['sem'].acquire() # set the new x and y data self.image['x'] = xs self.image['y'] = ys if zs is not None: self.image['z'] = zs s...
Python
nomic_cornstack_python_v1
function process_labels self input_file begin set p = call Parser input_file set current_line = 0 while call has_more_comamnds begin process set cmd_type = call _cmd_type if cmd_type == A_CMD or cmd_type == C_CMD begin set current_line = current_line + 1 end else begin call insert_entry call _sym current_line end end e...
def process_labels(self, input_file): p = Parser.Parser(input_file) current_line = 0 while p.has_more_comamnds(): p.process() cmd_type = p._cmd_type() if cmd_type == p.A_CMD or cmd_type == p.C_CMD: current_line += 1 else: ...
Python
nomic_cornstack_python_v1
function split_data self df split_column_idx split_value begin set data = values set split_column_values = data at tuple slice : : split_column_idx set type_of_feature = features_type at split_column_idx if type_of_feature == string continuous begin set data_below = data at split_column_values <= split_value set dat...
def split_data(self, df, split_column_idx, split_value): data = df.values split_column_values = data[:, split_column_idx] type_of_feature = self.features_type[split_column_idx] if type_of_feature == "continuous": data_below = data[split_column_values <= split_value] ...
Python
nomic_cornstack_python_v1
comment noqa: E501 # noqa: E501 function __init__ self table_name=none queries=none desc=none display_text=none server_text=none query_descriptions=none output_type=none string_size=none local_vars_configuration=none begin if local_vars_configuration is none begin set local_vars_configuration = call Configuration end s...
def __init__(self, table_name=None, queries=None, desc=None, display_text=None, server_text=None, query_descriptions=None, output_type=None, string_size=None, local_vars_configuration=None): # noqa: E501 # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() ...
Python
nomic_cornstack_python_v1
comment https://codeforces.com/problemset/problem/1167/A comment Lang : Python 3.8 comment Time : 46 ms comment Memory : 0 KB set t = integer input for x in range 0 t begin set tuple n s = tuple integer input input set i = find s string 8 if expression i >= 0 and n - i >= 11 then print string YES else print string NO e...
#https://codeforces.com/problemset/problem/1167/A #Lang : Python 3.8 #Time : 46 ms #Memory : 0 KB t=int(input()) for x in range(0,t): n,s=int(input()),input() i=s.find('8') print("YES") if (i>=0 and n-i>=11) else print("NO")
Python
zaydzuhri_stack_edu_python
function error self update context begin warning string Update "%s" caused error "%s" update error end function
def error(self, update, context): logger.warning('Update "%s" caused error "%s"', update, context.error)
Python
nomic_cornstack_python_v1
function close self begin call _close end function
def close(self): self._close()
Python
nomic_cornstack_python_v1
import sqlalchemy as db import pandas as pd set engine = call create_engine string mysql+pymysql://eknath:1nath@Mysql@localhost/classicmodels set connection = call connect set metadata = call MetaData set customers = call Table string customers metadata autoload=true autoload_with=engine set offices = call Table string...
import sqlalchemy as db import pandas as pd engine = db.create_engine('mysql+pymysql://eknath:1nath@Mysql@localhost/classicmodels') connection = engine.connect() metadata = db.MetaData() customers = db.Table('customers', metadata, autoload=True, autoload_with=engine) offices = db.Table('offices', metadata, autoload=Tru...
Python
zaydzuhri_stack_edu_python
comment x = 'dog' comment for letter in x: comment print(letter) comment # d o g comment for i in range(0, 5): comment print(i) comment prints 0 1 2 3 4 comment while something_true: comment do_something comment def im_a_function(im_an_argument): comment do_something_with_argument comment return can_return_stuff_with_s...
# x = 'dog' # for letter in x: # print(letter) # # d o g # for i in range(0, 5): # print(i) # prints 0 1 2 3 4 # while something_true: # do_something # def im_a_function(im_an_argument): # do_something_with_argument # return can_return_stuff_with_stuff # if expression: # do_this # elif expression: #...
Python
zaydzuhri_stack_edu_python
function update_envelope_transfer_rules self account_id **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string callback begin return call update_envelope_transfer_rules_with_http_info account_id keyword kwargs end else begin set data = call update_envelope_transfer_rules_with_http_info a...
def update_envelope_transfer_rules(self, account_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_envelope_transfer_rules_with_http_info(account_id, **kwargs) else: (data) = self.update_envelope_transfer_rules_with_http_...
Python
nomic_cornstack_python_v1
function _handlePriceBarResetAllToDefaultButtonClicked self begin call _handleZoomScaleFactorResetButtonClicked call _handleHigherPriceBarColorResetButtonClicked call _handleLowerPriceBarColorResetButtonClicked call _handleBarCountGraphicsItemColorResetButtonClicked call _handleBarCountGraphicsItemTextColorResetButtonC...
def _handlePriceBarResetAllToDefaultButtonClicked(self): self._handleZoomScaleFactorResetButtonClicked() self._handleHigherPriceBarColorResetButtonClicked() self._handleLowerPriceBarColorResetButtonClicked() self._handleBarCountGraphicsItemColorResetButtonClicked() self._handleB...
Python
nomic_cornstack_python_v1
comment open_image_from_memory_2.py import io import urllib.request from PIL import Image comment Use a real URL to an image here: set url = string http://my_url/photo.jpg set f = url open url set data = read f with open call BytesIO data as image begin show string Downloaded Image end
# open_image_from_memory_2.py import io import urllib.request from PIL import Image # Use a real URL to an image here: url = "http://my_url/photo.jpg" f = urllib.request.urlopen(url) data = f.read() with Image.open(io.BytesIO(data)) as image: image.show("Downloaded Image")
Python
zaydzuhri_stack_edu_python
function _convert_to_boolean self value begin if type value is bool begin return value end if lower value not in BOOLEAN_STATES begin raise call ValueError string Not a boolean: %s % value end return BOOLEAN_STATES at lower value end function
def _convert_to_boolean(self, value): if type(value) is bool: return value if value.lower() not in self.BOOLEAN_STATES: raise ValueError('Not a boolean: %s' % value) return self.BOOLEAN_STATES[value.lower()]
Python
nomic_cornstack_python_v1
function detach_volume self instance_name mountpoint begin return true end function
def detach_volume(self, instance_name, mountpoint): return True
Python
nomic_cornstack_python_v1
function test_fma_invalid_param_bytes_intarray_floatarray_bytes_1088 self begin comment This version is expected to pass. call fma floatarrayx floatarrayy floatarrayz floatarrayout comment This is the actual test. with assert raises TypeError begin call fma bytesx intarrayy floatarrayz bytesout end end function
def test_fma_invalid_param_bytes_intarray_floatarray_bytes_1088(self): # This version is expected to pass. arrayfunc.fma(self.floatarrayx, self.floatarrayy, self.floatarrayz, self.floatarrayout) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.fma(self.bytesx, self.intarrayy, self.flo...
Python
nomic_cornstack_python_v1
async function close self begin debug string Closing connection. if _connected begin await call _stop_producer for handler in inputs begin await call stop end set _connected = false debug string Closed Kafka connection. end else begin raise exception string Trying to close a Kafka connection that is not open end end fu...
async def close(self): logger.debug("Closing connection.") if self._connected: await self._stop_producer() for handler in self.inputs: await handler.stop() self._connected = False logger.debug("Closed Kafka connection.") else: ...
Python
nomic_cornstack_python_v1
comment Функция, которая принимает три аргумента function info object color price begin print string Объект: object print string Цвет: color print string Цена: price print end function comment передача параметров в прямом порядке info string ручка string синий 1 comment передача параметров в произвольном порядке info p...
# Функция, которая принимает три аргумента def info(object, color, price): print('Объект:', object) print('Цвет:', color) print('Цена:', price) print() # передача параметров в прямом порядке info('ручка', 'синий', 1) # передача параметров в произвольном порядке info(price=5, object='чашка', color='ора...
Python
zaydzuhri_stack_edu_python
import matplotlib import numpy as np import pandas as pd from collections import namedtuple from matplotlib import pyplot as plt import config from matplotlib import animation import os from mpl_toolkits.mplot3d import Axes3D set EpisodeStats = named tuple string Stats list string episode_lengths string episode_rewards...
import matplotlib import numpy as np import pandas as pd from collections import namedtuple from matplotlib import pyplot as plt import config from matplotlib import animation import os from mpl_toolkits.mplot3d import Axes3D EpisodeStats = namedtuple("Stats", ["episode_lengths", "episode_rewards"]) def plot_cost_he...
Python
zaydzuhri_stack_edu_python
import urllib import urllib2 import time import scipy.stats from cookielib import CookieJar set cj = call CookieJar set opener = call build_opener call HTTPCookieProcessor cj set url = string http://localhost/login.php set values = dict string username string sdfasdfs ; string password string sdfasdfa ; string Login st...
import urllib import urllib2 import time import scipy.stats from cookielib import CookieJar cj = CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) url = 'http://localhost/login.php' values = { 'username':'sdfasdfs', 'password':'sdfasdfa', 'Login':'Login'}
Python
zaydzuhri_stack_edu_python
import os import Tkinter as tk import Image , ImageTk import pyglet import gui import lilypond as ly import alt_notation.blocks as blocks comment TODO: find PDF viewer class ScoreViewer begin function __init__ self score_file begin string Create a ScoreViewer object. args ---- score_file: Lilypond file containing the i...
import os import Tkinter as tk import Image, ImageTk import pyglet import gui import lilypond as ly import alt_notation.blocks as blocks # TODO: find PDF viewer class ScoreViewer: def __init__(self, score_file): """Create a ScoreViewer object. args ---- score_file: Lilypond file containing the initi...
Python
zaydzuhri_stack_edu_python
function add_master self zone flavor k8s_version=KUBERNETES_BASE_VERSION k8s_conf=none **kwargs begin set cloud_config = cloud_config set master = call create_new_master zone flavor set loop = call get_event_loop set key = call find_keypair name set koris_env = dict string k8s_version k8s_version update koris_env get k...
def add_master( self, zone, flavor, k8s_version=KUBERNETES_BASE_VERSION, k8s_conf=None, **kwargs): cloud_config = self.cloud_config master = self.create_new_master(zone, flavor) loop = asyncio.get_event_loop() key...
Python
nomic_cornstack_python_v1
string see fishMonger_readme import time import tensorflow as tf import numpy as np import convnet as cv from skimage import io as skio import os import random as rd import math comment from skimage.viewer import ImageViewer from skimage import util as skut import multiprocessing from functools import partial import sy...
""" see fishMonger_readme """ import time import tensorflow as tf import numpy as np import convnet as cv from skimage import io as skio import os import random as rd import math # from skimage.viewer import ImageViewer from skimage import util as skut import multiprocessing from functools import partial ...
Python
zaydzuhri_stack_edu_python
function get_contributors_repo repoName organization outputFileName begin from yaml import dump function open_json fileUrl begin import json import requests if fileUrl at slice 0 : 4 : == string http begin comment es URL set pointer = get requests fileUrl return loads decode content string utf-8 end else begin comment...
def get_contributors_repo(repoName, organization, outputFileName): from yaml import dump def open_json(fileUrl): import json import requests if fileUrl[0:4] == "http": # es URL pointer = requests.get(fileUrl) return json.loads(pointer.content.decode(...
Python
zaydzuhri_stack_edu_python
function chamfer_loss control_points num_cps im distance_im covariance probabilistic_map_generator grid begin set batch_size = shape at 0 set pmap = call probabilistic_map_generator control_points num_cps covariance mode=string p set pred_seq = call bezier control_points num_cps unsqueeze linear space 0 1 150 device=de...
def chamfer_loss(control_points, num_cps, im, distance_im, covariance, probabilistic_map_generator, grid): batch_size = im.shape[0] pmap = probabilistic_map_generator(control_points, num_cps, covariance, mode='p') pred_seq = bezier(control_points, num_cps, torch.linspace(0, 1, 150, d...
Python
nomic_cornstack_python_v1
import unittest import random from faker import Faker from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from common.common import login , get_welcome_message , logout class...
import unittest import random from faker import Faker from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from common.common import login, get_welcome_message, logout clas...
Python
zaydzuhri_stack_edu_python
function type_token_ratio text begin set count = call split_and_cleaned_tokens text comment Create a list of split and cleaned tokens and for each token if it is comment not in the new list, append it. Then divide the amount of tokens by comment the total number of words. set token = list for item in count begin if it...
def type_token_ratio(text): count = split_and_cleaned_tokens(text) # Create a list of split and cleaned tokens and for each token if it is # not in the new list, append it. Then divide the amount of tokens by # the total number of words. token = [] for item in count: if item no...
Python
nomic_cornstack_python_v1
for line in my_fa begin set a = a + 1 set line_min = line at slice : - 1 : set o = list split line_min string print o at 0 o at 1 set work = work + integer o at 1 append min_20 o at 0 if integer o at 1 <= 20000 begin print string string меньше 20000- o at 0 o at 1 end end print integer work / a string - средняя зарп...
for line in my_fa: a += 1 line_min = line[:-1] o = list(line_min.split(' ')) print(o[0], o[1]) work = work + int(o[1]) min_20.append(o[0]) if int(o[1]) <= 20000: print('\t','меньше 20000-',o[0],o[1]) print(int(work/a), '- средняя зарплата всех сотрудников') print(min_20...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri Sep 10 14:46:31 2021 @author: Kuniyoshi Nakane import cv2 import numpy as np comment VideoCaptureオブジェクトを取得 set capture = call VideoCapture 0 while true begin set tuple ret frame = read capture if ret begin set blur = call medianBlur frame 5 set img = call cvtColor blu...
# -*- coding: utf-8 -*- """ Created on Fri Sep 10 14:46:31 2021 @author: Kuniyoshi Nakane """ import cv2 import numpy as np # VideoCaptureオブジェクトを取得 capture = cv2.VideoCapture(0) while(True): ret, frame = capture.read() if ret : blur = cv2.medianBlur(frame, 5) img = cv2.cvtColor(blur, cv...
Python
zaydzuhri_stack_edu_python
function getNode self begin set node = call getNode self set tag = string edge set attrib at string bgn = id set attrib at string end = id return node end function
def getNode(self): node = Element.getNode(self) node.tag = 'edge' node.attrib['bgn'] = self.bgn.id node.attrib['end'] = self.end.id return(node)
Python
nomic_cornstack_python_v1
comment refactored code given by someone by fb user from Amigoscode import math , os , random , re , sys string 240321: # don't know how to execute code in vs code # guessing I have to wrap in a function # will just run the code as is in HR # ran in HR - works # NEXT STEP: Understand and explain code. comment 290321: n...
# refactored code given by someone by fb user from Amigoscode import math, os, random, re, sys ''' 240321: # don't know how to execute code in vs code # guessing I have to wrap in a function # will just run the code as is in HR # ran in HR - works # NEXT STEP: Understand and explain code. ''' # 290321: no rule for...
Python
zaydzuhri_stack_edu_python
function modifier self begin set match = match split string string . at - 1 return if expression match then call group 1 else none end function
def modifier(self) -> str: match = RE_MODIFIER.match(self.string.split(".")[-1]) return match.group(1) if match else None
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri May 10 17:53:08 2019 @author: rajubingi import pandas as pd import numpy as np import os from util import getCleansingNames , getListCount , flattened from matplotlib import pyplot as plt function BNPP1 inputfile begin comment This Progra...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 10 17:53:08 2019 @author: rajubingi """ import pandas as pd import numpy as np import os from util import getCleansingNames, getListCount, flattened from matplotlib import pyplot as plt def BNPP1(inputfile): #####################################...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 string 2014-2-10 习题33:While循环 set i = 0 set numbers = list
#coding=utf-8 ''' 2014-2-10 习题33:While循环 ''' i = 0 numbers = []
Python
zaydzuhri_stack_edu_python
function __init__ __self__ resource_name opts=none access_token_validity=none allowed_oauth_flows=none allowed_oauth_flows_user_pool_client=none allowed_oauth_scopes=none analytics_configuration=none auth_session_validity=none callback_urls=none default_redirect_uri=none enable_propagate_additional_user_context_data=no...
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, access_token_validity: Optional[pulumi.Input[int]] = None, allowed_oauth_flows: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, allow...
Python
nomic_cornstack_python_v1
for i in range 1 N + 1 begin if 2 ^ i - 1 < K begin set ans = ans + 2 ^ i - 1 end else begin set ans = ans + K end end print ans
for i in range(1,N+1): if 2**(i-1) < K: ans = ans + 2**(i-1) else: ans = ans + K print(ans)
Python
zaydzuhri_stack_edu_python
function accept self *args begin return call SphereSegment_accept self *args end function
def accept(self, *args): return _osgSim.SphereSegment_accept(self, *args)
Python
nomic_cornstack_python_v1
function default_collate batch begin set elem_type = type batch at 0 if is instance batch at 0 Tensor begin set out = none if _use_shared_memory begin comment If we're in a background process, concatenate directly into a comment shared memory tensor to avoid an extra copy set numel = sum list comprehension numel x for ...
def default_collate(batch): elem_type = type(batch[0]) if isinstance(batch[0], torch.Tensor): out = None if _use_shared_memory: # If we're in a background process, concatenate directly into a # shared memory tensor to avoid an extra copy numel = sum([x.numel()...
Python
nomic_cornstack_python_v1
function validate_address_request address_request begin if string street not in address_request begin raise call ValidationError string Missing street in address! end if string city not in address_request begin raise call ValidationError string Missing city in address! end if string zip_code not in address_request begi...
def validate_address_request(address_request): if 'street' not in address_request: raise ValidationError("Missing street in address!") if 'city' not in address_request: raise ValidationError("Missing city in address!") if 'zip_code' not in address_request: ...
Python
nomic_cornstack_python_v1
function WipeChromeData device begin try begin if call IsUserBuild begin call _UninstallIfMatch device _CHROME_PACKAGE_REGEX call RunShellCommand string rm -rf %s/* % call GetExternalStoragePath shell=true check_return=true call RunShellCommand string rm -rf /data/local/tmp/* shell=true check_return=true end else begin...
def WipeChromeData(device): try: if device.IsUserBuild(): _UninstallIfMatch(device, _CHROME_PACKAGE_REGEX) device.RunShellCommand( 'rm -rf %s/*' % device.GetExternalStoragePath(), shell=True, check_return=True) device.RunShellCommand( 'rm -rf /data/local/t...
Python
nomic_cornstack_python_v1
string '1' = 2 '2' = 5 '3' = 5 '4' = 4 '5' = 5 '6' = 6 '7' = 3 '8' = 7 '9' = 6 '0' = 6 set entrada = integer input string comment Inicia a variável set totalLeds = 0 for i in range entrada begin set numero = string input string set lista = list numero for i in range length lista begin if lista at i == string 1 begin se...
""" '1' = 2 '2' = 5 '3' = 5 '4' = 4 '5' = 5 '6' = 6 '7' = 3 '8' = 7 '9' = 6 '0' = 6""" entrada = int(input("")) totalLeds = 0 #Inicia a variável for i in range (entrada): numero = str(input("")) lista = list(numero) for i in range (len(lista)): if (lista[i] == '1'): totalLeds = totalL...
Python
zaydzuhri_stack_edu_python
function getProjectTasks self pid archived=false begin return call request PROJECTS + format string /{0} pid + string /tasks end function
def getProjectTasks(self, pid, archived=False): return self.request(Endpoints.PROJECTS + '/{0}'.format(pid) + '/tasks')
Python
nomic_cornstack_python_v1
import numpy as np function linear_intrp x x1 x2 y1 y2 begin return y2 - y1 / x2 - x1 * x - x1 + y1 end function class clsRateCurve begin function __init__ self curveMat curveRate begin set curveMat = curveMat set curveRate = curveRate end function function interpolate self t method begin if method == string linear beg...
import numpy as np def linear_intrp(x, x1, x2, y1, y2): return (y2-y1)/(x2-x1)*(x-x1) + y1 class clsRateCurve(): def __init__(self, curveMat, curveRate): self.curveMat = curveMat self.curveRate = curveRate def interpolate(self, t, method): if method == "linear": if t <=...
Python
zaydzuhri_stack_edu_python
from PyQt5.QtWidgets import QApplication , QMainWindow comment QMainWindow 를 상속합니다. class MyWindow extends QMainWindow begin function __init__ self begin comment 부모 클래스의 초기화 메서드를 가져와 실행합니다. call __init__ call setWindowTitle string My App call setGeometry 100 100 300 300 end function end class set app = call QApplicatio...
from PyQt5.QtWidgets import QApplication, QMainWindow class MyWindow(QMainWindow): # QMainWindow 를 상속합니다. def __init__(self): super().__init__() # 부모 클래스의 초기화 메서드를 가져와 실행합니다. self.setWindowTitle('My App') self.setGeometry(100, 100, 300, 300) app = QApplication([]) my_window = MyWindow(...
Python
zaydzuhri_stack_edu_python
import numpy as np import scipy as sp from scipy.fftpack import fftshift , ifftshift from tools import rayleighmode as _rayleighmode from tools import lowpassfilter as _lowpassfilter comment Try and use the faster Fourier transform functions from the anfft module if comment available try begin import anfft as _anfft co...
import numpy as np import scipy as sp from scipy.fftpack import fftshift, ifftshift from tools import rayleighmode as _rayleighmode from tools import lowpassfilter as _lowpassfilter # Try and use the faster Fourier transform functions from the anfft module if # available try: import anfft as _anfft # measure == True...
Python
zaydzuhri_stack_edu_python