code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function add_static_relationships
begin
for r in STATIC_RELATIONSHIPS
begin
if not first filter by query name=r
begin
add session call Relationship name=r description=STATIC_RELATIONSHIPS at r
end
end
end function | def add_static_relationships():
for r in STATIC_RELATIONSHIPS:
if not Relationship.query.filter_by(name=r).first():
db.session.add(Relationship(name=r,
description=STATIC_RELATIONSHIPS[r])) | Python | nomic_cornstack_python_v1 |
comment Fonction puissance
function fonction_puissance valeur puissance
begin
if puissance == 0
begin
return 1
end
if puissance == 1
begin
return valeur
end
set temp = valeur
while puissance != 1
begin
set temp = temp * valeur
set puissance = puissance - 1
end
return temp
end function | #Fonction puissance
def fonction_puissance(valeur, puissance):
if puissance == 0:
return 1
if puissance == 1:
return valeur
temp = valeur
while puissance !=1:
temp = temp * valeur
puissance = puissance - 1
return temp | Python | zaydzuhri_stack_edu_python |
function generate_k_folds dataset k
begin
set tuple f c = dataset
set tuple N D = shape
set idx = call permutation N
set tuple f c = tuple f at idx c at idx
comment fs, cs = np.array_split(f, k), np.array_split(c, k)
set folds = list
set test_size = N // k
for fold in range k
begin
comment pdb.set_trace()
set test_idx... | def generate_k_folds(dataset, k):
f, c = dataset
N, D = f.shape
idx = np.random.permutation(N)
f, c = f[idx], c[idx]
# fs, cs = np.array_split(f, k), np.array_split(c, k)
folds = []
test_size = N // k
for fold in range(k):
# pdb.set_trace()
test_idx = np.arang... | Python | nomic_cornstack_python_v1 |
function display_laps self figsize=tuple 8 4 mark_elapsed_time=true minutes_elapsed=false show_stop=true annotate=true verbose=true vlines=true styles=list string ggplot string seaborn-talk
begin
if not times
begin
print string No times to display.
return
end
if show_stop
begin
set times = times
end
else
begin
set time... | def display_laps(self,
figsize=(8,4),
mark_elapsed_time=True,
minutes_elapsed=False,
show_stop=True,
annotate=True,
verbose=True,
vlines=True,
styles... | Python | nomic_cornstack_python_v1 |
function with_metaclass meta *bases
begin
class metaclass extends meta
begin
set __call__ = __call__
set __init__ = __init__
function __new__ cls name this_bases d
begin
if this_bases is none
begin
return call __new__ cls name tuple d
end
return call meta name bases d
end function
end class
return call metaclass strin... | def with_metaclass(meta, *bases):
class metaclass(meta):
__call__ = type.__call__
__init__ = type.__init__
def __new__(cls, name, this_bases, d):
if this_bases is None:
return type.__new__(cls, name, (), d)
return meta(name, bases, d)
return metacl... | Python | nomic_cornstack_python_v1 |
function runEliminaContacto self
begin
comment C = Contactos.Contactos(self.userID)
call agregaContacto contactoID contactoNombre contactoEstado
call eliminaContacto contactoID
assert raises ContactosError consultaContacto contactoID
end function | def runEliminaContacto(self):
#C = Contactos.Contactos(self.userID)
self.C.agregaContacto(self.contactoID, self.contactoNombre, self.contactoEstado)
self.C.eliminaContacto(self.contactoID)
self.assertRaises(Contactos.ContactosError,self.C.consultaContacto,self.contactoID) | Python | nomic_cornstack_python_v1 |
function add_tag_data tag
begin
set add_tag = call Tag tag=tag
add session add_tag
try
begin
commit session
end
except tuple Exception SQLAlchemyError InvalidRequestError IntegrityError as e
begin
print tag + string + string e
end
end function | def add_tag_data(tag):
add_tag = Tag(tag=tag)
db.session.add(add_tag)
try:
db.session.commit()
except (Exception, exc.SQLAlchemyError, exc.InvalidRequestError, exc.IntegrityError) as e:
print(tag + '\n' + str(e)) | Python | nomic_cornstack_python_v1 |
function support_redirect request **kwargs
begin
return call HttpResponseRedirect call get_support_url request
end function | def support_redirect(request, **kwargs):
return HttpResponseRedirect(get_support_url(request)) | Python | nomic_cornstack_python_v1 |
function is_published self
begin
set current_date = now
if current_date >= pub_date
begin
return true
end
return false
end function | def is_published(self):
current_date = timezone.now()
if (current_date >= self.pub_date):
return True
return False | Python | nomic_cornstack_python_v1 |
import heapq
import math
class Solution
begin
function minAreaRect self points
begin
set min_area = inf
set q = list comprehension x for x in points
call heapify q
set max_y_line = dict
while length q > 0
begin
set top = q at 0 at 0
set ps = list
comment get all the (x,y) pairs for this x
while length q > 0 and q at ... | import heapq
import math
class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
min_area = math.inf
q = [x for x in points]
heapq.heapify(q)
max_y_line = {}
while len(q) > 0:
top = q[0][0]
ps = []
# get all the (x,y) pa... | Python | zaydzuhri_stack_edu_python |
function ballot_marked_avg self
begin
return _ballot_stats at string ballot.marked.avg
end function | def ballot_marked_avg(self):
return self._ballot_stats['ballot.marked.avg'] | Python | nomic_cornstack_python_v1 |
function remove_order_detail self n_order_detail
begin
pop order_detail n_order_detail
return length order_detail - 1
end function | def remove_order_detail(self, n_order_detail):
self.order_detail.pop(n_order_detail)
return len(self.order_detail) - 1 | Python | nomic_cornstack_python_v1 |
from rosalind import readfile
import math
function log_prob dna gcprob
begin
set probs = dict string A 1 - gcprob / 2 ; string T 1 - gcprob / 2 ; string G gcprob / 2 ; string C gcprob / 2
set base = 1
for nucleotide in dna
begin
set base = base * probs at nucleotide
end
return call log10 base
end function
set lines = c... | from rosalind import readfile
import math
def log_prob(dna, gcprob):
probs = {"A":(1-gcprob)/2,
"T":(1-gcprob)/2,
"G":gcprob/2,
"C":gcprob/2}
base = 1
for nucleotide in dna:
base *= probs[nucleotide]
return math.log10(base)
lines = readfile()
dna = lines[... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding:UTF-8-*-
string @File:test_demo.py @Author: Yaochenglong @Date : @Desc:
import json
comment json.dumps()用于将dict类型的数据转成str,因为如果直接将dict类型的数据写入json文件中会发生报错,因此在将数据写入时需要用到该函数
set name_emb = dict string a string 111 ; string b string 222 ; string c string 333
comment print(name_em... | #!/usr/bin/python3
# -*- coding:UTF-8-*-
'''
@File:test_demo.py
@Author: Yaochenglong
@Date :
@Desc:
'''
import json
########### json.dumps()用于将dict类型的数据转成str,因为如果直接将dict类型的数据写入json文件中会发生报错,因此在将数据写入时需要用到该函数
name_emb={'a':'111','b':'222','c':'333'}
# print(name_emb)
# print(type(name_emb))
# jsObj = json.dumps(name_em... | Python | zaydzuhri_stack_edu_python |
function getPolygonTriangleVertices self polygonId triangleId
begin
pass
end function | def getPolygonTriangleVertices(self, polygonId, triangleId):
pass | Python | nomic_cornstack_python_v1 |
function trivial_pow x y
begin
comment first iteration is here
set result = x
for _ in range y - 1
begin
set result = result * x
end
return result
end function
comment exponentiation by squaring
function optimazed_pow x y
begin
if y < 0
begin
return call optimazed_pow 1 / x - y
end
else
if y == 0
begin
return 1
end
els... | def trivial_pow(x, y):
result = x # first iteration is here
for _ in range(y-1):
result *= x
return result
# exponentiation by squaring
def optimazed_pow(x, y):
if y < 0:
return optimazed_pow(1/x, -y)
elif y == 0:
return 1
elif y == 1:
return x
elif y % 2 == ... | Python | zaydzuhri_stack_edu_python |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import sys
append path string ../../scripts/
from smoothers import kernel_smoother
import pandas as pd
comment Import data
set data = read csv string ../../data/utilities.csv delimiter=string ,
comment Parse data
set X = data at string t... | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append('../../scripts/')
from smoothers import kernel_smoother
import pandas as pd
# Import data
data = pd.read_csv('../../data/utilities.csv', delimiter=',')
# Parse data
X = data['temp']
Y = np.log(data['gasbill'... | Python | zaydzuhri_stack_edu_python |
function kwargs_to_matrix **kwargs
begin
string Turn a set of keyword arguments into a transformation matrix.
set matrix = call eye 4
if string matrix in kwargs
begin
comment a matrix takes precedence over other options
set matrix = kwargs at string matrix
end
else
if string quaternion in kwargs
begin
set matrix = call... | def kwargs_to_matrix(**kwargs):
"""
Turn a set of keyword arguments into a transformation matrix.
"""
matrix = np.eye(4)
if 'matrix' in kwargs:
# a matrix takes precedence over other options
matrix = kwargs['matrix']
elif 'quaternion' in kwargs:
matrix = transformations.q... | Python | jtatman_500k |
function lagrangian_quantization_with_lambda x_org y_true x_adv model lambda_ y_target=none
begin
comment Eq. (2)
set unquantized_perturbation = x_adv - x_org
comment If the unquantized perturbation is an integer already, preserve this number.
comment Essentially, this step prevents floating point errors, e.g. prevent ... | def lagrangian_quantization_with_lambda(x_org, y_true, x_adv, model, lambda_, y_target=None):
# Eq. (2)
unquantized_perturbation = x_adv - x_org
# If the unquantized perturbation is an integer already, preserve this number.
# Essentially, this step prevents floating point errors, e.g. prevent floor(0.9... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
string 6,写函数,接收两个数字参数,返回比较大的那个数字。
function get_a_bigger num1 num2
begin
if num1 > num2
begin
return num1
end
else
begin
return num2
end
end function
set n1 = 5
set n2 = 6
set ret = call get_a_bigger n1 n2
print ret
print string ------------------1
comment 三目运算
s... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
6,写函数,接收两个数字参数,返回比较大的那个数字。
'''
def get_a_bigger(num1,num2):
if num1 > num2:
return num1
else:
return num2
n1 = 5
n2 = 6
ret = get_a_bigger(n1,n2)
print(ret)
print('------------------1')
#三目运算
a=10
b=20
d= 'jack'
c = a if a > b else b
# c = a i... | Python | zaydzuhri_stack_edu_python |
function attach_all_trees self node axis
begin
set sub_seg_tree = call attach_one_tree node axis
if sub_seg_tree is not none
begin
append _queue at axis + 1 sub_seg_tree
end
if left is not none
begin
call attach_all_trees left axis
end
if right is not none
begin
call attach_all_trees right axis
end
end function | def attach_all_trees(self, node, axis):
sub_seg_tree = self.attach_one_tree(node, axis)
if sub_seg_tree is not None:
self._queue[axis+1].append(sub_seg_tree)
if node.left is not None:
self.attach_all_trees(node.left, axis)
if node.right is not None:
se... | Python | nomic_cornstack_python_v1 |
import datetime
import time
import tweepy as twitter
import keys
import random
set auth = call OAuthHandler api_key api_secret
call set_access_token access_key access_secret
set api = call API auth
function twitter_bot_retweet hashtag delay
begin
while true
begin
print string { now } /n
for tweet in items call Cursor s... | import datetime
import time
import tweepy as twitter
import keys
import random
auth = twitter.OAuthHandler(keys.api_key, keys.api_secret)
auth.set_access_token(keys.access_key, keys.access_secret)
api = twitter.API(auth)
def twitter_bot_retweet(hashtag, delay):
while True:
print(f'\n{datetime.datetime.... | Python | zaydzuhri_stack_edu_python |
function get_op_handle self tf_op
begin
if is instance tf_op list
begin
return list comprehension call get_op_handle_by_name name for op in tf_op
end
else
begin
return call get_op_handle_by_name name
end
end function | def get_op_handle(self, tf_op):
if isinstance(tf_op, list):
return [self.get_op_handle_by_name(op.name) for op in tf_op]
else:
return self.get_op_handle_by_name(tf_op.name) | Python | nomic_cornstack_python_v1 |
function generate_random_filename_from_email email
begin
set email_prefix = email at slice : index email string @ :
set random_file_name = join string list string hex at slice : 6 : email_prefix string .json
return random_file_name
end function | def generate_random_filename_from_email(email):
email_prefix = email[:email.index("@")]
random_file_name = ''.join([str(uuid.uuid4().hex[:6]), email_prefix, '.json'])
return random_file_name | Python | nomic_cornstack_python_v1 |
string Challenge #369 (easy)from /r/dailyprogrammer https://old.reddit.com/r/dailyprogrammer/comments/a0lhxx/20181126_challenge_369_easy_hex_colors/
from functools import reduce
function hexcolor1 red green blue
begin
string Most straightforward solution
return format string #{:02x}{:02x}{:02x} red green blue
end funct... | """
Challenge #369 (easy)from /r/dailyprogrammer
https://old.reddit.com/r/dailyprogrammer/comments/a0lhxx/20181126_challenge_369_easy_hex_colors/
"""
from functools import reduce
def hexcolor1(red, green, blue):
"""Most straightforward solution"""
return '#{:02x}{:02x}{:02x}'.format(red, green, blue)
# Fun/b... | Python | zaydzuhri_stack_edu_python |
function bucket_sort numbers num_buckets=10
begin
string Sort given numbers by distributing into buckets representing subranges, then sorting each bucket and concatenating all buckets in sorted order. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?
end funct... | def bucket_sort(numbers, num_buckets=10):
"""Sort given numbers by distributing into buckets representing subranges,
then sorting each bucket and concatenating all buckets in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
... | Python | zaydzuhri_stack_edu_python |
from collections import OrderedDict
from bs4 import BeautifulSoup
from selenium import webdriver
comment Complete the url
set url = string https://URLHERE.xyz/
set attemps = 0
function get_mp3 query
begin
string :param query: Artist/Song to search for. It gets transformed in a proper url by the transform_query method E... | from collections import OrderedDict
from bs4 import BeautifulSoup
from selenium import webdriver
#Complete the url
url = "https://URLHERE.xyz/"
attemps = 0
def get_mp3(query):
'''
:param query: Artist/Song to search for. It gets transformed in a proper url by the transform_query method Ex. 'Avenged Sevenfol... | Python | zaydzuhri_stack_edu_python |
function input msg=string default=string title=string Lackey Input hidden=false
begin
string Creates an input dialog with the specified message and default text. If `hidden`, creates a password dialog instead. Returns the entered value.
set root = call Tk
set input_text = call StringVar
set default
call PopupInput ro... | def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInpu... | Python | jtatman_500k |
function tag_break_points graph=none
begin
set break_points_list = call break_points graph=graph
for break_point in break_points_list
begin
set tuple id1 id2 = break_point
set edge at id1 at id2 at string label = string $
set edge at id1 at id2 at string type = string breakpoint
end
end function | def tag_break_points(graph = None):
break_points_list = break_points(graph = graph)
for break_point in break_points_list:
id1, id2 = break_point
graph.edge[id1][id2]['label']= '$'
graph.edge[id1][id2]['type']='breakpoint' | Python | nomic_cornstack_python_v1 |
function load_data self filename
begin
comment if "stanford" in filename:
set columns = list string t string ped id string x string y
if delim == string tab
begin
set data = read csv filename header=none delimiter=string names=columns dtype=dict string t float64 ; string ped id int32 ; string x float64 ; string y floa... | def load_data(self,filename):
#if "stanford" in filename:
columns = ['t','ped id','x','y']
if self.delim=="tab":
data=pd.read_csv(filename,header=None,delimiter="\t",names=columns, dtype={'t': np.float64, 'ped id': np.int32, 'x': np.float64, 'y': np.float64})
elif self.delim=="space":
data=pd.read_csv(fil... | Python | nomic_cornstack_python_v1 |
function plot_cumulative_returns stocklist_mean_return period=1 ax=none
begin
if ax is none
begin
set tuple f ax = call subplots 1 1 figsize=tuple 18 6
end
set ret_wide = call pivot index=string date columns=string factor_quantile values=period
if period > 1
begin
set compound_returns = lambda ret period -> call nanmea... | def plot_cumulative_returns(stocklist_mean_return, period=1, ax=None):
if ax is None:
f, ax = plt.subplots(1, 1, figsize=(18, 6))
ret_wide = stocklist_mean_return.reset_index()\
.pivot(index='date', columns='factor_quantile', values=period)
if period > 1:
compound_returns = lambd... | Python | nomic_cornstack_python_v1 |
comment game environment #
import tkinter as tk
import tkinter.messagebox
import numpy as np
from game_logic import game_logic
comment default value
comment pixels of unit
set UNIT = 30
comment grid height
set GAME_H = 15
comment grid width
set GAME_W = 15
comment Chess radius
set RADIUS = 12
comment height of checkerb... | ####################
# game environment #
####################
import tkinter as tk
import tkinter.messagebox
import numpy as np
from game_logic import game_logic
# default value
UNIT = 30 # pixels of unit
GAME_H = 15 # grid height
GAME_W = 15 # grid width
RADIUS = 12 # Chess radius
# height of checkerboard + fin... | Python | zaydzuhri_stack_edu_python |
string What a framebuffer should support: 1. init with random trajectories
import tqdm
import torch
import numpy as np
from robot.utils import togpu
class CircleBuffer
begin
function __init__ self maxlen
begin
set buffer = list none * maxlen
set maxlen = maxlen
set index = 0
set size = 0
set start = 0
end function
func... | """
What a framebuffer should support:
1. init with random trajectories
"""
import tqdm
import torch
import numpy as np
from robot.utils import togpu
class CircleBuffer:
def __init__(self, maxlen):
self.buffer = [None] * maxlen
self.maxlen = maxlen
self.index = 0
self.size = 0
... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from tkinter import scrolledtext , messagebox
from PIL import ImageTk , Image
import mysql.connector
from mysql.connector import Error
import serial
import time
from add_book import add_book
from update_book import update_book
function display_scanned_book
begin
global status
try
begin
comment Get... | from tkinter import *
from tkinter import scrolledtext, messagebox
from PIL import ImageTk, Image
import mysql.connector
from mysql.connector import Error
import serial
import time
from add_book import add_book
from update_book import update_book
###########################################################... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
set app = APP
set client = test_client
set database_path = string postgres://postgres:postgres@localhost:5432/casting_test
call setup_db app database_path
set casting_assistant_auth = dict string authorization string Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlFVTTRSRVUxUVRWR016VkNPVV... | def setUp(self):
self.app = APP
self.client = self.app.test_client
self.database_path = "postgres://postgres:postgres@localhost:5432/casting_test"
setup_db(self.app, self.database_path)
self.casting_assistant_auth = {
'authorization': 'Bearer eyJhbGciOiJSUzI1NiIsIn... | Python | nomic_cornstack_python_v1 |
function kube_node_status_ready self message **kwargs
begin
set service_check_name = NAMESPACE + string .node.ready
for metric in metric
begin
call _condition_to_service_check metric service_check_name condition_to_status_positive tags=list call _label_to_tag string node label
end
end function | def kube_node_status_ready(self, message, **kwargs):
service_check_name = self.NAMESPACE + '.node.ready'
for metric in message.metric:
self._condition_to_service_check(metric, service_check_name, self.condition_to_status_positive,
tags=[self._labe... | Python | nomic_cornstack_python_v1 |
function test_send_with_attachments_multiple_recipients self
begin
set attachments = dict string attachment_file1.txt call ContentFile string content ; string attachment_file2.txt call ContentFile string content
set email = call send recipients=list string a@example.com string b@example.com sender=string from@example.c... | def test_send_with_attachments_multiple_recipients(self):
attachments = {
'attachment_file1.txt': ContentFile('content'),
'attachment_file2.txt': ContentFile('content'),
}
email = send(recipients=['a@example.com', 'b@example.com'],
sender='from@exampl... | Python | nomic_cornstack_python_v1 |
function test_distance_correlation_multivariate self
begin
set matrix1 = array tuple tuple 1 2 3 tuple 4 5 6 tuple 7 8 9
set matrix2 = array tuple tuple 7 3 6 tuple 2 1 4 tuple 3 8 1
set matrix3 = array tuple tuple 1 1 1 tuple 2 1 1 tuple 1 1 1
set constant_matrix = ones tuple 3 3
set correlation = call distance_correl... | def test_distance_correlation_multivariate(self):
matrix1 = np.array(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
matrix2 = np.array(((7, 3, 6), (2, 1, 4), (3, 8, 1)))
matrix3 = np.array(((1, 1, 1), (2, 1, 1), (1, 1, 1)))
constant_matrix = np.ones((3, 3))
correlation = dcor.distance_corre... | Python | nomic_cornstack_python_v1 |
function gcloud_upload_file audio_data gcloud_bucket_name
begin
set bucket = call get_bucket gcloud_bucket_name
set remote_filepath = string %s % uuid 4
set blob = call blob remote_filepath
comment Upload the audio
call upload_from_string audio_data
set url = public_url
if is instance url binary_type
begin
set url = de... | def gcloud_upload_file(audio_data, gcloud_bucket_name):
bucket = gce_storage_client.get_bucket(gcloud_bucket_name)
remote_filepath = "%s" % uuid4()
blob = bucket.blob(remote_filepath)
# Upload the audio
blob.upload_from_string(audio_data)
url = blob.public_url
if isinstance(url, six.binar... | Python | nomic_cornstack_python_v1 |
function __isNotRcaEvent self event
begin
if HEALTH_EVENT_TYPE in event at PROPERTIES and upper event at PROPERTIES at HEALTH_EVENT_TYPE == RCA
begin
return false
end
if RECOMMENDED_ACTIONS_CONTENT in event at PROPERTIES
begin
return false
end
return true
end function | def __isNotRcaEvent(self, event: Dict) -> bool:
if HEALTH_EVENT_TYPE in event[PROPERTIES] and event[PROPERTIES][HEALTH_EVENT_TYPE].upper() == RCA:
return False
if RECOMMENDED_ACTIONS_CONTENT in event[PROPERTIES]:
return False
return True | Python | nomic_cornstack_python_v1 |
function _get_desktop_size
begin
if name == string posix
begin
try
begin
set xrandr_query = check output list string xrandr string --query
set sizes = find all string \bconnected primary (\d+)x(\d+) xrandr_query
if sizes at 0
begin
return call Point integer sizes at 0 at 0 integer sizes at 0 at 1
end
end
comment pylint... | def _get_desktop_size():
if os.name == "posix":
try:
xrandr_query = subprocess.check_output(["xrandr", "--query"])
sizes = re.findall(r"\bconnected primary (\d+)x(\d+)", xrandr_query)
if sizes[0]:
return point.Point(int(sizes[0][0]), int(sizes[0][1]))
except: # pylint: disable=bare-... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import numpy as np
function read dimensao
begin
string Metodo para ler arquivos das matrizes para serem multiplicadas. @param dimensao: dimensão das matrizes para serem lidas. @return mA: matriz A @return mB: matriz B
set matriz_vetor = list
set contador = 0
s... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
def read(dimensao):
""" Metodo para ler arquivos das matrizes para serem multiplicadas.
@param dimensao: dimensão das matrizes para serem lidas.
@return mA: matriz A
@return mB: matriz B
"""
matriz_vetor = []
contador = 0
ma... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import scipy.stats as stats
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing
import seaborn as sns
import pymc3 as pm
import theano
from sklearn.metrics import mean_squared_error
class UnpooledMod... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import scipy.stats as stats
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing
import seaborn as sns
import pymc3 as pm
import theano
from sklearn.metrics import mean_squared_error
class UnpooledMo... | Python | zaydzuhri_stack_edu_python |
function network_config self
begin
return get pulumi self string network_config
end function | def network_config(self) -> Optional[pulumi.Input['NetworkConfigArgs']]:
return pulumi.get(self, "network_config") | Python | nomic_cornstack_python_v1 |
function append_ellapsed_time func
begin
function wrapper *args **kwargs
begin
set start_time = time
set diagnostics = call func *args keyword kwargs
set diagnostics at string info at string elapsed-time = time - start_time
return diagnostics
end function
return wrapper
end function | def append_ellapsed_time(func):
def wrapper(*args, **kwargs):
start_time = time()
diagnostics = func(*args, **kwargs)
diagnostics['info']['elapsed-time'] = time() - start_time
return diagnostics
return wrapper | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function findTheDifference self s t
begin
string :type s: str :type t: str :rtype: str
set cnt = list 0 * 265
for c in s
begin
set cnt at ordinal c = cnt at ordinal c + 1
end
for c in t
begin
if cnt at ordinal c == 0
begin
return c
end
set cnt at ordinal c = cnt at ordinal c - 1
end
... | class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
cnt = [0]*265
for c in s:
cnt[ord(c)] += 1
for c in t:
if cnt[ord(c)]==0:
return c
cnt[ord(c)] ... | Python | zaydzuhri_stack_edu_python |
function find_tool coreclr_args tool_name search_core_root=true search_product_location=true search_path=true throw_on_not_found=true
begin
comment First, look in Core_Root, if there is one.
if search_core_root and has attribute coreclr_args string core_root and core_root is not none and is directory path core_root
beg... | def find_tool(coreclr_args, tool_name, search_core_root=True, search_product_location=True, search_path=True, throw_on_not_found=True):
# First, look in Core_Root, if there is one.
if search_core_root and hasattr(coreclr_args, "core_root") and coreclr_args.core_root is not None and os.path.isdir(coreclr_args.c... | Python | nomic_cornstack_python_v1 |
comment https://leetcode.com/problems/shortest-distance-to-a-character/
class Solution
begin
function shortestToChar self S C
begin
set ret = list
set ix = list
for x in range 0 length S
begin
comment equals to inf
append ret 100000
if S at x == C
begin
append ix x
set ret at - 1 = 0
end
end
set prev = - 1
for x in i... | # https://leetcode.com/problems/shortest-distance-to-a-character/
class Solution:
def shortestToChar(self, S: str, C: str) -> List[int]:
ret = []
ix = []
for x in range(0, len(S)) :
ret.append(100000) # equals to inf
if S[x] == C :
ix.append(x)
... | Python | zaydzuhri_stack_edu_python |
function get_single_parameter self name
begin
set params = parameters project at name
set values = values call parametervalues
assert length values == 1
return call get_value values at 0
end function | def get_single_parameter(self, name):
params = self.project.parameters()[name]
values = params.parametervalues().values()
assert len(values) == 1
return self.get_value(values[0]) | Python | nomic_cornstack_python_v1 |
function stop self
begin
warning string Stop called from thread ``%s'' and %r name call getcurrent
set stopping = true
if ident != _thread
begin
call wakeup
end
else
begin
call shutdown_tasks _services _tasks
end
end function | def stop(self):
self._log.warning("Stop called from thread ``%s'' and %r",
threading.current_thread().name, greenlet.getcurrent())
self.stopping = True
if threading.current_thread().ident != self._thread:
self.wakeup()
else:
self.shutdown_tasks(self._s... | Python | nomic_cornstack_python_v1 |
string 5 5 50 50 70 80 100 7 100 95 90 80 70 60 50 3 70 90 80 3 70 90 81 9 100 99 98 97 96 95 94 93 91
set tc = integer input
for i in range 1 tc + 1
begin
set scores = list map int split input
set N = pop scores 0
set avg = sum scores / N
set over_avg = 0
for j in scores
begin
if j > avg
begin
set over_avg = over_avg ... | '''
5
5 50 50 70 80 100
7 100 95 90 80 70 60 50
3 70 90 80
3 70 90 81
9 100 99 98 97 96 95 94 93 91
'''
tc = int(input())
for i in range(1,tc+1):
scores = list(map(int,input().split()))
N = scores.pop(0)
avg = sum(scores)/N
over_avg = 0
for j in scores:
if j >avg:
over_avg +=1
... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode.cn id=160 lang=python3
comment [160] 相交链表
class ListNode
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
comment @lc code=start
comment Definition for singly-linked list.
comment class ListNode:
comment def __init__(self, x):
comment self.val = x
comment ... | #
# @lc app=leetcode.cn id=160 lang=python3
#
# [160] 相交链表
#
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
... | Python | zaydzuhri_stack_edu_python |
from file_storage import FileStorage
class StorageFactory extends object
begin
function factory type conf
begin
string Creates an instance of AbstractStorage class :raises: RuntimeError
if type == string file
begin
return call FileStorage conf
end
raise call RuntimeError string Unable to instantiate storage with type %... | from file_storage import FileStorage
class StorageFactory(object):
def factory(type, conf):
"""Creates an instance of AbstractStorage class
:raises: RuntimeError
"""
if type == 'file':
return FileStorage(conf)
raise RuntimeError('Unable to instantiate storage ... | Python | zaydzuhri_stack_edu_python |
function api_node_groups_schema request
begin
set ng = dict
return ng
end function | def api_node_groups_schema(request):
ng = {
}
return ng | Python | nomic_cornstack_python_v1 |
function cancel self user_id
begin
call trace string Canceling the review of user { user_id } .
call cancel user_id
end function | def cancel(self, user_id: int) -> None:
log.trace(f"Canceling the review of user {user_id}.")
self._review_scheduler.cancel(user_id) | Python | nomic_cornstack_python_v1 |
function Fu self xs u
begin
set v = u at 0
set phi_dot = u at 1
set delta_dot = u at 2
set sigma = xs at 3
set psi = xs at 4
set phi = xs at 5
set t = dt
set V_result = zeros tuple length xs length u
set V00 = t * cos psi
set V10 = t * sin psi
set V32 = t / w * sigma ^ 2.0 * w ^ 2.0 + 1.0
set V40 = t * sigma / cos phi
... | def Fu(self, xs, u):
v = u[0]
phi_dot = u[1]
delta_dot = u[2]
sigma = xs[3]
psi = xs[4]
phi = xs[5]
t = self.dt
V_result = np.zeros((len(xs), len(u)))
V00 = t * np.cos(psi)
V10 = t * np.sin(psi)
V32 = (t / self.w) * ((sigma ** 2.... | Python | nomic_cornstack_python_v1 |
function bytes2human n
begin
set symbols = tuple string K string M string G string T string P string E string Z string Y
set prefix = dict
for tuple i s in enumerate symbols
begin
set prefix at s = 1 ? i + 1 * 10
end
for s in reversed symbols
begin
if n >= prefix at s
begin
set value = decimal n / prefix at s
comment ... | def bytes2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
#return '%.2f %s' % (value, s)
... | Python | nomic_cornstack_python_v1 |
function get_patches img psd seg box psdid
begin
set img_p = img at index box / 255.0
set psd_p = as type psd at index box == psdid string float32
set seg_p = seg at index box
comment transposing to fit net's conventions
set img_p = transpose img_p tuple 2 1 0
set psd_p = transpose psd_p tuple 2 1 0
set seg_p = transpo... | def get_patches(img, psd, seg, box, psdid):
img_p = img[box.index()] / 255.0
psd_p = (psd[box.index()] == psdid).astype("float32")
seg_p = seg[box.index()]
# transposing to fit net's conventions
img_p = img_p.transpose((2, 1, 0))
psd_p = psd_p.transpose((2, 1, 0))
seg_p = seg_p.transpose((... | Python | nomic_cornstack_python_v1 |
string the python challenge #8
import pcutils
import bz2
function get_auth
begin
comment this is icky but ran into problems with \\s
set page_bytes = call get_bytes_from_page string def/ string integrity start=string <!-- end=string -->
set un_pw = split page_bytes bNEWLINE
set un_bytes = encode decode un_pw at 0 at sl... | '''
the python challenge #8
'''
import pcutils
import bz2
def get_auth():
# this is icky but ran into problems with \\s
page_bytes = pcutils.get_bytes_from_page('def/', 'integrity',
start='<!--', end='-->', )
un_pw = page_bytes.split(pcutils.bNEWLINE)
... | Python | zaydzuhri_stack_edu_python |
function add self item
begin
set current = head
set previous = none
set stop = false
while current is not none and not stop
begin
if get_data > item
begin
comment position found
set stop = true
end
else
begin
set previous = current
set current = call get_next
end
end
set temp = call Node item
if previous is none
begin
... | def add(self, item):
current = self.head
previous = None
stop = False
while current is not None and not stop:
if current.get_data > item:
stop = True # position found
else:
previous = current
current = current.get_... | Python | nomic_cornstack_python_v1 |
function resample_and_also_resample_operating_regime self resample_args=tuple string 10T resample_kwargs=none operating_regime_file_path=none additional_outlier_mask
begin
decorator call load_exist_pkl_file_otherwise_run_and_save default_results_saving_path at string resample_and_also_resample_operating_regime
function... | def resample_and_also_resample_operating_regime(self,
resample_args: tuple = ('10T',),
resample_kwargs: dict = None, *,
operating_regime_file_path: Path = None,
... | Python | nomic_cornstack_python_v1 |
function dumpjson object **kwds
begin
set file = call BytesIO
dump object file cls=JSONEncoder
seek file 0
return file
end function | def dumpjson(object, **kwds):
file = BytesIO()
json.dump(object, file, cls=JSONEncoder)
file.seek(0)
return file | Python | nomic_cornstack_python_v1 |
function HallSymbol self
begin
return _Hall
end function | def HallSymbol(self):
return self._Hall | Python | nomic_cornstack_python_v1 |
function test_create_subnetpool self
begin
with call override_role self
begin
call _create_subnetpool
end
end function | def test_create_subnetpool(self):
with self.rbac_utils.override_role(self):
self._create_subnetpool() | Python | nomic_cornstack_python_v1 |
import eli5
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import make_classification
comment Creating a dataset for classification
set tuple X y = call make_classification
comment Fitting the MLPClassifier model
set model = call MLPClassifier
fit model X y
comment Displaying model weights
print... | import eli5
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import make_classification
# Creating a dataset for classification
X, y = make_classification()
# Fitting the MLPClassifier model
model = MLPClassifier()
model.fit(X, y)
# Displaying model weights
print(eli5.show_weights(model))
# Le... | Python | flytech_python_25k |
string Mapping properties from PDB structures to Uniprot proteins using SIFTS data.
import os.path
from lxml import etree
import urllib
import prody
from collections import defaultdict
from itertools import izip
class NoSIFTSMappingException extends Exception
begin
pass
end class
set SIFTS_URL = string ftp://ftp.ebi.ac... | '''
Mapping properties from PDB structures to Uniprot proteins using SIFTS data.
'''
import os.path
from lxml import etree
import urllib
import prody
from collections import defaultdict
from itertools import izip
class NoSIFTSMappingException(Exception):
pass
SIFTS_URL = "ftp://ftp.ebi.ac.uk/pub/databases/msd/sif... | Python | zaydzuhri_stack_edu_python |
from collections import Counter
set N = integer input
set tuple *A = map int split input
set l = counter list comprehension i - A at i for i in range N
set r = counter list comprehension i + A at i for i in range N
set ans = 0
for tuple k v in items l
begin
set ans = ans + v * r at k
end
print ans | from collections import Counter
N = int(input())
*A, = map(int, input().split())
l = Counter([i-A[i] for i in range(N)])
r = Counter([i+A[i] for i in range(N)])
ans = 0
for k, v in l.items():
ans += v*r[k]
print(ans)
| Python | zaydzuhri_stack_edu_python |
function reconstruct_error self
begin
comment activation = self.dot()
set activation = call maximum 0 dot
set reconstruction = dot T activation
set error = sum call abs_ x - T
return tuple reconstruction error
end function | def reconstruct_error(self):
# activation = self.dot()
activation = t.maximum(0, self.dot())
reconstruction = t.dot(self.w.T, activation)
error = t.sum(t.abs_(self.x - reconstruction.T))
return reconstruction, error | Python | nomic_cornstack_python_v1 |
string Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A... | """
Given an array nums, return true if the array was originally sorted in non-decreasing order,
then rotated some number of positions (including zero). Otherwise, return false.
There may be duplicates in the original array.
Note: An array A rotated by x positions results in an array B of the same length such that A[i... | Python | zaydzuhri_stack_edu_python |
set tuple cod n_pecas v_uni = split input string
set tuple cod2 n_pecas2 v_uni2 = split input string
set cod = integer cod
set n_pecas = integer n_pecas
set v_uni = decimal v_uni
set cod2 = integer cod2
set n_pecas2 = integer n_pecas2
set v_uni2 = decimal v_uni2
set total = n_pecas * v_uni + n_pecas2 * v_uni2
print for... | cod,n_pecas,v_uni = input().split(" ")
cod2,n_pecas2,v_uni2 = input().split(" ")
cod = int(cod)
n_pecas = int(n_pecas)
v_uni = float(v_uni)
cod2 = int(cod2)
n_pecas2 = int(n_pecas2)
v_uni2 = float(v_uni2)
total = (n_pecas * v_uni) + (n_pecas2 * v_uni2)
print("VALOR A PAGAR: R$ {:.2f}".format(total))
| Python | zaydzuhri_stack_edu_python |
function get_biom_format_url_string
begin
return __url__
end function | def get_biom_format_url_string():
return __url__ | Python | nomic_cornstack_python_v1 |
comment s = "abcd"
comment p = "dddabce"
set star = list string *
set star = star at 0
set point = list string .
set point = point at 0
set s = string abcd
set p = string ddabcddd
set lists = list s
set listp = list p
set lst = list
for i in range length s
begin
for j in range length p
begin
if point not in listp and ... | # s = "abcd"
# p = "dddabce"
star = ["*"]
star = star[0]
point =['.']
point = point[0]
s = "abcd"
p = "ddabcddd"
lists = list(s)
listp = list(p)
lst = []
for i in range(len(s)):
for j in range(len(p)):
if point not in listp and star not in listp:
if len(p) < len(s):
print(False)... | Python | zaydzuhri_stack_edu_python |
function EQ classical_reg1 classical_reg2 classical_reg3
begin
string Produce an EQ instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalEqual instance.
set tuple c... | def EQ(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an EQ instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalEqual instan... | Python | jtatman_500k |
function random_points self n minmass=none maxmass=none minage=none maxage=none minfeh=none maxfeh=none
begin
if minmass is none
begin
set minmass = minmass
end
if maxmass is none
begin
set maxmass = maxmass
end
if minage is none
begin
set minage = minage
end
if maxage is none
begin
set maxage = maxage
end
if minfeh is... | def random_points(self,n,minmass=None,maxmass=None,
minage=None,maxage=None,
minfeh=None,maxfeh=None):
if minmass is None:
minmass = self.minmass
if maxmass is None:
maxmass = self.maxmass
if minage is None:
minage =... | Python | nomic_cornstack_python_v1 |
import os
set files_table = dict string 128B power 2 7 ; string 256B power 2 8 ; string 512B power 2 9 ; string 1KB power 2 10 ; string 10KB power 2 10 * 10 ; string 100KB power 2 10 * 100 ; string 500KB power 2 10 * 500 ; string 1MB power 2 20 ; string 1GB power 2 30
function generate_files
begin
if not exists path st... | import os
files_table = {
"128B": pow(2, 7),
"256B": pow(2, 8),
"512B": pow(2, 9),
"1KB": pow(2, 10),
"10KB": pow(2, 10) * 10,
"100KB": pow(2, 10) * 100,
"500KB": pow(2, 10) * 500,
"1MB": pow(2, 20),
"1GB": pow(2, 30)
}
def generate_files():
if not os.path.exists("resources"... | Python | zaydzuhri_stack_edu_python |
function transaction callback **ctx_options
begin
set fut = call transaction_async callback keyword ctx_options
return call get_result
end function | def transaction(callback, **ctx_options):
fut = transaction_async(callback, **ctx_options)
return fut.get_result() | Python | nomic_cornstack_python_v1 |
import glob
import os
function CreateUsersFilmsDictionary
begin
comment parameters:
set i = 0
set j = 0
set curr_path = directory name path absolute path path __file__
set path = curr_path + string \training_set\training_set\*.txt
set UserFilmDictionary = dictionary
comment create a lint of all files
set files = glob g... | import glob
import os
def CreateUsersFilmsDictionary():
# parameters:
i =0
j=0
curr_path = os.path.dirname(os.path.abspath(__file__))
path = curr_path + r'\training_set\training_set\*.txt'
UserFilmDictionary = dict()
#create a lint of all files
files = glob.glob(path)
# iterate o... | Python | zaydzuhri_stack_edu_python |
function get_db
begin
if not exists path config at string SCRAPER_DB
begin
call init_db
end
return call connect_db
end function | def get_db():
if not path.exists(config['SCRAPER_DB']):
init_db()
return connect_db() | Python | nomic_cornstack_python_v1 |
function inBoard self row col
begin
return 0 <= row < rows and 0 <= col < cols
end function | def inBoard(self, row, col):
return 0 <= row < self.rows and 0 <= col < self.cols | Python | nomic_cornstack_python_v1 |
string Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out.
set text = string X-DSPAM-Confidence: 0.8475
set pos = find text string 0.8475
print pos + 1
set constr = decimal text at slic... | '''Write code using find() and string slicing (see section 6.10) to extract the number
at the end of the line below.
Convert the extracted value to a floating point number and print it out.'''
text = "X-DSPAM-Confidence: 0.8475"
pos=text.find('0.8475')
print(pos+1)
constr=float(text[pos + 1:])
print(constr) | Python | zaydzuhri_stack_edu_python |
function correct_scanpy adatas **kwargs
begin
string Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of parameters to use for batch correction. ... | def correct_scanpy(adatas, **kwargs):
"""Batch correct a list of `scanpy.api.AnnData`.
Parameters
----------
adatas : `list` of `scanpy.api.AnnData`
Data sets to integrate and/or correct.
kwargs : `dict`
See documentation for the `correct()` method for a full list of
paramet... | Python | jtatman_500k |
string The template of the main script of the machine learning process
import arkanoid.communication as comm
from arkanoid.communication import SceneInfo , GameInstruction
import pickle
import numpy as np
function ml_loop
begin
string The main loop of the machine learning process This loop is run in a seperate process,... | """The template of the main script of the machine learning process
"""
import arkanoid.communication as comm
from arkanoid.communication import SceneInfo, GameInstruction
import pickle
import numpy as np
def ml_loop():
"""The main loop of the machine learning process
This loop is run in a seperate proce... | Python | zaydzuhri_stack_edu_python |
function add_sharing event
begin
set shares = get attribute context SHARING_ATTR dict
for user_id in get shares string admin list
begin
append acl tuple Allow user_id tuple string view string edit
end
for user_id in get shares string editors list
begin
append acl tuple Allow user_id tuple string view string edit
end
fo... | def add_sharing(event):
shares = getattr(event.context, SHARING_ATTR, {})
for user_id in shares.get('admin', []):
event.acl.append((Allow, user_id, ('view', 'edit')))
for user_id in shares.get('editors', []):
event.acl.append((Allow, user_id, ('view', 'edit')))
fo... | Python | nomic_cornstack_python_v1 |
function inverte_lista l
begin
set l = l at slice : : - 1
return l
end function | def inverte_lista(l):
l = l[::-1]
return l | Python | zaydzuhri_stack_edu_python |
import sys
function main
begin
set inp = call splitlines
set prompt = inp at 0
set tuple new students slots capacity = generator expression integer x for x in split inp at 0
set stored = list comprehension integer x for x in split inp at 1
set toadd = list comprehension 0 for i in range slots
for slot in sorted range s... | import sys
def main():
inp = sys.stdin.read().splitlines()
prompt = inp[0]
new,students,slots,capacity = (int(x) for x in inp[0].split())
stored = [int(x) for x in inp[1].split()]
toadd = [0 for i in range(slots)]
for slot in sorted(range(slots), key = lambda x: stored[x]):
add = min(ne... | Python | zaydzuhri_stack_edu_python |
function plotFocalPlane camera fieldSizeDeg_x=0 fieldSizeDeg_y=none dx=0.1 dy=0.1 figsize=tuple 10.0 10.0 useIds=false showFig=true savePath=none
begin
try
begin
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
end
except ImportError
begin
raise c... | def plotFocalPlane(camera, fieldSizeDeg_x=0, fieldSizeDeg_y=None, dx=0.1, dy=0.1, figsize=(10., 10.),
useIds=False, showFig=True, savePath=None):
try:
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
... | Python | nomic_cornstack_python_v1 |
function find_all_index arr item
begin
return list comprehension i for tuple i a in enumerate arr if a == item
end function
set list = list string 138 string 123 string 123123 string 123 string 123 string 123
set set_l = set list
for i in set_l
begin
set a = call find_all_index list i
print i + string 有 + string length... | def find_all_index(arr,item):
return [i for i,a in enumerate(arr) if a==item]
list=['138','123','123123','123','123','123']
set_l=set(list)
for i in set_l:
a=find_all_index(list,i)
print(i+"有"+str(len(a))+"个")
| Python | zaydzuhri_stack_edu_python |
function series_iter self
begin
for s in iterate call tag string Image
begin
yield call Series s
end
end function | def series_iter(self):
for s in self.tree.iter(tag("Image")):
yield Series(s) | Python | nomic_cornstack_python_v1 |
function upgrade_example_device_model1234_firmware self node ports
begin
comment Any commands needed to perform the firmware upgrade should go here.
comment If you plan on actually flashing firmware every cleaning cycle, you
comment should ensure your device will not experience flash exhaustion. A
comment good practice... | def upgrade_example_device_model1234_firmware(self, node, ports):
# Any commands needed to perform the firmware upgrade should go here.
# If you plan on actually flashing firmware every cleaning cycle, you
# should ensure your device will not experience flash exhaustion. A
# good practic... | Python | nomic_cornstack_python_v1 |
function export_gif model ticks params=none scale=1.0 fade=0.0 name=none setup=string Setup go=string go duration=none fps=10 subrectangles=false
begin
set frames = call find_frames ticks
call export_frames model frames params setup go
set file_name = call make_name model name ending=string .gif
if scale != 1.0
begin
c... | def export_gif(model, ticks, params=None, scale=1.0, fade=0.0, name=None, setup='Setup', go='go', duration=None, fps=10, subrectangles=False):
frames = find_frames(ticks)
export_frames(model, frames, params, setup, go)
file_name = make_name(model, name, ending='.gif')
if scale !=... | Python | nomic_cornstack_python_v1 |
function wipe_models_and_permissions app_config name
begin
set tuple Permission Group = call get_permission_models
set app_label = name
set content_type = first filter app_label=app_label model=name
delete
delete
delete
end function | def wipe_models_and_permissions(app_config, name):
Permission, Group = get_permission_models()
app_label = app_config.name
content_type = ContentType.objects.filter(
app_label=app_label,
model=name,
).first()
Group.objects.filter(
name=name
).delete()
Permission.obj... | Python | nomic_cornstack_python_v1 |
import scrollphathd
from scrollphathd.fonts import font5x5
from picamera import PiCamera
from os import system
import time
set DISPLAY_BAR = false
set BRIGHTNESS = 0.3
function showSecondsOnScrollPhatHD seconds
begin
clear scrollphathd
set float_sec = seconds % 60 / 59.0
set seconds_progress = float_sec * 15
if DISPLAY... | import scrollphathd
from scrollphathd.fonts import font5x5
from picamera import PiCamera
from os import system
import time
DISPLAY_BAR = False
BRIGHTNESS = 0.3
def showSecondsOnScrollPhatHD(seconds):
scrollphathd.clear()
float_sec = (seconds % 60) / 59.0
seconds_progress = float_sec * 15
if DISPLAY_B... | Python | zaydzuhri_stack_edu_python |
function test_rackspace_uploader_lookup_url_none self mock1
begin
set filename = string test.jpg
with patch string pybossa.uploader.rackspace.pyrax.cloudfiles as mycf
begin
set cdn_enabled_mock = call PropertyMock return_value=false
set cdn_enabled = cdn_enabled_mock
set return_value = fake_container
set u = call Racks... | def test_rackspace_uploader_lookup_url_none(self, mock1):
filename = 'test.jpg'
with patch('pybossa.uploader.rackspace.pyrax.cloudfiles') as mycf:
cdn_enabled_mock = PropertyMock(return_value=False)
type(fake_container).cdn_enabled = cdn_enabled_mock
mycf.get_con... | Python | nomic_cornstack_python_v1 |
import math , random
from array import array
function merge left right
begin
comment tableau vide qui reoit les rsultats
set tableau = array string i list
while length left > 0 and length right > 0
begin
if left at 0 < right at 0
begin
append tableau pop left 0
end
else
begin
append tableau pop right 0
end
end
set tabl... | import math, random
from array import array
def merge(left, right):
tableau = array('i', []) # tableau vide qui reoit les rsultats
while len(left) > 0 and len(right) > 0:
if left[0] < right[0]: tableau.append(left.pop(0))
else: tableau.append(right.pop(0))
tableau += left + right
retu... | Python | zaydzuhri_stack_edu_python |
import random
import pdb
function initvertices nver degrange
begin
set vertices = list
for i in range nver
begin
append vertices call randrange degrange
end
return vertices
end function
function gettotdegree vertices
begin
set totdegree = 0
for deg in vertices
begin
set totdegree = totdegree + deg
end
return totdegree... | import random
import pdb
def initvertices(nver, degrange):
vertices = []
for i in range(nver):
vertices.append(random.randrange(degrange))
return vertices
def gettotdegree(vertices):
totdegree = 0
for deg in vertices:
totdegree += deg
return totdegree
def choosenode(vertices,... | Python | zaydzuhri_stack_edu_python |
function delete self data wholeNode=false
begin
set tuple parent current = call _lookup data
comment data was found
if current
begin
if expression wholeNode then call clearData else delete data
comment we have deleted the last element from current node!
if not current
begin
comment 2 children
if left and right
begin
se... | def delete(self, data, wholeNode=False):
parent, current = self._lookup(data)
if current: # data was found
current.clearData() if wholeNode else current.delete(data)
if not current: # we have deleted the last element from current node!
if current.left and curren... | Python | nomic_cornstack_python_v1 |
function construct_fence price_str
begin
set price = integer join string split price_str at slice 1 : : string ,
return string H * 1000000 // price
end function | def construct_fence(price_str):
price = int(''.join(price_str[1:].split(',')))
return 'H' * (1000000 // price)
| Python | zaydzuhri_stack_edu_python |
import math
function is_prime n
begin
if n % 2 == 0 and n > 2
begin
return false
end
for i in range 3 integer square root n + 1 2
begin
if n % i == 0
begin
return false
end
end
return true
end function
function is_factor n div
begin
return n % div == 0
end function
function largest_prime_factor n
begin
if call is_prime... | import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def is_factor(n, div):
return n % div == 0
def largest_prime_factor(n):
if is_prime(n):
return n
highe... | Python | zaydzuhri_stack_edu_python |
function _pi_solve self gym
begin
comment Precompute optimal q(s,a).
set copy = copy info
set copy at string Q = Q
set copy = iloc at values
set copy at string S' = apply copy at string S' lambda arr -> arr at 0
comment Initialize policy from initial state.
set policy = list start
comment Iterately append.
while true
b... | def _pi_solve(self, gym):
## Precompute optimal q(s,a).
copy = gym.info.copy()
copy['Q'] = self.Q
copy = copy.iloc[copy.groupby('S').Q.idxmax().values]
copy["S'"] = copy["S'"].apply(lambda arr: arr[0])
## Initialize policy from initial state.
pol... | Python | nomic_cornstack_python_v1 |
function core_hamiltonian basis labels coords
begin
set t = call kinetic basis=basis labels=labels coords=coords
set v = call nuclear basis=basis labels=labels coords=coords
return call ascontiguousarray t + v
end function | def core_hamiltonian(basis, labels, coords):
t = kinetic(basis=basis, labels=labels, coords=coords)
v = nuclear(basis=basis, labels=labels, coords=coords)
return numpy.ascontiguousarray(t + v) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.