code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
while true
begin
set n = integer input string 정수를 입력하시오:
if n == - 99
begin
break
end
append nlist n
end
print length nlist string 개의 유효한 정수 중 가장 큰 정수는 max nlist string 이고 string 가장 작은 정수는 min nlist string 입니다. | while True:
n = int(input("정수를 입력하시오: "))
if n == -99:
break
nlist.append(n)
print(len(nlist),"개의 유효한 정수 중 가장 큰 정수는",max(nlist),"이고","가장 작은 정수는",min(nlist),"입니다.")
| Python | zaydzuhri_stack_edu_python |
string REFERENCES : 1)https://arxiv.org/abs/1412.5567 ----- DEEP_SPEECH_1 2)https://github.com/chagge/DeepSpeech-1
import os
import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import ctc_ops
from math import ceil
from collections import OrderedDict
from xdg import BaseDirector... | """REFERENCES : 1)https://arxiv.org/abs/1412.5567 ----- DEEP_SPEECH_1
2)https://github.com/chagge/DeepSpeech-1
"""
import os
import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import ctc_ops
from math import ceil
from collections import OrderedDict
from xdg im... | Python | zaydzuhri_stack_edu_python |
import serial
import serial.tools.list_ports
import asyncio
import struct
import typing
comment seconds
set SLEEP_TIME = 0.2
set ANALOG2VOLT = 3.3 / 4095.0
set VOLT2TEMP = 1000.0 / 5.0
set CMD_SUBMIT_CODE = 240
set CMD_ERROR_CODE = 224
set CMD_ACQ = 250
function get_ports
begin
return list comprehension tuple port name... | import serial
import serial.tools.list_ports
import asyncio
import struct
import typing
SLEEP_TIME = 0.2 # seconds
ANALOG2VOLT = 3.3 / 4095.0
VOLT2TEMP = (1000.0 / 5.0)
CMD_SUBMIT_CODE = 0xF0
CMD_ERROR_CODE = 0xE0
CMD_ACQ = 0xFA
def get_ports() -> typing.List[typing.Tuple[str, str]]:
return [(port, name) for (... | Python | zaydzuhri_stack_edu_python |
function get_welcome_response
begin
set session_attributes = dict
set card_title = string Welcome
set speech_output = string Welcome to ze jukebox
comment If the user either does not reply to the welcome message or says something
comment that is not understood, they will be prompted again with this text.
set reprompt_... | def get_welcome_response():
session_attributes = {}
card_title = "Welcome"
speech_output = "Welcome to ze jukebox"
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "Welcome to ze juk... | Python | nomic_cornstack_python_v1 |
function radians self
begin
call _setDegreesPerAU 2 * pi
end function | def radians(self):
self._setDegreesPerAU(2*math.pi) | Python | nomic_cornstack_python_v1 |
function _job_get_state self job_id
begin
comment check if we have already reach a terminal state
if jobs at job_id at string state == CANCELED or jobs at job_id at string state == FAILED or jobs at job_id at string state == DONE
begin
return jobs at job_id at string state
end
comment check if we can / should update
if... | def _job_get_state(self, job_id):
# check if we have already reach a terminal state
if self.jobs[job_id]['state'] == saga.job.CANCELED \
or self.jobs[job_id]['state'] == saga.job.FAILED \
or self.jobs[job_id]['state'] == saga.job.DONE:
return self.jobs[job_id]['state']
... | Python | nomic_cornstack_python_v1 |
import sys
import os
import random
from collections import Counter
class MetaPathGenerator
begin
function __init__ self
begin
set id_author = dictionary
set id_conf = dictionary
set author_coauthorlist = dictionary
set conf_authorlist = dictionary
set author_conflist = dictionary
set paper_author = dictionary
set autho... | import sys
import os
import random
from collections import Counter
class MetaPathGenerator:
def __init__(self):
self.id_author = dict()
self.id_conf = dict()
self.author_coauthorlist = dict()
self.conf_authorlist = dict()
self.author_conflist = dict()
self.paper_author = dict()
self.author_paper = dict... | Python | zaydzuhri_stack_edu_python |
async function game self
begin
pass
end function | async def game(self):
pass | Python | nomic_cornstack_python_v1 |
class FingerTable
begin
function __init__ self my_id
begin
set table = list
for i in range m
begin
set x = 2 ^ i
set entry = my_id + x % 2 ^ m
append table list entry none
end
end function
function get_table_enteries self index
begin
return table at index
end function
function set_successor self node index
begin
set ta... | class FingerTable:
def __init__(self, my_id):
self.table = list()
for i in range(m):
x = (2**i)
entry = (my_id + x) % (2**m)
self.table.append( [entry, None] )
def get_table_enteries(self, index):
return self.table[index]
def set_successor(self, ... | Python | zaydzuhri_stack_edu_python |
async function get_locator_info self reset_inactivity_timeout=true response_timeout_in_seconds=none
begin
set command = call _create_read_locator_command sequence_number=call _get_and_increment_command_sequence_number wait_for_response=true reset_inactivity_timeout=reset_inactivity_timeout
set response_packet = await c... | async def get_locator_info(self,
reset_inactivity_timeout=True,
response_timeout_in_seconds=None):
command = _create_read_locator_command(sequence_number=self._get_and_increment_command_sequence_number(),
... | Python | nomic_cornstack_python_v1 |
function GetCIPDFromCache instance_id=CIPD_INSTANCE_ID
begin
set cache_dir = join path call GetCacheDir string cipd
set bin_cache = call CipdCache cache_dir
set key = tuple instance_id
set ref = call Lookup key
set default ref string cipd:// + instance_id
return path
end function | def GetCIPDFromCache(instance_id=CIPD_INSTANCE_ID):
cache_dir = os.path.join(path_util.GetCacheDir(), 'cipd')
bin_cache = CipdCache(cache_dir)
key = (instance_id,)
ref = bin_cache.Lookup(key)
ref.SetDefault('cipd://' + instance_id)
return ref.path | Python | nomic_cornstack_python_v1 |
function stop self
begin
if sock is not none
begin
close sock
end
set sock = none
end function | def stop( self ):
if self.sock is not None:
self.sock.close()
self.sock = None | Python | nomic_cornstack_python_v1 |
function __init__ self geometry envelope occupancy hvac rc_model comfort internal_loads age solar gv
begin
set geometry = geometry
set architecture = call EnvelopeProperties envelope
comment FIXME: rename to uses!
set occupancy = occupancy
set hvac = hvac
set rc_model = rc_model
set comfort = comfort
set internal_loads... | def __init__(self, geometry, envelope, occupancy, hvac,
rc_model, comfort, internal_loads, age, solar, gv):
self.geometry = geometry
self.architecture = EnvelopeProperties(envelope)
self.occupancy = occupancy # FIXME: rename to uses!
self.hvac = hvac
self.rc_mod... | Python | nomic_cornstack_python_v1 |
function _pool_op self in_obj pool_axes
begin
set manual_pad = ordered dictionary list comprehension tuple name tuple 0 0 for ax in axes
set tuple pad_int extra_pad = call _get_pad_int pool_axes
update manual_pad extra_pad
if any generator expression pad != tuple 0 0 for pad in values manual_pad
begin
set in_obj = call... | def _pool_op(self, in_obj, pool_axes):
manual_pad = collections.OrderedDict([(ax.name, (0, 0)) for ax in in_obj.axes])
pad_int, extra_pad = self._get_pad_int(pool_axes)
manual_pad.update(extra_pad)
if any((pad != (0, 0)) for pad in manual_pad.values()):
in_obj = ng.pad(in_obj... | Python | nomic_cornstack_python_v1 |
function runTests self
begin
try
begin
set testPath = call getCurrentProject at string testPath
run list string python testPath timeout=1.5
return false
end
except TimeoutExpired
begin
return true
end
end function | def runTests(self):
try:
testPath = self.getCurrentProject()["testPath"]
subprocess.run(['python', testPath], timeout=1.5)
return False
except subprocess.TimeoutExpired:
return True | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
comment location of big edge list csv
set filename = string E:\Downloads\PaperReferences.txt.gz
comment Use pandas.read_csv: can read compressed csvs, and can iterate chunks to conserve
set data_iterator = read csv filename delimiter=string chunksize=1000000 compression=string gz... | import pandas as pd
import numpy as np
# location of big edge list csv
filename = "E:\Downloads\PaperReferences.txt.gz"
# Use pandas.read_csv: can read compressed csvs, and can iterate chunks to conserve
data_iterator = pd.read_csv(filename, delimiter='\t', chunksize=1000000, compression='gzip', dtype='Int64')
# usec... | Python | zaydzuhri_stack_edu_python |
import json
set fill_path = string E:\PyCharm2019\data-analysis\start_pandas\herolist.json
set data_str = read open fill_path encoding=string utf-8
if starts with data_str string
begin
set data_str = decode encode data_str string utf-8 at slice 3 : : string utf-8
end
set data_list = loads data_str encoding=string u... | import json
fill_path = 'E:\PyCharm2019\data-analysis\start_pandas\herolist.json'
data_str = open(fill_path, encoding='utf-8').read()
if data_str.startswith(u'\ufeff'):
data_str = data_str.encode('utf-8')[3:].decode('utf-8')
data_list = json.loads(data_str, encoding='utf-8')
js = json.dumps(data_lis... | Python | zaydzuhri_stack_edu_python |
function visualise_colors
begin
call init
comment parameters
set colors = call load_palette_from_pal_file string ../../ + PALETTE_DIR
set font = call Font string ../../ + FONT_DIR 20
set size = 64
comment open pygame window and fill it with colors
set window = call set_mode tuple length colors * size size
call fill tup... | def visualise_colors():
pg.init()
# parameters
colors = load_palette_from_pal_file("../../" + PALETTE_DIR)
font = pg.font.Font("../../" + FONT_DIR, 20)
size = 64
# open pygame window and fill it with colors
window = pg.display.set_mode((len(colors) * size, size))
window.fill((0, 0, 0))
for i, col in enumerat... | Python | nomic_cornstack_python_v1 |
from search.models import *
import sys
import urllib2
import json
import re
import xml.etree.ElementTree as ET
from TEX.settings import SECRET_AWS_KEY
set URL_STUB = string https://www.googleapis.com/books/v1/volumes?q=isbn:
set USER_AGENT = list tuple string User-agent string Mozilla/5.0
set FNTCVR_STUB = string ./sta... | from search.models import *
import sys
import urllib2
import json
import re
import xml.etree.ElementTree as ET
from TEX.settings import SECRET_AWS_KEY
URL_STUB="https://www.googleapis.com/books/v1/volumes?q=isbn:"
USER_AGENT=[("User-agent", "Mozilla/5.0")]
FNTCVR_STUB= './static/frontcover_%s.jpg'
THUMB_STUB= './stati... | Python | zaydzuhri_stack_edu_python |
function getlines self filename start end include_comments=false
begin
if start < 1
begin
raise call IndexError string start must be >= 1
end
call _init_file filename
if include_comments
begin
set start = call find_comment_block_start filename start
end
comment shift to zero-based index for cache contents
set start = s... | def getlines(self, filename, start, end, include_comments=False):
if start < 1:
raise IndexError('start must be >= 1')
self._init_file(filename)
if include_comments:
start = self.find_comment_block_start(filename, start)
start -= 1 # shift to zero-based index for... | Python | nomic_cornstack_python_v1 |
function __set__ self instance value
begin
raise call NotImplementedError string Can't change the current date
end function | def __set__(self, instance, value):
raise NotImplementedError("Can't change the current date") | Python | nomic_cornstack_python_v1 |
string Unit tests path where testing Environment.
import unittest
import gym
from environments import Environment
from models import Vector
class TestEnvironment extends TestCase
begin
function setUp self
begin
comment An observation space
set observation_space = call Discrete 7
comment Default reward
set default_rewar... | """
Unit tests path where testing Environment.
"""
import unittest
import gym
from environments import Environment
from models import Vector
class TestEnvironment(unittest.TestCase):
def setUp(self):
# An observation space
observation_space = gym.spaces.Discrete(7)
# Default reward
... | Python | zaydzuhri_stack_edu_python |
import face_recognition
import cv2 as cv
import threading
from time import ctime , sleep
import os
import geocoder
import time
import pygame
import serial
set src = string C:/Users/LattePanda/Desktop/FaceRecognization/resourses/image/Robert.jpg
set RecognitionMusic = string recognition.mp3
set WarningMusic = string war... | import face_recognition
import cv2 as cv
import threading
from time import ctime,sleep
import os
import geocoder
import time
import pygame
import serial
src = 'C:/Users/LattePanda/Desktop/FaceRecognization/resourses/image/Robert.jpg'
RecognitionMusic = 'recognition.mp3'
WarningMusic = 'warning.mp3'
SuccessMusic = 'face... | Python | zaydzuhri_stack_edu_python |
function check text
begin
string Check the text.
set err = string misc.not_guilty
set msg = string 'not guilty beyond a reasonable doubt' is an ambiguous phrasing.
set regex = string not guilty beyond (a |any )?reasonable doubt
return call existence_check text list regex err msg
end function | def check(text):
"""Check the text."""
err = "misc.not_guilty"
msg = u"'not guilty beyond a reasonable doubt' is an ambiguous phrasing."
regex = r"not guilty beyond (a |any )?reasonable doubt"
return existence_check(text, [regex], err, msg) | Python | jtatman_500k |
function valid_datastores cls
begin
set dblist = list directory DATASTORE_DIR
return dblist
end function | def valid_datastores(cls):
dblist = os.listdir(DATASTORE_DIR)
return dblist | Python | nomic_cornstack_python_v1 |
function gestisciAssociazioni request assoType viaggiIds
begin
set viaggiIds = list map int viaggiIds
set user = user
if not call has_perm string tam.change_viaggio
begin
error request string Non hai il permesso di modificare i viaggi.
return call HttpResponseRedirect reverse string tamCorse
end
call associate assoType... | def gestisciAssociazioni(request, assoType, viaggiIds):
viaggiIds = list(map(int, viaggiIds))
user = request.user
if not user.has_perm("tam.change_viaggio"):
messages.error(request, "Non hai il permesso di modificare i viaggi.")
return HttpResponseRedirect(reverse("tamCorse"))
associate(... | Python | nomic_cornstack_python_v1 |
function test_number65 x y
begin
if x == 65 or y == 65 or x + y == 65
begin
return true
end
else
begin
return false
end
end function
print call test_number65 65 2
print call test_number65 64 1
print call test_number65 6 5 | def test_number65(x, y):
if x == 65 or y == 65 or (x + y) == 65:
return True
else :
return False
print(test_number65(65, 2))
print(test_number65(64, 1))
print(test_number65(6, 5)) | Python | zaydzuhri_stack_edu_python |
import re , logging , os , math , functools
set inputs = call __import__ string inputs
set logger = call getLogger string day6
set LOGLEVEL = upper get environ string LOGLEVEL string INFO
call basicConfig level=LOGLEVEL
set INPUT = call get_input 2020 6 split=string
set EXAMPLE = call get_input 2020 6 true split=string... | import re, logging, os, math, functools
inputs = __import__("inputs")
logger = logging.getLogger('day6')
LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper()
logging.basicConfig(level=LOGLEVEL)
INPUT = inputs.get_input(2020, 6, split='\n\n')
EXAMPLE = inputs.get_input(2020, 6, True, split='\n\n')
def part_one(grou... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import math
set t = list 5 6 7 8 9 10 11 12
comment Creating the list. Logorithm of sample size. Will be plotted in x-axist_0 = [16.000000,22.500000,20.750000,28.125000,61.812500,119.750000,230.656250,384.000000]
set t_1 = list 11.0 14.5 16.75 40.75 55.4375 96.40625 16... | import numpy as np
import matplotlib.pyplot as plt
import math
t = [5,6,7,8,9,10,11,12]
#Creating the list. Logorithm of sample size. Will be plotted in x-axist_0 = [16.000000,22.500000,20.750000,28.125000,61.812500,119.750000,230.656250,384.000000]
t_1 = [11.000000,14.500000,16.750000,40.750000,55.437500,96.406250... | Python | zaydzuhri_stack_edu_python |
function post self request
begin
set createform = call QuotationForm POST
if call is_valid
begin
set req = dict string name cleaned_data at string name ; string email cleaned_data at string email ; string phone cleaned_data at string phone ; string vehiculeModel cleaned_data at string vehiculeModel ; string vehiculeYea... | def post(self, request):
self.createform = forms.QuotationForm(request.POST)
if self.createform.is_valid():
req = {
"name": self.createform.cleaned_data['name'],
"email": self.createform.cleaned_data['email'],
"phone": self.createform.cleaned_d... | Python | nomic_cornstack_python_v1 |
import torch
from torch.utils.tensorboard import SummaryWriter
import time
import numpy as np
import torch.nn as nn
import os
import matplotlib.pyplot as plt
import matplotlib._color_data as mcd
class MLPAutoEncoder extends Module
begin
function __init__ self NN_SIZE=512
begin
call __init__
set layer_1 = linear 16 NN_S... | import torch
from torch.utils.tensorboard import SummaryWriter
import time
import numpy as np
import torch.nn as nn
import os
import matplotlib.pyplot as plt
import matplotlib._color_data as mcd
class MLPAutoEncoder(nn.Module):
def __init__(self, NN_SIZE = 512):
super(MLPAutoEncoder, self).__init__()
... | Python | zaydzuhri_stack_edu_python |
function wait_for_relation service_name relation_name timeout=120
begin
string Wait `timeout` seconds for a given relation to come up.
set start_time = time
while true
begin
set relation = get call unit_info service_name string relations relation_name
if relation is not none and relation at string state == string up
be... | def wait_for_relation(service_name, relation_name, timeout=120):
"""Wait `timeout` seconds for a given relation to come up."""
start_time = time.time()
while True:
relation = unit_info(service_name, 'relations').get(relation_name)
if relation is not None and relation['state'] == 'up':
... | Python | jtatman_500k |
function test_constructor_call get_token_network custom_token secret_registry_contract get_accounts channel_participant_deposit_limit token_network_deposit_limit
begin
set tuple A controller = call get_accounts 2
comment failure with no arguments
with raises TypeError
begin
call get_token_network list
end
comment failu... | def test_constructor_call(
get_token_network: Callable,
custom_token: Contract,
secret_registry_contract: Contract,
get_accounts: Callable,
channel_participant_deposit_limit: int,
token_network_deposit_limit: int,
) -> None:
(A, controller) = get_accounts(2)
# failure with no arguments... | Python | nomic_cornstack_python_v1 |
import requests
import emojis
from bs4 import BeautifulSoup
function get_article
begin
set bbc_request = get requests string https://www.bbc.com/news
set soup = call BeautifulSoup text string html.parser
set raw_article = find all find all soup string div dict string class string gs-c-promo-body gel-1/2@xs gel-1/1@m gs... | import requests
import emojis
from bs4 import BeautifulSoup
def get_article():
bbc_request = requests.get('https://www.bbc.com/news')
soup = BeautifulSoup(bbc_request.text, "html.parser")
raw_article = soup.find_all('div', {'class': 'gs-c-promo-body gel-1/2@xs gel-1/1@m gs-u-mt@m'})[0].find_all(text=True,... | Python | zaydzuhri_stack_edu_python |
string Created on 2013-4-4 @author: Bobi Pu, bobi.pu@usc.edu
import numpy
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics.metrics import accuracy_score , classification_report
class ERClassifier extends object
begin
fun... | '''
Created on 2013-4-4
@author: Bobi Pu, bobi.pu@usc.edu
'''
import numpy
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics.metrics import accuracy_score, classification_report
class ERClassifier(object):
def __init... | Python | zaydzuhri_stack_edu_python |
for i in range t
begin
set n = integer input
set n = n + 2
set flag = 1
for i in range 2 n
begin
if n % i == 0
begin
set flag = 0
end
end
comment else:
comment flag=1
if flag == 1
begin
print string Yes
end
else
begin
print string No
end
end | for i in range(t):
n=int(input())
n=n+2
flag=1
for i in range(2,n):
if n%i==0:
flag=0
#else:
# flag=1
if flag==1:
print('Yes')
else:
print('No') | Python | zaydzuhri_stack_edu_python |
comment 1> 完成 5 行内容的简单输出
comment 2> 分析每行内部的 * 应该如何处理?
comment 每行显示的星星和当前所在的行数是一致的
comment 嵌套一个小的循环,专门处理每一行中 列 的星星显示
set row = 1
set lie = 1
while row <= 5
begin
set col = 1
string 1 1 2 2 3 3 4 4 5 5
while col <= row
begin
comment print("%d"%col)
print string * end=string
set col = col + 1
end
comment print("第%d行"%row)... | # 1> 完成 5 行内容的简单输出
# 2> 分析每行内部的 * 应该如何处理?
# 每行显示的星星和当前所在的行数是一致的
# 嵌套一个小的循环,专门处理每一行中 列 的星星显示
row = 1
lie = 1
while row <= 5:
col = 1
"""
1 1
2 2
3 3
4 4
5 5
"""
while col <= row:
# print("%d"%col)
print("*",end="")
col += 1
# print("第%d行"... | Python | zaydzuhri_stack_edu_python |
function parse_arguments
begin
set parser = call ArgumentParser
comment add these command line arg options
call add_argument string departure_date help=string Provide departure date in MM/DD/YYYY
call add_argument string return_date help=string Provide return date in MM/DD/YYYY
call add_argument string departure_airpor... | def parse_arguments():
parser = argparse.ArgumentParser()
# add these command line arg options
parser.add_argument("departure_date", help="Provide departure date in MM/DD/YYYY")
parser.add_argument("return_date", help="Provide return date in MM/DD/YYYY")
parser.add_argument("departure_airport", hel... | Python | nomic_cornstack_python_v1 |
function iou self other
begin
string Compute the IoU of this bounding box with another one. IoU is the intersection over union, defined as:: ``area(intersection(A, B)) / area(union(A, B))`` ``= area(intersection(A, B)) / (area(A) + area(B) - area(intersection(A, B)))`` Parameters ---------- other : imgaug.BoundingBox O... | def iou(self, other):
"""
Compute the IoU of this bounding box with another one.
IoU is the intersection over union, defined as::
``area(intersection(A, B)) / area(union(A, B))``
``= area(intersection(A, B)) / (area(A) + area(B) - area(intersection(A, B)))``
Pa... | Python | jtatman_500k |
from sqlalchemy.orm import sessionmaker
from models import connect , DUser
from Crypto.Hash import SHA256
set session_class = call sessionmaker bind=connect
class LoginService
begin
function login self username password
begin
set session = call session_class
set user = first filter by query session DUser username=usern... | from sqlalchemy.orm import sessionmaker
from models import connect, DUser
from Crypto.Hash import SHA256
session_class = sessionmaker(bind=connect)
class LoginService:
def login(self, username, password):
session = session_class()
user = session.query(DUser).filter_by(username=username).first()
... | Python | zaydzuhri_stack_edu_python |
function has_key dictionary key
begin
if key in keys dictionary
begin
return true
end
else
begin
return false
end
end function
comment return key in dictionary.keys()
comment ---
function measure_the_depth lst
begin
return count string lst string [
end function
comment ---
function sort_nums_ascending lst
begin
return ... | def has_key(dictionary, key):
if key in dictionary.keys():
return True
else:
return False
#return key in dictionary.keys()
# ---
def measure_the_depth(lst):
return str(lst).count("[")
# ---
def sort_nums_ascending(lst):
return sorted(lst)
#sort mutates and does not return, sorted does not mutate but return... | Python | zaydzuhri_stack_edu_python |
function type self
begin
return get pulumi self string type
end function | def type(self) -> str:
return pulumi.get(self, "type") | Python | nomic_cornstack_python_v1 |
string Created on Thu Nov 23 20:37:18 2017 Last modified on Thu Nov 23 20:37:18 2017 @author: Patrick X. Li Department of Mathematics and Statistics McMaster University @email: lip@math.mcmaster.ca
from scipy.optimize import fsolve
from matplotlib import rcParams
import matplotlib.pyplot as plt
from random import norma... | """
Created on Thu Nov 23 20:37:18 2017
Last modified on Thu Nov 23 20:37:18 2017
@author: Patrick X. Li
Department of Mathematics and Statistics
McMaster University
@email: lip@math.mcmaster.ca
"""
from scipy.optimize import fsolve
from matplotlib import rcParams
import matplotlib.pyplot as plt
fr... | Python | zaydzuhri_stack_edu_python |
function find found_item hash_table_cell
begin
if found_item
begin
set found_item at 1 = obj
end
else
begin
append hash_table_cell list key obj
set size = size + 1
append _keys key
end
end function | def find(found_item, hash_table_cell):
if found_item:
found_item[1] = obj
else:
hash_table_cell.append([key, obj])
self.size += 1
self._keys.append(key) | Python | nomic_cornstack_python_v1 |
function colorizeAnyLanguage self p leading=none trailing=none
begin
set c = c
comment g.trace("incremental",self.incremental,p)
if killFlag
begin
call removeAllTags
return
end
try
begin
comment @ << initialize ivars & tags >>
comment @+node:ekr.20031218072017.1602:<< initialize ivars & tags >> colorizeAnyLanguage
comm... | def colorizeAnyLanguage (self,p,leading=None,trailing=None):
c = self.c
# g.trace("incremental",self.incremental,p)
if self.killFlag:
self.removeAllTags()
return
try:
#@ << initialize ivars & tags >>
#@+node:ekr.200... | Python | nomic_cornstack_python_v1 |
function fs_group self
begin
return get pulumi self string fs_group
end function | def fs_group(self) -> pulumi.Input['FSGroupStrategyOptionsArgs']:
return pulumi.get(self, "fs_group") | Python | nomic_cornstack_python_v1 |
function setup_method self
begin
set tuple hmc hmc_resources = call standard_test_hmc
set uris = tuple tuple string /api/cpcs/([^/]+) CpcHandler tuple string /api/cpcs/([^/]+)/operations/set-cpc-power-capping CpcSetPowerCappingHandler
set urihandler = call UriHandler uris
end function | def setup_method(self):
self.hmc, self.hmc_resources = standard_test_hmc()
self.uris = (
(r'/api/cpcs/([^/]+)', CpcHandler),
(r'/api/cpcs/([^/]+)/operations/set-cpc-power-capping',
CpcSetPowerCappingHandler),
)
self.urihandler = UriHandler(self.uris) | Python | nomic_cornstack_python_v1 |
from Bio import SeqIO
set truncated = list
for record in parse SeqIO string 016.fasta string fasta
begin
set n = length seq // 3
set start = n
set end = length seq - integer n
set seq = seq at slice integer start : integer end :
append truncated record
end
write SeqIO truncated string truncated.fasta string fasta | from Bio import SeqIO
truncated = []
for record in SeqIO.parse('016.fasta', 'fasta'):
n = len(record.seq) // 3
start = n
end = len(record.seq) - int(n)
record.seq = record.seq[int(start): int(end)]
truncated.append(record)
SeqIO.write(truncated, 'truncated.fasta', 'fasta') | Python | zaydzuhri_stack_edu_python |
import logging
import threading
import requests
set logger = call getLogger __name__
class ENS extends Thread
begin
function __init__ self config *args **kwargs
begin
call __init__ *args keyword kwargs
set name = string ens
set daemon = true
set config = config
end function
function run self
begin
set _config = config
... | import logging
import threading
import requests
logger = logging.getLogger(__name__)
class ENS(threading.Thread):
def __init__(self, config, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = 'ens'
self.daemon = True
self.config = config
def run(sel... | Python | zaydzuhri_stack_edu_python |
function token_urlsafe nbytes=32
begin
string Return a random URL-safe text string, in Base64 encoding. This is taken and slightly modified from the Python 3.6 stdlib. The string has *nbytes* random bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. >>> token_urlsafe(16) #doctest:+SKIP 'Drmhz... | def token_urlsafe(nbytes=32):
"""Return a random URL-safe text string, in Base64 encoding.
This is taken and slightly modified from the Python 3.6 stdlib.
The string has *nbytes* random bytes. If *nbytes* is ``None``
or not supplied, a reasonable default is used.
>>> token_urlsafe(16) #doctest:... | Python | jtatman_500k |
function filter_even nums_list
begin
set nums_list = list filter lambda x -> x % 2 == 0 nums_list
print nums_list
end function
set numbers = list comprehension integer el for el in split input
call filter_even numbers | def filter_even(nums_list):
nums_list = list(filter(lambda x: (x % 2 == 0), nums_list))
print(nums_list)
numbers = [int(el) for el in input().split()]
filter_even(numbers)
| Python | zaydzuhri_stack_edu_python |
function get_next_url self request
begin
set next_url = get GET string next
if not next_url
begin
set next_url = reverse LOGGED_IN_REDIRECT_URL_NAME
end
if not call url_has_allowed_host_and_scheme next_url allowed_hosts=set literal call get_host require_https=true
begin
comment We are not logging the unsafe URL to prev... | def get_next_url(self, request):
next_url = request.GET.get("next")
if not next_url:
next_url = reverse(magicauth_settings.LOGGED_IN_REDIRECT_URL_NAME)
if not url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}, require_https=True):
# We are not l... | Python | nomic_cornstack_python_v1 |
function split filehandler delimiter=string , row_limit=4000000 output_name_template=string output_%02d.csv output_path=string . keep_headers=true
begin
import csv
set reader = reader filehandler delimiter=delimiter
set current_piece = 1
set current_out_path = join path output_path output_name_template % current_piece
... | def split(filehandler, delimiter=',', row_limit=4000000,
output_name_template='output_%02d.csv', output_path='.', keep_headers=True):
import csv
reader = csv.reader(filehandler, delimiter=delimiter)
current_piece = 1
current_out_path = os.path.join(
output_path,
output_name_templat... | Python | nomic_cornstack_python_v1 |
function draw_text self player_name current_score high_score
begin
call init
set font = call SysFont string Impact 11 * scale
set text_field_1 = call render player_name + string + string HIGH SCORE true WHITE
set text_field_2 = call render string + string current_score true WHITE
set text_field_3 = call render string... | def draw_text(self, player_name, current_score, high_score):
pygame.font.init()
font = pygame.font.SysFont('Impact', 11 * scale)
text_field_1 = font.render(player_name + ' ' + 'HIGH SCORE', True, WHITE)
text_field_2 = font.render(' ' + str(current_score), True, WHITE)
text_fi... | Python | nomic_cornstack_python_v1 |
import random , string
class Usuario
begin
function __init__ self usuario contraseña email
begin
set usuario = usuario
comment Sigue siendo un atributo privado
set __contraseña = call keygen contraseña
set email = email
end function
function keygen self contraseña
begin
set myrg = call SystemRandom
set longitud = 10
se... | import random, string
class Usuario:
def __init__(self, usuario, contraseña, email):
self.usuario = usuario
self.__contraseña = self.keygen(contraseña)#Sigue siendo un atributo privado
self.email = email
def keygen(self, contraseña):
myrg = random.SystemRandom()
lo... | Python | zaydzuhri_stack_edu_python |
function event_m10_15_x100 z68=10152700 z69=10152705
begin
string State 0,1: [Reproduction] Enemy display switching at the gimmick door_SubState
set call = call event_m10_15_x101 z68=z68 z69=z69
if get call == 0
begin
string State 2: [Condition] Enemy display switching with gimmick door: Lobby side closes_SubState
asse... | def event_m10_15_x100(z68=10152700, z69=10152705):
"""State 0,1: [Reproduction] Enemy display switching at the gimmick door_SubState"""
call = event_m10_15_x101(z68=z68, z69=z69)
if call.Get() == 0:
"""State 2: [Condition] Enemy display switching with gimmick door: Lobby side closes_SubState"""
... | Python | nomic_cornstack_python_v1 |
function setUp self
begin
pass
end function | def setUp(self):
pass | Python | nomic_cornstack_python_v1 |
comment Fibonacci sequence
function Fibonacci n
begin
set a = 0
set b = 1
end function | # Fibonacci sequence
def Fibonacci(n):
a = 0
b = 1 | Python | flytech_python_25k |
function list_potential_submissions bucket_id
begin
for page in pages
begin
for blob in page
begin
if match name
begin
yield format string gs://{}/{} bucket_id name
end
end
end
end function | def list_potential_submissions(bucket_id):
for page in storage.Client().bucket(bucket_id).list_blobs(prefix="lapdog-executions", fields='items/name,nextPageToken').pages:
for blob in page:
if lapdog_submission_pattern.match(blob.name):
yield 'gs://{}/{}'.format(bucket_id, blob.na... | Python | nomic_cornstack_python_v1 |
comment -*- coding: UTF-8 -*-
comment 1 首先获得用户-书籍-评分,放到文件1.data 中 包含 164534 条记录
comment 2 获得 图书--作者--出版社 放到2.data 中 保函 22441 条记录
comment 3 将两者和并,输出到3.data 中
comment 4 将data 3 的文件 编号重新排序,生成 用户编号1,2,3... 图书编号1,2,3....
import codecs
set fo_1 = open string 1.data string r encoding=string utf-8
set fo_2 = open string 2.data... | # -*- coding: UTF-8 -*-
# 1 首先获得用户-书籍-评分,放到文件1.data 中 包含 164534 条记录
# 2 获得 图书--作者--出版社 放到2.data 中 保函 22441 条记录
# 3 将两者和并,输出到3.data 中
# 4 将data 3 的文件 编号重新排序,生成 用户编号1,2,3... 图书编号1,2,3....
import codecs
fo_1 = codecs.open('1.data','r',encoding='utf-8')
fo_2 = codecs.open('2.data', 'r', encoding='utf-8')
fo_3 = codecs.... | Python | zaydzuhri_stack_edu_python |
function e_z kx ky kz tz=1 c_=1 a=1
begin
set res = 2 * tz * cos kz * c_ * cos kx * a - cos ky * a ^ 2
set res = res * cos kx * a / 2 * cos ky * a / 2
return res
end function | def e_z(kx, ky, kz, tz=1, c_=1, a=1):
res = 2*tz * np.cos(kz*c_) * (np.cos(kx*a) - np.cos(ky*a))**2
res *= np.cos(kx*a/2) * np.cos(ky*a/2)
return res | Python | nomic_cornstack_python_v1 |
import sys
set tuple K N = map int split read line stdin
set lines = list
for _ in range K
begin
append lines integer input
end
set left = 1
set right = sum lines // K + 1
while left < right
begin
set mid = left + right // 2
set cnt = 0
for line in lines
begin
set cnt = cnt + line // mid
end
if cnt >= N
begin
set left... | import sys
K,N=map(int,sys.stdin.readline().split())
lines=[]
for _ in range(K):
lines.append(int(input()))
left=1
right=sum(lines)//K+1
while left<right:
mid=(left+right)//2
cnt=0
for line in lines:
cnt+=line//mid
if cnt>=N:
left=mid+1
answer=mid
else:
right=... | Python | zaydzuhri_stack_edu_python |
function sort_list list
begin
set sorted_list = sorted list
return sorted_list
end function
set list = list 1 7 5 9 3
comment will print [1, 3, 5, 7, 9]
print call sort_list list | def sort_list(list):
sorted_list = sorted(list)
return sorted_list
list = [1, 7, 5, 9 , 3]
print(sort_list(list)) # will print [1, 3, 5, 7, 9] | Python | iamtarun_python_18k_alpaca |
import numpy as np
import os
import math
import unittest
class TestCase extends TestCase
begin
string docstring for TestCase
function assertTensorClose self v0 v1 max_err=1e-06 name=none
begin
set v0 = call ascontiguousarray v0 dtype=float32
set v1 = call ascontiguousarray v1 dtype=float32
assert call isfinite sum and ... | import numpy as np
import os
import math
import unittest
class TestCase(unittest.TestCase):
"""docstring for TestCase"""
def assertTensorClose(self, v0, v1, *, max_err=1e-6, name=None):
v0 = np.ascontiguousarray(v0, dtype=np.float32)
v1 = np.ascontiguousarray(v1, dtype=np.float32)
ass... | Python | zaydzuhri_stack_edu_python |
from math import ceil , floor
import re
function read_text_file file_name
begin
with open file_name string r as f
begin
set data = read lines f
set data = list comprehension replace line string string for line in data
set data = list comprehension split line string for line in data
end
return data
end function
functio... | from math import ceil, floor
import re
def read_text_file (file_name):
with open(file_name, "r") as f:
data = f.readlines()
data = [line.replace("\n", "") for line in data]
data = [line.split(" ") for line in data]
return data
def binary_search (search_list, top=True):
mid = l... | Python | zaydzuhri_stack_edu_python |
import sys
call setrecursionlimit 10 ^ 7
set INTMAX = 9223372036854775807
set INTMIN = - 9223372036854775808
set DVSR = 1000000007
function POW x y
begin
return power x y DVSR
end function
function INV x d=DVSR
begin
return power x d - 2 d
end function
function DIV x y d=DVSR
begin
return x * call INV y d % d
end funct... | import sys
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, d=DVSR): return pow(x, d - 2, d)
def DIV(x, y, d=DVSR): return (x * INV(y, d)) % d
def LI(): return [int(x) for x in input().split()]
def LF(): return [fl... | Python | zaydzuhri_stack_edu_python |
function select_features self X y
begin
set random_cols = list
comment trying for all features
for i in range 1 n_random_col + 1
begin
set random_col = format string __random_{}__ i
set X at random_col = call rand shape at 0
append random_cols random_col
end
set tuple _ trials = call optimize_hyperparam values values ... | def select_features(self, X, y):
random_cols = []
# trying for all features
for i in range(1, self.n_random_col + 1):
random_col = "__random_{}__".format(i)
X[random_col] = self.random_state.rand(X.shape[0])
random_cols.append(random_col)
_, trials =... | Python | nomic_cornstack_python_v1 |
function __init__ self mu sigma *args **kwargs
begin
set mu = mu
set sigma = sigma
call __init__ *args keyword kwargs
end function | def __init__(self, mu, sigma, *args, **kwargs):
self.mu = mu
self.sigma = sigma
super(GaussianRV, self).__init__(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
comment Naive Bayes Classifier and Evaluation
comment Jwu-Hsuan Hwang
import os
import math
import numpy as np
import nltk
from nltk.corpus import stopwords
from collections import defaultdict
from nltk.tokenize import word_tokenize
class NaiveBayes
begin
function __init__ self
begin
set class_dict = dict 0 string neg ... | # Naive Bayes Classifier and Evaluation
# Jwu-Hsuan Hwang
import os
import math
import numpy as np
import nltk
from nltk.corpus import stopwords
from collections import defaultdict
from nltk.tokenize import word_tokenize
class NaiveBayes():
def __init__(self):
self.class_dict = {0: 'neg', 1: 'pos'}
... | Python | zaydzuhri_stack_edu_python |
function LogisticFuction Val
begin
set Val = - 1.0 * Val
set logistc_val = 1.0 / 1.0 + exp Val
return logistc_val
end function | def LogisticFuction(Val):
Val = -1.0 * Val
logistc_val = 1.0 / (1.0 + np.exp(Val))
return logistc_val | Python | nomic_cornstack_python_v1 |
function _postCreateVirtual cls newNode type=META_TYPE god_meta_name=META_GOD_ND_NAME
begin
call _postCreateVirtual newNode
try
begin
set god_mata_nd = call PyNode god_meta_name
end
except any
begin
set god_mata_nd = call GodMetaNode
end
set SUBNODE_TYPE
call add_meta_node newNode
set name = format string {}_METAND str... | def _postCreateVirtual(
cls,
newNode,
type=constants.META_TYPE,
god_meta_name=constants.META_GOD_ND_NAME,
):
MetaNode._postCreateVirtual(newNode)
try:
god_mata_nd = pmc.PyNode(god_meta_name)
except:
god_mata_nd = GodMetaNode()
n... | Python | nomic_cornstack_python_v1 |
function job_not_running self jid tgt tgt_type minions is_finished
begin
string Return a future which will complete once jid (passed in) is no longer running on tgt
set ping_pub_data = yield call tgt string saltutil.find_job list jid tgt_type=tgt_type
set ping_tag = call tagify list ping_pub_data at string jid string r... | def job_not_running(self, jid, tgt, tgt_type, minions, is_finished):
'''
Return a future which will complete once jid (passed in) is no longer
running on tgt
'''
ping_pub_data = yield self.saltclients['local'](tgt,
'saltutil... | Python | jtatman_500k |
function addrow self row
begin
comment make sure we have a header defined
if header is none
begin
raise call TableError string Header is needed before rows can be added.
end
if rows is none
begin
set rows = list
end
comment go through the data and add to the table
if row is not none
begin
comment The data should be an ... | def addrow(self, row):
# make sure we have a header defined
if self.header is None:
raise TableError('Header is needed before rows can be added.')
if self.rows is None:
self.rows = list()
# go through the data and add to the table
if row is not None:
... | Python | nomic_cornstack_python_v1 |
from helpers import *
import re
import string
comment Gets the name of the host by looking at hositng job and most common first two words
function getFacts data
begin
set factsList = call find_matching_tweets_from_data string .*(?i)(fun fact:).* data
set factsList2 = list
for tweet in factsList
begin
set text = get tw... | from helpers import *
import re
import string
# Gets the name of the host by looking at hositng job and most common first two words
def getFacts(data):
factsList = find_matching_tweets_from_data('.*(?i)(fun fact:).*', data)
factsList2 = []
for tweet in factsList:
text = tweet.get('text')
fa... | Python | zaydzuhri_stack_edu_python |
function magnetic_field date lat lon alt output_format=string cartesian
begin
set g = call GeoMag
return call GeoMag array list lat lon alt date location_format=string geodetic output_format=output_format
end function | def magnetic_field(date: datetime.datetime, lat, lon, alt, output_format='cartesian'):
g = GeoMag()
return g.GeoMag(np.array([lat, lon, alt]), date, location_format='geodetic', output_format=output_format) | Python | nomic_cornstack_python_v1 |
for line in f
begin
append arr integer line
end
close f
comment print(arr)
comment arr = [8,7,6,5,4,3,2,1]
comment arr =[37, 7, 2, 14, 35, 47, 10, 24, 44, 17, 34, 11, 16, 48, 1, 39, 6, 33, 43, 26, 40, 4, 28, 5, 38, 41, 42, 12, 13, 21, 29, 18, 3, 19, 0, 32, 46, 27, 31, 25, 15, 36, 20, 8, 9, 49, 22, 23, 30, 45]
set new_a... | for line in f:
arr.append(int(line))
f.close()
# print(arr)
# arr = [8,7,6,5,4,3,2,1]
# arr =[37, 7, 2, 14, 35, 47, 10, 24, 44, 17, 34, 11, 16, 48, 1, 39, 6, 33, 43, 26, 40, 4, 28, 5, 38, 41, 42, 12, 13, 21, 29, 18, 3, 19, 0, 32, 46, 27, 31, 25, 15, 36, 20, 8, 9, 49, 22, 23, 30, 45]
new_arr = [0] * len(arr)
correc... | Python | zaydzuhri_stack_edu_python |
function sort_dict_by_value dict
begin
set sorted_dict = dictionary sorted items dict key=lambda kv -> kv at 1 reverse=true
return sorted_dict
end function
set sorted_dict = call sort_dict_by_value dictionary
print sorted_dict | def sort_dict_by_value(dict):
sorted_dict = dict(sorted(dict.items(), key = lambda kv: kv[1], reverse = True))
return sorted_dict
sorted_dict = sort_dict_by_value(dictionary)
print(sorted_dict)
| Python | flytech_python_25k |
function PostEvent *args **kwargs
begin
return call PostEvent *args keyword kwargs
end function | def PostEvent(*args, **kwargs):
return _core_.PostEvent(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
function predict_end
begin
set data = json
if data
begin
set pred_dict at string end_date = data at string end_date
end
else
begin
pass
end
return string Non tam praeclarum est scire latine, quam turpe nescire
end function | def predict_end():
data = request.json
if data:
predictor.pred_dict["end_date"] = data["end_date"]
else:
pass
return 'Non tam praeclarum est scire latine, quam turpe nescire' | Python | nomic_cornstack_python_v1 |
import tkinter as tk
comment Set up the root window
set root = call Tk
comment Create the table
set table = call Frame root
grid row=0 column=0
comment Set the row and column numbers
set rows = 5
set columns = 5
comment Create the label for column 0
for i in range rows
begin
for j in range 1 columns
begin
set b = call ... | import tkinter as tk
# Set up the root window
root = tk.Tk()
# Create the table
table = tk.Frame(root)
table.grid(row=0, column=0)
# Set the row and column numbers
rows = 5
columns = 5
# Create the label for column 0
for i in range(rows):
for j in range(1, columns):
b = tk.Entry(table, text="")
... | Python | jtatman_500k |
import sys
set T = integer read line stdin
function dfs L_graph n
begin
set visited at n = true
append result n
print string 시작하는 것 : n
for i in L_graph at n
begin
if not visited at i
begin
call dfs L_graph i
end
end
print string 끝나는 것 : n
print string result : result
set result_num = length result
if result_num > 1
be... | import sys
T = int(sys.stdin.readline())
def dfs(L_graph, n):
visited[n] = True
result.append(n)
print('시작하는 것 : ', n)
for i in L_graph[n]:
if not visited[i]:
dfs(L_graph, i)
print('끝나는 것 : ', n)
print(' result : ',result)
result_num = len(result)
if result_num > 1... | Python | zaydzuhri_stack_edu_python |
function __set_to_default self
begin
set uri_ports = format string {0}/{1} base_uri_ports percents_name
comment get Port data related to configuration
set port_data = dict
comment Set interfaces into correct form
if string interfaces in port_data
begin
if __is_special_type and name == string lag
begin
set interfaces =... | def __set_to_default(self):
uri_ports = "{0}/{1}".format(
Interface.base_uri_ports, self.percents_name
)
# get Port data related to configuration
port_data = {}
# Set interfaces into correct form
if "interfaces" in port_data:
if self.__is_special... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time , datetime
class Scraper
begin
function __init__ self dr... | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time, datetime
class Scraper:
def __init__(sel... | Python | zaydzuhri_stack_edu_python |
function test_correct_header self
begin
comment this pulls data from the text file
set header_file = read open string utils/header_border.txt string r
comment this requests the data from the URL again
set header_url = content
comment this compares the 2 (REPLACE WITH TRY, IF, EXCEPT)
comment adds line break
print strin... | def test_correct_header(self):
# this pulls data from the text file
header_file = open('utils/header_border.txt', 'r').read()
# this requests the data from the URL again
header_url = requests.get(
"https://va-mosaic-agios-beta.s3.amazonaws.com/images/agios/horizontal-bar.png... | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
call __init__ 0 0 0 255
end function | def __init__(self) -> None:
super().__init__(0, 0, 0, 255) | Python | nomic_cornstack_python_v1 |
for i in range 1 ls + 1
begin
for j in range 1 lt + 1
begin
if s at i - 1 == t at j - 1
begin
set dp at i at j = dp at i - 1 at j - 1 + 1
end
else
begin
set dp at i at j = max dp at i at j - 1 dp at i - 1 at j
end
end
end
set l = dp at ls at lt
set ans = string
set i = ls
set j = lt
while l > 0
begin
if s at i - 1 == ... | for i in range(1,ls+1):
for j in range(1,lt+1):
if s[i-1]==t[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i][j-1],dp[i-1][j])
l=dp[ls][lt]
ans=''
i=ls
j=lt
while l>0:
if s[i-1]==t[j-1]:
ans=str(s[i-1])+ans
l-=1
i-=1
j-=1
elif dp[i][j]==dp[i-1][j]:
i-=1
else:
j... | Python | zaydzuhri_stack_edu_python |
function _filter_mrpack_files file_list mrpack_install_options
begin
set filtered_list : List at MrpackFile = list
for file in file_list
begin
if string env not in file
begin
append filtered_list file
continue
end
if file at string env at string client == string required
begin
append filtered_list file
end
if file at ... | def _filter_mrpack_files(file_list: List[MrpackFile], mrpack_install_options: MrpackInstallOptions) -> List[MrpackFile]:
filtered_list: List[MrpackFile] = []
for file in file_list:
if "env" not in file:
filtered_list.append(file)
continue
if file["env"]["client"] == "req... | Python | nomic_cornstack_python_v1 |
function get_event_id self
begin
comment osid.id.Id
return
end function | def get_event_id(self):
return # osid.id.Id | Python | nomic_cornstack_python_v1 |
function test_init_optional_base_def_call mocked_init_model_factory
begin
comment pylint: disable=protected-access
set spec = call MagicMock
set base = call MagicMock
call _init_optional_base base=base spec=spec
call assert_called_once_with base=base spec=spec models_filename=none spec_path=none
end function | def test_init_optional_base_def_call(mocked_init_model_factory: mock.MagicMock):
# pylint: disable=protected-access
spec = mock.MagicMock()
base = mock.MagicMock()
open_alchemy._init_optional_base(base=base, spec=spec)
mocked_init_model_factory.assert_called_once_with(
base=base, spec=spec... | Python | nomic_cornstack_python_v1 |
comment Поиск первого вхождения методом грубой силы, приведенный в книге
comment Удобен в использовании для низкоуровневих языков программирования
from random import randrange
function match massive element
begin
set i = 0
comment Лишняя проверка (i < len(massive) на кождом шаге итерации
while i < length massive and ma... | #Поиск первого вхождения методом грубой силы, приведенный в книге
#Удобен в использовании для низкоуровневих языков программирования
from random import randrange
def match(massive, element):
i = 0
while i < len(massive) and massive[i] != element: #Лишняя проверка (i < len(massive) на кождом шаге итераци... | Python | zaydzuhri_stack_edu_python |
function sleepDeprive self interval=none threshold=none
begin
if interval == none
begin
set interval = inactivity_threshold
end
if threshold == none and string FLY_AREA_AVG in debug_info
begin
set threshold = decimal debug_info at string FLY_AREA_AVG * interval
end
else
begin
set threshold = 20 * interval
end
set aslee... | def sleepDeprive(self, interval=None, threshold=None):
if interval == None:
interval = self.inactivity_threshold
if threshold == None and 'FLY_AREA_AVG' in self.debug_info:
threshold = float (self.debug_info['FLY_AREA_AVG']) * interval
else:
thresho... | Python | nomic_cornstack_python_v1 |
function version_label self
begin
return get pulumi self string version_label
end function | def version_label(self) -> Optional[str]:
return pulumi.get(self, "version_label") | Python | nomic_cornstack_python_v1 |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
import numpy as np
import least_squares as lsq
import sys
function gradient_descent model eta max_iterations=10000.0 epsilon=1e-05 beta_start=none
begin
string Gradient descent Parameters ---------- model: optimization model object eta: learning rate max_iterations: maximum number of gradient iterations epsilon: tolera... | import numpy as np
import least_squares as lsq
import sys
def gradient_descent(model, eta, max_iterations=1e4, epsilon=1e-5,
beta_start=None):
"""
Gradient descent
Parameters
----------
model: optimization model object
eta: learning rate
max_iterations: maximum number ... | Python | zaydzuhri_stack_edu_python |
function heat_capacity self q
begin
return _Cpd * 1 - q + _Cvap * q
end function | def heat_capacity(self, q):
return self._Cpd*(1-q) + self._Cvap*q | Python | nomic_cornstack_python_v1 |
from random import randint
import pygame
from paddle import Paddle
from ball import Ball
call init
comment colors
set BLACK = tuple 0 0 0
set WHITE = tuple 255 255 255
comment Window
set screen = call set_mode tuple 1000 800
call set_caption string PONG GAME
comment Paddle A
set paddleA = call Paddle WHITE 10 100
set x... | from random import randint
import pygame
from paddle import Paddle
from ball import Ball
pygame.init()
#colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Window
screen = pygame.display.set_mode((1000,800))
pygame.display.set_caption('PONG GAME')
# Paddle A
paddleA = Paddle(WHITE, 10, 100)
paddleA.rect.x = 20
paddl... | Python | zaydzuhri_stack_edu_python |
function executeQuery self
begin
try
begin
comment self.checkValName()
execute cursor query val
set cnt = total_changes
end
except Exception as e
begin
print string Query failed: %s % e
end
end function | def executeQuery(self):
try:
# self.checkValName()
self.cursor.execute(self.query, self.val)
self.cnt = self.conn.total_changes
except Exception as e:
print("Query failed: %s" % e) | Python | nomic_cornstack_python_v1 |
function loadtemps
begin
set file = open string temps.txt
comment load temps file into list
set temps = list
for line in file
begin
set line = strip line
set line = decimal line
append temps line
end
return temps
end function
comment define start and stop
function calavg temps start stop
begin
comment define total
set... | def loadtemps():
file = open('temps.txt')
temps = [] #load temps file into list
for line in file:
line = line.strip()
line = float(line)
temps.append(line)
return temps
def calavg(temps, start, stop): # define start a... | Python | zaydzuhri_stack_edu_python |
string This file aims to count the number of times the word bitch has been used in each episode of breaking bad and then plot a graph of it.
from os import listdir
comment For getting the all the things in the folder
from os.path import isfile , join
comment To get only files in the subtitles folder
import matplotlib.p... | """
This file aims to count the number of times the word
bitch has been used in each episode of breaking bad and
then plot a graph of it.
"""
from os import listdir
#For getting the all the things in the folder
from os.path import isfile, join
#To get only files in the subtitles folder
import matplotlib.p... | Python | zaydzuhri_stack_edu_python |
function sol_true t y0
begin
return y0 * exp t ^ 2
end function | def sol_true(t, y0):
return y0*np.exp(t**2) | 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.