content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from .reader import Reader
from .exception import ParseException
class Node(object):
"""
ノードを示す基底クラス
"""
def __init__(self) -> None:
#: ノードの開始位置
self.startpos:int = 0
#: ノードの終了位置
self.endpos:int = 0
#: ノード番号
self.nodenum:int = 0
... | python |
# Copyright (c) Jeremías Casteglione <jrmsdev@gmail.com>
# See LICENSE file.
import os
import os.path
import sqlite3
from datetime import datetime
from _sadm import log
from _sadm.utils import sh, path
__all__ = ['SessionDB']
_detectTypes = sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES
_sessTable = """
CREATE ... | python |
from app.models.DAO import DAOUsuario
import pymysql
from app import app
from config import mysql
from flask import jsonify
from flask import flash, request
from werkzeug.security import generate_password_hash, check_password_hash
from app.models.classes_basicas.User import User
def add_user(user):
try:... | python |
import sys
import time
import logging
import h5pyd
if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
print("usage: python get_station_ids <ghcn_file>")
sys.exit(0)
filename = sys.argv[1]
logging.basicConfig(level=logging.ERROR)
start_time = time.time()
logging.info(f"start_time: {start_time:.2f}")
f ... | python |
"""
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from byceps.services.global_setting import service as settings_service
from byceps.services.global_setting.transfer.models import GlobalSetting
def test_create(admin_app):
name = 'name1'
v... | python |
def delt(a,b,c):
dell = (b**2) - (4*a*c)
return dell | python |
from typing import *
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
def calc_orbit(p0: Tuple[int, int], v0: Tuple[int, int], aa: List[Tuple[int, int]], d: int):
p = p0
v = v0
orbit = [p0]
for i in range(d-1):
ax, ay = 0, 0
if abs(p[0]) >= abs(p[1])... | python |
# -*- coding: utf-8 -*-
import sys
sys.path.append("../")
from unittest import TestCase, main
from chat.graph import Database
from chat.mytools import Walk, time_me
class WalkUserData(Walk):
def handle_file(self, filepath, pattern=None):
self.db.handle_excel(filepath)
class TestMe(TestCase)... | python |
# Generated by Django 2.2.24 on 2021-12-27 08:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('hom... | python |
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import math
import os
from moviepy.editor import VideoFileClip
from IPython.display import HTML
# List of images from test_images folder
test_path = "test_images/"
test_output_path="test_image... | python |
#!/usr/bin/python3
def print_last_digit(number):
n = abs(number) % 10
print(n, end='')
return n
| python |
from ScanResult import *
from TokenFileWorker import *
from AlgorithmScan import *
from PIL import Image
import profile
# Имя файла с изображением бланка.
#---------------------------------------------------
SOURCE_IMAGE = "001_2.jpg"
#---------------------------------------------------
tokenFileWorker = TokenFileWor... | python |
"""This module aims to load and process the data."""
# pylint: disable=import-error, no-name-in-module
import argparse
import os
import torch
import yaml
from torch.utils.data import DataLoader
from data.preprocessing import apply_preprocessing
from data.dataset_utils import basic_random_split, RegressionDataset, load... | python |
"""Waypoint planning."""
from typing import List, Optional, Sequence, Tuple
from typing_extensions import Final
from opentrons.types import Point
from opentrons.hardware_control.types import CriticalPoint
from .types import Waypoint, MoveType
from .errors import DestinationOutOfBoundsError, ArcOutOfBoundsError
DEFAU... | python |
"""Tests for parsing."""
import unittest
from typing import Iterable
import citation_url
from citation_url import IRRECONCILABLE, PREFIXES, PROTOCOLS, Result, Status
class TestParse(unittest.TestCase):
"""Tests for parsing."""
def test_protocols(self):
"""Test all protocols are formed properly."""
... | python |
import click
from graviteeio_cli.http_client.apim.api import ApiClient
from ....exeptions import GraviteeioError
@click.command()
@click.option('--api', 'api_id',
help='API id',
required=True)
@click.pass_obj
def stop(obj, api_id):
"""Stops an API."""
api_client: ApiClient = obj[... | python |
from __future__ import absolute_import, print_function
import argparse
import math
try:
import cPickle as pickle
except ImportError:
import pickle
import scipy.sparse
from xgboost.sklearn import XGBClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
fr... | python |
# 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 by applicable law or agreed to in... | python |
#
# =================================================================
# =================================================================
from oslo.config import cfg
from powervc_nova.network.powerkvm.agent import commandlet
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
CONF = c... | python |
import pickle
import tempfile
import numpy as np
import pytest
from scipy import stats
import hypney
import hypney.utils.eagerpy as ep_util
def test_naming():
m = hypney.models.uniform(name="bla")
assert m.name == "bla"
# Names are preserved in WrappedModel
assert m.fix_except("rate").name == "bla"
... | python |
# import gi
# gi.require_version("Gtk", "3.24")
from gi.repository import Gtk as g,cairo
try:
from gi_composites import GtkTemplate
except:
from sysmontask.gi_composites import GtkTemplate
if __name__=='sysmontask.sidepane':
from sysmontask.sysmontask import files_dir
else:
from sysmontask import fil... | python |
"""
URLConf for Caching app
"""
from __future__ import unicode_literals
from django.urls import path
from . import views
urlpatterns = [
path('', views.stats_page, {}, 'keyedcache_stats'),
path('view/', views.view_page, {}, 'keyedcache_view'),
path('delete/', views.delete_page, {}, 'keyedcache_delete'),
]... | python |
import numpy as np
"""
Utility functions to initialize a lattice .
image, random, random positive, random within range with a single 'maximum' ping site in center, center ping binary 0s except maximum 1 in center, binary 1 and 0 with density parameter
magic square and scaled primes are amusing seeds
"""
from PIL impo... | python |
"""
Overview
========
PySB implementations of the extrinsic apoptosis reaction model version 1.0
(EARM 1.0) originally published in [Albeck2008]_.
This file contains functions that implement the extrinsic pathway in three
modules:
- Receptor ligation to Bid cleavage (:py:func:`rec_to_bid`)
- Mitochondrial Outer Memb... | python |
# SVR
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
# Splitting the dataset into the Training set and Test set
"""from sklearn.cross_... | python |
from BeautifulSoup import BeautifulSoup
import re
import os
import sys
import string
openclosetags = re.compile('''<.*?>|</.*?>''',re.DOTALL)
spaces = re.compile('''\s+''',re.DOTALL)
files = []
#files.append('./docs/apple/osx/developer.apple.com.library/mac/documentation/Cocoa/Reference/NSCondition_class/... | python |
from cloudshell.devices.runners.configuration_runner import ConfigurationRunner
from vyos.flows.restore import VyOSRestoreFlow
from vyos.flows.save import VyOSSaveFlow
class VyOSConfigurationRunner(ConfigurationRunner):
@property
def restore_flow(self):
return VyOSRestoreFlow(cli_handler=self.cli_han... | python |
from numpy.random import random
from bokeh.plotting import *
output_server("markers.py example")
def myscatter(x, y, typestr):
scatter(x, y, type=typestr,
line_color="#6666ee", fill_color="#ee6666", fill_alpha=0.5, size=12, tools="pan,zoom")
def mytext(x, y, textstr):
text(x, y, text=textstr, angle... | python |
"""
개발환경 : PyQt5 x64, Python 3.4.3 x64, Windows 8.1 x64
파일 : CryptoCommon.py
내용 : 암호에서 자주 쓰이는 변수들을 지원할 예정
"""
import os
class CryptoCommon:
common_long_keyspace = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
def __init__(self):
self.message = ''
... | python |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Checkpoint manager
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# -------------------------------------------------------------... | python |
# -*- coding: utf-8 -*-
from sys import maxsize
from model.group import Group
def test_add_group(app):
old_groups = app.group.get_group_list()
added_group = Group(name="Grop1", header="Heder1", footer="Footer1")
app.group.create(added_group)
assert len(old_groups)+1 == app.group.count() #"""хеш функ... | python |
import pytest
from django.conf import settings
from django.contrib.messages import get_messages
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from tests.api_tokens_tests.factories import AuthTokenFactory
from tests.factories import UserFactory
from tests.utils import get_view_fo... | python |
from gfl.core.manager.node import GflNode
from gfl.core.manager.manager import NodeManager
| python |
import numpy as np
targets = np.loadtxt('qm9_targets.dat',dtype=str)[:,1]
factors = [1., 1., 27.2114, 27.2114, 27.2114, 1., 27211.4, 1., 1., 1., 1., 1., 0.043363, 0.043363, 0.043363, 0.043363, 1., 1., 1., 0.043363]
assert len(factors) == len(targets)
seeds = ['11','22','33']
mae_avg = []
mae_std = []
for target i... | python |
import json
import argparse
import os
import io
import shutil
import copy
import sys
from datetime import datetime
from pick import pick
from time import sleep
from urllib.parse import urlparse
import requests
#################### Patched - Slacker ######################
# Purpose of the patch is to allow for a cookie... | python |
from .CSGOMarketAPI import *
from .Exceptions import *
from .Item import *
from .types import *
__all__ = ['Item', 'CSGOMarketAPI', 'Exceptions', 'types']
| python |
#-----------------------------------------------------
# Mimas: conference submission and review system
# (c) Allan Kelly 2016-2020 http://www.allankelly.net
# Licensed under MIT License, see LICENSE file
# -----------------------------------------------------
import unittest
import datetime
from google.appengine.ext... | python |
import pandas as pd
import yfinance as yf
from src.config import Config
def main(cfg: Config):
metadata = pd.read_csv(cfg.METADATA_FILEPATH, comment="#")
ticker_symbols = " ".join(metadata[cfg.TICKER_SYMBOL_COLUMN])
data = yf.download(tickers=ticker_symbols, period=cfg.PERIOD, interval=cfg.INTERVAL, group... | python |
import sys
n, *a = map(int, sys.stdin.read().split())
def main():
res = 0
for i in range(1, n-1):
cur = a[i]
l = 0
for j in range(i):
if a[j] < cur:
l += 1
r = 0
for j in range(i+1, n):
if a[j] < cur:
... | python |
import numpy as np
from random import randint
import matplotlib.pyplot as plt
def createTestData(X, y, word):
img_word = []
word = str(word)
for char in range(len(word)):
if(word[char] == ' '):
img_word.append(-1)
else:
indices = [i for i, x in enumerate(y) if x ==... | python |
#!/usr/bin/env python
def part1(path):
with open(path) as f:
lines = f.read().strip().split("\n")
earliest = int(lines[0])
ids = [int(x) for x in lines[1].split(",") if x != "x"]
a = [(id, ((earliest // id) + 1) * id) for id in ids]
min_ = min(a, key=lambda x: x[1])
return (min_[1] - e... | python |
from tests.test_limesurvey import TestBase
from limesurveyrc2api.limesurvey import LimeSurveyError
class TestSurveys(TestBase):
def test_list_surveys_success(self):
"""A valid request for list of surveys should not return empty."""
result = self.api.survey.list_surveys()
for survey in res... | python |
try:
a
except Exc as b:
b
except Exc2 as c:
b
# Check that capturing vars are properly local
def foo():
try:
a
except Exc as b:
b
| python |
# Generated by Django 2.1.3 on 2018-12-03 07:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0008_auto_20181203_0659'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='followings',
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-21 19:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lookup_tables', '0015_auto_20170220_1348'),
]
operations = [
migrations.Alt... | python |
# Boolean Variables
x = True
print(bool(x))
x = 4
y = 4
print("X :",x)
print("Y :",y)
print("Is X=Y ? " , bool(x==y))
y = 3
print("Y :",y)
print("Is X=Y ? " , bool(x==y))
print("NOTE : If empty sequence, strings, values, are passed, then bool returns false")
def mod(num):
return (bool(num%2==0))
num = int(input(... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class qKanji2num_class:
def __init__(self, ):
self.kans = '〇一二三四五六七八九'
self.tais1 = '千百十'
self.tais2 = '京兆億万'
self.suuji = {'〇', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', \
'百', '千', '万', '億', '兆', \
... | python |
"""
venvs creates virtualenvs.
By default it places them in the appropriate data directory for your platform
(See `appdirs <https://pypi.python.org/pypi/appdirs>`_), but it will also
respect the :envvar:`WORKON_HOME` environment variable for compatibility with
:command:`mkvirtualenv`.
"""
from functools import parti... | python |
from itsdangerous import json
from models.vagas import VagasEmpregoModel
class VagasEmpregoService:
def buscar_vaga(self, vaga_id: int) -> dict:
vaga = VagasEmpregoModel.procurar_vaga(vaga_id)
return vaga
def listar_vagas(self) -> list:
lista_vagas = VagasEmpregoModel.listar_vagas()
... | python |
import matplotlib; matplotlib.use('Agg')
from daft_builder import pgm
import pytest
def test_Param_init():
param = pgm.Param(r"$y$", xy=(0.5, 0.5), of=["x"])
assert param.name == "y"
assert param.x, param.y == (0.5, 0.5)
assert param.anchor_node is None
assert param.edges_to == ["x"]
@pytest.ma... | python |
from .neurons import *
| python |
#!/usr/bin/env python
__author__ = "Mari Wahl"
__copyright__ = "Copyright 2014"
__credits__ = ["Mari Wahl"]
__license__ = "GPL"
__version__ = "2.0"
__maintainer__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
''' this should be automatize, declare everything like this is terrible, but it was for historical rea... | python |
"""
This file contains form classes for abstracting
forms across picbackend app
"""
from django.forms import ModelForm
from picmodels.models import NavMetricsLocation
class NavMetricsLocationForm(ModelForm):
# country = ModelChoiceField(queryset=Country.objects.all(), empty_label="Choose Country", to_field_name... | python |
# 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 by applicable law or agreed to in writing, software
# distributed under the Li... | python |
#**************************************************************************
#* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
#* *
#* Author: The ALICE Off-line Project. *
#* Contributors ... | python |
import re
import difflib
import collections
from . import ComicBookCrawlerBase, ChapterItem, ComicBookItem, SearchResultItem
from ..exceptions import ComicbookNotFound, ChapterNotFound
class ComicBookCrawler(ComicBookCrawlerBase):
SOURCE_NAME = '鼠绘漫画'
SITE = "ishuhui"
CHAPTER_INTERVAL_PATTERN = re.compil... | python |
import paddle
import pit
import numpy as np
from reprod_log import ReprodLogger
# import argparse
from DeiT.losses import DistillationLoss
from DeiT.regnet import build_regnet as build_teacher_model
from DeiT.losses import DistillationLoss ,SoftTargetCrossEntropyLoss
reprod_logger = ReprodLogger()
# 定义加载模型
model = ... | python |
import copy
import itertools
from taichi.core import ti_core as _ti_core
import taichi as ti
# Helper functions
def get_rel_eps():
arch = ti.cfg.arch
if arch == ti.opengl:
return 1e-3
elif arch == ti.metal:
# Debatable, different hardware could yield different precisions
# On AMD... | python |
from lxml import etree, objectify
class norm_attribute:
def __remove_attributes_node(self, mt_node):
if not mt_node.attrib: return True
for at in mt_node.attrib.keys():
del mt_node.attrib[at]
def __remove_attributes_tree(self, mt_tree):
self.__remove_attributes_node(mt_tree... | python |
import os
from pysigtool import extract_authenticode
def test_extract_authenticode() -> None:
script_dir: str = os.path.abspath(os.path.dirname(__file__))
input_bin: str = os.path.join(script_dir, "msvcr120.dll")
output_der: str = os.path.join(
script_dir, "msvcr120.dll".replace(".", "_") + ".de... | python |
'''
Export/Spreadsheet/spreadsheetrow
_________________________________
Base object for generating spreadsheet data rows.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
# load modules/submodules
from xldlib.qt.... | python |
expected_output={
'tunnel_id': {
1: {
'active_time': 2856,
'auth_sign': 'psk',
'auth_verify': 'psk',
'ce_id': 1406,
'cisco_trust_security_sgt': 'disabled',
'dh_grp': 20,
'dpd_configured_time': 10,
'dyna... | python |
#!/usr/bin/env python
import requests
possible_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
password = '8Ps3H0GWbn5rd9S7GmAdgQNdkhPkq9cw'
auth=('natas17', password)
used_chars = ''
for char in possible_chars:
payload = {'username': ('natas18" AND password LIKE BINARY "%%%c%%" and slee... | python |
from .data_wrangling import dip2strike
from .data_wrangling import strike2dipaz
from .data_wrangling import xyzinterp
from .data_wrangling import linear_interpolate_2dp
from .geometric_bias import unitvectorx
from .geometric_bias import unitvectory
from .geometric_bias import unitvectorz
from .geometric_bias import is... | python |
from .base import Widget
class RectangleWidget(Widget):
def __init__(self, size, position=(0, 0)):
super().__init__(position)
self.size = size
def draw(self, window):
width, height = self.extent(window)
window.rectangle(self.x, self.y, self.x + width - 1, self.y + height - 1)
... | python |
import sys
import pandas as pd
import numpy as np
import torch
from torch import nn
from torch.utils.data import random_split, DataLoader
from utils import (
read_glove_vector,
get_one_hot_matrix,
get_glove_matrix,
create_emb_layer,
)
from dataset import UtteranceSlotDataset
from train import train
fr... | python |
from bokeh.models import FuncTickFormatter
import bokeh.palettes
import numpy as np
logFmtr = FuncTickFormatter(code="""
var trns = [
'\u2070',
'\u00B9',
'\u00B2',
'\u00B3',
'\u2074',
'\u2075',
'\u2076',
'\u2077',
'\u2078',
'\u2079'];
var tick_power = Math.floor(Math.log10(tick));
var tick_mult = Math.pow(10, Math.l... | python |
from sklearn.kernel_approximation import (RBFSampler,Nystroem)
from sklearn.ensemble import RandomForestClassifier
import pandas
import numpy as np
import random
from sklearn.svm import SVC
from sklearn.metrics.pairwise import rbf_kernel,laplacian_kernel,chi2_kernel,linear_kernel,polynomial_kernel,cosine_similarity
fro... | python |
# Generated by Django 3.0.8 on 2020-08-29 14:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bugtrack', '0014_user_notification'),
]
operations = [
migrations.AddField(
model_name='bug',
name='notifType',
... | python |
# -*- coding: utf-8 -*-
import shutil
import locm, routem, mapm, dropboxm, gmaps, tools, bokehm, tspm
import logging.config, os, yaml, inspect
import time, math
import numpy as np
tver_coords = {u'lat':56.8583600,u'lng':35.9005700}
ryazan_coords = {u'lat':54.6269000,u'lng':39.6916000}
def setup_logging(
default_p... | python |
# -*- coding: utf-8 -*-
"""
In the test, we assume:
- id_col: id, string, generated by ``import uuid``
- sort_col: time, datetime
"""
from __future__ import division
from sqlalchemy import MetaData, Table, Column
from sqlalchemy import String, DateTime
table_name = "events"
id_col_name = "id"
sort_col_name = "time"... | python |
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import chamfer
from torch.autograd import Function
from util.sampler import sampler, sampler_color, sampler_uv, uv2color
from torch.autograd import Variable
class RGBPriorLoss(nn.Module):
def __init__(self, options)... | python |
from neuroquery import datasets
from neuroquery_image_search import NeuroQueryImageSearch
datasets.fetch_neuroquery_model()
NeuroQueryImageSearch()
| python |
# -*- coding: utf-8 -*-
"""
dcm - Direction Cosine Matric (DCM) class for Astrodynamic Toolkit
Copyright (c) 2017 - Michael Kessel (mailto: the.rocketredneck@gmail.com)
a.k.a. RocketRedNeck, RocketRedNeck.com, RocketRedNeck.net
RocketRedNeck and MIT Licenses
RocketRedNeck hereby grants license for others to copy a... | python |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# MetricScope model
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# --------------------------------------------------------------... | python |
import os
import pickle
import random
import torch
import numpy as np
import math
from torch.utils.data import Dataset
class RicoDataset(Dataset):
'''
dataset Loader for rico
'''
def __init__(self,
data_path,
debug=False
) -> None:
super().__in... | python |
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import scipy.optimize as opt
import emcee
import triangle, walkers
import priors
np.random.seed(666)
def randomData(a, b, sig, npts = 100):
x = np.random.random(npts)
mean = a + b * x
y = stats.norm(loc=mean, scale=sig).rvs(... | python |
import os
from Zoo.World import World
from Zoo.Position import Position
from Zoo.Organisms.Grass import Grass
from Zoo.Organisms.Sheep import Sheep
from Zoo.Organisms.Dandelion import Dandelion
from Zoo.Organisms.Wolf import Wolf
from Zoo.Organisms.Toadstool import Toadstool
if __name__ == '__main__':
pyWorld = Worl... | python |
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
import os
import re
import time
import random
import fileinput
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from spyci import spyci
def write_spice(sch_path, file_name, corner):
extension = '.spice'
lines = ["\n* Parameters\n... | python |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine.post_process import Filter
DEPS = [
'archive',
'chromium',
'depot_tools/gclient',
'recipe_engine/context',
'recipe_engine/json'... | python |
#!/usr/bin/python -Wall
# ================================================================
# Please see LICENSE.txt in the same directory as this file.
# John Kerl
# kerl.john.r@gmail.com
# 2007-05-31
# ================================================================
ispec_mul_table = [99]
ispec_inv_table = []
| python |
# sys.path.append(os.getcwd() + '/..') # Uncomment for standalone running
from abstract_filter import *
import re
class RepeatedChars(AbstractFilter):
def __init__(self):
self.num_of_scans = 0
self.src_language = ""
self.trg_language = ""
self.repeated_chars_re = None
#
def initialize(self, source_langua... | python |
import itertools
import random
import logging
import numpy as np
import matplotlib.pyplot as plt
import os
#from evaluate_reservoir import *
from utilis import *
from args import args as my_args
from evaluate_encoder import *
from itertools import product
import time
if __name__ == '__main__':
args... | python |
#! /usr/bin/python
import ctypes
import os
__author__ = 'fyabc'
# Try to locate the shared library
_file = 'my_utils.dll'
_path = os.path.join(*(os.path.split(__file__)[:-1] + (_file,)))
_module = ctypes.cdll.LoadLibrary(_path)
# void myPrint(int)
myPrint = _module.myPrint
myPrint.argtypes = (ctypes.c_int,)
myPrin... | python |
import urllib.request
import re
import sys
class WordReader:
MEANING_URL = "https://dict.longdo.com/search/%s"
@staticmethod
def __get_url_content(url):
fp = urllib.request.urlopen(url)
content = fp.read().decode("utf8")
fp.close()
return content
@staticmethod
def... | python |
# -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module to manage failure message of builds."""
from __future__ import print_function
import sys
from chromite.lib import fai... | python |
'''
this file contains time tests for scanner algorithms
'''
from FreeAndSimpleScanner import *
import unittest
from time import time
from random import uniform
class AreaScannerMethodsTest(unittest.TestCase):
@staticmethod
def used_regions_sample():
usedRegions = [((5.5, 1), (7.5, 4)), ((1, 5.5), (... | python |
import yaml
import json
import numpy as np
from json import dumps, loads
from kafka import KafkaProducer, KafkaConsumer
from fedrec.communications.messages import JobSubmitMessage
from fedrec.utilities import registry
with open("configs/dlrm_fl.yml", 'r') as cfg:
config = yaml.load(cfg, Loader=yaml.FullLoader)
de... | python |
import urllib.request
import csv
import datetime
from requests import get
import fcntl
# expireDate
# http://stock.finance.sina.com.cn/futures/api/openapi.php/StockOptionService.getRemainderDay?date=201706
# frontrow = [
# 'Date', 'ExpireDate', 'OptionType', 'Strike', 'Contract Name', 'Last',
# 'Bid', 'Ask', '... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, print_function, absolute_import,
unicode_literals)
import logging
from itertools import imap
from osrc.database import get_pipeline, format_key
# The default time-to-live for every key.
DEFAULT_TTL = 2 * 7 * 24 * ... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | python |
# _*_coding:utf-8_*_
# @auther:FelixFu
# @Date: 2021.4.14
# @github:https://github.com/felixfu520
import numpy as np
import os
import cv2
from base import BaseDataSet, BaseDataLoader
class BDDDataset(BaseDataSet):
def __init__(self, **kwargs):
self.num_classes = 29
super(BDDDataset, self).__init... | python |
import numpy as np
from scipy.optimize import least_squares
from sklearn.cluster import KMeans
from sklearn.neighbors import NearestNeighbors
def sol_u(t, u0, alpha, beta):
return u0*np.exp(-beta*t) + alpha/beta*(1-np.exp(-beta*t))
def sol_s(t, s0, u0, alpha, beta, gamma):
exp_gt = np.exp(-gamma*t)
if bet... | python |
#!/usr/bin/env
#Imports
import subprocess
from collections import defaultdict
import re
import os
import string
import sys
import argparse
import datetime
def transform_groups(blob):
lines = blob.stdout.decode('utf-8').split('\n')
stat = defaultdict(lambda: defaultdict())
months = []
for line in line... | python |
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm, Textarea, TextInput, Select
from django.utils import timezone
# Create your models here.
class Unvetted(models.Model):
token_address = models.CharField(max_length=120)
telegram_url = models.CharField(... | python |
from .base_options import BaseOptions
class TrainOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self._parser.add_argument('--total_epoch', type=int, default=20, help='total epoch for training')
self._parser.add_argument('--learning_rate', type=float, default=0.00... | python |
import json
import os.path
import codecs
from sampledata.exceptions import ParameterError
LOCALES = ['us']
OCCUPATIONS_PATH = os.path.join(os.path.dirname(__file__), 'occupations')
class Occupation(object):
data = {}
def __load_locale(self, locale):
locale_path = os.path.join(OCCUPATIONS_PATH, "{0... | python |
"""Facebook platform for notify component."""
import json
import logging
from aiohttp.hdrs import CONTENT_TYPE
import requests
import voluptuous as vol
from homeassistant.components.notify import (
ATTR_DATA,
ATTR_TARGET,
PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.const import CONT... | python |
"""jinjalint
Usage:
jinjalint [options] [INPUT ...]
Options:
-h --help Show this help message and exit.
--version Show version information and exit.
-v --verbose Verbose mode.
-c --config FILE Specify the configuration file.
The configuration file must be a valid Python file.
"""
... | python |
import logging
import re
from datetime import datetime
class SFHelper(object):
@staticmethod
def get_pi_name(path, log = True):
pi_names = {"staudt": "Louis_Staudt", "Staudt": "Louis_Staudt", "Soppet": "Daniel_Soppet", "Schrump": "David_Schrump", "Shrump": "David_Schrump",
"Elec... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.