content stringlengths 4 20k |
|---|
"""
Train the program by launching it with random parametters
"""
from tqdm import tqdm
import os
def main():
"""
Launch the training with different parametters
"""
# TODO: define:
# step+noize
# log scale instead of uniform
# Define parametter: [min, max]
dictParams = {
... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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 later version.
T... |
import errno
import glob
import json
import os
import os.path
import platform
import time
import uuid
from timing import monotonic_time_nanos
def create_symlink(original, symlink):
if platform.system() == "Windows":
# Not worth dealing with the convenience symlink on Windows.
return
else:
... |
import re
from ...const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from . import Rule
#---------------------------------------... |
from __future__ import absolute_import
from nark import *
from base import *
from app import conf
import app.model
import app
import os
from datetime import datetime
@resolve(app.scope)
class Home(object):
def __init__(self, session=ISession):
self.session = session
self.flash_service = app.model.Flash(... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re, logging, platform,time
from socket import gethostbyname
from sys import exit
from sys import stdout
from datetime import datetime
import os.path, cx_Oracle
if os.name == 'nt':
import ntpath
from subprocess import STDOUT, Popen, PIPE
from socket import inet_aton
imp... |
import numpy
import PIL.Image as PILimage
import PIL.ImageTk as PILimageTk
from ginga import Mixins, Bindings, colors
from ginga.canvas.mixins import DrawingMixin, CanvasMixin, CompoundMixin
try:
from ginga.aggw.ImageViewAgg import ImageViewAgg as ImageView, \
ImageViewAggError as ImageViewError
except... |
import docker
import pytest
from requests.exceptions import ConnectionError, SSLError
from requests.packages.urllib3.exceptions import ProtocolError
from dockci.exceptions import *
CONN_REFUSED = ConnectionRefusedError(61, 'Connection refused')
class TestDockerUnreachableError(object):
""" Test ``DockerUnreac... |
from __future__ import division
import sys
import os
import re
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--input", help="edge list input file", dest="edgelist")
parser.add_option("--output", help="Output filename", dest="outfile")
parser.add_option("--thresh", help="Min edge weigh... |
from datetime import datetime
import logging
import pkgutil
import string
import pytz
import babel
from babel import Locale
from babel.core import LOCALE_ALIASES
import babel.dates
import formencode
from pylons.i18n import _
from pylons.i18n import add_fallback, set_lang
from pylons import tmpl_context as c
from adho... |
from builtins import str
from django.http import (
HttpResponse,
HttpResponseNotAllowed,
HttpResponseBadRequest,
Http404,
HttpResponseServerError,
JsonResponse,
)
from omeroweb.webclient.decorators import login_required, render_response
from django.shortcuts import render
from django.views.deco... |
try:
import psycopg2
import psycopg2.extras
except ImportError:
postgresqldb_found = False
else:
postgresqldb_found = True
class NotSupportedError(Exception):
pass
# ===========================================
# PostgreSQL module specific support methods.
#
def set_owner(cursor, schema, owner):
... |
import socket
import subprocess
import sys
import textwrap
import unittest
from tornado.escape import utf8, to_unicode
from tornado import gen
from tornado.iostream import IOStream
from tornado.log import app_log
from tornado.tcpserver import TCPServer
from tornado.test.util import skipIfNonUnix
from tornado.testing i... |
def execute_config_command(commands, module):
try:
module.configure(commands)
except ShellError, clie:
module.fail_json(msg='Error sending CLI commands',
error=str(clie), commands=commands)
def get_cli_body_ssh(command, response, module):
"""Get response for when t... |
import multiprocessing, sqlite3, sys
from concurrent.futures import ProcessPoolExecutor
def ipv4_to_int(ipstring):
parts = [int(part) for part in ipstring.split('.')]
return (parts[0] << 24) + (parts[1] << 16) + (parts[2] << 8) + (parts[3] << 0)
SEARCH_CACHE = {}
ROW_CACHE = {}
def get_row(c, rownum):
g... |
import os
from _datetime import datetime
import hurry.filesize
from tkinter import Tk, Frame, Label, Entry, Button
from tkinter.constants import VERTICAL, HORIZONTAL
from tkinter.filedialog import askdirectory
from tkinter.messagebox import showerror
from tkinter.ttk import Treeview, Scrollbar
from deterministic_enc... |
import m5, os, optparse, sys
from m5.objects import *
m5.util.addToPath('../configs/common')
from Benchmarks import SysConfig
import FSConfig
m5.util.addToPath('../configs/ruby')
m5.util.addToPath('../configs/topologies')
import Ruby
import Options
# Add the ruby specific and protocol specific options
parser = optpar... |
from unittest import TestCase
class TestPy3venv(TestCase):
def test_sys_attrs(self):
from itertools import product
import os
import sys
plugin_dir = os.path.dirname(os.path.dirname(__file__))
plugin_dir = os.path.join(plugin_dir, "plugin")
if sys.path[0] != plugin_... |
#!/usr/bin/python
"""
Copyright (C) International Business Machines Corp., 2005, 2006
Authors: Dan Smith <<EMAIL>>
Daniel Stekloff <<EMAIL>>
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 Foundat... |
from setuptools import setup
version = '0'
setup(
name='myplay',
version=version,
description='Simple music player service',
author='Dan Korostelev',
author_email='<EMAIL>',
url='http://code.google.com/p/myplay/',
license='GPL',
classifiers=[
'Development Status :: 2 - Pre-Alp... |
import os
from horizon.test.settings import * # noqa
from horizon.utils import secret_key
from openstack_dashboard import exceptions
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_PATH = os.path.abspath(os.path.join(TEST_DIR, ".."))
SECRET_KEY = secret_key.generate_or_read_from_file(
os.path.join(... |
import unittest
import itertools
import numpy
import six
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
from chainer.utils import conv
from chainer.util... |
import json
import hashlib
import re
from social.apps.django_app.default.models import UserSocialAuth
from django.http import HttpResponse, HttpResponseBadRequest
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, redirect
from django.contrib.auth import logout as auth_logou... |
"""
TreeView class is a subclass of QT QTreeView class.
Subclass is done in order to:
- implement a simple (ie not complex) drag & drop
- get selection events
@newfield purpose: Purpose
@newfield sideeffect: Side effect, Side effects
@purpose: display tree structure of the .dxf file, select,
enable ... |
import os
import json
import requests
import six
from retrying import retry
from datetime import datetime
from bs4 import BeautifulSoup
from wargaming.exceptions import RequestError, ValidationError
from wargaming.settings import (
ALLOWED_GAMES,
ALLOWED_REGIONS,
HTTP_USER_AGENT_HEADER,
RETRY_COUNT,
... |
# -*- coding: utf-8 -*-
import datetime
W_MONDAY = 0
W_TUESDAY = 1
W_WEDNESDAY = 2
W_THURSDAY = 3
W_FRIDAY = 4
W_SATURDAY = 5
W_SUNDAY = 6
class _reiter(object):
def __init__(self, f):
self.f = f
def __iter__(self):
return self.f()
def prev_month(y, m):
if m == 1:
return (y - 1... |
from draftjs_exporter.dom import DOM
from wagtail.admin.rich_text.converters.html_to_contentstate import LinkElementHandler
from wagtail.documents import get_document_model
# draft.js / contentstate conversion
def document_link_entity(props):
"""
Helper to construct elements of the form
<a id="1" linkt... |
""" Utilities for accessing the platform's clipboard.
"""
import subprocess
import sys
from IPython.ipapi import TryNext
def win32_clipboard_get():
""" Get the current clipboard's text on Windows.
Requires Mark Hammond's pywin32 extensions.
"""
try:
import win32clipboard
except ImportEr... |
""" Coherence and Nautilus bridge to export folders as a DLNA/UPnP MediaServer
usable as Nautilus Extension or a Script
for use an extension, copy it to ~/.nautilus/python-extensions
or for a system-wide installation to /usr/lib/nautilus/extensions-2.0/python
for us as a script put it into ~/.gnome2/... |
try:
import json
except ImportError:
import simplejson as json
import time
from aliyun.log.util import Util
class LogtailConfigDetail :
"""The common parts of logtail config
:type config_name : string
:param config_name : the config name
:type logstore_name: string
:param logstore_name: ... |
from django.db import models, IntegrityError
from datetime import datetime, timedelta
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from datetime import datetime
import random, string
def default_starting_time():
... |
import os
import re
import iet_target
class IetAllowDeny(object):
ALLOWDENY_REGEX='\s*(?P<target>\S+)\s+(?P<hosts>.+)'
def __init__(self, filename):
self.targets = {}
self.filename = filename
def parse_file(self):
if os.path.exists(self.filename):
f = open(self.filename... |
"""Utility functions to work with CSV files.
Copyright (c) 2019 Red Hat Inc.
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 later version.
... |
from ert import Version
from ert_gui.shell import assertConfigLoaded, ErtShellCollection
class Debug(ErtShellCollection):
def __init__(self, parent):
super(Debug, self).__init__("debug", parent)
self.addShellFunction(name="site_config", function=Debug.siteConfig, help_message="Show the path to th... |
"""empty message
Revision ID: 0e41e78563c4
Revises: e4e46dd976a5
Create Date: 2017-09-08 13:23:34.216570
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0e41e78563c4'
down_revision = 'e4e46dd976a5'
branch_labels = None
depends_on = None
def upgrade():
# ... |
"""TinyCert Session
This module provides the Session class which wraps an authenticated session with TinyCert's rest API.
"""
# pylint: disable=wrong-import-order,wrong-import-position
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from past.builtins i... |
__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer',
'RepresenterError']
import datetime
import copy_reg
import types
from error import *
from nodes import *
class RepresenterError(YAMLError):
pass
class BaseRepresenter(object):
yaml_representers = {}
yaml_multi_representers = {}
d... |
import unittest
from webkitpy.common.system import executive_mock
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.tool.mocktool import MockOptions
from webkitpy.layout_tests.port import linux
from webkitpy.layout_tests.port import port_testcase
class LinuxPortTest(port_testcase.PortT... |
from typing import Dict, Any, Iterable, Optional, Union
from azure.eventhub._eventprocessor.in_memory_checkpoint_store import InMemoryCheckpointStore as CheckPointStoreImpl
from .checkpoint_store import CheckpointStore
class InMemoryCheckpointStore(CheckpointStore):
def __init__(self):
self._checkpoint_st... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys
from setuptools import setup, find_packages
from distutils.command.install_data import install_data
from distutils.command.install import INSTALL_SCHEMES
def read(*path):
return open(os.path.join(os.path.abspath(os.path.dirname(__file__)), *path)).read()
... |
import logging
import tensorflow as tf
from typeguard import typechecked
@tf.keras.utils.register_keras_serializable(package="Addons")
class WeightNormalization(tf.keras.layers.Wrapper):
"""Performs weight normalization.
This wrapper reparameterizes a layer by decoupling the weight's
magnitude and direc... |
import itertools
from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.contrib.humanize.templatetags.humanize import intcomma
from manoria.models import Co... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Description of the CEA FPA Campaign.
:History:
Created on Wed Oct 02 17:26:00 2019
:author: Ruyman Azzollini
"""
# IMPORT STUFF
from collections import OrderedDict
from pdb import set_trace as stop
import numpy as np
import copy
#from vison.pipe import lib as pil... |
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from django.utils.feedgenerator import Rss201rev2Feed as RSS
from tower import ugettext as _
import amo
from amo.helpers import absolutify, url, strip_html
from devhub.models import ActivityLog, RssKey
class ActivityFee... |
"""Support for Huawei LTE router notifications."""
import logging
import voluptuous as vol
import attr
from homeassistant.components.notify import (
BaseNotificationService, ATTR_TARGET, PLATFORM_SCHEMA)
from homeassistant.const import CONF_RECIPIENT, CONF_URL
import homeassistant.helpers.config_validation as cv
... |
from __future__ import absolute_import
import logging
import time
from sentry.digests import get_option_key
from sentry.digests.backends.base import InvalidState
from sentry.digests.notifications import (
build_digest,
split_key,
)
from sentry.models import (
Project,
ProjectOption,
)
from sentry.task... |
'''
Created on 18 oct. 2011
@author: openerp
'''
from openerp.osv import osv
from openerp.tools.translate import _
class plugin_handler(osv.osv_memory):
_name = 'plugin.handler'
def _make_url(self, cr, uid, res_id, model, context=None):
"""
@param res_id: on which document the message is... |
#
# mxmparser -
#
from mxmout import *
from mxmutils import *
from tempfile import NamedTemporaryFile
import mxmmaxima
import mxmstack
import string
import sys
import os
tokens = [ '<code>', '<eof>' ]
keywords = [ 'polynomial', 'terms', 'initialise', 'term', 'finalise', 'begin', 'end' ]
commentLeader =... |
import sys
sys.path.insert(1, "..")
from SOAPpy import *
detailed_fault = \
"""
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://... |
import time
import uuid
from .orm import Model, StringField, BooleanField, FloatField, TextField
def next_id():
return '%015d%s000' % (int(time.time() * 1000), uuid.uuid4().hex)
class User(Model):
__table__ = 'users'
id = StringField(primary_key=True, default=next_id, ddl='varchar(50)')
email = St... |
'''
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 use this ... |
"""
Tests masking functionality specific to WISH. Working masking behaviour is critical in general, but is heavily used on WISH.
- Email Pascal Manuel @ ISIS if things break here and let him know how his scripts may need to be modified.
"""
import systemtesting
import os
from mantid.simpleapi import *
class WishMask... |
#!/usr/bin/env python
import time
import struct
import sys
import requests
import signal
from serial import Serial
from serial.serialutil import SerialException
from ConfigParser import ConfigParser, NoSectionError, NoOptionError
from requests.exceptions import ConnectionError
#Config file name
CONFIG_FILE = "paperwei... |
class PartWorkbench ( Workbench ):
"Part workbench object"
Icon = """
/* XPM */
static char * part_xpm[] = {
"16 16 9 1",
" c None",
". c #000209",
"+ c #00061D",
"@ c #010A2F",
... |
def remove_adjacent(nums):
# +++your code here+++
result = []
for num in nums:
if len(result) == 0 or num != result[-1]:
result.append(num)
return result
# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the... |
from typing import List
from xml.etree import cElementTree as ElementTree
from datetime import datetime
from .services.entrez import EfetchPackage, EsummaryResult
from .models import BioProject
from .xml_helpers import get_xml_text, get_xml_attribute, xml_to_root
from .utils import make_number, date_parse
def parse_... |
'''
General utilities for form validation
@author: Luca Cinquini
'''
import os
import imghdr
def validate_image(form, field_name):
'''
Validates an image field that is part of a form,
before the image is uploaded to the server.
'''
cleaned_data = form.cleaned_data
image = cleaned_data.ge... |
import mail_compose_message
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from __future__ import absolute_import
import os
import subprocess
import sys
import psutil
from distutils.util import strtobool
from distutils.version import LooseVersion
import mozpack.path as mozpath
# Minimum recommended logical processors in system.
PROCESSORS_THRESHOLD = 4
# Minimum recommended total system ... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
('wagtailcore', '0025_collection_initial_data'),
]
operations = [
migrations.CreateModel(
name='GroupCollectionPermission... |
"""This script runs an automated Cronet native performance benchmark.
This script:
1. Starts HTTP and QUIC servers on the host machine.
2. Runs benchmark executable.
Prerequisites:
1. quic_server and cronet_native_perf_test have been built for the host machine,
e.g. via:
gn gen out/Release --args="is_debug=fa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tahmatassu Web Server
~~~~~~~~~~~~~~~~~~~~~
CherryPy run script for Tahmatassu Web Server.
Simple and easy way to run tahmatassu in production.
:copyright: (c) 2014 by Teemu Puukko.
:license: MIT, see LICENSE for more details.
"""
from .server import app
from flask imp... |
from gravity.tae.stemmer.snowball.so import Stemmer as SnowballStemmer
import gravity.tae.stemmer.stemmer
class Stemmer(gravity.tae.stemmer.stemmer.Stemmer):
def __init__(self, lang = "nl"):
super(self.__class__, self).__init__(lang)
self.stemmer_lang = {'nl':'dutch', 'en':'english' }[lang]
... |
from gi.repository import GLib, GObject, Gio, Gedit
from .viewactivatable import MultiEditViewActivatable
class MultiEditWindowActivatable(GObject.Object, Gedit.WindowActivatable):
window = GObject.Property(type=Gedit.Window)
def do_activate(self):
action = Gio.SimpleAction.new_stateful("multiedit"... |
""" Test Iterator Length Transparency
Some functions or methods which accept general iterable arguments have
optional, more efficient code paths if they know how many items to expect.
For instance, map(func, iterable), will pre-allocate the exact amount of
space required whenever the iterable can report its lengt... |
"""
==========
Kernel PCA
==========
This example shows that Kernel PCA is able to find a projection of the data
that makes data linearly separable.
"""
print __doc__
# Authors: Mathieu Blondel
# License: BSD
import numpy as np
import pylab as pl
from sklearn.decomposition import PCA, KernelPCA
np.random.seed(0)
... |
#!/usrbin/env python
# Line too long - pylint: disable=C0301
# Invalid name - pylint: disable=C0103
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you ... |
"""
Unit Support: Classes and methods to allow Unum and Quantities unit
packages to interact with Topographica.
"""
import param
from param.parameterized import bothmethod
from topo import sheet, pattern, base, numbergen
import numpy as np
from unittest import SkipTest
got_unum = False; got_pq=False
try:
impo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_activities(apps, schema_editor):
Proposal = apps.get_model("deck", "Proposal")
Activity = apps.get_model("deck", "Activity")
for proposal in Proposal.objects.all():
Activity.objects.create... |
import unittest as ut
import unittest_decorators as utx
import sys
import math
import numpy as np
import espressomd
import espressomd.electrokinetics
import espressomd.shapes
import ek_common
from tests_common import DynamicDict
##########################################################################
# ... |
from __future__ import absolute_import
import re
import posix_ipc
from celery import task
from django.conf import settings
from .cachedb import CacheDB
from .tilecache import TileCache
import logging
logger=logging.getLogger("ndtilecache")
@task(queue='prefetch')
def fetchcube ( token, slice_type, channels, colors... |
import datetime
import logging
import multiprocessing
import os
import subprocess
import sys
import optparse
from pylib import android_commands
def _ListTombstones(adb):
"""List the tombstone files on the device.
Args:
adb: An instance of AndroidCommands.
Yields:
Tuples of (tombstone filename, date t... |
author = 'Anton Bobrov<<EMAIL>>'
name = 'Python support'
desc = 'Autocompletion, navigation and smart ident'
import weakref
import os.path
from snaked.core.problems import mark_exact_problems, \
attach_to_editor as attach_problem_tooltips_to_editor
handlers = weakref.WeakKeyDictionary()
outline_dialog = None
tes... |
"""distutils.command.build
Implements the Distutils 'build' command."""
# created 1999/03/08, Greg Ward
__revision__ = "$Id: build.py,v 1.31 2000/10/14 04:06:40 gward Exp $"
import sys, os
from distutils.core import Command
from distutils.util import get_platform
def show_compilers ():
from distutils.ccompile... |
from git.config import SectionConstraint
from git.util import join_path
from git.exc import GitCommandError
from .symbolic import SymbolicReference
from .reference import Reference
__all__ = ["HEAD", "Head"]
class HEAD(SymbolicReference):
"""Special case of a Symbolic Reference as it represents the repository'... |
import re
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
re_accepts_gzip = re.compile(r'\bgzip\b')
class GZipMiddleware(object):
"""
This middleware compresses content if the browser allows gzip compression.
It sets the Vary header accordingly, so that cach... |
from collections import defaultdict
import os
import re
import unittest
import sys
################################################################################
class SmartyParser:
def __init__(self, path):
if not os.path.isdir(path):
raise Exception("Expected a valid path to parse through")
... |
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.functional import lazy
from mptt.models import MPTTModel, TreeForeignKey
def get_app_choices():
from routes.apphook_pool import apphook_pool
return apphook_pool.app_choices
class Route(MPTTModel):
APP_C... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.compat.tests import unittest
from ans... |
import simplejson, sys, shutil, os, ast , re
from mpipe import OrderedStage , Pipeline
import glob, json, uuid, logging , time ,datetime
import subprocess, threading,traceback
from collections import OrderedDict
from pprint import pprint , pformat
import parallel_tools as parallel
from mpipe import OrderedStage , Pip... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import tempfile
import tarfile
from subprocess import Popen, PIPE
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native
from ansible.module_utils.com... |
"""
"""
"""
def sortList(line, char):
if char
def selectionSort():
for char in open(file)
sortAgain = sortList(line, char)
"""
"""
def selectionSort(lst,file):
"""
'docstring'
"""
for line in open(file):
print(line.strip)
n=len(file)
for i in range (0, n-1):
... |
"""
Producer-Consumer Proxy.
"""
from zope.interface import implementer
from twisted.internet import interfaces
@implementer(interfaces.IProducer, interfaces.IConsumer)
class BasicProducerConsumerProxy:
"""
I can act as a man in the middle between any Producer and Consumer.
@ivar producer: the Producer... |
# Exercise 3.4. A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:
# def do_twice(f):
# f()
# f()
# Here’s an example that uses do_twice to call a function named print_spam twice.
#... |
# -*- coding: utf-8 -*-
"""Storage writer for Redis."""
from plaso.lib import definitions
from plaso.storage import interface
from plaso.storage.redis import redis_store
class RedisStorageWriter(interface.StorageWriter):
"""Redis-based storage writer."""
def __init__(
self, session, storage_type=definitio... |
#!/usr/bin/env python3
import os
import sys
def main(argv):
print("""
#################################
# Gathering Arsenal Access Data #
#################################
""")
inpath = os.path.abspath(argv[1])
if os.path.exists(inpath):
print("Scraping in: {}".format(inpath))
outpath = os.p... |
# -*- coding: utf-8 -*-
#
from rest_framework.generics import UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from common.utils import get_logger, get_object_or_none
fro... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
from frappe.model.document import Document
from erpnext.education.api import get_grade
from erpnext.education.api import get_assessment_details
from frappe.utils.csvutils import getlink
import erpnext.education
clas... |
from typing import Dict, Set
from django.db import transaction
from django.db import models
from django.utils import timezone
from data_refinery_common.models.models import Sample, Experiment, OriginalFile
class SurveyJob(models.Model):
"""Records information about a Surveyor Job."""
class Meta:
db... |
"""This module exports the Bashate plugin class."""
from SublimeLinter.lint import Linter
import os
class Bashate(Linter):
"""Provides an interface to bashate."""
cmd = 'bashate'
defaults = {
'selector': 'source.shell.bash',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ... |
from flask.blueprints import Blueprint
from flask.helpers import url_for
from tornado.web import RequestHandler, asynchronous
from werkzeug.utils import redirect
api = Blueprint('api', __name__)
api_docs = {}
api_docs_missing = []
api_nonblock = {}
class NonBlockHandler(RequestHandler):
def __init__(self, appli... |
"""
@author: Andrew Case
@license: GNU General Public License 2.0 or later
@contact: <EMAIL>
@organization: Digital Forensics Solutions
"""
from rekall.plugins.linux import common
class Banner(common.LinuxPlugin):
"""Prints the Linux banner information."""
__name = "banner"
def render(se... |
import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import render_template
from flask import redirect
from flask import url_for
from flask import flash
from flask import request
from flask import send_from_directory
from flask import abort
from flask import current_app
from flask import jsonify
from flask.ext.lo... |
def request_method_decorator(f):
"""Wraps methods returned from a resource to capture HttpRequests.
When a method which returns HttpRequests is called, it will
pass the method and arguments off to the transport to be executed.
This wrapping allows the transport to skim arguments off the top
of the... |
from functools import partial
import os.path as op
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/T... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SupervisionDocument'
db.create_table(u'ilsgateway_supervisiondocument', (
(u'i... |
from selenium.webdriver.common import service
class Service(service.Service):
def __init__(self, executable_path, port=0, verbose=False, log_path=None):
"""
Creates a new instance of the EdgeDriver service.
EdgeDriver provides an interface for Microsoft WebDriver to use
with Micr... |
"""
=================================================================
Test with permutations the significance of a classification score
=================================================================
In order to test if a classification score is significative a technique
in repeating the classification procedure aft... |
#/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from celery import Celery, Task
celery = Celery('tasks')
celery.config_from_object('celeryconfig')
celery.conf.update(
CELERY_RESULT_SERIALIZER='json',
CELERY_TASK_SERIALIZER='json',
CELERY_TASK_RESULT_EXPIRES=60,
C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.