code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function WriteField self sensor_idx discrete_time
begin
assert is instance discrete_time int and discrete_time >= 0
assert length shape == 2 and shape at 1 == 2
set xind = as type sensor_idx at tuple slice : : 0 int
set yind = as type sensor_idx at tuple slice : : 1 int
comment For the purpose of performance anal... | def WriteField(self, sensor_idx, discrete_time):
assert isinstance(discrete_time, int) and discrete_time >= 0
assert len(sensor_idx.shape) == 2 and sensor_idx.shape[1] == 2
xind = sensor_idx[:, 0].astype(int)
yind = sensor_idx[:, 1].astype(int)
# For the purpose of performance a... | Python | nomic_cornstack_python_v1 |
function fit self X y
begin
set tuple X y = call _validate_data X y=y y_numeric=true
comment populated in predict methods
set stats_ = dict
if length X >= n_analogs
begin
set k_ = n_analogs
end
else
begin
warn string length of X is less than n_analogs, setting n_analogs = len(X)
set k_ = length X
end
set kdtree_kwargs... | def fit(self, X, y):
X, y = self._validate_data(X, y=y, y_numeric=True)
self.stats_ = {} # populated in predict methods
if len(X) >= self.n_analogs:
self.k_ = self.n_analogs
else:
warnings.warn('length of X is less than n_analogs, setting n_analogs = len(X)')
... | Python | nomic_cornstack_python_v1 |
function get_block_comment_delta line
begin
set in_pragma = 0
set block_comment_delta_pos = 0
set block_comment_delta_neg = 0
for match in call finditer line
begin
comment Double dash
if not in_pragma and not block_comment_delta_pos - block_comment_delta_neg and call group 1
begin
return tuple block_comment_delta_pos b... | def get_block_comment_delta(line):
in_pragma = 0
block_comment_delta_pos = 0
block_comment_delta_neg = 0
for match in agda_comment_regex.finditer(line):
# Double dash
if not in_pragma and\
not block_comment_delta_pos - block_comment_delta_neg\
and match.group... | Python | nomic_cornstack_python_v1 |
function getDepotInfoList args
begin
call dout DEBUG string getDepotInfoList: called with %s % args
set depot_info_list = list
for depot_id in keys _depot_map
begin
try
begin
set depot_info = dictionary call query_depot depot_id
end
except KeyError
begin
call dout WARNING string pahook.getDepotInfoList: could not quer... | def getDepotInfoList(args):
_utils.dout(logging.DEBUG, 'getDepotInfoList: called with %s' % args)
depot_info_list = []
for depot_id in _service._depot_map.keys():
try:
depot_info = dict(_service.query_depot(depot_id))
except KeyError:
_service.utils.dout(loggin... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from Library import ConfigReader
function startBrowser
begin
global driver
if call readconfigData string Details string Browser == string Chrome
begin
set path = string ./Driver/chromedriver.exe
set driver = call Chrome executable_path=path
end
else
if call readconfigData string Details s... | from selenium import webdriver
from Library import ConfigReader
def startBrowser():
global driver
if(ConfigReader.readconfigData('Details','Browser')=="Chrome"):
path = "./Driver/chromedriver.exe"
driver = webdriver.Chrome(executable_path=path)
elif(ConfigReader.readconfigData('Details','Br... | Python | zaydzuhri_stack_edu_python |
comment Problem ID: 2679
comment Submit Time: 2012-08-30 18:02:14
comment Run Time: 920
comment Run Memory: 320
comment ZOJ User: calvinxiao
import sys
function getline
begin
return read line stdin
end function
function getint
begin
return integer read line stdin
end function
function getlist
begin
return split strip r... | #Problem ID: 2679
#Submit Time: 2012-08-30 18:02:14
#Run Time: 920
#Run Memory: 320
#ZOJ User: calvinxiao
import sys
def getline():
return sys.stdin.readline()
def getint():
return int(sys.stdin.readline())
def getlist():
return sys.stdin.readline().strip().split()
def isprime(n):
sn = pow(n, 0.5)
... | Python | zaydzuhri_stack_edu_python |
function colorThreshFunc self
begin
function result category value
begin
return call colorThreshFor category value
end function
return result
end function | def colorThreshFunc(self):
def result(category, value):
return self.colorThreshFor(category, value)
return result | Python | nomic_cornstack_python_v1 |
class animals
begin
set food = string plant
set growth = true
set reproduction = true
set noise = string wow
function wow self
begin
print noise
end function
end class
class artiodactyls extends animals
begin
set hoof = true
end class
class birds extends animals
begin
set wing = true
end class
class cows extends artiod... | class animals:
food='plant'
growth=True
reproduction=True
noise="wow"
def wow(self):
print(self.noise)
class artiodactyls(animals):
hoof=True
class birds(animals):
wing=True
class cows(artiodactyls):
give_milk=True
class goats(artiodactyls):
give_milk=True
class sheep(artiodactyls):
give_me... | Python | zaydzuhri_stack_edu_python |
import re
from abc import ABCMeta , abstractmethod
import sys , time
from trie import PyTrie
from nltk.corpus import words , names
set INPUTFILE_YAHOO = string plaintxt_yahoo.txt
set INPUTFILE_CSDN = string www.csdn.net.sql
set SEPERATOR_YAHOO = b':'
set SEPERATOR_CSDN = b' # '
set ECHO = 1000
function inc dict key
beg... | import re
from abc import ABCMeta, abstractmethod
import sys, time
from trie import PyTrie
from nltk.corpus import words, names
INPUTFILE_YAHOO = "plaintxt_yahoo.txt"
INPUTFILE_CSDN = "www.csdn.net.sql"
SEPERATOR_YAHOO = b":"
SEPERATOR_CSDN = b" # "
ECHO = 1000
def inc(dict, key):
dict.setdefault(key, 0)
di... | Python | zaydzuhri_stack_edu_python |
function milani x observations prop_params l=zeros tuple 6 6 dr=0.1 dv=0.005 max_iter=15
begin
set n = length x
set delta = array list dr dr dr dv dv dv
comment Must break the stopping criteria
set delta_x = ones n
set i = 0
while not call stopping_criteria delta_x and i < max_iter
begin
set c = zeros tuple n n
set d =... | def milani(x: np.ndarray, observations: List[Observation], prop_params: PropParams,
l=np.zeros((6, 6)), dr=.1, dv=.005, max_iter=15) -> Tuple[np.ndarray, np.ndarray]:
n = len(x)
delta = np. array([dr, dr, dr, dv, dv, dv])
delta_x = np.ones(n) # Must break the stopping criteria
i = 0
wh... | Python | nomic_cornstack_python_v1 |
function focal_loss predictions labels gamma=2 alpha=1.0 weights=1.0 epsilon=1e-07 scope=none
begin
with call name_scope scope string focal_loss tuple predictions labels weights as scope
begin
set predictions = call to_float predictions
set labels = call to_float labels
call assert_is_compatible_with call get_shape
set... | def focal_loss(predictions, labels, gamma=2, alpha=1.0, weights=1.0,
epsilon=1e-7, scope=None):
with ops.name_scope(scope, "focal_loss",
(predictions, labels, weights)) as scope:
predictions = math_ops.to_float(predictions)
labels = math_ops.to_float(labels)
prediction... | Python | nomic_cornstack_python_v1 |
function bubble_sort arr
begin
set n = length arr
for i in range n - 1
begin
for j in range 0 n - i - 1
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
return arr
end function
set arr = list 64 34 25 12 22 11 90
set sorted_arr = call bubble_sort arr
print... | def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(0, n - i - 1):
if arr[j] < arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print("Sorted array in descending order:")
... | Python | greatdarklord_python_dataset |
function CalculateWaterUsePerYear self problemManager
begin
set theUnitManager = call UnitManager
comment tonnes per year
set processingCapacityInTonne = processingCapacity * call ConvertTo string tonne
comment in kL/year assumes 2.35 kL water per tonne
set q = 2.35 * processingCapacityInTonne
comment should be 1:1 in ... | def CalculateWaterUsePerYear(self, problemManager):
theUnitManager = UnitManager()
processingCapacityInTonne = problemManager.theMineDataManager.theProcessingSystem.processingCapacity* theUnitManager.ConvertTo("tonne") # tonnes per year
q = 2.35* processingCapacityInTonne # in kL/year assumes... | Python | nomic_cornstack_python_v1 |
function toggle_article_flag self article
begin
set flag = not flag
with _sqlite_connection
begin
execute _sqlite_connection string UPDATE articles SET flag = ? WHERE identifier = ? and feed_id = ? list flag identifier feed_id
end
end function | def toggle_article_flag(self, article: Article) -> None:
article.flag = not article.flag
with self._sqlite_connection:
self._sqlite_connection.execute('''UPDATE articles SET flag = ? WHERE identifier = ? and feed_id = ?''', [article.flag, article.identifier, article.feed_id]) | Python | nomic_cornstack_python_v1 |
function prereposetup_hook conduit
begin
return call init_hook conduit
end function | def prereposetup_hook(conduit):
return init_hook(conduit) | Python | nomic_cornstack_python_v1 |
function find self vport_name=none emulation_host=none **filters
begin
return find call super IxnPimV6InterfaceEmulation self list string topology string deviceGroup string ipv4Loopback string ldpTargetedRouter string ldppwvpls string ipv6Loopback string pimV6Interface vport_name emulation_host filters
end function | def find(self, vport_name=None, emulation_host=None, **filters):
return super(IxnPimV6InterfaceEmulation, self).find(["topology","deviceGroup","ipv4Loopback","ldpTargetedRouter","ldppwvpls","ipv6Loopback","pimV6Interface"], vport_name, emulation_host, filters) | Python | nomic_cornstack_python_v1 |
function __init__ self os logs
begin
debug string INSTALLERS: Instantiating Endpoint object
comment Darwin is code for Mac
if os == string Darwin
begin
debug string INSTALLERS: Operating system: { os }
call _docker_mac logs=logs
end
else
begin
set msg = string Docker installation is not automated for this operating sys... | def __init__(self, os: str, logs: logging.Logger) -> None:
logs.debug("INSTALLERS: Instantiating Endpoint object")
if os == "Darwin": # Darwin is code for Mac
logs.debug(f"INSTALLERS: Operating system: {os}")
self._docker_mac(logs=logs)
else:
msg = f"""Dock... | Python | nomic_cornstack_python_v1 |
set n = integer call raw_input
set arr = map int split call raw_input
set t = max arr
set new = filter lambda x -> x != t arr | n = int(raw_input())
arr = map(int, raw_input().split())
t=max(arr)
new = filter(lambda x:x!=t,arr) | Python | zaydzuhri_stack_edu_python |
import random
set dinheiros = 1000
set k = true
while k
begin
set per1 = input string Você quer apostar ?
if per1 != string não
begin
set dado1 = random 1 6
set dado2 = random 1 2
set soma = dado1 + dado2
set aposta = integer input string Quanto você quer apostar?
set dinheiros = dinheiros - 30
if aposta == soma
begin
... | import random
dinheiros = 1000
k = True
while k:
per1 = input("Você quer apostar ?")
if per1 != "não":
dado1 = random(1,6)
dado2 = random(1,2)
soma = dado1 + dado2
aposta = int(input("Quanto você quer apostar? "))
dinheiros -= 30
if aposta == soma:
din... | Python | zaydzuhri_stack_edu_python |
comment ! -*- coding:utf-8 -*-
import sys
import time
import gevent
from gevent import monkey
import urllib2
import threading
import multiprocessing
set urls = list string http://www.baidu.com string http://www.github.com string http://www.python.org string http://www.qq.com/ string http://www.163.com/ * 4
function get... | #! -*- coding:utf-8 -*-
import sys
import time
import gevent
from gevent import monkey
import urllib2
import threading
import multiprocessing
urls = ['http://www.baidu.com', 'http://www.github.com', 'http://www.python.org',
'http://www.qq.com/', 'http://www.163.com/'] * 4
def get_data(url):
print('Start... | Python | zaydzuhri_stack_edu_python |
comment main.py
comment Januari 18
comment Geodetic Engineers of Utrecht
comment Loading the modules
import os
import os , os.path
import mapnik
comment os.chdir('/home/user/git/TwoLocations') | # main.py
# Januari 18
# Geodetic Engineers of Utrecht
## Loading the modules
import os
import os,os.path
import mapnik
#os.chdir('/home/user/git/TwoLocations') | Python | zaydzuhri_stack_edu_python |
string 문제1) goods 테이블을 이용하여 다음과 같은 형식으로 출력하시오. <조건1> 전자레인지 수량, 단가 수정 <조건2> HDTV 수량 수정 [ goods 테이블 현황 ] 1 냉장고 2 850000 2 세탁기 3 550000 3 전자레인지 5 600000 <- 수량, 단가 수정 4 HDTV 2 1500000 <- 수량 수정 전체 레코드 수 : 4
import sqlite3
try
begin
set conn = call connect string ./chap09_Database/data/sqlite.db
set cursor = call cursor
stri... | '''
문제1) goods 테이블을 이용하여 다음과 같은 형식으로 출력하시오.
<조건1> 전자레인지 수량, 단가 수정
<조건2> HDTV 수량 수정
[ goods 테이블 현황 ]
1 냉장고 2 850000
2 세탁기 3 550000
3 전자레인지 5 600000 <- 수량, 단가 수정
4 HDTV 2 1500000 <- 수량 수정
전체 레코드 수 : 4
'''
import sqlite3
try :
conn = sqlite3.connect("./chap09_Database/data/sqlite.db")
... | Python | zaydzuhri_stack_edu_python |
function is_done self
begin
set _times_called_is_done = _times_called_is_done + 1
return done
end function | def is_done(self):
self._times_called_is_done += 1
return self.done | Python | nomic_cornstack_python_v1 |
function connect client
begin
call confirmConnection
call enableApiControl true
call armDisarm true
end function | def connect(client):
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True) | Python | nomic_cornstack_python_v1 |
function _compute_section_attrs self
begin
set underlying_dx = decimal _underlying_dim1_coords at 1 - _underlying_dim1_coords at 0
set _trace_idx = call column_stack tuple _dim1_idx _dim2_idx
set _trace = call column_stack tuple _underlying_dim2_coords at _dim2_idx + underlying_dx / 2 _underlying_dim1_coords at _dim1_i... | def _compute_section_attrs(self):
underlying_dx = float(
self._underlying_dim1_coords[1] - self._underlying_dim1_coords[0]
)
self._trace_idx = np.column_stack((self._dim1_idx, self._dim2_idx))
self._trace = np.column_stack(
(
self._underlying_dim2_... | Python | nomic_cornstack_python_v1 |
function __gt__ self other
begin
if date > date
begin
return true
end
else
begin
return false
end
end function | def __gt__(self, other):
if self.date > other.date:
return True
else:
return False | Python | nomic_cornstack_python_v1 |
import json
function lookup_user UUID
begin
set data = none
with open string ./data.json string rb as datafile
begin
set data = load json datafile at string data
end
try
begin
set target = filter lambda datum -> datum at string UUID == UUID data at 0
return target at string User
end
except tuple KeyError ValueError Ind... | import json
def lookup_user(UUID):
data = None
with open('./data.json', 'rb') as datafile:
data = json.load(datafile)['data']
try:
target = filter(lambda datum: datum['UUID'] == UUID, data)[0]
return target["User"]
except (KeyError, ValueError, IndexError):
return None
if __name__ == '__main__':
UUID1 ... | Python | zaydzuhri_stack_edu_python |
string
function int_as_array num
begin
return list map int list comprehension y for y in string num
end function
function array_as_int arr
begin
return integer join string map str arr
end function
function read_int
begin
return integer input
end function
function read_array
begin
return list map int split input strin... | """
"""
def int_as_array(num): return list(map(int, [y for y in str(num)]))
def array_as_int(arr): return int(''.join(map(str, arr)))
def read_int(): return int(input())
def read_array(): return list(map(int, input().split(' ')))
def array_to_string(arr, sep=' '): return sep.join(map(str, arr))
def matrix_t... | Python | zaydzuhri_stack_edu_python |
function create_image self data=none **kwargs
begin
if string name not in kwargs
begin
set name = call rand_name __name__ + string -image
set kwargs at string name = name
end
set params = dictionary kwargs
if data
begin
comment NOTE: On glance v1 API, the data should be passed on
comment a header. Then here handles the... | def create_image(self, data=None, **kwargs):
if 'name' not in kwargs:
name = data_utils.rand_name(self.__name__ + "-image")
kwargs['name'] = name
params = dict(kwargs)
if data:
# NOTE: On glance v1 API, the data should be passed on
# a header. Th... | Python | nomic_cornstack_python_v1 |
function generate_traj P N start=none stop=none dt=1
begin
set sampler = call MarkovChainSampler P dt=dt
return call trajectory N start=start stop=stop
end function | def generate_traj(P, N, start=None, stop=None, dt=1):
sampler = MarkovChainSampler(P, dt=dt)
return sampler.trajectory(N, start=start, stop=stop) | Python | nomic_cornstack_python_v1 |
function get_fu_no_adv self uj
begin
set fu = zeros like uj
comment loop over internal cells
for j in intern
begin
comment no advection
set fu at j = uj at j
end
return fu
end function | def get_fu_no_adv(self, uj):
fu = np.zeros_like(uj)
for j in self.intern: # loop over internal cells
fu[j] = uj[j] # no advection
return fu | Python | nomic_cornstack_python_v1 |
function validate_file self file_path
begin
with open file_path string r as file
begin
set count = 0
set len_of_sequence = - 1
for line in file
begin
set line = strip line
if line == string
begin
return tuple false string Empty line at line: + string count + 1
end
set line_kind = count % 4
set tuple valid_line msg = c... | def validate_file(self, file_path):
with open(file_path, "r") as file:
count = 0
len_of_sequence = -1
for line in file:
line = line.strip()
if line == "":
return False, "Empty line at line: " + str(count+1)
... | Python | nomic_cornstack_python_v1 |
function add_or_remove_a_connection self number_of_times
begin
set task = list string a string b
for action in range number_of_times
begin
set pick = random choice task
if pick == string a
begin
call add_connection_auto
end
else
if pick == string b
begin
call close_a_random_connection
end
end
end function | def add_or_remove_a_connection(self, number_of_times):
task = ["a", "b"]
for action in range(number_of_times):
pick = random.choice(task)
if pick == "a":
self.add_connection_auto()
elif pick == "b":
self.close_a_random_connection... | Python | nomic_cornstack_python_v1 |
function receive self data
begin
raise NotImplementedError
end function | def receive(self, data):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function no_match
begin
set S1 = call Spectrum
call add_peak 50.7 234
call add_peak 54.6 585
call add_peak 60.7 773
call add_peak 65.6 387
call add_peak 87.7 546
call add_peak 104.6 598
set pep_mass = 100
call euclidean_scale
set S2 = call Spectrum
call add_peak 50.2 234
call add_peak 53.8 585
call add_peak 61.3 773
ca... | def no_match():
S1=Spectrum.Spectrum()
S1.add_peak(50.7,234)
S1.add_peak(54.6,585)
S1.add_peak(60.7,773)
S1.add_peak(65.6,387)
S1.add_peak(87.7,546)
S1.add_peak(104.6,598)
S1.pep_mass=100
S1.euclidean_scale()
S2=Spectrum.Spectrum()
S2.add_peak(50.2,234)
S2.add_peak(53.8,... | Python | nomic_cornstack_python_v1 |
function plusMinus arr
begin
set pos = 0
set neg = 0
set zero = 0
set n = length arr
for i in arr
begin
if i > 0
begin
set pos = pos + 1
end
else
if i < 0
begin
set neg = neg + 1
end
else
begin
set zero = zero + 1
end
end
print round pos / n 6
print round neg / n 6
print round zero / n 6
end function | def plusMinus(arr):
pos = 0
neg = 0
zero = 0
n = len(arr)
for i in arr:
if i >0:
pos += 1
elif i <0:
neg += 1
else:
zero += 1
print(round(pos/n,6))
print(round(neg/n,6))
print(round(zero/n,6)) | Python | zaydzuhri_stack_edu_python |
function decode_withdraw_nonce_account instruction
begin
return call cast WithdrawNonceAccountParams call _decode_withdraw_nonce_account instruction
end function | def decode_withdraw_nonce_account(
instruction: Instruction,
) -> WithdrawNonceAccountParams:
return cast(WithdrawNonceAccountParams, _decode_withdraw_nonce_account(instruction)) | Python | nomic_cornstack_python_v1 |
function requested_size_gib self
begin
return get pulumi self string requested_size_gib
end function | def requested_size_gib(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "requested_size_gib") | Python | nomic_cornstack_python_v1 |
function step self state action reward next_state done
begin
if not done
begin
set Q at state at action = Q at state at action + alpha * reward + gamma * max Q at next_state - Q at state at action
call policyUpdate state
end
else
begin
set Q at state at action = Q at state at action + alpha * reward - Q at state at act... | def step(self, state, action, reward, next_state , done):
if(not done):
self.Q[state][action] += self.alpha*(reward +self.gamma*(np.max(self.Q[next_state])) - \
self.Q[state][action] )
self.policyUpdate(... | Python | nomic_cornstack_python_v1 |
function find_pos_hmmer_hitsx infilepath1 infilepath2 fwdeval reveval outfilepath just_evalue
begin
comment print('\t' + os.path.basename(infilepath1))
comment print('\t' + os.path.basename(infilepath2))
comment print('\t' + str(fwdeval))
comment print('\t' + str(reveval))
comment print('\t' + os.path.basename(outfilep... | def find_pos_hmmer_hitsx(infilepath1, infilepath2, fwdeval, reveval,
outfilepath, just_evalue):
#print('\t' + os.path.basename(infilepath1))
#print('\t' + os.path.basename(infilepath2))
#print('\t' + str(fwdeval))
#print('\t' + str(reveval))
#print('\t' + os.path.basename(outfilepath))
#... | Python | nomic_cornstack_python_v1 |
function onExitCanceled self position
begin
pass
end function | def onExitCanceled(self, position):
pass | Python | nomic_cornstack_python_v1 |
function hamming_distance p q
begin
set mismatches = 0
set p_bases = deque p
set q_bases = deque q
while length p_bases > 0 and length q_bases > 0
begin
if call popleft != call popleft
begin
set mismatches = mismatches + 1
end
end
return mismatches
end function | def hamming_distance(p, q):
mismatches = 0
p_bases = deque(p)
q_bases = deque(q)
while len(p_bases) > 0 and len(q_bases) > 0:
if p_bases.popleft() != q_bases.popleft():
mismatches += 1
return mismatches | Python | nomic_cornstack_python_v1 |
import time
from selenium import webdriver
set link = string http://suninjuly.github.io/registration2.html
try
begin
set browser = call Chrome
get browser link
comment Находим элементы для проверки
set first_inp = call find_element_by_css_selector string input.first[required]
set second_inp = call find_element_by_css_s... | import time
from selenium import webdriver
link = "http://suninjuly.github.io/registration2.html"
try:
browser = webdriver.Chrome()
browser.get(link)
# Находим элементы для проверки
first_inp = browser.find_element_by_css_selector('input.first[required]')
second_inp = browser.find_element_by_css_selector('input.s... | Python | zaydzuhri_stack_edu_python |
function is_palindrome phrase
begin
set phrase = lower phrase
set phrase = replace phrase string string
set i = 0
set j = length phrase - 1
while i < j
begin
if phrase at i != phrase at j
begin
return false
end
set i = i + 1
set j = j - 1
end
return true
end function | def is_palindrome(phrase):
phrase = phrase.lower()
phrase = phrase.replace(" ","")
i = 0
j = len(phrase) - 1
while i < j:
if phrase[i] != phrase [j]:
return False
i+=1
j-=1
return True | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import json
import os
import sys
import pymworks
import tables
import numpy
try
begin
import mworks.data
set MWORKS_AVAILABLE = true
end
except ImportError
begin
set MWORKS_AVAILABLE = false
end
class MworksFile extends object
begin
function __init__ self filename
begin
if not MWORKS_AVAILA... | #!/usr/bin/env python
import json
import os
import sys
import pymworks
import tables
import numpy
try:
import mworks.data
MWORKS_AVAILABLE = True
except ImportError:
MWORKS_AVAILABLE = False
class MworksFile(object):
def __init__(self, filename):
if not MWORKS_AVAILABLE:
raise ... | Python | zaydzuhri_stack_edu_python |
comment 어떤 식당의 메뉴판을 보여주는 함수를 만드세요.
comment 스크립트에서 이 함수를 반복 호출 합니다.
comment 메뉴번호를 입력 받아 해당 메뉴의 가격을 합산하되
comment 메뉴선택 종료를 의미하는 5값을 입력 받을 때까지 계속 반복하여 메뉴를 선택하게 하고,
comment 선택종료 후 선택한 메뉴의 총 합계금액을 출력하세요.
comment 앞서 만든 문제 1에 추가로 함수를 더 구현해 사용합니다.
comment 단, 사용할 메뉴는 다음과 같습니다.
comment 1. 피자(15,000원), 2. 스파게티(10,000원), 3. 샐러드(7,0... | # 어떤 식당의 메뉴판을 보여주는 함수를 만드세요.
# 스크립트에서 이 함수를 반복 호출 합니다.
# 메뉴번호를 입력 받아 해당 메뉴의 가격을 합산하되
# 메뉴선택 종료를 의미하는 5값을 입력 받을 때까지 계속 반복하여 메뉴를 선택하게 하고,
# 선택종료 후 선택한 메뉴의 총 합계금액을 출력하세요.
# 앞서 만든 문제 1에 추가로 함수를 더 구현해 사용합니다.
# 단, 사용할 메뉴는 다음과 같습니다.
# 1. 피자(15,000원), 2. 스파게티(10,000원), 3. 샐러드(7,000원), 4. 음료수(2,000원), 5. 종료
def SelectMenu():
... | Python | zaydzuhri_stack_edu_python |
function sigmoid x x0=0.5 k=10.0 L=1.0
begin
return L / 1.0 + exp - k * x - x0
end function | def sigmoid(x, x0=0.5, k=10.0, L=1.0):
return L / (1.0 + np.exp(-k * (x - x0))) | Python | nomic_cornstack_python_v1 |
comment printing [1, 2, 3]
set A = list range 0 5
print A
print string Reading from left: A at slice 1 : 4 :
print string Reading from right: A at slice - 4 : - 1 : | ##printing [1, 2, 3]
A = list( range(0, 5) )
print(A)
print("Reading from left: ", A[1:4] )
print("Reading from right: ", A[-4:-1] ) | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function myPow self x n
begin
set fu = false
if n < 0
begin
set fu = true
set n = - n
end
set k = 1
set db = dict 1 x
while k < n
begin
set c = k * 2
set db at c = db at k * db at k
set k = c
end
set res = 1
set serach = binary n
set ind = 1
for i in range - 1 - length serach + 1 - 1
begin
if serac... | class Solution:
def myPow(self, x, n):
fu=False
if n <0:
fu=True
n=-n
k=1
db={1:x}
while k<n:
c=k*2
db[c]=db[k]*db[k]
k=c
res=1
serach=bin(n)
ind=1
for i in range(-1,-len(serach)+1,-1... | Python | zaydzuhri_stack_edu_python |
function extract_metadata file
begin
set config_text : str
set content_text : str
set config : List at str = list
set content : List at str = list
set reading_config : bool = false
set tuple start_block end_block = tuple string <!-- string -->
with open fullpath string r as fp
begin
for line in read lines fp
begin
if... | def extract_metadata(file: MarkdownFile) -> MarkdownFile:
config_text: str
content_text: str
config: List[str] = []
content: List[str] = []
reading_config: bool = False
start_block, end_block = "<!--", "-->\n"
with open(file.fullpath, "r") as fp:
for line in fp.readlines():
... | Python | nomic_cornstack_python_v1 |
from Utils.RingBuffer import RingBuffer
class SCIPort extends object
begin
function __init__ self rx_buf_size tx_buf_size
begin
set rxb = call RingBuffer rx_buf_size
set txb = call RingBuffer tx_buf_size
end function
function write_rx self buffer offset count
begin
return write rxb buffer offset count
end function
func... | from ..Utils.RingBuffer import RingBuffer
class SCIPort(object):
def __init__(self, rx_buf_size, tx_buf_size):
self.rxb = RingBuffer(rx_buf_size)
self.txb = RingBuffer(tx_buf_size)
def write_rx(self, buffer, offset, count):
return self.rxb.write(buffer, offset, count)
def write_t... | Python | zaydzuhri_stack_edu_python |
function _lock_ self
begin
call _setNewFieldLock_ true
end function | def _lock_(self):
self._setNewFieldLock_(True) | Python | nomic_cornstack_python_v1 |
function __is_output_used self node
begin
set render_template = call __get_render_template node is_proxy=false
set proxy_render_template = call __get_render_template node is_proxy=true
for template in list render_template proxy_render_template
begin
if not template
begin
continue
end
comment check for output key and al... | def __is_output_used(self, node):
render_template = self.__get_render_template(node, is_proxy=False)
proxy_render_template = self.__get_render_template(node, is_proxy=True)
for template in [render_template, proxy_render_template]:
if not template:
continue
... | Python | nomic_cornstack_python_v1 |
function take_snapshot_for instance
begin
set flv = flv_file
set tuple path ext = call splitext name
set upload_to = string format time time upload_to
set image_name = join path upload_to base name path path + string .jpg
set inp = join path VIDEOS_TEMP_DIR name
set outp = join path VIDEOS_TEMP_DIR image_name
try
begin... | def take_snapshot_for(instance):
flv = instance.flv_file
path, ext = os.path.splitext(flv.name)
upload_to = time.strftime(instance.splash_image.field.upload_to)
image_name = os.path.join(upload_to, os.path.basename(path) + '.jpg')
inp = os.path.join(settings.VIDEOS_TEMP_DIR, flv.name)
outp ... | Python | nomic_cornstack_python_v1 |
function reverse_string s
begin
set start = 0
set end = length s - 1
comment Convert the string to a list of characters for swapping
set s = list s
comment Swap characters until start is no longer less than end
while start < end
begin
set tuple s at start s at end = tuple s at end s at start
set start = start + 1
set e... | def reverse_string(s):
start = 0
end = len(s) - 1
# Convert the string to a list of characters for swapping
s = list(s)
# Swap characters until start is no longer less than end
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
#... | Python | jtatman_500k |
function prepare_firewall self device_ids
begin
info call _ string Prepare firewall rules %s. length device_ids
set dev_list = list device_ids
if length dev_list > 10
begin
set sublists = list comprehension dev_list at slice x : x + 10 : for x in range 0 length dev_list 10
end
else
begin
set sublists = list dev_list
e... | def prepare_firewall(self, device_ids):
LOG.info(_("Prepare firewall rules %s."), len(device_ids))
dev_list = list(device_ids)
if len(dev_list) > 10:
sublists = [dev_list[x:x + 10] for x in range(0, len(dev_list),
10)]
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Mar 28 21:42:00 2019 @author: Manoj
import numpy as np
import cv2
import time
from scipy import ndimage
function recordFrames
begin
set cap = call VideoCapture string harry2.mp4
sleep 3
set background = 0
for i in range 300
begin
set tuple ret background = read cap
se... | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 21:42:00 2019
@author: Manoj
"""
import numpy as np
import cv2
import time
from scipy import ndimage
def recordFrames():
cap = cv2.VideoCapture("harry2.mp4")
time.sleep(3)
background=0
for i in range(300):
ret,background = cap.read()... | Python | zaydzuhri_stack_edu_python |
function test_delete_idea self
begin
pass
end function | def test_delete_idea(self):
pass | Python | nomic_cornstack_python_v1 |
class bank
begin
function __init__ self acnt name types
begin
set ac = acnt
set nm = name
set typ = types
set bal = 0
end function
function prntdtls self
begin
print string Account Holder Name: nm
print string Account Number: ac
print string Account Type: typ
end function
function deposit self d1
begin
set bal = bal + ... | class bank():
def __init__(self, acnt, name, types):
self.ac = acnt
self.nm = name
self.typ = types
self.bal = 0
def prntdtls(self):
print("Account Holder Name:", self.nm)
print("Account Number:", self.ac)
print("Account Type:", self.typ)
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Thu Oct 24 10:06:11 2019 @author: Chuanzhen Hu
import sys
import struct
import scipy as sp
import scipy.linalg as splin
import numpy as np
import scipy.sparse as sparse
from scipy.sparse.linalg import splu
import scipy.optimize as optimize
comment In[] define function for... | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 10:06:11 2019
@author: Chuanzhen Hu
"""
import sys
import struct
import scipy as sp
import scipy.linalg as splin
import numpy as np
import scipy.sparse as sparse
from scipy.sparse.linalg import splu
import scipy.optimize as optimize
# In[] define function... | Python | zaydzuhri_stack_edu_python |
for x in pelanggan
begin
print x
print pelanggan at x
end
set daftar_pelanggan = list
append daftar_pelanggan pelanggan
append daftar_pelanggan pelanggan_2
for pelanggan in daftar_pelanggan
begin
print format string Nama: {} pelanggan at string nama
print format string Umur: {} pelanggan at string umur
end | for x in pelanggan:
print(x)
print(pelanggan[x])
daftar_pelanggan = []
daftar_pelanggan.append(pelanggan)
daftar_pelanggan.append(pelanggan_2)
for pelanggan in daftar_pelanggan:
print("Nama: {}".format(pelanggan["nama"]))
print("Umur: {}".format(pelanggan["umur"])) | Python | zaydzuhri_stack_edu_python |
function findRoute self x1 y1 x2 y2
begin
comment Check to see if the start and end node are the same
if x1 == x2 and y1 == y2
begin
return list tuple x1 y1
end
set root_node = call DijkstraNode x1 y1 none 0
set neighbours = call getNeighbours x1 y1
comment Create a dictionary to store all of the nodes
set all_nodes = ... | def findRoute(self, x1, y1, x2, y2):
# Check to see if the start and end node are the same
if x1 == x2 and y1 == y2:
return [(x1, y1)]
root_node = DijkstraNode(x1, y1, None, 0)
root_node.neighbours = self.getNeighbours(x1, y1)
# Create a dictionary to store all of the nodes
all_nodes = {(x1,... | Python | nomic_cornstack_python_v1 |
import numpy as np
comment name: Ngo Duy Khanh Vy
comment x is a list [x_1, x_2]
comment return gradient vector
function derivative_function x
begin
set der = list 0 0
comment TODO: compute gradient of the following function: (1−x_1)^2+100(x_2−x_1^2)^2
set der at 0 = - 2 * 1 - x at 0 + 100 * 2 * x at 1 - x at 0 ^ 2 * -... | import numpy as np
# name: Ngo Duy Khanh Vy
## x is a list [x_1, x_2]
## return gradient vector
def derivative_function(x):
der = [0, 0]
# TODO: compute gradient of the following function: (1−x_1)^2+100(x_2−x_1^2)^2
der[0] = -2 * (1 -x[0]) + 100 * 2 * (x[1] -(x[0] ** 2)) * -2 * x[0]
der[1] = 2 * 100 * (... | Python | zaydzuhri_stack_edu_python |
function unique_id self
begin
return entry_id
end function | def unique_id(self):
return self.config_entry.entry_id | Python | nomic_cornstack_python_v1 |
function getConfiguration self
begin
comment TODO: Split metadata (e.g. name and version) from configuration data.
comment Currently, we do this by selectively copying from __dict__. A
comment cleaner separation would require refactoring all the way through how
comment we create update objects.
set config = dict
for k... | def getConfiguration(self):
# TODO: Split metadata (e.g. name and version) from configuration data.
# Currently, we do this by selectively copying from __dict__. A
# cleaner separation would require refactoring all the way through how
# we create update objects.
config = {}
... | Python | nomic_cornstack_python_v1 |
function _order_params self data
begin
string Convert params to list with signature as last element :param data: :return:
set has_signature = false
set params = list
for tuple key value in items data
begin
if key == string signature
begin
set has_signature = true
end
else
begin
append params tuple key value
end
end
co... | def _order_params(self, data):
"""Convert params to list with signature as last element
:param data:
:return:
"""
has_signature = False
params = []
for key, value in data.items():
if key == 'signature':
has_signature = True
... | Python | jtatman_500k |
function on_epoch_end self epoch logs=none
begin
info string For epoch { epoch } , training loss / accuracy is { format string {:7.2f} logs at string loss } / { format string {:7.2f} logs at string acc }
info string For epoch { epoch } , validation loss / accuracy is { format string {:7.2f} logs at string val_loss } / ... | def on_epoch_end(self, epoch, logs=None):
logging.info(f"For epoch {epoch}, training loss / accuracy is {'{:7.2f}'.format(logs['loss'])} / {'{:7.2f}'.format(logs['acc'])} ")
logging.info(f"For epoch {epoch}, validation loss / accuracy is {'{:7.2f}'.format(logs['val_loss'])} / {'{:7.2f}'.format(logs['val... | Python | nomic_cornstack_python_v1 |
function ksonnet self
begin
return get pulumi self string ksonnet
end function | def ksonnet(self) -> Optional[pulumi.Input['ApplicationOperationSyncSourceKsonnetArgs']]:
return pulumi.get(self, "ksonnet") | Python | nomic_cornstack_python_v1 |
import os
import pandas as pd
import nltk
from nltk.stem import PorterStemmer
import gensim
from gensim.corpora import MmCorpus , Dictionary
from gensim.test.utils import get_tmpfile
import pickle
comment NLTK Stop words
from nltk.corpus import stopwords
set DATA_DIR = string ../Data
set TWEETS_PATH = join path DATA_DI... | import os
import pandas as pd
import nltk
from nltk.stem import PorterStemmer
import gensim
from gensim.corpora import MmCorpus, Dictionary
from gensim.test.utils import get_tmpfile
import pickle
# NLTK Stop words
from nltk.corpus import stopwords
DATA_DIR = "../Data"
TWEETS_PATH = os.path.join(DATA_DIR, 'tweets')
T... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Fri Apr 6 17:36:41 2018 @author: yujia
import numpy as np
import ot
import matplotlib.pyplot as plt
import matplotlib
call rc string xtick labelsize=20
import ipot
set batchsize = 100
comment data#############
comment n bins
set n = batchsize... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 17:36:41 2018
@author: yujia
"""
import numpy as np
import ot
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc('xtick', labelsize=20)
import ipot
batchsize = 100
###########data#############
n = batchsize # n bins
# bin... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import os
function crearlista archivo_entrada
begin
comment Dirección para guardar el archivo de salida, que sería en la carpeta del perfil de usuario
set archivo_salida = environ at string USERPROFILE + string \Documents\people.out
try
begin
comment Abrir, leer y cerrar el archivo de entrada
set f ... | import pandas as pd
import os
def crearlista(archivo_entrada):
#Dirección para guardar el archivo de salida, que sería en la carpeta del perfil de usuario
archivo_salida = os.environ['USERPROFILE'] + "\\Documents\\people.out"
try:
#Abrir, leer y cerrar el archivo de entrada
f = open(arch... | Python | zaydzuhri_stack_edu_python |
function have_fastReturnFileEntries self
begin
return true
end function | def have_fastReturnFileEntries(self):
return True | Python | nomic_cornstack_python_v1 |
function all self exclude=list
begin
comment get a list of all of the network devices available now.
set interfaces = list directory string /sys/class/net
comment Remove the loopback interface and any other specified interfaces
for x in exclude + list string lo
begin
if x in interfaces
begin
remove interfaces x
end
end... | def all(self, exclude=[]):
# get a list of all of the network devices available now.
interfaces = os.listdir('/sys/class/net')
# Remove the loopback interface and any other specified interfaces
for x in exclude+['lo']:
if x in interfaces:
interfaces.remove(x)
... | Python | nomic_cornstack_python_v1 |
function lookback_day user df date_pivot month
begin
set df at string loan_past_day_diff = as type apply call to_datetime df at string loan_time lambda x -> date_pivot - x string timedelta64[D]
for back in list 7 21 45 57
begin
set lookback = reset index sum
if shape at 0 == 0
begin
continue
end
set mdf = merge user at... | def lookback_day(user , df, date_pivot, month):
df['loan_past_day_diff'] = pd.to_datetime(df['loan_time']).apply(lambda x : date_pivot - x ).astype('timedelta64[D]')
for back in [7,21,45,57]:
lookback = df[df['loan_past_day_diff'] <= back][['uid','loan_amount']].groupby('uid').sum().reset_index()
... | Python | nomic_cornstack_python_v1 |
function recompute self
begin
set tuple dbpath config = call _start
call msg1 string Deleting existing scores
set scorestab = call ModelScoreTable dbpath
call empty
call msg1 string Fetching model ids
set modelids = call get_model_names dbpath
set references = call get_ref_names dbpath
call msg1 string Computing model ... | def recompute(self):
dbpath, config = self._start()
self.logger.msg1("Deleting existing scores")
scorestab = ModelScoreTable(self.dbpath)
scorestab.empty()
self.logger.msg1("Fetching model ids")
modelids = get_model_names(self.db... | Python | nomic_cornstack_python_v1 |
function get_vehicle_cfg_state_name self vehcfgstateid
begin
set vehcfgid_cond = call SQLBinaryExpr COL_NAME_VEHICLECFGSTATES_VEHICLECFGSTATEID OP_EQ call SQLLiteral vehcfgstateid
set entries = call select_generic_data select_list=list COL_NAME_VEHICLECFGSTATES_NAME table_list=list TABLE_NAME_VEHICLECFGSTATES where=veh... | def get_vehicle_cfg_state_name(self, vehcfgstateid):
vehcfgid_cond = SQLBinaryExpr(COL_NAME_VEHICLECFGSTATES_VEHICLECFGSTATEID, OP_EQ, SQLLiteral(vehcfgstateid))
entries = self.select_generic_data(select_list=[COL_NAME_VEHICLECFGSTATES_NAME],
table_list=[TABLE_... | Python | nomic_cornstack_python_v1 |
function OnCaptionDoubleClicked self pane_window
begin
comment try to find the pane
set paneInfo = call GetPane pane_window
if not call IsOk
begin
raise exception string Pane window not found
end
if not call IsFloatable or not call IsDockable or _agwFlags ? AUI_MGR_ALLOW_FLOATING == 0
begin
return
end
set indx = index ... | def OnCaptionDoubleClicked(self, pane_window):
# try to find the pane
paneInfo = self.GetPane(pane_window)
if not paneInfo.IsOk():
raise Exception("Pane window not found")
if not paneInfo.IsFloatable() or not paneInfo.IsDockable() or \
self._agwFlags & AU... | Python | nomic_cornstack_python_v1 |
function domain self
begin
return call split_entity_id entity_id at 0
end function | def domain(self):
return split_entity_id(self.entity_id)[0] | Python | nomic_cornstack_python_v1 |
comment fibonacci
function fibo n
begin
if n == 0
begin
return
end
if n == 1
begin
return 1
end
set s = 0
set n1 = 0
set n2 = 1
set count = 0
while n > count
begin
print s
set s = n1 + n2
comment print(s)
set n1 = n2
set n2 = s
set count = count + 1
end
end function
call fibo 5
comment fibonacci recursivo
function fibo... | # fibonacci
def fibo(n):
if n == 0: return
if n == 1: return 1
s = 0
n1=0
n2=1
count=0
while n > count:
print(s)
s = n1+n2
#print(s)
n1=n2
n2 = s
count+=1
fibo(5)
# fibonacci recursivo
def fiboR(n):
if n<=1: return n
return (fiboR(n-... | Python | zaydzuhri_stack_edu_python |
function __init__ self params
begin
comment d = np.loadtxt('camb_m_pow_l.dat')
comment k = d[:,0]
comment P = d[:,1]
set C = call CosmoPie copy cosmology p_space=string jdem
set zs = array list 0.01 1.01
set z_fine = array range 0.0005 max zs 0.002
set poly_params = copy polygon_params
set poly_geo = call PolygonGeo zs... | def __init__(self,params):
#d = np.loadtxt('camb_m_pow_l.dat')
#k = d[:,0]
#P = d[:,1]
self.C = CosmoPie(defaults.cosmology.copy(),p_space='jdem')
self.zs = np.array([.01,1.01])
self.z_fine = np.arange(0.0005,np.max(self.zs),0.002)
self.poly_params = defaults.pol... | Python | nomic_cornstack_python_v1 |
function _serialize t
begin
return dumps t separators=tuple string , string :
end function | def _serialize(t):
return json.dumps(t, separators=(',', ':')) | Python | nomic_cornstack_python_v1 |
function normalizeSpecSet specSet
begin
for i in range shape at 0
begin
set intens : ndarray = specSet at tuple i slice : :
set intens = intens - min
if max != 0
begin
set intens = intens / max
end
set specSet at tuple i slice : : = intens
end
return specSet
end function | def normalizeSpecSet(specSet: np.ndarray) -> np.ndarray:
for i in range(specSet.shape[0]):
intens: np.ndarray = specSet[i, :]
intens -= intens.min()
if intens.max() != 0:
intens /= intens.max()
specSet[i, :] = intens
return specSet | Python | nomic_cornstack_python_v1 |
comment Function to implement Linear Search
function linear_search arr x
begin
for i in range length arr
begin
if arr at i == x
begin
return i
end
end
return - 1
end function
comment Test
set arr = list 1 2 3 4 5 6
set x = 4
comment Function call
set result = call linear_search arr x | #Function to implement Linear Search
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
#Test
arr = [1, 2, 3, 4, 5, 6]
x = 4
#Function call
result = linear_search(arr, x)
| Python | flytech_python_25k |
function get_nn_model celltype mtype metric=string r2 verbose=true filts=false cell=0 fnum=0
begin
if not filts
begin
set path = string SavedModels/%s_best_%s_%s % tuple celltype mtype metric
end
else
begin
set path = string SavedModels/filts_%s_best_%s_%s % tuple celltype mtype metric
end
if cell >= 1
begin
set path =... | def get_nn_model(celltype, mtype, metric='r2', verbose=True, filts=False, cell=0, fnum=0):
if not filts: path = 'SavedModels/%s_best_%s_%s' % (celltype, mtype, metric);
else: path = 'SavedModels/filts_%s_best_%s_%s' % (celltype, mtype, metric);
if cell >= 1: path += '_cell%s' % (str(cell));
if fnum > 0:... | Python | nomic_cornstack_python_v1 |
function __hash__ self
begin
set pair = tuple size self tuple generator expression tuple e for e in _cover_relations
return call hash pair
end function | def __hash__(self):
pair = (self.size(), tuple(tuple(e) for e in self._cover_relations))
return hash(pair) | Python | nomic_cornstack_python_v1 |
function get_json self
begin
return dumps content
end function | def get_json(self):
return json.dumps(self.content) | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
call init_node string expand_map
comment stores data coming in
set map = list
set width = none
set height = none
set resolution = none
comment stores data realte to paths
set path = list
set cost = list
set mapPose = list
comment pub to gridcells
set pubClosedX = call Publisher string /... | def __init__(self):
rospy.init_node("expand_map")
# stores data coming in
self.map = []
self.width = None
self.height = None
self.resolution = None
# stores data realte to paths
self.path = []
self.cost = []
self.mapPose = []
# pu... | Python | nomic_cornstack_python_v1 |
function cmd_REQ_E self data
begin
call update_other_mem_size data
set free_memory_size = call get_free_mem_ad
debug format string {} Got request for free memory advertisement, sending: {} nodeID free_memory_size
call send_msg CMD_ACK_E free_memory_size
end function | def cmd_REQ_E(self, data):
self.scheduler.update_other_mem_size(data)
free_memory_size = self.qmm.get_free_mem_ad()
logger.debug("{} Got request for free memory advertisement, sending: {}".format(self.node.nodeID,
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3.5
import argparse
import xml.etree.ElementTree as ET
import plantuml
function parseUML umlFile
begin
comment uml can be a sequence diagram or a state diagram
set tree = parse ET umlFile
end function
function main inputFile outputFile
begin
comment generate a figure of uml iva plantuml
comment ... | #!/usr/bin/python3.5
import argparse
import xml.etree.ElementTree as ET
import plantuml
def parseUML(umlFile):
# uml can be a sequence diagram or a state diagram
tree = ET.parse(umlFile)
def main(inputFile, outputFile):
# generate a figure of uml iva plantuml
#pl = plantuml.PlantUML()
#pl.proces... | Python | zaydzuhri_stack_edu_python |
function from_sdl_event cls sdl_event
begin
raise call NotImplementedError
end function | def from_sdl_event(cls, sdl_event: Any) -> Event:
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import sys
import threading
import time
import requests
set data = list
set thread_limit = 50
class myThread extends Thread
begin
function __init__ self url
begin
call __init__ self
set url = url
end function
function run self
begin
set val = status_code
append data string val + string : + url... | #!/usr/bin/python
import sys
import threading
import time
import requests
data = []
thread_limit = 50
class myThread (threading.Thread):
def __init__(self, url):
threading.Thread.__init__(self)
self.url = url
def run(self):
val = requests.get(self.url).status_code
data.appen... | Python | zaydzuhri_stack_edu_python |
comment 특정열을 선택하는 두가지방법
comment 첫번째 열의 인덱스값을 사용하는 방법 - 6번
comment 두번째 열의 헤더를 사용하는 방법 - 7번
import pandas as pd
import sys
set input_file = argv at 1
set output_file = argv at 2
comment my_columns = [0, 3]
set data_frame = read csv input_file
set data_frame_column_by_index = iloc at tuple slice : : list 0 3
to csv dat... | # 특정열을 선택하는 두가지방법
# 첫번째 열의 인덱스값을 사용하는 방법 - 6번
# 두번째 열의 헤더를 사용하는 방법 - 7번
import pandas as pd
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
#my_columns = [0, 3]
data_frame = pd.read_csv(input_file)
data_frame_column_by_index = data_frame.iloc[:, [0, 3]]
data_frame_column_by_index.to_csv(output_file... | Python | zaydzuhri_stack_edu_python |
string 多个装饰器 def zhuangshiqi1(hanshu): print("zhuangshi1_ing") def inner1(): print("inner1函数") hanshu return inner1 def zhuangshiqi2(hanshu): print("zhuangshi2_ing") def inner2(): print("inner2函数") hanshu return inner2 @zhuangshiqi1 @zhuangshiqi2 def aaa(): print("aaa") aaa() 注意:不要出现test,不然会有蜜汁bug
string 装饰器装饰有参函数 方法1(... | """
多个装饰器
def zhuangshiqi1(hanshu):
print("zhuangshi1_ing")
def inner1():
print("inner1函数")
hanshu
return inner1
def zhuangshiqi2(hanshu):
print("zhuangshi2_ing")
def inner2():
print("inner2函数")
hanshu
return inner2
@zhuangshiqi1
@zhuangshiqi2
def aaa():
pri... | Python | zaydzuhri_stack_edu_python |
function starts_at_or_after self value
begin
return start >= value
end function | def starts_at_or_after(self, value):
return self.start >= value | Python | nomic_cornstack_python_v1 |
function rule model j
begin
set ind_i = timeslots
if task_chunk_max at j <= 1
begin
set total = sum generator expression A2 at tuple i j + A3 at tuple i j + A4 at tuple i j for i in ind_i
return tuple none total 0
end
else
if task_chunk_max at j <= 2
begin
set total = sum generator expression A3 at tuple i j + A4 at tu... | def rule(model, j):
ind_i = model.timeslots
if self.task_chunk_max[j] <= 1:
total = sum(
model.A2[i, j] + model.A3[i, j] + model.A4[i, j] for i in
ind_i)
return None, total, 0
elif self.task_chunk_max[j] <= 2:
... | Python | nomic_cornstack_python_v1 |
function patches_by_project self project_id params=none
begin
set url = call _create_url format string /projects/{project_id}/patches project_id=project_id
set patches = call _lazy_paginate_by_date url params
return generator expression patch patch self for patch in patches
end function | def patches_by_project(self, project_id, params=None):
url = self._create_url('/projects/{project_id}/patches'.format(project_id=project_id))
patches = self._lazy_paginate_by_date(url, params)
return (Patch(patch, self) for patch in patches) | Python | nomic_cornstack_python_v1 |
function get_fixed_source_any_destination_any_port devices
begin
set tables = find all string ./report/part/[@ref='SECURITYAUDIT']/section/[@ref='FILTER.RULE.NEAA']/section[@ref='FINDING']/table
set rules = dict
for table in tables
begin
for device in devices
begin
if device in split get table string title
begin
set h... | def get_fixed_source_any_destination_any_port(devices):
tables = nipper_xml.findall("./report/part/[@ref='SECURITYAUDIT']/section/[@ref='FILTER.RULE.NEAA']/"
"section[@ref='FINDING']/table")
rules = {}
for table in tables:
for device in devices:
if devi... | Python | nomic_cornstack_python_v1 |
function read_campaign root_import_path
begin
if is file path join path root_import_path campaign_filename
begin
comment any missing **required** fields will make this false. spawns MISSING error. Fatal.
comment is_complete = True
comment any missing data will make this false. spawns a warning.
comment is_minally_ok = ... | def read_campaign(root_import_path):
if os.path.isfile(os.path.join(root_import_path, campaign_filename)):
# any missing **required** fields will make this false. spawns MISSING error. Fatal.
#is_complete = True
# any missing data will make this false. spawns a warning.
#is_minally_... | Python | nomic_cornstack_python_v1 |
string Terminal>python second2years.py Can a baby live in 1e+09 s? Yes, it would be 31.69 years | """
Terminal>python second2years.py
Can a baby live in 1e+09 s? Yes, it would be 31.69 years
"""
| Python | zaydzuhri_stack_edu_python |
function nearestSafeCell
begin
if weightedMap at y at x == 1
begin
set d_SafeZone at 0 = 0
set d_SafeZone at 1 = y
set d_SafeZone at 2 = x
end
else
if weightedMap at y - 1 at x == 1
begin
set d_SafeZone at 0 = 1
set d_SafeZone at 1 = y - 1
set d_SafeZone at 2 = x
end
else
if weightedMap at y at x - 1 == 1
begin
set d_S... | def nearestSafeCell():
if gameStatus.game.weightedMap[gameStatus.game.me.y][gameStatus.game.me.x] == 1:
gameStatus.game.d_SafeZone[0] = 0
gameStatus.game.d_SafeZone[1] = gameStatus.game.me.y
gameStatus.game.d_SafeZone[2] = gameStatus.game.me.x
else:
if gameStatus.game.weightedMap... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.