code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _verifyParameterCounts self endpoints begin set expected_params = list string AlexNet/conv1 string AlexNet/conv2 string AlexNet/pool2 string AlexNet/conv3 string AlexNet/pool3 string AlexNet/fc6 string AlexNet/fc7 call assertSetEqual set expected_params set keys endpoints end function
def _verifyParameterCounts(self, endpoints): expected_params = [ "AlexNet/conv1", "AlexNet/conv2", "AlexNet/pool2", "AlexNet/conv3", "AlexNet/pool3", "AlexNet/fc6", "AlexNet/fc7", ] self.assertSetEqual(set(expec...
Python
nomic_cornstack_python_v1
while length a > 0 begin if flag == 1 begin if a at length a - 1 > a at 0 begin set alex = alex + a at length a - 1 pop a length a - 1 end else begin set alex = alex + a at 0 pop a 0 end end else if a at length a - 1 > a at 0 begin set lee = lee + a at length a - 1 pop a length a - 1 end else begin set lee = lee + a at...
while len(a)>0: if flag==1: if(a[len(a)-1]>a[0]): alex+=a[len(a)-1] a.pop(len(a)-1) else: alex+=a[0] a.pop(0) else: if (a[len(a) - 1] > a[0]): lee+= a[len(a) - 1] a.pop(len(a) - 1) else: lee += a[...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python function outlierCleaner predictions ages net_worths begin string Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). s...
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the ...
Python
zaydzuhri_stack_edu_python
function _translate__l3vpn_ntw_vpn_services_vpn_service_ie_profiles_ie_profile_vpn_targets input_yang_obj translated_yang_obj=none begin for tuple k listInst in call iteritems begin set innerobj = call _translate__l3vpn_ntw_vpn_services_vpn_service_ie_profiles_ie_profile_vpn_targets_vpn_target listInst translated_yang_...
def _translate__l3vpn_ntw_vpn_services_vpn_service_ie_profiles_ie_profile_vpn_targets(input_yang_obj, translated_yang_obj=None): for k, listInst in input_yang_obj.vpn_target.iteritems(): innerobj = _translate__l3vpn_ntw_v...
Python
nomic_cornstack_python_v1
function test_delete_api_resource self mock_delete mock_set_token begin set exonet_client = call ExonetClient string kaSD0ffAD1ldSA92A0KODkaksda02KDAK call delete_api_resource call ApiResource dict string type string dns_records ; string id string qjJWA0Km8xgw comment Check mock calls. assert call_count == 1 assert cal...
def test_delete_api_resource(self, mock_delete: Mock, mock_set_token: Mock) -> None: exonet_client = ExonetClient("kaSD0ffAD1ldSA92A0KODkaksda02KDAK") exonet_client.delete_api_resource( ApiResource({"type": "dns_records", "id": "qjJWA0Km8xgw"}) ) # Check mock calls. ...
Python
nomic_cornstack_python_v1
import numpy as np class wiener_class begin function __init__ self begin return end function comment genera la matriz A hermitica basada en el vector de entrada Nx1 y el numero de coeficientes M comment elegido. resultando en una matriz de M filas y N (N-M) columnas function generateAHermitica self u M begin set col = ...
import numpy as np class wiener_class: def __init__(self): return # genera la matriz A hermitica basada en el vector de entrada Nx1 y el numero de coeficientes M # elegido. resultando en una matriz de M filas y N (N-M) columnas def generateAHermitica(self,u,M): col=u.size-M aH=np.zeros...
Python
zaydzuhri_stack_edu_python
comment Write your function, here. function remainder num1 num2 begin return num1 % num2 end function comment > 1 print call remainder 1 3 comment > 3 print call remainder 3 4 comment > 0 print call remainder 5 5 comment > 1 print call remainder 7 2
# Write your function, here. def remainder(num1, num2): return num1 % num2 print(remainder(1, 3)) # > 1 print(remainder(3, 4)) # > 3 print(remainder(5, 5)) # > 0 print(remainder(7, 2)) # > 1
Python
zaydzuhri_stack_edu_python
function randiter iterable begin string Create an iterator that yields random elements from the iterable object *iterable*. It expects the iterable object to implement __getitem__ and __len__. set iter_len = length iterable for index in call xrandrange iter_len begin yield iterable at index end end function
def randiter(iterable): ''' Create an iterator that yields random elements from the iterable object *iterable*. It expects the iterable object to implement __getitem__ and __len__.''' iter_len = len(iterable) for index in xrandrange(iter_len): yield iterable[index]
Python
jtatman_500k
comment IMPORTS####### from global_vars import * comment FUNCTION DEFINITIONS######### function instantiate_file begin set charge_file_path = LOCAL_LOCUS_PATH + string data/dca/Charges_10_21.csv set df = read csv charge_file_path set df = rename columns=dict string Violation Date string CHRG Date set df at string Conta...
#######IMPORTS####### from global_vars import * #######FUNCTION DEFINITIONS######### def instantiate_file(): charge_file_path = LOCAL_LOCUS_PATH + "data/dca/Charges_10_21.csv" df = pd.read_csv(charge_file_path) df = df.rename(columns={"Violation Date": "CHRG Date"}) df['Contact Phone'] ...
Python
zaydzuhri_stack_edu_python
comment 同样首先,我们调用模块 comment matplotlib是python专门用于画图的库 import matplotlib.pyplot as plt comment SK 样本数据 from sklearn import datasets comment 导入 数据集(波士顿房间数据) set loaded_data = call load_boston comment 导入所有特征变量 set x_data = data comment 导入目标值(房价) set y_data = target set name_data = feature_names print string --类型--- commen...
#同样首先,我们调用模块 # matplotlib是python专门用于画图的库 import matplotlib.pyplot as plt # SK 样本数据 from sklearn import datasets # 导入 数据集(波士顿房间数据) loaded_data = datasets.load_boston() x_data = loaded_data.data # 导入所有特征变量 y_data = loaded_data.target # 导入目标值(房价) name_data = loaded_data.feature_names print("...
Python
zaydzuhri_stack_edu_python
function test_toffoli self target_wire begin set control_wires = list range 3 del control_wires at target_wire comment pick some random unitaries (with a fixed seed) to make the circuit less trivial set U1 = call rvs 8 random_state=1 set U2 = call rvs 8 random_state=2 set dev = device string default.qubit wires=3 decor...
def test_toffoli(self, target_wire): control_wires = list(range(3)) del control_wires[target_wire] # pick some random unitaries (with a fixed seed) to make the circuit less trivial U1 = unitary_group.rvs(8, random_state=1) U2 = unitary_group.rvs(8, random_state=2) dev =...
Python
nomic_cornstack_python_v1
function tag_and_enqueue_add infojsonfile source_file output_directory created_futures add_pool rmtrash_pool begin comment fs sync? sleep 3 with open as jsonfile begin debug string opening json file set ytdl_update_dict = load json jsonfile encoding=string utf-8 end set kind2 = call Atom string Media Kind JSON_TV_SHOW_...
def tag_and_enqueue_add( infojsonfile: Path, source_file: Path, output_directory: Path, created_futures: List[Any], add_pool: ThreadPoolExecutor, rmtrash_pool: ThreadPoolExecutor, ) -> None: time.sleep(3) # fs sync? with infojsonfile.open() as jsonfile: logger.debug("opening jso...
Python
nomic_cornstack_python_v1
function icursor self index begin return call _w string icursor index end function
def icursor(self, index): return self.tk.call(self._w, 'icursor', index)
Python
nomic_cornstack_python_v1
comment #变量创建过程: comment 先申请一块存储空间来存储数据 comment 将变量名指向这一块空间 set name = string old-data print string name addr call id name set name2 = name print string name2 addr call id name2 comment ************# set data3 = string old set data4 = data3 print data3 call id data3 string data4 call id data4 set data3 = string new pr...
# #变量创建过程: # 先申请一块存储空间来存储数据 # 将变量名指向这一块空间 name="old-data" print("name addr",id(name)) name2=name print("name2 addr",id(name2)) #************# data3="old" data4=data3 print(data3,id(data3)," ",data4,id(data4)) data3="new" print(data3,id(data3)," ",data4,id(data4)) # output: # name addr 2215906459952 # na...
Python
zaydzuhri_stack_edu_python
from pathlib import Path import matplotlib.pyplot as plt import numpy as np from skimage.util import view_as_blocks from skimage.transform import rescale from skimage.io import imsave function plot_image image factor=1.0 clip_range=none figsize=tuple 15 15 **kwargs begin string Utility function for plotting RGB images....
from pathlib import Path import matplotlib.pyplot as plt import numpy as np from skimage.util import view_as_blocks from skimage.transform import rescale from skimage.io import imsave def plot_image(image, factor=1.0, clip_range=None, figsize=(15, 15), **kwargs): """ Utility function for plotting RGB images. ...
Python
zaydzuhri_stack_edu_python
string def listsum(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listsum(numList[1:len(numList)]) numList = [1,2,3,4] print numList[1:len(numList)] print listsum(numList) def toStr(n,base): convString = "0123456789ABCDEF" if n < base: return convString[n] else: return toStr(n//base,base) +...
''' def listsum(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listsum(numList[1:len(numList)]) numList = [1,2,3,4] print numList[1:len(numList)] print listsum(numList) def toStr(n,base): convString = "0123456789ABCDEF" if ...
Python
zaydzuhri_stack_edu_python
class BankAccount begin function __init__ self interest_rate balance=0 begin set balance = balance set interest_rate = interest_rate end function function deposit self amount begin set balance = balance + amount return self end function function withdraw self amount begin if balance >= amount begin set balance = balanc...
class BankAccount: def __init__(self, interest_rate, balance=0): self.balance = balance self.interest_rate = interest_rate def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): if self.balance >= amount: self.balan...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment -*- coding: utf-8 -*- import numpy as np import tensorflow as tf class Brain extends object begin function __init__ self scope env gamma=0.99 learning_rate=0.003 epsilon=0.1 output_graph=false begin set n_states = n_states set n_actions = n_actions set gamma = gamma set learning_ra...
#! /usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import tensorflow as tf class Brain(object): def __init__(self, scope, env, gamma=0.99, learning_rate=0.003, epsilon=0.1, output_graph=False): self.n_states = env.n_states self.n_actions = env.n_actions sel...
Python
zaydzuhri_stack_edu_python
comment !/usr/local/bin/python import os import csv function file_name file_dir begin set list = list for tuple root dirs files in walk file_dir begin for file in files begin append list file end end return list end function function readData list begin for file in list begin set csv_file = reader open string /Volumes...
#!/usr/local/bin/python import os import csv def file_name(file_dir): list = [] for root, dirs, files in os.walk(file_dir): for file in files: list.append(file) return list def readData(list): for file in list: csv_file = csv.reader(open('/Volumes/Code/code_archive/yellowp...
Python
zaydzuhri_stack_edu_python
string 本模块的功能为创建FP_growth树 aythor:胡觉文 直接调用网络创建模块 辅助(弃用) import reader class treeNode begin function __init__ self nameValue numOccur parentNode begin set name = nameValue set count = numOccur set nodeLink = none set parent = parentNode set children = dict end function function inc self numOccur begin set count = count...
''' 本模块的功能为创建FP_growth树 aythor:胡觉文 直接调用网络创建模块 辅助(弃用) ''' import reader class treeNode: def __init__(self, nameValue, numOccur, parentNode): self.name = nameValue self.count = numOccur self.nodeLink = None self.parent = parentNode self.children = {} def inc(self, numOccu...
Python
zaydzuhri_stack_edu_python
from cmath import exp from math import pi import numpy as np from time import time import random class FastBigNum begin function __init__ self x begin set x = x end function function __mul__ self y begin set tuple a b = call prepare self y return call multiply a b end function function __str__ self begin return string ...
from cmath import exp from math import pi import numpy as np from time import time import random class FastBigNum: def __init__(self, x): self.x = x def __mul__(self,y): a,b = prepare(self,y) return multiply(a,b) def __str__(self): return str(self.x) def omega(k,n): retu...
Python
zaydzuhri_stack_edu_python
function normal_kl mean stddev eps=1e-08 begin set var = call square stddev set kl = 0.5 * call reduce_sum call square mean + var - 1.0 - log var + eps return kl end function
def normal_kl(mean, stddev, eps=1e-8): var = tf.square(stddev) kl = 0.5*tf.reduce_sum(tf.square(mean)+var-1.-tf.log(var+eps)) return kl
Python
nomic_cornstack_python_v1
comment 文件处理的3步操作(打开、读取及关闭) comment 切记:下面的慕容飞儿文件必须与此文件在同级目录下 comment 打开文件 set f = open string 慕容飞儿 encoding=string utf-8 comment data = f.read() comment print(data) comment f.close() #打开之后必须要关闭文件,不然会不停的占系统内存 comment readline用法 comment data = f.readline() comment print('第一次打印:',data) comment print('第二次打印:',data) comment...
# 文件处理的3步操作(打开、读取及关闭) # 切记:下面的慕容飞儿文件必须与此文件在同级目录下 # 打开文件 f = open('慕容飞儿',encoding='utf-8') # data = f.read() # print(data) # f.close() #打开之后必须要关闭文件,不然会不停的占系统内存 # readline用法 # data = f.readline() # print('第一次打印:',data) # print('第二次打印:',data) # print('第三次打印:',data) # readlines用法 data = f.readlines() print('第一次打印:',d...
Python
zaydzuhri_stack_edu_python
function open self begin set port = name set timeout = ser_rtimeout set write_timeout = ser_wtimeout set inter_byte_timeout = ser_itimeout set parity = ser_parity set baudrate = ser_baudrate set bytesize = ser_bytesize set stopbits = ser_stopbits set xonxoff = ser_xonxoff set dsrdtr = ser_dsrdtr set rtscts = ser_rtscts...
def open(self): self.serial.port = self.name self.serial.timeout = self.ctrl_client.ser_rtimeout self.serial.write_timeout = self.ctrl_client.ser_wtimeout self.serial.inter_byte_timeout = self.ctrl_client.ser_itimeout self.serial.parity = self.ctrl_client.ser_parity self.serial.baudrate = self.c...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Jan 23 11:31:12 2020 @author: thomas comment Power/Recovery: Qualitative Figure comment We will be showing the power and recovery locations for swimmers of different Re comment We can either show it using v_CM or by showing y_CM. What wil...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 23 11:31:12 2020 @author: thomas """ #Power/Recovery: Qualitative Figure #We will be showing the power and recovery locations for swimmers of different Re #We can either show it using v_CM or by showing y_CM. What will be used is tbd #Power/Recover...
Python
zaydzuhri_stack_edu_python
function get_team_info self id begin set params = dict string key key ; string start_at_team_id id ; string teams_requested 1 set r = get requests TEAM_URL params=params return call TeamResponse json r at string result at string teams at 0 end function
def get_team_info(self, id): params = {'key': self.key, 'start_at_team_id': id, 'teams_requested': 1} r = requests.get(self.TEAM_URL, params=params) return TeamResponse(r.json()['result']['teams'][0])
Python
nomic_cornstack_python_v1
function list_nodes_full conn=none call=none begin string Return a list of VMs with all the information about them CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack if call == string action begin raise call SaltCloudSystemExit string The list_nodes_full function must be called with -f or --func...
def list_nodes_full(conn=None, call=None): ''' Return a list of VMs with all the information about them CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function mus...
Python
jtatman_500k
comment !/usr/bin/env python comment _*_ coding: utf-8 _*_ string Problem: Find the sum of the digits in the number 100! function factors n begin if n == 1 begin return n end else begin return n * call factors n - 1 end end function function sum_of_factors n begin return sum list comprehension integer c for c in string...
#!/usr/bin/env python # _*_ coding: utf-8 _*_ """ Problem: Find the sum of the digits in the number 100! """ def factors(n): if n == 1: return n else: return n * factors(n-1) def sum_of_factors(n): return sum([int(c) for c in str(factors(n)) if c.isdigit()])
Python
zaydzuhri_stack_edu_python
function find_donor name begin for donor in donor_db begin comment do a case-insensitive compare if lower strip name == lower donor at 0 begin return donor end end return none end function
def find_donor(name): for donor in OO_mailroom.Donor.donor_db: # do a case-insensitive compare if name.strip().lower() == donor[0].lower(): return donor return None
Python
nomic_cornstack_python_v1
function as_bullets value options=string begin if options == string begin set max = 10 end else begin set tokens = split options string , set max = integer tokens at 0 end set one = string <i class="fas fa-circle fa-xs" title="%d"></i> % value set blank = string <i class="fas fa-circle fa-xs blank" title="%d"></i> % v...
def as_bullets(value, options=''): if options == '': max = 10 else: tokens = options.split(',') max = int(tokens[0]) one = '<i class="fas fa-circle fa-xs" title="%d"></i>'%(value) blank = '<i class="fas fa-circle fa-xs blank" title="%d"></i>'%(value) x = 0 res = '' wh...
Python
nomic_cornstack_python_v1
function user_agent name version begin string Return User-Agent ~ "name/version language/version interpreter/version os/version". function _interpreter begin set name = call python_implementation set version = call python_version set bitness = call architecture at 0 if name == string PyPy begin set version = join strin...
def user_agent(name, version): """Return User-Agent ~ "name/version language/version interpreter/version os/version".""" def _interpreter(): name = platform.python_implementation() version = platform.python_version() bitness = platform.architecture()[0] if name == 'PyPy': ...
Python
jtatman_500k
function naive_primality integer begin set prime = true if integer <= 1 begin set prime = false end else begin for i in range 2 integer begin if integer % i == 0 begin set prime = false end end end return prime end function
def naive_primality(integer): prime = True if integer <= 1: prime = False else: for i in range(2, integer): if integer % i == 0: prime = False return prime
Python
nomic_cornstack_python_v1
function setUp self begin set client = call Client set user = call create_user string testuser string test@user.com string q2w3E$R% set meter = call create meter_name=string testmeter meter_unit=string X save set reading = call create meter=meter reading=100 date=call date remark=string test reading save end function
def setUp(self): self.client = Client() self.user = User.objects.create_user('testuser', 'test@user.com', 'q2w3E$R%') self.meter = Meter.objects.create(meter_name='testmeter', meter_unit='X') self.meter.save() reading = Reading.objects.create(meter=self.meter, ...
Python
nomic_cornstack_python_v1
function from_tibiadata cls content begin string Builds a character object from a TibiaData character response. Parameters ---------- content: :class:`str` The JSON content of the response. Returns ------- :class:`Character` The character contained in the page, or None if the character doesn't exist Raises ------ Inval...
def from_tibiadata(cls, content): """Builds a character object from a TibiaData character response. Parameters ---------- content: :class:`str` The JSON content of the response. Returns ------- :class:`Character` The character contained i...
Python
jtatman_500k
comment Importing Modules import pygame , random , time , os , sys from pygame.locals import * call init comment Set-Up - Dimensions, Fullscreen, caption, time set screen = call set_mode tuple 1920 1080 FULLSCREEN call set_caption string Faction Wars set clock = call Clock comment Images set playerImg = load image join...
##Importing Modules import pygame, random, time, os, sys from pygame.locals import * pygame.init() #Set-Up - Dimensions, Fullscreen, caption, time screen = pygame.display.set_mode((1920, 1080), pygame.FULLSCREEN) pygame.display.set_caption("Faction Wars") clock = pygame.time.Clock() #Images playerImg = pygame.image....
Python
zaydzuhri_stack_edu_python
function step_sample self begin set tuple n p = shape append null_sample at which_var sum set sigma_resid = sigma_resid set quadratic_term = 1.0 / sigma_resid ^ 2 + 1.0 / rough_sigma * sd_inter ^ 2 set sampling_sd = 1.0 / square root quadratic_term set sampling_mean = Y_inter * 1.0 / rough_sigma * sd_inter ^ 2 / quadra...
def step_sample(self): n, p = self.X.shape self.null_sample[self.which_var].append((self._X_j * self.Y_sample).sum()) sigma_resid = self.sigma_resid quadratic_term = 1. / sigma_resid**2 + 1. / (self.rough_sigma * self.sd_inter)**2 sampling_sd = 1. / np.sqrt(quadratic_term) ...
Python
nomic_cornstack_python_v1
from mathematicians import simple_get import matplotlib.pyplot as plt import numpy as np import pandas as pd import re import threading function read_data name variables begin string Reads the csv file under the 'name' and places it into a dataframe Parameters: name of csv file Returns: dataframe set df = read csv name...
from mathematicians import simple_get import matplotlib.pyplot as plt import numpy as np import pandas as pd import re import threading def read_data(name, variables): """ Reads the csv file under the 'name' and places it into a dataframe Parameters: name of csv file Returns: dataframe """ df ...
Python
zaydzuhri_stack_edu_python
function combine self boundingBox begin return boolean end function
def combine(self, boundingBox): return bool()
Python
nomic_cornstack_python_v1
comment !usr/bin/env/python3 from flask import Flask from flask_restful import Api , Resource , reqparse from fuzzywuzzy import process from string import punctuation , whitespace , digits from flask_cors import CORS from redisworks import Root import logging from typing import Dict , List , Set set app = call Flask __...
#!usr/bin/env/python3 from flask import Flask from flask_restful import Api, Resource, reqparse from fuzzywuzzy import process from string import punctuation, whitespace, digits from flask_cors import CORS from redisworks import Root import logging from typing import Dict, List, Set app = Flask(__name__) api = Api(app...
Python
zaydzuhri_stack_edu_python
async function publish self request begin try begin set json_data = dict string name get form string name ; string email get form string email ; string message get form string message ; string digest get form string digest set json_string = dumps json_data set encoded = base64 encode encode json_string string utf-8 set...
async def publish(self, request): try: json_data = {'name': request.form.get('name'), 'email': request.form.get('email'), 'message': request.form.get('message'), 'digest': request.form.get('digest')} json_string ...
Python
nomic_cornstack_python_v1
comment public. function error self value begin comment Input validation in public method should be done first. if is instance value str is true begin set _error = value end else begin raise call _K2hr3UserAgentError format string error should be str, not {} value end end function
def error(self, value: str) -> None: # public. # Input validation in public method should be done first. if isinstance(value, str) is True: self._error = value else: raise _K2hr3UserAgentError( 'error should be str, not {}'.format(value))
Python
nomic_cornstack_python_v1
function parse_ip4_netmask octets begin set size = 0 set index = 0 for octet in octets begin comment ensure no gaps between octets if not index * 8 == size and not octet == 0 begin return false end set index = index + 1 if octet == 255 begin set size = size + 8 end else if octet == 254 begin set size = size + 7 end els...
def parse_ip4_netmask(octets): size = 0 index = 0 for octet in octets: # ensure no gaps between octets if not index * 8 == size and not octet == 0: return False index += 1 if octet == 255: size += 8 elif octet == 254: size += 7 ...
Python
nomic_cornstack_python_v1
import sys import math from PyQt5.QtWidgets import QWidget , QLabel , QLineEdit , QPushButton , QComboBox , QApplication class Example extends QWidget begin function __init__ self begin call __init__ call initUI end function function initUI self begin set lbl = call QLabel string self set combo = call QComboBox self c...
import sys import math from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, QPushButton, QComboBox, QApplication) class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.lbl = QLabel("", self) self.combo = QComboBox(self) ...
Python
zaydzuhri_stack_edu_python
comment Authors: comment uniqnames: comment Date: comment Purpose: comment Description: import sys import math import csv import measures string Requires: data is a list of numbers Modifies: nothing Effects: returns the average of the numbers in data function mean data begin pass end function string Requires: data is a...
# Authors: # uniqnames: # Date: # Purpose: # Description: import sys import math import csv import measures """ Requires: data is a list of numbers Modifies: nothing Effects: returns the average of the numbers in data """ def mean(data): pass """ Requires: data is a list of numbers Modifies: nothing Effects: retur...
Python
zaydzuhri_stack_edu_python
function _get_igraph G edge_weights=none node_weights=none begin if type edge_weights == str begin set edge_weights = list edge_weights end if type node_weights == str begin set node_weights = list node_weights end set G = copy G set G = call convert_node_labels_to_integers G set Gig = call Graph directed=true call add...
def _get_igraph(G, edge_weights=None, node_weights=None): if type(edge_weights) == str: edge_weights = [edge_weights] if type(node_weights) == str: node_weights = [node_weights] G = G.copy() G = nx.relabel.convert_node_labels_to_integers(G) Gig = ig.Graph(directed=True) G...
Python
nomic_cornstack_python_v1
function load_docker_cache tag docker_registry begin string Imports tagged container from the given docker registry if docker_registry begin comment noinspection PyBroadException try begin import docker_cache info string Docker cache download is enabled from registry %s docker_registry call load_docker_cache registry=d...
def load_docker_cache(tag, docker_registry) -> None: """Imports tagged container from the given docker registry""" if docker_registry: # noinspection PyBroadException try: import docker_cache logging.info('Docker cache download is enabled from registry %s', docker_registr...
Python
jtatman_500k
function name self begin return _name end function
def name(self): return self._name
Python
nomic_cornstack_python_v1
function writeFitsHeader filename model inc pa azi begin set tuple data header = call getdata filename header=true set header at string DISTANCE = tuple distance string Distance in parsec. set header at string CHEMMOD = tuple split fn string / at - 1 string Chemical model used. set header at string INC = tuple inc stri...
def writeFitsHeader(filename, model, inc, pa, azi): data, header = fits.getdata(filename, header=True) header['DISTANCE'] = model.distance, 'Distance in parsec.' header['CHEMMOD'] = model.header.fn.split('/')[-1], 'Chemical model used.' header['INC'] = inc, 'Inclianation in radians.' header['PA'] = ...
Python
nomic_cornstack_python_v1
class Solution begin function calculateMinimumHP self dungeon begin string :type dungeon: List[List[int]] :rtype: int if not dungeon begin return 0 end set rowLen = length dungeon set colLen = length dungeon at 0 set minReq = list 1 * colLen comment minReq = [[1]*colLen]*rowLen comment print (minReq) comment store mini...
class Solution: def calculateMinimumHP(self, dungeon): """ :type dungeon: List[List[int]] :rtype: int """ if not dungeon: return 0 rowLen = len(dungeon) colLen = len(dungeon[0]) minReq = [1]*colLen #minReq = [[1]*colLen]*rowLen ...
Python
zaydzuhri_stack_edu_python
function findAndSubtractBackground self radius offset iterations skipLimit begin set imp = call getImage set ip = call getProcessor set width = call getWidth set height = call getHeight set stats = call getStatistics set histogram = call histogram set ratio = histogram at 0 / width * height * 1.0 if ratio > skipLimit b...
def findAndSubtractBackground(self, radius, offset, iterations, skipLimit): imp = IJ.getImage() ip = imp.getProcessor() width = imp.getWidth() height = imp.getHeight() stats = imp.getStatistics() histogram = stats.histogram() ratio = histogram[0] / ((width * heigh...
Python
nomic_cornstack_python_v1
function common a b c begin set res = list for i in list set a begin if i in b and i in c begin append res i end end return res end function set a = list 1 5 10 20 40 80 20 set b = list 6 7 20 80 100 set c = list 3 4 15 20 30 70 80 120 print call common a b c
def common(a,b,c): res = [] for i in list(set(a)): if i in b and i in c: res.append(i) return res a = [1,5,10,20,40,80,20] b = [6,7,20,80,100] c = [3,4,15,20,30,70,80,120] print(common(a,b,c))
Python
zaydzuhri_stack_edu_python
function destroy self begin call destroy self comment iterates over the complete set of associated streams to close comment them as the parser is now going to be destroyed and they cannot comment be reached any longer (invalidated state) set streams = values legacy streams for stream in streams begin close stream end s...
def destroy(self): parser.Parser.destroy(self) # iterates over the complete set of associated streams to close # them as the parser is now going to be destroyed and they cannot # be reached any longer (invalidated state) streams = netius.legacy.values(self.streams) ...
Python
nomic_cornstack_python_v1
function save_numpy_array_to_csv template l data begin comment Create the file path of the results file set fp_r_f = call create_fp_file template l string r comment Write the data to the results file call savetxt fp_r_f data delimiter=string , print format string {}.csv saved l return end function
def save_numpy_array_to_csv( template, l: str, data: numpy.array, ) -> None: # Create the file path of the results file fp_r_f = create_fp_file(template, l, "r") # Write the data to the results file numpy.savetxt(fp_r_f, data, delimiter = ",") print("{}.csv saved".form...
Python
nomic_cornstack_python_v1
import functools import itertools import logging from operator import or_ from typing import Tuple , Any , Callable , Union from bases.mixins import BinaryOp from bases.util import type_checking comment TODO class ParsingError extends Exception begin pass end class class Parser extends object begin function __init__ se...
import functools import itertools import logging from operator import or_ from typing import Tuple, Any, Callable, Union from bases.mixins import BinaryOp from bases.util import type_checking # TODO class ParsingError(Exception): pass class Parser(object): def __init__(self, fn=None): self.fn = fn ...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment Day 10 - Elves Look, Elves Say import re , itertools set gs = compile string ((\d)(?:\2*)) function gen_seq inpt begin while true begin set inpt = join string generator expression string length seq + ch for tuple seq ch in find all inpt yield inpt end end function function main be...
#! /usr/bin/env python # Day 10 - Elves Look, Elves Say import re, itertools gs = re.compile(r'((\d)(?:\2*))') def gen_seq(inpt): while True: inpt = ''.join(str(len(seq)) + ch for seq, ch in gs.findall(inpt)) yield inpt def main(): for index, result in enumerate(itertools.islice(gen_seq('3113322113'), 50)): ...
Python
zaydzuhri_stack_edu_python
function plusMinus arr begin set ap = list comprehension i for i in arr if i > 0 set an = list comprehension i for i in arr if i < 0 set az = list comprehension i for i in arr if i == 0 set apl = decimal length ap set anl = decimal length an set azl = decimal length az set arrl = decimal length arr print apl / arrl pri...
def plusMinus(arr): ap = [i for i in arr if i > 0] an = [i for i in arr if i < 0] az = [i for i in arr if i == 0] apl = float(len(ap)) anl = float(len(an)) azl = float(len(az)) arrl = float(len(arr)) print(apl / arrl) print(anl / arrl) print(azl / arrl) """ LIST = [0, None, 2, ...
Python
zaydzuhri_stack_edu_python
function __init__ self begin call __init__ self call subscribe _eventGen _wakeUp self end function
def __init__(self): Strategy.__init__(self) event.subscribe(self._eventGen, _(self)._wakeUp, self)
Python
nomic_cornstack_python_v1
comment __author__ = 'sergejyurskyj' comment # NOTE: in the following, you must use "dbm" instead of "anydbm" comment # in Python 3.X (this module was renamed in 3.X only). Also note comment # that these are incomplete, partial examples as is. comment """ comment import anydbm comment file = anydbm.open("filename") # L...
# __author__ = 'sergejyurskyj' # # # # NOTE: in the following, you must use "dbm" instead of "anydbm" # # in Python 3.X (this module was renamed in 3.X only). Also note # # that these are incomplete, partial examples as is. # """ # import anydbm # file = anydbm.open("filename") # Link to file # file['key'] = 'data...
Python
zaydzuhri_stack_edu_python
function train self num_epochs=10 train_relative=0.95 begin set tuple xx yy = call load_training_data comment reshape for non-LSTM-like input comment xx = xx.reshape((xx.shape[0], -1)) comment split into x and y, train and test sets set train_size = integer length xx * train_relative set x_train = xx at slice : train_...
def train(self, num_epochs: int = 10, train_relative: float = 0.95) -> None: xx, yy = self.load_training_data() # reshape for non-LSTM-like input # xx = xx.reshape((xx.shape[0], -1)) # split into x and y, train and test sets train_size = int(len(xx) * train_relative) x...
Python
nomic_cornstack_python_v1
function set_default_tick self tick=0 begin comment make sure the tick value is within range if 0 <= tick < length _ticklist begin call set_tick tick set _tick_default = tick comment TODO not sure if this is needed any more set _handle_default = _handle_pos end else begin raise call ValueError string The tick value is ...
def set_default_tick(self, tick=0): if 0 <= tick < len(self._ticklist): # make sure the tick value is within range self.set_tick(tick) self._tick_default = tick self._handle_default = self._handle_pos # TODO not sure if this is needed any more else: rais...
Python
nomic_cornstack_python_v1
function trainAndTune self trainingData trainingLabels validationData validationLabels Cgrid begin string *** YOUR CODE HERE *** end function comment Begin timer
def trainAndTune(self, trainingData, trainingLabels, validationData, validationLabels, Cgrid): "*** YOUR CODE HERE ***" # Begin timer
Python
nomic_cornstack_python_v1
function test_interface_addresses bf sot begin set interface_props = call frame for tuple _ row in call iterrows begin set interface_name = interface if not row at string Active or row at string Access_VLAN or row at string Description == string [type=ISP] or interface_name in INTERFACES_WITHOUT_ADDRESS begin continue ...
def test_interface_addresses(bf: Session, sot: SoT) -> None: interface_props = bf.q.interfaceProperties(nodes=SNAPSHOT_NODES_SPEC).answer().frame() for _, row in interface_props.iterrows(): interface_name = row["Interface"].interface if not row["Active"] or \ row["Access_VLAN"] ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 function main begin set limit = 100 set ways = list comprehension 0 for _ in range limit + 1 set ways at 0 = 1 for n in range 1 limit begin for m in range n limit + 1 begin set ways at m = ways at m + ways at m - n end end print ways at 100 end function if __name__ == string __main__ begin...
#!/usr/bin/env python3 def main(): limit = 100 ways = [0 for _ in range(limit + 1)] ways[0] = 1 for n in range(1, limit): for m in range(n, limit + 1): ways[m] += ways[m - n] print(ways[100]) if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
function plot self *args **kwargs begin if plotter is none begin raise call NotImplementedError string This NDCube object does not have a .plotter defined so no default plotting functionality is available. end return plot *args keyword kwargs end function
def plot(self, *args, **kwargs): if self.plotter is None: raise NotImplementedError( "This NDCube object does not have a .plotter defined so " "no default plotting functionality is available.") return self.plotter.plot(*args, **kwargs)
Python
nomic_cornstack_python_v1
function forward self datax datay Ns Nc Nq total_classes begin set k = shape at 0 set K = random choice total_classes Nc replace=false set Query_x = tensor if gpu begin set Query_x = cuda Query_x end set Query_y = list set Query_y_count = list set centroid_per_class = dict set class_label = dict set label_encoding ...
def forward(self, datax, datay, Ns, Nc, Nq, total_classes): k = total_classes.shape[0] K = np.random.choice(total_classes, Nc, replace=False) Query_x = torch.Tensor() if(self.gpu): Query_x = Query_x.cuda() Query_y = [] Query_y_count = [] centroid_per_c...
Python
nomic_cornstack_python_v1
comment 用于计算两个数的和 string def sum(x,y): """ 用于计算两个数的和""" return x + y sum2 = lambda x,y:x+y print(sum(1,2)) print(sum2(1,9)) print(sum2) # 通过lambda表达式简化代码 # lambda 可以所谓一个函数的参数 def go_home(callback): print("开始执行") callback(); print("完成执行") # fn = lambda : print("lmbda函数") go_home(lambda : print("lmbda函数")) string def max...
# 用于计算两个数的和 ''' def sum(x,y): """ 用于计算两个数的和""" return x + y sum2 = lambda x,y:x+y print(sum(1,2)) print(sum2(1,9)) print(sum2) # 通过lambda表达式简化代码 # lambda 可以所谓一个函数的参数 def go_home(callback): print("开始执行") callback(); print("完成执行") # fn = lambda : print("lmbda函数") go_home(lambda : print("lmbda函数...
Python
zaydzuhri_stack_edu_python
function onZoomOut self event begin call zoomOut event end function
def onZoomOut(self, event): self.plotter.zoomOut(event)
Python
nomic_cornstack_python_v1
function PlotBayes2D bayes=list dev=list N_bayes=1 x=list y=list xlabel=string ylabel=string P_min=1e-05 graphs=false plane=false ax=none posterior=false begin if ax is none begin set tuple fig ax = call subplots end if posterior begin set P_label = string P/P_{\rm max} end else begin set P_label = string \mathca...
def PlotBayes2D( bayes=[], dev=[], N_bayes=1, x=[], y=[], xlabel='', ylabel='', P_min=1e-5, graphs=False, plane=False, ax=None, posterior=False ): if ax is None: fig, ax = plt.subplots() if posterior: P_label = r"P/P_{\rm max}" else: P_label = r"\mathcal{B}/\mathcal{B}_{\rm...
Python
nomic_cornstack_python_v1
function __init__ self amount date receipt place preturi bunuri begin set __amount = call __parse_data amount set __date = date set __receipt = call __parse_data receipt set __place = list call __parse_data place at 0 set __preturi = call __parse_data preturi set __bunuri = call __parse_data bunuri set __completa = cal...
def __init__(self, amount, date, receipt, place, preturi, bunuri): self.__amount = Data.__parse_data(amount) self.__date = date self.__receipt = Data.__parse_data(receipt) self.__place = [Data.__parse_data(place)[0]] self.__preturi = Data.__parse_data(preturi) self.__bunu...
Python
nomic_cornstack_python_v1
function time_stats df begin print string Calculating The Most Frequent Times of Travel... set start_time = time comment TO DO: display the most common month set popular_month = mode at 0 set popular_month_name = valid_month at popular_month print format string The most common month in dataset is {} popular_month_name ...
def time_stats(df): print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # TO DO: display the most common month popular_month = df['month'].mode()[0] popular_month_name = valid_month[popular_month] print("The most common month in dataset is {}".format(popu...
Python
nomic_cornstack_python_v1
import turtle call speed 5 call bgcolor string black call pencolor string white call penup comment setting start pos call left 135 call forward 60 call right 90 comment Start A fill call pendown call forward 60 call right 45 call forward 85 call left 45 call forward 60 call left 135 call forward 170 call left 45 call f...
import turtle turtle.speed(5) turtle.bgcolor("black") turtle.pencolor("white") turtle.penup() #setting start pos turtle.left(135) turtle.forward(60) turtle.right(90) #Start A fill turtle.pendown() turtle.forward(60) turtle.right(45) turtle.forward(85) turtle.left(45) turtle.forward(60) turtle.left(135) turtle.forwa...
Python
zaydzuhri_stack_edu_python
function update self begin string Calculate the smoothing parameter value. The following example is explained in some detail in module |smoothtools|: >>> from hydpy.models.dam import * >>> parameterstep() >>> highestremotedischarge(1.0) >>> highestremotetolerance(0.0) >>> derived.highestremotesmoothpar.update() >>> fro...
def update(self): """Calculate the smoothing parameter value. The following example is explained in some detail in module |smoothtools|: >>> from hydpy.models.dam import * >>> parameterstep() >>> highestremotedischarge(1.0) >>> highestremotetolerance(0.0) ...
Python
jtatman_500k
import requests import re import logging from pyquery import PyQuery as pq import json import icalendar import datetime import pytz import hashlib import getpass comment init a basic output in terminal call basicConfig set s = call session set CLASS_LENGTH = time delta minutes=45 set CLASS = dict 0 time delta hours=8 m...
import requests import re import logging from pyquery import PyQuery as pq import json import icalendar import datetime import pytz import hashlib import getpass logging.basicConfig() # init a basic output in terminal s = requests.session() CLASS_LENGTH = datetime.timedelta(minutes=45) CLASS = { 0: datetime.tim...
Python
zaydzuhri_stack_edu_python
import csv from sys import argv set filename = argv at 1
import csv from sys import argv filename = argv[1]
Python
zaydzuhri_stack_edu_python
function insert value heap begin append heap value call bubble_up heap length heap - 1 end function
def insert(value: Node, heap: List[Node]) -> None: heap.append(value) bubble_up(heap, len(heap) - 1)
Python
nomic_cornstack_python_v1
comment Funções function verifica_gabarito prova gabarito begin set respostas_aluno = list prova set respostas_corretas = list gabarito set acertos = 0 for i in range length respostas_aluno begin if respostas_aluno at i == respostas_corretas at i begin set acertos = acertos + 1 end else begin pass end end return acerto...
# Funções def verifica_gabarito(prova , gabarito): respostas_aluno = list(prova) respostas_corretas = list(gabarito) acertos = 0 for i in range(len(respostas_aluno)): if respostas_aluno[i] == respostas_corretas[i]: acertos += 1 else: pass return acertos # Exe...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import talib import numpy as np class trade begin function __init__ self begin set capital = 1 set startcapital = capital set amountbytrade = 0.1 comment {'symbol' : symbol, 'type' : 1, 'nb' : nbbuy, 'price' : price, 'stoploss' : stoploss, 'profit' : profit} se...
#!/usr/bin/env python # -*- coding: utf-8 -*- # import talib import numpy as np class trade(): def __init__(self): self.capital = 1 self.startcapital = self.capital self.amountbytrade = 0.1 self.trade = [] #{'symbol' : symbol, 'type' : 1, 'nb' : nbbuy, 'price' : price, 'stoploss' : stoploss, 'profit' : pr...
Python
zaydzuhri_stack_edu_python
import numpy as np comment 1. linspace, logspace Function comment linspace : 설정한 범위에서 선형적으로 분할한 위치의 값을 출력 comment logspace : 설정한 범위에서 로그로 분할한 위치의 값을 출력 comment linspace comment [ 0. 25. 50. 75. 100.] print linear space 0 100 5 comment logspace comment log10(x1)=2, log10(x2)=3, log10(x3)=4 comment [ 100. 1000. 10000.] p...
import numpy as np # 1. linspace, logspace Function # linspace : 설정한 범위에서 선형적으로 분할한 위치의 값을 출력 # logspace : 설정한 범위에서 로그로 분할한 위치의 값을 출력 # linspace print(np.linspace(0,100,5)) # [ 0. 25. 50. 75. 100.] # logspace # log10(x1)=2, log10(x2)=3, log10(x3)=4 print(np.logspace(2,4,3)) # [ 100. 1000. 10000.] # 2. nump...
Python
zaydzuhri_stack_edu_python
from pid import PID set target_obj_size = 45 class Controller extends object begin function __init__ self drone image_cx image_cy begin set drone = drone set image_cx = image_cx set image_cy = image_cy set h_pid = call PID 0.1 1e-05 0.01 set v_pid = call PID 0.5 1e-05 0.01 set dist_pid = call PID 0.1 1e-05 0.01 end fun...
from pid import PID target_obj_size = 45 class Controller(object): def __init__(self, drone, image_cx, image_cy): self.drone = drone self.image_cx = image_cx self.image_cy = image_cy self.h_pid = PID(0.1, 0.00001, 0.01) self.v_pid = PID(0.5, 0.00001, 0.01) self.dist...
Python
zaydzuhri_stack_edu_python
function extract_substring string start end begin string This function will extract the substring between two given key words if start in string and end in string begin set start_index = find string start + length start set end_index = find string end set extracted_string = string at slice start_index : end_index : re...
def extract_substring(string, start, end): '''This function will extract the substring between two given key words''' if start in string and end in string: start_index = string.find(start) + len(start) end_index = string.find(end) extracted_string = string[start_index:end_index] ...
Python
jtatman_500k
function get_or_create_version_step self begin set version_step_tensor = call _get_version_step if version_step_tensor is none begin set version_step_tensor = call _create_version_step end return version_step_tensor end function
def get_or_create_version_step(self): version_step_tensor = self._get_version_step() if version_step_tensor is None: version_step_tensor = self._create_version_step() return version_step_tensor
Python
nomic_cornstack_python_v1
function Interpret tree begin call set_param jitdriver string trace_limit 25000 set register = call ReturnType set tree = tree set env = map set k = call EndK while 1 begin call jit_merge_point tree=tree env=env k=k register=register if is instance k FinalK begin break end if is instance tree Num begin set tuple regist...
def Interpret(tree): set_param(jitdriver, "trace_limit", 25000) register = ReturnType() tree = tree env = Map() k = EndK() while 1: jitdriver.jit_merge_point(tree=tree, env=env, k=k, register=register) if isinstance(k, FinalK): break if isinstance(tree, p...
Python
nomic_cornstack_python_v1
import random import matplotlib.pyplot as plt from skimage import io from handlers import files_handler as fh from utils.consts import * function get_max_width df begin return max end function function get_max_height df begin return max end function function get_random_images images_names img_num begin set images_index...
import random import matplotlib.pyplot as plt from skimage import io from handlers import files_handler as fh from utils.consts import * def get_max_width(df): return (df["right_x"] - df["left_x"]).max() def get_max_height(df): return (df["bottom_y"] - df["top_y"]).max() def get_random_images(images_nam...
Python
zaydzuhri_stack_edu_python
function make_timeplot df_measure df_prediction begin comment mode = 'confirmed' set mode = string active set df_measure_confirmed = df_measure at mode set colors = Dark24 set n_colors = length colors set fig = figure for tuple i country in enumerate columns begin call add_trace scatter go x=index y=df_measure_confirme...
def make_timeplot(df_measure, df_prediction): # mode = 'confirmed' mode = 'active' df_measure_confirmed = df_measure[mode] colors = px.colors.qualitative.Dark24 n_colors = len(colors) fig = go.Figure() for i, country in enumerate(df_measure_confirmed.columns): fig.add_trace(go.Scatte...
Python
nomic_cornstack_python_v1
function rgb2colspace rgb colspace begin if colspace == string rgb begin return rgb end if colspace == string grey begin set luminance = call rgb2gray rgb comment add back in third channel return luminance at tuple Ellipsis none end raise call ValueError string Unknown colour space "%s" % colspace end function
def rgb2colspace(rgb, colspace): if colspace == 'rgb': return rgb if colspace == 'grey': luminance = rgb2gray(rgb) # add back in third channel return luminance[..., None] raise ValueError('Unknown colour space "%s"' % colspace)
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup function parse_company url begin set content = text set soup = call BeautifulSoup content string html.parser set subceo = find soup string span dict string class string subceo set ceo_inn = none if subceo begin set ceo_inn = get text subceo end return dict string ceo_inn ce...
import requests from bs4 import BeautifulSoup def parse_company(url): content = requests.get(url).text soup = BeautifulSoup(content, 'html.parser') subceo = soup.find('span', {'class': 'subceo'}) ceo_inn = None if subceo: ceo_inn = subceo.get_text() return {'ceo_inn': ceo_inn} name = "...
Python
zaydzuhri_stack_edu_python
import secrets import string from conf import config from random_username.generate import generate_username comment create a random user name function generate_random_username begin return call generate_username SINGLE_USER at 0 end function comment generate a random password function generate_random_password begin set...
import secrets import string from conf import config from random_username.generate import generate_username #create a random user name def generate_random_username(): return generate_username(config.SINGLE_USER)[0] #generate a random password def generate_random_password(): alphabet = string.ascii_lett...
Python
zaydzuhri_stack_edu_python
function create_task self name app revision=none batch_input=none batch_by=none inputs=none description=none run=false disable_batch=false interruptible=true execution_settings=none begin string Creates a task for this project. :param name: Task name. :param app: CWL app identifier. :param revision: CWL app revision. :...
def create_task(self, name, app, revision=None, batch_input=None, batch_by=None, inputs=None, description=None, run=False, disable_batch=False, interruptible=True, execution_settings=None): """ Creates a task for this project. :param n...
Python
jtatman_500k
function makeGaussian size fwhm=3 center=none begin set x = array range 0 size 1 float set y = x at tuple slice : : newaxis if center is none begin set x0 = size // 2 set y0 = size // 2 end else begin set x0 = center at 0 set y0 = center at 1 end return exp - 4 * log 2 * x - x0 ^ 2 + y - y0 ^ 2 / fwhm ^ 2 end functi...
def makeGaussian(size, fwhm = 3, center=None): x = np.arange(0, size, 1, float) y = x[:,np.newaxis] if center is None: x0 = y0 = size // 2 else: x0 = center[0] y0 = center[1] return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / fwhm**2)
Python
nomic_cornstack_python_v1
string Flask Documentation: http://flask.pocoo.org/docs/ Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/ Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/ This file creates your application. from app import app from flask import render_template , request , redirect , url_for , flash from ap...
""" Flask Documentation: http://flask.pocoo.org/docs/ Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/ Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/ This file creates your application. """ from app import app from flask import render_template, request, redirect, url_for, flash f...
Python
zaydzuhri_stack_edu_python
function SizeDistribution self z R dcrit=1.686 dzero=0.0 begin comment Comoving matter density set rho0_m = rho_m_z0 * rho_cgs set M = call Mass R set S = array list comprehension call Variance z RR for RR in R set tuple _M _dlnSdlnM = call central_difference log M at slice - 1 : : - 1 log S at slice - 1 : : - 1 set ...
def SizeDistribution(self, z, R, dcrit=1.686, dzero=0.0): # Comoving matter density rho0_m = self.cosm.rho_m_z0 * rho_cgs M = self.Mass(R) S = np.array([self.Variance(z, RR) for RR in R]) _M, _dlnSdlnM = central_difference(np.log(M[-1::-1]), np.log(S[-1::-1])) ...
Python
nomic_cornstack_python_v1
comment Definition for binary tree with next pointer. class TreeLinkNode extends object begin function __init__ self x begin set val = x set left = none set right = none set next = none end function end class class Solution extends object begin function connect self root begin string :type root: TreeLinkNode :rtype: no...
# Definition for binary tree with next pointer. class TreeLinkNode(object): def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution(object): def connect(self, root): """ :type root: TreeLinkNode :rtype: nothi...
Python
zaydzuhri_stack_edu_python
comment printing hello world set my_name = string sandeep print string Hello world and welcome + my_name + string ! import logging comment set log level set logger = call getLogger __name__ call setLevel DEBUG comment create a file handler set handler = call FileHandler string hello_world_app_logs.log call setLevel DEB...
#printing hello world my_name = "sandeep" print("Hello world and welcome " + my_name + "!") import logging #set log level logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create a file handler handler = logging.FileHandler('hello_world_app_logs.log') handler.setLevel(logging.DEBUG) # create a...
Python
zaydzuhri_stack_edu_python
class Warehouse begin function __init__ self w_name begin set w_name = w_name end function end class class Equipment begin function __init__ self manufacturer model color_mode quantity_wh quantity_office begin set manufacturer = manufacturer set model = model set color_mode = color_mode set quantity_wh = quantity_wh se...
class Warehouse: def __init__(self, w_name: str): self.w_name = w_name class Equipment: def __init__(self, manufacturer: str, model: str, color_mode: str, quantity_wh: int, quantity_office): self.manufacturer = manufacturer self.model = model self.color_mode = color_mode ...
Python
zaydzuhri_stack_edu_python
function wavelet_denoised self image begin set img = call _read_image self image set denoised_image = call denoise_wavelet img sigma=0.1 return denoised_image end function
def wavelet_denoised(self, image): img = Data._read_image(self, image) denoised_image = denoise_wavelet(img, sigma=0.1) return denoised_image
Python
nomic_cornstack_python_v1
function make_random_gaussians_table n_sources param_ranges random_state=none begin string Make a `~astropy.table.Table` containing randomly generated parameters for 2D Gaussian sources. Each row of the table corresponds to a Gaussian source whose parameters are defined by the column names. The parameters are drawn fro...
def make_random_gaussians_table(n_sources, param_ranges, random_state=None): """ Make a `~astropy.table.Table` containing randomly generated parameters for 2D Gaussian sources. Each row of the table corresponds to a Gaussian source whose parameters are defined by the column names. The parameters a...
Python
jtatman_500k
comment -*- coding: utf-8 -*- string Created on Tue Jun 16 15:14:28 2020 @author: sir95 comment module import import pickle import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import time import numpy as np comment mnist 데이터셋 다운로드 후 저장:...
# -*- coding: utf-8 -*- """ Created on Tue Jun 16 15:14:28 2020 @author: sir95 """ # module import import pickle import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import time import numpy as np # mnist 데이터셋 다운로드 후 저장...
Python
zaydzuhri_stack_edu_python
function test_see_all_different_products_handler self begin set tables = list string customers string products string rentals set mongo_drop_table = call DropData tables set result = call drop_table print result try begin set current_dir = get current directory set directory_name = current_dir + string \lesson5\data\ s...
def test_see_all_different_products_handler(self): tables = ['customers', 'products', 'rentals'] mongo_drop_table = mdb.DropData(tables) result = mongo_drop_table.drop_table() print(result) try: current_dir = os.getcwd() directory_name = current_dir + '\\...
Python
nomic_cornstack_python_v1
function run_sync self query language=string ADQL maxrec=none uploads=none begin set q = call QUERY_CLASS baseurl query language=language maxrec=maxrec uploads=uploads return execute q end function
def run_sync(self, query, language="ADQL", maxrec=None, uploads=None): q = self.QUERY_CLASS( self.baseurl, query, language=language, maxrec=maxrec, uploads=uploads) return q.execute()
Python
nomic_cornstack_python_v1
function copy_facemap_roi procfile videofile outputfile=none begin set videodata = item load np procfile allow_pickle=true set videodata at string filenames = list list videofile if outputfile is none begin set outputfile = call splitext videofile at 0 + string _proc.npy end if is file path outputfile begin print strin...
def copy_facemap_roi(procfile, videofile, outputfile=None): videodata = np.load(procfile, allow_pickle=True).item() videodata['filenames'] = [[videofile]] if outputfile is None: outputfile = os.path.splitext(videofile)[0]+'_proc.npy' if os.path.isfile(outputfile): print(f'File {outputf...
Python
nomic_cornstack_python_v1