content
stringlengths
5
1.05M
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: # Method 1: hash table: time O(n) space O(n) cache = {} # key of the number which the idx is finding, value is the idx for i, num in enumerate(numbers): if num in cache: return [cache[...
import random def log_normal_value(sigma, mean): """ Log normal distribution is an approximation on the 50th percentile :param sigma: The larger the value, the longer the tail :param mean: The 50th percentile of latencies :return: the log normal value """ return float(round(random.gauss(me...
import torch import torch.nn as nn import torch.nn.functional as F from os import path import os class ConvLBP(nn.Conv3d): """ A 3D convolution layer with fixed binary weights source: https://github.com/dizcza/lbcnn.pytorch/ """ def __init__(self, in_channels, out_channels, kernel_size=3, sparsit...
import logging from django.utils.translation import gettext_lazy as _ from rest_framework import status from rest_framework import viewsets from rest_framework.exceptions import NotFound from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from service import consta...
import os import json from .convert_dataset import convert_dataset def convert_maestro(input_path, output_path): info_filename = os.path.join(input_path, "maestro-v1.0.0.json") with open(info_filename) as file: info = json.load(file) for split in ["train", "validation", "test"]: names = ...
file = open('Street_Centrelines.csv') def tupls(): for line in file: line = line.split(',') output1 = (line[2],line[3],line[6],line[7]) print("tuple of STR_NAME,FULL_NAME,FROM_STR,TO_STR is:",output1) #tupls() def dictionary(): for line in file: line = line.split(',') output2 = zip(line[12],line[0]) pr...
import os import pandas as pd from torchvision.datasets import ImageFolder class Imagenette(ImageFolder): def __init__(self, root, subset='train', csv="noisy_imagenette.csv", **kwargs): data_path = os.path.join(root, subset) super().__init__(data_path, **kwargs) csv_path = os.path.join(ro...
from logging import info import cv2 import numpy as np import matplotlib.pyplot as plt from .TabDetectDewarp import detect_bbox, get_dewarped_table def detect_line(im): ''' Args: im (np.array): input image Returns: dict: { 'address_line_1': [left,top,ri...
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): if not db.dry_run: db.rename_column('key_value', 'system_id', 'obj_id') def backwards(self, orm): if not db.dry_run: db.rena...
import numpy as np def load_csv_test_data(filename): with open(filename, 'r') as input_file: return [[item for item in line.strip().split(',')] for line in input_file] def load_csv_data(filename:str) -> np.ndarray: if not filename.endswith('.csv'): filename += '.csv' with...
## @file ## `metaL`: homoiconic interpreter engine ## (c) Dmitry Ponyatov <<dponyatov@gmail.com>> 2020 MIT ## * homoiconic interpreter engine ## * in-memory object graph database ## * interactive programming system from .core import * from .geo import * from .gui import * from .web import *
"""Machine Learning Detection metrics for single table datasets.""" from sdmetrics.single_table.detection.sklearn import LogisticDetection, SVCDetection __all__ = [ 'LogisticDetection', 'SVCDetection' ]
# Run with nosetests tests/test_cppcheck.py:test_cppcheck from debile.slave.runners.cppcheck import cppcheck, version from debile.slave.wrappers.cppcheck import parse_cppcheck from firehose.model import (Analysis, Generator, Metadata) import lxml.etree import unittest import mock class CppcheckTestCase(unittest.Test...
from .ipn_hand import IPN from .temporal_transform import * from .target_transform import * from .utils import get_dataset_root INPUT_MEAN = (0.485, 0.456, 0.406) INPUT_STD = (0.229, 0.224, 0.225) IPN_HAND_ROOT = get_dataset_root()
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: user_config.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _r...
# -*- coding: utf-8 -*- import time from odoo import api, models, _ from odoo.exceptions import UserError class ReportGeneralLedger(models.AbstractModel): _name = 'report.accounting_pdf_reports.report_generalledger' def _get_account_move_entry(self, accounts, init_balance, sortby, display_account): ...
import os import logging from keras.layers import Dense, Input, MaxPooling2D from keras.layers import Conv2D, Flatten, Lambda, Dropout from keras.layers import Reshape, Conv2DTranspose from keras.models import Model from keras.losses import mse from keras.utils import plot_model from keras import backend as K from date...
import numpy as np import bayesfast as bf import numdifftools as nd bf.utils.random.set_generator(0) rng = bf.utils.random.get_generator() x = rng.normal(size=(50, 4)) def poly_f(x): return ( x[..., 0]**3 - 2 * x[..., 1]**3 + 3 * x[..., 1] * x[..., 2] * x[..., 3] - 4 * x[..., 2]**2 * x[..., 3] + ...
from typing import Sequence from maru.feature.extractor.abstract import IFeatureExtractor from maru.types import FeatureVector, Word class SuffixExtractor(IFeatureExtractor): def __init__(self, sizes: Sequence[int] = range(1, 4)): self._sizes = sorted(sizes) def extract(self, word: Word) -> FeatureV...
import torch.nn as nn import torch.nn.functional as F from base import BaseModel class MnistModel(BaseModel): def __init__(self, num_classes=10): super().__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropo...
# -*- coding: utf-8 -*- '''A module to run the development server.''' from wordfusion import app app.run(debug=True)
""" [5/12/2014] Challenge #162 [Easy] Novel Compression, pt. 1: Unpacking the Data https://www.reddit.com/r/dailyprogrammer/comments/25clki/5122014_challenge_162_easy_novel_compression_pt_1/ # [](#EasyIcon) _(Easy)_: Novel Compression, pt. 1: Unpacking the Data Welcome to this week's Theme Week. We're going to be cre...
import toml snooty = toml.load("scripts/rstspec.toml") snippets = [] for directive in snooty["directive"]: if "example" in snooty["directive"][directive]: print("Working on {}\n\n".format(directive)) # Don't build snippets for devhub-only directives - they're handled elsewhere if str(di...
# Octave example: # [W,s,v] = svd((repmat(sum(x.*x,1), size(x,1),1).*x)*x^1);
from model.group import Group from random import randrange import pytest import random import string def random_string(prefix, maxlen): symbols = string.ascii_letters + string.digits + " "*10 return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) test_data = [ Group(n...
from .UrlParser import TwitchUrlParser from .PlaylistAccessToken import TwitchPlaylist from Core import GlobalExceptions from Services.Utils.WorkerThreads import WorkerThread from Services.Twitch.Gql import TwitchGqlAPI from Services.Twitch.Playback import TwitchPlaybackAccessTokens class Exceptions(GlobalExceptions...
import sys for line in sys.stdin: if line.startswith('#'): print line.strip() else: print line[31:38].strip(), line[38:46].strip(), line[46:54].strip()
# -*- coding: utf-8 -*- class Player: def __init__(self, name): self.name = name self.points = 0 def win_point(self): self.points += 1 def won_with(self, other_player): return self.points >= 4 and other_player.points >= 0 and \ (self.points - other_player.poin...
import numpy as np from ..local_interpolation import ThirdOrderHermitePolynomialInterpolation from .base import AbstractAdaptiveSDESolver, AbstractStratonovichSolver from .runge_kutta import AbstractERK, ButcherTableau _midpoint_tableau = ButcherTableau( a_lower=(np.array([0.5]),), b_sol=np.array([0.0, 1.0])...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.view_form, name='view_form'), url(r'^create_form$', views.create_form, name='create_form'), url(r'^created_form$', views.created_form, name='created_form'), ]
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.or...
#!/usr/bin/python '''_____________________________________________________________________________ ' ' Created By: Kevin M. Albright ' Creation Date: 04.13.2014 ' ' Modified By: Kevin M. Albright ' Last Modified: 04.14.2014 ' ' Assignment: Lab8 ' File Name: albright_lab8.py ' Purpose: Th...
import os if os.environ.get('RUN_ON_DORA'): import dorasl as DoraServerless dora = DoraServerless.Dora() number_of_replicas = 3 number_of_gpu = 1 number_of_cpu = '200m' dora.upload('./', 'home', 'pytest45') dora.sync('./', 'home', 'pytest45', True) # Setup the workload wk = DoraServerless.Workload('my.py...
def f(n,left): if n==1 or n==2: return 1 if n==3: return 2 if n>3 and left==3: return f(3,0)*f(n-3,0) if n>3 and left>3: return f(3,left-2)*f(n-2,left-2)+f(1,0)*f(n-1,left-1) if __name__=='__main__': for step in range(1,11): print '%3d s...
import numpy as np from scipy import optimize as opt import math # Create coefficient tables to solve for equations of state PS_COEFF = np.zeros([10, 10]) PS_COEFF[0][2] = 0.24657688*math.pow(10, 6) PS_COEFF[0][3] = 0.51359951*math.pow(10, 2) PS_COEFF[1][2] = 0.58638965*math.pow(10, 0) PS_COEFF[1][3] = -0.28646939*ma...
import pytest from spacy.attrs import ORTH, LENGTH from spacy.tokens import Doc, Span, Token from spacy.vocab import Vocab from spacy.util import filter_spans from .test_underscore import clean_underscore # noqa: F401 @pytest.fixture def doc(en_tokenizer): # fmt: off text = "This is a sentence. This is anot...
import numpy as np import pyaudio import time, sys, math from collections import deque from src.utils import * class Stream_Reader: """ The Stream_Reader continuously reads data from a selected sound source using PyAudio Arguments: device: int or None: Select which audio stream to read . ...
from pyproj import Proj # Criar um objeto para transformar projeções p = Proj(init='epsg:3857') # código da EPSG para a projeção web mercator (g-maps) # Converter lon/lat para web mercator e o contrário print(p(-97.740372, 30.282642)) print(p(-10880408.440985134, 3539932.820497298, inverse=True))
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class StockQuantityHistory(models.TransientModel): _name = 'stock.quantity.history' _description = 'Stock Quantity History' compute_at_date = fields.Selection([ ...
from flask import Flask, jsonify, request from transformers import pipeline import torch from transformers import PreTrainedTokenizerFast from transformers.models.bart import BartForConditionalGeneration app = Flask(__name__) # use summarize model (pipeline) summarizer = pipeline('summarization') # use kobart model ...
# Go through all downloaded raw texts and convert them to simple text, removing punctuation, etc import utils import unicodedata import os import re from icelandicTextList import icepahcList, sagasList, modernBookList def parseIcelandic(): RAW_FOLDER = "../rawTexts/icelandic/" PARSED_FOLDER = "icelandic/" ...
import platform import subprocess if __name__ == "__main__": print("Running CMake...") if platform.system() == "Windows": subprocess.call("cmake -B build -G \"Visual Studio 16 2019\"") elif platform.system() == "Darwin": subprocess.call("cmake -B build -G Xcode", shell=True) print("CMak...
#!/usr/bin/env python3 from pwn import * PATH = './challenge' def get_offset(): p = process(PATH) c = cyclic(50000) p.sendline(c) p.recvuntil('[check] 0x') check = p.recvline().strip() sequence = unhex(check) # extract cyclic from hex ptr little_endian = u32(sequen...
from flask import render_template, request, redirect, url_for, current_app from pprint import pprint from SPARQLWrapper import SPARQLWrapper, JSON from rdflib import Graph, plugin, URIRef, Literal from rdflib.parser import Parser from rdflib.serializer import Serializer import json import re from . import main @main...
# Generated by Django 3.2.7 on 2022-01-10 12:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('hood', '0006_business'), ] operations = [ migrations.RenameField( model_name='business', old_name='neighbourhood', ...
### Encadenamiento F={'nombre':{'primero':'Juan','segundo':'Marcelo'},'trabajo':['profesor','ingeniero']} print(F) print('nombre') print(F['nombre']['primero']) print(F['nombre']['segundo']) print(F['trabajo']) print(F['trabajo'][0]) print(F['trabajo'][1]) F['trabajo'].append('pintor') print(F) print(F['trabajo'][2])...
# -*- coding: utf-8 -*- """Largest Continuous Sum.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1oYbOWHDKKRyP3AkhohaVPQ1lHngeLMZF """ def large_cont_sum(arr): if len(arr) == 0: return 0 sum = largest_sum = arr[0] current_point =0 ...
from datetime import datetime from celery import shared_task from django.db import connections from scripts.helpers import ordered_query_iterator from capdb.models import * def sync_case_body_cache_for_all_vols(): """ Call sync_case_body_cache_for_vol celery task for each volume """ for volume_id...
#!/usr/bin/python """ Field Robot Event 2014 (ver0 - autonomous landing on heliport sign) usage: ./fre_drone.py <task> """ import sys import datetime import multiprocessing import cv2 import math import numpy as np from pave import PaVE, isIFrame, frameNumber, timestamp, correctTimePeriod, frameEncodedWidth...
# -*- coding: utf-8 -*- ''' https://leetcode.com/problems/add-digits/ ''' class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ if not num: return 0 result = num % 9 if not result: result = 9 r...
import os import pytest from twindb_backup.cache.cache import Cache, CacheException def test_init_raises_exception(): with pytest.raises(CacheException): Cache('foo') def test_in(cache_dir): c = Cache(str(cache_dir)) assert 'bar' not in c cache_dir.mkdir('foo') assert 'foo' in c def...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Dec 20 23:05:15 2018 @author: Thomas Atta-Fosu (attafosu@yahoo.com) """ import pandas as pd import datetime import numpy as np from matplotlib import pylab as plt from matplotlib import dates as mdates from dateutil import relativedelta #%% Recession ...
# # PySNMP MIB module SUN-CLUSTER-EVENTS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUN-CLUSTER-EVENTS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:04:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
import json import asyncio import threading from sanic import Sanic, response from sanic.websocket import WebSocketProtocol from hhagent.meta import BANNER from hhagent.tools import manifest app = Sanic(name='hhagent') async def _consumer_handler(ws): while True: # TODO: do things here interactively ...
#!/usr/bin/env python3 # ******************************************************* # Copyright (c) VMware, Inc. 2020. All Rights Reserved. # SPDX-License-Identifier: MIT # ******************************************************* # * # * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT # * WARRANTIES OR CONDITI...
from shooter.config import LANDSCAPE_PALM from shooter.game_object.landscape import Landscape class Palm(Landscape): """Класс пальмы""" def __init__(self, x, y, image=LANDSCAPE_PALM): super().__init__(x, y, image)
import torch import numpy as np import os import cv2 from LapNet import LAPNet from create_dataset import createDataset from torch.nn import DataParallel from collections import OrderedDict from torch.nn.parameter import Parameter import json import base64 import numpy as np from flask import Flask, request, Respons...
import dolfin as df import numpy as np def make_line_mesh(vertices, cells=None, close_path=False): '''Mesh from data by MeshEditor''' assert vertices.ndim == 2 # Path mesh if cells is None: nvertices = len(vertices) if not close_path: cells = np.array([(i, i+1) for...
import logging import sys from typing import TYPE_CHECKING from grouper import public_key from grouper.ctl.base import CtlCommand from grouper.ctl.util import ensure_valid_username, make_session from grouper.models.audit_log import AuditLog from grouper.models.user import User from grouper.plugin.exceptions import Plu...
from catello.settings.base import * ALLOWED_HOSTS = ["*"] LOGLEVELDEBUG=True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'catello_bot', 'USER': 'bruand', 'PASSWORD': None, 'HOST': 'localhost', 'PORT': 5432, } }
import os import numpy as np import pandas as pd # Paths to text files ROOT_DIR = os.path.join(os.path.dirname(__file__), '..') DATA_DIR = os.path.join(ROOT_DIR, 'data') DATA_PATH = os.path.join(DATA_DIR, 'data.txt') TRAIN_DATA_PATH = os.path.join(DATA_DIR, 'train.txt') TEST_DATA_PATH = os.path.join(DATA_DIR, 'test.t...
from rest_framework import serializers from rest_framework.routers import DefaultRouter from rest_framework.viewsets import ModelViewSet from hc.api.models import Channel class ChannelSerializer(serializers.ModelSerializer): class Meta: model = Channel fields = ('code', 'kind', 'value', 'user', '...
from django.shortcuts import (render, redirect, reverse, get_object_or_404, HttpResponse) from django.contrib import messages from django.views.decorators.http import require_POST from django.contrib.auth.decorators import login_required from django.conf import settings from django.utils i...
#Interphase - Copyright (C) 2009 James Garnon <https://gatc.ca/> #Released under the MIT License <https://opensource.org/licenses/MIT> from __future__ import division import os try: _set = set except NameError: from sets import Set as _set from interphase.env import engine __docformat__ = 'restructuredtext' ...
""" Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distrib...
#!/usr/bin/env python import json import requests import threading from retrying import retry EVENT_ENDPOINT = 'https://bitpay.com/events' CONTENT_TYPE_HEADER = {'content-type': 'text/event-stream'} SUBSCRIBE_QUERY = 'action=subscribe&events%%5B%%5D=payment&token=%s' STATUS_FIELD = 'status' STATUS_EXPIRED = 'expired...
# Testing module instance_type.i2 import pytest import ec2_compare.internal.instance_type.i2 def test_get_internal_data_instance_type_i2_get_instances_list(): assert len(ec2_compare.internal.instance_type.i2.get_instances_list()) > 0 def test_get_internal_data_instance_type_i2_get(): assert len(ec2_compare.intern...
# Library imports from urllib.request import urlopen, FancyURLopener, Request class TWURLOpener(FancyURLopener): # UrlOpener version info version = "PyTwitch"
#!/usr/bin/env python #import freenect import numpy as np import cv2 import time from matplotlib import pyplot as plt import copy # calibrate kinect to world # https://github.com/amiller/libfreenect-goodies/blob/master/calibkinect.py # also check out mouse_and_match class User_ROI_Selection: NUM_FRAMES = 0 ...
import logging import os import pytest from testing.functional_tests.t_utils import __tmp_dir__, create_tmp_dir, __data_testing_dir__, download_functional_test_files from testing.common_testing_util import remove_tmp_dir logger = logging.getLogger(__name__) def setup_function(): create_tmp_dir() @pytest.mark.sc...
#!/usr/bin/env python3 # Copyright 2020 Unai Martinez-Corral <unai.martinezcorral@ehu.eus> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
"""Unit tests for the selected_tests script.""" import json import os import unittest from buildscripts import errorcodes # Debugging errorcodes.list_files = True TESTDATA_DIR = './buildscripts/tests/data/errorcodes/' class TestErrorcodes(unittest.TestCase): """Test errorcodes.py.""" def setUp(self): ...
#encoding:utf-8 import word_util import codecs import numpy as np import seaborn as sns import matplotlib.pyplot as plt import random def word_idf_equal_zero(word_idf_map): idf_0_list = list(map(lambda x:float(word_idf_map[x])<1e-6,word_idf_map)) #print(type(idf_0_list)) count_idf_count_zero = np.sum(i...
from SloppyCell.ReactionNetworks import * net = IO.from_SBML_file('BIOMD0000000051.xml', 'base') net.compile() traj = Dynamics.integrate(net, [0, 40]) Plotting.figure(1, figsize=(8,8)) Plotting.clf() vars = ['cglcex','cfdp','cg1p','cg6p','cpep','cpyr','cf6p','cgap','cpg'] for ii, v in enumerate(vars): ax = Plott...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ import datetime from personnel.models import Person, JobPosting, Organization from lab_website.tests import BasicTests MODELS = [Perso...
# Import the OpenStack connection class from the SDK from openstack import connection # Create a connection object by calling the constructor and pass the security information conn = connection.Connection(auth_url="http://192.168.0.106/identity", project_name="demo", username="admin", password="manoj", user_domain_id=...
from osr2mp4.ImageProcess import imageproc from osr2mp4.ImageProcess.PrepareFrames.YImage import YImage urarrow = "editor-rate-arrow" def prepare_urarrow(settings): frame = YImage(urarrow, settings, settings.scale * settings.settings["Score meter size"] * 0.75, defaultpath=True).img imageproc.changealpha(frame, 0...
"""Resources management (files/directories/etc.).""" __version__ = '0.1.3'
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
# -*- coding: utf-8 -*- import commands import thread import signal import os import time import subprocess import platform import sys import traceback import glob if platform.system() == "Windows": import win32api from tasbot.utilities import * from tasbot.plugin import IPlugin import udpinterface def addorreplac...
""" Geonomics Help (:mod:`geonomics.help`) ====================================== .. currentmodule:: geonomics.help Memory Help ----------- get_obj_size Get the full size of a complex object Parameters Help --------------- plot_movement Plot example movement tracks generated by the input ...
import pytest pytestmark = pytest.mark.asyncio async def test_main(): assert True
# This file contains functions for training a TensorFlow model import tensorflow as tf import numpy as np import os MODEL_DIR = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'models' ) def load_data(): mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data...
#km hm dam m dm cm mm medida=float(input('digite a medida em metros : ')) dm=medida*10 cm=medida*100 mm=medida*1000 dam=medida/10 hm=medida/100 km=medida/1000 print(""" a converção de metros para dm é {:.1f} a converção de metros para cm é {:.1f} a converção de metros para mm é {:.1f} a converção de metros para dam ...
import numpy as np from astropy.table import Table from astropy.io import ascii deg = np.pi/180.0 # np.random.seed(42) np.random.seed(43) N_systems = 10 # let's get a sample of uniformly oriented disks in 3D space # Generate randomly oriented momentum vector on the sky. U = np.random.uniform(size=N_systems) V = np.r...
class Solution: def canCompleteCircuit(self, gas, cost): start = 0 deficit = 0 tank = 0 for i, (g, c) in enumerate(zip(gas, cost)): tank += g - c if tank < 0: start = i + 1 deficit -= tank tank = 0 ...
# -*- coding: utf-8 -*- dh.define_table('article', Field('article_uuid', type='string', length=36, #default=uuid4(), required=True, require...
from fireo.fields import TextField, IDField, DateTime from fireo.models import Model from datetime import datetime def test_fix_issue_77(): class UserIssue77(Model): name = TextField() created_on = DateTime(auto=True) UserIssue77.collection.create(name="Azeem") UserIssue77.collection.crea...
import os import pickle import numpy as np from numba import jit from .ucb import UCB @jit(nopython=True) def calc_confidence_multiplier(confidence_scaling_factor, approximator_dim, iteration, bound_features, reg_factor, delta): return confidence_scaling_factor * np.sqrt(approxima...
from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) import airbnbapi.resources
from .descriptors import ( number_of_rotatable_bonds, number_of_rotatable_bonds_target_clipped, )
import math class Solution(object): def getPermutation(self, n, k): ans = '' fact = [1] * n num = [str(i) for i in range(1, 10)] for i in range(1, n): fact[i] = fact[i - 1] * i k -= 1 for i in range(n, 0, -1): first = k // fact[i - 1] ...
# -*- coding: utf-8 -*- import os import glob import models import preprocessing import wordembedding import postprocessing import generalize_rules def load_file(path): """Loads file and return its content as list. Args: path: Path to file. Returns: list: Content splited by linebreak. ...
class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ res = "" for i in range(len(strs)): for j in range(len(strs[i])): if strs[i][j] == '|': ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # TODO: Comment this code import sys import shutil import os from gluon.languages import findT sys.path.insert(0, '.') file = sys.argv[1] apps = sys.argv[2:] d = {} for app in apps: path = 'applications/%s/' % app findT(path, file) data = eval(open(os.path...
StateAbbreviations = [ 'al', 'ak', 'az', 'ar', 'ca', 'co', 'ct', 'de', 'fl', 'ga', 'hi', 'id', 'il', 'in', 'ia', 'ks', 'ky', 'la', 'me', 'md', 'ma', 'mi', 'mn', 'ms', 'mo', 'mt', 'ne', 'nv', 'nh', 'nj...
# coding: utf-8 """ Accounting Extension These APIs allow you to interact with HubSpot's Accounting Extension. It allows you to: * Specify the URLs that HubSpot will use when making webhook requests to your external accounting system. * Respond to webhook calls made to your external accounting system by HubSp...
class Tone: def __init__(self, frequency): self._frequency = abs(frequency) # Hertz (Hz) @property def frequency(self): return self._frequency
# coding: utf-8 from __future__ import absolute_import from pyblaze.base import BlazeError from pyblaze.qed import sparse2qed_fp32, sparse2qed_fp16 import numpy as np import logging import sys, getopt def print_help(): print 'build_qed -p <path> -i <infile> -o <ofile> -s <precision> -t <threadnum>' print '' pri...
# -*- coding: utf-8 -*- """ Academy Spectral Similarity Index (SSI) ======================================= Defines the *Academy Spectral Similarity Index* (SSI) computation objects: - :func:`colour.spectral_similarity_index` References ---------- - :cite:`TheAcademyofMotionPictureArtsandSciences2019` : The Acad...