code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function generate_excerpt self begin if not call is_editable begin raise call Unauthorized string Editing is not allowed end if not call can_generate_excerpt begin raise call Forbidden string Generating excerpt is not allowed in this state. end try begin call generate_excerpt title=form at string excerpt_title end exce...
def generate_excerpt(self): if not self.context.model.is_editable(): raise Unauthorized("Editing is not allowed") if not self.agenda_item.can_generate_excerpt(): raise Forbidden('Generating excerpt is not allowed in this state.') try: self.agenda_item.genera...
Python
nomic_cornstack_python_v1
from gensim.models.keyedvectors import KeyedVectors import numpy as np import networkx as nx import random import math import os import io import Constant comment Path a carpeta con los embeddings set EMBEDDING_FOLDER = EMBEDDING_FOLDER class CrossMatchTestClass begin comment Resultados set _RESULT = RESULTS_FOLDER / s...
from gensim.models.keyedvectors import KeyedVectors import numpy as np import networkx as nx import random import math import os import io import Constant # Path a carpeta con los embeddings EMBEDDING_FOLDER = Constant.EMBEDDING_FOLDER class CrossMatchTestClass: # Resultados _RESULT = Constant.RESULTS_FOL...
Python
zaydzuhri_stack_edu_python
function is_integer j begin return not integer 2 * j % 2 end function
def is_integer(j): return not(int(2*j)%2)
Python
nomic_cornstack_python_v1
function test_image filename x_size=350 y_size=350 begin comment Create image and loop over all pixels set im = call new string RGB tuple x_size y_size set pixels = load im for i in range x_size begin for j in range y_size begin set x = call remap_interval i 0 x_size - 1 1 set y = call remap_interval j 0 y_size - 1 1 c...
def test_image(filename, x_size=350, y_size=350): # Create image and loop over all pixels im = Image.new("RGB", (x_size, y_size)) pixels = im.load() for i in range(x_size): for j in range(y_size): x = remap_interval(i, 0, x_size, -1, 1) y = remap_interval(j, 0, y_size, -1...
Python
nomic_cornstack_python_v1
function b_vs_r r t=0.97 begin set min_b = log 1 - t / log 1 - 0.95 ^ r return min_b end function
def b_vs_r(r, t=.97): min_b = (np.log(1-t))/(np.log(1-.95**r)) return min_b
Python
nomic_cornstack_python_v1
comment -*- coding:UTF-8 -*- function display_message begin string 显示本章学习的内容 print string Yor‘ll learn the 'function'. end function call display_message
# -*- coding:UTF-8 -*- def display_message(): """显示本章学习的内容""" print("Yor‘ll learn the 'function'.") display_message()
Python
zaydzuhri_stack_edu_python
import math from random import random as rand from math import pi as pi import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D set fig = figure set ax = call add_subplot 111 projection=string 3d set X = list set Y = list set Z = list set T = list function plateMotion x y z delta ...
import math from random import random as rand from math import pi as pi import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X=[] Y=[] Z=[] T=[] def plateMotion(x,y,z,delta,n,tstep): n=float(n) delta=float(delta)...
Python
zaydzuhri_stack_edu_python
import random comment Define lists of words set adjectives = list string happy string sad string tired string excited string bored set nouns = list string day string night string morning string afternoon string evening set verbs = list string went string ate string slept string worked string studied comment Generate a ...
import random # Define lists of words adjectives = ['happy', 'sad', 'tired', 'excited', 'bored'] nouns = ['day', 'night', 'morning', 'afternoon', 'evening'] verbs = ['went', 'ate', 'slept', 'worked', 'studied'] # Generate a random sentence sentence = random.choice(adjectives) + ' ' + random.choice(nouns) + ' ' + random...
Python
jtatman_500k
import pandas as pd import os from sklearn.utils import shuffle function xlsx_to_csv_pd excel_path csv_path begin set data_xls = call read_excel excel_path encoding=string utf-8 set labels = data_xls at string cluster_name set label_uni = unique set num_class = size print num_class set label_map = dictionary comprehens...
import pandas as pd import os from sklearn.utils import shuffle def xlsx_to_csv_pd(excel_path,csv_path): data_xls = pd.read_excel(excel_path,encoding='utf-8') labels = data_xls['cluster_name'] label_uni = labels.unique() num_class = label_uni.size print(num_class) label_map = {label: ind for ind, label in enumera...
Python
zaydzuhri_stack_edu_python
function to_list bits begin set positions = list for r in range 8 begin for c in range 8 begin set mask = call pos_mask r c if bits ? mask > 0 begin append positions call Position r c end end end return positions end function
def to_list(bits: int) -> list[Position]: positions = [] for r in range(8): for c in range(8): mask = pos_mask(r, c) if bits & mask > 0: positions.append(Position(r, c)) return positions
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: UTF-8 -*- string 1、学习怎样使用python中的“with” string 2、demo:一个商店,例如沃尔玛,要求建立一个信息系统,这个系统可以查询到商店的员工信息和商品信息。 每个员工有一些像id、name、age等这样的信息,每个商品也要求有一些属性信息。当用户打开系统,他们可以 查询员工和商品信息。用户输入id,系统就返回员工或者商品的信息。
#!/usr/bin/python # -*- coding: UTF-8 -*- """ 1、学习怎样使用python中的“with” """ """ 2、demo:一个商店,例如沃尔玛,要求建立一个信息系统,这个系统可以查询到商店的员工信息和商品信息。 每个员工有一些像id、name、age等这样的信息,每个商品也要求有一些属性信息。当用户打开系统,他们可以 查询员工和商品信息。用户输入id,系统就返回员工或者商品的信息。 """
Python
zaydzuhri_stack_edu_python
function zip arrays depth_limit=none begin import awkward import vector import vector.backends.awkward if not is instance arrays dict begin raise call TypeError string argument passed to vector.zip must be a dictionary end set tuple is_momentum dimension names columns = call _check_names arrays list keys arrays set beh...
def zip(arrays: dict[str, typing.Any], depth_limit: int | None = None) -> typing.Any: import awkward import vector import vector.backends.awkward if not isinstance(arrays, dict): raise TypeError("argument passed to vector.zip must be a dictionary") is_momentum, dimension, names, columns =...
Python
nomic_cornstack_python_v1
function convert_dict_of_lists_to_df time_dict begin return call DataFrame time_dict end function
def convert_dict_of_lists_to_df(time_dict): return pd.DataFrame(time_dict)
Python
nomic_cornstack_python_v1
class Humano begin string Esta es la clase Humano exige atributos nombreEntrada: Hace referencia al nombre del usuario edadEntrada: Hace referencia al edad del usuario estaturaEntrada: Hace referencia al estatura del usuario Tiene las siguientes acciones: *hablar(mensaje): dado un mensaje lo muestra en pantalla *mostra...
class Humano (): ''' Esta es la clase Humano exige atributos nombreEntrada: Hace referencia al nombre del usuario edadEntrada: Hace referencia al edad del usuario estaturaEntrada: Hace referencia al estatura del usuario Tiene las siguientes acciones: *hablar(mensaje): ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string LearningFluentyPython.Delegate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Delegate.py :copyright: (c) 2018 by Raymond. :last modified by 2018-07-03 15:35:41 class Proxy begin function __init__ self obj begin set _obj = obj end function function __getattr__ self name begin return get attribute _...
# -*- coding: utf-8 -*- """ LearningFluentyPython.Delegate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Delegate.py :copyright: (c) 2018 by Raymond. :last modified by 2018-07-03 15:35:41 """ class Proxy: def __init__(self, obj): self._obj = obj def __getattr__(self, name): return get...
Python
zaydzuhri_stack_edu_python
function Mean_Radius ClusterResults begin return mean np list comprehension call average Size95X weights=Members for CR in ClusterResults end function
def Mean_Radius(ClusterResults): return np.mean([np.ma.average(CR.Size95X, weights=CR.Members) for CR in ClusterResults])
Python
nomic_cornstack_python_v1
function _input_expr self match base begin set tokens = parse self call group 0 set segments = eval tokens return base % call _set_regex *segments end function
def _input_expr(self, match, base): tokens = self.parse(match.group(0)) segments = self.eval(tokens) return base % _set_regex(*segments)
Python
nomic_cornstack_python_v1
import random import discord import json from discord.ext import commands from random import randint comment <== you can change this set Defualt_bot_prefix = string / comment your token set token = string set client = call Bot command_prefix=Defualt_bot_prefix decorator event comment This will tell if the bot is ready...
import random import discord import json from discord.ext import commands from random import randint Defualt_bot_prefix = '/' # <== you can change this token = '' # your token client = commands.Bot(command_prefix=Defualt_bot_prefix) #This will tell if the bot is ready or not: # All events for the bot @c...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sat Nov 25 20:40:23 2017 @author: vpx365 import os from os.path import isdir , isfile , join from pathlib import Path import pandas as pd comment Math import numpy as np import math from scipy.fftpack import fft from scipy import signal from scipy.io import wavfile from s...
# -*- coding: utf-8 -*- """ Created on Sat Nov 25 20:40:23 2017 @author: vpx365 """ import os from os.path import isdir, isfile, join from pathlib import Path import pandas as pd # Math import numpy as np import math from scipy.fftpack import fft from scipy import signal from scipy.io import wavfile from sklearn.de...
Python
zaydzuhri_stack_edu_python
function reset_bd begin call delete_many dict end function
def reset_bd() -> None: COLLECTION.delete_many({})
Python
nomic_cornstack_python_v1
function plot_isoline self level=0.0 n=none tri_alpha=0 begin set hv = call ensure_holoviews if n == - 1 begin set plot = call Path list end else begin set plot = plot n=n tri_alpha=tri_alpha end if is instance level Iterable begin for lvl in level begin set plot = plot * call plot_isoline level=lvl n=- 1 end return pl...
def plot_isoline(self, level=0.0, n=None, tri_alpha=0): hv = ensure_holoviews() if n == -1: plot = hv.Path([]) else: plot = self.plot(n=n, tri_alpha=tri_alpha) if isinstance(level, Iterable): for lvl in level: plot = plot * self.plot_i...
Python
nomic_cornstack_python_v1
function test begin import unittest set tests = call discover string tests run tests end function
def test(): import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
Python
nomic_cornstack_python_v1
function actions self actions begin if actions is none begin raise call ValueError string Invalid value for `actions`, must not be `None` end set _actions = actions end function
def actions(self, actions): if actions is None: raise ValueError("Invalid value for `actions`, must not be `None`") self._actions = actions
Python
nomic_cornstack_python_v1
function type self begin return __type end function
def type(self) -> Union[AssetType, str]: return self.__type
Python
nomic_cornstack_python_v1
function Nu X x begin return length list comprehension 1 for v in X if v > x end function
def Nu(X, x): return len([1 for v in X if v > x])
Python
nomic_cornstack_python_v1
function fails self model begin function _fail_dict msg treatment begin return dict string error_code _error_code ; string inconsistent_variables _var_names ; string error_message msg ; string treatment name end function for treatment in call treatments begin if call _is_defined_for_all model treatment begin set amount...
def fails(self, model): def _fail_dict(msg, treatment): return { 'error_code': self._error_code, 'inconsistent_variables': self._var_names, 'error_message': msg, 'treatment': treatment.name ...
Python
nomic_cornstack_python_v1
function execute context log begin try begin comment Don't run if there were errors or if this is a dry run set ok_to_run = true set dry = false comment return codes from all runs set ret = list comment assume the worst set return_code = 1 if length gear_dict at string errors > 0 begin set ok_to_run = false append ret...
def execute(context, log): try: # Don't run if there were errors or if this is a dry run ok_to_run = True dry = False ret = [] # return codes from all runs return_code = 1 # assume the worst if len(context.gear_dict['errors']) > 0: ok_to_run = False ...
Python
nomic_cornstack_python_v1
function filtered_rows filename operation thread stage begin set data = list for row in call filter_lines filename operation thread stage begin append data row end return data end function
def filtered_rows(filename, operation, thread, stage): data = [] for row in filter_lines(filename, operation, thread, stage): data.append(row) return data
Python
nomic_cornstack_python_v1
function compute_decorr_time sfreq data begin set n_channels = shape at 0 set decorrelation_times = call empty tuple n_channels for j in range n_channels begin set _acf = call _unbiased_autocorr data at tuple j slice : : set zc = diff np call sign _acf != 0 if any zc begin set decorr_time = argument maximum zc + 1 se...
def compute_decorr_time(sfreq, data): n_channels = data.shape[0] decorrelation_times = np.empty((n_channels,)) for j in range(n_channels): _acf = _unbiased_autocorr(data[j, :]) zc = np.diff(np.sign(_acf)) != 0 if np.any(zc): decorr_time = np.argmax(zc) + 1 dec...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment plots SNR for cross-correlation functions with steadily growing window lengths comment starting at 32 seconds (one file) and ending in somewhat around 73 files merged (40 mins) import numpy as np import csv import matplotlib.pyplot as plt import datetime from obspy import UTCDateTi...
# -*- coding: utf-8 -*- # plots SNR for cross-correlation functions with steadily growing window lengths # starting at 32 seconds (one file) and ending in somewhat around 73 files merged (40 mins) import numpy as np import csv import matplotlib.pyplot as plt import datetime from obspy import UTCDateTime from matplot...
Python
zaydzuhri_stack_edu_python
function addTask self script taskId clearMemory=true begin return run script taskId clearMemory end function
def addTask(self, script:str, taskId:int, clearMemory:bool = True): return self.pool.run(script, taskId, clearMemory)
Python
nomic_cornstack_python_v1
function calcular_PuntosClave_Descriptores imagen sigma=1.6 num_intervalos=3 assumed_blur=0.5 ancho_borde_imagen=5 begin set imagen = as type imagen string float32 set imagen_base = call generar_Imagen_Base imagen sigma assumed_blur set numero_octavas = call calcular_Numero_Octavas shape set kernels_gaussianos = call g...
def calcular_PuntosClave_Descriptores(imagen, sigma=1.6, num_intervalos=3, assumed_blur=0.5, ancho_borde_imagen=5): imagen = imagen.astype('float32') imagen_base = generar_Imagen_Base(imagen, sigma, assumed_blur) numero_octavas = calcular_Numero_Octavas(imagen_base.shape) kernels_gaussianos = generar_Ke...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib import matplotlib.pyplot as pyplot import collections import scipy import scipy.stats import scipy.fftpack import struct import subprocess from fractions import gcd from wave import open as open_wave import warnings try begin from IPython.display import Audio end except any begin wa...
import numpy as np import matplotlib import matplotlib.pyplot as pyplot import collections import scipy import scipy.stats import scipy.fftpack import struct import subprocess from fractions import gcd from wave import open as open_wave import warnings try: from IPython.display import Audio except: warnings...
Python
zaydzuhri_stack_edu_python
function get_daily_goals self surface dates begin set iterator = call order_by string day return list comprehension list day average * DJU_TO_KWH * KWH_TO_EUROS * surface for x in iterator end function
def get_daily_goals(self, surface, dates): iterator = DjuDay.objects.filter(day__in=dates).order_by('day') return [ [x.day, x.average * DJU_TO_KWH * KWH_TO_EUROS * surface] for x in iterator ]
Python
nomic_cornstack_python_v1
function clear_flair_templates self subreddit is_link=false begin string Clear flair templates for the given subreddit. :returns: The json response from the server. set data = dict string r call text_type subreddit ; string flair_type if expression is_link then string LINK_FLAIR else string USER_FLAIR return call reque...
def clear_flair_templates(self, subreddit, is_link=False): """Clear flair templates for the given subreddit. :returns: The json response from the server. """ data = {'r': six.text_type(subreddit), 'flair_type': 'LINK_FLAIR' if is_link else 'USER_FLAIR'} return s...
Python
jtatman_500k
function asteriscos n begin set a = n * string string * return a end function set a = call asteriscos n print a
def asteriscos (n): a=n*str("*") return a a=asteriscos(n) print(a)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string Переиндексирует объявления и URL-ы Вход: URL вьюдира или файл «id_file» с id-шниками (перед id гудса должен быть дефис) Выход: ничего (переиндексированные объявления) Нужно помнить, что farpost.ru отдает максимум 180 страниц вьюдира. Если объявлений >9000, то их нужно разбить на час...
#!/usr/bin/env python3 ''' Переиндексирует объявления и URL-ы Вход: URL вьюдира или файл «id_file» с id-шниками (перед id гудса должен быть дефис) Выход: ничего (переиндексированные объявления) Нужно помнить, что farpost.ru отдает максимум 180 страниц вьюдира. Если объявлений >9000, то их нужно разбить на части (напр...
Python
zaydzuhri_stack_edu_python
comment Developed By : NIRANJAN KUMAR G S comment From : INDIA comment Email : niranjan4@outlook.in comment Updated date : 12/sep/2017 from requests import get from bs4 import BeautifulSoup import pandas as pd import re import matplotlib.pyplot as plt comment this is not complete code contact 7019832930 class Webscrape...
# Developed By : NIRANJAN KUMAR G S # From : INDIA # Email : niranjan4@outlook.in # Updated date : 12/sep/2017 from requests import get from bs4 import BeautifulSoup import pandas as pd import re import matplotlib.pyplot as plt ### this is not complete code contact 7019832930 class Webscraper: def __init__(self, u...
Python
zaydzuhri_stack_edu_python
function process cls target begin set result : List at Attr = list for attr in attrs begin set pos = find collections result attr set existing = if expression pos > - 1 then result at pos else none if not existing begin append result attr end else if not is_attribute or is_enumeration begin set help = help or help set...
def process(cls, target: Class): result: List[Attr] = [] for attr in target.attrs: pos = collections.find(result, attr) existing = result[pos] if pos > -1 else None if not existing: result.append(attr) elif not (attr.is_attribute or attr.i...
Python
nomic_cornstack_python_v1
function snyder_opt self structure begin string Calculates Snyder's optical sound velocity (in SI units) Args: structure: pymatgen structure object Returns: Snyder's optical sound velocity (in SI units) set nsites = num_sites set volume = volume set num_density = 1e+30 * nsites / volume return 1.66914e-23 * call long_v...
def snyder_opt(self, structure): """ Calculates Snyder's optical sound velocity (in SI units) Args: structure: pymatgen structure object Returns: Snyder's optical sound velocity (in SI units) """ nsites = structure.num_sites volume = structure.volum...
Python
jtatman_500k
set x = input print upper x at 0 + x at slice 1 : :
x = input() print(x[0].upper() + x[1:])
Python
zaydzuhri_stack_edu_python
import pickle import pygame from game.player.player import Player from game.environment.board import Board from game.player.bullets import ActiveBullets from game.player.health_bar import HealthBar from game.environment.directions import Direction from game.bots.ai_bot import AI_bot import numpy as np function run_trai...
import pickle import pygame from game.player.player import Player from game.environment.board import Board from game.player.bullets import ActiveBullets from game.player.health_bar import HealthBar from game.environment.directions import Direction from game.bots.ai_bot import AI_bot import numpy as np def run_train_A...
Python
zaydzuhri_stack_edu_python
function multiplication number1 number2 begin return number1 * number2 end function
def multiplication(number1, number2): return number1 * number2
Python
nomic_cornstack_python_v1
try begin import os import json import io import urllib.request from robobrowser import RoboBrowser import html end except Exception as err begin print format string Error 101:Import failed {0} err exit 101 end set fromusr = string set tousr = string set topsd = string set b = call RoboBrowser parser=string html.par...
try: import os import json import io import urllib.request from robobrowser import RoboBrowser import html except Exception as err: print("Error 101:Import failed {0}".format(err)) exit(101) fromusr="" tousr="" topsd="" b=RoboBrowser(parser="html.parser") def getURL...
Python
zaydzuhri_stack_edu_python
import numpy as np function kdists matrix k=7 ix=none begin string Returns the k-th nearest distances, row-wise, as a column vector set ix = ix or call kindex matrix k return T end function function kindex matrix k begin string Returns indices to select the kth nearest neighbour set ix = tuple array range length matrix...
import numpy as np def kdists(matrix, k=7, ix=None): """ Returns the k-th nearest distances, row-wise, as a column vector """ ix = ix or kindex(matrix, k) return matrix[ix][np.newaxis].T def kindex(matrix, k): """ Returns indices to select the kth nearest neighbour""" ix = (np.arange(len(matrix...
Python
zaydzuhri_stack_edu_python
function plot_emoji_heatmap df size=tuple 20 5 agg=string from axs=none begin set df_smiley = call agg list string count __custom_smiley_aggregator set ls_smiley = list for x in call itertuples begin for tuple smiley count in _2 begin append ls_smiley tuple Index smiley count end end set df_smiley_reduced = call DataF...
def plot_emoji_heatmap(df, size=(20, 5), agg='from', axs=None): df_smiley = df.groupby(agg)['emojis'].agg(['count', __custom_smiley_aggregator]) ls_smiley = [] for x in df_smiley.itertuples(): for smiley, count in x._2: ls_smiley.append((x.Index, smiley, count)) df_smiley_reduced = p...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- import unittest from q import Casier as CasierStudent from Casier import * from Biere import * import random as rd seed 2019 set nom_biere = list string Jupiler string leffe string Chimay function generateCasier min_value max_value begin set instances = list compr...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import unittest from q import Casier as CasierStudent from Casier import * from Biere import * import random as rd rd.seed(2019) nom_biere=["Jupiler","leffe","Chimay"] def generateCasier(min_value,max_value): instances=[[] for i in range(5)] for i in range(5): ...
Python
zaydzuhri_stack_edu_python
function _params_slice_for_W_zero self params_type begin return call _general_params_slice nemf end function
def _params_slice_for_W_zero(self, params_type): return self._general_params_slice(self.nemf)
Python
nomic_cornstack_python_v1
import datetime import argparse import re import json import time import math import numpy as np function parse_deviation log_name limit=0 begin string Create JSON files in ./dumps directory: 1) log_clients_diff_{lines parsed}.json -- Time difference between requests 2) log_clients_mean_{lines parsed}.json -- Mean valu...
import datetime import argparse import re import json import time import math import numpy as np def parse_deviation(log_name: str, limit=0) -> None: """ Create JSON files in ./dumps directory: 1) log_clients_diff_{lines parsed}.json -- Time difference between requests 2) log_clients_mean_{l...
Python
zaydzuhri_stack_edu_python
import time from tinydb import TinyDB , Query class DatabaseManager begin string A class representing an object used to interact with a local database, to keep track of visitors interacting with the robot set __db : TinyDB function __init__ self begin comment Initialize the database set __db = call TinyDB string ./visi...
import time from tinydb import TinyDB, Query class DatabaseManager(): """ A class representing an object used to interact with a local database, to keep track of visitors interacting with the robot """ __db: TinyDB def __init__(self): # Initialize the database self.__db = TinyDB...
Python
zaydzuhri_stack_edu_python
comment Time: O(n) comment Space: O(n) string Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Exampl...
# Time: O(n) # Space: O(n) """ Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: G...
Python
zaydzuhri_stack_edu_python
function get_node_connection self client_settings node begin set tuple settings timeout = value set cache_key = tuple node client_settings if cache_key not in __connection_cache begin set __connection_cache at cache_key = call ClickhousePool host_name port __user __password __database client_settings=settings send_rece...
def get_node_connection( self, client_settings: ClickhouseClientSettings, node: ClickhouseNode, ) -> ClickhousePool: settings, timeout = client_settings.value cache_key = (node, client_settings) if cache_key not in self.__connection_cache: self.__connection_cache[cache_k...
Python
nomic_cornstack_python_v1
function fix_continuity self continuity begin return call fix_continuity self continuity end function
def fix_continuity(self, continuity): return fix_continuity(self, continuity)
Python
nomic_cornstack_python_v1
function del_tags self tags begin string remove a tag or tags from a symbol Parameters ---------- tags : str or [str,] Tags to be removed comment SQLA Adding a SymbolTag object, feels awkward/uneccessary. comment Should I be implementing this functionality a different way? if is instance tags tuple str unicode begin se...
def del_tags(self, tags): """ remove a tag or tags from a symbol Parameters ---------- tags : str or [str,] Tags to be removed """ # SQLA Adding a SymbolTag object, feels awkward/uneccessary. # Should I be implementing this functiona...
Python
jtatman_500k
import random set sentence = string ManchesterMetropolitanUniversity0123456789|{_@& set size = length sentence set passwords = list set orderedNumbers = list set charList = list sentence
import random sentence = 'ManchesterMetropolitanUniversity0123456789|{_@&' size = len(sentence) passwords = [] orderedNumbers = [] charList = list(sentence)
Python
zaydzuhri_stack_edu_python
function setName self name createNamespace=string False begin pass end function
def setName(self, name, createNamespace='False'): pass
Python
nomic_cornstack_python_v1
function next_collatz n begin if n <= 1 begin raise call ValueError string eular14.next_collatz: n must be a positive integer larger than 1! end else if n % 2 == 0 begin return n // 2 end else begin return 3 * n + 1 end end function
def next_collatz(n): if n <= 1: raise ValueError('eular14.next_collatz: n must be a positive integer larger than 1!') elif n % 2 == 0: return n // 2 else: return (3 * n) + 1
Python
nomic_cornstack_python_v1
function deserialize_model_instance self model_class begin return call from_dictionary request_body end function
def deserialize_model_instance(self, model_class): return model_class.from_dictionary(self.request_body)
Python
nomic_cornstack_python_v1
from tkinter import * import random from tkinter import messagebox function load_card_images card_list begin set suits = list string heart string diamond string club string spade set face_cards = list string king string queen string jack if TkVersion >= 8.6 begin set extension = string png end else begin set extension ...
from tkinter import * import random from tkinter import messagebox def load_card_images(card_list): suits = ['heart', 'diamond', 'club', 'spade'] face_cards= ['king', 'queen', 'jack'] if TkVersion >= 8.6: extension = 'png' else: extension = 'ppm' for suit in suits: ...
Python
zaydzuhri_stack_edu_python
function oauth2_auth_url redirect_uri=none client_id=none base_url=OH_BASE_URL begin if not client_id begin set client_id = call getenv string OHAPI_CLIENT_ID if not client_id begin raise call SettingsError string Client ID not provided! Provide client_id as a parameter, or set OHAPI_CLIENT_ID in your environment. end ...
def oauth2_auth_url(redirect_uri=None, client_id=None, base_url=OH_BASE_URL): if not client_id: client_id = os.getenv('OHAPI_CLIENT_ID') if not client_id: raise SettingsError( "Client ID not provided! Provide client_id as a parameter, " "or set OHAPI_CLIEN...
Python
nomic_cornstack_python_v1
for number in numbers begin if number not in number_counts begin set number_counts at number = 0 end set number_counts at number = number_counts at number + 1 end for tuple number count in items number_counts begin print string { number } - { count } times end
for number in numbers: if number not in number_counts: number_counts[number] = 0 number_counts[number] += 1 for number, count in number_counts.items(): print(f"{number} - {count} times")
Python
zaydzuhri_stack_edu_python
import sys function strToInt s begin set s = strip s if not s begin return 0 end set index = 0 set symbol = true if s at index == string - begin set symbol = false set index = index + 1 end set result = 0 while index < length s begin set num = s at index - string 0 if num < 0 or num > 9 begin return 0 end set result = ...
import sys def strToInt(s): s = s.strip() if not s: return 0 index = 0 symbol = True if s[index] == '-': symbol = False index += 1 result = 0 while index < len(s): num = s[index] - '0' if num < 0 or num > 9: return 0 result = result * 10 + num if result > sys.max: retu...
Python
zaydzuhri_stack_edu_python
from pages.google_home import GoogleHome from tests.base_test import BaseTest class TestGoogleSearch extends BaseTest begin function setup_method self method begin call get_driver method set google_home = call GoogleHome driver call visit end function function teardown_method self _ begin call quit_driver end function ...
from pages.google_home import GoogleHome from tests.base_test import BaseTest class TestGoogleSearch(BaseTest): def setup_method(self, method): self.get_driver(method) self.google_home = GoogleHome(self.driver) self.google_home.visit() def teardown_method(self, _): self.quit_d...
Python
zaydzuhri_stack_edu_python
import unittest import numpy.testing as npt import pb.ball class TestBall extends TestCase begin function testGetPhantomPos self begin comment H <-- B set ball = call Ball 1 0 0.5 set pos = call get_phantom_pos tuple 0 0 call assert_almost_equal pos tuple 2 0 comment H comment ^ comment | comment B set ball = call Ball...
import unittest import numpy.testing as npt import pb.ball class TestBall(unittest.TestCase): def testGetPhantomPos(self): # H <-- B ball = pb.ball.Ball(1,0,0.5) pos = ball.get_phantom_pos((0,0)) npt.assert_almost_equal(pos, (2,0)) # H # ^ # | # B ...
Python
zaydzuhri_stack_edu_python
import json from collections import defaultdict import csv from pathlib import Path set business_data = list set review_data = list comment Path where Rishabh's data is stored print string Reading Business JSON for line_business in open string D:\Courses\18755\yelp_dataset\yelp_academic_dataset_business.json string r...
import json from collections import defaultdict import csv from pathlib import Path business_data = [] review_data = [] # Path where Rishabh's data is stored print("Reading Business JSON") for line_business in open('D:\Courses\\18755\yelp_dataset\yelp_academic_dataset_business.json', 'r', encoding="utf8"): ...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import xlsxwriter comment read file, 按行创建一个列表 set f0 = open string hall0.txt string r encoding=string utf-8 set content_list0 = list comprehension i for i in f0 if string mag in i close f0 set f1 = open string hall1.txt string r encoding=string utf-8 set content_list1 = list comprehension i...
# -*- coding:utf-8 -*- import xlsxwriter # read file, 按行创建一个列表 f0 = open('hall0.txt', 'r', encoding='utf-8') content_list0 = [i for i in f0 if 'mag' in i] f0.close() f1 = open('hall1.txt', 'r', encoding='utf-8') content_list1 = [i for i in f1 if 'mag' in i] f1.close() # 创建一个excel workbook = xlsxwriter.Workbook("hal...
Python
zaydzuhri_stack_edu_python
function gandiva_node_set_adjust self cur_time jobs begin set total_gpu_demands = 0 set nl_gpu_demands = dictionary set nl_gpu_occupied = dictionary for tuple num_gpu node_list in items node_g begin set total_jobs = 0 set occupied_gpus = 0 for node_set in node_list begin set total_jobs = total_jobs + length node_set at...
def gandiva_node_set_adjust(self, cur_time, jobs): total_gpu_demands = 0 nl_gpu_demands = dict() nl_gpu_occupied = dict() for num_gpu, node_list in self.node_g.items(): total_jobs = 0 occupied_gpus = 0 for node_set in node_list: ...
Python
nomic_cornstack_python_v1
string Shared functions/constructs are here. from torch.optim import SGD , lr_scheduler import torch.nn.functional as F from torch import nn function pretrain_optimizers parameters momentum weight_decay lr lars=true begin string If using the LARS optimizer, cosine decay schedule is used. This is a simpler scheduler, dr...
''' Shared functions/constructs are here. ''' from torch.optim import SGD, lr_scheduler import torch.nn.functional as F from torch import nn def pretrain_optimizers(parameters, momentum, weight_decay, lr, lars=True): ''' If using the LARS optimizer, cosine decay schedule is used. This is a simpler...
Python
zaydzuhri_stack_edu_python
from manim import * class SquareToCircle extends Scene begin function construct self begin set circle = call Circle set square = call Square set triangle = call Triangle set text = call Text string Alice set p1 = list - 1 - 1 0 set p2 = list 1 - 1 0 set p3 = list 1 1 0 set p4 = list - 1 1 0 set a = call append_points c...
from manim import * class SquareToCircle(Scene): def construct(self): circle = Circle() square = Square() triangle = Triangle() text = Text("Alice") p1 = [-1, -1, 0] p2 = [1, -1, 0] p3 = [1,1, 0] p4 = [-1, 1, 0] a = Line(p1, p2).append_po...
Python
zaydzuhri_stack_edu_python
function predictions model x_train y_train x_test y_test begin comment Train the model on training data. fit model x_train y_train comment Use the model to predict the test set. set y_pred = predict model x_test comment Create a confusion matrix and write to file. set cm_df = call DataFrame call confusion_matrix y_test...
def predictions(model, x_train, y_train, x_test, y_test): # Train the model on training data. model.fit(x_train, y_train) # Use the model to predict the test set. y_pred = model.predict(x_test) # Create a confusion matrix and write to file. cm_df = pd.DataFrame(metrics.confusion_matrix...
Python
nomic_cornstack_python_v1
comment Without Lambda function high_marks n begin if n >= 60 begin return true end end function set result = list filter high_marks a print result print type result print comment With Lambda set result = list filter lambda n -> n >= 60 a print result print type result
# Without Lambda def high_marks(n): if n >= 60: return True result = list(filter(high_marks,a)) print(result) print(type(result)) print() # With Lambda result = list(filter(lambda n : (n>=60),a)) print(result) print(type(result))
Python
zaydzuhri_stack_edu_python
function getInputSpecification cls begin set inputSpecification = call getInputSpecification call addSub call parameterInputFactory string costID contentType=StringType call addSub call parameterInputFactory string valueID contentType=StringType return inputSpecification end function
def getInputSpecification(cls): inputSpecification = super(ParetoFrontier, cls).getInputSpecification() inputSpecification.addSub(InputData.parameterInputFactory('costID' , contentType=InputTypes.StringType)) inputSpecification.addSub(InputData.parameterInputFactory('valueID', contentType=InputTypes.StringT...
Python
nomic_cornstack_python_v1
function map_objects cls all_objects begin comment Do the object mapping for obj in all_objects begin comment Add the Object to its respective dictionary if id_ begin set id_objects at id_ = obj end else if idref and idref not in idref_objects begin set idref_objects at idref = list obj end else if idref and idref in i...
def map_objects(cls, all_objects): # Do the object mapping for obj in all_objects: # Add the Object to its respective dictionary if obj.id_: cls.id_objects[obj.id_] = obj elif obj.idref and obj.idref not in cls.idref_objects: cls.idref_...
Python
nomic_cornstack_python_v1
function func begin set user_input = input string Enter a string: set vowels = list string a string e string i string o string u set vowel_count = 0 set consonant_count = 0 for char in user_input begin if lower char in vowels begin set vowel_count = vowel_count + 1 end else if is alpha char begin set consonant_count = ...
def func(): user_input = input("Enter a string: ") vowels = ['a', 'e', 'i', 'o', 'u'] vowel_count = 0 consonant_count = 0 for char in user_input: if char.lower() in vowels: vowel_count += 1 elif char.isalpha(): consonant_count += 1 print("The number of vow...
Python
greatdarklord_python_dataset
import numpy as np import cv2 function count_non_singleton_dimension array begin set array_shape = shape set nsd_numerosity = sum generator expression 1 for i in array_shape if i > 1 return nsd_numerosity end function function filter1d_x volume kernel border_type=BORDER_REFLECT_101 begin if length shape != 3 begin rais...
import numpy as np import cv2 def count_non_singleton_dimension(array): array_shape = array.shape nsd_numerosity = sum(1 for i in array_shape if i > 1) return nsd_numerosity def filter1d_x(volume, kernel, border_type = cv2.BORDER_REFLECT_101): if len(volume.shape) != 3: raise ValueError("T...
Python
zaydzuhri_stack_edu_python
function test_range_check begin set filter_ = range 2 4 false true assert not call check 2 assert call check 3 assert call check 4 assert string filter_ == string >2,<=4 set filter_ = range 2 none true true assert not call check 1 assert call check 2 assert string filter_ == string >=2 set filter_ = range 2 none false ...
def test_range_check() -> None: filter_ = Range(2, 4, False, True) assert not filter_.check(2) assert filter_.check(3) assert filter_.check(4) assert str(filter_) == ">2,<=4" filter_ = Range(2, None, True, True) assert not filter_.check(1) assert filter_.check(2) assert str(filter_)...
Python
nomic_cornstack_python_v1
comment Interview Scheduling Problem from constraint import Problem from constraint import AllDifferentConstraint set problem = call Problem comment The possible appointment times are 1, 2, 3 or 4 comment There are four applicants: Ali, Bob, Cyl, and Dan comment Ali is busy from 2 to 3 call addVariable string Ali list ...
# Interview Scheduling Problem from constraint import Problem from constraint import AllDifferentConstraint problem = Problem() # The possible appointment times are 1, 2, 3 or 4 # There are four applicants: Ali, Bob, Cyl, and Dan problem.addVariable('Ali',[1,3,4])# Ali is busy from 2 to 3 problem.addVariable('Dan',[...
Python
zaydzuhri_stack_edu_python
import sys import numpy as np import scipy.sparse.linalg from conditions import Neumann from helpers import central_difference from integrate import integrate from interpolate import calculate_poisson_derivatives , interpolate from nonuniform import has_uniform_steps , liu_coefficients from refine import refine_after ,...
import sys import numpy as np import scipy.sparse.linalg from .conditions import Neumann from .helpers import central_difference from .integrate import integrate from .interpolate import calculate_poisson_derivatives, interpolate from .nonuniform import has_uniform_steps, liu_coefficients from .refine import refine_a...
Python
zaydzuhri_stack_edu_python
for c in tuple 2 n begin if n % c == 0 and n != c begin set cont = cont + 1 end end if cont == 0 begin print string Numero primo end else if cont != 0 begin print string Numero não é primo end
for c in (2, n): if n % c == 0 and n != c: cont = cont + 1 if cont == 0: print('Numero primo') elif cont != 0: print('Numero não é primo')
Python
zaydzuhri_stack_edu_python
from django.test import TestCase comment Create your tests here. set a = list 1 2 3 set b = string 1 set c = 1 print iterate a print iterate b
from django.test import TestCase # Create your tests here. a=[1,2,3] b='1' c=1 print(iter(a)) print(iter(b))
Python
zaydzuhri_stack_edu_python
from itertools import permutations from math import sqrt function is_prime num begin if num < 2 begin return false end for i in range 2 integer square root num + 1 begin if num % i == 0 begin return false end end return true end function function find_prime_permutations num begin set num_str = string num set digits = l...
from itertools import permutations from math import sqrt def is_prime(num): if num < 2: return False for i in range(2, int(sqrt(num)) + 1): if num % i == 0: return False return True def find_prime_permutations(num): num_str = str(num) digits = [int(d) for d in num_str] ...
Python
jtatman_500k
comment -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import datetime from pattern.en import singularize import sys comment sys.path.insert(0,"I:\Projects\finderbuddy") comment sys.path.insert(0,"C:\Users\aman_AV\Desktop\Finder_Buddy\finder_Buddy") comment from msgbox import threshold from...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import datetime from pattern.en import singularize import sys #sys.path.insert(0,"I:\Projects\finderbuddy") #sys.path.insert(0,"C:\Users\aman_AV\Desktop\Finder_Buddy\finder_Buddy") #from msgbox import threshold from .logic_adapter import Logi...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt function get_insights data begin print string Getting insights from KPIs! comment Purchase By Type: ONEOFF_ONLY, INSTALLMENTS_ONLY, BOTH_ONEOFF_INSTALL, NONE_ONEOFF_INSTALL comment This KPI is done here because of it's none number value and later is dropped set data at string PURCHASE_TY...
import matplotlib.pyplot as plt def get_insights(data): print("Getting insights from KPIs!") # Purchase By Type: ONEOFF_ONLY, INSTALLMENTS_ONLY, BOTH_ONEOFF_INSTALL, NONE_ONEOFF_INSTALL # This KPI is done here because of it's none number value and later is dropped data["PURCHASE_...
Python
zaydzuhri_stack_edu_python
for i in item begin if i != temp begin set rs = rs + i end set temp = i end print rs
for i in item: if i != temp: rs += i temp = i print(rs)
Python
zaydzuhri_stack_edu_python
function integral_tangential p_i p_j begin function func s begin return - xc - xa - sin beta * s * sin beta + yc - ya + cos beta * s * cos beta / xc - xa - sin beta * s ^ 2 + yc - ya + cos beta * s ^ 2 end function return call quad lambda s -> call func s 0.0 length at 0 end function
def integral_tangential(p_i, p_j): def func(s): return ( (-(p_i.xc-(p_j.xa-math.sin(p_j.beta)*s))*math.sin(p_i.beta) +(p_i.yc-(p_j.ya+math.cos(p_j.beta)*s))*math.cos(p_i.beta)) /((p_i.xc-(p_j.xa-math.sin(p_j.beta)*s))**2 +(p_i.yc-(p_j.ya+math.cos(p_j.bet...
Python
nomic_cornstack_python_v1
function create_list_node Admonition begin set list_node = type lower __name__ + string list_node tuple generic_list_node General Element dict return list_node end function
def create_list_node(Admonition): list_node = type( Admonition.__name__.lower()+'list_node', (generic_list_node, nodes.General, nodes.Element), {} ) return list_node
Python
nomic_cornstack_python_v1
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data set mnist = call read_data_sets string data/MNIST/ one_hot=true comment mnist data setinde işlem yapmayı sağlayan kütüphane. comment Bu kodla mnisti indirerek işlem yapmaya hazır hale getiriyoruz. comment labeller one hot olarak istendi ...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist= input_data.read_data_sets("data/MNIST/", one_hot=True) #mnist data setinde işlem yapmayı sağlayan kütüphane. # Bu kodla mnisti indirerek işlem yapmaya hazır hale getiriyoruz. #labeller one hot olarak istendi yani 10 uzunluğunda ve...
Python
zaydzuhri_stack_edu_python
function run self begin info string Update the Infos of the Router( + string id + string ) ... 1 call connect_with_remote_system try begin comment Model set model = call _get_router_model comment MAC set mac = call _get_router_mac comment SSID set ssid = call _get_router_ssid comment NetworkInterfaces set interfaces = ...
def run(self): Logger().info("Update the Infos of the Router(" + str(self.router.id) + ") ...", 1) self.network_ctrl.connect_with_remote_system() try: # Model self.router.model = self._get_router_model() # MAC self.router.mac = self._get_router_mac...
Python
nomic_cornstack_python_v1
function run_one_iteration self current_state current_log_pdf begin comment Start the loop over nsamples - this code uses the parallel version of the stretch algorithm set all_inds = array range nchains set inds = all_inds % 2 set accept_vec = zeros tuple nchains comment Separate the full ensemble into two sets, use on...
def run_one_iteration(self, current_state, current_log_pdf): # Start the loop over nsamples - this code uses the parallel version of the stretch algorithm all_inds = np.arange(self.nchains) inds = all_inds % 2 accept_vec = np.zeros((self.nchains, )) # Separate the full ensemble i...
Python
nomic_cornstack_python_v1
function export_model_to_pb model_name_or_path export_path inputs outputs begin set gpu_config = call ConfigProto set allow_growth = true set sess = call Session config=gpu_config set saver = call Saver if is directory path model_name_or_path begin set ckpt_file = call latest_checkpoint model_name_or_path if ckpt_file ...
def export_model_to_pb(model_name_or_path, export_path, inputs: dict, outputs: dict): gpu_config = tf.ConfigProto() gpu_config.gpu_options.allow_growth = True sess = tf.Session(config=gpu_config) saver = tf.train.Saver() if os.path.isdir(model_name_or_path): ckpt_file...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Nov 14 06:27:57 2018 @author: Charan import pandas as pd set transactions = call DataFrame set customerProfile = call DataFrame function inititalizeTransaction_df begin global transactions print string Initalizing the Kitty Bank set dict2 = dict string Custid list 101...
# -*- coding: utf-8 -*- """ Created on Wed Nov 14 06:27:57 2018 @author: Charan """ import pandas as pd transactions = pd.DataFrame() customerProfile = pd.DataFrame() def inititalizeTransaction_df(): global transactions print('Initalizing the Kitty Bank') dict2 = {'Custid':[101,102,103,10...
Python
zaydzuhri_stack_edu_python
set white = string #FFFFFF set nordred = string #BF616A set nordorange = string #D08770 set nordyellow = string #EBCB8B set nordgreen = string #A3BE8C set nordmagenta = string #B48EAD set darkblack = string #2e3440 set nordblack = string #3b4252 set mediumblack = string #434c5e set brightblack = string #4c566a set nord...
white = '#FFFFFF' nordred = '#BF616A' nordorange = '#D08770' nordyellow = '#EBCB8B' nordgreen = '#A3BE8C' nordmagenta = '#B48EAD' darkblack = '#2e3440' nordblack = '#3b4252' mediumblack = '#434c5e' brightblack = '#4c566a' nordwhite = '#d8dee9' brigherwhite = '#e5e9f0' brightestwhite = '#eceff4' nordcyan = '#8fbcbb...
Python
zaydzuhri_stack_edu_python
function post_on_hastebin content begin set post = post string https://hastebin.com/documents data=encode content return string string https://hastebin.com/ + json post at string key end function
def post_on_hastebin(content: str) -> str: post = requests.post("https://hastebin.com/documents", data=content.encode()) return str("https://hastebin.com/" + post.json()["key"])
Python
nomic_cornstack_python_v1
function __init__ self master loop=none begin if loop is none begin set loop = call get_event_loop end set loop = loop set master = master comment Dict with sockets as keys and boolean indicating mute as values set all_sockets = dict set commands = dict string help send_help ; string raw enable_raw ; string unraw disa...
def __init__(self, master, loop=None): if loop is None: loop = asyncio.get_event_loop() self.loop = loop self.master = master # Dict with sockets as keys and boolean indicating mute as values self.all_sockets = {} self.commands = { 'help': self.s...
Python
nomic_cornstack_python_v1
function send self destiny subject context send_image=false img=string begin try begin if length server > 1 begin set server = server at 1 end if length server == 0 begin set server = server at 0 end if send_image begin set img_data = read open img string rb set message = call MIMEMultipart set message at string subjec...
def send(self, destiny, subject, context, send_image=False, img=""): try: if len(self.server) > 1: server = self.server[1] if len(self.server) == 0: server = self.server[0] if send_image: img_data = open(img, 'rb').read() ...
Python
nomic_cornstack_python_v1
function build_ibb_graph_from ea_source sourcenode reachgraph begin set flowgraph = call create_flowgraph_from 4465616 call add_disasm_lines_to_flowgraph flowgraph call write_VCG_File string C:\test.vcg end function
def build_ibb_graph_from( ea_source, sourcenode, reachgraph ): flowgraph = create_flowgraph_from( 0x4423D0 ) add_disasm_lines_to_flowgraph( flowgraph ) flowgraph.write_VCG_File("C:\\test.vcg")
Python
nomic_cornstack_python_v1
function fight self opponent begin if health - call getDamage > 0 begin set health = health - call getDamage print string attack failed. Remaining Health: health return false end else begin print string successful attack return true end end function
def fight(self, opponent): if(self.health - opponent.getDamage() > 0): self.health -= opponent.getDamage() print("attack failed. Remaining Health: ", self.health) return False else: print("successful attack") return True
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Date : 2020-03-15 06:41:38 comment @Author : mutudeh (josephmathone@gmail.com) comment @Link : ${link} comment @Version : $Id$ import os class Solution extends object begin function findRadius self houses heaters begin string :type houses: List[int] :t...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-15 06:41:38 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def findRadius(self, houses, heaters): """ :type houses: List[int] :type heaters: List[int] ...
Python
zaydzuhri_stack_edu_python
function run_call self expanded unexpanded begin if not expanded begin return call errormessage string Needs an object id to call end comment Michel@DC: you should factor the object out of this eval and comment validate it with comment SecurityManager.checkPermission('View', object). comment Also, 'eval' without an nam...
def run_call(self, expanded, unexpanded) : if not expanded : return self.errormessage("Needs an object id to call") # Michel@DC: you should factor the object out of this eval and # validate it with # SecurityManager.checkPermission('View', object). # Also, 'eval' without an namespace qualifying 'in' ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 from typing import List import numpy as np from estimator.models.data_container_base import DataContainer from estimator.models.gaussian_noise import GaussianNoiseModel from estimator.models.line import LineModel class RecordedData extends DataContainer begin function __init__ self noise s...
#!/usr/bin/env python3 from typing import List import numpy as np from estimator.models.data_container_base import DataContainer from estimator.models.gaussian_noise import GaussianNoiseModel from estimator.models.line import LineModel class RecordedData(DataContainer): def __init__(self, noise: GaussianNoiseMo...
Python
zaydzuhri_stack_edu_python