code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
string You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset). function bitrep n begin string Returns the signed 32-bit binary representation of an...
""" You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset). """ def bitrep(n): """ Returns the signed 32-bit binary representation of an integ...
Python
zaydzuhri_stack_edu_python
function getHist self name **kwargs begin set extra = get kwargs string extra string set hist1 = list comprehension clone get _f format string {0[dir]}/{0[histname]}/{0[histname]}NFin{0[NFin]:02d}JetPt{0[pT]:02d}{0[extra]} dict string dir _directory1 ; string histname name ; string NFin _NFIN ; string pT i ; string ext...
def getHist(self, name, **kwargs): extra = kwargs.get("extra", "") hist1 = [ self._f.Get( "{0[dir]}/{0[histname]}/{0[histname]}NFin{0[NFin]:02d}JetPt{0[pT]:02d}{0[extra]}".format( { "dir": self._directory1, ...
Python
nomic_cornstack_python_v1
from functools import reduce import operator import itertools import matplotlib.pyplot as plt set xs = list tuple - 17 9 - 5 tuple - 1 7 13 tuple - 19 12 5 tuple - 6 - 6 - 4 set testx = list tuple - 1 0 2 tuple 2 - 10 - 7 tuple 4 - 8 8 tuple 3 5 - 1 set vs = list tuple 0 0 0 tuple 0 0 0 tuple 0 0 0 tuple 0 0 0 function...
from functools import reduce import operator import itertools import matplotlib.pyplot as plt xs = [(-17, 9, -5), (-1, 7, 13), (-19, 12, 5), (-6, -6, -4)] testx = [(-1, 0, 2), (2, -10, -7), (4, -8, 8), (3, 5, -1)] vs = [(0,0,0),(0,0,0),(0,0,0),(0,0,0)] def velocity_comp(vs): if vs[0] > vs[1]: return +1 ...
Python
zaydzuhri_stack_edu_python
function port_init self port_id num_queues st_queues ring_depth pkt_buffer_size begin try begin set port_cmd = string port_init %s %s %s %s %s % tuple port_id num_queues st_queues ring_depth pkt_buffer_size call sendline port_cmd call expect string xilinx-app> timeout=60 set result = before end except EOF begin set res...
def port_init(self, port_id, num_queues, st_queues, ring_depth, pkt_buffer_size): try: port_cmd = 'port_init %s %s %s %s %s' % (port_id, num_queues, st_queues, ring_depth, pkt_buffer_size) self.process.sendline(port_cmd) self.process.expect("xilinx-app>", timeout=60) ...
Python
nomic_cornstack_python_v1
function load_weights self model begin set weights = weights set this_weights = weights set non_expandable = list string bn string bias string relu string pad string pool for layer in layers begin set exp_weights = list for weight in weights begin if all begin append exp_weights call expand_dims call numpy axis=0 end ...
def load_weights(self, model): weights = self.ResNet50_2D.weights this_weights = model.weights non_expandable = ['bn', 'bias', 'relu', 'pad', 'pool'] for layer in self.ResNet50_2D.layers: exp_weights = [] for weight in layer.weights: if np.array([False fo...
Python
nomic_cornstack_python_v1
import pandas as pd comment create a dataframe set df = call DataFrame dict string Name list string John string Mary string Chris ; string Score list 90 80 95 comment function to calculate the grade
import pandas as pd # create a dataframe df = pd.DataFrame({ 'Name': ['John', 'Mary', 'Chris'], 'Score': [90, 80, 95], }) # function to calculate the grade
Python
iamtarun_python_18k_alpaca
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import requests from selenium import webdriver set driver = call Chrome string C:/Users/tertychnyy/PycharmProjects/webdriver/chromedriver.exe set url = get driver string http://192.168.165.48/OMK/i...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import requests from selenium import webdriver driver = webdriver.Chrome('C:/Users/tertychnyy/PycharmProjects/webdriver/chromedriver.exe') url = driver.get('http://192.168.165.48/OMK/index....
Python
zaydzuhri_stack_edu_python
for registro in registros begin set campos = split registro string , for campo in campos begin set valores = split campo string = print string { capitalize valores at 0 } : { valores at 1 } end print string ==================== end
for registro in registros: campos = registro.split(",") for campo in campos: valores = campo.split("=") print(f"{valores[0].capitalize()}: {valores[1]}") print("====================")
Python
zaydzuhri_stack_edu_python
import sys import getpass import hashlib import logging set logFile = open string log.txt call basicConfig level=DEBUG filename=string log.txt filemode=string a format=string %(asctime)s %(levelname)s %(message)s function main begin set uname = input string Username: set passwd = call getpass set salt = string #*&!678G...
import sys import getpass import hashlib import logging logFile = open('log.txt') logging.basicConfig(level=logging.DEBUG, filename='log.txt', filemode='a', format='%(asctime)s %(levelname)s %(message)s' ) def main(): uname = input('Username: ') passwd = getpass.getpass() ...
Python
zaydzuhri_stack_edu_python
function list self project instance begin set request : HttpRequest set request = list project=project instance=instance set response = execute request return response at string items end function
def list(self, project: str, instance: str) -> List[dict]: request: googleapiclient.http.HttpRequest request = self.admin.service.databases().list( project=project, instance=instance ) self.admin.response = request.execute() return self.admin.response["items"]
Python
nomic_cornstack_python_v1
function __init__ self begin comment Initialize cache. set _cache = dict comment Initialize default settings. set defaults = dict string api_url string http://127.0.0.1:8000/api ; string client_id string ; string client_secret string ; string refresh_token string ; string verbose string false set _defaults = call P...
def __init__(self): # Initialize cache. self._cache = {} # Initialize default settings. defaults = { 'api_url': 'http://127.0.0.1:8000/api', 'client_id': '', 'client_secret': '', 'refresh_token': '', 'verbose': 'false', ...
Python
nomic_cornstack_python_v1
for i in range n begin set tuple ai bi = map int split input append ab ai + bi end set cnt = 0 for i in range length ab begin if i - ab at i >= 0 and h at i - ab at i == 1 begin set h at i - ab at i = 0 set cnt = cnt + 1 end end print cnt
for i in range(n): ai, bi = map(int, input().split()) ab.append(ai + bi) cnt = 0 for i in range(len(ab)): if i - ab[i] >= 0 and h[i - ab[i]] == 1: h[i - ab[i]] = 0 cnt += 1 print(cnt)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Mar 5 14:43:11 2019 @author: Fortaleza import numpy as np set entradas = array list list 0 0 list 0 1 list 1 0 list 1 1 set saidas = array list 0 0 0 1 set pesos = array list 0.0 0.0 set taxaAprendizagem = 0.1 function stepFunction soma begin if soma >= 1 begin return...
# -*- coding: utf-8 -*- """ Created on Tue Mar 5 14:43:11 2019 @author: Fortaleza """ import numpy as np entradas = np.array( [ [0,0],[0,1],[1,0],[1,1] ]) saidas = np.array([0,0,0,1]) pesos = np.array([0.0,0.0]) taxaAprendizagem = 0.1 def stepFunction(soma): if (soma >= 1): return 1 return 0 ...
Python
zaydzuhri_stack_edu_python
function from_optimization_endpoints result rel_cutoff=none max_size=inf percentile=none **kwargs begin if rel_cutoff is none and percentile is none begin set abs_cutoff = inf end else if rel_cutoff is not none begin set abs_cutoff = fval + rel_cutoff if percentile is not none begin warning string percentile is going t...
def from_optimization_endpoints( result: Result, rel_cutoff: float = None, max_size: int = np.inf, percentile: float = None, **kwargs, ): if rel_cutoff is None and percentile is None: abs_cutoff = np.inf elif rel_cutoff is not None: abs...
Python
nomic_cornstack_python_v1
comment https://github.com/jiecaoyu/pytorch_imagenet/blob/master/networks/model_list/alexnet.py import torch.nn as nn class LRN extends Module begin function __init__ self local_size=1 alpha=1.0 beta=0.75 ACROSS_CHANNELS=true begin call __init__ set ACROSS_CHANNELS = ACROSS_CHANNELS if ACROSS_CHANNELS begin set average...
# https://github.com/jiecaoyu/pytorch_imagenet/blob/master/networks/model_list/alexnet.py import torch.nn as nn class LRN(nn.Module): def __init__(self, local_size=1, alpha=1.0, beta=0.75, ACROSS_CHANNELS=True): super(LRN, self).__init__() self.ACROSS_CHANNELS = ACROSS_CHANNELS if ACROSS_CHANNELS: self.aver...
Python
zaydzuhri_stack_edu_python
function setPixelColorRGB self n red green blue white=0 begin debug string setPixelColorRGB end function
def setPixelColorRGB(self, n, red, green, blue, white=0): self._logger.debug("setPixelColorRGB")
Python
nomic_cornstack_python_v1
function load_file self begin comment Check if a channel is selected if currentSelected == 0 begin call show_popup string No Selected Pannel string First Select a Panel by clicking on it pass end else begin set i = 0 comment Open File set tuple filename format = call getOpenFileName none string Load Signal string /home...
def load_file(self): # Check if a channel is selected if signalViewer.currentSelected == 0: self.show_popup("No Selected Pannel", "First Select a Panel by clicking on it") pass else: signalViewer.i = 0 # Open File self.filename, self.fo...
Python
nomic_cornstack_python_v1
function setViewletsForType self type viewlet_ids default_viewlet begin if viewlet_ids == tuple DEFAULT begin call setTypeUseDefaultSetup type set viewlet_ids = call getForType type set viewlets = list comprehension call getViewletById viewlet_id for viewlet_id in viewlet_ids end else begin call clearForType type set v...
def setViewletsForType(self, type, viewlet_ids, default_viewlet): if viewlet_ids == (DEFAULT, ): self._viewlet_registry.setTypeUseDefaultSetup(type) viewlet_ids = self._viewlet_registry.getForType(type) viewlets = [self.getViewletById(viewlet_id) for v...
Python
nomic_cornstack_python_v1
function test_bind_some begin function factory inner_value begin return call Some inner_value * 2 end function set input_value = 5 set bound = call bind factory assert bound == call factory input_value assert string bound == string <Some: 10> end function
def test_bind_some(): def factory(inner_value: int) -> Maybe[int]: return Some(inner_value * 2) input_value = 5 bound = Some(input_value).bind(factory) assert bound == factory(input_value) assert str(bound) == '<Some: 10>'
Python
nomic_cornstack_python_v1
function event_log tx_hash events provider contract begin try begin set receipt = call getTransactionReceipt tx_hash end except TransactionNotFound begin comment hard coded sleep for 3 seconds... maybe this will help? sleep 3000 comment retry try begin set receipt = call getTransactionReceipt tx_hash end except Transac...
def event_log(tx_hash: str, events: List[str], provider: Web3, contract: Web3Contract) -> \ Tuple[str, Optional[AttributeDict]]: try: receipt = provider.eth.getTransactionReceipt(tx_hash) except TransactionNotFound: time.sleep(3000) # hard coded sleep for 3 seconds... maybe this will he...
Python
nomic_cornstack_python_v1
string Форматирование import sys import logging comment Результат %()-9s соответствует comment операции {:<9} когда вы используете функцию format() comment длина слова set WORD = string CRITICAL length WORD comment Правый отступ равен 9 - длина слово comment Таким образом, мы имеем 1 пробел между словом и решеткой prin...
""" Форматирование """ import sys import logging # Результат %()-9s соответствует # операции {:<9} когда вы используете функцию format() # длина слова WORD = 'CRITICAL' len(WORD) # Правый отступ равен 9 - длина слово # Таким образом, мы имеем 1 пробел между словом и решеткой print('{:<9}#text'.forma...
Python
zaydzuhri_stack_edu_python
import sys set int1 = lambda x -> integer x - 1 set p2D = lambda x -> print *x sep=string function II begin return integer read line stdin end function function MI begin return map int split read line stdin end function function LI begin return list map int split read line stdin end function function LLI rows_number be...
import sys int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sy...
Python
jtatman_500k
function find_optimal_route fuel distance time storm_factor begin set n = length distance set f = list comprehension list 0 * n for _ in range n for j in range 1 n begin set f at 0 at j = fuel at j end for i in range 1 n begin for j in range i + 1 n begin set f at i at j = decimal string inf for k in range j begin set ...
def find_optimal_route(fuel, distance, time, storm_factor): n = len(distance) f = [[0] * n for _ in range(n)] for j in range(1, n): f[0][j] = fuel[j] for i in range(1, n): for j in range(i+1, n): f[i][j] = float('inf') for k in range(j): f[i][j] = ...
Python
jtatman_500k
from typing import List function intersection nums1 nums2 begin sort nums1 sort nums2 set i = 0 set j = 0 set nums_set = set while i < length nums1 and j < length nums2 begin if nums1 at i > nums2 at j begin set j = j + 1 end else if nums1 at i < nums2 at j begin set i = i + 1 end else if nums1 at i == nums2 at j begin...
from typing import List def intersection(nums1:List[int],nums2:List[int]): nums1.sort() nums2.sort() i=0 j=0 nums_set=set() while i<len(nums1)and j<len(nums2): if nums1[i]>nums2[j]: j+=1 elif nums1[i]<nums2[j]: i+=1 elif nums1[i]==nums2[j]: ...
Python
zaydzuhri_stack_edu_python
from StringIO import StringIO from docx.shared import Cm from docxtpl import DocxTemplate , InlineImage function get_context begin string You can generate your context separately since you may deal with a lot of documents. You can carry out computations, etc in here and make the context look like the sample below. retu...
from StringIO import StringIO from docx.shared import Cm from docxtpl import DocxTemplate, InlineImage def get_context(): """ You can generate your context separately since you may deal with a lot of documents. You can carry out computations, etc in here and make the context look like the sample b...
Python
zaydzuhri_stack_edu_python
function plot_pmf self **options begin set tuple xs ps = zip *sorted(self.items()) plot xs ps keyword options end function
def plot_pmf(self, **options): xs, ps = zip(*sorted(self.items())) plt.plot(xs, ps, **options)
Python
nomic_cornstack_python_v1
import numpy as np import cv2 comment The following line loads our classifier. set faceCascade = call CascadeClassifier string classifiers/haarcascade_frontalface_default.xml set smileCascade = call CascadeClassifier string classifiers/haarcascade_smile.xml set face_label = string Face Detected comment Enable web camer...
import numpy as np import cv2 # The following line loads our classifier. faceCascade = cv2.CascadeClassifier('classifiers/haarcascade_frontalface_default.xml') smileCascade = cv2.CascadeClassifier('classifiers/haarcascade_smile.xml') face_label = "Face Detected" # Enable web camera, set width and height. cap = cv2.V...
Python
zaydzuhri_stack_edu_python
comment D set s = input if s at 0 == s at - 1 begin if length s % 2 == 0 begin print string First end else begin print string Second end end else if length s % 2 == 0 begin print string Second end else begin print string First end
#D s = input() if s[0] == s[-1]: if len(s)%2==0: print("First") else: print("Second") else: if len(s)%2==0: print("Second") else: print("First")
Python
jtatman_500k
comment encoding=utf-8 import random from pip._vendor.distlib.compat import raw_input set a1 = integer call raw_input string 请输入购买彩票注数: for i in range 0 a1 begin set alis = random sample range 1 34 6 set B = random integer 0 15 print string 第 i + 1 string 注: alis string , [ B + 1 string ] end
# encoding=utf-8 import random from pip._vendor.distlib.compat import raw_input a1 = int(raw_input("请输入购买彩票注数:")) for i in range(0, a1): alis = random.sample(range(1, 34), 6) B = random.randint(0, 15) print("第", i + 1, "注:", alis, ", [", B + 1, "]")
Python
zaydzuhri_stack_edu_python
function onApply self event begin comment Rename all of the files based on the substitution. for tuple old new in zip m_diskNames m_newNames begin if old != new begin set old = join path m_curPath old set new = join path m_curPath new try begin rename old new end except OSError begin pass end end end comment Now we out...
def onApply(self, event): # Rename all of the files based on the substitution. for (old, new) in zip(self.m_diskNames, self.m_newNames): if old != new: old = os.path.join(self.m_curPath, old) new = os.path.join(self.m_curPath, new) try: ...
Python
nomic_cornstack_python_v1
string Listing 2.49 If the data is already in memory, it is more efficient to use heapify to rearrange the items of the list in place The result of building a list in heap order one item at a time is the same as building an underordered list and then calling heapify() import heapq from heapq_showtree import show_tree f...
""" Listing 2.49 If the data is already in memory, it is more efficient to use heapify to rearrange the items of the list in place The result of building a list in heap order one item at a time is the same as building an underordered list and then calling heapify() """ import heapq from heapq_showtree import show_tre...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from xp import XP class Vocab begin set __EOS = 0 set __PAD = - 1 function __init__ self n_vocab leng gpu seed begin call set_library gpu seed set n_vocab = n_vocab set leng = leng end function function gen_train_data self n_data begin set train_data = list for _ in range n_data begin set...
# -*- coding: utf-8 -*- from xp import XP class Vocab(): __EOS = 0 __PAD = -1 def __init__(self, n_vocab, leng, gpu, seed): XP.set_library(gpu, seed) self.n_vocab = n_vocab self.leng = leng def gen_train_data(self, n_data): train_data = [] for _ in range(n_da...
Python
zaydzuhri_stack_edu_python
function SumSquareDiff n begin comment The Summation Idenity for the sum of i^2 where n goes from 1 to n set squareSum = n * n + 1 * 2 * n + 1 / 6 comment The Summation Idenity for the sum of i where n goes from 1 to n set sumSquare = n * n + 1 / 2 comment Need to square the sum of i set sumSquare = sumSquare * sumSqua...
def SumSquareDiff (n): # The Summation Idenity for the sum of i^2 where n goes from 1 to n squareSum = (n * (n + 1) * (2 * n + 1)) / 6 # The Summation Idenity for the sum of i where n goes from 1 to n sumSquare = (n * (n + 1)) / 2 # Need to square the sum of i sumSquare = sumSquare * sumSqu...
Python
zaydzuhri_stack_edu_python
function compare_match test_case expected received parameterized=true begin set msg = format string {} != {} call pretty_print_match expected parameterized=parameterized call pretty_print_match received parameterized=parameterized call compare_ignoring_whitespace test_case expected received msg end function
def compare_match(test_case, expected, received, parameterized=True): msg = '\n{}\n\n!=\n\n{}'.format( pretty_print_match(expected, parameterized=parameterized), pretty_print_match(received, parameterized=parameterized)) compare_ignoring_whitespace(test_case, expected, received, msg)
Python
nomic_cornstack_python_v1
comment append, extend, pop, remove, del, insert etc comment [1, 4, 9, 16, 25] set nums = list 1 2 3 4 5 set new_nums = list for i in nums begin append new_nums i * i end print new_nums print list range 1 11 2 comment find the sum of all numbers from 0 to 100 set all_nums = 0 for i in range 0 101 begin set all_nums = ...
# append, extend, pop, remove, del, insert etc nums = [1, 2, 3, 4, 5] # [1, 4, 9, 16, 25] new_nums = [] for i in nums: new_nums.append(i * i) print(new_nums) print(list(range(1, 11, 2))) # find the sum of all numbers from 0 to 100 all_nums = 0 for i in range(0, 101): all_nums = all_nums + i print(all_nums...
Python
zaydzuhri_stack_edu_python
import re comment https://regex101.com/r/DfXYXM/1/ set regexp = compile string ^(?:\(\d{2}\)\s)(?:9\s)(?:\d{4}-\d{4})$ flags=M set texto = string (21) 9 8852-5214 (11)9955-1231 (11) 9955-1231 (35) 9 9975-4521 (31) 3851-2587 9 8571-5213 1234-5647 for telefone in find all texto begin print telefone end
import re # https://regex101.com/r/DfXYXM/1/ regexp = re.compile(r'^(?:\(\d{2}\)\s)(?:9\s)(?:\d{4}-\d{4})$', flags=re.M) texto = ''' (21) 9 8852-5214 (11)9955-1231 (11) 9955-1231 (35) 9 9975-4521 (31) 3851-2587 9 8571-5213 1234-5647 ''' for telefone in regexp.findall(texto): print(telefone)
Python
zaydzuhri_stack_edu_python
function getMostImportantLatentTopic id LT begin set CLT = min LT key=lambda ControlLatentTopic -> call getBelongingDegree id if call getBelongingDegree id >= 0 begin return max LT key=lambda ControlLatentTopic -> call getBelongingDegree id end else begin return none end end function
def getMostImportantLatentTopic(id, LT): CLT=min(LT, key=lambda ControlLatentTopic: ControlLatentTopic.getBelongingDegree(id)) if CLT.getBelongingDegree(id)>=0: return max(LT, key=lambda ControlLatentTopic: ControlLatentTopic.getBelongingDegree(id)) else: return None
Python
nomic_cornstack_python_v1
function getColor rgb=none hsv=none begin string Convert a color or list of colors to (r,g,b) format from many input formats. :param bool hsv: if set to `True`, rgb is assumed as (hue, saturation, value). Example: - RGB = (255, 255, 255), corresponds to white - rgb = (1,1,1) is white - hex = #FFFF00 is yellow - string ...
def getColor(rgb=None, hsv=None): """ Convert a color or list of colors to (r,g,b) format from many input formats. :param bool hsv: if set to `True`, rgb is assumed as (hue, saturation, value). Example: - RGB = (255, 255, 255), corresponds to white - rgb = (1,1,1) is white ...
Python
jtatman_500k
import tensorflow as tf import numpy as np function test1 begin set a = array list list 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 list 0.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 1.0 0.0 list 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 list 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 list 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 list 1.0 0.0...
import tensorflow as tf import numpy as np def test1(): a = np.array([[0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0., 1., 0., 1., 0.], [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.], [0., 0., 1., 0., 0., 0., 0., 0., 0., 1.], ...
Python
zaydzuhri_stack_edu_python
string NVidia Dave model trainer import argparse import csv import udacitylib import drivinglog from keras.models import Sequential from keras.layers import Flatten , Dense from keras.layers import Conv2D from keras.layers import Cropping2D from keras.layers import Lambda from keras.layers import Dropout from sklearn.u...
"""NVidia Dave model trainer """ import argparse import csv import udacitylib import drivinglog from keras.models import Sequential from keras.layers import Flatten, Dense from keras.layers import Conv2D from keras.layers import Cropping2D from keras.layers import Lambda from keras.layers import Dropout from sklear...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt set x = linear space - 1.0 1.0 500 set y = zeros 500 function huber_loss prediction label delta=0.5 begin set error = label - prediction set cond = absolute error < delta set squared_loss = 0.5 * call square error set linear_loss = delta * absol...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1., 1., 500) y = np.zeros(500) def huber_loss(prediction, label, delta=0.5): error = label - prediction cond = tf.abs(error) < delta squared_loss = 0.5 * tf.square(error) linear_loss = delta * ( tf.abs(error) -...
Python
zaydzuhri_stack_edu_python
function get_total_size_from_content_range self content_range begin set total_size = split content_range string / at - 1 set total_size = integer total_size return total_size end function
def get_total_size_from_content_range(self, content_range): total_size = content_range.split("/")[-1] total_size = int(total_size) return total_size
Python
nomic_cornstack_python_v1
function check_problem self data override_time=false begin set event_info = dictionary set event_info at string state = call get_state set event_info at string problem_id = call to_deprecated_string set answers = call make_dict_of_responses data set answers_without_files = call convert_files_to_filenames answers set ev...
def check_problem(self, data, override_time=False): event_info = dict() event_info['state'] = self.lcp.get_state() event_info['problem_id'] = self.location.to_deprecated_string() answers = self.make_dict_of_responses(data) answers_without_files = convert_files_to_filenames...
Python
nomic_cornstack_python_v1
function get self host_id begin set tuple resp body = get request_manager string /os-hosts/%s % host_id return body at string host end function
def get(self, host_id): resp, body = self.request_manager.get('/os-hosts/%s' % host_id) return body['host']
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Process uav files in prep for processing. This includes data logger and image comment files used for stitching and SFM processing set available_libs = list try begin import flytrex append available_libs string flytrex end except any begin pass end import glob import os from optpars...
#!/usr/bin/env python # Process uav files in prep for processing. This includes data logger and image # files used for stitching and SFM processing available_libs = [] try: import flytrex available_libs.append("flytrex") except: pass import glob import os from optparse import OptionParser, OptionGroup ...
Python
zaydzuhri_stack_edu_python
function word_count phrase begin return dictionary comprehension word : count split phrase word for word in split phrase end function
def word_count(phrase): return {word: phrase.split().count(word) for word in phrase.split()}
Python
zaydzuhri_stack_edu_python
function create_array rows cols begin set arr = list for i in range rows begin set row = list for j in range cols begin while true begin try begin set num = integer input string Enter an integer for index [ { i } ][ { j } ]: append row num break end except ValueError begin print string Invalid input. Please enter an ...
def create_array(rows, cols): arr = [] for i in range(rows): row = [] for j in range(cols): while True: try: num = int(input(f"Enter an integer for index [{i}][{j}]: ")) row.append(num) break ...
Python
jtatman_500k
comment Resetting Cursor Position in the file set file = open string myfile.txt string r read file 10 seek file - 5 1 set cursor = tell file print string Cursor Position Before Read : + string cursor close file
#Resetting Cursor Position in the file file=open("myfile.txt","r") file.read(10) file.seek(-5,1) cursor=file.tell() print("Cursor Position Before Read : " + str(cursor)) file.close()
Python
zaydzuhri_stack_edu_python
function init_timeseries_plot_config self begin comment Verify the section exist if string TIMESERIES not in config begin set config at string TIMESERIES = dict set config at string TIMESERIES at string IP = call get_ip set config at string TIMESERIES at string PORT = string 4241 set config at string TIMESERIES at str...
def init_timeseries_plot_config(self): # Verify the section exist if 'TIMESERIES' not in self.config: self.config['TIMESERIES'] = {} self.config['TIMESERIES']['IP'] = RtiConfig.get_ip() self.config['TIMESERIES']['PORT'] = '4241' self.config['TIMESERIES'][...
Python
nomic_cornstack_python_v1
function get_description self begin set d = dict set d at string type = string SymbolicIntegral0 return d end function
def get_description(self): d = {} d["type"] = "SymbolicIntegral0" return d
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Nov 16 11:43:30 2017 @author: lenovo import os import sys import struct import datetime import pandas as pd import sqlite3 comment 建立数据库 function createDataBase begin set cn = call connect string d:\hyb\STOCKDATA.db string GPDMB股票代码表 GPDM股票代码 GPMC股票名称 PY拼音 SSRQ上市日期 GP...
# -*- coding: utf-8 -*- """ Created on Thu Nov 16 11:43:30 2017 @author: lenovo """ import os import sys import struct import datetime import pandas as pd import sqlite3 ######################################################################## #建立数据库 ####################################################################...
Python
zaydzuhri_stack_edu_python
function heat_four_level t t1 t2 N10 mu=0 N20=0 N30=0 begin comment The experimental t = 0 is not necessarily the same as t=0 here. comment mu shifts the function on the x axis set t = t - mu set aux0 = exp t / t1 + t / t2 * t1 + exp t / t1 * t2 - exp t / t1 + t / t2 * t2 set aux1 = exp - t / t2 - t / t1 * N10 * aux0 -...
def heat_four_level(t, t1, t2, N10, mu=0, N20=0, N30=0): # The experimental t = 0 is not necessarily the same as t=0 here. # mu shifts the function on the x axis t = t - mu aux0 = (((np.exp(((t/t1)+(t/t2))))*t1)+((np.exp((t/t1)))*t2))-(( np.exp(((t/t1)+(t/t2))))*t2) aux1 = ( (np.exp(...
Python
nomic_cornstack_python_v1
function unregister_robot redis model_keys robot begin delete key_robots_prefix + name end function
def unregister_robot( redis: ctrlutils.RedisClient, model_keys: ModelKeys, robot: RobotModel ) -> None: redis.delete(model_keys.key_robots_prefix + robot.articulated_body.name)
Python
nomic_cornstack_python_v1
set numbers = list 1 2 3 4 5 6 7 8 9 10
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Python
jtatman_500k
function rods_connect begin set tuple status env = call getRodsEnv assert status == 0 msg string connect(): getRodsEnv() failed (%s): %s % tuple status call strerror status set tuple conn err = call rcConnect rodsHost rodsPort rodsUserName rodsZone assert status == 0 msg string connect(): rcConnect() failed (%s): %s % ...
def rods_connect(): status, env = irods.getRodsEnv() assert status == 0, 'connect(): getRodsEnv() failed (%s): %s' % (status, irods.strerror(status)) conn, err = irods.rcConnect(env.rodsHost, env.rodsPort, env.rodsUserName, ...
Python
nomic_cornstack_python_v1
import pygame from app.settings import * class StatDisplay begin function __init__ self background pos font statName=none textColor=HUD_FONT_COLOR begin set background = background set stat = none set statName = statName set printedLine = none set position = pos set font = font set textColor = textColor set stat2 = non...
import pygame from app.settings import * class StatDisplay: def __init__(self,background,pos,font,statName=None, textColor=HUD_FONT_COLOR): self.background = background self.stat = None self.statName = statName self.printedLine = None self.position = pos self.font = ...
Python
zaydzuhri_stack_edu_python
function sendrawtransaction self hexstring begin return call sendrawtransaction hexstring end function
def sendrawtransaction(self, hexstring): return self.proxy.sendrawtransaction(hexstring)
Python
nomic_cornstack_python_v1
function test_SqliteDb self begin set db = call SqliteDb call _createConnection modelGoldSqlite timeout=1000 set tables = list string Objects string Relations assert equal tables call getTables comment Test getting the version, for the gold file it should be 0 assert equal 0 call getVersion close db end function
def test_SqliteDb(self): db = SqliteDb() db._createConnection(self.modelGoldSqlite, timeout=1000) tables = ['Objects', 'Relations'] self.assertEqual(tables, db.getTables()) # Test getting the version, for the gold file it should be 0 self.assertEqual(0, ...
Python
nomic_cornstack_python_v1
string This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit. The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as testing instructions are located at http://amzn.to/1LzFrj6 For additional samples, visit the Alexa Skills Kit Getting Started guide at http://amzn.to/1...
""" This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit. The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as testing instructions are located at http://amzn.to/1LzFrj6 For additional samples, visit the Alexa Skills Kit Getting Started guide at http://amzn.to/1LG...
Python
zaydzuhri_stack_edu_python
function __get_intent self sentence begin set input_vector = call get_bow_unpacked sentence frequent_words return predict ml_model input_vector end function
def __get_intent(self, sentence: str): input_vector = get_bow_unpacked(sentence, self.frequent_words) return self.ml_model.predict(input_vector)
Python
nomic_cornstack_python_v1
comment coding=utf-8 set tuple a b = map int split call raw_input set outputs = list b set num = 1 while b > a begin if b % 2 == 0 begin set b = b / 2 append outputs b set num = num + 1 end else if b - 1 % 10 == 0 begin set b = b - 1 / 10 append outputs b set num = num + 1 end else begin break end end
#coding=utf-8 a,b=map(int,raw_input().split()) outputs=[b] num=1 while b>a: if b%2==0: b=b/2 outputs.append(b) num+=1 else: if (b-1)%10==0: b=(b-1)/10 outputs.append(b) num+=1 else: break
Python
zaydzuhri_stack_edu_python
function get_b_or_w begin try begin set color = input if color not in list string B string W begin raise Exception end end except any begin raise SystemExit end try else begin return color end end function
def get_b_or_w() -> str: try: color = input() if color not in ['B','W']: raise Exception except: raise SystemExit else: return color
Python
nomic_cornstack_python_v1
function fully_connected_relu input size begin return relu call fully_connected input size end function
def fully_connected_relu(input, size): return tf.nn.relu(fully_connected(input, size))
Python
nomic_cornstack_python_v1
comment Coding: UTF-8 comment This package allows the conversion of cable data to JSON objects. function map_dictionary descrip supplydict separator=string . *args begin string Map the contents of the flat dictionary 'supplydict' with the prefix 'descrip' to the keys contained with '*args'. This assumes that keys in '*...
# # Coding: UTF-8 # This package allows the conversion of cable data to JSON objects. def map_dictionary(descrip, supplydict, separator='.', *args): """ Map the contents of the flat dictionary 'supplydict' with the prefix 'descrip' to the keys contained with '*args'. This assumes that keys in '*args' are...
Python
zaydzuhri_stack_edu_python
function calcUnboundCounterpart2c self utils cCase begin set _unboundCounterpart = call parseCorrenspondingCounterpart2c call getReference string unbound cCase _unfilteredReferenceAtomCount set _unboundCounterpartBackup = copy _unboundCounterpart end function
def calcUnboundCounterpart2c(self, utils, cCase): self._unboundCounterpart = utils.parseCorrenspondingCounterpart2c(self.getReference(), "unbound", cCase, self._unfilteredReferenceAtomCount) self._unboundCounterpartBackup = self._unboundCounterpart.copy()
Python
nomic_cornstack_python_v1
function VDR_read self begin set VDRlines = list set line = false while line != string ## begin set line = read line vox comment Read next line append VDRlines strip strip line string string / end return VDRlines end function
def VDR_read(self): VDRlines = [] line = False while line != '##\x0c\n': line = self.vox.readline() #Read next line VDRlines.append(line.strip('\n').strip('/')) return VDRlines
Python
nomic_cornstack_python_v1
import xlwings as xw import tkinter as tk from DividendPortfolio import Column , get_start_row from yahoofinancials import YahooFinancials function insert_new_ticker begin set wb = call caller set sheet = sheets at 0 comment Create GUI frame set root = call Tk call geometry string 300x100 title root string Insert New T...
import xlwings as xw import tkinter as tk from DividendPortfolio import Column, get_start_row from yahoofinancials import YahooFinancials def insert_new_ticker(): wb = xw.Book.caller() sheet = wb.sheets[0] # Create GUI frame root = tk.Tk() root.geometry("300x100") root.title("Insert New Ticker"...
Python
zaydzuhri_stack_edu_python
string Codecs provide the knowledge of how to transform between a buffer of bytes and a higher-level representation. Codecs provide an encode from controlbox.adapter import ConnectorCodec from controlbox.stateful.controller import LongDecoder , ShortDecoder from controlbox.stateless.codecs import BaseState class Scaled...
""" Codecs provide the knowledge of how to transform between a buffer of bytes and a higher-level representation. Codecs provide an encode """ from controlbox.adapter import ConnectorCodec from controlbox.stateful.controller import LongDecoder, ShortDecoder from controlbox.stateless.codecs import BaseState class Sca...
Python
zaydzuhri_stack_edu_python
string 72. 编辑距离 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 示例 1: 输入: word1 = "horse", word2 = "ros" 输出: 3 解释: horse -> rorse (将 'h' 替换为 'r') rorse -> rose (删除 'r') rose -> ros (删除 'e') 示例 2: 输入: word1 = "intention", word2 = "execution" 输出: 5 解释: intention -> inention (删...
''' 72. 编辑距离 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 示例 1: 输入: word1 = "horse", word2 = "ros" 输出: 3 解释: horse -> rorse (将 'h' 替换为 'r') rorse -> rose (删除 'r') rose -> ros (删除 'e') 示例 2: 输入: word1 = "intention", word2 = "execution" 输出: 5 解释: intention -> inention (删除...
Python
zaydzuhri_stack_edu_python
from MDP import MDP import numpy as np class BellmanDPSolver extends object begin function __init__ self discountRate begin set MDP = call MDP set dr = discountRate set S = list comprehension tuple x y for x in range 5 for y in range 5 append S string GOAL append S string OUT set A = list string DRIBBLE_UP string DRIBB...
from MDP import MDP import numpy as np class BellmanDPSolver(object): def __init__(self, discountRate): self.MDP = MDP() self.dr = discountRate self.S = [(x,y) for x in range(5) for y in range(5)] self.S.append("GOAL") self.S.append("OUT") self.A = ["DRIBBLE_UP","DRIBBLE_DOWN","DRIBBLE_LEFT","DRIBBLE_RIG...
Python
zaydzuhri_stack_edu_python
function _fit num_objs _ begin set num_objs = call asarray num_objs dtype=int_ set nlevels = length num_objs if min num_objs < 0 begin raise call ValueError string must have at least one object in each level end if nlevels < 1 begin raise call ValueError string array of object counts is empty end if shape at 0 < 2 begi...
def _fit(num_objs, _): num_objs = np.asarray(num_objs, dtype=np.int_) nlevels = len(num_objs) if min(num_objs) < 0: raise ValueError("must have at least one object in each level") if nlevels < 1: raise ValueError("array of object counts is empty") if np.unique(num_objs).shape[0] < 2:...
Python
nomic_cornstack_python_v1
function write_raw self msg begin call sendall msg end function
def write_raw(self, msg): self._conn.sendall(msg)
Python
nomic_cornstack_python_v1
function test_people_4 self begin set packet = call APPUpdateMessage device_id=2 people=list set payload = string for hex_str in split string 95 string : begin set payload = payload + character integer hex_str 16 end set _payload = payload set people = call people assert not sitting assert not sitting assert sitting a...
def test_people_4(self): packet = APPUpdateMessage(device_id=2, people=[]) payload = "" for hex_str in "95".split(":"): payload += chr(int(hex_str, 16)) packet._payload = payload people = packet.people() assert not people[0].sitting assert not people[1...
Python
nomic_cornstack_python_v1
function list self roomId=none personId=none personEmail=none max=none **request_parameters begin string List room memberships. By default, lists memberships for rooms to which the authenticated user belongs. Use query parameters to filter the response. Use `roomId` to list memberships for a room, by ID. Use either `pe...
def list(self, roomId=None, personId=None, personEmail=None, max=None, **request_parameters): """List room memberships. By default, lists memberships for rooms to which the authenticated user belongs. Use query parameters to filter the response. Use `roomId` to li...
Python
jtatman_500k
comment -*- coding: utf-8 -*- string Created on Dec 25, 2014 @author: lisong 闭包 string def outer(): x = 1 def inner(): print x return inner foo = outer() foo() still working print foo.func_closure # doctest: +ELLIPSIS function outer x begin function inner begin print x end function return inner end function set print1 ...
# -*- coding: utf-8 -*- ''' Created on Dec 25, 2014 @author: lisong 闭包 ''' ''' def outer(): x = 1 def inner(): print x return inner foo = outer() foo() still working print foo.func_closure # doctest: +ELLIPSIS ''' def outer(x): def inner(): print(x) return inner print1 = oute...
Python
zaydzuhri_stack_edu_python
function has_duplicated_literal head body begin return length body != length set call get_literals end function
def has_duplicated_literal(head: Atom, body: Body) -> bool: return len(body) != len(set(body.get_literals()))
Python
nomic_cornstack_python_v1
function calculate_composition self nx=50 ny=50 begin set axr = xrange set ayr = yrange set gpleft = 0 for tuple ix ps in items sections begin set paxr = xrange set payr = yrange set grid = call GridData ps nx=round nx * paxr at 1 - paxr at 0 / axr at 1 - axr at 0 ny=round ny * payr at 1 - payr at 0 / ayr at 1 - ayr at...
def calculate_composition(self, nx=50, ny=50): axr = self.xrange ayr = self.yrange gpleft = 0 for ix, ps in self.sections.items(): paxr = ps.xrange payr = ps.yrange grid = GridData( ps, nx=round(nx * (paxr[1] - paxr[0]) ...
Python
nomic_cornstack_python_v1
function _queue_client_message self begin if connection_type == string database_request begin set client_message = call _create_client_message content_type=string db_request end else comment Without any content since it is a request if connection_type == string transaction_broadcast begin set client_message = call _cre...
def _queue_client_message(self): if self.connection_type == "database_request": client_message = FullNodeConnection._create_client_message( content_type="db_request") # Without any content since it is a request elif self.connection_type == "transaction_broadcast": ...
Python
nomic_cornstack_python_v1
from typing import List class Solution begin function nextGreatestLetter self letters target begin function binarySearch letters target begin set tuple left right = tuple 0 length letters - 1 while left <= right begin set mid = left + right // 2 if letters at mid >= target begin set left = mid + 1 end else begin set ri...
from typing import List class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: def binarySearch(letters,target): left,right=0,len(letters)-1 while left <= right: mid = (left+right)//2 if letters[mid] >= target: left = mid...
Python
zaydzuhri_stack_edu_python
import time import numpy as np from scipy.linalg import solve import matplotlib.pyplot as plt function mat v begin if v == string x begin set tuple A B C N = tuple Ax Bx Cx Nx end else if v == string y begin set tuple A B C N = tuple Ay By Cy Ny end else begin set tuple A B C N = tuple Az Bz Cz Nz end set M = zeros tup...
import time import numpy as np from scipy.linalg import solve import matplotlib.pyplot as plt def mat(v): if v=='x': (A,B,C,N)=(Ax,Bx,Cx,Nx) elif v=='y': (A,B,C,N)=(Ay,By,Cy,Ny) else: (A,B,C,N)=(Az,Bz,Cz,Nz) M=np.zeros((N-2,N),dtype=complex) for i in range(0,N-2): M[...
Python
zaydzuhri_stack_edu_python
function sieve n begin set arr = list false false + list true * n - 2 for i in range 2 integer square root n + 1 begin if arr at i begin for j in range 2 * i n i begin set arr at j = false end end end return generator expression i for i in range length arr if arr at i end function
def sieve(n): arr = [False, False] + [True] * (n - 2) for i in range(2, int(math.sqrt(n)) + 1): if arr[i]: for j in range(2 * i, n, i): arr[j] = False return (i for i in range(len(arr)) if arr[i])
Python
nomic_cornstack_python_v1
function verify self signature_input signature begin try begin decode _ECDSASignature signature return call verify signature signature_input hashfunc=sha256 sigdecode=sigdecode_der end except tuple UnexpectedDER ASN1Error as e begin raise call EncodingError string Invalid DER encoding for signature %s encode signature ...
def verify(self, signature_input, signature): try: _ECDSASignature.decode(signature) return self.__key.verify(signature, signature_input, hashfunc=hashlib.sha256, sigdecode=ecdsa.util.sigdecode_der) except ...
Python
nomic_cornstack_python_v1
function get_optimal_bst_fast p q begin assert p is not none assert q is not none assert length p == length q set n = length p - 1 assert n >= 0 set e = list comprehension list comprehension - 1 for _ in range 0 n + 1 for _ in range 0 n + 2 set w = list comprehension list comprehension - 1 for _ in range 0 n + 1 for _ ...
def get_optimal_bst_fast(p, q): assert p is not None assert q is not None assert len(p) == len(q) n = len(p) - 1 assert n >= 0 e = [[-1 for _ in range(0, n + 1)] for _ in range(0, n + 2)] w = [[-1 for _ in range(0, n + 1)] for _ in range(0, n + 2)] root = [[-1 for _ in range(0, n)] for...
Python
nomic_cornstack_python_v1
function test_laser_galilean show=false begin comment Choose the regular timestep (required by moving window) set dt = L_prop * 1.0 / c / N_diag comment Test modes up to m=2 for m in range 3 begin print string print string Testing mode m=%d % m call propagate_pulse Nz Nr m + 1 zmin zmax Lr L_prop zf dt N_diag w0 ctau k...
def test_laser_galilean(show=False): # Choose the regular timestep (required by moving window) dt = L_prop*1./c/N_diag # Test modes up to m=2 for m in range(3): print('') print('Testing mode m=%d' %m) propagate_pulse( Nz, Nr, m+1, zmin, zmax, Lr, L_prop, zf, dt, ...
Python
nomic_cornstack_python_v1
function float_to_fixed x nint nfrac begin set x_sat = call saturate x nint nfrac set x_fixed = integer round x * 2 ^ nfrac return x_fixed end function
def float_to_fixed(x, nint, nfrac): x_sat = saturate(x, nint, nfrac) x_fixed = int(round(x * (2 ** nfrac))) return x_fixed
Python
nomic_cornstack_python_v1
comment kNN import math import random import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D function abs num begin if num < 0 begin return num * - 1 end else begin return num end end function function distancia v1 v2 begin set tuple dim soma = tuple length v1 0 comment nao quer calcular o ultimo dado(...
#kNN import math import random import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def abs(num): if num<0: return num*(-1) else: return num def distancia(v1,v2): dim,soma = len(v1), 0 for i in range(dim-1):# nao quer calcular o ultimo dado(said...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sun Jan 20 15:06:20 2019 @author: shrikar.amirisetty string This file calculates the smallest multiple of all numbers between 1 and any input number set maxNumRange = integer input string Input a number: set smallestMultiple = 1 set multiplie...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 20 15:06:20 2019 @author: shrikar.amirisetty """ """ This file calculates the smallest multiple of all numbers between 1 and any input number """ maxNumRange = int(input("Input a number: ")) smallestMultiple = 1 multipliedNumbers = [1] for num in...
Python
zaydzuhri_stack_edu_python
function adjust_learning_rate_D_right optimizer epoch begin set lr = 1e-05 * 0.1 ^ epoch // 10 set log = string ** new learning rate: %f (for disright) % lr print log for param_group in param_groups begin set param_group at string lr = lr end end function
def adjust_learning_rate_D_right(optimizer, epoch): lr = 1e-5 * (0.1 ** (epoch // 10)) log = " ** new learning rate: %f (for disright)" % (lr) print(log) for param_group in optimizer.param_groups: param_group['lr'] = lr
Python
nomic_cornstack_python_v1
function rm_caso self btps caso begin set nombre = string %s:%s % tuple bpts caso try begin set test_dom = parse md test end except any begin set e = call _ string No se ha podido cargar el fichero de tests + test error e raise call ProyectoRecuperable e end set caso_dom = list comprehension f for f in call getElements...
def rm_caso(self, btps, caso): nombre = "%s:%s" % (bpts,caso) try: test_dom = md.parse(self.test) except: e = _("No se ha podido cargar el fichero de tests ") + self.test log.error(e) raise ProyectoRecuperable(e) caso_dom = [f for f in ...
Python
nomic_cornstack_python_v1
import sys import math import fractions from collections import defaultdict set stdin = stdin set ns = lambda -> right strip read line stdin set ni = lambda -> integer right strip read line stdin set nm = lambda -> map int split read line stdin set nl = lambda -> list map int split read line stdin set X = integer i...
import sys import math import fractions from collections import defaultdict stdin = sys.stdin ns = lambda: stdin.readline().rstrip() ni = lambda: int(stdin.readline().rstrip()) nm = lambda: map(int, stdin.readline().split()) nl = lambda: list(map(int, stdin.readline().split())) X=int(input()) ans=0 if(400<=X a...
Python
zaydzuhri_stack_edu_python
import re , webbrowser , sys class WindowsBot begin set negative_responses = list string no string don't string nope string bye string nothing string nada string nein string iiye set exit_commands = list string bye string goodbye string leave string stop string later string quit string pause string no string don't stri...
import re, webbrowser, sys class WindowsBot: negative_responses = ["no", "don't", "nope", "bye", "nothing", "nada", "nein", "iiye"] exit_commands = ["bye", "goodbye", "leave", "stop", "later", "quit", "pause", "no", "don't", "nope", "bye", "nothing", "nada", "nein", "iiye"] def __init__(self)...
Python
zaydzuhri_stack_edu_python
set person_data = dict string first_name string John ; string last_name string Doe ; string age 28
person_data = { "first_name": "John", "last_name": "Doe", "age": 28 }
Python
flytech_python_25k
comment -*- coding: utf-8 -*- string Created on Fri Oct 9 22:53:02 2020 @author: Kevin import cv2 set img = call imread string ecg1.png set crop_img = img at tuple slice 310 : 1170 : slice 65 : 1560 : call imwrite string cropped.jpg crop_img
# -*- coding: utf-8 -*- """ Created on Fri Oct 9 22:53:02 2020 @author: Kevin """ import cv2 img = cv2.imread("ecg1.png") crop_img = img[310:1170, 65:1560] cv2.imwrite('cropped.jpg', crop_img)
Python
zaydzuhri_stack_edu_python
class ListNode begin function __init__ self val=0 next=none begin set val = val set next = next end function end class function removeElements head X begin comment Step 1 set maxValue = decimal string -inf set curr = head while curr begin set maxValue = max maxValue val set curr = next end comment Step 3 if not head or...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def removeElements(head: ListNode, X: int) -> ListNode: # Step 1 maxValue = float('-inf') curr = head while curr: maxValue = max(maxValue, curr.val) curr = curr.next # Step...
Python
jtatman_500k
function test_valid_data self begin set url = reverse string api:obtain_token set request = post url dict string email string test@test.com set response = call call as_view request assert data == dict string Success string Token has been sent to your email. Use it to authenticate your API calls. comment noqa assert sta...
def test_valid_data(self): url = reverse("api:obtain_token") request = self.factory.post(url, {"email": "test@test.com"}) response = ObtainTokenView.as_view()(request) assert response.data == { "Success": "Token has been sent to your email. Use it to authenticate your AP...
Python
nomic_cornstack_python_v1
class PointKDTree begin class Node begin function __init__ self begin set left = none set right = none end function function print self begin pass end function function search self value begin pass end function end class class Leaf extends Node begin function __init__ self values begin call __init__ set values = values...
class PointKDTree: class Node: def __init__(self): self.left = None self.right = None def print(self): pass def search(self, value): pass class Leaf(Node): def __init__(self, values): super().__init__() se...
Python
zaydzuhri_stack_edu_python
import random from typing import Optional from torchvision import transforms from PIL import ImageFilter , ImageOps , Image class SSLTrainTransform extends object begin function __init__ self gaussian_blur_prob solarize_prob jitter_strength global_asymmetric_trans num_global_crops=2 global_input_size=224 global_scale=t...
import random from typing import Optional from torchvision import transforms from PIL import ImageFilter, ImageOps, Image class SSLTrainTransform(object): def __init__( self, # Augmentation options gaussian_blur_prob: float, solarize_prob: float, jitter_strength: float, ...
Python
zaydzuhri_stack_edu_python
for i in range length s begin append s_list s at i end set count = 0 set start = s_list at 0 for i in range 1 length s begin if start != s_list at i begin set start = s_list at i set count = count + 1 end end if count % 2 == 0 begin set count = count // 2 end else begin set count = count // 2 + 1 end comment 뭉테기 자체의 수 ...
for i in range(len(s)): s_list.append(s[i]) count = 0 start = s_list[0] for i in range(1, len(s)): if start != s_list[i]: start = s_list[i] count+=1 if count%2 == 0: count//=2 else: count=count//2+1 # 뭉테기 자체의 수 (000,111,00,11)를 구하면 홀짝나눌 필요 없음 count//=2 print(count)
Python
zaydzuhri_stack_edu_python
function get_kld_dist dfc begin set gnrs = list unique dfc at string tag set artsts = list unique dfc at string artist set trks = list unique dfc at string lfm_id set nbr_cls = 7 set acst_gnr_dict = call dict_gnrgs dfc gnrs pd set tuple sz_dict gnr_ind waet_dict vol_dict = call gnrt_sup_dicts acst_gnr_dict gnrs set acs...
def get_kld_dist(dfc): gnrs = list(np.unique(dfc['tag'])) artsts = list(np.unique(dfc['artist'])) trks = list(np.unique(dfc['lfm_id'])) nbr_cls = 7 acst_gnr_dict = dict_gnrgs(dfc, gnrs, pd) sz_dict, gnr_ind, waet_dict, vol_dict = gnrt_sup_dicts(acst_gnr_dict, gnrs) acst_mat = krnl_acst_mp...
Python
nomic_cornstack_python_v1
function convert_celsius celsius begin comment Convert celsius to Fahrenheit set fahrenheit = celsius * 9 / 5 + 32 comment Return fahrenheit value return fahrenheit end function comment Test set celsius = 32 print call convert_celsius celsius
def convert_celsius(celsius): # Convert celsius to Fahrenheit fahrenheit = celsius * 9/5 + 32 # Return fahrenheit value return fahrenheit # Test celsius = 32 print(convert_celsius(celsius))
Python
jtatman_500k