code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function referenced_ports self begin string Return all Ports referenced by this Compound. Returns ------- list of mb.Compound A list of all ports referenced by the Compound from mbuild.port import Port return list comprehension port for port in values labels if is instance port Port end function
def referenced_ports(self): """Return all Ports referenced by this Compound. Returns ------- list of mb.Compound A list of all ports referenced by the Compound """ from mbuild.port import Port return [port for port in self.labels.values() ...
Python
jtatman_500k
function reachable self begin return list callsite + calls end function
def reachable(self): return [self.callsite] + self.calls
Python
nomic_cornstack_python_v1
function load_pcf instream begin set pcf_data = call _read_pcf instream set glyphs = call _convert_glyphs pcf_data set props = call _convert_props pcf_data set font = call Font glyphs keyword props return call label end function
def load_pcf(instream): pcf_data = _read_pcf(instream) glyphs = _convert_glyphs(pcf_data) props = _convert_props(pcf_data) font = Font(glyphs, **props) return font.label()
Python
nomic_cornstack_python_v1
comment 1a. Write a function that takes a string name variable as its only argument and prints hello to comment the name passed in. function greet_person name begin print string Hello { name } end function call greet_person string Tom call greet_person string Dick call greet_person string Harry comment 1b. Write anothe...
#1a. Write a function that takes a string name variable as its only argument and prints hello to #the name passed in. def greet_person(name): print(f'Hello {name}') greet_person('Tom') greet_person('Dick') greet_person('Harry') #1b. Write another function that takes a single number as an argument and returns Tr...
Python
zaydzuhri_stack_edu_python
for x in read lines file begin set komma = integer find x string , set komma1 = komma + 1 append encs x at slice : komma : append msgs x at slice komma1 : : end set enc = input string Welche Nachricht willst du entschlüsseln? set num = index encs enc set msg = msgs at num print msg
for x in file.readlines(): komma = int(x.find(",")) komma1 = komma + 1 encs.append(x[:komma]) msgs.append(x[komma1:]) enc = input("Welche Nachricht willst du entschlüsseln? ") num = encs.index(enc) msg = msgs[num] print(msg)
Python
zaydzuhri_stack_edu_python
import numpy as np from sklearn.svm import SVC from matplotlib import pyplot as plt comment x = np.array([[0,0],[0,1],[1,0],[1,1]],dtype=np.float) comment y = np.array([0,1,1,0],dtype=np.float) comment plt.scatter(x[:,0],x[:,1]) comment plt.show() set X = randn 200 2 set X_train = X at tuple slice : 150 : slice : :...
import numpy as np from sklearn.svm import SVC from matplotlib import pyplot as plt # x = np.array([[0,0],[0,1],[1,0],[1,1]],dtype=np.float) # y = np.array([0,1,1,0],dtype=np.float) # plt.scatter(x[:,0],x[:,1]) # plt.show() X = np.random.randn(200,2) X_train = X[:150,:] X_test = X[150:,:] y_train = np.l...
Python
zaydzuhri_stack_edu_python
function test_phv_test_queries_with_phv_in_string self begin set url = call get_url for query in TEST_PHV_QUERIES begin set response = get client url dict string q string phv + query set returned_pks = call get_autocomplete_view_ids response set expected_matches = TEST_PHV_QUERIES at query comment Make sure number of m...
def test_phv_test_queries_with_phv_in_string(self): url = self.get_url() for query in TEST_PHV_QUERIES: response = self.client.get(url, {'q': 'phv' + query}) returned_pks = get_autocomplete_view_ids(response) expected_matches = TEST_PHV_QUERIES[query] # Ma...
Python
nomic_cornstack_python_v1
function add_parent_success self parent begin append success self end function
def add_parent_success(self, parent): parent.success.append(self)
Python
nomic_cornstack_python_v1
function symDistance args begin set tuple pair1 pair2 = args set tuple seq1 triple1 = pair1 set tuple seq2 triple2 = pair2 set hmm1 = call tripleToHMM triple1 set hmm2 = call tripleToHMM triple2 set s1_m2 = call loglikelihood call toSequence seq1 set s2_m1 = call loglikelihood call toSequence seq2 end function
def symDistance(args): pair1, pair2 = args seq1, triple1 = pair1 seq2, triple2 = pair2 hmm1 = tripleToHMM(triple1) hmm2 = tripleToHMM(triple2) s1_m2 = hmm2.loglikelihood(toSequence(seq1)) s2_m1 = hmm1.loglikelihood(toSequence(seq2))
Python
nomic_cornstack_python_v1
function convert_dict_to_df res_a res_b platform_a platform_b begin set tuple p1_strings p1_counters = list zip *list(res_a.items()) set p1_names = list comprehension string { platform_a } for _ in range length p1_strings set tuple p2_strings p2_counters = list zip *list(res_b.items()) set p2_names = list comprehension...
def convert_dict_to_df(res_a, res_b, platform_a, platform_b): p1_strings, p1_counters = list(zip(*list(res_a.items()))) p1_names = [f"{platform_a}" for _ in range(len(p1_strings))] p2_strings, p2_counters = list(zip(*list(res_b.items()))) p2_names = [f"{platform_b}" for _...
Python
nomic_cornstack_python_v1
function send_animation self address animation=string simon begin call publish address dumps ANIMATIONS at animation end function
def send_animation(self, address, animation='simon'): self.publish(address, json.dumps(ANIMATIONS[animation]))
Python
nomic_cornstack_python_v1
for n in a begin if is digit n begin append b n end end print integer join string b
for n in a : if n.isdigit(): b.append(n) print(int("".join(b)))
Python
zaydzuhri_stack_edu_python
function countCond kata begin set cond = false set cond1 = count kata string h set cond2 = count kata string a set cond3 = count kata string c set cond4 = count kata string k set cond5 = count kata string e set cond6 = count kata string r set cond7 = count kata string t if cond1 >= 2 and cond2 >= 2 and cond3 >= 2 and c...
def countCond(kata): cond = False cond1 = kata.count('h') cond2 = kata.count('a') cond3 = kata.count('c') cond4 = kata.count('k') cond5 = kata.count('e') cond6 = kata.count('r') cond7 = kata.count('t') if cond1 >= 2 and cond2 >= 2 and cond3 >= 2 and cond4 >= 1 and cond5 >= 1 and cond...
Python
zaydzuhri_stack_edu_python
for i in reversed range 1 11 begin print i end
for i in reversed(range(1,11)): print(i)
Python
flytech_python_25k
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: import numpy as np , pandas as pd from statsmodels.graphics.tsaplots import plot_acf , plot_pacf import matplotlib.pyplot as plt import itertools call use string fivethirtyeight update rcParams dict string figure.figsize tuple 15 7 ; string figure.dpi 12...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np, pandas as pd from statsmodels.graphics.tsaplots import plot_acf, plot_pacf import matplotlib.pyplot as plt import itertools plt.style.use('fivethirtyeight') plt.rcParams.update({'figure.figsize':(15,7), 'figure.dpi':120}) # In[3]: ov = pd.read_cs...
Python
zaydzuhri_stack_edu_python
function blockify source begin set paragraphs = list string for line in split strip source string begin set line = strip line if line begin set paragraphs at - 1 = paragraphs at - 1 + line + string end else if paragraphs at - 1 begin append paragraphs string end end return paragraphs end function
def blockify(source): paragraphs = [""] for line in source.strip().split("\n"): line = line.strip() if line: paragraphs[-1] += line + " " elif paragraphs[-1]: paragraphs.append("") return paragraphs
Python
nomic_cornstack_python_v1
function preloop self begin comment handle any auto-commands for this cmdloop run comment handle any auto-commands set by the game (ag) comment auto-commanding when needed global PLAY_COMMAND_QUEUE comment do any auto-comments set cmdqueue = PLAY_COMMAND_QUEUE comment set any auto-command we want the nex cmploop to run...
def preloop(self): # handle any auto-commands for this cmdloop run # handle any auto-commands set by the game (ag) global PLAY_COMMAND_QUEUE # auto-commanding when needed self.cmdqueue = PLAY_COMMAND_QUEUE # do any auto-comments # se...
Python
nomic_cornstack_python_v1
function insert_graph graph v1 v2 road_type=none begin if v1 not in keys graph begin set graph at v1 = list end if road_type == none begin append graph at v1 v2 end else begin append graph at v1 tuple v2 road_type end return graph end function function get_edges graph road_type begin set qualifiying_edges = list for ...
def insert_graph(graph, v1, v2, road_type=None): if v1 not in graph.keys(): graph[v1] = [] if road_type == None: graph[v1].append(v2) else: graph[v1].append((v2,road_type)) return graph def get_edges(graph, road_type): qualifiying_edges = [] for vertex, edges in graph.items(): for edge in edges: if ed...
Python
zaydzuhri_stack_edu_python
comment MOTOR DE BUSQUEDA comment Rastreo de sitios a traves de la barra de búsqueda import requests from bs4 import BeautifulSoup class Content begin string Clase para contenidos de algun articulo de pagina web function __init__ self topic url title body begin set topic = topic set title = title set body = body set ur...
#MOTOR DE BUSQUEDA #Rastreo de sitios a traves de la barra de búsqueda import requests from bs4 import BeautifulSoup class Content: ''' Clase para contenidos de algun articulo de pagina web ''' def __init__(self, topic, url, title, body): self.topic = topic self.title = t...
Python
zaydzuhri_stack_edu_python
function test_transpose_words_in_list_not_string begin assert call transpose_words_in_list list string abc string abcde 12345 is none end function
def test_transpose_words_in_list_not_string(): assert transpose.transpose_words_in_list(["abc", "abcde", 12345]) is None
Python
nomic_cornstack_python_v1
async function difference self ctx query begin if not query begin set query = string X Y end set urlquery = join string + split query set emb = call green_embed string A lot of 'what is the difference between X and Y' kinds of questions can be answered by typing something like the following into google (click the links...
async def difference(self, ctx, *, query): if not query: query = "X Y" urlquery = '+'.join(query.split()) emb = hf.green_embed(f"A lot of 'what is the difference between X and Y' kinds of questions can be answered " f"by typing something like the followin...
Python
nomic_cornstack_python_v1
function test_poisson self begin set nt = 50 set ns = 1000 set num_giter = 5 set net = poisson set times = list for i in range ns begin set arrv = random sample nt set obs = call subset lambda a e -> call is_last_in_queue e copy_evt set gsmp = call gibbs_resample arrv 0 num_giter set resampled = gsmp at - 1 set evts =...
def test_poisson(self): nt = 50 ns = 1000 num_giter = 5 net = self.poisson times = [] for i in range(ns): arrv = net.sample (nt) obs = arrv.subset (lambda a,e: a.is_last_in_queue(e), copy_evt) gsmp = net.gibbs_resample (arrv, 0, num_gi...
Python
nomic_cornstack_python_v1
function test_monitoring_application self mock_config begin set return_value = none set plugin = call KubeJobProgress app_id info_plugin collect_period retries set rds = call MockRedis set b_v1 = call MockKube app_id set datasource = call MockInfluxConnector for i in range 5 begin call rpush string job string job end f...
def test_monitoring_application(self, mock_config): mock_config.return_value = None plugin = KubeJobProgress(self.app_id, self.info_plugin, self.collect_period, self.retries) plugin.rds = MockRedis() plugin.b_v1 = MockKube(plugin.app_id) plugin.d...
Python
nomic_cornstack_python_v1
import pygame import resources.Resources as Resources from pygame.locals import * set COLOR_INACTIVE = call Color string lightskyblue3 set COLOR_ACTIVE = call Color string dodgerblue2 class TextBox begin function __init__ self x y width height text=string begin set x = x set y = y set width = width set height = height ...
import pygame import resources.Resources as Resources from pygame.locals import * COLOR_INACTIVE = pygame.Color("lightskyblue3") COLOR_ACTIVE = pygame.Color("dodgerblue2") class TextBox: def __init__(self, x, y, width, height, text=""): self.x = x self.y = y self.width = width sel...
Python
zaydzuhri_stack_edu_python
function clone self begin return call QuatSphericalLinearChannel_clone self end function
def clone(self): return _osgAnimation.QuatSphericalLinearChannel_clone(self)
Python
nomic_cornstack_python_v1
comment You have been given an array A of size N consisting of positive integers. comment You need to find and print the product of all the number in this array Modulo . comment Input Format: comment The first line contains a single integer N denoting the size of the array. comment The next line contains N space separa...
# You have been given an array A of size N consisting of positive integers. # You need to find and print the product of all the number in this array Modulo . # Input Format: # The first line contains a single integer N denoting the size of the array. # The next line contains N space separated integers denoting the el...
Python
zaydzuhri_stack_edu_python
function SetServerInformation self server port begin set hostname = server set port = port end function
def SetServerInformation(self, server, port): self.hostname = server self.port = port
Python
nomic_cornstack_python_v1
function Agendamiento eventos begin comment Inicializar diccionario set agenda = dict comment Ciclo para agregar un nuevo evento for tuple fEvento hEvento aEvento in eventos begin comment Fuerza la entrada if get agenda fEvento == none begin comment Creacion de un nuevo evento set agenda at fEvento = list end comment...
def Agendamiento(eventos: list): agenda={} #Inicializar diccionario for fEvento,hEvento,aEvento in eventos: #Ciclo para agregar un nuevo evento if agenda.get(fEvento) == None: #Fuerza la entrada agenda[fEvento] = [] #Creacion de un nuevo evento ...
Python
zaydzuhri_stack_edu_python
function create_logger app begin set Logger = call getLoggerClass class DebugLogger extends Logger begin function getEffectiveLevel self begin if level == 0 and debug begin return DEBUG end return call getEffectiveLevel self end function end class class DebugHandler extends StreamHandler begin function emit self record...
def create_logger(app): Logger = getLoggerClass() class DebugLogger(Logger): def getEffectiveLevel(self): if self.level == 0 and app.debug: return DEBUG return Logger.getEffectiveLevel(self) class DebugHandler(StreamHandler): def emit(self, record): ...
Python
nomic_cornstack_python_v1
function bubble_sort arr begin comment Always aim for O(nlogn) set swap_occurred = true while swap_occurred begin set swap_occurred = false for num in range length arr - 1 begin if arr at num > arr at num + 1 begin comment print("Swapping....") set swap_occurred = true set tuple arr at num arr at num + 1 = tuple arr at...
def bubble_sort(arr): # Always aim for O(nlogn) swap_occurred = True while swap_occurred: swap_occurred = False for num in range(len(arr) - 1): if arr[num] > arr[num + 1]: # print("Swapping....") swap_occurred = True arr[num],arr[nu...
Python
zaydzuhri_stack_edu_python
import socket import time comment from random import randint set HOST = string 127.0.0.1 comment HOST = '10.202.104.153' set listen_PORT = 5678 set send_PORT = 1234 set s = call socket AF_INET SOCK_STREAM call bind tuple HOST PORT call listen 5 for i in range 1 11 begin set tuple conn addr = call accept print string Co...
import socket import time #from random import randint HOST = '127.0.0.1' #HOST = '10.202.104.153' listen_PORT = 5678 send_PORT = 1234 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(5) for i in range(1,11) : conn, addr = s.accept() print('Connected...
Python
zaydzuhri_stack_edu_python
function merge_zip_files feature_branch_content_zip_file_path artifacts_zip_path original_zip_path begin rename artifacts_zip_path original_zip_path set unified_zip = zip file artifacts_zip_path string a ZIP_DEFLATED with zip file original_zip_path string r as master_zip begin set feature_zip = zip file feature_branch_...
def merge_zip_files(feature_branch_content_zip_file_path, artifacts_zip_path, original_zip_path): os.rename(artifacts_zip_path, original_zip_path) unified_zip = z.ZipFile(artifacts_zip_path, 'a', z.ZIP_DEFLATED) with z.ZipFile(original_zip_path, 'r') as master_zip: feature_zip = z.ZipFile(feature_br...
Python
nomic_cornstack_python_v1
import numpy as np set a = array range 9 print a set b = a at slice : 5 : set c = a at slice 5 : : set d = a at slice 1 : 5 : 2 comment reverse set e = a at slice 8 : : - 1 print b print c print d print e
import numpy as np a=np.arange(9) print(a) b=a[:5] c=a[5:] d=a[1:5:2] e=a[8::-1]#reverse print(b) print(c) print(d) print(e)
Python
zaydzuhri_stack_edu_python
function get_formatted_prop_t ents_dict qid pid i begin return call format_t call get_prop_t call get_prop ents_dict=ents_dict qid=qid pid=pid i end function
def get_formatted_prop_t(ents_dict, qid, pid, i): return format_t(get_prop_t(get_prop(ents_dict=ents_dict, qid=qid, pid=pid), i))
Python
nomic_cornstack_python_v1
string * You can work both operating system windows and linux below way import os import platform if call system == string Windows begin call system string cls end else begin comment -- Linux like operating system call system string clear end
''' * You can work both operating system windows and linux below way ''' import os import platform if platform.system() == 'Windows': os.system('cls') else: os.system('clear') # -- Linux like operating system
Python
zaydzuhri_stack_edu_python
function capability_definition_validator field presentation context capability_value node_obj node_variant begin set the_parent_capability_type_name = capability set the_parent_node_type_name = node if node_obj begin call _is_capability_in_node context node_variant node_obj presentation field capability_value end if th...
def capability_definition_validator(field, presentation, context, capability_value, node_obj, node_variant): the_parent_capability_type_name = _get_requirement_in_type(context, presentation).\ capability the_parent_node_type_name ...
Python
nomic_cornstack_python_v1
function breakingRecords scores begin set min = scores at 0 set max = scores at 0 set tuple lose gain = tuple 0 0 for i in range 1 length scores begin if scores at i < min begin set lose = lose + 1 set min = scores at i end else if scores at i > max begin set gain = gain + 1 set max = scores at i end end print gain los...
def breakingRecords(scores): min = scores[0] max = scores[0] lose, gain=0,0 for i in range(1, len(scores)): if scores[i]<min: lose+=1 min=scores[i] elif scores[i]>max: gain+=1 max=scores[i] print (gain, lose) breakingRecords...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment import comand line related libraries import sys , getopt comment helper functions
#!/usr/bin/python # import comand line related libraries import sys, getopt #helper functions
Python
zaydzuhri_stack_edu_python
function Even_Fibonacci_numbers max_limit begin set temp = 0 set total = 0 set num1 = 0 set num2 = 1 while temp < max_limit begin set temp = num1 + num2 set num1 = num2 set num2 = temp if temp % 2 == 0 begin set total = total + temp end end return total end function call Even_Fibonacci_numbers 4000000
def Even_Fibonacci_numbers(max_limit): temp = 0 total = 0 num1 = 0 num2 = 1 while temp < max_limit: temp = num1 + num2 num1 = num2 num2 = temp if temp%2 == 0: total+=temp return total Even_Fibonacci_numbers(4000000)
Python
zaydzuhri_stack_edu_python
function __init__ self begin call __init__ self call __init__ self set _adsense = call Adsense set _event = event set _username = none set _password = none set _autoupdate = false set _updaterate = 0.0 set _quit = false set _login_valid = false call set_status STATUS_NO end function
def __init__(self): threading.Thread.__init__(self) gobject.GObject.__init__(self) self._adsense = Adsense.Adsense() self._event = threading.Event() self._username = None self._password = None self._autoupdate = False self._updaterate = 0.0 self._q...
Python
nomic_cornstack_python_v1
import pandas as pd function mean_rolling_window df attr_name winsize=2 extended=true begin string For each row (and for each sku) compute the MEAN of n previous rows (extended -> all previous rows) @param df: @param attr_name: name of the column to take into account @param winsize: with extended keep it always 2 @para...
import pandas as pd def mean_rolling_window(df, attr_name: str, winsize=2, extended=True) -> pd.DataFrame: """ For each row (and for each sku) compute the MEAN of n previous rows (extended -> all previous rows) @param df: @param attr_name: name of the column to take into account @param winsize: wi...
Python
zaydzuhri_stack_edu_python
function add config args begin if args == list begin call help return end set tuple amount context date = tuple 0 string string for arg in args begin if match string ^[0-9]*([\.,][0-9]{0,2}){0,1}$ arg and not amount begin set amount = decimal replace arg string , string . end else if starts with arg string @ and len...
def add(config, args): if args == []: help() return amount, context, date = 0, "", "" for arg in args: if re.match("^[0-9]*([\.,][0-9]{0,2}){0,1}$", arg) and not amount: amount = float(arg.replace(',', '.')) elif arg.startswith("@") and (len(arg) > 1): context = ','.join([context, arg[1:]]) elif not ...
Python
nomic_cornstack_python_v1
comment case 1 set a = string Hello set b = string World set c = a + b print c comment case 2 set a = string Hello set b = string World set c = a + string + b print c
#case 1 a = "Hello" b = "World" c = a+b print(c) #case 2 a = "Hello" b = "World" c = a+" "+b print(c)
Python
zaydzuhri_stack_edu_python
function test_mosaic_segmentation_model self input_size pyramid_pool_bin_nums decoder_input_levels decoder_stage_merge_styles begin set num_classes = 32 call set_image_data_format string channels_last set backbone = call MobileNet model_id=string MobileNetMultiAVGSeg set encoder_input_level = 4 comment Create a regular...
def test_mosaic_segmentation_model(self, input_size, pyramid_pool_bin_nums, decoder_input_levels, decoder_stage_merge_styles): num_classes = 32 tf.keras.backend.set_image_data_format('channels_last') backbone = backbones.MobileNet(mod...
Python
nomic_cornstack_python_v1
set n = integer input set arr = list 0 0 0 set arr at 0 = integer input set arr at 1 = integer input set arr at 2 = n - sum arr print max arr
n = int(input()) arr = [0, 0, 0] arr[0] = int(input()) arr[1] = int(input()) arr[2] = n - sum(arr) print(max(arr))
Python
zaydzuhri_stack_edu_python
from relation_app.ext import db comment "一方" class School extends Model begin set __tablename__ = string schools set id = call Column Integer primary_key=true autoincrement=true set name = call Column call String 20 nullable=false set address = call Column call String 50 comment 关联学生模型,并设置反向引用名称 set students = call rel...
from relation_app.ext import db class School(db.Model): # "一方" __tablename__ = "schools" id = db.Column(db.Integer,primary_key=True,autoincrement=True) name = db.Column(db.String(20),nullable=False) address = db.Column(db.String(50)) students = db.relationship("Student",backref="sch") # 关联学生模型,并...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment coding=utf-8 comment title : uni_cgi.py comment description : unicode cgi comment author : JackieTsui comment organization : pytoday.org comment date : 2018/9/14 22:18 comment email : jackietsui72@gmail.com comment notes : comment ================================================== ...
#!/usr/bin/env python3 # coding=utf-8 # title : uni_cgi.py # description : unicode cgi # author : JackieTsui # organization : pytoday.org # date : 2018/9/14 22:18 # email : jackietsui72@gmail.com # notes : # ================================================== # Import t...
Python
zaydzuhri_stack_edu_python
import signal import serial import time , wave import sys import glob import math import numpy import pyaudio from random import randint import atexit set baudrate = 115200 set timeout = 0 set testResponse = string A set waitIterations = 5 set duration = 0.06 set freq = 450 set samplingRate = 44100 function serial_port...
import signal import serial import time, wave import sys import glob import math import numpy import pyaudio from random import randint import atexit baudrate=115200 timeout=0 testResponse='A' waitIterations=5 duration=0.06 freq=450 samplingRate=44100 def serial_ports(): foundPort=False """ Lists serial port ...
Python
zaydzuhri_stack_edu_python
import os import json import logging import argparse import numpy as np import regressor as reg import keras.backend as K function absolute_sum_error y_true y_pred begin return mean K absolute y_true - y_pred end function if __name__ == string __main__ begin set parser = call ArgumentParser description=string Script to...
import os import json import logging import argparse import numpy as np import regressor as reg import keras.backend as K def absolute_sum_error(y_true, y_pred): return K.mean(K.abs(y_true - y_pred)) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Script to train the sasa models fro...
Python
zaydzuhri_stack_edu_python
import numpy as np import cv2 comment 각자의 도형을 그리는 함수가 있음. 함수마다 약간의 옵션이 다름. comment 직선 그리기 comment cv2.line(img, pt1, pt2, color, thickness, lineType, shift, ...) comment img : 그릴 영상(캔버스, 도화지) comment pt1, pt2 : 선의 시작점, 끝점(튜플) comment color : 색상, thickness: 선의 두께(기본값 1) comment lineType : 선타입(cv2.LINE_4, cv2.LINE_8(기본값)...
import numpy as np import cv2 # 각자의 도형을 그리는 함수가 있음. 함수마다 약간의 옵션이 다름. ### 직선 그리기 # cv2.line(img, pt1, pt2, color, thickness, lineType, shift, ...) # img : 그릴 영상(캔버스, 도화지) # pt1, pt2 : 선의 시작점, 끝점(튜플) # color : 색상, thickness: 선의 두께(기본값 1) # lineType : 선타입(cv2.LINE_4, cv2.LINE_8(기본값), cv2.LINE_AA(주로 많이 씀. 안티앨리어...
Python
zaydzuhri_stack_edu_python
function saveGame self state fileName begin try begin set file at fileName = state end except any begin print string No file specified, please load file first. end end function
def saveGame(self, state, fileName): try: self.file[fileName] = state except: print('No file specified, please load file first.')
Python
nomic_cornstack_python_v1
import pandas as pd import pdb from FitnessEstimator import FitnessEstimator from VariantQuartiles import load_variant_quartiles from load_data import create_gene_df_stratified from load_data import get_coverage_filter function load_df strat_df_file begin set mut_rates_path = string input_data/mutation_probabilities.xl...
import pandas as pd import pdb from FitnessEstimator import FitnessEstimator from VariantQuartiles import load_variant_quartiles from load_data import create_gene_df_stratified from load_data import get_coverage_filter def load_df(strat_df_file): mut_rates_path = 'input_data/mutation_probabilities.xls' mutati...
Python
zaydzuhri_stack_edu_python
function setWarningLogFile self fname=none begin if file begin comment May raise an exception (for user to deal with) set warnfd = open fname string a end else begin set warnfd = stdout end end function
def setWarningLogFile(self, fname = None): if(file): # May raise an exception (for user to deal with) self.warnfd = open(fname, 'a') else: self.warnfd = stdout
Python
nomic_cornstack_python_v1
function amIcut self begin if call contains myCell begin set myStringCode = string 1 return false end else if call intersects Domain begin set myStringCode = string 2 return true end else begin set myStringCode = string 0 return false end end function
def amIcut(self): if self.Domain.contains(self.myCell): self.myStringCode = '1' return False elif self.myCell.intersects(self.Domain): self.myStringCode = '2' return True else: self.myStringCode...
Python
nomic_cornstack_python_v1
from keras.models import Model from keras.layers import Conv1D , LSTM , BatchNormalization , Flatten , Dense , Activation , Input , concatenate from keras.models import Sequential from keras.layers.wrappers import Bidirectional from keras.optimizers import Nadam from clr_callback import CyclicLR import keras.backend as...
from keras.models import Model from keras.layers import (Conv1D, LSTM, BatchNormalization, Flatten, Dense, Activation, Input, concatenate) from keras.models import Sequential from keras.layers.wrappers import Bidirectional from keras.optimizers import Nadam from clr_callback import CyclicLR i...
Python
zaydzuhri_stack_edu_python
import pytest from fixtures.store_item.model import Item from fixtures.store_item.model import ItemResponse class TestStoreItem begin decorator positive function test_change_item self app item begin string Steps. 1. Register new user 2. Access to store with valid data 3. Add user info 4. Add store 5. Add item 6. Try to...
import pytest from fixtures.store_item.model import Item from fixtures.store_item.model import ItemResponse class TestStoreItem: @pytest.mark.positive def test_change_item(self, app, item): """ Steps. 1. Register new user 2. Access to store with valid data ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import os import argparse comment this function copy files unless it got argument move as True, then comment instead of copying the file it moving the file
#!/usr/bin/python import os import argparse # this function copy files unless it got argument move as True, then # instead of copying the file it moving the file
Python
zaydzuhri_stack_edu_python
from pydub import AudioSegment from scipy.io.wavfile import read as read_wav import shutil import tempfile class MP3Reader begin function __init__ self begin set TMP_DIR = make dir temp set EXPORT_PATH = TMP_DIR + string /export.wav end function function __del__ self begin string Removes the temporary directory before ...
from pydub import AudioSegment from scipy.io.wavfile import read as read_wav import shutil import tempfile class MP3Reader: def __init__(self): self.TMP_DIR = tempfile.mkdtemp() self.EXPORT_PATH = self.TMP_DIR + '/export.wav' def __del__(self): """Removes the temporary directory befor...
Python
zaydzuhri_stack_edu_python
import sys set s = argv at 1 set prefix = argv at 2
import sys s = sys.argv[1] prefix = sys.argv[2]
Python
zaydzuhri_stack_edu_python
import markup import os import pytest import tempfile import re function test_tokenize_symbols begin set output = call terminal 0 set text = string _`*+-#<> set tokens = call tokenize text string string output at 0 assert call __str__ == string <type: UNDERSCORE, value: SYM><type: GRAVE, value: SYM><type: STAR, value...
import markup import os import pytest import tempfile import re def test_tokenize_symbols(): output = markup.terminal.terminal(0) text = "_`*+-#<>\t\n" tokens = markup.tokenize.tokenize(text, "", "", output)[0] assert tokens.__str__() == '<type: UNDERSCORE, value: SYM><type: GRAVE, value: S...
Python
zaydzuhri_stack_edu_python
class Solution begin function maximumGap self A begin set maxRightNumbers = list set minLeftNumbers = list for elem in A begin if not minLeftNumbers or elem < minLeftNumbers at - 1 begin append minLeftNumbers elem end else begin append minLeftNumbers minLeftNumbers at - 1 end end for elem in reversed A begin if not m...
class Solution: def maximumGap(self, A): maxRightNumbers = [] minLeftNumbers = [] for elem in A: if not minLeftNumbers or elem<minLeftNumbers[-1]: minLeftNumbers.append(elem) else: minLeftNumbers.append(minLeftNumbers[-1]) for elem in reversed(A): if not maxRightNumbers or elem>maxRightNumb...
Python
zaydzuhri_stack_edu_python
function is_prime n begin string This function checks if a number is prime or not. It does this by checking if the number is divisible by any number up to its square root. If it is, it's not a prime number. If it isn't, it is a prime number. if n == 1 begin return false end else if n == 2 begin return true end else beg...
def is_prime(n): """ This function checks if a number is prime or not. It does this by checking if the number is divisible by any number up to its square root. If it is, it's not a prime number. If it isn't, it is a prime number. """ if n == 1: return False elif n == 2: retur...
Python
jtatman_500k
import sys function reducer begin set airports = 0 set oldKey = none set max_total = 0 for line in stdin begin set value_data = split strip line string if length value_data != 2 begin continue end set tuple thisKey c = value_data if oldKey and oldKey != thisKey begin if airports > max_total begin set max_region = oldKe...
import sys def reducer(): airports=0 oldKey=None max_total=0 for line in sys.stdin: value_data=line.strip().split(" ") if(len(value_data)!=2): continue thisKey, c = value_data if oldKey and oldKey!=thisKey: if(airports>max_total): ...
Python
zaydzuhri_stack_edu_python
function uadapterplot adapter_content adapter_names=none outfile=none inline=false height=40 bar_width=10 spacing=2 multi_bar=false begin comment Width of plot required for each bar set width = bar_width + spacing * 2 comment Colours for each adapter set fg_colors = tuple string red string blue string green string blac...
def uadapterplot(adapter_content,adapter_names=None,outfile=None, inline=False,height=40,bar_width=10,spacing=2, multi_bar=False): # Width of plot required for each bar width = bar_width + spacing*2 # Colours for each adapter fg_colors = ('red','blue','green','black') ...
Python
nomic_cornstack_python_v1
string This is an interactive widget program to convert Miles to kms. comment Importing the necessary libraries and modules import tkinter as tk from tkinter.constants import END function miles_to_km begin set miles = decimal get miles_input set km = miles * 1.609 call config text=string { km } end function comment Cre...
""" This is an interactive widget program to convert Miles to kms.""" # Importing the necessary libraries and modules import tkinter as tk from tkinter.constants import END def miles_to_km(): miles = float(miles_input.get()) km = miles * 1.609 km_result_label.config(text = f"{km}") #Creating a new windo...
Python
zaydzuhri_stack_edu_python
from Textures import * class Player begin function __init__ self position begin comment x position of a player set x_pos = position at 0 comment y position of a player set y_pos = position at 1 comment flags the desire of a player to move left set move_left = false comment flags the desire of a player to move right set...
from Textures import * class Player: def __init__(self, position): self.x_pos = position[0] # x position of a player self.y_pos = position[1] # y position of a player self.move_left = False # flags the desire of a player to move left self.move_right = False # flags the desire o...
Python
zaydzuhri_stack_edu_python
function range_freq_of_linear L R a b mod lo hi begin if lo >= hi begin return 0 end assert 0 <= lo and lo < hi and hi <= mod set x1 = call floor_sum_of_linear L R a b - lo mod set x2 = call floor_sum_of_linear L R a b - hi mod return x1 - x2 end function
def range_freq_of_linear(L: int, R: int, a: int, b: int, mod: int, lo: int, hi: int) -> int: if lo >= hi: return 0 assert 0 <= lo and lo < hi and hi <= mod x1 = floor_sum_of_linear(L, R, a, b - lo, mod) x2 = floor_sum_of_linear(L, R, a, b - hi, mod) return x1 - x2
Python
nomic_cornstack_python_v1
function tobs begin comment Create our session (link) from Python to the DB set session = call Session engine comment Initializing an empty dict to hold the precipitation data for each date comment in list_of_dates_in_a_year set tobs_dict = dict comment Initializing an index value for use in the following for-loop set...
def tobs(): # Create our session (link) from Python to the DB session = Session(engine) # Initializing an empty dict to hold the precipitation data for each date # in list_of_dates_in_a_year tobs_dict = {} # Initializing an index value for use in the following for-loop ind = 0 # Using a ...
Python
nomic_cornstack_python_v1
comment coins.py comment coin image from clipartlord.com import pygame from pygame.locals import * from pygamegame import * class Coins extends Sprite begin function __init__ self x y begin set x = x set y = y set surf = load image string modules/coin.png set rect = call get_rect end function end class
#coins.py # coin image from clipartlord.com import pygame from pygame.locals import * from pygamegame import * class Coins(pygame.sprite.Sprite): def __init__(self, x, y): self.x = x self.y = y self.surf = pygame.image.load('modules/coin.png') rect = self.surf.get_rect()
Python
zaydzuhri_stack_edu_python
string Common functions for drive_train.py and drive_test.py from dltoolkit.iomisc import HDF5Reader from dltoolkit.utils.image import rgb_to_gray , normalise , clahe_equalization , adjust_gamma import numpy as np from PIL import Image function crop_image imgs img_height img_width begin string Cut off the top and botto...
"""Common functions for drive_train.py and drive_test.py""" from dltoolkit.iomisc import HDF5Reader from dltoolkit.utils.image import rgb_to_gray, normalise, clahe_equalization, adjust_gamma import numpy as np from PIL import Image def crop_image(imgs, img_height, img_width): """Cut off the top and bottom pixel ...
Python
zaydzuhri_stack_edu_python
import shutil import os import re from urllib.request import urlopen from urllib.parse import urlsplit , urlunsplit , quote function get_filename url begin return call safe_characters split url string / at - 1 end function function encode_uri uri begin set chunks = list call urlsplit uri set chunks at 2 = quote chunks ...
import shutil import os import re from urllib.request import urlopen from urllib.parse import urlsplit, urlunsplit, quote def get_filename(url): return safe_characters(url.split('/')[-1]) def encode_uri(uri): chunks = list(urlsplit(uri)) chunks[2] = quote(chunks[2]) uri = urlunsplit(chunks) retu...
Python
zaydzuhri_stack_edu_python
function setVY self v_xyz begin set v_xyz = call normalize3 v_xyz set self at tuple 0 1 = v_xyz at 0 set self at tuple 1 1 = v_xyz at 1 set self at tuple 2 1 = v_xyz at 2 return self end function
def setVY(self, v_xyz): v_xyz = normalize3(v_xyz) self[0, 1] = v_xyz[0] self[1, 1] = v_xyz[1] self[2, 1] = v_xyz[2] return self
Python
nomic_cornstack_python_v1
import torch.optim as optim comment Specifying learning rate and momentum set optimizer = sgd parameters model lr=0.01 momentum=0.9 comment Let me examine if everything is fine # 1. Specified learning rate and momentum for the optimizer # Executing code.
import torch.optim as optim # Specifying learning rate and momentum optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9) # Let me examine if everything is fine # 1. Specified learning rate and momentum for the optimizer # Executing code.
Python
flytech_python_25k
comment num=int(input("enter the num")) comment sum=0 comment b=num comment while num>0: comment rem=num%10 comment var=rem**3 comment sum=sum+var comment num=num//10 comment print(sum) comment if sum==b: comment print(sum,"it is armstron num") comment else: comment print(sum, "it is not armstrong num") set num = integ...
# num=int(input("enter the num")) # sum=0 # b=num # while num>0: # rem=num%10 # var=rem**3 # sum=sum+var # num=num//10 # print(sum) # if sum==b: # print(sum,"it is armstron num") # else: # print(sum, "it is not armstrong num") num=int(input("enter the num=")) i=0 sum=0 b=num while i<num: re...
Python
zaydzuhri_stack_edu_python
import numpy as np import scipy import matplotlib.pyplot as pp from pylab import * comment Abrimos el archivo que contiene los datos (dos columnas que corresponden a X y a Y) with open string tabla.dat string r as data begin set x = list set y = list for line in data begin set p = split line append x decimal p at 0 a...
import numpy as np import scipy import matplotlib.pyplot as pp from pylab import * #Abrimos el archivo que contiene los datos (dos columnas que corresponden a X y a Y) with open('tabla.dat','r') as data: x=[] y=[] for line in data: p = line.split() x.append(float(p[0])) ...
Python
zaydzuhri_stack_edu_python
string Example to show implementation of Sobel thresholds import os import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg function mag_sobel img sobel_kernel=3 thresh=tuple 190 255 begin set gray = call cvtColor img COLOR_RGB2GRAY call imwrite string gray_test.jpg gray set tuple...
''' Example to show implementation of Sobel thresholds ''' import os import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg def mag_sobel(img, sobel_kernel=3, thresh = (190,255)): gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) cv2.imwrite('gray_test.jpg', gray) ...
Python
zaydzuhri_stack_edu_python
if age >= 18 and passport == string ja begin print string Gefeliciteerd, je mag stemmen! end
if age >= 18 and passport == 'ja': print('Gefeliciteerd, je mag stemmen!')
Python
zaydzuhri_stack_edu_python
function form_invalid self form instrumento_linea_form begin return call render_to_response call get_context_data form=form instrumento_linea_form=instrumento_linea_form end function
def form_invalid(self, form, instrumento_linea_form): return self.render_to_response( self.get_context_data(form=form, instrumento_linea_form=instrumento_linea_form))
Python
nomic_cornstack_python_v1
import sys append path string src from euler_estimator import * import matplotlib.pyplot as plt set rates = dict string deer lambda t x -> 0.6 * x at string deer - 0.05 * x at string deer * x at string wolves ; string wolves lambda t x -> 0.02 * x at string deer * x at string wolves - 0.9 * x at string wolves set model...
import sys sys.path.append('src') from euler_estimator import * import matplotlib.pyplot as plt rates = { 'deer': (lambda t,x: (0.6*x['deer']) - (0.05*x['deer']*x['wolves'])), 'wolves': (lambda t,x: (0.02*x['deer']*x['wolves']) - (0.9*x['wolves']))} model = EulerEstimator(rates) initial_vals = {'deer': 100, 'w...
Python
zaydzuhri_stack_edu_python
import asyncio import time set now = lambda -> time async function dosomething num begin print format string 第 {} 任務,第一步 num await sleep 2 print format string 第 {} 任務,第二步 num return format string 第 {} 任務完成 num end function async function raise_error num begin raise ValueError print string will not print end function a...
import asyncio import time now = lambda: time.time() async def dosomething(num): print('第 {} 任務,第一步'.format(num)) await asyncio.sleep(2) print('第 {} 任務,第二步'.format(num)) return '第 {} 任務完成'.format(num) async def raise_error(num): raise ValueError print('will not print') async def BMI_cal(): ...
Python
zaydzuhri_stack_edu_python
function _add_bin_lib_python env package_group_dir include_python=true begin call _append_to_path env string PATH join path package_group_dir string bin call _append_to_path env string LD_LIBRARY_PATH join path package_group_dir string lib if include_python begin call _append_to_path env string PYTHONPATH join path pac...
def _add_bin_lib_python(env, package_group_dir, include_python=True): _append_to_path(env, "PATH", os.path.join(package_group_dir, 'bin')) _append_to_path(env, 'LD_LIBRARY_PATH', os.path.join(package_group_dir, 'lib')) if include_python: _append_to_path(env, 'PYTHONPATH', ...
Python
nomic_cornstack_python_v1
function eta self begin comment Make a list for the output set h = list 0 * _len_h if _is_ts begin comment Loop over channels for i in range _len_h begin set data = data at i set u = unique events at i set event_types = u at unique events at i != 0 set h at i = call empty tuple shape at 0 len_et dtype=complex comment T...
def eta(self): #Make a list for the output h = [0] * self._len_h if self._is_ts: # Loop over channels for i in range(self._len_h): data = self.data[i] u = np.unique(self.events[i]) event_types = u[np.unique(self.ev...
Python
nomic_cornstack_python_v1
function test_analyze_with_PM self begin set seq = string ATGTCGTTCTGCAGCTTCTTCGGGGGCGAGGTTTTCCAGAATCACTTTGAACCT set stdseq = string ATGTCGTTCTGCAGCTTCTTCGGGGGCGAGGTTTTCCAGAATCACTTTGAAACT set status = call analyze seq stdseq assert equal status call PM nt_pm=1 aa_pm=1 stdseq=stdseq assert equal seq seq assert equal std...
def test_analyze_with_PM(self): seq = 'ATGTCGTTCTGCAGCTTCTTCGGGGGCGAGGTTTTCCAGAATCACTTTGAACCT' stdseq = 'ATGTCGTTCTGCAGCTTCTTCGGGGGCGAGGTTTTCCAGAATCACTTTGAAACT' status = analyze(seq, stdseq) self.assertEqual(status, PM(nt_pm=1, aa_pm=1, stdseq=stdseq)) self.assertEqual(status.s...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Mar 5 12:12:19 2019 @author: Lenovo set xa = input string podaj x punktu a: print xa set ya = input string podaj y punktu a: print ya set xb = input string podaj x punktu b: print xb set yb = input string podaj y punktu b: print yb set xp = input string podaj x punktu...
# -*- coding: utf-8 -*- """ Created on Tue Mar 5 12:12:19 2019 @author: Lenovo """ xa=input('podaj x punktu a:') print(xa) ya=input('podaj y punktu a:') print(ya) xb=input('podaj x punktu b:') print(xb) yb=input('podaj y punktu b:') print(yb) xp=input('podaj x punktu p:') print(xp) yp=input('podaj y...
Python
zaydzuhri_stack_edu_python
function count_unique hashable_objects begin comment len(set(hashable_objects)) return call nunique end function
def count_unique(hashable_objects: pd.Series) -> int: return hashable_objects.nunique() #len(set(hashable_objects))
Python
nomic_cornstack_python_v1
function schedule_next_task self cursor timestamp begin call add_task_for_repo repo call task_name ACTION cursor=cursor timestamp=string call timegm call utctimetuple end function
def schedule_next_task(self, cursor, timestamp): self.add_task_for_repo( self.repo, self.task_name(), self.ACTION, cursor=cursor, timestamp=str(calendar.timegm(timestamp.utctimetuple())))
Python
nomic_cornstack_python_v1
function setup_class cls begin set connection_config = call ConnectionConfig name=string connection_name author=string author version=string 0.1.0 connections=set literal old_connection_id protocols=set literal old_protocol_id restricted_to_protocols=set literal old_protocol_id excluded_protocols=set literal old_protoc...
def setup_class(cls): cls.connection_config = ConnectionConfig( name="connection_name", author="author", version="0.1.0", connections={cls.old_connection_id}, protocols={cls.old_protocol_id}, restricted_to_protocols={cls.old_protocol_id}, ...
Python
nomic_cornstack_python_v1
function vert p1 p2 begin set vx = p2 at 0 - p1 at 0 set vy = p2 at 1 - p1 at 1 set vz = p2 at 2 - p1 at 2 return list vx vy vz end function
def vert (p1, p2): vx = p2[0]-p1[0] vy = p2[1]-p1[1] vz = p2[2]-p1[2] return [vx, vy, vz]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding : utf-8 import os import smtplib import string import sys from email import Encoders from email.mime.text import MIMEText from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email.Utils import formatdate comment -----------------------------...
#!/usr/bin/env python ##### coding : utf-8 import os import smtplib import string import sys from email import Encoders from email.mime.text import MIMEText from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email.Utils import formatdate #-------------------------------------------...
Python
zaydzuhri_stack_edu_python
function set_target_raid_config self node_ident target_raid_config os_ironic_api_version=none global_request_id=none begin set path = string %s/states/raid % node_ident return update self path target_raid_config http_method=string PUT os_ironic_api_version=os_ironic_api_version global_request_id=global_request_id end f...
def set_target_raid_config( self, node_ident, target_raid_config, os_ironic_api_version=None, global_request_id=None): path = "%s/states/raid" % node_ident return self.update(path, target_raid_config, http_method='PUT', os_ironic_api_version=os_ironic_a...
Python
nomic_cornstack_python_v1
from layer import * import tensorflow as tf import numpy as np from utils import * from math import exp class VAEGCell extends object begin string Variational Auto Encoder cell. function __init__ self adj features z_dim begin string Args: adj : adjacency matrix features: feature matrix set adj = adj set features = feat...
from layer import * import tensorflow as tf import numpy as np from utils import * from math import exp class VAEGCell(object): """Variational Auto Encoder cell.""" def __init__(self, adj, features, z_dim): ''' Args: adj : adjacency matrix features: feature matrix ''' self.a...
Python
zaydzuhri_stack_edu_python
function parse_san self board san begin return call parse_san san end function
def parse_san(self, board: chess.Board, san: str) -> chess.Move: return board.parse_san(san)
Python
nomic_cornstack_python_v1
function __init__ self opts begin call __init__ opts set options = get opts string fn_cb_protection dict end function
def __init__(self, opts): super(FunctionComponent, self).__init__(opts) self.options = opts.get("fn_cb_protection", {})
Python
nomic_cornstack_python_v1
from sense_hat import SenseHat set sense = call SenseHat comment Define Colours comment Green set g = tuple 0 255 0 comment Black set b = tuple 0 0 0 comment setup where each colour will display set image_pixel = list g g g g g g g g g g g g g g g g g b b g g b b g g b b g g b b g g g g b b g g g g g b b b b g g g g b ...
from sense_hat import SenseHat sense = SenseHat() # Define Colours g = (0,255,0) # Green b = (0,0,0) # Black # setup where each colour will display image_pixel = [ g,g,g,g,g,g,g,g, g,g,g,g,g,g,g,g, g,b,b,g,g,b,b,g, g,b,b,g,g,b,b,g, g,g,g,b,b,g,g,g, g,g,b,b,b,b,g,g, g,g,b,b,b,b,g,g, g,...
Python
zaydzuhri_stack_edu_python
comment Serena Chen comment alice2bob from rsa import RSA set maxPW = 99999 function Alice2Bob newpassword begin if 0 > newpassword or newpassword > maxPW begin raise call ValueError format string Password must be between 0 and {} maxPW end set rsa = call RSA call from_message_bit_length call bit_length comment rsa.fro...
#Serena Chen #alice2bob from rsa import RSA maxPW = 99999 def Alice2Bob(newpassword): if 0 > newpassword or newpassword > maxPW: raise ValueError("Password must be between 0 and {}".format(maxPW)) rsa = RSA() rsa.from_message_bit_length(maxPW.bit_length()) #rsa.from_given_pqe(61,53,17...
Python
zaydzuhri_stack_edu_python
function compute_q_bounce_path_euler domain q epsilon begin set cur_point = list comprehension call inv_lazutkin_param_non_arc domain call fdiv i q for i in range q // 2 + 1 set cur_point at - 1 = if expression q % 2 == 0 then 1 / 2 else cur_point at - 1 set grad = list comprehension call length_gradient domain i cur_p...
def compute_q_bounce_path_euler(domain, q, epsilon): cur_point = [inv_lazutkin_param_non_arc(domain, fdiv(i, q)) for i in range(q // 2 + 1)] cur_point[-1] = 1 / 2 if (q % 2 == 0) else cur_point[-1] grad = [length_gradient(domain, i, cur_point) for i in range(len(cur_point))] grad_sup_n...
Python
nomic_cornstack_python_v1
function test_category_name_field_max_length self begin set cat = get objects id=1 set max_length = max_length assert equal max_length 20 end function
def test_category_name_field_max_length(self): cat = Category.objects.get(id=1) max_length = cat._meta.get_field('name').max_length self.assertEqual(max_length, 20)
Python
nomic_cornstack_python_v1
class Animal extends object begin function __init__ self begin print string Animal Class Defined end function function whoAmI self begin print string Animal end function function eating self begin print string Eating end function end class class Dog extends Animal begin function __init__ self begin call __init__ self p...
class Animal(object): def __init__(self): print("Animal Class Defined") def whoAmI(self): print("Animal") def eating(self): print("Eating") class Dog(Animal): def __init__(self): Animal.__init__(self) print("Dog Class Created") def whoAmI(self): ...
Python
zaydzuhri_stack_edu_python
function show_help_popup event begin set control = call GetEventObject set template = call help_template set html = item_html % tuple call GetLabel call get_help call HTMLHelpWindow control html 0.25 0.13 end function
def show_help_popup ( event ): control = event.GetEventObject() template = help_template() html = template.item_html % ( control.GetLabel(), control.trait.get_help() ) HTMLHelpWindow( control, html, .25, .13 )
Python
nomic_cornstack_python_v1
async function process self name args bot chat user msg_id begin if name not in commands begin raise call ValueError string Command not found end set cmd = commands at name if not await call is_authorized bot chat user begin return false end await execute cmd args bot chat user msg_id return true end function
async def process(self, name: str, args: str, bot: "latexbot.LatexBot", chat: pyryver.Chat, user: pyryver.User, msg_id: str) -> bool: if name not in self.commands: raise ValueError("Command not found") cmd = self.commands[name] if not await cmd.is_authorized(bot, chat, user): ...
Python
nomic_cornstack_python_v1