code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Two sum: https://leetcode.com/problems/target-sum/#/description
class Solution extends object
begin
function findTargetSumWays self nums S
begin
string :type nums: List[int] :type S: int :rtype: int
function find n nums sum
begin
if n == length nums
begin
return if expression sum == 0 then 1 else 0
end
return f... | #Two sum: https://leetcode.com/problems/target-sum/#/description
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
def find(n, nums, sum):
if n == len(nums):
return 1 if su... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3.5
comment encoding: utf-8
comment Created by leiwei on 2020/8/17 16:48
set person1 = dict string name string zhangsan ; string age 18 ; string score 652.5
set person2 = dict string sex string 男
set person3 = dict string name string lisi
comment 添加
update person1 person2
comment 覆盖
update p... | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/8/17 16:48
person1 = {'name': 'zhangsan', 'age': 18, 'score': 652.5}
person2 = {'sex': '男'}
person3 = {'name': 'lisi'}
# 添加
person1.update(person2)
# 覆盖
person1.update(person3)
print(person1)
| Python | zaydzuhri_stack_edu_python |
comment 保存模块
import csv
from setting import csv_file_path
import pandas as pd
class SaveIp extends object
begin
comment 参数:csv_file_path 本地数据池的路径
comment 参数:mode 保存ip代理的方式
function __init__ self csv_file_path=csv_file_path mode=string w
begin
set mode = mode
set csv_file_path = csv_file_path
end function
function chang... | # 保存模块
import csv
from setting import csv_file_path
import pandas as pd
class SaveIp(object):
# 参数:csv_file_path 本地数据池的路径
# 参数:mode 保存ip代理的方式
def __init__(self,csv_file_path=csv_file_path,mode='w'):
self.mode=mode
self.csv_file_path = csv_file_path
def change_file_pat... | Python | zaydzuhri_stack_edu_python |
string The infinite continued fraction can be written, 2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, 23 = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for 2. H... | '''
The infinite continued fraction can be written, 2 = [1;(2)], (2) indicates
that 2 repeats ad infinitum. In a similar way, 23 = [4;(1,3,1,8)].
It turns out that the sequence of partial values of continued fractions for
square roots provide the best rational approximations. Let us consider the
convergents for 2.
He... | Python | zaydzuhri_stack_edu_python |
function detect_backup_vm_guestOS_hang_info parser
begin
set ssh = call get_ssh parser at string NFS_ip parser at string NFS_usr parser at string NFS_pwd
comment 獲取ssh
sleep decimal 5
set fail = call get_vm_infofail parser at string BackupOS_name parser at string vm_name parser ssh
comment guestOS hang and reboot succe... | def detect_backup_vm_guestOS_hang_info(parser):
ssh = shell_server.get_ssh(parser["NFS_ip"]
, parser["NFS_usr"]
, parser["NFS_pwd"]) #獲取ssh
time.sleep(float(5))
fail = HAagent_info.get_vm_infofail(parser["BackupOS_name"],parser["vm_name"], parser, ssh)
... | Python | nomic_cornstack_python_v1 |
import torch
function save_model_weights model
begin
save state dict model string /content/AI-13B-v20e8/AI-13B-v20e8.pth
end function | import torch
def save_model_weights(model):
torch.save(model.state_dict(), '/content/AI-13B-v20e8/AI-13B-v20e8.pth')
| Python | flytech_python_25k |
function get_routing_queue self queue_id **kwargs
begin
set all_params = list string queue_id
append all_params string callback
set params = locals
for tuple key val in call iteritems params at string kwargs
begin
if key not in all_params
begin
raise call TypeError string Got an unexpected keyword argument '%s' to meth... | def get_routing_queue(self, queue_id, **kwargs):
all_params = ['queue_id']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword ... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function isSubsequence self s t
begin
string :type s: str :type t: str :rtype: bool
set indexT = 0
for ch in s
begin
while indexT < length t and t at indexT != ch
begin
set indexT = indexT + 1
end
if indexT == length t
begin
return false
end
set indexT = indexT + 1
end
return true
end function
end ... | class Solution:
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
indexT = 0
for ch in s:
while indexT < len(t) and t[indexT] != ch:
indexT += 1
if indexT == len(t):
return Fal... | Python | zaydzuhri_stack_edu_python |
function gift_card self cardid season to
begin
call execute_command command=string giftcard cardid=string cardid season=string season to=to
end function | def gift_card(self, cardid: int, season: int, to: str) -> None:
self.execute_command(
command="giftcard", cardid=str(cardid), season=str(season), to=to
) | Python | nomic_cornstack_python_v1 |
while true
begin
try
begin
set s = input
print string hello, + s
end
except EOFError
begin
break
end
end | while True:
try:
s = input()
print("hello, " + s)
except EOFError:
break | Python | zaydzuhri_stack_edu_python |
class Instance extends object
begin
set sample_data = dict
set sample_data at string i-3e43qa = dict string owner string operations ; string id string i-3e43qa
set sample_data at string i-abc123 = dict string owner string alphanumeric ; string id string i-abc123
function __init__ self instance_id
begin
set scope = sam... | class Instance(object):
sample_data = {}
sample_data["i-3e43qa"] = {
"owner": "operations",
"id": "i-3e43qa"
}
sample_data["i-abc123"] = {
"owner": "alphanumeric",
"id": "i-abc123"
}
def __init__(self, instance_id):
self.scope = Instance.sample_data[inst... | Python | zaydzuhri_stack_edu_python |
comment A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
comment 012 021 102 120 201 210
co... | # A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
# 012 021 102 120 201 210
# ... | Python | zaydzuhri_stack_edu_python |
function check
begin
set tuple pp ch = map float split input string ;
if ch < pp
begin
return string ERROR
end
else
if ch == pp
begin
return string Zero
end
set ch = ch - pp
set response = list
set i = 0
while ch >= 0 and i < length denomination
begin
comment print(denomination[i], ch)
if changes at denomination at i ... | def check():
pp, ch = map(float, input().split(";"))
if ch < pp:
return "ERROR"
elif ch == pp:
return "Zero"
ch = ch - pp
response = []
i = 0
while ch >= 0 and i < len(denomination):
# print(denomination[i], ch)
if changes[denomination[i]] <= ch:
ch -= changes[denomination[i]]
response.append(de... | Python | zaydzuhri_stack_edu_python |
import json
import logging
from multiprocessing import Process
import pika
import sqlalchemy
from cool_app import Message , RabbitMQ
from cool_app.models import Customer , Session
set log = call getLogger __name__
class RabbitMQConsumer extends RabbitMQ
begin
string A consumer for processing rabbitmq messages
function ... | import json
import logging
from multiprocessing import Process
import pika
import sqlalchemy
from cool_app import Message, RabbitMQ
from cool_app.models import Customer, Session
log = logging.getLogger(__name__)
class RabbitMQConsumer(RabbitMQ):
"""A consumer for processing rabbitmq messages"""
def __init... | Python | zaydzuhri_stack_edu_python |
function _create_samples self trim
begin
set nlp = none
if trim
begin
set nlp = load spacy string en_core_web_lg
set sentencizer = call create_pipe string sentencizer
call add_pipe sentencizer
end
comment # pos tags
set pos_tags = call load_tag_file pos_tag_path
set pos_vocabulary = call Vocabulary pos_tags length pos_... | def _create_samples(self, trim):
nlp = None
if (trim):
nlp = spacy.load("en_core_web_lg")
sentencizer = nlp.create_pipe("sentencizer")
nlp.add_pipe(sentencizer)
# # pos tags
pos_tags = load_tag_file(self.args.pos_tag_path)
pos_vocabulary = Voc... | Python | nomic_cornstack_python_v1 |
function typeName self
begin
pass
end function | def typeName(self):
pass | Python | nomic_cornstack_python_v1 |
from hashlib import sha256
from collections import OrderedDict
import json
function hash_block_data block
begin
string Creates a SHA-256 hash object of the block. :param block: The block to be hashed. :return: string - the encoded block in hexadecimal string format.
set block_copy = copy __dict__
del block_copy at stri... | from hashlib import sha256
from collections import OrderedDict
import json
def hash_block_data(block):
"""
Creates a SHA-256 hash object of the block.
:param block: The block to be hashed.
:return: string - the encoded block in hexadecimal string format.
"""
block_copy = block.__dict__.copy()
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import minmax_scale
comment https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60
comment Read data from Image Segmentation Database
set data = read csv string data... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import minmax_scale
# https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60
# Read data from Image Segmentation Database
data = pd.read_csv('data/seg.test')
# Lo... | Python | zaydzuhri_stack_edu_python |
comment -*- encoding: utf-8 -*-
string Created on 25 Dec 2016 @author: jogin
import codecs
import re
import wordcloud
class Wordwolke
begin
function __init__ self
begin
pass
end function
from wordcloud import WordCloud , STOPWORDS
import matplotlib.pyplot as plt
comment Convert all the required text into a single strin... | # -*- encoding: utf-8 -*-
'''
Created on 25 Dec 2016
@author: jogin
'''
import codecs
import re
import wordcloud
class Wordwolke():
def __init__(self):
pass
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
#Convert all the required text into a single strin... | Python | zaydzuhri_stack_edu_python |
comment Creates classes for databases where their attributes are stored
from website import db
comment Volunteer class for eligible emails for event registration
class Volunteer extends Model
begin
set __bind_key__ = string valid emails
set email = call Column call String 100 unique=true nullable=false primary_key=true... | # Creates classes for databases where their attributes are stored
from website import db
# Volunteer class for eligible emails for event registration
class Volunteer(db.Model):
__bind_key__ = 'valid emails'
email = db.Column(db.String(100), unique=True, nullable=False, primary_key=True)
def __repr__(self... | Python | zaydzuhri_stack_edu_python |
string I opened up a dictionary to a page in the middle and started flipping through, looking for words I didn't know. I put each word I didn't know at increasing indices in a huge list I created in memory. When I reached the end of the dictionary, I started from the beginning and did the same thing until I reached the... | """
I opened up a dictionary to a page in the middle and started flipping through,
looking for words I didn't know. I put each word I didn't know at increasing
indices in a huge list I created in memory. When I reached the end of the
dictionary, I started from the beginning and did the same thing until I reached
th... | Python | zaydzuhri_stack_edu_python |
from PIL import Image
import pytesseract
import re
set image_path = string example_image.png
set image = open image_path
set text = call image_to_string image
set hashtag_pattern = string #\w+
set hashtags = find all hashtag_pattern text
set sorted_hashtags = sorted hashtags
with open string sorted_hashtags.txt string ... | from PIL import Image
import pytesseract
import re
image_path = 'example_image.png'
image = Image.open(image_path)
text = pytesseract.image_to_string(image)
hashtag_pattern = r'#\w+'
hashtags = re.findall(hashtag_pattern, text)
sorted_hashtags = sorted(hashtags)
with open('sorted_hashtags.txt', 'w') as f:
f.writ... | Python | flytech_python_25k |
class Stock
begin
function __init__ self ticker price
begin
set price = price
set ticker = ticker
print string this is the init function
end function
function buy self
begin
print string buy a stock
end function
function __del__ self
begin
print string delete the object
end function
function __str__ self
begin
return s... | class Stock:
def __init__(self, ticker, price):
self.price = price
self.ticker = ticker
print("this is the init function")
def buy(self):
print("buy a stock")
def __del__(self):
print("delete the object")
def __str__(self):
return f"this is a stock call... | Python | zaydzuhri_stack_edu_python |
function open_output self file_name=none
begin
if file_name is none
begin
set file_name = file_prefix
if not ends with file_name string _
begin
set file_name = file_name + string _
end
set file_name = file_name + call getTs
end
if not match file_name string ^.*\.[^.]+$
begin
set file_name = file_name + string . + file_... | def open_output(self, file_name=None):
if file_name is None:
file_name = self.file_prefix
if not file_name.endswith("_"):
file_name += "_"
file_name += SlTrace.getTs()
if not re.match(file_name, r"^.*\.[^.]+$"):
file_name += "." + s... | Python | nomic_cornstack_python_v1 |
function cos_gamma _a incl tol=0.0001
begin
if absolute incl < tol
begin
return 0
end
comment real
return cos _a / square root cos _a ^ 2 + 1 / tan incl ^ 2
end function | def cos_gamma(_a: float, incl: float, tol=10e-5) -> float:
if abs(incl) < tol:
return 0
return np.cos(_a) / np.sqrt(np.cos(_a) ** 2 + 1 / (np.tan(incl) ** 2)) # real | Python | nomic_cornstack_python_v1 |
string source from : www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/
from nltk import FreqDist
from nltk import classify
from nltk import NaiveBayesClassifier
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer , PorterStemmer
from nltk.corpus import stopwords
set... | """
source from :
www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/
"""
from nltk import FreqDist
from nltk import classify
from nltk import NaiveBayesClassifier
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer, PorterStemmer
from nltk.corpus import stopwords
po... | Python | zaydzuhri_stack_edu_python |
function do_libfuzzer_cleanse testcase testcase_file_path expected_crash_state
begin
set timeout = call get_value string LIBFUZZER_CLEANSE_TIMEOUT 180
set tuple output_file_path _ = call _run_libfuzzer_tool string cleanse testcase testcase_file_path timeout expected_crash_state
if output_file_path
begin
log string LibF... | def do_libfuzzer_cleanse(testcase, testcase_file_path, expected_crash_state):
timeout = environment.get_value('LIBFUZZER_CLEANSE_TIMEOUT', 180)
output_file_path, _ = _run_libfuzzer_tool(
'cleanse', testcase, testcase_file_path, timeout, expected_crash_state)
if output_file_path:
logs.log('LibFuzzer cle... | Python | nomic_cornstack_python_v1 |
function logits_to_string logits text
begin
comment TODO option to truncate the end_logits to [start_index:] to force end_index to be > start_index
comment start_idx, end_idx = logits[: len(text)].argmax(dim=0).cpu().numpy()
set tuple start_idx end_idx = call numpy
if end_idx <= start_idx
begin
return text
end
else
beg... | def logits_to_string(logits, text):
# TODO option to truncate the end_logits to [start_index:] to force end_index to be > start_index
# start_idx, end_idx = logits[: len(text)].argmax(dim=0).cpu().numpy()
start_idx, end_idx = logits.argmax(dim=0).cpu().numpy()
if end_idx <= start_idx:
return te... | Python | nomic_cornstack_python_v1 |
function get_num_neighbors_grid grid
begin
set num_grid = call copy_grid grid
for y in range length grid
begin
for x in range length grid at y
begin
set num_grid at y at x = call get_num_neighbors grid x y
end
end
return num_grid
end function | def get_num_neighbors_grid(grid):
num_grid = copy_grid(grid)
for y in range(len(grid)):
for x in range(len(grid[y])):
num_grid[y][x] = get_num_neighbors(grid, x, y)
return num_grid | Python | nomic_cornstack_python_v1 |
import numpy as np
import imageio
import cv2
function crop_div factor img
begin
set len_y = length img
set len_x = length img at 0
while len_y % factor != 0
begin
set len_y = len_y - 1
end
while len_x % factor != 0
begin
set len_x = len_x - 1
end
return img at tuple slice : len_y : slice : len_x :
end function
func... | import numpy as np
import imageio
import cv2
def crop_div(factor, img):
len_y = len(img)
len_x = len(img[0])
while len_y % factor != 0:
len_y -= 1
while len_x % factor != 0:
len_x -= 1
return img[:len_y, :len_x]
def normalize(max, img):
bimg = cv2.blur(img, (3, 3))
fac = ... | Python | zaydzuhri_stack_edu_python |
function getSet self name
begin
string Get the set with the corresponding name. Args: name: Name of the set to be found. Raises: TypeError: if the specified set does not exist.
return call lock_and_call lambda -> set call getSet name _lock
end function | def getSet(self, name):
"""
Get the set with the corresponding name.
Args:
name: Name of the set to be found.
Raises:
TypeError: if the specified set does not exist.
"""
return lock_and_call(
lambda: Set(self._impl.getSet(name)),
... | Python | jtatman_500k |
comment Automating AWS services using boto3.
import boto3
set s3 = call resource string s3
call download_file string source_file string destination_file | # Automating AWS services using boto3.
import boto3
s3 = boto3.resource('s3')
s3.Bucket('bucket_name').download_file('source_file', 'destination_file')
| Python | flytech_python_25k |
function run code
begin
set i = 0
while true
begin
set c = code at i
if c is 1
begin
set code at code at i + 3 = code at code at i + 1 + code at code at i + 2
set i = i + 4
end
else
if c is 2
begin
set code at code at i + 3 = code at code at i + 1 * code at code at i + 2
set i = i + 4
end
else
if c is 99
begin
return c... | def run(code):
i = 0
while True:
c = code[i]
if c is 1:
code[code[i+3]] = code[code[i+1]] + code[code[i+2]]
i += 4
elif c is 2:
code[code[i+3]] = code[code[i+1]] * code[code[i+2]]
i += 4
elif c is 99:
return code[0]
... | Python | zaydzuhri_stack_edu_python |
function biggest_guy
begin
set number1 = input string Number 1:
set number2 = input string Number 2:
set number3 = input string Number 3:
if number1 > number2 and number1 > number3
begin
set biggest_number = number1
print string The biggest number among + number1 + string , + number2 + string , + number3 + string ,is +... | def biggest_guy():
number1 = input("Number 1: ")
number2 = input("Number 2: ")
number3 = input("Number 3: ")
if (number1>number2) and (number1>number3):
biggest_number = number1
print("The biggest number among " +number1+"," +number2+"," +number3+","
"is " +biggest_numbe... | Python | zaydzuhri_stack_edu_python |
function random_brightness image
begin
set hsv_channel = call cvtColor image COLOR_RGB2HSV
set brightness_scalar = call rand
set ratio = 1.0 + 0.4 * brightness_scalar - 0.5
set hsv_channel at tuple slice : : slice : : 2 = hsv_channel at tuple slice : : slice : : 2 * ratio
return call cvtColor hsv_channel CO... | def random_brightness(image):
hsv_channel = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
brightness_scalar = np.random.rand()
ratio = 1.0 + 0.4 * (brightness_scalar - 0.5)
hsv_channel[:,:,2] = hsv_channel[:,:,2] * ratio
return cv2.cvtColor(hsv_channel, cv2.COLOR_HSV2RGB) | Python | nomic_cornstack_python_v1 |
from title_case import title_case
import unittest
class TestTitleCase extends TestCase
begin
function test self
begin
function solve title minor_words
begin
return if expression minor_words is none then call title_case title else call title_case title minor_words
end function
assert equal call solve string string stri... | from title_case import title_case
import unittest
class TestTitleCase(unittest.TestCase):
def test(self):
def solve(title, minor_words):
return title_case(title) if minor_words is None else title_case(title, minor_words)
self.assertEqual(solve('', ''), '')
self.assertEqual(... | Python | zaydzuhri_stack_edu_python |
function convert_date_time input_str
begin
try
begin
set tuple date_str time_str = split input_str string
set tuple year month day = split date_str string -
set tuple hour minute second = split time_str string :
set output_str = string { day } - { month } - { year } { hour } : { minute }
return output_str
end
except Va... | def convert_date_time(input_str):
try:
date_str, time_str = input_str.split(" ")
year, month, day = date_str.split("-")
hour, minute, second = time_str.split(":")
output_str = f"{day}-{month}-{year} {hour}:{minute}"
return output_str
except ValueError:
return "Er... | Python | jtatman_500k |
function tmp_dir tmpdir_factory
begin
set tmpd = call mktemp string output
change directory string tmpd
for ext in tuple string .tsv string .case-data-1
begin
copy 2 join path data_dir target_root_name + ext string tmpd
end
print format string Tests are in: {} string tmpd
end function | def tmp_dir(tmpdir_factory):
tmpd = tmpdir_factory.mktemp("output")
os.chdir(str(tmpd))
for ext in (".tsv", ".case-data-1"):
shutil.copy2(os.path.join(data_dir, target_root_name + ext), str(tmpd))
print("Tests are in: {}".format(str(tmpd))) | Python | nomic_cornstack_python_v1 |
import numpy as np
import random
import torch
class ReplayBuffer extends object
begin
function __init__ self size
begin
set _storage = list
set _maxsize = size
set _next_idx = 0
end function
function __len__ self
begin
return length _storage
end function
function add self obs_t action R preact var d
begin
set data = t... | import numpy as np
import random
import torch
class ReplayBuffer(object):
def __init__(self, size):
self._storage = []
self._maxsize = size
self._next_idx = 0
def __len__(self):
return len(self._storage)
def add(self, obs_t, action, R, preact, var, d):
data = (ob... | Python | zaydzuhri_stack_edu_python |
function selection_parser options=dict string --back string back
begin
while true
begin
try
begin
print string Please select from the following options:
if string --back in keys options
begin
del options at string --back
set options at string --BACK = string back
end
if string --logout in keys options
begin
del options... | def selection_parser(options={"--back": "back"}) -> str:
while True:
try:
print("Please select from the following options:")
if "--back" in options.keys():
del options["--back"]
options["--BACK"] = "back"
if "--l... | Python | nomic_cornstack_python_v1 |
import sys
function endian_conv value
begin
set left_most_byte = value ? 255 ? 0
set left_mid_byte = value ? 65280 ? 8
set right_mid_byte = value ? 16711680 ? 16
set right_most_byte = value ? 4278190080 ? 24
set left_most_byte = left_most_byte ? 24
set left_mid_byte = left_mid_byte ? 16
set right_mid_byte = right_mid_b... | import sys
def endian_conv(value):
left_most_byte = (value & 0x000000ff) >> 0
left_mid_byte = (value & 0x0000ff00) >> 8
right_mid_byte = (value & 0x00ff0000) >> 16
right_most_byte= (value & 0xff000000) >> 24
left_most_byte <<= 24
left_mid_byte <<= 16
right_mid_byte <<= 8
right_most_byte ... | Python | zaydzuhri_stack_edu_python |
from nltk import word_tokenize , pos_tag
from nltk.stem.porter import PorterStemmer
import regex as re
import sys
class Scanner
begin
function __init__ self
begin
set stemmer = call PorterStemmer
return
end function
function scan self text wordKey referenceWords
begin
set sentenceWords = dict
call loadRelationsMatchin... | from nltk import word_tokenize, pos_tag
from nltk.stem.porter import PorterStemmer
import regex as re
import sys
class Scanner:
def __init__(self):
self.stemmer = PorterStemmer()
return
def scan(self, text, wordKey, referenceWords):
self.sentenceWords = {}
self.loadRel... | Python | zaydzuhri_stack_edu_python |
function prefix cls __and=true __key=none **kwargs
begin
return call _queries string LIKE __key __and list comprehension tuple k string { call _escape_like v } % for tuple k v in items kwargs
end function | def prefix(cls, __and=True, __key=None, **kwargs):
return _queries("LIKE", __key, __and, [(k, f"{_escape_like(v)}%") for k, v in kwargs.items()]) | Python | nomic_cornstack_python_v1 |
function create_placeholders nx classes
begin
set x1 = call placeholder string float tuple none nx name=string x
set y1 = call placeholder string float tuple none classes name=string y
return tuple x1 y1
end function | def create_placeholders(nx, classes):
x1 = tf.placeholder("float", (None, nx), name="x")
y1 = tf.placeholder("float", (None, classes), name="y")
return x1, y1 | Python | nomic_cornstack_python_v1 |
function get_title_or_id_from_uid uid
begin
string Returns the title or ID from the given UID
set obj = call get_object_by_uid uid default=none
if obj is none
begin
return string
end
set title_or_id = call get_title obj or call get_id obj
return title_or_id
end function | def get_title_or_id_from_uid(uid):
"""Returns the title or ID from the given UID
"""
obj = api.get_object_by_uid(uid, default=None)
if obj is None:
return ""
title_or_id = api.get_title(obj) or api.get_id(obj)
return title_or_id | Python | jtatman_500k |
function as_ self direction
begin
if direction not in set literal string to string from
begin
raise call InvalidDirection string tf casn
end
set _data at string = title _data at string
return dictionary comprehension direction + title k : v for tuple k v in items _data
end function | def as_(self, direction: str) -> dict:
if direction not in {'to', 'from'}:
raise InvalidDirection('tf casn')
self._data[''] = self._data[''].title()
return {
direction + k.title(): v
for k, v in self._data.items()
} | Python | nomic_cornstack_python_v1 |
function beat_correlation_bi x peaks sampling_rate buf_size=12
begin
function max_buf_corr arr prev_buf succ_buf
begin
set prev = call nanmean call _corr_multi prev_buf arr
set succ = call nanmean call _corr_multi succ_buf arr
return max prev succ
end function
set hsr = sampling_rate // 2
set prev_buf = zeros tuple buf... | def beat_correlation_bi(x, peaks, sampling_rate, buf_size=12):
def max_buf_corr(arr, prev_buf, succ_buf):
prev = np.nanmean(_corr_multi(prev_buf, arr))
succ = np.nanmean(_corr_multi(succ_buf, arr))
return max(prev, succ)
hsr = sampling_rate // 2
prev_buf = np.zeros((buf_size, sampli... | Python | nomic_cornstack_python_v1 |
import random
comment Write a program to select a random name out of a list.
comment Starter code:
set names_string = input string Give me everybody's names, separated by a comma.
set names = split names_string string ,
comment End starter code.
set random_index = random integer 0 length names - 1
print string { names ... | import random
#Write a program to select a random name out of a list.
#Starter code:
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
#End starter code.
random_index = random.randint(0, len(names) - 1)
print(f"{names[random_index]} is going to buy the meal to... | Python | zaydzuhri_stack_edu_python |
function managed_identity_certificate_expiration_time self
begin
return get pulumi self string managed_identity_certificate_expiration_time
end function | def managed_identity_certificate_expiration_time(self) -> pulumi.Output[str]:
return pulumi.get(self, "managed_identity_certificate_expiration_time") | Python | nomic_cornstack_python_v1 |
function save_sums_cache tracer_id model sums verbose=true
begin
for tuple iso_group types in items sums
begin
for tuple composition_type table in items types
begin
set table_name = call sums_table_name composition_type iso_group=iso_group
call save_table_cache table tracer_id=tracer_id model=model table_name=table_nam... | def save_sums_cache(tracer_id, model, sums, verbose=True):
for iso_group, types in sums.items():
for composition_type, table in types.items():
table_name = network.sums_table_name(composition_type, iso_group=iso_group)
save_table_cache(table, tracer_id=tracer_id, model=model,
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sat Mar 20 21:52:06 2021 @author: Karthik
import numpy as np
set Inp = list
set no_features = integer input string Enter the number of features:
set no_instances = integer input string Enter the number of instances:
print string Enter the data with enter:
for i in range ... | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 20 21:52:06 2021
@author: Karthik
"""
import numpy as np
Inp=[]
no_features=int(input('Enter the number of features: '))
no_instances=int(input('Enter the number of instances: '))
print('Enter the data with enter:')
for i in range(0, no_features*no_instance... | Python | zaydzuhri_stack_edu_python |
import math
import sys
comment sys.setrecursionlimit(100000)
function input
begin
return strip read line stdin
end function
function input_int
begin
return integer input
end function
function input_int_list
begin
return list comprehension integer i for i in split input
end function
function main
begin
set n = call inpu... | import math
import sys
# sys.setrecursionlimit(100000)
def input():
return sys.stdin.readline().strip()
def input_int():
return int(input())
def input_int_list():
return [int(i) for i in input().split()]
def main():
n = input_int()
_x = []
_y = []
for _ in range(n):
x, y = in... | Python | zaydzuhri_stack_edu_python |
function lookup_project self credentials match filter_ options
begin
return call object_lookup AUTHORITY_NAME string project match filter_
end function | def lookup_project(self, credentials, match, filter_, options):
return self._resource_manager_tools.object_lookup(self.AUTHORITY_NAME, 'project', match, filter_) | Python | nomic_cornstack_python_v1 |
function _set_cpus self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=yc_cpus_openconfig_access_points__access_points_access_point_system_cpus is_container=string container yang_name=string cpus parent=self path_helper=_path_helper extmeth... | def _set_cpus(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_cpus_openconfig_access_points__access_points_access_point_system_cpus, is_container='container', yang_name="cpus", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, reg... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import scipy as sp
import argparse
class Graph
begin
function __init__ self p g
begin
set G = call from_numpy_matrix call todense
set n_num = length G
set e_num = call number_of_edges
set nodes = call nodes
set edges = call edges
set ovl_p = p
set... | import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import scipy as sp
import argparse
class Graph:
def __init__(self, p, g):
self.G = nx.from_numpy_matrix(sp.sparse.load_npz('graphs/'+ g).todense())
self.n_num = len(self.G)
self.e_num = self.G.number_of_edges()
... | Python | zaydzuhri_stack_edu_python |
string The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime,... | '''
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime... | Python | zaydzuhri_stack_edu_python |
function write self
begin
write json_o
end function | def write(self):
self.json_o.write() | Python | nomic_cornstack_python_v1 |
function task_template_ids self task_template_ids
begin
if task_template_ids is none
begin
call _set string task_templates list
end
else
if not is instance task_template_ids list
begin
raise call ValidationError string Task template ids must be a list, not a %s. % __name__
end
else
begin
set task_template_ids = list se... | def task_template_ids(self, task_template_ids):
if task_template_ids is None:
self._set('task_templates', [])
elif not isinstance(task_template_ids, list):
raise ValidationError("Task template ids must be a list, not a %s." % type(task_template_ids).__name__)
else:
... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import requests
from datetime import datetime
from time import sleep
from modules.gc_bucket import download_blob , upload_blob
function open_site_html_file
begin
comment abre arquivo com toda programação
set file = call download_blob string site.html
set site = call BeautifulSoup file stri... | from bs4 import BeautifulSoup
import requests
from datetime import datetime
from time import sleep
from modules.gc_bucket import download_blob, upload_blob
def open_site_html_file():
# abre arquivo com toda programação
file = download_blob('site.html')
site = BeautifulSoup(file, 'lxml')
return ... | Python | zaydzuhri_stack_edu_python |
string 하지만 이 공간이동 장치는 이동 거리를 급격하게 늘릴 경우 기계에 심각한 결함이 발생하는 단점이 있어서, 이전 작동시기에 k광년을 이동하였을 때는 k-1 , k 혹은 k+1 광년만을 다시 이동할 수 있다. 예를 들어, 이 장치를 처음 작동시킬 경우 -1 , 0 , 1 광년을 이론상 이동할 수 있으나 사실상 음수 혹은 0 거리만큼의 이동은 의미가 없으므로 1 광년을 이동할 수 있으며, 그 다음에는 0 , 1 , 2 광년을 이동할 수 있는 것이다. ( 여기서 다시 2광년을 이동한다면 다음 시기엔 1, 2, 3 광년을 이동할 수 있다. 김우현은 공간이동 장치 ... | """
하지만 이 공간이동 장치는 이동 거리를 급격하게 늘릴 경우 기계에 심각한 결함이 발생하는 단점이 있어서,
이전 작동시기에 k광년을 이동하였을 때는 k-1 , k 혹은 k+1 광년만을 다시 이동할 수 있다.
예를 들어, 이 장치를 처음 작동시킬 경우 -1 , 0 , 1 광년을 이론상 이동할 수 있으나 사실상 음수 혹은 0 거리만큼의 이동은 의미가 없으므로 1 광년을 이동할 수 있으며,
그 다음에는 0 , 1 , 2 광년을 이동할 수 있는 것이다. ( 여기서 다시 2광년을 이동한다면 다음 시기엔 1, 2, 3 광년을 이동할 수 있다.
김우현은 공간이동 장치... | Python | zaydzuhri_stack_edu_python |
function export_correlation_table output_path=PATH_CORR
begin
set df = call build_correlation_table
to csv df string { output_path }
end function | def export_correlation_table(output_path=PATH_CORR):
df = build_correlation_table()
df.to_csv(f'{output_path}') | Python | nomic_cornstack_python_v1 |
function __init__ self library_dir=none
begin
set library_dir = if expression library_dir then call Path library_dir else call _default_podcast_library_dir
if not call is_dir
begin
raise call LibraryNotFoundException string Library directory ' { library_dir } ' not found
end
set library_dir = library_dir
set library_fi... | def __init__(self, library_dir=None):
library_dir = pathlib.Path(library_dir) if library_dir else PodcastLibrary._default_podcast_library_dir()
if not library_dir.is_dir():
raise LibraryNotFoundException(f"Library directory '{library_dir}' not found")
self.library_dir = library_dir
... | Python | nomic_cornstack_python_v1 |
comment Algorithm to minimize the weighted sum of the completion time of
comment a number of jobs. The jobs have positive and integral weights
comment and lengths, but they are NOT distinct, so ties must be dealt with.
comment The algorithm should schedules jobs in decreasing order of the
comment difference (weight/len... | ## Algorithm to minimize the weighted sum of the completion time of
## a number of jobs. The jobs have positive and integral weights
## and lengths, but they are NOT distinct, so ties must be dealt with.
##
## The algorithm should schedules jobs in decreasing order of the
## difference (weight/length).
##
## Tie... | Python | zaydzuhri_stack_edu_python |
function is_divide_operator self
begin
if not call is_operator
begin
return false
end
return call get_subtype == OPERATOR_DIVIDE_ID
end function | def is_divide_operator(self):
if not self.is_operator():
return False
return self.get_subtype() == _mexp_operators.OPERATOR_DIVIDE_ID | Python | nomic_cornstack_python_v1 |
import numpy as np
from models import pso
import itertools
import matplotlib.pyplot as plt
from params import showout
set a1_percent = 0.5
set pop = 20
set time = 200
set resolution = 10
set mat = call empty shape=tuple resolution resolution
set a_ = list linear space 0 4 resolution
set w_ = list linear space - 1 1 res... | import numpy as np
from models import pso
import itertools
import matplotlib.pyplot as plt
from params import showout
a1_percent = 0.5
pop = 20
time = 200
resolution = 10
mat = np.empty(shape=(resolution, resolution))
a_ = list(np.linspace(0, 4, resolution))
w_ = list(np.linspace(-1, 1, resolution))
for i, total_a ... | Python | zaydzuhri_stack_edu_python |
function ProcessCloudPolicyForExtensions self request response token_info username=none
begin
comment Send one PolicyFetchResponse for each extension that has
comment configuration data at the server.
set ids = call ListMatchingComponents policy_type
if not ids
begin
comment Fetch the ids from the policy JSON, if none ... | def ProcessCloudPolicyForExtensions(self, request, response, token_info,
username=None):
# Send one PolicyFetchResponse for each extension that has
# configuration data at the server.
ids = self.server.ListMatchingComponents(request.policy_type)
if not ids:
# ... | Python | nomic_cornstack_python_v1 |
function calc_timesteps path=string ./
begin
import os , glob
set path = string path
set fn_list = list join path path string moments1.out join path path string moments0.out join path path string domain000 string moments1.out join path path string domain000 string moments0.out
for tuple i fn in enumerate fn_list
begin
... | def calc_timesteps(path='./'):
import os, glob
path = str(path)
fn_list = [os.path.join(path,'moments1.out'),
os.path.join(path,'moments0.out'),
os.path.join(path,'domain000','moments1.out'),
os.path.join(path,'domain000','moments0.out')]
for i,fn in enumer... | Python | nomic_cornstack_python_v1 |
function paintFreeMode self redfunc greenfunc bluefunc alphafunc maximumValue=- 1
begin
set dc = call MemoryDC
call SelectObject buffer
set d = maxx / decimal maximumValue
if d < 1
begin
set d = 1
end
if not background
begin
info string Constructing background from minval = %d, maxval = %d % tuple minval maxval
set bac... | def paintFreeMode(self, redfunc, greenfunc, bluefunc, alphafunc, maximumValue = -1):
self.dc = wx.MemoryDC()
self.dc.SelectObject(self.buffer)
d = self.maxx / float(maximumValue)
if d < 1:d = 1
if not self.background:
Logging.info("Constructing background from minval = %d, maxval = %d" % (self.minval, sel... | Python | nomic_cornstack_python_v1 |
function get_fromOrderKey in_rec session timeout=60.0 attempts=4
begin
comment Get the "Order Key" and "Downlink Segment ID" from the CSV file record
set order_key = in_rec at string Order Key
set download_segment_id = in_rec at string Downlink Segment ID
comment Create the query with the downlink segment ID
set query ... | def get_fromOrderKey(in_rec, session, timeout=60.0, attempts=4):
# Get the "Order Key" and "Downlink Segment ID" from the CSV file record
order_key = in_rec['Order Key']
download_segment_id = in_rec['Downlink Segment ID']
# Create the query with the downlink segment ID
query = "RCM.DOWNLIN... | Python | nomic_cornstack_python_v1 |
function optimalPoint magic dist
begin
comment Write your code here
comment loop through all starting points
comment map to dict the starting point and the ending amount
function test x
begin
set fuel = 0
for j in range length magic
begin
set fuel = fuel + magic at x
set fuel = fuel - dist at x
if fuel < 0
begin
return... | def optimalPoint(magic, dist):
# Write your code here
# loop through all starting points
### map to dict the starting point and the ending amount
###
def test(x):
fuel = 0
for j in range(len(magic)):
fuel += magic[x]
fuel -= dist[x... | Python | zaydzuhri_stack_edu_python |
function test_method_not_allowed self
begin
set resp = post string /orders/0
assert equal status_code HTTP_405_METHOD_NOT_ALLOWED
end function | def test_method_not_allowed(self):
resp = self.app.post('/orders/0')
self.assertEqual(resp.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) | Python | nomic_cornstack_python_v1 |
function mie_S12 coeffs u
begin
set tuple pin tin = call mie_pt u nmax
set n = array range 1 nmax + 1 dtype=float
set n2 = 2 * n + 1 / n * n + 1
set pin = pin * n2
set tin = tin * n2
set S1 = dot an pin + dot bn tin
set S2 = dot an tin + dot bn pin
return tuple S1 S2
end function | def mie_S12(coeffs,u):
(pin,tin) = mie_pt(u,coeffs.nmax)
n = arange(1, coeffs.nmax+1, dtype=float)
n2 = (2*n+1)/(n*(n+1))
pin *= n2
tin *= n2
S1 = dot(coeffs.an,pin)+dot(coeffs.bn,tin)
S2 = dot(coeffs.an,tin)+dot(coeffs.bn,pin)
return (S1, S2) | Python | nomic_cornstack_python_v1 |
function __hide_from_get self
begin
return tuple all all all
end function | def __hide_from_get(self):
return self.db_hide_from_players.all(), self.db_hide_from_objects.all(), self.db_hide_from_channels.all() | Python | nomic_cornstack_python_v1 |
function test_501
begin
assert call spiralize 501 == 83960501
end function | def test_501():
assert homework.spiralize(501) == 83960501 | Python | nomic_cornstack_python_v1 |
function writeEntry DATA
begin
global printedDBError
comment Get the current time in the RFC3339 format for InfluxDB
set t = call utcnow
comment Z is for Zulu timezone, idk why I need it but stackoverflow says to
set t = call isoformat string T + string Z
comment Make the json body to send to the database
set json_body... | def writeEntry(DATA):
global printedDBError
# Get the current time in the RFC3339 format for InfluxDB
t = datetime.datetime.utcnow()
t = t.isoformat("T") + "Z" # Z is for Zulu timezone, idk why I need it but stackoverflow says to
# Make the json body to send to the database
json_body = []
... | Python | nomic_cornstack_python_v1 |
function CheckIfWiredConnecting self
begin
if connecting_thread
begin
return is_connecting
end
else
begin
return false
end
end function | def CheckIfWiredConnecting(self):
if self.wired.connecting_thread:
return self.wired.connecting_thread.is_connecting
else:
return False | Python | nomic_cornstack_python_v1 |
while number != string quit
begin
set square = integer number ^ 2
print square
set number = input string type a number or 'quit':
end | while number != "quit":
square = int(number) ** 2
print(square)
number = input("type a number or 'quit': ")
| Python | zaydzuhri_stack_edu_python |
function macaulay_duration flows discount_rate
begin
set discounted_flows = call discount index discount_rate * call DataFrame flows
set weights = discounted_flows / sum
return call average index weights=iloc at tuple slice : : 0
end function | def macaulay_duration(flows, discount_rate):
discounted_flows = discount(flows.index, discount_rate)*pd.DataFrame(flows)
weights = discounted_flows/discounted_flows.sum()
return np.average(flows.index, weights=weights.iloc[:,0]) | Python | nomic_cornstack_python_v1 |
function _get_elements self
begin
set address_elements = dict string organisation format string {}{} if expression organisation then organisation else string if expression department then string + department else string ; string sub-building name sub_building_name ; string building name building_name ; string buildin... | def _get_elements(self):
address_elements = {
'organisation': "{}{}".format(
self.organisation if self.organisation else "",
'\n' + self.department if self.department else "",
),
'sub-... | Python | nomic_cornstack_python_v1 |
from BankingMethods import account_balance , deposit , withdraw , change_pin , pin_checker
from Members import members
from Checker import pin_validator
function user_options choice
begin
if choice == string A
begin
call account_balance
end
else
if choice == string B
begin
call deposit
end
else
if choice == string C
be... | from BankingMethods import account_balance, deposit, withdraw, change_pin, pin_checker
from Members import members
from Checker import pin_validator
def user_options(choice):
if choice == "A":
account_balance()
elif choice == "B":
deposit()
elif choice == "C":
withdraw()
elif c... | Python | zaydzuhri_stack_edu_python |
function instance_id self
begin
return get pulumi self string instance_id
end function | def instance_id(self) -> pulumi.Output[str]:
return pulumi.get(self, "instance_id") | Python | nomic_cornstack_python_v1 |
function is_on self
begin
set attr = _sensor at 0
set val = get attribute vehicle attr
if attr == string bulb_failures
begin
return length val > 0
end
else
if attr in list string doors string windows
begin
return any list comprehension val at key for key in val if string Open in key
end
else
begin
return val != string ... | def is_on(self):
attr = self._sensor[0]
val = getattr(self.vehicle, attr)
if attr == 'bulb_failures':
return len(val) > 0
elif attr in ['doors', 'windows']:
return any([val[key] for key in val if 'Open' in key])
else:
return val != 'Normal' | Python | nomic_cornstack_python_v1 |
function get_pages_with_http_info self account_id document_id envelope_id **kwargs
begin
set all_params = list string account_id string document_id string envelope_id string count string dpi string max_height string max_width string nocache string show_changes string start_position
append all_params string callback
app... | def get_pages_with_http_info(self, account_id, document_id, envelope_id, **kwargs):
all_params = ['account_id', 'document_id', 'envelope_id', 'count', 'dpi', 'max_height', 'max_width', 'nocache', 'show_changes', 'start_position']
all_params.append('callback')
all_params.append('_return_http_dat... | Python | nomic_cornstack_python_v1 |
comment 1536. Minimum Swaps to Arrange a Binary Grid
comment Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
comment A grid is said to be valid if all the cells above the main diagonal are zeros.
comment Return the minimum number of steps needed to make the grid valid... | # 1536. Minimum Swaps to Arrange a Binary Grid
# Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
# A grid is said to be valid if all the cells above the main diagonal are zeros.
# Return the minimum number of steps needed to make the grid valid, or -1 if the grid c... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from activators import SigmoidActivator , TanhActivator , SoftmaxActivator
class LstmLayer
begin
function __init__ self input_width state_width output_width learning_rate penaltyL2 momentum
begin
set input_width = input_width
set state_width = state_width
set output_width = output_width
set learning_... | import numpy as np
from activators import SigmoidActivator, TanhActivator, SoftmaxActivator
class LstmLayer():
def __init__(self, input_width, state_width, output_width,
learning_rate, penaltyL2, momentum):
self.input_width = input_width
self.state_width = state_width
self... | Python | zaydzuhri_stack_edu_python |
function main
begin
set x0 = 0.9
set x = list list 0 0 x0 list 0 1 x0 list 1 0 x0 list 1 1 x0
set D = list 0 1 1 0
call backpropagation x 0.2 0.3 - 0.9 0.1 D
end function
function backpropagation x w1 w2 w0 eta D
begin
set itera = 0
while true
begin
set tuple suma d_acum = tuple 0 0
for i in range 0 4
begin
set tuple x... | def main():
x0 = 0.9
x = [[0,0,x0],[0,1,x0],[1,0,x0],[1,1,x0]]
D = [0,1,1,0]
backpropagation(x,0.2,0.3,-0.9,0.1,D)
def backpropagation(x,w1, w2, w0, eta, D):
itera = 0
while(True):
suma,d_acum = 0,0
for i in range(0, 4):
x1,x2,x0 = x[i]
suma = (w0 * x0)... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function countBits self n
begin
set res = list
function myfun x
begin
set count = 0
while x != 0
begin
set tuple x y = divide mod x 2
if y == 1
begin
set count = count + 1
end
end
return count
end function
for i in range n + 1
begin
comment x =
append res call myfun i
end
return res
end function
e... | class Solution:
def countBits(self, n: int) -> List[int]:
res = []
def myfun(x):
count = 0
while x != 0:
x, y = divmod(x, 2)
if y == 1:
count += 1
return count
for i in range(n+1):
... | Python | zaydzuhri_stack_edu_python |
function showResult processPool record result
begin
comment extract the result
set averageTime = result at 0
set waitingTimeDict = result at 1
print string ----------------------------------
print string Name BT AT priority
for item in processPool
begin
print item
end
print string ----------------------------------
pri... | def showResult(processPool,record, result):
#extract the result
averageTime = result[0]
waitingTimeDict = result[1]
print("\n\n----------------------------------")
print(" Name BT AT priority ")
for item in processPool:
print(item)
print("---------------------------... | Python | nomic_cornstack_python_v1 |
import random
class Dice
begin
function roll self
begin
set first = random integer 1 6
set second = random integer 1 6
return tuple first second
end function
end class
set dice = call Dice
print call roll | import random
class Dice:
def roll(self):
first=random.randint(1, 6)
second=random.randint(1, 6)
return first, second
dice=Dice()
print(dice.roll()) | Python | zaydzuhri_stack_edu_python |
function get_weather_data filename=string weather.csv **kwargs
begin
if string datapath not in kwargs
begin
set kwargs at string datapath = directory name path __file__
end
set file = join path kwargs at string datapath filename
comment download example weather data file in case it does not yet exist
if not is file pat... | def get_weather_data(filename='weather.csv', **kwargs):
if 'datapath' not in kwargs:
kwargs['datapath'] = os.path.dirname(__file__)
file = os.path.join(kwargs['datapath'], filename)
# download example weather data file in case it does not yet exist
if not os.path.isfile(file):
req = r... | Python | nomic_cornstack_python_v1 |
function get_running_containers unit namespace
begin
set config = dict string host call get_random_node_ip
try
begin
set service_info = decode check output list string kubectl string --namespace namespace string get string service unit string -o string json string utf-8
set service = loads service_info
set ports = dict... | def get_running_containers(unit, namespace):
config = {'host': get_random_node_ip()}
try:
service_info = check_output(['kubectl',
'--namespace', namespace,
'get',
'service',
... | Python | nomic_cornstack_python_v1 |
import re
import datetime
from dateutil.parser import parse
function local_utcoffset
begin
string Returns a timedelta rounded to the nearest minute of the ACTUAL difference between localtime and utc time. For some crazy reason, there is no simple way to do this in python. I've read dozens of articles. And time.daylight... | import re
import datetime
from dateutil.parser import parse
def local_utcoffset():
""" Returns a timedelta rounded to the nearest minute of the ACTUAL
difference between localtime and utc time. For some crazy reason, there is
no simple way to do this in python. I've read dozens of articles.
And time.... | Python | zaydzuhri_stack_edu_python |
function account
begin
set user = format string {} {} session at string user at string first_name session at string user at string last_name
set reviews = list find reviews dict string reviewed_by user
string Code for pagination is from https://gist.github.com/mozillazg/ 69fb40067ae6d80386e10e105e6803c9
set tuple page ... | def account():
user = "{} {}".format(
session['user']['first_name'], session['user']['last_name'])
reviews = list(mongo.db.reviews.find({"reviewed_by": user}))
"""
Code for pagination is from https://gist.github.com/mozillazg/
69fb40067ae6d80386e10e105e6803c9
"""
page, per_page, o... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: UTF-8 -*-
import mpd
from cgi import escape
from sys import argv
function item_track t
begin
try
begin
set title = string %s - %s % tuple t at string artist t at string title
end
except any
begin
try
begin
set title = t at string title
end
except any
begin
set title = sp... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import mpd
from cgi import escape
from sys import argv
def item_track(t):
try:
title = "%s - %s" % (t['artist'], t['title'])
except:
try:
title = t['title']
except:
title = t['file'].split('/')[-1]
if t == m.currentsong():
title = '► ' +... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import rospy
from geometry_msgs.msg import Pose , PoseArray
from nav_msgs.msg import Path
class Path2PoseArray extends object
begin
function __init__ self
begin
set value = 0
call init_node string path2posearray
set pub = call Publisher string plan_posearray PoseArray queue_size=1
call Subs... | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import Pose, PoseArray
from nav_msgs.msg import Path
class Path2PoseArray(object):
def __init__(self):
self.value = 0
rospy.init_node('path2posearray')
self.pub = rospy.Publisher('plan_posearray', PoseArray, queue_size = 1)
... | Python | zaydzuhri_stack_edu_python |
function resample_vertline_dist self M
begin
comment Get original distribution of vertical lines
set vertline = call vertline_dist
comment Get maximal vertical line length
set L_max = call max_vertlength
comment Get resampled distribution
set resampled_dist = zeros length vertline
set resampled_dist at slice : L_max +... | def resample_vertline_dist(self, M):
# Get original distribution of vertical lines
vertline = self.vertline_dist()
# Get maximal vertical line length
L_max = self.max_vertlength()
# Get resampled distribution
resampled_dist = np.zeros(len(vertline))
resampled... | Python | nomic_cornstack_python_v1 |
function hdflitter
begin
try
begin
with open string hdflitter.json string r as f
begin
set inputs = load json f object_pairs_hook=OrderedDict
set orixe_name = inputs at string origin
set buffer_name = inputs at string buffer
set dt = inputs at string acumulation_time
set path_lags = inputs at string path_lag_files
set ... | def hdflitter():
try:
with open('hdflitter.json', 'r') as f:
inputs = json.load(f, object_pairs_hook=OrderedDict)
orixe_name = inputs['origin']
buffer_name = inputs['buffer']
dt = inputs['acumulation_time']
path_lags = inputs['path_lag_files']
... | Python | nomic_cornstack_python_v1 |
function traced_grid_from_grid self grid
begin
return grid - call deflections_2d_from_grid grid=grid
end function | def traced_grid_from_grid(self, grid):
return grid - self.deflections_2d_from_grid(grid=grid) | Python | nomic_cornstack_python_v1 |
function fibo3 n
begin
set f = list 0 1
for i in range 2 n + 1
begin
append f f at i - 1 + f at i - 2
end
return f at n
end function
print call fibo3 7
set f = list 0 1
for i in range 2 7 + 1
begin
append f f at i - 1 + f at i - 2
end
print f at 7 | def fibo3(n):
f = [0, 1]
for i in range(2, n + 1):
f.append(f[i-1] + f[i-2])
return f[n]
print(fibo3(7))
f = [0, 1]
for i in range(2, 7 + 1):
f.append(f[i-1] + f[i-2])
print(f[7]) | Python | zaydzuhri_stack_edu_python |
function on event
begin
function decorator method
begin
append _handlers call Handler event=event method=method
return method
end function
return decorator
end function | def on(event: str) -> Callable[[Callable], Callable]:
def decorator(method: Callable) -> Callable:
_handlers.append(Handler(event=event, method=method))
return method
return decorator | 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.