content string |
|---|
import logging
class NewlineStreamHandler(logging.StreamHandler):
"""A StreamHandler with configurable message terminator
When StreamHandler writes a formatted log message to its stream, it
adds a newline terminator. This behavior is inherited by FileHandler
and the other classes which derive from it... |
import os.path, sys
from kuralib import kuraapp
from kuragui.guiconfig import guiConf
from kuragui import guiconfig
if guiConf.backend == guiconfig.FILE:
kuraapp.initApp(guiConf.backend,
dbfile = os.path.join(guiConf.filepath, guiConf.datastore))
elif guiConf.backend == guiconfig.SQL:
if gu... |
"""
Collaborative Filtering Classification Example.
"""
from __future__ import print_function
import sys
from pyspark import SparkContext
# $example on$
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="PythonColl... |
from functools import partial
from ...utils import verbose
from ..utils import (has_dataset, _data_path, _get_version, _version_doc,
_data_path_doc)
has_brainstorm_data = partial(has_dataset, name='brainstorm')
_description = u"""
URL: http://neuroimage.usc.edu/brainstorm/Tutorials/PhantomCtf
"... |
from __future__ import absolute_import
import six
import struct
import wire_format
def _VarintSize(value):
"""Compute the size of a varint value."""
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
i... |
from oslo.config import cfg
import webob
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.api.v2 import base
from neutron.api.v2 import resource
from neutron.common import constants as const
from neutron.common import exceptions as n_exc
from neutron import manager
from neutron.ope... |
from genshi.builder import tag
from genshi.filters import Transformer
from genshi.filters.transform import StreamBuffer
from trac.core import Component, TracError, implements
from trac.ticket.model import Ticket
from trac.ticket.web_ui import TicketModule
from trac.util import get_reporter_id
from trac.util.datefmt im... |
"""Tests for lexicon_builder."""
# disable=no-name-in-module,unused-import,g-bad-import-order,maybe-no-member
import os.path
import tensorflow as tf
import syntaxnet.load_parser_ops
from tensorflow.python.framework import test_util
from tensorflow.python.platform import googletest
from tensorflow.python.platform im... |
"""Certificate chain with 1 intermediary, where the intermediary is expired
(violates validity.notAfter). Verification is expected to fail."""
import common
# Self-signed root certificate (part of trust store).
root = common.create_self_signed_root_certificate('Root')
root.set_validity_range(common.JANUARY_1_2015_UTC... |
FILEPATH = "E:/Downloads/C-small-attempt0.in"
def isPrime(number):
if number <= 2:
return False
i = 2
while i <= number/2:
if number % i == 0:
return False
i += 1
return True
def baseTransform(number, base):
result = 0
power = 0
while number != 0:
... |
import datetime
import pytest
from shuup.simple_cms.models import Page
from shuup.simple_cms.views import PageView
from shuup.testing.factories import get_default_shop
from shuup.testing.utils import apply_request_middleware
from shuup_tests.simple_cms.utils import create_page
@pytest.mark.django_db
@pytest.mark.pa... |
import logging.config
from alembic import context
from flask import current_app
from sqlalchemy import engine_from_config, pool
from indico.core.db import db
from indico.core.db.sqlalchemy.util.session import update_session_options
from indico.core.db.sqlalchemy.util.models import import_all_models
# Ensure all our... |
try:
# Only exists in Python 2.4+
from threading import local
except ImportError:
# Import copy of _thread_local.py from Python 2.4
from django.utils._threading_local import local
class BaseDatabaseWrapper(local):
"""
Represents a database connection.
"""
ops = None
def __init__(sel... |
"""Script for constraining traffic on the local machine."""
import ctypes
import logging
import os
import subprocess
import sys
class NetworkEmulatorError(BaseException):
"""Exception raised for errors in the network emulator.
Attributes:
fail_msg: User defined error message.
cmd: Command for which the ... |
#!/usr/bin/env python
import sys
import gzip
import cPickle as pickle
import numpy as np
usage='''
Converts plain text embedding file to pickle file
pyton <vector file> <pickle file for output> <skip first line 1|0 > <unk word>
<vector file> : plain txt file <word> <vector of numbers>
<output file> : output fi... |
# encoding: utf-8
import argparse
import math
import os.path
import pickle
import re
import sys
import time
from nltk.translate import bleu_score
import numpy
import six
import chainer
from chainer import cuda
import chainer.functions as F
import chainer.links as L
from chainer import reporter
from chainer import tr... |
from six.moves import urllib
from keystoneclient import base
class User(base.Resource):
"""Represents a Keystone user."""
def __repr__(self):
return "<User %s>" % self._info
def delete(self):
return self.manager.delete(self)
def list_roles(self, tenant=None):
return self.man... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
from sklearn.linear_model import LogisticRegression
from sklearn.grid_search import GridSearchCV
import mord
def fit_classifier_with_crossvalidation(X, y, basemod, cv, param_grid,
scoring='r2', verbose=False):
"""Fit a classifier ... |
import logging
from tornado.options import options
from tornado.httpclient import HTTPError
from tornado_botocore import Botocore
logger = logging.getLogger(__name__)
class DDBBase(object):
TABLE_NAME = ''
# The data type for the attribute. You can specify S for string data,
# N for numeric data, or ... |
import pytest
import json
from twisted.python import usage
from twisted.application import service
import txtemplates.common.service as vcs
def test_options_errors():
"""
tests the errors in the Options class for the service configuration.
"""
config = vcs.Options()
with pytest.raises(usage.Us... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Electrical resistivity tomography"""
import numpy as np
import pygimli as pg
from .ertModelling import ERTModelling
from .ertScheme import createData
createERTData = createData # backward compatibility
def simulate(mesh, scheme, res, **kwargs):
"""Simulate an E... |
"""Tests for ceilometer/publisher/messaging.py
"""
import datetime
import uuid
import mock
from oslo_config import fixture as fixture_config
from oslo_utils import netutils
import testscenarios.testcase
from ceilometer.event.storage import models as event
from ceilometer.publisher import messaging as msg_publisher
fr... |
# -*- coding: utf-8 -*
from setuptools.command.install import install
from setuptools import find_packages
from setuptools import setup
from sys import version_info, stderr, exit
import codecs
import sys
import os
def read(*parts):
# intentionally *not* adding an encoding option to open
# see here: https://gi... |
import falcon
import mock
from oslo.config import fixture as fixture_config
from oslotest import base
import requests
from monasca.common import kafka_conn
from monasca.v2.elasticsearch import metrics
try:
import ujson as json
except ImportError:
import json
class TestParamUtil(base.BaseTestCase):
def ... |
from oslo_log import log
import oslo_messaging
from sqlalchemy.orm import exc
from neutron.agent import securitygroups_rpc as sg_rpc
from neutron.api.rpc.handlers import dvr_rpc
from neutron.callbacks import events
from neutron.callbacks import registry
from neutron.callbacks import resources
from neutron.common impor... |
from unittest import TestCase
from more_collections.multisets import multiset, frozenmultiset, orderable_multiset, orderable_frozenmultiset, nestable_orderable_frozenmultiset
try: # Python compat < 3.3
from collections.abc import Hashable, Set
except ImportError:
from collections import Hashable, Set
from itert... |
# -*- coding: UTF-8 -*-
__revision__ = '$Id$'
# Copyright (c) 2005-2009 Vasco Nunes, Piotr Ożarowski
#
# 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... |
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import pytz
from django.db import models
from django.test import override_settings, TestCase
from django.utils import timezone
from kolibri.core.fields import DateTimeTzField, parse_timezonestamp
from kolibri.core.serializers imp... |
import numpy
import six
from chainer.backends import cuda
from chainer import function
from chainer.utils import type_check
def _roi_pooling_slice(size, stride, max_size, roi_offset):
start = int(numpy.floor(size * stride))
end = int(numpy.ceil((size + 1) * stride))
start = min(max(start + roi_offset, 0... |
# encoding: utf-8
from __future__ import absolute_import
import os
import json
from flask_restful.inputs import boolean
# path of the configuration file for each instances
INSTANCES_DIR = os.getenv('JORMUNGANDR_INSTANCES_DIR', '/etc/jormungandr.d')
# Start the thread at startup, True in production, False for test en... |
""" The tool bar manager for the Envisage workbench window. """
# Enthought library imports.
import pyface.action.api as pyface
from traits.api import Instance
# Local imports.
from .action_controller import ActionController
class ToolBarManager(pyface.ToolBarManager):
""" The tool bar manager for the Envisage... |
from odoo import fields, models
class AccountInvoiceTax(models.Model):
_inherit = "account.invoice.tax"
base_company = fields.Monetary(
string='Base in company currency',
compute="_compute_base_amount_company",
)
amount_company = fields.Monetary(
string='Amount in company curr... |
import json
from passrotate.provider import Provider, ProviderOption, PromptType, register_provider
from passrotate.forms import get_form
from urllib.parse import urlparse
import requests
from bs4 import BeautifulSoup
class GitLab(Provider):
"""
[gitlab.com]
username=Your GitLab username
"""
name ... |
"""The ``restler`` package is a simple and flexible serialization to JSON and XML of App Engine Models and Queries.
A Simple Example
----------------
First, we'll need to import some appengine and
restler package classes and functions.
>>> from google.appengine.ext import db
>>> from restler.serializers import Mode... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import os
from ansible.module_utils.basic import AnsibleModule
def parse_vgs(data):
... |
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function, unicode_literals
from oucfeed.crawler import util
from oucfeed.crawler.newsspider import NewsSpider
class Spider(NewsSpider):
"""信息科学与工程学院
这个网站列表页的排序半死不活的(或许有隐藏的置顶功能?),只能从首页抓取
主站和党团网站数据库相通,党团网站首页内容多一点,所以从党团网站抓取
... |
from .imports import *
class Night(Talker):
'''Night objects handle information specific to the night.'''
def __init__(self, name, instrument, **kwargs):
'''Initialize a night object.'''
Talker.__init__(self)
# how do we refer to this night?
self.name = name
self.inst... |
"""
This is a wrapper around threading.Thread, but it will only actually thread
if django configuration is enabled. Otherwise, it will be an object with the
same api where start just calls run and.
"""
import threading
from django.conf import settings
class Thread(threading.Thread):
_use_thread = False
def ... |
#!/usr/bin/env python3
"""
Ben Saylor
November 2015, January 2016
Process a set of biomass data files (ATN*.csv) - one file per simulation -
create a summary CSV file with one row per simulation with various features
calculated from the biomass data.
FIXME: update description
"""
import sys
import os.path
import gz... |
import errno
import logging
import os
import stat
import time
import zopkio.constants as constants
from zopkio.remote_host_helper import better_exec_command, get_sftp_client, get_ssh_client, copy_dir
import zopkio.runtime as runtime
logger = logging.getLogger(__name__)
class Deployer(object):
"""Abstract class spe... |
import rman
def convert_matrix(m):
v = [m[0][0], m[1][0], m[2][0], m[3][0],
m[0][1], m[1][1], m[2][1], m[3][1],
m[0][2], m[1][2], m[2][2], m[3][2],
m[0][3], m[1][3], m[2][3], m[3][3]]
return v
def convert_matrix4x4(m):
mtx = convert_matrix( m )
rman_mtx = rman.Types.RtMatr... |
"""
This is the video capture for the pulse base image.
"""
from math import pi
import cv2
import time
import subprocess
import tempfile
import os
from color_classification import *
def list_video_devices():
"""List all video devices.
Currently, this only works under Linux."""
return [os.path.join("/dev"... |
import codecs
import os
import shutil
import tempfile
import unittest2 as unittest
from .checkout import Checkout
from .changelog import ChangeLogEntry
from .scm import CommitMessage, SCMDetector
from .scm.scm_mock import MockSCM
from webkitpy.common.webkit_finder import WebKitFinder
from webkitpy.common.system.execut... |
from VisionEgg.Text import Text
from LightData import dictattr
from Core import Stimulus
class Hint(Stimulus):
def __init__(self, params, **kwargs):
super(Hint, self).__init__(params=params, **kwargs)
self.name = 'hint'
self.parameters = dictattr()
self.set_parameters(self.parameter... |
import logging
from Tensile.SolutionStructs import Convolution
log =logging.getLogger("testlog")
def test_nhwc_defaults(tensile_state, run_convolution_level):
z={} # problemType definition
conv = Convolution(z, 'ConvolutionForward',
config={'TensorAFormat': 'NHWC',
'TensorBF... |
from django.contrib.auth.models import Group, Permission
from django.views.generic import View
from django.shortcuts import render
from django.utils.safestring import mark_safe
from django.http import HttpResponse
from django import forms
from django.conf import settings
import json
try:
jquery_path = settings.PE... |
"""
A Django command that exports a course to a tar.gz file.
"""
import shutil
import tarfile
from tempfile import mkdtemp
from textwrap import dedent
from path import path
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.... |
import argparse
import json
import tempfile
import unittest
from nose.tools import nottest
from itertools import combinations
from mock import create_autospec
from aria_cli import utils
from aria_cli import commands
from aria_cli.tests import cli_runner
TEMP_FILE = tempfile.NamedTemporaryFile()
ARG_VALUES = {
... |
import unittest
from biothings_explorer.registry import Registry
from biothings_explorer.user_query_dispatcher import SingleEdgeQueryDispatcher
from .utils import get_apis
reg = Registry()
class TestSingleHopQuery(unittest.TestCase):
def test_bp2protein(self):
"""Test gene-protein"""
seqd = Singl... |
from django.http import Http404
from django.core.paginator import Paginator, InvalidPage
from django.shortcuts import render, get_object_or_404
from django.utils.translation import ugettext_lazy as _
from example.apps.things.models import Thing
def _pagination(request, object_list):
paginator = Paginator(object_... |
'''
This script is a check for lookup at memory consumption over ssh without
having an agent on the other side
'''
import os
import sys
import optparse
import base64
import subprocess
# Ok try to load our directory to load the plugin utils.
my_dir = os.path.dirname(__file__)
sys.path.insert(0, my_dir)
try:
impo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0019_verbose_names_cleanup'),
('tests', '0012_filepage'),
]
operations = [
migrations.CreateModel(
... |
# Defines an object class, where an object is defined as an assembly of surfaces.
import numpy as N
from spatial_geometry import general_axis_rotation
from assembly import Assembly
class AssembledObject(Assembly):
""" Defines an assembly of surfaces as an object. The object has its own set of
coordinates suc... |
"""pymoku example: Basic Frequency Response Analyzer
This example demonstrates how you can generate output sweeps using the
Frequency Response Analyzer instrument, and view transfer function data in
real-time.
(c) 2019 Liquid Instruments Pty. Ltd.
"""
from pymoku import Moku
from pymoku.instruments import FrequencyRe... |
"""Simple data loader module.
Loads data files from the "data" directory shipped with a game.
Enhancing this to handle caching etc. is left as an exercise for the reader.
"""
import os
__docformat__ = 'restructuredtext'
data_py = os.path.abspath(os.path.dirname(__file__))
data_dir = os.path.normpath(os.path.join... |
from collections import OrderedDict
from typing import Dict, Type
from .base import DatastoreTransport
from .grpc import DatastoreGrpcTransport
from .grpc_asyncio import DatastoreGrpcAsyncIOTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[DatastoreTransport]]
... |
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from django.db.utils import Error
from django.contrib.auth.models import User
class Command(BaseCommand):
help = "Used to create a user"
option_list = BaseCommand.option_list + (
make_option('--usernam... |
from flask import (abort, after_this_request, current_app, Blueprint, jsonify,
request)
from recommendation import conf
from recommendation.memcached import memcached
main = Blueprint('main', __name__)
@main.route('/')
def view():
@after_this_request
def cache_control_headers(response):... |
import json
from mozlog.structured.formatters.base import BaseFormatter
class WptreportFormatter(BaseFormatter):
"""Formatter that produces results in the format that wpreport expects."""
def __init__(self):
self.raw_results = {}
self.results = {}
def suite_start(self, data):
if... |
from msrest.pipeline import ClientRawResponse
import uuid
from .. import models
class UsageDetailsOperations(object):
"""UsageDetailsOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:... |
class callproxy:
__slots__ = ('key', 'attr', 'model')
def __init__(self, key, model, attr):
self.key, self.attr, self.model = key, attr, model
def __call__(self, *a, **ka):
return getattr(self.model.redis, self.attr)(self.key, *a, **ka)
def __repr__(self):
return '<{!r} prox... |
import os
# toolchains options
ARCH='arm'
CPU='cortex-m4'
CROSS_TOOL='gcc'
# bsp lib config
BSP_LIBRARY_TYPE = None
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if os.getenv('RTT_ROOT'):
RTT_ROOT = os.getenv('RTT_ROOT')
# cross_tool provides the cross compiler
# EXEC_PATH is the compiler execute... |
# pylint: disable=no-name-in-module,import-error
import os
import sys
import subprocess
import pkg_resources
import shutil
from setuptools import setup
from distutils.errors import LibError
from distutils.command.build import build as _build
if sys.platform == 'darwin':
library_file = "sim_unicorn.dylib"
else:
... |
""" Class to manage connections for the Message Queue resources.
Also, set of 'private' helper functions to access and modify the message queue connection storage.
They are ment to be used only internally by the MQConnectionManager, which should
assure thread-safe access to it and standard S_OK/S_ERROR erro... |
# encoding: utf-8
"""
section.py
Created by Thomas Mangin on 2014-06-22.
Copyright (c) 2014-2015 Exa Networks. All rights reserved.
"""
from exabgp.configuration.engine.registry import Raised
import time
import random
# ====================================================================== Section
# The common func... |
import copy
import unittest
from systems.tests.testdata import get_test_object_futures_with_pos_sizing
from systems.basesystem import System
from systems.portfolio import Portfolios
from systems.accounts.accounts_stage import Account
class Test(unittest.TestCase):
def setUp(self):
(
posobjec... |
from flask.ext.sqlalchemy import SQLAlchemy, SignallingSession, SessionBase
class _SignallingSession(SignallingSession):
"""A subclass of `SignallingSession` that allows for `binds` to be specified
in the `options` keyword arguments.
"""
def __init__(self, db, autocommit=False, autoflush=True, **opti... |
from __future__ import division; __metaclass__ = type
import logging
log = logging.getLogger(__name__)
class RestartDriver(object):
def __init__(self, sim_manager, plugin_config):
super(RestartDriver, self).__init__()
if not sim_manager.work_manager.is_master:
return
self... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import mock
import os.path
from django.template import Template, Context, TemplateSyntaxError
from django.test import TestCase
from mock import patch
import six
from .utils import override_settings
__all__ = [
"MustacheJSTemplateTagTest",
"Ra... |
# -*- coding:utf-8 -*-
"""
utilizations for amr graph representaion
@author: Chuan Wang
@since: 2013-11-20
"""
from collections import defaultdict
import re
def trim_concepts(line):
"""
quote all the string literals
"""
pattern = re.compile('(:name\s*\(n / name\s*:op\d)\s*\(([^:)]+)\)\)')
def qu... |
import unittest
from . import CmdError, FunctionalTestCase
class BadUploadTest(FunctionalTestCase):
"""
Test missing volume upload using duplicity binary
"""
def test_missing_file(self):
"""
Test basic lost file
"""
try:
self.backup("full", "testfiles/dir1"... |
import sigrokdecode as srd
class Decoder(srd.Decoder):
api_version = 1
id = 'jtag'
name = 'JTAG'
longname = 'Joint Test Action Group (IEEE 1149.1)'
desc = 'Protocol for testing, debugging, and flashing ICs.'
license = 'gplv2+'
inputs = ['logic']
outputs = ['jtag']
probes = [
... |
import json
from httpretty import HTTPretty
from ...exceptions import AuthFailed
from .oauth import OAuth2Test
class GitLabOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.gitlab.GitLabOAuth2'
user_data_url = 'https://gitlab.com/api/v3/user'
expected_username = 'foobar'
access_token_bod... |
"""
Simple classes to get info from the ip system utility
"""
from subprocess import check_output as sub
import re
__all__ = ['Devices', 'Routes']
class Devices(object):
""" Network devices from IP """
def __init__(self):
self.ips = {}
self.states = {}
# Get states
for i in s... |
import sys
class temp_largest:
start_index = None
end_index = None
tsum = None
class solution:
max_sum = -sys.maxint
nelems = None
elems = []
all_negative = True
def __init__(self, n):
self.nelems = n
def append_element(self,elem):
self.elems.append(elem)
... |
"""
Django settings for sitio_web project.
Generated by 'django-admin startproject' using Django 1.11.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import ... |
###
# Script for Gephi using Jpython console
###
import java.awt
import operator
def f(x):
a = 0.07
b = 15
return a * x * 2 + b
def select_nodes(str):
top_nodes = {}
for node in g.nodes:
if node.name == str:
top_nodes[node.Id] = node
node.Label = ""
node.size = 20
return top_nodes
def color_nodes(... |
import requests
from datetime import datetime
import pytz
try:
city = input("Въведете град в България: \n")
url = "http://api.openweathermap.org/data/2.5/weather/?q=" + city + ",bg&units=metric&appid=c1d344dc9eb1db61f225488045d115be"
print('...получаваме информация за времето...')
print()
r = re... |
from django.contrib.admin import site
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from coredb.abstracts.getter import get_artifact_model, get_project_model, get_run_model
from coredb.administration.artifacts import ArtifactAdmin
from coredb.administration.projects imp... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ModelerDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*************************... |
#!/usr/bin/env python
"""check_postgresql
Usage:
check_postgresql (-h | --help)
check_postgresql (-r | --replication) -w <warn> -c <crit>
check_postgresql [-H <hostname> | -I <ip_address>] [-p <port>] [-d <database>] [-u <username>] [-P <password>]
check_postgresql (-r | --replication) [-H <hostname> ... |
"""Coordination and locking utilities."""
import inspect
import random
import threading
import uuid
import decorator
import eventlet
from eventlet import tpool
import itertools
from oslo_config import cfg
from oslo_log import log
import six
from tooz import coordination
from tooz import locking
from cinder import ex... |
from datetime import datetime
from unittest.mock import patch
import pytest
from szurubooru import api, db, errors, model
from szurubooru.func import comments, posts
@pytest.fixture(autouse=True)
def inject_config(config_injector):
config_injector(
{"privileges": {"comments:create": model.User.RANK_REGU... |
# coding=utf-8
from django.db import models
import datetime
from tag.models import Tag
# Create your models here.
from django.db.models.signals import post_save
from comment.models import *
from like.models import *
from notification.models import *
class Post (models.Model):
id = models.AutoField( primary_key =... |
#coding=utf-8
from ctypes import *
NULLPTR = POINTER(c_int)()
###### libc #######
class Timeval(Structure):
_fields_ = [("tv_sec", c_long),
("suseconds_t", c_long)]
##### redis #######
"""
/* This is the reply object returned by redisCommand() */
typedef struct redisReply {
int type... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Command line interface for imap account
Set of high level mail management functions. All managed in CLI"""
import setuptools
setuptools.setup(
author="Romain Soufflet",
author_email="<EMAIL>",
classifiers=[
"Development Status :: 3 - Alpha",
... |
# -*- coding: utf-8 -*-
"""Output related functions and classes for testing."""
import os
import unittest
from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.path import factory as path_spec_factory
from plaso.formatters import interface as formatters_interface
from plaso.formatters import mediator as ... |
from .proxy_resource import ProxyResource
class BackupLongTermRetentionPolicy(ProxyResource):
"""A backup long term retention policy.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource ID.
:vartype id: str
:ivar name: Resource name.
... |
#!/usr/bin/env python3
"""
Set CD/DVD drive speed.
"$HOME/.config/cdspeed.json" contain configuration information.
"""
import argparse
import glob
import json
import os
import shutil
import signal
import socket
import sys
from typing import List
import command_mod
import subtask_mod
class Options:
"""
Opti... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Food',
fields=[
('id', models.AutoField(verbose... |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcParams['text.latex.preamble'] = [r"\usepackage{lmodern}"]
params = {'text.usetex': True,
'font.size': 14,
'font.family': 'lmodern',
'text.latex.unicode': True}
plt.rcParams.update(params)
d... |
"""Tests for the brick library."""
from __future__ import print_function
import os
from chromite.cbuildbot import constants
from chromite.lib import brick_lib
from chromite.lib import cros_test_lib
from chromite.lib import osutils
from chromite.lib import workspace_lib
class BrickLibTest(cros_test_lib.WorkspaceTes... |
import networkx as nx
__author__ = """\n""".join(['Jordi Torrents <<EMAIL>>',
'Aric Hagberg (<EMAIL>)'])
__all__=['degree_centrality',
'betweenness_centrality',
'closeness_centrality']
def degree_centrality(G, nodes):
r"""Compute the degree centrality for nodes... |
from smartobjects import SmartObjectsClient, Environments
from smartobjects.model import Model, Timeseries, ObjectAttribute, OwnerAttribute, EventType, ObjectType
CLIENT_ID = "<CLIENT_ID>"
CLIENT_SECRET = "<CLIENT_SECRET>"
# This workflow create/deploy attributes. These operations are limited to the
# sandbox enviro... |
"""
Validator for a regular language.
"""
from typing import Dict
from prompt_toolkit.document import Document
from prompt_toolkit.validation import ValidationError, Validator
from .compiler import _CompiledGrammar
__all__ = [
"GrammarValidator",
]
class GrammarValidator(Validator):
"""
Validator which... |
"""
A test for RPC users with restricted permissions
"""
from test_framework.test_framework import SyscoinTestFramework
import os
from test_framework.util import (
get_datadir_path,
assert_equal,
str_to_b64str
)
import http.client
import urllib.parse
def rpccall(node, user, method):
url = urllib.parse.... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class List(Choreography):
def __init__(self, temboo_session):
"""
Create a new inst... |
#!/usr/bin/env python
import argparse
from pptx import Presentation
from src.parser.MetatagHandler import MetatagsHandler
from src.utils.Logger import Logger
from src.parser.PresentationParser import PresentationParser
from src.provider.basic.ImageProvider import ImageProvider
from src.provider.basic.TextP... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from transifex.resources.models import Resource
PRIORITY_LEVELS = (
('0', 'Normal'),
('1', 'High'),
('2', 'Urgent'),
)
class ResourcePriority(models.Model):
"""
A priority level associate... |
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
pre = document.getElementById('edoutput')
b = document.getElementById('runinjector')
if b == None:
b = document.createEle... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.