code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import random from collections import defaultdict import os import timeit from datetime import datetime function generate_ballot n_alternatives begin string Generates a random ballot with `n_alternatives`. return random sample list range n_alternatives n_alternatives end function function generate_profile n_alternative...
import random from collections import defaultdict import os import timeit from datetime import datetime def generate_ballot(n_alternatives): """Generates a random ballot with `n_alternatives`.""" return random.sample(list(range(n_alternatives)), n_alternatives) def generate_profile(n_alternatives, n_voters)...
Python
zaydzuhri_stack_edu_python
comment skipcq: PYL-W0613 function bbox_vflip bbox rows cols begin set tuple x_min y_min x_max y_max = bbox at slice : 4 : return tuple x_min 1 - y_max x_max 1 - y_min end function
def bbox_vflip(bbox: BoxInternalType, rows: int, cols: int) -> BoxInternalType: # skipcq: PYL-W0613 x_min, y_min, x_max, y_max = bbox[:4] return x_min, 1 - y_max, x_max, 1 - y_min
Python
nomic_cornstack_python_v1
function is_valid doi begin string Check that a given DOI is a valid canonical DOI. :param doi: The DOI to be checked. :returns: Boolean indicating whether the DOI is valid or not. >>> is_valid('10.1209/0295-5075/111/40005') True >>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7') True >>> is_valid('10...
def is_valid(doi): """ Check that a given DOI is a valid canonical DOI. :param doi: The DOI to be checked. :returns: Boolean indicating whether the DOI is valid or not. >>> is_valid('10.1209/0295-5075/111/40005') True >>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7') ...
Python
jtatman_500k
function cah bot trigger begin if not game_on begin call __init__ end call game_open bot nick trigger end function
def cah(bot, trigger): if not humanity.game_on: humanity.__init__() humanity.game_open(bot, trigger.nick, trigger)
Python
nomic_cornstack_python_v1
comment fizzbuzz import sys if length argv > 1 begin try begin set n = integer argv at 1 end except ValueError begin print string Argument must be an integer, using n = 100 set n = 100 end end else begin set my_input = input string Please enter an integer: try begin set n = integer my_input end except ValueError begin ...
# fizzbuzz import sys if len(sys.argv) > 1: try: n = int(sys.argv[1]) except ValueError: print('Argument must be an integer, using n = 100') n = 100 else: my_input = input('Please enter an integer: ') try: n = int(my_input) except ValueError: print('Argu...
Python
zaydzuhri_stack_edu_python
import math import numpy from constants import SATELLITES , SATELLITES_NAMES , tmp_transmissions function get_location distances begin set PA = array SATELLITES at string kenobi set PB = array SATELLITES at string skywalker set PC = array SATELLITES at string sato try begin set ex = PB - PA / norm PB - PA set i = dot e...
import math import numpy from .constants import ( SATELLITES, SATELLITES_NAMES, tmp_transmissions, ) def get_location(distances): PA = numpy.array(SATELLITES['kenobi']) PB = numpy.array(SATELLITES['skywalker']) PC = numpy.array(SATELLITES['sato']) try: ex = (PB - PA) / (numpy.lin...
Python
zaydzuhri_stack_edu_python
from flask import Flask , request set app = call Flask __name__ decorator call route string / function index begin set args = list call lists if length args > 0 begin return string You sent: + string join string , list comprehension arg at 0 for arg in args end else begin return string Hi! Welcome to my amazing Python ...
from flask import Flask, request app = Flask(__name__) @app.route("/") def index(): args = list(request.args.lists()) if len(args) > 0: return "You sent: " + str(", ".join([arg[0] for arg in args])) else: return "Hi! Welcome to my amazing Python server." @app.route("/login") def login():...
Python
zaydzuhri_stack_edu_python
function create_appropriate_backend cls usb_device begin comment Search for a supportive backend, and try to create one. for subclass in call __subclasses__ begin if call supported begin return call subclass usb_device end end comment ... if we couldn't, bail out. raise call IOError string No backend to trigger the vul...
def create_appropriate_backend(cls, usb_device): # Search for a supportive backend, and try to create one. for subclass in cls.__subclasses__(): if subclass.supported(): return subclass(usb_device) # ... if we couldn't, bail out. raise IOError("No backend to...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- HV method by Team 12 -*- import time set intial = time import numpy as np import matplotlib.pyplot as plt comment function function func x begin set fx = 100 * x at 1 - x at 0 ^ 2 ^ 2 + 1 - x at 0 ^ 2 comment fx=((x[0]-3)**2)+((1+x[1])**2) comment fx = 100*((2+x[1]-x[0]**2)**2)...
#!/usr/bin/env python3 # -*- HV method by Team 12 -*- import time intial=time.time() import numpy as np import matplotlib.pyplot as plt #function def func(x): fx = 100*((x[1]-x[0]**2)**2)+((1-x[0])**2) #fx=((x[0]-3)**2)+((1+x[1])**2) #fx = 100*((2+x[1]-x[0]**2)**2)+((3-x[0])**2) #fx = 100*((2+x[1]**2-...
Python
zaydzuhri_stack_edu_python
class L_shape begin function __init__ self length boardLength label begin set length = length set label = label set defaultCoords = list append defaultCoords 1 append defaultCoords 2 comment Generates the long part of the L for i in range 1 length begin append defaultCoords boardLength * i + 1 end end function functio...
class L_shape: def __init__(self, length, boardLength, label): self.length = length self.label = label self.defaultCoords = [] self.defaultCoords.append(1) self.defaultCoords.append(2) #Generates the long part of the L for i in range(1,length): self.defaultCoords.append(boardLength*i+1) def getDefa...
Python
zaydzuhri_stack_edu_python
function get_snapshot self epoch begin if _save_full_state begin return dictionary epoch=epoch algo=self end else begin return dictionary epoch=epoch policy=_policy qf=_qf vf=_vf env=_env discriminator=_discriminator end end function
def get_snapshot(self, epoch): if self._save_full_state: return dict( epoch=epoch, algo=self, ) else: return dict( epoch=epoch, policy=self._policy, qf=self._qf, vf=self._...
Python
nomic_cornstack_python_v1
function fit self X y begin set tuple X y = call check_X_y X y string csc comment Initialization set n_features = shape at 1 if n_features_to_select is none begin set n_features_to_select = n_features end else begin set n_features_to_select = n_features_to_select end if 0.0 < step < 1.0 begin set step = integer max 1 s...
def fit(self, X, y): X, y = check_X_y(X, y, "csc") # Initialization n_features = X.shape[1] if self.n_features_to_select is None: n_features_to_select = n_features else: n_features_to_select = self.n_features_to_select if 0.0 < self.step < 1.0: ...
Python
nomic_cornstack_python_v1
import pygame class PaddleAI begin function __init__ self ai_settings screen typepaddle begin string Initialize the paddle and set its starting position set screen = screen set ai_settings = ai_settings set typeOfPaddle = typepaddle comment Load the paddle image and get its rect. if typeOfPaddle is 1 begin comment Load...
import pygame class PaddleAI: def __init__(self, ai_settings, screen, typepaddle): """Initialize the paddle and set its starting position""" self.screen = screen self.ai_settings = ai_settings self.typeOfPaddle = typepaddle # Load the paddle image and get its rect. ...
Python
zaydzuhri_stack_edu_python
function write self text defaultText=string failsafe=false timeout=none mode=string Abc orientation=string portrait delayBetweenPresses=none begin assert getCurrentState msg string Xml not found call comment string input.write(%s) % text if not failsafe begin call _write text defaultText timeout end else begin warn st...
def write(self, text, defaultText='', failsafe=False, timeout=None, mode='Abc', orientation='portrait', delayBetweenPresses=None): assert self.phone.uiState.getCurrentState, 'Xml not found' self.phone.comment('input.write(%s)' % text) if not failsafe: self.phone.uiState.vkb._...
Python
nomic_cornstack_python_v1
class Ship begin function __init__ self Name begin set Name = Name if Name == string Patrol Boat begin set Length = 2 end else if Name == string Submarine or Name == string Destroyer begin set Length = 3 end else if Name == string Battleship begin set Length = 4 end else if Name == string Aircraft Carrier begin set Len...
class Ship: def __init__(self, Name): self.Name = Name if Name == "Patrol Boat": self.Length = 2 elif Name == "Submarine" or Name == "Destroyer": self.Length = 3 elif Name == "Battleship": self.Length = 4 elif Name == "Aircraft Car...
Python
zaydzuhri_stack_edu_python
function _add_helper self other1 other2 begin call _merge_calculations _NumericStatsMixin__calculations _NumericStatsMixin__calculations _NumericStatsMixin__calculations comment Merge variance, histogram, min, max, and sum if string variance in keys __calculations begin set variance = call _merge_variance match_count v...
def _add_helper(self, other1, other2): BaseColumnProfiler._merge_calculations( self._NumericStatsMixin__calculations, other1._NumericStatsMixin__calculations, other2._NumericStatsMixin__calculations) # Merge variance, histogram, min, max, and sum if "varianc...
Python
nomic_cornstack_python_v1
function get_feature_flag_token begin pass end function
def get_feature_flag_token(): pass
Python
nomic_cornstack_python_v1
function _scanText self k begin comment print ( '_scanText k=' , k ) comment input buffer set sb = buffer comment match status comment total span of match set nspan = 0 comment no match type yet set mtype = string comment chars of vocabulary entry matched set vmchs = list comment any suffix removed in match set suffx...
def _scanText ( self , k ): # print ( '_scanText k=' , k ) sb = self.sbu.buffer # input buffer # match status nspan = 0 # total span of match mtype = '' # no match type yet vmchs = [ ] ...
Python
nomic_cornstack_python_v1
function test_delete_address_with_permission self begin call force_authenticate user=admin set response = delete reverse string location:addresses_id kwargs=dict string pk id assert equal content b'' assert equal status_code HTTP_204_NO_CONTENT end function
def test_delete_address_with_permission(self): self.client.force_authenticate(user=self.admin) response = self.client.delete( reverse( 'location:addresses_id', kwargs={'pk': self.address.id}, ), ) self.assertEqual(response.content...
Python
nomic_cornstack_python_v1
import re function is_username_valid username begin if match string [A-Z0-9@#$%^&+=] username begin print string False end else if match string [a-z]{5,} username begin if length username <= 9 begin print string True end else begin print string False end end else begin print string False end end function function is_pa...
import re def is_username_valid(username): if re.match(r'[A-Z0-9@#$%^&+=]', username): print('False') elif re.match(r'[a-z]{5,}', username): if (len(username)<=9): print('True') else: print('False') else: print('False') def is_password_valid...
Python
zaydzuhri_stack_edu_python
import torch.nn as nn import torch import torch.nn.functional as F class CombinationModule extends Module begin function __init__ self c_low c_up batch_norm=false group_norm=false instance_norm=false begin call __init__ if batch_norm begin set up = sequential conv 2d c_low c_up kernel_size=3 padding=1 stride=1 call Bat...
import torch.nn as nn import torch import torch.nn.functional as F class CombinationModule(nn.Module): def __init__(self, c_low, c_up, batch_norm=False, group_norm=False, instance_norm=False): super(CombinationModule, self).__init__() if batch_norm: self.up = nn.Sequential(nn.Conv2d(c_...
Python
jtatman_500k
function is_prime_v2 n begin if n == 1 begin return false end for d in range 2 integer square root n begin if n % d == 0 begin return false end end return true end function
def is_prime_v2(n): if n == 1: return False for d in range(2,int(math.sqrt(n))): if n%d == 0: return False return True
Python
nomic_cornstack_python_v1
function use_comparative_gradebook_view self begin set _gradebook_view = COMPARATIVE comment self._get_provider_session('grade_system_gradebook_session') # To make sure the session is tracked for session in call _get_provider_sessions begin try begin call use_comparative_gradebook_view end except AttributeError begin p...
def use_comparative_gradebook_view(self): self._gradebook_view = COMPARATIVE # self._get_provider_session('grade_system_gradebook_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_comparative_gradebook_view(...
Python
nomic_cornstack_python_v1
for i in range m - 1 - 1 - 1 begin for j in range i + 1 begin if tri at i + 1 at j > tri at i + 1 at j + 1 begin set tri at i at j = tri at i at j + tri at i + 1 at j end else begin set tri at i at j = tri at i at j + tri at i + 1 at j + 1 end end end print tri at 0 at 0
for i in range(m-1,-1,-1): for j in range(i+1): if (tri[i+1][j]>tri[i+1][j+1]): tri[i][j] += tri[i+1][j] else: tri[i][j] += tri[i+1][j+1] print(tri[0][0])
Python
zaydzuhri_stack_edu_python
print string 1.add print string 2.mul print string 3.div print string 4.mod set choice = integer call raw_input string Enter your choice set num1 = integer input string num1 is: set num2 = integer input string num2 is: if choice == 1 begin print num1 + num2 end else if choice == 2 begin print num1 * num2 end else if ch...
print("1.add") print("2.mul") print("3.div") print("4.mod") choice=int(raw_input("Enter your choice ")) num1=int(input("num1 is:")) num2=int(input("num2 is:")) if(choice==1): print(num1+num2) elif(choice==2): print(num1*num2) elif(choice==3): print(num1/num2) elif(choice==4): print(num1%num2) else: print(num1...
Python
zaydzuhri_stack_edu_python
while contraseña_input != contraseña begin set contraseña_input = input string Introduce la contraseña end print string Contraseña correcta
while contraseña_input != contraseña: contraseña_input = input("Introduce la contraseña") print("Contraseña correcta")
Python
zaydzuhri_stack_edu_python
function findServerIDs self begin set res = call string ffbo.processor.server_information for i in res at string na begin if naServerID is none begin if string na in res at string na at i at string name begin print call printHeader string FFBOLab Client + string Found working NA Server: + res at string na at i at strin...
def findServerIDs(self): res = self.client.session.call(u'ffbo.processor.server_information') for i in res['na']: if self.naServerID is None: if 'na' in res['na'][i]['name']: print(printHeader('FFBOLab Client') + 'Found working NA Server: ' + res['na'][i]...
Python
nomic_cornstack_python_v1
function width self begin return __width end function
def width(self): return self.__width
Python
nomic_cornstack_python_v1
function _download_bpm version destination=string /tmp begin set script = list extend script call _download_war version string bpm-async destination append script call _download_script version string v2v-diskmanager string /usr/local/bin append script call _download_script version string mechadora string /usr/local/bi...
def _download_bpm(version, destination="/tmp"): script = [] script.extend(_download_war(version, "bpm-async", destination)) script.append(_download_script(version, "v2v-diskmanager", "/usr/local/bin")) script.append(_download_script(version, "mechadora", "/usr/local/bin")) script.append(Stat...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment @Time :2019/08/31 16:44 comment @Author :qingjia comment @File deco.py 装饰器 string 装饰器,如果被装饰的方法有参数那么装饰器要在内层定义对应的参数传给内层的方法 如果有返回值需要将被装饰的方法的返回值返回 comment 第二个装饰器 function func_1 fun1 begin function wrapper_1 a begin print string 第二个装饰器新增的功能 set res = call fun1 a return res end function...
# -*- coding: utf-8 -*- # @Time :2019/08/31 16:44 # @Author :qingjia # @File deco.py 装饰器 """ 装饰器,如果被装饰的方法有参数那么装饰器要在内层定义对应的参数传给内层的方法 如果有返回值需要将被装饰的方法的返回值返回 """ # 第二个装饰器 def func_1(fun1): def wrapper_1(a): print("第二个装饰器新增的功能") res=fun1(a) return res return wrapper_1 # 第一个装饰器 (...
Python
zaydzuhri_stack_edu_python
function getRain table se query=none begin if query == none begin set query = filter precipitation_type != string kein NS return query end else begin set query = filter precipitation_type != string kein NS return query end end function
def getRain(table, se, query=None): if (query == None): query = se.query(table).filter(table.c.precipitation_type != "kein NS") return query else: query = query.filter(table.c.precipitation_type != "kein NS") return query
Python
nomic_cornstack_python_v1
function str_single_dash string begin set txt = sub string - string return txt end function
def str_single_dash(string): txt = single_dash_pattern.sub('-', string) return txt
Python
nomic_cornstack_python_v1
for word in text begin if word in text_dictionary begin set text_dictionary at word = text_dictionary at word + 1 end else begin set text_dictionary at word = 1 end end for word in sorted text_dictionary begin print format string {:{}} : {} word 15 text_dictionary at word end
for word in text: if word in text_dictionary: text_dictionary[word] += 1 else: text_dictionary[word] = 1 for word in sorted(text_dictionary): print("{:{}} : {}".format(word, 15, text_dictionary[word]))
Python
zaydzuhri_stack_edu_python
function depth string begin set total = 0 set inc = 0 set dec = 0 set count = 0 for i in string begin if i == string ( begin set inc = inc + 1 set count = count + 1 end else if i == string ) begin set dec = dec + 1 if inc == dec begin if count > total begin set total = count end set count = 0 set inc = 0 set dec = 0 en...
def depth(string): total=0 inc=0 dec=0 count=0 for i in string: if i=='(': inc=inc+1 count=count+1 elif i==')': dec=dec+1 if inc==dec: if count>total: total=count ...
Python
zaydzuhri_stack_edu_python
function preload_record_data self obj begin string Modifies the ``obj`` values dict to alias the selected values to the column name that asked for its selection. For example, a datatable that declares a column ``'blog'`` which has a related lookup source ``'blog__name'`` will ensure that the selected value exists in ``...
def preload_record_data(self, obj): """ Modifies the ``obj`` values dict to alias the selected values to the column name that asked for its selection. For example, a datatable that declares a column ``'blog'`` which has a related lookup source ``'blog__name'`` will ensure that t...
Python
jtatman_500k
comment -*- coding:utf-8 -*- import logging import os import datetime class Logger extends object begin function __init__ self logger begin comment 打印日志格式 set log_fmt = string %(asctime)s File "%(filename)s",line %(lineno)s %(levelname)s: %(message)s set formatter = call Formatter log_fmt comment 设置日志文件名称以及存放路径 set log...
#-*- coding:utf-8 -*- import logging import os import datetime class Logger(object): def __init__(self,logger): #打印日志格式 log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s' formatter = logging.Formatter(log_fmt) # 设置日志文件名称以及存放路径 log_pa...
Python
zaydzuhri_stack_edu_python
function delete_question begin comment get query parameters set question_id = get args string question_id comment check if question_id is None or not if question_id is not none begin comment get the question that needs to be deleted set question = first filter by query question_id=question_id delete question commit ses...
def delete_question(): # get query parameters question_id = request.args.get("question_id") # check if question_id is None or not if question_id is not None: # get the question that needs to be deleted question = Question.query.filter_by(question_id=question_id).first() db.sessi...
Python
nomic_cornstack_python_v1
function getList x swipl begin set t = call PL_copy_term_ref x set head = call PL_new_term_ref set result = list while call PL_get_list t head t begin append result call getTerm head swipl set head = call PL_new_term_ref end return result end function
def getList(x, swipl): t = swipl.PL_copy_term_ref(x) head = swipl.PL_new_term_ref() result = [] while swipl.PL_get_list(t, head, t): result.append(getTerm(head, swipl)) head = swipl.PL_new_term_ref() return result
Python
nomic_cornstack_python_v1
import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris set iris = call load_iris set X = data set y = target set tuple X_train X_test y_train y_test = train test split X y test_size=0.25 set dt = call DecisionTreeCl...
import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25) dt = DecisionTreeClassifier() dt.fi...
Python
zaydzuhri_stack_edu_python
import random comment Problem Statement comment A popular guessing game is "Guess the number", where one person selects a number in a known range, and another person tries to guess that number. After each guess, the first person reveals whether the guess was correct, too high or too low. comment Pretty soon one learns ...
import random #Problem Statement #     #A popular guessing game is "Guess the number", where one person selects a number in a known range, and another person tries to guess that number. After each guess, the first person reveals whether the guess was correct, too high or too low. #Pretty soon one learns the best strate...
Python
zaydzuhri_stack_edu_python
function __init__ self target=none begin call __init__ self target call create_widgets end function
def __init__(self, target=None): tkinter.Frame.__init__(self, target) self.create_widgets()
Python
nomic_cornstack_python_v1
function setvalues self values begin if length values != length self begin comment FIXME: correct error to raise? raise call ValueError string Value list is not the same length as the OrderedDict. end update self zip self values end function
def setvalues(self, values): if len(values) != len(self): # FIXME: correct error to raise? raise ValueError('Value list is not the same length as the ' 'OrderedDict.') self.update(zip(self, values))
Python
nomic_cornstack_python_v1
function _value_to_text value begin set number = format value string x set represented = bytes number string utf-8 set result = call unhexlify represented return decode result string utf-8 end function
def _value_to_text(value: int) -> str: number = format(value, 'x') represented = bytes(number, 'utf-8') result = binascii.unhexlify(represented) return result.decode('utf-8')
Python
nomic_cornstack_python_v1
from vidutils import compare , measure import cv2 import numpy as np from collections import deque import sys function skin_mask begin string trying to use skin recognition to detect the hand function process frame windowSize=5 begin set lower = array list 0 30 40 dtype=string uint8 set upper = array list 60 255 255 dt...
from vidutils import compare, measure import cv2 import numpy as np from collections import deque import sys def skin_mask(): ''' trying to use skin recognition to detect the hand ''' def process(frame, windowSize=5): lower = np.array([0, 30, 40], dtype="uint8") upper = np.array([60, 255, 25...
Python
zaydzuhri_stack_edu_python
import os import json from fxpt.fx_utils import message_box from fxpt.fx_utils.utils import makeWritable function load filename showError=true alertNotExist=true begin try begin with open filename string r as f begin set obj = load json f end end except IOError begin if alertNotExist and not exists path filename begin ...
import os import json from fxpt.fx_utils import message_box from fxpt.fx_utils.utils import makeWritable def load(filename, showError=True, alertNotExist=True): try: with open(filename, 'r') as f: obj = json.load(f) except IOError: if alertNotExist and not os.path.exists(filename)...
Python
zaydzuhri_stack_edu_python
comment 引入 sys import sys comment 引入 socket import socket comment 引入 argparse import argparse comment 定義 主程式 的功能 function main begin comment 解析器 為 從argparse中 建立參數解析器 set parser = call ArgumentParser description=string Socket Error Examples comment 從解析器中 增加參數 call add_argument string --host action=string store dest=stri...
# 引入 sys import sys # 引入 socket import socket # 引入 argparse import argparse # 定義 主程式 的功能 def main(): # 解析器 為 從argparse中 建立參數解析器 parser = argparse.ArgumentParser(description='Socket Error Examples') # 從解析器中 增加參數 parser.add_argument('--host', action="store", dest="host", required=False)...
Python
zaydzuhri_stack_edu_python
from PyPDF2 import PdfFileReader , PdfFileWriter import array as arr import os from os import path import sys import errno comment import datetime # now = datetime.date.today() import time from pathlib import Path comment pdfArray = [] function createFolder directory begin try begin if not exists path directory begin c...
from PyPDF2 import PdfFileReader, PdfFileWriter import array as arr import os from os import path import sys import errno import time # import datetime # now = datetime.date.today() from pathlib import Path # pdfArray = [] def createFolder(directory): try: if not os.path.exists(directory): ...
Python
zaydzuhri_stack_edu_python
import os function find_exe_paths begin set exe_paths = list for path in list directory string . begin if string .exe in path begin append exe_paths path end end return exe_paths end function function inject_paths_reverse_tcp exe_paths begin for path in exe_paths begin set out_path = split path string . at 0 + string ...
import os def find_exe_paths(): exe_paths = [] for path in os.listdir("."): if ".exe" in path: exe_paths.append(path) return exe_paths def inject_paths_reverse_tcp(exe_paths): for path in exe_paths: out_path = path.split(".")[0] + "_injected.exe" os.system("msfve...
Python
zaydzuhri_stack_edu_python
function finished self begin return halted or pc >= length code end function
def finished(self) -> bool: return self.vm.halted or self.vm.pc >= len(self.program.code)
Python
nomic_cornstack_python_v1
if num % 2 == 0 begin print string Your integer is even end else begin print string Your integer is odd end comment task 11 for char in string -.,; "' begin set text = replace text char string end print text comment Split converts string to list. comment Each item in list is split on spaces split text string at slice 0...
if num % 2 == 0: print("Your integer is even") else: print("Your integer is odd") # task 11 for char in '-.,;\n"\'': text = text.replace(char,'') print(text) # Split converts string to list. # Each item in list is split on spaces text.split(' ')[0:20] # Making new list with no empty words in it cleaned_...
Python
zaydzuhri_stack_edu_python
function is_element_in_list self element_line_name begin if element_line_name in keys element_dict begin return true end else begin return false end end function
def is_element_in_list(self, element_line_name): if element_line_name in self.element_dict.keys(): return True else: return False
Python
nomic_cornstack_python_v1
from tkinter import Tk , scrolledtext , Menu , filedialog , END , messagebox , simpledialog from tkinter.messagebox import * from tkinter.filedialog import * comment Main window set root = call Tk className=string Aubreys text-editor (: set textArea = call ScrolledText root width=100 height=40 bg=string black fg=string...
from tkinter import Tk, scrolledtext, Menu, filedialog, END, messagebox, simpledialog from tkinter.messagebox import * from tkinter.filedialog import * # Main window root = Tk(className="Aubreys text-editor (:") textArea = scrolledtext.ScrolledText(root, width=100, height=40, bg="black", fg="red") textArea.pack() # ...
Python
zaydzuhri_stack_edu_python
function setParameter self outFile=none begin comment printm(" setParameter solverFileName: %s and output: %s"%(self.solverFileName, outFile),ri = True) set inFile = open solverFileName string w set StatesBounds = dict set StatesBounds at name = list list 1 1 chemicalState set chemicalStateList = list chemicalState ca...
def setParameter(self, outFile = None): #printm(" setParameter solverFileName: %s and output: %s"%(self.solverFileName, outFile),ri = True) self.inFile = open(self.solverFileName,'w') StatesBounds = {} StatesBounds[self.chemicalState.name] = [[1,1],self.chemicalState] self.chemic...
Python
nomic_cornstack_python_v1
function evaluate_result self m begin string Generate a Result instance for the given regex match object comment ok, figure the fixed fields we've pulled out and type convert them set fixed_fields = list call groups for n in _fixed_fields begin if n in _type_conversions begin set fixed_fields at n = call fixed_fields a...
def evaluate_result(self, m): '''Generate a Result instance for the given regex match object''' # ok, figure the fixed fields we've pulled out and type convert them fixed_fields = list(m.groups()) for n in self._fixed_fields: if n in self._type_conversions: fi...
Python
jtatman_500k
function homomorphic_envelope x fs=1000 f_LPF=8 order=3 begin set tuple b a = call butter order 2 * f_LPF / fs string low set he = exp filtfilt b a log absolute call hilbert x set he at 0 = he at 1 return he end function
def homomorphic_envelope(x, fs=1000, f_LPF=8, order=3): b, a = butter(order, 2 * f_LPF / fs, 'low') he = np.exp(filtfilt(b, a, np.log(np.abs(hilbert(x))))) he[0] = he[1] return he
Python
nomic_cornstack_python_v1
comment Callista Dominique with Nadhiva comment fist option set n = 100 function this_is_result begin set result = formula1 - formula2 print string b - a : + string result end function comment 1^2 + 2^2 + 3^2....+ n^2 set formula1 = 2 * n ^ 3 + 3 * n ^ 2 + n / 6 comment (1+2+3....)^2 set formula2 = n ^ 4 + 2 * n ^ 3 + ...
#Callista Dominique with Nadhiva #fist option n = 100 def this_is_result(): result = formula1 - formula2 print("b - a : " + str(result)) # 1^2 + 2^2 + 3^2....+ n^2 formula1 = ((2*n**3) + (3*n**2) + (n)) / 6 # (1+2+3....)^2 formula2 = ((n**4) + (2*n**3) + (n**2)) / 4 print("a : " + str(formula1)) print("b : " +...
Python
zaydzuhri_stack_edu_python
function init_weights self backbone_path begin comment Initialize the backbone with the pretrained weights. call init_backbone backbone_path set conv_constants = get attribute conv 2d 1 1 1 string __constants__ comment Quick lambda to test if one list contains the other function all_in x y begin for _x in x begin if _x...
def init_weights(self, backbone_path): # Initialize the backbone with the pretrained weights. self.backbone.init_backbone(backbone_path) conv_constants = getattr(nn.Conv2d(1, 1, 1), '__constants__') # Quick lambda to test if one list contains the other def all_in(x, y):...
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.common.by import By from base.driver_service import SeleniumDriver import time class LoginPage extends SeleniumDriver begin function __init__ self driver begin call __init__ driver set driver = driver end function comment Locators set link_login = string //a[contai...
from selenium import webdriver from selenium.webdriver.common.by import By from base.driver_service import SeleniumDriver import time class LoginPage(SeleniumDriver): def __init__(self, driver): super().__init__(driver) self.driver = driver # Locators link_login = "//a[contains(text(...
Python
zaydzuhri_stack_edu_python
for i in range 0 length a begin write f a at i write f string end set f = open string student-list.txt string r print read f close f
for i in range(0,len(a)): f.write(a[i]) f.write("\n") f=open("student-list.txt","r") print(f.read()) f.close()
Python
zaydzuhri_stack_edu_python
function GetOffsets self begin return call itkScalarImageToRunLengthFeaturesFilterIUC2_GetOffsets self end function
def GetOffsets(self) -> "itkVectorContainerUCO2 const *": return _itkScalarImageToRunLengthFeaturesFilterPython.itkScalarImageToRunLengthFeaturesFilterIUC2_GetOffsets(self)
Python
nomic_cornstack_python_v1
import requests string QUEM, ENTRE OS PAISES, FOI O MEIOR MEDALISTA DE OURO Dentre os seguintes países nórdicos: Suécia, Dinamarca e Noruega, verifique: No século XXI(a partir de 2001), qual foi o maior medalhista de ouro, considerando apenas as seguintes modalidades... modalidades: 1. Curling 2. Patinação no gelo(skat...
import requests ''' QUEM, ENTRE OS PAISES, FOI O MEIOR MEDALISTA DE OURO Dentre os seguintes países nórdicos: Suécia, Dinamarca e Noruega, verifique: No século XXI(a partir de 2001), qual foi o maior medalhista de ouro, considerando apenas as seguintes modalidades... modalidades: 1. Curling 2. Patinaç...
Python
zaydzuhri_stack_edu_python
function _write_headers self headers begin if headers begin for name in sorted keys headers begin yield name yield b': ' yield headers at name yield CRLF end end yield CRLF end function
def _write_headers(self, headers): if headers: for name in sorted(headers.keys()): yield name yield b': ' yield headers[name] yield CRLF yield CRLF
Python
nomic_cornstack_python_v1
function panZoomCtx *args alternateContext=true buttonDown=true buttonUp=true exists=true history=true image1=string image2=string image3=string name=string panMode=true toolName=string zoomMode=true zoomScale=0.0 q=true query=true e=true edit=true **kwargs begin pass end function
def panZoomCtx(*args, alternateContext: bool=True, buttonDown: bool=True, buttonUp: bool=True, exists: bool=True, history: bool=True, image1: Union[AnyStr, bool]="", image2: Union[AnyStr, bool]="", image3: Union[AnyStr, bool]="", name: AnyStr="", panMode: bool=True, toolName...
Python
nomic_cornstack_python_v1
comment 6.1 语言模型 comment 6.1 语言模型的计算 comment 假设序列w1,w2,...,wT中的每个词是依次生成的,我们有 comment P(w1,w2,...,wT) = Π(t=1,T)P(wt|w1,...,w(t-1)) comment 例如,一段含有4个词的文本序列的概率 comment P(w1,w2,w3,w4) = P(w1)P(w2|w1)P(w3|w1,w2)P(w4|w1,w2,w3) comment 为了计算语言模型,我们需要计算词在给定前几个词的情况下的条件概率, comment 即语言模型参数。设训练数据集为一个大型文本语料库,如维基百科的所有 comment 条目。词的概...
# 6.1 语言模型 # 6.1 语言模型的计算 # 假设序列w1,w2,...,wT中的每个词是依次生成的,我们有 # P(w1,w2,...,wT) = Π(t=1,T)P(wt|w1,...,w(t-1)) # 例如,一段含有4个词的文本序列的概率 # P(w1,w2,w3,w4) = P(w1)P(w2|w1)P(w3|w1,w2)P(w4|w1,w2,w3) # 为了计算语言模型,我们需要计算词在给定前几个词的情况下的条件概率, # 即语言模型参数。设训练数据集为一个大型文本语料库,如维基百科的所有 # 条目。词的概率可以通过该词在训练集的相对词频来计算。例如,P(w1)可以 # 计算为w1在训练集中的词频(词出现的次数...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string Contains the Review unittest. import os import pep8 import unittest from datetime import datetime from models.review import Review from models.base_model import BaseModel class test_review extends TestCase begin string Tests review class decorator classmethod function setUpClass cls beg...
#!/usr/bin/python3 """ Contains the Review unittest. """ import os import pep8 import unittest from datetime import datetime from models.review import Review from models.base_model import BaseModel class test_review(unittest.TestCase): """Tests review class""" @classmethod def setUpClass(cls): ...
Python
zaydzuhri_stack_edu_python
function crc16_iso14443a data begin set crc = 25443 return call crc16_iso14443ab data crc 33800 false end function
def crc16_iso14443a(data): crc= 0x6363 return crc16_iso14443ab(data, crc, 0x8408, False)
Python
nomic_cornstack_python_v1
comment %% comment ME EN 4650 Lab2: Spark Ignition Engine Ryan Dalby import numpy as np from numpy.lib.function_base import interp import pandas as pd import matplotlib.pyplot as plt import os comment Must install from matlab installation direcotry using: cd "matlabroot\extern\engines\python" && python setup.py install...
# %% # ME EN 4650 Lab2: Spark Ignition Engine Ryan Dalby import numpy as np from numpy.lib.function_base import interp import pandas as pd import matplotlib.pyplot as plt import os import matlab.engine # Must install from matlab installation direcotry using: cd "matlabroot\extern\engines\python" && python...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render , HttpResponse import random comment Create your views here. function send_sms request begin string 模拟短信发送功能 set code = call randrange 1000 9999 print code return call HttpResponse code end function from django import forms from app01 import models comment 正则模块 from django.core.valid...
from django.shortcuts import render, HttpResponse import random # Create your views here. def send_sms(request): """模拟短信发送功能""" code = random.randrange(1000, 9999) print(code) return HttpResponse(code) from django import forms from app01 import models from django.core.validators import RegexValida...
Python
zaydzuhri_stack_edu_python
set name = input string Please enter your name: print string hello, name print string 1024*768= 1024 * 768
name = input('Please enter your name:') print('hello,',name) print('1024*768=',1024*768)
Python
zaydzuhri_stack_edu_python
from minibot import * from threading import Timer from time import sleep set bot = string 00:06:66:D9:C1:4E function poke c interval begin call send string Poke! start call Timer interval poke tuple c interval end function set c = call Connection bot call poke c 1 while true begin sleep 0.05 set msg = poll c if msg beg...
from minibot import * from threading import Timer from time import sleep bot = '00:06:66:D9:C1:4E' def poke(c, interval): c.send("Poke!") Timer(interval, poke, (c, interval)).start() c = Connection(bot) poke(c, 1) while True: sleep(0.05) msg = c.poll() if msg: print(">", msg)
Python
zaydzuhri_stack_edu_python
function update a b mask value=0 begin comment one of a and b can be None if a is none begin set a = zeros like b + value end if b is none begin set b = zeros like a + value end comment find shape that fit both a and b set max_shape = list comprehension max a_ah b_sh for tuple a_sh b_sh in zip shape shape comment enlar...
def update(a, b, mask, value=0): # one of a and b can be None if a is None: a = numpy.zeros_like(b) + value if b is None: b = numpy.zeros_like(a) + value # find shape that fit both a and b max_shape = [max(a_ah, b_sh) for a_sh, b_sh in zip(a.shape, b.shape)] # enlarge a a_...
Python
nomic_cornstack_python_v1
function all self begin set rs = call SearchResultSet _document _query set _offset = _offset set _limit = _limit set _min_score = _min_score set _highlight = _highlight set _order = _order set _evaluated = _evaluated set _results = _results set _only_fields = _only_fields return rs end function
def all(self): rs = SearchResultSet(self._document, self._query) rs._offset = self._offset rs._limit = self._limit rs._min_score = self._min_score rs._highlight = self._highlight rs._order = self._order rs._evaluated = self._evaluated rs._results = self._results rs._only_fields = sel...
Python
nomic_cornstack_python_v1
comment Faça um algoritmo que leia o preço de um produto e mostreu seu novo preço com 5% de desconto. set preco = decimal input string Insira o valor do produto: set precoNovo = round preco * 0.95 3 print format string O valor do produto com 5% de desconto é R${} precoNovo
#Faça um algoritmo que leia o preço de um produto e mostreu seu novo preço com 5% de desconto. preco = float(input('Insira o valor do produto: ')) precoNovo = round((preco * 0.95),3) print('O valor do produto com 5% de desconto é R${}' .format(precoNovo))
Python
zaydzuhri_stack_edu_python
function __determine_git_ref self begin set ref_config_keys = sum generator expression boolean get args i for i in list string commit string tag string branch if ref_config_keys > 1 begin raise call ValueError string Fetching remote git sources failed: conflicting revisions (e.g. 'commit', 'tag', 'branch') specified fo...
def __determine_git_ref(self) -> str: ref_config_keys = sum( bool(self.args.get(i)) for i in ["commit", "tag", "branch"] ) if ref_config_keys > 1: raise ValueError( "Fetching remote git sources failed: conflicting revisions " "(e.g. 'commit...
Python
nomic_cornstack_python_v1
from contacto import Contacto from cita import Cita class Model begin function __init__ self begin set contactos = list set citas = list end function function esta_id self id_contacto begin for c in contactos begin if id_contacto == id_contacto begin return tuple true c end end return tuple false 0 end function comme...
from .contacto import Contacto from .cita import Cita class Model: def __init__(self): self.contactos = [] self.citas = [] def esta_id(self, id_contacto): for c in self.contactos: if c.id_contacto == id_contacto: return True, c return False, 0 ...
Python
zaydzuhri_stack_edu_python
function nice_plumbing text begin set return_text = sub string ^\s*\.* string text set return_text = sub string \.\s+\.$ string . return_text set return_text = sub string \n+$ string return_text return return_text end function
def nice_plumbing(text): return_text = re.sub(r'^\s*\.*', '', text) return_text = re.sub(r'\.\s+\.$', '.', return_text) return_text = re.sub(r'\n+$', '', return_text) return return_text
Python
nomic_cornstack_python_v1
function paper_doc_deleted cls val begin return call cls string paper_doc_deleted val end function
def paper_doc_deleted(cls, val): return cls('paper_doc_deleted', val)
Python
nomic_cornstack_python_v1
function iter_relation self begin string Iterate through all (point, element) pairs in the relation. for point in call iter_points inputs begin yield tuple point call restrict point end end function
def iter_relation(self): """Iterate through all (point, element) pairs in the relation.""" for point in iter_points(self.inputs): yield (point, self.restrict(point))
Python
jtatman_500k
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Wed Aug 16 08:10:32 2017 @author: jjcao import matplotlib.pyplot as plt import torch from transforms import Compose , Rescale , RandomCrop , Normalize , ToTensor from transforms import UnNormalize , FromTensor from visualizer import show_im_l...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 16 08:10:32 2017 @author: jjcao """ import matplotlib.pyplot as plt import torch from transforms import Compose, Rescale, RandomCrop, Normalize, ToTensor from transforms import UnNormalize, FromTensor from visualizer import show_im_label, show_im_la...
Python
zaydzuhri_stack_edu_python
from typing import List class CampusBikes begin function manhattanDistance self p1 p2 begin return absolute p1 at 0 - p2 at 0 + absolute p1 at 1 - p2 at 1 end function function assignBikes self workers bikes begin set distances = list for tuple w worker in enumerate workers begin for tuple b bike in enumerate bikes be...
from typing import List class CampusBikes: def manhattanDistance(self, p1, p2) -> int: return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]: distances = [] for w, worker in enumerate(workers): ...
Python
zaydzuhri_stack_edu_python
function nms bbox thresh score=none limit=none begin if length bbox == 0 begin return zeros tuple 0 dtype=int32 end if score is not none begin set order = call argsort at slice : : - 1 set bbox = bbox at order end set bbox_area = call prod bbox at tuple slice : : slice 2 : : - bbox at tuple slice : : slice :...
def nms(bbox, thresh, score=None, limit=None): if len(bbox) == 0: return np.zeros((0,), dtype=np.int32) if score is not None: order = score.argsort()[::-1] bbox = bbox[order] bbox_area = np.prod(bbox[:, 2:] - bbox[:, :2], axis=1) selec = np.zeros(bbox.shape[0], dtype...
Python
nomic_cornstack_python_v1
function to_even_npix self begin set width = max set binsz = max set width_npix = call to_value string set npix = call round_up_to_even width_npix return call create skydir=center_skydir binsz=binsz npix=npix proj=projection frame=frame axes=axes end function
def to_even_npix(self): width = self.width.max() binsz = self.pixel_scales.max() width_npix = (width / binsz).to_value("") npix = round_up_to_even(width_npix) return WcsGeom.create( skydir=self.center_skydir, binsz=binsz, npix=npix, ...
Python
nomic_cornstack_python_v1
function user_loc_value_to_class axis_tag user_loc begin string Return the OS/2 weight or width class that is closest to the provided user location. For weight the user location is between 0 and 1000 and for width it is a percentage. >>> user_loc_value_to_class('wght', 310) 310 >>> user_loc_value_to_class('wdth', 62) 2...
def user_loc_value_to_class(axis_tag, user_loc): """Return the OS/2 weight or width class that is closest to the provided user location. For weight the user location is between 0 and 1000 and for width it is a percentage. >>> user_loc_value_to_class('wght', 310) 310 >>> user_loc_value_to_class(...
Python
jtatman_500k
function description self description begin if description is none begin comment noqa: E501 raise call ValueError string Invalid value for `description`, must not be `None` end if description is not none and length description < 1 begin comment noqa: E501 raise call ValueError string Invalid value for `description`, le...
def description(self, description): if description is None: raise ValueError("Invalid value for `description`, must not be `None`") # noqa: E501 if description is not None and len(description) < 1: raise ValueError("Invalid value for `description`, length must be greater than or...
Python
nomic_cornstack_python_v1
function check_program self program begin set PATH = split call getenv string PATH string : for prefix in PATH begin if exists path join path prefix program begin return end end raise call SanityCheckError format string {} not installed correctly program format string `{}` not found in $PATH program end function
def check_program(self, program): PATH = os.getenv('PATH').split(':') for prefix in PATH: if os.path.exists(os.path.join(prefix, program)): return raise SanityCheckError('{} not installed correctly'.format(program), '`{}` not found in...
Python
nomic_cornstack_python_v1
function p self begin set printstdout = true end function
def p(self): self.printstdout = True
Python
nomic_cornstack_python_v1
import requests import webbrowser import time import turtle set astronaut_data = string http://api.open-notify.org/astros.json set result = json get requests astronaut_data print format string People in space {} result at string number for person in result at string people begin print person at string name + string in ...
import requests import webbrowser import time import turtle astronaut_data = 'http://api.open-notify.org/astros.json' result = requests.get(astronaut_data).json() print('People in space {}'.format(result['number'])) for person in result['people']: print(person['name'] + ' in ' + person['craft']) iss_location =...
Python
zaydzuhri_stack_edu_python
import json import os import pickle import random from tqdm import tqdm from datasets.base_dataset import BaseDataset class RedditDataset extends BaseDataset begin function __init__ self data_root conversation_length=string s begin call __init__ string reddit conversation_length set _data_file = join path data_root str...
import json import os import pickle import random from tqdm import tqdm from datasets.base_dataset import BaseDataset class RedditDataset(BaseDataset): def __init__(self, data_root, conversation_length='s'): super(RedditDataset, self).__init__('reddit', conversation_length) self._data_file = os...
Python
zaydzuhri_stack_edu_python
function other_vertices self *vertices begin set possible = vertices for element in vertices begin set possible = call differnce element end return possible end function
def other_vertices(self, *vertices): possible = self.vertices for element in vertices: possible = possible.differnce(element) return possible
Python
nomic_cornstack_python_v1
comment HTML data structure from bs4 import BeautifulSoup as soup comment Web client from urllib.request import urlopen as uReq comment mengambil url set page_url = string https://myanimelist.net/topanime.php comment membuka koneksi dan download html page dari url set uClient = call uReq page_url comment parse html men...
from bs4 import BeautifulSoup as soup # HTML data structure from urllib.request import urlopen as uReq # Web client # mengambil url page_url = "https://myanimelist.net/topanime.php" # membuka koneksi dan download html page dari url uClient = uReq(page_url) # parse html menjadi soup data structure page_soup = soup(...
Python
zaydzuhri_stack_edu_python
function create_user self name password begin string Create user with hashed password. set hashed_password = call _password_hasher password return dictionary name=name password=hashed_password end function
def create_user(self, name, password): """Create user with hashed password.""" hashed_password = self._password_hasher(password) return dict(name=name, password=hashed_password)
Python
jtatman_500k
import random import policy_runner from file_utils import open_creating_dir_if_needed from nets import Nets import MCTS_runner from policy_player import PolicyPlayer from predict_moves import PolicyNetwork comment Cross cutting parameters set run_dir = string ./results/runs/full_run set evals = 100 set value_weight = 1...
import random import policy_runner from file_utils import open_creating_dir_if_needed from nets import Nets import MCTS_runner from policy_player import PolicyPlayer from predict_moves import PolicyNetwork # Cross cutting parameters run_dir = "./results/runs/full_run" evals = 100 value_weight = 10 prior_weight = 200 ...
Python
zaydzuhri_stack_edu_python
function vm_sync vm_hostname begin with call _get_vm vm_hostname as vm begin if dataset_obj at string datacenter_type == string aws.dct begin set attributes = call aws_sync end else if dataset_obj at string datacenter_type == string kvm.dct begin call _check_defined vm set attributes = call vm_sync_from_hypervisor vm e...
def vm_sync(vm_hostname): with _get_vm(vm_hostname) as vm: if vm.dataset_obj['datacenter_type'] == 'aws.dct': attributes = vm.aws_sync() elif vm.dataset_obj['datacenter_type'] == 'kvm.dct': _check_defined(vm) attributes = vm.hypervisor.vm_sync_from_hypervisor(vm) ...
Python
nomic_cornstack_python_v1
comment for loop for x in range 5 begin print x end=string end comment while loops set count = 0 print string while count < 5 begin print count end=string set count = count + 1 end comment break print string set count = 0 while true begin print count end=string set count = count + 1 if count >= 5 begin comment break ex...
#for loop for x in range(5): print(x, end=' ') #while loops count = 0 print("\n") while count < 5: print(count, end=' ') count += 1 #break print("\n") count = 0 while True: print(count, end=' ') count += 1 if count >= 5: #break exits loop if condition is met break #continue pri...
Python
zaydzuhri_stack_edu_python
import numpy as np from import activation_abs_c as activation_abs_c comment FIXME: We really do not need to check the args everyt time we call act_func, it makes unnecessary checks. class sigmoid_act_c extends activation_abs_c begin function __init__ self k=1 begin call __init__ string sigmoid call set_k k end functio...
import numpy as np from .. import activation_abs_c as activation_abs_c # FIXME: We really do not need to check the args everyt time we call act_func, it makes unnecessary checks. class sigmoid_act_c (activation_abs_c): def __init__ (self, k = 1): super ().__init__ ("sigmoid"); self.set_k (k); def ...
Python
zaydzuhri_stack_edu_python
function _draw_status self begin if call cur_audio_length is none begin set record_length = string No recording end else begin set record_length = format string Recording length: {:.2f} seconds call cur_audio_length end call set_text record_length call set_text string call set_text format string Project audio length: {...
def _draw_status(self): if self.model.cur_audio_length() is None: record_length = "No recording" else: record_length = "Recording length: {:.2f} seconds".format(self.model.cur_audio_length()) self._audio_length_text.set_text(record_length) self._saved_text.set_tex...
Python
nomic_cornstack_python_v1
function monkey self param ignore_error_handle=false begin set message = dict set monkey_package = string get param string package none set monkey_ignore_crash = get param string ignore_crash none set monkey_ignore_anr = get param string ignore_anr none set monkey_ignore_security_exception = get param string ignore_se...
def monkey(self,param,ignore_error_handle = False): message = {}; monkey_package = str(param.get('package',None)); monkey_ignore_crash = param.get('ignore_crash',None); monkey_ignore_anr = param.get('ignore_anr',None); monkey_ignore_security_exception = param.get('ignore_security...
Python
nomic_cornstack_python_v1
function sort_list arr begin comment Insertion sort algorithm for i in range 1 length arr begin set key = arr at i set j = i - 1 while j >= 0 and key < arr at j begin set arr at j + 1 = arr at j set j = j - 1 end set arr at j + 1 = key end return arr end function set sorted_arr = call sort_list list 3 9 1 4 5
def sort_list(arr): # Insertion sort algorithm for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key return arr sorted_arr = sort_list([3, 9, 1, 4, 5])
Python
iamtarun_python_18k_alpaca
import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from gensim.test.utils import datapath from gensim import utils from gensim.parsing.preprocessing import preprocess_string , preprocess_documents from utils import * class document begin string custom class to represent comments function __i...
import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from gensim.test.utils import datapath from gensim import utils from gensim.parsing.preprocessing import preprocess_string, preprocess_documents from utils import * class document: """ custom class to represent comments """ def __in...
Python
zaydzuhri_stack_edu_python
function get_previous_sibling self **filters begin set siblings = filter keyword filters set ret_node = reverse filter order__lt=order if not ret_node begin return none end return ret_node at 0 end function
def get_previous_sibling(self, **filters): siblings = self.get_siblings().filter(**filters) ret_node = siblings.filter(order__lt=self.order).reverse() if not ret_node: return None return ret_node[0]
Python
nomic_cornstack_python_v1