code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function vline self x color=RED
begin
set _vline = tuple x color
if _data_plot_widget
begin
call vline x color
end
end function | def vline(self, x, color=RED):
self._vline = (x, color)
if self._data_plot_widget:
self._data_plot_widget.vline(x, color) | Python | nomic_cornstack_python_v1 |
comment Created by Alessandro Maraio on 06/04/2020.
comment Copyright (c) 2020 University of Sussex.
comment contributor: Alessandro Maraio <am963@sussex.ac.uk>
string This file is dedicated to the CMB map generation TODO: something about folders, or saving the data somewhere in particular?
import os
import time
import... | # Created by Alessandro Maraio on 06/04/2020.
# Copyright (c) 2020 University of Sussex.
# contributor: Alessandro Maraio <am963@sussex.ac.uk>
"""
This file is dedicated to the CMB map generation
TODO: something about folders, or saving the data somewhere in particular?
"""
import os
import time
import ctypes
impo... | Python | zaydzuhri_stack_edu_python |
function _calculate_reciprocal_lattice self lattice
begin
set lattice = array lattice
set tuple a b c alpha beta gamma = call convert_unitcell_to_abc
set volume = call calculate_volume
set inverse_lattice = call inv lattice
set reciprocal_lattice = inverse_lattice
end function | def _calculate_reciprocal_lattice(self, lattice):
self.lattice = np.array(lattice)
self.a, self.b, self.c, self.alpha, self.beta, self.gamma = self.convert_unitcell_to_abc()
self.volume = self.calculate_volume()
self.inverse_lattice = np.linalg.inv(self.lattice)
self.reciprocal_l... | Python | nomic_cornstack_python_v1 |
function percent self per
begin
set per = call _pwm_percent_limits per
set _percent = per
append percent_hist per
if percent_hist at - 2 != per and _daq
begin
set msg = message_bytes
call transmit msg
end
end function | def percent(self, per: float):
per = self._pwm_percent_limits(per)
self._percent = per
self.percent_hist.append(per)
if self.percent_hist[-2] != per and self._daq:
msg = Message("percent", per, self.checksum).message_bytes
self._daq.asynch.transmit(msg) | Python | nomic_cornstack_python_v1 |
function set_isccp4 self isccp4
begin
comment Possibly this should be internally accessible only?
set __isccp4 = isccp4
end function | def set_isccp4(self, isccp4):
# Possibly this should be internally accessible only?
self.__isccp4 = isccp4 | Python | nomic_cornstack_python_v1 |
string Utility functions.
comment ------------------------------------------------------------------
import os
comment ------------------------------------------------------------------
comment -----------------------------------------------------------------------------------------
comment file functions
comment -----... | '''
Utility functions.
'''
#------------------------------------------------------------------
import os
#------------------------------------------------------------------
#-----------------------------------------------------------------------------------------
# file functions
#----------------------------------... | Python | zaydzuhri_stack_edu_python |
function read self length=- 1
begin
string Reads from the FIFO. Reads as much data as possible from the FIFO up to the specified length. If the length argument is negative or ommited all data currently available in the FIFO will be read. If there is no data available in the FIFO an empty string is returned. Args: lengt... | def read(self, length=-1):
"""
Reads from the FIFO.
Reads as much data as possible from the FIFO up to the specified
length. If the length argument is negative or ommited all data
currently available in the FIFO will be read. If there is no data
available in the FIFO an ... | Python | jtatman_500k |
function read_lines_from_file filename
begin
with open filename as f
begin
set content = read lines f
end
set content = list comprehension strip x for x in content
return content
end function | def read_lines_from_file(filename):
with open(filename) as f:
content = f.readlines()
content = [x.strip() for x in content]
return content | Python | nomic_cornstack_python_v1 |
function __mul__ self factor
begin
pass
end function | def __mul__(self, factor):
pass | Python | nomic_cornstack_python_v1 |
import waldo
function get_host
begin
set valid_input = false
while not valid_input
begin
set host = call raw_input string Please enter domain or IP:
set host = split replace replace lower strip host string string https:// string string http:// string string / at 0
if length host > 0
begin
set valid_input = true
end
end... | import waldo
def get_host():
valid_input = False
while not valid_input:
host = raw_input("Please enter domain or IP: ")
host = host.strip(' ').lower().replace("https://","").replace("http://","").split('/')[0]
if len(host) > 0:
valid_input = True | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
if length argv != 3
begin
print string #usage: python argv at 0 string <VCF> <Filter>
exit
end
set fVCF = argv at 1
set sFilter = argv at 2
with open fVCF string r as fr
begin
for line in fr
begin
if sFilter in line
begin
set lLine = split line string
set sChr = lLine at 0
set sPos =... | #!/usr/bin/python
import sys
if len(sys.argv) != 3:
print("#usage: python",sys.argv[0],"<VCF> <Filter>")
sys.exit()
fVCF = sys.argv[1]
sFilter = sys.argv[2]
with open(fVCF,'r') as fr:
for line in fr:
if sFilter in line:
lLine = line.split("\t")
sChr = lLine[0]
... | Python | zaydzuhri_stack_edu_python |
import os
import sys
import re
import time
import inspect
import datetime
import multiprocessing
import getopt
import shutil
import tempfile
import random
import json
import math
import logging
import logging.config
import logging.handlers
call basicConfig level=INFO format=string %(asctime)s %(filename)s:%(lineno)d [P... | import os
import sys
import re
import time
import inspect
import datetime
import multiprocessing
import getopt
import shutil
import tempfile
import random
import json
import math
import logging
import logging.config
import logging.handlers
logging.basicConfig(
level = logging.INFO ,
format = "%(asctim... | Python | zaydzuhri_stack_edu_python |
function test_detach_volume self
begin
set volume = call volumes at 2
with call mock_post string volumes/ { id } as mock
begin
set result = detach volume
assert call_url == string /volumes/ { id } /detach
assert result is true
end
end function | def test_detach_volume(self):
volume = self.client.volumes()[2]
with self.mock_post(f"volumes/{volume.id}") as mock:
result = volume.detach()
assert mock.call_url == f"/volumes/{volume.id}/detach"
assert result is True | Python | nomic_cornstack_python_v1 |
function read_s_met f
begin
set df = read csv f header=none na_values=list string - - 99999 99999 6999 - 6999 parse_dates=list list 1 2 3 date_parser=doy_parser index_col=string 1_2_3 names=list string 0 string 1 string 2 string 3 string ref_temp string precip string soil_tmp4 string soil_heat_flux8_1 string soil_heat_... | def read_s_met(f):
df = pd.read_csv(f, header=None, na_values=['-', -99999, 99999, 6999, -6999], parse_dates=[[1, 2, 3]],
date_parser=doy_parser,
index_col='1_2_3', names=['0', '1', '2', '3',
'ref_temp', 'precip', 'soil_tmp4',... | Python | nomic_cornstack_python_v1 |
function deleted self
begin
return get pulumi self string deleted
end function | def deleted(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "deleted") | Python | nomic_cornstack_python_v1 |
function convert_to_pig_latin sentence
begin
set vowels = set literal string a string e string i string o string u
set punctuation_marks = set literal string . string ! string ?
set words = split sentence
set transformed_words = list
for word in words
begin
comment Check if the word ends with punctuation marks
if word... | def convert_to_pig_latin(sentence: str) -> str:
vowels = {'a', 'e', 'i', 'o', 'u'}
punctuation_marks = {'.', '!', '?'}
words = sentence.split()
transformed_words = []
for word in words:
# Check if the word ends with punctuation marks
if word[-1] in punctuation_marks:
... | Python | greatdarklord_python_dataset |
comment Create database using LHS samlping.
comment Usage: call load_data(parameter), parameter is the size of
comment samples in one dimension (same size in two dimensions)
from pyDOE import *
import numpy as np
import matplotlib.pyplot as plt
function load_data sample_size
begin
set sampling = call lhs 2 samples=samp... | # Create database using LHS samlping.
# Usage: call load_data(parameter), parameter is the size of
# samples in one dimension (same size in two dimensions)
from pyDOE import *
import numpy as np
import matplotlib.pyplot as plt
def load_data(sample_size):
sampling = lhs(2,samples=sample_size,criterion='center')
... | Python | zaydzuhri_stack_edu_python |
string Created on 2017. 8. 1. @author: acorn
string 산포도 그래프 1. 자료의 분포를 표시할때, 2. 생성: scatter 3. 색상변화 줄 항목: c 4. colorbar() 인덱스에 해당하는 색상출력 # 차트에 표시해야하는 문자에 한글잇을떈 from matplotlib import font_manager, rc font_name = font_manager.FontProperties(fname = '글꼴파일이름').get_name() rc('font', family = font_name)
from pandas import S... | '''
Created on 2017. 8. 1.
@author: acorn
'''
"""
산포도 그래프
1. 자료의 분포를 표시할때,
2. 생성: scatter
3. 색상변화 줄 항목: c
4. colorbar() 인덱스에 해당하는 색상출력
# 차트에 표시해야하는 문자에 한글잇을떈
from matplotlib import font_manager, rc
font_name = font_manager.FontProperties(fname = '글꼴파일이름').get_name()
rc('font', family = font_name)
"""
... | Python | zaydzuhri_stack_edu_python |
function xd_identity np_vector axis_name units=none attrs=none
begin
if axis_name in long_name
begin
set the_long_name = long_name at axis_name
end
else
begin
warn string Unknown axis name + axis_name + string encountered in xd_identity creation.
end
if axis_name in default_units
begin
set the_units = default_units at ... | def xd_identity(np_vector, axis_name, units=None, attrs=None):
if axis_name in long_name:
the_long_name = long_name[axis_name]
else:
warnings.warn('Unknown axis name ' + axis_name + ' encountered in xd_identity creation.')
if axis_name in default_units:
the_units = default_units[axis... | Python | nomic_cornstack_python_v1 |
comment Nathan Seltzer
comment Homework 5
comment Problem1b.py
comment import neccesary modules
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
comment opens file with intention of reading, but hasn't read yet
set f = open string stocks.dat string r
comment bypass first line
read line f
comment s... | #Nathan Seltzer
#Homework 5
#Problem1b.py
#import neccesary modules
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
f = open('stocks.dat', 'r') #opens file with intention of reading, but hasn't read yet
f.readline() #bypass first line
#same as annotions for problem1
apple = []
microsoft = []
d... | Python | zaydzuhri_stack_edu_python |
function set_attenuation self att=list 11 * 12
begin
call set_level level=att at 0 ch=string 1X
call set_level level=att at 1 ch=string 1Y
call set_level level=att at 2 ch=string 1X
call set_level level=att at 3 ch=string 1Y
call set_level level=att at 4 ch=string 1X
call set_level level=att at 5 ch=string 1Y
call set_... | def set_attenuation(self, att=[11]*12):
self.driver1.set_level(level=att[0], ch='1X')
self.driver1.set_level(level=att[1], ch='1Y')
self.driver2.set_level(level=att[2], ch='1X')
self.driver2.set_level(level=att[3], ch='1Y')
self.driver3.set_level(level=att[4], ch='1X')
se... | Python | nomic_cornstack_python_v1 |
function all_buckets self
begin
return all
end function | def all_buckets(self):
return self.s3.buckets.all() | Python | nomic_cornstack_python_v1 |
import tkinter as tk
from tkinter import ttk
comment 탭 컨트롤(위젯)을 생성하는 클래스 : Notebook()
set win = call Tk
call geometry string 640x400
call resizable false false
set tabControl = call Notebook win
comment 첫번째 탭
set tab1 = call Frame tabControl
add tabControl tab1 text=string Tab 1
comment 두번째 탭
set tab2 = call Frame tabC... | import tkinter as tk
from tkinter import ttk
# 탭 컨트롤(위젯)을 생성하는 클래스 : Notebook()
win = tk.Tk()
win.geometry("640x400")
win.resizable(False, False)
tabControl = ttk.Notebook(win)
# 첫번째 탭
tab1 = ttk.Frame(tabControl)
tabControl.add(tab1, text='Tab 1')
# 두번째 탭
tab2 = ttk.Frame(tabControl)
tabControl.a... | Python | zaydzuhri_stack_edu_python |
function compute self *args **kwargs
begin
pass
end function | def compute(self, *args, **kwargs):
pass | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import sys
set begin = integer argv at 1
set end = integer argv at 2
for line in stdin
begin
print strip line at slice begin : end :
end | #!/usr/bin/env python3
import sys
begin = int(sys.argv[1])
end = int(sys.argv[2])
for line in sys.stdin:
print( line.strip()[begin:end])
| Python | zaydzuhri_stack_edu_python |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
function create_dudle dudlr=none request=none
begin
set dudlr = dudlr or call get_dudlr
set dudle = call Dudle name=string A doodle
set artist = dudlr
comment todo save
comment if not dudlr and request:
comment dudle.ip_address = request.
set partial_data = call Blob string
set partial_stroke_data = call Blob string
pu... | def create_dudle(dudlr=None, request=None):
dudlr = dudlr or get_dudlr()
dudle = Dudle(name="A doodle")
dudle.artist = dudlr
# todo save
#if not dudlr and request:
# dudle.ip_address = request.
dudle.partial_data = db.Blob('')
dudle.partial_stroke_data = db.Blob('')
dudle.put()
... | Python | nomic_cornstack_python_v1 |
from core import sql
from core import debug
import os
import re
from config import ConfigReader
function get_projects
begin
string Return a list of (id, name) of projects
set data = call list_projects
set names = list comprehension tuple d at string id d at string name for d in data
return names
end function
function g... | from core import sql
from core import debug
import os
import re
from config import ConfigReader
def get_projects():
"""
Return a list of (id, name) of projects
"""
data = sql.list_projects()
names = [(d['id'], d['name']) for d in data]
return names
def get_groups(id_project):
"""
Re... | Python | zaydzuhri_stack_edu_python |
string name = input("What's your name? ") color = input("What's your favorite color? ") print(name + " likes "+color) year = input("What's your birth year? ") age = 2021 - int(year) print("You are "+ str(age)+ "'s old.") name = input("Eneter your name: ") si = len(name) if 3> si: print("Name must be at least 3 chracter... | '''
name = input("What's your name? ")
color = input("What's your favorite color? ")
print(name + " likes "+color)
year = input("What's your birth year? ")
age = 2021 - int(year)
print("You are "+ str(age)+ "'s old.")
name = input("Eneter your name: ")
si = len(name)
if 3> si:
print("Name must be at least 3 chr... | Python | zaydzuhri_stack_edu_python |
function forward self obj_fmaps obj_logits rel_inds vr obj_labels=none boxes_per_cls=none
begin
if mode == string predcls
begin
set obj_dists2 = call Variable call to_onehot data num_obj_cls
end
else
begin
set obj_dists2 = obj_logits
end
if mode == string sgdet and not training
begin
set probs = softmax obj_dists2 1
se... | def forward(self, obj_fmaps, obj_logits, rel_inds, vr, obj_labels=None, boxes_per_cls=None):
if self.mode == 'predcls':
obj_dists2 = Variable(to_onehot(obj_labels.data, self.num_obj_cls))
else:
obj_dists2 = obj_logits
if self.mode == 'sgdet' and not self.training:
... | Python | nomic_cornstack_python_v1 |
comment 8/19/2020
comment Passing a list to a function
function books_available books
begin
string Show a list of books available to buy
for book in books
begin
set books_in_stock = string The following title is available to buy: + title book + string .
print books_in_stock
end
end function | ### 8/19/2020
### Passing a list to a function
def books_available(books):
""" Show a list of books available to buy"""
for book in books:
books_in_stock = "The following title is available to buy: " + book.title() + "."
print(books_in_stock)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8-*-
import pam
set p = call pam
set userName = input string Nom usuari:
set userPasswd = input string Passwd:
call authenticate userName userPasswd
print format string {} {} code reason
if code == 0
begin
for i in range 1 11
begin
print i
end
end
else
begin
print string... | #!/usr/bin/python
#-*- coding: utf-8-*-
import pam
p=pam.pam()
userName=input("Nom usuari: ")
userPasswd=input("Passwd: ")
p.authenticate(userName, userPasswd)
print('{} {}'.format(p.code,p.reason))
if p.code == 0:
for i in range(1,11):
print(i)
else:
print("Error autenticacio")
| Python | zaydzuhri_stack_edu_python |
import xlrd as xl
from sklearn.cluster import KMeans
import numpy as np
import csv
function readData fname num_nodes
begin
set file = call open_workbook fname
set sheet = call sheet_by_index 0
set cols = list
end function | import xlrd as xl
from sklearn.cluster import KMeans
import numpy as np
import csv
def readData(fname, num_nodes):
file = xl.open_workbook(fname)
sheet = file.sheet_by_index(0)
cols = [] | Python | zaydzuhri_stack_edu_python |
function factorial n
begin
if n == 0
begin
return 1
end
else
begin
return n * call factorial n - 1
end
end function | def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1) | Python | jtatman_500k |
function block_eval node table=call Memory
begin
for statement in statements
begin
set table = call statement_eval statement table
end
return table
end function | def block_eval(node, table=Memory()):
for statement in node.statements:
table = statement_eval(statement, table)
return table | Python | nomic_cornstack_python_v1 |
function cells_overlapped self aabb2d
begin
set tuple cell_w cell_h = _cell_size
set tuple offset_x offset_y = _pos
comment Translate the bounding box's coordinates to the grid's coordinate for indexing.
set tuple x1 y1 = tuple x - offset_x y - offset_y
set tuple x2 y2 = tuple x1 + width y1 + height
comment Get index b... | def cells_overlapped(self, aabb2d) -> Generator[Tuple[int, int], None, None]:
cell_w, cell_h = self._cell_size
offset_x, offset_y = self._pos
# Translate the bounding box's coordinates to the grid's coordinate for indexing.
x1, y1 = aabb2d.x - offset_x, aabb2d.y - offset_y
x2, y... | Python | nomic_cornstack_python_v1 |
function variables g width
begin
set nv = call number_of_nodes
comment p = range(1, nv * nv + 1)
comment nvar = nv * nv + 1
comment p = np.reshape(p, (nv, nv))
set nvar = 1
set p = list comprehension list comprehension 0 for u in range nv for v in range nv
for u in range nv
begin
for v in range nv
begin
if u != v
begin... | def variables(g,width):
nv = g.number_of_nodes()
# p = range(1, nv * nv + 1)
# nvar = nv * nv + 1
# p = np.reshape(p, (nv, nv))
nvar = 1
p = [[0 for u in range(nv)] for v in range(nv)]
for u in range(nv):
for v in range(nv):
if u != v:
p[u][v] = nvar
... | Python | nomic_cornstack_python_v1 |
string We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted orde... | """
We are given a list schedule of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order... | Python | zaydzuhri_stack_edu_python |
function mprotect self lpAddress dwSize flNewProtect
begin
string Set memory protection in the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx} @type lpAddress: int @param lpAddress: Address of memory to protect. @type dwSize: int @param dwSize: Number of bytes to protect. @t... | def mprotect(self, lpAddress, dwSize, flNewProtect):
"""
Set memory protection in the address space of the process.
@see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx}
@type lpAddress: int
@param lpAddress: Address of memory to protect.
@type dwSize: int
... | Python | jtatman_500k |
function make_percolation_dataset side=8 threshold=0.42 n_examples=10
begin
set X_data = as type random list n_examples side side 1 > threshold float
set Y_data = zeros list n_examples 1
for i in range 0 n_examples
begin
if call percolate X_data at tuple i slice : : slice : : 0
begin
set Y_data at tuple i 0 = 1
e... | def make_percolation_dataset(side=8, threshold=0.42, n_examples=10):
X_data = (np.random.random([n_examples, side, side, 1]) > threshold).astype(float)
Y_data = np.zeros([n_examples, 1])
for i in range(0, n_examples):
if percolate(X_data[i, :, :, 0]):
Y_data[i, 0] = 1
dataset = [{'im... | Python | nomic_cornstack_python_v1 |
function both_with_vc_vcp request
begin
set p = call PlatformWrapper
if param at 1 == string local
begin
call start_wrapper_platform p with_http=true add_local_vc_address=true
end
else
begin
call start_wrapper_platform p with_http=true
end
if param at 0 == string vcp-first
begin
set vcp_uuid = call add_volttron_central... | def both_with_vc_vcp(request):
p = PlatformWrapper()
if request.param[1] == 'local':
start_wrapper_platform(p, with_http=True, add_local_vc_address=True)
else:
start_wrapper_platform(p, with_http=True)
if request.param[0] == 'vcp-first':
vcp_uuid = add_volttron_central_platform... | Python | nomic_cornstack_python_v1 |
function length sequence **kwargs
begin
if not sequence
begin
return 0
end
if is instance sequence str or is instance sequence list
begin
if is instance sequence str
begin
set parsed_sequence = parse sequence keyword kwargs
end
else
begin
set parsed_sequence = sequence
end
set num_term_groups = 0
if call is_term_mod pa... | def length(sequence, **kwargs):
if not sequence:
return 0
if isinstance(sequence, str) or isinstance(sequence, list):
if isinstance(sequence, str):
parsed_sequence = parse(sequence, **kwargs)
else:
parsed_sequence = sequence
num_term_groups = 0
if... | Python | nomic_cornstack_python_v1 |
import logging
function foo s
begin
return 10 / integer s
end function
function bar s
begin
return call foo s * 2
end function
function main
begin
try
begin
bar 0
end
except Exception as e
begin
print string Error: %s % e
exception e
end
finally
begin
print string finally...
end
end function
call main
comment 抛出错误
comm... | import logging
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
try:
bar(0)
except Exception as e:
print('Error: %s' % e)
logging.exception(e)
finally:
print('finally...')
main()
# 抛出错误
# class FooError(ValueError):
# pass
# def foo1(s):
# n = int(s)
# if n... | Python | zaydzuhri_stack_edu_python |
function _make_action self a
begin
comment #modify
comment example: set a velocity for each joint
for tuple i_oh i_a in zip oh_joint a
begin
call obj_set_velocity i_oh i_a
end
end function
comment TODO: Change this to force control instead of velocity,
comment also test and figure out what the right action space range ... | def _make_action(self, a):
# #modify
# example: set a velocity for each joint
for i_oh, i_a in zip(self.oh_joint, a):
self.obj_set_velocity(i_oh, i_a)
#TODO: Change this to force control instead of velocity,
# also test and figure out what the right action space range is
#self.obj_set_force(i_oh, i_... | Python | nomic_cornstack_python_v1 |
function test_create_acl_user_rule_invalid_cidr_failure shared_zone_test_context
begin
set client = ok_vinyldns_client
set acl_rule = dict string accessLevel string Read ; string description string test-acl-user-id ; string userId string 789 ; string recordMask string 10.0.0/50 ; string recordTypes list string PTR
set ... | def test_create_acl_user_rule_invalid_cidr_failure(shared_zone_test_context):
client = shared_zone_test_context.ok_vinyldns_client
acl_rule = {
"accessLevel": "Read",
"description": "test-acl-user-id",
"userId": "789",
"recordMask": "10.0.0/50",
"recordTypes": ["PTR"]
... | Python | nomic_cornstack_python_v1 |
function remote_start_drive self password
begin
set url = string /command/remote_start_drive
set data = dict string password password
set method = METHOD_POST
return call _call method url data
end function | def remote_start_drive(self, password: str) -> dict:
url = '/command/remote_start_drive'
data = {
'password': password
}
method = METHOD_POST
return self._call(method, url, data) | Python | nomic_cornstack_python_v1 |
function __init__ self metadata
begin
if type metadata is not dict
begin
raise call ValueError format string metadata must be type dict, received {} type metadata
end
call __init__
set metadata = metadata
end function | def __init__(self, metadata: Dict):
if type(metadata) is not dict:
raise ValueError('metadata must be type dict, received {}'.format(type(metadata)))
super().__init__()
self.metadata = metadata | Python | nomic_cornstack_python_v1 |
function format_number number padding
begin
set formated_number = string
for count in range integer padding - length string number
begin
set formated_number = formated_number + string 0
end
return formated_number + string number
end function | def format_number(number,padding):
formated_number = ''
for count in range(int(padding) - len(str(number))):
formated_number += '0'
return formated_number + str(number) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import matplotlib.pyplot as plt
from prep_terrain_data import makeTerrainData
from class_vis import prettyPicture
from sklearn.metrics import accuracy_score
from time import time
set tuple features_train labels_train features_test labels_test = call makeTerrainData
comment the training data (fe... | #!/usr/bin/python
import matplotlib.pyplot as plt
from prep_terrain_data import makeTerrainData
from class_vis import prettyPicture
from sklearn.metrics import accuracy_score
from time import time
features_train, labels_train, features_test, labels_test = makeTerrainData()
### the training data (features_train, labe... | Python | zaydzuhri_stack_edu_python |
comment %load q05_number_of_commanders/build.py
import pandas as pd
import numpy as np
import seaborn as sns
call set_style string white
import sys , os
append path join path directory name path curdir
from greyatomlib.game_of_thrones.q01_feature_engineering.build import q01_feature_engineering
import matplotlib
call u... | # %load q05_number_of_commanders/build.py
import pandas as pd
import numpy as np
import seaborn as sns
sns.set_style('white')
import sys,os
sys.path.append(os.path.join(os.path.dirname(os.curdir)))
from greyatomlib.game_of_thrones.q01_feature_engineering.build import q01_feature_engineering
import matplotlib
matplotlib... | Python | zaydzuhri_stack_edu_python |
string Quick test script to test the song similarity method using the DTW algorithm
comment Test if saving the onset curve worked
from song import Song
import matplotlib.pyplot as plt
import numpy as np
import sys
from essentia import *
from essentia.standard import FrameGenerator
set s1 = call Song string ../music/FIL... | '''
Quick test script to test the song similarity method using the DTW algorithm
'''
# Test if saving the onset curve worked
from song import Song
import matplotlib.pyplot as plt
import numpy as np
import sys
from essentia import *
from essentia.standard import FrameGenerator
s1 = Song('../music/FILL IN')
s1.open()
... | Python | zaydzuhri_stack_edu_python |
function publisher self
begin
return get pulumi self string publisher
end function | def publisher(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "publisher") | Python | nomic_cornstack_python_v1 |
for o in range 1 201
begin
print o
end | for o in range(1,201):
print(o) | Python | zaydzuhri_stack_edu_python |
string Python 3 defines 63 built-in exceptions, and all of them form a tree-shaped hierarchy ArithmeticError Location: BaseException ← Exception ← ArithmeticError AssertionError Location: BaseException ← Exception ← AssertionError BaseException Location: BaseException IndexError Location: BaseException ← Exception ← Lo... | """
Python 3 defines 63 built-in exceptions, and all of them form a tree-shaped hierarchy
ArithmeticError
Location: BaseException ← Exception ← ArithmeticError
AssertionError
Location: BaseException ← Exception ← AssertionError
BaseException
Location: BaseException
IndexError
Location: BaseException ← Exception ← L... | Python | zaydzuhri_stack_edu_python |
import pytest
from main import increment , divide , NonIntegerException
decorator xfail reason=string not an integer!
function test_increment
begin
assert call increment string 0 == 1
end function
decorator xfail raises=NonIntegerException
function test_increment_xfail
begin
assert call increment string 0 == 1
end func... | import pytest
from main import increment, divide, NonIntegerException
@pytest.mark.xfail(reason="not an integer!")
def test_increment():
assert increment('0') == 1
@pytest.mark.xfail(raises=NonIntegerException)
def test_increment_xfail():
assert increment('0') == 1
def test_increment_raises():
with py... | Python | zaydzuhri_stack_edu_python |
function warning text
begin
return call __apply__ text __warning__
end function | def warning(text):
return Style.__apply__(text, Style.__warning__) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[ ]:
import numpy as np
import pandas as pd
import plotly as plt
import plotly.offline as po
import cufflinks as cf
comment In[ ]:
call init_notebook_mode connected=string True
call go_offline
comment In[ ]:
function dataframe_func var
begin
if data == 1
begi... | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import numpy as np
import pandas as pd
import plotly as plt
import plotly.offline as po
import cufflinks as cf
# In[ ]:
po.init_notebook_mode(connected='True')
cf.go_offline()
# In[ ]:
def dataframe_func(var):
if data == 1:
df = pd.DataFrame(np.rando... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function combinationSum4 self nums target
begin
sort nums
set dp = list 0 * target + 1
set dp at 0 = 1
for i in range 1 target + 1
begin
for num in nums
begin
if num > i
begin
break
end
else
begin
set dp at i = dp at i + dp at i - num
end
end
end
comment dp[n] = dp[n-1] + dp[n-2] + ... + dp[1] + dp... | class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
nums.sort()
dp = [0] * (target+1)
dp[0] = 1
for i in range(1, target+1):
for num in nums:
if num > i: break
else:
dp[i] += dp[i-num]
... | Python | zaydzuhri_stack_edu_python |
function get_locations db_path
begin
set locations : List at Location = list
set conn : Connection = call connect join path db_path string company_data.db
set cur : Cursor = call cursor
for row in execute cur string SELECT name, area, climate FROM locations
begin
append locations call Location row at 0 row at 1 call C... | def get_locations(db_path: str) -> List[Location]:
locations: List[Location] = []
conn: Connection = sqlite3.connect(path.join(db_path, 'company_data.db'))
cur: Cursor = conn.cursor()
for row in cur.execute('SELECT name, area, climate FROM locations'):
locations.append(Location(row[0], row[1], C... | Python | nomic_cornstack_python_v1 |
function _atan2_re_re lhs rhs
begin
set x = x
set y = x
set den = x ^ 2 + y ^ 2
if den == 0.0
begin
set dz_dx = 0.0
set dz_dy = 0.0
end
else
begin
set dz_dx = - y / den
set dz_dy = x / den
end
return call UncertainReal call atan2 y x call merge_weighted_vectors _u_components dz_dy _u_components dz_dx call merge_weighte... | def _atan2_re_re(lhs,rhs):
x = rhs.x
y = lhs.x
den = (x**2 + y**2)
if den == 0.0:
dz_dx = dz_dy = 0.0
else:
dz_dx = -y/den
dz_dy = x/den
return UncertainReal(
math.atan2(y,x)
, vector.merge_weighted_vectors(lhs._u_components,dz_dy,rhs._... | Python | nomic_cornstack_python_v1 |
function new_temporal_user_receiver sender instance created *args **kwargs
begin
if created
begin
call disconnect new_temporal_user_receiver sender=sender
set full_name = first_name + string + last_name
set qr_code_string = first_name + string _ + last_name + string random integer 1 10 + string random integer 1 10 + j... | def new_temporal_user_receiver(sender, instance, created, *args, **kwargs):
if created:
post_save.disconnect(new_temporal_user_receiver, sender=sender)
instance.full_name = instance.first_name + ' ' + instance.last_name
instance.qr_code_string = (instance.first_name
... | Python | nomic_cornstack_python_v1 |
comment 1부터 n까지의 합을 구하는 프로그램
function sum_a a
begin
set b = 0
for i in range 1 a + 1
begin
set b = b + i
end
return b
end function
comment 예제 실습
comment 1부터 10까지의 합 55이 나오면 성공
print call sum_a 10
comment 1부터 100까지의 합 5050이 나오면 성공
print call sum_a 100 | ## 1부터 n까지의 합을 구하는 프로그램
def sum_a(a):
b = 0
for i in range(1,a+1):
b+=i
return b
# 예제 실습
print(sum_a(10)) # 1부터 10까지의 합 55이 나오면 성공
print(sum_a(100)) # 1부터 100까지의 합 5050이 나오면 성공
| Python | zaydzuhri_stack_edu_python |
for i in range 0 length scores
begin
if scores at i > scores at highest
begin
set highest = i
end
end | for i in range(0, len(scores)):
if scores[i] > scores[highest]:
highest = i
| Python | zaydzuhri_stack_edu_python |
string Defna a função prodnlista que recebe como argumento uma lista de inteiros e devolve o produto dos seus elementos
function prodnlista list
begin
if length list == 0
begin
return 1
end
else
begin
return list at length list - 1 * call prodnlista list at slice : - 1 :
end
end function
print call prodnlista list 2 3... | """
Defna a função prodnlista que recebe como argumento uma lista de inteiros e
devolve o produto dos seus elementos
"""
def prodnlista(list):
if len(list) == 0:
return 1
else:
return list[len(list) - 1] * prodnlista(list[:-1])
print(prodnlista([2,3,4]))
print(prodnlista([2,3]))
| Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
function _get_mean_rock self mag _rake rrup is_reverse imt
begin
string Calculate and return the mean intensity for rock sites. Implements an equation from table 2.
if mag <= NEAR_FIELD_SATURATION_MAG
begin
set C = COEFFS_ROCK_LOWMAG at imt
end
else
begin
set C = COEFFS_ROCK_HIMAG at imt
end
comment clip mag if greater... | def _get_mean_rock(self, mag, _rake, rrup, is_reverse, imt):
"""
Calculate and return the mean intensity for rock sites.
Implements an equation from table 2.
"""
if mag <= self.NEAR_FIELD_SATURATION_MAG:
C = self.COEFFS_ROCK_LOWMAG[imt]
else:
C = ... | Python | jtatman_500k |
function fn_Calc_PulseWidth_RadarEq P_Tx G_Tx G_Rx rho_Rx rho_Tx wavelength RCS snr T0 radar_loss
begin
set k_B = boltzmann_constant
set numerator = 4 * pi ^ 3 * rho_Rx ^ 2 * rho_Tx ^ 2 * snr * k_B * T0 * radar_loss
set denominator = P_Tx * G_Tx * G_Rx * RCS * wavelength ^ 2
set pulse_width = numerator / denominator
re... | def fn_Calc_PulseWidth_RadarEq(P_Tx, G_Tx, G_Rx, rho_Rx, rho_Tx, wavelength, RCS, snr, T0, radar_loss):
k_B = RC.boltzmann_constant;
numerator = (4*math.pi)**3 * (rho_Rx**2)*(rho_Tx**2)*snr* k_B*T0*radar_loss;
denominator = P_Tx*G_Tx*G_Rx*RCS*(wavelength**2);
pulse_width = numerator/denominator;
... | Python | nomic_cornstack_python_v1 |
class ExtendedStack extends list
begin
comment операция сложения
function sum self
begin
set first = pop self
set second = pop self
set res = first + second
append self res
return self
end function
comment операция вычитания
function sub self
begin
set first = pop self
set second = pop self
set res = first - second
app... | class ExtendedStack(list):
def sum(self): # операция сложения
first = self.pop()
second = self.pop()
res = first + second
self.append(res)
return self
def sub(self): # операция вычитания
first = self.pop()
second = self.pop()
res = first - secon... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from __future__ import division
import math
set p = integer input string digite o valor de p:
set r = integer input string digite o valor de r: | # -*- coding: utf-8 -*-
from __future__ import division
import math
p=int(input('digite o valor de p:'))
r=int(input('digite o valor de r:')) | Python | zaydzuhri_stack_edu_python |
function load_cfg_file cfg_file keys separator=string =
begin
if cfg_file is none
begin
raise call ValueError string Missing configuration file argument
end
set config = dict
comment seek start of file
seek cfg_file 0 SEEK_SET
set count = 0
for line in cfg_file
begin
set line = strip line
set count = count + 1
comment... | def load_cfg_file(cfg_file, keys, separator='='):
if cfg_file is None:
raise ValueError('Missing configuration file argument')
config = {}
cfg_file.seek(0, SEEK_SET) # seek start of file
count = 0
for line in cfg_file:
line = line.strip()
count += 1
# skip blank or... | Python | nomic_cornstack_python_v1 |
function multi_escalar vector num
begin
set fila = length vector
set col = length vector at 0
for i in range fila
begin
for j in range col
begin
set vector at i at j = call producto_complejos vector at i at j num
end
end
return vector
end function | def multi_escalar(vector:list,num:list) :
fila = len(vector)
col = len(vector[0])
for i in range(fila):
for j in range(col):
vector[i][j] = producto_complejos(vector[i][j],num)
return vector | Python | nomic_cornstack_python_v1 |
function replace_entities entities pattern
begin
string Replaces all entity names in a given pattern with the corresponding values provided by entities. Args: entities (dict): A dictionary mapping entity names to entity values. pattern (str): A path pattern that contains entity names denoted by curly braces. Optional p... | def replace_entities(entities, pattern):
"""
Replaces all entity names in a given pattern with the corresponding
values provided by entities.
Args:
entities (dict): A dictionary mapping entity names to entity values.
pattern (str): A path pattern that contains entity names denoted
... | Python | jtatman_500k |
function getReactant self *args
begin
return call Reaction_getReactant self *args
end function | def getReactant(self, *args):
return _libsbml.Reaction_getReactant(self, *args) | Python | nomic_cornstack_python_v1 |
function test_get_all_strategic_action_updates test_client_with_token
begin
set updates = call create_batch 5
set num_updates = count objects
set client = test_client_with_token
set url = reverse string strategic-action-update-list
set response = get client url
assert status_code == 200
assert length data == num_update... | def test_get_all_strategic_action_updates(
test_client_with_token,
):
updates = StrategicActionUpdateFactory.create_batch(5)
num_updates = StrategicActionUpdate.objects.count()
client = test_client_with_token
url = reverse("strategic-action-update-list")
response = client.get(url)
assert res... | Python | nomic_cornstack_python_v1 |
function run self
begin
set t1 = time
set heatmap = run OUTPUT_TENSOR_NAME
set t2 = time
set total = t2 - t1 * 1000
set heatmap = heatmap at tuple 0 slice : : slice : : slice : :
comment print(feature[0].max())
comment print(feature[0].min())
return tuple heatmap total
end function | def run(self):
t1 = time.time()
heatmap = self.sess.run(
self.OUTPUT_TENSOR_NAME,
)
t2 = time.time()
total = (t2 - t1) * 1000
heatmap = heatmap[0, :, :, :]
# print(feature[0].max())
# print(feature[0].min())
return heatmap, total | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import ssl
from urllib.request import urlopen
import re , os , colorama , json , ssl
string COLORAMA MODULE
call init
set GREEN = GREEN
set GRAY = LIGHTBLACK_EX
set RESET = RESET
set YELLOW = YELLOW
set BLUE = BLUE
set RED = RED
string 'URL SSL
set base_url = string https://www.math.kit.ed... | from bs4 import BeautifulSoup
import ssl
from urllib.request import urlopen
import re, os, colorama, json, ssl
''' COLORAMA MODULE '''
colorama.init()
GREEN = colorama.Fore.GREEN
GRAY = colorama.Fore.LIGHTBLACK_EX
RESET = colorama.Fore.RESET
YELLOW = colorama.Fore.YELLOW
BLUE = colorama.Fore.BLUE
RED = colorama.Fore.R... | Python | zaydzuhri_stack_edu_python |
class Restaurant
begin
set number_served = 0
function __init__ self name type
begin
set name = name
set type = type
end function
function describe_Restaurant self name type
begin
print string 저희 레스토랑 명칭은 %s 이고 %s 전문점입니다. % tuple name type
end function
function open_Restaurant self name
begin
print string 저희 %s 레스토랑이 열렸... | class Restaurant:
number_served = 0
def __init__(self,name,type):
self.name = name
self.type = type
def describe_Restaurant(self, name, type):
print("저희 레스토랑 명칭은 %s 이고 %s 전문점입니다." % (self.name,self.type))
def open_Restaurant(self, name):
print("저희 %s 레스토랑이 열렸습니다." % (self... | Python | zaydzuhri_stack_edu_python |
import streamlit as st
import numpy as np
import pandas as pd
import pickle
import xgboost
import matplotlib.pyplot as plt
set equip_dict = dict string 10003540 0 ; string P-1000-N002 2 ; string P-1000-N006 5 ; string P-3000-N006 7 ; string P-ZCBM-N002 9
set model = load pickle open string xgb_model.pkl string rb
set d... | import streamlit as st
import numpy as np
import pandas as pd
import pickle
import xgboost
import matplotlib.pyplot as plt
equip_dict = {'10003540':0,
'P-1000-N002':2,
'P-1000-N006':5,
'P-3000-N006':7,
'P-ZCBM-N002':9}
model = pickle.load(open('xgb_model.... | Python | zaydzuhri_stack_edu_python |
function _read_returned_msg self method_frame
begin
string Support method to read a returned (basic.return) Message from the current frame buffer. Will return a Message with return_info, or re-queue current frames and raise a FrameUnderflow. :returns: Message with the return_info attribute set, where return_info is a d... | def _read_returned_msg(self, method_frame):
'''
Support method to read a returned (basic.return) Message from the
current frame buffer. Will return a Message with return_info, or
re-queue current frames and raise a FrameUnderflow.
:returns: Message with the return_info attribute... | Python | jtatman_500k |
class Mapping
begin
function __init__ self iterable
begin
set items_list = list
comment __update 메소드를 사용하고 있다
call __update iterable
end function
function update self iterable
begin
for item in iterable
begin
append items_list item
end
end function
comment private copy of original update() method
set __update = update... | class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable) # __update 메소드를 사용하고 있다
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update #private copy of original update() method
... | Python | zaydzuhri_stack_edu_python |
function load_config config_file_name use_environ=true
begin
with open config_file_name as input_file
begin
set config_dict = load yaml input_file Loader
end
comment allow settings to be supplied or overridden with environment variables
if use_environ
begin
set prefix = string RHIZO_
for tuple name value in items envir... | def load_config(config_file_name, use_environ=True):
with open(config_file_name) as input_file:
config_dict = yaml.load(input_file, yaml.Loader)
# allow settings to be supplied or overridden with environment variables
if use_environ:
prefix = 'RHIZO_'
for (name, value) in os.environ... | Python | nomic_cornstack_python_v1 |
function pipeline_configuration_body self
begin
return get pulumi self string pipeline_configuration_body
end function | def pipeline_configuration_body(self) -> Optional[str]:
return pulumi.get(self, "pipeline_configuration_body") | Python | nomic_cornstack_python_v1 |
function update_scenario_section self
begin
set rconfig = call RawConfigParser
read rconfig conf_file
set filename = get attribute CONF string { case_name } _image filename
if not call has_section string scenario
begin
call add_section string scenario
end
set string scenario string img_file filename
set string scenario... | def update_scenario_section(self):
rconfig = configparser.RawConfigParser()
rconfig.read(self.conf_file)
filename = getattr(
config.CONF, f'{self.case_name}_image', self.filename)
if not rconfig.has_section('scenario'):
rconfig.add_section('scenario')
rcon... | Python | nomic_cornstack_python_v1 |
import sys
import math
import requests
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication , QWidget , QPushButton , QLabel , QLineEdit , QRadioButton , QButtonGroup
from PyQt5.QtCore import Qt
set SCREEN_SIZE = list 800 450
class Example extends QWidget
begin
function __init__ self
begin
call __in... | import sys
import math
import requests
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QLineEdit, QRadioButton, QButtonGroup
from PyQt5.QtCore import Qt
SCREEN_SIZE = [800, 450]
class Example(QWidget):
def __init__(self):
super().__init__()
... | Python | zaydzuhri_stack_edu_python |
comment Alexa Armitage
comment NSID: ama043
comment Student ID: 11158883
comment CMPT 317 Assignment 1 Question 1
class MathProblemState
begin
function __init__ self equation goal numbers path_cost=1
begin
string Represents the equation state for a simple math problem Keyword Arguments: equation -- The equation for the... | #Alexa Armitage
#NSID: ama043
#Student ID: 11158883
#CMPT 317 Assignment 1 Question 1
class MathProblemState:
def __init__(self, equation, goal, numbers, path_cost=1):
"""Represents the equation state for a simple math problem
Keyword Arguments:
equation -- The equation for the current sta... | Python | zaydzuhri_stack_edu_python |
for i in matrix
begin
append minlist min i
end
print max minlist | for i in matrix:
minlist.append(min(i))
print(max(minlist))
| Python | zaydzuhri_stack_edu_python |
set tuple a b = map int split input string
set c = input
print c at slice : b - 1 : + lower c at slice b - 1 : b : + c at slice b : : | a, b = map(int, input().split(' '))
c = input()
print(c[:b-1]+c[b-1:b].lower()+c[b:]) | Python | jtatman_500k |
function __get_occurence_counter self
begin
comment We want to count the number of occurences of each token, then
set occurence_counter = counter
comment filter the tokens down.
for sentence in _tokenized_doc
begin
update occurence_counter sentence
end
set UNK_counter = counter
comment Filtering for maximum vocab size:... | def __get_occurence_counter(self):
occurence_counter = Counter() # We want to count the number of occurences of each token, then
# filter the tokens down.
for sentence in self._tokenized_doc:
occurence_counter.update(sentence)
UNK_counter = Counter()
# Filtering for... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should... | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that perso... | Python | zaydzuhri_stack_edu_python |
comment Importamos SocketServer para el socket del servidor, pymongo para el cliente
comment de mongoDB, Nominatim para obtener las coordenadas de nuestro RPI y time para
comment obtener informacion de la hora y fecha en la que se envia al servidor la informacion.
import SocketServer
import base64
from geopy.geocoders ... | #Importamos SocketServer para el socket del servidor, pymongo para el cliente
#de mongoDB, Nominatim para obtener las coordenadas de nuestro RPI y time para
#obtener informacion de la hora y fecha en la que se envia al servidor la informacion.
import SocketServer
import base64
from geopy.geocoders import Nominatim
imp... | Python | zaydzuhri_stack_edu_python |
import socket
set ip_port = tuple string 127.0.0.1 8888
set sk = call socket
set data = call connect ip_port
comment sk.settimeout(5)
while true
begin
set data = call recv 1024
print string receive: decode data string utf8
set inp = input string please input:
print string ---- + inp
if not length inp
begin
set inp = in... | import socket
ip_port = ('127.0.0.1', 8888)
sk = socket.socket()
data = sk.connect(ip_port)
#sk.settimeout(5)
while True:
data = sk.recv(1024)
print('receive:', data.decode('utf8'))
inp = input('please input:')
print('----'+inp)
if not len(inp):
inp = input('re-input:')
print('----... | Python | zaydzuhri_stack_edu_python |
if operator == string +
begin
print a string + b string =: a + b
end
else
if operator == string -
begin
print a string - b string =: a - b
end
else
if operator == string *
begin
print a string * b string =: a * b
end
else
if operator == string /
begin
print a string / b string = a / b
end
else
begin
print string 无效的运算符... | if operator=="+":
print(a,'+',b,'=:',a+b)
elif operator == "-":
print(a,'-',b,'=:',a-b)
elif operator == "*":
print(a,'*',b,'=:',a*b)
elif operator == "/":
print(a,'/',b,'=',a/b)
else:
print('无效的运算符') | Python | zaydzuhri_stack_edu_python |
string practise for pandas
import pandas as pd
from pandas import Series
set PATH = string ../data/athlete_events.csv
class Assignment1
begin
string The dataset has the following features: ID - Unique number for each athlete Name - Athlete's name Sex - M or F Age - Integer Height - In centimeters Weight - In kilograms ... | """
practise for pandas
"""
import pandas as pd
from pandas import Series
PATH = '../data/athlete_events.csv'
class Assignment1:
"""
The dataset has the following features:
ID - Unique number for each athlete
Name - Athlete's name
Sex - M or F
Age - Integer
Height ... | Python | zaydzuhri_stack_edu_python |
function transform self data
begin
set data = call _common_preprocess data
set data = loc at tuple slice : : include_cols
set X = drop data string ckd axis=1
set y = data at string ckd
return tuple X y
end function | def transform(self, data):
data = self._common_preprocess(data)
data = data.loc[:, self.include_cols]
X = data.drop('ckd', axis = 1)
y = data['ckd']
return X, y | Python | nomic_cornstack_python_v1 |
comment Problem:
comment Given a case of Dummy game, return the time that the game is over.
comment My Solution:
from collections import deque
set size = integer input
set n_apple = integer input
set pos_apple = list
for _ in range n_apple
begin
append pos_apple list map int split input
end
set n_dir = integer input
s... | # Problem:
# Given a case of Dummy game, return the time that the game is over.
# My Solution:
from collections import deque
size = int(input())
n_apple = int(input())
pos_apple=[]
for _ in range(n_apple):
pos_apple.append(list(map(int, input().split())))
n_dir = int(input())
dir_li = []
for i in range(n_dir):
... | Python | zaydzuhri_stack_edu_python |
function _update_and_verify_sub_config cfg allowed_cfg dataset_name
begin
for tuple k v in items allowed_cfg
begin
if is instance v dict and dataset_name in keys v
begin
set v = v at dataset_name
end
if k not in cfg
begin
set cfg at k = v at 0
print string Warning: dataset. { k } not set. Using default value { v at 0 }... | def _update_and_verify_sub_config(cfg, allowed_cfg, dataset_name):
for k, v in allowed_cfg.items():
if isinstance(v, dict) and dataset_name in v.keys():
v = v[dataset_name]
if k not in cfg:
cfg[k] = v[0]
print(f"Warning: dataset.{k} not set. Using default value ... | Python | nomic_cornstack_python_v1 |
function iterIdentifiers self
begin
return iterate sources
end function | def iterIdentifiers(self):
return iter(self.dd.sources) | Python | nomic_cornstack_python_v1 |
function testC_CondorTest self
begin
set nRunning = call getCondorRunningJobs user
assert equal nRunning 0 string User currently has %i running jobs. Test will not continue % nRunning
comment Get the config and set the removal time to -10 for testing
set config = call getConfig
set removeTime = - 10.0
append pluginName... | def testC_CondorTest(self):
nRunning = getCondorRunningJobs(self.user)
self.assertEqual(nRunning, 0, "User currently has %i running jobs. Test will not continue" % (nRunning))
# Get the config and set the removal time to -10 for testing
config = self.getConfig()
config.BossAir... | Python | nomic_cornstack_python_v1 |
string Represents Bullets in the game world
import pygame
from constants import *
set ENEMY = 0
set PLAYER = 1
class BossBullet extends Sprite
begin
function __init__ self screen x_pos y_pos x_speed y_speed blocks bullet_type=ENEMY
begin
call __init__
set screen = screen
set screen_width = call get_width
set screen_hei... | """ Represents Bullets in the game world """
import pygame
from constants import *
ENEMY = 0
PLAYER = 1
class BossBullet(pygame.sprite.Sprite):
def __init__(self, screen, x_pos, y_pos, x_speed, y_speed, blocks, bullet_type=ENEMY):
super().__init__()
self.screen = screen
self.screen_width =... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function rotate self matrix
begin
string Do not return anything, modify matrix in-place instead.
set tuple l r = tuple 0 length matrix - 1
set max_runs = length matrix - 2
if max_runs == 0
begin
set max_runs = max_runs + 1
end
for j in range max_runs
begin
for i in range r - l
begin
set top = l
set... | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
l,r = 0, len(matrix) -1
max_runs = len(matrix) -2
if max_runs == 0:
max_runs+= 1
for j in range(max_runs):
... | 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.