code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string IMPORTING NECCESARY PACKAGES
from tkinter import *
from tkinter import ttk
import datetime
import time
import tkinter.messagebox
import sqlite3
import os
import tkinter as tk
import pandas as pd
import comtypes.client
import webbrowser
string IMPORTING SUCCESSFUL
string CREATING CLASS
class School_Portal
begin
s... | ''' IMPORTING NECCESARY PACKAGES'''
from tkinter import *
from tkinter import ttk
import datetime
import time
import tkinter.messagebox
import sqlite3
import os
import tkinter as tk
import pandas as pd
import comtypes.client
import webbrowser
''' IMPORTING SUCCESSFUL'''
''' CREATING CLASS'''
c... | Python | zaydzuhri_stack_edu_python |
function pick_closedref_otus pcro infname reference outdirname logger
begin
info string Picking closed-reference OTUs with QIIME
set qiime_pcrodir = run infname reference outdirname
info string OTUs picked by QIIME (closed-reference) + string written to: %s qiime_pcrodir
return qiime_pcrodir
end function | def pick_closedref_otus(pcro, infname, reference, outdirname, logger):
logger.info("Picking closed-reference OTUs with QIIME")
qiime_pcrodir = pcro.run(infname, reference, outdirname)
logger.info("OTUs picked by QIIME (closed-reference) " +
"written to:\n\t%s", qiime_pcrodir)
return qiim... | Python | nomic_cornstack_python_v1 |
function get_doubles_then_triples L
begin
return call get_multiple_of_list L 2 + call get_multiple_of_list L 3
end function | def get_doubles_then_triples(L):
return get_multiple_of_list(L,2) + get_multiple_of_list(L,3) | Python | nomic_cornstack_python_v1 |
import numpy as np
import sklearn.metrics as skm
function auc y_true y_pred round=true
begin
string Area under the ROC curve
if round
begin
set y_true = round
end
if length y_true == 0 or length unique y_true < 2
begin
return nan
end
return call roc_auc_score y_true y_pred
end function
function auprc y_true y_pred
begi... | import numpy as np
import sklearn.metrics as skm
def auc(y_true, y_pred, round=True):
"""Area under the ROC curve
"""
if round:
y_true = y_true.round()
if len(y_true) == 0 or len(np.unique(y_true)) < 2:
return np.nan
return skm.roc_auc_score(y_true, y_pred)
def auprc(y_true, y_pr... | Python | zaydzuhri_stack_edu_python |
from Camion import camion
from Cosecha import Cosecha
from ManejadorC import manejadorc
function op0
begin
print string salir
end function
function op1
begin
set i = integer input string Ingrese el numero del camion:
set peso = call peso i - 1
print format string La cantidad de kilos descargados para el camion {} es: {... | from Camion import camion
from Cosecha import Cosecha
from ManejadorC import manejadorc
def op0():
print("salir")
def op1():
i=int(input("Ingrese el numero del camion: \n"))
peso=cosecha.peso(i-1)
print("La cantidad de kilos descargados para el camion {} es: {}".format(i,peso))
def op2():... | Python | zaydzuhri_stack_edu_python |
function __init__ self label leaf=false
begin
set tuple label leaf = tuple label leaf
comment Child nodes of this root
set children = dict
end function | def __init__(self, label, leaf=False):
self.label, self.leaf = label, leaf
# Child nodes of this root
self.children = {} | Python | nomic_cornstack_python_v1 |
function main upper_limit
begin
set primes = call primes_up_to upper_limit
set twice_squares = list comprehension 2 * x ^ 2 for x in range 1 floor upper_limit ^ 0.5
for odd in list comprehension x for x in range 3 upper_limit + 1 2 if x not in primes
begin
if not call meets_criterion odd primes twice_squares
begin
retu... | def main(upper_limit):
primes = primes_up_to(upper_limit)
twice_squares = [2 * x ** 2 for x in range(1, floor(upper_limit ** 0.5))]
for odd in [x for x in range(3, upper_limit + 1, 2) if x not in primes]:
if not meets_criterion(odd, primes, twice_squares):
return odd
return -1 | Python | nomic_cornstack_python_v1 |
function deseq aligner=none directory=none project_name=none project_description=string species=none single_stranded_protocol=false
begin
comment Set the codes base path
set basepath = directory name path real path path __file__
comment Load the credentials if they are not supplied
try
begin
set tuple stirplate_id sti... | def deseq(aligner=None,
directory=None,
project_name=None,
project_description='',
species=None,
single_stranded_protocol=False):
# Set the codes base path
basepath = os.path.dirname(os.path.realpath(__file__))
# Load the credentials if they are not suppli... | Python | nomic_cornstack_python_v1 |
function rho self Ppump
begin
set tuple etaP EsatL TR = tuple etaP EsatL TR
return call Psteady Ppump * etaP / EsatL * TR * call w0 Ppump ^ 2
end function | def rho(self, Ppump):
etaP, EsatL, TR = self.etaP, self.EsatL, self.TR
return(self.Psteady(Ppump) * etaP / (EsatL * TR * self.w0(Ppump)**2)) | Python | nomic_cornstack_python_v1 |
function tie self output
begin
call tie writechannel
end function | def tie(self, output):
self._vdma.readchannel.tie(output._vdma.writechannel) | Python | nomic_cornstack_python_v1 |
function InsertTestStep self testStep position
begin
set callResult = call _Call string InsertTestStep testStep position
end function | def InsertTestStep(self, testStep, position):
callResult = self._Call("InsertTestStep", testStep, position) | Python | nomic_cornstack_python_v1 |
print 10 + 5
print 10 - 5
print 10 * 5
print 10 / 5
print 10 // 5
print 10 % 5
print 9 ^ 2
print 9 ^ 3 |
print (10 + 5)
print (10 - 5)
print (10 * 5)
print (10 / 5)
print (10 // 5)
print (10 % 5)
print (9**2)
print(9**3) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Задание 19.1b Дополнить функцию send_show_command из задания 19.1a таким образом, чтобы обрабатывалось не только исключение, которое генерируется при ошибке аутентификации на устройстве, но и исключение, которое генерируется, когда IP-адрес устройства недоступен. При возникновении о... | # -*- coding: utf-8 -*-
'''
Задание 19.1b
Дополнить функцию send_show_command из задания 19.1a таким образом,
чтобы обрабатывалось не только исключение, которое генерируется
при ошибке аутентификации на устройстве, но и исключение,
которое генерируется, когда IP-адрес устройства недоступен.
При возникновении ошибки, ... | Python | zaydzuhri_stack_edu_python |
from ROOT import TFile
from info import *
from utils import get_effpur
comment Read in data trees
set files = list comprehension call TFile data_dir + x + string .root for x in data_filenames
set trees = list comprehension get f string h100 for f in files
set n_trees = length trees
comment The cuts we found for each de... | from ROOT import TFile
from info import *
from utils import get_effpur
# Read in data trees
files = [TFile(data_dir + x + ".root") for x in data_filenames]
trees = [f.Get('h100') for f in files]
n_trees = len(trees)
# The cuts we found for each decay channel
cuts = {"hadr": "Ech>20&&Nefl>13",
"muon": "Ech>40&... | Python | zaydzuhri_stack_edu_python |
function unit_of_measurement self
begin
return display_currency
end function | def unit_of_measurement(self):
return self.display_currency | Python | nomic_cornstack_python_v1 |
function get_data_loader name train=true
begin
if name == string MNIST
begin
return call get_mnist train
end
else
if name == string USPS
begin
return call get_usps train
end
end function | def get_data_loader(name, train=True):
if name == "MNIST":
return get_mnist(train)
elif name == "USPS":
return get_usps(train) | Python | nomic_cornstack_python_v1 |
comment Get the total number of characters
set total = length text
comment Count the number of vowels
set vowels = 0
for character in text
begin
if character in string aeiou
begin
set vowels = vowels + 1
end
end
comment Count the number of consonants
set consonants = 0
for character in text
begin
if character in string... | # Get the total number of characters
total = len(text)
# Count the number of vowels
vowels = 0
for character in text:
if character in 'aeiou':
vowels += 1
# Count the number of consonants
consonants = 0
for character in text:
if character in 'bcdfghjklmnpqrstvwxyz':
consonants += 1
# Print the result... | Python | jtatman_500k |
function rules cls
begin
set rules_ClassificationDatasetCommon = dict string data_path dict string type str ; string batch_size dict string type int ; string shuffle dict string type bool ; string drop_last dict string type bool ; string n_class dict string type int ; string train_portion dict string type tuple int flo... | def rules(cls):
rules_ClassificationDatasetCommon = {"data_path": {"type": str},
"batch_size": {"type": int},
"shuffle": {"type": bool},
"drop_last": {"type": bool},
... | Python | nomic_cornstack_python_v1 |
comment Funksjon som printer to stringer etter hverandre
function connect_string s1 s2
begin
print s1 + string + s2
end function
call connect_string string James string Bond
print string b)
set list1 = list string abc string defg string hijklm string nop
comment Funksjon som printer sammen en liste med stringer
functi... | # Funksjon som printer to stringer etter hverandre
def connect_string(s1, s2):
print(s1 + " " + s2)
connect_string("James", "Bond")
print("\nb)")
list1 = ["abc", "defg", "hijklm", "nop"]
# Funksjon som printer sammen en liste med stringer
def print_list_string(liste):
res = ""
for i in liste:
... | Python | zaydzuhri_stack_edu_python |
function get_prev self
begin
return call get_previous_by_created_at
end function | def get_prev(self):
return self.get_previous_by_created_at() | Python | nomic_cornstack_python_v1 |
function _init_ha_kv self
begin
try
begin
set ha_kv = get kv ha_key at 1
if not ha_kv
begin
for item in kv_data at ha_main_key
begin
set key = keys item at 0
set value = item at key
if is instance value list
begin
for sub_item in value
begin
set sub_key = keys sub_item at 0
set sub_value = sub_item at sub_key
call _put... | def _init_ha_kv(self):
try:
ha_kv = self.consul_cluster_client.kv.get(self.ha_key)[1]
if not ha_kv:
for item in self.kv_data[self.ha_main_key]:
key = item.keys()[0]
value = item[key]
if isinstance(value, list):
... | Python | nomic_cornstack_python_v1 |
function calculate_tail_correction box_length cutoff number_particles
begin
set volume = call power box_length 3
set sig_by_cutoff3 = call power 1.0 / cutoff 3
set sig_by_cutoff9 = call power sig_by_cutoff3 3
set e_correction = sig_by_cutoff9 - 3.0 * sig_by_cutoff3
set e_correction = e_correction * 8.0 / 9.0 * pi * num... | def calculate_tail_correction(box_length, cutoff, number_particles):
volume = np.power(box_length, 3)
sig_by_cutoff3 = np.power(1.0 / cutoff, 3)
sig_by_cutoff9 = np.power(sig_by_cutoff3, 3)
e_correction = sig_by_cutoff9 - 3.0 * sig_by_cutoff3
e_correction *= 8.0 / 9.0 * np.pi * number_particles /... | Python | nomic_cornstack_python_v1 |
function save_book self
begin
add session self
commit session
end function | def save_book(self):
db.session.add(self)
db.session.commit() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
from modgrammar import *
from modgrammar import Terminal , error_result , util , GrammarClass
from modgrammar.extras import *
import re
from sys import *
comment grammar_whitespace = re.compile("\s+")
comment formatting helper functions
function StripWhitespace string
begin
set ret = sub s... | #!/usr/bin/env python3
from modgrammar import *
from modgrammar import Terminal, error_result, util, GrammarClass
from modgrammar.extras import *
import re
from sys import *
#grammar_whitespace = re.compile("\s+")
#
# formatting helper functions
#
def StripWhitespace( string ):
ret = re.sub( "\s+", " ", string,... | Python | zaydzuhri_stack_edu_python |
function linear_search arr key
begin
for tuple index element in enumerate arr
begin
if element == key
begin
return index
end
end
return - 1
end function
print call linear_search arr key | def linear_search(arr, key):
for index, element in enumerate(arr):
if element == key:
return index
return -1
print(linear_search(arr, key)) | Python | iamtarun_python_18k_alpaca |
function queryable self
begin
return get pulumi self string queryable
end function | def queryable(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "queryable") | Python | nomic_cornstack_python_v1 |
import turtle
import pandas
set my_screen = call Screen
title my_screen string US states game
call penup
call hideturtle
set image = string blank_states_img.gif
call bgpic image
set data = read csv string 50_states.csv
set states = call to_list
set x_cor = call to_list
set y_cor = call to_list
function visualize answer... | import turtle
import pandas
my_screen = turtle.Screen()
my_screen.title('US states game')
turtle.penup()
turtle.hideturtle()
image = 'blank_states_img.gif'
my_screen.bgpic(image)
data = pandas.read_csv('50_states.csv')
states = data.state.to_list()
x_cor = data.x.to_list()
y_cor = data.y.to_list()
def visualize(an... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Thu Dec 24 09:56:33 2020 @author: HP
import numpy as np
set a = array list list 2 3 list 4 5
set res = call det a
print res | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 09:56:33 2020
@author: HP
"""
import numpy as np
a = np.array([[2,3],[4,5]])
res = np.linalg.det(a)
print(res) | Python | zaydzuhri_stack_edu_python |
comment step1- collect/define all numbers
range 10
comment step2 - Write some logic to print only even numbers | #step1- collect/define all numbers
range(10)
# step2 - Write some logic to print only even numbers | Python | zaydzuhri_stack_edu_python |
print string prathik
set a = 250
set b = 500
set true = a < b
set false = b < a
print a > b
set a = input string Enter a's value
set b = input string Enter b's value
set c = a + b
print c | print("prathik")
a=250
b=500
true=a<b
false=b<a
print(a>b)
a=input("Enter a's value")
b=input("Enter b's value")
c=a+b
print(c) | Python | zaydzuhri_stack_edu_python |
class Game
begin
function __init__ self title=string Hello World x=0 y=0 height=100 width=200
begin
set title = title
set x = x
set y = y
set height = height
set width = width
end function
function run self
begin
pass
end function
end class
class DemoGame extends Game
begin
pass
end class | class Game:
def __init__(self, title: str = 'Hello World',
x: int = 0, y: int = 0,
height: int = 100, width: int = 200):
self.title = title
self.x = x
self.y = y
self.height = height
self.width = width
def run(self):
pass
class... | Python | zaydzuhri_stack_edu_python |
function from_parser cls parser _length_hint=none
begin
return call cls read parser _WIDTH
end function | def from_parser(
cls: Type[UInt64], parser: BinaryParser, _length_hint: Optional[int] = None
) -> UInt64:
return cls(parser.read(_WIDTH)) | Python | nomic_cornstack_python_v1 |
function insights self
begin
return json call _request string GET string v2/insights
end function | def insights(self):
return self._request("GET", "v2/insights").json() | Python | nomic_cornstack_python_v1 |
async function lookup ctx user location=string
begin
if length strip location < 1
begin
set location = none
end
try
begin
set res = none
if location is none
begin
set res = await call kblookup user string usernames _fields
end
else
begin
set res = await call kblookup user location _fields
end
end
except Exception as er... | async def lookup(ctx, user : str, location : str = ''):
if len(location.strip()) < 1:
location = None
try:
res = None
if location is None:
res = await utils.kblookup(user, 'usernames', _fields)
else:
res = await utils.kblookup(user, location, _fields)
... | Python | nomic_cornstack_python_v1 |
comment Aufgabe 1 (for - Schleife durch eine Liste)
string Fuehren Sie den unten stehenden Code auf einmal aus. Beobachten Sie die Ausgabe in der Konsole. Welche Zahlen werden ausgegeben.
for ii in list 1 2 3 4 5
begin
print ii
end
print string alles fertig
comment Aufgabe 2 (for - Scheife durch einen String)
string Fu... | # Aufgabe 1 (for - Schleife durch eine Liste)
"""Fuehren Sie den unten stehenden Code auf einmal aus. Beobachten Sie die
Ausgabe in der Konsole. Welche Zahlen werden ausgegeben."""
for ii in [1,2,3,4,5]:
print (ii)
print("alles fertig")
# Aufgabe 2 (for - Scheife durch einen String)
"""Fuehren Sie den unten steh... | Python | zaydzuhri_stack_edu_python |
function forms_valid self forms
begin
string Calls `save()` on each form.
for form in call itervalues forms
begin
save
end
return call forms_valid forms
end function | def forms_valid(self, forms):
"""
Calls `save()` on each form.
"""
for form in six.itervalues(forms):
form.save()
return super(MultiModelFormView, self).forms_valid(forms) | Python | jtatman_500k |
function is_prime number
begin
if number < 2
begin
return false
end
for i in range 2 integer number ^ 0.5 + 1
begin
if number % i == 0
begin
return false
end
end
return true
end function
set number1 = integer input string Number1:
set number2 = integer input string Number2:
if number1 < 1 or number1 > 100 or number2 < ... | def is_prime(number):
if number < 2:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
number1 = int(input("Number1: "))
number2 = int(input("Number2: "))
if number1 < 1 or number1 > 100 or number2 < 1 or number2 > 100:
pri... | Python | jtatman_500k |
function genetic_breeding self
begin
set fitness_tot = sum
for i in range n_population
begin
set fitness_score at i = fitness_score at i / fitness_tot
if i != 0
begin
set fitness_score at i = fitness_score at i + fitness_score at i - 1
end
end
set new_weights = list
set choice = uniform 0 1
set threshold = N_GENERATION... | def genetic_breeding(self):
fitness_tot = self.fitness_score.sum()
for i in range(self.n_population):
self.fitness_score[i] /= fitness_tot
if i != 0:
self.fitness_score[i] += self.fitness_score[i - 1]
new_weights = list()
choice = random.uniform(... | Python | nomic_cornstack_python_v1 |
function test_api_samples self
begin
comment load api base
set r = json get requests format string {server}/api/0.1/ server=call get_server_url
comment load samples from url specified in api base
set r = json get requests r at string samples
assert in string count r
assert in string next r
assert in string prev r
asser... | def test_api_samples(self):
# load api base
r = requests.get('{server}/api/0.1/'.format(
server=self.get_server_url())).json()
# load samples from url specified in api base
r = requests.get(r['samples']).json()
self.assertIn('count', r)
self.assertIn('next', r... | Python | nomic_cornstack_python_v1 |
import pygame
class Button
begin
function __init__ self x y width height text
begin
set x = x
set y = y
set width = width
set height = height
set text = text
set rectangle = call Rect x y width height
end function
function is_within self x y
begin
if x < x < x + width and y < y < y + height
begin
return true
end
return... | import pygame
class Button:
def __init__(self, x, y, width, height, text):
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.rectangle = pygame.Rect(x, y, width, height)
def is_within(self, x, y):
if self.x < x < (self... | Python | zaydzuhri_stack_edu_python |
function spatial_discrim mot ilane iLPF detect_min detect_max h=none
begin
comment %% define two spatial lanes of traffic
set lane = sum axis=0
comment %% motion PSD
set Flane = call fftshift absolute fft lane ^ 2
comment %% motion detected within magnitude limits
set N = integer detect_min <= sum <= detect_max
comment... | def spatial_discrim(
mot: np.ndarray, ilane: typing.Tuple[int, int], iLPF: typing.Tuple[int, int], detect_min: float, detect_max: float, h=None
) -> int:
# %% define two spatial lanes of traffic
lane = mot[ilane[0]: ilane[1], :].sum(axis=0)
# %% motion PSD
Flane = np.fft.fftshift(abs(np.fft.fft(lane... | Python | nomic_cornstack_python_v1 |
function remove_duplicates lst
begin
set seen = set
set result = list
for element in lst
begin
if element not in seen
begin
add seen element
append result element
end
end
return result
end function
comment test the function with the given example
set input_list = list 2 3 4 2 3 5 4.5 string apple string banana string ... | def remove_duplicates(lst):
seen = set()
result = []
for element in lst:
if element not in seen:
seen.add(element)
result.append(element)
return result
# test the function with the given example
input_list = [2, 3, 4, 2, 3, 5, 4.5, "apple", "banana", "apple", [1, 2, 3], ... | Python | jtatman_500k |
function _get_webhook_url self
begin
set webhooks_path = call getenv string WEBHOOKS_PATH string /run/secrets/webhooks.yml
with open webhooks_path string r as webhooks_file
begin
set all_webhooks = call safe_load webhooks_file
end
set webhook = all_webhooks at webhook_name
debug format string Loaded webhook {} successf... | def _get_webhook_url(self):
webhooks_path = os.getenv('WEBHOOKS_PATH', '/run/secrets/webhooks.yml')
with open(webhooks_path, 'r') as webhooks_file:
all_webhooks = yaml.safe_load(webhooks_file)
webhook = all_webhooks[self.webhook_name]
logger.debug('Loaded webhook {} successfu... | Python | nomic_cornstack_python_v1 |
function save self project subject_template_name=string password_reset_subject.txt email_template_name=string password_reset_email.html use_https=false token_generator=default_token_generator from_email=none
begin
from django.core.mail import send_mail
for user in users_cache
begin
set c = dict string email email ; str... | def save(self, project, subject_template_name='password_reset_subject.txt',
email_template_name='password_reset_email.html',
use_https=False, token_generator=default_token_generator,
from_email=None):
from django.core.mail import send_mail
for user in self.users_ca... | Python | nomic_cornstack_python_v1 |
import pygame as pg
import time
comment perf_counter returns a float that represents the time in seconds
comment we'll use it to record the run time of the algorithm
from time import perf_counter
comment this allows you to generate a random number from a specified range
from random import randrange as rand
comment turn... | import pygame as pg
import time
# perf_counter returns a float that represents the time in seconds
# we'll use it to record the run time of the algorithm
from time import perf_counter
# this allows you to generate a random number from a specified range
from random import randrange as rand
# turns out there's a math f... | Python | zaydzuhri_stack_edu_python |
function cfg_singleslit self ow=0.1 pos=0.3
begin
comment Source
set __src_posx = pml_length
set __src_emissionlength = integer 0.9 * __nx - 2.0 * pml_length
set __src_starty = integer __nx / 2.0 - __src_emissionlength / 2.0
set __src_function = __planesource
comment Absorber
set yy = linear space 0.0 __size __ny - 2 *... | def cfg_singleslit(self, ow=0.1, pos=0.3):
#Source
self.__src_posx = self.pml_length
self.__src_emissionlength = int(.9*(self.__nx-2.*self.pml_length))
self.__src_starty = int(self.__nx/2.-self.__src_emissionlength/2.)
self.__src_function = self.__planesource
#Absorber
... | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
class Network extends object
begin
function __init__ self num_classes word_embedding_initializer
begin
comment hyper parameter
set num_classes = num_classes
set num_steps = 0
set pos_num = 0
set pos_size = 0
comment input & placeholder
set input_word = call placeholder dtype=int32 shape=list non... | import tensorflow as tf
class Network(object):
def __init__(self, num_classes, word_embedding_initializer):
# hyper parameter
self.num_classes = num_classes
num_steps = 0
pos_num = 0
pos_size = 0
# input & placeholder
self.input_word = tf.placeholder(dtype... | Python | zaydzuhri_stack_edu_python |
import datetime as dt
import pytest
from inventory import models
decorator fixture
function variation_option variation_option_factory
begin
set variation_option = call create
call full_clean
return variation_option
end function
decorator fixture
function new_variation_option
begin
set variation_option = call VariationO... | import datetime as dt
import pytest
from inventory import models
@pytest.fixture
def variation_option(variation_option_factory):
variation_option = variation_option_factory.create()
variation_option.full_clean()
return variation_option
@pytest.fixture
def new_variation_option():
variation_option =... | Python | zaydzuhri_stack_edu_python |
function closest_fraction won total
begin
comment Step 2: Calculate the fraction of medals won
set fraction_won = won / total
comment Step 3: List of possible fractions
set fractions = list string 1/4 string 1/5 string 1/6 string 1/7 string 1/8 string 1/9
comment Step 4: Convert fractions to decimal values
set decimal_... | def closest_fraction(won, total):
# Step 2: Calculate the fraction of medals won
fraction_won = won / total
# Step 3: List of possible fractions
fractions = ['1/4', '1/5', '1/6', '1/7', '1/8', '1/9']
# Step 4: Convert fractions to decimal values
decimal_values = []
for frac in frac... | Python | dbands_pythonMath |
function solution participant completion
begin
sort participant
sort completion
for n in range length completion
begin
if participant at n != completion at n
begin
return participant at n
end
end
return participant at - 1
end function
set participant = list string mislav string stanko string mislav string ana
set compl... | def solution(participant, completion):
participant.sort()
completion.sort()
for n in range(len(completion)):
if participant[n] != completion[n]:
return participant[n]
return participant[-1]
participant = ["mislav", "stanko", "mislav", "ana"]
completion = ["stanko", "ana", "mislav... | Python | zaydzuhri_stack_edu_python |
function __gen_buffer_instance self layer
begin
set num_input_fmaps = input_shapes at 0 at - 1
set num_inputs_per_fmap = call prod kernel_size
comment num_inputs = num_input_fmaps * num_inputs_per_fmap
set num_inputs = 1 * num_inputs_per_fmap
set output_act_name = string %s_buf_act % name
set output_valid_name = string... | def __gen_buffer_instance(self, layer):
num_input_fmaps = layer.input_shapes[0][-1]
num_inputs_per_fmap = np.prod(layer.kernel_size)
# num_inputs = num_input_fmaps * num_inputs_per_fmap
num_inputs = 1 * num_inputs_per_fmap
output_act_name = "%s_buf_act" % layer.name
output_valid_name = "%s_buf_valid" % laye... | Python | nomic_cornstack_python_v1 |
import configparser
set config1 = config parser
set character = dict
function read_config
begin
set configfilepath = string config.ini
read config1 configfilepath
for i in range 15
begin
set character at string i = get config1 string main string i + 1
print character
end
for i in character
begin
if character at string... | import configparser
config1 = configparser.ConfigParser()
character = {}
def read_config():
configfilepath = 'config.ini'
config1.read(configfilepath)
for i in range(15):
character[str(i)] = config1.get('main', str(i + 1))
print(character)
for i in character:
if character[str... | Python | zaydzuhri_stack_edu_python |
function test_depth_buffer_saving image_test
begin
call create_window width=800 height=600
set show_triangle_left = true
set show_text = false
set show_checkerboard = false
function step dt
begin
call save_and_load_depth_buffer
set show_text = true
return true
end function
call schedule_once step
call ask_question stri... | def test_depth_buffer_saving(image_test):
image_test.create_window(width=800, height=600)
image_test.show_triangle_left = True
image_test.show_text = False
image_test.show_checkerboard = False
def step(dt):
image_test.save_and_load_depth_buffer()
image_test.show_text = True
... | Python | nomic_cornstack_python_v1 |
import sqlite3
string Represents a car object implemented as a doubly linked list with sublists for cars of the same color
class Car
begin
function __init__ self id=none name=none color=none left=none right=none leftcolor=none rightcolor=none
begin
set id = id
set name = name
set color = color
set left = left
set right... | import sqlite3
"""
Represents a car object implemented as a
doubly linked list with sublists for cars
of the same color
"""
class Car():
def __init__(self, id=None, name=None, color=None, left=None, right=None, leftcolor=None, rightcolor=None):
self.id = id
self.name = name
self.color = c... | Python | zaydzuhri_stack_edu_python |
function bounding_box nodes
begin
set node_poses = list
for n in nodes
begin
if is instance n basestring and call objExists n
begin
comment get object's position
set pos = call xform n query=true translation=true worldSpace=true
append node_poses pos
end
else
begin
comment it's a position list, add to list directly
ap... | def bounding_box(nodes):
node_poses = []
for n in nodes:
if isinstance(n, basestring) and cmds.objExists(n):
# get object's position
pos = cmds.xform(n, query=True, translation=True, worldSpace=True)
node_poses.append(pos)
else:
# it's a position... | Python | nomic_cornstack_python_v1 |
function setHPLCInjectValveOpen self nReagent bValveOpen
begin
if bValveOpen
begin
call HPLCInject
end
else
begin
call HPLCLoad
end
end function | def setHPLCInjectValveOpen(self, nReagent, bValveOpen):
if bValveOpen:
self.hardwareComm.HPLCInject()
else:
self.hardwareComm.HPLCLoad() | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
import pygame
from Vector2D import *
from Mosaico import *
class Objeto extends object
begin
string Clase abastracta que representa un objeto genérico: posición, velocidad, modelo, ...
set ESCENARIO = none
function __init__ self
begin
set posicion = call Vector2D
set velocidad = call Vector2D
set ... | # coding: utf-8
import pygame;
from Vector2D import *;
from Mosaico import *;
class Objeto(object):
"""Clase abastracta que representa un objeto genérico: posición, velocidad, modelo, ..."""
ESCENARIO = None;
def __init__(self):
self.posicion = Vector2D();
self.velocidad = Vector2D();
self.aceleracion = Ve... | Python | zaydzuhri_stack_edu_python |
function get_ascii_sum s
begin
return sum generator expression ordinal c for c in s
end function
function sort_strings string_list
begin
return sorted string_list key=lambda x -> call get_ascii_sum x at 0 + call get_ascii_sum x at 1 reverse=true
end function
comment Example usage
set string_list = list tuple string key... | def get_ascii_sum(s):
return sum(ord(c) for c in s)
def sort_strings(string_list):
return sorted(string_list, key=lambda x: get_ascii_sum(x[0]) + get_ascii_sum(x[1]), reverse=True)
# Example usage
string_list = [("key1", "value1"), ("key2", "value2"), ("key3", "value3")]
sorted_list = sort_strings(string_list... | Python | jtatman_500k |
function remove_suspicious_number cls number
begin
if not number
begin
raise call ValueError string "number" must not be empty.
end
return remove SuspiciousPhoneNumbers number
end function | def remove_suspicious_number(cls, number):
if not number:
raise ValueError('"number" must not be empty.')
return SuspiciousPhoneNumbers.remove(number) | Python | nomic_cornstack_python_v1 |
for i in range length letters
begin
append L ordinal letters at i
end
set L_2 = list set L
set L_3 = list
set tmp = list
for i in range length L_2
begin
if i == length L_2 - 1
begin
if L_2 at i - 1 == L_2 at i - 1
begin
append tmp L_2 at i
append L_3 tmp
break
end
else
begin
break
end
end
if L_2 at i == L_2 at i + 1 ... | for i in range(len(letters)):
L.append(ord(letters[i]))
L_2 = list(set(L))
L_3 = []
tmp = []
for i in range(len(L_2)):
if i == len(L_2) - 1:
if L_2[i - 1] == L_2[i] - 1:
tmp.append(L_2[i])
L_3.append(tmp)
break
else:
break
if L_2[i] == L_... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
from typing import List
import sys
function read_input_file filename
begin
with open filename string r as input_file
begin
return list comprehension integer num for num in read input_file if num != string
end
end function
function moves cups num_moves verbose=true
begin
set move_id = 1
se... | #!/usr/bin/env python3
from typing import List
import sys
def read_input_file(filename):
with open(filename, 'r') as input_file:
return [int(num) for num in input_file.read() if num != '\n']
def moves(cups: List[int], num_moves: int, verbose = True):
move_id = 1
current_id = 0
len_cups = len... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
from app.engines import EmotionRecognizer , FaceDetector
function blur_faces face_detection_inference_results original_image
begin
return original_image
end function
function emotion_recognition_processing original_frame
begin
return original_frame
end function
function face_detector_infer... | import cv2
import numpy as np
from app.engines import EmotionRecognizer, FaceDetector
def blur_faces(face_detection_inference_results: np.ndarray, original_image: np.ndarray) -> np.ndarray:
return original_image
def emotion_recognition_processing(original_frame: np.ndarray) -> np.ndarray:
return original_f... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from enum import IntEnum
from datetime import datetime
from arp_basecollection import VMBaseCollection
from arp_settings import VMSettings
import json
class VMDiffType extends IntEnum
begin
set NONE = 0
set ADDED = 1
set CHANGEDMAC = 2
set CHANGEDNODE = 3
set CHANGEDMACNODE = 4
set CLOSED ... | # -*- coding: utf-8 -*-
from enum import IntEnum
from datetime import datetime
from arp_basecollection import VMBaseCollection
from arp_settings import VMSettings
import json
class VMDiffType(IntEnum):
NONE = 0
ADDED = 1
CHANGEDMAC = 2
CHANGEDNODE = 3
CHANGEDMACNODE = 4
CLOSED = 5
@stati... | Python | zaydzuhri_stack_edu_python |
function test_year_boundaries self
begin
call create name=string Date Test 2007 baked_date=call datetime year=2007 month=12 day=31 consumed_at=call datetime year=2007 month=12 day=31 hour=23 minute=59 second=59
call create name=string Date Test 2006 baked_date=call datetime year=2006 month=1 day=1 consumed_at=call date... | def test_year_boundaries(self):
Donut.objects.create(
name='Date Test 2007',
baked_date=datetime.datetime(year=2007, month=12, day=31),
consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59),
)
Donut.objects.create(
... | Python | nomic_cornstack_python_v1 |
from twixt import twixtBoard
import sys
import agent
from util import printc , bcolors | from twixt import twixtBoard
import sys
import agent
from util import printc, bcolors
| Python | zaydzuhri_stack_edu_python |
function func2 x
begin
return x * x
end function | def func2(x):
return x*x | Python | nomic_cornstack_python_v1 |
function main
begin
set db = call get_db_connection
call clean_db db
call make_tables db
call import_rows db DATA_FILE
close db
end function | def main():
db = get_db_connection()
clean_db(db)
make_tables(db)
import_rows(db, DATA_FILE)
db.close() | Python | nomic_cornstack_python_v1 |
import sys
import shutil
from unzipper import unzp
from compute import run_algo_on_dirs
if __name__ == string __main__
begin
string :parameter argv[1]: location of zip file with all assignments. The names of directories will be used for student_id fields :parameter argv[2]: location of zip file with starter code (direc... | import sys
import shutil
from unzipper import unzp
from compute import run_algo_on_dirs
if __name__ == "__main__":
"""
:parameter argv[1]: location of zip file with all assignments.
The names of directories will be used for student_id fields
:parameter argv[2]: location of zip file with starter code... | Python | zaydzuhri_stack_edu_python |
function test_get_file_executors self
begin
pass
end function | def test_get_file_executors(self):
pass | Python | nomic_cornstack_python_v1 |
function Add self other
begin
set new_descriptors = list
for desc in descriptors + descriptors
begin
if desc not in new_descriptors
begin
append new_descriptors desc
end
end
return call TypeDescriptorSet *new_descriptors
end function | def Add(self, other):
new_descriptors = []
for desc in self.descriptors + other.descriptors:
if desc not in new_descriptors:
new_descriptors.append(desc)
return TypeDescriptorSet(*new_descriptors) | Python | nomic_cornstack_python_v1 |
from sys import stdin
set input = readline
set n = integer right strip input
set num = list comprehension integer x for x in split right strip input
for _ in range integer right strip input
begin
set tuple s e = list comprehension integer x for x in split right strip input
set s = s - 1
set e = e - 1
if e - s % 2
begin... | from sys import stdin
input = stdin.readline
n = int(input().rstrip())
num = [int(x) for x in input().rstrip().split()]
for _ in range(int(input().rstrip())):
s, e = [int(x) for x in input().rstrip().split()]
s -= 1
e -= 1
if (e-s)%2:
print(0)
else:
if num[s:(s+e)//2] == num[(s+e)/... | Python | zaydzuhri_stack_edu_python |
function pump_command self param
begin
string Models "LNP Pump Commands" functionality of device. Switches between automatic or manual pump mode, and adjusts speed when in manual mode. :param param: 'a0' for auto, 'm0' for manual, [0-N] for speed. :return:
set lookup = list comprehension c for c in string 0123456789:;<... | def pump_command(self, param):
"""
Models "LNP Pump Commands" functionality of device.
Switches between automatic or manual pump mode, and adjusts speed when in manual mode.
:param param: 'a0' for auto, 'm0' for manual, [0-N] for speed.
:return:
"""
lookup = [c ... | Python | jtatman_500k |
string Write a script which asks the user to enter some numbers separated by spaces. It then prints the smallest and the largest of entered numbers, as well as sum of them. To make things more interesting, however, the numbers provided by the user are expressed using English words. That is user may input: one, two, thr... | '''
Write a script which asks the user to enter some numbers separated by spaces.
It then prints the smallest and the largest of entered numbers, as well as sum of them.
To make things more interesting, however, the numbers provided by the user are expressed using English words.
That is user may input: one, two, three,... | Python | zaydzuhri_stack_edu_python |
function get_genres
begin
set query = json get requests string https://api.themoviedb.org/3/genre/movie/list?api_key= + api_key + string &language=es-ES
set lista = list
for g in query at string genres
begin
set _genre = call Genero id=g at string id nombre=g at string name
append lista _genre
end
return lista
end fun... | def get_genres() -> List[Genero]:
query = (requests.get(
"https://api.themoviedb.org/3/genre/movie/list?api_key=" +
api_key+"&language=es-ES")).json()
lista = []
for g in query['genres']:
_genre = Genero(id=g['id'], nombre=g['name'])
lista.append(_genre)
return lista | Python | nomic_cornstack_python_v1 |
if hours == 24
begin
set hours = 0
end
if minutes == 60
begin
set minutes = 0
end
if minutes < 10
begin
print string { hours } :0 { minutes }
end
else
begin
print string { hours } : { minutes }
end | if hours == 24:
hours = 0
if minutes == 60:
minutes = 0
if minutes < 10:
print(f"{hours}:0{minutes}")
else:
print(f"{hours}:{minutes:}")
| Python | zaydzuhri_stack_edu_python |
import datetime
set total = call datetime 1 1 1
set total = total + time delta seconds=integer input
set total = total + time delta seconds=integer input
set total = total + time delta seconds=integer input
print string format time total string %#M:%S | import datetime
total = datetime.datetime(1, 1, 1)
total += datetime.timedelta(seconds=int(input()))
total += datetime.timedelta(seconds=int(input()))
total += datetime.timedelta(seconds=int(input()))
print(total.strftime('%#M:%S'))
| Python | zaydzuhri_stack_edu_python |
function skipNullPadding self buff
begin
string 不断地寻找 CHUNK_STRINGPOOL_TYPE,目前暂时没有遇到这种样本。
function readNext buff first_run=true
begin
set datas = call unpack string <i read buff 4
set header = datas at 0
if header == CHUNK_NULL_TYPE and first_run
begin
print string Skipping null padding in StringPoolChunk header
set he... | def skipNullPadding(self, buff):
'''
不断地寻找 CHUNK_STRINGPOOL_TYPE,目前暂时没有遇到这种样本。
'''
def readNext(buff, first_run=True):
datas = unpack('<i', buff.read(4))
header = datas[0]
if header == CHUNK_NULL_TYPE and first_run:
print("Skipping nul... | Python | jtatman_500k |
for i in S
begin
if i == string W
begin
set suma = suma + count
end
else
begin
set count = count + 1
end
end
print suma | for i in S:
if i=="W":
suma += count
else:
count += 1
print(suma) | Python | zaydzuhri_stack_edu_python |
function create self request
begin
set serializer = call CreateWorkArrangementSerializer data=data
if call is_valid raise_exception=true
begin
set request_data = save
try
begin
set work_arrangement = call add_work_arrangement request_data=request_data
set serializer = call PresentWorkArrangementsDataSerializer work_arr... | def create(self, request):
serializer = data_serializers.CreateWorkArrangementSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
request_data = serializer.save()
try:
work_arrangement = self.controller.add_work_arrangement(request_data=req... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import csv
import datetime
function isDebugMode bl
begin
global driver
if bl == true
begin
set driver = call Chrome
end
else
begin
set options = options
call add_argument string --headles... | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import csv
import datetime
def isDebugMode(bl):
global driver
if bl == True:
driver = webdriver.Chrome()
else:
options = Options()
options.add_argum... | Python | zaydzuhri_stack_edu_python |
import numpy as np
class nnlayer
begin
function __init__ self input_size output_size batch_size
begin
set input_size = input_size
set output_size = output_size
set batch_size = batch_size
set w = call init_weights
set b = call init_bias
end function
function forward self x
begin
set wx = matrix multiply w x + b
return ... | import numpy as np
class nnlayer():
def __init__(self, input_size, output_size, batch_size):
self.input_size = input_size
self.output_size = output_size
self.batch_size = batch_size
self.w = self.init_weights()
self.b = self.init_bias()
def forwar... | Python | zaydzuhri_stack_edu_python |
comment Clase autómata
from evaluador.automata.paso import *
class Automata extends Grafo
begin
function __init__ self
begin
call __init__
set __estados = _Grafo__nodos
set addEstado = addNodo
set __palabra = list
set pila = call Pila
call incluir string #
end function
function addNodo self valor final
begin
append _G... | #Clase autómata
from evaluador.automata.paso import *
class Automata(Grafo):
def __init__(self):
super().__init__()
self.__estados = self._Grafo__nodos
self.addEstado = self.addNodo
self.__palabra = []
self.pila = Pila()
self.pila.incluir("#")
def addNodo(self, v... | Python | zaydzuhri_stack_edu_python |
function init_db_command
begin
call init_db
call echo string Initialized the database.
end function | def init_db_command():
init_db()
click.echo('Initialized the database.') | Python | nomic_cornstack_python_v1 |
function to_bqstorage self
begin
set tuple table_id _ _ = call partition string @
set tuple table_id _ _ = call partition string $
set table_ref = string projects/ { project } /datasets/ { dataset_id } /tables/ { table_id }
return table_ref
end function | def to_bqstorage(self) -> str:
table_id, _, _ = self.table_id.partition("@")
table_id, _, _ = table_id.partition("$")
table_ref = (
f"projects/{self.project}/datasets/{self.dataset_id}/tables/{table_id}"
)
return table_ref | Python | nomic_cornstack_python_v1 |
import unittest
comment from telnetlib import EC
import self as self
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdr... | import unittest
# from telnetlib import EC
import self as self
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.s... | Python | zaydzuhri_stack_edu_python |
set myList = list 87 45 41 65 94 41 99 94
print string Sample List- myList
set myNewList = list call fromkeys myList
print string Unique Items- myNewList
set myTuple = tuple myNewList
print string Tuple= myTuple
print string Min- min myNewList
print string Max- max myNewList | myList = [87, 45, 41, 65, 94, 41, 99, 94]
print("Sample List- ", myList)
myNewList = list(dict.fromkeys(myList))
print("Unique Items- ",myNewList)
myTuple = tuple(myNewList)
print("Tuple= ", myTuple)
print("Min- ", min(myNewList))
print("Max- ", max(myNewList))
| Python | zaydzuhri_stack_edu_python |
function _native_download_file meta full_dst_file_name max_concurrency
begin
set download_url = presigned_url
set gcs_headers = none
set access_token : Optional at str = none
if not download_url
begin
set download_url = call generate_file_url stage_info at string location left strip src_file_name string /
set access_to... | def _native_download_file(
meta: "SnowflakeFileMeta", full_dst_file_name: str, max_concurrency: int
):
download_url = meta.presigned_url
gcs_headers = None
access_token: Optional[str] = None
if not download_url:
download_url = SnowflakeGCSUtil.generate_file_url(
... | Python | nomic_cornstack_python_v1 |
function epsilon self
begin
if steps > EPS_DECAY
begin
return EPS_END
end
else
begin
set delta = EPS_START - EPS_END * steps / EPS_DECAY
return EPS_START - delta
end
end function | def epsilon(self):
if self.steps > EPS_DECAY:
return EPS_END
else:
delta = ( EPS_START - EPS_END ) * ( self.steps / EPS_DECAY )
return EPS_START - delta | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
set data = list 2 3 5 6 8 4 2 4 6 9
histogram data
title plt string Histogram of Data
x label string Data Values
y label string Frequency
show | import matplotlib.pyplot as plt
data = [2, 3, 5, 6, 8, 4, 2, 4, 6, 9]
plt.hist(data)
plt.title("Histogram of Data")
plt.xlabel("Data Values")
plt.ylabel("Frequency")
plt.show()
| Python | flytech_python_25k |
function roc_score model X_test_set y_test_set
begin
set y_pred = call predict_proba X_test_set at tuple slice : : 1
set tuple fpr tpr thresholds = call roc_curve y_test_set y_pred
set roc_auc = call auc fpr tpr
print string Area under the ROC curve : %f % roc_auc
end function | def roc_score(model,X_test_set,y_test_set):
y_pred = model.predict_proba(X_test_set)[:,1]
fpr,tpr,thresholds = roc_curve(y_test_set,y_pred)
roc_auc=auc(fpr,tpr)
print ("Area under the ROC curve : %f" % roc_auc) | Python | nomic_cornstack_python_v1 |
comment Lint as: python3
comment pylint: disable=g-bad-file-header
comment Copyright 2020 DeepMind Technologies Limited. All Rights Reserved.
comment Licensed under the Apache License, Version 2.0 (the "License");
comment you may not use this file except in compliance with the License.
comment You may obtain a copy of ... | # Lint as: python3
# pylint: disable=g-bad-file-header
# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.a... | Python | zaydzuhri_stack_edu_python |
comment real signature unknown; restored from __doc__
function XPathEvaluator etree_or_element namespaces=none extensions=none regexp=true smart_strings=true
begin
pass
end function | def XPathEvaluator(etree_or_element, namespaces=None, extensions=None, regexp=True, smart_strings=True): # real signature unknown; restored from __doc__
pass | Python | nomic_cornstack_python_v1 |
comment This script takes an input directory with a number of (hyper)stacks.
comment Each input stack will be formatted as a montage with the chosen
comment dimensions and frame interval. The resulting montage images are saved
comment in the chosen output directory.
comment Jorik van Rijn <jorik.vanrijn@gmail.com> - 20... | # This script takes an input directory with a number of (hyper)stacks.
# Each input stack will be formatted as a montage with the chosen
# dimensions and frame interval. The resulting montage images are saved
# in the chosen output directory.
# Jorik van Rijn <jorik.vanrijn@gmail.com> - 2020
import os
import ij.IJ as ... | Python | zaydzuhri_stack_edu_python |
function compareLongestString str1 str2
begin
if length str1 > length str2
begin
set longestString = str1
end
else
if length str2 > length str1
begin
set longestString = str2
end
else
begin
set longestString = string Strings have the same length
end
return longestString
end function
print call compareLongestString stri... | def compareLongestString(str1, str2):
if len(str1) > len(str2):
longestString = str1
elif len(str2) > len(str1):
longestString = str2
else:
longestString = "Strings have the same length"
return longestString
print(compareLongestString("Python", "C++")) | Python | iamtarun_python_18k_alpaca |
function connect self
begin
set con = call connect name + string .db
set text_factory = str
end function | def connect(self):
self.con = lite.connect(self.name + '.db')
self.con.text_factory = str | Python | nomic_cornstack_python_v1 |
function set_offset self offset
begin
set _offset = offset
end function | def set_offset(self, offset):
self._offset = offset | Python | nomic_cornstack_python_v1 |
function resolve_field struct_object attr_name attr_value
begin
if starts with attr_name string _
begin
return none
end
if is instance attr_value BaseField
begin
comment pylint: disable=protected-access
set new_field : BaseField = call _replace_parent parent=struct_object
return new_field
end
return none
end function | def resolve_field(struct_object: Struct, attr_name: str, attr_value: Any) -> Optional[BaseField]:
if attr_name.startswith("_"):
return None
if isinstance(attr_value, BaseField):
new_field: BaseField = attr_value._replace_parent(parent=struct_object) # pylint: disable=protected-... | Python | nomic_cornstack_python_v1 |
from math import sqrt
string line (a, b, c) in the form ax+by+c=0 point (x0,y0)
function distance_to_line point line
begin
set tuple a b c = line
set tuple x0 y0 = point
set dist = absolute a * x0 + b * y0 + c
set norm_term = square root a ^ 2 + b ^ 2
return dist / norm_term
end function
comment stores a line using thr... | from math import sqrt
'''
line (a, b, c) in the form ax+by+c=0
point (x0,y0)
'''
def distance_to_line(point, line):
a, b, c = line
x0, y0 = point
dist = abs(a * x0 + b * y0 + c)
norm_term = sqrt(a ** 2 + b ** 2)
return dist / norm_term
# stores a line using three variable A, B, C
# which represents line Ax+B... | Python | zaydzuhri_stack_edu_python |
function _get_parser
begin
set parser = call ArgumentParser description=__doc__ formatter_class=ArgumentDefaultsHelpFormatter
call add_argument string --backend required=true help=string Backend to check 5xx ratio.
call add_argument string --base-url-path default=string 127.0.0.1/haproxy/stats
call add_argument string ... | def _get_parser():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--backend", required=True, help="Backend to check 5xx ratio.")
parser.add_argument("--base-url-path", default="127.0.0.1/haproxy/stats")
parser.add_argume... | Python | nomic_cornstack_python_v1 |
from __future__ import absolute_import
from compat import Iterable
from dtypes import is_string , is_integer , is_bool
from scalar import is_scalar
from lists import is_list_same , is_list_unique
function is_iterable_unique x
begin
assert not call is_scalar x
return call is_list_unique list comprehension elem for elem ... | from __future__ import absolute_import
from ..compat import Iterable
from ..dtypes import is_string, is_integer, is_bool
from .scalar import is_scalar
from .lists import is_list_same, is_list_unique
def is_iterable_unique(x):
assert not is_scalar(x)
return is_list_unique([elem for elem in x])
def is_iterab... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.