code
stringlengths
1
199k
import click import os import penguin.pdf as pdf import penguin.utils as utils def check_src(src): if not all((map(utils.is_valid_source, src))): raise click.BadParameter("src arguments must be either a valid directory" " or pdf file.") @click.group() def penguin(): pass...
import math def even_numbers_only(thelist): ''' Returns a list of even numbers in thelist ''' return [x for x in thelist if x%2 == 0] def is_perfect_square(x): ''' Returns True if x is a perfect square, False otherwise ''' thesqrt = int(math.sqrt(x)) return thesqrt * thesqrt == x
from __future__ import print_function import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.contrib import rnn import time from datetime import timedelta import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=T...
""" Starlet wavelet transform, i.e., isotropic undecimated wavelet transform (IUWT), or à trous wavelet transform. And multi-scale variance stabling transform (MS-VST), which can be used to effectively remove the Poisson noises. """ __version__ = "0.2.5" __date__ = "2016-04-22" import sys import os import argparse f...
def subtrees_equal(expected_schema_node, actual_node): if expected_schema_node[0] != actual_node.get_name(): return False if expected_schema_node[1] != actual_node.get_state(): return False expected_children = expected_schema_node[2] actual_children = actual_node.get_children() actual_children_names = [child.g...
import sys import string from datetime import datetime,timedelta import calendar import csv import re fp = open(sys.argv[1],'r') wfp = open('/path/to/program/csv_data/formatted.csv', 'a') writer = csv.writer(wfp, lineterminator='\n') yesterday = datetime.now() + timedelta(days=-1) print "下記の日時のログ整形データをformatted.csvに書き...
''' Precondition successfully pass a users test. ''' from datetime import datetime, timedelta import time import pytest import requests from kii import AccountType, exceptions as exc, results as rs from kii.data import BucketType, clauses as cl from tests.conf import ( get_env, get_api_with_test_user, c...
import inspect from functools import total_ordering def yield_once(iterator): """ Decorator to make an iterator yield each result only once. :param iterator: Any iterator :return: An iterator that yields every result only once at most. """ def yield_once_generator(*args, **kwargs): ...
def count_inversion(sequence): flag, answer, sequence = True, 0, list(sequence) while flag: flag = False for i in xrange(1, len(sequence)): if sequence[i-1] > sequence[i]: sequence[i], sequence[i-1] = sequence[i-1], sequence[i] answer += 1 ...
from datetime import datetime from .base import BaseModel class Comment(BaseModel): def __init__(self, **kwargs): # Add created and updated attrs by default. self.created = self.updated = datetime.now() super().__init__(**kwargs) def update(self): """ Extends update method to upd...
import json import httplib2 import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) sys.stderr = codecs.getwriter('utf8')(sys.stderr) foursquare_client_id = 'SMQNYZFVCIOYIRAIXND2D5SYBLQUOPDB4HZTV13TT22AGACD' foursquare_client_secret = 'IHBS4VBHYWJL53NLIY2HSVI5A1144GJ3MDTYYY1KLKTMC4BV' google_api_key ...
""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import serialize from twilio.base import values from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from ...
from flask.ext.wtf import Form from wtforms import IntegerField, StringField, FieldList from wtforms.validators import DataRequired, Email, ValidationError def word_length(limit=None, message=None): message = message or 'Must not be more than %d words' message = message % limit def _length(form, field): ...
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="color", parent_name="icicle.outsidetextfont", **kwargs ): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=par...
from . import tree class Node: def __init__(self, container, parent, value=None): self._node = tree.Node(container, parent, value) @property def _container(self): return self._node._container @property def id(self): return self._node.id @property def value(self): ...
import h2o import numpy as np import pandas as pd from h2o.estimators.gbm import H2OGradientBoostingEstimator from h2o.estimators.random_forest import H2ORandomForestEstimator from h2o.grid.grid_search import H2OGridSearch import sys from operator import add from pyspark import SparkContext from pyspark.sql import Spar...
import sys import ctypes def popcount(N): if sys.platform.startswith('linux'): libc = ctypes.cdll.LoadLibrary('libc.so.6') return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N)) elif sys.platform == 'darwin': libc = ctypes.cdll.LoadLibrary('libSystem.dylib') ...
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ def fill(n): if n == l: result.append(''.join(combination)) return for cs in ds[digits[n]]: for c ...
import unittest from numpy import arange, linspace from numpy.random import seed from src.bases.root import Root from src.examples.example_setups import setup_stat_scm from src.utils.sem_utils.toy_sems import StationaryDependentSEM as StatSEM from src.utils.sequential_intervention_functions import get_interventional_gr...
import io import functools import hashlib import hmac import logging import os import re import shlex import shutil import stat import subprocess import urllib.parse import uuid import werkzeug import zipfile from . import app, config, models from urllib.parse import urlparse from flask import request, session, redirec...
import hmac import json import urllib.parse import subprocess from .main import ( PullReqState, parse_commands, db_query, INTERRUPTED_BY_HOMU_RE, synchronize, ) from . import utils from . import gitlab from .utils import lazy_debug import jinja2 import requests import pkg_resources from bottle impor...
""" test_python_2d_ns ---------------------------------- Tests for `python_2d_ns` module. """ import sys import unittest from python_2d_ns.python_2d_ns import * class TestPython_2d_ns(unittest.TestCase): #test x, y coordinates generated by function IC_coor #assume use 2 threads and rank==1 #y coordinate sho...
from gimpfu import * def bdfix(image, drawable, w0, c0, w1, c1): # for Undo pdb.gimp_context_push() pdb.gimp_image_undo_group_start(image) # border-0 pdb.gimp_image_resize(image, image.width + w0*2, image.height + w0*2, w0, w0) cz = pdb.gimp_context_get_background() pdb.gimp_context_set_background(c0) p...
""" Django settings for turbo project. Generated by 'django-admin startproject' using Django 1.11.1. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import datetime...
from distutils.core import Extension from collections import defaultdict def get_extensions(): import numpy as np exts = [] # malloc mac_incl_path = "/usr/include/malloc" cfg = defaultdict(list) cfg['include_dirs'].append(np.get_include()) cfg['include_dirs'].append(mac_incl_path) cfg['i...
from frappe.model.document import Document class WorkspaceShortcut(Document): pass
N = int(input()) ans = [0] * N for i in range(0, N, 5): q = [0] * N for j in range(i, min(N, i + 5)): q[j] = 10 ** (j - i) print('? {}'.format(' '.join(map(str, q))), flush=True) S = str(int(input().strip()) - sum(q) * 7)[::-1] for j in range(i, min(N, i + 5)): ans[j] = (int(S[j - i]...
import glob import json from os.path import basename, dirname, realpath from BeautifulSoup import BeautifulSoup from flask import Response, request, render_template, send_from_directory from annotaria import app from store import Store app.config.from_object(__name__) app.config.update(dict( SPARQL_ENDPOINT="http:/...
import curses from cursesmenu import clear_terminal from cursesmenu.items import MenuItem class ExternalItem(MenuItem): """ A base class for items that need to do stuff on the console outside of curses mode. Sets the terminal back to standard mode until the action is done. Should probably be subclassed....
from .voxel_dir import task_dir, storage_dir, image_dir
""" Contains a few template tags relating to autotags Specifically, the autotag tag itself, and the filters epoch and cstag. """ from django import template from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from tags.models import Tag import datetime import calendar import types...
import os from .. import OratorTestCase from . import IntegrationTestCase class MySQLIntegrationTestCase(IntegrationTestCase, OratorTestCase): @classmethod def get_manager_config(cls): ci = os.environ.get("CI", False) if ci: database = "orator_test" user = "root" ...
from __future__ import print_function from PIL import Image import os import sys class Interval(object): def __init__(self, interval="0"): self.setinterval(interval) def setinterval(self, interval): self.hilo = [] for s in interval.split(","): if not s.strip(): ...
import json, random, time, sys """ Creating a random JSON object based on lists of info and random numbers to assign the index """ input_file = "test.json" def process_message(outcome, file_name, operation_type): print "*******%s File: %s %s *******" % (outcome, file_name, operation_type) try: open_file=open...
import tkinter import PIL.Image import PIL.ImageTk from tkinter.ttk import Progressbar as pbar from PyFont import Font, SVG class TkFont(): CHARY = 200 CHARX = 50 LINEY = CHARY / 2 MAIN_COLOR = '#FFFFFF' def set_label(self): tmp = self.words[-1].export_png_to_str() photoImg = PIL.Ima...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('computing', '0004_auto_20141127_1425'), ] operations = [ migrations.CreateModel( name='Subnet', fields=[ ('id', m...
string = """ Twinkle, twinkle, little star, \t\tUp above the world so high, \t\tLike a diamond in the sky. Twinkle, twinkle, little star, \tHow I wonder what you are """ print string
"""Test the print-to-python-file module This just uses the simpleparsegrammar declaration, which is parsed, then linearised, then loaded as a Python module. """ import os, unittest import test_grammarparser testModuleFile = 'test_printers_garbage.py' class PrintersTests(test_grammarparser.SimpleParseGrammarTests): def...
import numpy as np import pytest from nilabels.tools.image_colors_manipulations.relabeller import relabeller, permute_labels, erase_labels, \ assign_all_other_labels_the_same_value, keep_only_one_label, relabel_half_side_one_label def test_relabeller_basic(): data = np.array(range(10)).reshape(2, 5) relabel...
class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ low, high = 0, len(nums) - 1 while low <= high: mid = (low + high) / 2 if nums[mid] < target: ...
''' plot the results from the files igraph_degree_assort_study and degree_assortativity ''' from igraph import * import os import numpy as np import matplotlib.pyplot as plt IN_DIR = '/home/sscepano/Projects7s/Twitter-workspace/ALL_SR' img_out_plot = "7MOda_unweighted.png" def read_in_res(): f = open('7MODeg_assort_s...
import shelve """ Currently unused. All mysql queries are now done via IomDataModels. May be resurrected to help with shelve and pickles """ from USCProjectDAOs import IOMProjectDAO class IOMService(IOMProjectDAO): """ This handles interactions with the IOM data database and storage files. All user applicat...
from direction import Direction, Pivot from charcoaltoken import CharcoalToken as CT from unicodegrammars import UnicodeGrammars from wolfram import ( String, Rule, DelayedRule, Span, Repeated, RepeatedNull, PatternTest, Number, Expression ) import re from math import floor, ceil def FindAll(haystack, needle): ...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('booking', '0017_auto_20150309_1910'), ] operations = [ migrations.AlterField( model_name='booking', name='date', fiel...
""" file: __main__.py Description: the entry point to SEM. author: Yoann Dupont MIT License Copyright (c) 2018 Yoann Dupont 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, incl...
from django.conf.urls import patterns, include, url from darkoob.book import views as book_views urlpatterns = patterns('', url(r'^(?P<book_id>\d+)/(?P<book_title>[a-zA-Z0-9\-_]+)/$', book_views.page, name='book_page'), url(r'^look/$', book_views.book_lookup), url(r'^author/$', book_views.author_lookup), ...
""" Django settings for testproject 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__)) SECRET_KE...
""" The consumer's code. It takes HTML from the queue and outputs the URIs found in it. """ import asyncio import json import logging from typing import List from urllib.parse import urljoin import aioredis from bs4 import BeautifulSoup from . import app_cli, redis_queue _log = logging.getLogger('url_extractor') def _s...
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Legendgrouptitle(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "histogram2d" _path_str = "histogram2d.legendgrouptitle" _valid_props = {"font", "text...
from dataclasses import dataclass, field import itertools import logging import os import numpy as np import torch from fairseq import metrics from fairseq.data import ( ConcatDataset, ConcatSentencesDataset, data_utils, Dictionary, IdDataset, indexed_dataset, NestedDictionaryDataset, Nu...
"""Docstring violation definition.""" from collections import namedtuple from functools import partial from itertools import dropwhile from typing import Any, Callable, Iterable, List, Optional from .parser import Definition from .utils import is_blank __all__ = ('Error', 'ErrorRegistry', 'conventions') ErrorParams = n...
from typing import List, Optional from fastapi import FastAPI, Header app = FastAPI() @app.get("/items/") async def read_items(x_token: Optional[List[str]] = Header(None)): return {"X-Token values": x_token}
import yaml import tornado.web import elephunk.handlers import elephunk.database import elephunk.ui_methods import elephunk.ui_modules def create(port, debug, config_file): with open(config_file, 'r') as f: config = yaml.load(f.read()) application = tornado.web.Application( elephunk.handlers.han...
try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.md').read() with open('requirements.txt') as reqs: requirements = reqs.read().split() setup( name='pagseguro', version='0.3.4', description='Pagseguro API v2 wrapper', author='Bruno R...
from rest_framework import serializers def serializer_factory(model, serializer_class=serializers.ModelSerializer, attrs=None, meta=None): """ Generate a simple serializer for the given model class. :param model: Model class :param serializer_class: Serializer base class :param attrs: Serializer cla...
from django.conf.urls import url from profiles import views urlpatterns = [ url( regex=r"^edit/$", view=views.ProfileEditUpdateView.as_view(), name="profile_edit" ), url( regex="^confirm_role/(?P<membership_id>[-\w]+)/(?P<action>verify|deny)/$", view=views.profile_con...
from . import NamedEntity class Application(NamedEntity): def __init__(self, name, provider): NamedEntity.__init__(self, name) self.provider = provider def get_descendants(self): return []
from shuttl.tests import testbase from shuttl.Models.User import User, UserDataTakenException, NoOrganizationException, ToManyOrganizations from shuttl.Models.organization import Organization from shuttl.Models.Reseller import Reseller class UserTestCase(testbase.BaseTest): def _setUp(self): self.reseller =...
import ababe import sys, ast import click import yaml from ababe.cmdline.apps import * def run(): try: ababe.cmdline.runabalib.exec_from_cmdline() except KeyboardInterrupt: pass except EOFError: pass @click.group() @click.version_option(version='0.1.0') def exec_from_cmdline(): p...
""" Provide a common way to import Qt classes used by pytest-qt in a unique manner, abstracting API differences between PyQt5 and PySide2/6. .. note:: This module is not part of pytest-qt public API, hence its interface may change between releases and users should not rely on it. Based on from https://github.com/epage/...
""" Test suite for django-staticshard. """ import uuid from urlparse import urlparse from django.conf import settings from django.test import TestCase from django.core.exceptions import ImproperlyConfigured from ..settings import STATICSHARD_HOSTS from ..utils import get_absolute_url class StaticShardTests(TestCase): ...
from __future__ import unicode_literals from sqlalchemy import create_engine, Column, ForeignKey, Integer, String,\ Boolean, Unicode, Date, DateTime, and_, func from sqlalchemy.orm import relationship, backref, sessionmaker from sqlalchemy.engine.url import URL from sqlalchemy.ext.declarative import declarative_bas...
from indico.core.db import db from indico.util.string import format_repr class SuggestedCategory(db.Model): __tablename__ = 'suggested_categories' __table_args__ = {'schema': 'users'} user_id = db.Column( db.Integer, db.ForeignKey('users.users.id'), primary_key=True, index=Tr...
from flask import Flask, jsonify, request app = Flask(__name__) from charge.chargeManager import ChargeManager from data.dataProvider import DataProvider @app.route('/') def hello_world(): return jsonify(testPreMa(['棉花'],20)) @app.route('/result') def get_result(): name = request.args.get('name').encode('utf-8'...
import itertools import os import os.path as osp import chainer import numpy as np import scipy.misc from sklearn.model_selection import train_test_split from base import APC2016DatasetBase def ids_from_scene_dir(scene_dir, empty_scene_dir): for i_frame in itertools.count(): empty_file = osp.join( ...
import os import socket import struct from OpenSSL import SSL from mitmproxy import exceptions from mitmproxy import flow from mitmproxy.proxy.protocol import base from mitmproxy.net import tcp from mitmproxy.net import websockets from mitmproxy.websocket import WebSocketFlow, WebSocketBinaryMessage, WebSocketTextMessa...
from __future__ import absolute_import, division, print_function from builtins import (bytes, str, open, super, range, zip, round, input, int, pow, object) import unittest from python_uptimer import up_check import requests from datetime import timedelta class MyTestCase(unittest.TestCase): de...
import stripe import json from django.conf import settings from django.http import HttpResponse from django.shortcuts import render from django.views.generic import TemplateView, DetailView, ListView from carton.cart import Cart from .models import Sale, SaleProduct, SaleError from products.models import Product class ...
from sys import argv from GeekToolKickassTorrentFeed import GeekToolKickassTorrentFeed if __name__ == "__main__" and len(argv) > 1: mode = argv[1] print(str.format("{0}{1}", "\t" * 4, mode.capitalize())) feed = GeekToolKickassTorrentFeed(mode) if feed: feed_data = feed.get_top_seeded_torrents()....
"""empty message Revision ID: 02ccb3e6a553 Revises: None Create Date: 2016-05-17 22:15:03.881575 """ revision = '02ccb3e6a553' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('roles', sa.Column('id...
""" Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; ot...
import math import sys base = -2.0 result = "" number = int(sys.argv[1]) print "converting number " + str(number) + " to negabinary value:" while number != 0: ceilOfDivision = int(math.ceil(number / base)) reminder = int(number % base) result = result + str(int(math.fabs(reminder))) number = ceilOfDivis...
import mt import queue import _thread import time class DummySocket: def __init__(self, ID): self.id = ID self.lastMsg = "" def send(self, msg): print(self.id+":",msg) self.lastMsg = msg def close(self): print(self.id+": CLOSE CALLED") self.lastMsg = "CLOSED" ...
"""Pytrafikverket module.""" from pytrafikverket.trafikverket import (AndFilter, FieldFilter, FieldSort, Filter, FilterOperation, NodeHelper, OrFilter, SortOrder, Trafikverket) from pytrafikverket.trafikverket_train import (StationInfo, T...
''' __ ___________________________________________ | \ ||______ | |______|_____||______|______ | \_||______ | |______| |______||______ ________ __________________________ _____ _ _ | | || ||______ | | |_____]| | \___/ | | ||_____|______|__|__|_____ |_____]|_____|_/ \_ + ---...
from __future__ import unicode_literals from django.contrib import admin from core.models import Post from core.models import Category from core.models import Comment from core.models import Tag from core.forms import PostForm @admin.register(Post) class PostAdmin(admin.ModelAdmin): # raw_id_fields = ('tags',) ...
def palindrome(test): while len(test) > 2: if test[0] == test[-1]: test = test.rstrip(test[-1]) test = test.lstrip(test[0]) else: return False if test[0] == test[-1]: return True def palindrome2(test): if test == "".join(reversed(test)): re...
""" Prosta klasa reprezentująca posiłek składający się z wielu innych obiektów jadalnych. """ class BigMeal: def __init__(self, edibles): # TODO: zainicjuj obiekt przekazaną listą obiektów jadalnych # "edibles" def get_name(self): # TODO: zaimplementuj metodę zwracającą nazwę obiektu ...
from operator import add f = sc.textFile("data/README.md") wc = f.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add) wc.saveAsTextFile("wc_out")
import json import csv import codecs import uuid from cloudant.client import Cloudant from cloudant.result import Result, ResultByKey, QueryResult from cloudant.query import Query f = open('cloudant_credentials_id.json', 'r') cred = json.load(f) f.close() print cred f = open('database_name.json', 'r') dbn = json.load(f...
from txzookeeper.client import ZookeeperClient from txzookeeper.retry import RetryClient import zookeeper import sys from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA import os from twisted.python import log from twisted.internet import reactor, defer log.startLogging(sys.stdout) class Config(): """ ...
"""The module implements the linux specific address resolution plugin.""" __author__ = "Michael Cohen <scudette@gmail.com>" import re from rekall import obj from rekall.plugins.common import address_resolver from rekall.plugins.linux import common class LKMModule(address_resolver.Module): """A Linux kernel module."...
from lmc import * from mpi4py import MPI mpi_rank = MPI.COMM_WORLD.Get_rank() from numpy.random import rand startx = [-10.0, -10.0, 10.0, 10.0] starty = [-10.0, 10.0, -10.0, 10.0] x = Parameter(name='x', value=startx[mpi_rank], width=0.1) y = Parameter(name='y', value=starty[mpi_rank], width=0.1) class Thing: def _...
import time import pyslurm def reservation_display(reservation): if reservation: for key,value in reservation.items(): print("\t{}={}".format(key, value)) if __name__ == "__main__": try: end = time.time() start = end - (30*24*60*60) print("start={}, end={}".format(star...
from math import * import sys import string k = (sqrt(2.)-1.)*4./3. chars = [] encoding = [] count = 1 first = 1 def append(s): chars.append(s) def rint(x): return int(round(x)) """ if x>=0: return int(x+0.5) else: return int(x-0.5) """ class vec: def __init__(self, x, y=0): if type(x) is ...
from Plugins.Plugin import PluginDescriptor from Screens.Console import Console from Screens.ChoiceBox import ChoiceBox from Screens.MessageBox import MessageBox from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Screens.Ipkg import Ipkg from Screens.SoftwareUpdate import UpdatePlugin fr...
""" *************************************************************************** utils.py --------------------- Date : November 2009 Copyright : (C) 2009 by Martin Dobias Email : wonder dot sk at gmail dot com *************************************************...
"""tifis_platform URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Cla...
item_id = 4986168 user_id = 20000 item_category = 9656 time = 31
""" """ import os, sys import cgi import cgitb; cgitb.enable() """ Small function that adds pxStats to the sys path. """ sys.path.insert(1, sys.path[0] + '/../../..') from pxStats.lib.StatsPaths import StatsPaths from pxStats.lib.LanguageTools import LanguageTools """ Small method required to add pxLib to syspa...
import sys import getopt import time import os DATA_DIR='/local/devel/guppy/testing/' opts, args = getopt.getopt(sys.argv[1:], 'c:t') transfer = False listdir = False for opt, optarg in opts: if opt == '-c': if optarg == 'get' or optarg == 'put': transfer = True if optarg == 'dir': listdir = True if optarg...
from SipGenericHF import SipGenericHF class SipReplaces(SipGenericHF): hf_names = ('replaces',) call_id = None from_tag = None to_tag = None early_only = False params = None def __init__(self, body = None, call_id = None, from_tag = None, to_tag = None, \ early_only = False, params = N...
import os from os.path import join, getsize from random import randint def addEntry (XMLFile, finfo, dirs, NASPath): #finfo[1].replace(' ', '_') finfo[1] = finfo[1].replace('.', '_', finfo.count('.')-1) title = finfo[1].split('.')[0] root = '' genre = 'Tom and Frederika' pathlist = finfo[0].spli...
def comb(xs): if len(xs) == 0: return [""] else: return comb2(xs) + [""] def comb2(xs): if len(xs) == 1: return [ xs ] else: subwo = comb2( xs[1:] ) head = xs[0] subwith = [ head + zs for zs in subwo ] return subwo + subwith + [ head ] result = com...
from datetime import date import sys import os extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'sympa' copyright = u'%s, Direction Informatique' % date.today().strftime("%Y") version = '0.1' release = '0.1' exclu...
from __future__ import print_function import datetime import glob import os import re import sys import subprocess from picard import __version__, compat if sys.version_info < (2, 6): print("*** You need Python 2.6 or higher to use Picard.") args = {} try: from py2app.build_app import py2app do_py2app = Tru...
from django.conf.urls import url, patterns from rango import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^about/$', views.about, name='about'), # 匹配URL斜杠前所有的字母数字 # 例如 a-z, A-Z, 或者 0-9)和连字符(- # 然后把这个值作为category_name_slug参数传递给views.category(), url(r'^category/(?P<...
__author__ = 'ramuta' a = 1 b = 2 if a < b: a = b print a print b """ Java equivalent if (a < b) { a = b; } If you delete parenthesis, brackets and semicolons you get python. """
from celery import Celery from datetime import timedelta import os BROKER_URL = 'redis://localhost:6379/0' celery = Celery('EOD_TASKS', broker=BROKER_URL) celery.config_from_object('celeryconfig') CELERY_RESULT_BACKEND = 'redis' CELERY_IMPORTS = ("task",) CELERYBEAT_SCHEDULE = { 'fetch-tweets': { 'task': 't...
from os.path import join, isfile from uuid import uuid4 from seecr.test import SeecrTestCase, CallTrace from weightless.core import be, asString, consume, NoneOfTheObserversRespond, retval from meresco.core import Observable from meresco.distributed.constants import WRITABLE, READABLE from meresco.distributed.utils imp...