content
stringlengths
4
20k
from __future__ import absolute_import from io import BytesIO from splunklib.six import StringIO from tests import testlib from time import sleep import splunklib.results as results import io class ResultsTestCase(testlib.SDKTestCase): def test_read_from_empty_result_set(self): job = self.service.jobs.c...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os, string, MySQLdb, getopt, os.path sys.path.append('..') sys.path.append('../import') sys.path.append('../lib') from LoadConfig import config from ErrorsHandler import * db = MySQLdb.connect(host=config.DBhost, user=config.DBuser, passwd=config.DBpass, db=c...
# coding: utf-8 """ The wheel binary package format does not support post install hooks so we deploy necessary system files here. """ import sys import os import platform import subprocess import pkg_resources from distutils.version import LooseVersion import acmd DEFAULT_COMPLETION_DIR = '/etc/bash_completion.d...
""" Checks that primitive values are not used in an iterating/mapping context. """ # pylint: disable=missing-docstring,invalid-name,too-few-public-methods,no-init,no-self-use,import-error,unused-argument,bad-mcs-method-argument,wrong-import-position,no-else-return from __future__ import print_function # primitives num...
import os import shutil import stat import sys import tarfile import hashlib from subprocess import Popen, PIPE try: # py2 from urllib2 import urlopen except ImportError: # py3 from urllib.request import urlopen from .msg import fatal, debug, info, warn pjoin = os.path.join # https://github.com/zero...
#!/usr/bin/python # GPL V2, author phe __module_name__ = "dummy_robot" __module_version__ = "1.0" __module_description__ = "dummy robot" import sys import tool_connect import common_html import os import thread import time import job_queue E_ERROR = 1 E_OK = 0 def ret_val(error, text): if error: print ...
import hashlib import re import random import time import debug_toolbar import django.db.backends.mysql.base from debug_toolbar.middleware import DebugToolbarMiddleware from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import validate_ipv4_address from djan...
from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db import connection from django.db.models import Q from build.management.commands.build_human_proteins import Command as BuildHumanProteins from residue.functions import * from structure.functions import Bla...
import csp rgby = ['R', 'G', 'B', 'Y'] d2 = { 'A' : rgby, 'B' : rgby, 'C' : ['R'], 'D' : rgby,} v2 = d2.keys() n2 = {'A' : ['B', 'C', 'D'], 'B' : ['A', 'C', 'D'], 'C' : ['A', 'B'], 'D' : ['A', 'B'],} def constraints(A, a, B, b): if A == B: # e.g. NSW == NSW return True if a ...
"""Make the custom certificate and private key files used by test_ssl and friends.""" import os import shutil import sys import tempfile from subprocess import * req_template = """ [req] distinguished_name = req_distinguished_name x509_extensions = req_x509_extensions prompt ...
#!/usr/bin/env python # Constants AUTHORS = 'Victor Stinner' DESCRIPTION = "Find subfile in any binary stream" CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural Language :: English', 'Operatin...
# -*- coding: utf-8 -*- from typing import Text from zerver.lib.test_classes import WebhookTestCase class TaigaHookTests(WebhookTestCase): STREAM_NAME = 'taiga' TOPIC = "subject" URL_TEMPLATE = u"/api/v1/external/taiga?stream={stream}&api_key={api_key}" FIXTURE_DIR_NAME = 'taiga' def setUp(self): ...
# coding=utf-8 import os import json import sys from flask import Flask, url_for, redirect, render_template, send_from_directory import Utilities import CorpusViewer import TextViewer import RankViewer from Support.flask_util_js.flask_util_js import FlaskUtilJs from config import DevelopmentConfig runSentry = False t...
import time import operator import os import numpy as np import pandas as pd import cytoolz as ct import multiprocessing as mp from functools import partial from numba import jit from collections import defaultdict from collections import deque import operator import difflib import copy from .Encoder import Encoder fr...
""" Network packages ================== """ from __future__ import with_statement import re from fabric.api import hide from fabric.contrib.files import sed, append from fabtools.utils import run_as_root def host(ipaddress, hostnames, use_sudo=False): """ Add a ipadress and hostname(s) in /etc/hosts file ...
from __future__ import print_function from _slackrequest import SlackRequest from _channel import Channel from _util import SearchList from websocket import create_connection import json from ssl import SSLError class Server(object): def __init__(self, token, connect=True): self.token = token self....
""" I/O classes provide a uniform API for low-level input and output. Subclasses will exist for a variety of input/output mechanisms. """ __docformat__ = 'reStructuredText' import sys try: import locale except: pass import re from docutils import TransformSpec from docutils._compat import b class Input(Tra...
import logging import os import angus.service import angus.storage PORT = os.environ.get('PORT', 8080) LOGGER = logging.getLogger('dummy') def compute(resource, data): if 'echo' in data: resource['echo'] = data['echo'] else: resource['echo'] = "echo" def main(): logging.basicConfig(le...
"""Hook for Telegram""" from typing import Optional import telegram import tenacity from airflow.exceptions import AirflowException from airflow.hooks.base import BaseHook class TelegramHook(BaseHook): """ This hook allows you to post messages to Telegram using the telegram python-telegram-bot library. ...
#!/usr/bin/python # Calculate hours for the week, format it nicely # Lauren Caliolio 7/26/2014 """This will: Enter the info from the tickets Calculates the total hours worked Puts it into the format he wants """ """Tech notes: Create class containing variables and functions needed from user input ...
import mock from pytest import raises from paasta_tools.cli.cmds import performance_check @mock.patch('paasta_tools.cli.cmds.performance_check.validate_service_name', autospec=True) @mock.patch('requests.post', autospec=True) @mock.patch('paasta_tools.cli.cmds.performance_check.load_performance_check_config', autosp...
# CUDA_VISIBLE_DEVICES='0' python gan.py import argparse import struct import time import numpy as np print 'numpy ' + np.__version__ np.set_printoptions(threshold='nan') np.set_printoptions(linewidth=250) np.set_printoptions(formatter={'float': '{:12.8f}'.format, 'int': '{:4d}'.format}) import tensorflow as tf print '...
import json import os import tempfile from unittest import TestCase from common import load_data, BaseTest from c7n.filters.iamaccess import check_cross_account, CrossAccountAccessFilter from c7n.mu import LambdaManager, LambdaFunction, PythonPackageArchive from c7n.resources.sns import SNS from c7n.resources.iam imp...
from math import ceil from django.core.paginator import Paginator, Page, EmptyPage, PageNotAnInteger class CustomPage(Page): def start_index(self): # Special case, return zero if no items. if self.paginator.count == 0: return 0 elif self.number == 1: return 1 ...
class PluginSettings: PROVIDERS_ENABLED = 'oauth.providers_enabled' GOOGLE_CLIENT_ID = 'oauth.google_client_id' GOOGLE_CLIENT_SECRET = 'oauth.google_client_secret' GITHUB_CLIENT_ID = 'oauth.github_client_id' GITHUB_CLIENT_SECRET = 'oauth.github_client_secret' LINKEDIN_CLIENT_ID = 'oauth.linke...
'''OpenGL extension NV.texture_shader This module customises the behaviour of the OpenGL.raw.GL.NV.texture_shader to provide a more Python-friendly API Overview (from the spec) Standard OpenGL and the ARB_multitexture extension define a straightforward direct mechanism for mapping sets of texture coordinates t...
__AUTHOR__= 'FARIZA DIAN PRASETYO' # Package QGIS from qgis.core import * import qgis.utils from PyQt4.QtCore import * from header_config_variable import * import os import sys import pandas as pd import numpy as np class HazardLayer: def __init__(self,base_input_layer_name,hazard_class_file,layer_output_name,f...
from heat.common import exception from heat.common.i18n import _ from heat.engine import attributes from heat.engine import constraints from heat.engine import properties from heat.engine import resource from heat.engine import support class Node(resource.Resource): """A resource that creates a Senlin Node. ...
from gi.repository import Gtk from quodlibet import _ from quodlibet import util from quodlibet.qltk import Icons from quodlibet.plugins.editing import EditTagsPlugin from quodlibet.plugins import PluginConfigMixin from quodlibet.util.string.titlecase import _humanise class TitleCase(EditTagsPlugin, PluginConfigMixi...
import logging import os import psycopg2 import stat from celery.utils.functional import uniq from django.conf import settings import tempfile from django.conf import settings from footprint.client.configuration import InitFixture, resolve_fixture from footprint.main.database.command_execution import CommandExecutio...
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST,...
#!/usr/bin/env python # encoding: utf-8 import datetime import cotyledon import threading from racoon.storage import connection from oslo_config import cfg from oslo_log import log from oslo_utils import timeutils CONF = cfg.CONF LOG = log.getLogger(__name__) class JanitorService(cotyledon.Service): def __i...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Moodle Development Kit Copyright (c) 2013 Frédéric Massart - FMCorz.net 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...
#!/usr/bin/env python # Receive message type geometry_msgs.msg Point # Publish goal to MoveBase action import rospy from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal import actionlib from actionlib_msgs.msg import * from geometry_msgs.msg import Pose, Point, Quaternion #from people_msgs import People class ...
"""Module for testing the map_dns_domain command.""" import unittest if __name__ == '__main__': import utils utils.import_depends() from brokertest import TestBrokerCommand class TestMapDnsDomain(TestBrokerCommand): def test_100_map_ut(self): cmd = "map dns domain --room utroom1 --dns_domain a...
import logging from django.db import models from model_utils import Choices from model_utils.models import TimeStampedModel, StatusModel import facebook from instagram.client import InstagramAPI from .conf import settings logger = logging.getLogger(__name__) STATUS_CHOICES = Choices( ('active', 'Active',), ...
from sympy import (Abs, Add, atan, ceiling, cos, E, Eq, exp, factorial, fibonacci, floor, Function, GoldenRatio, I, Integral, integrate, log, Mul, N, oo, pi, Pow, product, Product, Rational, S, Sum, sin, sqrt, sstr, sympify, Symbol, Max, nfloat) from sympy.core.evalf import (complex_accuracy, PrecisionExhau...
#!/usr/bin/env python # -*- codeing: utf-8 -*- ''' send udp request one by one, then get the response about device info, the result is saved in result.xml, you can drag it into excel for format. ''' import csv from xmlutils.xml2csv import xml2csv import logging import socket import time from xml.dom.minidom import pa...
from __future__ import print_function import argparse import sys import textwrap is_python3 = bool(sys.version_info.major == 3) ALL_PRAGMAS = ['no cover', 'no win32', 'python2', 'python3', 'untested', 'win32'] DEFAULT_PRAGMAS = ALL_PRAGMAS[:] if is_python3: DEFAULT_PRAGMAS.remove('python3') else...
#libreria import pygame from Algebralineal import * BLANCO=(255,255,255) NEGRO=(0,0,0) ROJO=(255,0,0) AZUL=(0,0,255) VERDE=(0,255,0) def triangulo(p, lsp): pygame.draw.line(p,ROJO,lsp[0],lsp[1]) pygame.draw.line(p,ROJO,lsp[1],lsp[2]) pygame.draw.line(p,ROJO,lsp[2],lsp[0]) class Plano: cx = 100 ...
#!/usr/bin/python # -*- coding: utf-8 -*- #script to be executed in folder where EMS ZIP files are stored #created starting from https://github.com/emergenzeHack/terremotocentro_geodata/blob/gh-pages/CopernicusEMS/scripts/copernicus_EMSR.py import os import zipfile import shutil import glob import shapefile ########...
""" API for Web Map Service (WMS) methods and metadata. Currently supports only version 1.1.1 of the WMS protocol. """ from __future__ import (absolute_import, division, print_function) from .map import wms111, wms130 from .util import clean_ows_url def WebMapService(url, version='1.1.1', ...
from PyQt4 import QtGui import util import client import os # These mods are always on top mods = {} mod_crucial = ["faf"] # These mods are not shown in the game list mod_invisible = [] mod_favourites = [] # LATER: Make these saveable and load them from settings class ModItem(QtGui.QListWidgetItem): def __in...
"""Rosie web service data access object. Classes: DAO - data access object. """ import sqlalchemy as al LATEST_TABLE_NAME = "latest" MAIN_TABLE_NAME = "main" META_TABLE_NAME = "meta" OPTIONAL_TABLE_NAME = "optional" def _col_by_key(table, key): """Return the column in "table" matched by "key".""" for...
import pyxb import pyxb.binding import pyxb.binding.saxer import io import pyxb.utils.utility import pyxb.utils.domutils import sys # Unique identifier for bindings created at the same time _GenerationUID = pyxb.utils.utility.UniqueIdentifier('urn:uuid:0613818f-6f61-11e4-85c1-542696dd94ef') # Version of Py...
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ import warnings from django.http import ( Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect, ) from dj...
# -*- coding: utf-8 -*- # Agile Core documentation build configuration file import sys import os import sphinx_rtd_theme from sphinx.highlighting import lexers from pygments.lexers.web import PhpLexer lexers['php'] = PhpLexer(startinline=True, linenos=1) lexers['php-annotations'] = PhpLexer(startinline=True, linenos=...
from __future__ import print_function, division # requires Python >= 2.6 # numpy and scipy imports import numpy as np from scipy.sparse import kron, identity, lil_matrix from scipy.sparse.linalg import eigsh # Lanczos routine from ARPACK # We will use python's "namedtuple" to represent the Block and EnlargedBlock #...
""" KeepNote RichText base classes for tags """ # # KeepNote # Copyright (c) 2008-2009 Matt Rasmussen # # 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; version 2 of the License. #...
""" api_base.py: Base class for all API classes """ try: from urllib.parse import quote # Python3 except ImportError: from urllib import quote # Python2 class ApiBase(object): """ Base class for all API objects """ def __init__(self, client): self._client = client def _build_option_string...
# Module: utils """Utilities Various utility classes and functions. """ import os import re import sys import string from time import time from os.path import isfile from itertools import chain from random import seed, choice, sample class Error(Exception): "Error Exception" class State(object): """Cre...
"""Tests for the Pfam library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl.testing import absltest from absl.testing import parameterized import train_hmmer_model_for_paper FLAGS = flags.FLAGS class TestTrainHmmerMo...
from ROOT import gROOT,gSystem gSystem.Load( 'libNucDB' ) from ROOT import NucDBManager,NucDBExperiment,NucDBMeasurement,NucDBDiscreteVariable,NucDBInvariantMassDV,NucDBPhotonEnergyDV from NucDBExtractors import * import os class CLASExtractor(NucDBRawDataExtractor): def __init__(self): NucDBRawDataExtract...
from solfetch import fetch from solplot import normalize, plot, unwrap, unwrap_windowed from solflag import flag
import six from girder.api import rest from girder.models.model_base import AccessException from girder.utility import optionalArgumentDecorator from girder.utility.model_importer import ModelImporter @optionalArgumentDecorator def admin(fun, scope=None): """ REST endpoints that require administrator access ...
from __future__ import print_function from numpy import int16 def connect(route,**args): return BRIDGE(route,**args) class BRIDGE(): POWER_ON =0x01 RESET =0x07 RES_1000mLx =0x10 RES_500mLx =0x11 RES_4000mLx =0x13 gain_choices=[RES_500mLx,RES_1000mLx,RES_4000mLx] gain_literal_choices=['500mLx','1000mLx',...
"""A custom list that manages index/position information for contained elements. :author: Jason Kirtland ``orderinglist`` is a helper for mutable ordered relationships. It will intercept list operations performed on a :func:`_orm.relationship`-managed collection and automatically synchronize changes in list position...
def search(re, chars): """Given a regular expression and an iterator of chars, return True if re matches some prefix of ''.join(chars); but only consume chars up to the end of the match.""" states = set([re]) for ch in chars: states = set(sum((after(ch, state) for state in states), [])) ...
import os import vizQuery as vq import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys import json from sklearn import preprocessing, datasets, linear_model from sklearn.cross_validation import train_test_split import itertools as it from scipy.stats import linregress import warnings #Read Q...
import os import robot from keywordgroup import KeywordGroup class _ScreenshotKeywords(KeywordGroup): def __init__(self): self._screenshot_index = 0 # Public def capture_page_screenshot(self, filename=None): """Takes a screenshot of the current page and embeds it into the log...
from freezegun import freeze_time import six from mock import call, patch from bulbs.utils.test import BaseIndexableTestCase, make_content from bulbs.liveblog.models import LiveBlogEntry from example.testcontent.models import TestLiveBlog class TestLiveBlogModel(BaseIndexableTestCase): def test_pinned_content(...
import logging import secrets from typing import Any, Dict, List, Optional, Tuple from django.conf import settings from django.http import HttpRequest, HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render from django.urls import reverse from django.utils.cache import patch_cache_control fr...
#!/usr/bin/env python from __future__ import print_function, unicode_literals import datetime import os import sys from subprocess import check_call import requests from apscheduler.schedulers.blocking import BlockingScheduler from decouple import config from pathlib2 import Path schedule = BlockingScheduler() DEA...
from cloudinit import cloud from cloudinit import helpers from cloudinit import util from cloudinit.config import cc_ca_certs from ..helpers import TestCase import logging import shutil import tempfile import unittest try: from unittest import mock except ImportError: import mock try: from contextlib imp...
from __future__ import division, print_function import os from argparse import Namespace import pytest import myhdl from myhdl import (Signal, ResetSignal, intbv, always, always_comb, instance, delay, StopSimulation,) from myhdl.conversion import verify from rhea.system import Signals, Global, Cl...
# -*- coding: utf-8 -*- import re from module.plugins.internal.Account import Account class DatoidCz(Account): __name__ = "DatoidCz" __type__ = "account" __version__ = "0.38" __status__ = "testing" __description__ = """Datoid.cz account plugin""" __license__ = "GPLv3" __authors__ = [("G...
#!/bin/env python # # AutoPyfactory batch plugin for Condor # import commands import logging import os import re import string import subprocess import time from autopyfactory.interfaces import BatchSubmitInterface import autopyfactory.utils as utils from autopyfactory import jsd from autopyfactory.persistence impo...
''' Reverse a singly linked list. ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ ...
import os import unittest import tempfile from Dell import recovery_xml ilegal_utf8string = bytes(bytearray(range(129, 255))) class NewStr(object): def __init__(self, _str): self._str = _str def __repr__(self): return self._str def __iter__(self): return iter(self._str.encode())...
# $Id: ShowFeats.py 537 2007-08-20 14:54:35Z landrgr1 $ # # Created by Greg Landrum Aug 2006 # # from __future__ import print_function _version = "0.3.2" _usage=""" ShowFeats [optional args] <filenames> if "-" is provided as a filename, data will be read from stdin (the console) """ _welcomeMessage="This is S...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Update encrypted deploy password in Travis config file """ from __future__ import print_function import base64 import json import os from getpass import getpass import yaml from cryptography.hazmat.primitives.serialization import load_pem_public_key from cryptography.h...
import types from spacewalk.server import rhnSQL, rhnUser class InvalidUserError(Exception): pass class InvalidOrgError(Exception): pass class InvalidServerGroupError(Exception): pass class ServerGroup: def __init__(self): self._row_server_group = None _query_lookup = rhnSQL.Statement(...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule, bytes_to_human from ansible.module_util...
import config from datetime import datetime import os import math import pickle from urbansearch.utils.p_utils import PickleUtils CATEGORIES = config.get('score', 'categories') CATEGORIES_NO_OTHER = config.get('score', 'categories_no_other') DATA_SETS_DIRECTORY = config.get('resources', 'data_sets') MODELS_DIRECTORY ...
import espressomd from espressomd import lb, shapes, lbboundaries import numpy as np try: from espressomd.virtual_sites import VirtualSitesInertialessTracers, VirtualSitesOff except ImportError: pass from espressomd.utils import handle_errors class VirtualSitesTracersCommon: box_height = 10. box_lw = ...
from weboob.capabilities.travel import ICapTravel, Station, Departure, RoadStep from weboob.tools.backend import BaseBackend from .browser import Transilien from .stations import STATIONS class TransilienBackend(BaseBackend, ICapTravel): NAME = 'transilien' MAINTAINER = u'Julien Hébert' EMAIL = '<EMAIL>'...
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import HttpResponseForbidden from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.views.decora...
""" Django settings for django_test project. Generated by 'django-admin startproject' using Django 1.8.3. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build ...
"""Support for monitoring a Neurio energy sensor.""" from datetime import timedelta import logging import neurio import requests.exceptions import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_API_KEY, ENERGY_KILO_WATT_HOUR, POWER_WATT...
from __future__ import absolute_import, unicode_literals import pytest from case import Mock, sentinel, skip from celery.app import backends from celery.backends import elasticsearch as module from celery.backends.elasticsearch import ElasticsearchBackend from celery.exceptions import ImproperlyConfigured @skip.unl...
""" Classes and interfaces for labeling tokens with category labels (or X{class labels}). Typically, labels are represented with strings (such as C{'health'} or C{'sports'}). Classifiers can be used to perform a wide range of classification tasks. For example, classifiers can be used... - to classify documents by...
# -*- coding: utf-8 -*- # Download Status Module by: Blazetamer (2014) import os import xbmc import xbmcaddon from libs import addonwindow as pyxbmct import kodi from libs import message addon_id=kodi.addon_id _addon = xbmcaddon.Addon() _addon_path = _addon.getAddonInfo('path') file_name = "http://trakt.tv/pin/7558" ...
# This file demonstrates the use of fast fruchterman reingold layout from # fastlayout extension in graph tool import graph_tool.all as gt import numpy as np import fastlayout as fl import time # create a network to have some graph data g = gt.collection.data["celegansneural"] # set various constants dimension = 2 ...
# -*- coding: utf-8 -*- from datetime import datetime from dateutil.relativedelta import relativedelta from openerp import api, fields, models, tools _INTERVALS = { 'hours': lambda interval: relativedelta(hours=interval), 'days': lambda interval: relativedelta(days=interval), 'weeks': lambda interval: r...
import click from parsec.cli import pass_context, json_loads from parsec.decorators import custom_exception, dict_output @click.command('update_repository') @click.argument("id", type=str) @click.argument("tar_ball_path", type=str) @click.option( "--commit_message", help="Commit message used for the underlyin...
import traceback from lib.FileManager.workers.baseWorkerCustomer import BaseWorkerCustomer class CreateArchive(BaseWorkerCustomer): def __init__(self, params, session, *args, **kwargs): super(CreateArchive, self).__init__(*args, **kwargs) self.path = params.get('path') self.session = ses...
#!/usr/bin/env python from __future__ import print_function # -*- coding: latin1 -*- __author__ = 'Herbert OLiveira Rocha' #Python import sys import os import commands class CodeBeautify(object): def __init__(self): self.path_tool = os.path.abspath('modules/uncrustify/uncrustify') self.option_t...
import urllib import hashlib from django import template from django.conf import settings from django.utils.safestring import mark_safe from django.utils.encoding import force_bytes, force_text from readthedocs.projects.models import Project from readthedocs.core.resolver import resolve register = template.Library()...
from datetime import timedelta, datetime # noqa: F401 from typing import List, Optional # noqa: F401 from lib.api import oauth, twitch from lib.data import ChatCommandArgs from lib.helper.chat import cooldown, permission_not_feature @cooldown(timedelta(seconds=60), 'uptime') async def commandUptime(args: ChatComm...
class Graph: def __init__(self): self.edges = {} # Map a node with coresponding edges def neighbors(self, id): return self.edges[id] ############################################### #### Helperfunction used by a_star_search import heapq class PriorityQueue: def __init__(self): self.elements = [] ...
"""Perform IO on BWF files. Convenience functions for reading from and writing to BWF files using bwfmetaedit subprocess calls. Attributes: bwfmetaedit (list): List of strings to be passed to subprocess.run(). This list should be appended to (after copy()-ing) in order to perform the needed function. Its ...
#!/usr/bin/python import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument('inset', choices=['test', 'val', 'train', 'all']) parser.add_argument('recog', choices=['clean', 'reverb', 'noisy', 'retrain', 'all']) phase_group = parser.add_mutually_exclusive_group(required = False) pha...
""" yubistack.exceptions ~~~~~~~~~~~~~~~~~~~~ List all custom exceptions here """ STATUS_CODES = { # YKAuth 'BAD_PASSWORD': 'Invalid password', 'DISABLED_TOKEN': 'Token is disabled', 'UNKNOWN_USER': 'Unknown user', 'INVALID_TOKEN': 'Token is not associated with user', # YKVal 'BACKEND_ERR...
############################################################################## # # Version 10 # Added removeTrivial function - removes any row with only zero as entries. # # TODO: # Determine which elements are torsion # Determine distinct generators for cocycles # DONE: # Determine distinct generators for co...
from ipalib.plugins.baseldap import * from ipalib.plugins.dns import dns_container_exists from ipalib import api, Str, StrEnum, Password, DefaultFrom, _, ngettext, Object from ipalib.parameters import Enum from ipalib import Command from ipalib import errors from ipapython import ipautil from ipalib import util try: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Example code on using the alt_slice_overlay function in the plotting.py file. Takes two h5 files--a RISR file and an OMTI file-- and creates 2 objects. This is inputed into alt_slice_overlay. The output is a 2D colorplot with the OMTI data on the bottom in grayscale an...
"""Tests for qutebrowser.commands.runners.""" import pytest from qutebrowser.misc import objects from qutebrowser.commands import runners, cmdexc class TestCommandParser: def test_parse_all(self, cmdline_test): """Test parsing of commands. See https://github.com/qutebrowser/qutebrowser/issues/...
# coding: utf-8 from __future__ import unicode_literals from datetime import datetime from calendar import timegm import io import logging import os from jinja2.exceptions import TemplateNotFound import jinja2 import json from mkdocs import nav, search, utils from mkdocs.utils import filters from mkdocs.relative_pat...
""" Django settings for homeboard project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) ...
"""Tentative prolongator""" __docformat__ = "restructuredtext en" import numpy as np from scipy.sparse import isspmatrix_csr, bsr_matrix from pyamg import amg_core __all__ = ['fit_candidates'] def fit_candidates(AggOp, B, tol=1e-10): """Fit near-nullspace candidates to form the tentative prolongator Param...