code
stringlengths
1
199k
"""Modulo que contiene la clase directorio de funciones ----------------------------------------------------------------- Compilers Design Project Tec de Monterrey Julio Cesar Aguilar Villanueva A01152537 Jose Fernando Davila Orta A00999281 ----------------------------------------------------------------- DOCUME...
from webhelpers import * from datetime import datetime def time_ago( x ): return date.distance_of_time_in_words( x, datetime.utcnow() ) def iff( a, b, c ): if a: return b else: return c
from __future__ import absolute_import, unicode_literals import datetime from collections import namedtuple import mock import six from django.conf import settings from django.test import TestCase from django.utils import timezone from wagtail.wagtailcore.models import Page from articles.models import ArticleCategory, ...
from itertools import groupby from swf.models.event import EventFactory, CompiledEventFactory from swf.models.event.workflow import WorkflowExecutionEvent from swf.utils import cached_property class History(object): """Execution events history container History object is an Event subclass objects container ...
import csv import re import datetime import string import collections def get_nr_data(): ''' returns a list of lists each entry represents one row of NiceRide data in form -- [[11/1/2015, 21:55], '4th Street & 13th Ave SE', '30009', [11/1/2015, 22:05], 'Logan Park', '30104', '565', 'Casual'] where the ...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'PushResult' db.create_table(u'notos_pushresult', ( (u'id', self.gf('django.db.models.fields.AutoField')(pri...
from distutils.core import setup setup( name='bumpversion_demo', version='0.1.0', packages=[''], url='https://github.com/tantale/bumpversion_demo', license='MIT License', author='Tantale', author_email='tantale.solution@gmail.com', description='Demonstration of ``bumpversion`` usage in t...
import struct from . import crc16 class PacketWriter: MAX_PAYLOAD = 1584 MIN_LEN = 6 MAX_LEN = 1590 SOF = 0x01 OFFSET_SOF = 0 OFFSET_LENGTH = 1 OFFSET_CMD = 3 OFFSET_PAYLOAD = 4 def __init__(self): self._packet = None def Clear(self): self._packet = None def N...
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' SQLALCHEMY_COMMIT_ON_TEARDOWN = True MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = 'frey.maxim@gmail.com' ...
import re import sys if sys.version < '3': def u(x): return x.decode('utf-8') else: unicode = str def u(x): return x rx_section = re.compile(r'^([\w\-]+) \{$', re.UNICODE) rx_named_section = re.compile( r'^([\w\-]+) ([\w\-\"\./@:=\+]+) \{$', re.UNICODE ) rx_value = re.compile(r'^([\w\-]+...
""" Notices indicate how a regulation has changed since the last version. This module contains code to compile a regulation from a notice's changes. """ from bisect import bisect from collections import defaultdict import copy import itertools import logging from regparser.grammar.tokens import Verb from regparser.tree...
from django.apps import AppConfig class TravellerConfig(AppConfig): name = 'traveller'
import argparse import logging import os logger = logging.getLogger("cli_utils") def type_input_file(path): if path == '-': return path if not os.path.isfile(path): logger.error('File "%s" not found' % path) raise argparse.ArgumentError return path def add_common_args(parser): pa...
from PySide.QtGui import * from PySide.QtCore import * class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() button = QPushButton(self) button.setGeometry(QRect(100, 100, 100, 100)) machine = QStateMachine(self) s1 = QState() s1.assignP...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'SystemStats' db.create_table('core_systemstats', ( ('date', self.gf('django.db.models.fields.DateTimeField'...
from .versioner import DBVersioner, DBVersionCommander
''' Author: Yin Lin Date: September 23, 2013 The class object StarClass loads stars from the catalog.py and from the source extractor cat file and converts them into proper format. The lists of stars are then passed to the subclass, StarCalibration, to cross match two lists and perform offset and rotational cali...
""" (c) 2014-2016 - Copyright Red Hat Inc Authors: Pierre-Yves Chibon <pingou@pingoured.fr> """ from __future__ import unicode_literals, absolute_import import logging import os import flask import pygit2 from binaryornot.helpers import is_binary_string import pagure.config import pagure.doc_utils import pagure.ex...
import os,sys, re, json, requests from oxapi import * def get_a_task(ox): folder = ox.get_standard_folder('tasks') task = list(ox.get_tasks(folder.id))[0] return task def upload(bean, args=[{'content':None,'file':None, 'mimetype':'text/plain','name':'attachment.txt'}]): from requests.packages.urllib3.fi...
from tg.configuration import AppConfig, config from tg import request from pollandsurvey import model from tgext.pyutilservice import Utility import logging log = logging.getLogger(__name__) from tgext.pylogservice import LogDBHandler class InterfaceWebService(object): def __init__(self): self.modules ='INT...
import os import re import unittest from binascii import hexlify from Cryptodome.Util.py3compat import b, tobytes, bchr, unhexlify from Cryptodome.Util.strxor import strxor_c from Cryptodome.Util.number import long_to_bytes from Cryptodome.SelfTest.st_common import list_test_cases from Cryptodome.Cipher import AES from...
''' Arff loader for categorical and numerical attributes, based on scipy.io.arff.arffloader With minor changes for this project (eg. categorical attributes are mapped onto integers and whole dataset is returned as numpy array of floats) If any unsupported data types appear or if arff is malformed, ParseArffError with i...
''' Modulo Movimiento Nanometros @author: P1R0 import ObjSerial, sys; ObjSer = ObjSerial.ObjSerial(0,9600) ObjSer.cts = True ObjSer.dtr = True ObjSer.bytesize = 8 ''' SxN = 59.71 #Constante de Calibracion del Motor def init(ObjSer,A): ObjSer.flushOutput() ObjSer.write(unicode("A\r\n")) echo(Obj...
#!/usr/bin/python def add(x, y): a=1 while a>0: a = x & y b = x ^ y x = b y = a << 1 return b def vowel_count(word): vowels_counter = 0 for letter in word: if letter.isalpha(): if letter.upper() in 'AEIOUY': vowels_counter += 1 return vowels_counter if __name__ =...
import argparse import sys import traceback as tb from datetime import datetime from cfme.utils.path import log_path from cfme.utils.providers import list_provider_keys, get_mgmt def parse_cmd_line(): parser = argparse.ArgumentParser(argument_default=None) parser.add_argument('--nic-template', ...
from ycmd.utils import ToUtf8IfNeeded from ycmd.completers.completer import Completer from ycmd import responses, utils, hmac_utils import logging import urlparse import requests import httplib import json import tempfile import base64 import binascii import threading import os from os import path as p _logger = loggin...
import sys import csv import json try: import pyproj except ImportError: sys.stderr.write("Please install the pyproj python module!\n") sys.exit(3) try: from pymongo import MongoClient except ImportError: sys.stderr.write("Please install the pymongo python module!\n") sys.exit(3) isNAD83 = True ...
from django.db import models from django.contrib.auth import models as auth import datetime from application import settings from django.db.models.signals import post_save from django.dispatch import receiver typeChoices = ( ('task', 'Task'), ('userStory', 'User Story'), ) statusChoices = ( ('toDo', 'To do'), ('in...
from django.contrib.auth import logout as auth_logout from django.contrib.auth.decorators import login_required from django.http import * from django.template import Template, Context from django.shortcuts import render_to_response, redirect, render, RequestContext, HttpResponseRedirect def login(request): return r...
""" ConversionParser.py $Id: ConversionParser.py,v 1.5 2004/10/20 01:44:53 chrish Exp $ Copyright 2003 Bill Nalen <bill.nalen@towers.com> Distributable under the GNU General Public License Version 2 or newer. Provides methods to wrap external convertors to return PluckerTextDocuments """ import os, sys, string, tempf...
from Products.Zuul.form import schema from Products.Zuul.utils import ZuulMessageFactory as _t from Products.Zuul.infos.component import IComponentInfo from Products.Zuul.interfaces import IFacade class IPuppetClientInfo(IComponentInfo): signed = schema.Bool(title=_t(u'Is the client SSL signed?'), group='Details') ...
import BRT from collections import namedtuple import configparser import os import logging from os.path import expanduser import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', '--submit', help='Execute the submission', action='store_true') parser.add_argument('-q', '--quiet', help='Jast do the jo...
from bus import Bus from collections import namedtuple, OrderedDict import struct, time, os, sys bmap = namedtuple('status', 'name mask color') identity_req = namedtuple('identity_req', 'cmd') status_req = namedtuple('status_req', 'cmd') read_req = namedtuple('read_req', 'cmd address') write_req = namedtuple('write_req...
import requests import yaml class RequestsApi: def __init__(self): 'init' self.config = yaml.load(open("config/request_settings.yml", "r")) def get_objects(self, sector): 'request to get objects' objects_points = [] url = self.config['host'] + self.config['object_path'] % sector response = requests.get(ur...
__author__ = "Cyril Jaquier, Steven Hiscocks, Yaroslav Halchenko" __copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2008-2013 Fail2Ban Contributors" __license__ = "GPL" try: import setuptools from setuptools import setup except ImportError: setuptools = None from distutils.core import setup try: # python 3.x fro...
import greengraph if __name__ == '__main__': from matplotlib import pyplot as plt mygraph = greengraph.Greengraph('New York','Chicago') data = mygraph.green_between(20) plt.plot(data) plt.show()
__author__ = 'Andy Gallagher <andy.gallagher@theguardian.com>' import xml.etree.ElementTree as ET import dateutil.parser from .vidispine_api import always_string class VSMetadata: def __init__(self, initial_data={}): self.contentDict=initial_data self.primaryGroup = None def addValue(self,key,va...
from os import path from os.path import abspath from urllib.parse import urlparse from urllib.request import urlopen import magic from urllib.error import HTTPError import logging log = logging.getLogger("oa.{0}".format(__name__)) def filetype(file_path): if path.exists(file_path) and path.isfile(file_path): ...
""" .. moduleauthor:: Calin Pavel <calin.pavel@codemart.ro> """ import os import logging from logging.handlers import MemoryHandler from tvb.basic.profile import TvbProfile from tvb.basic.logger.simple_handler import SimpleTimedRotatingFileHandler class ClusterTimedRotatingFileHandler(MemoryHandler): """ This i...
from distutils.core import setup from DistUtilsExtra.command import * import glob import os setup(name='unattended-upgrades', version='0.1', scripts=['unattended-upgrade'], data_files=[ ('../etc/apt/apt.conf.d/', ["data/50unattended-upgrades"]), ('../etc/logrotate.d/...
from datetime import datetime, timedelta import time class Match: def __init__(self, json): i = (int)(json['_links']['competition']['href'].rfind('/') + 1) self.competitionId = (int)(json['_links']['competition']['href'][i:]) ind = (int)(json['_links']['self']['href'].rfind('/') + 1) ...
class Mycar168Pipeline(object): def process_item(self, item, spider): return item
''' mysql> desc problem; +-------------+---------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------------+------+-----+---------+----------------+ | pid | int(11) | NO | PRI | NULL | auto_increment | | title...
import math import summon from summon.core import * from summon import shapes, colors def interleave(a, b): c = [] for i in xrange(0, len(a), 2): c.extend(a[i:i+2] + b[i:i+2]) return c def curve(x, y, start, end, radius, width): p = shapes.arc_path(x, y, start, end, radius, 30) p2 = shapes.a...
import logging from .model import LogEntry, LogLevels class NGWLogHandler(logging.Handler): """ Simple standard log handler for nextgisweb_log """ def __init__(self, level=LogLevels.default_value, component=None, group=None): logging.Handler.__init__(self, level=level) self.component = c...
import numpy as np import matplotlib.pyplot as plt from sklearn import ensemble from sklearn import datasets from sklearn.utils import shuffle from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score from sklearn.ensemble.partial_dependence import plot_partial_dependence from sklearn.model_se...
import sys import boto3 import os from botocore.exceptions import ClientError import json import argparse from botocore.utils import InstanceMetadataFetcher from botocore.credentials import InstanceMetadataProvider import platform region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1') duration = int(os.getenv('AWS_CLIEN...
""" IMU Plugin Copyright (C) 2015 Olaf Lüke <olaf@tinkerforge.com> Copyright (C) 2015 Matthias Bolte <matthias@tinkerforge.com> Copyright (C) 2019 Erik Fleckstein <erik@tinkerforge.com> imu_3d_widget.py: IMU OpenGL representation This program is free software; you can redistribute it and/or modify it under the terms of...
lidar_run = 2 # Imports point cloud as canopy and point density rasters lpi_run = 0 # Creates Light Penetration Index (LPI) from point cloud preprocessing_run = 0 # Creates derivative GIS products slope, aspect, tree height, albedo rsun_run = 0 # Runs GRASS light model, r.sun algore_r...
NAME = 'django-adminactions' VERSION = __version__ = (0, 4, 0, 'final', 0) __author__ = 'sax' import subprocess import datetime import os def get_version(version=None): """Derives a PEP386-compliant version number from VERSION.""" if version is None: version = VERSION assert len(version) == 5 as...
import os import RecordTimer import Components.ParentalControl from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Components.ActionMap import ActionMap from Components.config import config from Components.AVSwitch import AVSwitch from Components.Console import Console from Components.Impor...
"""Pure TTY chooser UI""" from __future__ import print_function, absolute_import __author__ = "Stephan Sokolow (deitarion/SSokolow)" __license__ = "GNU GPL 2 or later" import os try: import readline # Shut PyFlakes up readline # pylint: disable=pointless-statement except ImportError: pass def parse_cho...
__author__ = 'Ben "TheX1le" Smith' __email__ = 'thex1le@gmail.com' __website__= 'http://trac.aircrack-ng.org/browser/trunk/scripts/airgraph-ng/' __date__ = '03/02/09' __version__ = '' __file__ = 'airgraph-ng' __data__ = 'This is the main airgraph-ng file' """ Welcome to airgraph written by TheX1le Special Thanks to Rel...
import mock from flask import url_for from invenio_accounts.testutils import login_user_via_session from utils import get_json from rero_ils.modules.patron_transactions.permissions import \ PatronTransactionPermission def test_pttr_permissions_api(client, patron_martigny, system_librar...
""" *************************************************************************** ogr2ogrclipextent.py --------------------- Date : November 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ********************************************...
import time from mind.Goal import Goal def false(_): return False def true(_): return True class Delayed(Goal): """Will delay execution of sub goals until the specified time.""" def __init__(self, time: float, sub_goals: list, desc="A delayed goal."): Goal.__init__(self, desc=desc, fulfilled=self.is_rig...
''' Allmyvideos urlresolver plugin Copyright (C) 2013 Vinnydude This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is ...
import os DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Sinan Midillili', 'sinan@rahatol.com'), ) DEFAULT_FROM_EMAIL = 'sinan@rahatol.com', SERVER_EMAIL = 'sinan@rahatol.com' MANAGERS = ADMINS ALLOWED_HOSTS = [] TIME_ZONE = 'Europe/Istanbul' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True USE_L10N = True USE...
import os import shutil import subprocess import sys if os.environ.get('DESTDIR'): install_root = os.environ.get('DESTDIR') + os.path.abspath(sys.argv[1]) else: install_root = sys.argv[1] if not os.environ.get('DESTDIR'): schemadir = os.path.join(install_root, 'glib-2.0', 'schemas') print('Compile gsettings sch...
"""This module provides functionality to work with zip files.""" from os import path from zipfile import ZipFile from translate.storage import factory from translate.storage import directory from translate.misc import wStringIO class ZIPFile(directory.Directory): """This class represents a ZIP file like a directory...
import elliptic import heat import IRT print "Loading comatmor version 0.0.1"
import random import time import threading import unittest from lru_cache import LruCache class TesLruCache(unittest.TestCase): def test_cache_normal(self): a = [] @LruCache(maxsize=2, timeout=1) def foo(num): a.append(num) return num foo(1) foo(1) ...
""" Copyright (C) 2007-2013 Guake authors This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hop...
import sys import json from elasticsearch1 import Elasticsearch def init_es(es_host, es_index): es = Elasticsearch([ es_host ]) es.indices.delete( es_index, ignore=[400, 404] ) es.indices.create( es_index, ignore=400 ) # create mappings with open('pcawg_summary.mapping.json', 'r') as m: es_m...
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Thi...
"""okc_scraper includes all the functions needed to scrape profiles from OKCupid""" import requests import cPickle as pickle import time from BeautifulSoup import BeautifulSoup def authorize(username, password): """Log into OKCupid to scrape profiles""" user_info = {"username": username, "password": password} ...
"""Support classes and functions for testing the cmdlib module. """ from cmdlib.testsupport.cmdlib_testcase import CmdlibTestCase, \ withLockedLU from cmdlib.testsupport.config_mock import ConfigMock from cmdlib.testsupport.iallocator_mock import patchIAllocator from cmdlib.testsupport.livelock_mock import LiveLockMo...
import unittest import apt_pkg import apt.progress.base class TestCache(unittest.TestCase): """Test invocation of apt_pkg.Cache()""" def setUp(self): apt_pkg.init_config() apt_pkg.init_system() def test_wrong_invocation(self): """cache_invocation: Test wrong invocation.""" ap...
"""Module with a *procedures* dictionary specifying available quantum chemical methods. """ from __future__ import print_function from __future__ import absolute_import from . import proc from . import interface_cfour procedures = { 'energy': { 'hf' : proc.run_scf, 'scf' ...
class DownloadView: def __init__ (self, downloadlist): self.downloadlist = downloadlist downloadlist.view = self def add_download (self, download): print 'DownloadView.add_download (download): stub' def update_download (self, download): print 'DownloadView.update_download (do...
""" Estimate the international "visibility" of countries by retrieving the average number of articles the New York Times returns in its search query. For each year and each country, a query is send to the NYT api and the number of returned hits (i.e. articles) is taken as estimate for the international "visibility". To...
from mock import patch import os import pprint import shutil import subprocess import unittest from pyspatialite import dbapi2 as db import qgis.core # Need to import this before PyQt to ensure QGIS parts work from PyQt4.QtSql import QSqlQuery, QSqlDatabase from Roadnet.database import connect_and_open from Roadnet.te...
import check from fractions import gcd def intersection(x1, y1, x2, y2, x3, y3, x4, y4): x_numerator = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) denominator = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) if (denominator == 0) : return "parallel" x_gcd = gcd(x_numerator,denominat...
__author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi class ItusozlukBaslikSpider(GenericSozlukSpider): name = 'itusozluk' def _...
import osclib.api import osc.conf import os import os.path import vcr import pytest import requests TESTROOT = os.path.join(pytest.config.rootdir, "osclib-tests") OSCRC = os.path.join(TESTROOT, "oscrc", "oscrc_test_api") VCRROOT = os.path.join(TESTROOT, "fixtures", "vcr") def test_default_api(monkeypatch): """ ...
r"""A proxy enabling multiple wiring guide instances to interact with the same SpiNNaker boards. A very simple protocol is used between the client and server. Clients may send the following new-line delimited commands to the server: * ``VERSION,[versionstring]\n`` The server will disconnect any client with an incompa...
from __future__ import absolute_import from __future__ import unicode_literals from dnfpluginscore import _, logger import dnf import dnf.cli import dnf.exceptions import dnf.i18n import dnf.subject import dnfpluginscore import hawkey import itertools import os import shutil import copy import glob import subprocess im...
from testscenarios import TestWithScenarios import unittest from geocode.geocode import GeoCodeAccessAPI class GeoCodeTests(TestWithScenarios, unittest.TestCase): scenarios = [ ( "Scenario - 1: Get latlng from address", { 'address': "Sydney NSW", 'latl...
""" package/module TEST Descripción del test. Autor: PABLO PIZARRO @ github.com/ppizarror Fecha: AGOSTO 2016 Licencia: GPLv2 """ __author__ = "ppizarror" from _testpath import * # @UnusedWildImport import unittest DISABLE_HEAVY_TESTS = True DISABLE_HEAVY_TESTS_MSG = "Se desactivaron los tests pesados" VERBOSE = False ...
import serial gSerialName = '/dev/ttyS0' gBaudrate = 9600 gTimeout = 0 gRequestByte = 1 if __name__ == "__main__": ser = serial.Serial( port = gSerialName, baudrate = gBaudrate, bytesize = serial.EIGHTBITS, parity = serial.PARITY_NONE, stopbits = serial.ST...
import unittest from blivet.devices import DiskDevice from blivet.formats import get_format from blivet.size import Size from pyanaconda.modules.common.constants.objects import DISK_SELECTION from pyanaconda.modules.common.errors.storage import UnavailableStorageError from pyanaconda.modules.common.structures.validatio...
""" This is the Create_Modify_Interface function (along with its helpers). It is used by WebSubmit for the "Modify Bibliographic Information" action. """ __revision__ = "$Id$" import os import re import time import pprint from invenio.dbquery import run_sql from invenio.websubmit_config import InvenioWebSubmitFunctionE...
from enigma import eEPGCache, getBestPlayableServiceReference, \ eServiceReference, iRecordableService, quitMainloop from Components.config import config from Components.UsageConfig import defaultMoviePath from Components.TimerSanityCheck import TimerSanityCheck from Screens.MessageBox import MessageBox import Screens...
import unittest import mock import blivet from pykickstart.constants import CLEARPART_TYPE_ALL, CLEARPART_TYPE_LINUX, CLEARPART_TYPE_NONE from parted import PARTITION_NORMAL from blivet.flags import flags DEVICE_CLASSES = [ blivet.devices.DiskDevice, blivet.devices.PartitionDevice ] @unittest.skipUnless(not any...
from entry import Entry from blob import Entry_blob class Entry_u_boot_spl_nodtb(Entry_blob): def __init__(self, image, etype, node): Entry_blob.__init__(self, image, etype, node) def GetDefaultFilename(self): return 'spl/u-boot-spl-nodtb.bin'
''' IMPORTANT: Please turn off logging (MEASUREMENT_ENABLE = False) in constants.py before running these testbenches. ''' import unittest import reporter, node, host, link, router import flow, event_simulator, event, events import link, link_buffer, packet import constants from static_flow_test_node import * import vi...
from setuptools import setup, find_packages from os import path setup( name="lines", version="1.4.0", description="Program for plotting powder diffraction patterns and background subtraction", author="Stef Smeets", author_email="s.smeets@esciencecenter.nl", license="GPL", url="https://github...
""" [tests/stdlib/test_help.py] Test the help command. """ import unittest class TestHelp(unittest.TestCase): """Tests the 'help' command.""" def test_list_commands(self): """ Tests listing all commands using the 'help commands' command. """
""" Source : Les recettes Python de Tyrtamos http://python.jpvweb.com/mesrecettespython/doku.php?id=date_de_paques """ class jourferie: def datepaques(self,an): """Calcule la date de Pâques d'une année donnée an (=nombre entier)""" a=an//100 b=an%100 c=(3*(a+25))//4 d=(3*(a+25))...
"""Make osversion.osmajor_id non-NULLable Revision ID: 5ab66e956c6b Revises: 286ed23a5c1b Create Date: 2017-12-20 15:54:38.825703 """ revision = '5ab66e956c6b' down_revision = '286ed23a5c1b' from alembic import op from sqlalchemy import Integer def upgrade(): op.alter_column('osversion', 'osmajor_id', existing_type...
""" Functions performing URL trimming and cleaning """ import logging import re from collections import OrderedDict from urllib.parse import parse_qs, urlencode, urlparse, ParseResult from .filters import validate_url from .settings import ALLOWED_PARAMS, CONTROL_PARAMS,\ TARGET_LANG_DE, TARGET_LA...
__doc__ = """ Reads a GraphicsMagick source file and parses the specially formatted comment blocks which precede each function and writes the information obtained from the comment block into a reStructuredText file. Usage: format_c_api_docs.py [options] SRCFILE OUTFILE SRCFILE is the path to a Graphicsmagick AP...
import sys def bye(): sys.exit(40) # Crucial error: abort now! try: bye() except Exception: print('got it') # Oops--we ignored the exit print('continuing...')
if __name__ == "__main__": sum_one_hundred = sum([x for x in range(1, 101)]) sum_one_hundred_squared = sum_one_hundred * sum_one_hundred sum_squared = sum([x ** 2 for x in range(1, 101)]) solution = sum_one_hundred_squared - sum_squared print(solution)
import os import gtk import gconf from common.settings import * from common.factory import GconfKeys class Config: #FIXME The class should be generic config getter and setter __client = gconf.Client() def set_value(self, key, value): if not key.startswith("/"): key = GconfKeys.keys[key] ...
import xorn.storage rev = xorn.storage.Revision() ob0 = rev.add_object(xorn.storage.Line()) ob1, = rev.get_objects() ob2 = rev.add_object(xorn.storage.Line()) assert ob0 is not ob1 assert ob0 == ob1 assert hash(ob0) == hash(ob1) assert ob0 is not ob2 assert ob0 != ob2 assert hash(ob0) != hash(ob2) assert ob1 is not ob2...
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) exce...
__author__ = 'george' from baseclass import Plugin import time from apscheduler.scheduler import Scheduler class AreWeDone(Plugin): def __init__(self, skype): super(AreWeDone, self).__init__(skype) self.command = "arewedoneyet" self.sched = Scheduler() self.sched.start() self...
ucodes = { "U0001" : "High Speed CAN Communication Bus" , "U0002" : "High Speed CAN Communication Bus (Performance)" , "U0003" : "High Speed CAN Communication Bus (Open)" , "U0004" : "High Speed CAN Communication Bus (Low)" , "U0005" : "High Speed CAN Communication Bus (High)" , "U0006" : "High Speed CAN C...
from typing import TypeVar, Callable, List, Tuple, Optional from . import mdiff from .thirdparty import attr F = TypeVar("F") L = TypeVar("L") def annotate( base: F, parents: Callable[[F], List[F]], decorate: Callable[[F], Tuple[List[L], bytes]], diffopts: mdiff.diffopts, skip: Optional[Callable[[F]...