code stringlengths 1 199k |
|---|
"""Performance analyzer constants."""
DISPLAY_COLUMNS = [
{
'name': 'type',
'title': 'Issue type',
'tooltip': 'Type of issue affecting the fuzz target.'
},
{
'name': 'percent',
'title': 'Percent runs affected',
'tooltip': 'Percentage of fuzz target runs impact... |
import struct
from . import packet_base
from . import packet_utils
ICMP_ECHO_REPLY = 0
ICMP_DEST_UNREACH = 3
ICMP_SRC_QUENCH = 4
ICMP_REDIRECT = 5
ICMP_ECHO_REQUEST = 8
ICMP_TIME_EXCEEDED = 11
ICMP_ECHO_REPLY_CODE = 0
ICMP_HOST_UNREACH_CODE = 1
ICMP_PORT_UNREACH_CODE = 3
ICMP_TTL_EXPIRED_CODE = 0
class icmp(packet_base... |
import json
import logging
import os
import tempfile
import threading
from pyformance.reporters.reporter import Reporter
from desktop.lib.metrics import global_registry
LOG = logging.getLogger(__name__)
class FileReporter(Reporter):
def __init__(self, location, *args, **kwargs):
super(FileReporter, self).__init__... |
import os, time, math
from datetime import datetime
from time import mktime
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw
def GetKmlFiles():
"""Locates and reads local .kml files, returns a list of kml dictionary data"""
KmlData = []
for dirname, dirnames, filenames in os.walk('.'):
... |
from mongoengine import Document, StringField, DateTimeField, ListField, DateTimeField, IntField, BooleanField, \
ObjectIdField, FloatField
class Covelement(Document):
instructionsCov = IntField()
instructionsMis = IntField()
branchesCov = IntField()
branchesMis = IntField()
lineCov = IntField()... |
"""GRR restful API rendering plugins."""
from grr.gui.api_plugins import aff4
from grr.gui.api_plugins import artifact
from grr.gui.api_plugins import config
from grr.gui.api_plugins import docs
from grr.gui.api_plugins import hunt
from grr.gui.api_plugins import reflection
from grr.gui.api_plugins import stats |
from sklearn import datasets
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
loaded_data = datasets.load_boston()
data_X = loaded_data.data
data_y = loaded_data.target
model = LinearRegression()
model.fit(data_X, data_y)
print(model.predict(data_X[:4,:]))
print(data_y[:4])
print(model.... |
"""
Application level configuration and logging
"""
import os
import global_settings
import sys
from logging.config import dictConfig
from importlib import import_module
import logging
log = logging.getLogger(__name__)
class Settings(object):
"""
Configuration class for percept
"""
settings_list = None
... |
"""Test icatdump and icatingest.
"""
from subprocess import CalledProcessError
import pytest
import icat
import icat.config
from icat.query import Query
from conftest import DummyDatafile, gettestdata, getConfig, callscript
ds_params = str(gettestdata("ingest-ds-params.xml"))
datafiles = str(gettestdata("ingest-datafil... |
"""Tests for lookup ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import numpy as np
import six
from tensorflow.python import tf2
from tensorflow.python.client import session
from tensorflow.python.data.experimental.ops imp... |
"""Support for Abode Security System cameras."""
from datetime import timedelta
import logging
import requests
from homeassistant.components.camera import Camera
from homeassistant.util import Throttle
from . import DOMAIN as ABODE_DOMAIN, AbodeDevice
DEPENDENCIES = ['abode']
MIN_TIME_BETWEEN_UPDATES = timedelta(second... |
import sys
import os
import shlex
extensions = [
'sphinx.ext.autodoc',
# 'sphinxcontrib.fulltoc',
'releases'
]
releases_github_path = 'brandicted/ramses'
releases_debug = True
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Ramses'
copyright = u'2015, Brandicted'
auth... |
import numpy as np
from collections import namedtuple
import tensorflow as tf
from tensorpack.tfutils.scope_utils import under_name_scope
from config import config
@under_name_scope()
def clip_boxes(boxes, window, name=None):
"""
Args:
boxes: nx4, xyxy
window: [h, w]
"""
boxes = tf.maxim... |
'''
This module is to create model of Course
'''
from openerp import api, fields, models, _
class Course(models.Model):
'''
This class create model of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True) # Field reserved
description = fiel... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.utils.timezone import utc
import datetime
class Migration(migrations.Migration):
dependencies = [
('feed', '0003_auto_20141227_2343'),
]
operations = [
migrations.AddField(
model_name='ne... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('directorio', '0011_auto_20160225_0957'),
]
operations = [
migrations.CreateModel(
name='Video',
fields=[
('id', m... |
"""
Copyright © Val Neekman ([Neekware Inc.](http://neekware.com))
[ info@neekware.com, [@vneekman](https://twitter.com/vneekman) ]
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of so... |
import json
import urllib2
from books.models import Book
domain = "http://smartebook.zmapp.com:9026"
def sync_book(bid, cm):
# 完结了的图书不更新信息
if Book.objects.filter(id=bid, status=1).count() == 0:
page = urllib2.urlopen("http://wap.cmread.com/r/p/viewdata.jsp?bid=%s&cm=%s&vt=9" % (bid, cm))
data = ... |
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__, '_unpacker.cp35-win32.pyd')
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__() |
"""Unit tests to cover AdParamService."""
__author__ = 'api.sgrinberg@gmail.com (Stan Grinberg)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..'))
import unittest
from datetime import date
from adspygoogle.common import Utils
from tests.adspygoogle.adwords import HTTP_PROXY
from tests.adspygoogle.... |
"""
Copyright 2016 Alex Cortelyou
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 to in wr... |
from collections import Counter
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = filter(None, nums)
if not nums:
return 0
c = Counter(nums)
N = max(nums)
buckets = [0] * (N + 1... |
import os
import requests # pip install requests
API_KEY = "******************************************"
BASE_URL = "https://api.pdf.co/v1"
SourceFile = ".\\sample.pdf"
def main(args = None):
uploadedFileUrl = uploadFile(SourceFile)
if (uploadedFileUrl != None):
getInfoFromPDF(uploadedFileUrl)
def getInf... |
from collections import abc
import os
import re
from trove.common import cfg
from trove.common import pagination
from trove.common import utils
from trove.guestagent.common import operating_system
CONF = cfg.CONF
def update_dict(updates, target):
"""Recursively update a target dictionary with given updates.
Upd... |
"""gender sensitivity test English."""
import bigbench.api.task as task
import numpy as np
import re
import json
import os
import random
class gender_sensitivity_test_English(task.Task):
"""A gender sensitivity test for English language models.
Gender sensitivity test English consists of three tests:
(1... |
"""Constants for AccuWeather integration."""
from __future__ import annotations
from typing import Final
from homeassistant.components.weather import (
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_CLOUDY,
ATTR_CONDITION_EXCEPTIONAL,
ATTR_CONDITION_FOG,
ATTR_CONDITION_HAIL,
ATTR_CONDITION_LIGHTNING... |
import sys
from collections import deque
from Catalog.Schema import DBSchema
from Query.Operators.TableScan import TableScan
from Query.Operators.Select import Select
from Query.Operators.Project import Project
from Query.Operators.Union import Union
from Query.Operators.Join import Join
from Query.Opera... |
import itertools
import p4
from collections import defaultdict
def _get_extracted_headers(parse_state):
extracted = set()
return extracted
def _find_parser_paths(hlir):
def _find_paths(state, paths, current_path, path_hdrs, tag_stacks_index):
try:
next_states = set(state.branch_to.values... |
import pandas as pd
import numpy as np
import numpy.testing as npt
from aneris import harmonize
from aneris import utils
nvals = 6
_df = pd.DataFrame({
'gas': ['BC'] * nvals,
'region': ['a'] * nvals,
'units': ['Mt'] * nvals,
'sector': ['bar', 'foo'] + [str(x) for x in range(nvals - 2)],
'2010': [2, ... |
import asyncio
import logging
from typing import Text
from rasa.core.agent import Agent
from rasa.shared.utils.cli import print_info, print_success
from rasa.shared.utils.io import json_to_string
logger = logging.getLogger(__name__)
def run_cmdline(model_path: Text) -> None:
"""Loops over CLI input, passing each me... |
"""Command line interface for mcuxpresso_builder."""
import argparse
import pathlib
import sys
from pw_build_mcuxpresso import components
def _parse_args() -> argparse.Namespace:
"""Setup argparse and parse command line args."""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='com... |
import json
import math
from threading import Lock
class StatsAccumulator:
'''
A low-memory helper class to collect statistical samples and provide
summary statistics.
'''
def __init__(self, label='', other=None):
self._modlock = Lock()
self.clear(label)
if not other == None:... |
from __future__ import print_function
from getopt import getopt, GetoptError
import os
import re
import subprocess
import sys
from twext.enterprise.dal.model import Schema, Table, Column, Sequence
from twext.enterprise.dal.parseschema import addSQLToSchema, schemaFromPath
from twisted.python.filepath import FilePath
US... |
import logging
from db_operation import *
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')
def query_conf(marathon,app):
"""
:marathon marathon name
:app_id app id
"""
db=DB()
sql="select * from ... |
"""This package defines helpful utilities for FTL ."""
import os
import time
import logging
import subprocess
import tempfile
import datetime
import json
from ftl.common import constants
from ftl.common import ftl_error
from containerregistry.client.v2_2 import append
from containerregistry.transform.v2_2 import metada... |
"""Documentation control decorators."""
from typing import Iterable, Optional, TypeVar
T = TypeVar("T")
_DEPRECATED = "_tf_docs_deprecated"
def set_deprecated(obj: T) -> T:
"""Explicitly tag an object as deprecated for the doc generator."""
setattr(obj, _DEPRECATED, None)
return obj
def is_deprecated(obj) -> bool... |
from .account import AccountViewSet
from .allocation import AllocationViewSet
from .allocation_source import AllocationSourceViewSet
from .boot_script import BootScriptViewSet
from .base import BaseRequestViewSet
from .credential import CredentialViewSet
from .email_template import EmailTemplateViewSet
from .event impo... |
"""Defines the base broker class"""
from abc import ABCMeta
from collections import namedtuple
"""
FileDownload tuple contains an additional partial flag for defining whether the file
is allowed to be accessed directly or must be copied into running container. This is
currently only applicable to the S3Broker and requi... |
"""Network environment formatter."""
from aquilon.aqdb.model import NetworkEnvironment
from aquilon.worker.formats.formatters import ObjectFormatter
class NetworkEnvironmentFormatter(ObjectFormatter):
def format_raw(self, netenv, indent="", embedded=True,
indirect_attrs=True):
details = [... |
from __future__ import absolute_import, division, print_function, \
with_statement
import errno
import traceback
import socket
import logging
import json
import collections
import signal
import sys
import os
import datetime
from shadowsocks import common, eventloop, tcprelay, udprelay, asyncdns, shell
BUF_SIZE = 15... |
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.ya... |
from Queue import Queue, Empty
from SocketServer import StreamRequestHandler, ThreadingTCPServer
from collections import defaultdict
from threading import Lock, Thread
from socket import error
conversations = defaultdict(set)
"""Key is a conversation ID string, value is a set of ConnectionHandlers
that use that ID"""
c... |
"""
filterMapview.py <input mapview file> <output filename>
Author: Tony Papenfuss
Date: Mon Jun 16 14:31:42 EST 2008
"""
import os, sys
from useful import progressMessage
iFilename = sys.argv[1]
oFilename = sys.argv[2]
mQ_cutoff = 40
nSeqs = 280000000
oFile = open(oFilename, 'w')
headers = ['name','chrom','start','str... |
import user
import inscription
import notes
import util
import stage |
"""
Configuration of 'memos' Flask app.
Edit to fit development or deployment environment.
"""
PORT = 7420 # random.randint(5000, 8000)
MONGO_PORT = 4152
DEBUG = False # Because it's unsafe to run outside localhost
MONGO_URL = "mongodb://memos_user:peach-cobbler@localhost:4152/memos" |
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_realname(first_name, last_name, is_last_name_front):
... |
"""script to write M&C records to a CSV file
"""
from astropy.time import Time, TimeDelta
from hera_mc import mc, cm_utils
valid_tables = {
"hera_obs": {"method": "get_obs_by_time"},
"rtp_server_status": {
"method": "get_rtp_server_status",
"filter_column": "hostname",
"arg_name": "hostn... |
"""autogenerated by genpy from outdoor_bot/mainTargetsCommand_msg.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class mainTargetsCommand_msg(genpy.Message):
_md5sum = "b1faa92c8dffb7694c609d94e4e2d116"
_type = "outdoor_bot/mainTargetsCommand_msg"... |
try: # pragma: no cover
import django
from django.conf import settings
django_loaded = True
except ImportError: # pragma: no cover
django_loaded = False
if django_loaded: # pragma: no cover
if not settings.configured:
settings.configure(
DATABASES={
'default': ... |
'''
Designs oligos for a pre RNA-seq selection method
'''
import sys
import os
import numpy as np
def readFastaFile(fastaFilePath):
'''
Given a path to a multiline fasta file, reads the file, returning two lists - one containing the sequences, the other containing the headers
inputs: path to a fasta file
outputs: a... |
import glib
from about_dialog import AboutDialog
from application import application
from reinteract.native_main_menu import NativeMainMenu
class MainMenu(NativeMainMenu):
"""This class is an interface to OS X main menu. (The interface
of this class could likely be used for other types of main menu
if the n... |
"""
WSGI config for hackathon project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS... |
from readers import (autodiscover, FeedReader, TimestampedModelFeedReader,
RSSFeedReader)
from library import (FeedLibrary)
from dispatch import (SubscriptionDispatcher, SubscriptionEmailer)
from utils import (FeedRecordUpdater, FeedRecordCleaner) |
import os
import sys
import time
import traceback
from datetime import datetime
import atexit
import threading
try:
threading.stack_size(128 * 1024)
except:
pass
try:
import tracemalloc
tracemalloc.start(10)
except:
pass
current_path = os.path.dirname(os.path.abspath(__file__))
default_path = os.pat... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from ._overlap import _compute_overlap
__all__ = ['compute_overlap']
def compute_overlap(ilon, ilat, olon, olat):
"""Compute the overlap between two 'pixels' in spherical coordinates.
... |
import sys
from importlib import import_module
import warnings
from django.utils import six
from django.utils.module_loading import import_string
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
class InvalidSearchBackendError(ImproperlyConfigured):
pass
def get_search_backen... |
import math
import datetime
def red(txt):
return '\033[1;31m%s\033[0m' % txt
def green(txt):
return '\033[1;32m%s\033[0m' % txt
def yellow(txt):
return '\033[1;33m%s\033[0m' % txt
def blue(txt):
return '\033[1;34m%s\033[0m' % txt
def purple(txt):
return '\033[1;35m%s\033[0m' % txt
def cyan(txt):
... |
import numpy as np
import pandas as pd
from break4w.question import Question
class Continous(Question):
def __init__(self, name, description, units=np.nan, dtype=float,
limits=None,
sig_figs=None, magnitude=1, order=None, **kwargs):
"""A Question object with continous responses
Param... |
from behave import step
from behave.api.async_step import async_run_until_complete
import asyncio
@step('an async-step waits {duration:f} seconds')
@async_run_until_complete
async def step_async_step_waits_seconds_py35(context, duration):
"""Simple example of a coroutine as async-step (in Python 3.5)"""
await a... |
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('page_breaks04.xlsx')
self.ignore_files = ... |
from celeryone.helpers import queue_one_key, kwargs_to_list, force_string
import pytest
import six
def test_force_string_1():
assert force_string('a') == 'a'
def test_force_string_2():
assert force_string(u'a') == 'a'
def test_force_string_3():
assert force_string('é') == 'é'
def test_force_string_4():
... |
"""Leetcode 124. Binary Tree Maximum Path Sum
Hard
URL: https://leetcode.com/problems/binary-tree-maximum-path-sum/
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting
node to any node in the tree along the parent-child connections. T... |
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
install_requires = [
'requests==2.8.1'
]
setup(
name='linkedin-auth',
ver... |
import base64
import httplib
import json
import os
import re
import ssl
import urllib
from urlparse import urlunsplit
from exceptions import CloudPassageAuthentication
class HaloSession(object):
"""All Halo API session management happens in this object.
Args:
key(str): Halo API key
secret(str): ... |
"""HTML Exporter class"""
import os
from traitlets import default, Unicode
from traitlets.config import Config
from nbconvert.filters.highlight import Highlight2HTML
from nbconvert.filters.markdown_mistune import IPythonRenderer, MarkdownWithMath
from .templateexporter import TemplateExporter
class HTMLExporter(Templat... |
from setuptools import setup, find_packages
import os
def strip_comments(l):
return l.split('#', 1)[0].strip()
def reqs(*f):
return list(filter(None, [strip_comments(l) for l in open(
os.path.join(os.getcwd(), *f)).readlines()]))
def get_version(version_tuple):
if not isinstance(version_tuple[-1], i... |
from .parseStateProtoFile import *
from .StateTreeModel import * |
from flask import Flask
from webassets.loaders import PythonLoader as PythonAssetsLoader
from appname import assets
from appname.models import db
from appname.controllers.main import main
from appname.controllers.categories import categories
from appname.controllers.products import products
from appname.controllers.cat... |
from django.test import TestCase
from django.contrib.gis.geos import (LineString, Polygon, MultiPolygon,
MultiLineString, MultiPoint, Point)
from django.core.exceptions import ValidationError
from django.conf import settings
from django.test.utils import override_settings
from unitt... |
import pylab
import scipy
import scipy.stats # We need this one for the norm.pdf function
def clear_the_figure_and_empty_points_list():
global coords_array
global point_handles_array
# Reset our variables to be empty
coords_array = scipy.array([])
point_handles_array = scipy.array([])
handle_of... |
import os
import mimetypes
from django.core.urlresolvers import reverse_lazy
import djcelery
from django.conf import global_settings
from dss import logsettings
from utils import here
from localsettings import *
from pipelinesettings import *
from storagesettings import *
from paymentsettings import *
DEVELOPMENT = DEB... |
"""
WSGI config for base freebasics.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault(
"DJANGO_SETTI... |
from ConfigParser import ConfigParser, NoOptionError, NoSectionError
import os
import sys
import requests
API_URL = 'https://www.transifex.com/api/2'
LANGUAGES = [
'ar',
'de',
'el',
'es',
'fr',
'it',
'nl',
'pt_BR',
]
def fetch_po_for(language, username, password):
print('Downloading ... |
def solve():
return sum([n for n in range(1,1000) if (n % 3 == 0) or (n % 5 == 0)]) |
np.identity(3) |
from __future__ import absolute_import, unicode_literals
from datetime import datetime
import json
import random
import pytz
from smartmin.models import SmartModel
from temba import TembaClient
from django.conf import settings
from django.contrib.auth.models import User, Group
from django.core.cache import cache
from d... |
"""
`GrammarLexer` is compatible with Pygments lexers and can be used to highlight
the input using a regular grammar with token annotations.
"""
from __future__ import unicode_literals
from pygments.token import Token
from prompt_toolkit.layout.lexers import Lexer
from .compiler import _CompiledGrammar
__all__ = (
... |
import re
import traceback
from contextlib import closing, contextmanager
from collections import defaultdict
import pymysql
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
from config import _is_affirmative
from checks import AgentCheck
GAUGE = "gauge"
RATE = "rate"
... |
import sys
from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed
from django.core.signals import got_request_exception
from django.http import HttpResponse
from django.template import engines
from django.template.response import TemplateResponse
from django.test import RequestFactory, Si... |
raise Exception("tests where moved to emzed to avoid circular dependencies") |
"""Tests for cement.core.extension."""
from cement.core import exc, backend, extension, handler, output, interface
from cement.utils import test
class IBogus(interface.Interface):
class IMeta:
label = 'bogus'
class BogusExtensionHandler(extension.CementExtensionHandler):
class Meta:
interface = ... |
import time
import re
import os
import shutil
class CoordinateSystem(object):
"""
A generic class defining a coordinate system. Several coordinate systems
can be layered on top of one another (with a reference to the underlying
coordinate system given by the 'base_stage' pointer). When motion of a given... |
from mcfw.consts import DEBUG
from plugins.rogerthat_api.api import system
from plugins.tff_backend.bizz import get_tf_token_api_key
from plugins.tff_backend.bizz.global_stats import _get_currency_conversions
from plugins.tff_backend.models.global_stats import GlobalStats
from plugins.tff_backend.plugin_consts import B... |
import sys
import os
import pkg_resources
def version():
return pkg_resources.get_distribution(aux.__package__.title()).version
def base_dir():
return os.path.abspath(os.path.dirname(aux.__file__))
def working_dir():
return os.getcwd()
import aux
from aux.logger import LogController
from datetime import dat... |
from docar import Document, Collection
from docar import fields
from docar.backends.http import HttpBackendManager
from libthirty.state import uri, app_uri, service_uri, resource_collection_uri
from libthirty.validators import naming, max_25_chars, naming_with_dashes
import os
HttpBackendManager.SSL_CERT = os.path.join... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import filer.fields.file
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0001_initial'),
('filer', '0007_auto_201610... |
"""Memory allocation algorithm for vertex arrays and buffers.
The region allocator is used to allocate vertex indices within a vertex
domain's multiple buffers. ("Buffer" refers to any abstract buffer presented
by `pyglet.graphics.vertexbuffer`.
The allocator will at times request more space from the buffers. The cur... |
"""Module that handles interactions with a Validation Pool.
The validation pool is the set of commits that are ready to be validated i.e.
ready for the commit queue to try.
"""
import ConfigParser
import contextlib
import cPickle
import functools
import httplib
import logging
import os
import sys
import time
import url... |
squares = [x**2 for x in range(10)]
print squares
couples = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
print couples |
from __future__ import absolute_import
from envisage.plugins.refresh_code.refresh_code_plugin import * |
from django.core.files.uploadedfile import InMemoryUploadedFile
import re
import six
from django import forms
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.loader import render_to_string
from django.utils.encoding import force_t... |
from django.forms import ModelForm
from django import forms
from crispy_forms import layout
from crispy_forms.layout import Layout, HTML
from hs_core.forms import BaseFormHelper, Helper
from hs_core.hydroshare import users
from hs_modelinstance.models import ModelOutput, ExecutedBy
from hs_modflow_modelinstance.models ... |
from django.apps import apps
from django.conf import settings
from django_sharding_library.fields import BasePostgresShardGeneratedIDField
from django_sharding_library.exceptions import DjangoShardingException, InvalidMigrationException
from django_sharding_library.utils import (
is_model_class_on_database,
get... |
import random
import string
from django.contrib.auth.models import User
from django.test import TestCase
from longerusernameandemail.forms import UserCreationForm
def get_random_string(alpha=string.ascii_letters, length=100):
"Get a 'long', randmon string"
return ''.join([random.choice(alpha) for i in range(len... |
import code
import datetime
import os
import socket
import sys
__all__ = [ 'options', 'arguments', 'main' ]
usage="%prog [gem5 options] script.py [script options]"
version="%prog 2.0"
brief_copyright=\
"gem5 is copyrighted software; use the --copyright option for details."
def parse_options():
import config
... |
import unittest
from scrapy.http import Request
from scrapy.utils.request import request_fingerprint, _fingerprint_cache, \
request_authenticate, request_httprepr
class UtilsRequestTest(unittest.TestCase):
def test_request_fingerprint(self):
r1 = Request("http://www.example.com/query?id=111&cat=222")
... |
import redis
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
authorization_policy = ACLAuthorizationP... |
"""Package contenant la commande 'matelot' et ses sous-commandes.
Dans ce fichier se trouve la commande même.
"""
from primaires.interpreteur.commande.commande import Commande
from .affecter import PrmAffecter
from .creer import PrmCreer
from .editer import PrmEditer
from .info import PrmInfo
from .liste import PrmList... |
from django.utils import unittest
from django.contrib import admin
from hyperadmin.sites import ResourceSite
class SiteTestCase(unittest.TestCase):
def test_install_from_admin_site(self):
site = ResourceSite()
admin.autodiscover()
site.install_models_from_site(admin.site)
self.assert... |
def extract夢見る世界(item):
"""
Parser for '夢見る世界'
"""
if 'Otome Games' in item['tags']:
return None
if 'Drama CDs' in item['tags']:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [
('Miss ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.