content
stringlengths
4
20k
''' Created on Apr 4, 2017 kNN: k Nearest Neighbors Input: inX: vector to compare to existing dataset (1xN) dataSet: size m data set of known vectors (NxM) labels: data set labels (1xM vector) k: number of neighbors to use for comparison (should be an odd number) O...
from org.apache.hadoop.fs import Path from org.apache.hadoop.io import * from org.apache.hadoop.mapred import * from org.apache.hadoop.abacus import * from java.util import *; import sys class AbacusMapper(ValueAggregatorMapper): def map(self, key, value, output, reporter): ValueAggregatorMapper.map(sel...
import regtran # control board interface module # TODO: # factor out HEX file parsing to a separate module def wordToByteString(word): return eval('"\\x' + hex(word & 0xff)[2:].rjust(2, '0') + '\\x' + hex((word & 0xff00) >> 8)[2:].rjust(2, '0') + '"') class ControlBoard: REG_STATE = 's' REG_ADDRESS = 'a' REG_FL...
# -*- coding: utf-8 -*- """ ymir.schema.validators """ import os from voluptuous import Invalid def nested_vagrant_validator(dct, ): """ """ if not isinstance(dct, dict): err = ("expected hash for key @ `vagrant`") raise Invalid(err) for key in 'name boot_timeout box box_check_update sync_...
import unittest import writer_code import os class TestFileDumper(unittest.TestCase): def testDumpVariablesImpl(self): tempType = writer_code.TemplateType('std::map', [writer_code.intType, writer_code.stringType], 'map') tempVar = writer_code.Variable('pippo', tempType) dumper = writer_cod...
# coding: utf-8 from __future__ import unicode_literals import os.path import re from .common import InfoExtractor from ..compat import compat_urllib_parse_unquote from ..utils import url_basename class DropboxIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?dropbox[.]com/sh?/(?P<id>[a-zA-Z0-9]{15})/.*' ...
from __future__ import unicode_literals from django.test import TestCase from .models import Tournament, Organiser, Pool, PoolStyle class ExistingRelatedInstancesTests(TestCase): fixtures = ['tournament.json'] def test_foreign_key(self): with self.assertNumQueries(2): tournament = Tourna...
from bisect import bisect_left, insort class search: def __init__(self): self.values = [] def insert(self, value): assert not value in self.values print "insert", value insort(self.values, value) def delete(self, value): assert value in self.values print "delete", value assert(self.values.pop(self.po...
import re from random import randrange from struct import pack, unpack def generate(): # UHm... crappy Python has an maximum integer of 2**31-1. top = (1L<<31)-1 return pack("IIII", randrange(top), randrange(top), randrange(top), randrange(top)) def bin_to_string(uuid): uuid1, uuid2, uuid3 = unpack('...
# import curvyEdges;curvyEdges.UI() import maya.cmds as cmds import pymel.core as pm class UI(object): def __init__(self): title = 'curvyEdges' version = '1.01' self.ceObj = spline(self) if pm.window('curvyEdgesWin', exists=True): pm.deleteUI('curvyEdgesWin') ...
from operator import * import os.path import sys import unittest import warnings if __name__ == '__main__': # Only munge path if invoked as a script. Testrunners should have setup # the paths already sys.path.insert(0, os.path.abspath(os.path.join(os.pardir, os.pardir))) from pytz.lazy import LazyList, ...
"""Import core names of TensorFlow. Programs that want to build TensorFlow Ops and Graphs without having to import the constructors and utilities individually can import this file: from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf ""...
import sys import unittest from html5lib.filters.formfiller import SimpleFilter class FieldStorage(dict): def getlist(self, name): l = self[name] if isinstance(l, list): return l elif isinstance(l, tuple) or hasattr(l, '__iter__'): return list(l) return [l] ...
#!/usr/bin/env python3 import sys import argparse import os from tqdm import tqdm from ucca.ioutil import file2passage, passage2file, external_write_mode desc = """Parses an XML in UCCA standard format, and writes them in binary Pickle format.""" def main(args): os.makedirs(args.outdir, exist_ok=True) for ...
from __future__ import absolute_import, division, print_function __metaclass__ = type import sys import importlib import pytest from .FakeAnsibleModule import FakeAnsibleModule @pytest.fixture def fake_ansible_module(request): """Returns fake AnsibleModule with fake module params.""" if hasattr(request, 'p...
# -*- coding: utf-8 -*- # http://www.statoids.com/upy.html DEPARTMENT_CHOICES = ( ('AG', u'Alto Paraguay'), ('AA', u'Alto Paraná'), ('AM', u'Amambay'), ('AS', u'Asunción'), ('BQ', u'Boquerón'), ('CG', u'Caaguazú'), ('CZ', u'Caazapá'), ('CY', u'Canindeyú'), ('CE', u'Central'), (...
from grimoirelib_alch.query.its import ( DB as ITSDB, Query as ITSQuery ) from grimoirelib_alch.query.common import GrimoireDatabase from sqlalchemy import func, Column, Integer, ForeignKey, or_ from sqlalchemy.sql import label class DB (ITSDB): """Class for dealing with SCR (Bicho-Gerrit) databases. ...
""" Reactor-based Services Here are services to run clients, servers and periodic services using the reactor. If you want to run a server service, L{StreamServerEndpointService} defines a service that can wrap an arbitrary L{IStreamServerEndpoint} as an L{IService}. See also L{twisted.internet.strports.service} for c...
from importlib import import_module import os from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured from django.utils.module_loading import module_has_submodule from django.utils._os import upath MODELS_MODULE_NAME = 'models' class AppConfig(object): """ Class representing a Django a...
""" A module with various ``typing.Protocol`` subclasses that implement the ``__call__`` magic method. See the `Mypy documentation`_ on protocols for more details. .. _`Mypy documentation`: https://mypy.readthedocs.io/en/stable/protocols.html#callback-protocols """ from __future__ import annotations import sys fro...
from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render from spark.activities.models import Notification from spark.decorators import ajax_required @login_required def notifications(request): user = request.user notifications = Notifi...
#!/usr/bin/python """ " @section DESCRIPTION " Helper functions for training and evaluating RF models """ import os import numpy as np import cPickle as pickle from scipy.io import loadmat from scipy.linalg import toeplitz from sklearn.neighbors import kneighbors_graph from numpy.lib import stride_tricks from operator...
from mozdef_util.utilities.toUTC import toUTC from mq.plugins.stackdriver import message class TestStackDriver(object): def setup(self): self.plugin = message() self.metadata = {"index": "events"} # Should never match and be modified by the plugin def test_nodetails_log(self): met...
import os, sys, string, random, tempfile, unittest from test.test_support import run_unittest class TestImport(unittest.TestCase): def __init__(self, *args, **kw): self.package_name = 'PACKAGE_' while self.package_name in sys.modules: self.package_name += random.choose(string...
from __future__ import absolute_import, division, print_function from datetime import timedelta from tornado import gen, locks from tornado.gen import TimeoutError from tornado.testing import gen_test, AsyncTestCase from tornado.test.util import unittest, skipBefore35, exec_test class ConditionTest(AsyncTestCase): ...
"""Audio tools for recording and analyzing audio. The audio tools provided here are mainly to: - record playing audio. - remove silence from beginning and end of audio file. - compare audio files using PESQ tool. The tools are supported on Windows and Linux. """ import commands import ctypes import logging import os...
import requests from xml.etree import ElementTree from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate import time def getWeatherMessages(): 'Grabs weather information from NOAH and returns a some information about the forecast' weather_url = 'http://graphical.weather.gov/xml/SOAP_serv...
import os import logging from autotest.client.shared import error from autotest.client import utils from virttest import virsh from virttest import xml_utils from virttest import libvirt_storage from virttest import libvirt_xml from virttest.utils_test import libvirt as utlv from provider import libvirt_version def r...
import unittest from mock import Mock, patch from common import cleanup_json import utils from utils import ServicePortAssigner class TestUtils(unittest.TestCase): def test_get_task_ip_and_ports_ip_per_task(self): app = { "ipAddress": { "discovery": { "p...
import configparser import os import shlex import shutil import shell import shouter config = None configfile = None user = None password = None stored = None def read(configname=None): if not configname: global configfile configname = configfile parsedconfig = configparser.ConfigParser() ...
import os import sys import logging import platform try: import sh except ImportError: import pbs as sh SUPPORTED_PLATFORMS = { "Ubuntu": [ "trusty", ], } APT_DEPENDENCIES = { "trusty": [ "closure-compiler", "libffi-dev", "memcached", "rabbitmq-server", ...
import os from setuptools import setup this_dir = os.path.dirname(__file__) long_description = "\n" + open(os.path.join(this_dir, 'README.rst')).read() setup( name='hmac_cli', version='0.0.0', description='Simple CLI for encrypting data with a private key, using HMAC', long_description=long_descriptio...
"""The tests for the Dialogflow component.""" import json from unittest.mock import Mock import pytest from homeassistant import data_entry_flow from homeassistant.components import dialogflow, intent_script from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "a...
# coding=utf-8 """ © 2014 LinkedIn Corp. 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 ...
#!/usr/bin/env python3 import sys import os from sigil_bs4 import BeautifulSoup from sigil_bs4.builder._lxml import LXMLTreeBuilderForXML import re from urllib.parse import unquote from urllib.parse import urlsplit from lxml import etree from io import BytesIO from opf_newparser import Opf_Parser from hrefutils import...
from kippo.core.honeypot import HoneyPotCommand from kippo.core.fs import * from twisted.web import client from twisted.internet import reactor import stat, time, urlparse, random, re, exceptions import os.path commands = {} def tdiff(seconds): t = seconds days = int(t / (24 * 60 * 60)) t -= (days * 24 * ...
from ._pylib import ffi, lib from . import createCallback createCallback("mLoggerPy", "log", "_pyLog") defaultLogger = None def installDefault(logger): global defaultLogger defaultLogger = logger lib.mLogSetDefaultLogger(logger._native) class Logger(object): FATAL = lib.mLOG_FATAL DEBUG = lib.mL...
import unittest import tqdm from ieml.dictionary.script import Script from ieml.ieml_database import IEMLDatabase, GitInterface from ieml.usl import PolyMorpheme, Lexeme, Word from ieml.usl.decoration.parser.parser import PathParser from ieml.usl.decoration.path import PolymorphemePath, GroupIndex, FlexionPath, Lexem...
from sqlalchemy import Column from sqlalchemy import MetaData from sqlalchemy import Table from sqlalchemy import Text def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine # Add a new column metrics to save metrics info for compute nodes compute_nodes = Table('compute_nodes', met...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import json import logging from pprint import pformat from ansible.module_utils.basic impor...
from __future__ import unicode_literals from django.db import models from django.test import TestCase from rest_framework import serializers from .models import OneToOneTarget class OneToOneSource(models.Model): name = models.CharField(max_length=100) target = models.OneToOneField(OneToOneTarget, r...
from __future__ import absolute_import # -*- coding: utf-8 -*- import json from datetime import datetime from xml.dom import minidom from StringIO import StringIO from django.conf import settings from django.core import serializers from django.db import transaction, connection from django.test import TestCase, Transa...
"""A Python driver for PostgreSQL psycopg is a PostgreSQL_ database adapter for the Python_ programming language. This is version 2, a complete rewrite of the original code to provide new-style classes for connection and cursor objects and other sweet candies. Like the original, psycopg 2 was written with the aim of b...
#!/usr/bin/python ''' Jsunpackn - A generic JavaScript Unpacker Network Edition Copyright (C) 2010 Blake Hartstein http://jsunpack.jeek.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Softwar...
from taiga.base.api.permissions import TaigaResourcePermission, AllowAny, IsSuperUser from taiga.permissions.permissions import HasProjectPerm, IsProjectAdmin class UserTimelinePermission(TaigaResourcePermission): enought_perms = IsSuperUser() global_perms = None retrieve_perms = AllowAny() class Projec...
#!/usr/bin/env python # run with nose: nosetests -v test_euler.py from nose.tools import * import networkx as nx from networkx import is_eulerian,eulerian_circuit class TestEuler: def test_is_eulerian(self): assert_true(is_eulerian(nx.complete_graph(5))) assert_true(is_eulerian(nx.complete_graph(...
import abc import inspect import logging import random import sys from collections import namedtuple log = logging.getLogger("edx.courseware") # This is a tuple for holding scores, either from problems or sections. # Section either indicates the name of the problem or the name of the section Score = namedtuple("Scor...
""" Supplies the internal functions for functools.py in the standard library """ # reduce() has moved to _functools in Python 2.6+. reduce = reduce class partial(object): """ partial(func, *args, **keywords) - new function with partial application of the given arguments and keywords. """ def __in...
#!/usr/bin/env Python """ Definition List Extension for Python-Markdown ============================================= Added parsing of Definition Lists to Python-Markdown. A simple example: Apple : Pomaceous fruit of plants of the genus Malus in the family Rosaceae. : An american computer co...
# -*- coding: utf-8 -*- import logging from copy import deepcopy import sys from modularodm import Q from framework.transactions.context import TokuTransaction from website.app import init_app from website.models import NodeLog from scripts import utils as script_utils logger = logging.getLogger(__name__) def get_t...
from typing import Any from unittest.mock import patch from zerver.lib.test_classes import WebhookTestCase class BeeminderHookTests(WebhookTestCase): STREAM_NAME = 'beeminder' URL_TEMPLATE = "/api/v1/external/beeminder?api_key={api_key}&stream={stream}" FIXTURE_DIR_NAME = "beeminder" @patch('zerver....
import unittest from handlers.statusbubble import StatusBubble from model.queues import Queue class MockAttachment(object): def __init__(self): self.id = 1 def status_for_queue(self, queue): return None def position_in_queue(self, queue): return 1 class StatusBubbleTest(unitt...
import os import integration_tests class TourTestCase(integration_tests.TestCase): def test_tour_no_arg(self): output = self.run_snapcraft('tour') self.assertTrue(os.path.isdir('snapcraft-tour'), 'Tour directory was created') self.assertIn('Snapcraft tour initiali...
# coding: utf-8 from __future__ import unicode_literals import re import time from .common import InfoExtractor from ..compat import ( compat_ord, ) from ..utils import ( int_or_none, parse_duration, ) class XMinusIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?x-minus\.org/track/(?P<id>[0-9]+)...
from pyspark.sql import SparkSession spark = SparkSession\ .builder\ .appName("Cloudant Spark SQL Example in Python using temp tables")\ .config("cloudant.host","ACCOUNT.cloudant.com")\ .config("cloudant.username", "USERNAME")\ .config("cloudant.password","PASSWORD")\ .getOrCreate() # ***1. L...
"""Sensor to get GTT's timetable for a stop.""" import logging from datetime import timedelta, datetime import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import DEVICE_CLASS_TIMESTAMP from homeassistant.helpers.entity import Entity import homeassistant.helpe...
#!/usr/bin/env python import fileinput import os base_url = 'https://mapbox.s3.amazonaws.com/mapbox-studio' html_start = ''' <html> <head><title>Mapbox Studio downloads</title></head> <body bgcolor="white"> <h1>Mapbox Studio downloads</h1><hr><pre> ''' html_end = ''' </pre><hr></body> </html> ''' line_template = '...
from unittest import mock from ironic.common import exception from ironic.conductor import task_manager from ironic.drivers.modules import ipmitool from ironic.tests.unit.drivers.modules.intel_ipmi import base class IntelIPMIManagementTestCase(base.IntelIPMITestCase): def test_configure_intel_speedselect_empty(s...
from openerp import _, api, exceptions, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" @api.model def _purchase_request_confirm_message_content(self, po, request, request_dict): if not request_dict: reque...
"""engine.SCons.Tool.f95 Tool-specific initialization for the generic Posix f95 Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2...
from spack import * import glob class Redundans(Package): """Redundans pipeline assists an assembly of heterozygous genomes.""" homepage = "https://github.com/Gabaldonlab/redundans" url = "https://github.com/Gabaldonlab/redundans/archive/v0.13c.tar.gz" git = "https://github.com/Gabaldonlab/...
from itertools import cycle import random import sys import time import datetime import logging import os import pygame from pygame.locals import * import matplotlib.pyplot as plt import json from genome import Genome from network import Network from population import Population from config import Config import pick...
import sys, traceback from async import asynchat from rencode import loads, dumps class Channel(asynchat.async_chat): endchars = '\0---\0' def __init__(self, conn=None, addr=(), server=None, map=None): asynchat.async_chat.__init__(self, conn, map) self.addr = addr self._server = server self._ibuffer = "" ...
"""An example workflow that demonstrates filters and other features. - Reading and writing data from BigQuery. - Manipulating BigQuery rows (as Python dicts) in memory. - Global aggregates. - Filtering PCollections using both user-specified parameters as well as global aggregates computed during pipeline e...
""" Tests for chi2, currently the only feature selection function designed specifically to work with sparse matrices. """ import numpy as np from scipy.sparse import coo_matrix, csr_matrix import scipy.stats from sklearn.feature_selection import SelectKBest, chi2 from sklearn.feature_selection.univariate_selection im...
from collections import namedtuple from django import forms from django.conf import settings from django.db import models from django.db.models.fields import related from django.utils import translation as translation_utils from django.utils.translation.trans_real import to_language import six from .hold import add_...
import multiprocessing import subprocess import sys import threading TEST_CMD_TEMPLATE = 'python manage.py test -x --nologcapture \ --with-nose-picker --which-process=%d --total-processes=%d --noinput' def main(): num_processes = int(multiprocessing.cpu_count()) tests = [] for i in...
from __future__ import print_function, division from sympy.core.decorators import wraps from sympy.core.compatibility import range def recurrence_memo(initial): """ Memo decorator for sequences defined by recurrence See usage examples e.g. in the specfun/combinatorial module """ cache = initial ...
import BaseHTTPServer from thrift.server import TServer from thrift.transport import TTransport class THttpServer(TServer.TServer): """A simple HTTP-based Thrift server This class is not very performant, but it is useful (for example) for acting as a mock version of an Apache-based PHP Thrift endpoint.""" d...
""" Soundcloud OAuth2 backend, docs at: http://psa.matiasaguirre.net/docs/backends/soundcloud.html """ from social.p3 import urlencode from social.backends.oauth import BaseOAuth2 class SoundcloudOAuth2(BaseOAuth2): """Soundcloud OAuth authentication backend""" name = 'soundcloud' AUTHORIZATION_URL = ...
from contextlib import nested import mock from neutron.openstack.common import importutils from neutron.tests import base OVSBRIDGE = 'neutron.agent.linux.ovs_lib.OVSBridge' PLUGINAPI = 'neutron.plugins.bigswitch.agent.restproxy_agent.PluginApi' CONTEXT = 'neutron.context' CONSUMERCREATE = 'neutron.agent.rpc.create_...
class render(object): """ Represents a report job being rendered. @param bin_datas a dictionary of name:<binary content> of images etc. @param path the path in which binary files can be discovered, useful for components (images) of the report. It can be: - a string, relative ...
import datetime from tempest.api.compute import base from tempest import test from tempest_lib import exceptions as e # Time that waits for until returning valid response # TODO(takmatsu): Ideally this value would come from configuration. VALID_WAIT = 30 class TenantUsagesTestJSON(base.BaseV2ComputeAdminTest): ...
import os import leveldb import time import threading import random import shutil import socket import base64 import cPickle import marshal import json import hashlib SERIALIZER = cPickle from kunai.stats import STATS from kunai.log import logger from kunai.threadmgr import threader from kunai.now import NOW # Will...
import sys import re import optparse import libavg class Option(object): def __init__(self, key, value, help=None): if not isinstance(key, str): raise ValueError('The type of %s key is not string (value=%s)' % (key, value)) self.__key = key self.value = value self.__h...
# Loader __author__="jim" __date__ ="$Jan 18, 2011 1:36:37 PM$" import procgame import locale from procgame import * import random import os import logging from procgame._version import __version_info__ base_path = config.value_for_key_path('base_path') game_path = base_path+"games/whirlwind/" speech_path = game_p...
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any l...
import os import copy import h5py from lazyflow.utility import PathComponents from lazyflow.graph import Graph from lazyflow.operators.ioOperators import OpInputDataReader, OpFormattedDataExport from ilastik.applets.pixelClassification.opPixelClassification import OpArgmaxChannel from ilastik.applets.dataExport.dataEx...
""" """ import os from neoteric.util.files import read_file, dir_of_file from neoteric.parsers.flat import FlatParser from neoteric.resource.package import Package from neoteric.resource.service import Service from neoteric.util.type import type_assert __all__ = ['SshdConfig', 'configure', 'SSHD_CONFIG_TEMPLATE'] ...
""" =================================================================== Multi-output Decision Tree Regression =================================================================== An example to illustrate multi-output regression with decision tree. The :ref:`decision trees <tree>` is used to predict simultaneously the ...
"""Generate and work with PEP 425 Compatibility Tags.""" import sys import warnings try: import sysconfig except ImportError: # pragma nocover # Python < 2.7 import distutils.sysconfig as sysconfig import distutils.util def get_config_var(var): try: return sysconfig.get_config_var(var) ...
#!/usr/bin/python """ requires tlslite - http://trevp.net/tlslite/ """ import binascii from gdata.tlslite.utils import keyfactory from gdata.tlslite.utils import cryptomath # XXX andy: ugly local import due to module name, oauth.oauth import gdata.oauth as oauth class OAuthSignatureMethod_RSA_SHA1(oauth.OAuthSign...
import logging import re from django import http from django.conf import settings from django.core import urlresolvers from django.core.exceptions import PermissionDenied from django.core.mail import mail_managers from django.utils.cache import get_conditional_response, set_response_etag from django.utils.encoding imp...
import proto # type: ignore from google.monitoring.dashboard_v1.types import scorecard as gmd_scorecard from google.monitoring.dashboard_v1.types import text as gmd_text from google.monitoring.dashboard_v1.types import xychart from google.protobuf import empty_pb2 as empty # type: ignore __protobuf__ = proto.modu...
import time import json import collections # COMMON CODE FOR MIGRATION import re from ansible.module_utils.basic import get_exception from ansible.module_utils.netcfg import NetworkConfig, ConfigLine from ansible.module_utils.shell import ShellError try: from ansible.module_utils.nxos import get_module except Im...
""" Forms in OpenLP are made up of two classes. One class holds all the graphical elements, like buttons and lists, and the other class holds all the functional code, like slots and loading and saving. The first class, commonly known as the **Dialog** class, is typically named ``Ui_<name>Dialog``. It is a slightly mod...
import struct class Readable(object): @classmethod def from_string(cls,string): """Takes a bytestring and returns an object loaded from that bytestring.""" t = struct.unpack(cls._struct_format,string) d = {} for n,i in enumerate(cls._struct_fields): if i: ...
import logging from collections import defaultdict from functools import partial import seq2seq.data.config as config class Tokenizer: """ Tokenizer class. """ def __init__(self, vocab_fname=None, pad=1, separator='@@'): """ Constructor for the Tokenizer class. :param vocab_f...
#!/usr/bin/python import argparse import re import gzip import sys import string import os from make import MakeEntry from make import MakeFile ############## # INPUT PROCESSSING ############## calling_dir = os.path.dirname(os.path.realpath(__file__)) print "########################################################" ...
# coding: utf-8 # - 练习 1:写程序,可由键盘读入用户姓名例如Mr. right,让用户输入出生的月份与日期,判断用户星座,假设用户是金牛座,则输出,Mr. right,你是非常有性格的金牛座!。 # In[1]: name=input('what is your name ?') print('when is you birthday ?example:5月21输入为以下各式:521') birthday=int(input()) if 421<=birthday<=521 : print('Mr.',name,'你是非常有个性的金牛座!') # - 练习 2:写程序,可由键盘读入两...
import os def generate(env, gcc_cross_prefix=None, gcc_strict=True, gcc_stop_on_warning=None, gcc_extra_options=''): if gcc_stop_on_warning == None: gcc_stop_on_warning = env['stop_on_warning'] ### compiler flags if gcc_strict: env.AppendUnique(CCFLAGS = ['-pedantic', '-Wall', '-W', '-Wundef', ...
"""Tests for Sliced Wasserstein Distance.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from scipy import ndimage from tensorflow.contrib.gan.python.eval.python import sliced_wasserstein_impl as swd from tensorflow.python.framework i...
# encoding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor class MailRuIE(InfoExtractor): IE_NAME = 'mailru' IE_DESC = 'Видео@Mail.Ru' _VALID_URL = r'http://(?:www\.)?my\.mail\.ru/(?:video/.*#video=/?(?P<idv1>(?:[^/]+/){3}\d+)|(?:(?P<idv2prefix>(?:[^/]+/){2})vi...
from . import base from .decorators import * import tuned.logs from tuned.utils.commands import commands import os import re log = tuned.logs.get() class VideoPlugin(base.Plugin): """ Plugin for tuning powersave options for some graphic cards. """ def _init_devices(self): self._devices_supported = True self....
""" Mostly deprecated clustering and data structural analysis routines. """ from typing import Tuple import numpy as np from matplotlib import pyplot as plt from scipy import sparse as spmat from bioflow.annotation_network.knowledge_access_analysis import ref_param_set, \ get_go_interface_instance from bioflow....
"""Utility functions for simple-salesforce""" import xml.dom.minidom from simple_salesforce.exceptions import ( SalesforceGeneralError, SalesforceExpiredSession, SalesforceMalformedRequest, SalesforceMoreThanOneRecord, SalesforceRefusedRequest, SalesforceResourceNotFound ) # pylint: disable=invalid-name...
#!/usr/bin/python # -*- coding: utf-8 -*- """ PyCOMPSs Testbench ======================== """ # Imports import unittest from pycompss.api.task import task from pycompss.api.parameter import * from pycompss.api.binary import binary from pycompss.api.compss import compss from pycompss.api.constraint import constrain...
import json vocab_file="/iesl/canvas/nmonath/data/wikipedia/20160305/en/enwiki-20160305-lstm-vocab.tsv" entity_to_freebase_mapping="/iesl/canvas/nmonath/data/freebase/20160513/en-freebase_wiki_cat_title_map.txt" #Read the entity_to_freebase_mapping file print('Read the entity_to_freebase_mapping file') name_to_mid = ...
import unittest from robot.model import Message from robot.utils.asserts import assert_equal, assert_raises from robot.utils import PY2, PY3 if PY3: unicode = str class TestHtmlMessage(unittest.TestCase): def test_empty(self): assert_equal(Message().html_message, '') assert_equal(Message(h...
import numpy as np import scipy.linalg as LA def lqr_gain(A,B,Q,R): ''' Arguments: State transition matrices (A,B) LQR Costs (Q,R) Outputs: K: optimal infinite-horizon LQR gain matrix given ''' # solve DARE: M=LA.solve_discrete_are(A,B,Q,R) # K=(B'MB + R)^(-1)*(B'MA) return np.dot(LA.inv(...