code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function on_train_begin self logs=dict
begin
set speedups = list
set current_best_metric = 0.0
set current_best_model = none
set timeout = timerReset
end function | def on_train_begin(self, logs={}):
self.speedups = []
self.current_best_metric = 0.0
self.current_best_model = None
self.timeout = self.timerReset | Python | nomic_cornstack_python_v1 |
import psycopg2
import json
comment Alte Tabellen löschen und neu erstellen #####
try
begin
set conn = none
set conn = call connect host=string localhost database=string dbs_project_covid19 user=string postgres password=string 20postgres20
set cur = call cursor
comment Testen ob Tabellen vorhanden
execute cur string SE... | import psycopg2
import json
##### Alte Tabellen löschen und neu erstellen #####
try:
conn = None
conn = psycopg2.connect(host="localhost", database="dbs_project_covid19", user="postgres", password="20postgres20")
cur = conn.cursor()
cur.execute('SELECT * FROM country') # Testen ob Tabellen vorhande... | Python | zaydzuhri_stack_edu_python |
import requests
from datetime import datetime , timedelta
from pprint import pprint
function get_questions_py tag=string python
begin
set url = string https://api.stackexchange.com/2.3/questions
set params = dict string fromdate string format time now - time delta days=2 string %Y-%m-%d ; string todate string format ti... | import requests
from datetime import datetime, timedelta
from pprint import pprint
def get_questions_py(tag='python'):
url = 'https://api.stackexchange.com/2.3/questions'
params = \
{
'fromdate': (datetime.now() - timedelta(days=2)).strftime('%Y-%m-%d'),
'todate': (datetime.now... | Python | zaydzuhri_stack_edu_python |
function read_info self dataset_name=none strict=false
begin
if dataset_name is none
begin
return self
end
else
begin
raise call MutantError string This is NOT a multi-dataset mutant - cannot provide dataset_name arg!
end
end function | def read_info(self, dataset_name=None, strict=False):
if dataset_name is None: return self
else: raise MutantError("This is NOT a multi-dataset mutant - cannot provide dataset_name arg!") | Python | nomic_cornstack_python_v1 |
async function blacklist self ctx
begin
pass
end function | async def blacklist(self, ctx: commands.Context) -> None:
pass | Python | nomic_cornstack_python_v1 |
function load_confirm_exit_bindings python_input
begin
set bindings = call KeyBindings
set handle = add
set confirmation_visible = condition lambda -> show_exit_confirmation
decorator call handle string y filter=confirmation_visible
decorator call handle string Y filter=confirmation_visible
decorator call handle strin... | def load_confirm_exit_bindings(python_input):
bindings = KeyBindings()
handle = bindings.add
confirmation_visible = Condition(lambda: python_input.show_exit_confirmation)
@handle("y", filter=confirmation_visible)
@handle("Y", filter=confirmation_visible)
@handle("enter", filter=confirmation_vi... | Python | nomic_cornstack_python_v1 |
from siphon.queue import Queue
from tests import BaseRedisTest
from nose.tools import raises
class TestQueue extends BaseRedisTest
begin
function setUp self
begin
setup call super
end function
function _create_queue self conn name=none
begin
set name = name or string foo
return queue name connection=conn
end function
d... | from siphon.queue import Queue
from tests import BaseRedisTest
from nose.tools import raises
class TestQueue(BaseRedisTest):
def setUp(self):
super().setUp()
def _create_queue(self, conn, name=None):
name = name or 'foo'
return Queue(name, connection=conn)
@raises(Exception)
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Time : 2021-06-22 19:37
comment @Author : zxl
comment @FileName: 386.py
comment TODO Wrong Answer
class Solution
begin
function calNum self n
begin
set base = 0
while n
begin
set base = base + 1
set n = n // 10
end
return base
end function
function recFind self n dic s
begin
if n ... | # -*- coding: utf-8 -*-
# @Time : 2021-06-22 19:37
# @Author : zxl
# @FileName: 386.py
#TODO Wrong Answer
class Solution:
def calNum(self,n):
base = 0
while n:
base+=1
n//=10
return base
def recFind(self,n,dic,s):
if n in dic:
return... | Python | zaydzuhri_stack_edu_python |
import re
import six
import copy
import inspect
import collections
from parser.representation import unicode_to_repr , field_repr
from parser.utils import ValidationError , SkipField , empty
from parser.validators import MaxValueValidator
from parser.validators import MinValueValidator
set MISSING_ERROR_MESSAGE = strin... | import re
import six
import copy
import inspect
import collections
from parser.representation import unicode_to_repr, field_repr
from parser.utils import ValidationError, SkipField, empty
from parser.validators import MaxValueValidator
from parser.validators import MinValueValidator
MISSING_ERROR_MESSAGE = (
'Val... | Python | zaydzuhri_stack_edu_python |
function my_self self
begin
print string my name is { title name }
print string my rollnum is { rollnum }
end function | def my_self(self):
print(f"my name is {self.name.title()}")
print(f"my rollnum is {self.rollnum}") | Python | nomic_cornstack_python_v1 |
function element_to_objects tree
begin
set entities = list
for element in tree
begin
set cls = get MAPPINGS tag none
if not cls
begin
continue
end
set attrs = call xml_children_as_dict element
set transformed = call transform_attributes attrs
if has attribute cls string fill_extra_attributes
begin
set transformed = ca... | def element_to_objects(tree):
entities = []
for element in tree:
cls = MAPPINGS.get(element.tag, None)
if not cls:
continue
attrs = xml_children_as_dict(element)
transformed = transform_attributes(attrs)
if hasattr(cls, "fill_extra_attributes"):
t... | Python | nomic_cornstack_python_v1 |
function clientConnectionFailed self connector reason
begin
pass
end function | def clientConnectionFailed(self, connector, reason):
pass | Python | nomic_cornstack_python_v1 |
function __init__ __self__ backend_address_pool_name backend_port frontend_port_range_end frontend_port_range_start inbound_nat_pool_name location public_ip_address_name resource_group
begin
set __self__ string backend_address_pool_name backend_address_pool_name
set __self__ string backend_port backend_port
set __self_... | def __init__(__self__, *,
backend_address_pool_name: pulumi.Input[str],
backend_port: pulumi.Input[int],
frontend_port_range_end: pulumi.Input[int],
frontend_port_range_start: pulumi.Input[int],
inbound_nat_pool_name: pulumi.Input[str]... | Python | nomic_cornstack_python_v1 |
import sys
import codecs
import os
comment ¶Ö are shown instead of broken bar and another character on mac
comment ˆ - 136
comment • - 149
comment œ - 156
comment ° - 179
comment ½ - 189
function findCharacters authCode volumeNumber
begin
print string Volume: + string volumeNumber
with open string source/%s/%s%d.txt % ... | import sys
import codecs
import os
#¶Ö are shown instead of broken bar and another character on mac
# ˆ - 136
# • - 149
# œ - 156
# ° - 179
# ½ - 189
def findCharacters(authCode, volumeNumber):
print('\tVolume: ' + str(volumeNumber))
with open('source/%s/%s%d.txt' % (authCode, authCode, volumeNumber), 'r+', ... | Python | zaydzuhri_stack_edu_python |
function noembed self
begin
if url
begin
debug string document {pk:%s, url:%s} init embedly % tuple pk url
from embedly import Embedly
set client = call Embedly MILLER_EMBEDLY_API_KEY
set embed = call oembed url raw=true
set contents = embed at string raw
end
end function
comment print json.embed
comment else:
comment ... | def noembed(self):
if self.url:
logger.debug('document {pk:%s, url:%s} init embedly' % (self.pk, self.url))
from embedly import Embedly
client = Embedly(settings.MILLER_EMBEDLY_API_KEY)
embed = client.oembed(self.url, raw=True)
self.contents = embed['raw']
# print json.embed
... | Python | nomic_cornstack_python_v1 |
function drop self
begin
set c = call cursor
for table in list string experiment string fact
begin
execute c format string drop table if exists {} table
end
commit self
end function | def drop(self):
c = self.cursor()
for table in ['experiment','fact']:
c.execute("drop table if exists {}".format(table))
self.commit() | Python | nomic_cornstack_python_v1 |
import numpy as np
from datetime import datetime , timedelta
from pytz import utc , timezone
from models import User
set raw_csv_data = call genfromtxt string density.csv delimiter=string , dtype=none encoding=string utf8
set activity_by_user = dict
for row in raw_csv_data
begin
set activity_by_user at row at 0 = arra... | import numpy as np
from datetime import datetime, timedelta
from pytz import utc, timezone
from models import User
raw_csv_data = np.genfromtxt("density.csv", delimiter=",", dtype=None, encoding="utf8")
activity_by_user = {}
for row in raw_csv_data:
activity_by_user[row[0]] = np.array(list(row)[1:])
print(activ... | Python | zaydzuhri_stack_edu_python |
set a = 6
set b = 7
set voornaam = string Jurgen
set tussenvoegsel = string
set achternaam = string Blokhuis
set mijnnaam = voornaam + tussenvoegsel + string + achternaam
print 75 > a and 75 < b
print length mijnnaam == length voornaam + tussenvoegsel + string + achternaam
print length mijnnaam > 5 * length tussenvo... | a = 6
b = 7
voornaam = 'Jurgen'
tussenvoegsel= ''
achternaam= 'Blokhuis'
mijnnaam =(voornaam + tussenvoegsel + ' ' + achternaam)
print (75>a and 75<b)
print (len(mijnnaam) == len(voornaam + tussenvoegsel + ' ' + achternaam))
print (len(mijnnaam)> (5*len(tussenvoegsel)))
print (tussenvoegsel in mijnnaam) | Python | zaydzuhri_stack_edu_python |
function get_page_path_by_link self page_link
begin
if string : not in page_link
begin
warning string no namespace alias in ' { page_link } '
return none
end
set tuple ns_alias page_title = split page_link string : 1
set namespace = call get_ns_by_alias ns_alias
set page = call get_page_by_title page_title
if not page
... | def get_page_path_by_link(self, page_link):
if ':' not in page_link:
logging.warning(f"no namespace alias in '{page_link}'")
return None
ns_alias, page_title = page_link.split(':', 1)
namespace = self.get_ns_by_alias(ns_alias)
page = namespace.get_page_by_title(... | Python | nomic_cornstack_python_v1 |
import re
string findall() return list finditer() return iterator search() only return the first match,return object,use group() to show content match() only search at the beginning,return object,use group() to show content split() return list . represent anything except /n * repeat times from zero to infinity + repeat... | import re
"""
findall() return list
finditer() return iterator
search() only return the first match,return object,use group() to show content
match() only search at the beginning,return object,use group() to show content
split() return list
. represent anything except /n
* repeat times from zero to infinity
+ repeat ti... | Python | zaydzuhri_stack_edu_python |
with open string input.txt string r encoding=string utf8 as f
begin
set info = list comprehension split right strip i for i in read lines f
end
with open string output.txt string w encoding=string utf8 as f
begin
for i in sorted info
begin
print i at 0 i at 1 i at 3 file=f
end
end | with open('input.txt', 'r', encoding='utf8') as f:
info = [i.rstrip().split() for i in f.readlines()]
with open('output.txt', 'w', encoding='utf8') as f:
for i in sorted(info):
print(i[0], i[1], i[3], file=f)
| Python | zaydzuhri_stack_edu_python |
from sympy import lambdify , Symbol , parse_expr
import numpy as np
import re
set outputFile = open string result.txt string w
close outputFile
function main
begin
set inputFile = open string input.txt string r
for tuple lineIndex line in enumerate inputFile
begin
set line = split replace line string string string ;
s... | from sympy import lambdify, Symbol, parse_expr
import numpy as np
import re
outputFile = open("result.txt", "w")
outputFile.close()
def main():
inputFile = open("input.txt", "r")
for lineIndex, line in enumerate(inputFile):
line = line.replace("\n","").split(";")
originalExpression = line[0]... | Python | zaydzuhri_stack_edu_python |
function dictsource_2_photopoints dictsource **kwargs
begin
if type dictsource is not dict
begin
raise call TypeError string 'dictsource' must be a dictionnary
end
comment - Does is have the requiered basic information:
for musthave in list string fluxes string variances string lbda
begin
if musthave not in keys dictso... | def dictsource_2_photopoints(dictsource,**kwargs):
if type(dictsource) is not dict:
raise TypeError("'dictsource' must be a dictionnary")
# - Does is have the requiered basic information:
for musthave in ["fluxes","variances","lbda"]:
if musthave not in dictsource.keys():
ra... | Python | nomic_cornstack_python_v1 |
from random import random
class Valet
begin
function __init__ self maxx maxy
begin
set locx = random * maxx
set locy = random * maxy
comment ASSUME available time to be -24 hours because
comment we know 24 hours ahead of time where customers will be
set avail_time = - 1440
end function
end class | from random import random
class Valet:
def __init__(self, maxx, maxy):
self.locx = random() * maxx
self.locy = random() * maxy
# ASSUME available time to be -24 hours because
# we know 24 hours ahead of time where customers will be
self.avail_time = -1440 | Python | zaydzuhri_stack_edu_python |
comment imports Adventure() class from respective file
from miniA5Adventurer import Adventurer
comment main execution outlines the program route by calling default values.
comment A name is given and health is increased and the new values are displayed.
function start
begin
set myAdventurer = call Adventurer
print stri... | # imports Adventure() class from respective file
from miniA5Adventurer import Adventurer
# main execution outlines the program route by calling default values.
# A name is given and health is increased and the new values are displayed.
def start():
myAdventurer = Adventurer()
print("The default values are:... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
comment question 1.1.1
comment Load 2 class
function load_data
begin
with load np string notMNIST.npz as data
begin
set tuple Data Target = tuple data at string images data at string labels
set posClass = 2
set negClass = 9
set dataIndx = Target... | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#question 1.1.1
# Load 2 class
def load_data():
with np.load("notMNIST.npz") as data :
Data, Target = data ["images"], data["labels"]
posClass = 2
negClass = 9
dataIndx = (Target==posClass) + (Target==ne... | Python | zaydzuhri_stack_edu_python |
from random import shuffle , choice
from mastermind import random_hand , evaluate
set _all = generator expression tuple map int string num for num in range 1023 9877
set _all = list comprehension num for num in _all if length set num == 4
class BaseAgent extends object
begin
string Basic agent interface
function __init... | from random import shuffle, choice
from mastermind import random_hand, evaluate
_all = (tuple(map(int, str(num)))
for num in range(1023, 9877))
_all = [num for num in _all if len(set(num))==4]
class BaseAgent(object):
"""Basic agent interface"""
def __init__(self):
raise NotImplementedError
... | Python | zaydzuhri_stack_edu_python |
function vclamp2arr L nthin=100
begin
set first = L at 0
set shape = tuple length L nthin
set dtype = list comprehension tuple k float shape for k in chain list string t names names
set result = view zeros tuple dtype=dtype recarray
for tuple i tuple t y _dy a in enumerate L
begin
set result at string t at tuple i sli... | def vclamp2arr(L, nthin=100):
first = L[0]
shape = len(L), nthin
dtype = [(k, float, shape)
for k in chain(["t"], first.y.dtype.names, first.a.dtype.names)]
result = np.zeros((), dtype=dtype).view(np.recarray)
for i, (t, y, _dy, a) in enumerate(L):
result["t"][i, :] = np.squeeze(thi... | Python | nomic_cornstack_python_v1 |
function get_user_asset collection=none asset_id=none
begin
if collection == string settlement
begin
return call Settlement _id=asset_id
end
else
if collection == string survivor
begin
return call Survivor _id=asset_id normalize_on_init=true
end
else
if collection == string user
begin
return call User _id=asset_id
end
... | def get_user_asset(collection=None, asset_id=None):
if collection == "settlement":
return settlements.Settlement(_id=asset_id)
elif collection == "survivor":
return survivors.Survivor(_id=asset_id, normalize_on_init=True)
elif collection == "user":
return users.User(_id=asset_id)
... | Python | nomic_cornstack_python_v1 |
function plotSIR self memberSelection=none
begin
set rowTitles = list string S string I string R
set tuple fig ax = call subplots 3 1 sharex=true sharey=true
set simCount = length sims
if simCount == list
begin
print string no sims to show
return
end
else
begin
for sim in sims
begin
set title = sim at 1
set sim = sim ... | def plotSIR(self, memberSelection = None):
rowTitles = ['S','I','R']
fig, ax = plt.subplots(3,1,sharex = True, sharey = True)
simCount = len(self.sims)
if simCount == []:
print("no sims to show")
return
else:
for sim in self.sims:
... | Python | nomic_cornstack_python_v1 |
function parse_errors line
begin
comment we are not interested in traces
if string TRACE in line
begin
return list
end
set error_classes = list tuple string : error: dereference of already deleted heap object list string invalid tuple string : error: dereferencing object of size [0-9]*B out of bounds list string inval... | def parse_errors(line):
# we are not interested in traces
if 'TRACE' in line:
return []
error_classes = [
(': error: dereference of already deleted heap object', ['invalid']),
(': error: dereferencing object of size [0-9]*B out of bounds', ['invalid']),
(': error: dereferenc... | Python | nomic_cornstack_python_v1 |
import pytesseract
from PIL import Image
import pyttsx3
set img = open string quote1.jpg
set tesseract_cmd = string C:\Program Files\Tesseract-OCR\tesseract.exe
set result = call image_to_string img
with open string magic.txt mode=string w as file
begin
write file result
end
set engine = call init string sapi5
set voic... | import pytesseract
from PIL import Image
import pyttsx3
img = Image.open('quote1.jpg')
pytesseract.pytesseract.tesseract_cmd =r'C:\Program Files\Tesseract-OCR\tesseract.exe'
result = pytesseract.image_to_string(img)
with open('magic.txt',mode='w') as file:
file.write(result)
engine = pyttsx3.init('s... | Python | zaydzuhri_stack_edu_python |
import os
import pickle
import json
import random
import csv
import cv2
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras.layers import Convolution2D , MaxPooling2D , Ze... | import os
import pickle
import json
import random
import csv
import cv2
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras.layers import Convolution2D, MaxPooling2D, Ze... | Python | zaydzuhri_stack_edu_python |
function prefix_to_wildcard_mask prefix
begin
return call _ipv4_int_to_str call _prefix_to_wildcard_mask prefix
end function | def prefix_to_wildcard_mask(prefix):
return _ipv4_int_to_str(_prefix_to_wildcard_mask(prefix)) | Python | nomic_cornstack_python_v1 |
function Destroy *args **kwargs
begin
call own false
return call Window_Destroy *args keyword kwargs
end function | def Destroy(*args, **kwargs):
args[0].this.own(False)
return _core_.Window_Destroy(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
function get self
begin
set current_user = call get_current_user
return call get_items_by_user_id id
end function | def get(self):
current_user = fjwte.get_current_user()
return Todo.get_items_by_user_id(current_user.id) | Python | nomic_cornstack_python_v1 |
function compute_normalized_BB df rm rstd window
begin
set normalized_bb = call DataFrame index=index
for sym in columns
begin
set df_tmp = df at sym - rm at sym / 2 * rstd at sym
set normalized_bb = join normalized_bb df_tmp
end
comment Update the NaN values which are initial values for the
set ix at tuple slice : wi... | def compute_normalized_BB(df,rm,rstd,window):
normalized_bb=pd.DataFrame(index=df.index)
for sym in df.columns:
df_tmp= (df[sym] - rm[sym])/(2 * rstd[sym])
normalized_bb=normalized_bb.join(df_tmp)
# Update the NaN values which are initial values for the
normalized_bb.ix[:... | Python | nomic_cornstack_python_v1 |
import json
import os
from lxml import etree as E
from Tokenize import Tokenize
set file_name = 0
set doc_no = 0
set count = 1
function writeToFile finalDocNo wordDictWithOffset
begin
global count
comment global catalogCount
set catalogCount = 1
end function | import json
import os
from lxml import etree as E
from Tokenize import Tokenize
file_name = 0
doc_no = 0
count = 1
def writeToFile(finalDocNo,wordDictWithOffset):
global count
# global catalogCount
catalogCount = 1 | Python | zaydzuhri_stack_edu_python |
from transformers import BertTokenizer
from constants import constants
from more_itertools import padded , split_before
import re
function split_most_probable_paragraph paragraph_text
begin
return split paragraph_text string
end function
function pad_document self documents
begin
set document_split = list comprehension... | from transformers import BertTokenizer
from constants import constants
from more_itertools import padded, split_before
import re
def split_most_probable_paragraph(paragraph_text):
return paragraph_text.split(" ")
def pad_document(self, documents):
document_split = [re.split("(<P>) | (</P>)", d) for d in doc... | Python | zaydzuhri_stack_edu_python |
import time
import re
from base_crawler import BaseCrawler
from models.article import Article
class CarrefourCrawler extends BaseCrawler
begin
function __init__ self
begin
call __init__
end function
function get_product_urls self urls
begin
set result = list
for url in urls
begin
get self url
for product in call find_... | import time
import re
from .base_crawler import BaseCrawler
from models.article import Article
class CarrefourCrawler(BaseCrawler):
def __init__(self):
super(CarrefourCrawler, self).__init__()
def get_product_urls(self, urls):
result = []
for url in urls:
self.get(url)
... | Python | zaydzuhri_stack_edu_python |
function subjs cls db changeset
begin
set fname = call fname
execute db string SELECT DISTINCT sourceId FROM %(fname)s WHERE changeset = '%(changeset)s' % variables
return call ResultsGenerator db
end function | def subjs(cls, db, changeset):
fname = cls.fname()
db.execute("SELECT DISTINCT sourceId FROM %(fname)s WHERE changeset = '%(changeset)s'" % vars())
return db.ResultsGenerator(db) | Python | nomic_cornstack_python_v1 |
function raise_nofile nofile_atleast=4096
begin
comment %% (0) what is current ulimit -n setting?
set tuple soft ohard = call getrlimit RLIMIT_NOFILE
set hard = ohard
comment %% (1) increase limit (soft and even hard) if needed
if soft < nofile_atleast
begin
set soft = nofile_atleast
if hard < soft
begin
set hard = sof... | def raise_nofile(nofile_atleast: int = 4096) -> tuple[int, int]:
# %% (0) what is current ulimit -n setting?
soft, ohard = res.getrlimit(res.RLIMIT_NOFILE)
hard = ohard
# %% (1) increase limit (soft and even hard) if needed
if soft < nofile_atleast:
soft = nofile_atleast
if hard < s... | Python | nomic_cornstack_python_v1 |
function two_axis_subplot self num fields run_ts ref_ts colours=tuple string b string g
begin
set ax_left = call _add_subplot num
set ax_right = call twinx
call Axes fig call get_position sharex=ax_right
comment Plot ref results as black lines with markers
call read_data string time fields at 0
set ref_line = plot inde... | def two_axis_subplot(self, num, fields, run_ts, ref_ts,
colours=('b', 'g')):
ax_left = self._add_subplot(num)
ax_right = ax_left.twinx()
matplotlib.axes.Axes(self.fig, ax_left.get_position(), sharex=ax_right)
# Plot ref results as black lines with markers
... | Python | nomic_cornstack_python_v1 |
comment Author - Praveen Taneja
comment last updated - 01/20/16
import glob
import wx
import os
comment import sys
import csv
comment import pandas as pd
set fn_match = string *.csv
comment start_row = 12 # counting from 1
comment col_num = 4# counting from 1
function choose_dir
begin
set app = call App
set dialog = ca... | # Author - Praveen Taneja
# last updated - 01/20/16
import glob
import wx
import os
#import sys
import csv
#import pandas as pd
fn_match = '*.csv'
#start_row = 12 # counting from 1
#col_num = 4# counting from 1
def choose_dir():
app = wx.App()
dialog = wx.DirDialog(None, "Choose a directory:",style=wx.DD_D... | Python | zaydzuhri_stack_edu_python |
import boto3
import sys
from time import sleep
from operator import itemgetter
comment get instance list with filter
function get_aws_instance_filter ec2 filter_name
begin
clear instances
for i in all
begin
set tags = dictionary list comprehension tuple tag at string Key tag at string Value for tag in tags
if filter_na... | import boto3
import sys
from time import sleep
from operator import itemgetter
# get instance list with filter
def get_aws_instance_filter(ec2, filter_name):
instances.clear()
for i in ec2.instances.all():
tags = dict([(tag['Key'], tag['Value']) for tag in i.tags])
if (filter_name in tags['Name... | Python | zaydzuhri_stack_edu_python |
from difflib import SequenceMatcher
import csv
import re
import graphviz as gv
from string import digits
set SIMILARITY_THRESHOLD = 0.4
set START_LINE = string begin level control 1 replan
comment file_name = "test_log.txt"
set file_name = string test-logs/LevelControl1.txt
set regex = string [0-9]*-[0-9]*-[0-9]* [0-9]... | from difflib import SequenceMatcher
import csv
import re
import graphviz as gv
from string import digits
SIMILARITY_THRESHOLD = 0.4
START_LINE = "begin level control 1 replan"
#file_name = "test_log.txt"
file_name = 'test-logs/LevelControl1.txt'
regex = '[0-9]*-[0-9]*-[0-9]* [0-9]*:[0-9]*:[0-9]*,[0-9]* \[(.*)\] (\... | Python | zaydzuhri_stack_edu_python |
function calcMeanAndStdDev serie1 serie2 method
begin
set tuple type_method_in type_serie1_in type_serie2_in = tuple type method type serie1 type serie2
comment Uncomment while debugging
set corr_values = list
set serie2_name = name
seed 0
for cycle in range 5
begin
comment first convert serie2 to numpy, then shuffle ... | def calcMeanAndStdDev(serie1, serie2, method):
type_method_in, type_serie1_in, type_serie2_in = (
type(method),
type(serie1),
type(serie2),
) # Uncomment while debugging
corr_values = []
serie2_name = serie2.name
np.random.seed(0)
for cycle in range(5):
# first c... | Python | nomic_cornstack_python_v1 |
function get_all_channels
begin
set dao = call DAO
if method == string GET
begin
set session = call get_session
set channel_table = call get_table string channels
set the_channels = dict string channels list
for channel in call order_by chan_id
begin
info string channel = %s % channel
if channel
begin
append the_chann... | def get_all_channels():
dao = DAO()
if request.method == 'GET':
session = dao.get_session()
channel_table = dao.get_table("channels")
the_channels = { "channels" : [] }
for channel in session.query(Channel).order_by(channel_table.c.chan_id... | Python | nomic_cornstack_python_v1 |
function ny self
begin
return _ny
end function | def ny(self):
return self._ny | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
set img = call imread string yumeko.jpg
set gray_img = call cvtColor img COLOR_BGR2GRAY
function init image
begin
set new_image = zeros shape uint8
for r in range shape at 0
begin
for c in range shape at 1
begin
set new_image at tuple r c = integer image at tuple r c
end
end
return new_ima... | import cv2
import numpy as np
img = cv2.imread('yumeko.jpg')
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
def init(image):
new_image = np.zeros(image.shape,np.uint8)
for r in range(image.shape[0]):
for c in range(image.shape[1]):
new_image[r,c] = int(image[r,c])
return new_image
de... | Python | zaydzuhri_stack_edu_python |
comment https://projecteuler.net/problem=79
from time import time
set start = time
with open string files/p079_keylog.txt string r as file
begin
set attempts = list comprehension list strip string for string in file
set d = dict
for i in range 10
begin
set d at string i = set
end
for attempt in attempts
begin
add d at... | #https://projecteuler.net/problem=79
from time import time
start = time()
with open('files/p079_keylog.txt', 'r') as file:
attempts = [list(string.strip()) for string in file]
d = {}
for i in range(10):
d[str(i)] = set()
for attempt in attempts:
d[attempt[0]].add(attempt[1])
d[a... | Python | zaydzuhri_stack_edu_python |
function trainTBNNSModel features_list_train features_list_dev description model_path path_to_saver FLAGS=dict features_type=string F2 downsample_train=none downsample_dev=none
begin
comment Reads the list of files provided for features/labels
print format string {} file(s) were provided and will be used for training ... | def trainTBNNSModel(features_list_train, features_list_dev, description, model_path,
path_to_saver, *, FLAGS={}, features_type="F2",
downsample_train=None, downsample_dev=None,):
# Reads the list of files provided for features/labels
print("{} file(s) were prov... | Python | nomic_cornstack_python_v1 |
while n > cont + 1
begin
set n3 = n1 + n2
set n1 = n2
set n2 = n3
set cont = cont + 1
print string { n1 } ➞ end=string
end
print string FIM | while n > cont +1:
n3 = n1 +n2
n1 = n2
n2 = n3
cont += 1
print(f'{n1} ➞ ', end='')
print('FIM') | Python | zaydzuhri_stack_edu_python |
from happypass.basecommand import Command
class UpdateCommand extends Command
begin
set name = string update
set summary = string Update the credit infomation
function __init__ self
begin
call __init__
call add_argument string --name string -n action=string store dest=string name help=string The name of the credit
call... | from happypass.basecommand import Command
class UpdateCommand(Command):
name = 'update'
summary = 'Update the credit infomation'
def __init__(self):
super(UpdateCommand, self).__init__()
self.parser.add_argument(
'--name', '-n',
action='store',
dest='na... | Python | zaydzuhri_stack_edu_python |
function fahrenheit_to_celsius f
begin
set celsius = f - 32.0 * 5.0 / 9.0
return celsius
end function
set fahrenheit = 98.6
set celsius = call fahrenheit_to_celsius fahrenheit
print string The temperature in celsius is: celsius | def fahrenheit_to_celsius(f):
celsius = (f - 32.0) * (5.0/9.0)
return celsius
fahrenheit = 98.6
celsius = fahrenheit_to_celsius(fahrenheit)
print("The temperature in celsius is: ", celsius)
| Python | flytech_python_25k |
function start_notifications self
begin
string Start the notifications thread. If an external callback is not set up (using `update_webhook`) then calling this function is mandatory to get or set resource. .. code-block:: python >>> api.start_notifications() >>> print(api.get_resource_value(device, path)) Some value >>... | def start_notifications(self):
"""Start the notifications thread.
If an external callback is not set up (using `update_webhook`) then
calling this function is mandatory to get or set resource.
.. code-block:: python
>>> api.start_notifications()
>>> print(api.g... | Python | jtatman_500k |
function get_tab_by_id tab_list tab_id
begin
return next generator expression tab for tab in tab_list if tab_id == tab_id none
end function | def get_tab_by_id(tab_list, tab_id):
return next((tab for tab in tab_list if tab.tab_id == tab_id), None) | Python | nomic_cornstack_python_v1 |
function generate_dps wordcorpus
begin
print string Loading model
set model = call load_word2vec_format BIN_NAME binary=true
print string Model loaded!
comment Limit the corpus to words in the model
set wcl = list generator expression word for word in wordcorpus if word in vocab
comment Precompute word vectors so the l... | def generate_dps(wordcorpus):
print('Loading model')
model = KeyedVectors.load_word2vec_format(BIN_NAME, binary=True)
print('Model loaded!')
# Limit the corpus to words in the model
wcl = list(word for word in wordcorpus if word in model.vocab)
# Precompute word vectors so the loops ... | Python | nomic_cornstack_python_v1 |
string Created on Sep 4, 2017 @author: idolchevic
import numpy as np
import pandas as pd
import re
import unidecode
import matplotlib.pyplot as plt
import seaborn as sns
set df_pop_count = read csv string pop_count.csv index_col=list 0 1
comment get all areas
set all_areas = list unique
comment get all years since 1968... | '''
Created on Sep 4, 2017
@author: idolchevic
'''
import numpy as np
import pandas as pd
import re
import unidecode
import matplotlib.pyplot as plt
import seaborn as sns
df_pop_count = pd.read_csv('pop_count.csv', index_col=[0,1])
# get all areas
all_areas = list(df_pop_count.index.get_level_values('area').unique()... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
set bb_csv_path = string ../baseballdatabank-2019.2/core
set pitching = read csv string { bb_csv_path } /Pitching.csv index_col=list string playerID string yearID string stint usecols=list string playerID string yearID string stint string pIPouts string pG
set batting = read csv s... | import numpy as np
import pandas as pd
bb_csv_path = "../baseballdatabank-2019.2/core"
pitching = pd.read_csv(f"{bb_csv_path}/Pitching.csv", index_col=["playerID","yearID","stint"], usecols=["playerID","yearID","stint", "pIPouts", "pG"])
batting = pd.read_csv(f"{bb_csv_path}/Batting.csv", index_col=["playerID","yearI... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
class TextReader
begin
function read self file
begin
set f = open file string r
set atoms = list
for lines in f
begin
set lines = strip lines string
set content = split lines string
for j in range length content
begin
set content at j = call unicode content at j string utf-8
append atoms ... | import cv2
import numpy as np
class TextReader:
def read(self, file):
f = open(file,"r");
self.atoms = [];
for lines in f:
lines = lines.strip("\n");
content = lines.split(" ");
for j in range(len(content)):
content[j] = unicode(content[j]... | Python | zaydzuhri_stack_edu_python |
set start = 5
set end = 100
print string Prime numbers between start string and end string are:
for num in range start end + 1
begin
if num > 1
begin
set is_prime = true
for i in range 2 integer num / 2 + 1
begin
if num % i == 0
begin
set is_prime = false
break
end
end
if is_prime
begin
print num
end
end
end | start = 5
end = 100
print("Prime numbers between", start, "and", end, "are:")
for num in range(start, end+1):
if num > 1:
is_prime = True
for i in range(2, int(num/2)+1):
if (num % i) == 0:
is_prime = False
break
if is_prime:
print(nu... | Python | jtatman_500k |
function plot_specs_surface_change_monthly2pdf arr res=string 4x5 dpi=160 no_dstr=true f_size=20 pcent=true specs=none dlist=none savetitle=string diff=false extend=string neither column=false scale=1 units=none set_window=false lat_0=none lat_1=none mask_invalids=false debug=false
begin
info string plot_specs_surface... | def plot_specs_surface_change_monthly2pdf(arr, res='4x5', dpi=160,
no_dstr=True, f_size=20, pcent=True, specs=None,
dlist=None,
savetitle='', diff=False, extend='neither',
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
function safe_float obj
begin
try
begin
set retval = decimal obj
end
comment ValueError, e:
except any
begin
set retval = string error happens
end
try else
begin
set retval = string no exceptions caught
end
return retval
end function
function main
begin
set obj = input string please enter ... | #!/usr/bin/env python3
def safe_float(obj):
try:
retval = float(obj)
except: #ValueError, e:
retval = "error happens"
else:
retval = "no exceptions caught\n"
return retval
def main():
obj = input("please enter a float number: ")
val = safe_float(obj)
print(val)
if ... | Python | zaydzuhri_stack_edu_python |
function isUnique str
begin
set arr = list false * 128
comment Bonus pts...converts it to const time.
if length str > 128
begin
return false
end
for char in str
begin
if arr at ordinal char
begin
return false
end
set arr at ordinal char = true
end
return true
end function
print call isUnique string yolo == false
print ... | def isUnique(str):
arr=[False]*128
#Bonus pts...converts it to const time.
if(len(str)>128):
return False
for char in str:
if(arr[ord(char)]):
return False
arr[ord(char)] = True
return True
print(isUnique("yolo")== False)
print(isUnique("rad")== True)
print(isUni... | Python | zaydzuhri_stack_edu_python |
import sys
set stdin = open string input2.txt string r
function mb i
begin
set b_top1 = - 1
set b_top2 = - 1
set b_stack1 = list 0 * n
set b_stack2 = list 0 * n
while case at i == string )
begin
if is digit case at i
begin
set b_top1 = b_top1 + 1
set b_stack1 at b_top1 = integer case at i
end
else
if case at i == strin... | import sys
sys.stdin = open("input2.txt", "r")
def mb(i):
b_top1 = -1
b_top2 = -1
b_stack1 = [0] * n
b_stack2 = [0] * n
while case[i] == ')':
if case[i].isdigit():
b_top1 += 1
b_stack1[b_top1] = int(case[i])
elif case[i] =='(':
b_stack1 + mb(i)
... | Python | zaydzuhri_stack_edu_python |
import logging , argparse
from common.initlogger import initloggerconfiguration
from simulator import simulatorengine
if __name__ == string __main__
begin
set games = list
set config_file = open string games_list.txt string r
for line in read lines config_file
begin
if line at 0 != string #
begin
append games split li... | import logging, argparse
from common.initlogger import initloggerconfiguration
from simulator import simulatorengine
if __name__ == "__main__":
games = []
config_file = open("games_list.txt", "r")
for line in config_file.readlines():
if line[0] != "#":
games.append(line.split()[0])
... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function minOperations self nums1 nums2
begin
set res = 0
set maxPossible1 = 6 * length nums1
set minPossible1 = length nums1
set maxPossible2 = 6 * length nums2
set minPossible2 = length nums2
if minPossible1 > maxPossible2 or minPossible2 > maxPossible1
begin
return - 1
end
set dif... | class Solution(object):
def minOperations(self, nums1, nums2):
res = 0
maxPossible1 = 6 * len(nums1)
minPossible1 = len(nums1)
maxPossible2 = 6 * len(nums2)
minPossible2 = len(nums2)
if minPossible1 > maxPossible2 or minPossible2 > maxPossible1:
return -1
... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python3
comment collection_deque implementation using collection.deque class
comment Use append() to add and popleft() elements in FiFo order
comment Deque if preferred over list because append is quicker [ O(1) ], but
comment pop operations as compared to list [ O(n) ]
from collections import deque
set c... | #!/bin/python3
#collection_deque implementation using collection.deque class
#Use append() to add and popleft() elements in FiFo order
# Deque if preferred over list because append is quicker [ O(1) ], but
# pop operations as compared to list [ O(n) ]
from collections import deque
collection_deque = deque()
# ap... | Python | zaydzuhri_stack_edu_python |
function submit_pipeline_jobs pipeline_file args
begin
set tempDict = dict
comment project name too long. Job not submitted.
set tempDict at string project_name = split string jid string .py at 0 at slice : 10 :
set argsDict = variables args
comment print argsDict
set tuple myList myJobs = call parse_LSF_job_specifi... | def submit_pipeline_jobs(pipeline_file,args):
tempDict = {}
tempDict['project_name'] = str(args.jid).split(".py")[0][:10] ## project name too long. Job not submitted.
argsDict = vars(args)
# print argsDict
myList,myJobs = parse_LSF_job_specification(pipeline_file)
myJobID_list = [] ## for backtrack if an... | Python | nomic_cornstack_python_v1 |
function edit self hardware_id userdata=none hostname=none domain=none notes=none
begin
set obj = dict
if userdata
begin
call setUserMetadata list userdata id=hardware_id
end
if hostname
begin
set obj at string hostname = hostname
end
if domain
begin
set obj at string domain = domain
end
if notes
begin
set obj at stri... | def edit(self, hardware_id, userdata=None, hostname=None, domain=None,
notes=None):
obj = {}
if userdata:
self.hardware.setUserMetadata([userdata], id=hardware_id)
if hostname:
obj['hostname'] = hostname
if domain:
obj['domai... | Python | nomic_cornstack_python_v1 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
from datetime import datetime
import argparse
from itertools import product
import random
import torch
import torch.optim as optim
import torch.nn as nn
from torch.utils.data import DataLoader
from d... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
from datetime import datetime
import argparse
from itertools import product
import random
import torch
import torch.optim as optim
import torch.nn as nn
from torch.utils.data import DataLoader
fro... | Python | zaydzuhri_stack_edu_python |
function least_squares_GD y tx initial_w max_iters gamma
begin
set tuple losses w = call gradient_descent_mse y tx initial_w max_iters gamma
return tuple w at - 1 losses at - 1
end function | def least_squares_GD(y, tx, initial_w, max_iters, gamma):
losses, w = gradient_descent_mse(y, tx, initial_w, max_iters, gamma)
return w[-1], losses[-1] | Python | nomic_cornstack_python_v1 |
comment encoding: utf-8
string @author: Kaiqi Yuan @software: PyCharm @file: utils.py @time: 18-6-13 上午8:35 @description:
import pickle
import random
import numpy as np
import prettytensor as pt
import tensorflow as tf
function build_drug_feature_matrix ddi_file file_prefix targetfile
begin
set drugs_list = call load_d... | # encoding: utf-8
"""
@author: Kaiqi Yuan
@software: PyCharm
@file: utils.py
@time: 18-6-13 上午8:35
@description:
"""
import pickle
import random
import numpy as np
import prettytensor as pt
import tensorflow as tf
def build_drug_feature_matrix(ddi_file, file_prefix, targetfile):
drugs_list = load_drugs_list(ddi_... | Python | zaydzuhri_stack_edu_python |
import os
import json
import sys
set dir = directory name path __file__
set infile = absolute path path join path dir string .. argv at 1
set outfile = absolute path path join path dir string .. argv at 2
function is_unicode tweet
begin
if not any generator expression ordinal string c > 31 and ordinal string c < 128 fo... | import os
import json
import sys
dir = os.path.dirname(__file__)
infile=os.path.abspath(os.path.join(dir,'..',sys.argv[1]))
outfile=os.path.abspath(os.path.join(dir,'..',sys.argv[2]))
def is_unicode(tweet):
if not any(ord(str(c)) > 31 and ord(str(c)) < 128 for c in tweet) :
return True
else:
... | Python | zaydzuhri_stack_edu_python |
import unittest
from knn import Knn
class KnnTestCase extends TestCase
begin
set knn = call Knn 3
set elementos = list list list 0 0 0 0 0 list list 0 0 0 1 1 list list 0 0 0 2 2 list list 0 0 0 0 0
end class | import unittest
from knn import Knn
class KnnTestCase(unittest.TestCase):
self.knn = Knn(3)
self.knn.elementos = [[[0, 0, 0, 0], 0], [[0, 0, 0, 1], 1], [[0, 0, 0, 2], 2], [[0, 0, 0, 0], 0]]
| Python | zaydzuhri_stack_edu_python |
comment -*-coding:utf-8 -*-
import math
import numpy as np
import random
from matplotlib import pyplot as plt
class GA_int_encoding
begin
comment 函数功能:GA类的构造函数
comment 函数输入:
comment 函数输出:
function __init__ self population_size crossover_probability mutation_probability coordinate
begin
set coordinate = coordinate
comme... | # -*-coding:utf-8 -*-
import math
import numpy as np
import random
from matplotlib import pyplot as plt
class GA_int_encoding:
# 函数功能:GA类的构造函数
# 函数输入:
# 函数输出:
def __init__(self, population_size, crossover_probability, mutation_probability, coordinate):
self.coordinate = coordin... | Python | zaydzuhri_stack_edu_python |
function getTableCellRendererComponent self table value isSelected hasFocus rowIndex columnIndex
begin
set comp = call getTableCellRendererComponent self table value isSelected hasFocus rowIndex columnIndex
set modelRow = call convertRowIndexToModel rowIndex
set percentSameStatus = call getValueAt modelRow 3
set percen... | def getTableCellRendererComponent(self, table, value, isSelected, hasFocus, rowIndex, columnIndex):
comp = DefaultTableCellRenderer.getTableCellRendererComponent(self, table, value, isSelected, hasFocus, rowIndex, columnIndex)
modelRow = table.convertRowIndexToModel(rowIndex)
percentSameStatus... | Python | nomic_cornstack_python_v1 |
comment 1020. 飞地的数量
comment https://leetcode-cn.com/problems/number-of-enclaves/
from typing import List
class Solution
begin
function numEnclaves self grid
begin
function dfs grid i j
begin
if 0 <= i < length grid and 0 <= j < length grid at 0 and grid at i at j == 1
begin
set grid at i at j = 0
call dfs grid i + 1 j
... | # 1020. 飞地的数量
# https://leetcode-cn.com/problems/number-of-enclaves/
from typing import List
class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
def dfs(grid, i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == 1:
grid[i][j] = 0
... | Python | zaydzuhri_stack_edu_python |
function calculate_variance beta
begin
set tuple n T = shape
set betadot = call gradient beta 1.0 / T - 1
set betadot = betadot at 1
set normbetadot = zeros T
set centroid = call calculatecentroid beta
set integrand = zeros tuple n n T
set t = linear space 0 1 T
for i in range 0 T
begin
set normbetadot at i = norm beta... | def calculate_variance(beta):
n, T = beta.shape
betadot = gradient(beta, 1. / (T - 1))
betadot = betadot[1]
normbetadot = zeros(T)
centroid = calculatecentroid(beta)
integrand = zeros((n, n, T))
t = linspace(0, 1, T)
for i in range(0, T):
normbetadot[i] = norm(betadot[:, i])
... | Python | nomic_cornstack_python_v1 |
function _create_placeholders self
begin
with call name_scope string input_data
begin
set input_tokens = call placeholder shape=tuple none look_back dtype=float32 name=string input_tokens
end
with call name_scope string output_data
begin
set output_tokens = call placeholder shape=tuple none look_back dtype=int32 name=s... | def _create_placeholders(self):
with tf.name_scope("input_data"):
self.input_tokens=tf.placeholder(shape=(None,self.look_back), dtype=tf.float32,name='input_tokens')
with tf.name_scope("output_data"):
self.output_tokens=tf.placeholder(shape=(None,self.look_back),dtype=tf.int32,name='output_tokens') | Python | nomic_cornstack_python_v1 |
comment from itertools import combinations
from typing import List
from math import sqrt
class Solution
begin
function bulbSwitch self n
begin
comment NOTE: 因数成对出现, 完全平方数会出现奇数个因数
return integer square root n
end function
end class
function main
begin
set sol = call Solution
set n = 3
assert call bulbSwitch n == 1
set n... | # from itertools import combinations
from typing import List
from math import sqrt
class Solution:
def bulbSwitch(self, n: int) -> int:
# NOTE: 因数成对出现, 完全平方数会出现奇数个因数
return int(sqrt(n))
def main():
sol = Solution()
n = 3
assert sol.bulbSwitch(n) == 1
n = 5
assert sol.bulbSwi... | Python | zaydzuhri_stack_edu_python |
function get_capabilities self
begin
set service = call __get_service
set capability = call __get_capability
set contents = dict string service service ; string capability capability
return tuple contents params at string format
end function | def get_capabilities(self):
service = self.__get_service()
capability = self.__get_capability()
contents = {"service" : service, "capability" : capability}
return contents, self.params['format'] | Python | nomic_cornstack_python_v1 |
for i in range length num
begin
if length num == 1
begin
set sum = num
break
end
if i == 0
begin
set sum = list num at - 1 + num at i + 1
end
else
if i == length num - 1
begin
set sum = sum + list num at 0 + num at i - 1
end
else
begin
set sum = sum + list num at i - 1 + num at i + 1
end
end
for i in range length sum
b... | for i in range(len(num)):
if len(num) == 1:
sum = num
break
if i == 0:
sum = [num[-1] + num[i+1]]
elif i == len(num)-1:
sum += [num[0] + num[i-1]]
else:
sum += [num[i-1] + num[i+1]]
for i in range(len(sum)):
print(sum[i], '', end='') | Python | zaydzuhri_stack_edu_python |
comment @ReservedAssignment
function hash path hash_function=sha512
begin
string Hash file or directory. Parameters ---------- path : ~pathlib.Path File or directory to hash. hash_function : ~typing.Callable[[], hash object] Function which creates a hashlib hash object when called. Defaults to ``hashlib.sha512``. Retur... | def hash(path, hash_function=hashlib.sha512): # @ReservedAssignment
'''
Hash file or directory.
Parameters
----------
path : ~pathlib.Path
File or directory to hash.
hash_function : ~typing.Callable[[], hash object]
Function which creates a hashlib hash object when called. Defa... | Python | jtatman_500k |
comment Script que toma como primer argumento un alineamiento y extrae el subalineamiento
comment donde esta nuestra muestra de interes
import sys
import re
from Bio import SeqIO , AlignIO
set infile = argv at 1
set name = sub string _aln.* string infile
set file = open infile string r
set output_name = string name + ... | # Script que toma como primer argumento un alineamiento y extrae el subalineamiento
# donde esta nuestra muestra de interes
import sys
import re
from Bio import SeqIO, AlignIO
infile = sys.argv[1]
name = re.sub("_aln.*", "", infile)
file = open(infile, "r")
output_name = str(name) + "_subaln.fasta"
output = open(outp... | Python | zaydzuhri_stack_edu_python |
comment voidcarro
set vet = list 0 1
set cont = integer 1
set i = integer 2
set ultimo = integer
set penultimo = integer
while true
begin
try
begin
set n = integer input
if n == 0 or n == 1
begin
print vet at n - 1
end
else
begin
while i <= n
begin
set ultimo = vet at i - 1
set penultimo = vet at i - 2
if cont == 2
beg... | #voidcarro
vet = [0,1]
cont = int(1)
i = int(2)
ultimo = int()
penultimo = int()
while True:
try:
n = int(input())
if n == 0 or n == 1:
print(vet[n-1])
else:
while i <= n:
ultimo = vet[i-1]
penultimo = vet[i-2]
if cont == 2:
vet.append(ultimo*penultimo)
cont = 1;
else:
... | Python | zaydzuhri_stack_edu_python |
function student_courses self
begin
return keys _student_courses
end function | def student_courses(self):
return self._student_courses.keys() | Python | nomic_cornstack_python_v1 |
function get_chip self window out_shape=none
begin
set sub_chips = call _get_sub_chips window raw=false out_shape=out_shape
set chip = stack sub_chips
for transformer in raster_transformers
begin
set chip = transform transformer chip channel_order
end
return chip
end function | def get_chip(self,
window: Box,
out_shape: Optional[Tuple[int, int]] = None) -> np.ndarray:
sub_chips = self._get_sub_chips(window, raw=False, out_shape=out_shape)
chip = np.stack(sub_chips)
for transformer in self.raster_transformers:
chip = transf... | Python | nomic_cornstack_python_v1 |
function best_fitness self
begin
return fitness
end function | def best_fitness(self):
return self._population[0].fitness | Python | nomic_cornstack_python_v1 |
comment 배열을 k번 회전시키기
function solution A K
begin
if length A == 0
begin
return A
end
else
begin
set K = K % length A
print string len(A) >> length A
print string K >> K end=string
end
print A at slice - K : :
print A at slice : - K : end=string
return A at slice - K : : + A at slice : - K :
end function
comment ... | # 배열을 k번 회전시키기
def solution(A, K):
if len(A) == 0:
return A
else:
K = K % len(A)
print('len(A) >> ', len(A))
print('K >>', K, end="\n\n")
print(A[-K:])
print(A[:-K], end="\n\n")
return A[-K:] + A[:-K]
# A = [3,8,9,7,6]
A = [1,2,3,4]
K = 4
# [6,3,8,9,7]
# [7,6,3,8,... | Python | zaydzuhri_stack_edu_python |
function closest_allele mhc pickle_path
begin
set mhc = call mhc_allele_group_protein_naming mhc
set examples_per_allele = load pickle open join path MHCNUGGETS_HOME pickle_path string rb
set alleles = sorted examples_per_allele
comment search for exact match
set match = call exact_match mhc alleles
if match
begin
retu... | def closest_allele(mhc,pickle_path):
mhc = mhc_allele_group_protein_naming(mhc)
examples_per_allele = pickle.load(open(os.path.join(MHCNUGGETS_HOME,pickle_path), 'rb'))
alleles = sorted(examples_per_allele)
# search for exact match
match = exact_match(mhc, alleles)
if match:
return mat... | Python | nomic_cornstack_python_v1 |
function SetIsDown self isDown
begin
set isDown = isDown
end function | def SetIsDown(self, isDown):
self.isDown = isDown | Python | nomic_cornstack_python_v1 |
import pandas as pd
set file = string D://Luis/Programming/Python/util-scripts-py/files/people.csv
set data = read csv file encoding=string utf-8
comment Printing Type
comment print(type(data))
comment Printing Data
describe data at string age
print data
comment Print out three rows instead
comment print(data.head(2)) | import pandas as pd
file = 'D://Luis/Programming/Python/util-scripts-py/files/people.csv'
data = pd.read_csv(file, encoding='utf-8')
#Printing Type
#print(type(data))
#Printing Data
data['age'].describe()
print(data)
#Print out three rows instead
#print(data.head(2)) | Python | zaydzuhri_stack_edu_python |
function BuildSymbolToFileAddressMapping
begin
set result = default dictionary list
comment Iterate over all the extracted_symbols_*.txt files.
for filename in list directory work_directory
begin
print string Checking filename %s % filename
if call fnmatch filename string extracted_symbols_*.txt
begin
print string Proc... | def BuildSymbolToFileAddressMapping():
result = defaultdict(list)
# Iterate over all the extracted_symbols_*.txt files.
for filename in os.listdir(FLAGS.work_directory):
print("Checking filename %s" % filename)
if fnmatch.fnmatch(filename, "extracted_symbols_*.txt"):
print("Processing file %s" % fil... | Python | nomic_cornstack_python_v1 |
import os
import json
import datetime
function is_num input
begin
try
begin
set input = integer input
return true
end
except ValueError
begin
try
begin
set input = decimal input
return true
end
except ValueError
begin
return false
end
end
end function
function get_num_from_str str
begin
try
begin
set num = integer str
... | import os
import json
import datetime
def is_num(input):
try:
input = int(input)
return True
except ValueError:
try:
input = float(input)
return True
except ValueError:
return False
def get_num_from_str(str):
try:
num = int(str)
return num
except ValueError:
try:
... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
set driver = call Chrome executable_path=string C:/Users\zakharove\drivers\chromedriver.exe
get driver string https://www.countries-ofthe-world.com/flags-of-the-world.html
comment maximize window size
call maximize_window
comment driver.execute_script("window.scrollBy(0, 1000)", "") # scr... | from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:/Users\zakharove\drivers\chromedriver.exe")
driver.get("https://www.countries-ofthe-world.com/flags-of-the-world.html")
driver.maximize_window() # maximize window size
# driver.execute_script("window.scrollBy(0, 1000)", "") # scroll down b... | Python | zaydzuhri_stack_edu_python |
function _extract_marine_fields data fields
begin
set extracted = dict
set data = split data string ,
if not length data == length _marine_fieldmap
begin
error string Data and field-map lengths do not match. Data: { data }
return none
end
for tuple i field in enumerate _marine_fieldmap
begin
if lower field in fields
b... | def _extract_marine_fields(data: str, fields: List[str]):
extracted = {}
data = data.split(',')
if not len(data) == len(_marine_fieldmap):
LOG.error(f"Data and field-map lengths do not match.\nData: {data}")
return None
for i, field in enumerate(_marine_fieldmap):
if field.lower(... | Python | nomic_cornstack_python_v1 |
function _next_train self
begin
if batching == string single_image
begin
set image_index = random integer 0 n_examples tuple
set ray_indices = random integer 0 batch_shape at 1 tuple batch_size
comment --------------------------------------------------------------------------------------
comment Get batch pixels and ra... | def _next_train(self):
if self.batching == "single_image":
image_index = np.random.randint(0, self.n_examples, ())
ray_indices = np.random.randint(0, self.rays.batch_shape[1],
(self.batch_size,))
#--------------------------------------------------------------... | Python | nomic_cornstack_python_v1 |
from Bucket import *
string Biblioteca Principal Nesta biblioteca implementou se as principais funções e objetos para que o Hashing Linear funcione. A class que define o objeto Hashing Linear é responsavel por receber os parâmetros principais do hashing e dos registros que irão ser armazenados e também por implementar ... | from Bucket import *
'''
Biblioteca Principal
Nesta biblioteca implementou se as principais funções e objetos para que o Hashing Linear funcione.
A class que define o objeto Hashing Linear é responsavel por receber os parâmetros principais do hashing e dos registros que irão ser armazenados e
também por implementar as... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.