code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string The basics of lists
comment Declare a list of values using square brackets
set fruits = list string apple string banana string cherry string durian string eggplant string fig
comment Printing a list prints all of its values
print fruits
comment Individual elements are accessed using [ ] and an index value
commen... | """
The basics of lists
"""
# Declare a list of values using square brackets
fruits = ['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig']
# Printing a list prints all of its values
print(fruits)
# Individual elements are accessed using [ ] and an index value
#
# LIST INDEXING IN PYTHON STARTS FROM ZERO!
#
#... | Python | zaydzuhri_stack_edu_python |
function search number lower_bound upper_bound
begin
set start = time
info string Start looking for %d number
if not lower_bound <= number <= upper_bound
begin
raise call RuntimeError string Given number must be in [ { lower_bound } , { upper_bound } ]
end
while true
begin
set guess = random integer lower_bound upper_b... | def search(number, lower_bound, upper_bound):
start = time.time()
logger.info("Start looking for %d", number)
if not lower_bound <= number <= upper_bound:
raise RuntimeError(f"Given number must be in [{lower_bound}, {upper_bound}]")
while True:
guess = random.randint(lower_bound, upper_b... | Python | nomic_cornstack_python_v1 |
function test_report_abuse self
begin
pass
end function | def test_report_abuse(self):
pass | Python | nomic_cornstack_python_v1 |
string i=1 while(12<i<20): print(i)
string a=float(input("Enter a Number:")); if(a%2==0): print("This Number is Even") else: print("This Number is Odd")
string import random r=random.randint(1,6) print(r)
string import random while True : a=input("press t")
string for i in range(1,100): for j in range(1,100): print(i,'... | '''i=1
while(12<i<20):
print(i)'''
"""a=float(input("Enter a Number:"));
if(a%2==0):
print("This Number is Even")
else:
print("This Number is Odd")"""
'''import random
r=random.randint(1,6)
print(r)'''
'''import random
while True :
a=input("press t")'''
"""for i in range(1,100):
for j in range(1,100):
print(... | Python | zaydzuhri_stack_edu_python |
function _SizeCalculator partition_size
begin
comment Minus footer size to return max image size.
return partition_size - integer power partition_size 0.95
end function | def _SizeCalculator(partition_size):
# Minus footer size to return max image size.
return partition_size - int(math.pow(partition_size, 0.95)) | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
import Login
comment put your own path of chromedriver
set browser = call Chrome string /Users/nippon/Downloads/chromedriver
get browser string https://linkedin.com
call click
sleep 1
call send_keys email
sleep 1
call ... | from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
import Login
browser = webdriver.Chrome('/Users/nippon/Downloads/chromedriver') # put your own path of chromedriver
browser.get('https://linkedin.com')
browser.find_element_by_link_text('Sign in').click()
sleep(1)
b... | Python | zaydzuhri_stack_edu_python |
function online_score_handler request context storage
begin
comment type: (MethodRequest, dict, InMemoryStorage) -> (str, int)
set tuple response code = tuple dict OK
try
begin
set nested_request = call OnlineScoreRequest keyword arguments
end
except TypeError
begin
set msg = string Extra arguments in request:
excepti... | def online_score_handler(request, context, storage):
# type: (MethodRequest, dict, InMemoryStorage) -> (str, int)
response, code = {}, OK
try:
nested_request = OnlineScoreRequest(**request.arguments)
except TypeError:
msg = 'Extra arguments in request: '
logging.exception('%s :' ... | Python | nomic_cornstack_python_v1 |
function campaign_well_plot campaign plot_tests=true plot_well_names=true fig=none style=string WTP
begin
set well_const0 = list
set names = list
for w in wells
begin
append well_const0 list pos at 0 pos at 1
append names w
end
set well_const = list well_const0
set fig = call plot_well_pos well_const names plot_well_... | def campaign_well_plot(
campaign, plot_tests=True, plot_well_names=True, fig=None, style="WTP"
):
well_const0 = []
names = []
for w in campaign.wells:
well_const0.append(
[campaign.wells[w].pos[0], campaign.wells[w].pos[1]]
)
names.append(w)
well_const = [well_co... | Python | nomic_cornstack_python_v1 |
function read_file self filename
begin
try
begin
read _config filename
end
except IOError as e
begin
print string e
end
try else
begin
append _loaded_paths call Path filename
call update_cached_options
end
end function | def read_file(self, filename: str) -> None:
try:
self._config.read(filename)
except IOError as e:
print(str(e))
else:
self._loaded_paths.append(Path(filename))
self.update_cached_options() | Python | nomic_cornstack_python_v1 |
function foundation_damping_paolucci ALR foundation_rotation DR
begin
comment TODO: refactor into a dictionary
set zeta_min = 0.036
if DR == 90
begin
set Nratio = list 2 3 4.5 6 7.5 9 10 15 20 25 30
set alpha = list 27.73 32.76 43.93 62.25 66.96 85.08 95.6 164.42 233.7 305.97 382.51
comment 4th number a bit high
set ze... | def foundation_damping_paolucci(ALR, foundation_rotation, DR):
# TODO: refactor into a dictionary
zeta_min = 0.036
if DR == 90:
Nratio = [2, 3, 4.5, 6, 7.5, 9, 10, 15, 20, 25, 30]
alpha = [
27.73,
32.76,
43.93,
62.25,
66.96,
... | Python | nomic_cornstack_python_v1 |
function __init__ self attributes=none **kwargs
begin
call __init__ list
for key in STRING_FIELDS
begin
set self at key = string
end
set self at string rank = default dictionary list
if attributes is not none
begin
update self attributes
end
update self kwargs
set problems = list string Not validated
end function | def __init__(self, attributes=None, **kwargs):
super().__init__(list)
for key in self.STRING_FIELDS:
self[key] = ''
self['rank'] = defaultdict(list)
if attributes is not None:
self.update(attributes)
self.update(kwargs)
self.problems = ['Not valid... | Python | nomic_cornstack_python_v1 |
class InvalidInputError extends Exception
begin
pass
end class
function calculate_sum input_list
begin
try
begin
comment Attempt to calculate the sum of the list
set total = sum input_list
return total
end
comment Catch the TypeError exception if any element in the list is non-integer
except TypeError
begin
raise call ... | class InvalidInputError(Exception):
pass
def calculate_sum(input_list):
try:
total = sum(input_list) # Attempt to calculate the sum of the list
return total
except TypeError: # Catch the TypeError exception if any element in the list is non-integer
raise InvalidInputError("Invalid... | Python | jtatman_500k |
function fit_nfw_rs_fixed z R_bins shear_red_obs shear_err sigma_crit omega_m c200m_interp **kwargs
begin
function f_min prms
begin
return call shear_red_nfw_rs_fixed_minimize prms=prms z=z R_bins=R_bins shear_red_obs=shear_red_obs shear_err=shear_err sigma_crit=sigma_crit omega_m=omega_m c200m_interp=c200m_interp
end ... | def fit_nfw_rs_fixed(
z, R_bins, shear_red_obs, shear_err,
sigma_crit, omega_m, c200m_interp,
**kwargs):
def f_min(prms):
return shear_red_nfw_rs_fixed_minimize(
prms=prms, z=z, R_bins=R_bins, shear_red_obs=shear_red_obs,
shear_err=shear_err, sigma_crit=sigma_... | Python | nomic_cornstack_python_v1 |
from flask import Flask
from flask import request
import numpy as np
import math
from forex_agent import ForexAgent
from forex_environment import ForexEnvironment
import threading
import logging
set log = call getLogger string werkzeug
set disabled = true
set app = call Flask __name__
set disabled = true
set myAgent = ... | from flask import Flask
from flask import request
import numpy as np
import math
from forex_agent import ForexAgent
from forex_environment import ForexEnvironment
import threading;
import logging
log = logging.getLogger('werkzeug')
log.disabled = True
app = Flask(__name__)
app.logger.disabled = True
myAgent = Fore... | Python | zaydzuhri_stack_edu_python |
function python_version self
begin
return version
end function | def python_version(self):
return self.requirement.version | Python | nomic_cornstack_python_v1 |
function secure_vm_disk_encryption_set_id self
begin
return get pulumi self string secure_vm_disk_encryption_set_id
end function | def secure_vm_disk_encryption_set_id(self) -> Optional[str]:
return pulumi.get(self, "secure_vm_disk_encryption_set_id") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import serial
import textwrap
import markdown
import time
import re
set DEVICE = string /dev/ttyAMA0
set SPEED = 19200
set VERSION = string 0.25 ALPHA
set DEBUG = true
comment bytecodes for various printer commands, perhaps soon to be legacy
set EMPHASIZE = 8
set DOUBLEHEIGHT = 16
set DOUBLEWID... | #!/usr/bin/python
import serial
import textwrap
import markdown
import time
import re
DEVICE = "/dev/ttyAMA0"
SPEED = 19200
VERSION = "0.25 ALPHA"
DEBUG = True
# bytecodes for various printer commands, perhaps soon to be legacy
EMPHASIZE = 8
DOUBLEHEIGHT = 16
DOUBLEWIDTH = 32
CHAR_WIDTH = 30
class RPrinter:
... | Python | zaydzuhri_stack_edu_python |
comment this module is required for opening movie youtube trailer
import webbrowser
string Movie class: Instace variables: -title: Movie title -storyline: Movie description -poster: Movie poster -trailer_youtube_url: Movie trailer youtube URL Instance methods: -show_trailer: Function that shows movie trailer in a web b... | # this module is required for opening movie youtube trailer
import webbrowser
"""
Movie class:
Instace variables:
-title: Movie title
-storyline: Movie description
-poster: Movie poster
-trailer_youtube_url: Movie trailer youtube URL
Instance methods:
-show_trailer: Function that shows movie trailer in a web browser
"... | Python | zaydzuhri_stack_edu_python |
function test_task_state_comb_3 plugin tmp_path
begin
set nn = call combine combiner=list string a
set cache_dir = tmp_path
assert splitter == string NA.a
assert splitter_rpn == list string NA.a
assert a == list
with call Submitter plugin=plugin as sub
begin
sub nn
end
comment checking the results
set results = call r... | def test_task_state_comb_3(plugin, tmp_path):
nn = fun_addtwo(name="NA").split(splitter="a", a=[]).combine(combiner=["a"])
nn.cache_dir = tmp_path
assert nn.state.splitter == "NA.a"
assert nn.state.splitter_rpn == ["NA.a"]
assert nn.inputs.a == []
with Submitter(plugin=plugin) as sub:
... | Python | nomic_cornstack_python_v1 |
function make_ari env device
begin
return call TorchTensorObservation call ResetARI call AtariARIWrapper env device
end function | def make_ari(env, device):
return TorchTensorObservation(ResetARI(AtariARIWrapper(env)), device) | Python | nomic_cornstack_python_v1 |
comment Declare size for while loop
set height = 0
comment initialize spaces to 1
set spaces = 1
comment while input between 1 and 8
while height <= 0 or height > 8
begin
comment take in input and cast to int
set height = input string Height:
comment if it fails to cast, set to 0
try
begin
set height = integer height
e... | # Declare size for while loop
height = 0
# initialize spaces to 1
spaces = 1
# while input between 1 and 8
while (height <= 0 or height > 8):
#take in input and cast to int
height = input("Height: ")
#if it fails to cast, set to 0
try:
height = int(height)
except ValueError:
height =... | Python | zaydzuhri_stack_edu_python |
async function async_id_unknown_devices config_dir
begin
await call async_load id_devices=1
for addr in devices
begin
set device = devices at addr
set flags = true
for name in operating_flags
begin
if not is_loaded
begin
set flags = false
break
end
end
if flags
begin
for name in properties
begin
if not is_loaded
begin
... | async def async_id_unknown_devices(config_dir):
await devices.async_load(id_devices=1)
for addr in devices:
device = devices[addr]
flags = True
for name in device.operating_flags:
if not device.operating_flags[name].is_loaded:
flags = False
bre... | Python | nomic_cornstack_python_v1 |
function create_barn_door self
begin
set light_shape = call getShape
set inputs = call inputs type=string aiBarndoor
if inputs
begin
set barn_door = inputs at 0
end
else
begin
set barn_door = call createNode string aiBarndoor
call attr string message ? next_available
end
end function | def create_barn_door(self):
light_shape = self.light.getShape()
inputs = light_shape.inputs(type='aiBarndoor')
if inputs:
self.barn_door = inputs[0]
else:
self.barn_door = pm.createNode('aiBarndoor')
self.barn_door.attr('message') >> \
... | Python | nomic_cornstack_python_v1 |
string Simple python stuff, but including for light revision
comment comparison operators
comment True
print 1 < 2
comment False
print 1 == 2
comment True
print 1 != 2
comment logical operators
comment False
print true and false
comment True
print true or false | """
Simple python stuff, but including for light revision
"""
# comparison operators
print(1 < 2) # True
print(1 == 2) # False
print(1 != 2) # True
# logical operators
print(True and False) # False
print(True or False) # True
| Python | zaydzuhri_stack_edu_python |
function set_resolution self width height
begin
try
begin
assert type width == int and type height == int msg string [ERROR] Input resolution is not integer
set _resolution_width = width
set _resolution_height = height
string Add your code here
return true
end
except AssertionError as error
begin
string Add your code h... | def set_resolution(self, width, height):
try:
assert (type(width) == int and type(height) == int), "[ERROR] Input resolution is not integer"
self._resolution_width = width
self._resolution_height = height
'''
Add your code here
'''
... | Python | nomic_cornstack_python_v1 |
function set_rating self user val activity
begin
call record_vote self user val
call record_event self user activity
end function
comment self.update_score() | def set_rating(self, user, val, activity):
Vote.objects.record_vote(self, user, val)
Event.record_event(self, user, activity)
#self.update_score() | Python | nomic_cornstack_python_v1 |
string This script should be used to download and process x-ray images from the NIH database of chest x-rays. It goes all the way throug the steps of procesing the data in pytorch tensors. Afterwards other scripts should be used for training and testing and experimentation with optimization alogorithms, kernel size, an... | '''
This script should be used to download and process x-ray images from the NIH
database of chest x-rays. It goes all the way throug the steps of procesing the
data in pytorch tensors. Afterwards other scripts should be used for training and testing
and experimentation with optimization alogorithms, kernel size, and... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
from unittest import TestCase
from collections import Counter
from sol1 import Solution
import logging , unittest
class Test extends TestCase
begin
set sol = none
function setUp self
begin
set sol = call Solution
end function
function test0 self
begin
set n = list string eat string tea string ... | #!/usr/bin/python3
from unittest import TestCase
from collections import Counter
from sol1 import Solution
import logging, unittest
class Test(TestCase):
sol = None
def setUp(self):
self.sol = Solution()
def test0(self):
n = ["eat", "tea", "tan", "ate", "nat", "bat"]
ans = [["ate... | Python | zaydzuhri_stack_edu_python |
function show_pupil self
begin
set tuple fig ax = call subplots 1 2 figsize=tuple 12 6 tight_layout=false
set sup_title = string NA = { NA } , n = { n }
if has attribute self string thickness
begin
set sup_title = sup_title + string , slab thickness = { thickness } $\mu$m, n1 = { n1 } , alpha = { alpha }
end
call supti... | def show_pupil(self):
fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=False)
sup_title = f'NA = {self.NA}, n = {self.n}'
if hasattr(self,'thickness'):
sup_title += f', slab thickness = {self.thickness} $\mu$m, n1 = {self.n1}, alpha = {self.alpha:.02f}'
f... | Python | nomic_cornstack_python_v1 |
function prepare_extraction features in_folder out_folder
begin
comment Get image feature extractors
set image_extractors = list
for feature in features
begin
if is_image
begin
append image_extractors name
end
end
set labels = call get_labels_from_folder in_folder
return call prepare_extraction_ out_folder labels imag... | def prepare_extraction(features, in_folder, out_folder):
# Get image feature extractors
image_extractors = []
for feature in features:
if feature.is_image:
image_extractors.append(feature.name)
labels = get_labels_from_folder(in_folder)
return prepare_extraction_(out_folder, la... | Python | nomic_cornstack_python_v1 |
function read self url
begin
info string Downloading KMZ file { base name url }
set kml = call fetch url
info string Parsing KML data
set iter_elems = call iterparse call BytesIO kml events=tuple string start string end resolve_entities=false
set prod_items = dict string issuer string Issuer ; string product_id string ... | def read(self, url: str):
log.info(f"Downloading KMZ file {basename(url)}")
kml = self.fetch(url)
log.info("Parsing KML data")
self.iter_elems = iterparse(BytesIO(kml), events=("start", "end"), resolve_entities=False)
prod_items = {
"issuer": "Issuer",
... | Python | nomic_cornstack_python_v1 |
function get_pgdict_from_cfg
begin
set cfg = call get_config
try
begin
set pghost = get cfg string postgres string host
set pgdb = get cfg string postgres string database
set pguser = get cfg string postgres string user
set pgpassword = get cfg string postgres string password
set dbitems = dict string PGUSER pguser ; s... | def get_pgdict_from_cfg():
cfg = configuration.get_config()
try:
pghost = cfg.get('postgres', 'host')
pgdb = cfg.get('postgres', 'database')
pguser = cfg.get('postgres', 'user')
pgpassword = cfg.get('postgres', 'password')
dbitems = {'PGUSER': pguser, 'PGPASSWORD': pgpas... | Python | nomic_cornstack_python_v1 |
function _observe_update self device
begin
call async_set_updated_data data=device
end function | def _observe_update(self, device: Device) -> None:
self.async_set_updated_data(data=device) | Python | nomic_cornstack_python_v1 |
function vector_field_module self dest_map=none force_free=false
begin
from vectorfield_module import VectorFieldModule , VectorFieldFreeModule
if dest_map is none
begin
set dest_map = _identity_map
end
set dest_map_name = _name
set codomain = _codomain
comment !# to be improved (replace dest_map_name by dest_map)
if d... | def vector_field_module(self, dest_map=None, force_free=False):
from vectorfield_module import VectorFieldModule, VectorFieldFreeModule
if dest_map is None:
dest_map = self._identity_map
dest_map_name = dest_map._name
codomain = dest_map._codomain
if dest_map_name not... | Python | nomic_cornstack_python_v1 |
function team_members_id_team_members_get self id **kwargs
begin
set kwargs at string _return_http_data_only = true
if get kwargs string callback
begin
return call team_members_id_team_members_get_with_http_info id keyword kwargs
end
else
begin
set data = call team_members_id_team_members_get_with_http_info id keyword ... | def team_members_id_team_members_get(self, id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.team_members_id_team_members_get_with_http_info(id, **kwargs)
else:
(data) = self.team_members_id_team_members_get_with_http_info(id, *... | Python | nomic_cornstack_python_v1 |
string This module represents the Marketplace. Computer Systems Architecture Course Assignment 1 March 2020
from threading import Lock
class Marketplace
begin
string Class that represents the Marketplace. It's the central part of the implementation. The producers and consumers use its methods concurrently.
function __i... | """
This module represents the Marketplace.
Computer Systems Architecture Course
Assignment 1
March 2020
"""
from threading import Lock
class Marketplace:
"""
Class that represents the Marketplace. It's the central part of the implementation.
The producers and consumers use its methods concurrently.
... | Python | zaydzuhri_stack_edu_python |
function compute num
begin
set tuple amnt fc = tuple 1 2
while fc * fc <= num
begin
if num % fc == 0
begin
set num = num / fc
set amnt = amnt + 1
end
else
begin
set fc = fc + 1
end
end
return amnt
end function
print call compute integer input | def compute(num):
amnt,fc = 1,2
while (fc*fc<=num):
if num%fc==0:
num/=fc
amnt+=1
else:
fc+=1
return amnt
print(compute(int(input())))
| Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment In[1]:
print string Based on : https://arxiv.org/abs/1411.2738 for forward and backpropogation derivations of Word2Vec CBOW & Skipgram.
comment numpy version '1.13.1'
comment In[ ]:
print string ######################
print string Make sure you have internet connection (2-5 Mbps),Tensorflo... | # coding: utf-8
# In[1]:
print ("Based on : https://arxiv.org/abs/1411.2738 for forward and backpropogation derivations of Word2Vec CBOW & Skipgram.")
#numpy version '1.13.1'
# In[ ]:
print ("######################")
print ("\n Make sure you have internet connection (2-5 Mbps),Tensorflow, math, numpy-1.13.1, NLT... | Python | zaydzuhri_stack_edu_python |
function connect self *args **kwargs
begin
raise NotImplementedError
end function | def connect(self, *args, **kwargs):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import sys
set N = integer strip call raw_input
set A = map int split strip call raw_input string
set p = 0.0
set z = 0.0
set n = 0.0
for i in range 0 N
begin
if A at i > 0
begin
set p = p + 1
end
if A at i < 0
begin
set n = n + 1
end
if A at i == 0
begin
set z = z + 1
end
end
print decimal p / N decimal n / N decimal ... | import sys
N = int(raw_input().strip())
A = map(int,raw_input().strip().split(' '))
p = 0.0
z = 0.0
n = 0.0
for i in range(0,N):
if(A[i] > 0):
p = p+1
if(A[i] < 0):
n = n +1
if(A[i] == 0):
z = z +1
print (float(p/N),float(n/N),float(z/N))
| Python | zaydzuhri_stack_edu_python |
function basic_block_conv inputs nChIn nChTmp kSize is_training data_format sparsity shared_weights block_name
begin
with call name_scope block_name
begin
set shortcut = inputs
with call name_scope string batch_normalization
begin
set inputs = call batch_norm_relu inputs is_training data_format
end
with call name_scope... | def basic_block_conv(inputs, nChIn, nChTmp, kSize, is_training, data_format,
sparsity, shared_weights, block_name):
with tf.name_scope(block_name):
shortcut = inputs
with tf.name_scope('batch_normalization'):
inputs = batch_norm_relu(inputs, is_training, data_format)
wit... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
from iminuit import Minuit , describe
from probfit import BinnedChi2 , Extended
from invisible_cities.core.core_functions import in_range
from plotting_functions import plot_residuals_E_reso_gaussC
from control_plots import labels , hist
function gaussC x mu sigma N Ny... | import numpy as np
import matplotlib.pyplot as plt
from iminuit import Minuit, describe
from probfit import BinnedChi2, Extended
from invisible_cities.core .core_functions import in_range
from plotting_functions import plot_residuals_E_reso_gaussC
from control_plots import labels, hist
def gaussC(x, mu, sigm... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function minCostToSupplyWater self n wells pipes
begin
string :type n: int :type wells: List[int] :type pipes: List[List[int]] :rtype: int
set adjList = default dictionary list
for index in range length pipes
begin
set tuple h1 h2 cost = tuple pipes at index at 0 pipes at index at 1 ... | class Solution(object):
def minCostToSupplyWater(self, n, wells, pipes):
"""
:type n: int
:type wells: List[int]
:type pipes: List[List[int]]
:rtype: int
"""
adjList = collections.defaultdict(list)
for index in range(len(pipes)):
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Nov 23 18:18:35 2020 @author: Sonwe
import tkinter as tk
set window = call Tk
comment 创建entry控件
set e = call Entry window
call pack
comment 创建radiobutton控件
set var = call IntVar
set MPT = list tuple string 01 COIL STATUS 1 tuple string 02 INPUT STATUS 2 tuple string 0... | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 18:18:35 2020
@author: Sonwe
"""
import tkinter as tk
window=tk.Tk()
#创建entry控件
e=tk.Entry(window)
e.pack()
#创建radiobutton控件
var = tk.IntVar()
MPT = [("01 COIL STATUS",1),("02 INPUT STATUS",2),("03 HOLIDING REGISTER",3),("04 INPUT REGISTER",4)]
f... | Python | zaydzuhri_stack_edu_python |
function after_upload_forcing msg config checklist
begin
set next_workers = dict string crash list ; string failure nowcast+ list ; string failure forecast2 list ; string failure ssh list ; string failure turbidity list ; string success nowcast+ list ; string success forecast2 list ; string success ssh list ; s... | def after_upload_forcing(msg, config, checklist):
next_workers = {
"crash": [],
"failure nowcast+": [],
"failure forecast2": [],
"failure ssh": [],
"failure turbidity": [],
"success nowcast+": [],
"success forecast2": [],
"success ssh": [],
"su... | Python | nomic_cornstack_python_v1 |
function test_atomic_non_negative_integer_enumeration_2_nistxml_sv_iv_atomic_non_negative_integer_enumeration_3_5 mode save_output output_format
begin
call assert_bindings schema=string nistData/atomic/nonNegativeInteger/Schema+Instance/NISTSchema-SV-IV-atomic-nonNegativeInteger-enumeration-3.xsd instance=string nistDa... | def test_atomic_non_negative_integer_enumeration_2_nistxml_sv_iv_atomic_non_negative_integer_enumeration_3_5(mode, save_output, output_format):
assert_bindings(
schema="nistData/atomic/nonNegativeInteger/Schema+Instance/NISTSchema-SV-IV-atomic-nonNegativeInteger-enumeration-3.xsd",
instance="nistDat... | Python | nomic_cornstack_python_v1 |
function ten_by_ten
begin
set grid = list range 1 101
set end_number = 0
for i in range 10
begin
if i in range end_number + 10 and i <= 100
begin
set line = grid at slice end_number : end_number + 10 :
print string line + string
set end_number = end_number + 10
end
end
end function | def ten_by_ten():
grid = list(range(1, 101))
end_number = 0
for i in range(10):
if i in range(end_number+10) and i <=100:
line = grid[end_number:end_number+10]
print(str(line)+ '\n')
end_number+=10 | Python | nomic_cornstack_python_v1 |
function score x y
begin
set r = x ^ 2 + y ^ 2 ^ 0.5
if r > 10
begin
return 0
end
else
if r > 5
begin
return 1
end
else
if r > 1
begin
return 5
end
else
begin
return 10
end
end function | def score(x, y):
r = (x ** 2 + y ** 2) ** 0.5
if r > 10:
return 0
elif r > 5:
return 1
elif r > 1:
return 5
else:
return 10 | Python | zaydzuhri_stack_edu_python |
function __init__ self roots
begin
if not is instance roots list
begin
raise call TypeError string roots type should be list.
end
for root in roots
begin
call _validate_bytes root SHA256_MIDSTATE_LEN string root element
end
set txn_dhashes = call new string miner_transaction_hash_t [] length roots
set _merkle_edge = ca... | def __init__(self, roots):
if not isinstance(roots, list):
raise TypeError("roots type should be list.")
for root in roots:
_validate_bytes(root, libminerhal.lib.SHA256_MIDSTATE_LEN, "root element")
self.txn_dhashes = libminerhal.ffi.new("miner_transa... | Python | nomic_cornstack_python_v1 |
function build_nested_field self field_name relation_info nested_depth
begin
raise call NotImplementedError string `build_nested_field()` must be implemented.
end function | def build_nested_field(self, field_name, relation_info, nested_depth):
raise NotImplementedError('`build_nested_field()` must be '
'implemented.') | Python | nomic_cornstack_python_v1 |
class Solution
begin
function house_robber_1 self nums
begin
set tuple prev now = tuple 0 0
for n in nums
begin
set tuple prev now = tuple now max prev + n now
end
return now
end function
function house_robber_2 self nums
begin
function rob nums
begin
set now = 0
set prev = 0
for n in nums
begin
set tuple now prev = tu... | class Solution():
def house_robber_1(self, nums):
prev, now = 0, 0
for n in nums:
prev, now = now, max(prev + n, now)
return now
def house_robber_2(self, nums):
def rob(nums):
now = prev = 0
for n in nums:
now, prev = max(now,... | Python | zaydzuhri_stack_edu_python |
for num in list 9 41 12 3 74 15
begin
if num > largest_so_far
begin
set largest_so_far = num
end
print largest_so_far num
end
print string After largest_so_far | for num in [9, 41, 12, 3, 74, 15]:
if num > largest_so_far:
largest_so_far = num
print(largest_so_far,num)
print('After',largest_so_far) | Python | zaydzuhri_stack_edu_python |
function sort_descending list
begin
set sorted_list = sorted list reverse=true
return sorted_list
end function | def sort_descending(list):
sorted_list = sorted(list, reverse=True)
return sorted_list | Python | iamtarun_python_18k_alpaca |
comment UMD 3
from colorama import init , Fore
call init
call init autoreset=true
comment Ejercicio 01
function es_par n
begin
set devolver = false
if n % 2 == 0
begin
set devolver = true
end
return devolver
end function
function es_primo n
begin
set devolver = true
for i in range n - 1 1 - 1
begin
if n % i == 0
begin
... | #UMD 3
from colorama import init, Fore
init()
init(autoreset=True)
#Ejercicio 01
def es_par(n):
devolver = False
if n % 2 == 0:
devolver = True
return devolver
def es_primo(n):
devolver = True
for i in range(n-1,1,-1):
if(n%i==0):
devolver = False
break
... | Python | zaydzuhri_stack_edu_python |
function create self form_data
begin
comment try:
print string in careate
set user = call get_user
set cover_image = pop form_data string cover_image
if cover_image
begin
set tuple cover_image _ = call base64_file cover_image
end
set serializer = call NoteCreateSerializer data=form_data
call is_valid raise_exception=tr... | def create(self, form_data):
# try:
print('in careate')
user = self.get_user()
cover_image = form_data.pop("cover_image")
if cover_image:
cover_image, _ = self.base64_file(cover_image)
serializer = NoteCreateSerializer(data=form_data)
serializer.is_val... | Python | nomic_cornstack_python_v1 |
import unittest
import sphere as sp
import math
import numpy as np
comment Here's our "unit".
comment # Constraint class
comment a1 = sp.Constraint([1, 2, 3], 3)
comment # a1 = sp.Constraint([1, 1, 1], 3)
comment x = np.array([0, 0, 0])
comment print(a1.directedDistanceFrom(x))
comment print(a1.nearestPoint(x))
comment... | import unittest
import sphere as sp
import math
import numpy as np
# Here's our "unit".
# # Constraint class
# a1 = sp.Constraint([1, 2, 3], 3)
# # a1 = sp.Constraint([1, 1, 1], 3)
# x = np.array([0, 0, 0])
# print(a1.directedDistanceFrom(x))
# print(a1.nearestPoint(x))
#
# # cons... | Python | zaydzuhri_stack_edu_python |
comment num=int(input("enter number"))
comment fact=1
comment if num==0:
comment print("factorial is 1")
comment else:
comment for i in range(1,num):
comment fact=fact*i
comment print("factorail is ",fact)
comment with function
function fact num
begin
set fact = 1
for i in range 1 num + 1
begin
set fact = fact * i
end
... | # num=int(input("enter number"))
# fact=1
# if num==0:
# print("factorial is 1")
# else:
# for i in range(1,num):
# fact=fact*i
# print("factorail is ",fact)
#with function
def fact(num):
fact=1
for i in range(1,(num+1)):
fact=fact*i
return fact
print(fact(5))
print("fatori... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
function get_book_details title author
begin
set url = string http://example.com/search?title= { title } &author= { author }
set response = get requests url
set soup = call BeautifulSoup text string html.parser
set book_details = find soup string div dict string class strin... | import requests
from bs4 import BeautifulSoup
def get_book_details(title, author):
url = f'http://example.com/search?title={title}&author={author}'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
book_details = soup.find('div', {'class': 'book-details'})
title = book_details.find('... | Python | flytech_python_25k |
function set_close_on_exec_on_listen_sockets self
begin
for sock in call iter_sockets
begin
if PY2
begin
call fcntl call fileno F_SETFD FD_CLOEXEC
end
else
begin
comment Python 3.4 and later default to sockets having close-on-exec
comment set (what PEP 0446 calls "non-inheritable"). This new method
comment on socket ob... | def set_close_on_exec_on_listen_sockets(self):
for sock in self.iter_sockets():
if six.PY2:
fcntl.fcntl(sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC)
else:
# Python 3.4 and later default to sockets having close-on-exec
# set (what PEP 04... | Python | nomic_cornstack_python_v1 |
from operations import *
function _infix_to_postfix expression
begin
set stack_operators = list
set stack = list
for token in expression
begin
if type token is list
begin
set func = token at 0
set sub_expression = token at 1
append stack call run sub_expression
end
else
if call is_operator token
begin
if CLOSED_BRACK... | from operations import *
def _infix_to_postfix(expression):
stack_operators = []
stack = []
for token in expression:
if type(token) is list:
func = token[0]
sub_expression = token[1]
stack.append(MATH_FUNCTIONS[func](run(sub_expression)))
elif is_opera... | Python | zaydzuhri_stack_edu_python |
function load_directory self dirname skip_balance_check=false
begin
comment which files are relevant
set pattern = string *.txt
comment sort the list so that we always load with matching balances
set files = sorted glob glob join path dirname pattern
for filename in files
begin
call load_file filename skip_balance_chec... | def load_directory(self, dirname, skip_balance_check=False):
# which files are relevant
pattern = "*.txt"
# sort the list so that we always load with matching balances
files = sorted(glob.glob(os.path.join(dirname, pattern)))
for filename in files:
self.load_file(f... | Python | nomic_cornstack_python_v1 |
comment The Standard & Poor's 500, often abbreviated as the S&P 500,
comment or just "the S&P", is an American stock market index based on the market capitalizations of 500 large companies
comment having common stock listed on the NYSE or NASDAQ. The S&P 500 index components and
comment their weightings are determined ... | #The Standard & Poor's 500, often abbreviated as the S&P 500,
#or just "the S&P", is an American stock market index based on the market capitalizations of 500 large companies
#having common stock listed on the NYSE or NASDAQ. The S&P 500 index components and
#their weightings are determined by S&P Dow Jones Indices.
i... | Python | zaydzuhri_stack_edu_python |
import unittest
from list import List
class TestList__init__ extends TestCase
begin
function test_init_with_one_object self
begin
set list1 = list 1
set list2 = list string well
set list3 = list dict string first string second
assert equal string list1 string [1]
assert equal length list1 1
assert equal string list2 st... | import unittest
from list import List
class TestList__init__(unittest.TestCase):
def test_init_with_one_object(self):
list1 = List(1)
list2 = List('well')
list3 = List({'first': 'second'})
self.assertEqual(str(list1), '[1]')
self.assertEqual(len(list1), 1)
self.as... | Python | zaydzuhri_stack_edu_python |
function adjacent_to_enemy self x y
begin
for tuple dx dy in list tuple 0 + 1 tuple + 1 + 1 tuple + 1 0 tuple + 1 - 1 tuple 0 - 1 tuple - 1 - 1 tuple - 1 0 tuple - 1 + 1
begin
if call is_on_board x + dx y + dy and board at x + dx at y + dy == player_just_moved
begin
return true
end
end
return false
end function | def adjacent_to_enemy(self, x, y):
for (dx, dy) in [(0, +1), (+1, +1), (+1, 0), (+1, -1), (0, -1),
(-1, -1), (-1, 0), (-1, +1)]:
if self.is_on_board(x + dx, y + dy) and \
self.board[x + dx][y + dy] == self.player_just_moved:
return True
... | Python | nomic_cornstack_python_v1 |
function getTags sections
begin
comment Keyword patterns to search for
set keywords = list string 2019[\-\s]?n[\-\s]?cov string 2019 novel coronavirus string coronavirus 2(?:019)? string coronavirus disease (?:20)?19 string covid(?:[\-\s]?(?:20)?19)? string n\s?cov[\-\s]?2019 string sars[\-\s]cov-?2 string wuhan (?:cor... | def getTags(sections):
# Keyword patterns to search for
keywords = [r"2019[\-\s]?n[\-\s]?cov", "2019 novel coronavirus", "coronavirus 2(?:019)?", r"coronavirus disease (?:20)?19",
r"covid(?:[\-\s]?(?:20)?19)?", r"n\s?cov[\-\s]?2019", r"sars[\-\s]cov-?2", r"wuhan (?:coronavirus|cov|p... | Python | nomic_cornstack_python_v1 |
function svm_loss_vectorized W X y reg
begin
set loss = 0.0
set dw = zeros shape
comment TODO: #
comment Implement a vectorized version of the structured SVM loss, storing the #
comment result in loss. #
set num_train = shape at 0
set num_class = shape at 1
set score = dot X W
set All_True_Label_Score = reshape score a... | def svm_loss_vectorized(W,X,y,reg):
loss=0.0
dw=np.zeros(W.shape)
#############################################################################
# TODO: #
# Implement a vectorized version of the structured SVM loss, storing the #... | Python | nomic_cornstack_python_v1 |
comment Memoization dictionary to store previously computed values
set memo = dict
function factorial n
begin
comment Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1
begin
return 1
end
comment Check if value is already memoized
if n in memo
begin
return memo at n
end
comment Recursive case: compute factorial o... | # Memoization dictionary to store previously computed values
memo = {}
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Check if value is already memoized
if n in memo:
return memo[n]
# Recursive case: compute factorial of n
resul... | Python | jtatman_500k |
comment ! /usr/bin/env python3.8
import os
set runEnv = upper call getenv string ENV default=string dev
set output = string We are working in { runEnv }
if starts with runEnv string PROD
begin
set output = string CAUTION !! + output
end
print output | #! /usr/bin/env python3.8
import os
runEnv = os.getenv("ENV", default="dev").upper()
output = f"We are working in {runEnv}"
if runEnv.startswith('PROD'):
output = "CAUTION !!" + output
print(output)
| Python | zaydzuhri_stack_edu_python |
function isInt w
begin
if length w > 0
begin
if w at 0 in list string 0 string 1 string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9
begin
return true
end
end
return false
end function
function printExpr elist
begin
if length elist == 0
begin
return tuple string elist
end
if call isInt elist at 0
b... | def isInt(w):
if(len(w)>0):
if w[0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
return True
return False
def printExpr(elist):
if(len(elist)==0):
return '', elist
if(isInt(elist[0])):
return elist[0], elist[1:]
if elist[0] == '*':
left, rest =... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding:utf-8 -*-
string @author: LoopGan @contact: ganwei4955@gamil.com @time: 9/5/2018 1:20 PM
class Solution
begin
function countDigitOne self n
begin
set result = 0
for i in range 1 n + 1
begin
set result = result + count string i string 1
end
return result
end function
end ... | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@author: LoopGan
@contact: ganwei4955@gamil.com
@time: 9/5/2018 1:20 PM
"""
class Solution:
def countDigitOne(self, n):
result = 0
for i in range(1, n + 1):
result += str(i).count('1')
return result
if __name__ ==... | Python | zaydzuhri_stack_edu_python |
comment Example usage
set string_list = list string apple string banana string orange string kiwi string grape string 1234 string apple! string apple1 string apple$ string banana
set length = 4
set filtered_list = call filter_strings string_list length
comment Output: ['banana', 'orange']</s>
print filtered_list | # Example usage
string_list = ["apple", "banana", "orange", "kiwi", "grape", "1234", "apple!", "apple1", "apple$", "banana"]
length = 4
filtered_list = filter_strings(string_list, length)
print(filtered_list) # Output: ['banana', 'orange']</s> | Python | greatdarklord_python_dataset |
function __getitem__ self key
begin
try
begin
return call __getitem__ self key
end
except tuple KeyError
begin
return key
end
end function | def __getitem__(self,key):
try:
return dict.__getitem__(self,key)
except (KeyError,):
return key | Python | nomic_cornstack_python_v1 |
function is_wave self path
begin
return length path at 0 > 1
end function | def is_wave(self,path):
return len(path[0])>1 | Python | nomic_cornstack_python_v1 |
import string
set encrypted = list string ejp mysljylc kd kxveddknmc re jsicpdrysi string rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd string de kr kd eoya kw aej tysr re ujdr lkgc jv string y qeez
set decrypted = list string our language is impossible to understand string there are twenty six factorial possibilities s... | import string
encrypted = ['ejp mysljylc kd kxveddknmc re jsicpdrysi', 'rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd', 'de kr kd eoya kw aej tysr re ujdr lkgc jv', 'y qeez']
decrypted = ['our language is impossible to understand', 'there are twenty six factorial possibilities', 'so it is okay if you want to just give ... | Python | zaydzuhri_stack_edu_python |
comment 深度学习库,Tensor 就是多维数组
import tensorflow as tf
function train epoch_num
begin
comment build a model
set model = sequential
add model flatten layers input_shape=tuple 28 28
add model dense 10 activation=softmax
compile optimizer=string adam loss=string sparse_categorical_crossentropy metrics=list string accuracy
co... | import tensorflow as tf # 深度学习库,Tensor 就是多维数组
def train(epoch_num):
# build a model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
model.compile(optimizer='adam', loss='sparse_categorical_... | Python | zaydzuhri_stack_edu_python |
function how_much_water water load clothes
begin
if load * 2 < clothes
begin
return string Too much clothes
end
else
if clothes < load
begin
return string Not enough clothes
end
set calculated_water = water * 1.1 ^ absolute load - clothes
return round calculated_water 2
end function | def how_much_water(water, load, clothes):
if load * 2 < clothes:
return 'Too much clothes'
elif clothes < load:
return 'Not enough clothes'
calculated_water = water * 1.1 ** abs(load - clothes)
return round(calculated_water, 2)
| Python | zaydzuhri_stack_edu_python |
function épar x
begin
return x % 2 == 0
end function
function par_ou_impar x
begin
if call épar x
begin
return string par
end
else
begin
return string impar
end
end function
print call par_ou_impar 4
print call par_ou_impar 5 | def épar(x):
return(x%2==0)
def par_ou_impar(x):
if épar(x):
return 'par'
else:
return 'impar'
print(par_ou_impar(4))
print(par_ou_impar(5))
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sun Mar 10 00:14:52 2019 @author: thewo
from matplotlib.image import imread
import matplotlib.pyplot as plt
set im = call imread string image.jpg
comment calculate mean value from RGB channels and flatten to 1D array
image show im cmap=string gray interpolation=string bic... | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 00:14:52 2019
@author: thewo
"""
from matplotlib.image import imread
import matplotlib.pyplot as plt
im = imread('image.jpg')
# calculate mean value from RGB channels and flatten to 1D array
plt.imshow(im, cmap = 'gray', interpolation = 'bicubic')
pl... | Python | zaydzuhri_stack_edu_python |
function svn_io_open_uniquely_named *args
begin
return apply svn_io_open_uniquely_named args
end function | def svn_io_open_uniquely_named(*args):
return apply(_core.svn_io_open_uniquely_named, args) | Python | nomic_cornstack_python_v1 |
function _async_raise tid exctype
begin
set tid = call c_long tid
if not call isclass exctype
begin
set exctype = type exctype
end
set res = call PyThreadState_SetAsyncExc tid call py_object exctype
if res == 0
begin
raise call ValueError string invalid thread id
end
else
if res != 1
begin
comment """if it returns a nu... | def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a numbe... | Python | nomic_cornstack_python_v1 |
function filter_bodies bodies
begin
set new_b = list
for b in bodies
begin
if call count_valid_points >= n_valid_points
begin
append new_b b
end
end
return new_b
end function | def filter_bodies(bodies):
new_b = list()
for b in bodies:
if b.count_valid_points() >= n_valid_points:
new_b.append(b)
return new_b | Python | nomic_cornstack_python_v1 |
function lambda_handler event context
begin
set division_by_zero = 4 / 0
return dict string status_code 200 ; string body division_by_zero
end function | def lambda_handler(event, context):
division_by_zero = 4/0
return {
'status_code': 200,
'body': division_by_zero
} | Python | nomic_cornstack_python_v1 |
function breadth_first_search self source
begin
comment Time complexity: O(num_vertices + num_edges), aka O(V+E)
comment Note: This initialization is a must, since other methods may change defaults
set color = list WHITE * length adjlist
comment For source vertex and all undiscovered vertices, their parents are None
se... | def breadth_first_search(self, source: int) -> list:
# Time complexity: O(num_vertices + num_edges), aka O(V+E)
# Note: This initialization is a must, since other methods may change defaults
self.color = [Color.WHITE] * len(self.adjlist)
# For source vertex and all undiscovered ... | Python | nomic_cornstack_python_v1 |
function _keep_all_values_but_diag self a b c d
begin
comment .tolil()
set sub = _sorted_doc_similarities at tuple slice a : b : slice c : d :
call setdiag 0
return sub
end function | def _keep_all_values_but_diag(self, a: int, b: int, c: int, d: int) -> csr_matrix:
sub = self._sorted_doc_similarities[a:b, c:d] # .tolil()
sub.setdiag(0)
return sub | Python | nomic_cornstack_python_v1 |
function get_redirect_url self **kwargs
begin
set billing_agreement_id = get GET string billing_agreement_id
set access_token = get GET string access_token
if billing_agreement_id
begin
try
begin
set session = amazonpaymentssession
end
except DoesNotExist
begin
set session = call AmazonPaymentsSession basket=basket
end... | def get_redirect_url(self, **kwargs):
billing_agreement_id = self.request.GET.get('billing_agreement_id')
access_token = self.request.GET.get('access_token')
if billing_agreement_id:
try:
session = self.request.basket.amazonpaymentssession
except AmazonPay... | Python | nomic_cornstack_python_v1 |
function get_equation self get_function
begin
set lhs_func = call get_function comb_class
set rhs_funcs = tuple generator expression call get_function comb_class for comb_class in children
return call get_equation lhs_func rhs_funcs
end function | def get_equation(
self, get_function: Callable[[CombinatorialClassType], Function]
) -> Eq:
lhs_func = get_function(self.comb_class)
rhs_funcs = tuple(get_function(comb_class) for comb_class in self.children)
return self.constructor.get_equation(lhs_func, rhs_funcs) | Python | nomic_cornstack_python_v1 |
function preprocess input_string doStopWords doPunctuation
begin
set new_str = lower input_string
if doPunctuation
begin
set new_str = call translate transtable
end
if doStopWords
begin
try
begin
set new_str = join string list comprehension word for word in split new_str if word not in stopwords
end
except ValueError ... | def preprocess(input_string, doStopWords, doPunctuation):
new_str = input_string.lower()
if doPunctuation:
new_str = new_str.translate(transtable)
if doStopWords:
try:
new_str = " ".join([word for word in new_str.split() if word not in stopwords])
except ValueError as e:
new_str = ""
return new_str | Python | nomic_cornstack_python_v1 |
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from dash.dependencies import Input , Output
import utils
from sqlalchemy import MetaData , Column , insert , Table
import pymysql
from mysql.connector import errorcode
from sqlalchemy impo... | import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from dash.dependencies import Input, Output
import utils
from sqlalchemy import MetaData, Column, insert, Table
import pymysql
from mysql.connector import errorcode
from sqlalchemy import c... | Python | zaydzuhri_stack_edu_python |
import os
import sys
import logging
import pandas as pd
from sklearn.model_selection import train_test_split
from utilities.aws import download_from_s3 , upload_to_s3
from config import input_filename , label_column , bucket , key
set logger = call getLogger string split_data
call setLevel INFO
set console_handle = cal... | import os
import sys
import logging
import pandas as pd
from sklearn.model_selection import train_test_split
from utilities.aws import download_from_s3, upload_to_s3
from config import input_filename, label_column, bucket, key
logger = logging.getLogger('split_data')
logger.setLevel(logging.INFO)
console_handle = logg... | Python | zaydzuhri_stack_edu_python |
function fields self
begin
set fields = fields
set tuple included_fields_root included_fields_nested = call _split_levels included_fields or list
set tuple excluded_fields_root excluded_fields_nested = call _split_levels excluded_fields or list
comment if there are fields to clean
if length included_fields_root != 0 or... | def fields(self) -> dict:
fields = super(DynamicFieldsSerializerMixin, self).fields
included_fields_root, included_fields_nested = self._split_levels(
self._df_conf.included_fields or []
)
excluded_fields_root, excluded_fields_nested = self._split_levels(
self._d... | Python | nomic_cornstack_python_v1 |
import sqlite3
from collections import defaultdict , OrderedDict
class CmuDb extends object
begin
function __init__ self db_filename
begin
set db = call connect db_filename
set cursor = call cursor
try
begin
execute cursor string CREATE TABLE cmu(word varchar(255), pron varchar(255))
execute cursor string CREATE INDEX ... | import sqlite3
from collections import defaultdict, OrderedDict
class CmuDb(object):
def __init__(self, db_filename):
self.db = sqlite3.connect(db_filename)
cursor = self.db.cursor()
try:
cursor.execute('CREATE TABLE cmu(word varchar(255), pron varchar(255))')
curso... | Python | zaydzuhri_stack_edu_python |
function bubble_sort arr
begin
set n = length arr
for i in range n
begin
for j in range n - 1 - i
begin
if arr at j > arr at j + 1
begin
set tuple arr at j arr at j + 1 = tuple arr at j + 1 arr at j
end
end
end
end function
set num = list 5 3 2 4 1
call bubble_sort num
print num | def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n-1-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
num = [5, 3, 2, 4, 1]
bubble_sort(num)
print(num)
| Python | zaydzuhri_stack_edu_python |
comment Definition for singly-linked list.
comment class ListNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution1 extends object
begin
function detectCycle self head
begin
comment 双指针法,不适用额外的内存
set tuple fast slow = tuple head head
while true
begin
comment 注意这里如果不存在... | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution1(object):
def detectCycle(self, head):
#双指针法,不适用额外的内存
fast,slow = head, head
while True:
#注意这里如果不存在环,python 返回空即可
... | Python | zaydzuhri_stack_edu_python |
function humanize_filesize filesize
begin
string Return human readable pair of size and unit from the given filesize in bytes.
for unit in list string string K string M string G string T string P string E string Z
begin
if filesize < 1024.0
begin
return tuple format string {:3.1f} filesize unit + string B
end
set file... | def humanize_filesize(filesize: int) -> Tuple[str, str]:
"""Return human readable pair of size and unit from the given filesize in bytes."""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if filesize < 1024.0:
return '{:3.1f}'.format(filesize), unit+'B'
filesize /= 1024.0 | Python | jtatman_500k |
for i in range 1 a + 1
begin
set b = b * i
set s = b + s
end
print s | for i in range(1,a+1):
b=b*i
s=b+s
print(s)
| Python | zaydzuhri_stack_edu_python |
function Flux_levels self flux r_lim=0.45
begin
if flux == string mass
begin
set set_integrand = lambda x -> x
end
else
if flux == string momentum
begin
set set_integrand = lambda x -> x ^ 2
end
else
if flux == string buoyancy
begin
set b = call read_vars list string b at string b
set set_integrand = lambda x -> x * b
... | def Flux_levels(self, flux, r_lim=0.45):
if flux == 'mass':
set_integrand = lambda x: x
elif flux == 'momentum':
set_integrand = lambda x: x**2
elif flux == 'buoyancy':
b = self.read_vars(['b'])['b']
set_integrand = lambda x: x*b
npx = s... | Python | nomic_cornstack_python_v1 |
comment noqa: E501 # noqa: E501
function __init__ self source_microversion=none serialization_version=none features=none microversion_skew=none feature_states=none
begin
set _source_microversion = none
set _serialization_version = none
set _features = none
set _microversion_skew = none
set _feature_states = none
set di... | def __init__(self, source_microversion=None, serialization_version=None, features=None, microversion_skew=None, feature_states=None): # noqa: E501 # noqa: E501
self._source_microversion = None
self._serialization_version = None
self._features = None
self._microversion_skew = None
... | Python | nomic_cornstack_python_v1 |
function New *args **kargs
begin
set obj = call __New_orig__
import itkTemplate
call New obj *args keyword kargs
return obj
end function | def New(*args, **kargs):
obj = itkImageToMeshFilterIF2PSSS2.__New_orig__()
import itkTemplate
itkTemplate.New(obj, *args, **kargs)
return obj | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import os
import cburealtimesettings
comment Load up the last stim_ip received
set fin = open join path call incomingmetapath string stim_ip.txt
set stim_ip = read line fin
close fin
comment Communicates with stimulus delivery machine
while 1
begin
set nccmdfile = popen string nc -l -p %d % cal... | #!/usr/bin/python
import os
import cburealtimesettings
# Load up the last stim_ip received
fin=open(os.path.join(cburealtimesettings.incomingmetapath(),'stim_ip.txt'));
stim_ip=fin.readline();
fin.close();
# Communicates with stimulus delivery machine
while (1):
nccmdfile=os.popen("nc -l -p %d"%cburealtimesettings.i... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import xlsxwriter
comment -----------------Driver initializations------------------------------------#
set amazon_driver = call Chrome call install
set flipkart_driver = call Chrome call install
comment... | from bs4 import BeautifulSoup
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import xlsxwriter
#-----------------Driver initializations------------------------------------#
amazon_driver=webdriver.Chrome(ChromeDriverManager().install())
flipkart_driver=webdriver.Chrome(Chr... | 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.