code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function display_mask i path begin set mask = argument maximum val_preds at i axis=- 1 set mask = call expand_dims mask axis=- 1 set img = call autocontrast call array_to_img mask set p = string //srvpnw/Volp5/CSB-Vision/temp/4DPI/Praktikum/Segmentation_examples/muscles_seg/ comment cv.imwrite(p + path.split("_jpg/")[1...
def display_mask(i, path): mask = np.argmax(val_preds[i], axis=-1) mask = np.expand_dims(mask, axis=-1) img = PIL.ImageOps.autocontrast(keras.preprocessing.image.array_to_img(mask)) p = "//srvpnw/Volp5/CSB-Vision/temp/4DPI/Praktikum/Segmentation_examples/muscles_seg/" #cv.imwrite(p + path.split...
Python
nomic_cornstack_python_v1
function fibonacci number begin set a = 1 set b = 1 print a print b for i in range 2 number begin set c = a + b set a = b set b = c print c end end function call fibonacci 5 comment How to use input function function smaller_num x y begin if x > y begin set number = y end else begin set number = x end return number end...
def fibonacci(number): a = 1 b = 1 print(a) print(b) for i in range(2,number): c = a + b a = b b = c print(c) fibonacci(5) #How to use input function def smaller_num(x,y): if x>y: number= y else: number= x retur...
Python
zaydzuhri_stack_edu_python
string Find the longest sequence using a starting number under one million. The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It can be seen that this...
"""Find the longest sequence using a starting number under one million. The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It...
Python
zaydzuhri_stack_edu_python
class StringIterator begin function __init__ self compressedString begin string :type compressedString: str set string = compressedString set ptr = 0 set ch = string set rem = - 1 call initialize end function function initialize self begin if ptr == length string begin set tuple ch rem = tuple string - 1 end else beg...
class StringIterator: def __init__(self, compressedString): """ :type compressedString: str """ self.string = compressedString self.ptr = 0 self.ch = ' ' self.rem = -1 self.initialize() def initialize(self): if self.ptr == len(self.string...
Python
zaydzuhri_stack_edu_python
import unittest import spotify class TestPoemSentence extends TestCase begin function setUp self begin set poem = call PoemSentence string It's #Spotify poem! end function function test_cleaned_sentence self begin set expected = string It's Spotify poem call assertEquals sentence expected end function function test_wor...
import unittest import spotify class TestPoemSentence(unittest.TestCase): def setUp(self): self.poem = spotify.PoemSentence("It's #Spotify\npoem!") def test_cleaned_sentence(self): expected = "It's Spotify poem" self.assertEquals(self.poem.sentence, expected) def test_words(self)...
Python
zaydzuhri_stack_edu_python
import argparse function add_fun begin set parser = call ArgumentParser description=string Description : This is first CLI program try begin call add_argument string add nargs=string * metavar=string num type=int help=string takes any number of input integers end except Exception as err begin print string err end set a...
import argparse def add_fun(): parser = argparse.ArgumentParser(description="Description : This is first CLI program") try: parser.add_argument("add", nargs = '*', metavar = 'num', type=int, help='takes any number of input integers') except Exception as err: print("err") args = parser.parse_args(...
Python
zaydzuhri_stack_edu_python
function test_request_details_image self amazon_api_request begin with call amazon_api_request begin set details = call request_details string B00YJJ4SNS end set valid_urls = list comprehension url for url in details at string images if string .jpg in url assert length set valid_urls == 2 end function
def test_request_details_image(self, amazon_api_request): with amazon_api_request(): details = Affiliate().request_details('B00YJJ4SNS') valid_urls = [url for url in details['images'] if '.jpg' in url] assert len(set(valid_urls)) == 2
Python
nomic_cornstack_python_v1
import csv import json import os import sys from pathlib import Path from typing import Iterable , Tuple , List from nltk.tokenize import sent_tokenize , word_tokenize from src.data.instance import DatasetSplit , Word , Document from src.utils import normalize_tokens import hashlib set EXAM2CEFR = dict string CAE strin...
import csv import json import os import sys from pathlib import Path from typing import Iterable, Tuple, List from nltk.tokenize import sent_tokenize, word_tokenize from src.data.instance import DatasetSplit, Word, Document from src.utils import normalize_tokens import hashlib EXAM2CEFR = { "CAE": "C1", "CP...
Python
zaydzuhri_stack_edu_python
function send_initialize_command_to_workers dict_worker_stubs begin for ws in values dict_worker_stubs begin call start_domset end end function
def send_initialize_command_to_workers (dict_worker_stubs): for ws in dict_worker_stubs.values (): ws.start_domset ()
Python
nomic_cornstack_python_v1
function request host path api_key url_params=dict string term string Fast Food ; string limit 50 ; string latitude 37.31954 ; string longitude - 122.045055 ; string radius 8046 begin set url = format string {0}{1} host quote encode path string utf8 set headers = dict string Authorization string Bearer %s % api_key pri...
def request(host, path, api_key, url_params= {'term': "Fast Food", 'limit': 50,'latitude':37.319540, 'longitude':-122.045055, 'radius': 8046}): url = '{0}{1}'.format(host, quote(path.encode('utf8'))) headers = { 'Authorization': 'Bearer %s' % api_key, ...
Python
nomic_cornstack_python_v1
function geli_rekey self pool slot=GELI_KEY_SLOT begin set geli_keyfile = pool at string encryptkey_path set geli_keyfile_tmp = string { geli_keyfile } .tmp set devs = list comprehension ed at string encrypted_provider for ed in call call_sync string datastore.query string storage.encrypteddisk list tuple string encryp...
def geli_rekey(self, pool, slot=GELI_KEY_SLOT): geli_keyfile = pool['encryptkey_path'] geli_keyfile_tmp = f'{geli_keyfile}.tmp' devs = [ ed['encrypted_provider'] for ed in self.middleware.call_sync( 'datastore.query', 'storage.encrypteddisk', [('encrypted...
Python
nomic_cornstack_python_v1
function ez_config auth_token filename options=none begin set status_code = 500 try begin set API_REQUEST_URL = API_URL + string /ez_config set payload = dict string options dumps options set files = list tuple string filename open filename string rb set headers = dict string Authorization string Bearer + string auth_t...
def ez_config(auth_token, filename, options = None): status_code = 500 try: API_REQUEST_URL = API_URL + "/ez_config" payload = { "options": json.dumps(options) } files = [("filename", open(filename, "rb"))] headers = { "Authorization": "Bearer " + ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Apr 21 19:35:01 2018 @author: k3sekido function getSublists L n begin set a = list set s = 0 set e = n for i in range length L - n + 1 begin append a L at slice s : e : set s = s + 1 set e = e + 1 end return a end function set L = list 1...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 21 19:35:01 2018 @author: k3sekido """ def getSublists(L, n): a = [] s=0 e=n for i in range(len(L)-n+1): a.append(L[s:e]) s+=1 e+=1 return a L = [10, 4, 6, 8, 3, 4, 5, 7, 7, 2] n=4 print(getSublis...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string 获取http请求 解析http请求 将请求发送给WebFrame(使用json) 从WebFrame接收反馈数据 将数据组织为Response格式发送给客户端 import json from socket import * import sys from threading import Thread import re from config import * comment 和frame进行交互 function connect_frame env begin set s = call socket try begin comment 链接webfram...
#!/usr/bin/env python3 ''' 获取http请求 解析http请求 将请求发送给WebFrame(使用json) 从WebFrame接收反馈数据 将数据组织为Response格式发送给客户端 ''' import json from socket import * import sys from threading import Thread import re from config import * #和frame进行交互 def connect_frame(env): s = socket() try: # 链接webframe s.connect((...
Python
zaydzuhri_stack_edu_python
function test_pwc_returns_callable self begin set c = call pwc 10 set argspec = call getfullargspec c assert callable c assert args == list string params string t end function
def test_pwc_returns_callable(self): c = qml.pulse.pwc(10) argspec = inspect.getfullargspec(c) assert callable(c) assert argspec.args == ["params", "t"]
Python
nomic_cornstack_python_v1
comment 导入函数库 import jqdata comment 初始化函数,设定基准等等 function initialize context begin comment 设定沪深300作为基准 call set_benchmark string 000300.XSHG comment 开启动态复权模式(真实价格) call set_option string use_real_price true comment 过滤掉order系列API产生的比error级别低的log comment log.set_level('order', 'error') comment 输出内容到日志 log.info() info str...
# 导入函数库 import jqdata ## 初始化函数,设定基准等等 def initialize(context): # 设定沪深300作为基准 set_benchmark('000300.XSHG') # 开启动态复权模式(真实价格) set_option('use_real_price', True) # 过滤掉order系列API产生的比error级别低的log # log.set_level('order', 'error') # 输出内容到日志 log.info() log.info('初始函数开始运行且全局只运行一次') ### 期货相关...
Python
zaydzuhri_stack_edu_python
function put key value ttl begin global memcache_client try begin if memcache_client is none begin set memcache_client = call _get_mc end return set key value time=ttl end except any begin set memcache_client = call _get_mc return set key value time=ttl end end function
def put(key, value, ttl): global memcache_client try: if memcache_client is None: memcache_client = _get_mc() return memcache_client.set(key, value, time = ttl ) except: memcache_client = _get_mc() return memcache_client.set(key, value, time = ttl )
Python
nomic_cornstack_python_v1
function itkSLICImageFilterIUS3IUS3_cast obj begin return call itkSLICImageFilterIUS3IUS3_cast obj end function
def itkSLICImageFilterIUS3IUS3_cast(obj: 'itkLightObject') -> "itkSLICImageFilterIUS3IUS3 *": return _itkSLICImageFilterPython.itkSLICImageFilterIUS3IUS3_cast(obj)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sun Jul 8 19:34:32 2018 @author: chuxuan import random import os function train_test_data NumOfImage NumOfTrainImge begin set all_ = random sample range NumOfImage NumOfImage set a = all_ at slice 0 : NumOfTrainImge : set b = all_ at slice N...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jul 8 19:34:32 2018 @author: chuxuan """ import random import os def train_test_data(NumOfImage,NumOfTrainImge): all_=random.sample(range(NumOfImage),NumOfImage) a = all_[0:NumOfTrainImge] b = all_[NumOfTrainImge:len(all_)] train...
Python
zaydzuhri_stack_edu_python
import os import time class SnacksTimes begin function __init__ self name begin set name = name end function end class
import os import time class SnacksTimes: def __init__(self, name): self.name = name
Python
zaydzuhri_stack_edu_python
function modify_entries self entry_id begin set query = string UPDATE entries SET title = ' { title } ', details= ' { details } ' WHERE entry_id= { entry_id } call execute_query query commit conn close conn end function
def modify_entries(self, entry_id): query = f""" UPDATE entries SET title = '{self.title}', details= '{self.details}' WHERE entry_id={entry_id} """ self.db.execute_query(query) self.db.conn.commit() self.db.co...
Python
nomic_cornstack_python_v1
string 导入包 import numpy as np from sklearn.datasets import load_diabetes from sklearn.utils import shuffle import matplotlib.pyplot as plt string 封装成类 class lr_model begin function __init__ self begin pass end function comment 替换为我自己写的函数 string 损失函数 function linear_loss self X y w b begin string 线性回归模型的损失函数 :param X: 特...
'''导入包''' import numpy as np from sklearn.datasets import load_diabetes from sklearn.utils import shuffle import matplotlib.pyplot as plt '''封装成类''' class lr_model(): def __init__(self): pass #替换为我自己写的函数 """损失函数""" def linear_loss(self,X, y, w, b): """ 线性回归模型的损失函数 :para...
Python
zaydzuhri_stack_edu_python
function finish_remote_batch self src_db dst_db tick_id begin comment this also commits set q = string select * from pgq_node.set_consumer_completed(%s, %s, %s) call exec_cmd dst_db q list queue_name consumer_name tick_id end function
def finish_remote_batch(self, src_db, dst_db, tick_id): # this also commits q = "select * from pgq_node.set_consumer_completed(%s, %s, %s)" self.exec_cmd(dst_db, q, [ self.queue_name, self.consumer_name, tick_id ])
Python
nomic_cornstack_python_v1
function _categorize_resource self resource required_permissions begin if is_user_provided begin append resources_reused dict string arn arn ; string required_permissions required_permissions end else begin append resources_created dict string arn arn end end function
def _categorize_resource(self, resource: Resource, required_permissions: str) -> None: if resource.is_user_provided: self.resources_reused.append({"arn": resource.arn, "required_permissions": required_permissions}) else: self.resources_created.append({"arn": resource.arn})
Python
nomic_cornstack_python_v1
function checkWeather self begin set tuple precipTime maxPrecip = maxPrecipProb comment if it rains if maxPrecip > 0.5 begin comment hands umbrella set status = string 1 end else comment if sunny is true if icon == string clear-day or icon == string clear-night or icon == string partly-cloudy-day or icon == string part...
def checkWeather(self): (self.precipTime, self.maxPrecip) = self.weatherForecast.maxPrecipProb if self.maxPrecip> 0.5: # if it rains self.status = "1" # hands umbrella elif self.weatherForecast.icon=="clear-day" or self.weatherForecast.icon=="clear-night" or self.weatherForecast.icon=="partly-cloudy-day" ...
Python
nomic_cornstack_python_v1
import socket import sys import time import threading from threading import Lock class CloudNode begin function __init__ self begin set cloud_queue = list set TCP_IP = string 127.0.0.1 set my_tcp_port = integer argv at 1 set node_time = time set max_time = 250 set cloud_node_queue = list end function function cloud_t...
import socket import sys import time import threading from threading import Lock class CloudNode: def __init__(self): self.cloud_queue = [] self.TCP_IP = '127.0.0.1' self.my_tcp_port = int(sys.argv[1]) self.node_time = time.time() self.max_time = 250 self.cloud_node...
Python
zaydzuhri_stack_edu_python
function sanity_checks df begin set df_temp = copy df comment checks that the max date is less than tomorrow's date. assert string parse time max string %Y-%m-%d < call utcnow + time delta days=1 comment checks that there are no duplicate dates assert sum == 0 msg string One or more rows share the same date. if string ...
def sanity_checks(df: pd.DataFrame) -> None: df_temp = df.copy() # checks that the max date is less than tomorrow's date. assert datetime.datetime.strptime(df_temp['Date'].max(), '%Y-%m-%d') < (datetime.datetime.utcnow() + datetime.timedelta(days=1)) # checks that there are no duplicate dates assert...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python class Solution begin function maximalRectangle self matrix begin string :type matrix: list[list[str]] :rtype int comment len for row set n = length matrix if n == 0 begin return n end comment len for column set m = length matrix at 0 set ans = 0 set heights = list 0 * m + 1 for i in range n...
#!/usr/bin/env python class Solution: def maximalRectangle(self, matrix) -> int: """ :type matrix: list[list[str]] :rtype int """ # len for row n = len(matrix) if n == 0: return n # len for column m = len(matrix[0]) self.an...
Python
zaydzuhri_stack_edu_python
string 153. 数字组合 II 给出一组候选数字(C)和目标数字(T),找出C中所有的组合,使组合中 数字的和为T。C中每个数字在每个组合中只能使用一次。 样例 给出一个例子,候选数字集合为[10,1,6,7,2,1,5] 和目标数字 8 , 解集为:[[1,7],[1,2,5],[2,6],[1,1,6]] 注意事项 所有的数字(包括目标数字)均为正整数。 元素组合(a1, a2, … , ak)必须是非降序(ie, a1 ≤ a2 ≤ … ≤ ak)。 解集不能包含重复的组合。 class Solution begin string @param num: Given the candidate numbers @par...
""" 153. 数字组合 II 给出一组候选数字(C)和目标数字(T),找出C中所有的组合,使组合中 数字的和为T。C中每个数字在每个组合中只能使用一次。 样例 给出一个例子,候选数字集合为[10,1,6,7,2,1,5] 和目标数字 8 , 解集为:[[1,7],[1,2,5],[2,6],[1,1,6]] 注意事项 所有的数字(包括目标数字)均为正整数。 元素组合(a1, a2, … , ak)必须是非降序(ie, a1 ≤ a2 ≤ … ≤ ak)。 解集不能包含重复的组合。 """ class Solution: """ @param num: Given the candidate numbe...
Python
zaydzuhri_stack_edu_python
import threading function working begin for i in range 5 begin print string 工作 end end function function playing begin for i in range 5 begin print string 玩乐 end end function set working_thread = thread target=working set playing_thread = thread target=playing if __name__ == string __main__ begin call setDaemon true st...
import threading def working(): for i in range(5): print('工作') def playing(): for i in range(5): print('玩乐') working_thread = threading.Thread(target=working) playing_thread = threading.Thread(target=playing) if __name__ == '__main__': working_thread.setDaemon(True) working_thread.star...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import time from xgboost.sklearn import XGBRegressor from sklearn.model_selection import GridSearchCV , PredefinedSplit , KFold , cross_val_score from sklearn.metrics import make_scorer , mean_squared_error import _pickle as cPickle import xgboost function get_rmse ground_truth pr...
import pandas as pd import numpy as np import time from xgboost.sklearn import XGBRegressor from sklearn.model_selection import GridSearchCV,PredefinedSplit, KFold, cross_val_score from sklearn.metrics import make_scorer, mean_squared_error import _pickle as cPickle import xgboost def get_rmse(ground_truth, predicti...
Python
zaydzuhri_stack_edu_python
import sys set input = readline function main begin set n = integer input set table = list comprehension 0 for i in range 10 ^ 6 + 2 for _ in range n begin set tuple a b = map int split input set table at a = table at a + 1 set table at b + 1 = table at b + 1 - 1 end for i in range length table - 1 begin set table at i...
import sys input = sys.stdin.readline def main(): n = int(input()) table = [0 for i in range(10**6+2)] for _ in range(n): a, b = map(int, input().split()) table[a] += 1 table[b+1] -= 1 for i in range(len(table)-1): table[i+1] += table[i] print(max(table)) if __name__ ...
Python
zaydzuhri_stack_edu_python
function safe function begin comment noinspection PyBroadException function safe_function *args **kwargs begin try begin return call function *args keyword kwargs end except any begin return decimal string inf end end function return safe_function end function
def safe(function): # noinspection PyBroadException def safe_function(*args, **kwargs): try: return function(*args, **kwargs) except: return float('inf') return safe_function
Python
nomic_cornstack_python_v1
function Reset self begin pass end function
def Reset(self): pass
Python
nomic_cornstack_python_v1
function initialize self begin assert length input == 0 msg string RandomStimulatorBox needs 0 inputs assert length output == 1 msg string RandomStimulatorBox needs exactly 1 output comment Initialize parameters from settings comment Target stimulation codes must be converted from string to comment OpenViBE internal co...
def initialize(self): assert len(self.input) == 0, 'RandomStimulatorBox needs 0 inputs' assert len(self.output) == 1, 'RandomStimulatorBox needs exactly 1 output' # Initialize parameters from settings # Target stimulation codes must be converted from string to # OpenViBE intern...
Python
nomic_cornstack_python_v1
import math for i in range 1 100000 begin set v = 1 + square root 2 * i * i - 2 * i + 1 / 2 end
import math for i in range(1, 100000): v = (1+math.sqrt(2*i*i-2*i+1))/2
Python
zaydzuhri_stack_edu_python
comment 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 comment 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 class Solution begin function find self target array begin set row = length array - 1 set col = length array at 0 - 1 set i = row set j = 0 while i >= 0 and j <= col begin if target < array at i at j begin ...
#在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 # 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 class Solution: def find(self,target, array): row = len(array)-1 col = len(array[0])-1 i = row j = 0 while i>=0 and j<=col: if target<array[i][j...
Python
zaydzuhri_stack_edu_python
function processExist pid begin if name == string nt begin comment >> pip install psutil from psutil import pid_exists return call pid_exists pid end else begin try begin call kill pid 0 end except OSError begin return false end try else begin return true end end end function
def processExist(pid): if os.name == 'nt': from psutil import pid_exists # >> pip install psutil return pid_exists(pid) else: try: os.kill(pid, 0) except OSError: return False else: return True
Python
nomic_cornstack_python_v1
function convert_time time begin if not is instance time int or time < 0 begin raise call ValueError string Invalid input: input must be a non-negative integer. end set seconds = time % 60 set minutes = time // 60 % 60 set hours = time // 3600 set result = list if hours > 0 begin append result string { hours } hour { ...
def convert_time(time): if not isinstance(time, int) or time < 0: raise ValueError("Invalid input: input must be a non-negative integer.") seconds = time % 60 minutes = (time // 60) % 60 hours = time // 3600 result = [] if hours > 0: result.append(f"{hours} hour{'s' if ...
Python
jtatman_500k
function cephfs self begin return get pulumi self string cephfs end function
def cephfs(self) -> Optional['outputs.CephFSVolumeSourcePatch']: return pulumi.get(self, "cephfs")
Python
nomic_cornstack_python_v1
function test_ping6_hostname_s_freebsd12 self begin assert equal parse ping freebsd12_ping6_hostname_s quiet=true freebsd12_ping6_hostname_s_json end function
def test_ping6_hostname_s_freebsd12(self): self.assertEqual(jc.parsers.ping.parse(self.freebsd12_ping6_hostname_s, quiet=True), self.freebsd12_ping6_hostname_s_json)
Python
nomic_cornstack_python_v1
import math import wpilib from wpilib.command import Subsystem from utilities.pov_button import POVButton from utilities.drive_control import * from utilities.settings import Settings from oi import OI from commands.manual.power_of_the_friendship import DriveWithJoystick class Drivetrain extends Subsystem begin functio...
import math import wpilib from wpilib.command import Subsystem from utilities.pov_button import POVButton from utilities.drive_control import * from utilities.settings import Settings from oi import OI from commands.manual.power_of_the_friendship import DriveWithJoystick class Drivetrain(Subsystem): def __init...
Python
zaydzuhri_stack_edu_python
comment 1. Write a Python function called compare date that takes as arguments two lists of two integers each. Each list contains a month and a year, in that order. The function should return -1 if the first month and year are earlier than the second month and year, 0 if they are the same, and 1 if the first month and ...
# 1. Write a Python function called compare date that takes as arguments two lists of two integers each. Each list contains a month and a year, in that order. The function should return -1 if the first month and year are earlier than the second month and year, 0 if they are the same, and 1 if the first month and year a...
Python
zaydzuhri_stack_edu_python
function get_one self audit begin if from_audits begin raise OperationNotPermitted end set context = context set rpc_audit = call get_resource string Audit audit call enforce context string audit:get rpc_audit action=string audit:get return call convert_with_links rpc_audit end function
def get_one(self, audit): if self.from_audits: raise exception.OperationNotPermitted context = pecan.request.context rpc_audit = api_utils.get_resource('Audit', audit) policy.enforce(context, 'audit:get', rpc_audit, action='audit:get') return Audit.convert_with_link...
Python
nomic_cornstack_python_v1
function update self AmountOfTraffic=none BurstSize=none CongestNumFrames=none CountRandomFrameSize=none CustomLoadUnit=none DelayAfterTransmit=none Duration=none EnableBpPassFail=none EnableHolbPassFail=none EnableMinFrameSize=none EnableOldStatsForReef=none ForceRegenerate=none FrameSizeMode=none Framesize=none Frame...
def update(self, AmountOfTraffic=None, BurstSize=None, CongestNumFrames=None, CountRandomFrameSize=None, CustomLoadUnit=None, DelayAfterTransmit=None, Duration=None, EnableBpPassFail=None, EnableHolbPassFail=None, EnableMinFrameSize=None, EnableOldStatsForReef=None, ForceRegenerate=None, FrameSizeMode=None, Framesize=N...
Python
nomic_cornstack_python_v1
import time set start_time = time set total = list function sleeper seconds begin sleep seconds append total seconds end function for s in tuple 1 2 3 begin call sleeper s end set end_time = time set total_time = end_time - start_time print format string Total time: {:.3} seconds. Sum: {} total_time sum total
import time start_time = time.time() total = [] def sleeper(seconds): time.sleep(seconds) total.append(seconds) for s in (1, 2, 3): sleeper(s) end_time = time.time() total_time = end_time - start_time print("Total time: {:.3} seconds. Sum: {}".format(total_time, sum(total)))
Python
zaydzuhri_stack_edu_python
function Usuarios_Group request pk begin try begin set objToken = get objects key=get query_params string tk set usuario = get objects pk=id end except ObjectDoesNotExist begin set content = dict string Datos incorrectos string El token enviado no coincide para ningun usuario return call Response content status=HTTP_40...
def Usuarios_Group(request, pk): try: objToken = Token.objects.get(key=request.query_params.get('tk')) usuario = User.objects.get(pk=objToken.user.id) except ObjectDoesNotExist: content = {'Datos incorrectos': 'El token enviado no coincide para ningun usuario'} ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import csv import sys import string set data = reader stdin delimiter=string , for info in data begin print info at 14 + string , + info at 16 + string + string 1 end
#!/usr/bin/env python import csv import sys import string data=csv.reader(sys.stdin,delimiter=',') for info in data: print(info[14] + ', ' +info[16] + '\t' + '1')
Python
zaydzuhri_stack_edu_python
function test_api_quota_detail_page_one_date self begin set response = open client path=string /api/quotas/guid/?since=2013-12-31 headers=valid_header assert equal status_code 200 comment Check if quota was rendered assert true string guid in keys json comment Check if quota data was rendered assert equal length json a...
def test_api_quota_detail_page_one_date(self): response = Client.open( self.client, path="/api/quotas/guid/?since=2013-12-31", headers=valid_header) self.assertEqual(response.status_code, 200) # Check if quota was rendered self.assertTrue('guid' in res...
Python
nomic_cornstack_python_v1
function groupby self by begin comment type: (Union[str, Callable[[GeoFeature], str]]) -> _CollectionGroupBy string Groups collection using a value of a property. Parameters ---------- by : str or callable If string, name of the property by which to group. If callable, should receive a GeoFeature and return the categor...
def groupby(self, by): # type: (Union[str, Callable[[GeoFeature], str]]) -> _CollectionGroupBy """Groups collection using a value of a property. Parameters ---------- by : str or callable If string, name of the property by which to group. If callable, sho...
Python
jtatman_500k
function _get_next_action self begin if _next_update_monitor_time and _next_update_spec_time begin comment Return the time that is closer in the future. if _next_update_monitor_time < _next_update_spec_time begin return _UPDATE_MONITOR end else begin return _UPDATE_SPEC end end else if _next_update_monitor_time begin r...
def _get_next_action(self): if self._next_update_monitor_time and self._next_update_spec_time: # Return the time that is closer in the future. if self._next_update_monitor_time < self._next_update_spec_time: return ServerMonitor._UPDATE_MONITOR else: ...
Python
nomic_cornstack_python_v1
string Usages: ./run_assignment3.py (reads out hte entire config dict) ./run_assignment3.py thiskey this value (sets 'thiskey' and 'thisvalue' in the dict) import sys from assignments.assignment3 import ConfigDict set cd = call ConfigDict string config_file.txt if length argv == 3 begin set key = argv at 1 set value = ...
""" Usages: ./run_assignment3.py (reads out hte entire config dict) ./run_assignment3.py thiskey this value (sets 'thiskey' and 'thisvalue' in the dict) """ import sys from assignments.assignment3 import ConfigDict cd = ConfigDict('config_file.txt') if len(sys.argv) == 3: key ...
Python
zaydzuhri_stack_edu_python
string Created on 2017年11月28日 @author: cm import pymysql as ps from pymysql import cursors class SqlHelper begin function __init__ self host user password database charset begin set host = host set user = user set password = password set database = database set charset = charset set db = none set curs = none end functi...
''' Created on 2017年11月28日 @author: cm ''' import pymysql as ps from pymysql import cursors class SqlHelper: def __init__(self, host, user, password, database, charset): self.host = host self.user = user self.password = password self.database = database self.charset = char...
Python
zaydzuhri_stack_edu_python
string lab 4 import numpy as np from numpy.linalg import eigh import matplotlib.pyplot as plt comment ********** mean calculation ************************ function find_mean x n d begin set mean = zeros d set summ = zeros d for j in range n begin set summ = summ + x at j end set mean = summ / n return mean end function...
''' lab 4 ''' import numpy as np from numpy.linalg import eigh import matplotlib.pyplot as plt #********** mean calculation ************************ def find_mean(x,n,d): mean=np.zeros(d) summ=np.zeros(d) for j in range(n): summ +=x[j] mean=summ/n return mean #**************************************...
Python
zaydzuhri_stack_edu_python
from math import sqrt set n = decimal input string Digite o valor: set raiz = square root n print raiz
from math import sqrt n = float(input("Digite o valor: ")) raiz= sqrt(n) print (raiz)
Python
zaydzuhri_stack_edu_python
function seq2science_parser workflows_dir=string ./seq2science/workflows/ begin comment setup the parser set parser = call ArgumentParser call add_argument string -v string --version action=string version version=string seq2science: v { __version__ } set subparsers = call add_subparsers dest=string command set required...
def seq2science_parser(workflows_dir="./seq2science/workflows/"): # setup the parser parser = argparse.ArgumentParser() parser.add_argument("-v", "--version", action="version", version=f"seq2science: v{seq2science.__version__}") subparsers = parser.add_subparsers(dest="command") subparsers.required ...
Python
nomic_cornstack_python_v1
function CNN_DCNN_model_define filter_size window_size strides hidden_size begin function Conv1DTranspose input_tensor filters kernel_size activation name=none strides=2 padding=string valid begin string Define a 1D deconvolution layer set x = call call Lambda lambda x -> call expand_dims x axis=2 input_tensor set x = ...
def CNN_DCNN_model_define(filter_size, window_size, strides, hidden_size): def Conv1DTranspose(input_tensor, filters, kernel_size, activation, name=None, strides=2, padding='valid'): """ Define a 1D deconvolution layer """ x = Lambda(lambda x: K.expand_dims(x, axis=2))(input_tensor) ...
Python
nomic_cornstack_python_v1
function get_parameter self name begin try begin set ind = index _param_names name end except IndexError begin set ind = none end if ind is none begin raise call KeyError format string {}: model has no parameter '{}' __name__ name end return _parameter_values at ind end function
def get_parameter(self, name): try: ind = self._param_names.index(name) except IndexError: ind = None if ind is None: raise KeyError("{}: model has no parameter '{}'".format(type(self).__name__, name)) return self._parameter_values[ind]
Python
nomic_cornstack_python_v1
function kuzushiji_f1 sub solution detection_only=false begin set sub = rename columns=dict string rowId string image_id ; string PredictionString string labels set solution = rename columns=dict string rowId string image_id ; string PredictionString string labels if not all values == values begin raise call ValueError...
def kuzushiji_f1(sub, solution, detection_only=False): sub = sub.rename(columns={'rowId': 'image_id', 'PredictionString': 'labels'}) solution = solution.rename(columns={'rowId': 'image_id', 'PredictionString': 'labels'}) if not all(sub['image_id'].values == solution['image_id'].values): raise V...
Python
nomic_cornstack_python_v1
function _check_heartbeats self ts *args **kwargs begin string Checks if the heartbeats are on-time. If not, the channel id is escalated to self._late_heartbeats and a warning is issued; once a hb is received again from this channel, it'll be removed from this dict, and an Info message logged. :param ts: timestamp, dec...
def _check_heartbeats(self, ts, *args, **kwargs): """ Checks if the heartbeats are on-time. If not, the channel id is escalated to self._late_heartbeats and a warning is issued; once a hb is received again from this channel, it'll be removed from this dict, and an Info message lo...
Python
jtatman_500k
from SkolaStranihJezika import Osoblje from SkolaStranihJezika import Polaznici from SkolaStranihJezika import Ponuda print print string *****SkolaStranihJezika Script***** print function main begin if not call login begin print print string Niste uneli dobro korisnicko ime i lozinku. print call main end else begin set...
from SkolaStranihJezika import Osoblje from SkolaStranihJezika import Polaznici from SkolaStranihJezika import Ponuda print() print("*****SkolaStranihJezika Script*****") print() def main(): if not login(): print() print("\nNiste uneli dobro korisnicko ime i lozinku.") prin...
Python
zaydzuhri_stack_edu_python
import sqlite3 comment Connect to simpsons database set conn = call connect string simpsons.db function createTable begin execute conn string CREATE TABLE if not exists SIMPSON_INFO( ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, GENDER TEXT, AGE INT, OCCUPATION TEXT ); end function
import sqlite3 # Connect to simpsons database conn = sqlite3.connect('simpsons.db') def createTable(): conn.execute("CREATE TABLE if not exists \ SIMPSON_INFO( \ ID INTEGER PRIMARY KEY AUTOINCREMENT, \ NAME TEXT, \ GENDER TEXT, \ AGE INT, \ OCCUPATION TEXT \ ...
Python
zaydzuhri_stack_edu_python
string You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. h...
""" You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. ht...
Python
zaydzuhri_stack_edu_python
string Packt Pub Scrapy Spider import scrapy import sys class PacktPubSpider extends Spider begin set name = string packtpub function __init__ self begin call __init__ set rows = 50 end function function start_requests self begin set urls = list string https://packtpub.com/all for url in urls begin yield call Request u...
''' Packt Pub Scrapy Spider ''' import scrapy import sys class PacktPubSpider(scrapy.Spider): name = 'packtpub' def __init__(self): scrapy.Spider.__init__() self.rows = 50 def start_requests(self): urls = [ 'https://packtpub.com/all' ] for url in urls: yield scrapy.Request( url=url, cal...
Python
zaydzuhri_stack_edu_python
from transform import lerp , vec comment search sorted keyframe lists from bisect import bisect_left from transform import quaternion_slerp , quaternion_matrix , quaternion , quaternion_from_euler , translate , rotate , scale from Node import Node import glfw class KeyFrames begin string Stores keyframe pairs for any v...
from transform import lerp, vec from bisect import bisect_left # search sorted keyframe lists from transform import (quaternion_slerp, quaternion_matrix, quaternion, quaternion_from_euler, translate, rotate, scale) from Node import Node import glfw class KeyFrames: """ Stores keyframe pa...
Python
zaydzuhri_stack_edu_python
function reach_3_model df rows=48 begin set df = copy tail df n=rows set df at string log_odds = 0.5157 + 0.267 * df at string rain_0_to_24h_sum + 0.1681 * df at string rain_24_to_48h_sum - 0.02855 * df at string days_since_sig_rain set df at string probability = sigmoid df at string log_odds set df at string safe = df...
def reach_3_model(df: pd.DataFrame, rows: int = 48) -> pd.DataFrame: df = df.tail(n=rows).copy() df['log_odds'] = ( 0.5157 + 0.267 * df['rain_0_to_24h_sum'] + 0.1681 * df['rain_24_to_48h_sum'] - 0.02855 * df['days_since_sig_rain'] ) df['probability'] = sigmoid(df['log_o...
Python
nomic_cornstack_python_v1
function transform_disturbances draws shocks_mean shocks_cholesky begin set draws_transformed = dot T set draws_transformed = draws_transformed + shocks_mean set draws_transformed at tuple slice : : slice : 2 : = call clip exp draws_transformed at tuple slice : : slice : 2 : 0.0 HUGE_FLOAT return draws_transfo...
def transform_disturbances(draws, shocks_mean, shocks_cholesky): draws_transformed = draws.dot(shocks_cholesky.T) draws_transformed += shocks_mean draws_transformed[:, :2] = np.clip( np.exp(draws_transformed[:, :2]), 0.0, HUGE_FLOAT ) return draws_transformed
Python
nomic_cornstack_python_v1
function clean_title self *args **kwargs begin comment Customer's given title. comment self.cleaned_data is a dict set title = get cleaned_data string title comment Checks if the customer's title has been used. comment title__iexact -> lookup for the same title ignoring the casing set qs = filter title__iexact=title co...
def clean_title(self, *args, **kwargs): # Customer's given title. title = self.cleaned_data.get('title') # self.cleaned_data is a dict # Checks if the customer's title has been used. qs = BlogPosts.objects.filter(title__iexact=title) # title__iexact -> lookup for the same title...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Dec 07 17:23:26 2016 @author: Brian string stacker model with feats import pickle from sklearn.cross_validation import KFold import xgboost as xgb from sklearn.ensemble import ExtraTreesRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.metrics ...
# -*- coding: utf-8 -*- """ Created on Wed Dec 07 17:23:26 2016 @author: Brian """ """ stacker model with feats """ import pickle from sklearn.cross_validation import KFold import xgboost as xgb from sklearn.ensemble import ExtraTreesRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.metrics i...
Python
zaydzuhri_stack_edu_python
function test_frontend_user_profile_like_emoji_twice_post self begin comment Create a second user set new_user = call create_user username=string 1 password=string 1 comment Create likes call create user=user post=all at 0 emoji_type=3 call create user=new_user post=all at 0 emoji_type=3 comment Login the user call log...
def test_frontend_user_profile_like_emoji_twice_post(self): # Create a second user new_user = User.objects.create_user(username="1", password="1") # Create likes React.objects.create(user=self.user, post=self.user.posts.all()[0], emoji_type=3) React.objects.create(user=new_user, ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment Imports import json import urllib2 comment Constants set json_weather = string http://api.openweathermap.org/data/2.5/weather?q= set city = string calgary,ca set home = string set weather_file = string .bashweather function get_data site begin try begin set site_data = url open site re...
#!/usr/bin/python # Imports import json import urllib2 # Constants json_weather = 'http://api.openweathermap.org/data/2.5/weather?q=' city = 'calgary,ca' home = '' weather_file = '.bashweather' def get_data(site): try: site_data = urllib2.urlopen(site) return site_data except: exit() ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np set x = linear space - 3 3 50 set y1 = 2 * x + 1 set y2 = x ^ 2 figure plot x y2 plot x y1 color=string red linewidth=1.0 linestyle=string -- comment 设置x坐标和y坐标的值的范围 call xlim tuple - 1 2 call ylim tuple - 2 3 comment x轴和y轴的标签(不支持中文) x label string aaa y label string bb...
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y1 = 2*x + 1 y2 = x**2 plt.figure() plt.plot(x, y2) plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') # 设置x坐标和y坐标的值的范围 plt.xlim((-1, 2)) plt.ylim((-2, 3)) # x轴和y轴的标签(不支持中文) plt.xlabel("aaa") plt.ylabel("bbb") # 设置x轴的坐标为-1到2,分为4...
Python
zaydzuhri_stack_edu_python
comment encoding=utf8 set __author__ = string Administrator set x2 = 1 for day in range 9 0 - 1 begin set x1 = x2 + 1 * 2 set x2 = x1 end
#encoding=utf8 __author__ = 'Administrator' x2 = 1 for day in range(9,0,-1): x1 = (x2 + 1) * 2 x2 = x1
Python
zaydzuhri_stack_edu_python
function main begin call echo __version__ end function
def main(): click.echo(__version__)
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt import matplotlib import math import random set rcParams at string font.family = string STSong set city_name = list set city_condition = list string python打开文件,并把文件内容传给f,传出的内容以字符串表示,引入了with语句来自动帮我们调用close()方法,'r'为对文件的操作。 调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按...
import numpy as np import matplotlib.pyplot as plt import matplotlib import math import random matplotlib.rcParams['font.family'] = 'STSong' city_name = [] city_condition = [] """ python打开文件,并把文件内容传给f,传出的内容以字符串表示,引入了with语句来自动帮我们调用close()方法,'r'为对文件的操作。 调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。每行都是一个字符串 要读取...
Python
zaydzuhri_stack_edu_python
function className self begin return call Animation_className self end function
def className(self): return _osgAnimation.Animation_className(self)
Python
nomic_cornstack_python_v1
function read_input filename begin try begin set input_file = open filename string r set permutation = split read input_file string set permutation = list comprehension integer i for i in permutation set n = length permutation append permutation n + 1 insert permutation 0 0 close input_file end except any begin print s...
def read_input(filename): try: input_file = open(filename, "r") permutation = input_file.read().split(" ") permutation = [int(i) for i in permutation] n = len(permutation) permutation.append(n+1) permutation.insert(0, 0) input_file.close() except: ...
Python
zaydzuhri_stack_edu_python
import matrix.dense_matrix as dm import matrix.sparse_matrix as sm print string = * 30 + string Problem 1 set dm1 = list list 1 2 3 list 3 4 5 list 5 6 5 set dm2 = list list 1 2 list 3 4 set res = add dm dm1 at slice : 2 : dm2 print string add: res set res = call multiply dm1 dm2 print string multiply: res print stri...
import matrix.dense_matrix as dm import matrix.sparse_matrix as sm print("="*30 + "\nProblem 1") dm1 = [[1, 2, 3], [3, 4, 5], [5, 6, 5]] dm2 = [[1, 2], [3, 4]] res = dm.add(dm1[:2], dm2) print("add:", res) res = dm.multiply(dm1, dm2) print("multiply:", res) print("="*30 + "\nProblem 2") sm1 = {'rows': 3, 'cols': 3,...
Python
zaydzuhri_stack_edu_python
function merge_np_arrays_in_chunks data1 data2 split_size begin set pacs1 = integer length data1 * split_size set pacs2 = integer length data2 * split_size set data1frac = list comprehension data1 at slice i * pacs1 : i + 1 * pacs1 : for i in range integer ceil 1 / split_size set data2frac = list comprehension data2 a...
def merge_np_arrays_in_chunks(data1, data2, split_size): pacs1 = int(len(data1) * split_size) pacs2 = int(len(data2) * split_size) data1frac = [data1[i * pacs1:(i + 1) * pacs1] for i in range(int(np.ceil(1 / split_size)))] data2frac = [data2[i * pacs2:(i + 1) * pacs2] for i in range(int(np.ceil(1 / spl...
Python
nomic_cornstack_python_v1
function cpy_c_files c_fl src dst flg=true begin if flg == false begin return 0 end end function
def cpy_c_files(c_fl, src, dst, flg = True): if flg == False: return 0
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon Aug 6 15:21:54 2018 @author: Administrator import numpy as np import scipy.io.wavfile as wf import matplotlib.pyplot as plt import numpy.fft as nf comment ./ML 当前目录的ML文件夹, ../ML 上一级目录的ML文件夹 set tuple sample_rate sigs = read wf string ../ML/data/freq.wav comment 44100 ...
# -*- coding: utf-8 -*- """ Created on Mon Aug 6 15:21:54 2018 @author: Administrator """ import numpy as np import scipy.io.wavfile as wf import matplotlib.pyplot as plt import numpy.fft as nf sample_rate, sigs = wf.read('../ML/data/freq.wav') # ./ML 当前目录的ML文件夹, ../ML 上一级目录的ML文件夹 print(sample_rate) ...
Python
zaydzuhri_stack_edu_python
if integer A > 1000 begin set e = integer A at - 2 set f = integer A at - 1 set d = integer integer A - 10 * e - f / 100 set error = 10 * c * e + b * f + c * f set error = integer error / 100 set ans = integer A * a + 10 * d * b + e * b + c * d + error print integer ans end else begin print integer integer A * decimal ...
if int(A) > 1000: e = int(A[-2]) f = int(A[-1]) d = int((int(A)- 10 * e - f)/100) error = 10 * (c * e + b * f) + c * f error = int(error/100) ans = int(A) * a + 10 * d * b + e * b + c * d + error print(int(ans)) else: print(int(int(A)*float(B)))
Python
zaydzuhri_stack_edu_python
string Solve each of the following problems using python scripts. Make sure you use appropriate variable names and comments, When there is a final answer have python print it to the screen. A person;s body mass index (BMI) is defined as: BMI - mass in kg / (height in m)^2 comment takes in body mass of person set bodyMa...
'''Solve each of the following problems using python scripts. Make sure you use appropriate variable names and comments, When there is a final answer have python print it to the screen. A person;s body mass index (BMI) is defined as: BMI - mass in kg / (height in m)^2 ''' bodyMass=float(input('enter your body mass in ...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment ### 202. Happy Number comment Write an algorithm to determine if a number is "happy". comment <br> comment A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process unt...
# coding: utf-8 # ### 202. Happy Number # Write an algorithm to determine if a number is "happy". # <br> # A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where...
Python
zaydzuhri_stack_edu_python
function convert_netdict_to_pydict dict begin set pydict = dict for key in Keys begin set pydict at key = dict at key end return pydict end function
def convert_netdict_to_pydict(dict): pydict = {} for key in dict.Keys: pydict[key] = dict[key] return pydict
Python
nomic_cornstack_python_v1
function fit self dataset params=none begin if params is none begin set params = dictionary end if is instance params tuple list tuple begin return list comprehension fit self dataset paramMap for paramMap in params end else if is instance params dict begin if params begin return call _fit dataset end else begin return...
def fit(self, dataset, params=None): if params is None: params = dict() if isinstance(params, (list, tuple)): return [self.fit(dataset, paramMap) for paramMap in params] elif isinstance(params, dict): if params: return self.copy(params)._fit(da...
Python
nomic_cornstack_python_v1
function autoencoder x width=3 depth=3 activation=elu z_dim=3 reuse=false normed_weights=false normed_encs=false bounds=none begin set out_dim = shape at 1 with call variable_scope string encoder reuse=reuse as vs_enc begin set x = dense x width activation=activation bounds=bounds for idx in range depth - 1 begin comme...
def autoencoder(x, width=3, depth=3, activation=tf.nn.elu, z_dim=3, reuse=False, normed_weights=False, normed_encs=False, bounds=None): out_dim = x.shape[1] with tf.variable_scope('encoder', reuse=reuse) as vs_enc: x = dense(x, width, activation=activation, bounds=bounds)...
Python
nomic_cornstack_python_v1
function models self type version file=string all.txt begin return format string {base}/{type}/{version}/lib/{file} base=config at string models type=type version=version file=file end function
def models(self, type, version, file='all.txt'): return '{base}/{type}/{version}/lib/{file}'.format( base=self.config['models'], type=type, version=version, file=file)
Python
nomic_cornstack_python_v1
function setAxes self steps=4 rMax=none makeGrid=true begin if makeGrid is false or gridSet begin return end if rMax is none begin if data is none begin set rMax = 1.0 end else begin set rMax = max data at string y end end set rMax = rMax comment Add radial grid lines (theta markers) set gridPen = call mkPen width=0.55...
def setAxes(self, steps=4, rMax=None, makeGrid=True): if makeGrid is False or self.gridSet: return if rMax is None: if self.data is None: rMax = 1.0 else: rMax = np.max(self.data['y']) self.rMax = rMax # Add radial grid ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env_python import smtplib import sys class tcolors begin set BLUE = string  set YELLOW = string  set RED = string  end class function slender begin set banner = string .dNd+:/yNNNm: /NNd+nDn/hNd` `mN/ `hMNd ....... mMs yN/ oN+ /NMm +` : .NN` om. +No -- oMMs `: -` mN. ...+y- `smhsy+ .NMm...
#!/usr/bin/env_python import smtplib import sys class tcolors: BLUE = '\033[34m' YELLOW = '\033[93m' RED = '\033[91m' def slender(): banner = (""" .dNd+:/yNNNm: /NNd+nDn/hNd` `mN/ `hMNd ...
Python
zaydzuhri_stack_edu_python
string Created on 11 sie 2016 @author: Magda from openpyxl import Workbook from openpyxl.writer.write_only import WriteOnlyCell from openpyxl.comments import Comment from openpyxl.styles import Font from openpyxl import load_workbook from openpyxl.styles import colors import list_parsing set location = string Integrati...
''' Created on 11 sie 2016 @author: Magda ''' from openpyxl import Workbook from openpyxl.writer.write_only import WriteOnlyCell from openpyxl.comments import Comment from openpyxl.styles import Font from openpyxl import load_workbook from openpyxl.styles import colors import list_parsing location = "IntegrationTests...
Python
zaydzuhri_stack_edu_python
for _ in range n begin set arr_item = integer input append a arr_item end comment result = candies(n, arr) set b = list 1 * n for i in range length a - 1 begin if a at i < a at i + 1 and b at i >= b at i + 1 begin set b at i + 1 = b at i + 1 end end print b for i in range length a - 1 0 - 1 begin comment print(i,a[i],"...
for _ in range(n): arr_item = int(input()) a.append(arr_item) #result = candies(n, arr) b=[1]*n for i in range(len(a)-1): if a[i]<a[i+1] and b[i]>=b[i+1]: b[i+1]=b[i]+1 print(b) for i in range(len(a)-1,0,-1): #print(i,a[i],"hi") if a[i-1]>a[i] and b[i]>=b[i-1]: b[i-1]=b[i]+1 print(b) print(sum(b))
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string 线上写一个脚本,拿到eventv4的第一条数据的时间 as online_start_time 拿到当前最后一条的数据的servertime as online_end_time 以start_time和end_time为range做一次count as count 生成json文件 {"start_time":ISODate() , "end_time":ISODate(),count: INT_number} --> onlineCount.json /Backup/v4_events_httplogs_orderstuff/monitor/onlineD...
# -*- coding: utf-8 -*- """ 线上写一个脚本,拿到eventv4的第一条数据的时间 as online_start_time 拿到当前最后一条的数据的servertime as online_end_time 以start_time和end_time为range做一次count as count 生成json文件 {"start_time":ISODate() , "end_time":ISODate(),count: INT_number} --> onlineCount.json /Backup/v4_events_httplogs_orderstuff/monitor/onlineDbCount.js...
Python
zaydzuhri_stack_edu_python
comment -*- encoding: utf-8 -*- import sqlite3 import getpass from PIL import Image function create_db begin string Crea dues bases de dades, una gestiona els usuaris i una altre gestiona les amistats entre aquets usuaris comment Nomes te que se cridada un cop set db = call connect string xarxa_social.db set cursor = c...
# -*- encoding: utf-8 -*- import sqlite3 import getpass from PIL import Image def create_db(): """ Crea dues bases de dades, una gestiona els usuaris i una altre gestiona les amistats entre aquets usuaris """ #Nomes te que se cridada un cop db = sqlite3.connect('xarxa_social.db') cursor = db.cur...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import os from skimage import io , color , transform function tail img begin for i in range shape at 0 begin if mean np img at tuple i slice : : != 1 begin set top = i break end end for i in reversed range top shape at 0 begin if mean np img at tuple i slice : : !=...
import numpy as np import matplotlib.pyplot as plt import os from skimage import io, color,transform def tail(img): for i in range(img.shape[0]): if (np.mean(img[i,:]) != 1): top = i break for i in reversed(range(top,img.shape[0])): if (np.mean(img[i,:]) != 1): bottom = i break for i in range(img.sh...
Python
zaydzuhri_stack_edu_python
function reverse_array arr begin set start = 0 set end = length arr - 1 while start < end begin set tuple arr at start arr at end = tuple arr at end arr at start set start = start + 1 set end = end - 1 end return arr end function set arr = list 1 2 3 4 5 print call reverse_array arr
def reverse_array(arr): start = 0 end = len(arr) - 1 while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 return arr arr = [1, 2, 3, 4, 5] print(reverse_array(arr))
Python
jtatman_500k
comment To add a new cell, type '# %%' comment To add a new markdown cell, type '# %% [markdown]' comment %% import json import pandas as pd from sklearn.model_selection import train_test_split import nltk from nltk.probability import FreqDist from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extractio...
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% import json import pandas as pd from sklearn.model_selection import train_test_split import nltk from nltk.probability import FreqDist from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import Tfid...
Python
zaydzuhri_stack_edu_python
function test_empty_pop begin from deque import Deque set deque = deque with raises AttributeError begin pop deque end end function
def test_empty_pop(): from deque import Deque deque = Deque() with pytest.raises(AttributeError): deque.pop()
Python
nomic_cornstack_python_v1
from cards import get_cards import random class CardsController begin function __init__ self begin set cards = call get_cards set used_cards = list set now = pop cards 0 set previous = none end function function reload_cards self begin set card_list = copy used_cards clear used_cards extend card_list cards shuffle ran...
from cards import get_cards import random class CardsController: def __init__(self): self.cards = get_cards() self.used_cards = [] self.now = self.cards.pop(0) self.previous = None def reload_cards(self): card_list = self.used_cards.copy() self.used_cards.cl...
Python
zaydzuhri_stack_edu_python
function CalculateAverageGraphEdgeLength graph begin set totalLength = 0 set numberOfEdgesCounted = 0 for node in Nodes begin if Index != - 1 begin for edge in call GetNodeEdges Index begin comment Increment edge counter set numberOfEdgesCounted = numberOfEdgesCounted + 1 comment Add length of edge to total length set ...
def CalculateAverageGraphEdgeLength(graph): totalLength = 0 numberOfEdgesCounted = 0 for node in graph.Nodes: if node.Index != -1: for edge in graph.GetNodeEdges(node.Index): # Increment edge counter numberOfEdgesCounted += 1 ...
Python
nomic_cornstack_python_v1