code stringlengths 1 199k |
|---|
"""Get a `re.Pattern` instance (as given by re.compile()) with control over defaults of it's methods.
Useful to reduce if/else boilerplate when handling the output of search functions (match, search, etc.)
See [regex_search_hack.md](https://gist.github.com/thorwhalen/6c913e9be35873cea6efaf6b962fde07) for more explanato... |
import requests
def client_getProductTypes():
url="http://172.31.3.73:8888/client/v1/clientAuth.action"
headers={"Connection": "keep-alive",
# "Referer": "http://172.31.3.73:6020/layout_new/login.jsp?url=http://172.31.3.73:6020/layout_new/login.html",
#"Accept-Language": "zh-CN",
#"x-req... |
from resumable import split, rebuild
import requests
def get(s):
return s
@rebuild
def example(_):
print('this is a good start')
value = split(requests.get, 'first')('http://ms.mause.me')
print(value.text)
value = split(lambda: 'hello', 'second')()
print('hello', value)
split(print, 'derp')(... |
from itertools import product
import requests
import shutil
def api_list(apiargs):
"""Google Street View Image API results.
Constructs a list of `Google Street View Image API queries <https://developers.google.com/maps/documentation/streetview/>`_
from a dictionary.
Args:
apiargs (listof dict):
Dict c... |
from polyphony import testbench
from polyphony import pipelined
def pipe10(xs):
for i in pipelined(range(len(xs) - 1), ii=-1):
v = xs[i] + xs[i + 1]
v >>= 1
xs[i] = v
@testbench
def test():
data = [0, 16, 32, -16, -64]
pipe10(data)
assert 8 == data[0]
assert 24 == data[1]
... |
__author__ = 'hmizumoto'
from flask import Blueprint, request, render_template, abort
from app.utils import jwt_decode
from app.views.auth import check_login, authorized_user, login
from app.models import DOMAIN
from app import app
from app.decoretor import login_required
from bson import ObjectId
import re
from loggin... |
import re
import time
from astropy import units as u
from astropy.coordinates import SkyCoord
from panoptes.utils.time import current_time
from panoptes.utils import error as error
from panoptes.pocs.mount.serial import AbstractSerialMount
class Mount(AbstractSerialMount):
"""
Mount class for iOptron mounts... |
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
pascal = []
if numRows >= 1:
pascal.append([1])
for i in range(1, numRows):
pascal.append([pascal[-1][0]])
for j in range(1, len(... |
from django import template
from django.contrib.contenttypes.models import ContentType
from django.template.loader import render_to_string
from ..models import TaggedItem, Tag
register = template.Library()
@register.assignment_tag
def get_tagged_items_for(object):
'''retrieve tagged items which relative with the sp... |
"""WSGI application."""
import os
from sys import argv
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from tweetTrack.app import app
application = DispatcherMiddleware(app)
if __name__ == '__main__':
if len(argv) < 2 or argv[1] == 'Dev':
os.environ['FLASK_CONFIG'] = '... |
import unittest
import ast
import sys
import logging
from datetime import datetime
import ast
sys.path.insert(0, '../src')
from ast_extensions import TypeDecASTModule
from check import (check_expr, check_mod, expr_template, call_function)
from parse_file import parse_type_decs
from ptype import PType
from errors import... |
'''Brainfuck interpreter'''
VERSION = '0.1.2.1103'
def __static_vars():
'''Decorate, add static attr'''
def decorate(func):
'''The decorate'''
setattr(func, 'stdin_buffer', [])
return func
return decorate
@__static_vars()
def __getchar() -> int:
'''Return one char from stdin'''
... |
"""Useful utilities for handling CWL inputs and outputs.
This is shared functionality abstracted across multiple approaches, currently
mostly handling CWL records. This needs some generalization to apply across
non-variant calling workflows.
"""
import collections
import pprint
import toolz as tz
def _get_all_cwlkeys(i... |
from setuptools import setup, find_packages
import re, os
PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(PACKAGE_PATH, 'pythonvideoannotator','__init__.py'), 'r') as fd:
content = fd.read()
version = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', content, re.MUL... |
"""Suite WorldWideWeb suite, as defined in Spyglass spec.:
Level 1, version 1
Generated from /Volumes/Sap/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 Folder/Netscape Communicator\xe2\x84\xa2
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'WWW!'
class WorldWide... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('questionnaires', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='AttentionRelatedCognitiveErrors',
new_name='Attentio... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('chef_buddy', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='ingredientflavorcompound',
name='score',
... |
from office365.runtime.client_object_collection import ClientObjectCollection
from office365.sharepoint.content_type import ContentType
class ContentTypeCollection(ClientObjectCollection):
"""Content Type resource collection"""
def __init__(self, context, resource_path=None):
super(ContentTypeCollection... |
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://rcarneva.github.io'
RELATIVE_URLS = False
FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'
DELETE_OUTPUT_DIRECTORY = True |
import numpy as np
from scipy.stats import skew, kurtosis, shapiro, pearsonr, ansari, mood, levene, fligner, bartlett, mannwhitneyu
from scipy.spatial.distance import braycurtis, canberra, chebyshev, cityblock, correlation, cosine, euclidean, hamming, jaccard, kulsinski, matching, russellrao, sqeuclidean
from sklearn.p... |
import os
import logging
from urllib.parse import urlencode, unquote
from flask import request, current_app
from flask_api import FlaskAPI
from flask_api.exceptions import APIException, NotFound
from . import services
from . import stores
from . import routes
log = logging.getLogger('api')
class TemplateNotFound(NotFou... |
import scipy.sparse as ss
import warnings
warnings.simplefilter('ignore', ss.SparseEfficiencyWarning)
from sparray import FlatSparray
class Operations(object):
params = [['FlatSparray', 'csr_matrix']]
param_names = ['arr_type']
def setup(self, arr_type):
mat = ss.rand(3000, 4000, density=0.1, format='csr')
... |
""" Methods for estimating structural breaks in time series regressions
TODO: extract and move Chow test from "commission test" over to here
"""
from __future__ import division
from collections import namedtuple
import logging
import numpy as np
import pandas as pd
from scipy.optimize import brentq
from scipy import st... |
from __future__ import unicode_literals, print_function
import os
import sys
import subprocess
import json
from ape import feaquencer
from ape import tasks
from .exceptions import ContainerError, ContainerNotFound, ProductNotFound
class Config(object):
APE_ROOT = os.environ['APE_ROOT_DIR']
SOURCE_HEADER = '#ple... |
'''
RSD: The reciprocal smallest distance algorithm.
Wall, D.P., Fraser, H.B. and Hirsh, A.E. (2003) Detecting putative orthologs, Bioinformatics, 19, 1710-1711.
Original author: Dennis P. Wall, Department of Biological Sciences, Stanford University.
Contributors: I-Hsien Wu, Computational Biology Initiative, Harvard... |
import os
import roomai.common
import copy
class DouDiZhuActionElement:
str_to_rank = {'3':0, '4':1, '5':2, '6':3, '7':4, '8':5, '9':6, 'T':7, 'J':8, 'Q':9, 'K':10, 'A':11, '2':12, 'r':13, 'R':14, 'x':15, 'b':16}
# x means check, b means bid
rank_to_str = {0: '3', 1: '4', 2: '5', 3: '6', 4: '7', 5: '8', 6... |
from collections import ChainMap
from django.conf import settings
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect, resolve_url
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.tokens import default_token_gene... |
from openpyxl import load_workbook
from libs.xlsxInterface import getLevelTypes, travesalLevels
import models
from prettyprint import pp
from functools import partial
from django.db import transaction
def generateLevels(levelDict, levelTypes, cellAndValues):
currentDict = levelDict
parentLevel = None
for in... |
import time
import random
import socket
from flask import Flask, render_template, redirect, url_for, request, jsonify
import config
log = None
class Agent():
def __init__(self, ip, cw=True, node=None, state='initial'):
self.ip = ip
self.cw = cw
self.state = state
self.node = node
... |
import json
import logging
from math import ceil
import os
import click
import cligj
from .helpers import resolve_inout
from . import options
import rasterio
from rasterio.errors import CRSError
from rasterio.transform import Affine
from rasterio.coords import disjoint_bounds
logger = logging.getLogger('rio')
files_ino... |
import subprocess
network_name = raw_input("What is the name of your network? ")
subprocess.check_call(['nmcli', 'c', 'up', 'id', network_name]) |
import sys
import utils
from scipy import stats
import numpy as np
from math import sqrt
def spearman(x,y):
return stats.spearmanr(x, y)[0]
def readMEN(annotation_file):
pairs=[]
humans=[]
f=open(annotation_file,'r')
for l in f:
l=l.rstrip('\n')
items=l.split()
pairs.append((items[0],items[1]))
... |
import unittest
from katas.beta.plus_1_array import up_array
class UpArrayTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(up_array([2, 3, 9]), [2, 4, 0])
def test_equals_2(self):
self.assertEqual(up_array([4, 3, 2, 5]), [4, 3, 2, 6])
def test_none(self):
self.ass... |
from __future__ import absolute_import
from base64 import b64encode, b64decode
from zope.interface import implementer
import twisted.internet.protocol
from twisted.internet.defer import maybeDeferred
from twisted.internet.interfaces import ITransport
from twisted.internet.error import ConnectionDone, ConnectionAborted,... |
from flake8_quotes import QuoteChecker
import os
import subprocess
from unittest import TestCase
class TestChecks(TestCase):
def test_get_noqa_lines(self):
checker = QuoteChecker(None, filename=get_absolute_path('data/no_qa.py'))
self.assertEqual(checker.get_noqa_lines(checker.get_file_contents()), ... |
import xml.etree.ElementTree as ET
from pprint import pprint
filename = 'GeoLogger.gpx'
def main():
tree = ET.parse(filename)
root = tree.getroot()
pprint(root.tag)
pprint(root.attrib)
pprint(root.findtext('.'))
if __name__ == "__main__":
main() |
"""Converts image data to TFRecords file format with Example protos.
The image data set is expected to reside in JPEG files located in the
following directory structure.
data_dir/run/video1/00001.jpeg
data_dir/run/video1/00002.jpeg
data_dir/run/video1/00003.jpeg
...
data_dir/run/video2/00001.jpeg
data_dir/r... |
from CIM15.IEC61970.Core.PowerSystemResource import PowerSystemResource
class RegulatingControl(PowerSystemResource):
"""Specifies a set of equipment that works together to control a power system quantity such as voltage or flow.Specifies a set of equipment that works together to control a power system quantity suc... |
"""
Authors: Jeremy Haugen, UCLA, Anthony Nguyen, UCLA
Created: June 2015
Copyright notice in LICENSE file
This file is used to take the raw files generated by
the SAM, which are in CSV format and processes it into
json format. Then it will contact the sMAP server and
upload the json data into sMAP
"""
import uuid_gen
... |
from subprocess import PIPE, Popen
from sqlalchemy import create_engine
def run(p):
try:
p["log"].info(p["action"]['query'])
proc = Popen(p["action"]['query'], shell=True,
stdin=PIPE, stdout=PIPE, stderr=PIPE)
result = proc.communicate()
message = ''
for ... |
from starcluster.clustersetup import ClusterSetup
from starcluster.logger import log
class PysamInstaller(ClusterSetup):
def run(self, nodes, master, user, user_shell, volumes):
for node in nodes:
log.info("Installing PySam 0.8.4 on %s" % (node.alias))
node.ssh.execute('mkdir -p /opt/software/pysam')
... |
"""
Author: Eric J. Ma
Affiliation: Massachusetts Institute of Technology
"""
from random import choice
from generate_id import generate_id
class Sequence(object):
"""
The Sequence object is the lowest level object in the pathogen simulator.
It provides a container for storing seed sequences for the pathogens presen... |
'''
This module defines scripts for selecting stuff.
See their documentation for more information.
'''
from __future__ import with_statement
import bisect
import re
import _ast
import os.path, sys
sys.path += [
os.path.dirname(__file__),
os.path.join(os.path.dirname(__file__), 'third_party.zip'),
]
import winga... |
from .routes_test_fixture import app # noqa
def test_stats_wiki_campaign(client):
# test active campaign
assert client.get("/stats/enwiki/1")._status_code == 200
# test archived campaign
assert client.get("/stats/enwiki/7")._status_code == 200
def test_stats(client):
assert client.get("/stats/")._s... |
from pyramid.security import (
_get_authentication_policy
)
def my_get_authentication_policy(request):
# CRITICAL
# _get_authentication_policy(request)
# this method will return the instanciate singleton object that handle
# policy in pyramid app
# the policy object store keys from conf for gene... |
import requests
import time
import json
"""
ansible 运行结果回调
"""
class CallbackModule(object):
def v2_runner_item_on_ok(self, *args, **kwargs):
# time.sleep(10)
# print args
for i in dir(args[0]):
if not i.startswith('__'):
print i
print '======'
# p... |
import json
import os
from errata_tool import ErrataConnector, Erratum
from errata_tool.products import ProductList
import requests
import pytest
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
FIXTURES_DIR = os.path.join(TESTS_DIR, 'fixtures')
class MockResponse(object):
status_code = 200
encoding = 'ut... |
"""Test events classes.
This file is part of PyVISA.
:copyright: 2019-2020 by PyVISA Authors, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
import logging
import pytest
from pyvisa import constants, errors
from pyvisa.events import Event
from . import BaseTestCase
class TestEvent(BaseTe... |
"""Findall regex operations in python.
findall(string[, pos[, endpos]])
Returns a list:
not like search and match which returns objects
Otherwise, it returns an empty list.
"""
import re
pattern = re.compile(r"\w+")
result = pattern.findall("hey bro")
print result
patt = re.compile(r"a*b")
res = patt.findall("abababb")... |
from OpenGLCffi.GL import params
@params(api='gl', prms=['index', 'type', 'normalized', 'value'])
def glVertexAttribP1ui(index, type, normalized, value):
pass
@params(api='gl', prms=['index', 'type', 'normalized', 'value'])
def glVertexAttribP1uiv(index, type, normalized, value):
pass
@params(api='gl', prms=['index',... |
public_key = b"\x30\x81\x9f\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x81\x8d\x00\x30\x81\x89\x02\x81\x81\x00\xaf\x15\xe8" + \
b"\x75\x00\x06\xe4\xc5\xd5\xda\x2c\xc5\x63\x6a\xef\xa3\x06\x81\x99\x19\x8f\x2a\xb5\xd3\x2e\x50\x76\x94\xe1\xc1\x5a\xa2\x84\xd7\xad" + \
b"\x91\x2... |
from sys import argv
script, first, second, third, fourth = argv
print "Your script is called ", script, ", which was the zeroth variable."
print "Your first variable was ", first
print "Your second variable was ", second
print "Your third variable was ", third
print "Your first variable was ", first |
from __future__ import print_function
from helpers import flatten, merge, add, search
import sys
import os
import yaml
import boto3
import termcolor
def str_presenter(dumper, data):
if len(data.splitlines()) == 1 and data[-1] == '\n':
return dumper.represent_scalar(
'tag:yaml.org,2002:str', data... |
import random
from ..simulator import Simulator
class RandomMover(Simulator):
ACTIONS = ('up', 'down', 'left', 'right')
def start(self):
self.init_game()
while True:
self._check_pygame_events()
for drone in self.drones:
drone.do_move(random.choice(self.ACT... |
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
"""
Tests for RecordView module and view
Note: this module tests for rendering specifically for RecordView values, using
view description sitedata files, and as such duplicates some tests covered by
module test_enti... |
'''
Created on 17-Feb-2015
@author: Asawari.Vaidya
'''
from PythonNetBanxSDK.common.DomainObject import DomainObject
class Pagination(DomainObject):
'''
classdocs
'''
def __init__(self,obj):
'''
Constructor
'''
# Handler dictionary
handler = dict()
handler... |
from pikka_bird_collector.parsers.table import Table as Parser
from .base_port_command import BasePortCommand, Base
class Mysql(BasePortCommand):
"""
Collector for MySQL (https://www.mysql.com/).
The collector is enabled whenever non-empty settings are passed.
Multiple instances running on t... |
from django.db.models import signals
from django.utils.functional import curry
from django.contrib.contenttypes.models import ContentType
from django.core import serializers
from django.contrib.admin.models import LogEntry
from django.contrib.sessions.models import Session
from django_extlog.models import ExtLog
class ... |
import io
import os
import requests
import shutil
import sys
import zipfile
from waxe_image import __version__
API_RELEASES_URL = 'https://api.github.com/repos/waxe/waxe-image/releases'
NG_BUILD_FOLDER = 'website'
def main(argv=sys.argv):
if len(argv) > 2:
print('Too many arguments')
sys.exit(1)
... |
from django.conf import settings
from django.test.client import Client
from .base import BaseRenderer
from django_perseus.exceptions import RendererException
import logging
import mimetypes
import os
logger = logging.getLogger('perseus')
class DefaultRenderer(BaseRenderer):
def render_path(self, path=None, view=Non... |
import argparse, json
parser = argparse.ArgumentParser()
parser.add_argument('plan', type=str, help='Plan data file')
args = parser.parse_args()
try:
with open(args.plan) as fp:
J = json.load(fp)
except Exception as e:
print("could not read JSON in file: %s\n" % args.plan + str(e))
exit(1)
for k in ... |
"""
Task
You are the manager of a supermarket.
You have a list of N items together with their prices that consumers bought on a particular day.
Your task is to print each item_name and net_price in order of its first occurrence.
item_name = Name of the item.
net_price = Quantity of the item sold multiplied by the price... |
"""Python library module for LSM6DS33 accelerometer and gyroscope.
This module for the Raspberry Pi computer helps interface the LSM6DS33
accelerometer and gyro.The library makes it easy to read
the raw accelerometer and gyro data through I²C interface and it also provides
methods for getting angular velocity and g for... |
from glob import glob
import numpy
import pickle
import os
home = os.environ["HOME"]
scripts = "%s/SCRIPT/repofish/analysis/methods" %(home)
base = "%s/data/pubmed" %os.environ["LAB"]
outfolder = "%s/repos" %(base)
articles_folder = "%s/articles" %(base)
if not os.path.exists(outfolder):
os.mkdir(outfolder)
folders... |
import os.path
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
=======
<<<<<<< HEAD
import re
import sys
=======
import sys
import gspread
>>>>>>> # This is a combination of 2 commits.
>>>>>>> Update README.md
try:
from setuptools import setup
except... |
import pygame
pygame.init()
background_color = (255,255,255)
(width, height) = (300, 200)
class Particle:
def __init__(self, (x, y), radius):
self.x = x
self.y = y
self.radius = radius
self.color = (255, 0, 0)
self.thickness = 1
def display(self):
pygame.draw.circ... |
import unittest
from scrapy.utils.sitemap import Sitemap, sitemap_urls_from_robots
class SitemapTest(unittest.TestCase):
def test_sitemap(self):
s = Sitemap("""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84">
<url>
<loc>http://www.example.com/</loc>
... |
import time
import datetime
import Adafruit_CharLCD as LCD
def file_get_contents(filename):
with open(filename) as f:
return f.read()
lcd_rs = 24 # Note this might need to be changed to 21 for older revision Pi's.
lcd_en = 23
lcd_d4 = 9
lcd_d5 = 11
lcd_d6 = 10
lcd_d7 ... |
import os
from celery import Celery
from django.apps import apps, AppConfig
from django.conf import settings
if not settings.configured:
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover
app = Celery('s... |
def runProgram(programLines,swapLine):
result = [False,0]
accumulator = 0
executionIndex = 0
setOfRunInstructions = []
while (executionIndex not in setOfRunInstructions) and (executionIndex < len(programLines)):
#print("Execution index: " + str(executionIndex)+ " accumulator: " + str(accumul... |
import unittest
import os
import sys
import responses
current_dir = (os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, os.path.join(current_dir, '..', '..'))
from processes.get_tmdb import Main, RequestAPI, StandardiseResponse, GatherException
class TestMain(unittest.TestCase):
"""Testing GetAPI"""
... |
import time
from marshmallow import fields
from marshmallow.decorators import post_dump
from indico.core.config import config
from indico.core.marshmallow import mm
class HTTPAPIError(Exception):
def __init__(self, message, code=None):
self.message = message
self.code = code
class HTTPAPIResult:
... |
'''
Created on Jun 20, 2016
@author: ionut
'''
import logging
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s] - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.... |
import math
from param import *
class Sample:
def __init__(self):
self.time = 0
self.home1_x = 0.0
self.home1_y = 0.0
self.home1_theta = 0.0
self.home2_x = 0.0
self.home2_y = 0.0
self.home2_theta = 0.0
self.away1_x = 0.0
self.away1_y = 0.0
... |
import _plotly_utils.basevalidators
class AlignValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="align", parent_name="scatterternary.hoverlabel", **kwargs
):
super(AlignValidator, self).__init__(
plotly_name=plotly_name,
parent_... |
import numpy as np
import cv2
import math
def rot_vec_to_euler(r):
# Rotate around x axis by 180 degrees to have [0, 0, 0] when facing forward
R = np.dot(np.array([[1, 0, 0],
[0, -1, 0],
[0, 0, -1]]),
np.array(cv2.Rodrigues(r)[0]))
sy = math.s... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'requirements.txt')) as fp:
requires = fp.readlines()
setup(
name='cebulany manager',
version='0.0.4',
classifiers=[],
author='Firemark',
author_email='marpiechula... |
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
extensions = [
'sphinx.ext.autodoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'hash-ring-ctypes'
copyright = u'2013, Matt Dennewitz'
version = '1.0.0'
release = '1.0.0'
exclude_patterns = ['_build']
pygmen... |
from typing import List
from test_framework import generic_test
def expression_synthesis(digits: List[int], target: int) -> bool:
# TODO - you fill in here.
return True
if __name__ == '__main__':
exit(
generic_test.generic_test_main('insert_operators_in_string.py',
... |
"""Tests for autotagging functionality.
"""
from __future__ import division, absolute_import, print_function
import re
import copy
from test import _common
from test._common import unittest
from beets import autotag
from beets.autotag import match
from beets.autotag.hooks import Distance, string_dist
from beets.library... |
"""1449. Form Largest Integer With Digits That Add up to Target
https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/
"""
from functools import lru_cache
from typing import List
class Solution:
def largest_number(self, cost: List[int], target: int) -> str:
def compare(a: str,... |
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
from xml.etree import ElementTree as et
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.datatype import AttribDict
from lib.cor... |
import codecs
import logging
import random
def import_url(path,lo,hi):
with codecs.open(path,encoding='utf-8') as f:
string = f.read()
arr = string.split('\n')
if not lo:
lo=0
if not hi:
hi=len(arr)
arr=arr[lo:hi]
url_arr = []
want = range(lo,hi)
# returns url and... |
"""Templatetags for the ``document_library`` app."""
from django import template
from ..models import Document
register = template.Library()
@register.assignment_tag
def get_files_for_document(document):
"""
Returns the available files for all languages.
In case the file is already present in another langua... |
from Instanssi.common.auth import user_access_required
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.urls import reverse
from Instanssi.users.forms import OpenIDLoginForm, DjangoLoginForm, ProfileForm
from Instanssi.common.misc import get_ur... |
import re
import htmlentitydefs
def unescape(text):
"""
Removes HTML or XML character references and entities from a text string.
text -- The HTML (or XML) source text.
return -- The plain text, as a Unicode string, if necessary.
"""
def fixup(m):
text = m.group(0)
if text[:2] ==... |
import unittest
from charlesbot.slack.slack_channel_joined import SlackChannelJoined
from charlesbot.slack.slack_channel_left import SlackChannelLeft
from charlesbot.slack.slack_group_joined import SlackGroupJoined
from charlesbot.slack.slack_group_left import SlackGroupLeft
from charlesbot.slack.slack_message import S... |
from __future__ import unicode_literals
import codecs
import distutils.dir_util
import os
import shutil
import sys
def touch_file(file_path):
"""
Create a new empty file at file_path.
"""
parent_dir = os.path.abspath(os.path.join(file_path, os.pardir))
if not os.path.isdir(parent_dir):
os.ma... |
import sys
import os
import shutil
import re
import subprocess
from glob import glob
from pycparser import c_parser, c_ast
from ctags import CTags, TagEntry
def collect_klee_runs():
'''Navigates all KLEE output directories and performs basic triage'''
errs = glob('klee-out-*/*.err')
col = {'ptr': 0, 'free':... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('quotation', '0005_auto_20150828_2207'),
]
operations = [
migrations.CreateModel(
name='Orderingcompany',
fields=[
... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
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 ri... |
"""
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
... |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from django.test.utils import override_settings
@override_settings(AUTHENTICATION_BACKENDS=
('django.contrib.auth.backends.ModelBackend',))
c... |
"""
Contains classes for working with the reaction model generated by RMG.
"""
import logging
import math
import numpy
import os.path
import itertools
from rmgpy.display import display
import rmgpy.constants as constants
from rmgpy.quantity import Quantity
import rmgpy.species
from rmgpy.thermo import Wilhoit, NASA, Th... |
from fabric import api as fab
from contextlib import contextmanager
@contextmanager
def with_vagrant():
with fab.settings(user="vagrant",host_string="127.0.0.1:2222",key_filename=".vagrant/machines/minecraft/virtualbox/private_key"):
yield
def ping(ip):
with with_vagrant():
return fab.run('ping ... |
from __future__ import print_function, absolute_import
import os
import sys
import time
import socket
import logging
class Daemon(object):
def __init__(self):
self.heartbeat = 50
def run(self):
logging.basicConfig(filename='daemon.log')
logging.error('daemon started')
self.daemon... |
UL_CATEGORY_LI = '//ul[@class="category"]/li'
H2_A_TITLELINK = './h2/a[@class="titlelink"]'
SPAN_A_TITLELINK = './span/a[@class="titlelink"]'
DIV_BODYFIELD_P = '//div[contains(@class,"bodyfield")]/p'
CATEGORY_H2_XPATH = [ UL_CATEGORY_LI, H2_A_TITLELINK ]
BODYFIELD_SPAN_XPATH = [ DIV_BODYFIELD_P, SPAN_A_TITLELINK ]
"""M... |
from flask_wtf import Form
from flask_wtf.file import FileRequired, FileAllowed, FileField
from wtforms import StringField, BooleanField, PasswordField, TextAreaField
from wtforms.validators import DataRequired, Email, Length
class SignUpForm(Form):
username = StringField('username', validators=[DataRequired(), Len... |
from .fb2_parser import FB2NoteParser
from .pdf_parser import PDFNoteParser
from .stat_parser import StatsAccessor
__all__ = ("FB2NoteParser", "PDFNoteParser", "StatsAccessor") |
"""Module loader file for /ciscripts/check/python.""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.