code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Task_3
from os import path , walk , listdir
import shutil
set new_project = string my_project_1
try
begin
for tuple root dirs files in walk new_project
begin
if string templates in dirs and root != new_project
begin
for entry in list directory join path root string templates
begin
copy tree join path root strin... | # Task_3
from os import path, walk, listdir
import shutil
new_project = 'my_project_1'
try:
for root, dirs, files in walk(new_project):
if 'templates' in dirs and root != new_project:
for entry in listdir(path.join(root, 'templates')):
shutil.copytree(path.join(root, 'template... | Python | zaydzuhri_stack_edu_python |
function save_clips clips
begin
with open DATA_FILE string wb as f
begin
write f call packb clips encoding=string utf-8
end
end function | def save_clips(clips):
with open(DATA_FILE, 'wb') as f:
f.write(msgpack.packb(clips, encoding='utf-8')) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment Given a list of addon ids, return a verdict of bad or not for each id.
comment Usage: sentiment_analysis.py
import csv
import json
import sys
import oauth2 as oauth
from alchemyapi import AlchemyAPI
import urllib2
import time
class BrowserWars
begin
string A class to fetch sentiment sco... | #!/usr/bin/python
# Given a list of addon ids, return a verdict of bad or not for each id.
# Usage: sentiment_analysis.py
import csv
import json
import sys
import oauth2 as oauth
from alchemyapi import AlchemyAPI
import urllib2
import time
class BrowserWars:
"""A class to fetch sentiment scores for different keywor... | Python | zaydzuhri_stack_edu_python |
function depthFirstSearch problem
begin
string *** YOUR CODE HERE ***
comment visited nodes closed set
set closed = set
comment stack to keep the problem nodes in
set fringe = stack
comment current state
set currentState = call getStartState
set node = call Node currentState
comment starts the graph search
call push no... | def depthFirstSearch(problem):
"*** YOUR CODE HERE ***"
closed = set() #visited nodes closed set
fringe = util.Stack() #stack to keep the problem nodes in
currentState = problem.getStartState() #current state
node = util.Node(currentState)
fringe.push(node) #starts the graph search
while fri... | Python | nomic_cornstack_python_v1 |
comment @Time : 2020/2/25 17:59
comment @Author : Xylia_Yang
comment @Description :
class TreeNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end function
end class
class Solution
begin
function isSymmetric self root
begin
return call Symmetric root root
end function
function Symm... | # @Time : 2020/2/25 17:59
# @Author : Xylia_Yang
# @Description :
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.Symmetric(root,root)
def Symmetric(self,roo1,r... | Python | zaydzuhri_stack_edu_python |
function set_sensor self number value
begin
set _sensors at number - 1 = value
end function | def set_sensor(self, number, value):
self._sensors[number - 1] = value | Python | nomic_cornstack_python_v1 |
function enable_aml_strict_match self enabled=false
begin
set config at string aml_strict_match = enabled is true
end function | def enable_aml_strict_match(self, enabled=False):
self.config["aml_strict_match"] = enabled is True | Python | nomic_cornstack_python_v1 |
function load_workflow resource workflow_name
begin
try
begin
set playbook_file = open resource string r
end
except tuple IOError OSError as e
begin
error format string Could not load workflow from {0}. Reason: {1} resource call format_exception_message e
return none
end
try else
begin
with playbook_file
begin
set work... | def load_workflow(resource, workflow_name):
try:
playbook_file = open(resource, 'r')
except (IOError, OSError) as e:
logger.error('Could not load workflow from {0}. Reason: {1}'.format(resource, format_exception_message(e)))
return None
else:
with ... | Python | nomic_cornstack_python_v1 |
import cv2
global img
global point1 point2
function on_mouse event x y flags param
begin
global img point1 point2
set img2 = copy img
comment 左键点击
if event == EVENT_LBUTTONDOWN
begin
set point1 = tuple x y
call circle img2 point1 10 tuple 0 255 0 5
image show string image img2
end
else
comment 按住左键拖曳
if event == EVENT_... | import cv2
global img
global point1, point2
def on_mouse(event, x, y, flags, param):
global img, point1, point2
img2 = img.copy()
if event == cv2.EVENT_LBUTTONDOWN: #左键点击
point1 = (x,y)
cv2.circle(img2, point1, 10, (0,255,0), 5)
cv2.imshow('image', img2)
elif event == ... | Python | zaydzuhri_stack_edu_python |
function qualify_key_s3 self key=string bucket=none
begin
set count = 0
set prefix = key
if bucket is none
begin
set bucket = AWS_S3_BUCKET
end
set paginator = call get_paginator string list_objects_v2
set response_iterator = paginate paginator Bucket=bucket Prefix=prefix Delimiter=string
for page in response_iterator... | def qualify_key_s3(self, key='', bucket=None):
count = 0
prefix = key
if bucket is None:
bucket = self.AWS_S3_BUCKET
paginator = self.get_s3_client().get_paginator('list_objects_v2')
response_iterator = paginator.paginate( Bucket=bucket, Prefix=pref... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string :platform: Unix :synopsis: Class to allow switching output messages on and off.
import os
import sys
class OutputControl
begin
function __init__ self
begin
set null = open string /dev/null string w
set null_fh = call fileno
set stdout_fh = call fileno
set stdout_copy_fh = call dup s... | # -*- coding: utf-8 -*-
"""
:platform: Unix
:synopsis: Class to allow switching output messages on and off.
"""
import os
import sys
class OutputControl:
def __init__(self):
self.null = open("/dev/null", "w")
self.null_fh = self.null.fileno()
self.stdout_fh = sys.stdout.fileno(... | Python | zaydzuhri_stack_edu_python |
function nim_game n k
begin
return n % k + 1 != 0
end function
if __name__ == string __main__
begin
set n = 5
set k = 3
print string Winning the game { call nim_game n k }
end | def nim_game(n, k):
return n % (k+1) != 0
if __name__ == "__main__":
n = 5
k = 3
print(f"Winning the game {nim_game(n, k)}")
| Python | zaydzuhri_stack_edu_python |
from races.models import Race , STATE_CHOICES
comment all races must have a last_race, and all last_races must have a winner
comment TODO what about two races w/o a greenest candidate? it should work if they have a winner.
function calculate_meter_info races
begin
set total_races = 0
set decided_races = 0
set green_rac... | from races.models import Race, STATE_CHOICES
# all races must have a last_race, and all last_races must have a winner
# TODO what about two races w/o a greenest candidate? it should work if they have a winner.
def calculate_meter_info(races):
total_races = 0
decided_races = 0
green_races = 0
previous_... | Python | zaydzuhri_stack_edu_python |
function fall self nodesList
begin
set land = call Rect 283 461 635 213
set leftCroc = call Rect 300 373 105 20
set leftStand = call Rect 485 300 76 10
set rightStand = call Rect 639 300 76 10
set rightBirb = call Rect 795 373 105 20
set extra = call Rect 0 0 0 0
set platformsList = list land leftCroc rightBirb leftSta... | def fall(self, nodesList):
land = pygame.Rect(283, 461, 635, 213)
leftCroc = pygame.Rect(300, 373, 105, 20)
leftStand = pygame.Rect(485, 300, 76, 10)
rightStand = pygame.Rect(639, 300, 76, 10)
rightBirb = pygame.Rect(795, 373, 105, 20)
extra = pygame.Rect(0, 0, 0, 0)
... | Python | nomic_cornstack_python_v1 |
function evaluate self expression unit=none dataset=none inner=none outer=none
begin
comment Validate input arguments.
if dataset is not none
begin
if is instance dataset str
begin
set dataset = self / string datasets / dataset
end
if not is instance dataset Node
begin
set error = string Dataset must be a dataset name ... | def evaluate(self, expression, unit=None, dataset=None,
inner=None, outer=None):
# Validate input arguments.
if dataset is not None:
if isinstance(dataset, str):
dataset = self/'datasets'/dataset
if not isinstance(dataset, Node):
... | Python | nomic_cornstack_python_v1 |
from tree import TreeNode
function helper root1 root2
begin
if not root1 or not root2
begin
return root1 == root2
end
return value == value and call helper left right and call helper right left
end function
function is_symmetric root
begin
return call helper root root
end function
if __name__ == string __main__
begin
s... | from tree import TreeNode
def helper(root1, root2):
if not root1 or not root2:
return root1 == root2
return (root1.value == root2.value) and helper(root1.left, root2.right) and helper(root1.right, root2.left)
def is_symmetric(root):
return helper(root, root)
if __name__ == '__main__':
root... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
set array = list
while true
begin
set number = call raw_input string input number
if number == string n
begin
break
end
else
begin
append array integer number
end
end
sort array | #!/usr/bin/python
array = []
while True:
number = raw_input("input number")
if number == 'n':
break
else:
array.append(int(number))
array.sort() | Python | zaydzuhri_stack_edu_python |
comment coding = utf-8
comment author: neil shi
comment 此代码仅供学习与交流,请勿用于商业用途。
comment 爬取小区数据的爬虫派生类
import re
from bs4 import BeautifulSoup
from model.community import *
from spider.base_spider import *
from geo.area import *
from utility.log import *
class CommunityBaseSpider extends BaseSpider
begin
function collect_ar... | # coding = utf-8
# author: neil shi
# 此代码仅供学习与交流,请勿用于商业用途。
# 爬取小区数据的爬虫派生类
import re
from bs4 import BeautifulSoup
from model.community import *
from spider.base_spider import *
from geo.area import *
from utility.log import *
class CommunityBaseSpider(BaseSpider):
def collect_area_community_data(self, city_name,... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python
comment Jason Landsborough
comment Last updated: 8/5/2013
comment Example of how to traverse directories and files recursively
comment Usage: python recursive_traversal.py
comment needed for os.walk()
import os
comment set to some other directory that has subfolders and files
set target_dir = ... | #! /usr/bin/python
## Jason Landsborough
## Last updated: 8/5/2013
##
## Example of how to traverse directories and files recursively
##
## Usage: python recursive_traversal.py
##
##
import os #needed for os.walk()
target_dir = os.getcwd() #set to some other directory that has subfolders and files
#go through di... | Python | zaydzuhri_stack_edu_python |
function _break_loop self
begin
set current_loop = current_loop
comment Search for the end of the loop if necessary
if end_addr is none
begin
set _program_counter = program_counter_next
while _program_counter < spec_len
begin
set cmd = spec_strm at _program_counter
set opcode = cmd ? 20 ? 255
set open_loops = 1
if opco... | def _break_loop(self):
current_loop = self.loop_stack.current_loop
# Search for the end of the loop if necessary
if current_loop.end_addr is None:
_program_counter = self.program_counter_next
while _program_counter < self.spec_len:
cmd = self.spec_strm[_... | Python | nomic_cornstack_python_v1 |
comment encoding: utf-8
string @ author: wangmingrui @ time: 2021/3/11 14:38 @ desc: 生成并使用进程
import multiprocessing
function foo i
begin
print string called function foo in process: %s % i
return
end function
if __name__ == string __main__
begin
set process_jobs = list
for i in range 5
begin
set p = process target=foo... | # encoding: utf-8
"""
@ author: wangmingrui
@ time: 2021/3/11 14:38
@ desc: 生成并使用进程
"""
import multiprocessing
def foo(i):
print("called function foo in process: %s" % i)
return
if __name__ == '__main__':
process_jobs = []
for i in range(5):
p = multiprocessing.Process(target=foo, args=(i,)... | Python | zaydzuhri_stack_edu_python |
function stop_immediate self
begin
call CC_StopImmediate serial
end function | def stop_immediate(self):
self.KCube.CC_StopImmediate(self.serial) | Python | nomic_cornstack_python_v1 |
from Value import Value
class BoxValue extends Value
begin
string 1,全部 2,上下・左右 3,上・左右・下 4,上・右・下・左
function __init__ self *args
begin
set l = length args
if l < 1 or l > 4
begin
raise exception string value over
end
set args = args
end function
function _get_str self
begin
return join string list comprehension string x... | from .Value import Value
class BoxValue(Value):
"""1,全部 2,上下・左右 3,上・左右・下 4,上・右・下・左"""
def __init__(self, *args:int):
l = len(args)
if l < 1 or l > 4:
raise Exception('value over')
self.args = args
def _get_str(self):
return ' '.join([str(x) + 'px' for x in self.... | Python | zaydzuhri_stack_edu_python |
set nome = string input string Digite seu nome:
set idade = integer input string Digite a sua idade:
set email = string input string Digite o seu e-mail:
set dados = dict string nome nome ; string idade idade ; string e-mail email
print dados | nome = str(input('Digite seu nome: '))
idade = int(input('Digite a sua idade: '))
email = str(input('Digite o seu e-mail: '))
dados = {'nome':nome, 'idade':idade, 'e-mail':email}
print(dados) | Python | zaydzuhri_stack_edu_python |
import requests
set r = get requests string https://financialmodelingprep.com/developer/docs/
print text
print status_code
string url="www.something.com" data={ "p1":3, "a2":4 } r2=requests.post(url=url,data=data) print(r2.text) | import requests
r=requests.get("https://financialmodelingprep.com/developer/docs/")
print(r.text)
print(r.status_code)
'''
url="www.something.com"
data={
"p1":3,
"a2":4
}
r2=requests.post(url=url,data=data)
print(r2.text)
''' | Python | zaydzuhri_stack_edu_python |
import sys
set input = readline
function solve a b k
begin
set ans = 0
set ca = list 0 * a + 1
set cb = list 0 * b + 1
for i in range k
begin
set ca at aa at i = ca at aa at i + 1
set cb at bb at i = cb at bb at i + 1
end
for i in range k
begin
set ans = ans + k + 1 - ca at aa at i - cb at bb at i
end
return ans // 2
e... | import sys
input = sys.stdin.readline
def solve(a,b,k):
ans = 0
ca = [0]*(a+1)
cb = [0]*(b+1)
for i in range(k):
ca[aa[i]]+=1
cb[bb[i]]+=1
for i in range(k):
ans += k + 1 - ca[aa[i]] -cb[bb[i]]
return ans//2
t = int(input())
for i in range(t):
a,b,k = map(int,in... | Python | zaydzuhri_stack_edu_python |
import re
import filters
set expr = string (+ (. (~(<a,1)) (+ (=a,5) (=b,8))) (. (~(=c,9)) (<d,e)) (>t,4) ) | import re
import filters
expr = '(+ (. (~(<a,1)) (+ (=a,5) (=b,8))) (. (~(=c,9)) (<d,e)) (>t,4) )'
| Python | zaydzuhri_stack_edu_python |
import matlab.engine
import numpy as np
set eng = call connect_matlab
comment Examples
comment Executing function
set tf = call isprime 37
print tf
comment eng.run('CreateWeightFunc.m', nargout=0)
comment Access variable from workspace
comment ans = eng.workspace['ans']
comment weightFun = eng.workspace['weightFunc']
c... | import matlab.engine
import numpy as np
eng = matlab.engine.connect_matlab()
# Examples
# Executing function
tf = eng.isprime(37)
print(tf)
# eng.run('CreateWeightFunc.m', nargout=0)
# Access variable from workspace
# ans = eng.workspace['ans']
# weightFun = eng.workspace['weightFunc']
#Create variable in workspac... | Python | zaydzuhri_stack_edu_python |
function get_measure_variants self port measure_obj measure_type=none
begin
set meas_type = type measure_obj
if meas_type is delay_measure or meas_type is slew_measure
begin
set variant_tuple = call get_delay_measure_variants port measure_obj
end
else
if meas_type is power_measure
begin
set variant_tuple = call get_pow... | def get_measure_variants(self, port, measure_obj, measure_type=None):
meas_type = type(measure_obj)
if meas_type is delay_measure or meas_type is slew_measure:
variant_tuple = self.get_delay_measure_variants(port, measure_obj)
elif meas_type is power_measure:
variant_tup... | Python | nomic_cornstack_python_v1 |
function get_account self user_name
begin
set url = call get_account_page_link user_name
set header = call generate_header __user_session
set response = get __req url headers=header
if status_code == HTTP_NOT_FOUND
begin
raise call InstagramNotFoundError string Account with given username does not exist.
end
if status_... | def get_account(self, user_name):
url = endpoints.get_account_page_link(user_name)
header = self.generate_header(self.__user_session)
response = self.__req.get(url, headers=header)
if response.status_code == self.HTTP_NOT_FOUND:
raise exception.InstagramNotFoundError('Accoun... | Python | nomic_cornstack_python_v1 |
function _get_rounded_bounding_box geom width
begin
return tuple bounds at 0 - bounds at 0 % width bounds at 1 - bounds at 1 % width bounds at 2 + - bounds at 2 % width bounds at 3 + - bounds at 3 % width
end function | def _get_rounded_bounding_box(
geom: BasePolygon, width: Numeric
) -> Tuple[int, int, int, int]:
return (
geom.bounds[0] - (geom.bounds[0] % width),
geom.bounds[1] - (geom.bounds[1] % width),
geom.bounds[2] + (-geom.bounds[2] % width),
geom.bounds[3] +... | Python | nomic_cornstack_python_v1 |
string 7. Reversed Integer Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer o... | '''
7. Reversed Integer
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer ov... | Python | zaydzuhri_stack_edu_python |
import argparse
from data_loader.batch_creator import ImageChatDataset
from torch.utils.data import DataLoader
from evaluation import evaluate
from model import TransresnetMultimodalModel
import torch
from torch import optim
from torch.nn.functional import log_softmax , nll_loss
set use_cuda = call is_available
functio... | import argparse
from data_loader.batch_creator import ImageChatDataset
from torch.utils.data import DataLoader
from evaluation import evaluate
from model import TransresnetMultimodalModel
import torch
from torch import optim
from torch.nn.functional import log_softmax, nll_loss
use_cuda = torch.cuda.is_available()
... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from tkinter import messagebox
set root = call Tk
set f = call Frame root height=200 width=200
set board = list comprehension list comprehension 0 for x in range 3 for y in range 3
set turn = 1
function check_winner
begin
if board at 0 at 0 at string text == board at 1 at 1 at string text == board... | from tkinter import *
from tkinter import messagebox
root = Tk()
f = Frame(root, height=200, width=200)
board = [[0 for x in range(3)] for y in range(3)]
turn = 1
def check_winner():
if(board[0][0]["text"] == board[1][1]["text"] == board[2][2]["text"]):
if(board[1][1]["text"] == "X"):
m... | Python | zaydzuhri_stack_edu_python |
function PipePacketReceived self
begin
return _PipePacketReceived
end function | def PipePacketReceived(self):
return self._PipePacketReceived | Python | nomic_cornstack_python_v1 |
for i in range num
begin
append r integer input
end
sort r
set count = 1
for i in range num - 1
begin
if r at i < r at i + 1
begin
set count = count + 1
end
end
print count | for i in range(num):
r.append(int(input()))
r.sort()
count = 1
for i in range(num - 1):
if r[i] < r[i + 1]:
count = count + 1
print(count)
| Python | zaydzuhri_stack_edu_python |
function _tagged_src_tgt self src_example tgt_example
begin
set maybe_augmented = split src_example src_delimiter
set source_only = strip maybe_augmented at 0
set augmented_part = if expression length maybe_augmented > 1 then strip maybe_augmented at 1 else none
set tokenized_source_string = split source_only
set token... | def _tagged_src_tgt(self, src_example, tgt_example) -> tuple:
maybe_augmented = src_example.split(self.src_delimiter)
source_only = maybe_augmented[0].strip()
augmented_part = (
maybe_augmented[1].strip() if len(maybe_augmented) > 1 else None
)
tokenized_source_str... | Python | nomic_cornstack_python_v1 |
function find_max nums
begin
set max_num = nums at 0
for x in nums
begin
if x > max_num
begin
set max_num = x
end
end
return max_num
end function
print call find_max list 1 9 5 18 21 2 | def find_max(nums):
max_num = nums[0]
for x in nums:
if x > max_num:
max_num = x
return max_num
print(find_max([1,9,5,18,21,2]))
| Python | flytech_python_25k |
function safe_incr self number addition=1
begin
set summed = number + addition
return if expression summed < TWO_BYTES then summed else summed % TWO_BYTES
end function | def safe_incr(self, number: int, addition: int = 1) -> int:
summed = number + addition
return summed if summed < TWO_BYTES else summed % TWO_BYTES | Python | nomic_cornstack_python_v1 |
import gi
from CrearFactura import CrearFactura
from Inventario import Inventario
call require_version string Gtk string 3.0
from gi.repository import Gtk
class TiendaOlivica
begin
function __init__ self
begin
set builder = call Builder
call add_from_file string TiendaOlivica.glade
set ventana = call get_object string ... | import gi
from CrearFactura import CrearFactura
from Inventario import Inventario
gi.require_version('Gtk','3.0')
from gi.repository import Gtk
class TiendaOlivica():
def __init__(self):
builder = Gtk.Builder()
builder.add_from_file("TiendaOlivica.glade")
self.ventana = builder.get_object(... | Python | zaydzuhri_stack_edu_python |
function crypto_withdraw self amount currency crypto_address
begin
string Withdraw funds to a crypto address. Args: amount (Decimal): The amount to withdraw currency (str): The type of currency (eg. 'BTC') crypto_address (str): Crypto address to withdraw to. Returns: dict: Withdraw details. Example:: { "id":"593533d2-f... | def crypto_withdraw(self, amount, currency, crypto_address):
""" Withdraw funds to a crypto address.
Args:
amount (Decimal): The amount to withdraw
currency (str): The type of currency (eg. 'BTC')
crypto_address (str): Crypto address to withdraw to.
Returns:... | Python | jtatman_500k |
function reset self do_resets=none
begin
set _iteration = _iteration + 1
call reset do_resets
end function | def reset(self, do_resets=None):
self._iteration += 1
super().reset(do_resets) | Python | nomic_cornstack_python_v1 |
function initialize self tup
begin
call set_io_dims tup
end function | def initialize(self, tup):
self.set_io_dims(tup) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding:utf-8
import types
import math
import asyncio
from tqdm import tqdm
class Downloader extends object
begin
function __init__ self handlers=list batch=10
begin
set handlers = handlers
set batch = batch
end function
function set_handlers self handlers
begin
set handlers = handl... | #!/usr/bin/env python
# coding:utf-8
import types
import math
import asyncio
from tqdm import tqdm
class Downloader(object):
def __init__(self, handlers=[], batch=10):
self.handlers = handlers
self.batch = batch
def set_handlers(self, handlers):
self.handlers = handlers
def a... | Python | zaydzuhri_stack_edu_python |
from sympy import *
set x = call Symbol string x
set c = list
append c 3
append c 2
set expr = c at 0 * x ^ c at 1
print expr
print call integrate expr x | from sympy import *
x = Symbol('x')
c = []
c.append(3)
c.append(2)
expr = c[0]*(x**c[1])
print(expr)
print(integrate(expr,x))
| Python | zaydzuhri_stack_edu_python |
comment coding=utf8
comment Copyright 2018 JDCLOUD.COM
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 the License at
comment http://www.apache.org/licenses/LICENSE-2.0
comment Unless requir... | # coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | Python | jtatman_500k |
import numpy as np
import pandas as pd
import re
comment cart代码
class Cart
begin
function __init__ self
begin
comment to store predicted labels
set label_x = list
end function
function gini self x
begin
string :param x: input data :return: Gini index of data x
comment n represents the length of the dataset
set n = len... | import numpy as np
import pandas as pd
import re
#cart代码
class Cart():
def __init__(self):
self.label_x = [] #to store predicted labels
def gini(self,x):
'''
:param x: input data
:return: Gini index of data x
'''
n = len(x) #n repr... | Python | zaydzuhri_stack_edu_python |
function send_mail event context
begin
if string data not in event
begin
raise call RuntimeError string Unable to get 'data' in pub/sub message. Aborting…
end
set message = decode base64 decode event at string data string utf-8
try
begin
set message = loads message
end
except Exception as error
begin
error string Unabl... | def send_mail(event, context):
if "data" not in event:
raise RuntimeError("Unable to get 'data' in pub/sub message. Aborting…")
message = base64.b64decode(event["data"]).decode("utf-8")
try:
message = json.loads(message)
except Exception as error:
logging.error("Unable to decode... | Python | nomic_cornstack_python_v1 |
function isPrime number
begin
set prime = true
for i in range 2 integer number ^ 0.5
begin
if number % i == 0
begin
set prime = false
break
end
end
return prime
end function | def isPrime(number):
prime = True
for i in range(2, int(number ** (0.5))):
if number % i == 0:
prime = False
break
return prime | Python | nomic_cornstack_python_v1 |
import sys
function xgcd b n
begin
set tuple x0 x1 y0 y1 = tuple 1 0 0 1
while n != 0
begin
set tuple q b n = tuple b // n n b % n
set tuple x0 x1 = tuple x1 x0 - q * x1
set tuple y0 y1 = tuple y1 y0 - q * y1
end
return tuple b x0 y0
end function
if __name__ == string __main__
begin
set t = integer input
for _ in range... | import sys
def xgcd(b, n):
x0, x1, y0, y1 = 1, 0, 0, 1
while n != 0:
q, b, n = b // n, n, b % n
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return b, x0, y0
if __name__ == "__main__":
t = int(input())
for _ in range(t):
a, b, x = [int(x) for x in input().spli... | Python | zaydzuhri_stack_edu_python |
comment 파일 읽어오기
function Read_File path
begin
with open string ./source/ + path string r as file
begin
set tempLine = list map int split read line file
set pizzaCount = tempLine at 0
set Team = tempLine at slice 1 : :
set ingredient = list 0 * pizzaCount
set ingredientNum = list 0 * pizzaCount
for n in range pizzaCou... | # 파일 읽어오기
def Read_File(path):
with open("./source/" + path, 'r') as file:
tempLine = list(map(int, file.readline().split()))
pizzaCount = tempLine[0]
Team = tempLine[1:]
ingredient = [0] * pizzaCount
ingredientNum = [0] * pizzaCount
for n in range(pizzaCount):
... | Python | zaydzuhri_stack_edu_python |
import csv
import codecs
import logging
import datetime
function create session model args
begin
set instance = call create model args
return instance
end function
function count session model
begin
set count = count session model
return count
end function
function read session model instanceId
begin
set instance = get... | import csv
import codecs
import logging
import datetime
def create(session, model, args):
instance = session.create(model, args)
return instance
def count(session, model):
count = session.count(model)
return count
def read(session, model, instanceId):
instance = session.get(model, instanceId)
... | Python | zaydzuhri_stack_edu_python |
while not false
begin
if num < 0
begin
break
end
end
print string Number is + string num | while not False:
if num < 0:
break
print('Number is ' + str(num))
| Python | zaydzuhri_stack_edu_python |
function generate_mt_message cls generate_mt_request
begin
set xml_string = xml_string
set root_element = call fromstring xml_string
set reference = text
set related_reference = string TRANSFER
set bank_bic = text
set sarb_bic = text
set narrative = call _create_narrative root_element
set message = call _create_mt199 b... | def generate_mt_message(cls, generate_mt_request):
xml_string = generate_mt_request.xml_string
root_element = ElementTree.fromstring(xml_string)
reference = root_element.find('REFERENCE').text
related_reference = 'TRANSFER'
bank_bic = root_element.find('BANK_BIC').text
sa... | Python | nomic_cornstack_python_v1 |
function list self name
begin
pass
end function | def list(
self,
name,
):
pass | Python | nomic_cornstack_python_v1 |
comment Jimmy Bowden
comment C8.py
from math import sqrt
import C4
class myRecommender
begin
function __init__ self
begin
from math import sqrt
end function
function manhattan self rating1 rating2
begin
string Computes the Manhattan distance. Both rating1 and rating2 are dictionaries
set distance = 0
set commonRatings ... | #Jimmy Bowden
#C8.py
from math import sqrt
import C4
class myRecommender:
def __init__(self):
from math import sqrt
def manhattan(self, rating1, rating2):
"""Computes the Manhattan distance. Both rating1 and rating2 are dictionaries
"""
distance = 0
commonRatings = Fal... | Python | zaydzuhri_stack_edu_python |
function get_all self offset limit sort dsc
begin
set query = query session __model_class
set query = call get_all_defaul_query query sort dsc
set querypage = call get_query_paged query offset limit
return tuple querypage count query
end function | def get_all(self, offset, limit, sort, dsc) -> List[object]:
query = self.session.query(self.__model_class)
query = self.get_all_defaul_query(query, sort, dsc)
querypage = self.get_query_paged(query, offset, limit)
return querypage, query.count() | Python | nomic_cornstack_python_v1 |
function get_confidence_interval_95 self
begin
return 1.96 * square root call get_accuracy * 1.0 - call get_accuracy / total
end function | def get_confidence_interval_95(self) -> float:
return 1.96 * math.sqrt(self.get_accuracy() * (1.0 - self.get_accuracy()) / self.total) | Python | nomic_cornstack_python_v1 |
function paciente_firma_path instance filename
begin
return format string paciente_{0}/firma_{1} numero_documento filename
end function | def paciente_firma_path(instance, filename):
return 'paciente_{0}/firma_{1}'.format(instance.numero_documento, filename) | Python | nomic_cornstack_python_v1 |
import copy
import json
import math
class SortingNetwork extends object
begin
comment 直列なネットワーク(暫定的)
set serialNet = none
comment 並列化されたネットワーク
set network = none
comment ネットワークの入力の数
set num_input = 0
function __init__ self num_input=none
begin
if num_input is none
begin
set num_input = 2
end
set num_input = num_input
s... | import copy
import json
import math
class SortingNetwork(object):
serialNet = None # 直列なネットワーク(暫定的)
network = None # 並列化されたネットワーク
num_input = 0 # ネットワークの入力の数
def __init__(self, num_input=None):
if num_input is None:
self.num_input=2
self.num_input = num_input
s... | Python | zaydzuhri_stack_edu_python |
function sam_to_bam self sam_file out_dir=string out_suffix=string threads=none delete_sam=false verbose=false quiet=false logs=true objectid=string NA **kwargs
begin
if not out_dir
begin
set out_dir = call get_file_directory sam_file
end
else
if not call check_paths_exist out_dir
begin
make directory pu out_dir
end
... | def sam_to_bam(self,sam_file,out_dir="",out_suffix="",threads=None, delete_sam=False,verbose=False,quiet=False,logs=True,objectid="NA",**kwargs):
if not out_dir:
out_dir=pu.get_file_directory(sam_file)
else:
if not pu.check_paths_exist(out_dir):
... | Python | nomic_cornstack_python_v1 |
import subprocess
import sys
function grid_voltage gate cathode
begin
set ssh_server = string xaber@128.3.183.210
set v_step = 100
set time_interval = 2
set cathode_command = format string python /home/xaber/utilities/hv_ramping/cathode_hv_control.py {} {} {} cathode v_step time_interval
set gate_command = format strin... | import subprocess
import sys
def grid_voltage(gate, cathode):
ssh_server = "xaber@128.3.183.210"
v_step = 100
time_interval = 2
cathode_command = "python /home/xaber/utilities/hv_ramping/cathode_hv_control.py {} {} {}".format(cathode, v_step, time_interval)
gate_command = "python /home/xaber/utilities/hv_ramping... | Python | zaydzuhri_stack_edu_python |
function time self
begin
return _time
end function | def time(self):
return self._time | Python | nomic_cornstack_python_v1 |
function generate self
begin
set generated_data = call DataFrame
set majority_class = call get_majority_class
set majority_size = shape at 0
for tuple i classe in enumerate classes
begin
set initial_size = shape at 0
set n = majority_size - initial_size
if n > 0
begin
set new_data = random sample n
set generated_data =... | def generate(self) -> pd.DataFrame:
generated_data = pd.DataFrame()
majority_class = self.get_majority_class()
majority_size = self.df[self.df[self.target] == majority_class].shape[0]
for i, classe in enumerate(self.classes):
initial_size = self.df[self.df[self.target] == cla... | Python | nomic_cornstack_python_v1 |
function encryption_type_number enctype
begin
if not enctype in KRB_ENCTYPE_NUMBERS
begin
raise call AssertionError string Unknown enctype: %s % enctype
end
return KRB_ENCTYPE_NUMBERS at enctype
end function | def encryption_type_number(enctype):
if not enctype in KRB_ENCTYPE_NUMBERS:
raise AssertionError("Unknown enctype: %s" % (enctype))
return KRB_ENCTYPE_NUMBERS[enctype] | Python | nomic_cornstack_python_v1 |
from app import db
from werkzeug.security import generate_password_hash , check_password_hash
from hashlib import md5
set followers = call Table string followers call Column string follower_id Integer call ForeignKey string user.id call Column string followed_id Integer call ForeignKey string user.id
comment FIX - caus... | from app import db
from werkzeug.security import generate_password_hash, \
check_password_hash
from hashlib import md5
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
# FIX - causes associat... | Python | zaydzuhri_stack_edu_python |
from blob import Blob
import pygame
class BlackBlob extends Blob
begin
function __init__ self x_boundary y_boundary
begin
call __init__ tuple 0 0 0 x_boundary y_boundary
end function
function move self
begin
set index = call get_pos
set x = x + index at 0
set y = y + index at 1
if index at 0 != x and index at 1 != y
be... | from blob import Blob
import pygame
class BlackBlob(Blob):
def __init__(self,x_boundary,y_boundary):
super().__init__((0,0,0), x_boundary, y_boundary)
def move(self):
index = pygame.mouse.get_pos()
self.x += index[0]
self.y += index[1]
if index[0] != self.x and index[1] != self.y:
new_b... | Python | zaydzuhri_stack_edu_python |
comment return topK string
comment @param strings string字符串一维数组 strings
comment @param k int整型 the k
comment @return string字符串二维数组
class HeapNode
begin
function __init__ self string times
begin
set string = string
set times = times
end function
end class
class Solution
begin
function topKstrings self strings k
begin
co... | #
# return topK string
# @param strings string字符串一维数组 strings
# @param k int整型 the k
# @return string字符串二维数组
#
class HeapNode:
def __init__(self, string, times):
self.string = string
self.times = times
class Solution:
def topKstrings(self , strings , k ):
# write code here
... | Python | zaydzuhri_stack_edu_python |
function pop_re self
begin
return pop rexps
end function | def pop_re(self):
return self.rexps.pop() | Python | nomic_cornstack_python_v1 |
function idx_state size st
begin
set tuple x state = tuple state % size at 1 state / size at 1
set tuple y state = tuple state % size at 0 state / size at 0
return tuple y x
end function | def idx_state( size, st ):
x, state = state % size[1], state / size[1]
y, state = state % size[0], state / size[0]
return y, x | Python | nomic_cornstack_python_v1 |
function showTest request product
begin
set pings = none
set productName = get filter pk=product
set tests = filter pk=product at 0
if PING in tests
begin
set paginator = call Paginator filter product=product PAGE_LIMIT
set page = get GET string page
try
begin
set pings = call page page
end
except PageNotAnInteger
begi... | def showTest(request, product):
pings = None
productName = Product.objects.filter(pk=product).get()
tests = Product.objects.values_list('test', flat=True).filter(pk=product[0])
if PING in tests:
paginator = Paginator(PingProduct.objects.filter(product=product), PAGE_LIMIT)
page = r... | Python | nomic_cornstack_python_v1 |
string Classes and types that provide for communication with the Dorbo access controller hardware via RS-232 serial.
import logging
from collections import namedtuple
import serial
set Wiegand26Credential = named tuple string Wiegand26Credential list string facility string user
string Represents one stored door access ... | """
Classes and types that provide for communication with the Dorbo access
controller hardware via RS-232 serial.
"""
import logging
from collections import namedtuple
import serial
Wiegand26Credential = namedtuple('Wiegand26Credential', ['facility', 'user'])
"""Represents one stored door access credential."""
SERIA... | Python | zaydzuhri_stack_edu_python |
function fast_inplace_check inputs
begin
set fgraph = fgraph
set protected_inputs = list comprehension protected for f in _features if is instance f Supervisor
comment flatten the list
set protected_inputs = sum protected_inputs list
extend protected_inputs outputs
set inputs = list comprehension i for i in inputs if n... | def fast_inplace_check(inputs):
fgraph = inputs[0].fgraph
protected_inputs = [f.protected for f in fgraph._features if isinstance(f,theano.compile.function_module.Supervisor)]
protected_inputs = sum(protected_inputs,[])#flatten the list
protected_inputs.extend(fgraph.outputs)
inputs = [i for ... | Python | nomic_cornstack_python_v1 |
function equipmentViewPage self state idstring action is_post
begin
set item = call get_equipment idstring
if item is none
begin
call addError string There is no piece of equipment associated with the IDString '%s'. % idstring
call equipmentPage state
return
end
call setTemplate string banned call getBannedUsers accoun... | def equipmentViewPage(self, state, idstring, action, is_post):
item = bsb.equipment.get_equipment(idstring)
if item is None:
state.addError("There is no piece of equipment associated with the IDString '%s'." % idstring)
self.equipmentPage(state)
return
... | Python | nomic_cornstack_python_v1 |
function test_update_metadata_non_existent_server self
begin
if not xenapi_apis
begin
raise call skipException string Metadata is read-only on non-Xen-based deployments.
end
set non_existent_server_id = call rand_uuid
set meta = dict string key1 string value1 ; string key2 string value2
assert raises NotFound update_se... | def test_update_metadata_non_existent_server(self):
if not CONF.compute_feature_enabled.xenapi_apis:
raise self.skipException(
'Metadata is read-only on non-Xen-based deployments.')
non_existent_server_id = data_utils.rand_uuid()
meta = {'key1': 'value1', 'key2': 'va... | Python | nomic_cornstack_python_v1 |
function find_package find_pkg directory
begin
string Find packages
set pkgs = list
if is directory path directory
begin
set installed = sorted list directory directory
set blacklist = call packages pkgs=installed repo=string local
if exists path directory
begin
for pkg in installed
begin
if not starts with pkg string... | def find_package(find_pkg, directory):
"""Find packages
"""
pkgs = []
if os.path.isdir(directory):
installed = sorted(os.listdir(directory))
blacklist = BlackList().packages(pkgs=installed, repo="local")
if os.path.exists(directory):
for pkg in installed:
... | Python | jtatman_500k |
function main
begin
print string This program determines the sum of numbers entered by a user.
set n = eval input string How many numbers would you like to sum:
set sum = 0
for i in range n
begin
set number = eval input string Enter a number:
set sum = sum + number
end
print string Your total sum is sum
end function
ca... | def main():
print("This program determines the sum of numbers entered by a user.")
n = eval(input("How many numbers would you like to sum: "))
sum = 0
for i in range(n):
number = eval(input("Enter a number: "))
sum = sum + number
print("Your total sum is", sum)
main() | Python | zaydzuhri_stack_edu_python |
comment Python3
class Solution
begin
function findMaxConsecutiveOnes self nums
begin
set i = 0
set n = length nums
set m = 0
while i <= n - 1
begin
while i <= n - 1 and nums at i != 1
begin
set i = i + 1
end
set s = i
while i <= n - 1 and nums at i == 1
begin
set i = i + 1
end
set e = i
set m = max m e - s
end
return m... | #Python3
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
i=0
n=len(nums)
m=0
while(i<=n-1):
while(i<=n-1 and nums[i]!=1):
i+=1
s=i
while(i<=n-1 and nums[i]==1):
i+=1
e=i
... | Python | zaydzuhri_stack_edu_python |
import pygame
from pygame.locals import *
import time
import random
comment getting computer performance
set clock = call Clock
comment setting fps to 60
set fps = 60
comment setting screen height
set screenWidth = 600
comment settign screen width
set screenHeight = 800
comment defining colors for the health bar
set ye... | import pygame
from pygame.locals import *
import time
import random
clock = pygame.time.Clock() # getting computer performance
fps = 60 # setting fps to 60
screenWidth = 600 # setting screen height
screenHeight = 800 # settign screen width
# defining colors for the health bar
yellow = (255,214,98)
blue = (0,83... | Python | zaydzuhri_stack_edu_python |
function p2bin self p
begin
return p / binsize
end function | def p2bin (self, p ):
return p/self.binsize | Python | nomic_cornstack_python_v1 |
comment Exercise 15: Reading Files
from sys import argv
comment you have to send the argument you want to pass with the file
comment ex. python Exercise_15.py Exercise_15_sample.txt
set tuple script filename = argv
set prompt = string >
comment we open the file we got passed through argv
comment run pydoc open to see h... | #Exercise 15: Reading Files
from sys import argv
# you have to send the argument you want to pass with the file
# ex. python Exercise_15.py Exercise_15_sample.txt
script, filename = argv
prompt = ">"
# we open the file we got passed through argv
# run pydoc open to see how open works
file = open(filename)
| Python | zaydzuhri_stack_edu_python |
function getGameDataUrl self date
begin
set month = string %02d % month
set day = string %02d % day
set year = string %02d % year
set url = string http://gd2.mlb.com/components/game/mlb/year_%s/month_%s/day_%s/scoreboard.xml % tuple year month day
return url
end function | def getGameDataUrl(self, date):
month = "%02d" % (date.month)
day = "%02d" % (date.day)
year = "%02d" % (date.year)
url = "http://gd2.mlb.com/components/game/mlb/year_%s/month_%s/day_%s/scoreboard.xml" % (year, month, day)
return url | Python | nomic_cornstack_python_v1 |
function release_mode_changed_callback self callback=none
begin
return call release_mode_changed_callback callback
end function | def release_mode_changed_callback(self, callback=None):
return self._arm.release_mode_changed_callback(callback) | Python | nomic_cornstack_python_v1 |
function get_valid_month
begin
string () -> int Return a valid month number input by user after (possibly repeated) prompting. A valid month number is an int between 1 and 12 inclusive.
set prompt = string Enter a valid month number:
set error_message = string Invalid input! Read the instructions and try again!
comment... | def get_valid_month():
""" () -> int
Return a valid month number input by user after (possibly repeated) prompting.
A valid month number is an int between 1 and 12 inclusive.
"""
prompt = 'Enter a valid month number: '
error_message = 'Invalid input! Read the instructions and try again!'
... | Python | zaydzuhri_stack_edu_python |
string Exercise 8.5. ------------- Encapsulate this code in a function named count , and generalize it so that it accepts the string and the letter as arguments. program counts the number of times the a letter appears in a string.
function count string letter
begin
set count = 0
for ch in string
begin
if ch == letter
b... | '''
Exercise 8.5.
-------------
Encapsulate this code in a function named count , and generalize it so that it accepts the string and the letter as arguments.
program counts the number of times the a letter appears in a string.
'''
def count(string, letter):
count =0
for ch in string:
if ch == letter... | Python | zaydzuhri_stack_edu_python |
function get_bit_series self bits=none
begin
string Get the `StateTimeSeries` for each bit of this `StateVector`. Parameters ---------- bits : `list`, optional a list of bit indices or bit names, defaults to all bits Returns ------- bitseries : `StateTimeSeriesDict` a `dict` of `StateTimeSeries`, one for each given bit... | def get_bit_series(self, bits=None):
"""Get the `StateTimeSeries` for each bit of this `StateVector`.
Parameters
----------
bits : `list`, optional
a list of bit indices or bit names, defaults to all bits
Returns
-------
bitseries : `StateTimeSeriesD... | Python | jtatman_500k |
function __init__ self url auth=string http_basic http_user=none http_password=none batch_request_size=32 status_update_interval_secs=10 request_timeout_secs=60 default_job_settings=dict string max_retries 1
begin
set _auth = none
if auth == string http_basic
begin
assert http_user is not none msg string HTTP user is r... | def __init__(self, url, auth='http_basic', http_user=None, http_password=None, batch_request_size=32,
status_update_interval_secs=10, request_timeout_secs=60, default_job_settings={'max_retries': 1}):
self._auth = None
if auth == 'http_basic':
assert http_user is not None, ... | Python | nomic_cornstack_python_v1 |
function plot_iteration_raydensity self
begin
call plot_raydensity lasif_comm iteration=current_iteration plot_stations=true save=true
set filename = join path lasif_root string OUTPUT string raydensity_plots string ITERATION_ { current_iteration } string raydensity.png
return filename
end function | def plot_iteration_raydensity(self) -> str:
lapi.plot_raydensity(
self.lasif_comm,
iteration=self.comm.project.current_iteration,
plot_stations=True,
save=True,
)
filename = os.path.join(
self.lasif_root,
"OUTPUT",
... | Python | nomic_cornstack_python_v1 |
import math as m
set x = pi / 2.0
print sin x
print cos x
set x = pi / 2
print cos x
set a = 2.0
set b = 3.0
set c = a + b
print c
print a / b
print square root 5 * c
print exp 10.0
print log 22026.47 | import math as m
x = m.pi / 2.0
print(m.sin(x))
print(m.cos(x))
x = m.pi / 2
print(m.cos(x))
a = 2.0
b = 3.0
c = a + b
print(c)
print(a/b)
print(m.sqrt(5*c))
print(m.exp(10.))
print(m.log(22026.47))
| Python | zaydzuhri_stack_edu_python |
function gshow X X1=none X2=none X3=none X4=none X5=none X6=none
begin
if call isbinary X
begin
set X = call gray X string uint8
end
set r = X
set g = X
set b = X
comment red 1 0 0
if X1 is not none
begin
assert call isbinary X1 msg string X1 must be binary overlay
set x1 = call gray X1 string uint8
set r = union r x1
... | def gshow(X, X1=None, X2=None, X3=None, X4=None, X5=None, X6=None):
if isbinary(X): X = gray(X,'uint8')
r = X
g = X
b = X
if X1 is not None: # red 1 0 0
assert isbinary(X1),'X1 must be binary overlay'
x1 = gray(X1,'uint8')
r = union(r,x1)
g = intersec(g,neg(x1))
b = in... | Python | nomic_cornstack_python_v1 |
function addDerivesFrom self child_id parent_id child_category=none parent_category=none
begin
call addTriple child_id globaltt at string derives_from parent_id subject_category=child_category object_category=parent_category
end function | def addDerivesFrom(
self, child_id, parent_id, child_category=None, parent_category=None
):
self.graph.addTriple(
child_id,
self.globaltt['derives_from'],
parent_id,
subject_category=child_category,
object_category=parent_category
... | Python | nomic_cornstack_python_v1 |
function get_user_details self response
begin
set tuple first_name last_name = tuple response at string first-name response at string last-name
set email = get response string email-address string
return dict string username first_name + last_name ; string fullname first_name + string + last_name ; string first_name f... | def get_user_details(self, response):
first_name, last_name = response['first-name'], response['last-name']
email = response.get('email-address', '')
return {'username': first_name + last_name,
'fullname': first_name + ' ' + last_name,
'first_name': first_name,
... | Python | nomic_cornstack_python_v1 |
comment program that calculate the average of the
comment square root of all the numbers from 1 to 1000
from pyspark import SparkContext
from operator import add
from math import sqrt
if __name__ == string __main__
begin
set sc = call SparkContext string local string squareroot_spark
comment Create an RDD of numbers ra... | #program that calculate the average of the
#square root of all the numbers from 1 to 1000
from pyspark import SparkContext
from operator import add
from math import sqrt
if __name__ == '__main__':
sc = SparkContext("local", "squareroot_spark")
# Create an RDD of numbers range from 1 to 1001
nums = sc.par... | Python | zaydzuhri_stack_edu_python |
function principal_id self
begin
return get pulumi self string principal_id
end function | def principal_id(self) -> str:
return pulumi.get(self, "principal_id") | Python | nomic_cornstack_python_v1 |
import numpy as np
from constants import *
function transition_to_next_period v
begin
string This function computes the new values after transitioning to the next period. This needs to be done for every index since the flow costs depend on it.
set u = call full tuple NUM_STATES + 1 PROD_SETTINGS MAX_PROD_TIME MAX_MAIN_... | import numpy as np
from ..constants import *
def transition_to_next_period(v: np.ndarray) -> np.ndarray:
"""
This function computes the new values after transitioning to the next
period. This needs to be done for every index since the flow costs depend
on it.
"""
u = np.full(
(NUM_STA... | Python | zaydzuhri_stack_edu_python |
function test_push
begin
set priorityQ = call PriorityQ
set numsPushed = list
for num in NUMBERS
begin
call push num
append numsPushed call PQNode num
assert priorityQ at 0 != max numsPushed
end
end function | def test_push():
priorityQ = PriorityQ()
numsPushed = []
for num in NUMBERS:
priorityQ.push(num)
numsPushed.append(PQNode(num))
assert priorityQ[0] != max(numsPushed) | Python | nomic_cornstack_python_v1 |
class DrinkAction
begin
function __init__ self drinker bac
begin
set drinker = drinker
set bac = decimal bac
end function
function get self
begin
set hours = 1
set gender_constant = if expression gender then 0.58 else 0.49
set adjusted_weight = weight * 0.453592 * gender_constant
set metabolized = 0.01 + 0.005 * tolera... | class DrinkAction:
def __init__(self, drinker, bac):
self.drinker = drinker
self.bac = float(bac)
def get(self):
hours = 1
gender_constant = 0.58 if self.drinker.gender else 0.49
adjusted_weight = self.drinker.weight * 0.453592 * gender_constant
metabolized = (0... | Python | zaydzuhri_stack_edu_python |
function datetime_timeplotxml self
begin
if time
begin
return string format time date string %b %d %Y + string + string format time time string %H:%M:%S + string GMT
end
else
begin
return string format time date string %b %d %Y + string + string 00:00:00 + string GMT
end
end function | def datetime_timeplotxml(self):
if self.time:
return self.date.strftime("%b %d %Y") + " " + self.time.strftime("%H:%M:%S") + " GMT"
else:
return self.date.strftime("%b %d %Y") + " " + "00:00:00" + " GMT" | Python | nomic_cornstack_python_v1 |
function calculate_covariance points_array lags step_size
begin
set covariance = list
comment Calculate distance
set distance_array = call calculate_distance points_array at tuple slice : : slice 0 : - 1 :
comment Calculate covariance
for h in lags
begin
set cov = list
set mu = 0
set distances_in_range = where cal... | def calculate_covariance(points_array, lags, step_size):
covariance = []
# Calculate distance
distance_array = calculate_distance(points_array[:, 0:-1])
# Calculate covariance
for h in lags:
cov = []
mu = 0
distances_in_range = np.where(
np.logical_and(
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string Created on Fri Jan 11 11:26:23 2019 @author: root
import jpype
import pandas as pd
import sqlite3
from timeit import default_timer as timer
set month = string 02
set conn = call connect string /Users/casa/Documents/sqlite-tools-osx-x86-3260000/ff.db
set... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 11:26:23 2019
@author: root
"""
import jpype
import pandas as pd
import sqlite3
from timeit import default_timer as timer
month='02'
conn = sqlite3.connect("/Users/casa/Documents/sqlite-tools-osx-x86-3260000/ff.db")
sql='select s1,s2,timestamp ... | 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.