code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import re set string = string There are 45.8 apples and 12.3 oranges. set numbers = find all string [-+]?\d*\.\d+|\d+ string print numbers comment Output: ['45.8', '12.3']
import re string = "There are 45.8 apples and 12.3 oranges." numbers = re.findall(r"[-+]?\d*\.\d+|\d+", string) print(numbers) # Output: ['45.8', '12.3']
Python
iamtarun_python_18k_alpaca
import unittest from state import State from dummy import DummySensor class TestState extends TestCase begin function setUp self begin set temp_sensor = call DummySensor list 37 38 39 set hr_sensor = call DummySensor list 100 110 90 set all_sensors = dict string temp temp_sensor ; string heartrate hr_sensor end functio...
import unittest from state import State from dummy import DummySensor class TestState(unittest.TestCase): def setUp(self): self.temp_sensor = DummySensor([37, 38, 39]) self.hr_sensor = DummySensor([100, 110, 90]) self.all_sensors = {'temp': self.temp_sensor, 'he...
Python
zaydzuhri_stack_edu_python
function _add_services self begin set this_service = dict string name string {{ metadata.package }} set other_services = list dict string name string mysql ; string location string cs:percona-cluster ; string constraints dict string mem string 3072M dict string name string rabbitmq-server dict string name string keysto...
def _add_services(self): this_service = {'name': '{{ metadata.package }}'} other_services = [ {'name': 'mysql', 'location': 'cs:percona-cluster', 'constraints': {'mem': '3072M'}}, {'name': 'rabbitmq-server'}, {'name': 'keystone'}, ...
Python
nomic_cornstack_python_v1
comment import point class DiscState begin string Gamestate info: whether it is flippable and valid to be dropped, how many discs of each color on the board, when and who wins function __init__ self turn wonMode board_row board_col begin set turn = turn set _wonMode = wonMode set _row = board_row set _col = board_col s...
##import point class DiscState: ''' Gamestate info: whether it is flippable and valid to be dropped, how many discs of each color on the board, when and who wins ''' def __init__(self, turn:str,wonMode:str,board_row:int,board_col:int): self.turn=turn self._wonMod...
Python
zaydzuhri_stack_edu_python
string input = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 import sys set num_tests = integer read line stdin for i in range num_tests begin set matrixA = list set matrixB = list for i in range 3 begin set rows = split read line stdin set row_list = list comprehension integer i for i in rows append matrixA row_list end for...
"""input = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1""" import sys num_tests = int(sys.stdin.readline()) for i in range(num_tests): matrixA = [] matrixB = [] for i in range(3): rows = sys.stdin.readline().split() row_list = [int(i) for i in rows] matrixA.append(row_list) fo...
Python
zaydzuhri_stack_edu_python
function test_tournaments_id_get self begin set headers = dict string Accept string application/json set response = open format string /v0.0.1/tournaments/{id} id=string id_example method=string GET headers=headers call assert200 response string Response body is : + decode data string utf-8 end function
def test_tournaments_id_get(self): headers = { 'Accept': 'application/json', } response = self.client.open( '/v0.0.1/tournaments/{id}'.format(id='id_example'), method='GET', headers=headers) self.assert200(response, ...
Python
nomic_cornstack_python_v1
function to_datetime string begin return string parse time string ISO8601 end function
def to_datetime(string): return datetime.strptime(string, ISO8601)
Python
nomic_cornstack_python_v1
function assign self value begin comment api Quaternion assign accepts Matrix, Quaternion and EulerRotation if is instance value Matrix begin set value = rotate end else begin if not has attribute value string __iter__ begin set value = tuple value end set value = call apicls *value end call assign self value return se...
def assign(self, value): # api Quaternion assign accepts Matrix, Quaternion and EulerRotation if isinstance(value, Matrix): value = value.rotate else: if not hasattr(value, '__iter__'): value = (value,) value = self.apicls(*value) self....
Python
nomic_cornstack_python_v1
function fix_unicode_quotes text begin set text = sub string [“”] string " text M ? I set text = sub string [‘’'] string ' text M ? I return sub string [—] string - text M ? I end function
def fix_unicode_quotes(text): text = re.sub(u'[\u201c\u201d]', '"', text, re.M | re.I) text = re.sub(u'[\u2018\u2019\u0027]', "'", text, re.M | re.I) return re.sub(u'[\u2014]', "-", text, re.M | re.I)
Python
nomic_cornstack_python_v1
function _category self begin string Type of the image: LOLA or WAC Note: Specify the attribute ``grid``, ``img`` and ``lbl` if split fname string _ at 0 == string WAC begin set grid = string WAC set img = join path wacpath fname + string .IMG set lbl = string end else if split fname string _ at 0 == string LDEM begin...
def _category(self): """ Type of the image: LOLA or WAC Note: Specify the attribute ``grid``, ``img`` and ``lbl` """ if self.fname.split('_')[0] == 'WAC': self.grid = 'WAC' self.img = os.path.join(self.wacpath, self.fname + '.IMG') self.lbl = '' ...
Python
jtatman_500k
from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup import requests import csv from pyvirtualdisplay import Display import time set url = string http://www.mapcoordinates.net/en set driver = call Firefox get driver url set elem = call find_elements_by_css_selecto...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup import requests import csv from pyvirtualdisplay import Display import time url = "http://www.mapcoordinates.net/en" driver = webdriver.Firefox() driver.get(url) elem = driver.find_elements_by_css_selector("*...
Python
zaydzuhri_stack_edu_python
comment layer = iface.addVectorLayer("F:/backup from laptop/data/india-latest.shp_3/places.shp", "India_places", "ogr") call setDestinationCrs call QgsCoordinateReferenceSystem 4269 set layer1 = call activeLayer set layer2 = call activeLayer import processing set features1 = call features layer1 set features2 = call fe...
#layer = iface.addVectorLayer("F:/backup from laptop/data/india-latest.shp_3/places.shp", "India_places", "ogr") iface.mapCanvas().mapRenderer().setDestinationCrs(QgsCoordinateReferenceSystem(4269 )) layer1 = iface.activeLayer() layer2 = iface.activeLayer() import processing features1 = processing.features(layer1) fea...
Python
zaydzuhri_stack_edu_python
class Solution begin function replaceElements self arr begin set prev_max = - 1 for i in range length arr - 1 - 1 - 1 begin if arr at i > prev_max begin set new_max = arr at i end else begin set new_max = prev_max end set arr at i = prev_max set prev_max = new_max end comment print(arr) comment print("final array", arr...
class Solution: def replaceElements(self, arr): prev_max = -1 for i in range(len(arr)-1, -1, -1): if arr[i] > prev_max: new_max = arr[i] else: new_max = prev_max arr[i] = prev_max prev_max = new_max # print(a...
Python
zaydzuhri_stack_edu_python
string Module containing the Resource class. from enum import Enum class Resource extends Enum begin string A resource is something that is transported between factories. set BLUE = 1 set RED = 2 end class
"""Module containing the Resource class.""" from enum import Enum class Resource(Enum): """A resource is something that is transported between factories.""" BLUE = 1 RED = 2
Python
zaydzuhri_stack_edu_python
function find_histogram clt begin set numLabels = array range 0 length unique labels_ + 1 set tuple hist _ = call histogram labels_ bins=numLabels set hist = as type hist string float set hist = hist / sum return hist end function
def find_histogram(clt): numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) (hist, _) = np.histogram(clt.labels_, bins=numLabels) hist = hist.astype("float") hist /= hist.sum() return hist
Python
nomic_cornstack_python_v1
comment tcp_emitter.py import socket import time set port = 8080 set sock = call socket AF_INET SOCK_STREAM set alarmFire = string msg(alarm,event,python,none,alarm(firetcp),1) set alarmTsunami = string msg(alarm,event,python,none,alarm(tsunamitcp),2) set onPressed = string msg(onPressed,event,python,none,onPressed(pyt...
############################################################## # tcp_emitter.py ############################################################## import socket import time port = 8080 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) alarmFire = "msg(alarm,event,python,none,alarm(firetcp),1)" alarmTsunami = ...
Python
zaydzuhri_stack_edu_python
import os from typing import List from collections import namedtuple set BASE_DIR = directory name path __file__ set TREE_CHAR = string # set Position = named tuple string Position string x, y set MapPoint = named tuple string MapPoint string value, x, y class FoldedMap extends object begin function __init__ self raw_m...
import os from typing import List from collections import namedtuple BASE_DIR = os.path.dirname(__file__) TREE_CHAR = "#" Position = namedtuple("Position", "x, y") MapPoint = namedtuple("MapPoint", "value, x, y") class FoldedMap(object): def __init__(self, raw_map: List[str]): self.raw_map = raw_map ...
Python
zaydzuhri_stack_edu_python
comment Link: https://leetcode.com/problems/count-square-submatrices-with-all-ones/ comment Approach: Basically, we initially add all ones. Now, for each cell matrix[i][j] which equals one, we do matrix[i][j] = matrix[i][j] + min(left_val, upper_val, upper_left_val). Why this is so because comment we see that the curre...
# Link: https://leetcode.com/problems/count-square-submatrices-with-all-ones/ # Approach: Basically, we initially add all ones. Now, for each cell matrix[i][j] which equals one, we do matrix[i][j] = matrix[i][j] + min(left_val, upper_val, upper_left_val). Why this is so because # we see that the current square will fo...
Python
zaydzuhri_stack_edu_python
function random_img spec begin comment Get a list of matching images, full path set matches = glob glob spec print string Found length matches string images if not length matches begin exit string No files found matching + spec end comment Pick a random image from the list set random_image = random choice matches print...
def random_img(spec): # Get a list of matching images, full path matches = glob.glob(spec) print("Found", len(matches), "images") if not len(matches): sys.exit("No files found matching " + spec) # Pick a random image from the list random_image = random.choice(matches) print("Random...
Python
nomic_cornstack_python_v1
function Step5 self begin set clustering_results = call CL config call get_distance_metric call generate_clusters end function
def Step5(self): self.clustering_results = CL(self.config, self.matric.get_distance_metric()) self.clustering_results.generate_clusters()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment @Time :2018/12/6 20:27 string ddt data drive study 数据驱动测试 string 1、结合我们的单元测试区执行用例 string 2、装饰器 string 3、安装pip install ddt comment def print_msg(*args):#动态参数 comment print(args) #*args 到了函数内部,就会变成一个元组 comment print('参数的个数:',len(args)) comment print_msg(1,...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time :2018/12/6 20:27 '''ddt data drive study 数据驱动测试''' '''1、结合我们的单元测试区执行用例''' '''2、装饰器''' '''3、安装pip install ddt''' # def print_msg(*args):#动态参数 # print(args) #*args 到了函数内部,就会变成一个元组 # print('参数的个数:',len(args)) # print_msg(1,2,3,4,5,'hello') #函数调用 打印出一个元组...
Python
zaydzuhri_stack_edu_python
function get_id_categorie self categorie_name begin set s = format string SELECT id FROM {entete}course_categories WHERE name = %(categorie_name)s entete=entete execute mark s params=dict string categorie_name categorie_name set ligne = call safe_fetchone return if expression ligne then ligne at 0 else none end functio...
def get_id_categorie(self, categorie_name): s = "SELECT id" \ " FROM {entete}course_categories" \ " WHERE name = %(categorie_name)s" \ .format(entete=self.entete) self.mark.execute(s, params={'categorie_name': categorie_name}) ligne = self.safe_fetchone() ...
Python
nomic_cornstack_python_v1
if user_movie in movies_Watched begin print string I have watched { user_movie } too. end else begin print string I haven't watched it yet. end set number = 7 set user_input = input string Enter 'y' if you would like to play: if user_input in tuple string y string Y begin set user_number = integer input string Guess ou...
if user_movie in movies_Watched: print(f"I have watched {user_movie} too.") else: print(f"I haven't watched it yet.") number = 7 user_input = input("Enter 'y' if you would like to play: ") if user_input in ("y", "Y"): user_number = int(input("Guess our number: ")) if user_number == number: pri...
Python
zaydzuhri_stack_edu_python
function schedule self url begin debug format string scheduling fetch of {} url put url end function
def schedule(self, url): log.debug("scheduling fetch of {}".format(url)) self.request.put(url)
Python
nomic_cornstack_python_v1
function csv_download begin return call process_csv param end function
def csv_download(): return process_csv(param)
Python
nomic_cornstack_python_v1
function example begin string this is also a type of multi line comment by this example we are now cleared what single and mutiple line comment is. return 1 end function
def example(): ''' this is also a type of multi line comment by this example we are now cleared what single and mutiple line comment is. ''' return 1
Python
nomic_cornstack_python_v1
function fmgf array sigma begin set tuple x y = tuple array range length array copy array set yg = call gaussian_filter y sigma set y = y - yg comment digitizing set m = 101 set dy = 6.0 * call mad y / m set ybin = array range min y - 5 * dy max y + 5 * dy + dy dy set z = zeros list length ybin length x set z at tuple ...
def fmgf(array, sigma): x, y = np.arange(len(array)), array.copy() yg = ndimage.filters.gaussian_filter(y, sigma) y -= yg # digitizing m = 101 dy = 6.0 * mad(y) / m ybin = np.arange(np.min(y) - 5 * dy, np.max(y) + 5 * dy + dy, dy) z = np.zeros([len(ybin), len(x)]) z[np.digitize(y, y...
Python
nomic_cornstack_python_v1
function nr_deepcopy_tree t begin return transform call Transformer_NonRecursive false t end function
def nr_deepcopy_tree(t): return Transformer_NonRecursive(False).transform(t)
Python
nomic_cornstack_python_v1
comment Keep Coding And change the world and do not forget anything... Not Again.. from collections import defaultdict from DynamicThresh import dynamic_threshing from ConnectedComponents import connected_components from BoundingRect import bounding_rect from Classifiy import Classifier import cv2 import argparse funct...
# Keep Coding And change the world and do not forget anything... Not Again.. from collections import defaultdict from DynamicThresh import dynamic_threshing from ConnectedComponents import connected_components from BoundingRect import bounding_rect from Classifiy import Classifier import cv2 import argparse def detec...
Python
zaydzuhri_stack_edu_python
function render_caddyfile hostname basedirectory begin set jinja_env = call Environment loader=call FileSystemLoader string . set template = call get_template name=string ./Caddyfile.j2 set result = call render hostname=hostname basedir=basedirectory with open string Caddyfile string w as file begin write file result e...
def render_caddyfile(hostname, basedirectory): jinja_env = Environment(loader=FileSystemLoader('.')) template = jinja_env.get_template(name = "./Caddyfile.j2") result = template.render(hostname = hostname, basedir = basedirectory) with open("Caddyfile", "w") as file: file.write(result)
Python
nomic_cornstack_python_v1
function test_cms_plugins_glimpse_context_and_html self begin set placeholder = call create slot=string test comment Create random values for parameters with a factory set glimpse = call GlimpseFactory set model_instance = call add_plugin placeholder GlimpsePlugin string en title=title set plugin_instance = call get_pl...
def test_cms_plugins_glimpse_context_and_html(self): placeholder = Placeholder.objects.create(slot="test") # Create random values for parameters with a factory glimpse = GlimpseFactory() model_instance = add_plugin( placeholder, GlimpsePlugin, "en", title=glimpse.title ...
Python
nomic_cornstack_python_v1
comment Ordena uma lista de forma crescente sort lista sort lista_animais print lista print lista_animais comment Ordena uma lista de forma descrecente reverse lista print lista comment criando uma tupla, os valores inseridos nao podem ser mudados set tupla = tuple 1 3 6 8 comment retornar quantos elementos tem na tupl...
# Ordena uma lista de forma crescente lista.sort() lista_animais.sort() print(lista) print(lista_animais) # Ordena uma lista de forma descrecente lista.reverse() print(lista) # criando uma tupla, os valores inseridos nao podem ser mudados tupla = (1, 3, 6, 8) # retornar quantos elementos tem na tupla ou lista print(...
Python
zaydzuhri_stack_edu_python
function persist_fields_during_stim event begin return list end function
def persist_fields_during_stim(event): return []
Python
nomic_cornstack_python_v1
from functools import reduce function get_int prompt begin while true begin try begin return integer input prompt end except ValueError begin print string Please enter a valid number! end end end function function get_nums begin while true begin set n = call get_int string Enter a whole number(0 to break): if n <= 0 be...
from functools import reduce def get_int(prompt): while True: try: return int(input(prompt)) except ValueError: print("Please enter a valid number!") def get_nums(): while True: n = get_int('Enter a whole number(0 to break): ') if n <= 0: break ...
Python
zaydzuhri_stack_edu_python
comment define functions without a parameter function calcWages begin set hourlyRate = 105 set numberOfHours = 16 return hourlyRate * numberOfHours end function comment execute function call calcWages comment define functions with parameters function calcWages numberOfHours hourlyRate begin return hourlyRate * numberOf...
# define functions without a parameter def calcWages(): hourlyRate= 105 numberOfHours = 16 return hourlyRate * numberOfHours # execute function calcWages() # define functions with parameters def calcWages(numberOfHours, hourlyRate): return hourlyRate * numberOfHours # execute function calcWages(20, 85)...
Python
zaydzuhri_stack_edu_python
function setup begin set config = call get_user_config set flow = call getOauthFlow set oauth_url = call step1_get_authorize_url set oauth_resources_dict = call _get_oauth_configration_resources_dict config oauth_url if method == string GET begin return call render_template string setup.html oauth_url=oauth_url oauth_c...
def setup(): config = ufo.get_user_config() flow = oauth.getOauthFlow() oauth_url = flow.step1_get_authorize_url() oauth_resources_dict = _get_oauth_configration_resources_dict(config, oauth_url) if flask.request.method == 'GET': return fl...
Python
nomic_cornstack_python_v1
function cascade_adding self begin call add_cascade label=string File menu=filemenu call add_cascade label=string Operations menu=actionmenu end function
def cascade_adding(self): self.rootbar.add_cascade(label="File", menu=self.filemenu) self.rootbar.add_cascade(label="Operations", menu=self.actionmenu)
Python
nomic_cornstack_python_v1
function readAllDatForCurrency data_dir currencyCode begin set datatestnames = list filter lambda a -> currencyCode in a list directory data_dir set dfs = list comprehension call readDAT data_dir + name for name in datatestnames set allDf = concat dfs set allDf = set index reset index sort values allDf by=list string d...
def readAllDatForCurrency(data_dir, currencyCode): datatestnames = list(filter(lambda a : (currencyCode in a), listdir(data_dir))) dfs = [readDAT(data_dir + name) for name in datatestnames] allDf = pd.concat(dfs) allDf = allDf.sort_values(by=['datetime'], ascending=True).reset_index(drop=True).set_index...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment encoding: utf-8 string @Time : 2019/11/30 20:03 @File : example_MB.py from CBD.MBs.MBOR import MBtoPC from CBD.MBs.pc_simple import pc_simple from CBD.MBs.MMMB.MMPC import MMPC from CBD.MBs.PCMB.getPC import getPC from CBD.MBs.HITON.HITON_PC import HITON_PC from CBD.MBs.semi_HITON.s...
#!/usr/bin/env python # encoding: utf-8 """ @Time : 2019/11/30 20:03 @File : example_MB.py """ from CBD.MBs.MBOR import MBtoPC from CBD.MBs.pc_simple import pc_simple from CBD.MBs.MMMB.MMPC import MMPC from CBD.MBs.PCMB.getPC import getPC from CBD.MBs.HITON.HITON_PC import HITON_PC from CBD.MBs.semi_HITON.sem...
Python
zaydzuhri_stack_edu_python
function add self state action reward next_state done begin set e = call experience state action reward next_state done append memory e end function
def add(self, state, action, reward, next_state, done): e = self.experience(state, action, reward, next_state, done) self.memory.append(e)
Python
nomic_cornstack_python_v1
function vector_sum vectors begin assert vectors msg string no vectors provided set num_elements = length vectors at 0 assert all generator expression length v == num_elements for v in vectors msg string vectors must be the same length return list comprehension sum generator expression vec at i for vec in vectors for i...
def vector_sum(vectors: List[Vector]) -> Vector: assert vectors, 'no vectors provided' num_elements = len(vectors[0]) assert all( len(v) == num_elements for v in vectors), 'vectors must be the same length' return [sum(vec[i] for vec in vectors) for i in range(num_elements)]
Python
nomic_cornstack_python_v1
function format_occupation P ls begin set occup_list = list string degauss string smearing set ls_in = list comprehension file for file in ls if string .in in file and string test_ not in file for file in ls_in begin set occup = call find_ctrl_l file string occupations one=true if occup == string 'smearing' begin list ...
def format_occupation(P, ls): occup_list = ["degauss", "smearing"] ls_in = [file for file in ls if ".in" in file and "test_" not in file] for file in ls_in: occup = P.find_ctrl_l(file, "occupations", one=True) if occup == "'smearing'": [P.force_uncomment_l(file, r"{}\s*=".format(suboption)) for suboption in o...
Python
nomic_cornstack_python_v1
from django.test import TestCase from main.forms import AccordionForm from main.models import Accordion comment Realiza pruebas a la vista encargada de editar los acordeones de un usuario class TestAcordeonEdit extends TestCase begin function setUp self begin set acordeon_mdl = call create title=string titulo2 title_st...
from django.test import TestCase from main.forms import AccordionForm from main.models import Accordion # Realiza pruebas a la vista encargada de editar los acordeones de un usuario class TestAcordeonEdit(TestCase): def setUp(self): self.acordeon_mdl = Accordion.objects.create( title="titulo2...
Python
zaydzuhri_stack_edu_python
function scan2d_from_nxs_01_copy path_to_i07_nxs_01 begin return call i07_nxs_parser path_to_i07_nxs_01 end function
def scan2d_from_nxs_01_copy(path_to_i07_nxs_01): return i07_nxs_parser(path_to_i07_nxs_01)
Python
nomic_cornstack_python_v1
comment 写一个配置类 有以下几个函数: comment 1:读取整数 comment 2:读取浮点数 comment 3:读取布尔值 comment 4:读取其他类型的数据 list tuple dict eval() comment 5:读取字符串 from configparser import ConfigParser from 接口自动化.API_2.common import project_path class ReadConfig begin function __init__ self file_name begin set cf = config parser read cf file_name encod...
#写一个配置类 有以下几个函数: #1:读取整数 #2:读取浮点数 #3:读取布尔值 #4:读取其他类型的数据 list tuple dict eval() #5:读取字符串 from configparser import ConfigParser from 接口自动化.API_2.common import project_path class ReadConfig: def __init__(self,file_name): self.cf=ConfigParser() self.cf.read(file_name,encoding='utf-8') def get_int(s...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment Helpers for working with views & static files import jinja2 import os set JINJA_ENVIRONMENT = call Environment loader=call FileSystemLoader absolute path path string ./views comment Render template using data function render template_file template_data=dict begin set template = cal...
# -*- coding: utf-8 -*- # # Helpers for working with views & static files # import jinja2 import os JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.abspath('./views'))) # Render template using data def render(template_file, template_data={}, ): template = JINJA_ENVIRONMENT.get_templa...
Python
zaydzuhri_stack_edu_python
function union A B begin set S = list set S = S + A for i in B begin if i not in S begin append S i end end return sorted S end function set A = list 1 2 3 set B = list 3 5 4 print union A B string From the above code we can assume A and B as a sequence and union as a function A and B are processed where S is empty in...
def union(A, B): S = [] S += A for i in B: if i not in S: S.append(i) return sorted(S) A = [1,2,3] B = [3,5,4] print(union(A, B)) ''' From the above code we can assume A and B as a sequence and union as a function A and B are processed where S is empty initially ...
Python
zaydzuhri_stack_edu_python
comment three parallel vertical lines comment their points share the y values call line tuple 20 10 tuple 20 90 call line tuple 50 10 tuple 50 90 call line tuple 80 10 tuple 80 90
# three parallel vertical lines # their points share the y values line((20, 10), (20, 90)) line((50, 10), (50, 90)) line((80, 10), (80, 90))
Python
zaydzuhri_stack_edu_python
function calculate_sum a b begin return b * b + 1 // 2 - a - 1 * a // 2 end function set sum = call calculate_sum 1 10 print sum
def calculate_sum(a,b): return (b*(b+1))//2 - ((a-1)*a)//2 sum = calculate_sum(1, 10) print(sum)
Python
jtatman_500k
function add self layer begin if length layers == 0 begin if input_shape is none begin raise exception string The input shape for the first layer of the model must be specified end end else begin set input_shape = output_shape end call build append layers layer end function
def add(self, layer): if len(self.layers) == 0: if layer.input_shape is None: raise Exception("The input shape for the first layer of the model must be " "specified") else: layer.input_shape = self.layers[-1].output_shape la...
Python
nomic_cornstack_python_v1
class Person begin function __init__ self first_name last_name begin set first_name = first_name set last_name = last_name end function function getDetails self begin return dict string first_name first_name ; string last_name last_name end function end class class Student extends Person begin function __init__ self fi...
class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def getDetails(self): return { "first_name": self.first_name, "last_name": self.last_name } class Student(Person): def __init__(self,...
Python
zaydzuhri_stack_edu_python
function test_typedef self begin call build set main_source_file = call SBFileSpec string main.cpp call run_to_source_breakpoint self string Set a breakpoint here call SBFileSpec string main.cpp comment First of all, check that we can get a typedefed type correctly in a simple case. set expr_result = call expect_expr s...
def test_typedef(self): self.build() self.main_source_file = lldb.SBFileSpec("main.cpp") lldbutil.run_to_source_breakpoint( self, "Set a breakpoint here", lldb.SBFileSpec("main.cpp") ) # First of all, check that we can get a typedefed type correctly in a simple case...
Python
nomic_cornstack_python_v1
import unittest from employees import Employee class EmployeeTestCase extends TestCase begin function setUp self begin set teng = call Employee string Teng string Yao Long 50000000 end function function test_give_default_raise self begin call give_raise assert equal annual_salary 50005000 end function function test_giv...
import unittest from employees import Employee class EmployeeTestCase(unittest.TestCase): def setUp(self): self.teng = Employee('Teng', 'Yao Long', 50000000) def test_give_default_raise(self): self.teng.give_raise() self.assertEqual(self.teng.annual_salary, 50005000) def test_give_custom_raise(self): ...
Python
zaydzuhri_stack_edu_python
for i in range N begin set dp at i at 0 = nums2 at i for j in range i - 1 - 1 - 1 begin for k in range 2 begin if dp at j at k != 99999999999 and nums at j < nums at i begin set dp at i at k + 1 = min dp at i at k + 1 dp at j at k + nums2 at i end end end end set ans = 99999999999 for i in range N begin set ans = min d...
for i in range(N): dp[i][0] = nums2[i] for j in range(i-1,-1,-1): for k in range(2): if dp[j][k] != 99999999999 and nums[j] < nums[i]: dp[i][k+1] = min(dp[i][k+1],dp[j][k]+nums2[i]) ans = 99999999999 for i in range(N): ans = min(dp[i][2],ans) if ans==99999999999: print -1
Python
zaydzuhri_stack_edu_python
comment print the length of string print length string
# print the length of string print(len(string))
Python
jtatman_500k
import pandas as pd set df at string new_col = sum axis=1 import pandas as pd import numpy as np set df at string new_col = where is null df at string A ? is null df at string B nan df at string A + df at string B import pandas as pd import numpy as np set df at string new_col = where is null df at string A ? is null d...
import pandas as pd df['new_col'] = df[['A', 'B']].sum(axis=1) import pandas as pd import numpy as np df['new_col'] = np.where((df['A'].isnull()) | (df['B'].isnull()), np.nan, df['A'] + df['B']) import pandas as pd import numpy as np df['new_col'] = np.where((df['A'].isnull()) | (df['B'].isnull()), np.nan, ...
Python
jtatman_500k
function load_e3d_par fp comment_chars=tuple string # begin set vals = dict with open fp as e3d begin for line in e3d begin if left strip line at 0 in comment_chars begin pass end set tuple key value = split line string = if key in vals begin raise call KeyError string Key { key } is in the emod3d parameter file at le...
def load_e3d_par(fp: str, comment_chars=("#",)): vals = {} with open(fp) as e3d: for line in e3d: if line.lstrip()[0] in comment_chars: pass key, value = line.split("=") if key in vals: raise KeyError( f"Key {key} is...
Python
nomic_cornstack_python_v1
function pokolenia tab begin set osoby = list set list comprehension tab at i at j for i in range length tab for j in range 2 set glowa = string for os in osoby begin for i in tab begin set udalosie = true if i at 1 == os begin set udalosie = false break end end if udalosie begin set glowa = os end end set rodzina = l...
def pokolenia(tab): osoby = list(set([tab[i][j] for i in range(len(tab)) for j in range(2)])) glowa = '' for os in osoby: for i in tab: udalosie = True if i[1] == os: udalosie = False break if udalosie: glowa = os rodz...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python from os import popen import sys class bcolors begin set HEADER = string  set OKBLUE = string  set OKGREEN = string  set WARNING = string  set FAIL = string  set ENDC = string  set BOLD = string  set UNDERLINE = string  end class set error = 0 if length argv ...
#!/usr/bin/python from os import popen import sys class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' error = 0 if (len(sys...
Python
zaydzuhri_stack_edu_python
function fibonacci n begin comment Base case: first two terms of the Fibonacci sequence if n == 0 begin return 0 end else if n == 1 begin return 1 end comment Recursive case: calculate the nth term by summing the previous two terms return call fibonacci n - 1 + call fibonacci n - 2 end function set n = 6 set fib_term =...
def fibonacci(n): # Base case: first two terms of the Fibonacci sequence if n == 0: return 0 elif n == 1: return 1 # Recursive case: calculate the nth term by summing the previous two terms return fibonacci(n - 1) + fibonacci(n - 2) n = 6 fib_term = fibonacci(n) print("The", n, "t...
Python
greatdarklord_python_dataset
import requests from bs4 import BeautifulSoup set base_url = string https://www.example.com set r = get requests base_url set soup = call BeautifulSoup content string html.parser set all_links = find all soup string a href=true for link in all_links begin set page_url = base_url + link at string href set page_response ...
import requests from bs4 import BeautifulSoup base_url = 'https://www.example.com' r = requests.get(base_url) soup = BeautifulSoup(r.content, 'html.parser') all_links = soup.find_all('a', href=True) for link in all_links: page_url = base_url + link['href'] page_response = requests.get(page_url) page_content = Be...
Python
jtatman_500k
import spacy from spacy.lang.en import English from spacy.matcher import Matcher call prefer_gpu function print_doc_analysis doc begin for token in doc begin print format string Index: {} | is_alpha {} | is_punct {} | like_num {} | is_title {} | POS {} | Text: {} i is_alpha is_punct like_num is_title pos_ text end end ...
import spacy from spacy.lang.en import English from spacy.matcher import Matcher spacy.prefer_gpu() def print_doc_analysis(doc): for token in doc: print ("Index: {} | is_alpha {} | is_punct {} | like_num {} | is_title {} | POS {} | Text: {}".format( token.i, token.is_alpha, token.is_punct, t...
Python
zaydzuhri_stack_edu_python
from typing import List , Dict class HelpQueueEntry begin string A simple class to represent one entry in the help queue function __init__ self name number course=string begin string Create this new HelpQueueEntry representing a student name, the queue position number, and an optional course. @param self : this help qu...
from typing import List, Dict class HelpQueueEntry: """ A simple class to represent one entry in the help queue """ def __init__ (self, name: str, number: int, course=''): """ Create this new HelpQueueEntry representing a student name, the queue position number, and an optional course. ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 import os import ConfigParser class Language begin function __init__ self langCode langName d begin set code = langCode set name = langName set dict = d end function function __getitem__ self item begin return dict at item end function end class class TDatabase begin f...
#!/usr/bin/env python #coding: utf-8 import os import ConfigParser class Language: def __init__(self, langCode, langName, d): self.code = langCode self.name = langName self.dict = d def __getitem__(self, item): return self.dict[item] class TDatabase: def __init__(self): self.d = {} self.langAv...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 set matrix_divided = matrix_divided set matrix = list list 0 2 7 list 8 5 6 print call matrix_divided matrix 3 print matrix
#!/usr/bin/python3 matrix_divided = __import__('2-matrix_divided').matrix_divided matrix = [ [0, 2, 7], [8, 5, 6] ] print(matrix_divided(matrix, 3)) print(matrix)
Python
zaydzuhri_stack_edu_python
comment importing the multiprocessing module import multiprocessing from time import sleep import pygame import msvcrt function ode_to_joy begin comment tempo of the piece, lower numbers are faster set speed = 0.04 set odesong = list list string e 1 list string e 1 list string f 1 list string g 1 list string g 1 list s...
# importing the multiprocessing module import multiprocessing from time import sleep import pygame import msvcrt def ode_to_joy(): speed = 0.04 # tempo of the piece, lower numbers are faster odesong = [['e', 1], ['e', 1], ['f', 1], ['g', 1], ['g', 1], ['f', 1], [ 'e', 1 ], ['d', 1], ['c', 1], ...
Python
zaydzuhri_stack_edu_python
comment advent of code day 11. This was @ASpittel solution which comment iteratively checks all combinations for each seat until comment either a seat which is empty or filled is found or there are no valid seats comment check if the seats are still within the boundary (i.e. the indices aren't too high or too low) func...
# advent of code day 11. This was @ASpittel solution which # iteratively checks all combinations for each seat until # either a seat which is empty or filled is found or there are no valid seats # check if the seats are still within the boundary (i.e. the indices aren't too high or too low) def check_valid_seat(se...
Python
zaydzuhri_stack_edu_python
import numpy as np import csv import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec function make_figure filename fig x y begin set my_data = call genfromtxt filename delimiter=string , comment it's a fake first row to make sure that the shading starts at 0, otherwise the shading looks poor set my_data...
import numpy as np import csv import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec def make_figure(filename, fig, x, y): my_data = np.genfromtxt(filename, delimiter=',') my_data[0,:] = np.array((0, 0, 0, 0, 0, 0, 0)) # it's a fake first row to make sure that the shading starts at 0, otherwise ...
Python
zaydzuhri_stack_edu_python
function get_config self dgroup=none begin if dgroup is none begin set dgroup = call get_group end set conf = get attribute dgroup string prepeak_config dict if string e0 not in conf begin set conf = dictionary e0=e0 elo=- 10 ehi=- 5 emin=- 40 emax=0 yarray=string norm end set prepeak_config = conf if not has attribute...
def get_config(self, dgroup=None): if dgroup is None: dgroup = self.controller.get_group() conf = getattr(dgroup, 'prepeak_config', {}) if 'e0' not in conf: conf = dict(e0 = dgroup.e0, elo=-10, ehi=-5, emin=-40, emax=0, yarray='norm') dgr...
Python
nomic_cornstack_python_v1
function check_type_long delivery_data begin set index_from = delivery_data at string индекс отправителя set index_to = delivery_data at string индекс получателя try begin set coord_from = index2coord at string index_from at slice : : - 1 set coord_to = index2coord at string index_to at slice : : - 1 set dist = km ...
def check_type_long(delivery_data): index_from = delivery_data["индекс отправителя"] index_to = delivery_data["индекс получателя"] try: coord_from = index2coord[str(index_from)][::-1] coord_to = index2coord[str(index_to)][::-1] dist = distance.distance(coord_from, coord_to).km ...
Python
nomic_cornstack_python_v1
function __call__ self value begin set prop = call Keyvalues _name value append _parents at - 1 prop return prop end function
def __call__(self, value: str) -> Keyvalues: prop = Keyvalues(self._name, value) self._builder._parents[-1].append(prop) return prop
Python
nomic_cornstack_python_v1
for i in range 0 length scores_list begin for tuple name mark in items scores begin if mark == scores_list at i begin print name end end end
for i in range (0,len(scores_list)): for (name,mark) in scores.items(): if mark == scores_list[i] : print(name)
Python
zaydzuhri_stack_edu_python
function closed_changed self state begin set model_indexes = call selectedIndexes if not model_indexes begin return none end set model_index = model_indexes at 0 set acc = data model_index role=UserRole comment Catch only changes that differ for selected account comment acc states in (0,1); Qt.CheckState in (0,1,2) com...
def closed_changed(self, state: int): model_indexes = self.selection.selectedIndexes() if not model_indexes: return None model_index = model_indexes[0] acc = model_index.data(role=Qt.UserRole) # Catch only changes that differ for selected account # acc state...
Python
nomic_cornstack_python_v1
string Mission Pinball Framework (mpf) setup.py. import re from setuptools import setup comment http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package set VERSIONFILE = string mpf/_version.py set VERSION_STRING_LONG = read open VERSIONFILE string rt set VSRE = string ^__version__ = ...
"""Mission Pinball Framework (mpf) setup.py.""" import re from setuptools import setup # http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package VERSIONFILE = "mpf/_version.py" VERSION_STRING_LONG = open(VERSIONFILE, "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" _MO = r...
Python
iamtarun_python_18k_alpaca
function mnd_train x_train y_train model_root_dir n_gpu=4 n_cpu=10 begin comment Horovod: initialize Horovod call init call clear_session call collect comment config = tf.ConfigProto(device_count={'GPU': n_gpu, 'CPU': n_cpu}) comment Horovod: pin GPU to be used to process local rank(one GPU perprocess) set config = cal...
def mnd_train(x_train, y_train, model_root_dir, n_gpu=4, n_cpu=10): # Horovod: initialize Horovod hvd.init() K.clear_session() gc.collect() # config = tf.ConfigProto(device_count={'GPU': n_gpu, 'CPU': n_cpu}) # Horovod: pin GPU to be used to process local rank(one GPU perprocess) config = ...
Python
nomic_cornstack_python_v1
string Copyright 2018 (c) Jinxin Xie Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
""" Copyright 2018 (c) Jinxin Xie Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in...
Python
zaydzuhri_stack_edu_python
function getResolution self begin return call _lowLevelGetDeviceResolution end function
def getResolution(self): return self._lowLevelGetDeviceResolution()
Python
nomic_cornstack_python_v1
function generate_numeric_captcha_image number begin comment Draw the colored number and fill any digit places comment according to the specified CAPTCHA length. comment EXAMPLE: if '25' was the number passed and the total comment CAPTCHA length is '4', its new value is '0025'. set captcha_text = string number set capt...
def generate_numeric_captcha_image(number): # Draw the colored number and fill any digit places # according to the specified CAPTCHA length. # # EXAMPLE: if '25' was the number passed and the total # CAPTCHA length is '4', its new value is '0025'. captcha_text = str(number) captcha_...
Python
nomic_cornstack_python_v1
from random import randint from hamcrest import assert_that , equal_to from src.page_objects.guru_bank import * from src.test_data.general.page_urls import PageUrls from src.data_objects.customer import Customer from src.wrappers.browser_wrapper import BrowserWrapper from src.data_objects.page_constants.deposit_page_co...
from random import randint from hamcrest import assert_that, equal_to from src.page_objects.guru_bank import * from src.test_data.general.page_urls import PageUrls from src.data_objects.customer import Customer from src.wrappers.browser_wrapper import BrowserWrapper from src.data_objects.page_constants.deposit_page_con...
Python
zaydzuhri_stack_edu_python
import unittest import radial_quadrature as rq from slater_test_f import slater_1s import numpy as np import math class RadialQuadratureTest extends TestCase begin function test_euler_maclaurin_radial_quad self begin comment Becke used this instead of Bragg-Slater value of 0.25A set h_becke_rad = 0.35 set tuple weights...
import unittest import radial_quadrature as rq from slater_test_f import slater_1s import numpy as np import math class RadialQuadratureTest(unittest.TestCase): def test_euler_maclaurin_radial_quad(self): # Becke used this instead of Bragg-Slater value of 0.25A h_becke_rad = 0.35 weights,r...
Python
zaydzuhri_stack_edu_python
function TextEncBlock L d scope=string TextEncBlock begin set e = call as_list at 2 with call variable_scope scope begin set conv_params = dict string filters 2 * d ; string kernel_size 1 ; string padding string same with call variable_scope string C_block1 begin comment relu(conv) set L1 = relu conv 1d inputs=L keywor...
def TextEncBlock(L,d,scope="TextEncBlock"): e = L.shape.as_list()[2] with tf.variable_scope(scope): conv_params = {"filters":2*d,"kernel_size":1,"padding":"same"} with tf.variable_scope("C_block1"): L1 = tf.nn.relu(conv1d(inputs=L,**conv_params)) # relu(conv) L2 = conv1...
Python
nomic_cornstack_python_v1
function controller observation begin set single_latent = call normal size=tuple 1 action_dim set raw_action = run raw_actions feed_dict=dict observation_ph observation ; latent_ph single_latent set tan_action = run tan_actions feed_dict=dict observation_ph observation ; latent_ph single_latent return if expression squ...
def controller(observation): single_latent = np.random.normal(size=(1, action_dim)) raw_action = sess.run(raw_actions, feed_dict={observation_ph: observation, latent_ph: single_latent}) tan_action = sess.run(tan_actions, feed_dict={observation_ph: obse...
Python
nomic_cornstack_python_v1
class InvalidInputException extends Exception begin pass end class function is_prime n begin if n <= 1 begin return false end if n <= 3 begin return true end if n % 2 == 0 or n % 3 == 0 begin return false end set i = 5 while i * i <= n begin if n % i == 0 or n % i + 2 == 0 begin return false end set i = i + 6 end retur...
class InvalidInputException(Exception): pass def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return T...
Python
greatdarklord_python_dataset
comment 다시풀기 k의 배수가 되도록 한꺼번에 빼주기 comment n,k = map(int,input().split()) comment result = 0 comment while True: comment target = (n//k)* k # n과 가장가까운 k의 배수가 타겟이다. comment result += (n - target) # 1을 빼주는 횟수만큼 더해준다 comment n = target comment if n < k: comment break comment result += 1 comment n //= k comment result += (n-...
# 다시풀기 k의 배수가 되도록 한꺼번에 빼주기 # n,k = map(int,input().split()) # result = 0 # while True: # target = (n//k)* k # n과 가장가까운 k의 배수가 타겟이다. # result += (n - target) # 1을 빼주는 횟수만큼 더해준다 # n = target # if n < k: # break # result += 1 # n //= k # result += (n-1) # print(r...
Python
zaydzuhri_stack_edu_python
from bisect import bisect_left function rwh_primes2 n begin comment https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 string Input n>=6, Returns a list of primes, 2 <= p < n set correction = n % 6 > 1 set n = dict 0 n ; 1 n - 1 ; 2 n + 4 ; 3 n + 3 ; 4 n + 2 ; 5...
from bisect import bisect_left def rwh_primes2(n): # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n%6>1) n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] sieve = [True]...
Python
jtatman_500k
comment traversing ASTs (Abstract Syntax Tress) class TimesNode extends object begin function __init__ self left right begin set right = right set left = left end function function eval self begin return eval * eval end function function inOrder self begin return format string ({} * {}) call inOrder call inOrder end fu...
# traversing ASTs (Abstract Syntax Tress) class TimesNode(object): def __init__(self, left, right): self.right = right self.left = left def eval(self): return self.left.eval() * self.right.eval() def inOrder(self): return "({} * {})".format(self.left.inOrder() , self.right.inOrder()) cla...
Python
zaydzuhri_stack_edu_python
string file: seeMeDont.py author: Ro from breezypythongui import EasyFrame class PeekABoo extends EasyFrame begin string buttons and events function __init__ self begin string sets up the window, label, and buttons. call __init__ self width=200 height=200 title=string PeekABoo background=string cyan comment A single la...
""" file: seeMeDont.py author: Ro """ from breezypythongui import EasyFrame class PeekABoo(EasyFrame): """buttons and events""" def __init__(self): """sets up the window, label, and buttons.""" EasyFrame.__init__(self, width = 200, height = 200, title = "PeekABoo", background = "cyan") # A sin...
Python
zaydzuhri_stack_edu_python
function delivery_address self begin set registered_office = call one_or_none if registered_office begin return filter address_type == string delivery end return filter address_type == DELIVERY end function
def delivery_address(self): registered_office = db.session.query(Office).filter(Office.business_id == self.id).\ filter(Office.office_type == 'registeredOffice').one_or_none() if registered_office: return registered_office.addresses.filter(Address.address_type == 'delivery') ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Dec 3 17:00:34 2017 @author: https://github.com/githubxiaowei comment from crawllib import save_text import requests from lxml import html import re import jieba import time class BaiduCrawler begin function __init__ self fpath=string begin comment 该参数为搜索文本保存路径 set fp...
# -*- coding: utf-8 -*- """ Created on Sun Dec 3 17:00:34 2017 @author: https://github.com/githubxiaowei """ #from crawllib import save_text import requests from lxml import html import re import jieba import time class BaiduCrawler: def __init__(self,fpath=''): self.fpath = fpath #该参数为搜索文本保存路径 ...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render , get_object_or_404 , redirect from django.forms import modelform_factory from models import Meeting , Room comment Create your views here. function detail request id begin set meeting = call get_object_or_404 Meeting pk=id return call render request string meetings/detail.html dict ...
from django.shortcuts import render, get_object_or_404, redirect from django.forms import modelform_factory from .models import Meeting, Room # Create your views here. def detail(request, id): meeting = get_object_or_404(Meeting, pk=id) return render(request, "meetings/detail.html", {"meeting": meeting}) de...
Python
zaydzuhri_stack_edu_python
function save_evaluations self evaluations_file=none begin string Saves evaluations at each iteration of the optimization :param evaluations_file: name of the file in which the results are saved. set iterations = array range 1 shape at 0 + 1 at tuple slice : : none set results = horizontal stack tuple iterations Y X...
def save_evaluations(self, evaluations_file = None): """ Saves evaluations at each iteration of the optimization :param evaluations_file: name of the file in which the results are saved. """ iterations = np.array(range(1, self.Y.shape[0] + 1))[:, None] results = np.hsta...
Python
jtatman_500k
class Solution begin function twoSum self nums target begin comment l=len(nums) # method 1 --> O(n2) comment res=[] comment for i in range(0,l): comment for j in range(i+1,l): comment if nums[i]+nums[j]==target: comment res.append(i) comment res.append(j) comment return res set l = length nums comment method 2 --> O(n)...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # l=len(nums) # method 1 --> O(n2) # res=[] # for i in range(0,l): # for j in range(i+1,l): # if nums[i]+nums[j]==target: # res.append(i) #...
Python
zaydzuhri_stack_edu_python
function to_device data device begin if is instance data tuple list tuple begin return list comprehension call to_device x device for x in data end return to data device non_blocking=true end function
def to_device(data, device): if isinstance(data, (list,tuple)): return [to_device(x, device) for x in data] return data.to(device, non_blocking=True)
Python
nomic_cornstack_python_v1
comment Daily Coding Problem: Problem #4 [Hard] comment This problem was asked by Stripe. comment Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and...
# Daily Coding Problem: Problem #4 [Hard] # This problem was asked by Stripe. # # Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numb...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment encoding:utf-8 comment Author: Shawn Roche import getpass import os import argparse from apperianapi import apperian class EasePub begin function __init__ self params begin set env = params at string env set user = string set password = string set meta_data = dict set file_name =...
#!/usr/bin/env python # encoding:utf-8 # Author: Shawn Roche ######################### import getpass import os import argparse from apperianapi import apperian class EasePub: def __init__(self, params): self.env = params['env'] self.user = '' self.password = '' self.meta_data = {...
Python
zaydzuhri_stack_edu_python
function SetFlag *args **kwargs begin return call SizerItem_SetFlag *args keyword kwargs end function
def SetFlag(*args, **kwargs): return _core_.SizerItem_SetFlag(*args, **kwargs)
Python
nomic_cornstack_python_v1
while length set ABC != 1 begin set A = sorted ABC at 0 set B = sorted ABC at 1 set C = sorted ABC at 2 if ABC at 0 % 2 == ABC at 1 % 2 == ABC at 2 % 2 begin set A = A + 2 set cnt = cnt + 1 end else begin set A = A + 1 set B = B + 1 set cnt = cnt + 1 end set ABC = tuple A B C end print cnt
while len(set(ABC))!=1: A = sorted(ABC)[0] B = sorted(ABC)[1] C = sorted(ABC)[2] if ABC[0]%2==ABC[1]%2==ABC[2]%2: A += 2 cnt += 1 else: A += 1 B += 1 cnt += 1 ABC = A,B,C print(cnt)
Python
zaydzuhri_stack_edu_python
class Solution begin function setZeroes self matrix begin string Do not return anything, modify matrix in-place instead. set row_set = set set column_set = set for i in range length matrix begin for j in range length matrix at i begin if matrix at i at j == 0 begin add row_set i add column_set j end end end for i in ro...
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ row_set = set() column_set = set() for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[...
Python
zaydzuhri_stack_edu_python
import RPi.GPIO as GPIO import time from time import sleep import threading set in1 = 24 set in2 = 23 set en = 25 set in3 = 17 set in4 = 27 set en2 = 22 call setmode BCM setup GPIO in1 OUT setup GPIO in2 OUT setup GPIO en OUT call output in1 LOW call output in2 LOW setup GPIO in3 OUT setup GPIO in4 OUT setup GPIO en2 O...
import RPi.GPIO as GPIO import time from time import sleep import threading in1 = 24 in2 = 23 en = 25 in3 = 17 in4 = 27 en2 = 22 GPIO.setmode(GPIO.BCM) GPIO.setup(in1, GPIO.OUT) GPIO.setup(in2, GPIO.OUT) GPIO.setup(en, GPIO.OUT) GPIO.output(in1, GPIO.LOW) GPIO.output(in2, GPIO.LOW) GPIO.setup(in3, GPIO.OUT) GPIO.se...
Python
zaydzuhri_stack_edu_python
function remove_black_borders self remove_black_borders begin set _remove_black_borders = remove_black_borders end function
def remove_black_borders(self, remove_black_borders): self._remove_black_borders = remove_black_borders
Python
nomic_cornstack_python_v1