code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function factorial n begin if n == 0 or n == 1 begin return 1 end else begin set result = 1 for item in range 2 n + 1 begin set result = result * item end end return result end function try begin set number = integer input string Give number: end except ValueError begin print string This is not a number end try else be...
def factorial(n): if n == 0 or n == 1: return 1 else: result = 1 for item in range(2, n + 1): result = result * item return result try: number = int(input("Give number:")) except ValueError: print("This is not a number") else: print(factorial(number))
Python
zaydzuhri_stack_edu_python
class Field begin string Base class for all fields function __init__ self name begin set name = name set children = list set bit_position = - 1 end function function name self begin return name end function function get_bit_position self begin return bit_position end function function set_bit_position self pos begin s...
class Field: """ Base class for all fields """ def __init__(self, name): self.name = name self.children = [] self.bit_position = -1 def name(self): return self.name def get_bit_position(self): return self.bit_position def set_bit_position(self, pos): ...
Python
zaydzuhri_stack_edu_python
function access_GitHubRepoCommits self begin return call access_GitHubAPISpecificEndpoint endpoint=string /commits?state=all end function
def access_GitHubRepoCommits(self) -> dict: return self.access_GitHubAPISpecificEndpoint(endpoint="/commits?state=all")
Python
nomic_cornstack_python_v1
function visit_Call self node begin string Visit a function call. We expect every logging statement and string format to be a function call. comment CASE 1: We're in a logging statement if call within_logging_statement begin if call within_logging_argument and call is_format_call node begin append violations tuple node...
def visit_Call(self, node): """ Visit a function call. We expect every logging statement and string format to be a function call. """ # CASE 1: We're in a logging statement if self.within_logging_statement(): if self.within_logging_argument() and self.is_for...
Python
jtatman_500k
comment Uses python3 import sys set visited = list set Ccum = list function reach adj x y begin comment write your code here global visited global Ccum set visited = list false * length adj set Ccum = list 0 * length adj set cc = 1 for tuple i v in enumerate adj begin if length adj at i == 0 begin continue end else if ...
# Uses python3 import sys visited = list() Ccum = list() def reach(adj, x, y): # write your code here global visited global Ccum visited = [False] * len(adj) Ccum = [0] * len(adj) cc = 1 for i, v in enumerate(adj): if len(adj[i]) == 0: continue else: ...
Python
zaydzuhri_stack_edu_python
function large_power base exponent begin if base ^ exponent > 5000 begin return true end else begin return false end end function function over_budget budget food_bill electricity_bill internet_bill rent begin if budget < food_bill + electricity_bill + internet_bill + rent begin return true end else begin return false ...
def large_power(base, exponent): if (base**exponent > 5000) : return True else : return False def over_budget(budget, food_bill, electricity_bill, internet_bill, rent) : if (budget < (food_bill + electricity_bill + internet_bill + rent)) : return True else : return F...
Python
zaydzuhri_stack_edu_python
import json comment Example JSON object set json_obj = string {"Name": "John Smith", "Age": 30, "City": "New York"} comment Convert JSON to Python dictionary with lowercase keys set py_dict = loads lower json_obj comment Sum all integer values in the dictionary set int_sum = sum list comprehension v for v in values py_...
import json # Example JSON object json_obj = '{"Name": "John Smith", "Age": 30, "City": "New York"}' # Convert JSON to Python dictionary with lowercase keys py_dict = json.loads(json_obj.lower()) # Sum all integer values in the dictionary int_sum = sum([v for v in py_dict.values() if isinstance(v, int)]) # Sort keys in...
Python
jtatman_500k
function print_image picture_array begin for pixelsArray in picture_array begin for pixel in pixelsArray begin if pixel begin print string * end=string end else begin print string end=string end end print string end end function call print_image picture call print_image picture call print_image picture print print_ima...
def print_image(picture_array): for pixelsArray in picture_array: for pixel in pixelsArray: if pixel: print('*', end='') else: print(' ', end='') print(' ') print_image(picture) print_image(picture) print_image(picture) print(print_image) pri...
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np set img = call imread string /home/nitolapio/Escritorio/Programación/Machine Learning/OpenCV/Resources/cards.jpg comment Con esto convertimos un elemento torcido en un elemento plano set tuple width height = tuple 250 350 comment Los puntos donde tenemos el cortante de la carta set pts1 = ...
import cv2 import numpy as np img = cv2.imread("/home/nitolapio/Escritorio/Programación/Machine Learning/OpenCV/Resources/cards.jpg") # Con esto convertimos un elemento torcido en un elemento plano width, height = 250, 350 pts1 = np.float32([[204, 215], [317, 217], [193, 368], [309, 369]]) # Los puntos donde tenem...
Python
zaydzuhri_stack_edu_python
function user_logout request begin from django.contrib.auth import logout call logout request return call HttpResponseRedirect string /rapid/login/ end function
def user_logout(request): from django.contrib.auth import logout logout(request) return HttpResponseRedirect('/rapid/login/')
Python
nomic_cornstack_python_v1
string Written by 17075800 from run import app import unittest import sqlite3 from base import BaseTestCase comment 1.Ensuring correct loading of basic pages and login required pages class LoadPageTest extends BaseTestCase begin comment 1.1.Ensuring correct loading of basic pages comment Ensure Index page loads correct...
""" Written by 17075800 """ from run import app import unittest import sqlite3 from base import BaseTestCase # 1.Ensuring correct loading of basic pages and login required pages class LoadPageTest(BaseTestCase): # 1.1.Ensuring correct loading of basic pages # Ensure Index page loads correctly ...
Python
zaydzuhri_stack_edu_python
function get_intro_prompt self begin string Print cabin mode message set sys_status = open help_path + string cabin.txt string r set server_msg = read sys_status return server_msg + call colorize string psiTurk version + version_number + string Type "help" for more information. string green false end function
def get_intro_prompt(self): ''' Print cabin mode message ''' sys_status = open(self.help_path + 'cabin.txt', 'r') server_msg = sys_status.read() return server_msg + colorize('psiTurk version ' + version_number + '\nType "help" for more information.', ...
Python
jtatman_500k
function set_SinceId self value begin call _set_input string SinceId value end function
def set_SinceId(self, value): super(RetrieveUserDashboardInputSet, self)._set_input('SinceId', value)
Python
nomic_cornstack_python_v1
function true begin global loop_start_time set loop_start_time = now return true end function
def true(): global loop_start_time loop_start_time = datetime.datetime.now() return True
Python
nomic_cornstack_python_v1
from numpy import * comment code jam 2012, question B. set filename = string B-large.in.txt set FILE = open filename string r set N = integer read line FILE for k in range N begin set T = map int split read line FILE set n = T at 0 set s = T at 1 set p = T at 2 set T = T at slice 3 : : comment print n,s,p,T comment T...
from numpy import* ## code jam 2012, question B. filename = "B-large.in.txt" FILE = open(filename, "r") N = int(FILE.readline()) for k in range(N): T = map(int, FILE.readline().split()) n = T[0] s = T[1] p = T[2] T = T[3:] #print n,s,p,T # T is now list of total scores... num1 = 0 ...
Python
zaydzuhri_stack_edu_python
import string import sys import codecs comment Reading data and obtaining the array of data function readData fileName begin set f = open fileName encoding=string utf-8 for line in f begin set data = join string list comprehension strip l for l in split line comment Cleaning data set translator = call maketrans string...
import string import sys import codecs # Reading data and obtaining the array of data def readData(fileName): f = codecs.open(fileName, encoding='utf-8') for line in f: data = ' '.join([l.strip() for l in line.split()]) # Cleaning data translator = str.maketrans('','',string.punctuatio...
Python
zaydzuhri_stack_edu_python
function move_to self file_name to_dir change_name_to=none begin call _check_filename file_name set src = join posixpath LOCAL_DIR file_name set file_name = if expression change_name_to is none then file_name else change_name_to set dest = join posixpath root to_dir file_name print string --> Moving file { src } to { d...
def move_to(self, file_name, to_dir, change_name_to=None): self._check_filename(file_name) src = posixpath.join(server_setup.LOCAL_DIR, file_name) file_name = file_name if change_name_to is None else change_name_to dest = posixpath.join(self.root, to_dir, file_name) print(f"--> M...
Python
nomic_cornstack_python_v1
string Evander Nyoni, March 28, 2019 This module contains all the functions for preprocessing the data, detecting faces in the input image and making prediction. soucre: https://www.pyimagesearch.com/2018/06/18/face-recognition-with-opencv-python-and-deep-learning/ comment import packages import cv2 import face_recogni...
""" Evander Nyoni, March 28, 2019 This module contains all the functions for preprocessing the data, detecting faces in the input image and making prediction. soucre: https://www.pyimagesearch.com/2018/06/18/face-recognition-with-opencv-python-and-deep-learning/ """ # import packages import cv2 import face_recogn...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment import the opencv library import cv2 import serial import time import numpy as np import skfuzzy as fuzz from skfuzzy import control as ctrl class fuzzy_control begin function __init__ self cols rows begin set x = cols set y = rows set position_y = call Antecedent array range 0 y +...
#!/usr/bin/env python3 # import the opencv library import cv2 import serial import time import numpy as np import skfuzzy as fuzz from skfuzzy import control as ctrl class fuzzy_control: def __init__(self, cols,rows): self.x = cols self.y = rows self.position_y = ctrl.Antecedent(np.a...
Python
zaydzuhri_stack_edu_python
string Airport class holds attributes of the airport object class Airport begin comment constructor function __init__ self id name country city lat long begin set id = integer id set name = name set country = country set city = city set lat = decimal lat set long = decimal long end function function __str__ self begin ...
'''Airport class holds attributes of the airport object''' class Airport: def __init__(self, id, name, country, city, lat, long): #constructor self.id = int(id) self.name = name self.country = country self.city = city self.lat = float(lat) se...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: UTF-8 -*- import os set pwd = absolute path path string . comment 返回文件名 print base name path string D:\practice comment 返回目录路径 print directory name path string D:\practice comment 分割文件名与路径 print split path string D:\practice comment 将目录和文件名合成一个路径 print join path string root ...
#!/usr/bin/python # -*- coding: UTF-8 -*- import os pwd = os.path.abspath('.') print( os.path.basename('D:\practice') ) # 返回文件名 print( os.path.dirname('D:\practice') ) # 返回目录路径 print( os.path.split('D:\practice') ) # 分割文件名与路径 print( os.path.join('root','test','D:\practice') ) # 将目录和文件名合成一个路径
Python
zaydzuhri_stack_edu_python
function n_components self begin set to_ret = length components return to_ret end function
def n_components(self): to_ret = len(self.components) return to_ret
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from onetimequeue import onetimequeue if __name__ == string __main__ begin set q = call onetimequeue append q 3 append q 4 append q 3 append q 5 end
#!/usr/bin/env python from onetimequeue import onetimequeue if __name__ == '__main__': q = onetimequeue() q.append(3) q.append(4) q.append(3) q.append(5)
Python
zaydzuhri_stack_edu_python
import requests from pokedex import db class Pokemon extends Model begin set id = call Column Integer primary_key=true set name = call Column call String 30 unique=true nullable=false set type_1 = call Column call String 15 nullable=false set type_2 = call Column call String 15 set abilities = call Column call String 3...
import requests from pokedex import db class Pokemon(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30), unique=True, nullable=False) type_1 = db.Column(db.String(15), nullable=False) type_2 = db.Column(db.String(15)) abilities = db.Column(db.String(30), nullabl...
Python
zaydzuhri_stack_edu_python
string 5 3 1 2 5 4 3 5 5 6 6 5 set tuple N K = map int split input set A = list map int split input set B = list map int split input while K > 0 begin set min_a = 0 set max_b = 0 for i in range N begin if A at min_a > A at i begin set min_a = i end if B at max_b < B at i begin set max_b = i end end if A at min_a >= B a...
""" 5 3 1 2 5 4 3 5 5 6 6 5 """ N, K = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) while K > 0: min_a = max_b = 0 for i in range(N): if A[min_a] > A[i]: min_a = i if B[max_b] < B[i]: max_b = i if A[min_a] >= B[...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import requests function scrape begin set link_list = list set r = get requests string https://ditkalamazoo.squarespace.com/shows for line in split text string begin if string href="http://www.google.com/calendar/event?action=TEMPLATE in line begin append link_list line end end return lin...
#!/usr/bin/env python3 import requests def scrape(): link_list = [] r = requests.get("https://ditkalamazoo.squarespace.com/shows") for line in r.text.split('\n'): if 'href="http://www.google.com/calendar/event?action=TEMPLATE' in line: link_list.append(line) return link_list
Python
zaydzuhri_stack_edu_python
function __sub__ self other begin return call call _handle_type other value - value end function
def __sub__(self, other): return self._handle_type(other)(self.value - other.value)
Python
nomic_cornstack_python_v1
function make_pw_hash name password salt=none begin if not salt begin set salt = call make_salt end set pw_hash = hex digest sha256 name + password + salt return string %s,%s % tuple pw_hash salt end function
def make_pw_hash(name, password, salt=None): if not salt: salt = make_salt() pw_hash = hashlib.sha256(name + password + salt).hexdigest() return '%s,%s' % (pw_hash, salt)
Python
nomic_cornstack_python_v1
function remove_work self key begin if call __find_work__ key == true begin set work = __work_list__ at key del __work_list__ at key return work end else begin return none end end function
def remove_work(self, key): if self.__find_work__(key) == True: work = self.__work_list__[key] del self.__work_list__[key] return(work) else: return(None)
Python
nomic_cornstack_python_v1
function _aggregate data norm=true sort_by=string value keys=none begin string Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non-redundant list of v...
def _aggregate(data, norm=True, sort_by='value', keys=None): ''' Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non...
Python
jtatman_500k
comment !/usr/bin/env python comment coding=utf-8 from Tkinter import Button from pgconfig import PConfig from Tkinter import Frame class PButton extends Button PConfig begin function __init__ self master=none title=string command=none begin call __init__ self master=master text=title command=command set __name = titl...
#!/usr/bin/env python # coding=utf-8 from Tkinter import Button from pgconfig import PConfig from Tkinter import Frame class PButton(Button, PConfig): def __init__(self, master=None, title='', command=None): Button.__init__(self, master=master, text=title, command=command) self.__name = title ...
Python
zaydzuhri_stack_edu_python
function domain_finder link begin import string set dot_splitter = split link string . set seperator_first = 0 if string // in dot_splitter at 0 begin set seperator_first = find dot_splitter at 0 string // + 2 end set seperator_end = string for i in dot_splitter at 2 begin if i in punctuation begin set seperator_end =...
def domain_finder(link): import string dot_splitter = link.split('.') seperator_first = 0 if '//' in dot_splitter[0]: seperator_first = (dot_splitter[0].find('//') + 2) seperator_end = '' for i in dot_splitter[2]: if i in string.punctuation: seperator_end = i ...
Python
zaydzuhri_stack_edu_python
function get self id begin set args = call parse_args return call search_associations subject_category=string phenotype object_category=string variant invert_subject_object=true subject=id subject_direct=direct object_taxon=taxon object_taxon_direct=direct_taxon user_agent=USER_AGENT keyword args end function
def get(self, id): args = core_parser_with_filters.parse_args() return search_associations( subject_category='phenotype', object_category='variant', invert_subject_object=True, subject=id, subject_direct=args.direct, object_taxon=ar...
Python
nomic_cornstack_python_v1
function activate self begin comment Send command call command string FRAMEBUFFER _id true comment Associate canvas now set canvas = call get_current_canvas if canvas is not none begin call associate glir end end function
def activate(self): # Send command self._glir.command('FRAMEBUFFER', self._id, True) # Associate canvas now canvas = get_current_canvas() if canvas is not None: canvas.context.glir.associate(self.glir)
Python
nomic_cornstack_python_v1
function post self request begin if method == string POST begin set form = call form POST if call is_valid begin call create_user cleaned_data at string username cleaned_data at string email cleaned_data at string password first_name=cleaned_data at string first_name last_name=cleaned_data at string last_name set usern...
def post(self, request): if request.method == 'POST': form = self.form(request.POST) if form.is_valid(): User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], f...
Python
nomic_cornstack_python_v1
function list_services request step begin string get the activated services added from the administrator :param request: request object :param step: the step which is proceeded :type request: HttpRequest object :type step: string :return the activated services added from the administrator set all_datas = list if step ...
def list_services(request, step): """ get the activated services added from the administrator :param request: request object :param step: the step which is proceeded :type request: HttpRequest object :type step: string :return the activated services added from the adm...
Python
jtatman_500k
class Room extends Model begin set number = call IntegerField set size = call IntegerField set bed_type = call CharField max_length=20 end class class Booking extends Model begin set start_date = call DateField set end_date = call DateField set guest_name = call CharField max_length=50 set room = call ForeignKey Room o...
class Room(models.Model): number = models.IntegerField() size = models.IntegerField() bed_type = models.CharField(max_length=20) class Booking(models.Model): start_date = models.DateField() end_date = models.DateField() guest_name = models.CharField(max_length=50) room = models.ForeignKey(R...
Python
jtatman_500k
function manipulability self q=none J=none begin if J is none begin if q is not none begin set q = call getvector q n set J = call jacob0 q end else begin raise call ValueError string One of q or J must be supplied end end else begin call verifymatrix J tuple 6 n end return square root call det J @ transpose np J end f...
def manipulability(self, q=None, J=None): if J is None: if q is not None: q = getvector(q, self.n) J = self.jacob0(q) else: raise ValueError('One of q or J must be supplied') else: verifymatrix(J, (6, self.n)) ...
Python
nomic_cornstack_python_v1
import numpy as np import cv2 from sklearn.cluster import DBSCAN set debug = 0 class CellDetector extends object begin function __init__ self begin pass end function function Detect self frame begin set gray = call cvtColor frame COLOR_BGR2GRAY set debug = 0 comment debug = 1 if debug == 1 begin image show string gray ...
import numpy as np import cv2 from sklearn.cluster import DBSCAN debug = 0 class CellDetector(object): def __init__(self): pass def Detect(self, frame): gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) debug = 0 # debug = 1 if (debug == 1): cv2.imshow('gray...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd from sklearn.model_selection import cross_val_score from sklearn.preprocessing import LabelEncoder , StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.ensemble import BaggingClassifier from sklearn.metrics import precision_score , accuracy_score set mlp ...
import numpy as np import pandas as pd from sklearn.model_selection import cross_val_score from sklearn.preprocessing import LabelEncoder, StandardScaler from sklearn.neural_network import MLPClassifier from sklearn.ensemble import BaggingClassifier from sklearn.metrics import precision_score, accuracy_score mlp ...
Python
zaydzuhri_stack_edu_python
comment Histogram comment Find and display histogram of frequency of numbers in a given list set lt = list 35 5 10 5 20 10 5 20 print string The given list is: lt set d = dict comment Storing Frequency : each number as key and frequency as its value for s in lt begin if s in keys d begin set d at s = d at s + 1 end el...
#Histogram #Find and display histogram of frequency of numbers in a given list lt = [35,5,10,5,20,10,5,20] print("The given list is: ",lt) d={} #Storing Frequency : each number as key and frequency as its value for s in lt: if( s in d.keys()): d[s]=d[s]+1 else: d[s]=1 pri...
Python
zaydzuhri_stack_edu_python
import sys set stdin = open string input.txt string r set stdout = open string output.txt string w set N = integer input set x1 = 0 if N > 0 begin if N % 2 == 0 begin print string YES print N + 2 end else begin print string NO print N + 1 end end else if N == 0 begin if N == 0 begin print string NO print N + 2 end end ...
import sys sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') N = int(input()) x1 = 0 if N > 0: if N % 2 == 0: print('YES') print(N + 2) else: print('NO') print(N + 1) elif N == 0: if N == 0: print('NO') print(N+2) elif N < 0: print('...
Python
zaydzuhri_stack_edu_python
function list_locks root=none begin set locks = dict set _locks = if expression root then join path root call relpath LOCKS sep else LOCKS try begin with call fopen _locks as fhr begin set items = split call to_unicode read fhr string for meta in list comprehension split item string for item in items begin set lock = ...
def list_locks(root=None): locks = {} _locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS try: with salt.utils.files.fopen(_locks) as fhr: items = salt.utils.stringutils.to_unicode(fhr.read()).split("\n\n") for meta in [item.split("\n") for ite...
Python
nomic_cornstack_python_v1
import discord class BotSystem begin function __init__ self begin set pError = string ```[権限エラー] todo:reload を実行する権限が有りません``` end function function is_exist_logch self ctx begin return get utils channels name=string bot-log end function function is_admin self ctx begin return author in list comprehension i for i in mem...
import discord class BotSystem(): def __init__(self): self.pError = '```[権限エラー] todo:reload を実行する権限が有りません```' def is_exist_logch(self,ctx): return discord.utils.get(ctx.guild.channels, name='bot-log') def is_admin(self,ctx): return ctx.author in [i for i in ctx.guild.member...
Python
zaydzuhri_stack_edu_python
for _ in range N begin set tuple t x y = map int split input append schedule tuple t x y end for i in range N begin set _t = absolute schedule at i at 0 - schedule at i + 1 at 0 set _x = absolute schedule at i at 1 - schedule at i + 1 at 1 set _y = absolute schedule at i at 2 - schedule at i + 1 at 2 set time = _t set ...
for _ in range(N): t, x, y = map(int, input().split()) schedule.append((t, x, y)) for i in range(N): _t = abs(schedule[i][0] - schedule[i+1][0]) _x = abs(schedule[i][1] - schedule[i+1][1]) _y = abs(schedule[i][2] - schedule[i+1][2]) time = _t distance = _x + _y if time < distance: ...
Python
zaydzuhri_stack_edu_python
from numpy import * set vet = zeros 6 set a = array eval input string dias de falta: for i in range size a begin if a at i == 2 begin set vet at 0 = vet at 0 + 1 end else if a at i == 3 begin set vet at 1 = vet at 1 + 1 end else if a at i == 4 begin set vet at 2 = vet at 2 + 1 end else if a at i == 5 begin set vet at 3...
from numpy import* vet=zeros(6) a=array(eval(input("dias de falta: "))) for i in range(size(a)): if(a[i]==2): vet[0]=vet[0]+1 elif(a[i]==3): vet[1]=vet[1]+1 elif(a[i]==4): vet[2]=vet[2]+1 elif(a[i]==5): vet[3]=vet[3]+1 elif(a[i]==6): vet[4]=vet[4]+1 elif(a[i]==7): vet[5]=vet[5]+1 b=sum(vet) for a in...
Python
zaydzuhri_stack_edu_python
function V_magVenus_2 alpha a_p d begin set V = 5.0 * call log10 a_p * d + 236.05828 - 2.81914 * alpha + 0.00839034 * alpha ^ 2.0 return V end function
def V_magVenus_2(alpha, a_p, d): V = 5.*np.log10(a_p*d) + 236.05828 - 2.81914e-00*alpha + 8.39034e-03*alpha**2. return V
Python
nomic_cornstack_python_v1
function bytes self begin return bytes dumps json self encoding=MESSAGE_ENCODING end function
def bytes(self): return bytes(json.dumps(self.json()), encoding=self.__class__.MESSAGE_ENCODING)
Python
nomic_cornstack_python_v1
import json import scraper function saveAsJSON filename lib begin set f = open filename string w write f dumps lib sort_keys=true indent=4 close f end function function readJSON filename begin set f = open filename string r comment dictionary set data = load json f comment Checking content set mandatory_keys = list str...
import json import scraper def saveAsJSON(filename, lib): f = open(filename, "w") f.write(json.dumps(lib, sort_keys=True, indent=4)) f.close() def readJSON(filename): f = open(filename, "r") data = json.load(f) #dictionary # Checking content mandatory_keys = ['lunch', 'dinner'] for ke...
Python
zaydzuhri_stack_edu_python
function test_shunt_shunt_states self begin comment Check shape. assert equal shape tuple num_scenarios expected_shunts comment Ensure the "on" percentage is fairly close (say, within 5%). set on_pct = sum / num_scenarios * expected_shunts call assertGreaterEqual on_pct shunt_closed_probability - 0.05 call assertLessEq...
def test_shunt_shunt_states(self): # Check shape. self.assertEqual(self.env.shunt_states.shape, (self.num_scenarios, self.expected_shunts)) # Ensure the "on" percentage is fairly close (say, within 5%). on_pct = self.env.shunt_states.sum().sum() \ / ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python # -*- coding: utf-8 -* function feibo n begin comment 递归版本 if n == 0 begin return 0 end if n == 1 begin return 1 end if n >= 2 begin return call feibo n - 1 + call feibo n - 2 end end function function fib n begin comment 用字典存储 set d = dict if n == 0 begin set d at n = 0 return 0 end if n ...
#!/usr/bin/env python # -*- coding: utf-8 -* def feibo(n): # 递归版本 if n == 0: return 0 if n == 1: return 1 if n >= 2: return feibo(n-1) + feibo(n-2) def fib(n): # 用字典存储 d = {} if n == 0: d[n] = 0 return 0 if n == 1: d[n] = 1 r...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import math import random as rand import matplotlib.animation as anim comment constants: set text = 100 set x_min = 0 set x_max = 10 set t_max = 10000 set dt = 0.01 set init_random = 0.1 set heat_constant = 101 set temp_max = 0 comment setting up initial conditions: se...
import numpy as np import matplotlib.pyplot as plt import math import random as rand import matplotlib.animation as anim #constants: text=100 x_min=0 x_max=10 t_max=10000 dt=0.01 init_random=0.1 heat_constant=101 temp_max=0 #setting up initial conditions: x=[] y=[] s=float(0) for i in range(x_...
Python
zaydzuhri_stack_edu_python
function load self context begin string Returns the debugger plugin, if possible. Args: context: The TBContext flags including `add_arguments`. Returns: A DebuggerPlugin instance or None if it couldn't be loaded. if not debugger_data_server_grpc_port > 0 or debugger_port > 0 begin return none end set flags = flags try ...
def load(self, context): """Returns the debugger plugin, if possible. Args: context: The TBContext flags including `add_arguments`. Returns: A DebuggerPlugin instance or None if it couldn't be loaded. """ if not (context.flags.debugger_data_server_grpc_port > 0 or context.f...
Python
jtatman_500k
function AUC output target classID1=0 classID2=1 begin comment sorting index according to output set idx = sort index output comment number positives set np = count target classID1 comment number negatives set nn = count target classID2 comment true and false positives set tuple tp fp = tuple 0.0 0.0 comment old pos of...
def AUC(output, target, classID1=0, classID2=1): idx = sort_index(output) # sorting index according to output np = target.count(classID1) # number positives nn = target.count(classID2) # number negatives tp, fp = 0.0, 0.0 # true and false positives ox, oy = 0.0, 0.0 # old...
Python
nomic_cornstack_python_v1
function postinit self lower=none upper=none step=none begin string Do some setup after initialisation. :param lower: The lower index in the slice. :value lower: NodeNG or None :param upper: The upper index in the slice. :value upper: NodeNG or None :param step: The step to take between index. :param step: NodeNG or No...
def postinit(self, lower=None, upper=None, step=None): """Do some setup after initialisation. :param lower: The lower index in the slice. :value lower: NodeNG or None :param upper: The upper index in the slice. :value upper: NodeNG or None :param step: The step to take...
Python
jtatman_500k
function get_interfaces_description device interface=none begin try begin set out = parse device format string show interfaces descriptions {interface} interface=interface end except SchemaEmptyParserError as e begin return none end comment Sample output comment { comment "interface-information": { comment "physical-in...
def get_interfaces_description(device, interface=None): try: out = device.parse('show interfaces descriptions {interface}'.format( interface=interface )) except SchemaEmptyParserError as e: return None # Sample output # { # "interface-information": { ...
Python
nomic_cornstack_python_v1
function test_v1 self begin set api_data = call MockAPIData dict string revenue_budget_actual_v1 list dict string item.code string 1300 ; string amount.sum 200 ; string financial_year_end.year 2050 ; string amount_type.code string ORGB dict string item.code string 1300 ; string amount.sum 210 ; string financial_year_en...
def test_v1(self): api_data = MockAPIData( { "revenue_budget_actual_v1": [ { "item.code": "1300", "amount.sum": 200, "financial_year_end.year": 2050, "amount_type.code"...
Python
nomic_cornstack_python_v1
for i in n begin if i not in a begin append a i end end print length a
for i in n: if i not in a: a.append(i) print(len(a))
Python
zaydzuhri_stack_edu_python
function _generate iterable base_value modifier=tuple begin for c in iterable begin yield tuple c tuple base_value modifier set base_value = base_value + 1 end end function
def _generate(iterable, base_value, modifier=()): for c in iterable: yield (c, (base_value, modifier)) base_value += 1
Python
nomic_cornstack_python_v1
from typing import List from bob.model.game import Game from bob.simulation.actions.action import Action from bob.simulation.actions.build import Build from bob.simulation.actions.train import Train function get_actions game begin set actions = list set actions = actions + call get_actions game set actions = actions +...
from typing import List from bob.model.game import Game from bob.simulation.actions.action import Action from bob.simulation.actions.build import Build from bob.simulation.actions.train import Train def get_actions(game: Game) -> List[Action]: actions = [] actions += Build.get_actions(game) actions += Tr...
Python
zaydzuhri_stack_edu_python
from random import choice , randint function exchange_gifts gift_dict begin set gifts_exchanged = dict set gifts_list = list for person in gift_dict begin append gifts_list list person gift_dict at person end comment i = 0 comment while i < len(gifts_list)-1: comment gifts_exchanged[_list[1]] = gifts_list[i][1] for _...
from random import choice, randint def exchange_gifts(gift_dict): gifts_exchanged = {} gifts_list = [] for person in gift_dict: gifts_list.append([person, gift_dict[person]]) # i = 0 # while i < len(gifts_list)-1: # gifts_exchanged[_list[1]] = gifts_list[i][1] for _list in ...
Python
zaydzuhri_stack_edu_python
function get_bad_char self string size begin set bad_char = list - 1 * NO_OF_CHARS for i in range size begin comment ord('A') == chr(65) set bad_char at ordinal string at i = i end return bad_char end function
def get_bad_char(self, string, size): bad_char = [-1] * self.NO_OF_CHARS for i in range(size): # ord('A') == chr(65) bad_char[ord(string[i])] = i return bad_char
Python
nomic_cornstack_python_v1
function calc_bill_amount quantity_food distance_in_kms food_type begin set vegiterian_food = 120 set non_vegiterian_food = 150 set bill_amount = 0 if quantity_food >= 1 and distance_in_kms >= 1 begin if food_type == string V begin set vegSubTotal = vegiterian_food * quantity_food if distance_in_kms <= 5 begin set bill...
def calc_bill_amount(quantity_food, distance_in_kms, food_type): vegiterian_food = 120 non_vegiterian_food = 150 bill_amount = 0 if quantity_food >= 1 and distance_in_kms >= 1: if food_type == "V": vegSubTotal = vegiterian_food * quantity_food if distance_in_kms <= 5: ...
Python
zaydzuhri_stack_edu_python
function test_create_debugger2 self begin set plugin = call get_plugin string hqc_meas.debug set core = call get_plugin string enaml.workbench.core set cmd = string enaml.workbench.ui.select_workspace call invoke_command cmd dict string workspace string hqc_meas.debug.workspace self comment Check the plugin got the wor...
def test_create_debugger2(self): plugin = self.workbench.get_plugin(u'hqc_meas.debug') core = self.workbench.get_plugin(u'enaml.workbench.core') cmd = u'enaml.workbench.ui.select_workspace' core.invoke_command(cmd, {'workspace': u'hqc_meas.debug.workspace'}, ...
Python
nomic_cornstack_python_v1
import struct import array import numpy as np comment SVM prediction from sklearn import svm from sklearn.externals import joblib function loadMNISTImages file_name begin set image_file = open file_name string rb set head1 = read image_file 4 set head2 = read image_file 4 set head3 = read image_file 4 set head4 = read ...
import struct import array import numpy as np # SVM prediction from sklearn import svm from sklearn.externals import joblib def loadMNISTImages(file_name): image_file = open(file_name, 'rb') head1 = image_file.read(4) head2 = image_file.read(4) head3 = image_file.read(4) head4 = imag...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Dec 25 19:42:23 2014 @author: wepon code of PCA Algrithom import numpy as np comment 根据要求的方差百分比,求出所需要的特征值的个数n function percent2n eigVals percent begin comment 升序 set sortArray = sort np eigVals comment 逆转,即降序 set sortArray = sortArray at slice - 1 : : - 1 set arraySu...
# -*- coding: utf-8 -*- """ Created on Thu Dec 25 19:42:23 2014 @author: wepon code of PCA Algrithom """ import numpy as np #根据要求的方差百分比,求出所需要的特征值的个数n def percent2n(eigVals,percent): sortArray=np.sort(eigVals) #升序 sortArray=sortArray[-1::-1] #逆转,即降序 arraySum=sum(sortArray) tmp=0 num=0 for i...
Python
zaydzuhri_stack_edu_python
function predict_y x w begin set r = list set n = length w for i in range length x begin set temp = 0 for j in range n begin set temp = temp + w at n - j - 1 * x at i ^ j end set r = r + list temp end return r end function
def predict_y(x, w): r = [] n = len(w) for i in range(len(x)): temp = 0 for j in range(n): temp = temp+w[n-j-1]*(x[i]**j) r = r+[temp] return r
Python
nomic_cornstack_python_v1
function compute_GEOPOT filename inputinf=none begin set ncfile = call Dataset filename string r set geopot = call getvar ncfile string geopotential ALL_TIMES set atts = dict string standard_name string geopotential ; string long_name string full_model_level_geopotential ; string units string m2 s-2 ; string hgt string...
def compute_GEOPOT(filename,inputinf=None): ncfile = nc.Dataset(filename,'r') geopot = wrf.getvar(ncfile, "geopotential",wrf.ALL_TIMES) atts = {"standard_name": "geopotential", "long_name": "full_model_level_geopotential", "units" : "m2 s-2" , ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Functions for visualization import numpy as np comment import pandas as pd comment import geopandas as gpd from bokeh.sampledata.us_states import data as states from shapely import affinity from shapely.geometry import Polygon from shapely.geometry import mapping , shape function df...
# -*- coding: utf-8 -*- """ Functions for visualization """ import numpy as np #import pandas as pd #import geopandas as gpd from bokeh.sampledata.us_states import data as states from shapely import affinity from shapely.geometry import Polygon from shapely.geometry import mapping, shape ##############################...
Python
zaydzuhri_stack_edu_python
function create_user self email username password=none begin if not email begin raise call ValueError string User must have an email address end if not username begin raise call ValueError string Users must have a username end set email = call normalize_email email set user = model email=email username=username call se...
def create_user(self, email, username, password=None): if not email: raise ValueError("User must have an email address") if not username: raise ValueError('Users must have a username') email = self.normalize_email(email) user = self.model(email=email, username=u...
Python
nomic_cornstack_python_v1
function insufficient_access self begin return _reason == string INSUFFICIENT_ACCESS end function
def insufficient_access(self) -> bool: return self._reason == "INSUFFICIENT_ACCESS"
Python
nomic_cornstack_python_v1
string 透視投影(perspective)とは、3次元の物体を見たとおりに2次元平面に描画するための図法である import cv2 import numpy as np try begin comment 画像の読み込み set img = call imread string ./tmp/lena.jpg if img is none begin print string 読み込みできませんでした import sys exit end comment 画像から座標を入力(y,x) set tuple init_y init_x = shape at slice : 2 : set x0 = init_x / 4 se...
""" 透視投影(perspective)とは、3次元の物体を見たとおりに2次元平面に描画するための図法である """ import cv2 import numpy as np try: # 画像の読み込み img = cv2.imread('./tmp/lena.jpg') if img is None: print('読み込みできませんでした') import sys sys.exit() # 画像から座標を入力(y,x) init_y, init_x = img.shape[:2] x0 = init_x/4 x1 ...
Python
zaydzuhri_stack_edu_python
function us39_list_upcoming_anniversaries self pt=false debug=false write=false begin set upcoming_ann_list = list set debug_list = list set timedelta = time delta days=30 for family in values families begin if husband and wife and marriage_date and not divorce_date begin for individual in values individuals begin if...
def us39_list_upcoming_anniversaries(self, pt=False, debug=False, write=False): upcoming_ann_list = [] debug_list = [] timedelta = datetime.timedelta(days=30) for family in self.families.values(): if family.husband and family.wife and family.marriage_date and not family.divo...
Python
nomic_cornstack_python_v1
function organization_memberships_create_many self data **kwargs begin string https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-many-memberships set api_path = string /api/v2/organization_memberships/create_many.json return call api_path method=string POST data=data keyword kwargs end fun...
def organization_memberships_create_many(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-many-memberships" api_path = "/api/v2/organization_memberships/create_many.json" return self.call(api_path, method="POST", data=data, **kwargs)
Python
jtatman_500k
comment For smooth importing of all the below packages (if not used, Pylance or comment Microsoft Python Language server might cause issues) import sys append path string ..\smartvigilance comment Supress unimportant warnings from Transformers, Numpy and Matplotlib import warnings import logging from IgnoreDependencyWa...
# For smooth importing of all the below packages (if not used, Pylance or # Microsoft Python Language server might cause issues) import sys sys.path.append("..\smartvigilance") # Supress unimportant warnings from Transformers, Numpy and Matplotlib import warnings import logging from IgnoreDependencyWarnings.ignore_wa...
Python
zaydzuhri_stack_edu_python
function getDateRange options begin comment print(options) set queries = list set fromyear = options at string fromyear set toyear = options at string toyear string if frommonth is Jan and tomonth is Dec, a single loop is sufficient else first and last years has to be dealt seperately if options at string frommonth is...
def getDateRange(options): #print(options) queries = [] fromyear = options['fromyear'] toyear = options['toyear'] """ if frommonth is Jan and tomonth is Dec, a single loop is sufficient else first and last years has to be dealt seperately """ if options['frommonth'] is not "Jan": #print(...
Python
nomic_cornstack_python_v1
function getCurrentPitch self begin comment Get pitch, use calibrated level. Round to 2 decimal places return round degrees - levelPitch 2 end function
def getCurrentPitch(self) -> float: # Get pitch, use calibrated level. Round to 2 decimal places return round(self.robot.pose_pitch.degrees - self.levelPitch, 2)
Python
nomic_cornstack_python_v1
import warnings from contextlib import suppress from typing import Any , Callable , Iterable , Tuple import funcy import numpy as np from ipywidgets import interact , widgets from skimage.transform import downscale_local_mean as downscale from boiling_learning.preprocessing import ImageDataset from boiling_learning.pre...
import warnings from contextlib import suppress from typing import Any, Callable, Iterable, Tuple import funcy import numpy as np from ipywidgets import interact, widgets from skimage.transform import downscale_local_mean as downscale from boiling_learning.preprocessing import ImageDataset from boiling_learning.prepr...
Python
zaydzuhri_stack_edu_python
function get_density_matrix self qbits=none basis=ilo begin if qbits is none begin set qbits = sorted keys q_bits reverse=basis == dlo end set res = call get_result qbits if density_matrix is not none begin return density_matrix end raise call InvalidResultType string density_matrix end function
def get_density_matrix( self, qbits: Optional[Sequence[Qubit]] = None, basis: BasisOrder = BasisOrder.ilo, ) -> np.ndarray: if qbits is None: qbits = sorted(self.q_bits.keys(), reverse=(basis == BasisOrder.dlo)) res = self.get_result(qbits) if res.density_...
Python
nomic_cornstack_python_v1
import codecs import logging import os import pickle import socket import sys import threading from socketserver import TCPServer , BaseRequestHandler from typing import Tuple , Any , Dict , Type , Union , Optional set dont_write_bytecode = true set BASE_PATH : str = get current directory set SERVER_SETUP_FILE : str = ...
import codecs import logging import os import pickle import socket import sys import threading from socketserver import TCPServer, BaseRequestHandler from typing import Tuple, Any, Dict, Type, Union, Optional sys.dont_write_bytecode = True BASE_PATH: str = os.getcwd() SERVER_SETUP_FILE: str = os.path.join(BASE_PATH, ...
Python
zaydzuhri_stack_edu_python
import sys from src.tokenizer import Tokenizer from src.parser import Parser from src.semantic_analyzer import SemanticAnalyzer function process filename begin with open filename as file begin set text = read file if not text begin raise exception string Cannot read text from file end set tokenizer = call Tokenizer tex...
import sys from src.tokenizer import Tokenizer from src.parser import Parser from src.semantic_analyzer import SemanticAnalyzer def process(filename): with open(filename) as file: text = file.read() if not text: raise Exception("Cannot read text from file") tokenizer = Tokenizer...
Python
zaydzuhri_stack_edu_python
function city self city begin set _city = city end function
def city(self, city): self._city = city
Python
nomic_cornstack_python_v1
comment Q59 ハンカチ落としの総走行距離 comment ハンカチ落としでは、鬼以外の人が円になって座ったあと、鬼が円の外を走ります。鬼が誰かの後ろでハンカチを落とすと、 comment 落とされた人は鬼が一周してくるまでの間に気づき、鬼を追いかける必要があります。今回は、全員が同じ速さで走るため、 comment 鬼が追い付かれることはないものとし、また、落とされた人は鬼が一周回ってくるまでに必ず気づくものとします。 comment このゲームを行い、円に並んでいる人の並び順を「最初の並び順の逆にする」ことを考えます。 comment 1〰8の番号が付いた8人が座っているところに、「0」の鬼が入ったとき、並び順が逆になる...
# Q59 ハンカチ落としの総走行距離 # ハンカチ落としでは、鬼以外の人が円になって座ったあと、鬼が円の外を走ります。鬼が誰かの後ろでハンカチを落とすと、 # 落とされた人は鬼が一周してくるまでの間に気づき、鬼を追いかける必要があります。今回は、全員が同じ速さで走るため、 # 鬼が追い付かれることはないものとし、また、落とされた人は鬼が一周回ってくるまでに必ず気づくものとします。 # このゲームを行い、円に並んでいる人の並び順を「最初の並び順の逆にする」ことを考えます。 # 1〰8の番号が付いた8人が座っているところに、「0」の鬼が入ったとき、並び順が逆になる場合の # 総走行距離が「最短」になる場合を考え、その走行距離を答えてく...
Python
zaydzuhri_stack_edu_python
function _check_atom_connectivity_in_rd_mol_block self rmg_mol rd_mol_block begin for line in rd_mol_block begin set splits = split line if length splits == 4 begin set tuple index1 index2 = tuple integer splits at 0 - 1 integer splits at 1 - 1 assert in atoms at index1 list keys edges end end end function
def _check_atom_connectivity_in_rd_mol_block(self, rmg_mol, rd_mol_block): for line in rd_mol_block: splits = line.split() if len(splits) == 4: index1, index2 = int(splits[0]) - 1, int(splits[1]) - 1 self.assertIn(rmg_mol.atoms[index1], list(rmg_mol.atoms[...
Python
nomic_cornstack_python_v1
function otsu image begin set histogram = call create_histogram image comment sum the values of all pixels set sum_all = 0 for t in range 256 begin set sum_all = sum_all + t * histogram at t end set tuple sum_back w_back w_for v_max t_best = tuple 0 0 0 0 0 set total = shape at 0 * shape at 1 comment Go over all possib...
def otsu(image): histogram = create_histogram(image) # sum the values of all pixels sum_all = 0 for t in range(256): sum_all += t * histogram[t] sum_back, w_back, w_for, v_max, t_best = 0, 0, 0, 0, 0 total = image.shape[0] * image.shape[1] # Go over all possible thresholds f...
Python
nomic_cornstack_python_v1
from builtin import * print name comment print(dir(A)) print Copy print Paste print Cut print Delete print name comment print(dir(B)) print Copy print Paste print Cut print Delete print name comment print(dir(C)) print Copy print Paste print Cut print Delete print name comment print(dir(D)) print Copy print Paste print...
from builtin import * print(A.name) # print(dir(A)) print(A.Copy) print(A.Paste) print(A.Cut) print(A.Delete) print(B.name) # print(dir(B)) print(B.Copy) print(B.Paste) print(B.Cut) print(B.Delete) print(C.name) # print(dir(C)) print(C.Copy) print(C.Paste) print(C.Cut) print(C.Delete) print(D.name) # print(dir(D)) ...
Python
zaydzuhri_stack_edu_python
comment approve all posts in unmoderated queue import praw import datetime set CLIENT_ID = string set CLIENT_SECRET = string set USER_AGENT = string set USER_PASSWORD = string set USER_NAME = string set SUBREDDIT = string comment logs into reddit function login begin print string ### Logging in... set reddit = ca...
### approve all posts in unmoderated queue import praw import datetime CLIENT_ID = '' CLIENT_SECRET = '' USER_AGENT = '' USER_PASSWORD = '' USER_NAME = '' SUBREDDIT = "" # logs into reddit def login(): print("### Logging in...") reddit = praw.Reddit(client_id=CLIENT_ID, client_secre...
Python
zaydzuhri_stack_edu_python
function fit self X y begin set X = if expression is instance X list then array X dtype=float64 else X set y = if expression is instance y list then array y else y comment Matrix A or class 1 data set mat_A = X at y == 1 comment Matrix B or class -1 data set mat_B = X at y == - 1 comment Vectors of ones set mat_e1 = on...
def fit(self, X, y): X = np.array(X, dtype=np.float64) if isinstance(X, list) else X y = np.array(y) if isinstance(y, list) else y # Matrix A or class 1 data mat_A = X[y == 1] # Matrix B or class -1 data mat_B = X[y == -1] # Vectors of ones mat_e1 = np...
Python
nomic_cornstack_python_v1
function test_invalid_directories qtbot pathmanager begin if name == string nt begin set paths = list string /lib/site-packages/foo string /lib/dist-packages/foo end else begin set paths = list string /lib/python3.6/site-packages/foo string /lib/python3.6/dist-packages/foo end function interact_message_box begin set ch...
def test_invalid_directories(qtbot, pathmanager): if os.name == 'nt': paths = ['/lib/site-packages/foo', '/lib/dist-packages/foo'] else: paths = ['/lib/python3.6/site-packages/foo', '/lib/python3.6/dist-packages/foo'] def interact_message_box(): chi...
Python
nomic_cornstack_python_v1
while true begin set name = input if name == string STOP begin print string Winner is { winner } - { max_sum_letters } ! break end set sum_letters = 0 for letter in name begin set sum_letters = sum_letters + ordinal letter end if sum_letters > max_sum_letters begin set max_sum_letters = sum_letters set winner = name en...
while True: name = input() if name == "STOP": print(f'Winner is {winner} - {max_sum_letters}!') break sum_letters = 0 for letter in name: sum_letters += ord(letter) if sum_letters > max_sum_letters: max_sum_letters = sum_letters winner = name
Python
zaydzuhri_stack_edu_python
comment Adding solution for count inversion in O(n^3) function count_inversion arr k begin set n = length arr set count = 0 for i in range 0 n - k + 1 begin for j in range i + 1 n - k + 2 begin if arr at i > arr at j begin for k in range j + 1 n begin if arr at j > arr at k begin set count = count + 1 end end end end e...
#Adding solution for count inversion in O(n^3) def count_inversion(arr,k): n=len(arr) count =0 for i in range(0,n-k+1): for j in range(i+1,n-k+2): if arr[i]>arr[j]: for k in range(j+1,n): if arr[j]>arr[k]: count +=1
Python
zaydzuhri_stack_edu_python
function distance self word_a word_b begin set tuple word_a word_b = tuple upper word_a upper word_b set s_a = word_lookup at word_a set s_b = word_lookup at word_b set j = 1 set max_len = min length s_a length s_b while j <= max_len begin if s_a at - j != s_b at - j begin break end set j = j + 1 end return j end funct...
def distance(self, word_a, word_b): word_a, word_b = word_a.upper(), word_b.upper() s_a = self.word_lookup[word_a] s_b = self.word_lookup[word_b] j = 1 max_len = min(len(s_a), len(s_b)) while j <= max_len: if s_a[-j] != s_b[-j]: break ...
Python
nomic_cornstack_python_v1
function positionsIter self begin set elapsedTime = 0 while elapsedTime < timeToMove begin yield call lerp currentTarget elapsedTime / timeToMove set elapsedTime = elapsedTime + _dt end yield currentTarget end function
def positionsIter(self): elapsedTime = 0 while (elapsedTime < self.timeToMove): yield pygame.Vector2(self.rect.midbottom).lerp(self.currentTarget, elapsedTime / self.timeToMove) elapsedTime += self._dt yield self.currentTarget
Python
nomic_cornstack_python_v1
function space_name self begin if space_name is none begin return string end return decode space_name _decode_type end function
def space_name(self): if self._resp.space_name is None: return '' return self._resp.space_name.decode(self._decode_type)
Python
nomic_cornstack_python_v1
function validateFloat pregunta begin set isCorrectData = false while isCorrectData == false begin try begin set valor = decimal input pregunta set isCorrectData = true end except ValueError begin print string datos incorrectos, ingresalos nuevamente end return valor end end function function validateString pregunta be...
def validateFloat (pregunta): isCorrectData = False while (isCorrectData == False): try: valor = float (input(pregunta)) isCorrectData = True except ValueError: print ("datos incorrectos, ingresalos nuevamente") return valor def validateString (pregun...
Python
zaydzuhri_stack_edu_python
function login_sequence self username password begin set driver = driver call click call send_keys username call send_keys password call click debug string Clicked 'Log in' call implicitly_wait TIMEOUT call click call implicitly_wait TIMEOUT call click debug string Chose the universe. call window window_handles at 1 de...
def login_sequence(self, username: str, password: str): driver = self.driver driver.find_element_by_id("ui-id-1").click() driver.find_element_by_id("usernameLogin").send_keys(username) driver.find_element_by_id("passwordLogin").send_keys(password) driver.find_element_by_id("log...
Python
nomic_cornstack_python_v1
function test_raise_exception_for_rename_with_path self begin set td = temporary directory set BASE_DIRECTORY = string parent comment Try to Rename the Directory with call TemporaryDirectoryHandler td begin set renamed_directory_name = call get_random_file_name BASE_DIRECTORY set new_directory_path = join path BASE_DIR...
def test_raise_exception_for_rename_with_path(self): td = tempfile.TemporaryDirectory() BASE_DIRECTORY = str(pathlib.Path(td.name).parent) # Try to Rename the Directory with TemporaryDirectoryHandler(td): renamed_directory_name = utils.get_random_file_name(BASE_DIREC...
Python
nomic_cornstack_python_v1
import numpy as np from scipy.optimize import linprog from sparse_interior import create_sparse_matrix , rowcol_to_sparse , initial_vector_sparse from scipy.sparse.linalg import spsolve from scipy import sparse import matplotlib.pyplot as plt function create_matrix A x y s **options begin set tuple m n = call shape A s...
import numpy as np from scipy.optimize import linprog from sparse_interior import ( create_sparse_matrix, rowcol_to_sparse, initial_vector_sparse, ) from scipy.sparse.linalg import spsolve from scipy import sparse import matplotlib.pyplot as plt def create_matrix(A, x, y, s, **options): m, n = np.shap...
Python
zaydzuhri_stack_edu_python
comment Python Strings print string Strings in python are surrounded by either single quotation marks, or double quotation marks. comment 'hello' is same as "hello" print string Hello print string Hello comment Assign String to a Variable set a = string Chandra print a print string <--------Multiline Strings--------> c...
# Python Strings print('Strings in python are surrounded by either single quotation marks, or double quotation marks.') # 'hello' is same as "hello" print("Hello") print('Hello') # Assign String to a Variable a = 'Chandra' print(a) print('<--------Multiline Strings-------->') # You can assign a multiline string to a va...
Python
zaydzuhri_stack_edu_python
function hasRequiredElements self begin return call FbcAnd_hasRequiredElements self end function
def hasRequiredElements(self): return _libsbml.FbcAnd_hasRequiredElements(self)
Python
nomic_cornstack_python_v1