code
stringlengths
1
199k
import sys def _all_countries_scanner(fn, callback, max_n=1): """ Scans the 'allCountries.txt' file and calls the callback for each record. """ fp = open(fn, "r") for i,line in enumerate(fp): if max_n > 0 and i >= max_n: break if i % 1000 == 0: sys.stderr....
import sys sys.path.append('bindings/python/') import elliptics import argparse def percentage(routes): from operator import itemgetter percentages = routes.percentages() for group in percentages: print 'Group {0}:'.format(group) for host in percentages[group]: for backend_id in ...
""" barcodes.py parses and stores barcode information associated with a double barcoded illumina amplicon project """ import sys from dbcAmplicons import misc class barcodeTable: # ---------------- barcodes class ---------------- """ Class to read in and hold barcode table information associated with an Ill...
import cadquery as cq from Helpers import show exploded = False # when true, moves the base away from the top so we see showTop = True # When true, the top is rendered. showCover = True # When true, the cover is rendered width = 2.2 # Nominal x dimension of the part height = 0.5 ...
from traits.api import HasTraits, Instance from traitsui.api import View, Item from chaco.api import VPlotContainer, ArrayPlotData, Plot from enable.component_editor import ComponentEditor from numpy import linspace, sin class ContainerExample(HasTraits): plot = Instance(VPlotContainer) traits_view = View(Item(...
"""The ALU contains all possibile operations.""" import backend class ALU(object): def __init__(self, cpu): # store pointer to cpu, since the operations need the registers self.__cpu = cpu # register all instructions self.__register_instr() backend.LOGGER.log("init ALU comple...
import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.pyplot as plt cg0 = np.genfromtxt("cgwin_abacus.txt") avg0 = np.average(cg0[:,1]) print 'avg cg in figure: ',avg0 p1, = plt.plot(cg0[:,0]/1000, cg0[:,1],ls=':',lw=3.0) plt.ylim(0, 90) plt.xlim(0, 30) plt.xlabel('Time in Seconds', fontsize=...
import argparse import subprocess import sys import os if __name__ == '__main__': parser = argparse.ArgumentParser(description='Given a text file, and a prob-threshold trains a unidirectional RNNLM, and segments the text according to those places where the threshold is reached.') parser.add_argument('text', met...
import scrapy class IavivaItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() url = scrapy.Field() pass
import os import json import sys from pprint import pprint from keystoneauth1 import identity from keystoneauth1 import session from ironicclient import client as ironic_client from novaclient import client as nova_client """ Credit to: https://github.com/rscarazz/tripleo-director-instance-ha/blob/master/create-stonith...
from bitmovin.errors import MissingArgumentError from bitmovin.resources.models import H264PictureTimingTrimmingInputStream as \ H264PictureTimingTrimmingInputStreamResource from ..rest_service import RestService class H264PictureTimingTrimmingInputStream(RestService): BASE_ENDPOINT_URL = 'encoding/encodings/{e...
import sqlite3 class Database(object): def __init__(self, filename): self.conn = sqlite3.connect(filename) self._create_tables() def _create_tables(self): with self.conn: self.conn.execute(''' CREATE TABLE IF NOT EXISTS users ( username TEX...
from __future__ import unicode_literals import json import re import itertools from .common import InfoExtractor from .subtitles import SubtitlesInfoExtractor from ..compat import ( compat_HTTPError, compat_urllib_parse, compat_urllib_request, compat_urlparse, ) from ..utils import ( ExtractorError,...
import sys from tornado.ioloop import IOLoop async def handle(line): print('> %s\n' % line.strip()) def main(): ioloop = IOLoop.instance() ioloop.add_handler( sys.stdin, lambda fd, event: ioloop.add_callback(handle, fd.readline()), IOLoop.READ) print('waiting input ...\n') tr...
""" note you can remove subsequences, not just substrings so you can always remove all the a's in one go and then all the b's so either the string is empty, then the answer is 0 or it's already a palindrome and the answer is 1 or you can remove each letter type, and with 2 letters, the answer is 2 """ class Solution: ...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "scontacts.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from abc import ABC, abstractmethod from typing import TypeVar, Generic, Iterable, List, Iterator, Dict, Tuple from pyflink.common.typeinfo import TypeInformation, Types __all__ = [ 'ValueStateDescriptor', 'ValueState', 'ListStateDescriptor', 'ListState', 'MapStateDescriptor', 'MapState' ] T = T...
from __future__ import print_function import gen_csharp import gen_docs_json import gen_java import gen_python import gen_R import gen_thrift import bindings import sys import os sys.path.insert(0, "../../scripts") import run import atexit bindings.check_requirements() results_dir = "../build/logs" if not os.path.exist...
""" """ from oslo_config import cfg from oslo_log import log as logging from umbrella.common import wsgi from umbrella import i18n from umbrella.db.sqlalchemy import api as db_api from umbrella.db.sqlalchemy import models import time import json import collections LOG = logging.getLogger(__name__) _ = i18n._ _LE = i18n...
from tempest import config # noqa from tempest import test # noqa from tempest_lib import exceptions as lib_exc # noqa import testtools # noqa from manila_tempest_tests.tests.api import base from manila_tempest_tests import utils CONF = config.CONF class SharesNFSTest(base.BaseSharesTest): """Covers share funct...
"""Define APIs for the servicegroup access.""" from nova.openstack.common import cfg from nova.openstack.common import importutils from nova.openstack.common import lockutils from nova.openstack.common import log as logging from nova import utils import random LOG = logging.getLogger(__name__) _default_driver = 'db' se...
from datetime import datetime from django.core.validators import RegexValidator from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.sites.models import Site from core.spaces.file_validation import ContentTypeRestrictedFileF...
"""Support for Neato Connected Vacuums.""" from datetime import timedelta import logging import requests import voluptuous as vol from homeassistant.components.vacuum import ( ATTR_BATTERY_ICON, ATTR_BATTERY_LEVEL, ATTR_STATUS, DOMAIN, STATE_CLEANING, STATE_DOCKED, STATE_ERROR, STATE_IDLE, STATE_PAUSED, STATE_R...
"""The Virtual File System (VFS) definitions.""" COMPRESSION_METHOD_BZIP2 = u'bzip2' COMPRESSION_METHOD_DEFLATE = u'deflate' COMPRESSION_METHOD_LZMA = u'lzma' COMPRESSION_METHOD_XZ = u'xz' COMPRESSION_METHOD_ZLIB = u'zlib' ENCODING_METHOD_BASE16 = u'base16' ENCODING_METHOD_BASE32 = u'base32' ENCODING_METHOD_BASE64 = u'...
import proto # type: ignore from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="google.cloud.aiplatform.v1beta1", manifest={"Context",}, ) class Context(proto.Message): r"""Instance of a general context. Attr...
from xii import attribute class AnsibleAttribute(attribute.Attribute): def get_virt_url(self): return self.component().get_virt_url() def get_tmp_volume_path(self): return self.other_attribute("image").get_tmp_volume_path()
""" Created on Sun Nov 24 09:11:01 2013 @author: clisle """ from tree_interchange import * def InvokeDataIntegrator(tree_collection_name,tree_coll,matrix_collection_name,matrix_coll, out_tree_collection_name,verbose): # first convert tree to an APE tree ape_tree_in_R = ConvertArborTreeIntoApe(tree_coll,tree_col...
from openstackclient.common import utils from openstackclient.tests.volume.v2 import fakes as volume_fakes from openstackclient.volume.v2 import snapshot class TestSnapshot(volume_fakes.TestVolume): def setUp(self): super(TestSnapshot, self).setUp() self.snapshots_mock = self.app.client_manager.volu...
import argparse import gzip import json import logging import os import subprocess import sys import uuid import yaml from rally.cli import envutils from rally.common import objects from rally import osclients from rally.ui import utils LOG = logging.getLogger(__name__) LOG.setLevel(logging.DEBUG) MODES_PARAMETERS = { ...
"""Define networks for various EHR data encoders. Networks are sonnet models that are used in the model construction. """ import functools as ft import itertools from typing import List, Type from ehr_prediction_modeling import types from ehr_prediction_modeling.models.nets import encoder_base from ehr_prediction_model...
""" This code was generated by Codezu. Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. """ from mozurestsdk.mozuclient import default as default_client from mozurestsdk.mozuurl import MozuUrl; from mozurestsdk.urllocation import UrlLocation from mozurestsdk.api...
try: frozenset except NameError: # Import from the sets module for python 2.3 from sets import Set as set from sets import ImmutableSet as frozenset try: from collections import deque except ImportError: from utils import deque from constants import spaceCharacters from constants import entities...
from partner.models import Partner class PartnerIdsMixin(object): __partner_ids = None def get_partner_ids(self): if self.__partner_ids is None: if hasattr(self, 'request'): active_partner = self.request.active_partner else: active_partner = self.c...
import json import requests import utils.utils BASE_SCW_URL = 'https://integration-api.securecodewarrior.com/api/v1/trial?id=bugcrowd&mappingList=vrt&mappingKey=' OUTPUT_FILENAME = 'scw_links.json' def scw_url(vrt_id): return f'{BASE_SCW_URL}{vrt_id.replace(".", ":")}' def scw_mapping(vrt_id): path = scw_url(vr...
from .tc_gcc import * class AndroidGccToolChain(GccToolChain): def __init__(self, name, ndkDir, gccVersionStr, platformVer, archStr, prefix = "", suffix = ""): # TODO: non-windows host platform hostPlatform = 'windows' installDir = os.path.join(ndkDir, 'toolchains', prefix + gccVersionStr, '...
import unittest import robocup import main import evaluation.opponent import constants class TestPassing(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestPassing, self).__init__(*args, **kwargs) self.context = robocup.Context() def setUp(self): main.set_context(self.con...
import contextlib import os import time import mock from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_log import formatters from oslo_log import log as logging from oslo_utils import importutils from six.moves import cStringIO from nova import conductor import nova.conf from nov...
'''Source: https://github.com/GoogleCloudPlatform/tensorflow-without-a-phd/blob/master/tensorflow-rl-pong/setup.py''' from setuptools import find_packages from setuptools import setup import subprocess from distutils.command.build import build as _build import setuptools class build(_build): """A build command clas...
from ggrc import db from .mixins import ( deferred, Noted, Described, Hyperlinked, WithContact, Titled, Slugged, ) from .relationship import Relatable from .object_document import Documentable from .object_person import Personable class Response(Noted, Described, Hyperlinked, WithContact, Titled, Slu...
from __future__ import absolute_import, division, print_function, unicode_literals from abc import abstractmethod from pants.util.meta import AbstractClass from pants.util.objects import Exactly class ParseError(Exception): """Indicates an error parsing BUILD configuration.""" class SymbolTable(AbstractClass): """A...
""" Provides functionality to interact with fans. For more details about this component, please refer to the documentation at https://home-assistant.io/components/fan/ """ import asyncio from datetime import timedelta import functools as ft import logging import voluptuous as vol from homeassistant.components import gr...
from edmunds.foundation.patterns.manager import Manager from flask_security import Security, SQLAlchemyUserDatastore from edmunds.database.db import db class AuthManager(Manager): """ Auth Manager """ def __init__(self, app): """ Initiate the manager :param app: The a...
import argparse from ray.train import Trainer from ray.train.examples.train_fashion_mnist_example import train_func from ray.train.callbacks.logging import MLflowLoggerCallback def main(num_workers=2, use_gpu=False): trainer = Trainer(backend="torch", num_workers=num_workers, use_gpu=use_gpu) trainer.start() ...
''' Created on Apr 25, 2015 @author: kydos ''' import dds import sys def showShapeType(s): if s != None: msg = "(color: %s, x: %d, y: %d, size: %d)\n" % (s.color, s.x, s.y, s.shapesize) sys.stdout.write(msg) sys.stdout.flush() def readData(dr): samples = dr.read() while samples.hasNe...
from google.cloud import dialogflow_v2beta1 async def sample_create_entity_type(): # Create a client client = dialogflow_v2beta1.EntityTypesAsyncClient() # Initialize request argument(s) entity_type = dialogflow_v2beta1.EntityType() entity_type.display_name = "display_name_value" entity_type.kin...
"""Display objects for the different kinds of charts. Not intended for end users, use the methods in __init__ instead.""" import warnings from mapreduce.lib.graphy.backends.google_chart_api import util class BaseChartEncoder(object): """Base class for encoders which turn chart objects into Google Chart URLS. Object...
from setuptools import setup, find_packages, Command import os with open('LICENSE') as f: license = f.read() class UnitTestCommand(Command): """A custom command to run Pylint on all Python source files.""" description = 'run the unit tests' user_options = [ ] def initialize_options(self): pass def...
while True: print('Loja Tabajara') cont = 1 total = 0 # segundo while para calcular cada produto while True: valor = float(input("Produto {}: R$ ".format(cont))) cont += 1 total += valor # se for digitado 0 encerra a compra if valor == 0: break ...
from __future__ import print_function from __future__ import unicode_literals from __future__ import division import os from email.mime.application import MIMEApplication from django.conf import settings from django.core.files.storage import default_storage from django.core.mail import EmailMessage from django.template...
import json import requests from son_editor.app.database import db_session from son_editor.app.exceptions import NotFound from son_editor.models.descriptor import Function, Service from son_editor.models.repository import Catalogue NS_PREFIX = "network-services" VNF_PREFIX = "vnfs" CATALOGUE_SPECIFIC_URL = "/{type}/ven...
class MethodMixin: def get_all_config(self): resp = self.request_list('GetAllConfig') config = {} for attr in resp: # If there is multiple attributes with the same name if attr['n'] in config: if isinstance(config[attr['n']], str): ...
import os os.system("/data/soft/riak-1.1.4/dev/dev1/bin/riak start") os.system("/data/soft/riak-1.1.4/dev/dev2/bin/riak start") os.system("/data/soft/riak-1.1.4/dev/dev3/bin/riak start") os.system("/data/soft/riak-1.1.4/dev/dev4/bin/riak start") os.system("/usr/local/bin/fdfs_trackerd /etc/fdfs/tracker.conf") os.system...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import * import numpy as np from .utils import MentionScorer from ..annotations import save_marginals class Classifier(object): """Simple abstract base c...
"""Integration providing core pieces of infrastructure.""" import asyncio import itertools as it import logging import voluptuous as vol from homeassistant.auth.permissions.const import CAT_ENTITIES, POLICY_CONTROL import homeassistant.config as conf_util from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_L...
""" Authentication schemes for Moonrock: - Username/password - Twitter """ from urllib.parse import parse_qsl from urllib.parse import urlencode from pyramid.httpexceptions import HTTPFound, HTTPUnauthorized from pyramid_sqlalchemy import Session import requests from requests_oauthlib import OAuth1 from rest_toolkit im...
from enum import Enum, unique @unique class Weekday(Enum): Sun = 0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 day1 = Weekday.Mon print('day1 =', day1) print('Weekday.Tue =', Weekday.Tue) print('Weekday[\'Tue\'] =', Weekday['Tue']) print('Weekday.Tue.value =', Weekday.Tue.value) print('d...
""" Exposes the minimal amount of code to use Win32 native file locking. We only need two APIs, so this is far lighter weight than pulling in all of pywin32. """
from __future__ import annotations import collections.abc import dataclasses import json from typing import * from edb.edgeql import compiler as qlcompiler from edb.ir import staeval from edb.ir import statypes from edb.schema import name as sn from . import types SETTING_TYPES = {str, int, bool, statypes.Duration, sta...
from setuptools import setup, find_packages import os.path VERSION = '0.4.4' NAME = 'openstack-client-shell' module_dir = 'openstack' version_file = os.path.join(module_dir, 'version.py') version_module_contents = """\ version = {version} """.format(version=VERSION) with open(version_file, 'w') as fd: fd.write(vers...
import sys import base64 """ Makes bitextors .docs files humand readable """ if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('-html', help='show HTML', action='store_true') args = parser.parse_args() for line in sys.stdin: line = line.strip()...
class Solution: def shoppingOffers(self, price, special, needs): d = {} def dp(i, needs): if (i, needs) in d: return d[(i, needs)] if i == len(special): return sum(n*price[i] for i, n in enumerate(needs)) needs = list(needs) ...
class DemoPipeline(object): def process_item(self, item, spider): return item
def power(x,n): s = 1 while n > 0: n = n - 1 s = s*x return s def power2(x,n = 2): s = 1 for m in range(1,n+1): s = s*x return s print('利用for函数来计算:') print(power2(4,3)) name1 = int(input('输入power参数计算x的n次方')) name2 = int(input('输入N参数')) print(power(name1,name2)) def enroll...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0008_auto_20170708_1416'), ] operations = [ migrations.AlterField( model_name='post', name='chismes_de', fiel...
import random mac = [ 0x02, random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff), random.randint(0x00, 0xff) ] print ':'.join(map(lambda x: "%02x" % x, mac))
from fixture.actions import ActionsHelper from model.contact import Contact import contextlib import time import re class ContactHelper(ActionsHelper): # @contextlib.contextmanager # def wait_for_page_load(self): # timeout = 6 # wd = self.app.wd # old_page = wd.find_element_by_xpath("//i...
settings = dict( # Defaults the user may wish to override default_instance_size='m1.small', default_ami='ami-9a562df2', # Ubuntu 14.04 LTS sizes=['m3.large', 'm3.xlarge', 'm3.2xlarge', 'm1.small', 'm1.medium', 'm3.medium', 'm1.large', 'm1.xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4...
from tornado import gen from tornado.ioloop import IOLoop from .. import metrics @gen.coroutine def main(): data = yield metrics.fetch_data("http://localhost:3002/", "bst", "drone", auth_username="bst", auth_password="bst") print(data) print("X.shape:\t" + str(data['X'].shape)) print("y.shap...
""" Layer that transforms VNC config objects to ifmap representation """ from cfgm_common.zkclient import ZookeeperClient, IndexAllocator from gevent import ssl, monkey monkey.patch_all() import gevent import gevent.event from gevent.queue import Queue, Empty import time from pprint import pformat from lxml import etre...
from django.test import TestCase from django.db.models import fields from django.db.models.signals import pre_save from django_mixins import MixinBase, ModelBase class PreSaveReveicerTests(TestCase): def test_receiver_must_provide_args(self): class DummyMixinWithFieldsPreSave(MixinBase): instanc...
"""Main training protocol used for structured label prediction models.""" import os import pickle import copy from shared import architectures from shared import train_utils from shared import evaluation_metrics import pandas as pd import tensorflow as tf from tensorflow.python.ops import array_ops, variable_scope from...
from oslo_serialization import jsonutils from mistralclient.api import base from mistralclient import utils class Environment(base.Resource): resource_name = 'Environment' def _set_attributes(self): """Override loading of the "variables" attribute from text to dict.""" for k, v in self._data.ite...
from importlib import import_module from django.apps import AppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "websqlrunner" def ready(self): import_module("websqlrunner.receivers") import_module("websqlrunner.settings")
'''Code representing clocking or resets for an IP block''' from typing import Dict, List, Optional from .lib import check_keys, check_list, check_bool, check_optional_name import re class ClockingItem: def __init__(self, clock: Optional[str], reset: Optional[str], ...
def match_ends(words): matchingWords = 0 for word in words: if len(word)>1: if word[0]==word[-1]: matchingWords += 1 return matchingWords def front_compare(word): if word[0]=='x': return ' '+word else: return 'Z'+word def front_x(words): return sorted(words, key = front_compare) def sort_...
__version__ = '3.0.0.2.dev1' import re from flask import Blueprint, current_app, url_for try: from wtforms.fields import HiddenField except ImportError: def is_hidden_field_filter(field): raise RuntimeError('WTForms is not installed.') else: def is_hidden_field_filter(field): return isinstan...
from gwt.ui.FocusPanel import ( ClickHandler, DOM, Factory, Focus, FocusHandler, FocusMixin, FocusPanel, KeyboardHandler, MouseHandler, SimplePanel, )
"""Gevent Session.""" try: import grequests import gevent from gevent.threading import Lock except ModuleNotFoundError as e: print("grequests is not installed, try pip install grequests") raise e try: import gevent from gevent.threading import Lock except ModuleNotFoundError as e: print(...
policy_data = """ { "admin_api": "role:admin", "admin_or_owner": "is_admin:True or project_id:%(project_id)s", "context_is_admin": "role:admin or role:administrator", "default": "rule:admin_or_owner" } """
import pyexpat print( "Imported pyexpat, should use our one." ) print( dir(pyexpat) )
"""Tests for tink.tools.testing.python.testing_server.""" from absl.testing import absltest import grpc import tink from tink import aead from tink import daead from tink import hybrid from tink import mac from tink import prf from tink import signature from tink import streaming_aead from proto.testing import testing_...
from time import sleep from machine import Pin while True: pin = Pin(4, Pin.OUT, value=1) # set pin high on creation sleep(1.0) pin.value(0) sleep(0.2) pin.value(1) sleep(0.2) pin.value(0) sleep(0.2)
import optparse from collections import defaultdict import numpy as np def stacking_create_training_set_silk(input_file_name,output_file_name,gold_standard_name,N): input_read = open(input_file_name,'rU') #read input file train = open(output_file_name,'w') #write on output file gold_standard_read = op...
from pycalendar.datetime import DateTime from pycalendar.timezone import Timezone from txweb2 import responsecode from txweb2.dav.http import ErrorResponse from txweb2.dav.noneprops import NonePropertyStore from txweb2.dav.util import allDataFromStream from txweb2.http import Response, HTTPError, StatusResponse, XMLRes...
import pytest from unittest import mock from aiohttp import helpers import datetime def test_parse_mimetype_1(): assert helpers.parse_mimetype('') == ('', '', '', {}) def test_parse_mimetype_2(): assert helpers.parse_mimetype('*') == ('*', '*', '', {}) def test_parse_mimetype_3(): assert (helpers.parse_mime...
""" processing of timeseries """ import logging logger = logging.getLogger(__name__) from netCDF4 import Dataset from cdo import * # python version cdo = Cdo() cdo.forceOutput = True def fldmean(resource, prefix=None, dir_output = None ): from os import path # join, basename , curdir from os import mkdir """ ...
import getpass import os from threading import Thread from flask import Flask, session, redirect, url_for, render_template, flash from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_script import Manager, Shell from flask_sqlalchemy import SQLAlchemy from flask_wtf import Form from wtforms ...
"kapitan targets" import json import logging import multiprocessing import os import shutil import sys import tempfile import time from collections import defaultdict from functools import partial import jsonschema import yaml from kapitan import cached, defaults from kapitan.dependency_manager.base import fetch_depend...
from google.appengine.ext import db import django from django import shortcuts from blog.models import BlogPost def index(request): """Displays the index page.""" # Fetch all of the BlogPosts posts = BlogPost.all().order('-date') # Setup the data to pass on to the template template_values = { ...
from pyro.contrib.gp.parameterized import Parameterized class Likelihood(Parameterized): """ Base class for likelihoods used in Gaussian Process. Every inherited class should implement a forward pass which takes an input :math:`f` and returns a sample :math:`y`. """ def __init__(self): s...
import socket import time from azurelinuxagent.common.datacontract import DataContract, DataContractList from azurelinuxagent.common.future import ustr from azurelinuxagent.common.utils.flexible_version import FlexibleVersion from azurelinuxagent.common.utils.textutil import getattrib from azurelinuxagent.common.versio...
import os import argparse import logging from alembic import config as alembic_config from alembic import command as alembic_command from alembic import util as alembic_util from apiocr import cfg from apiocr import log from apiocr import db LOG = logging.getLogger(__name__) def do_alembic_command(cmd, *args, **kwargs)...
import socket import time import sys import random import math import threading msg_header = 'AADD' msg_stamp = '\x00\x00\x00\x00' msg_id_gw = '2016A008' msg_id_dev = '00000000' msg_devtype = '\x01\x00' msg_auth_key = '88888888' msg_auth_datatype = '\x1c\x00' msg_auth = msg_header+msg_stamp+msg_id_gw+msg_id_dev+msg_dev...
from .services.adaptation import AdaptationClient from .services.adaptation import AdaptationAsyncClient from .services.speech import SpeechClient from .services.speech import SpeechAsyncClient from .types.cloud_speech import LongRunningRecognizeMetadata from .types.cloud_speech import LongRunningRecognizeRequest from ...
import os import time class Watcher(object): def __init__(self, conf, logger): self.audit_type = None self.outfile = None self.logger = logger def start(self, audit_type): filename = "/tmp/%s-%d.auditlog" % (audit_type, os.getpid()) self.outfile = open(filename, "a") ...
import imaplib import imaplib_connect with imaplib_connect.open_connection() as c: # Find the "SEEN" messages in INBOX c.select('INBOX') typ, [response] = c.search(None, 'SEEN') if typ != 'OK': raise RuntimeError(response) msg_ids = ','.join(response.decode('utf-8').split(' ')) # Create ...
import logging from cloudify import manager from cloudify import context from cloudify.decorators import workflow from cloudify import exceptions as cfy_exc from cloudify import ctx as CloudifyContext from cloudify_rest_client.client import CloudifyClient from cloudify_common_sdk.filters import (get_field_value_recursi...
"""Task definition for evaluator code.""" import numpy as np from common.framework import LpTask DATASET = 'cifar10' L2_THRESHOLD = 1.0 LINF_THRESHOLD = 4.0 / 255.0 TASKS = { 'attack_linf.py': LpTask(np.inf, LINF_THRESHOLD), 'attack_linf_torch.py': LpTask(np.inf, LINF_THRESHOLD), 'attack_linf_soln.py': LpTa...
""" Fine-tuning a 🤗 Transformers model on text translation. """ import argparse import logging import math import os import random import datasets import numpy as np import torch from datasets import load_dataset, load_metric from torch.utils.data.dataloader import DataLoader from tqdm.auto import tqdm import transfor...
""" @author wangzheng11@baidu.com @date 2014/10/08 @brief put_disableDomainDkim """ import os import sys import time import traceback _NOW_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' _BCE_PATH = _NOW_PATH + '../' sys.path.insert(0, _BCE_PATH) import bes_base_case from baidubce.services.ses import client fro...