code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_Interfaces self begin assert true call parse_state pattern=string ospf_ints cmd_key=string sh_ospf_ints == list string Ethernet0 string OSPF: interfaces not found end function
def test_Interfaces(self): self.assertTrue( self.ospf.parse_state( pattern='ospf_ints', cmd_key='sh_ospf_ints') == ['Ethernet0'], 'OSPF: interfaces not found')
Python
nomic_cornstack_python_v1
function ndim self begin return call ndim self end function
def ndim(self): return _functional.ndim(self)
Python
nomic_cornstack_python_v1
function simStateCallBack self data begin set index = 0 set namespace = call get_namespace set namespace = namespace at slice 1 : - 1 : + string ::base_link try begin set index = index name namespace end except Exception begin call logdebug string Failed to get index. Skipping... return end set positionX = x set posit...
def simStateCallBack(self, data): index = 0 namespace = rospy.get_namespace() namespace = namespace[1:-1] + "::base_link" try: index = data.name.index(namespace) except Exception: rospy.logdebug("Failed to get index. Skipping...") return ...
Python
nomic_cornstack_python_v1
function get_all_historical_klines symbol interval start_time end_time begin set total_data = list set total_time_delta = 1000 * INTERVAL_TIME_DELTA_MAPPING at interval while start_time < end_time begin set t0 = time set temp_end_time = start_time + total_time_delta if temp_end_time > end_time begin set temp_end_time ...
def get_all_historical_klines(symbol, interval, start_time, end_time): total_data = [] total_time_delta = 1000 * INTERVAL_TIME_DELTA_MAPPING[interval] while start_time < end_time: t0 = time.time() temp_end_time = start_time + total_time_delta if temp_end_time > end_time: ...
Python
nomic_cornstack_python_v1
comment -*- encoding: utf-8 -*- string Created on 2016-06-21 14:56:52 @author: Srgzyq try begin import cPickle as pickle end except ImportError begin import pickle end set d = dictionary name=string Bob age=20 score=88 comment 把任意对象序列化成一个str,然后就可以把这个str写入文件
#-*- encoding: utf-8 -*- ''' Created on 2016-06-21 14:56:52 @author: Srgzyq ''' try: import cPickle as pickle except ImportError: import pickle d = dict(name='Bob', age=20, score=88) # 把任意对象序列化成一个str,然后就可以把这个str写入文件
Python
zaydzuhri_stack_edu_python
function doh_b64_encode s begin return right strip decode call urlsafe_b64encode s string utf-8 string = end function
def doh_b64_encode(s: bytes) -> str: return base64.urlsafe_b64encode(s).decode('utf-8').rstrip('=')
Python
nomic_cornstack_python_v1
comment !/usr/bin/env pyhton comment -*- coding: utf-8 -*- comment Copyright (c) 2021 , Inc. All Rights Reserved string Authors: jufei Date: 2021/5/21 9:27 下午 from typing import List class Solution begin function singleNumber self nums begin string 异或运算的运用; :param nums: :return: set cur = 0 for num in nums begin set cu...
#!/usr/bin/env pyhton # -*- coding: utf-8 -*- # # Copyright (c) 2021 , Inc. All Rights Reserved # """ Authors: jufei Date: 2021/5/21 9:27 下午 """ from typing import List class Solution: def singleNumber(self, nums: List[int]) -> int: """ 异或运算的运用; :param nums: :return: "...
Python
zaydzuhri_stack_edu_python
function collect_OAnORD self obs_t act_t obs_t_prime rew_t done_t begin replace _pool at _idx obs_t=obs_t act_t=act_t obs_t_prime=obs_t_prime rew_t=rew_t done_t=done_t string Move index position ready for next sample collection. The index loop over container when _load == capacity set _idx = _idx + 1 % CAPACITY if not ...
def collect_OAnORD(self, obs_t: np.ndarray, act_t: np.ndarray, obs_t_prime: np.ndarray, rew_t: float, done_t: int) -> None: self._pool[self._idx].replace(obs_t=obs_t, act_t=act_t, obs_t_prime=obs_t_prime, rew_t=rew_t, done_t=done_t) """ Move index position ready f...
Python
nomic_cornstack_python_v1
function parse self response begin set event_list_container = call css string dl.simcal-events-list-container for tuple event_date event_details in zip call css string dt.simcal-day-label call css string dd.simcal-day begin comment format of date is Monday, April 13th set date = get call css string .simcal-date-format:...
def parse(self, response): event_list_container = response.css("dl.simcal-events-list-container") for event_date, event_details in zip( event_list_container.css("dt.simcal-day-label"), event_list_container.css("dd.simcal-day") ): #format of date is Monday, April 13th ...
Python
nomic_cornstack_python_v1
function test_get_indels_from_cigar begin set cigar = list tuple 4 21 tuple 0 100 tuple 2 1 tuple 0 30 set results = dict true dict 99 tuple string D 1 ; false dict 120 tuple string D 1 for value in list true false begin comment pylint:disable=protected-access call assert_dict_equal results at value call get_indel_from...
def test_get_indels_from_cigar(): cigar = [(4, 21), (0, 100), (2, 1), (0, 30)] results = {True: {99: ('D', 1)}, False: {120: ('D', 1)}} for value in [True, False]: # pylint:disable=protected-access assert_dict_equal(results[value], get_indel_from_cigar(cigar, ignore_softclip=...
Python
nomic_cornstack_python_v1
function unlock self begin pass end function
def unlock(self): pass
Python
nomic_cornstack_python_v1
function positives_focused_loss_fn_old loss_fn labels logits task_weights class_weights begin info string NOTE: using positives focused loss! set task_losses = list for task_num in range call get_shape at 1 begin append task_losses call multiply as type task_weights at task_num string float32 call loss_fn labels at tu...
def positives_focused_loss_fn_old(loss_fn, labels, logits, task_weights, class_weights): logging.info("NOTE: using positives focused loss!") task_losses = [] for task_num in range(labels.get_shape()[1]): task_losses.append( tf.multiply( task_weights[task_num].astype("floa...
Python
nomic_cornstack_python_v1
comment This code WILL NOT run in repl.it! You must comment load it on a computer with pygame! comment get the required libraries import pygame , sys , random from pygame.locals import * comment start up pygame call init comment two free colours! Feel free to add more! comment a great colour scheme creator is coolors.c...
#This code WILL NOT run in repl.it! You must #load it on a computer with pygame! #get the required libraries import pygame, sys, random from pygame.locals import * #start up pygame pygame.init() #two free colours! Feel free to add more! #a great colour scheme creator is coolors.co BLACK = (0, 0, 0) WHI...
Python
zaydzuhri_stack_edu_python
function lap1D k m dx begin return dot call div1D k m dx call grad1D k m dx end function
def lap1D(k, m, dx): return np.dot(div1D(k, m, dx), grad1D(k, m, dx))
Python
nomic_cornstack_python_v1
function serve_static self fs_path ims begin comment Get basic info from the filesystem and start building a response. comment ================================================================= set mtime = call stat fs_path at ST_MTIME set content_type = call guess_type fs_path at 0 or string text/plain set response = c...
def serve_static(self, fs_path, ims): # Get basic info from the filesystem and start building a response. # ================================================================= mtime = os.stat(fs_path)[stat.ST_MTIME] content_type = mimetypes.guess_type(fs_path)[0] or 'text/plain' ...
Python
nomic_cornstack_python_v1
comment /usr/bin/env python string Created on June 28, 2011 @author: sbobovyc import os import sys set DCS_path = absolute path path string .. append path DCS_path
#/usr/bin/env python """ Created on June 28, 2011 @author: sbobovyc """ import os import sys DCS_path = os.path.abspath("..") sys.path.append(DCS_path)
Python
zaydzuhri_stack_edu_python
string INPUTS comment provide the processed MP3 review file name (pkl file). Must be in the data folder set inputFile = string MP3reviews_redux.pkl set outputFile = string MP3model_redux.pkl comment number of aspects set NUM_ASPECTS = 3 comment END OF INPUTS ############################################################ ...
''' INPUTS ''' # provide the processed MP3 review file name (pkl file). Must be in the data folder inputFile = 'MP3reviews_redux.pkl' outputFile = 'MP3model_redux.pkl' NUM_ASPECTS = 3 # number of aspects ############################################################################### ##########################...
Python
zaydzuhri_stack_edu_python
function get_path self node begin return call getpath node end function
def get_path(self, node): return node.getroottree().getpath(node)
Python
nomic_cornstack_python_v1
function chan_faces n1 n2 xform dim begin set lines = list list 0 1 2 3 4 5 6 7 0 set tuple bflange hall tweb tflange = dim comment distance from shear center to neutral axis comment zsc_na = 3 * bflange ** 2 / (6 * bflange + h) # per msc 2018 refman comment TODO: consider the shear center set zsc = 0.0 comment if 0: #...
def chan_faces(n1, n2, xform, dim): lines = [[0, 1, 2, 3, 4, 5, 6, 7, 0]] bflange, hall, tweb, tflange = dim # distance from shear center to neutral axis #zsc_na = 3 * bflange ** 2 / (6 * bflange + h) # per msc 2018 refman zsc = 0. ## TODO: consider the shear center #if 0: # pragma: no cover ...
Python
nomic_cornstack_python_v1
function measurement_config self begin set MEASURE_CONFIG = MMC3316xMT_TM call write_byte_data MMC3316xMT_DEFAULT_ADDRESS MMC3316xMT_CNTRL_0 MEASURE_CONFIG sleep 0.1 set MEASURE_CONFIG = MMC3316xMT_SET call write_byte_data MMC3316xMT_DEFAULT_ADDRESS MMC3316xMT_CNTRL_0 MEASURE_CONFIG set MEASURE_CONFIG = MMC3316xMT_COIL...
def measurement_config(self): MEASURE_CONFIG = (MMC3316xMT_TM) bus.write_byte_data(MMC3316xMT_DEFAULT_ADDRESS, MMC3316xMT_CNTRL_0, MEASURE_CONFIG) time.sleep(0.1) MEASURE_CONFIG = (MMC3316xMT_SET) bus.write_byte_data(MMC3316xMT_DEFAULT_ADDRESS, MMC3316xMT_CNTRL_0, MEASURE_CONFIG) MEASURE_CONFIG = (MMC...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Dec 6 17:17:48 2018 @author: hanifa import numpy as np class MLPTwoLayers begin function __init__ self p layer1 layer2 begin set p = p set layer1 = layer1 set layer2 = layer2 end function function to_string self begin print string p=%d an...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 6 17:17:48 2018 @author: hanifa """ import numpy as np class MLPTwoLayers: def __init__(self,p,layer1,layer2): self.p=p self.layer1=layer1 self.layer2=layer2 def to_string(self): print("p=%d and layer1=%d a...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import requests set url = string http://www.baidu.com set html = get requests url set encoding = string utf-8
# -*- coding:utf-8 -*- import requests url = 'http://www.baidu.com' html = requests.get(url) html.encoding = 'utf-8'
Python
zaydzuhri_stack_edu_python
function add_listener self listener begin append _listeners listener end function
def add_listener(self, listener): self._listeners.append(listener)
Python
nomic_cornstack_python_v1
string netwerk utilities 2017_0604 WeMOS Lolin32 - first version function doConnect essid password begin import network set wlan = call WLAN STA_IF call active true if not call isconnected begin print string connecting to network... essid call connect essid password while not call isconnected begin pass end end print s...
''' netwerk utilities 2017_0604 WeMOS Lolin32 - first version ''' def doConnect(essid, password): import network wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print('connecting to network... ', essid) wlan.connect(essid, password) while not...
Python
zaydzuhri_stack_edu_python
function sys q begin comment Count the number of calls to function set ncalls = ncalls + 1 comment Initialize set z = zeros 2 dtype=string float64 set x = q at 0 set y = q at 1 set A = 10000.0 comment Calculate set z at 0 = A * x * y - 1 set z at 1 = exp - x + exp - y - 1 - 1 / A return z end function
def sys(q): # Count the number of calls to function globvar.ncalls += 1 # Initialize z = np.zeros(2, dtype='float64') x = q[0] y = q[1] A = 10000.0 # Calculate z[0] = A * x * y - 1 z[1] = np.exp(-x) + np.exp(-y) - 1 - (1 / A) return z
Python
nomic_cornstack_python_v1
function cert_id self cert_id begin if client_side_validation and cert_id is none begin comment noqa: E501 raise call ValueError string Invalid value for `cert_id`, must not be `None` end comment noqa: E501 set _cert_id = cert_id end function
def cert_id(self, cert_id): if ( self.local_vars_configuration.client_side_validation and cert_id is None ): # noqa: E501 raise ValueError( "Invalid value for `cert_id`, must not be `None`" ) # noqa: E501 self._cert_id = cert_id
Python
nomic_cornstack_python_v1
function history begin set userid = session at string user_id set transactions = execute db string SELECT * FROM purchase WHERE userid = :userid userid=userid for transaction in transactions begin set transaction at string price = call usd transaction at string tot / transaction at string shares set transaction at stri...
def history(): userid = session["user_id"] transactions = db.execute("SELECT * FROM purchase WHERE userid = :userid", userid = userid) for transaction in transactions: transaction["price"] = usd(transaction["tot"]/transaction["shares"]) transaction["name"] = lookup(transaction["symbol"])['na...
Python
nomic_cornstack_python_v1
class Solution extends object begin function inorderTraversal1 self root begin set res = list call helper root res return res end function function helper self root res begin if root begin call helper left res append res val call helper right res end end function function inorderTraversal self root begin string :type ...
class Solution(object): def inorderTraversal1(self, root): res = [] self.helper(root, res) return res def helper(self, root, res): if root: self.helper(root.left, res) res.append(root.val) self.helper(root.right, res) def inorderTraversa...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function maxDistToClosest self seats begin string :type seats: List[int] :rtype: int set res = 0 set loc = 0 set first = - 1 for i in range length seats begin if seats at i == 1 begin if first == - 1 begin set first = i set loc = i continue end if i - loc // 2 > res begin set res = i...
class Solution(object): def maxDistToClosest(self, seats): """ :type seats: List[int] :rtype: int """ res = 0 loc = 0 first = -1 for i in range(len(seats)): if seats[i] == 1: if first == -1: firs...
Python
zaydzuhri_stack_edu_python
function apply_widget_template self field_name begin string Applies widget template overrides if available. The method uses the `get_widget_template` method to determine if the widget template should be exchanged. If a template is available, the template_name property of the widget instance is updated. :param field_nam...
def apply_widget_template(self, field_name): """ Applies widget template overrides if available. The method uses the `get_widget_template` method to determine if the widget template should be exchanged. If a template is available, the template_name property of the widget instanc...
Python
jtatman_500k
import pygame import threading import time from rx.subject import Subject try begin import wiringpi end except ImportError begin set wiringpi = none end class Button begin function __init__ self controls pin=none key=none begin set pin = pin set key = key set press = call Subject set pressed = false if wiringpi begin c...
import pygame import threading import time from rx.subject import Subject try: import wiringpi except ImportError: wiringpi = None class Button: def __init__(self, controls, pin=None, key=None): self.pin = pin self.key = key self.press = Subject() self.pressed = False ...
Python
zaydzuhri_stack_edu_python
function generate_detection_results self rois gt_class_ids gt_boxes image_meta begin comment Trim zeros. set zero_ix = where rois at tuple slice : : 4 == 0 at 0 set N = if expression shape at 0 > 0 then zero_ix at 0 else shape at 0 set rois = rois at tuple slice : N : slice : 4 : set non_zeros = as type sum abso...
def generate_detection_results(self, rois, gt_class_ids, gt_boxes, image_meta): # Trim zeros. zero_ix = np.where(rois[:, 4] == 0)[0] N = zero_ix[0] if zero_ix.shape[0] > 0 else rois.shape[0] rois = rois[:N, :4] non_zeros = np.sum(np.abs(gt_boxes), axis=1).astype(np.bool) ...
Python
nomic_cornstack_python_v1
function apply_correction dev device_id cal_dict amplitude begin comment the numeration goes from 1 to 8 in the device, but from 0 to 7 in the programming... set chI = cal_dict at string AWG chI - 1 comment apply offsets call setDouble format string /{}/sigouts/{}/offset device_id chI cal_dict at string Offset chI call...
def apply_correction(dev,device_id,cal_dict,amplitude): chI = cal_dict['AWG chI']-1 #the numeration goes from 1 to 8 in the device, but from 0 to 7 in the programming... #apply offsets dev.setDouble('/{}/sigouts/{}/offset'.format(device_id,chI), cal_dict['Offset chI']) dev....
Python
nomic_cornstack_python_v1
comment Author: Nima Farnoodian <nima.farnoodian@student.uclouvain.be>, Louvain-La-Neuve, Belgium. import pickle import matplotlib.pyplot as plt import numpy as np import statistics as st import pandas as pd from scipy import stats import time from sklearn.feature_selection import SelectFromModel from sklearn.model_sel...
# Author: Nima Farnoodian <nima.farnoodian@student.uclouvain.be>, Louvain-La-Neuve, Belgium. import pickle import matplotlib.pyplot as plt import numpy as np import statistics as st import pandas as pd from scipy import stats import time from sklearn.feature_selection import SelectFromModel from sklearn.model_selectio...
Python
zaydzuhri_stack_edu_python
function check_odd_even number odd=true begin if odd begin if number % 2 == 1 begin print string Correct, number { number } is odd end else begin print string wrong, number { number } is not odd end end else if number % 2 == 1 begin print string Correct, number { number } is even end else begin print string wrong, numb...
def check_odd_even(number, odd=True): if odd: if number % 2 == 1: print(f"Correct, number {number} is odd") else: print(f"wrong, number {number} is not odd") else: if number % 2 == 1: print(f"Correct, number {number} is even") else: ...
Python
nomic_cornstack_python_v1
import math set k = integer input set A = list comprehension integer i for i in split input set A = A at slice : : - 1 set tuple u_lim l_lim = tuple 2 2 set ans = 0 for i in range k begin set a = A at i if ceil l_lim / a > floor u_lim / a begin set ans = - 1 end set l_lim = ceil l_lim / a * a set u_lim = floor u_lim ...
import math k=int(input()) A=[int(i) for i in input().split()] A=A[::-1] u_lim,l_lim=2,2 ans=0 for i in range(k): a=A[i] if math.ceil(l_lim/a)>math.floor(u_lim/a): ans=-1 l_lim=math.ceil(l_lim/a)*a u_lim=math.floor(u_lim/a)*a+a-1 if ans==-1: print(-1) else: print(l_lim,u_lim)
Python
zaydzuhri_stack_edu_python
function create_stateless_model stateful_model max_id begin set stateless_model = sequential list gru 128 return_sequences=true input_shape=list none max_id gru 128 return_sequences=true call TimeDistributed dense max_id activation=string softmax call build input_shape=call TensorShape list none max_id call set_weights...
def create_stateless_model(stateful_model, max_id): stateless_model = keras.models.Sequential([ keras.layers.GRU(128, return_sequences=True, input_shape=[None, max_id]), keras.layers.GRU(128, return_sequences=True), keras.layers.TimeDistributed(keras.layers.Dense(max_id, ...
Python
nomic_cornstack_python_v1
function get_project_name_from_path path append_mx=false begin string Get the project name from a path. For a path "/home/peter/hans/HLC12398/online/M1_13.tdms" or For a path "/home/peter/hans/HLC12398/online/data/M1_13.tdms" or without the ".tdms" file, this will return always "HLC12398". Parameters ---------- path: s...
def get_project_name_from_path(path, append_mx=False): """Get the project name from a path. For a path "/home/peter/hans/HLC12398/online/M1_13.tdms" or For a path "/home/peter/hans/HLC12398/online/data/M1_13.tdms" or without the ".tdms" file, this will return always "HLC12398". Parameters ----...
Python
jtatman_500k
function cast obj begin return call itkNoiseImageFilterISS3ISS3_cast obj end function
def cast(obj: 'itkLightObject') -> "itkNoiseImageFilterISS3ISS3 *": return _itkNoiseImageFilterPython.itkNoiseImageFilterISS3ISS3_cast(obj)
Python
nomic_cornstack_python_v1
comment coding: utf-8 string 画出 DOM 树的打分图,测试用 import json import networkx as nx import matplotlib.pyplot as plt from bs4 import Tag from News.utils.util import get_document from News.extractor import GeneralExtractor from News.extractor import score_dom_tree_new , choose_content_tag set __author__ = string Sven Lee set...
# coding: utf-8 """ 画出 DOM 树的打分图,测试用 """ import json import networkx as nx import matplotlib.pyplot as plt from bs4 import Tag from News.utils.util import get_document from News.extractor import GeneralExtractor from News.extractor import score_dom_tree_new, choose_content_tag __author__ = "Sven Lee" __copyright__ =...
Python
zaydzuhri_stack_edu_python
comment %% import os with open string test_file.txt string a as f begin comment read_date = f.read() comment for line in f: comment print(line, end='') comment print(read_date) write lines f string This is line 5 end with open string test_file.txt string r as g begin for line in g begin print line end=string end end cl...
#%% import os with open('test_file.txt', 'a') as f: #read_date = f.read() # for line in f: # print(line, end='') #print(read_date) f.writelines('\nThis is line 5') with open('test_file.txt','r') as g: for line in g: print(line, end='') f.closed g.closed # %% import os my_dir = os.open('C:\\User...
Python
zaydzuhri_stack_edu_python
for i in range 1 n begin set f3 = f1 + f2 print f1 set f1 = f2 set f2 = f3 end
for i in range(1,n): f3=f1+f2 print(f1) f1=f2 f2=f3
Python
zaydzuhri_stack_edu_python
function _get_k8s_cache begin global _k8s_cache if _k8s_cache is none begin set _k8s_cache = call KubernetesCache start_caching=false end return _k8s_cache end function
def _get_k8s_cache(): global _k8s_cache if _k8s_cache is None: _k8s_cache = KubernetesCache(start_caching=False) return _k8s_cache
Python
nomic_cornstack_python_v1
function extract_date str_date begin set rgx = compile string \d{4}-\d{2}-\d{2} set o_match = search str_date if o_match is not none begin set i_start = start o_match set i_end = i_start + 10 return tuple call datetime *time.strptime(str_date[i_start:i_end], '%Y-%m-%d')[0:6] str_date at slice 0 : i_start : + str_date ...
def extract_date(str_date): rgx = re.compile('\d{4}-\d{2}-\d{2}') o_match = rgx.search(str_date) if o_match is not None: i_start = o_match.start() i_end = i_start+10 return (datetime( *(time.strptime(str_date[i_start:i_end], "%Y-%m-%d")[0:6])), str_date[0:i_st...
Python
nomic_cornstack_python_v1
function on_stop_order self stop_order begin pass end function
def on_stop_order(self, stop_order: StopOrder): pass
Python
nomic_cornstack_python_v1
function printPublishConfigurationResult self begin set list_size = call SingleRegister set status = call getDeviceListSize list_size remote_id print format string List size: {0} list_size at 0 if list_size at 0 != length anchors begin call printPublishErrorCode string configuration return end set device_list = call De...
def printPublishConfigurationResult(self): list_size = SingleRegister() status = self.pozyx.getDeviceListSize(list_size, self.remote_id) print("List size: {0}".format(list_size[0])) if list_size[0] != len(self.anchors): self.printPublishErrorCode("configuration") ...
Python
nomic_cornstack_python_v1
function print_top filename begin set counter_list = call count_words filename sort counter_list key=lambda t -> t at 1 reverse=true print join string list comprehension string { t at 0 } { t at 1 } for tuple i t in enumerate counter_list if i < 20 end function
def print_top(filename): counter_list = count_words(filename) counter_list.sort(key=lambda t: t[1], reverse=True) print('\n'.join([f'{t[0]} {t[1]}' for i, t in enumerate(counter_list) if i < 20]))
Python
nomic_cornstack_python_v1
function attention n l=0 begin function attention_pair i j l=0 begin string Transforms the state to contain information regarding the attention for a pair of word embeddings (of dimension N) represented as statevectors for an N-qubit system using a trainable parameterized general two-body interaction. Args: i, j (int):...
def attention(n, l=0): def attention_pair(i, j, l=0): """Transforms the state to contain information regarding the attention for a pair of word embeddings (of dimension N) represented as statevectors for an N-qubit system using a trainable parameterized...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt comment data to plot set n_groups = 7 set VERIFICATION_FILE = tuple 64 76 84 81 87 77 87 set VERIFICATION_FUNCTION = tuple 61 60 67 67 62 60 62 comment create plot set tuple fig ax = call subplots set index = array range n_groups set bar_width = 0.35 set opacity = 0.8 ...
import numpy as np import matplotlib.pyplot as plt # data to plot n_groups = 7 VERIFICATION_FILE = (64,76,84,81,87,77,87) VERIFICATION_FUNCTION = (61,60,67,67,62,60,62) # create plot fig, ax = plt.subplots() index = np.arange(n_groups) bar_width = 0.35 opacity = 0.8 rects1 = plt.bar(index, VERIFICATION...
Python
zaydzuhri_stack_edu_python
comment equivalent to step/move function run self **kwargs begin call update_game_status call everyone_move keyword kwargs end function
def run(self, **kwargs): # equivalent to step/move self.update_game_status() self.everyone_move(**kwargs)
Python
nomic_cornstack_python_v1
function find_entity_views self view_type begin_entity=none properties=none begin string Find all ManagedEntity's of the requested type. :param view_type: The type of ManagedEntity's to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. The default is to start the search at the r...
def find_entity_views(self, view_type, begin_entity=None, properties=None): """Find all ManagedEntity's of the requested type. :param view_type: The type of ManagedEntity's to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The defaul...
Python
jtatman_500k
import copy function solution key lock begin set n = length key set m = length lock comment 회전 함수 function rotate key begin set nkey = list comprehension list 0 * n for _ in range n for a in range n begin for b in range n begin set nkey at a at b = key at n - b - 1 at a end end return nkey end function comment nlock 만들...
import copy def solution(key, lock): n = len(key) m = len(lock) # 회전 함수 def rotate(key): nkey = [[0]*n for _ in range(n)] for a in range(n): for b in range(n): nkey[a][b] = key[n-b-1][a] return nkey # nlock 만들기 nlock = [[0] * (2*n+m) for _ i...
Python
zaydzuhri_stack_edu_python
function field_trip request begin set state = get GET string state none set state_name = none if state begin set sites = call order_by string name set form = call PassSiteStateForm initial=dict string state state set state_name = STATES at state end else begin set form = call PassSiteStateForm set sites = list end ret...
def field_trip(request): state = request.GET.get('state', None) state_name = None if state: sites = FieldTripResource().list(state).order_by('name') form = PassSiteStateForm(initial={'state': state}) state_name = STATES[state] else: form = PassSiteStateForm() si...
Python
nomic_cornstack_python_v1
function run self begin while true begin set host_type = get hostsqueue set list qtype host = split host_type string / set rrSet = call lookup qtype host put tuple host rrSet end end function
def run(self): while True: host_type = self.hostsqueue.get() [qtype, host] = host_type.split('/') rrSet = self.lookup(qtype, host) self.answersqueue.put((host, rrSet))
Python
nomic_cornstack_python_v1
function yin x w1 w2 b begin set yin = b + x at 0 * w1 + x at 1 * w2 return yin end function function calc_error w1 w2 b begin set error = 0 for i in range 0 length x begin set yi = call yin x at i w1 w2 b set e = t at i - yi * t at i - yi set error = error + e end return error end function function adaline_learn x Y a...
def yin(x, w1, w2, b): yin = b + x[0]*w1 + x[1]*w2 return yin def calc_error(w1,w2,b): error = 0 for i in range(0, len(x)): yi = yin(x[i],w1,w2,b) e = (t[i]-yi)*(t[i]-yi) error = error + e return error def adaline_learn(x, Y, alpha, tolerance): w1=0.1 ...
Python
zaydzuhri_stack_edu_python
comment export data sheets from xlsx to csv comment Found this code on Github: comment https://gist.github.com/julianthome/2d8546e7bed869079ab0f409ae0faa87 comment By julianthome from xlrd import open_workbook import csv from os import sys function get_all_sheets excel_file begin set sheets = list set workbook = call ...
# export data sheets from xlsx to csv # Found this code on Github: # https://gist.github.com/julianthome/2d8546e7bed869079ab0f409ae0faa87 # By julianthome from xlrd import open_workbook import csv from os import sys def get_all_sheets(excel_file): sheets = [] workbook = open_workbook(excel_file) all_works...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import os import sys from itertools import permutations insert path 0 directory name path directory name path real path path __file__ import copy import unittest from satispy import * from satispy.io import * from satispy.solver import * class VariableTest extends TestCase begin function te...
#!/usr/bin/env python import os import sys from itertools import permutations sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import copy import unittest from satispy import * from satispy.io import * from satispy.solver import * class VariableTest(unittest.TestCase): def testV...
Python
zaydzuhri_stack_edu_python
set str1 = string I Love You set name = str1 at slice : 6 : print name set Xia = call casefold print Xia
str1 = " I Love You " name = str1[:6] print(name) Xia = str1.casefold() print(Xia)
Python
zaydzuhri_stack_edu_python
function mdrae self benchmark=none begin return decimal median absolute call _relative_error benchmark end function
def mdrae(self, benchmark: np.ndarray = None) -> float: return float(np.median(np.abs(self._relative_error(benchmark))))
Python
nomic_cornstack_python_v1
string Class to Generate the BatMobile import pygame set bat_img = load image string batmobile.png class Symbol begin string Creates the Batmobile and prints it to the screen function __init__ self x y screen begin string Arg: x (int): x axis postion y (int): y axis postion screen(pygame.display): the screen to display...
""" Class to Generate the BatMobile """ import pygame bat_img = pygame.image.load('batmobile.png') class Symbol: """ Creates the Batmobile and prints it to the screen """ def __init__(self, x, y, screen): """ Arg: x (int): x axis postion y (int): y axis ...
Python
zaydzuhri_stack_edu_python
function fim_weight_location_location self begin return - hessian_weight_location_location end function
def fim_weight_location_location(self) -> Union[np.ndarray, dask.array.core.Array]: return -self.hessian_weight_location_location
Python
nomic_cornstack_python_v1
function get self request rest_id begin set restaurant = get Restaurant rest_id set restaurant = call model_to_json restaurant return call JsonResponse restaurant end function
def get(self, request, rest_id): restaurant = Restaurant.get(rest_id) restaurant = model_to_json(restaurant) return JsonResponse(restaurant)
Python
nomic_cornstack_python_v1
function debug s begin if config at string DEBUG begin print s end end function
def debug(s): if app.config['DEBUG']: print(s)
Python
nomic_cornstack_python_v1
function calc_R_2 y_hat y_test begin set SSR = sum set SST = sum return 1 - SSR / SST end function
def calc_R_2(y_hat, y_test): SSR = ((y_test - y_hat)**2).sum() SST = ((y_test - y_test.mean())**2).sum() return 1 - (SSR/SST)
Python
nomic_cornstack_python_v1
function moveArm self joint_id target_rotation begin set normalized_target_rotation = target_rotation % 2 * pi set difference = normalized_target_rotation - joints at joint_id if __abs__ < step_size begin set joints at joint_id = normalized_target_rotation end else if difference < pi begin set joints at joint_id = join...
def moveArm(self, joint_id, target_rotation): normalized_target_rotation = target_rotation%(2*np.pi) difference = normalized_target_rotation-self.joints[joint_id] if(difference.__abs__<self.step_size): self.joints[joint_id] = normalized_target_rotation elif(differe...
Python
nomic_cornstack_python_v1
import os , sys import glob import math from scipy.optimize import cobyla as co from jinja2 import Template import subprocess comment Load templates set f = open string templates/Trebuchet.inp string r set template_trebuchet_raw = read f close f set template = call Template template_trebuchet_raw set job_id = string Tr...
import os,sys import glob import math from scipy.optimize import cobyla as co from jinja2 import Template import subprocess # Load templates f = open('templates/Trebuchet.inp','r') template_trebuchet_raw = f.read() f.close() template = Template(template_trebuchet_raw) job_id = "Trebuchet" [cw_mass_index, cw_beam_len...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*-
#!/usr/bin/python # -*- coding: utf-8 -*-
Python
zaydzuhri_stack_edu_python
comment https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb comment http://www.thushv.com/natural_language_processing/word2vec-part-1-nlp-with-deep-learning-with-tensorflow-skip-gram/ comment http://www.hankcs.com/ml/cbow-word2vec.html from __future__ import print_function ...
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb # http://www.thushv.com/natural_language_processing/word2vec-part-1-nlp-with-deep-learning-with-tensorflow-skip-gram/ # http://www.hankcs.com/ml/cbow-word2vec.html from __future__ import print_function import collect...
Python
zaydzuhri_stack_edu_python
function test_chpl_type_name self begin set test_cases = list tuple string function string procedure tuple string iterfunction string iterator tuple string type string type tuple string data string tuple string method string tuple string itermethod string tuple string opfunction string operator tuple string opmethod...
def test_chpl_type_name(self): test_cases = [ ('function', 'procedure'), ('iterfunction', 'iterator'), ('type', 'type'), ('data', ''), ('method', ''), ('itermethod', ''), ('opfunction', 'operator'), ('opmethod', ''),...
Python
nomic_cornstack_python_v1
async function test_integration_log_level_logger_not_loaded hass hass_ws_client hass_admin_user begin set websocket_client = await call hass_ws_client await call send_json dict string id 7 ; string type string logger/log_level ; string integration string websocket_api ; string level DEBUG ; string persistence string no...
async def test_integration_log_level_logger_not_loaded( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_admin_user: MockUser ) -> None: websocket_client = await hass_ws_client() await websocket_client.send_json( { "id": 7, "type": "logger/log_level", ...
Python
nomic_cornstack_python_v1
comment 원 경로 comment /opt/conda/lib/python3.7/site-packages/pororo/models/brainbert/BrainRoBERTa.py comment Copyright (c) Facebook, Inc., its affiliates and Kakao Brain. All Rights Reserved from typing import Dict , Tuple , Union import numpy as np import torch from fairseq.models.roberta import RobertaHubInterface , R...
# 원 경로 # /opt/conda/lib/python3.7/site-packages/pororo/models/brainbert/BrainRoBERTa.py # Copyright (c) Facebook, Inc., its affiliates and Kakao Brain. All Rights Reserved from typing import Dict, Tuple, Union import numpy as np import torch from fairseq.models.roberta import RobertaHubInterface, RobertaModel from ...
Python
zaydzuhri_stack_edu_python
import math , time , serial import RPi.GPIO as GPIO set ser = call Serial port=string /dev/ttyS0 baudrate=19200 call setmode BCM set TRIG1 = 23 set TRIG2 = 17 set ECHO1 = 24 set ECHO2 = 27 print string Distance Measurement In Progress setup GPIO TRIG1 OUT setup GPIO ECHO1 IN setup GPIO TRIG2 OUT setup GPIO ECHO2 IN cal...
import math,time,serial import RPi.GPIO as GPIO ser = serial.Serial(port='/dev/ttyS0',baudrate = 19200) #################################################################################################### GPIO.setmode(GPIO.BCM) TRIG1 = 23 TRIG2 = 17 ECHO1 = 24 ECHO2 = 27 print ("Distance Measurement In Progress") GPI...
Python
zaydzuhri_stack_edu_python
from tkinter import * set root = call Tk call geometry string 600x400+100+100 set main_menu = call Menu root call config menu=main_menu function about_program begin print string Super mega program! end function function change_theme theme begin set txt_area at string bg = theme_colors at theme at string txt_bg set txt_...
from tkinter import * root = Tk() root.geometry('600x400+100+100') main_menu = Menu(root) root.config(menu=main_menu) def about_program(): print('Super mega program!') def change_theme(theme): txt_area['bg'] = theme_colors[theme]['txt_bg'] txt_area['fg'] = theme_colors[theme]['txt_fg'] ...
Python
zaydzuhri_stack_edu_python
comment pylint: disable=E1101 from __future__ import division from math import sqrt import cv function histogram_image hist color=tuple 255 255 255 background_color=tuple 0 0 0 num_bins=256 begin string Returns an image displaying the the given histogram. set max_value = integer call GetMinMaxHistValue hist at 1 set im...
# pylint: disable=E1101 from __future__ import division from math import sqrt import cv def histogram_image(hist, color=(255,255,255), background_color=(0,0,0), num_bins=256): '''Returns an image displaying the the given histogram.''' max_value = int(cv.GetMinMaxHistValue(hist)[1]) img = cv.CreateImage(...
Python
zaydzuhri_stack_edu_python
function to_dask_array self apply_mask_hardness=false begin if apply_mask_hardness and string dask in _custom begin if hardmask begin call harden_mask end else begin call soften_mask end end try begin return _custom at string dask end except KeyError begin raise call ValueError string { __name__ } object has no data en...
def to_dask_array(self, apply_mask_hardness=False): if apply_mask_hardness and "dask" in self._custom: if self.hardmask: self.harden_mask() else: self.soften_mask() try: return self._custom["dask"] except KeyError: ...
Python
nomic_cornstack_python_v1
comment Copyright 2023 CNRS comment Author: Florent Lamiraux comment Redistribution and use in source and binary forms, with or without comment modification, are permitted provided that the following conditions comment are met: comment 1. Redistributions of source code must retain the above copyright comment notice, th...
# Copyright 2023 CNRS # Author: Florent Lamiraux # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following...
Python
zaydzuhri_stack_edu_python
function download_pnl filepath_or_buffer=none order_refs=none accounts=none sids=none start_date=none end_date=none timezone=none details=false output=string csv begin set params = dict if order_refs begin set params at string order_refs = order_refs end if accounts begin set params at string accounts = accounts end i...
def download_pnl( filepath_or_buffer: FilepathOrBuffer = None, order_refs: Union[list[str], str] = None, accounts: Union[list[str], str] = None, sids: Union[list[str], str] = None, start_date: str = None, end_date: str = None, timezone: str = None, details: bool = False, output: Lite...
Python
nomic_cornstack_python_v1
import random class newNode begin function __init__ self data begin set data = data set left = none set right = none end function end class function insertLevelOrder arr root i n begin if i < n begin set temp = call newNode arr at i set root = temp set left = call insertLevelOrder arr left 2 * i + 1 n set right = call ...
import random class newNode: def __init__(self, data): self.data = data self.left = self.right = None def insertLevelOrder(arr, root, i, n): if i < n: temp = newNode(arr[i]) root = temp root.left = insertLevelOrder(arr, root.left,2 * i + 1, n) root....
Python
zaydzuhri_stack_edu_python
function delete_app self name begin raise NotImplementedError end function
def delete_app(self, name): raise NotImplementedError
Python
nomic_cornstack_python_v1
function test_contents_installed_changed_manifest self begin call image_create rurl call pkg string install nopathA comment Specify location as filesystem path. call pkgsign_simple call get_repodir string nopathA call pkg string refresh --full call pkg string contents -m nopathA call assert_ string signature not in out...
def test_contents_installed_changed_manifest(self): self.image_create(self.rurl) self.pkg("install nopathA") # Specify location as filesystem path. self.pkgsign_simple(self.dc.get_repodir(), "nopathA") self.pkg("refresh --full") ...
Python
nomic_cornstack_python_v1
function sort_by cls field direction begin if field not in columns begin set field = string tid end if direction not in tuple string asc string desc begin set direction = string desc end return tuple field direction end function
def sort_by(cls, field, direction): if field not in cls.__table__.columns: field = 'tid' if direction not in ('asc', 'desc'): direction = 'desc' return field, direction
Python
nomic_cornstack_python_v1
comment I will first do the conversion on the testing data set as I first wanna do/test the forward pass comment so, for every image in the test set, convert every pixel from the image to spike train comment thus a 28x28 image => 28x28x1000 comment next apply the conv. filters spatially, namelly for each t=1...1000 app...
#I will first do the conversion on the testing data set as I first wanna do/test the forward pass #so, for every image in the test set, convert every pixel from the image to spike train #thus a 28x28 image => 28x28x1000 #next apply the conv. filters spatially, namelly for each t=1...1000 apply filter on the 28x28 ``tim...
Python
zaydzuhri_stack_edu_python
comment Import library import random comment Generate random numbers set random_nums = list for i in range 5 begin append random_nums random integer 0 100 end comment Print random numbers print random_nums
# Import library import random # Generate random numbers random_nums = [] for i in range(5): random_nums.append(random.randint(0,100)) # Print random numbers print(random_nums)
Python
flytech_python_25k
function run begin print call wrap_file keyword variables call parse_args end function
def run(): print(wrap_file(**vars(parse_args())))
Python
nomic_cornstack_python_v1
function gets_agency_db name begin return first filter by query name=name end function
def gets_agency_db(name): return Agency.query.filter_by(name=name).first()
Python
nomic_cornstack_python_v1
function lottery self begin sleep 1 call text_effect string Did you know? The 'L' also stands for Lottery! call text_effect string That means we'll use a number generator to choose your college. call text_effect string But don't worry, your chances are probably better than 1 in 14,000,605. comment Randomly selects a co...
def lottery(self): time.sleep(1) self.text_effect("Did you know? The 'L' also stands for Lottery!") self.text_effect("That means we'll use a number generator to choose your college.") self.text_effect("But don't worry, your chances are probably better than 1 in 14,000,6...
Python
nomic_cornstack_python_v1
from turtle import Turtle , Screen import random set timmy_the_turtle = call Turtle call shape string turtle set colors = list string blue string red string black string green string orange string pink string purple string indigo string yellow string cyan comment draw some shapes comment 360 degrees / # of sides commen...
from turtle import Turtle, Screen import random timmy_the_turtle = Turtle() timmy_the_turtle.shape("turtle") colors = ["blue", "red", "black", "green", "orange", "pink", "purple", "indigo", "yellow", "cyan"] #draw some shapes # 360 degrees / # of sides # 3 sided shape to 10 sided shape # each side is 100 length #-tri...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function generate_index_dict self list_x begin set index_dict = dictionary for tuple index value in enumerate list_x begin set index_dict at value = index end return index_dict end function function anagramMappings self A B begin string :type A: List[int] :type B: List[int] :rtype: L...
class Solution(object): def generate_index_dict(self, list_x): index_dict = dict() for index, value in enumerate(list_x): index_dict[value] = index return index_dict def anagramMappings(self, A, B): """ :type A: List[int] :type B: List[int] ...
Python
zaydzuhri_stack_edu_python
for v in enumerate lst begin print v end
for v in enumerate(lst): print( v)
Python
zaydzuhri_stack_edu_python
comment 3 function putconbound self i_ bk_ bl_ bu_ begin if not is instance bk_ boundkey begin raise call TypeError string Argument bk has wrong type end set res = call putconbound i_ bk_ bl_ bu_ if res != 0 begin set tuple result msg = call __getlasterror res raise error call rescode res msg end end function
def putconbound(self,i_,bk_,bl_,bu_): # 3 if not isinstance(bk_,boundkey): raise TypeError("Argument bk has wrong type") res = self.__obj.putconbound(i_,bk_,bl_,bu_) if res != 0: result,msg = self.__getlasterror(res) raise Error(rescode(res),msg)
Python
nomic_cornstack_python_v1
import tkinter as tk import pymysql import tkinter.messagebox from tkinter import ttk set win = call Tk title win string 通讯录 call geometry string 600x400 comment 新建菜单条 set menubar = call Menu win call config menu=menubar comment 创建一个菜单选项新建 set menu1 = call Menu menubar tearoff=false comment 删除选项菜单 set menu2 = call Menu...
import tkinter as tk import pymysql import tkinter.messagebox from tkinter import ttk win = tk.Tk() win.title('通讯录') win.geometry('600x400') menubar = tk.Menu(win)#新建菜单条 win.config(menu =menubar) menu1 = tk.Menu(menubar,tearoff = False)#创建一个菜单选项新建 menu2 = tk.Menu(menubar,tearoff = False)#删除选项菜单 menu3 = tk.Menu(me...
Python
zaydzuhri_stack_edu_python
from typing import Set , Tuple set State = Set at Tuple function state_to_str state begin string Just for debugging, print out a state sort the fluents first for consistency (could be expensive) each line shows one fluent value. Example: >>> s = set() >>> s.add(("done", )) >>> s.add(("clean", "obj_a")) >>> s.add(("in",...
from typing import Set, Tuple State = Set[Tuple] def state_to_str(state: State) -> str: r''' Just for debugging, print out a state sort the fluents first for consistency (could be expensive) each line shows one fluent value. Example: >>> s = set() >>> s.add(("done", )) >>...
Python
zaydzuhri_stack_edu_python
comment print(f.readline())#this statement print u.txt files 1st line comment print(f.readline())#this statement not print u.txt files 1st line but print after that line comment print(f.readline()) comment stuff=f.read() comment print(f.readline())#now this statement not print becoz stuff variable is read whole comment...
# print(f.readline())#this statement print u.txt files 1st line # print(f.readline())#this statement not print u.txt files 1st line but print after that line # print(f.readline()) # stuff=f.read() # print(f.readline())#now this statement not print becoz stuff variable is read whole # file becoz of that we can't read f...
Python
zaydzuhri_stack_edu_python
function scheduled_sample self ground_truth_x generated_x batch_size num_ground_truth begin set idx = call random_shuffle range batch_size set ground_truth_idx = gather tf idx range num_ground_truth set generated_idx = gather tf idx range num_ground_truth batch_size set ground_truth_examps = gather tf ground_truth_x gr...
def scheduled_sample(self, ground_truth_x, generated_x, batch_size, num_ground_truth): idx = tf.random_shuffle(tf.range(batch_size)) ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth)) generated_idx = tf.ga...
Python
nomic_cornstack_python_v1
from interpreteur import Interpreteur from mod.fct.mod_file import get_allfiles , file_exists , get_ext from os import remove , rename function binarise_all begin string compresse legerement les fichiers jex en bex, ecrase les anciens bex et supprime les jex source set Inter = call Interpreteur for fichier in call get_...
from interpreteur import Interpreteur from mod.fct.mod_file import get_allfiles, file_exists, get_ext from os import remove, rename def binarise_all(): """compresse legerement les fichiers jex en bex, ecrase les anciens bex et supprime les jex source""" Inter = Interpreteur() for fichier in get_allfiles("../"*bool(...
Python
zaydzuhri_stack_edu_python
async function createClaimRequest self schemaId proverId=none reqNonRevoc=true begin string Creates a claim request to the issuer. :param schemaId: The schema ID (reference to claim definition schema) :param proverId: a prover ID request a claim for (if None then the current prover default ID is used) :param reqNonRevo...
async def createClaimRequest(self, schemaId: ID, proverId=None, reqNonRevoc=True) -> ClaimRequest: """ Creates a claim request to the issuer. :param schemaId: The schema ID (reference to claim definition schema) :param proverId: a prover ID reque...
Python
jtatman_500k
import pygame as pg import sys from os import path from pygame_functions import * from settings import * from sprites import * from tilemap import * import random import time function aix self begin set loopy = USEREVENT + 1 call set_timer loopy 100 set loopx = USEREVENT + 2 call set_timer loopx 100 set xnieuw = 0 end ...
import pygame as pg import sys from os import path from pygame_functions import * from settings import * from sprites import * from tilemap import * import random import time def aix(self): self.loopy = pygame.USEREVENT + 1 pygame.time.set_timer(self.loopy, 100) self.loopx = pygame.USEREVENT + 2 pygame...
Python
zaydzuhri_stack_edu_python
comment Write a Python program access the index of a list. set L = list set n = integer input string Enter the value of n : for i in range n begin set v = integer input string Enter Value : append L v end for i in range n begin print string index : i string & value : L at i end
# Write a Python program access the index of a list. L = [] n = int(input("Enter the value of n : ")) for i in range(n): v = int(input("Enter Value : ")) L.append(v) for i in range(n): print("index :",i," & value :",L[i])
Python
zaydzuhri_stack_edu_python
function keys self begin return keys _curr end function
def keys(self): return self._curr.keys()
Python
nomic_cornstack_python_v1
function log_export tablename credential request contenttype title begin if starts with get headers string User-Agent string string resttest begin comment ignore resttest return end put end function
def log_export(tablename, credential, request, contenttype, title): if request.headers.get('User-Agent', '').startswith('resttest'): return # ignore resttest gaetk_ExportLog( tablename=tablename, title=title, uid=credential.uid, remote_addr=request.remote_addr, ...
Python
nomic_cornstack_python_v1