code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function encode self text begin if verbatim begin return text end comment compile the regexps once. do it here so one can see them. comment first the braces. if not call has_key string encode_re_braces begin set encode_re_braces = compile string ([{}]) end set text = sub string {\\\1} text if not call has_key string en...
def encode(self, text): if self.verbatim: return text # compile the regexps once. do it here so one can see them. # # first the braces. if not self.__dict__.has_key('encode_re_braces'): self.encode_re_braces = re.compile(r'([{}])') text = self.enco...
Python
nomic_cornstack_python_v1
class Dog begin set name = string comment Конструктор comment Вызывается на момент создания объекта этого типа function __init__ self newName begin set name = newName end function comment Можем в любой момент вызвать и изменить имя function setName self newName begin set name = newName end function comment Можем в люб...
class Dog(): name="" # Конструктор # Вызывается на момент создания объекта этого типа def __init__ (self, newName): self.name = newName # Можем в любой момент вызвать и изменить имя def setName (self, newName): self.name = newName # Можем в любой момент вызвать и у...
Python
zaydzuhri_stack_edu_python
string # Definition for an Interval. class Interval: def __init__(self, start: int = None, end: int = None): self.start = start self.end = end class Solution begin function employeeFreeTime self schedule begin comment Grab intervals comment Sort intervals comment Combine intervals comment Loop through combined and add ...
""" # Definition for an Interval. class Interval: def __init__(self, start: int = None, end: int = None): self.start = start self.end = end """ class Solution: def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]': # Grab intervals # Sort intervals # Combi...
Python
zaydzuhri_stack_edu_python
function parse_products begin set products = list with open call data_path string products.csv as csvfile begin set reader = reader csvfile set schema = next set Product = named tuple string Product schema for line in reader begin append products product line at 0 line at 1 line at 2 decimal line at 3 integer line at ...
def parse_products(): products = [] with open(data_path('products.csv')) as csvfile: reader = csv.reader(csvfile) schema = reader.next() Product = namedtuple('Product', schema) for line in reader: products.append(Product( line[0], line[1], line[2], flo...
Python
nomic_cornstack_python_v1
function average_to_vertices self dofs begin set tuple data_qp integral = call interp_to_qp dofs set vertex_dofs = call average_qp_to_vertices data_qp integral return vertex_dofs end function
def average_to_vertices(self, dofs): data_qp, integral = self.interp_to_qp(dofs) vertex_dofs = self.average_qp_to_vertices(data_qp, integral) return vertex_dofs
Python
nomic_cornstack_python_v1
function _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_targets_vpn_target input_yang_obj translated_yang_obj=none begin for tuple k listInst in call iteritems begin set innerobj = call _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_targets_vpn_target_route_targets listInst...
def _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_targets_vpn_target(input_yang_obj, translated_yang_obj=None): for k, listInst in input_yang_obj.route_targets.iteritems(): innerobj = _trans...
Python
nomic_cornstack_python_v1
import socket import threading import time import pytext as pt import tkinter as tk set editor = none class Client_Thread extends Thread begin function __init__ self name address connection begin call __init__ self set client_name = string Client + string name set address = address comment same address set socketIn = c...
import socket import threading import time import pytext as pt import tkinter as tk editor = None class Client_Thread(threading.Thread): def __init__(self, name, address, connection): threading.Thread.__init__(self) self.client_name = "Client" + str(name) self.address = address # ...
Python
zaydzuhri_stack_edu_python
function tx_packet self final=false begin debug string Transmitting BFD packet to %s:%s remote CONTROL_PORT call sendto call encode_packet final tuple remote CONTROL_PORT end function
def tx_packet(self, final=False): log.debug('Transmitting BFD packet to %s:%s', self.remote, CONTROL_PORT) self.client.sendto( self.encode_packet(final), (self.remote, CONTROL_PORT))
Python
nomic_cornstack_python_v1
if c % 2 == 0 begin for i in range 0 c 2 begin set t = s at i set s at i = s at i + 1 set s at i + 1 = t end end
if c%2 ==0: for i in range(0,c,2): t=s[i] s[i]=s[i+1] s[i+1]=t
Python
zaydzuhri_stack_edu_python
function schema_descriptor self json_schema begin set derefed_json_schema = call _deref_json_schema json_schema comment merging the derefed json schema into the actual json schema. This preserves fields in the schema which comment were specified alongside the $ref set metadata_schema_data = merge json_schema derefed_js...
def schema_descriptor(self, json_schema): derefed_json_schema = self._deref_json_schema(json_schema) # merging the derefed json schema into the actual json schema. This preserves fields in the schema which # were specified alongside the $ref metadata_schema_data = merge(json_schema, der...
Python
nomic_cornstack_python_v1
function __imul__ self *args begin return call Velocity3D___imul__ self *args end function
def __imul__(self, *args): return _almathswig.Velocity3D___imul__(self, *args)
Python
nomic_cornstack_python_v1
function grep self regex begin set regex_search = search return join string generator expression strip line for line in call splitlines if call regex_search line end function
def grep(self, regex): regex_search = re.compile(regex, re.I).search return "\n".join( line.strip() for line in self.contents.splitlines() if regex_search(line) )
Python
nomic_cornstack_python_v1
function total_intensity par_int per_int begin string Calculate total intensity from parallel and perpendicular intensity. Parameters ---------- par_int: Parallel intensity component. per_int: Perpendicular intensity component. return par_int + 2 * per_int end function function anisotropy_from_intensity par_int per_int...
def total_intensity(par_int, per_int): """Calculate total intensity from parallel and perpendicular intensity. Parameters ---------- par_int: Parallel intensity component. per_int: Perpendicular intensity component. """ return par_int + 2 * per_int def anisotropy_from_intensity(par_int, p...
Python
zaydzuhri_stack_edu_python
function test_parse_args_proposed_components_split self begin set args = call parse_args list string --proposed-components string main contrib non-free assert equal proposed_components list string main string contrib string non-free end function
def test_parse_args_proposed_components_split(self) -> None: args = parse_args(["--proposed-components", "main contrib non-free"]) self.assertEqual(args.proposed_components, ["main", "contrib", "non-free"])
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding=utf-8 class Solution extends object begin function lengthOfLIS self nums begin string :type nums: List[int] :rtype: int set n = length nums if n == 0 begin return 0 end else if n == 1 begin return 1 end else if n == 2 begin if nums at 0 < nums at 1 begin return 2 end else beg...
#!/usr/bin/env python # coding=utf-8 class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n == 0: return 0 elif n == 1: return 1 elif n == 2: if nums[0] < nu...
Python
zaydzuhri_stack_edu_python
function use_with data fn *attrs begin string Apply a function on the attributes of the data :param data: an object :param fn: a function :param attrs: some attributes of the object :returns: an object Let's create some data first:: >>> from collections import namedtuple >>> Person = namedtuple('Person', ('name', 'age'...
def use_with(data, fn, *attrs): """Apply a function on the attributes of the data :param data: an object :param fn: a function :param attrs: some attributes of the object :returns: an object Let's create some data first:: >>> from collections import namedtuple >>> Person = nam...
Python
jtatman_500k
comment ! /usr/bin/env python3 import argparse import re import subprocess from pathlib import Path import requests import pandas as pd import numpy as np comment Inspired by comment https://github.com/wwood/ena-fast-download/blob/master/ena-fast-download.py comment --- Constants --- set accession_path = string https:/...
#! /usr/bin/env python3 import argparse import re import subprocess from pathlib import Path import requests import pandas as pd import numpy as np # Inspired by # https://github.com/wwood/ena-fast-download/blob/master/ena-fast-download.py # --- Constants --- accession_path = 'https://www.ncbi.nlm.nih.gov/geo/query/...
Python
zaydzuhri_stack_edu_python
comment Oving 6 import random import time from irproximity_sensor import IRProximitySensor from motors import Motors from reflectance_sensors import ReflectanceSensors from ultrasonic import Ultrasonic from zumo_button import ZumoButton from camera import Camera from imager2 import Imager comment update class BBCON beg...
#Oving 6 import random import time from irproximity_sensor import IRProximitySensor from motors import Motors from reflectance_sensors import ReflectanceSensors from ultrasonic import Ultrasonic from zumo_button import ZumoButton from camera import Camera from imager2 import Imager #update class BBCON: def __init...
Python
zaydzuhri_stack_edu_python
string Create a dictionary representing a network device. The dictionary should have key-value pairs representing the 'ip_addr', 'vendor', 'username', and 'password' fields. Print out the 'ip_addr' key from the dictionary. If the 'vendor' field is 'cisco', then set the 'platform' to 'ios'. If the 'vendor' field is 'jun...
""" Create a dictionary representing a network device. The dictionary should have key-value pairs representing the 'ip_addr', 'vendor', 'username', and 'password' fields. Print out the 'ip_addr' key from the dictionary. If the 'vendor' field is 'cisco', then set the 'platform' to 'ios'. If the 'vendor' field is 'junipe...
Python
zaydzuhri_stack_edu_python
function configure_before_handlers app begin pass end function
def configure_before_handlers(app): pass
Python
nomic_cornstack_python_v1
comment !/usr/bin/python from urllib import urlencode from urllib2 import urlopen , Request from json import loads import sys class LeetPhorum begin function __init__ self url begin set f = url open url set i = info close f if not string Set-Cookie in i begin raise exception string Cookie is missing end set url = url s...
#!/usr/bin/python from urllib import urlencode from urllib2 import urlopen, Request from json import loads import sys class LeetPhorum: def __init__(self, url): f = urlopen(url) i = f.info() f.close() if not 'Set-Cookie' in i: raise Exception('Cookie is missing') ...
Python
zaydzuhri_stack_edu_python
function split_name filename begin comment *********** My filename are in the format ./CaAl2Si2O8_T3_nvt_a12.5. comment ******* so I can split their name with _ and take the compound and T from their name set filename = strip filename string ./ set temperature = string integer decimal strip split filename string _ at 1...
def split_name(filename): # *********** My filename are in the format ./CaAl2Si2O8_T3_nvt_a12.5. # ******* so I can split their name with _ and take the compound and T from their name filename = filename.strip('./') temperature = str(int(float(filename.split('_')[1].strip('T'))*1000)) acell = filena...
Python
nomic_cornstack_python_v1
function korean_pron text begin comment print("바꾸기전:" + text) for tuple i j in items korean_rule begin for k in j begin if text == k begin set text = i end end end comment print("바뀐후(문자):" + text) for tuple i j in items korean_number_system begin for k in i begin if text == k begin set text = string j end end end comme...
def korean_pron(text): # print("바꾸기전:" + text) for i, j in korean_rule.items(): for k in j: if (text == k): text = i # print("바뀐후(문자):" + text) for i, j in korean_number_system.items(): for k in i: if (text == k): text = str(j) ...
Python
zaydzuhri_stack_edu_python
class OnCloseCallbackMixin begin set __on_close_callback = none function set_on_close self callback begin set __on_close_callback = callback end function function on_close self begin if __on_close_callback is not none begin call __on_close_callback end end function end class
class OnCloseCallbackMixin: __on_close_callback = None def set_on_close(self, callback: callable): self.__on_close_callback = callback def on_close(self): if self.__on_close_callback is not None: self.__on_close_callback()
Python
zaydzuhri_stack_edu_python
function threeKeywordSuggestions numReviews repository customerQuery begin comment loop over each character of the customerQuery comment create new subQuery based on that comment loop over each word in the repo comment see if it starts with the subQuery set outputs = list set loweredRepo = sorted list comprehension lo...
def threeKeywordSuggestions(numReviews, repository, customerQuery): # loop over each character of the customerQuery # create new subQuery based on that # loop over each word in the repo # see if it starts with the subQuery outputs = [] loweredRepo = sorted([word.lower() for word in repository]) ...
Python
zaydzuhri_stack_edu_python
comment Custom fields for django models from django.db import models from django.core.serializers.json import DjangoJSONEncoder import json comment Extending DjangoJSONEncoder for serialize custom classes. class CustomJSONEncoder extends DjangoJSONEncoder begin function default self obj begin try begin return call defa...
# Custom fields for django models from django.db import models from django.core.serializers.json import DjangoJSONEncoder import json # Extending DjangoJSONEncoder for serialize custom classes. class CustomJSONEncoder(DjangoJSONEncoder): def default(self, obj): try: return DjangoJSONEncoder.de...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- codind:utf-8 -*- comment Author:ljb set salary = input string input your salary: if is digit salary begin set salary = integer salary end else begin exit string invalid data type end set welcome_msg = call center 50 string - print welcome_msg set exit_flags = true set product_li...
#!/usr/bin/env python # -*- codind:utf-8 -*- #Author:ljb salary = input('input your salary:') if salary.isdigit(): salary = int(salary) else: exit('invalid data type') welcome_msg = "Welcome to My Shoping mail".center(50,'-') print(welcome_msg) exit_flags = True product_list = [ ('iphone',5000), ('M...
Python
zaydzuhri_stack_edu_python
function installExceptionHandler handler=none begin set excepthook = if expression handler is not none then handler else baseExceptionHandler return true end function
def installExceptionHandler(handler=None): sys.excepthook = handler if handler is not None else baseExceptionHandler return True
Python
nomic_cornstack_python_v1
function test_shuffle self begin comment Workaround for small deck sizes causing shuffled decks to comment retain the original order for card in card_list * 10 begin call insert_card card end reverse card_list shuffle deck assert not equal card_list card_list * 10 end function
def test_shuffle(self): # Workaround for small deck sizes causing shuffled decks to # retain the original order for card in self.card_list*10: self.deck.insert_card(card) self.card_list.reverse() self.deck.shuffle() self.assertNotEqual(self.deck.card_list, sel...
Python
nomic_cornstack_python_v1
comment -*- coding: cp1252 function main begin string El usuario ingresa la tarifa por segundo, cuántas comunicaciones se realizaron. y la duración de cada comunicación expresadas en horas. minutos y segundos.Como resultado se informa la duración en segundos de cada comunicación y su costo. set f = input string ¿Cuánto...
# -*- coding: cp1252 def main(): """El usuario ingresa la tarifa por segundo, cuántas comunicaciones se realizaron. y la duración de cada comunicación expresadas en horas. minutos y segundos.Como resultado se informa la duración en segundos de cada comunicación y su costo.""" f = input("¿...
Python
zaydzuhri_stack_edu_python
function product x y begin return x * y end function
def product(x, y): return x * y
Python
jtatman_500k
import pandas as pd from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Conv1D , Dense , Flatten , Dropout , GlobalMaxPooling1D , Embedding from sklearn.model_selection import train_test_split from python_file...
import pandas as pd from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Conv1D, Dense, Flatten, Dropout, GlobalMaxPooling1D, Embedding from sklearn.model_selection import train_test_split from python_files ...
Python
zaydzuhri_stack_edu_python
function dispatch_dl distribution_u_want a begin return call get dict string bernoulli lambda -> 1.0 + a ; string geometric lambda -> 1.0 / 1.0 - a ; string exponential lambda -> - 1.0 / a distribution_u_want lambda -> none end function
def dispatch_dl(distribution_u_want, a): return { 'bernoulli': lambda: 1. + a, 'geometric': lambda: 1. / (1. - a), 'exponential': lambda: -1. / a, }.get(distribution_u_want, lambda: None)()
Python
nomic_cornstack_python_v1
async function read self num_bytes=0 begin if num_bytes < 1 begin set num_bytes = in_waiting or 1 end return await call _read num_bytes end function
async def read(self, num_bytes=0) -> bytes: if num_bytes < 1: num_bytes = self.in_waiting or 1 return await self._read(num_bytes)
Python
nomic_cornstack_python_v1
import hashlib import binascii comment entrer le secret function mot10char begin set secret = input string Donnez un secret de 10 caractères au maximum : while length secret > 11 begin set secret = input string C'est beaucoup trop long, 10 caractères S.V.P : end return secret end function function long_message begin se...
import hashlib import binascii def mot10char(): # entrer le secret secret = input("Donnez un secret de 10 caractères au maximum : ") while (len(secret) > 11): secret = input("C'est beaucoup trop long, 10 caractères S.V.P : ") return (secret) def long_message(): secret = input("Enter a secret...
Python
zaydzuhri_stack_edu_python
string 206. Reverse Linked List Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? comment Definition for singly-linked list. class ListNode begin function __init__ self val=0...
''' 206. Reverse Linked List Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? ''' # Definition for singly-linked list. class ListNode: def __init__(self, val=0, nex...
Python
zaydzuhri_stack_edu_python
function plot_environment_and_mean self begin set fig = figure set ax = call Axes3D fig call set_title string Environment, Mean and Data on a 3d Plot call set_xlabel string Action call set_ylabel string Context call set_zlabel string Reward comment plot self.mu on a wire frame. call plot_wireframe input_mesh at 0 input...
def plot_environment_and_mean(self): fig = plt.figure() ax = Axes3D(fig) ax.set_title('Environment, Mean and Data on a 3d Plot') ax.set_xlabel('Action') ax.set_ylabel('Context') ax.set_zlabel('Reward') # plot self.mu on a wire frame. ax.plot_wireframe(self.input_mesh[0], self.input_mesh...
Python
nomic_cornstack_python_v1
function safe_bulk_metadata ids marc=false sleep_time=1 begin try begin set metadata = call get_bulk_metadata ids marc if sleep_time begin sleep sleep_time end return metadata end except ValueError as err begin error err return dictionary end end function
def safe_bulk_metadata(ids, marc=False, sleep_time=1): try: metadata = get_bulk_metadata(ids, marc) if sleep_time: sleep(sleep_time) return metadata except ValueError as err: logging.error(err) return dict()
Python
nomic_cornstack_python_v1
from PIL import Image import colorsys import time set start_time = call clock function color_comp begin print string File name? set img = input string try begin set im = open img string r set tuple width height = size comment converted = list(map(lambda x: colorsys.rgb_to_hsv(*x), list(im.getdata()))) comment return co...
from PIL import Image import colorsys import time start_time = time.clock() def color_comp(): print("File name?") img = input("") try: im = Image.open(img, 'r') width, height = im.size #converted = list(map(lambda x: colorsys.rgb_to_hsv(*x), list(im.getdata()))) #return converted[100] x = [colorsys.rgb...
Python
zaydzuhri_stack_edu_python
string QuinteroMichael_complex_CRI1_1404 Michael Quintero How to Run: import QuinteroMichael_complex_CRI1_1404 reload(QuinteroMichael_complex_CRI1_1404) import pymel.core as pm
''' QuinteroMichael_complex_CRI1_1404 Michael Quintero How to Run: import QuinteroMichael_complex_CRI1_1404 reload(QuinteroMichael_complex_CRI1_1404) ''' import pymel.core as pm
Python
zaydzuhri_stack_edu_python
comment My Solution function isUnique str begin set d = dictionary for i in str begin if get d i 0 == 0 begin set d at i = 1 end else begin set d at i = d at i + 1 end end for tuple _ j in items d begin if j != 1 begin return false end end return true end function print call isUnique string asdf!! comment Another Solut...
# My Solution def isUnique(str): d = dict() for i in str: if d.get(i,0) == 0: d[i] = 1 else: d[i] += 1 for _, j in d.items(): if j != 1: return False return True print(isUnique("asdf!!")) # Another Solution import unittest def isUnique(strin...
Python
zaydzuhri_stack_edu_python
function runIsing begin set energies = zeros STEPS set mags = zeros STEPS with open PATH + string / + string round T 2 + string _ + string SIZE + string _ + string STEPS + string .csv string w newline=string as csvfile begin set testWriter = writer csvfile delimiter=string quotechar=string | quoting=QUOTE_MINIMAL writ...
def runIsing(): energies = np.zeros(STEPS) mags = np.zeros(STEPS) with open(PATH +'/' +str(round(T, 2)) + '_' + str(SIZE) + '_'+ str(STEPS)+'.csv', 'w', newline='') as csvfile: testWriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) ...
Python
nomic_cornstack_python_v1
from turtle import * comment CREATE FUNCTIONS FOR EACH SHAPE comment TRIANGLE function tri begin for i in range 3 begin call forward 150 call right 120 end end function comment mainloop() comment SQUARE function squ begin call forward 100 call right 90 call forward 100 call right 90 call forward 100 call right 90 call ...
from turtle import * ## CREATE FUNCTIONS FOR EACH SHAPE # TRIANGLE def tri(): for i in range(3): forward(150) right(120) # mainloop() # SQUARE def squ(): forward(100) right(90) forward(100) right(90) forward(100) right(90) forward(100) # mainloop() # PENTAGON ...
Python
zaydzuhri_stack_edu_python
function nodata self begin set nodatas = list comprehension call GetNoDataValue for i in range 1 bands + 1 if length list set nodatas == 1 begin return nodatas at 0 end else begin return nodatas end end function
def nodata(self): nodatas = [self.raster.GetRasterBand(i).GetNoDataValue() for i in range(1, self.bands + 1)] if len(list(set(nodatas))) == 1: return nodatas[0] else: return nodatas
Python
nomic_cornstack_python_v1
comment LIST(Mutable, Hetrogenous) string list_1 = ['History', 'Math', 'Physics', 'CompSci'] #some list functions print(len(list_1)) print(list_1[0]) print(list_1[-1]) # -1 starting from the last print(list_1[0:2]) #last index (here 2) will not ne included print(list_1[:2]) # same as above print(list_1[2:]) # 2(includi...
#LIST(Mutable, Hetrogenous) """ list_1 = ['History', 'Math', 'Physics', 'CompSci'] #some list functions print(len(list_1)) print(list_1[0]) print(list_1[-1]) # -1 starting from the last print(list_1[0:2]) #last index (here 2) will not ne included print(list_1[:2]) # same as above print(list_1[2:]) # 2(including) to e...
Python
zaydzuhri_stack_edu_python
import uuid from class_email import Email from example_data import applicants from model.model_base import * from model.model_city import City from model.model_mentor import Mentor from model.model_school import School from model.model_interviewslot import InterviewSlot class Applicant extends BaseModel begin string Ap...
import uuid from class_email import Email from example_data import applicants from model.model_base import * from model.model_city import City from model.model_mentor import Mentor from model.model_school import School from model.model_interviewslot import InterviewSlot class Applicant(BaseModel): """ Applicant...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 string Context Helpers for unit test data. comment ----------------------------------------------------------------------------- comment Imports comment ----------------------------------------------------------------------------- from typing import TYPE_CHECKING , Optional , Type , Dict if TYPE_C...
# coding: utf-8 ''' Context Helpers for unit test data. ''' # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- from typing import TYPE_CHECKING, Optional, Type, Dict if TYPE_CHECKING: import uni...
Python
zaydzuhri_stack_edu_python
function hex_to_dec hex_str begin set hex_dict = dict string 0 0 ; string 1 1 ; string 2 2 ; string 3 3 ; string 4 4 ; string 5 5 ; string 6 6 ; string 7 7 ; string 8 8 ; string 9 9 ; string a 10 ; string b 11 ; string c 12 ; string d 13 ; string e 14 ; string f 15 set user_input = input string Enter a hexadecimal valu...
def hex_to_dec(hex_str): hex_dict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'a': 10 , 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15} user_input = input("Enter a hexadecimal value you would like to convert to a decimal: ") length = len(user_input) -1 for digit in ...
Python
zaydzuhri_stack_edu_python
function schedule_workflow self workflow_uuid begin set current_time = call get_current_time set workflow = workflows at workflow_uuid comment IMPORTANT: tasks are not scheduled by eft because they will comment be automatically sorted in event loop. for task in tasks begin if not parents begin call add_event event=even...
def schedule_workflow(self, workflow_uuid: str) -> None: current_time = self.event_loop.get_current_time() workflow = self.workflows[workflow_uuid] # IMPORTANT: tasks are not scheduled by eft because they will # be automatically sorted in event loop. for task in workflow.task...
Python
nomic_cornstack_python_v1
function deactivate self begin set active = 0 end function
def deactivate(self): self.active = 0
Python
nomic_cornstack_python_v1
function getAliasList self begin pass end function
def getAliasList(self): pass
Python
nomic_cornstack_python_v1
function field2str field begin return join string map join field end function function solve field words positions begin if not words begin print call field2str field exit end set tuple words word = tuple words at slice : - 1 : words at - 1 for position in positions begin set tuple i j di dj = position set go_furthe...
def field2str(field): return '\n'.join(map(''.join, field)) def solve(field, words, positions): if not words: print(field2str(field)) exit() words, word = words[:-1], words[-1] for position in positions: i, j, di, dj = position go_further = True next_field = [...
Python
zaydzuhri_stack_edu_python
function prepare_dfs json_path get_CBS=false only_converged=false begin set data_dict = read json json_path set df_qc = call qc_dframe data_dict only_converged=only_converged set df_qats = call qats_dframe data_dict if get_CBS begin set df_qc = call add_cbs_extrap_qc_df df_qc cbs_basis_key=string aug basis_set_lower=st...
def prepare_dfs(json_path, get_CBS=False, only_converged=False): data_dict = read_json(json_path) df_qc = qc_dframe(data_dict, only_converged=only_converged) df_qats = qats_dframe(data_dict) if get_CBS: df_qc = add_cbs_extrap_qc_df( df_qc, cbs_basis_key='aug', basis_set_lower='aug-cc...
Python
nomic_cornstack_python_v1
string @author: raghul import numpy as np class neural_network begin function __init__ self features_len begin set input_nodes = features_len set output_nodes = 1 comment self.hidden_layer = 1 comment self.weight = np.random.randn(self.input_nodes, self.output_nodes) set weight = zeros tuple input_nodes output_nodes dt...
''' @author: raghul ''' import numpy as np class neural_network: def __init__(self, features_len): self.input_nodes = features_len self.output_nodes = 1 #self.hidden_layer = 1 #self.weight = np.random.randn(self.input_nodes, self.output_nodes) self.weight = np.zeros(...
Python
zaydzuhri_stack_edu_python
import os , shutil set theFolder = string build set folders = list directory string . for folder in folders begin if is directory path folder begin set file_path = join path folder theFolder print string Deleting folowing directory: + file_path try begin if is directory path file_path begin remove tree file_path end en...
import os, shutil theFolder = 'build' folders = os.listdir('.') for folder in folders: if os.path.isdir(folder): file_path = os.path.join(folder, theFolder) print( 'Deleting folowing directory: ' + file_path) try: if os.path.isdir(file_path): shutil.rmtree(fil...
Python
zaydzuhri_stack_edu_python
function bandreject self wllow wlhigh begin set new_phase = call bandreject_filter phase sample_spacing wllow wlhigh set new_phase at ? call isfinite phase = nan set phase = new_phase return self end function
def bandreject(self, wllow, wlhigh): new_phase = bandreject_filter(self.phase, self.sample_spacing, wllow, wlhigh) new_phase[~m.isfinite(self.phase)] = m.nan self.phase = new_phase return self
Python
nomic_cornstack_python_v1
function set_up_to_date self *outfile_names begin comment For efficiency, we can update many outfiles at once. for outfile_name in outfile_names begin try begin set new_file_info = call get_transaction outfile_name end except tuple NameError AssertionError begin raise call KeyError string %s: Must call changed_files() ...
def set_up_to_date(self, *outfile_names): # For efficiency, we can update many outfiles at once. for outfile_name in outfile_names: try: new_file_info = self._db.get_transaction(outfile_name) except (NameError, AssertionError): raise KeyError( ...
Python
nomic_cornstack_python_v1
function test_traffic_alert_shuts_off_after_alert self begin set alert = call TrafficAlert set test_traffic = deque comment fake up some traffic for i in range alert_threshold * alert_period + 1 begin append test_traffic dict string time time ; string src_ip string 0.0.0.0 ; string path string / end comment trigger the...
def test_traffic_alert_shuts_off_after_alert(self): alert = TrafficAlert() test_traffic = collections.deque() # fake up some traffic for i in range(self.alert_threshold*self.alert_period + 1): test_traffic.append({'time': time.time(), 'src_ip'...
Python
nomic_cornstack_python_v1
function given_name self begin return get pulumi self string given_name end function
def given_name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "given_name")
Python
nomic_cornstack_python_v1
function my_kde_bandwidth obj fac=1.0 / 5 begin return call power n - 1.0 / d + 4 * fac end function
def my_kde_bandwidth(obj, fac=1./5): return np.power(obj.n, -1./(obj.d+4)) * fac
Python
nomic_cornstack_python_v1
function get_contract_factory self contract_name begin try begin set interface = __raw_contract_cache at contract_name end except KeyError begin raise call UnknownContract format string {} is not a compiled contract. contract_name end set contract = call contract abi=interface at string abi bytecode=interface at string...
def get_contract_factory(self, contract_name) -> Contract: try: interface = self.__raw_contract_cache[contract_name] except KeyError: raise self.UnknownContract('{} is not a compiled contract.'.format(contract_name)) contract = self.w3.eth.contract(abi=interface['abi'], ...
Python
nomic_cornstack_python_v1
function sample_top a=list top_k=10 begin set a = array a set idx = call argsort a at slice : : - 1 set idx = idx at slice : top_k : comment a = a[idx] set probs = a at idx set probs = probs / sum probs set choice = random choice idx p=probs return choice end function
def sample_top(a=[], top_k=10): a = np.array(a) idx = np.argsort(a)[::-1] idx = idx[:top_k] # a = a[idx] probs = a[idx] probs = probs / np.sum(probs) choice = np.random.choice(idx, p=probs) return choice
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri May 25 14:03:00 2018 @author: edwin comment Gráficas de temperaturas de las estaciones en la SAbana de Bogotá import pandas as pd import numpy as np import os import matplotlib.pyplot as plt from matplotlib import style function lista_nom...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 25 14:03:00 2018 @author: edwin """ #Gráficas de temperaturas de las estaciones en la SAbana de Bogotá import pandas as pd import numpy as np import os import matplotlib.pyplot as plt from matplotlib import style def lista_nombres(base): b...
Python
zaydzuhri_stack_edu_python
from tkinter import Tk , simpledialog , messagebox function read_from_file begin with open string capital_data.txt as file begin for line in file begin set line = right strip line string set tuple country city = split line string / set world at country = city end end end function function write_to_file country_name cit...
from tkinter import Tk, simpledialog, messagebox def read_from_file(): with open('capital_data.txt') as file: for line in file: line = line.rstrip('\n') country, city = line.split('/') world[country] = city def write_to_file(country_name, city_name): with open('capi...
Python
zaydzuhri_stack_edu_python
function get_predicted_structure self structure icsd_vol=false begin set new_structure = copy structure call scale_lattice predict self structure icsd_vol=icsd_vol return new_structure end function
def get_predicted_structure(self, structure, icsd_vol=False): new_structure = structure.copy() new_structure.scale_lattice(self.predict(structure, icsd_vol=icsd_vol)) return new_structure
Python
nomic_cornstack_python_v1
comment Helper for merging traces function merge a b path=none begin set a = dictionary a if path is none begin set path = list end for key in b begin if key in a and is instance a at key dict and is instance b at key dict begin set a at key = merge a at key b at key path + list string key end else begin set a at key ...
# Helper for merging traces def merge(a, b, path=None): a = dict(a) if path is None: path = [] for key in b: if key in a and isinstance(a[key], dict) and isinstance(b[key], dict): a[key] = merge(a[key], b[key], path + [str(key)]) else: a[key] = b[key] return a ...
Python
zaydzuhri_stack_edu_python
import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output import numpy as np import pandas as pd from sklearn.metrics.cluster import silhouette_score import model import dashboard.app_misc as misc from dashboard.cache import cache set clustering_dropdown = call Dropdown...
import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output import numpy as np import pandas as pd from sklearn.metrics.cluster import silhouette_score import model import dashboard.app_misc as misc from dashboard.cache import cache clustering_dropdown = misc.Dropdow...
Python
zaydzuhri_stack_edu_python
function test_filtering_request_numeric_field_wrong_type flask_app begin set data = dict string criteria dict string price string test with call test_request_context method=string POST json=data begin set validated_request = call validate_filter_request request assert string error in validated_request and validated_req...
def test_filtering_request_numeric_field_wrong_type(flask_app): data = { 'criteria': { 'price': 'test' } } with flask_app.test_request_context(method='POST', json=data): validated_request = request_helper.validate_filter_request(request) assert ('error' in valida...
Python
nomic_cornstack_python_v1
function vit_small_patch16_224 pretrained=false **kwargs begin set model_kwargs = dictionary patch_size=16 embed_dim=768 depth=8 num_heads=8 mlp_ratio=3.0 qkv_bias=false norm_layer=LayerNorm keyword kwargs if pretrained begin comment NOTE my scale was wrong for original weights, leaving this here until I have better on...
def vit_small_patch16_224(pretrained=False, **kwargs): model_kwargs = dict( patch_size=16, embed_dim=768, depth=8, num_heads=8, mlp_ratio=3., qkv_bias=False, norm_layer=nn.LayerNorm, **kwargs) if pretrained: # NOTE my scale was wrong for original weights, leaving this here until I have b...
Python
nomic_cornstack_python_v1
function update_calculator self id_ calc begin if not id_ in __calculators begin return call Err string not_found end set __calculators at id_ = calc return call Ok calc end function
def update_calculator(self, id_: str, calc: Calculator) -> Result[Calculator, str]: if not id_ in self.__calculators: return Err('not_found') self.__calculators[id_] = calc return Ok(calc)
Python
nomic_cornstack_python_v1
function toFlatDict dictvalue begin set keys = keys dictvalue set todelete = list set toadd = dict comment Flat the dict array for key in keys begin if is instance dictvalue at key dict begin set subkeys = dictvalue at key for subkey in subkeys begin set fullsubkey = string %(key)s.%(subkey)s % locals set toadd at fu...
def toFlatDict(dictvalue): keys = dictvalue.keys() todelete = [] toadd = {} # Flat the dict array for key in keys: if isinstance(dictvalue[key],dict): subkeys = dictvalue[key] for subkey in subkeys: fullsubkey = '%(key)s.%(subkey)s' % locals() ...
Python
nomic_cornstack_python_v1
function test_delete_self_authenticated_as_superuser self begin comment Login as normal user set authenticated = call login username=admin at string email password=admin at string password assert true authenticated comment Delete self set delete_url = reverse call get_url_name __name__ string api-profile-delete kwargs=...
def test_delete_self_authenticated_as_superuser(self): # Login as normal user authenticated = self.client.login(username=self.admin['email'], password=self.admin['password']) self.assertTrue(authenticated) # Delete self delete_url = reverse(get_url_name(__name__, 'ap...
Python
nomic_cornstack_python_v1
comment Lists can be nested, that is called matrix set nested_list = list list 0 1 list 10 11 list 100 111 print nested_list comment Use multiple index to refer a specific item print nested_list at 0 nested_list at 1 at 1 comment Create matrix set matrix = list set n = 3 comment Method 1 for i in range n begin set mat...
# Lists can be nested, that is called matrix nested_list = [[0, 1], [10, 11], [100, 111]] print(nested_list) # Use multiple index to refer a specific item print(nested_list[0], nested_list[1][1]) # Create matrix matrix = [] n = 3 # Method 1 for i in range(n): matrix += [[0] * n] print(matrix) # Method 2 matrix...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render , redirect from models import Product , Movie import pdb comment Create your views here. function main request begin return call render request string product/main.html end function function list request begin set product = all set context = dict string product product return call re...
from django.shortcuts import render, redirect from .models import Product, Movie import pdb # Create your views here. def main(request): return render(request, 'product/main.html') def list(request): product = Product.objects.all() context = { 'product': product, } return render(reque...
Python
zaydzuhri_stack_edu_python
string Created on 2019年5月15日 @author: Tree 使用python语言实现决策树中的ID3算法. 要求: 1.按要求补全下面缺失的代码. 2.不用实现剪枝和树的可视化. 3.本次实验的输入、输出、代码内部的数据处理和计算 都用ndarray(numpy).(在本实验中,所有函数输入的数据集,默认最后一列为"标签") 4.写代码的时候可以用"银行贷款数据",最后测试用蘑菇分类数据集. 5.这次实验以个人为单位,每人交一份自己写的代码,星期五晚班长统一发我.(备注好 姓名、班级、学号) 6.参考资料"机器学习实战.pdf",第三章决策树. string 需要用到的包 import math impor...
''' Created on 2019年5月15日 @author: Tree 使用python语言实现决策树中的ID3算法. 要求: 1.按要求补全下面缺失的代码. 2.不用实现剪枝和树的可视化. 3.本次实验的输入、输出、代码内部的数据处理和计算 都用ndarray(numpy).(在本实验中,所有函数输入的数据集,默认最后一列为"标签") 4.写代码的时候可以用"银行贷款数据",最后测试用蘑菇分类数据集. 5.这次实验以个人为单位,每人交一份自己写的代码,星期五晚班长统一发我.(备注好 姓名、班级、学号) 6.参考资料"机器学习实战.pdf",第三章决策树. ''' ''' 需要用到的包 ''' import math ...
Python
zaydzuhri_stack_edu_python
function step_wait self begin set tuple obs_tuple rews news infos = call step_wait set tuple obs_img obs_measure = call process_obs obs_tuple set ret = ret * gamma + rews set obs = call _obfilt obs_img if ret_rms begin update ret_rms ret set rews = call clip rews / square root var + epsilon - cliprew cliprew end return...
def step_wait(self): obs_tuple, rews, news, infos = self.venv.step_wait() obs_img, obs_measure = self.process_obs(obs_tuple) self.ret = self.ret * self.gamma + rews obs = self._obfilt(obs_img) if self.ret_rms: self.ret_rms.update(self.ret) rews = np.clip(r...
Python
nomic_cornstack_python_v1
comment print(type(make_dict)) set name = list string Shirshak string yug string ram string hari set ages = list 21 16 15 12 set counter = 0 for names in name begin set make_dict at names = ages at counter set counter = counter + 1 end print make_dict print string a string b string c print string hello string shirshak ...
#print(type(make_dict)) name=["Shirshak","yug","ram","hari"] ages=[21,16,15,12] counter=0 for names in name: make_dict[names]=ages[counter] counter=counter+1 print(make_dict) print("a","b","c") print ("hello","shirshak") print("hello"+"shirshak")
Python
zaydzuhri_stack_edu_python
import numpy as np import layers class PolicyNet extends object begin string Policy network consisting of two dense layers. function __init__ self input_dim num_actions nhidden=100 begin string Initialize a new network. comment initialize weights and biases set params = dict set params at string W1 = randn nhidden inp...
import numpy as np import layers class PolicyNet(object): """ Policy network consisting of two dense layers. """ def __init__(self, input_dim, num_actions, nhidden=100): """ Initialize a new network. """ # initialize weights and biases self.params = {} ...
Python
zaydzuhri_stack_edu_python
comment This files contains your custom actions which can be used to run comment custom Python code. comment See this guide on how to implement these action: comment https://rasa.com/docs/rasa/core/actions/#custom-actions/ from typing import Any , Text , Dict , List from rasa_sdk import Action , Tracker from rasa_sdk.e...
# This files contains your custom actions which can be used to run # custom Python code. # # See this guide on how to implement these action: # https://rasa.com/docs/rasa/core/actions/#custom-actions/ from typing import Any, Text, Dict, List from rasa_sdk import Action, Tracker from rasa_sdk.executor import Collecti...
Python
zaydzuhri_stack_edu_python
function clear cls fn begin if has attribute fn CACHE_VAR begin delete attribute fn CACHE_VAR end end function
def clear(cls, fn: AnyFunction): if hasattr(fn, cls.CACHE_VAR): delattr(fn, cls.CACHE_VAR)
Python
nomic_cornstack_python_v1
function setup hass config begin from influxdb import InfluxDBClient , exceptions if not call validate_config config dict DOMAIN list string host CONF_USERNAME CONF_PASSWORD _LOGGER begin return false end set conf = config at DOMAIN set host = conf at CONF_HOST set port = call convert get conf CONF_PORT int DEFAULT_POR...
def setup(hass, config): from influxdb import InfluxDBClient, exceptions if not validate_config(config, {DOMAIN: ['host', CONF_USERNAME, CONF_PASSWORD]}, _LOGGER): return False conf = config[DOMAIN] host...
Python
nomic_cornstack_python_v1
import tkinter as tk from tkinter import ttk set root = call Tk title root string Quotes Table comment create a table of quote objects set tree = call Treeview root columns=list string name string quote show=string headings call column string name width=100 anchor=string w call heading string name text=string Name call...
import tkinter as tk from tkinter import ttk root = tk.Tk() root.title('Quotes Table') # create a table of quote objects tree = ttk.Treeview(root, columns=['name', 'quote'], show = 'headings') tree.column('name', width=100, anchor='w') tree.heading('name', text='Name') tree.column('quote', width=300, anchor='w') tr...
Python
jtatman_500k
function save self begin comment Save the GUI state version. call _save_global call _save_local end function
def save(self): # Save the GUI state version. self._save_global() self._save_local()
Python
nomic_cornstack_python_v1
comment https://github.com/orisano/owiener import owiener set c = 0 set e = 0 set N = 0 set d = call attack e N if d is none begin print string Failed end else begin print format string Hacked d={} d end set dec = power c d N set dx = hexadecimal dec at slice 2 : : set msg = list for i in range 0 length ds 2 begin s...
import owiener #https://github.com/orisano/owiener c = 0 e = 0 N = 0 d = owiener.attack(e, N) if d is None: print("Failed") else: print("Hacked d={}".format(d)) dec = pow(c, d, N) dx = hex(dec)[2:] msg = [] for i in range(0, len(ds), 2): c = chr(int(dx[i:i+2], 16)) # print(ds[i:i+2]) # print(c)...
Python
zaydzuhri_stack_edu_python
function _auto_fill_metrics self result begin set current_time = time set current_datetime = now if TIME_THIS_ITER_S in result begin set time_this_iter = result at TIME_THIS_ITER_S end else begin set time_this_iter = current_time - last_report_time end set iteration = iteration + 1 set time_total = time_total + time_th...
def _auto_fill_metrics(self, result: dict) -> dict: current_time = time.time() current_datetime = datetime.now() if TIME_THIS_ITER_S in result: time_this_iter = result[TIME_THIS_ITER_S] else: time_this_iter = current_time - self.last_report_time self.itera...
Python
nomic_cornstack_python_v1
function sum_list l begin string This function returns the sum of all the values in a list set sum = 0 for val in l begin set sum = sum + val end return sum end function
def sum_list(l): '''This function returns the sum of all the values in a list''' sum = 0 for val in l: sum = sum + val return sum
Python
jtatman_500k
if a < 0 or a > 23 begin print string Hora inválida end else if a > 3 and a < 12 begin print string Bom dia end else if a >= 12 and a < 18 begin print string Boa tarde end else begin print string boa noite end
if a<0 or a>23: print('Hora inválida') else: if a>3 and a<12: print('Bom dia') elif a>=12 and a<18: print('Boa tarde') else: print('boa noite')
Python
zaydzuhri_stack_edu_python
import math function masses_from_file begin return list comprehension integer line for line in read lines open string input end function function fuel_for mass begin return floor mass / 3 - 2 end function function total_fuel_for mass total=0 begin set fuel = call fuel_for mass if fuel <= 0 begin return total end return...
import math def masses_from_file(): return [int(line) for line in open('input').readlines()] def fuel_for(mass): return math.floor(mass / 3) - 2 def total_fuel_for(mass, total=0): fuel = fuel_for(mass) if fuel <= 0: return total return total_fuel_for(fuel, total + fuel) def required_fuel...
Python
zaydzuhri_stack_edu_python
function test_list_date_max_length_nistxml_sv_iv_list_date_max_length_1_2 mode save_output output_format begin call assert_bindings schema=string nistData/list/date/Schema+Instance/NISTSchema-SV-IV-list-date-maxLength-1.xsd instance=string nistData/list/date/Schema+Instance/NISTXML-SV-IV-list-date-maxLength-1-2.xml cla...
def test_list_date_max_length_nistxml_sv_iv_list_date_max_length_1_2(mode, save_output, output_format): assert_bindings( schema="nistData/list/date/Schema+Instance/NISTSchema-SV-IV-list-date-maxLength-1.xsd", instance="nistData/list/date/Schema+Instance/NISTXML-SV-IV-list-date-maxLength-1-2.xml", ...
Python
nomic_cornstack_python_v1
function randGaussianV2 mean stdev coveigen datasize nData begin from numpy import random , diag comment mean and standard deviation set tuple mu sigma = tuple call matrix mean call matrix stdev comment generate random samples from normal (gaussian) => normalized independent Gaussian random variables set R = call matri...
def randGaussianV2(mean,stdev,coveigen,datasize,nData): from numpy import random, diag mu, sigma = matrix(mean), matrix(stdev) # mean and standard deviation R = matrix(random.randn(int(datasize), nData)) # generate random samples from normal (gaussian) => normalized independent Gaussian random variab...
Python
nomic_cornstack_python_v1
function get_subgraph self v=none hop=none begin if v == none begin set v = source_node end if hop == none begin set hop = _obs_hop end set n_hop_tree = call dfs_tree graph v hop set _current_subgraph = call subgraph graph n_hop_tree return _current_subgraph end function
def get_subgraph(self, v=None, hop=None): if v == None: v = self.source_node if hop == None: hop = self._obs_hop n_hop_tree = nx.dfs_tree(self.graph, v, hop) self._current_subgraph = nx.subgraph(self.graph, n_hop_tree) return self._current_subgraph
Python
nomic_cornstack_python_v1
function response_delete request obj_display begin return call HttpResponseRedirect reverse string admin:establishment_system end function
def response_delete(request, obj_display): return HttpResponseRedirect(reverse('admin:establishment_system'))
Python
nomic_cornstack_python_v1
function check_standard_unique self begin set standard_search = search list tuple string standard_id string = id tuple string division_id string = id tuple string school_id string = id tuple string id string not in ids if standard_search begin raise call ValidationError call _ string La division et la classe doivent êt...
def check_standard_unique(self): standard_search = self.env['school.standard' ].search([('standard_id', '=', self.standard_id.id), ('division_id', '=', ...
Python
nomic_cornstack_python_v1
comment A substring is a contiguous (non-empty) sequence of characters within a comment string. comment A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', comment 'o', and 'u') and has all five vowels present in it. comment Given a string word, return the number of vowel substrings in word. c...
# A substring is a contiguous (non-empty) sequence of characters within a # string. # # A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', # 'o', and 'u') and has all five vowels present in it. # # Given a string word, return the number of vowel substrings in word. # # # Example ...
Python
zaydzuhri_stack_edu_python
function test_urole_remove self begin comment Add a user-defined User for our tests set user2 = dict string name string user2 ; string description string User #2 ; string type string standard ; string authentication-type string local ; string password string bla ; string password-rule-uri string /api/console/password-r...
def test_urole_remove(self): # Add a user-defined User for our tests user2 = { 'name': 'user2', 'description': 'User #2', 'type': 'standard', 'authentication-type': 'local', 'password': 'bla', 'password-rule-uri': '/api/console/pas...
Python
nomic_cornstack_python_v1
import yaml from appium.webdriver.webdriver import WebDriver from selenium.webdriver.common.by import By from selenium.webdriver.remote.webelement import WebElement from po_test_hysapp.driver.hysClient import HysClient from datetime import datetime import allure import os import logging import time class HysBase extend...
import yaml from appium.webdriver.webdriver import WebDriver from selenium.webdriver.common.by import By from selenium.webdriver.remote.webelement import WebElement from po_test_hysapp.driver.hysClient import HysClient from datetime import datetime import allure import os import logging import time class HysBase(obje...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: import math set l = list 2 3 for i in range 5 101 begin for j in range 2 integer square root i + 1 begin if i % j == 0 begin break end end for else begin append l i end end print join string map str l comment In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[1]: import math l=[2,3] for i in range(5,101): for j in range(2,int(math.sqrt(i))+1): if i%j==0: break else: l.append(i) print(" ".join(map(str,l))) # In[ ]:
Python
zaydzuhri_stack_edu_python
from typing import List class Node begin function __init__ self data begin set data = data set next_node = none end function function __repr__ self begin return data end function end class class LinkedList begin function __init__ self nodes=none begin set head = none if nodes is not none begin set node = call Node data...
from typing import List class Node: def __init__(self, data)-> None: self.data = data self.next_node = None def __repr__(self) -> str: return self.data class LinkedList: def __init__(self, nodes=None) -> None: self.head = None if nodes is not None: ...
Python
zaydzuhri_stack_edu_python
function get_val var begin if is instance var TensorVariable begin return test_value end if is instance var TensorConstant begin return value end if is instance var SharedVariable begin return call get_value end return var end function
def get_val(var): if isinstance(var, tt.TensorVariable): return var.tag.test_value if isinstance(var, tt.TensorConstant): return var.value if isinstance(var, tt.SharedVariable): return var.get_value() return(var)
Python
nomic_cornstack_python_v1
function first_of deps begin call mark_hidden deps decorator call datasource deps function inner broker begin for c in deps begin if c in broker begin return broker at c end end end function return inner end function
def first_of(deps): dr.mark_hidden(deps) @datasource(deps) def inner(broker): for c in deps: if c in broker: return broker[c] return inner
Python
nomic_cornstack_python_v1