code
stringlengths
1
199k
import tensorflow as tf import hyperchamber as hc import hypergan as hg import numpy as np from hypergan.losses.least_squares_loss import LeastSquaresLoss from hypergan.ops import TensorflowOps from unittest.mock import MagicMock from tests.mocks import mock_gan loss_config = {'test': True, 'reduce':'reduce_mean', 'lab...
class Kifu: def __init__(self): self.kifu = [] def add(self, from_x, from_y, to_x, to_y, promote, koma): self.kifu.append((from_x, from_y, to_x, to_y, promote, koma)) def pop(self): return self.kifu.pop()
from __future__ import unicode_literals import frappe from frappe.model.document import Document desk_properties = ("search_bar", "notifications", "chat", "list_sidebar", "bulk_actions", "view_switcher", "form_sidebar", "timeline", "dashboard") class Role(Document): def before_rename(self, old, new, merge=False): i...
""" Created on Tue Dec 13 23:10:40 2016 @author: zhouyu """ import pandas as pd import numpy as np import os import re import nltk from nltk.corpus import stopwords from bs4 import BeautifulSoup os.chdir('/Users/zhouyu/Documents/Zhou_Yu/DS/kaggle_challenge/text processing') import glob alltrainfiles = glob.glob("*.csv"...
CELERY_RESULT_BACKEND = 'database' CELERY_RESULT_DBURI = 'sqlite:///mydatabase.db' BROKER_TRANSPORT = 'sqlalchemy' BROKER_HOST = 'sqlite:///tasks.db' BROKER_PORT = 5672 BROKER_VHOST = '/' BROKER_USER = 'guest' BROKER_PASSWORD = 'guest' CELERYD_CONCURRENCY = 1 CELERYD_TASK_TIME_LIMIT = 20 CELERYD_LOG_LEVEL = 'INFO'
def add_without_op(x, y): while y !=0: carry = x & y x = x ^ y y = carry << 1 print(x) def main(): x, y = map(int, input().split()) add_without_op(x, y) if __name__ == "__main__": main()
__author__ = 'Sean Yu' __mail__ = 'try.dash.now@gmail.com' import sqlite3 def CreateTable(dbname, table,table_define): db = sqlite3.connect(dbname) cu=db.cursor() cu.execute("""create table %s ( %s )"""%(table,table_define)) db.commit() cu.close() db.close() def InsertRecord(dbname, table,record...
import logging from mwoauth import ConsumerToken, Handshaker, AccessToken from mwoauth.errors import OAuthException import urllib.parse from django.conf import settings from django.contrib import messages from django.contrib.auth import login, authenticate from django.contrib.auth.models import User from django.core.ex...
""" @author: Tobias """ """@brief List of register classes""" _registerClasses = [ ['al', 'ah', 'ax', 'eax', 'rax'], ['bl', 'bh', 'bx', 'ebx', 'rbx'], ['cl', 'ch', 'cx', 'ecx', 'rcx'], ['dl', 'dh', 'dx', 'edx', 'rdx'], ['bpl', 'bp', 'ebp', 'rbp'], ['dil', 'di', 'edi', 'rdi'], ['sil', 'si', '...
"""Remove brief status column Revision ID: 590 Revises: 580 Create Date: 2016-03-03 14:56:59.218753 """ revision = '590' down_revision = '580' from alembic import op import sqlalchemy as sa def upgrade(): op.drop_column('briefs', 'status') def downgrade(): op.add_column('briefs', sa.Column('status', sa.VARCHAR(...
class Penguin(object): def __init__(self, name, mood, id=None): self.name = name self.mood = mood self.id = id def __repr__(self): return '< %s the %s penguin >' % (self.name, self.mood) class Goose(object): def __init__(self, name, favorite_penguin, id=None): self.na...
from unittest import TestCase from firstinbattle.deck import Card from firstinbattle.json_util import js class TestJson(TestCase): def test_encode_loads(self): cards = { Card(5, 'diamond'), Card(9, 'heart'), } encoded_str = js.encode({ 'message': 'test_msg...
from collections import OrderedDict n = int(input()) occurrences = OrderedDict() for _ in range(0, n): word = input().strip() occurrences[word] = occurrences.get(word, 0) + 1 print(len(occurrences)) print(sep=' ', *[count for _, count in occurrences.items()])
from distutils.core import setup setup( name = 'ical_dict', packages = ['ical_dict'], version = '0.2', description = 'A Python library to convert an .ics file into a Dictionary object.', author = 'Jay Ravaliya', author_email = 'jayrav13@gmail.com', url = 'https://github.com/jayrav13/ical_dic...
import os, pygame x = 320 y = 200 size_mult = 4 bright_mult = 4 pygame.init() os.environ['SDL_VIDEO_WINDOW_POS'] = str(0) + "," + str(40) #put window in consistent location os.environ['SDL_VIDEO_WINDOW_POS'] = str(0) + "," + str(40) #put window in consistent location screen = pygame.display.set_mode((x*size_mult, y*siz...
from twisted.internet import defer from nodeset.common import log from nodeset.core import config class Observer(object): def __init__(self, callable, *args, **kwargs): self.callable = callable self.args = args self.kwargs = kwargs #print "-- %s, %s" % (self.args, self.kwargs) ...
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRe...
import sys sys.path.insert(0, '../../build/swig/python') import cueify import struct import unittest def TRACK_DESCRIPTOR(session, adr, ctrl, track, abs_min, abs_sec, abs_frm, min, sec, frm): return [session, (((adr & 0xF) << 4) | (ctrl & 0xF)), 0, track, abs_min, abs_sec, abs_frm, ...
from __future__ import absolute_import, unicode_literals from qproject.celery import app as celery_app __all__ = ['celery_app']
from mqtt_as import MQTTClient, config from config import wifi_led, blue_led import uasyncio as asyncio import network import gc TOPIC = 'shed' # For demo publication and last will use same topic outages = 0 rssi = -199 # Effectively zero signal in dB. async def pulse(): # This demo pulses blue LED each time a subsc...
import subprocess import os def start_service(): subprocess.Popen("ipy start_srv.py", stdout=subprocess.PIPE) return 0 def close_service(): os.system("taskkill /im ipy.exe /f")
from openslides.core.config import config from openslides.motions.exceptions import WorkflowError from openslides.motions.models import Motion, State, Workflow from openslides.users.models import User from openslides.utils.test import TestCase class ModelTest(TestCase): def setUp(self): self.motion = Motion...
>>> myTuple = (1, 2, 3) >>> myTuple[1] 2 >>> myTuple[1:3] (2, 3)
""" eve.methods.post ~~~~~~~~~~~~~~~~ This module imlements the POST method, supported by the resources endopints. :copyright: (c) 2015 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from datetime import datetime from flask import current_app as app, abort from eve.utils imp...
from __future__ import unicode_literals import collections import hashlib import logging import requests from wxpy.api.messages import Message from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic from wxpy.utils.misc import get_text_without_at_bot from wxpy.utils import enhance_connection logger = loggin...
""" Sales module URLs """ from django.conf.urls.defaults import * urlpatterns = patterns('maker.sales.views', url(r'^(\.(?P<response_format>\w+))?$', 'index', name='sales'), url(r'^index(\.(?P<response_format>\w+))?/?$', 'index', name='sales_index'), url(r'^index/open(\.(?P<response_format>\...
import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w3.org/2000/svg' START = 1 END = 2 class Line(object): def __init__(self, line_element): a = line_elem...
from django.conf.urls import url, include from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^', include('symcon.urls')), url(r'^pages/', include('django.contrib.flatpages.urls')), url(r'^admin/', include(admin.site.urls)), ] urlpattern...
from django.contrib import admin from django.contrib.auth.models import User from .models import Stock, StockHistory, StockSelection, SectorHistory, StockNews class CommonAdmin(admin.ModelAdmin): date_hierarchy = 'pub_date' class SectorAdmin(CommonAdmin): list_display = ('Symbol', 'Sector', 'pub_date') sear...
from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('multiexplorer', '0006_pullhistory'), ] operations = [ migrations.CreateModel( name='PushHistory', fi...
""" Jump Search Find an element in a sorted array. """ import math def jump_search(arr,target): """ Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in...
from __future__ import division,print_function,absolute_import,unicode_literals import sys import os os.chdir(sys.path[0]) sys.path.append('/mnt/sda2/github/TSF1KEV/TSFpy') from TSF_io import * from TSF_shuffle import * from TSF_match import * from TSF_calc import * from TSF_time import * TSF_Forth_init(TSF_io_argvs(),...
from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisBizStatusAvailable(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.biz/status_available.txt" host = "whois.biz" part = yawhois.record.Part(open(fixtu...
""" Redis Blueprint =============== **Fabric environment:** .. code-block:: yaml blueprints: - blues.redis settings: redis: # bind: 0.0.0.0 # Set the bind address specifically (Default: 127.0.0.1) """ import re from fabric.decorators import task from fabric.utils import abort from refabric....
import json from flask import Flask from flask import request from flask import jsonify import time from psutil import net_io_counters from asyncftp import __version__ import threading from asyncftp.Logger import _LogFormatter t = time.time() net = net_io_counters() formatter = _LogFormatter(color=False) log_message = ...
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('l...
from src.interfacing.ogs.connect import Authentication import codecs import sys import os from time import sleep def loadList(pNameFile): iList = [] with codecs.open(pNameFile, "r", "utf-8") as f: for line in f: iList.append(line) return iList if __name__ == "__main__": a = Authentic...
""" Helper module for Python version 3.0 and above - Ordered dictionaries - Encoding/decoding urls - Unicode/Bytes (for sending/receiving data from/to socket, base64) - Exception handling (except Exception as e) """ import base64 from urllib.parse import unquote, quote from collections import OrderedDict def modulename...
""" Created on 27/04/2015 @author: C&C - HardSoft """ from util.HOFs import * from util.CobolPatterns import * from util.homogenize import Homogenize def calc_length(copy): if isinstance(copy, list): book = copy else: if isinstance(copy, str): book = copy.splitlines() e...
from threading import local from django.contrib.sites.models import Site import os _locals = local() def get_current_request(): return getattr(_locals, 'request', None) def get_current_site(): request = get_current_request() host = request.get_host() try: return Site.objects.get(domain__iexact=h...
from msrest.serialization import Model class GenerateArmTemplateRequest(Model): """Parameters for generating an ARM template for deploying artifacts. :param virtual_machine_name: The resource name of the virtual machine. :type virtual_machine_name: str :param parameters: The parameters of the ARM templa...
import factory from data.tests.factories import DepartmentFactory from ..models import Tourist, TouristCard class TouristFactory(factory.DjangoModelFactory): class Meta: model = Tourist first_name = 'Dave' last_name = 'Greel' email = 'greel@musicians.com' class TouristCardFactory(factory.DjangoM...
__author__ = 'kjoseph' import itertools import Queue from collections import defaultdict from dependency_parse_object import DependencyParseObject, is_noun, is_verb def get_parse(dp_objs): term_map = {} map_to_head = defaultdict(list) for parse_object in dp_objs: if parse_object.head > 0: ...
""" Python's random module includes a function choice(data) that returns a random element from a non-empty sequence. The random module includes a more basic function randrange, with parametrization similar to the built-in range function, that return a random choice from the given range. Using only the randrange functio...
num = input("What is the numerator") dem = input("What is the denominator") counta = 2 countb = 2 def math (num,dem): remainsa = 1 remainsb = 1 remains = remainsa - remainsb while remains > 0: a = num / counta b = dem / countb remainsa = num % counta remainsb = num % coun...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rii_Api', '0001_initial'), ] operations = [ migrations.AlterField( model_name='location', name='state', field=models....
"""Some classes to support import of data files """ import os, glob import numpy import time try: import ConfigParser as configparser #gets rename to lowercase in python 3 except: import configparser class _BaseDataFile(object): """ """ def __init__(self, filepath): """ """ s...
__author__ = 'emre' print "hello world"
import os from flask import Flask, g, session, redirect, request, url_for, jsonify from requests_oauthlib import OAuth2Session OAUTH2_CLIENT_ID = os.environ['OAUTH2_CLIENT_ID'] OAUTH2_CLIENT_SECRET = os.environ['OAUTH2_CLIENT_SECRET'] OAUTH2_REDIRECT_URI = 'http://localhost:5000/callback' API_BASE_URL = os.environ.get(...
from MirrorAI.dataset.directional.label_image import label_image import numpy def test(): d = numpy.array([1, 1, 0]) answer = label_image(d, target=0) solution = [0, 0, 1] assert (answer == solution).all()
import time import json import pprint import hashlib import struct import re import base64 import httplib import sys from multiprocessing import Process ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} pp = pprint.PrettyPrinter(indent=4) class BitcoinRPC: OBJID = 1 def __init__(self, host, port, username, password):...
from __future__ import unicode_literals import autoslug.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('teams', '0001_initial'), ('accounts', '0001_initial')...
import re import logging from google.appengine.ext import db from google.appengine.api import users, memcache from handler import Handler, SlashRedirect from webapp2_extras.routes import RedirectRoute, PathPrefixRoute import webapp2 from webapp2_extras.routes import RedirectRoute, PathPrefixRoute import articles import...
from datetime import datetime import time import json from Commit import Commit; import Constant; import collections from yattag import Doc def generateHTML(commits, projectName, commitData, fileExtensionMap): totalAuthors = len(commitData) generateBestAuthors(projectName, commitData) generateFileByExtensio...
""" Django settings for gnucash_explorer project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECR...
import sublime from . import SblmCmmnFnctns class Spinner: SYMBOLS_ROW = u'←↑→↓' SYMBOLS_BOX = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' def __init__(self, symbols, view, startStr, endStr): self.symbols = symbols self.length = len(symbols) self.position = 0 self.stopFlag = False self.view = view self.startStr = startStr self.endS...
from django.conf.urls import url from sms import views app_name = 'sms' urlpatterns = [ url(r'^$', views.index, name="index"), ]
f = open('input.txt') triangles = [map(int,l.split()) for l in f.readlines()] possible = 0 for t in triangles: t.sort() if t[0] + t[1] > t[2]: possible += 1 print(possible)
import asyncio import sys import config import sender import receiver print(sys.argv) async def receiveMessageFromSerial(): return "Message" def help(): print('Luiza 1.0 - (luiza.santost@hotmail.com)') print('Usage: python3 app.py [Options][Message][source][dest]') print('') print('SENDING MESSAGE')...
""" Testing module from creating product using http://www.sendfromchina.com/default/index/webservice """ from flask import Flask, render_template, request from flask_wtf.csrf import CSRFProtect from werkzeug.datastructures import MultiDict from forms import SFCCreateOrder, SFCCreateProduct, SFCOrderDetail, SFCASNInfo, ...
''' python 2.7.3 (win) 0 1 <...> 998 boom ''' def f(n): print n f(n+1) try: f(0) except: print 'boom'
""" A unit test for ext_pylib file module's Parsable mixin class. """ import pytest from . import utils from ext_pylib.files import File, Parsable class ParsableFile(Parsable, File): """Dummy class extending Parsable and File.""" FILE = """This is a sample file. This is a sample file. This is a sample file. Documen...
import sys base_url = sys.argv[0] addon_handle = int(sys.argv[1]) import xbmcplugin xbmcplugin.setContent(addon_handle, 'episodes') import urlparse args = urlparse.parse_qs(sys.argv[2][1:]) mode = args.get('mode', None) from urllib import FancyURLopener, urlencode class URLOpener(FancyURLopener): version = 'Mozilla...
import operator import ply.lex as lex from jpp.parser.operation import Operation from jpp.parser.expression import SimpleExpression reserved = { 'extends': 'EXTENDS', 'import': 'IMPORT', 'local': 'LOCAL', 'imported': 'IMPORTED', 'user_input': 'USER_INPUT', } NAME_TOK = 'NAME' tokens = [ 'INTEGER...
from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib import auth admin.autodiscover() urlpatterns = patterns('stepup.views', # Examples: # url(r'^$', 'volunteer.views.home', name='home'), # url(r'^blog/', include('blog.urls')), #auth url(r'^admin/'...
""" This program collects Portugal weather forecasts from IPMA and uploads them to the Orion Context Broker. It uploads the list of stations on the fly from - http://api.ipma.pt/json/locations.json. Legal notes: - http://www.ipma.pt/en/siteinfo/index.html?page=index.xml Examples: - get...
from aiohttp import ClientSession from aiowing import settings async def test_unauthenticated_records(test_app, test_client): cli = await test_client(test_app) resp = await cli.get(test_app.router['admin_records'].url(), allow_redirects=False) assert resp.headers.get('Location') == ...
class Slot(object): """ To use comb, you should create a python module file. we named *slot*. A legal slot must be named 'Slot' in your module file and it must be at least contain four method: * `initialize` initial resource, e.g: database handle * `__enter__` get next data to do,you can fet...
from biohub.core.plugins import PluginConfig class TestConfig(PluginConfig): name = 'tests.core.plugins.test' title = '' author = '' description = ''
from flask.ext.wtf import Form from wtforms import TextField from wtforms.validators import Required class NameForm(Form): name = TextField('What is your name?', validators = [ Required() ])
from django.test import TestCase from django.core.urlresolvers import reverse class TestHomePage(TestCase): def test_uses_index_template(self): response = self.client.get(reverse("home")) self.assertTemplateUsed(response, "home/index.html") def test_uses_base_template(self): response = s...
import os import sys import warnings from setuptools import setup version_contents = {} here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, "shippo", "version.py"), encoding="utf-8") as f: exec(f.read(), version_contents) setup( name='shippo', version=version_contents['VERSION'], ...
from __future__ import absolute_import from functools import partial from pkg_resources import Requirement, resource_filename import re from mako.template import Template from sqlalchemy import MetaData, select, create_engine, text from sqlalchemy.exc import ArgumentError from fixturegen.exc import ( NoSuchTable, ...
""" Django settings for gamesapi project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os BA...
import time from typing import List, Optional from utils import tasks from zirc.event import Event from utils.database import Database from zirc.wrappers import connection_wrapper def chunks(l: List, n: int): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] de...
from base64 import b64decode, b64encode from hashlib import sha256 from Crypto import Random from Crypto.Cipher import AES from frontstage import app class Cryptographer: """Manage the encryption and decryption of random byte strings""" def __init__(self): """ Set up the encryption key, this wil...
''' Created on 22/ago/2011 @author: norby ''' from core.moduleexception import ModuleException, ProbeException, ExecutionException, ProbeSucceed from core.moduleguess import ModuleGuess from core.argparse import ArgumentParser, StoredNamespace from core.argparse import SUPPRESS from ast import literal_eval import rando...
from django.db import migrations def update_domain_forward(apps, schema_editor): """Set site domain and name.""" Domain = apps.get_model("domains", "Domain") Domain.objects.update_or_create(pk=1, name="fedrowanie.siecobywatelska.pl") class Migration(migrations.Migration): dependencies = [("domains", "00...
from django.http import HttpResponse from django.shortcuts import render from django.views import generic import api.soql import json from api.soql import * def indexView(request): context = { "vehicleAgencies": getUniqueValuesWithAggregate("gayt-taic", "agency", "max(postal_code)"), "vehicl...
from __future__ import absolute_import, print_function, unicode_literals from ..actions.install import install from ._base import BaseCommand from .options import dev, no_check, no_clean class Command(BaseCommand): name = "install" description = "Generate Pipfile.lock to synchronize the environment." argume...
import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc")) import json import shutil import subprocess import tempfile import traceback from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from util import * from netutil import * def run_bind_test(...
import copy class Solution: # @param strs: A list of strings # @return: A list of strings def anagrams(self, strs): # write your code here str1=copy.deepcopy(strs) def hashLize(s): dicts1= dict() for i in range(26): dicts1[chr(i+ord("a"))]=0 ...
""" functionモジュールのparticle_resampling関数をテストする """ from functions import particles_resampling import pfoe robot1 = pfoe.Robot(sensor=4,choice=3,particle_num=100) for i in range(100): robot1.particles.distribution[i] = i % 5 robot1.particles.weight[i] = 1.0 / 100.0 robot1.particles = particles_resampling(robot1.p...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Course', '0005_coursegroup'), ] operations = [ migrations.AlterField( model_name='department', n...
"""Package. Manages event queues. Writing event-driven code ------------------------- Event-driven procedures should be written as python coroutines (extended generators). To call the event API, yield an instance of the appropriate command. You can use sub-procedures - just yield the appropriate generator (a minor nuis...
from setuptools import setup from setuptools import find_packages setup(name='gym_square', version='0.0.1', author='Guillaume de Chambrier', author_email='chambrierg@gmail.com', description='A simple square world environment for openai/gym', packages=find_packages(), url='https://git...
""" Read the list of chimeric interactions and generate a file that can be read by circos. """ import sys import argparse from collections import defaultdict from math import log import pro_clash def process_command_line(argv): """ Return a 2-tuple: (settings object, args list). `argv` is a list of argument...
from __future__ import unicode_literals from django.db import models import datetime from django.db.models.signals import pre_save from django.urls import reverse from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from source_utils.starters import CommonInfo, GenericCategory f...
import logging import os import shlex import unittest import sys from toil.common import toilPackageDirPath from toil.lib.bioio import getBasicOptionParser, parseSuiteTestOptions log = logging.getLogger(__name__) class ToilTest(unittest.TestCase): """ A common base class for our tests. Please have every test ca...
from setuptools import setup, find_packages from pip.req import parse_requirements version = "6.27.20" requirements = parse_requirements("requirements.txt", session="") setup( name='frappe', version=version, description='Metadata driven, full-stack web framework', author='Frappe Technologies', author_email='info@f...
<<<<<<< HEAD <<<<<<< HEAD from . import client, rest, session ======= from . import client, rest, session >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= from . import client, rest, session >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
import os import subprocess from pathlib import Path from time import sleep PACKAGES = Path('packages') class Module: def __init__(self, name, path=None, files=None, dependencies=None): self.name = name if path is None: path = PACKAGES / name self.path = path self.files =...
"""pandoc-fignos: a pandoc filter that inserts figure nos. and refs.""" import re import functools import itertools import io import sys import pandocfilters from pandocfilters import stringify, walk from pandocfilters import RawInline, Str, Space, Para, Plain, Cite, elt from pandocattributes import PandocAttributes Im...
""" Encapsulate the absence of an object by providing a substitutable alternative that offers suitable default do nothing behavior. """ import abc class AbstractObject(metaclass=abc.ABCMeta): """ Declare the interface for Client's collaborator. Implement default behavior for the interface common to all clas...
import 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 'ModelFieldData.foreign' db.alter_column('blogs_modelfielddata', 'foreign_id', self.gf('django.db.models.fields.relate...
import filecmp from transfert import Resource from transfert.actions import copy def estimate_nb_cycles(len_data, chunk_size): return (len_data // chunk_size) + [0, 1][(len_data % chunk_size) > 0] def test_simple_local_copy(tmpdir): src = tmpdir.join('alpha') dst = tmpdir.join('beta') src.write('some da...
import json from django.db.models import Q, Subquery from django.core.management.base import BaseCommand from readthedocs.oauth.models import RemoteRepository from readthedocs.oauth.services import registry from readthedocs.oauth.services.base import SyncServiceError from readthedocs.projects.models import Project from...
''' @author: lockrecv@gmail.com A pure python ping implementation using raw socket. Note that ICMP messages can only be sent from processes running as root. Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>. ''' import os import select import socket import struct import time class Ping: ''' Power On Stat...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline i...
import sys from osgeo import gdal from osgeo import ogr bReadOnly = False bVerbose = True bSummaryOnly = False nFetchFID = ogr.NullFID papszOptions = None def EQUAL(a, b): return a.lower() == b.lower() def main(argv = None): global bReadOnly global bVerbose global bSummaryOnly global nFetchFID g...