text stringlengths 2 999k |
|---|
# coding: utf-8
import datetime
from django.conf import settings
from django.db import models
from django.db.models import permalink
from embedly.client import Embedly
from django.db.models.manager import Manager
from model_utils import Choices
from model_utils.managers import QueryManager
from model_utils.models impo... |
class SpellChecker:
def print_first_word(self):
print(self.dictionary.pop(1))
def __init__(self, path_to_dictionary):
with open(path_to_dictionary) as text:
lines = text.readlines()
self.dictionary = [word.strip('\n\r') for word in lines]
self.print_first_wo... |
import torch
from torch.nn.utils import parameters_to_vector, vector_to_parameters
from laplace.baselaplace import BaseLaplace, FullLaplace, KronLaplace, DiagLaplace
from laplace.feature_extractor import FeatureExtractor
from laplace.matrix import Kron
from laplace.curvature import BackPackGGN
__all__ = ['FullLLLap... |
# -*- coding: utf-8 -*-
# Copyright 2014 Objectif Libre
#
# 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 ... |
#https://www.codewars.com/kata/58865bfb41e04464240000b0/train/python
def bits_war(numbers):
odds = 0
evens = 0
for number in numbers:
multiplier = 1 if number > 0 else -1
binary_rep = "{0:b}".format(number)
count_strength = binary_rep.count('1')
if number % 2 == 0:
... |
# -*- coding: utf-8 -*-
"""Cisco DNA Center GetDefaultAuthenticationProfile data model.
Copyright (c) 2019-2021 Cisco Systems.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction,... |
#26
numero = float(input('Digite um valor de area em metros quadrados : '))
print(numero*0.0001)
|
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
class Mlp(nn.Module):
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop_rate=0.0,
):
super().__init__()
self.dr... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------------------------------------------------------------... |
import os
import re
import sys
import traceback
from socket import error as SocketError
from errno import EPIPE as BROKEN_PIPE
import pygmi
from pygmi.util import prop
from pygmi import monitor, client, curry, call, program_list, _
__all__ = ('keys', 'events', 'Match')
class Match(object):
"""
A class used ... |
"""test_util.py"""
from d1lod import util
def test_can_match_doi_strings():
"""Tests the matching algorithm which takes unstructured strings and guesses
their identifier structure using string-matching.
"""
assert util.getIdentifierScheme("http://doi.org/10.XX") == "doi"
assert util.getIdentifi... |
"""distutils.command.register
Implements the Distutils 'register' command (register with the repository).
"""
# created 2002/10/21, Richard Jones
__revision__ = "$Id: register.py 67944 2008-12-27 13:28:42Z tarek.ziade $"
import os, string, urllib2, getpass, urlparse
import StringIO
from distutils.core import PyPIR... |
import unittest
from http import HTTPStatus
from typing import Dict, List
from flask import Response, jsonify, make_response
from amundsen_application import create_app
from amundsen_application.base.base_mail_client import BaseMailClient
local_app = create_app('amundsen_application.config.LocalConfig', 'static/tem... |
# The Admin4 Project
# (c) 2013-2022 Andreas Pflug
#
# Licensed under the Apache License,
# see LICENSE.TXT for conditions of usage
import wx.lib.ogl as wxOgl
import math
import wx
from wh import GetBitmap
BMP_BORDER=3
ARROWMARGIN=5
wxOgl.OGLInitialize()
class ExplainText(wx.TextCtrl):
def __init__(self, paren... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import mock
from six import iteritems
def test_init(check, redis_instance):
check = check(redis_instance)
assert check.connections == {}
assert check.last_timestamp_seen == 0
def test__get_... |
import torch
from torch import nn, optim
from torch.autograd.variable import Variable
from torchvision import transforms, datasets
K = 64
class IISPTNet(torch.nn.Module):
def __init__(self):
super(IISPTNet, self).__init__()
# Input depth:
# Intensity RGB
# Normals XYZ
# D... |
'''"Executable documentation" for the pickle module.
Extensive comments about the pickle protocols and pickle-machine opcodes
can be found here. Some functions meant for external use:
genops(pickle)
Generate all the opcodes in a pickle, as (opcode, arg, position) triples.
dis(pickle, out=None, memo=None,... |
# -*- coding: utf-8 -*-
"""Test the TcEx Threat Intel Module."""
from ..tcex_init import tcex
# pylint: disable=W0201
class TestVictim:
"""Test TcEx Victim."""
def setup_class(self):
"""Configure setup before all tests."""
self.ti = tcex.ti
def test_attributes(self, victim_id=None, name... |
from __future__ import unicode_literals
from .utils import get_output_str, termwidth, textwrap
from .base import BaseRow
from .enums import WidthExceedPolicy
from .compat import basestring, to_unicode, zip_longest
class RowData(BaseRow):
def _get_row_within_width(self, row):
"""Process a row so that it is... |
from django.contrib import admin
from .models import Watch
class WatchAdmin(admin.ModelAdmin):
list_display = ('subscriber', 'content_object', 'created')
admin.site.register(Watch, WatchAdmin)
|
'''
inflect.py: correctly generate plurals, ordinals, indefinite articles;
convert numbers to words
Copyright (C) 2010 Paul Dyson
Based upon the Perl module Lingua::EN::Inflect by Damian Conway.
This program is free software: you can redistribute it and/or modify
it under the terms... |
import pandas as pd
from exasol_data_science_utils_python.preprocessing.scikit_learn.sklearn_prefitted_transformer import SKLearnPrefittedTransformer
class SKLearnPrefittedContrastMatrixTransformer(SKLearnPrefittedTransformer):
def __init__(self, contrast_matrix: pd.DataFrame):
self.contrast_matrix = con... |
# -*- coding: utf8 -*-
# Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org>
# This program is Free Software see LICENSE file for details
"""
Anaconda imports validator
"""
from jedi import Script
DEBUG = True
class Validator:
"""Try to import whatever import that is in the given source
"""
... |
# This module imports the initial csv containing book data
# into the database
import csv
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
# Check for environment variable
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
# Set ... |
"""
Classes involved in doctesting
This module controls the various classes involved in doctesting.
AUTHORS:
- David Roe (2012-03-27) -- initial version, based on Robert Bradshaw's code.
"""
# ****************************************************************************
# Copyright (C) 2012 David Roe <roed.math... |
from jira_instance.jira_instance import check_jira_server
import sys, traceback
## Run validation checks on a given configuration json object
def validate_config(config_json):
try:
assert "server" in config_json # config must have server specified
assert check_jira_server(config_json["server"]) # specified s... |
from time import sleep
from scrapy import log
import httplib, urllib,json, requests
def bag42_geocode(address):
"""
Use the BAG42 service to geocode a given address.
"""
log.msg('Geocoding address %s' % address, evel=log.INFO)
address_fields = ['street', 'zip_code', 'city']
payload = []
... |
from tclCommands.TclCommand import *
class TclCommandAddPolygon(TclCommandSignaled):
"""
Tcl shell command to create a polygon in the given Geometry object
"""
# array of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon)
aliases = ['add_polygon', 'a... |
# -*- coding: utf-8 -*-
import datetime
import glob
import os
import shutil
import unittest
from tempfile import gettempdir, mkdtemp
from lxml import etree
from simple_idml.idml import IDMLPackage
from simple_idml.test import SimpleTestCase
from simple_idml.utils import etree_dom_to_tree
CURRENT_DIR = os.path.dirname... |
"""mBuild bulk materials library."""
from mbuild.lib.bulk_materials.amorphous_silica_bulk import AmorphousSilicaBulk
|
#!/usr/bin/env python
""" Convert weights of huggingface Bert to onmt Bert"""
from argparse import ArgumentParser
import torch
from onmt.encoders.bert import BertEncoder
from onmt.models.bert_generators import BertPreTrainingHeads
from onmt.modules.bert_embeddings import BertEmbeddings
from collections import OrderedDi... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
import sys
from spack import *
class Lbann(CMakePackage):
"""LBANN: Livermore Big Artificial Neural Networ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from six.moves.urllib.request import URLopener
# This script downloads these .mag files if not already present.
mag_files = [
'http://download.magenta.tensorflow.org/models/attention_rnn.mag',
... |
from .varnames import (var_names, partial, terms_from_var_names, #noqa
index_from_var_names) # noqa
|
import torch.nn as nn
import math
import torch.nn.functional as F
class Ensemble(nn.Module):
def __init__(self, model_list):
super(Ensemble, self).__init__()
self.model_list = []
for each in model_list:
self.model_list.append(each)
def forward(self, x):
output = []... |
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
DROPSELECT
Drop select widget. This is similar to HTML selects, it can contain many items
(options) to select. The selection is unique.
"""
__all__ = [
'DropSelect',
'DropSelectManager'
]
import math
import pygame
import pygame_menu
import pygame_menu.... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mall.settings')
try:
from django.core.management import execute_from_command_line
except ImportE... |
import pytest
from privacy_evaluator.attacks.membership_inference.membership_inference import (
MembershipInferenceAttack,
)
from privacy_evaluator.classifiers.classifier import Classifier
from privacy_evaluator.datasets.torch.cifar10 import TorchCIFAR10
from privacy_evaluator.models.torch.dcti.dcti import load_dc... |
#!/usr/bin/python
#
# Copyright 2013 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 b... |
import request_pb2
import proto_message as message
import socket
import config
import sys, struct
if len(sys.argv) == 2:
n = int(sys.argv[1])
else:
n = 1000
id = 9
m = open("reqs.dat","rb").read()
print "Loaded Messages"
print "Starting send"
sock_list = []
for i in range(0,n):
b = m[:4]
size = stru... |
# Generated by Django 3.2.10 on 2022-02-22 09:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tag', '0002_auto_20210922_1104'),
]
operations = [
migrations.AddField(
model_name='tag',
name='is_stain',
... |
from model.contact import Contact
import random
def test_delete_any_contact(app, db, check_ui):
if len(db.get_contact_list()) == 0:
app.contact.create(
Contact(firstname="Name", lastname="Last name", email="kovernik@softbalance.ru", mobilephone="+79110000000",
homephone="+7... |
#!/usr/local/autopkg/python
"""
JamfExtensionAttributeUploader processor for uploading extension attributes
to Jamf Pro using AutoPkg
by G Pugh
"""
import json
import re
import os
import subprocess
import uuid
from collections import namedtuple
from base64 import b64encode
from pathlib import Path
from shutil im... |
import pandas as pd
from glob import glob
import json
def _read_all_data(root_path="../Chapter16/data/311/2019/06"):
files = glob(root_path + "/**.csv")
datas = []
for file in files:
try:
df = pd.read_csv(file, index_col=0)
if len(df) > 0:
for col in [
... |
import argparse
import decoding_data
import matplotlib.pyplot as plt
import matplotlib.cm
from matplotlib.collections import LineCollection
import measure
import numpy as np
import pandas
import plots
from scipy import stats
import utils
predictor_key_dict = {
"all": "hidden_all",
"gates": "hidden_gates_tplus1... |
import os
from talon import (
Module,
actions,
app,
clip,
cron,
ctrl,
imgui,
noise,
ui,
)
from talon_plugins import eye_mouse, eye_zoom_mouse
from talon_plugins.eye_mouse import config, toggle_camera_overlay, toggle_control
key = actions.key
self = actions.self
scroll_amount = 50
c... |
import datetime
from kardboard.app import app
from kardboard.models.kard import Kard
class Person(app.db.Document):
name = app.db.StringField(required=True, unique=True)
"""A unique string that identifies the person"""
reported = app.db.ListField(
app.db.ReferenceField('Kard', dbref=False),
... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
import binascii
import pytest
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, se... |
"""
eZmax API Definition (Full)
This API expose all the functionnalities for the eZmax and eZsign applications. # noqa: E501
The version of the OpenAPI document: 1.1.7
Contact: support-api@ezmax.ca
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401... |
'''This class will log 1d array in Nd matrix from device and qualisys object'''
import numpy as np
from datetime import datetime as datetime
from time import time
from utils_mpc import quaternionToRPY
class LoggerControl():
def __init__(self, dt, joystick=None, estimator=None, loop=None, planner=None, logSize=60e... |
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2011 Nathanael C. Fritz, Lance J.T. Stout
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp import Iq
from sleekxmpp.xmlstream import register_stanza_plugin
from sleekxmpp.plugins import BasePlugin
from s... |
from ma import ma
from models.lease import LeaseModel
from models.tenant import TenantModel
from models.property import PropertyModel
from utils.time import time_format
from marshmallow import fields, validates, ValidationError
class LeaseSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = LeaseModel
... |
# Adapted from tune.rllib
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import json
import numpy as np
import os
import sys
import tensorflow as tf
from tuna.variant_generator import TrainingResult
if sys.version_info[0] == 2:
import cStr... |
# Copyright 2015 The TensorFlow 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.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from __future__ import print_function
import logging
import select
from threading import Thread, Event
import time
log = logging.getLogger('mpikat.pipe_monitor')
class PipeMonitor(Thread):
def __init__(self, pipe, handler, sentinel=b'', timeout=1):
"""
@brief Class for parsing output of subpro... |
from collections import Counter
from typing import Callable, Union
import numpy as np
from rdkit import Chem
from dglt.data.featurization.mol2features import register_features_generator
from third_party.descriptastorus.descriptors import rdDescriptors
Molecule = Union[str, Chem.Mol]
FeaturesGenerator = Callable[[Mol... |
import networkx as nx
class CFG:
def __init__(self):
self.graph = nx.DiGraph()
self.graph_nodes_lookup = {}
self.completed = 0x0
def add_node(self, cfg_node):
if cfg_node.label not in self.graph_nodes_lookup:
self.graph.add_node(cfg_node)
self.graph_... |
"""Permissions and needs helpers
Roles logic is defined like this :
admin > developer > maintainer > installer
"""
from flask_principal import Permission, RoleNeed
admin_permission = Permission(RoleNeed('admin'))
dev_permission = Permission(RoleNeed('admin'), RoleNeed('developer'))
maintainer_permission = Permissio... |
import sys
import json
import os
import numpy as np
from dateutil.parser import parse as date_parse
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from mpl_toolkits.axes_grid1 import make_axes_locatable
from sklearn.preprocessing import LabelEncoder
from collections import defaultdict... |
import boto3
import subprocess
successes = 0
# Dummy AWS Handler to kick off high level processes
def lambda_handler(source_region, destination_region, credentials):
session = boto3.Session()
# Load Records into KINESIS
CLIENT_NAME = 'kinesis'
kinesis = session.client(CLIENT_NAME, region_name=source... |
from enum import Enum
from typing import Optional
from pydantic import BaseModel
class ImportBooksResponseStatus(Enum):
"""status codes for Borrowing a book"""
success = "successfully imported"
fail = "import failed"
class BorrowResponseModel(BaseModel):
"""Response model for borrowing a book"""
... |
from __future__ import division
__copyright__ = "Copyright (C) 2009-2013 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including withou... |
#!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... |
#!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANS... |
# -*- coding: utf-8 -*-
import datetime
from dogpile.cache import make_region
#: Subliminal's cache version
CACHE_VERSION = 1
#: Expiration time for show caching
SHOW_EXPIRATION_TIME = datetime.timedelta(weeks=3).total_seconds()
#: Expiration time for episode caching
EPISODE_EXPIRATION_TIME = datetime.timedelta(da... |
from talon import Module, actions, speech_system
mod = Module()
macro = []
recording = False
@mod.action_class
class Actions:
def macro_record():
"""Begin recording a new voice command macro."""
global macro
global recording
macro = []
recording = True
def macro_sto... |
"""Utilities relating to creation and verification of Metronome jobs
************************************************************************
FOR THE TIME BEING WHATEVER MODIFICATIONS ARE APPLIED TO THIS FILE
SHOULD ALSO BE APPLIED TO sdk_jobs IN ANY OTHER PARTNER REPOS
************************************************... |
from emmet.api.routes.oxidation_states.query_operators import PossibleOxiStateQuery
from monty.tempfile import ScratchDir
from monty.serialization import loadfn, dumpfn
def test_possible_oxi_state_query():
op = PossibleOxiStateQuery()
assert op.query(possible_species="Cr2+, O2-") == {
"criteria": {"... |
"""
utility functions for django-form-utils
Time-stamp: <2009-03-26 12:32:41 carljm utils.py>
"""
from django.template import loader
def select_template_from_string(arg):
"""
Select a template from a string, which can include multiple
template paths separated by commas.
"""
if ',' in arg:
... |
"""
Kerberos aware Requester
"""
from jenkinsapi.utils.requester import Requester
from requests_kerberos import HTTPKerberosAuth, OPTIONAL
#pylint: disable=W0222
class KrbRequester(Requester):
"""
A class which carries out HTTP requests with Kerberos/GSSAPI authentication.
"""
def __init__(self, ssl_v... |
if __name__ == "__main__":
print("hi")
|
#!/usr/bin/env python
from __future__ import print_function
from random import choice
from vizdoom import *
game = DoomGame()
game.set_vizdoom_path("../../bin/vizdoom")
# Use CIG example config or your own.
game.load_config("../../examples/config/cig.cfg")
# Select game and map you want to use.
game.set_doom_game... |
#!/usr/bin/env python
# coding: utf-8
from threading import Thread
from time import sleep
from random import uniform
from random import randint
found = 0
# declare a new Exception type, sometimes useful whenever you
# would like a dictionary of values instead of a single message
# or additional functionality.
class... |
"""Set module version.
<Major>.<Minor>.<maintenance>[alpha/beta/..]
Alphas will be numbered like this -> 0.4.0a0
"""
VERSION = '0.6.0-a0'
|
import _plotly_utils.basevalidators
class SelectedValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name='selected', parent_name='scatter', **kwargs
):
super(SelectedValidator, self).__init__(
plotly_name=plotly_name,
parent_name=par... |
from mxnet import gluon
from mxnet.gluon import HybridBlock
class Conv2DNormed(HybridBlock):
"""
Convenience wrapper layer for 2D convolution followed by a normalization layer
(either BatchNorm or InstanceNorm).
norm_type: Either BatchNorm (default) or InstanceNorm strings.
axis ... |
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
curr_dir, curr_pos = 0, (0, 0)
for instruction in instructions:
if instruction == "R":
curr_dir = (curr_dir + 1) % 4
elif instructio... |
# -*- coding: utf-8 -*-
# Copyright 2017 Novo Nordisk Foundation Center for Biosustainability,
# Technical University of Denmark.
#
# 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... |
# pylint: disable-msg=E1101,W0612
from datetime import datetime, time, timedelta, date
import sys
import os
import operator
from distutils.version import LooseVersion
import nose
import numpy as np
randn = np.random.randn
from pandas import (Index, Series, TimeSeries, DataFrame,
isnull, date_ran... |
# Copyright 2019 The Feast Authors
#
# 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 wr... |
CARS = [
{
"code": "bmw",
"name": "BMW"
},
{
"code": "mercedes",
"name": "MERCEDES"
}
]
|
'''
This file contains all the settings such as the University coordinates for the
program
'''
# set the minimum and maximum prices for the apartments
MIN_PRICE = 0
MAX_PRICE = 1299
#DELAY = 10
# maximum distance away from university
MAX_DIST_TO_UNI = 100
# maximum distance away closest LRT station
MAX_DIST_TO_LRT ... |
#
# Copyright (C) 2010 JiangXin@ossxp.com
#
# 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 t... |
#!/usr/bin/env python
import dropbox
import traceback
import sys
import os
access_token = os.environ['DROPBOX_ACCESS_TOKEN']
client = dropbox.Dropbox(access_token)
file_name = sys.argv[1]
with open(file_name, 'rb') as f:
try:
if os.path.getsize(file_name) < 32 * 1024 * 1024:
result = client... |
import mysql.connector
import logging.config
import database
import utils
import concepts_file_parser
import os
import sys
_files_read = 0
_concepts_read = 0
_concepts_inserted = 0
_concepts_updated = 0
_concepts_errors = 0
_results_file = None
_errors_file = None
def _get_logger():
logger = logging.getLogger(__n... |
from pprint import pprint
from . import load
from . import base
from . import blocks
#
# CONSTANTS
#
DEFAULT_BTYPE='stack'
INT_BTYPE='conv'
STACK='stack'
#
# Encoder: a flexible generic encoder
#
class Encoder(base.Model):
#
# CONSTANTS
#
NAME='Encoder'
DEFAULT_CLASSIFIER=base.Model.GLOBAL_POOLING... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run regression test suite.
This module calls down into individual test cases via subprocess. It will
f... |
import pytest
from ciphey import decrypt
from ciphey.iface import Config
answer_str = "Hello my name is bee and I like dog and apple and tree"
def test_affine():
res = decrypt(
Config().library_default().complete_config(),
"Ihsst bf kxbh rd ghh xky R srjh ytz xky xccsh xky muhh",
)
asser... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Omar and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class EInvoiceItem(Document):
pass
|
# -*- coding: utf-8 -*-
"""
* TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-蓝鲸 PaaS 平台(BlueKing-PaaS) available.
* Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in co... |
import os, time, csv, re, random, collections
import gensim
from gensim.models.doc2vec import TaggedDocument
import numpy as np
import matplotlib.mlab as mlab
from matplotlib import colors
import matplotlib.pyplot as plt
from tabulate import tabulate
NEAR_MATCH_THRESHOLD = 0.03 # how close a template match must be to ... |
# импорт библиотек
import sqlite3
import os
# ПУТЬ К БАЗЕ ДАННЫХ
path_db = "db.sqlite"
# подключение к базе
def connect_db(file_db):
try:
# подключение к db.sqlite
conn = sqlite3.connect(file_db)
return conn
except Exception as ex:
print(str(ex))
# закрываем по... |
"""
rest.py
quantumML is
Handles the primary functions
"""
from urllib.request import urlopen
import json
import urllib
import os
import io
import math
from pymatgen.core.structure import Structure
from ase.io import vasp
from dscribe.descriptors import SOAP
from pymatgen.io.vasp import Xdatcar, Oszicar
from sklearn.... |
# Generated by Django 2.0.3 on 2018-06-02 11:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('perftracker', '0006_auto_20180602_1129'),
]
operations = [
migrations.AlterField(
model_name='comparisonmodel',
name... |
"""Fixer for generator.throw(E, V, T).
g.throw(E) -> g.throw(E)
g.throw(E, V) -> g.throw(E(V))
g.throw(E, V, T) -> g.throw(E(V).with_traceback(T))
g.throw("foo"[, V[, T]]) will warn about string exceptions."""
# Author: Collin Winter
# Local imports
from .. import pytree
from ..pgen2 import token... |
from ec2_volume_manager.ec2_instance import EC2Instance
def test_ec2_instance_get_tags():
data = {
"AmiLaunchIndex": 0,
"ImageId": "ami-0caa0ee1474fb9a30",
"InstanceId": "i-055ca20559826a323",
"InstanceType": "a1.medium",
"KeyName": "mark",
"LaunchTime": "2020-07-04... |
import hashlib
import hmac
import six
from jose.constants import ALGORITHMS
from jose.exceptions import JWKError
from jose.utils import base64url_decode, base64url_encode
from jose.utils import constant_time_string_compare
from jose.backends.base import Key
try:
from jose.backends import RSAKey # noqa: F401
exc... |
"""A PasswordController Module."""
import uuid
from masonite import env, Mail, Session
from masonite.auth import Auth
from masonite.helpers import config, password as bcrypt_password
from masonite.request import Request
from masonite.view import View
from masonite.validation import Validator
from config.auth import A... |
# Generated by Django 3.1.1 on 2021-09-02 17:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('crawler', '0007_remove_crawlerline_product'),
]
operations = [
migrations.RenameField(
model_name='crawlerline',
old_name='p... |
def read_doc_data(fn, col_delim="|", word_delim=" ", sent_delim=".", w2c_doc_limit=None, w2c_target_limit=None):
with open(fn, "r", encoding="utf-8") as f:
lines = f.readlines()
rv = []
w2c_doc, w2c_target = {}, {}
for line in lines:
line = line.rstrip()
if len(line) == 0: cont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.