content string |
|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('electronics', '0010_auto_20141120_0704'),
]
operations = [
migrations.CreateModel(
name='Order',... |
from odoo import fields, api, models
import base64
class L10nArAfipwsUploadCertificate(models.TransientModel):
_name = 'afipws.upload_certificate.wizard'
@api.model
def get_certificate(self):
return self.env['afipws.certificate'].browse(
self._context.get('active_id'))
certificat... |
import logging
import argparse
from helper_functions import (load_graph_database, select_itr,
load_options, attach_table,
generate_special_database_name,
grab_vector, grab_all,compute_parallel)
import invariants
desc = "Updates ... |
import re,sys,urllib,urllib2,urlparse,HTMLParser,time,random,base64,unicodedata
RES_8K = ['8k', 'hd8k', 'hd8k ', '8khd', '8khd ', '4320p', '4320i', 'hd4320', '4320hd', '4320p ', '4320i ', 'hd4320 ', '4320hd ', '5120p', '5120i', 'hd5120', '5120hd', '5120p ', '5120i ', 'hd5120 ', '5120hd ', '8192p', '8192i', 'hd8192'... |
"""KTEQ-FM SLACK API CALLS.
This module contains all of the SlackClient API calls for the TeqBot project.
These api calls are all located centrally within this module for convenience.
All API calls will be built in this module, and corresponding wapper functions
will be created for each of these calls for TeqBot to ... |
# -*- coding: utf-8 -*-
import re
import string
import json
from pkg_resources import resource_string
import Levenshtein
COMMON_BREWERY_TERMS = [
u'Trappistenbrouwerij',
u'Trappistenbier-Brauerei',
u'Bierbrouwerij',
u'Bryggeri & Spiseri',
u'Mikrobryggeri',
u'Microbirrificio',
u'Ølbryggeri'... |
from . import base
from grow.common import utils as common_utils
from boto.s3 import connection
from boto.s3 import key
from grow.pods import env
from protorpc import messages
import boto
import cStringIO
import logging
import os
import mimetypes
class Config(messages.Message):
bucket = messages.StringField(1)
... |
from __future__ import print_function
import bisect
from rdkit import DataStructs
from rdkit.DataStructs.TopNContainer import TopNContainer
class GenericPicker(object):
_picks = None
def MakePicks(self, force=False):
raise NotImplementedError("GenericPicker is a virtual base class")
def __len__(self):
... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v6.resources",
marshal="google.ads.googleads.v6",
manifest={"ParentalStatusView",},
)
class ParentalStatusView(proto.Message):
r"""A parental status view.
Attributes:
resource_name (str):
... |
import sys
import platform
def getArch() :
"""
Return the NuPIC architecture name.
Note that this is redundant with the calculation in configure.ac (<-- TODO so remove?)
"""
if sys.platform == "linux2":
#
# platform.processor() vs. platform.machine() is a bit of a mystery
# On linux systems, the... |
"""IdNr (Steuerliche Identifikationsnummer, German personal tax number).
The IdNr (or Steuer-IdNr) is a personal identification number that is
assigned to individuals in Germany for tax purposes and is meant to replace
the Steuernummer. The number consists of 11 digits and does not embed any
personal information.
Mor... |
"""Shapes for Spriteworld.
Contains functions that generate np.arrays containing vertex arrays for various
sprite shapes.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import range
def _polar2cartesian(r, theta):
... |
from struct import (
calcsize,
pack,
unpack,
Struct
)
class Structs(object):
Byte = Struct('!B')
Int16 = Struct('!h')
Int32 = Struct('!i')
Int64 = Struct('!q')
class BinaryReader(object):
def __init__(self, buf):
self._buf = buf
def ReadString(self):
str_len, = Structs.Int16.unpack(sel... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
xpath_attr,
xpath_text,
)
class RuutuIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\... |
# -*- coding: utf-8 -*-
"""
@file __init__.py
@author Michael Behrisch
@author Jakob Erdmann
@date 2011-06-23
@version $Id: __init__.py 13811 2013-05-01 20:31:43Z behrisch $
Python interface to SUMO especially for parsing output files.
SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
Copyr... |
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
s... |
from pandas import DataFrame, read_csv, concat
from os import walk
import numpy as np
from pdb import set_trace
import sys
def say(text):
sys.stdout.write(str(text))
def shuffle(df, n=1, axis=0):
df = df.copy()
for _ in range(n):
df.apply(np.random.shuffle, axis=axis)
return df
def cs... |
from epsilon.hotfix import require
require("twisted", "trial_assertwarns")
from axiom.store import Store
from axiom.item import Item
from axiom.attributes import integer, text, AND
from twisted.trial import unittest
from xmantissa import tdb, scrolltable
class X(Item):
typeName = 'test_tdb_model_dummy'
sche... |
'''
Created on 11/07/2013
@author: mmpe
'''
import sys
import os
from mmpe.build_exe.cx.tests.demonstration.matplotlibwidget import MatplotlibWidget
if os.path.realpath("../../../") not in sys.path:
sys.path.append(os.path.realpath("../../../"))
import os
from mmpe.build_exe.cx import build_cx_exe
import os
imp... |
from discord.ext import commands
from cogs.database import *
class Pick:
"""Pick a random hero or set of heroes."""
def __init__(self, bot):
self.bot = bot
self.agora = self.bot.get_cog('Agora') # Requires the Agora extension be loaded
@commands.command()
async def pick(self, ctx):... |
#!/usr/bin/env python3
from setuptools import setup
with open("README.md", "r") as f:
long_description = f.read()
setup(
name='passpy',
version='1.0.1',
description='ZX2C4\'s pass compatible Python library and cli',
long_description=long_description,
long_description_content_type='text/mark... |
import logging
from cubetl.core import Node, Component
from cubetl.core.exceptions import ETLConfigurationException
# Get an instance of a logger
logger = logging.getLogger(__name__)
class MDXQuery(Node):
"""
Not yet implemented.
"""
def __init__(self, mapper, query):
super().__init__()
... |
# coding: utf-8
"""
Flip API
Flip # noqa: E501
The version of the OpenAPI document: 3.1
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import telestream_cloud_flip
from telestream_cloud_flip.models.pagi... |
from datetime import timedelta
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
class UserProfile(models.Model):... |
from idd3.base import *
config = Config()
all_transformations = []
all_rulesets = []
def use_language(module):
"""Configure idd3's global variables (config, all_transformations,
and all_rulesets) using those from module.
"""
global config, all_transformations, all_rulesets
for key, value in... |
import GUI
class TextureBar(object):
def __init__(self, texture=''):
self.pb = GUI.Simple(texture)
def add(self):
GUI.addRoot(self.pb)
def delete(self):
GUI.delRoot(self.pb)
def addChild(self,a,b=''):
if b:
self.pb.addChild(a,b)
else:
... |
"""Initial config
Revision ID: 9d31265577
Revises: None
Create Date: 2013-06-21 11:48:43.609000
"""
# revision identifiers, used by Alembic.
revision = '9d31265577'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated ... |
"""
utilities_console_warnings test.
"""
import os
import mutlib
from mysql.utilities.exception import MUTLibError
from mysql.utilities.common.tools import check_python_version
class test(mutlib.System_test):
""" Test the warnings generated at startup for the console. Test requires
Python 2.6.
"""
... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2014, Matthias Feurer
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this li... |
# coding: u8
import atexit
import datetime
import psycopg2
import dhtlib
class Store(dhtlib.Store):
def __init__(self, user, pwd, host, port, db='dht', max_cache_size=1500):
self.max_cache_size = max_cache_size
self.conn = psycopg2.connect(database=db, user=user, password=pwd,
host... |
import dateutil.parser
import six
from django import forms
from django.core import exceptions
from django.db.models import Max
from .models import CACertificate, Certificate
from OpenSSL import crypto
from certs.certgen.certgen import (
createKeyPair,
createCertRequest,
createCertificate,
)
MAX_LENGTH =... |
import re
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class RegistrationForm(forms.Form):
username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Username"), error_mess... |
# -*- coding: utf-8 -*-
from string import Template
import yaml
import shutil, errno
import glob, os
def path_del(path, rm=True):
if os.path.exists(path):
if os.path.isdir(path):
if rm:
shutil.rmtree(path)
else:
for the_file in os.listdir(path):
... |
"""actofgoods URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
'''
Task: contains the Task class.
This is the main class for using jug.
There are two main alternatives:
- Use the ``Task`` class directly to build up tasks, such as ``Task(function, arg0, ...)``.
- Rely on the ``TaskGenerator`` decorator as a shortcut for this.
'''
from .hash import new_hash_object, hash_update,... |
from __future__ import print_function
import numpy as np
class ResultMunger(object):
def __init__(self, tree_summaries, mutlist, mutass):
self._tree_summaries = tree_summaries
self._mutlist = mutlist
self._mutass = mutass
def _convert_keys_to_ints(self, dic):
keys = dic.keys()
for key in dic.k... |
"""
Usage:
eval.py [--equal-precision-recall] <output_dir>
Arguments:
<output_dir> Output spectrogram probability masks
--equal-precision-recall If set, output the point where the precision and recall are equal
"""
import docopt
import sys
import os
from PIL import Image
import ... |
"""The objects in this module represent a series of operations
which can be performed against an array of samples. These
samples could theoretically be anything, but the core purpose
is audio data. All of these operations support multi-channel
audio as their core input, but may only operate on one channel, if
they desi... |
"""
The MIT License (MIT)
Copyright (c) 2016 Coin Graham IV
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge... |
'''
Created on 8 Sep 2017
@author: Miguel Molina Romero, Techical University of Munich
@contact: <EMAIL>
@license: LPGL
'''
import unittest
import nibabel as nib
import numpy as np
import os
import shutil
from dwybss.bss import bss, bss_cals, utils
class TestBssCals(unittest.TestCase):
def setUp(self):
s... |
""" This module is a sample configuration of the Land Change Cover Model (LCCM).
It is intended to be modified to specify parameters to the model, or to
make basic modifications to its behavior."""
#############################################################################
# Configuration settings
##########... |
import base64
import odoo.tests
from odoo.modules.module import get_module_resource
@odoo.tests.tagged('post_install', '-at_install')
class TestUi(odoo.tests.HttpCase):
def setUp(self):
super(TestUi, self).setUp()
# Setup attributes and attributes values
self.product_attribute_1 = self... |
from typing import Dict, List, Iterator, Any, Optional
import sys
import textwrap
import requests
__all__ = (
'BugZooException',
'ConnectionFailure',
'BadManifestFile',
'BadCoverageInstructions',
'UnexpectedResponse',
'UnexpectedServerError',
'UnexpectedStatusCode',
'BugAlreadyBuilt',... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
__author__ = "Viktor Petersson"
__copyright__ = "Copyright 2012, WireLoad Inc"
__license__ = "Dual License: GPLv2 and Commercial License"
__version__ = "0.1.4"
__email__ = "<EMAIL>"
from datetime import datetime, timedelta
from functools import wraps
from hurry.filesize im... |
"""
LLDB AppKit formatters
part of The LLVM Compiler Infrastructure
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
"""
# example summary provider for NSMachPort
# the real summary is now C++ code built into LLDB
import lldb
import ctypes
import lldb.runtime.... |
from selenium.common.exceptions import (ElementClickInterceptedException,
ElementNotInteractableException,
ElementNotSelectableException,
ElementNotVisibleException,
... |
"""
.. _bkr-system-release:
bkr system-release: Release a reserved Beaker system
====================================================
.. program:: bkr system-release
Synopsis
--------
:program:`bkr system-release` [*options*] <fqdn>...
Description
-----------
Releases a Beaker system which has been reserved (usin... |
try:
from . import generic as g
except BaseException:
import generic as g
class VisualTest(g.unittest.TestCase):
def test_visual(self):
mesh = g.get_mesh('featuretype.STL')
# stl shouldn't have any visual properties defined
assert not mesh.visual.defined
for facet in mes... |
#-*-coding:utf-8-*-
from django.shortcuts import render,render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from tools.dbcon import *
from online.models import User
import json
import sys
reload(sys)
sys.setdef... |
import os
import sys
from .. import SetWallpaper
class Win32SetWallpaper(SetWallpaper):
def __init__(self, config):
super(Win32SetWallpaper, self).__init__(config)
def platform_check(self):
return sys.platform == 'win32' and self.config['set-wallpaper'] == 'auto' or self.config['set-wallpaper... |
"""Classes for representing documents for the Google Cloud Firestore API."""
import copy
from google.api_core import retry as retries # type: ignore
from google.cloud.firestore_v1.types import Document
from google.cloud.firestore_v1 import _helpers
from google.cloud.firestore_v1 import field_path as field_path_modu... |
"""Unit tests for GoogleV2CustomMachine class."""
import unittest
from dsub.providers import google_v2_base
import parameterized
class CustomMachineTest(unittest.TestCase):
@parameterized.parameterized.expand([
# (number of vCPUs, expected even number of vCPUs)
(1, 1), # 1 is the only acceptable odd ... |
"""Functions for recovering anchor based topics from a coocurrence matrix"""
import scipy.sparse
import numpy
import random
import numba
from .pipeline import Dataset, filter_empty_words
from .util import sample_categorical
@numba.jit(nopython=True)
def logsum_exp(y):
"""Computes the sum of y in log space"""
... |
"""Model tests for distro series source package branch links."""
__metaclass__ = type
from lp.code.model.seriessourcepackagebranch import (
SeriesSourcePackageBranchSet,
)
from lp.code.tests.helpers import make_linked_package_branch
from lp.registry.interfaces.pocket import PackagePublishingPocket
from lp.tes... |
import platform
from .ome_types import CompileOptions
platform_defines = {
'linux': [
('OME_PLATFORM_POSIX', ''),
('_GNU_SOURCE', ''),
('_LARGEFILE_SOURCE', ''),
('_FILE_OFFSET_BITS', '64'),
],
'darwin': [
('OME_PLATFORM_POSIX', '')
],
}
class BuildOptions(Comp... |
"""Fichier contenant le paramètre 'supprimer' de la commande 'cap'."""
from primaires.interpreteur.masque.parametre import Parametre
class PrmSupprimer(Parametre):
"""Commande 'cap supprimer'.
"""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, "supprimer", ... |
from AppKit import *
from math import floor
import vanilla
import os
from fontTools.misc.arrayTools import pointInRect
from robofab.pens.reverseContourPointPen import ReverseContourPointPen
from mojo.events import BaseEventTool, installTool
from mojo.roboFont import CreateCursor
from mojo.extensions import getExten... |
"""This module is deprecated. Please use :mod:`airflow.providers.qubole.operators.qubole_check`."""
import warnings
from airflow.providers.qubole.operators.qubole_check import ( # noqa
QuboleCheckOperator,
QuboleValueCheckOperator,
)
warnings.warn(
"This module is deprecated. Please use `airflow.provide... |
#!/usr/bin/env python
""" This is a long-running worker process that generates values asychronously
for dogpile.cache and the fcomm_connector api.
It should be run under a sysvinit script as a daemon. It should be run as 8 or
so threads.
"""
import tg
import os
import sys
import json
import time
import types
import ... |
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img1 = Image.open('multipage.tif')
# The following approach seems to be having issue with the
# current TIFF format data
print('The size of each frame is:')
print(img1.size)
# Plots first frame
print('Frame 1'... |
#!/usr/bin/python
import sys
import os
import subprocess
import argparse
import time
from machinekit import launcher
from machinekit import rtapi
launcher.register_exit_handler()
# launcher.set_debug_level(5)
configs_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(configs_dir)
parser = argparse.ArgumentPar... |
class SubscriptionTracking(object):
def __init__(self, enable=None, text=None, html=None, substitution_tag=None):
self._enable = None
self._text = None
self._html = None
self._substitution_tag = None
if enable is not None:
self.enable = enable
if text is... |
def extract_numbers(text, mask=None):
"""
Extracts floats and integers from string text.
Returns:
numbers - list of numbers
locations - locations of each number as list of triples (line, start position, length)
"""
import re
numeric_const_pattern = r"""
[-+]? # optional sig... |
from __future__ import print_function
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path... |
import factory
from django.urls import reverse
from waldur_core.structure.tests import factories as structure_factories
from .. import models
from ..apps import JiraConfig
class JiraServiceSettingsFactory(structure_factories.ServiceSettingsFactory):
type = JiraConfig.service_name
backend_url = 'http://jira/... |
#!/usr/bin/python3
"""
Flask App that renders template for number_page when integer is input
"""
from flask import Flask, render_template
# flask setup
app = Flask(__name__)
app.url_map.strict_slashes = False
port = 5000
ip = '0.0.0.0'
# begin flask page rendering
@app.route('/')
def index():
"""Hello World Resp... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'PersonVote.dataCadastro'
db.alter_column(u'persons_per... |
from typing import Dict
import gevent
import logging
import os
import sys
if os.name == "nt":
from win32api import STD_INPUT_HANDLE
from win32console import (
GetStdHandle,
KEY_EVENT,
ENABLE_ECHO_INPUT,
ENABLE_LINE_INPUT,
ENABLE_PROCESSED_INPUT,
)
else:
import s... |
import re
import sigrokdecode as srd
def _decode_intensity(val):
intensity = val & 0x0f
if intensity == 0:
return 'min'
elif intensity == 15:
return 'max'
else:
return intensity
registers = {
0x00: ['No-op', lambda _: ''],
0x09: ['Decode', lambda v: '0b{:08b}'.format(v)... |
import pytest
import raccoon as rc
def test_index():
actual = rc.Series([4, 5, 6], index=['a', 'b', 'c'])
result = actual.index
assert result == ['a', 'b', 'c']
assert isinstance(result, list)
# test that a view is returned
result.append('bad')
assert actual.index == ['a', 'b', 'c', 'bad... |
import logging
import Queue
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener
from lethril.handlers import StdOutHandler, GenericHandlerWorker
from threading import Thread
# Module level logger
log = logging.getLogger("lethril.twitter")
class TwitterListener(St... |
import asyncio
from aiohttp import web
from .decorators import leela_get, leela_api
class LeelaService(object):
__middlewares = []
@classmethod
def set_middlewares(cls, middlewares):
cls.__middlewares = middlewares
@classmethod
def middlewares(cls):
for mw in cls.__middlewares:
... |
import sys
sys.path.append('..')
from app import *
from datetime import datetime
import pandas as pd
columns = [
Dataset.investigation_type,
Dataset.library_source,
Dataset.env_package,
Dataset.library_strategy,
Dataset.library_screening_strategy,
Dataset.library_construction_method,
Datase... |
"""An extension to the Core and Topology package that models information on the electrical characteristics of Transmission and Distribution networks. This package is used by network applications such as State Estimation, Load Flow and Optimal Power Flow.
"""
from CIM15.CDPSM.Asset.IEC61970.Wires.PerLengthSequenceImped... |
"""
Implementation of neural network
Core implementations
Tianqi Chen
"""
import numpy as np
import sys
# Full connected layer
# note: all memory are pre-allocated, always use a[:]= instead of a= in assignment
class FullLayer:
def __init__( self, i_node, o_node, init_sigma, rec_gsqr = False ):
asser... |
"""
Formtools Preview application.
"""
from django.http import Http404
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils.crypto import constant_time_compare
from django.contrib.formtools.utils import form_hmac
AUTO_ID = 'formtools_%s' # Each form here... |
from datetime import datetime
from django.test import TestCase
from django.core.exceptions import ValidationError
from pacientes_app.models import Paciente
class PacienteTest(TestCase):
def setUp(self):
self.paciente = Paciente.objects.create(
cedula='18423347',
fecha_nacimiento='1988-03-26'
)
... |
import logging
import threading
# Possible future states (for internal use by the futures package).
PENDING = 'PENDING'
RUNNING = 'RUNNING'
# The future was cancelled by the user...
CANCELLED = 'CANCELLED'
# ...and _Waiter.add_cancelled() was called by a worker.
CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED'
FINISH... |
def analytical_slab_waveguide(settings):
from pypropagate.coordinate_ndarray import CoordinateNDArray
import expresso.pycas as pc
from pypropagate import expression_to_array
import scipy.optimize
import scipy.integrate
from scipy.special import j0,j1,k0,k1
import numpy as np
from numpy i... |
from UnitTest import UnitTest
from ClassTest import PassMeAClass
from ClassTest import ExampleChildClass
from ClassTest import ExampleMultiSuperclassParent1
import Factory2
class Handler:
def __init__(self, x):
self._x = x
def handle(self, y):
return self._x is y
def aProcedure():
x = 1... |
#!/usr/bin/env python3
# Python standard library imports
from enum import Enum
import json
# Imports from external modules
# Internal modules import
class ScoreboardEventListener:
def on_scoreboard_update(self, scoreboard):
raise NotImplementedError
class ScoreboardEntry:
def __init__(self, key, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
import django.db.models.deletion
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
('cursos', '__first__'),
]
operations = [
... |
"""Common utilities for serialize."""
import os
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Callable, ContextManager, Dict, Union
from funcy import reraise
from typing_extensions import Protocol
from dvc.exceptions import DvcException
if TYPE_CHECKING:
from dvc.fs.base import Bas... |
import re
import sublime
import sublime_plugin
class QuickFindEverywhereCommand(sublime_plugin.TextCommand):
def run(self, edit, forward=True, case_sensitive=False):
search_term_region, is_word = self.extract_search_term()
# print("Searching for - region: \'{}\', is_word: {}".format(sear... |
import sys
import subprocess
from termcolor import colored
class VerbosityMixin(object):
"""
Verbosity Mixin that generates beautiful stdout outputs.
Main method:
output()
"""
verbose = False
def output(self, value, normal=False, color=None, error=False,
arrow=False, inde... |
"""
Read .env file, basically taken from docker-compose for simplicity and modified
for our usecase
"""
import os
import contextlib
import codecs
import re
import shutil
def split_env(env):
if '=' in env:
return env.split('=', 1)
else:
return env, None
def env_vars_from_file(filename):
... |
# -*- coding: utf-8 -*-
"""Extremely simple mock workflow stage task."""
import json
import logging
import sys
import time
from _version import __version__
from sip_logging import init_logger
def main():
"""Run the workflow task."""
log = logging.getLogger('sip.mock_workflow_stage')
if len(sys.argv) != ... |
from __future__ import unicode_literals
import os
from setuptools import find_packages, setup
setup(
name='django-registrationwall',
version='0.1.5',
description='A Django mixin application to raise a registration or paywall',
long_description=open(os.path.join(os.path.dirname(os.path.abspath(__file... |
#coding:utf-8
import bs4
from bs4 import BeautifulSoup
html_str = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" i... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
TestTools.py
---------------------
Date : February 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
***************************... |
import json
import logging
from tornado.web import RequestHandler
from tornado.gen import coroutine
from db import RealDb
class RealDataHandler(RequestHandler):
def initialize(self):
self.db = RealDb()
self.db.get_all()
def set_default_headers(self):
self.set_header("Access-Control... |
import datetime
from azure.cli.core.util import CLIError, sdk_no_wait
from azure.cli.core.commands import LongRunningOperation
from azure.cli.core.profiles import ResourceType
from knack.log import get_logger
from ._client_factory import (resource_client_factory)
logger = get_logger(__name__)
def validate_and_deplo... |
"""Helper to check the configuration file."""
from collections import OrderedDict, namedtuple
from typing import List
import attr
import voluptuous as vol
from homeassistant import loader
from homeassistant.core import HomeAssistant
from homeassistant.config import (
CONF_CORE,
CORE_CONFIG_SCHEMA,
CONF_PA... |
import json
from datetime import datetime
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid_beaker import (session_factory_from_settings,
set_cache_regions_from_settings)
from .models import DBSession, Base, User
def isk_fmt(f):
""" Format... |
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python... |
import request
import reply_thread
class PostWithoutImage(Exception):
def __str__(self):
return 'Post does not have images.'
class PostWithoutReplies(Exception):
def __str__(self):
return 'Post does not have replies.'
class Post(object):
def __init__(self, translator, data):
self... |
"""A module for the Builder base class."""
import difflib
import cr
class Builder(cr.Action, cr.Plugin.Type):
"""Base class for implementing builders.
Builder implementations must override the Build and Clean methods at a
minimum to build a target and clean up back to a pristine state respectively.
They ca... |
from django.contrib import admin
#from django.utils.html import format_html_join
#from django.utils.safestring import mark_safe
#from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.admin import UserAdmin
try:
from django.util... |
from .sub_resource import SubResource
class IPConfiguration(SubResource):
"""IPConfiguration.
:param id: Resource Identifier.
:type id: str
:param private_ip_address: The private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private... |
import sys, os
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import gettext
import imp
nebula_dir = os.getenv('NEBULA_DIR')
modules_dir = nebula_dir + '/modules'
set_visuals = imp.load_source('set_visuals', modules_dir + '/set_visuals.py')
gettext.bindtextdomain('games_nebula', nebula... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.