code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function __getitem__ self index
begin
set ele = WaveNameMap at index
if UseCache
begin
comment need to read in the data (ele is the file path)
return call DataFromFileCache ele
end
else
begin
comment element itself has what we want
return ele
end
end function | def __getitem__(self,index):
ele = self.WaveNameMap[index]
if (self.UseCache):
# need to read in the data (ele is the file path)
return self.DataFromFileCache(ele)
else:
# element itself has what we want
return ele | Python | nomic_cornstack_python_v1 |
function features self
begin
return list comprehension field for field in values _fields if is instance field Feature
end function | def features(self) -> List[Feature]:
return [field for field in self._fields.values() if isinstance(field, Feature)] | Python | nomic_cornstack_python_v1 |
function mapping self
begin
set foundMarker = dict
set List1 = list
comment loop though all beamlines (e.g. Injector, Aramis)
for i in range 0 length PartsList
begin
set p = PartsList at i
set found = 0
comment line=self.BeamPath(i)
set j = 1
set k = 0
comment loops through atomic line of each beamline
for subsec in ... | def mapping(self):
foundMarker = {}
List1 = []
for i in range(0, len(self.PartsList)): # loop though all beamlines (e.g. Injector, Aramis)
p = self.PartsList[i]
found = 0
# line=self.BeamPath(i)
j = 1
k = 0
for subsec in p... | Python | nomic_cornstack_python_v1 |
function transform self tokenized_collection
begin
set transformed_collection = list comprehension call transform_string element for element in tokenized_collection
return transformed_collection
end function | def transform(self, tokenized_collection):
transformed_collection = [
self.transform_string(element)
for element in tokenized_collection
]
return transformed_collection | Python | nomic_cornstack_python_v1 |
import bisect
from collections import Counter , defaultdict
import sys
import nltk
class Featurizer
begin
set PREFIX_WORD_NGRAM = string N:
set PREFIX_CHAR_NGRAM = string C:
set PREFIX_FRAMENET = string FN:
function __init__ self binary=true lowercase=false remove_stopwords=false
begin
comment delimiter to split tweets... | import bisect
from collections import Counter, defaultdict
import sys
import nltk
class Featurizer:
PREFIX_WORD_NGRAM="N:"
PREFIX_CHAR_NGRAM="C:"
PREFIX_FRAMENET="FN:"
def __init__(self,binary=True,lowercase=False,remove_stopwords=False):
# delimiter to split tweets into tokens
self.D... | Python | zaydzuhri_stack_edu_python |
function __init__ self container job_definition_name=none node_props=none parameters=none retry_attempts=none timeout=none
begin
if is instance container dict
begin
set container = call JobDefinitionContainer keyword container
end
set _values = dict string container container
if job_definition_name is not none
begin
se... | def __init__(
self,
*,
container: "JobDefinitionContainer",
job_definition_name: typing.Optional[str] = None,
node_props: typing.Optional["IMultiNodeProps"] = None,
parameters: typing.Optional[typing.Mapping[str, str]] = None,
retry_attempts: typing.Optional[jsii.... | Python | nomic_cornstack_python_v1 |
function load_query_docs self filename
begin
if is file path filename
begin
with open filename string rb as f
begin
set query_docs = load pickle f
set query_docs = query_docs
end
end
end function | def load_query_docs(self, filename):
if os.path.isfile(filename):
with open(filename, "rb") as f:
query_docs = pickle.load(f)
self.query_docs = query_docs | Python | nomic_cornstack_python_v1 |
function remove_duplicates arr
begin
set length = length arr
if length <= 1
begin
return arr
end
set index = 1
while index < length
begin
set inner_index = 0
while inner_index < index
begin
if arr at index == arr at inner_index
begin
for i in range index length - 1
begin
set arr at i = arr at i + 1
end
set length = len... | def remove_duplicates(arr):
length = len(arr)
if length <= 1:
return arr
index = 1
while index < length:
inner_index = 0
while inner_index < index:
if arr[index] == arr[inner_index]:
for i in range(index, length - 1):
arr[i] = arr[... | Python | jtatman_500k |
comment python 类的语法
comment class 类名: #类名的规范:数字字母下划线组成,不能以数字开头,首字母大写,驼峰命名
comment 类属性 #类里面的变量值
comment 类方法 #写在类里面的类方法
comment 调用 ##########################################
comment 调用的方法:实例方法self,类方法@classmethod,静态方法@staticmethod 属性只能用实例来调用
comment 区别:
comment 1.实例方法可以调用类属性:self.属性名
comment 2.类方法和静态方法不可以调用类里面的属性,如果需要参数,... | #python 类的语法
#class 类名: #类名的规范:数字字母下划线组成,不能以数字开头,首字母大写,驼峰命名
#类属性 #类里面的变量值
#类方法 #写在类里面的类方法
##############################调用 ##########################################
#调用的方法:实例方法self,类方法@classmethod,静态方法@staticmethod 属性只能用实例来调用
#区别:
# 1.实例方法可以调用类属性:self.属性名
# 2.类方法和静态方法不可以调用类里面的属性,如果需要参数,需要另外... | Python | zaydzuhri_stack_edu_python |
function test_holiday_mode_none self
begin
with open call path string files/responses/systemcontrol string r as file
begin
set raw_system = loads read file
end
set holiday_mode = call map_holiday_mode_from_system raw_system
assert is not none holiday_mode
assert false is_active
assert is not none start_date
assert is n... | def test_holiday_mode_none(self) -> None:
with open(path("files/responses/systemcontrol"), "r") as file:
raw_system = json.loads(file.read())
holiday_mode = mapper.map_holiday_mode_from_system(raw_system)
self.assertIsNotNone(holiday_mode)
self.assertFalse(holiday_mode.is_ac... | Python | nomic_cornstack_python_v1 |
function mutates_with_this self
begin
return tuple
end function | def mutates_with_this(self):
return () | Python | nomic_cornstack_python_v1 |
comment real signature unknown; restored from __doc__
function __init__ self *more
begin
pass
end function | def __init__(self, *more): # real signature unknown; restored from __doc__
pass | Python | nomic_cornstack_python_v1 |
function get_id_params self
begin
set params = dict
comment Add in the assets.
for tuple n asset in enumerate _assets
begin
update params generator expression tuple format string {n}_{key} n=n key=key value for tuple key value in call iteritems call _get_and_check_id_params
end
comment All done.
return params
end func... | def get_id_params(self):
params = {}
# Add in the assets.
for n, asset in enumerate(self._assets):
params.update(
("{n}_{key}".format(
n = n,
key = key,
), value)
for key, value
in... | Python | nomic_cornstack_python_v1 |
comment Author: Md Lutfar Rahman, PhD student, UofM
comment Recommendation system
import math , copy , random , operator
class CollabFilter
begin
function __init__ self ratings avg_ratings movies seen_movies
begin
set ratings = ratings
set rt_copy = deep copy ratings
set avg_ratings = avg_ratings
set movies = movies
se... | # Author: Md Lutfar Rahman, PhD student, UofM
# Recommendation system
import math, copy, random, operator
class CollabFilter():
def __init__(self,ratings,avg_ratings,movies,seen_movies):
self.ratings = ratings
self.rt_copy = copy.deepcopy(self.ratings)
self.avg_ratings = avg_ratings
self.movies = movies
s... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
import torch
import torch.nn as nn
import torch.optim as optim
import time
import logging
from data_fashion_mnist import Dataset
call basicConfig level=INFO format=string %(asctime)s - %(levelname)s: %(message)s
function try_gpu
begin
string 尝试使用 GPU
set device = if expression call is_avail... | # -*- coding:utf-8 -*-
import torch
import torch.nn as nn
import torch.optim as optim
import time
import logging
from data_fashion_mnist import Dataset
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s: %(message)s')
def try_gpu():
''' 尝试使用 GPU '''
device = torch... | Python | zaydzuhri_stack_edu_python |
function read_files_rTNT self ERP centroids_list
begin
set SIGNALSFILE = subject_name + session_name + string -signals.csv
set MARKERSFILE = subject_name + session_name + string -clean2_markers.csv
set signals = read csv join path SIGNALSFILE sep=string ,
set markers = read csv join path MARKERSFILE sep=string ,
call c... | def read_files_rTNT(self, ERP, centroids_list):
SIGNALSFILE = self.subject_name + self.session_name + '-signals.csv'
MARKERSFILE = self.subject_name + self.session_name + '-clean2_markers.csv'
signals = pa.read_csv(join(self.path, SIGNALSFILE), sep=',')
markers = pa.read_csv(join(self.p... | Python | nomic_cornstack_python_v1 |
function get_transactions self address_list limit=100 min_block=none
begin
set ret = default dictionary list
set min_block = min_block or 0
set address_list_local = address_list at slice : :
while address_list_local
begin
set tuple addresses address_list_local = call _pop_chunks address_list_local rate_limit_per_sec... | def get_transactions(self, address_list, limit=100, min_block=None):
ret = defaultdict(list)
min_block = min_block or 0
address_list_local = address_list[:]
while address_list_local:
addresses, address_list_local = self._pop_chunks(address_list_local, self.rate_limit_per_sec ... | Python | nomic_cornstack_python_v1 |
function print_lines lines
begin
for line in lines
begin
print line
end
end function | def print_lines(lines):
for line in lines:
print(line) | Python | nomic_cornstack_python_v1 |
function miss_probability self dx dy dt
begin
return exp - call conc dx dy * dt
end function | def miss_probability(self, dx, dy, dt):
return np.exp(-self.conc(dx, dy) * dt) | Python | nomic_cornstack_python_v1 |
async function on_command_error ctx error
begin
if is instance error CheckFailure
begin
await call send string You are not authorized to use this command.
end
end function | async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CheckFailure):
await ctx.send("You are not authorized to use this command.") | Python | nomic_cornstack_python_v1 |
function _makeSummaryForCDS record CDS hStr summaryFormat getAttrFuncs=none
begin
if getAttrFuncs is none
begin
set getAttrFuncs = GET_ATTR_FUNCS
end
set summaryElements = list comprehension call CDS record hStr for x in summaryFormat
return join string summaryElements
end function | def _makeSummaryForCDS(record, CDS, hStr, summaryFormat, getAttrFuncs = None) :
if getAttrFuncs is None :
getAttrFuncs = GET_ATTR_FUNCS
summaryElements = [getAttrFuncs[x](CDS, record, hStr) for x in summaryFormat]
return "\t".join(summaryElements) | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return string DateAnswer: {id: '%s', answer: '%s'} % tuple id answer
end function | def __repr__(self):
return "DateAnswer: {id: '%s', answer: '%s'}" % (self.id, self.answer) | Python | nomic_cornstack_python_v1 |
function _fig_VRTe_ ax coord data_sol **kwargs
begin
set tuple coord_x coord_y = call parseCoord coord dim=string 2d
if get kwargs string clim is not none
begin
set clim = get kwargs string clim
set norm_z = data_sol - clim at 0 / clim at 1 - clim at 0
end
else
begin
set norm_z = data_sol - min data_sol / max data_sol ... | def _fig_VRTe_(ax, coord, data_sol, **kwargs):
coord_x, coord_y = parseCoord(coord, dim="2d")
if kwargs.get("clim") is not None:
clim = kwargs.get("clim")
norm_z = (data_sol - clim[0]) / (clim[1] - clim[0])
else:
norm_z = (data_sol - min(data_sol)) / (max(data_sol) - min(data_sol))
... | Python | nomic_cornstack_python_v1 |
function compress_array str_list withHC=LZ4_HIGH_COMPRESSION
begin
string Compress an array of strings Parameters ---------- str_list: `list[str]` The input list of strings which need to be compressed. withHC: `bool` This flag controls whether lz4HC will be used. Returns ------- `list[str` The list of the compressed st... | def compress_array(str_list, withHC=LZ4_HIGH_COMPRESSION):
"""
Compress an array of strings
Parameters
----------
str_list: `list[str]`
The input list of strings which need to be compressed.
withHC: `bool`
This flag controls whether lz4HC will be used.
Retur... | Python | jtatman_500k |
from models.region_model import Region
from models.community_model import Community
class CountyArea extends Region
begin
string Attributes: name (str) administrative_number (int) communities (list) voivodeship (Voivodeship) area_type (str)
set area_type = string
function __init__ self name number voivodeship
begin
ca... | from models.region_model import Region
from models.community_model import Community
class CountyArea(Region):
"""
Attributes:
name (str)
administrative_number (int)
communities (list)
voivodeship (Voivodeship)
area_type (str)
"""
area_type = ''
def __init_... | Python | zaydzuhri_stack_edu_python |
string Created on 04/04/2015 @author: ivan
from estego.automata import automata
from datetime import time
import time
function chiCuadrado muestra
begin
string Realiza una prueba de uniformidad a una lista de bits seudoaleatoria
set fo0 = count muestra 0
set fo1 = count muestra 1
set fe0 = length muestra / 2
set fe1 = ... | '''
Created on 04/04/2015
@author: ivan
'''
from estego.automata import automata
from datetime import time
import time
def chiCuadrado(muestra):
'''Realiza una prueba de uniformidad a una lista de bits seudoaleatoria
'''
fo0 = muestra.count(0)
fo1 = muestra.count(1)
fe0 = len(muestra)/2
fe1 = ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Jul 16 14:55:02 2019 @author: xiang
comment in this file, we will use the flask to handle the POST requests that we will get from the request.py
comment importing the mothods and libraries
comment numpy to create the array of requested data,
comment pickle to load our... | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 14:55:02 2019
@author: xiang
"""
# in this file, we will use the flask to handle the POST requests that we will get from the request.py
# importing the mothods and libraries
# numpy to create the array of requested data,
# pickle to load our trained model to predit
... | Python | zaydzuhri_stack_edu_python |
string Date 10/28/2018 author Neha Gupta As a data engineer, you are asked to create a mechanism to analyze past years data, specificially calculate two metrics: Top 10 Occupations and Top 10 States for certified visa applications. https://github.com/InsightDataScience/h1b_statistics
import csv
import sys
from collecti... | """
Date 10/28/2018
author Neha Gupta
As a data engineer, you are asked to create a mechanism to analyze past years data,
specificially calculate two metrics: Top 10 Occupations and Top 10 States for certified visa applications.
https://github.com/InsightDataScience/h1b_statistics
"""
import csv
... | Python | zaydzuhri_stack_edu_python |
function _init
begin
string build connection and init it
call connect
comment start track
comment all services were provided here:
comment https://android.googlesource.com/platform/system/core/+/jb-dev/adb/SERVICES.TXT
set ready_data = call encode_data string host:track-devices
call send ready_data
comment get status
s... | def _init():
""" build connection and init it"""
connection.connect()
# start track
# all services were provided here:
# https://android.googlesource.com/platform/system/core/+/jb-dev/adb/SERVICES.TXT
ready_data = utils.encode_data('host:track-devices')
connection.adb_socket.send(ready_data... | Python | jtatman_500k |
function session self
begin
return get _data string session
end function | def session(self):
return self._data.get('session') | Python | nomic_cornstack_python_v1 |
function correct_brackets sentence
begin
while string () in sentence or string [] in sentence or string {} in sentence
begin
set sentence = replace sentence string [] string
set sentence = replace sentence string () string
set sentence = replace sentence string {} string
end
return not sentence
end function
set sentenc... | def correct_brackets(sentence):
while '()' in sentence or '[]' in sentence or '{}' in sentence:
sentence = sentence.replace('[]','')
sentence = sentence.replace('()','')
sentence = sentence.replace('{}','')
return not sentence
sentence = input('Пожалуйста, введите скобочную последова... | Python | zaydzuhri_stack_edu_python |
if string portakal in meyveler
begin
print index meyveler string portakal
end
if string elma in meyveler
begin
print index meyveler string elma
end
print string ---------------------------------------------------
set meyveler1 = list string elma string muz string portakal string mandalina
print meyveler1
for eleman in ... | if "portakal" in meyveler:
print(meyveler.index("portakal"))
if "elma" in meyveler:
print(meyveler.index("elma"))
print("---------------------------------------------------")
meyveler1 = ["elma", "muz", "portakal", "mandalina"]
print(meyveler1)
for eleman in meyveler1:
if eleman == "portakal" or eleman ... | Python | zaydzuhri_stack_edu_python |
function connect_ls_to_lr ls lr rp rp_ip rp_mac db
begin
call ovn_nbctl string -- --id=@lrp create Logical_Router_port name=%s network=%s mac=%s -- add Logical_Router %s ports @lrp -- lsp-add %s rp-%s % tuple rp rp_ip rp_mac lr ls rp db
call ovn_nbctl string set Logical-Switch-Port rp-%s type=router options:router-port... | def connect_ls_to_lr(ls, lr, rp, rp_ip, rp_mac, db):
ovn_nbctl("-- --id=@lrp create Logical_Router_port name=%s network=%s "
"mac=%s -- add Logical_Router %s ports @lrp -- lsp-add %s "
"rp-%s" % (rp, rp_ip, rp_mac, lr, ls, rp), db)
ovn_nbctl("set Logical-Switch-Port rp-%s type=router... | Python | nomic_cornstack_python_v1 |
function enmap_from_healpix_interp hp_map shape wcs rot=string gal,equ interpolate=false
begin
import healpy as hp
from astropy.coordinates import SkyCoord
import astropy.units as u
set eq_coords = list string fk5 string j2000 string equatorial
set gal_coords = list string galactic
set imap = zeros shape wcs
set tuple ... | def enmap_from_healpix_interp(hp_map, shape, wcs , rot="gal,equ",
interpolate=False):
import healpy as hp
from astropy.coordinates import SkyCoord
import astropy.units as u
eq_coords = ['fk5', 'j2000', 'equatorial']
gal_coords = ['galactic']
imap = enmap.zeros(shape, wcs)
Ny, Nx = shape
pixmap = enmap.... | Python | nomic_cornstack_python_v1 |
function test_operation_arg_expressions self parse_input_mocked_metadata
begin
set bb = call parse_input_mocked_metadata string float alpha = 0.5 float Delta=sqrt(2) Coherent(alpha**2.0, Delta*sqrt(pi), 0.2*10) | 0
set alpha = 0.5
set Delta = square root 2
set expected = list alpha ^ 2 Delta * square root pi 0.2 * 10
a... | def test_operation_arg_expressions(self, parse_input_mocked_metadata):
bb = parse_input_mocked_metadata(
"float alpha = 0.5\nfloat Delta=sqrt(2)\nCoherent(alpha**2.0, Delta*sqrt(pi), 0.2*10) | 0\n"
)
alpha = 0.5
Delta = np.sqrt(2)
expected = [alpha ** 2, Delta * np.s... | Python | nomic_cornstack_python_v1 |
function leading_members ctx msg
begin
set tuple ids left = call leading_mentions msg
set guild = guild
return tuple list comprehension m for m in generator expression get members id=i for i in set ids if m left
end function | def leading_members(ctx: Context, msg: str) -> tuple:
ids, left = leading_mentions(msg)
guild = ctx.guild
return [m for m in (get(guild.members, id=i) for i in set(ids)) if m], left | Python | nomic_cornstack_python_v1 |
import re
class VrboParser
begin
function __init__ self response
begin
set xpath = xpath
set response = response
end function
decorator property
function url self
begin
return url
end function
decorator property
function name self
begin
set name_xp = string //*[@itemprop='name']/@content
try
begin
set name = extract ca... | import re
class VrboParser:
def __init__(self, response):
self.xpath = response.xpath
self.response = response
@property
def url(self):
return self.response.url
@property
def name(self):
name_xp = "//*[@itemprop='name']/@content"
try:
name = se... | Python | zaydzuhri_stack_edu_python |
function stop_facial_recognition self
begin
call stop_capture
end function | def stop_facial_recognition(self):
self.facial_recog_thread.stop_capture() | Python | nomic_cornstack_python_v1 |
import pandas as pd
import argparse
from colorama import Fore , init
from pprint import pprint
comment bom = "D:/Tillo/Documents/Projects/hardware/safematic/CCU-010/CCU_Glimmprint/Project Outputs for CCU_Glimmprint/Rev03/Assembly Default/BOM/5000039_03_Glimmprint-BM.xls"
comment pp = "D:/Tillo/Documents/Projects/hardwa... | import pandas as pd
import argparse
from colorama import Fore, init
from pprint import pprint
# bom = "D:/Tillo/Documents/Projects/hardware/safematic/CCU-010/CCU_Glimmprint/Project Outputs for CCU_Glimmprint/Rev03/Assembly Default/BOM/5000039_03_Glimmprint-BM.xls"
# pp = "D:/Tillo/Documents/Projects/hardware/safematic... | Python | zaydzuhri_stack_edu_python |
function networks auth
begin
set response = get API auth string /v2.0/networks
return dictionary comprehension net at string id : net for net in json response at string networks
end function | def networks(auth):
response = API.get(auth, '/v2.0/networks')
return {net['id']: net for net in response.json()['networks']} | Python | nomic_cornstack_python_v1 |
function preprocess_image_meta image_labels save_dir=none
begin
set image_labels at string image_name = image_labels at string image
set image_labels at string x = image_labels at string left
set image_labels at string y = image_labels at string top
set image_labels at string w = image_labels at string width
set image_... | def preprocess_image_meta(
image_labels: pd.DataFrame, save_dir: Optional[str] = None
) -> pd.DataFrame:
image_labels["image_name"] = image_labels["image"]
image_labels["x"] = image_labels["left"]
image_labels["y"] = image_labels["top"]
image_labels["w"] = image_labels["width"]
image_labels["h"]... | Python | nomic_cornstack_python_v1 |
import re
from datetime import timedelta
from math import sqrt , cos , sin , atan2 , radians , degrees
from session.config import settings
from data.util import some , rounded
from data.utc import duration_str
comment ---------- Constants ----------
set AMSL_reading_regexp = compile string (\d+)( ?ft)?$ flags=IGNORECAS... | import re
from datetime import timedelta
from math import sqrt, cos, sin, atan2, radians, degrees
from session.config import settings
from data.util import some, rounded
from data.utc import duration_str
# ---------- Constants ----------
AMSL_reading_regexp = re.compile('(\\d+)( ?ft)?$', flags=re.IGNOR... | Python | zaydzuhri_stack_edu_python |
function forward self src_tokens src_lengths prev_output_tokens context_tokens context_lengths **kwargs
begin
set context_out = call context_encoder context_tokens src_lengths=context_lengths keyword kwargs
set encoder_out = call encoder src_tokens src_lengths=src_lengths context_out=context_out keyword kwargs
set deco... | def forward(self, src_tokens, src_lengths, prev_output_tokens, context_tokens, context_lengths, **kwargs):
context_out = self.context_encoder(context_tokens, src_lengths=context_lengths, **kwargs)
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, context_out=context_out, **kwargs)
... | Python | nomic_cornstack_python_v1 |
function get_title_hash self
begin
return hex digest call sha3_256 encode call get_title_str string utf-8
end function | def get_title_hash(self) -> str:
return hashlib.sha3_256(
self.get_title_str().encode('utf-8')
).hexdigest() | Python | nomic_cornstack_python_v1 |
comment !/bin/env python3
from smbus2 import SMBus , i2c_msg
from bitstring import BitArray , Bits , pack
from contextlib import contextmanager
import RPi.GPIO as GPIO
set DIAL_ADDRESS = 50
set READ_SENSOR_CMD = 1
set READY_PIN = 4
call setmode BCM
comment Set pin to be an input pin and set initial value to be pulled l... | #!/bin/env python3
from smbus2 import SMBus, i2c_msg
from bitstring import BitArray, Bits, pack
from contextlib import contextmanager
import RPi.GPIO as GPIO
DIAL_ADDRESS = 0x32
READ_SENSOR_CMD = 0x01
READY_PIN =4
GPIO.setmode(GPIO.BCM)
GPIO.setup(READY_PIN, GPIO.IN, pull_up_down=GPIO... | Python | zaydzuhri_stack_edu_python |
function stop self
begin
return call udp_debug_sptr_stop self
end function | def stop(self):
return _spacegrant_swig.udp_debug_sptr_stop(self) | Python | nomic_cornstack_python_v1 |
function get_relevant_rejected nodes outer=false leaves=false
begin
assert not outer and leaves
if outer
begin
set nodes = list comprehension node for node in nodes if rejected and all list comprehension not rejected for child in children
end
else
if leaves
begin
set nodes = list comprehension node for node in nodes if... | def get_relevant_rejected(nodes, outer=False, leaves=False):
assert not (outer and leaves)
if outer:
nodes = [node for node in nodes if node.rejected and all([not child.rejected for child in node.children])]
elif leaves:
nodes = [node for node in nodes if node.is_leaf]
... | Python | nomic_cornstack_python_v1 |
function test_add self
begin
add sample_list string Apple Pie string As American as... 6000
add sample_list string Ice Cream string Lieutenant Dan!! 1
assert equal name string Apple Pie
assert equal calories 6000
assert equal description string Lieutenant Dan!!
assert equal next_id 3
end function | def test_add(self):
self.sample_list.add("Apple Pie", "As American as...", 6000)
self.sample_list.add("Ice Cream", "Lieutenant Dan!!", 1)
self.assertEqual(self.sample_list.desserts[0].name, "Apple Pie")
self.assertEqual(self.sample_list.desserts[0].calories, 6000)
self.assertEqu... | Python | nomic_cornstack_python_v1 |
function Execute self conn request
begin
comment New request or old?
try
begin
set session = call getTagAttr string command string sessionid
end
except Exception
begin
set session = none
end
try
begin
set action = call getTagAttr string command string action
end
except Exception
begin
set action = none
end
if action ==... | def Execute(self, conn, request):
# New request or old?
try:
session = request.getTagAttr("command", "sessionid")
except Exception:
session = None
try:
action = request.getTagAttr("command", "action")
except Exception:
action = None
if action == None:
action = "execute"
# Check ... | Python | nomic_cornstack_python_v1 |
function check_transform ops data expect float_tol=1e-08 check_column_order=false cols_case_sensitive=false check_row_order=false local_data_model=none
begin
if local_data_model is none
begin
set local_data_model = default_data_model
end
if not is instance ops ViewRepresentation
begin
raise call TypeError string expect... | def check_transform(
ops,
data,
expect,
*,
float_tol=1e-8,
check_column_order=False,
cols_case_sensitive=False,
check_row_order=False,
local_data_model=None,
):
if local_data_model is None:
local_data_model = data_algebra.default_data_model
if not isinstance(ops, Vie... | Python | nomic_cornstack_python_v1 |
string Module to create the SpectralBiclusters algorithm
import sys
import os.path as o
append path absolute path o join o directory name o __file__ string ..
import pandas as pd
from collections import defaultdict
from sklearn.cluster.bicluster import SpectralBiclustering
from model.DataHelper import save_df_to_file ,... | '''
Module to create the SpectralBiclusters algorithm
'''
import sys
import os.path as o
sys.path.append(o.abspath(o.join(o.dirname(sys.modules[__name__].__file__), "..")))
import pandas as pd
from collections import defaultdict
from sklearn.cluster.bicluster import SpectralBiclustering
from model.DataHelper imp... | Python | zaydzuhri_stack_edu_python |
string Module with base test class.
import random
import secrets
import unittest
from aes import constants
class BaseTestCase extends TestCase
begin
string Base test class.
decorator classmethod
function setUpClass cls
begin
set offset = 0
set size = 4 * NB
set tests = 200
end function
decorator staticmethod
function _... | """Module with base test class."""
import random
import secrets
import unittest
from aes import constants
class BaseTestCase(unittest.TestCase):
"""Base test class."""
@classmethod
def setUpClass(cls):
cls.offset = 0
cls.size = 4 * constants.NB
cls.tests = 200
@staticmethod... | Python | zaydzuhri_stack_edu_python |
string ID: nbjarvi1 LANG: PYTHON3 TASK: crypt1
from itertools import product
function readnint handle
begin
return list map int split strip read line handle
end function
function list2int lst
begin
return sum generator expression item * 10 ^ i for tuple i item in enumerate reversed lst
end function
with open string cry... | """
ID: nbjarvi1
LANG: PYTHON3
TASK: crypt1
"""
from itertools import product
def readnint(handle):
return list(map(
int,
handle.readline().strip().split()))
def list2int(lst):
return sum(
item*10**i
for i, item in enumerate(reversed(lst)))
with open("crypt1.in", "r") as fin:... | Python | zaydzuhri_stack_edu_python |
class Services
begin
function __init__ self servicesList
begin
set servicesList = servicesList
end function
function setServicesList self servicesList
begin
set servicesList = servicesList
end function
function getServicesList self
begin
return servicesList
end function
end class | class Services:
def __init__(self, servicesList: list):
self.servicesList = servicesList
def setServicesList(self, servicesList: list):
self.servicesList = servicesList
def getServicesList(self):
return self.servicesList
| Python | zaydzuhri_stack_edu_python |
function fib i
begin
global fibs
while length fibs - 1 < i
begin
set fibs = fibs + list fibs at - 1 + fibs at - 2
end
return fibs at i
end function | def fib(i):
global fibs
while len(fibs)-1 < i:
fibs += [fibs[-1]+fibs[-2]]
return fibs[i];
| Python | zaydzuhri_stack_edu_python |
import threading
import time
class mythread extends Thread
begin
function __init__ self threadID name counter
begin
call __init__ self
set threadID = threadID
set name = name
set counter = counter
end function
end class | import threading
import time
class mythread(threading.Thread):
def __init__(self,threadID,name,counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render , redirect , get_object_or_404
from carrinho import Carrinho
from vendas.models import Produto
from forms import FormAddCarrinho
comment Create your views here.
function adicionar request
begin
if method == string ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect,get_object_or_404
from .carrinho import Carrinho
from vendas.models import Produto
from .forms import FormAddCarrinho
# Create your views here.
def adicionar(request):
if request.method == 'POST':
c... | Python | zaydzuhri_stack_edu_python |
function validate filename=none ocrd_page=none ocrd_file=none strictness=string strict strategy=string index1
begin
if ocrd_page
begin
set validator = call PageValidator ocrd_page strictness strategy
end
else
if ocrd_file
begin
set validator = call PageValidator call page_from_file ocrd_file strictness strategy
end
els... | def validate(filename=None, ocrd_page=None, ocrd_file=None, strictness='strict', strategy='index1'):
if ocrd_page:
validator = PageValidator(ocrd_page, strictness, strategy)
elif ocrd_file:
validator = PageValidator(page_from_file(ocrd_file), strictness, strategy)
elif fi... | Python | nomic_cornstack_python_v1 |
function __init__ self event_loop=none shutdown_grace_seconds=SHUTDOWN_GRACE_SECONDS
begin
set _event_loop = if expression event_loop is not none then event_loop else call get_event_loop
set _shutdown_grace_seconds = shutdown_grace_seconds
set _log = call getLogger __name__
end function | def __init__(self, event_loop=None, shutdown_grace_seconds=SHUTDOWN_GRACE_SECONDS):
self._event_loop = event_loop if event_loop is not None else asyncio.get_event_loop()
self._shutdown_grace_seconds = shutdown_grace_seconds
self._log = logging.getLogger(ActorContext.__name__) | Python | nomic_cornstack_python_v1 |
function UninstallPandasTools
begin
global _originalSettings
set __ge__ = _originalSettings at string Chem.Mol.__ge__
set __str__ = _originalSettings at string Chem.Mol.__str__
end function | def UninstallPandasTools():
global _originalSettings
Chem.Mol.__ge__ = _originalSettings['Chem.Mol.__ge__']
Chem.Mol.__str__ = _originalSettings['Chem.Mol.__str__'] | Python | nomic_cornstack_python_v1 |
function attach_session self
begin
string Create a session and inject it as context for this command and any subcommands.
assert session is none
set root = call find_root
set session = call Session root
call inject_context session=session
return session
end function | def attach_session(self):
""" Create a session and inject it as context for this command and any
subcommands. """
assert self.session is None
root = self.find_root()
session = self.Session(root)
root.inject_context(session=session)
return session | Python | jtatman_500k |
comment 09-27
comment Giuseppina
comment pf on regression problem
import numpy as np
import pickle
import matplotlib
call use string Agg
import matplotlib.pyplot as plt
seed 0
function relu X
begin
return call maximum X 0
end function
function dRelu x
begin
set x at x <= 0 = 0
set x at x > 0 = 1
return x
end function
f... | #09-27
#Giuseppina
# pf on regression problem
import numpy as np
import pickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
np.random.seed(0)
def relu(X):
return np.maximum(X, 0)
def dRelu(x):
x[x<=0] = 0
x[x>0] = 1
return x
def indeces(weights,N):
ind=np.random.choice(n... | Python | zaydzuhri_stack_edu_python |
set numbers = range 0 100 + 1
set sum_squares = sum list comprehension n * n for n in numbers
set total = sum numbers
set square_sum = total * total | numbers = range(0,100+1)
sum_squares = sum([n*n for n in numbers])
total = sum(numbers)
square_sum = total*total | Python | zaydzuhri_stack_edu_python |
import os
import yaml
from cassette import Cassette
function load_cassette cassette_path
begin
try
begin
set pc = load yaml open cassette_path
set cassette = call Cassette pc
return cassette
end
except IOError
begin
return none
end
end function
function save_cassette cassette_path cassette
begin
set tuple dirname filen... | import os
import yaml
from .cassette import Cassette
def load_cassette(cassette_path):
try:
pc = yaml.load(open(cassette_path))
cassette = Cassette(pc)
return cassette
except IOError:
return None
def save_cassette(cassette_path, cassette):
dirname, filename = os.path.spli... | Python | jtatman_500k |
comment Import Libraries
from tkinter import *
import tkinter as tk
import requests
import pandas as pd
from requests.packages.urllib3.exceptions import InsecureRequestWarning
comment To ignore the Insecure Request Warning
call disable_warnings InsecureRequestWarning
set m = call Tk
comment Font style and height
set LA... | #Import Libraries
from tkinter import *
import tkinter as tk
import requests
import pandas as pd
from requests.packages.urllib3.exceptions import InsecureRequestWarning
#To ignore the Insecure Request Warning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
m = Tk()
#Font style and heig... | Python | zaydzuhri_stack_edu_python |
function test_topology_connectivity topology
begin
if length firewall_objects + length panorama_objects == 0
begin
raise call ConnectionError string No firewalls or panorama instances could be connected.
end
return string ok
end function | def test_topology_connectivity(topology: Topology):
if len(topology.firewall_objects) + len(topology.panorama_objects) == 0:
raise ConnectionError("No firewalls or panorama instances could be connected.")
return "ok" | Python | nomic_cornstack_python_v1 |
function read_structure self structure_file
begin
comment Parse XML structure file
set structure_file = absolute path path structure_file
set structure_dict = call read_lime_questionnaire_structure structure_file
comment Get pandas.DataFrame table for the structure
set section_df = call DataFrame structure_dict at stri... | def read_structure(self, structure_file: str) -> None:
# Parse XML structure file
self.structure_file = os.path.abspath(structure_file)
structure_dict = read_lime_questionnaire_structure(structure_file)
# Get pandas.DataFrame table for the structure
section_df = pd.DataFrame(st... | Python | nomic_cornstack_python_v1 |
comment import sys
comment sys.stdin = open('17070.txt', 'r')
comment TC = int(input())
function cal x y state
begin
set result = 0
if x == N - 1 and y == N - 1
begin
return 1
end
for mode in range 3
begin
if mode == 0 and state == 2 or mode == 2 and state == 0
begin
continue
end
set Test_X = x + dx at mode
set Test_Y ... | # import sys
# sys.stdin = open('17070.txt', 'r')
# TC = int(input())
def cal(x, y, state):
result = 0
if x == N-1 and y == N-1:
return 1
for mode in range(3):
if (mode == 0 and state == 2) or (mode == 2 and state == 0):
continue
Test_X = x + dx[mode]
Test_Y = y ... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function combinationSum self candidates target
begin
string :type candidates: List[int] :type target: int :rtype: List[List[int]]
set results = list
call helper candidates target 0 list results
return results
end function
function helper self candidates target start soFar results
b... | class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
results = []
self.helper(candidates, target, 0, [], results)
return results
def helper(self, ca... | Python | zaydzuhri_stack_edu_python |
comment Class Definitions
comment -----------------
class shortgame
begin
set id = string
set url = string
set name = string
set rank = string
set year = string
set image = string
function __init__ self name_in url_in rank_in year_in image_url_in
begin
set name = name_in
set url = url_in
set rank = rank_in
set ye... | # Class Definitions
# -----------------
class shortgame:
id = ""
url = ""
name = ""
rank = ""
year = ""
image = ""
def __init__(self,name_in, url_in, rank_in, year_in, image_url_in):
self.name = name_in
self.url = url_in
self.rank = rank_in
self.year = ye... | Python | zaydzuhri_stack_edu_python |
from ann import Ann
import numpy as np
class BackPropagation extends Ann
begin
decorator staticmethod
function _sigmoid x
begin
return 1.0 / 1.0 + exp - x
end function
function run self inputs output_training nn seasons alfa
begin
set layer_size = length nn
for season in range seasons
begin
set z_input = list comprehen... | from ann import Ann
import numpy as np
class BackPropagation(Ann):
@staticmethod
def _sigmoid(x):
return 1.0/(1.0+np.exp(-x))
def run(self, inputs, output_training, nn, seasons, alfa):
layer_size = len(nn)
for season in range(seasons):
z_input = [[0 for z_i in range(... | Python | zaydzuhri_stack_edu_python |
function reset self
begin
pass
end function | def reset(self):
pass | Python | nomic_cornstack_python_v1 |
function solve
begin
set tuple D N = map int split input
set horses = list
for i in range N
begin
set tuple K S = map int split input
append horses list K S
end
sort horses key=lambda x -> x at 0 reverse=true
set maxtime = 0
for tuple i h in enumerate horses
begin
set time = D - h at 0 / h at 1
if time > maxtime
begin... | def solve():
D, N = map(int, input().split())
horses = []
for i in range(N):
K, S = map(int, input().split())
horses.append([K, S])
horses.sort(key = lambda x: x[0], reverse=True)
maxtime = 0
for i, h in enumerate(horses):
time = (D - h[0]) / h[1]
if time > maxt... | Python | zaydzuhri_stack_edu_python |
import collections
import os
function getAlldirWide path
begin
set queue = deque
append queue path
while length queue != 0
begin
set dirpath = call popleft
set filelist = list directory dirpath
for fileName in filelist
begin
set fileAbspath = join path dirpath fileName
if is directory path fileAbspath
begin
append queu... | import collections
import os
def getAlldirWide(path):
queue=collections.deque()
queue.append(path)
while len(queue)!=0:
dirpath=queue.popleft()
filelist=os.listdir(dirpath)
for fileName in filelist:
fileAbspath = os.path.join(dirpath, fileName)
i... | Python | zaydzuhri_stack_edu_python |
function home request
begin
return call render request string home.html
end function | def home(request):
return render(request, 'home.html') | Python | nomic_cornstack_python_v1 |
function to_geopandas self crs=none
begin
try
begin
import geopandas as gpd
end
except ImportError
begin
raise call ImportError string Using to_geopandas requires the `geopandas` package.You can install it via Pip or Conda.
end
if crs is none
begin
set crs = dict string init string epsg:4326
end
set gf = call from_feat... | def to_geopandas(self, crs=None):
try:
import geopandas as gpd
except ImportError:
raise ImportError(
'Using to_geopandas requires the `geopandas` package.'
'You can install it via Pip or Conda.'
)
if crs is None:
c... | Python | nomic_cornstack_python_v1 |
function get_children self
begin
return list values self
end function | def get_children(self) -> List[BaseServiceT]:
return list(self.values()) | Python | nomic_cornstack_python_v1 |
function __display_options self
begin
comment os.system("cls")
print string { prompt } { string - * 20 }
set backNumber = 1
if options
begin
set backNumber = length options + 1
for tuple index option in enumerate options
begin
print string { index + 1 } . { option at string text }
end
end
if back
begin
print string { b... | def __display_options(self):
# os.system("cls")
print(f"\n{self.prompt}\n{'-'*20}")
backNumber = 1
if self.options:
backNumber = len(self.options) + 1
for index, option in enumerate(self.options):
print(f"{index + 1}. {option['text']}")
if ... | Python | nomic_cornstack_python_v1 |
function get_tokens doc
begin
return list comprehension text for tok in doc
end function | def get_tokens(doc: Doc) -> List[str]:
return [tok.text for tok in doc] | Python | nomic_cornstack_python_v1 |
string 사다리 게임이 지겨워진 알고리즘 반 학생들이 새로운 게임을 만들었다. 가위바위보가 그려진 카드를 이용해 토너먼트로 한 명을 뽑는 것이다. 게임 룰은 다음과 같다. 1번부터 N번까지 N명의 학생이 N장의 카드를 나눠 갖는다. 전체를 두 개의 그룹으로 나누고, 그룹의 승자끼리 카드를 비교해서 이긴 사람이 최종 승자가 된다. 그룹의 승자는 그룹 내부를 다시 두 그룹으로 나눠 뽑는데, i번부터 j번까지 속한 그룹은 파이썬 연산으로 다음처럼 두개로 나눈다. ..... 두 그룹이 각각 1명이 되면 양 쪽의 카드를 비교해 승자를 가리고, 다시 더 큰 그룹의 승자를 뽑... | '''
사다리 게임이 지겨워진 알고리즘 반 학생들이 새로운 게임을 만들었다. 가위바위보가 그려진 카드를 이용해 토너먼트로 한 명을 뽑는 것이다. 게임 룰은 다음과 같다.
1번부터 N번까지 N명의 학생이 N장의 카드를 나눠 갖는다. 전체를 두 개의 그룹으로 나누고, 그룹의 승자끼리 카드를 비교해서 이긴 사람이 최종 승자가 된다.
그룹의 승자는 그룹 내부를 다시 두 그룹으로 나눠 뽑는데, i번부터 j번까지 속한 그룹은 파이썬 연산으로 다음처럼 두개로 나눈다.
.....
두 그룹이 각각 1명이 되면 양 쪽의 카드를 비교해 승자를 가리고, 다시 더 큰 그룹의 승자를 뽑는... | Python | zaydzuhri_stack_edu_python |
string This is a (slightly templated) Python script responsible for preparing the sys.path environment before each actual Turtle script runs.
comment optional, autodetected if set to None
set _cfg_base_dir = none
comment optional, autodetected if set to None
set _cfg_lib_dir_name = none
set _cfg_lib_dir_name_pattern = ... | '''
This is a (slightly templated) Python script responsible for preparing the sys.path environment
before each actual Turtle script runs.
'''
_cfg_base_dir = None # optional, autodetected if set to None
_cfg_lib_dir_name = None # optional, autodetected if set to None
_cfg_lib_dir_name_pattern = 'lib-python-%s.%s-%sbi... | Python | zaydzuhri_stack_edu_python |
comment Implement a function product to multiply 2 numbers recursively using + and - operators only.
function product x y
begin
if x == 0 or y == 0
begin
return 0
end
return x + product x y - 1
end function | #Implement a function product to multiply 2 numbers recursively using + and - operators only.
def product(x,y):
if x == 0 or y == 0:
return 0
return x +product(x,y-1)
| Python | zaydzuhri_stack_edu_python |
from bisect import bisect_left , bisect_right
set n = integer input
set A = sorted list map int split input
set B = list map int split input
set C = sorted list map int split input
set ans = 0
for b in B
begin
set index_a = call bisect_left A b
set index_c = call bisect_right C b
set ans = ans + index_a * n - index_c
e... | from bisect import bisect_left,bisect_right
n=int(input())
A=sorted(list(map(int,input().split())))
B=list(map(int,input().split()))
C=sorted(list(map(int,input().split())))
ans=0
for b in B:
index_a=bisect_left(A,b)
index_c=bisect_right(C,b)
ans +=index_a*(n-index_c)
print(ans) | Python | zaydzuhri_stack_edu_python |
for i in str1
begin
if i == char
begin
set count = count + 1
end
end
comment Print the result
print string The character { char } appears { count } times in the string { str1 } | for i in str1:
if i == char:
count = count + 1
# Print the result
print (f'The character {char} appears {count} times in the string {str1}') | Python | iamtarun_python_18k_alpaca |
function checkDivisibility a b
begin
if a % b == 0
begin
print string a is divisible by b
end
else
begin
print string a is not divisible by b
end
end function
comment Driver program to test the above function
call checkDivisibility 4 2
function getSum a b
begin
return a + b
end function
print string Addition Value is e... | def checkDivisibility(a, b):
if a % b == 0 :
print ("a is divisible by b")
else:
print ("a is not divisible by b")
#Driver program to test the above function
checkDivisibility(4, 2)
def getSum(a,b):
return a+b;
print("Addition Value is",end=" ")
print(getSum(5,5))
| Python | zaydzuhri_stack_edu_python |
function shutdown_clients self
begin
for rank in range 1 world_size
begin
set tuple _ message_code _ = call recv_package src=rank
if message_code == ParameterUpdate
begin
call recv_package src=rank
end
comment the next package is model request
set pack = call Package message_code=Exit
call send_package pack dst=rank
en... | def shutdown_clients(self):
for rank in range(1, self._network.world_size):
_, message_code, _ = PackageProcessor.recv_package(src=rank)
if message_code == MessageCode.ParameterUpdate:
PackageProcessor.recv_package(
src=rank) # the next package is mod... | Python | nomic_cornstack_python_v1 |
function get_translations_from_apps lang apps=none
begin
if lang == string en
begin
return dict
end
set translations = dict
for app in apps or call get_installed_apps _ensure_on_bench=true
begin
set path = call get_app_path app string translations lang + string .csv
update translations call get_translation_dict_from_... | def get_translations_from_apps(lang, apps=None):
if lang == "en":
return {}
translations = {}
for app in apps or frappe.get_installed_apps(_ensure_on_bench=True):
path = frappe.get_app_path(app, "translations", lang + ".csv")
translations.update(get_translation_dict_from_file(path, lang, app) or {})
if "-" ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import argparse
import json
import subprocess
import os
import sys
import time
set parser = call ArgumentParser description=string A tester to test your comepitive coding solution against test cases
set language = call add_mutually_exclusive_group required=true
call add_argument string program... | #!/usr/bin/python3
import argparse
import json
import subprocess
import os
import sys
import time
parser = argparse.ArgumentParser(
description="A tester to test your comepitive coding solution against test cases")
language = parser.add_mutually_exclusive_group(required=True)
parser.add_argument('program_file',
... | Python | zaydzuhri_stack_edu_python |
from Computer import Computer
class MiniComputer extends Computer
begin
set _company : str
function set_company self cmpy
begin
set _company = cmpy
end function
function billing self
begin
return string Billing method calling from MiniComputer Class
end function
end class | from Computer import Computer
class MiniComputer(Computer):
_company: str
def set_company(self, cmpy):
self._company = cmpy
def billing(self):
return "Billing method calling from MiniComputer Class"
| Python | zaydzuhri_stack_edu_python |
function Appliquer auto char
begin
set etat = 0
set i = 0
set final = - 1
while i < length char and etat != - 1
begin
comment ~ print char[i], etat, auto.delta[etat][ord(char[i])]
set etat = delta at etat at ordinal char at i
if etat in F
begin
set final = i
end
set i = i + 1
end
return final
end function | def Appliquer(auto, char):
etat = 0
i=0
final = -1
while i<len(char) and etat != -1:
#~ print char[i], etat, auto.delta[etat][ord(char[i])]
etat = auto.delta[etat][ord(char[i])]
if etat in auto.F:
final = i
i+=1
return final | Python | nomic_cornstack_python_v1 |
function elasticbeanstalk_platform_auto_update_check cache session awsAccountId awsRegion awsPartition
begin
set elasticbeanstalk = call client string elasticbeanstalk
comment ISO Time
set iso8601Time = call isoformat
for envs in call describe_environments cache session at string Environments
begin
comment B64 encode a... | def elasticbeanstalk_platform_auto_update_check(cache: dict, session, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:
elasticbeanstalk = session.client("elasticbeanstalk")
# ISO Time
iso8601Time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
for envs in des... | Python | nomic_cornstack_python_v1 |
function setMeta self title=none description=none
begin
string Set metadata for photo. (flickr.photos.setMeta)
set method = string flickr.photos.setMeta
if title is none
begin
set title = title
end
if description is none
begin
set description = description
end
call _dopost method auth=true title=title description=descr... | def setMeta(self, title=None, description=None):
"""Set metadata for photo. (flickr.photos.setMeta)"""
method = 'flickr.photos.setMeta'
if title is None:
title = self.title
if description is None:
description = self.description
_dopost(method... | Python | jtatman_500k |
class Animal
begin
function __init__ self typee color legs speed
begin
set typee = typee
set color = color
set legs = legs
set speed = speed
end function
function printval self
begin
print typee color legs speed
end function
end class
class Child extends Animal
begin
function __init__ self petage petname typee color le... | class Animal:
def __init__(self,typee,color,legs,speed):
self.typee=typee
self.color=color
self.legs=legs
self.speed=speed
def printval(self):
print(self.typee,self.color,self.legs,self.speed)
class Child(Animal):
def __init__(self,petage,petname,typee,color,legs,sp... | Python | zaydzuhri_stack_edu_python |
import time
import curses
set SPACE_BAR = 32
set TICK = 0.1
function game_runner stdscr Game
begin
comment Make stdscr.getch non-blocking
call nodelay true
clear stdscr
call keypad true
call curs_set false
comment curses.echo()
call cbreak
set player = 1
set game = call Game stdscr
call add_player player
set player = p... | import time
import curses
SPACE_BAR = 32
TICK = 0.1
def game_runner(stdscr, Game):
# Make stdscr.getch non-blocking
stdscr.nodelay(True)
stdscr.clear()
stdscr.keypad(True)
curses.curs_set(False)
# curses.echo()
curses.cbreak()
player = 1
game = Game(stdscr)
game.add_player(... | Python | zaydzuhri_stack_edu_python |
function calc_fwhm self fwhm_hor fwhm_ver z_focver=0 z_fochor=0 distances=dict E_phot=none
begin
set lam = c * h / electron_volt / E_phot
print lam * 10000000000.0
comment w = fwhm_fac*fwhm
set fwhm_fac = 1 / square root 2 * log 2
comment div_ver = np.arctan(fwhm_ver*fwhm_fac/2/(self.d_kbver+z_focver)) #half divergenc... | def calc_fwhm(
self, fwhm_hor, fwhm_ver, z_focver=0, z_fochor=0, distances={}, E_phot=None
):
lam = constants.c * constants.h / constants.electron_volt / E_phot
print(lam * 1e10)
fwhm_fac = 1 / np.sqrt(2 * np.log(2)) # w = fwhm_fac*fwhm
# div_ver = np.arctan(fwhm_ver*fwhm_fa... | Python | nomic_cornstack_python_v1 |
function canRelocate self fileHeader
begin
Ellipsis
end function | def canRelocate(self, fileHeader: ghidra.app.util.bin.format.coff.CoffFileHeader) -> bool:
... | Python | nomic_cornstack_python_v1 |
function cut value arg
begin
return replace value arg string
end function | def cut(value, arg):
return value.replace(arg, ' ') | Python | nomic_cornstack_python_v1 |
function increment self var value
begin
call _do_assignment var string += value
return self
end function | def increment(self, var: classical_types._ClassicalVar, value: AstConvertible) -> Program:
self._do_assignment(var, "+=", value)
return self | Python | nomic_cornstack_python_v1 |
comment Missile Launcher Code
import struct
import os
import sys
import platform
import time
import socket
import re
import json
import base64
set DEVICE = none
set DEVICE_TYPE = none
comment Car Code
import RPi.GPIO as GPIO
call setmode BOARD
setup GPIO 13 OUT
setup GPIO 15 OUT
setup GPIO 21 OUT
setup GPIO 19 OUT
setu... | #
# Missile Launcher Code
#
import struct
import os
import sys
import platform
import time
import socket
import re
import json
import base64
DEVICE = None
DEVICE_TYPE = None
#
# Car Code
#
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)
GPI... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import csv
class ReadModule extends object
begin
comment INIT STARTS###
comment Default quotes is none
function __init__ self filename header_count footer_count delimiter quote=string
begin
set filename = filename
set header_count = header_count
set footer_count = footer_count
set delimiter = delimi... | import pandas as pd
import csv
class ReadModule(object):
###INIT STARTS###
def __init__(self,filename,header_count,footer_count,delimiter,quote=''): #Default quotes is none
self.filename = filename
self.header_count = header_count
self.footer_count = footer_count
self.delimiter = delimiter
... | 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.