content string |
|---|
import json
from amcat.models import Medium, Article
from api.rest.mixins import DatatablesMixin
from api.rest.serializer import AmCATModelSerializer
from api.rest.viewset import AmCATViewSetMixin
__all__ = ("ArticleSerializer", "ArticleViewSet")
class ArticleViewSetMixin(AmCATViewSetMixin):
model_key = "article"... |
"""
Jump X Frames on Shift Up/Down
When you hit Shift Up/Down, you'll jump 10 frames forward/backwards.
Sometimes is nice to tweak that value.
In the User Preferences, Editing tab, you'll find a "Frames to Jump"
slider where you can adjust how many frames you'd like to move
forwards/backwards.
Make sure you save you... |
from osv import fields, osv
from tools.translate import _
import netsvc
import pooler
import time
import tools
import wizard
import base64
class calendar_event_import(osv.osv_memory):
"""
Import Calendar Event.
"""
cnt = 0
def process_imp_ics(self, cr, uid, ids, context=None):
"""
... |
"""Copyright 2009 Chris Davis
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 writing, software
dist... |
#!/usr/bin/env python
from time import sleep
import yaml
from player import Player
from attack import Attack
def main():
# Load YAML config
config_path = "./attack.yml"
f = open(config_path, 'r')
attack_config = yaml.load(f)
f.close()
# Load attacks
attacks = {}
for name, properties... |
import sys
sys.path.insert(0, '.') # nopep8
import logging
import sqlite3
import collections
import datetime as dt
from flask import Flask, g, jsonify
from timeit import default_timer as timer
import os
import flask
import oneoffs.joseki.opening_freqs as openings
# static_folder is location of npm build
app = Flas... |
try:
from thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
try:
from _abcoll import KeysView, ValuesView, ItemsView
except ImportError:
pass
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps ... |
"""Tests for the data_helper.check module"""
import sys, unittest
from BaseTest import BaseTestWrapper
class IsBoolTestCase(BaseTestWrapper.BaseTest):
"""check.is_bool() test cases"""
def test_string(self):
"""Test if string is False"""
x = 'y'
self.assertFalse(self._bt['func'](x))
... |
import flags
import unittest
import re
import source
class FlagTestCase(unittest.TestCase):
def testParseParamDescription(self):
desc = '{!bbb|ccc?} aaa This \nis the desc. '
self.assertEquals(
('aaa', '!bbb|ccc?', 'This \nis the desc.'),
flags.ParseParameterDescription(desc))
desc = '{..... |
"""
Verifies that app bundles are built correctly.
"""
import TestGyp
import sys
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
test.run_gyp('framework.gyp', chdir='framework')
test.build('framework.gyp', 'test_framework', chdir='framework')
# Binary
test.built_f... |
from contextlib import contextmanager
import os
import sys
from unittest import expectedFailure
from django.test import TestCase
from django.test.runner import DiscoverRunner
def expectedFailureIf(condition):
"""Marks a test as an expected failure if ``condition`` is met."""
if condition:
return expe... |
from docutils.parsers.rst import Directive, directives
from docutils import nodes
from string import upper
from sphinx.util.compat import make_admonition
from sphinx import addnodes
from sphinx.locale import _
class bestpractice(nodes.Admonition, nodes.Element):
pass
class BestPractice(Directive):
has_content... |
#pylint: disable=missing-docstring, no-else-return, invalid-name, unused-variable, superfluous-parens
"""Testing inconsistent returns"""
import math
import sys
# These ones are consistent
def explicit_returns(var):
if var >= 0:
return math.sqrt(var)
else:
return None
def explicit_returns2(var)... |
import os
import sys
from PIL import Image
from django.conf import settings
from django.core.files.storage import default_storage as storage
from core.utils import resize_image
prefix_profile = 'uploads/profiles/'
prefix_container = 'uploads/container/'
prefix_upload_company = 'upload/logo_company'
def upload_loca... |
"""
Decision Tree Classification Example.
"""
from __future__ import print_function
from pyspark import SparkContext
# $example on$
from pyspark.mllib.tree import DecisionTree, DecisionTreeModel
from pyspark.mllib.util import MLUtils
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="PythonDec... |
import fnmatch
import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def matches_patterns(path, patterns=None):
"""
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
"""
if patt... |
# -*- coding: utf-8 -*-
import re
from module.plugins.internal.Crypter import Crypter
from module.network.HTTPRequest import BadHeader
class EmbeduploadCom(Crypter):
__name__ = "EmbeduploadCom"
__type__ = "crypter"
__version__ = "0.07"
__status__ = "testing"
__pattern__ = r'http://(?:www... |
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
class account_automatic_reconcile(osv.osv_memory):
_name = 'account.automatic.reconcile'
_description = 'Automatic Reconcile'
_columns = {
'account_ids': fields.many2many('account.account', 'reconcile_account_re... |
class ExtendedGcdEuclidean:
def __init__(self, modulo_num, another_num):
self.modulo_num = modulo_num
self.r_list = list([modulo_num, another_num])
self.q_list = list([None, None])
self.x_list = list([1, 0])
self.y_list = list([0, 1])
self.iter_list = list([-1, 0])
... |
# -*- coding: utf-8 -*-
__version__ = "0.0.0.0.1b Pre Alpha Alpha"
__author__ = "Tony Martin"
# Creating a host file for blocking ads
# Based on the idea of various adblocking sw running on TomatoUSB
# The goal is to simplify the adblocking sw by having a central point
# that merges and hosts the host file - this will... |
# encoding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class OktoberfestTVIE(InfoExtractor):
_VALID_URL = r'https?://www\.oktoberfest-tv\.de/[^/]+/[^/]+/video/(?P<id>[^/?#]+)'
_TEST = {
'url': 'http://www.oktoberfest-tv.de/de/kameras/video/hb-zelt',
'info... |
#!/bin/python
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import numpy as np
import math
# State vector:
# 0-3: quaternions (q0, q1, q2, q3)
# 4-6: Velocity - m/sec (North, East, Down)
# 7-9: Position - m (North, East, Down)
# 10-12: Delta Angle bias - rad (X,Y,Z)
#... |
import abc
import typing
import pkg_resources
import google.auth # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.ads.googleads.v8.resources.types import c... |
import sys, unittest
import xml.etree.ElementTree as et
import pandas as pd
import numpy as np
from JSBSim_utils import CreateFDM, SandBox, ExecuteUntil
class TestScriptOutput(unittest.TestCase):
def setUp(self):
self.sandbox = SandBox()
self.script_path = self.sandbox.path_to_jsbsim_file('scripts... |
"""
This morphological reconstruction routine was adapted from CellProfiler, code
licensed under both GPL and BSD licenses.
Website: http://www.cellprofiler.org
Copyright (c) 2003-2009 Massachusetts Institute of Technology
Copyright (c) 2009-2011 Broad Institute
All rights reserved.
Original author: Lee Kamentsky
"""... |
#!/usr/bin/env python
# This script is used to test the new method implementation
# It does that by comparing the computed prayer times for specific
# locations on specific dates to the "official" times on these dates.
# "official" turns out to be a tricky one for locations in places
# that are in non-Muslim countries... |
# This file is a minimal clang-format vim-integration. To install:
# - Change 'binary' if clang-format is not on the path (see below).
# - Add to your .vimrc:
#
# map <C-I> :pyf <path-to-this-file>/clang-format.py<cr>
# imap <C-I> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
#
# The first line enables clang-fo... |
#!/bin/env python
"""
Spacewalk external inventory script
=================================
Ansible has a feature where instead of reading from /etc/ansible/hosts
as a text file, it can query external programs to obtain the list
of hosts, groups the hosts are in, and even variables to assign to each host.
To use thi... |
# coding=utf-8
import socket
import json
import logging
import configuracao
logger = logging.getLogger()
class Contadores(object):
def __init__(self):
self.idiomas = {}
self.com_link = 0
self.sem_link = 0
# Porta que o Servidor esta
self.tcp = socket.socket(socket.AF_INET,... |
# -*- coding: utf-8 -*-
"""
requests.auth
~~~~~~~~~~~~~
This module contains the authentication handlers for Requests.
"""
import os
import re
import time
import hashlib
from base64 import b64encode
from .compat import urlparse, str
from .cookies import extract_cookies_to_jar
from .utils import parse_dict_header, ... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
unified_strdate,
xpath_text,
)
class CinchcastIE(InfoExtractor):
_VALID_URL = r'https?://player\.cinchcast\.com/.*?assetId=(?P<id>[0-9]+)'
_TEST = {
# Actual test is run in generic,... |
"""Test configs for pack."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.lite.testing.zip_test_utils import create_tensor_data
from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests... |
""" Modified version of build_clib that handles fortran source files.
"""
from __future__ import division, absolute_import, print_function
import os
from glob import glob
import shutil
from distutils.command.build_clib import build_clib as old_build_clib
from distutils.errors import DistutilsSetupError, DistutilsError... |
#!/usr/bin/python
import unittest
import json
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__),
os.pardir,
os.pardir))
from nysa.cbuilder import sdb_component
SDB_DATA = \
" Set the Vendor ID (Hexidecimal 64-bit Number)\n" \... |
"""Tests for tensorflow.python.client.session.Session's partial run APIs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.client import session
from tensorflow.pyth... |
# encoding: utf-8
"""
Make reading the news more fun.
http://xkcd.com/1288/
"""
from __future__ import unicode_literals
import re
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
substitutes = {
"witnesses": "these dudes I know",
"Witnesses": "Th... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import inspect
import sys
from ansible.module_utils.basic import _load_params
from ansible.m... |
"""
Provides I{marshaller} core classes.
"""
from logging import getLogger
from suds import *
from suds.mx import *
from suds.mx.appender import ContentAppender
from suds.sax.element import Element
from suds.sax.document import Document
from suds.sudsobject import Property
log = getLogger(__name__)
class Core:
... |
#!/usr/bin env python
from tests.unit import AWSMockServiceTestCase
from boto.cloudsearch2.domain import Domain
from boto.cloudsearch2.layer1 import CloudSearchConnection
class TestCloudSearchCreateDomain(AWSMockServiceTestCase):
connection_class = CloudSearchConnection
def default_body(self):
retu... |
import json
import sys
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.urls import fetch_url
def scaleway_argument_spec():
return dict(
api_token=dict(required=True, fallback=(env_fallback, ['SCW_TOKEN', 'SCW_API_KEY', 'SCW_OAUTH_TOKEN', 'SCW_API_TOKEN']),
... |
"""
Verify handling of build variants.
TODO: Right now, only the SCons generator supports this, so the
test case is SCons-specific. In particular, it relise on SCons'
ability to rebuild in response to changes on the command line. It
may be simpler to just drop this feature if the other generators
can't be made to b... |
"""These functions are executed via gyp-flock-tool when using the Makefile
generator. Used on systems that don't have a built-in flock."""
import fcntl
import os
import struct
import subprocess
import sys
def main(args):
executor = FlockTool()
executor.Dispatch(args)
class FlockTool(object):
"""This class e... |
#!/usr/bin/python3
"""
Planbot's Facebook application. Handles requests and responses through the
Facebook Graph API. Converts location data to postcode with Postcodes.io API.
"""
import os
import logging
import requests
from bottle import Bottle, request, debug
from engine import Engine
# set environmental variabl... |
from django.utils.translation import gettext_lazy as _
from lino.mixins import RegistrableState
from lino.api import dd
class PollStates(dd.Workflow):
item_class = RegistrableState
verbose_name_plural = _("Poll states")
required_roles = dd.login_required(dd.SiteStaff)
add = PollStates.add_item
add('10', ... |
"""
WSGI config for logan project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... |
"""
===================
Main setup runner
===================
This module provides a wrapper around the distutils core setup.
"""
__author__ = "Andr\xe9 Malo"
__docformat__ = "restructuredtext en"
import configparser as _config_parser
from distutils import core as _core
import os as _os
import posixpath as _posixpat... |
'''
$ python3 sum_of_digits.py
Input a number that we will use as available digits: 12234
Input a number that represents the desired sum: 5
There are 4 solutions.
$ python3 sum_of_digits.py
Input a number that we will use as available digits: 11111
Input a number that represents the desired sum: 5
There is a unique so... |
from odoo.addons.survey.tests.common import TestSurveyCommon
class TestCourseCertificationFailureFlow(TestSurveyCommon):
def test_course_certification_failure_flow(self):
# Step 1: create a simple certification
# --------------------------------------------------
with self.with_user('surve... |
__all__ = [
'LXMLTreeBuilderForXML',
'LXMLTreeBuilder',
]
from StringIO import StringIO
import collections
from lxml import etree
from bs4.element import Comment, Doctype, NamespacedAttribute
from bs4.builder import (
FAST,
HTML,
HTMLTreeBuilder,
PERMISSIVE,
TreeBuilder,
XML)
from b... |
__author__ = 'ZSGX'
import mysql.connector
from model.group import Group
from model.contact import Contact
import re
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection... |
#!/usr/bin/env python3
# Week 3 homework
list = ["apples", "pears", "oranges", "peaches"]
print (list)
# prompt the user for a fruit to add to our list
fruit = input ("Add a fruit: ")
list.append(fruit)
print (list)
# prompt the user for a fruit by index number
index = 0
while (index <=0) or (index > len(list)):... |
from unittest import TestCase
import simplejson as json
# from http://json.org/JSON_checker/test/pass1.json
JSON = r'''
[
"JSON Test Pattern pass1",
{"object with 1 member":["array with 1 element"]},
{},
[],
-42,
true,
false,
null,
{
"integer": 1234567890,
"real": -... |
# -*- coding: utf-8 -*-
"""Video xmodule tests in mongo."""
from mock import patch
import os
import tempfile
import textwrap
import json
from datetime import timedelta
from webob import Request
from xmodule.contentstore.content import StaticContent
from xmodule.modulestore import Location
from xmodule.contentstore.dj... |
"""allow programmer to define multiple exit functions to be executedupon normal program termination.
Two public functions, register and unregister, are defined.
"""
class __loader__(object):
pass
def _clear(*args,**kw):
"""_clear() -> None
Clear the list of previously registered exit functions."""
... |
from __future__ import absolute_import
import time
import logging
from ..exceptions import (
ConnectTimeoutError,
MaxRetryError,
ProtocolError,
ReadTimeoutError,
ResponseError,
)
from ..packages import six
log = logging.getLogger(__name__)
class Retry(object):
""" Retry configuration.
... |
"""Tokenization utils for RoFormer."""
from typing import List
from tokenizers import NormalizedString, PreTokenizedString, normalizers
class JiebaPreTokenizer:
def __init__(self, vocab) -> None:
self.vocab = vocab
self.normalizers = normalizers.BertNormalizer(
clean_text=False,
... |
"""\
Core Linear Algebra Tools
-------------------------
Linear algebra basics:
- norm Vector or matrix norm
- inv Inverse of a square matrix
- solve Solve a linear system of equations
- det Determinant of a square matrix
- lstsq Solve linear least-squares problem... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ViewBox is the general-purpose graphical container that allows the user to
zoom / pan to inspect any area of a 2D coordinate system.
This unimaginative example demonstrates the constrution of a ViewBox-based
plot area with axes, very similar to the way PlotItem is built.... |
from functools import partial
from os import getcwd
import pdb
import sys
from warnings import warn
from nose.plugins import Plugin
from noseprogressive.runner import ProgressiveRunner
from noseprogressive.tracebacks import DEFAULT_EDITOR_SHORTCUT_TEMPLATE
from noseprogressive.wrapping import cmdloop, set_trace, Stre... |
DATE_FORMAT = 'd F Y' # 25 Ottobre 2006
TIME_FORMAT = 'H:i:s' # 14:30:59
DATETIME_FORMAT = 'l d F Y H:i:s' # Mercoledì 25 Ottobre 2006 14:30:59
YEAR_MONTH_FORMAT = 'F Y' # Ottobre 2006
MONTH_DAY_FORMAT = 'j/F' # 10/2006
SHORT_DATE_FORMAT = 'd/M/Y' # 25/12/2009
SHORT_DATETIME_FORMAT = 'd/M/Y H:i:s' # 25/10/2009 14:30:59... |
from openerp.osv import fields, osv
import time
from openerp.tools.translate import _
class res_partner(osv.osv):
""" add field to indicate default 'Communication Type' on customer invoices """
_inherit = 'res.partner'
def _get_comm_type(self, cr, uid, context=None):
res = self.pool.get('acc... |
"""Unit test for Google Test's break-on-failure mode.
A user can ask Google Test to seg-fault when an assertion fails, using
either the GTEST_BREAK_ON_FAILURE environment variable or the
--gtest_break_on_failure flag. This script tests such functionality
by invoking gtest_break_on_failure_unittest_ (a program written... |
# -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... |
from __future__ import print_function
import os
import sys
import tempfile
from target_test import FileSystemTargetTestMixin
from helpers import with_config, unittest
from boto.exception import S3ResponseError
from boto.s3 import key
from moto import mock_s3
from luigi import configuration
from luigi.s3 import FileN... |
"""OnscreenImage module: contains the OnscreenImage class"""
__all__ = ['OnscreenImage']
from panda3d.core import *
from direct.showbase.DirectObject import DirectObject
import types
class OnscreenImage(DirectObject, NodePath):
def __init__(self, image = None,
pos = None,
hpr = ... |
from couchpotato.api import addApiView
from couchpotato.core.event import fireEvent, addEvent
from couchpotato.core.helpers.variable import mergeDicts, getImdb
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
log = CPLog(__name__)
class Search(Plugin):
def __init__(self... |
"""Translation helper functions."""
import functools
import gettext as gettext_module
import os
import re
import sys
import warnings
from collections import OrderedDict
from threading import local
from django.apps import apps
from django.conf import settings
from django.conf.locale import LANG_INFO
from django.core.ex... |
import gettext
from Screen import Screen
from Components.ActionMap import ActionMap
from Components.Language import language
from Components.config import config
from Components.Sources.List import List
from Components.Label import Label
from Components.Pixmap import Pixmap
from Screens.InfoBar import InfoBar
from Scre... |
import unittest
import os, glob
from test_all import db, test_support, get_new_environment_path, \
get_new_database_path
#----------------------------------------------------------------------
class DBEnv(unittest.TestCase):
def setUp(self):
self.homeDir = get_new_environment_path()
self.... |
import random
from PyQt4 import QtCore, QtGui, QtNetwork
class FortuneThread(QtCore.QThread):
error = QtCore.pyqtSignal(QtNetwork.QTcpSocket.SocketError)
def __init__(self, socketDescriptor, fortune, parent):
super(FortuneThread, self).__init__(parent)
self.socketDescriptor = socketDescript... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'~/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.frameworks.opf.expd... |
"""
Session Management
(from web.py)
"""
import os, time, datetime, random, base64
import os.path
from copy import deepcopy
try:
import cPickle as pickle
except ImportError:
import pickle
try:
import hashlib
sha1 = hashlib.sha1
except ImportError:
import sha
sha1 = sha.new
import utils
import ... |
import os.path
import sys
import traceback
from trac.core import *
from trac.util.text import levenshtein_distance
from trac.util.translation import _
console_date_format = '%Y-%m-%d'
console_datetime_format = '%Y-%m-%d %H:%M:%S'
console_date_format_hint = 'YYYY-MM-DD'
class IAdminPanelProvider(Interface):
"""... |
"""Support for ThinkingCleaner sensors."""
from datetime import timedelta
import logging
from pythinkingcleaner import Discovery, ThinkingCleaner
import voluptuous as vol
from homeassistant import util
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_HOST, UNIT_PERCENTA... |
from __future__ import absolute_import
import cairo
from gi.repository import Gtk
from gi.repository import GObject
from gi.repository import Gdk
from .OverlayWindow import OverlayWindow
from .__init__ import NORTH, EAST, SOUTH, WEST
class ArrowButton (OverlayWindow):
""" Leafs will connect to the drag-drop sig... |
import rtorrent.rpc
from rtorrent.common import safe_repr
Method = rtorrent.rpc.Method
class Tracker:
"""Represents an individual tracker within a L{Torrent} instance."""
def __init__(self, _rt_obj, info_hash, **kwargs):
self._rt_obj = _rt_obj
self.info_hash = info_hash # : info hash for t... |
# test_getopt.py
# David Goodger <<EMAIL>> 2000-08-19
from test.support import verbose, run_doctest, run_unittest, EnvironmentVarGuard
import unittest
import getopt
sentinel = object()
class GetoptTests(unittest.TestCase):
def setUp(self):
self.env = EnvironmentVarGuard()
if "POSIXLY_CORRECT" in... |
"""Tests for the alot.commands.envelope module."""
import email
import os
import tempfile
import textwrap
import unittest
from unittest import mock
from alot.commands import envelope
from alot.db.envelope import Envelope
from alot.errors import GPGProblem
from alot.settings.errors import NoMatchingAccount
from alot.s... |
import os
import sys
import shutil
project_name = "mgmt"
main_file = "mgmt.py"
# If you get corrupted errors, use this
clean = " " # " --clean "
remove_spec_file = False
spec_file = project_name + ".spec"
# Don't wan't old spec files right now.
if remove_spec_file and os.path.exists(spec_file):
os.unlink(spec_... |
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class Sum(function.Function):
"""Sum of array elements over a given axis."""
keepdims = False
def __init__(self, axis=None, keepdims=False):
if axis is None:
self.axis = None
elif isins... |
import numpy as np
import unittest
import scipy.stats
from . import test_connect_helpers as hf
from .test_connect_parameters import TestParams
class TestPairwiseBernoulli(TestParams):
# specify connection pattern and specific params
rule = 'pairwise_bernoulli'
p = 0.5
conn_dict = {'rule': rule, 'p': ... |
from webkitpy.tool.commands.abstractsequencedcommand import AbstractSequencedCommand
from webkitpy.tool import steps
class PrettyDiff(AbstractSequencedCommand):
name = "pretty-diff"
help_text = "Shows the pretty diff in the default browser"
show_in_main_help = True
steps = [
steps.ConfirmDiff,... |
import logging
import plistlib
from django.db import transaction
from django.http import HttpResponse
from django.views.generic import View
from zentral.contrib.inventory.models import MetaBusinessUnit
from zentral.contrib.inventory.utils import commit_machine_snapshot_and_trigger_events
from zentral.contrib.mdm.comman... |
import sys
import argparse
def convert_to_parser_args(args_source=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=0)
#######################
### experiment info
#######################
parser.add_argument('--env_name', type=str)
parser.ad... |
#found this solution on http://stackoverflow.com/questions/8870261/how-to-split-text-without-spaces-into-list-of-words
def find_words(instring, prefix = '', words = None):
if not instring:
return []
if words is None:
words = set()
with open('/usr/share/dict/words') as f:
for ... |
"""Escaping/unescaping methods for HTML, JSON, URLs, and others.
Also includes a few other miscellaneous string manipulation functions that
have crept in over time.
"""
from __future__ import absolute_import, division, print_function, with_statement
import re
import sys
from tornado.util import unicode_type, basest... |
Constraints DEFINITIONS ::=
BEGIN
-- Single Value
SingleValue ::= INTEGER (1)
SingleValue2 ::= INTEGER (1..20)
predefined INTEGER ::= 1
SingleValue3 ::= INTEGER (predefined | 5 | 10)
Range2to19 ::= INTEGER (1<..<20)
Range10to20 ::= INTEGER (10..20)
ContainedSubtype ::= INTEGER (INCLUDES Range10to20)
-- Some ranges for... |
"""
Wrapper class that takes a list of template loaders as an argument and attempts
to load templates from them in order, caching the result.
"""
import hashlib
from django.template import TemplateDoesNotExist
from django.template.backends.django import copy_exception
from django.utils.encoding import force_bytes, fo... |
import json
import unittest
from fs.memoryfs import MemoryFS
from mock import Mock, patch
from xblock.field_data import DictFieldData
from xblock.fields import ScopeIds
from xmodule.error_module import NonStaffErrorDescriptor
from opaque_keys.edx.locations import SlashSeparatedCourseKey, Location
from xmodule.modules... |
"""subprocess management for dak
@copyright: 2013, Ansgar Burchardt <<EMAIL>>
@license: GPL-2+
"""
# 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 you... |
from __future__ import unicode_literals
from markupsafe import Markup, escape
from indico.modules.events.registration.models.items import PersonalDataType
from indico.util.i18n import _
from indico.util.placeholders import ParametrizedPlaceholder, Placeholder
from indico.web.flask.util import url_for
class FirstNam... |
import optparse
import sys
import time
import urllib2
def PrintAndFlush(s):
print s
sys.stdout.flush()
def main(args):
parser = optparse.OptionParser(usage='%prog [options] <URL to load>')
parser.add_option('--post', help='POST to URL.', dest='post',
action='store_true')
parser.add_optio... |
import errno
from functools import partial
import select
import sys
try:
from time import monotonic
except ImportError:
from time import time as monotonic
__all__ = ["NoWayToWaitForSocketError", "wait_for_read", "wait_for_write"]
class NoWayToWaitForSocketError(Exception):
pass
# How should we wait on ... |
from functools import wraps
from flask import g
from app.constants import (
ask_to_register_answer, student_required_answer, educator_required_answer
)
from app.models import User
from tg_bot import bot
def login_required_message(func):
@wraps(func)
def wrapper(message):
user = User.query.filter... |
import ConfigParser
import argparse
import gzip
import os
def readdoc(path=None):
if path is None:
return False
f = gzip.open(path, 'r')
return f.read()
configfile = os.path.join(os.environ['AIL_BIN'], 'packages/config.cfg')
cfg = ConfigParser.ConfigParser()
cfg.read(configfile)
# Indexer config... |
"""The 'grit android2grd' tool."""
import getopt
import os.path
import StringIO
from xml.dom import Node
import xml.dom.minidom
import grit.node.empty
from grit.node import io
from grit.node import message
from grit.tool import interface
from grit import grd_reader
from grit import lazy_re
from grit import tclib
f... |
from __future__ import absolute_import, division, print_function, \
with_statement
import errno
import traceback
import socket
import logging
import json
import collections
from shadowsocks import common, eventloop, tcprelay, udprelay, asyncdns, shell
BUF_SIZE = 1506
STAT_SEND_LIMIT = 50
class Manager(object)... |
from __future__ import print_function, division
from sympy.core import S, sympify, Expr, Rational, Symbol, Dummy
from sympy.core import Add, Mul, expand_power_base, expand_log
from sympy.core.cache import cacheit
from sympy.core.compatibility import default_sort_key, is_sequence
from sympy.core.containers import Tuple... |
from openerp.osv import fields, osv
class account_invoice(osv.osv):
_inherit = "account.invoice"
_columns = {
'incoterm_id': fields.many2one(
'stock.incoterms', 'Incoterm',
help="International Commercial Terms are a series of predefined commercial terms "
"used ... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, 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 Lic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.