src stringlengths 721 1.04M |
|---|
from numpy import zeros, array
class Ansys(object):
def __init__(self, log=None, debug=False):
pass
def read_ansys(self, ansys_filename):
with open(ansys_filename, 'r') as ansys_file:
lines = ansys_file.readlines()
nodes = []
elements = {}
i = 0
nl... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from lib.meos import MEoS
from lib import unidades
class nC5(MEoS):
"""Multiparameter equation of state for n-pentane"""
name = "pentane"
CASNumber = "109-66-0"
formula = "CH3-(CH2)3-CH3"
synonym = "R-601"
rhoc = unidades.Density(232.)
Tc = unidad... |
# -*- coding: utf-8 -*-
"""
celery.app.defaults
~~~~~~~~~~~~~~~~~~~
Configuration introspection and defaults.
"""
from __future__ import absolute_import
import sys
from collections import deque, namedtuple
from datetime import timedelta
from celery.five import items
from celery.utils import strtobool
f... |
config = {
"nightly_build": True,
"branch": "mozilla-central",
"en_us_binary_url": "https://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-central/",
"update_channel": "nightly",
# l10n
"hg_l10n_base": "https://hg.mozilla.org/l10n-central",
# mar
"enable_partials": True... |
from ..plugin import SimStatePlugin
from ...errors import SimMemoryError
from .. import sim_options as opts
import logging
l = logging.getLogger("angr.state_plugins.heap.heap_base")
# TODO: derive heap location from SimOS and binary info for something more realistic (and safe?)
DEFAULT_HEAP_LOCATION = 0xc0000000
DE... |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", path_list=[
[TestAction.add_image, 'image1', 'root', os.environ.get('isoForVmUrl')],
[TestAction.create_vm_by_image, 'image1', 'iso', 'vm1'],
[TestAction.create_v... |
# python
# This file is generated by a program (mib2py).
import ACCOUNTING_CONTROL_MIB
OIDMAP = {
'1.3.6.1.2.1.60': ACCOUNTING_CONTROL_MIB.accountingControlMIB,
'1.3.6.1.2.1.60.1': ACCOUNTING_CONTROL_MIB.acctngMIBObjects,
'1.3.6.1.2.1.60.1.1': ACCOUNTING_CONTROL_MIB.acctngSelectionControl,
'1.3.6.1.2.1.60.1.2': ACCO... |
# -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# MNEMONIC class for BIP0039 Mnemonic Key management
# © 2016 - 2020 November - 1200 Web Development <http://1200wd.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero ... |
"""This code does not work as for it will raise connection error"""
import requests
from bs4 import BeautifulSoup
import re
from time import sleep
def is_video(td):
"""it is a video if two prerequisites"""
pricelabels = td('span', 'pricelabel')
return(len(pricelabels) == 1 and
pricelabels[0].text.strip().startwi... |
"""empty message
Revision ID: 9e8429737ba0
Revises: ecbe7bbcbd6c
Create Date: 2017-08-12 19:53:27.652000
"""
# revision identifiers, used by Alembic.
revision = '9e8429737ba0'
down_revision = 'ecbe7bbcbd6c'
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
def upgrade():
# ### commands au... |
#!/usr/bin/env pypy
import sys
from datetime import datetime
from clipper import *
from timer import Timer
# import resource
from multiprocessing.dummy import Pool
from functools import partial
import math
import traceback
import threading
import logging
from operator import itemgetter, attrgetter
from copy import c... |
# coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class K8sIoApi... |
from plex.objects.core.base import Property
from plex.objects.library.metadata.base import Metadata
from plex.objects.library.metadata.photo import PhotoAlbum
from plex.objects.library.video import Video
class Clip(Video, Metadata):
grandparent = Property(resolver=lambda: Clip.construct_grandparent)
parent = ... |
from discord import Member, Role
from discord.ext.commands import Context
from cogbot.cogs.abc.base_cog import BaseCogServerState
from cogbot.cogs.join_leave.join_leave_options import JoinLeaveOptions
class JoinLeaveServerState(BaseCogServerState[JoinLeaveOptions]):
async def create_options(self) -> JoinLeaveOpt... |
"""Command line tool for creating ADDML metadata."""
from __future__ import unicode_literals
import io
import os
import sys
import csv
import six
import click
import addml
import lxml.etree as ET
from siptools.mdcreator import MetsSectionCreator
from siptools.utils import encode_path
click.disable_unicode_literals_... |
import numpy as np
import pandas as pd
import arff
import pdb
def main():
data = np.load('amazon.npy')
# Shuffle the data
sfflidx = np.random.permutation(data.shape[0])
data = data[sfflidx]
testidx = int(data.shape[0] * 0.7)
testdata = data[testidx:, ]
traindata = data[0:testidx, ]
... |
# pylint: disable=no-name-in-module,import-error
import os
import urllib2
import subprocess
import sys
import shutil
import glob
import tarfile
import multiprocessing
import platform
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
fr... |
#! /usr/bin/env python3
import os
impl = '''
class Unwrap(private var valid: Boolean) {
infix fun <R> nah(f: () -> R) {
if (!valid) f()
}
}
'''
template = '''
inline fun <{0}, R> unwrap(
{1},
block: ({0}) -> R): Unwrap {{
val valid = null !in arrayOf{4}({2})
if (valid) block({... |
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/doughnut.py
# doughnut chart
__version__=''' $Id$ '''
__doc__="""Doughnut chart
Produces a circular chart like the doughnut charts pr... |
# Copyright (c) 2015 Red Hat, 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 require... |
__all__ = ['ravel_coords',
'unravel_index',
'mgrid',
'ogrid',
'r_', 'c_', 's_',
'index_exp', 'ix_',
'ndenumerate','ndindex',
'fill_diagonal','diag_indices','diag_indices_from']
import sys
import numpy.core.numeric as _nx
from numpy.core.numer... |
# Copyright (C) 2020 OpenMotics BV
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribu... |
#!/usr/bin/env python
import unittest
from framework import VppTestCase, VppTestRunner
from vpp_sub_interface import VppSubInterface, VppDot1QSubint, VppDot1ADSubint
from vpp_ip_route import VppIpMRoute, VppMRoutePath, VppMFibSignal, \
MRouteItfFlags, MRouteEntryFlags
from scapy.packet import Raw
from scapy.laye... |
#!/usr/bin/python
from __future__ import print_function
import io # used to create file streams
import fcntl # used to access I2C parameters like addresses
import sys
import time # used for sleep delay and timestamps
class Taris_Sensor():
''' This object holds all required interface d... |
#! /usr/bin/env python
#
from autopyfactory.interfaces import SchedInterface
import logging
class StatusTest(SchedInterface):
id = 'statustest'
def __init__(self, apfqueue, config, section):
try:
self.apfqueue = apfqueue
self.log = logging.getLogger('auto... |
from django.http import HttpResponse, JsonResponse
import logging
from eitu.core import fetch_schedules, render, fetch_wifi
import eitu.constants as constants
import eitu.formaters as formaters
from datetime import datetime
import pytz
import json
def index(request):
# Logging
logging.getLogger().setLevel(l... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... |
import math
from kivy.graphics.context_instructions import PopMatrix, PushMatrix, Rotate
from kivy.properties import NumericProperty
from kivy.uix.image import Image
class Bone(Image):
angle = NumericProperty()
def __init__(self, **kw):
super(Bone, self).__init__(**kw)
self.name = kw['name'] if 'name' ... |
"""Exporter module for Isograph Availability Workbench."""
import logging
import networkx as nx
from itertools import count
from amtt.translator.ir import component_basename
from amtt.exporter import Exporter
from amtt.exporter.isograph.emitter.xml import XmlEmitter
from amtt.exporter.isograph.rbd import Rbd
from amtt... |
from django.contrib import admin
from .models import OrdenOdontologica, ArancelOdontologico, Entidad, Capitulo
class OrdenOdontologicaAdmin(admin.ModelAdmin):
list_display = [
'persona',
'localidad',
'lugar_trabajo',
'mes',
'anio'
]
search_fields = [
'pers... |
# This is Kconfiglib, a Python library for scripting, debugging, and extracting
# information from Kconfig-based configuration systems. To view the
# documentation, run
#
# $ pydoc kconfiglib
#
# or, if you prefer HTML,
#
# $ pydoc -w kconfiglib
#
# The examples/ subdirectory contains examples, to be run with e.g.
#
... |
from __future__ import division
import pickle
import numpy
import math
from nltk.tokenize import RegexpTokenizer
from sklearn.decomposition import NMF, TruncatedSVD
import sentenceFeatures
# Obtain distributional features ((2 * K) in number)
# IMPORTANT: both training and test set must be present in sentences
# senten... |
#!/usr/bin/env python
# Martin Kersner, 2016/03/11
from __future__ import print_function
import sys
import re
import numpy as np
import matplotlib.pyplot as plt
from utils import strstr
def main():
output_data, log_files = process_arguments(sys.argv)
train_iteration = []
train_loss = []
train_accuracy... |
#
# 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"); you may not... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from login.views import *
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static
from posts.views import *
from images.views import *
urlpatter... |
from datetime import datetime
import datetime as DT
import time
import calendar
class Clock(object):
def __init__(self,offset=None):
self.timezone=None
if offset is not None:
self.timezone=DT.timezone(DT.timedelta(hours=offset))
def to_str(self,timestamp=None,with_orig=False):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 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 Lice... |
#!/usr/bin/env python
"""
Main function for internationalization tools.
"""
import importlib
import sys
from path import Path
def get_valid_commands():
"""
Returns valid commands.
Returns:
commands (list): List of valid commands
"""
modules = [m.basename().split('.')[0] for m in Path(__f... |
from flask import Blueprint, render_template, request, redirect, url_for, Response, jsonify, flash
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DateTimeField, TextField, SubmitField, TextAreaField, RadioField
from wtforms import validators, ValidationError
from wtforms.validators impor... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# ==============================================================================
# IBMIMMMemVpdMap modeler plugin
#
# Zenoss community Zenpack for IBM SystemX Integrated Management Module
# version: 0.3
#
# (C) Copyright IBM Corp. 2011. All Rights Reserved.
#
# This program is free software; you can redistribute it an... |
"""
ENTITY
"""
class Entity(object):
"""
ENTITY
A wrapped for a data dictionary. Allows interface with data, but also
allows extending to allow methods to manipulate data.
"""
def __init__(self, collection, data=None):
if not data:
data = {}
super(Entity, self).__... |
#! /usr/bin/python
# excel2text.py
# A simple program to convert Excel files to text with user-defined delimiters.
#
# Copyright (C) 2013 copyright Jacob Malcom, jacob.malcom@utexas.edu
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publ... |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... |
import os,sys,xmpp
currentUser = None
xmppClient = None
nicks = {}
###### Bot Command
def commandNick():
pass
def commandHelp(client, user):
message = """
!help - See this menu.
!nick <new name> - Change nick name.
"""
client.send(xmpp.Message(user, message))
###### Bot Logic
def parseCommand(client, ... |
import pytest
from django.test import TestCase
from ..utils import InvalidODKGeometryError, odk_geom_to_wkt
class TestODKGeomToWKT(TestCase):
def setUp(self):
self.geoshape = ('45.56342779158167 -122.67650283873081 0.0 0.0;'
'45.56176327330353 -122.67669159919024 0.0 0.0;'
... |
#!/usr/bin/env python
"""
This script uses matplotlib to compare reference output file(s) with data in tabular form
with the corresponding file(s) generated by the automatic test.
Multiple files can be specified via the command line interface.
Example:
pltdiff.py t88o_DS2_PHDOS
Usage: pltdiff.py file1 [file2, ..... |
# To run it, you should have inside the example folder
import sys
sys.path.append('..')
import tago
ANALYSYS_TOKEN = 'a5da3fc5-3cd5-4ee4-9ab4-d781aab65ffd'
def my_analysis(context, scope):
# Getting the account token from analysis environment variable
account_token = list(filter(lambda account_token: account_to... |
# -*- coding: utf-8 -*-
# Description: generates a json file that contains the item ids in order they appear in the UI
# Example usage:
# python generate_coordinates.py ../data/ ../js/coords.json 100 10 10 50 20 3
from PIL import Image
import json
import math
import os
import sys
# input
if len(sys.argv) < 8:
... |
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Unicode
from sqlalchemy import UnicodeText
from sqlalchemy.util import classproperty
from ..utils import utcnow
from .base import Base
def get_content(id):
""" Return ... |
# -*- coding: utf-8 -*-
# Copyright(C) 2010-2013 Romain Bignon
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your... |
# coding=utf-8
# Copyright 2021 The Google Research 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Temperature conversion """
import decimal
decimal.getcontext().prec = 5
ABSOLUTE_DIFFERENCE = decimal.Decimal('273.15')
def fahrenheit_to_kelvin(degrees):
""" Convert temperature from Farenheit to Kelvin units.
Args:
degrees (float): Farenheit tem... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# list... |
""" Utility functions for PhotoScan processing """
import os, sys
import PhotoScan
def align_and_clean_photos(chunk):
ncameras = len(chunk.cameras)
for frame in chunk.frames:
frame.matchPhotos()
chunk.alignCameras()
for camera in chunk.cameras:
if camera.transform is None:
... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Saas Manager
# Copyright (C) 2014 Sistemas ADHOC
# No email
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
... |
__author__ = 'venkat'
from header import *
from json_http_handler import *
class FlowWindow:
bottom_frame = 0
bottom_row = 0
class FlowTable:
def __init__(self):
self.dest_ip = None
self.dest_mask = None
self.dest_mac = None
self.dest_port = None
self.dest_... |
#!/usr/bin/python
import MySQLdb
class Tree(object):
class Anon: pass
def __init__(self, conn):
self.conn = conn
def insert_siblings(self, names, siblingname):
self.conn.begin()
sibling = self.retrieve(siblingname)
cur = self.conn.cursor()
cur.execute("UPD... |
import xml.etree.cElementTree as ET
from collections import defaultdict
import re
street_type_re = re.compile(r'\S+\.?$', re.IGNORECASE)
city_type_re = re.compile(r'\S+\.?$', re.IGNORECASE)
expected = ["Street", "Avenue", "Boulevard", "Drive",
"Court", "Place", "Square", "Lane", "Road",
"Tra... |
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
from celery.signals import celeryd_init
from django.core.management import call_command
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"nurseconnect.settings.production")
app = Celery... |
#
# This code is part of Ansible, but is an independent component.
#
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complet... |
# ------------------------------------------------------------
# calclex.py
#
# tokenizer for a simple expression evaluator for
# numbers and +,-,*,/
# ------------------------------------------------------------
import ply.lex as lex
# List of token names. This is always required
tokens = (
'NUMBER',
'NEWLINE... |
"""This module is used to time the execution of other modules,
and is executed through tasks.json"""
import sys
import timeit
import cProfile
if len(sys.argv) < 2:
raise AssertionError("NoScript specified to time!")
elif ".py" not in sys.argv[1]:
print(str(sys.argv[1])+ " is not a python Script!")
exit(1)
... |
# Copyright 2006-2011 The FLWOR Foundation.
#
# 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... |
from rapt.treebrd.attributes import AttributeList
from ...treebrd.node import Operator
from ..base_translator import BaseTranslator
class SQLQuery:
"""
Structure defining the building blocks of a SQL query.
"""
def __init__(self, select_block, from_block, where_block=''):
self.prefix = ''
... |
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.utils import simplejson as json
from django.views.decorators.http import require_POST
from .forms import ReportForm
from .models import Report, STAGES
from .tasks import process_report
def index(request):
repo... |
#analyzers.py
from main import _export,test,x2,RESULTS,evaluation
def overlap(dic1,dic2):
summ = len(set(dic1).union(set(dic2))) # if it's a dic, here we take the mere keys()
# if it's a list, we take all
overlapOfPlaindics = len(set(dic1)) + len(set(dic2)) - summ
return overlapOfPlaindics
def unpack... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import tensorflow as tf
import numpy as np
import scipy.misc as misc
import os
import time
from collections import namedtuple
from .ops import conv2d, deconv2d, lrelu, fc, batch_norm, init_embedding, conditional_instan... |
import time
import pymongo
from django.conf import settings
from apps.rss_feeds.models import MStory, Feed
db = settings.MONGODB
batch = 0
start = 0
for f in xrange(start, Feed.objects.latest('pk').pk):
if f < batch*100000: continue
start = time.time()
try:
cp1 = time.time() - start
# if fe... |
import argparse
import unittest
import os
import sys
from xml.dom import minidom
import tempfile
import shutil
from avocado import Test
from avocado.core.plugins import xunit
from avocado.core import job
class ParseXMLError(Exception):
pass
class _Stream(object):
def start_file_logging(self, param1, param... |
import sys
sys.path.append('../')
import numpy
import Graffity
import CIAO_DatabaseTools
import astropy.time as aptime
from matplotlib import pyplot
import colorsys
def getFreqs():
while True:
retval = []
enteredText = raw_input("Enter a comma separated list of frequencies: ")
try:
... |
from django.template import Library, Node, Variable
from courant.core.search.forms import CourantSearchForm
register = Library()
class SearchFacetCheck(Node):
def __init__(self, facet, value, varname):
self.facet = facet
self.value = value
self.varname = varname
def... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
Union.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*********************************... |
#!/usr/bin/env python
import mimetypes
import os
import sys
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
def get_s3_conn():
return S3Connection()
def get_bucket(conn, name):
return conn.get_bucket(name)
og = os.environ.get
bucket_name = og('NAUTILUS_BUCKET_NAME', 'me... |
"""
This is an example settings/local.py file.
These settings overrides what's in settings/base.py
"""
from . import base
# To extend any settings from settings/base.py here's an example:
INSTALLED_APPS = base.INSTALLED_APPS + ('django_nose',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sql... |
# Copyright (C) 2012 Stefano Palazzo <stefano.palazzo@gmail.com>
# Copyright (C) 2012 Ondina, LLC. <http://ondina.co>
# 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 ver... |
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import math
import numpy as np
from koheron import command
class Oscillo(object):
def __init__(self, client):
self.client = client
self.wfm_size = 8192
self.sampling_rate = 125e6
self.t = np.arange(self.wfm_size)/self.sampl... |
#!/usr/bin/python
"""Python file for the installation of dotfiles."""
from __future__ import print_function
from subprocess import call
import datetime
import argparse
import os.path
import shutil
import os
ACTION_TYPE = ("\n\n\t" "safe[default]\n\t" "bashmarks (requires 'prepvim' be run first)\n\t" "prepvim\n")
HOM... |
# Copyright (c) 2013 Qubell Inc., http://qubell.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 agr... |
import unittest
class NamespaceTest(unittest.TestCase):
def test_actor_dead_error_import(self):
from pykka import ActorDeadError as ActorDeadError1
from pykka.exceptions import ActorDeadError as ActorDeadError2
self.assertEqual(ActorDeadError1, ActorDeadError2)
def test_timeout_import... |
import requests
from ml import svm
import json
import NLProcessor as nlp
import lxml.html
from requests import get
from goose import Goose
def getSuggestions(query):
url = 'https://api.cognitive.microsoft.com/bing/v5.0/suggestions/?q=' + query
headers = {'Ocp-Apim-Subscription-Key':'854e8088bb8347418e6f934b996... |
__author__ = 'ivan'
import socket
import sys
from socket import error as socket_error
import command
messages = command.send_jsons
#create a TCP/IP Socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind the socket to the port
#default server address else command line argument
if not (len(sys.argv) ==... |
#!/usr/bin/env python
# coding: utf-8
from argparse import ArgumentParser
import json
from requests import post
URL = "https://chashuibiao.org/word/lookup"
USER = "NightWish"
def translate(word):
data = {}
data['lookup'] = json.dumps({"word": word})
headers = {}
headers["USER"] = USER
try:
... |
"""Suppliers module.
"""
from . import utils
from . import messaging
class DbSupplier(object):
def __init__(self, query, params=None):
self.query = query
self.params = params
def __enter__(self):
return self
def __exit__(self, *args):
self.cursor.close()
def __call__... |
"""Models for the comments app."""
from __future__ import absolute_import
from builtins import str
from builtins import object
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
f... |
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handler
from awscfncli2.cli.utils.pprint import echo_pair_if_exists
@click.command('validate')
@click.pass_context
@command_exception_handler
def cli(ctx):
"""Validate template file."""
assert isin... |
"""
Downloader for multex east corpus.
"""
import os
from os.path import expanduser, abspath
import sys
import urllib
import zipfile
import nltk.data
isCustomPath = False
def main():
download()
def download():
try:
__download__()
except KeyboardInterrupt:
print("\nDiscarded download d... |
import numpy as np
import canal as canal
from .util import NumpyTestCase
class FromJSONTestCase(NumpyTestCase):
class Measurement(canal.Measurement):
int_field = canal.IntegerField()
alternate_db_name = canal.IntegerField(db_name="something_else")
float_field = canal.FloatField()
... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import pytest
from houston.state import State, var
def test_variable_construction():
class S(State):
foo = var(float, lambda c: 0.1)
assert set(n for n in S.variables) == {'foo'}
def test_constructor():
class S(State):
foo = var(float, lambda c: 0.1)
state = S(foo=0.1, time_offset=... |
#
# Solution to Project Euler problem 500
# Philippe Legault
#
# https://github.com/Bathlamos/Project-Euler-Solutions
from lib import primes_up_to
from fractions import Fraction
import heapq
import sys
# The totient function gives us the number of divisors
# If n is the smallest number with 2^500500 divisors
# an... |
import os
import logging
import decimal
import base64
import json
from datetime import datetime
from lib import config, util, util_litecoin
ASSET_MAX_RETRY = 3
D = decimal.Decimal
def parse_issuance(db, message, cur_block_index, cur_block):
if message['status'] != 'valid':
return
def modify_extended... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('symposion_conference', '0001_initial'... |
import os, os.path, sys, shutil, re, itertools, warnings
from collections import namedtuple
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.build import build as _build
from distutils.core import setup
from distutils.core import Extension
pack_name = 'rpy2'
pack_version = __imp... |
from klein import Klein
from twisted.internet import defer
from twisted.trial.unittest import TestCase
from txwebtest import TestClient
from urlparse import parse_qs
class Tests(TestCase):
def setUp(self):
self.app = TestClient(create_app().resource())
@defer.inlineCallbacks
def test_status_check... |
from qtpy.QtWidgets import (QWidget, QFrame, QMainWindow, QMenuBar, QStatusBar, QAction, QApplication,
QTabWidget, QVBoxLayout)
from qtpy.QtGui import QIcon
from openburn import RESOURCE_PATH
from openburn.ui.dialogs.about import AboutDialog
from openburn.ui.designtab import DesignTab
cl... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Long-Short Term Memory with Batch Normalization."""
import tensorflow as tf
from tensorflow.contrib.rnn import RNNCell, LSTMStateTuple
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.platform import tf_logging as logging
from .batch_norm... |
from random import uniform
from pokemongo_bot import inventory
from pokemongo_bot.human_behaviour import sleep
from pokemongo_bot.inventory import Pokemon
from pokemongo_bot.item_list import Item
from pokemongo_bot.base_task import BaseTask
class EvolvePokemon(BaseTask):
SUPPORTED_TASK_API_VERSION = 1
def __... |
"""
Implementation of proofs for checking commitment equality and if a commitment is a square ("Efficient Proofs that a
Committed NumberLies in an Interval" by F. Boudot).
Modified for use with range proofs ("An efficient range proof scheme." by K. Peng and F. Bao).
"""
from binascii import hexlify
from math import ce... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.