code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import grapher
from chronograph import Chronograph as Chrono
from memograph import Memograph as Memo
import finder
from textgen import Textgen
import statistics
import PyPDF2
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from textwrap import wr... | import grapher
from chronograph import Chronograph as Chrono
from memograph import Memograph as Memo
import finder
from textgen import Textgen
import statistics
import PyPDF2
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from textwrap import wr... | Python | zaydzuhri_stack_edu_python |
function check_entries entries message=string
begin
set has_entries = list comprehension call GetEntries > 0 for c in entries
if not any has_entries
begin
if message
begin
print string Skipping 0 entries (%s) % message
end
else
begin
print string Skipping 0 entries
end
return false
end
set max_bin = max list comprehens... | def check_entries(entries, message=""):
has_entries = [c.obj.GetEntries() > 0 for c in entries]
if not any(has_entries):
if message:
print("Skipping 0 entries (%s)" % (message))
else:
print("Skipping 0 entries")
return False
ma... | Python | nomic_cornstack_python_v1 |
async function async_setup hass
begin
async function hook action config_key
begin
string post_write_hook for Config View that reloads groups.
await call async_call DOMAIN SERVICE_RELOAD_CORE_CONFIG
end function
call register_view call CustomizeConfigView string customize string config CONFIG_PATH entity_id dict post_wr... | async def async_setup(hass):
async def hook(action, config_key):
"""post_write_hook for Config View that reloads groups."""
await hass.services.async_call(DOMAIN, SERVICE_RELOAD_CORE_CONFIG)
hass.http.register_view(
CustomizeConfigView(
"customize", "config", CONFIG_PATH, c... | Python | nomic_cornstack_python_v1 |
from fractions import Fraction
set a = eval input string Numaratorul 1=
set b = eval input string Numitorul 1=
set c = eval input string Numaratorul 2=
set d = eval input string Numaratorul 2=
set suma = call Fraction a b + call Fraction c d
set produsul = call Fraction a b * call Fraction c d
print string suma= suma
p... | from fractions import Fraction
a=eval(input("Numaratorul 1="))
b=eval(input("Numitorul 1="))
c=eval(input("Numaratorul 2="))
d=eval(input("Numaratorul 2="))
suma= Fraction(a,b)+Fraction(c,d)
produsul=Fraction(a,b)*Fraction(c,d)
print("suma=",suma)
print("produsul=",produsul) | Python | zaydzuhri_stack_edu_python |
import CardFuncs
import random
from tkinter import *
from tkinter import ttk
set num_cards = 0
set card_deck = list
class Player
begin
function __init__ self num_cards=0 num_aces=0 arrCard=list
begin
set num_cards = num_cards
set num_aces = num_aces
set arrCard = arrCard
end function
comment Class method to calculate ... | import CardFuncs
import random
from tkinter import *
from tkinter import ttk
num_cards = 0;
card_deck = [];
class Player:
def __init__(self, num_cards=0, num_aces=0, arrCard = []):
self.num_cards = num_cards;
self.num_aces = num_aces;
self.arrCard = arrCard
def handtot(self): ... | Python | zaydzuhri_stack_edu_python |
function dados_pessoais nome sobrenome idade sexo
begin
print format string Nome: {} Sobrenome: {} Idade: {} Sexo: {} nome sobrenome idade sexo
end function
call dados_pessoais string rafael string Carvalho 30 true
call dados_pessoais nome=string Rafael sobrenome=string Carvalho idade=30 sexo=string Masculino | def dados_pessoais(nome, sobrenome, idade, sexo):
print("Nome: {}\nSobrenome: {}\nIdade: {}\nSexo: {}"
.format(nome, sobrenome, idade, sexo))
dados_pessoais("rafael", "Carvalho", 30, True)
dados_pessoais(nome="Rafael", sobrenome="Carvalho", idade=30, sexo="Masculino") | Python | zaydzuhri_stack_edu_python |
function generate_s3_bucket
begin
string Create the blockade bucket if not already there.
debug string [#] Setting up S3 bucket
set client = call client string s3 region_name=PRIMARY_REGION
set buckets = call list_buckets
set matches = list comprehension x for x in get buckets string Buckets list if starts with x at st... | def generate_s3_bucket():
"""Create the blockade bucket if not already there."""
logger.debug("[#] Setting up S3 bucket")
client = boto3.client("s3", region_name=PRIMARY_REGION)
buckets = client.list_buckets()
matches = [x for x in buckets.get('Buckets', list())
if x['Name'].startswit... | Python | jtatman_500k |
function checkOracleCouchDbConsistency self config testRequestName
begin
comment TODO 1:
comment this list is not exhaustive and will be modified / amended
comment should be checked if the request parameter actually exists in
comment in both databases ... later this explicit list should be removed
comment and check wil... | def checkOracleCouchDbConsistency(self, config, testRequestName):
# TODO 1:
# this list is not exhaustive and will be modified / amended
# should be checked if the request parameter actually exists in
# in both databases ... later this explicit list should be removed
# and check ... | Python | nomic_cornstack_python_v1 |
function kml_data filename
begin
set kml_details = list
with open filename string r as csvfile
begin
set spamreader = reader csvfile delimiter=string , quotechar=string |
for row in spamreader
begin
try
begin
set name = row at 0
append kml_details name
set long = decimal row at 1 + decimal row at 2 / 60
append kml_det... | def kml_data(filename):
kml_details = []
with open(filename, 'r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in spamreader:
try:
name = row[0]
kml_details.append(name)
long = float(row[1]) + (floa... | Python | nomic_cornstack_python_v1 |
comment Ejercicio 1
comment Crear dos variables que representen dos productos, asignarle un precio
set producto_uno = 265
set producto_dos = 324.5
comment Ejercicio 2
comment Aplicarle iva (16% adicional del precio)
set iva = 0.16
set producto_uno_con_iva = producto_uno * 1 + iva
set producto_dos_con_iva = producto_dos... | ### Ejercicio 1
#
# Crear dos variables que representen dos productos, asignarle un precio
producto_uno = 265
producto_dos = 324.50
### Ejercicio 2
#
# Aplicarle iva (16% adicional del precio)
iva = 0.16
producto_uno_con_iva = producto_uno * (1 + iva)
producto_dos_con_iva = producto_dos * (1 + iva)
print("El preci... | Python | zaydzuhri_stack_edu_python |
comment Print the average of all the numbers from 0 to the given limit that are divisible by the given number
set limit = input string Enter limit:
set sum = 0
for i in range 0 integer limit + 1
begin
set sum = sum + i
end
set avg = sum / integer limit
print avg | # Print the average of all the numbers from 0 to the given limit that are divisible by the given number
limit = input("Enter limit: ")
sum = 0
for i in range(0, int(limit) + 1):
sum += i
avg = sum / int(limit)
print(avg)
| Python | zaydzuhri_stack_edu_python |
function grayscale img
begin
return call cvtColor img COLOR_RGB2GRAY
end function
comment Or use BGR2GRAY if you read an image with cv2.imread()
comment return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | def grayscale(img):
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
| Python | nomic_cornstack_python_v1 |
function __AddMultiQuery self identifier condition value enumerated_queries
begin
if lower condition in tuple string != string in and _keys_only
begin
raise call BadQueryError string Keys only queries do not support IN or != filters.
end
function CloneQueries queries n
begin
string Do a full copy of the queries and app... | def __AddMultiQuery(self, identifier, condition, value, enumerated_queries):
if condition.lower() in ('!=', 'in') and self._keys_only:
raise datastore_errors.BadQueryError(
'Keys only queries do not support IN or != filters.')
def CloneQueries(queries, n):
"""Do a full copy of the queries a... | Python | nomic_cornstack_python_v1 |
from lexer.lexer_utils import Position , Token
from utils.common_utils import interval
from functools import partial
import pydot
class Term extends object
begin
function __init__ self root
begin
set _root = root
end function
function sort_traversal self up_match_dict=tuple down_match_dict=tuple
begin
function _match ... | from lexer.lexer_utils import Position, Token
from utils.common_utils import interval
from functools import partial
import pydot
class Term(object):
def __init__(self, root):
self._root = root
def sort_traversal(self, up_match_dict=(), down_match_dict=()):
def _match(match_dict, node):
... | Python | zaydzuhri_stack_edu_python |
function log_popen p log_dir
begin
call check_dir string log_dir make_if_not=true
set tuple out err = communicate p
if out
begin
with open string w as f
begin
write f decode out
end
end
if err
begin
with open string w as f
begin
write f decode err
end
return false
end
return true
end function | def log_popen(p: Popen, log_dir: Path) -> bool:
check_dir(str(log_dir), make_if_not=True)
out, err = p.communicate()
if out:
with (log_dir / 'out.log').open('w') as f:
f.write(out.decode())
if err:
with (log_dir / 'err.log').open('w') as f:
f.write(err.decode())
... | Python | nomic_cornstack_python_v1 |
comment “student. a am I”
comment 两次翻转
class Solution
begin
function ReverseSentence self s
begin
set s_len = length s
set s = list s
set i = 0
set j = s_len - 1
while i < j
begin
set tuple s at i s at j = tuple s at j s at i
set i = i + 1
set j = j - 1
end
set i = 0
for tuple index v in enumerate s
begin
if v == strin... | # “student. a am I”
#两次翻转
class Solution:
def ReverseSentence(self, s):
s_len = len(s)
s = list(s)
i = 0
j = s_len - 1
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
i = 0
for index, v in enumerate(s):
if v... | Python | zaydzuhri_stack_edu_python |
function removeChild self childName
begin
try
begin
del __children at childName
return true
end
except KeyError
begin
return false
end
end function | def removeChild(self,childName):
try:
del self.__children[childName]
return True
except KeyError:
return False | Python | nomic_cornstack_python_v1 |
function format_dataset_char_level texts labels metadata trained_char_index=none
begin
if not trained_char_index
begin
print string -------Creating character set...
set all_text = join string texts
set chars = set all_text
print string CHARACTER SET: chars
print string Total Chars: %i % length chars
set char_index = d... | def format_dataset_char_level(texts, labels, metadata, trained_char_index=None):
if not trained_char_index:
print('\n-------Creating character set...')
all_text = ''.join(texts)
chars = set(all_text)
print("CHARACTER SET:", chars)
print('Total Chars: %i' % len(chars))
... | Python | nomic_cornstack_python_v1 |
function get_pwreset_state email_code
begin
set mail_expiration_time = email_code_timeout
set sms_expiration_time = phone_code_timeout
try
begin
set state = call get_state_by_email_code email_code raise_on_missing=true
debug string Found state using email_code { email_code } : { state }
comment assure mypy, raise_on_mi... | def get_pwreset_state(email_code: str) -> Union[ResetPasswordEmailState, ResetPasswordEmailAndPhoneState]:
mail_expiration_time = current_app.conf.email_code_timeout
sms_expiration_time = current_app.conf.phone_code_timeout
try:
state = current_app.password_reset_state_db.get_state_by_email_code(ema... | Python | nomic_cornstack_python_v1 |
import pickle
import cv2
import numpy as np
import matplotlib.pyplot as plt
from svd_estimate import display_lines
from scipy import interpolate
from svd_ransac import generate_lines
from svd_paral import generate_lines_paral
from utils import dist as get_dist
comment Meta ##
comment width to length ratio of stop sign ... | import pickle
import cv2
import numpy as np
import matplotlib.pyplot as plt
from svd_estimate import display_lines
from scipy import interpolate
from svd_ransac import generate_lines
from svd_paral import generate_lines_paral
from utils import dist as get_dist
## Meta ##
W2L = 1.9 / 29 # width to length ratio of stop ... | Python | zaydzuhri_stack_edu_python |
function set_pages self selenium
begin
set dispatch : Dispatch = call Dispatch selenium
end function | def set_pages(self, selenium: fixture) -> None:
self.dispatch: Dispatch = Dispatch(selenium) | Python | nomic_cornstack_python_v1 |
function addMutationHandler self mutation_handler weight=1 *args
begin
append mutation_handlers mutation_handler
append mutation_handlers_weights weight
set xtra_args = list
for arg in args
begin
append xtra_args arg
end
update mutation_external_data dict mutation_handler tuple xtra_args
end function | def addMutationHandler(self,mutation_handler, weight = 1, *args):
self.mutation_handlers.append(mutation_handler)
self.mutation_handlers_weights.append(weight)
xtra_args = []
for arg in args:
xtra_args.append(arg)
self.mutation_external_data.update({mutation_handler:tuple(xtra_args)}) | Python | nomic_cornstack_python_v1 |
function esMayor usuario
begin
return edad > 17
end function
class Usuario
begin
function __init__ self edad
begin
set edad = edad
end function
end class
set usuario = call Usuario 15
set usuario2 = call Usuario 21
set resultado1 = call esMayor usuario
set resultado2 = call esMayor usuario2
print resultado1 resultado2 | def esMayor(usuario):
return usuario.edad > 17
class Usuario:
def __init__(self, edad):
self.edad = edad
usuario = Usuario(15)
usuario2 = Usuario(21)
resultado1 = esMayor(usuario)
resultado2 = esMayor(usuario2)
print(resultado1, resultado2)
| Python | zaydzuhri_stack_edu_python |
function uncached_example cls example copy=true
begin
return call keyfilter lambda k -> k not in list string cache string slices if expression copy then deep copy example else example
end function | def uncached_example(cls, example: Dict, copy=True) -> Dict:
return tz.keyfilter(
lambda k: k not in ["cache", "slices"],
deepcopy(example) if copy else example,
) | Python | nomic_cornstack_python_v1 |
import sys , os , csv , collections
from exceptions import IllegalArgumentError
from customClasses import costList
set outFieldNames = split string drug_name,num_prescriber,total_cost string ,
set inFieldNames = split string id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost string ,
function openFile fi... | import sys, os, csv, collections
from exceptions import IllegalArgumentError
from customClasses import costList
outFieldNames = "drug_name,num_prescriber,total_cost".split(',')
inFieldNames = "id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost".split(',')
def openFile(fileN, perm):
try:
inFile = op... | Python | zaydzuhri_stack_edu_python |
function current_tally self **kwargs
begin
set card = 1
if not energies
begin
call process_energy keyword kwargs
end
set surfaces = list
if string surfaces in kwargs
begin
for surface in kwargs at string surfaces
begin
if is instance surface float
begin
extend surfaces list surface
end
if is instance surface list
begi... | def current_tally(self, **kwargs):
self.card = 1
if not self.energies:
self.process_energy(**kwargs)
self.surfaces = []
if "surfaces" in kwargs:
for surface in kwargs["surfaces"]:
if isinstance(surface, float):
self.surfaces.ext... | Python | nomic_cornstack_python_v1 |
for i in range iterations
begin
print i + 1 string Abracadabra
end | for i in range(iterations):
print(i+1, " Abracadabra") | Python | zaydzuhri_stack_edu_python |
function _toList self
begin
return list comprehension call text for block in call _iterateBlocksFrom call firstBlock
end function | def _toList(self):
return [block.text() \
for block in _iterateBlocksFrom(self._doc.firstBlock())] | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import seaborn as sb
import numpy as np
comment meaning to the plot
set k = list comprehension 5 * i for i in range 1 6
set x = k
set legend = list string UCF string SRS string SRS* string TSRS string TSRS* string Time-TSRS string TRS string HSRS
comment S@K... | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import seaborn as sb
import numpy as np
# meaning to the plot
k = [5 * i for i in range(1, 6)]
x = k
legend = ['UCF', 'SRS', 'SRS*', 'TSRS', 'TSRS*', 'Time-TSRS', 'TRS', 'HSRS']
# S@K
ucf = [2.383, 3.599, 4.399, 5.062, 5.669]
srs = [3.608, 5.266, 6.299, 7.017, ... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python3
import sys , math
function primeFactors n
begin
set arr = list
comment Print the number of two's that divide n
while n % 2 == 0
begin
append arr 2
set n = n / 2
end
comment n must be odd at this point
comment so a skip of 2 ( i = i + 2) can be used
for i in range 3 integer square root n + 1 2
beg... | #!/bin/python3
import sys, math
def primeFactors(n):
arr = []
# Print the number of two's that divide n
while n % 2 == 0:
arr.append(2)
n = n / 2
# n must be odd at this point
# so a skip of 2 ( i = i + 2) can be used
for i in range(3, int(math.sqrt(n))+1, 2):
... | Python | zaydzuhri_stack_edu_python |
function list_themes
begin
set themes = list *os.scandir(os.path.join(CONF_DIR, 'colorschemes')) *os.scandir(os.path.join(MODULE_DIR, 'colorschemes'))
return list comprehension t for t in themes if is file path path
end function | def list_themes():
themes = [*os.scandir(os.path.join(CONF_DIR, "colorschemes")),
*os.scandir(os.path.join(MODULE_DIR, "colorschemes"))]
return [t for t in themes if os.path.isfile(t.path)] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
set variable = string snc
comment variable = "snw-cover"
set cmip = string CMIP6
set lettre = string a
comment aabeg="1981"; aaend="2017"
set aabeg = string 1981
set aaend = string 2014
comment aabeg="1995"; aaend="2014"
set vertical = tru... | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
variable = "snc"
# variable = "snw-cover"
cmip = "CMIP6"
lettre = "a"
# aabeg="1981"; aaend="2017"
aabeg="1981"; aaend="2014"
# aabeg="1995"; aaend="2014"
vertical = True
nmon = 12
nyr=int(aaend)-int(aabeg)+1
labels = [ 'Jan', 'Feb', 'Mar', ... | Python | zaydzuhri_stack_edu_python |
function _checkContact self head
begin
set result = go
set triggers = list
for tuple trigger_bit trigger_func in zip list NSIGMA SLOPE PHASE list _chkNSigma _chkSlope _chkPhase
begin
if cont_mode ? trigger_bit
begin
set trigger = call trigger_func head
if trigger
begin
append triggers trigger
end
end
end
if not trigge... | def _checkContact(self, head):
result = self.ACTION.go
triggers = []
for trigger_bit, trigger_func in zip(
[self.config.NSIGMA, self.config.SLOPE, self.config.PHASE],
[self._chkNSigma, self._chkSlope, self._chkPhase]):
if self.config.cont_mode & trigge... | Python | nomic_cornstack_python_v1 |
function swap_positions string index_x index_y
begin
if index_x > index_y
begin
return call swap_positions string index_y index_x
end
return string at slice : index_x : + string at index_y + string at slice index_x + 1 : index_y : + string at index_x + string at slice index_y + 1 : :
end function
function swap_let... | def swap_positions(string, index_x, index_y):
if index_x > index_y:
return swap_positions(string, index_y, index_x)
return string[:index_x] + string[index_y] + string[index_x+1:index_y] + string[index_x] + string[index_y+1:]
def swap_letters(string, letter_x, letter_y):
return swap_positions(strin... | Python | zaydzuhri_stack_edu_python |
set s = string 1, 2, 3, -4, 5, 6, 2, -1
comment Remove any whitespace from the string
set s = replace s string string
comment Split the string into a list of numbers
set numbers = list comprehension integer num for num in split s string ,
comment Remove duplicates from the list
set numbers = list set numbers
comment S... | s = "1, 2, 3, -4, 5, 6, 2, -1"
# Remove any whitespace from the string
s = s.replace(" ", "")
# Split the string into a list of numbers
numbers = [int(num) for num in s.split(",")]
# Remove duplicates from the list
numbers = list(set(numbers))
# Sort the numbers in descending order
numbers.sort(reverse=True)
# Rem... | Python | jtatman_500k |
function test_match_validate_any self
begin
set analyzer = call IBANAnalyzer none validate=true
set body = string Mutlipe IBANS: DE89 3704 0044 0532 0130 00 and FR14 2004 1010 0505 0001 3 should not match
set match = match paste
assert true match
comment The validate method should filter the wrong FR IBAN out
assert eq... | def test_match_validate_any(self):
self.analyzer = IBANAnalyzer(None, validate=True)
self.paste.body = "Mutlipe IBANS: DE89 3704 0044 0532 0130 00 and FR14 2004 1010 0505 0001 3 should not match"
match = self.analyzer.match(self.paste)
self.assertTrue(match)
# The validate metho... | Python | nomic_cornstack_python_v1 |
import numpy as np
import utils.parse_files as files
comment Extrapolates from a given seed sequence
function generate_from_seed model seed sequence_length data_variance data_mean
begin
set seedSeq = copy seed
set output = list
comment The generation algorithm is simple:
comment Step 1 - Given A = [X_0, X_1, ... X_n],... | import numpy as np
import utils.parse_files as files
#Extrapolates from a given seed sequence
def generate_from_seed(model, seed, sequence_length, data_variance, data_mean):
seedSeq = seed.copy()
output = []
#The generation algorithm is simple:
#Step 1 - Given A = [X_0, X_1, ... X_n], generate X_n + 1
#Step 2 - ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment LeetCode #110: Balanced Binary Tree
comment https://leetcode.com/problems/balanced-binary-tree/description/
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
clas... | #!/usr/bin/env python3
# LeetCode #110: Balanced Binary Tree
# https://leetcode.com/problems/balanced-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isB... | Python | zaydzuhri_stack_edu_python |
function reads s filename=none loader=none implicit_tuple=true allow_errors=false
begin
string Load but don't evaluate a GCL expression from a string.
return call reads s filename=filename or string <input> loader=loader or default_loader implicit_tuple=implicit_tuple allow_errors=allow_errors
end function | def reads(s, filename=None, loader=None, implicit_tuple=True, allow_errors=False):
"""Load but don't evaluate a GCL expression from a string."""
return ast.reads(s,
filename=filename or '<input>',
loader=loader or default_loader,
implicit_tuple=implicit_tuple,
allow_errors=allow_errors) | Python | jtatman_500k |
function __init__ self num_channels latent_dim
begin
call __init__
set linear_layers = sequential linear latent_dim 7 * 7 * 256 relu
set conv_layers = sequential conv transpose 2d 256 128 4 stride=2 padding=1 call BatchNorm2d 128 relu conv transpose 2d 128 64 3 padding=1 call BatchNorm2d 64 relu conv transpose 2d 64 32... | def __init__(self, num_channels, latent_dim):
super().__init__()
self.linear_layers = torch.nn.Sequential(
torch.nn.Linear(latent_dim, 7 * 7 * 256),
torch.nn.ReLU(),
)
self.conv_layers = torch.nn.Sequential(
torch.nn.ConvTranspose2d(256, 128, 4, stri... | Python | nomic_cornstack_python_v1 |
function format_value content
begin
try
begin
set content = content + string
end
except TypeError
begin
set content = join string , content
end
return replace strip call remove_break_lines_characters content string ^ PRESERVECIRC
end function | def format_value(content):
try:
content += ""
except TypeError:
content = ", ".join(content)
return remove_break_lines_characters(
content).strip().replace('^', PRESERVECIRC) | Python | nomic_cornstack_python_v1 |
function main
begin
print string Quillbot Paraphrasing Tool
set filepath = input string Enter the path of the formatted text file:
call openfile filepath
end function | def main():
print("Quillbot Paraphrasing Tool")
filepath = input("Enter the path of the formatted text file: ")
openfile(filepath) | Python | nomic_cornstack_python_v1 |
function from_json cls fpath verb=false
begin
with open absolute path path fpath string rb as f
begin
set d = load json f
end
set kde = call cls glob_bw=d at string glob_bw alpha=d at string alpha diag_cov=d at string diag_cov
comment Reconstruct all internals without using fit again
set _std_X = call atleast_2d d at s... | def from_json(cls, fpath, verb=False):
with open(os.path.abspath(fpath), "rb") as f:
d = json.load(f)
kde = cls(glob_bw=d["glob_bw"], alpha=d["alpha"],
diag_cov=d["diag_cov"])
# Reconstruct all internals without using fit again
kde._std_X = np.atleast_2d(d... | Python | nomic_cornstack_python_v1 |
comment utility function used in ./auto-gen-bookmarks.py
import json
from os import remove
import subprocess
from string import punctuation
import datetime
comment load json file and return it as a workable string
function loadFile f_to_load
begin
string loadFile(f_to_load: str) This function will accept a file to load... | #### utility function used in ./auto-gen-bookmarks.py
import json
from os import remove
import subprocess
from string import punctuation
import datetime
### load json file and return it as a workable string
def loadFile(f_to_load: str):
"""
loadFile(f_to_load: str)
This function will accept a file to... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Tue Sep 15 20:11:03 2020 @author: matt
comment DEFINITIONS
import tkinter as tk
from tkinter import Tk
set window = call Tk
title window string TIC-TAC-TOE
call geometry string 300x300
set button = call StringVar
set click = true
set flag = 0... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 20:11:03 2020
@author: matt
"""
#DEFINITIONS
import tkinter as tk
from tkinter import Tk
window = tk.Tk()
window.title('TIC-TAC-TOE')
window.geometry("300x300")
button = tk.StringVar()
click = True
flag = 0
#GET PLAYER 1 TO CHOOSE X'S OR O'S
def... | Python | zaydzuhri_stack_edu_python |
function createAdPoolSuccess request
begin
return call render_to_response string createadpoolsuccess.html
end function | def createAdPoolSuccess(request):
return render_to_response('createadpoolsuccess.html') | Python | nomic_cornstack_python_v1 |
function inject_attribute_value_input self params model **kwargs
begin
transform _transformer params input_shape serialize string AttributeValue
end function | def inject_attribute_value_input(self, params, model, **kwargs):
self._transformer.transform(
params,
model.input_shape,
self._serializer.serialize,
'AttributeValue',
) | Python | nomic_cornstack_python_v1 |
import sqlite3
import time
import datetime
class DB_sensors_sql
begin
set con = call connect string TesisDavidSilTroy.db
set cur = call cursor
set table_name = string No_named
set main_table_name = string sensors_tests
set main_table_date_title = string id INTEGER PRIMARY KEY, test_name text, date text
function __init_... | import sqlite3
import time
import datetime
class DB_sensors_sql:
con = sqlite3.connect("TesisDavidSilTroy.db")
cur = con.cursor()
table_name = "No_named"
main_table_name = "sensors_tests"
main_table_date_title = f'id INTEGER PRIMARY KEY, test_name text, date text'
def __init__(self):
... | Python | zaydzuhri_stack_edu_python |
function combine_n_gram_features n_gram_probabilities
begin
if type n_gram_probabilities is not list
begin
raise exception string Invalid input to method. Only provide a list object.
end
set features = zeros tuple length n_gram_probabilities length keys probability_features
comment I think this works as a sanity check.... | def combine_n_gram_features(n_gram_probabilities):
if type(n_gram_probabilities) is not list:
raise Exception("Invalid input to method. Only provide a list object.")
features = np.zeros((len(n_gram_probabilities), len(n_gram_probabilities[0].probability_features.keys())))
# I think this works as a sanity check.... | Python | nomic_cornstack_python_v1 |
import boto3
import csv
set client = call client string ec2
set response = call describe_instances
comment This function written by Rustam Yuldoshev
comment You can get InstanceType,VpcId,SubnetId,AvailabilityZone,AccountNumber,Tags
comment And write to CSV file to management purpose
function get_ec2_instanceDetails fi... | import boto3
import csv
client=boto3.client('ec2')
response=client.describe_instances()
# This function written by Rustam Yuldoshev
#You can get InstanceType,VpcId,SubnetId,AvailabilityZone,AccountNumber,Tags
#And write to CSV file to management purpose
def get_ec2_instanceDetails(fileName):
client = boto3.client... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Feb 10 21:17:26 2015 @author: catking
set text_help = string 直接回复“姓名+空格+日期(数字)”即可查询员工本月的排班情况。如:发送 李小霆 5 将查阅李小霆在本月5日的排班情况。 若您是管理员,回复“AD”查看更多操作。
set text_admin_help = string 您好,若您是还没有注册的管理员,请回复“pw+空格+管理员密码”注册管理员。
set text_welcom = string 欢迎关注二室之家!本站将为您提供排班查询等服务。 + text_... | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 10 21:17:26 2015
@author: catking
"""
text_help = '直接回复“姓名+空格+日期(数字)”即可查询员工本月的排班情况。如:发送\n李小霆 5\n将查阅李小霆在本月5日的排班情况。\n若您是管理员,回复“AD”查看更多操作。'
text_admin_help = '您好,若您是还没有注册的管理员,请回复“pw+空格+管理员密码”注册管理员。'
text_welcom = '欢迎关注二室之家!本站将为您提供排班查询等服务。\n' + text_help
text_no_author_err... | Python | zaydzuhri_stack_edu_python |
function to_region region proj=false
begin
if is instance region Region
begin
return region
end
else
if is instance region bool or region is none
begin
return region
end
else
if is instance region str
begin
if proj and region == string all
begin
return regions
end
else
begin
return get attribute regions region
end
end
... | def to_region(region, proj=False):
if isinstance(region, aospy.region.Region):
return region
elif isinstance(region, bool) or region is None:
return region
elif isinstance(region, str):
if proj and region == 'all':
return proj.regions
else:
return ge... | Python | nomic_cornstack_python_v1 |
comment Write a Python function to find the Max of three numbers.
comment Enter the Number
set num1 = input string Enter the Number 1:
set num1 = integer num1
set num2 = input string Enter the Number 2:
set num2 = integer num2
set num3 = input string Enter the Number 3:
set num3 = integer num3
function find_Max num1 nu... | # Write a Python function to find the Max of three numbers.
# Enter the Number
num1=input("Enter the Number 1: ")
num1=int(num1)
num2=input("Enter the Number 2: ")
num2=int(num2)
num3=input("Enter the Number 3: ")
num3=int(num3)
def find_Max(num1,num2,num3):
if num1>num2:
if num1>num3:
print... | Python | zaydzuhri_stack_edu_python |
function run self
begin
for i in range n_images
begin
set fname = string stretched_image%04i % i + 1
comment Purely for saving disk space
set img = as type randn 1000 1000 string float32
comment image_tools.write_img(array=img, name=fname)
comment For a simple example don't write the original image to disk
set h_eql = ... | def run(self):
for i in range(self.n_images):
fname = 'stretched_image%04i' %(i+1)
img = numpy.random.randn(1000,1000).astype('float32') # Purely for saving disk space
#image_tools.write_img(array=img, name=fname)
# For a simple example don't write the origina... | Python | nomic_cornstack_python_v1 |
function organisations_list
begin
set page = get args string page type=int
if page is none
begin
set page = 1
end
set _organisations = paginate query page=page per_page=config at string APP_PAGE_SIZE
set payload = dump _organisations
return call jsonify payload
end function | def organisations_list():
page = request.args.get('page', type=int)
if page is None:
page = 1
_organisations = Organisation.query.paginate(page=page, per_page=app.config['APP_PAGE_SIZE'])
payload = OrganisationSchema(many=True, paginate=True, include_data=(
'people',
'people.par... | Python | nomic_cornstack_python_v1 |
async function connect self project_id=none
begin
set project_id = project_id or project_id
assert project_id is not none
assert call authenticated
comment look like a normal client if this works the way i expect it does :sunglasses:
set USER_AGENT = string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (... | async def connect(self, project_id=None):
self.project_id = project_id or self.project_id
assert self.project_id is not None
assert self.session.authenticated()
_websockets_client.USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3... | Python | nomic_cornstack_python_v1 |
function _check_dossier self dossier
begin
set dossier_stats = counter
set dossier_stats at string states = counter
set dossier_path = join string / call getPhysicalPath
set contained_docs = call unrestrictedSearchResults path=dict string query dossier_path object_provides=__identifier__
set dossier_stats at string tot... | def _check_dossier(self, dossier):
dossier_stats = Counter()
dossier_stats['states'] = Counter()
dossier_path = '/'.join(dossier.getPhysicalPath())
contained_docs = self.catalog.unrestrictedSearchResults(
path={'query': dossier_path},
object_provides=IBaseDocumen... | Python | nomic_cornstack_python_v1 |
function recall y_true y_pred
begin
set true_positives = sum round call clip y_true * y_pred 0 1
set possible_positives = sum round call clip y_true 0 1
set recall = true_positives / possible_positives + call epsilon
return recall
end function | def recall(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall | Python | nomic_cornstack_python_v1 |
import unittest
from maksukortti import Maksukortti
class TestMaksukortti extends TestCase
begin
function setUp self
begin
set maksukortti = call Maksukortti 1000
end function
function test_luotu_kortti_on_olemassa self
begin
assert not equal maksukortti none
end function
function test_kortin_saldon_alussa_oikein self
... | import unittest
from maksukortti import Maksukortti
class TestMaksukortti(unittest.TestCase):
def setUp(self):
self.maksukortti = Maksukortti(1000)
def test_luotu_kortti_on_olemassa(self):
self.assertNotEqual(self.maksukortti, None)
def test_kortin_saldon_alussa_oikein(self):
sel... | Python | zaydzuhri_stack_edu_python |
string 1. run 'locate wordlist' to find the dictionary to use for brute force 2. Get the name attribute of username, password and submit button in the html file of target website
import requests
set page_url = string http://www.targetwebsit.com/loginpage.html
comment this file contains possible password for a user
set ... | """
1. run 'locate wordlist' to find the dictionary to use for brute force
2. Get the name attribute of username, password and submit button in the html file of target website
"""
import requests
page_url = "http://www.targetwebsit.com/loginpage.html"
pass_dict = "passlist.txt" # this file contains possible passw... | Python | zaydzuhri_stack_edu_python |
function vgg13 *args
begin
return call _VGGWrapper call vgg13 *args
end function | def vgg13(*args):
return _VGGWrapper(models.vgg13(*args)) | Python | nomic_cornstack_python_v1 |
function use_svg_display
begin
call set_matplotlib_formats string svg
end function | def use_svg_display():
display.set_matplotlib_formats('svg') | Python | nomic_cornstack_python_v1 |
function main
begin
print string Facebook Events Crawl Started.
set graph = call GraphAPI access_token=ACCESS_TOKEN version=API_VERSION
set fields_param = join string , EVENT_FIELDS
set event_data_list = call get_object string me?fields=events{ + fields_param + string }
with open string fb_event_data.json string w as o... | def main():
print("Facebook Events Crawl Started.")
graph = facebook.GraphAPI(access_token=ACCESS_TOKEN, version=API_VERSION)
fields_param = ','.join(EVENT_FIELDS)
event_data_list = graph.get_object('me?fields=events{'+fields_param+'}')
with open('fb_event_data.json', 'w') as outfile:
json... | Python | nomic_cornstack_python_v1 |
function mainline self
begin
return call Mainline self lambda node -> node
end function | def mainline(self) -> Mainline[ChildNode]:
return Mainline(self, lambda node: node) | Python | nomic_cornstack_python_v1 |
function read_picture_data filename
begin
set file_name = join path string . string datas filename
try
begin
with open file_name string rb as file
begin
set read_data = read file
end
end
except FileNotFoundError
begin
print string Oups, the file { filename } was not found
end
try
begin
if filename == string train-image... | def read_picture_data(filename):
file_name = os.path.join('.', 'datas', filename)
try:
with open(file_name, 'rb') as file:
read_data = file.read()
except FileNotFoundError:
print(f'Oups, the file {filename} was not found')
try:
if filename == 'train-images.idx3-ubyt... | Python | nomic_cornstack_python_v1 |
comment filename: simple_messages.py
comment date: 03-20-2020
comment username: ryanbrockman@
comment name: Ryan Brockman
comment description: Python crash course - Chapter 2 - Exercise 2-2 - Simple messages
comment Store a message in a variable, then print that message.
set simpleMessage = string This is a simple mess... | # filename: simple_messages.py
# date: 03-20-2020
# username: ryanbrockman@
# name: Ryan Brockman
# description: Python crash course - Chapter 2 - Exercise 2-2 - Simple messages
# Store a message in a variable, then print that message.
simpleMessage = 'This is a simple message!'
print(simpleMessage)
# Then change the... | Python | zaydzuhri_stack_edu_python |
function restore_state output_dir
begin
string Restore State.
set params_file = join path output_dir string model.pkl
if not exists gfile params_file
begin
return call State step=none params=none history=call History
end
with call GFile params_file string rb as f
begin
set tuple params step history = load pickle f
end
... | def restore_state(output_dir):
"""Restore State."""
params_file = os.path.join(output_dir, "model.pkl")
if not gfile.exists(params_file):
return State(step=None, params=None, history=trax_history.History())
with gfile.GFile(params_file, "rb") as f:
(params, step, history) = pickle.load(f)
log("Model ... | Python | jtatman_500k |
function read_data self
begin
try
begin
if not my_conf at string app_monitoring_policy
begin
raise KeyError
end
end
except KeyError
begin
error string No data for Monitoring manager
exit 1
end
call parse_status
comment waiting for testing result
comment self.listen_testing()
comment self.data_check()
comment name_parse... | def read_data(self):
try:
if not self.my_conf['app_monitoring_policy']:
raise KeyError
except KeyError:
self.ManagerLog.error("No data for Monitoring manager")
sys.exit(1)
self.parse_status()
# waiting for testing result
... | Python | nomic_cornstack_python_v1 |
function test_traffic_light_grid self
begin
comment test the example in the absence of inflows
set exp = call traffic_light_grid_example render=false use_inflows=false
run 1 5
comment test the example in the presence of inflows
set exp = call traffic_light_grid_example render=false use_inflows=true
run 1 5
end function | def test_traffic_light_grid(self):
# test the example in the absence of inflows
exp = traffic_light_grid_example(render=False, use_inflows=False)
exp.run(1, 5)
# test the example in the presence of inflows
exp = traffic_light_grid_example(render=False, use_inflows=True)
... | Python | nomic_cornstack_python_v1 |
import requests
from lxml import etree
import pypinyin
import time
from xpinyin import Pinyin
set headers = dict string User-Agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
set news = list
set technlg = list
set car = list
set hou... | import requests
from lxml import etree
import pypinyin
import time
from xpinyin import Pinyin
headers = {
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
news = []
technlg = []
car = []
house = []
job = []
finance = []
life =... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string - welcoming - r, p, s - Possabilities
import random
class Game
begin
function __init__ self
begin
print string -------------------------------------------
print string Welcome to The Rock, paper, Scissors Game
print string -------------------------------------------
set P_result = 0
set... | #!/usr/bin/python3
"""
- welcoming
- r, p, s
- Possabilities
"""
import random
class Game:
def __init__(self):
print("-------------------------------------------")
print('Welcome to The Rock, paper, Scissors Game')
print("-------------------------------------------")
P_result = 0
... | Python | zaydzuhri_stack_edu_python |
import face_recognition as fr
import os
import cv2
import face_recognition
import numpy as np
function get_encoded_faces
begin
set encoded = dict
for tuple dirpath dnames fnames in walk string ./dataset
begin
for f in fnames
begin
if ends with f string .jpg or ends with f string .png
begin
set face = call load_image_f... | import face_recognition as fr
import os
import cv2
import face_recognition
import numpy as np
def get_encoded_faces():
encoded = {}
for dirpath, dnames, fnames in os.walk("./dataset"):
for f in fnames:
if f.endswith(".jpg") or f.endswith(".png"):
face = fr.load_im... | Python | zaydzuhri_stack_edu_python |
from __future__ import print_function , division
from enum import Enum
comment Define an enum to hold a list of expansions
comment --------------------------------------------------------------------------------
class MBSet extends Enum
begin
set UNDEFINED = 0
set BASE = 1
set SET_ROTATION = 2
set CROSSOVER = 3
set SPO... | from __future__ import print_function, division
from enum import Enum
# Define an enum to hold a list of expansions
# --------------------------------------------------------------------------------
class MBSet (Enum):
UNDEFINED = 0
BASE = 1
SET_ROTATION = 2
CROSSOVER = 3
SPONSORS = 4
FUSION_CH... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[14]:
import csv
import matplotlib.pyplot as plt
set features = list
with open string IRIS.csv string r as data
begin
set readData = reader data
for row in readData
begin
append features row
end
end
set sepal_length_setosa = list
set sepal_length_versilcolo... | #!/usr/bin/env python
# coding: utf-8
# In[14]:
import csv
import matplotlib.pyplot as plt
features = []
with open ("IRIS.csv","r") as data:
readData = csv.reader(data)
for row in readData:
features.append(row)
sepal_length_setosa = []
sepal_length_versilcolor = []
sepal_length_virginica = []
sepa... | Python | zaydzuhri_stack_edu_python |
function get_history self
begin
if not history_level
begin
return none
end
try
begin
set history_index = call get_current_history_length + 1 - history_level
if not history_index
begin
return none
end
return call get_history_item history_index
end
except NameError
begin
return none
end
end function | def get_history(self):
if not self.history_level:
return None
try:
history_index = readline.get_current_history_length() + 1 - self.history_level
if not history_index:
return None
return readline.get_history_item(history_index)
exc... | Python | nomic_cornstack_python_v1 |
function reg_q_nom_pp_comparison exp_dict
begin
set tuple fig ax = call subplots 1 2 figsize=tuple 8 3
call set_title string q1
call setup_ax ax at 0 0 550 100 20 1.2 2.2 0.1 0.05
call plot_curve ax at 0 exp_dict at string reg_nom_fbl at string qd1 at slice 50 : 600 : string r-- string target lw=2 alpha=0.8
call plot_... | def reg_q_nom_pp_comparison(exp_dict):
fig, ax = plt.subplots(1, 2, figsize=(8, 3))
ax[0].set_title('q1')
setup_ax(ax[0], 0, 550, 100, 20, 1.2, 2.2, 0.1, 0.05)
plot_curve(ax[0], exp_dict['reg_nom_fbl']['qd1'][50:600], 'r--', 'target', lw=2, alpha=0.8)
plot_curve(ax[0], exp_dict['reg_nom_pp']['q1'][5... | Python | nomic_cornstack_python_v1 |
function initializeUI self
begin
call setMinimumSize 1000 600
call setWindowTitle string 10.1 – Account Management GUI
call createConnection
call createTable
call setupWidgets
show
end function | def initializeUI(self):
self.setMinimumSize(1000, 600)
self.setWindowTitle('10.1 – Account Management GUI')
self.createConnection()
self.createTable()
self.setupWidgets()
self.show() | Python | nomic_cornstack_python_v1 |
function CalcExceed3TimesMedian Qvalues
begin
comment drop nan
set Qvalues = drop missing Qvalues
set median3x = sum
return median3x
end function | def CalcExceed3TimesMedian(Qvalues):
# drop nan
Qvalues = Qvalues.dropna()
median3x = (Qvalues > (Qvalues.median())*3).sum()
return ( median3x ) | Python | nomic_cornstack_python_v1 |
function readline self size=none
begin
set leneol = length eol
set line = bytearray
while true
begin
set c = read self 1
if c
begin
set line = line + c
if line at slice - leneol : : == eol
begin
break
end
if size is not none and length line >= size
begin
break
end
end
else
begin
break
end
end
return bytes line
end fu... | def readline(self, size=None):
leneol = len(self.eol)
line = bytearray()
while True:
c = self.read(1)
if c:
line += c
if line[-leneol:] == self.eol:
break
if size is not None and len(line) >= siz... | Python | nomic_cornstack_python_v1 |
for x in range 5 12
begin
print string Razvan este genial
print x
end
set RazArd = 10
while RazArd < 15
begin
print RazArd
set RazArd = RazArd + 1
end | for x in range(5 , 12):
print('Razvan este genial')
print(x)
RazArd = 10
while RazArd < 15:
print(RazArd)
RazArd += 1
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment MAD LIB MAKER
comment This script will generate mad-libs based off of a William Carlos
comment poem, 'The Red Wheelbarrow.' Each poem will then be
comment tweeted by the bot account.
import json , io , tweepy , time , urllib3
from random import randint
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# MAD LIB MAKER
# This script will generate mad-libs based off of a William Carlos
# poem, 'The Red Wheelbarrow.' Each poem will then be
# tweeted by the bot account.
import json, io, tweepy, time, urllib3
from random import randint
from credentials import *
auth = tweep... | Python | zaydzuhri_stack_edu_python |
function match_path path endpoints
begin
string Matches an actual string path to an endpoint template. Partial matches are also supported meaning that if the path is a prefix of an item of `endpoints`, the item is returned. For example, the path "/tradition/123" matches "/tradition/{tradId}". Note that the currently im... | def match_path(path: str, endpoints: list[str]) -> str | None:
"""
Matches an actual string path to an endpoint template.
Partial matches are also supported meaning
that if the path is a prefix of an item of `endpoints`,
the item is returned.
For example, the path "/tradition/123" matches "/tra... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from scipy import linalg
from markovchain import MarkovChain
class MRP extends MarkovChain
begin
string Markov reward process is Markov chain with a state-dependent reward function.
function __init__ self s0 P R gamma
begin
call __init__ s0 P gamma
set R = R
set gamma = gamma
set list S _ = shape
ass... | import numpy as np
from scipy import linalg
from markovchain import MarkovChain
class MRP(MarkovChain):
"Markov reward process is Markov chain with a state-dependent reward function."
def __init__(self, s0, P, R, gamma):
super(MRP, self).__init__(s0, P, gamma)
self.R = R
self.gamma = ... | Python | zaydzuhri_stack_edu_python |
from os import makedirs
from os.path import join
from argparse import ArgumentParser
import numpy as np
import pandas as pd
class ArgParseRange
begin
string List with this element restricts the argument to be in range [start, end].
function __init__ self start end
begin
set start = start
set end = end
end function
func... | from os import makedirs
from os.path import join
from argparse import ArgumentParser
import numpy as np
import pandas as pd
class ArgParseRange:
"""
List with this element restricts the argument to be
in range [start, end].
"""
def __init__(self, start, end):
self.start = start
sel... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
try
begin
from PIL import Image
end
except ImportError
begin
import Image
end
comment Open image file
set image = open string P1_1.jpeg
set my_dpi = 72.0
comment Set up figure
set fig = figure figsize=tuple decimal size at 0 / my_dpi decimal size at 1... | import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
try:
from PIL import Image
except ImportError:
import Image
# Open image file
image = Image.open('P1_1.jpeg')
my_dpi=72.
# Set up figure
fig=plt.figure(figsize=(float(image.size[0])/my_dpi,float(image.size[1])/my_dpi),dpi=my_dpi)
ax=fig.add_... | Python | zaydzuhri_stack_edu_python |
comment bibonacci
comment 0 1 1 2 3 5 8 13 21 34 55 89
set in_p = integer input string Enter >>>
set a = 1
set list1 = list 0 1
for i in list1
begin
set a = a + i
append list1 a
if i < in_p
begin
print i
end
else
begin
break
end
end | #bibonacci
#0 1 1 2 3 5 8 13 21 34 55 89
in_p = int(input('Enter\n>>>'))
a = 1
list1 = [0, 1]
for i in list1:
a += i
list1.append(a)
if i < in_p:
print(i)
else:
break | Python | zaydzuhri_stack_edu_python |
function MaxRandomFrameSize self
begin
return call _get_attribute string maxRandomFrameSize
end function | def MaxRandomFrameSize(self):
return self._get_attribute('maxRandomFrameSize') | Python | nomic_cornstack_python_v1 |
function plotDetectorOrigin self which=string both frame=none
begin
if frame is none
begin
set frame = _last_plot_frame
end
for ap in call _getFullApertures
begin
call plotDetectorOrigin frame=frame which=which
end
end function | def plotDetectorOrigin(self, which='both', frame=None):
if frame is None: frame = self._last_plot_frame
for ap in self._getFullApertures():
ap.plotDetectorOrigin(frame=frame, which=which) | Python | nomic_cornstack_python_v1 |
function copy self threshold
begin
set indicator = threshold at string indicator
set stage = threshold at string stage
set begin = threshold at string begin
set end = threshold at string end
set quality = threshold at string quality
set weight = threshold at string weight
return self
end function | def copy(self, threshold):
self.indicator = threshold['indicator']
self.stage = threshold['stage']
self.begin = threshold['begin']
self.end = threshold['end']
self.quality = threshold['quality']
self.weight = threshold['weight']
return self | Python | nomic_cornstack_python_v1 |
import math
function is_prime n
begin
if n <= 1
begin
return false
end
for i in range 2 integer square root n + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
function find_max_prime_with_repeated_digit arr
begin
set max_prime = - 1
for num in arr
begin
if call is_prime num and length set str... | import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def find_max_prime_with_repeated_digit(arr):
max_prime = -1
for num in arr:
if is_prime(num) and len(set(str(num))) < len(str(n... | Python | jtatman_500k |
function svn_fs_paths_changed2 *args
begin
return call svn_fs_paths_changed2 *args
end function | def svn_fs_paths_changed2(*args):
return _fs.svn_fs_paths_changed2(*args) | Python | nomic_cornstack_python_v1 |
function __call__ self
begin
if is instance encoding DefaultEncoding
begin
with call channel device io as dev
begin
set __response = call receive receive_count
end
end
else
begin
with call channel device io as dev
begin
set __response = call receive receive_count encoding=encoding
end
end
end function | def __call__(self):
if isinstance(self.encoding, DefaultEncoding):
with channel(self.device, self.io) as dev:
self.__response = dev.receive(self.receive_count)
else:
with channel(self.device, self.io) as dev:
self.__response = dev.receive(self.rece... | Python | nomic_cornstack_python_v1 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import zipfile
from pathlib import Path
from tqdm import tqdm
import h5py
import numpy as np
import pickle
from PIL import Image
from PIL.ImageOps import pad as pil_pad
from ... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import zipfile
from pathlib import Path
from tqdm import tqdm
import h5py
import numpy as np
import pickle
from PIL import Image
from PIL.ImageOps import pad as pil_pad
f... | Python | zaydzuhri_stack_edu_python |
function mask_is_equal_mask self another_mask
begin
comment number of used elements is not the same
if length unused_element_ids != length unused_element_ids
begin
return false
end
comment judge whether each used_element has a coinciding used_element
set flag = false
for element1 in used_elements
begin
for element2 in ... | def mask_is_equal_mask(self, another_mask):
# number of used elements is not the same
if len(self.unused_element_ids) != len(another_mask.unused_element_ids):
return False
# judge whether each used_element has a coinciding used_element
flag = False
for element... | Python | nomic_cornstack_python_v1 |
if key in keys and call issubset keys
begin
pop charen at curChar - 1 at 2 length charen at curChar - 1 at 2 - 1
pop charen at curChar - 1 at 2 length charen at curChar - 1 at 2 - 1
append charen at curChar - 1 at 2 whichChar
end
set whichChar = firstorderlogic__forall
if key in keys and call issubset keys
begin
pop ch... | if event.key in whichChar.keys and whichChar.keys.issubset(keys):
charray.charen[curChar-1][2].pop(len(charray.charen[curChar-1][2])-1)
charray.charen[curChar-1][2].pop(len(charray.charen[curChar-1][2])-1)
charray.charen[curChar-1][2].append(whichChar)
whichChar=firstorderlogic__forall
if event.key in whichChar.key... | Python | zaydzuhri_stack_edu_python |
function create self request
begin
set serializer = call NodeCreateRequest data=data
call is_valid raise_exception=true
set project = get validated_data string project
set source = get validated_data string source
set app = get validated_data string app string api
set host = get validated_data string host
set node = ge... | def create(self, request: Request) -> Response:
serializer = NodeCreateRequest(data=request.data)
serializer.is_valid(raise_exception=True)
project = serializer.validated_data.get("project")
source = serializer.validated_data.get("source")
app = serializer.validated_data.get("ap... | Python | nomic_cornstack_python_v1 |
comment usr/bin/env python3
comment Cleanify 0.1 beta
comment Program to create clean, profanity free UUIDs.
class uuid
begin
function __init__ self
begin
pass
end function
comment To search for a match in the bad words db (txt file).
function filter_uuid self string file=string bad_words.txt
begin
import re
set string... | #usr/bin/env python3
# Cleanify 0.1 beta
# Program to create clean, profanity free UUIDs.
class uuid:
def __init__(self):
pass
#To search for a match in the bad words db (txt file).
def filter_uuid(self, string, file='bad_words.txt'):
import re
string = string.lower()
with open(file, 'r') as fin:
count... | Python | zaydzuhri_stack_edu_python |
import sys
set a = list map int split read stdin
sort a
if a at 0 + a at 1 <= a at 2
begin
print string Maybe I should go out to sea...
end
else
begin
print string Huh? A triangle?
end | import sys
a = list(map(int,sys.stdin.read().split()))
a.sort()
if a[0] + a[1] <= a[2]:
print("Maybe I should go out to sea...")
else:
print("Huh? A triangle?")
| Python | zaydzuhri_stack_edu_python |
import string
print ascii_letters
print digits
print hexdigits
print punctuation
set str1 = string Hi i am monisha
set str2 = string 12345678
comment convert str1 to ascii letters
set text = join string list comprehension c for c in str1 if c in ascii_letters
print text
print all list comprehension call isnumeric for ... | import string
print(string.ascii_letters)
print(string.digits)
print(string.hexdigits)
print(string.punctuation)
str1 = "Hi i am monisha"
str2 = "12345678"
#convert str1 to ascii letters
text = "".join([c for c in str1 if c in string.ascii_letters])
print(text)
print(all([c.isnumeric() for c in str2])) | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
string Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. If possible, output any possible result. If not possible, return the empty string. Example 1: Input: S = "aab" Output: "aba" Example 2: Input: S = "aaab" Output: ... | #coding=utf-8
'''
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = "aab"
Output: "aba"
Example 2:
Input: S = "aaab"
Output: ""
'''... | 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.