repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
david-hoffman/scripts | colormaps.py | Python | apache-2.0 | 1,832 | 0.000546 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# __init__.py
"""
Convert colormaps to amira format
Copyright (c) 2018, David Hoffman
"""
import os
import matplotlib.cm
import colorcet
header = """# AmiraMesh 3D ASCII 2.0
define Lattice {N:d}
Parameters {{
ContentType "Colormap"
MinMax 0 {N:d}{extra:}
}}
L... | {
"Pastel1",
"Pastel2",
"Paired",
"Accent",
"Dark2",
"Set1",
"Set2",
"Set3",
"tab10",
"tab20",
"tab20b",
"tab20c",
}
for cmap_name, cmap in matplotlib.cm.cmap_d.items():
if cmap_name in qualitative:
... | ve")
else:
extra = ""
print(cmap_name)
cm_to_amira(cmap, "colormaps/" + cmap_name, extra=extra)
for cmap_name, cmap in colorcet.cm.items():
cm_to_amira(cmap, "colormaps/" + cmap_name, extra="")
print(cmap_name)
|
CountZer0/PipelineConstructionSet | python/maya/site-packages/pymel-1.0.5/pymel/core/context.py | Python | bsd-3-clause | 152 | 0.019737 | """
Contains | all context command functions (previously 'ctx').
"""
impo | rt pymel.internal.factories as _factories
_factories.createFunctions( __name__ ) |
edfungus/Music-Server | app/db_create.py | Python | apache-2.0 | 466 | 0.008584 | from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE... | ASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
| |
LLNL/spack | var/spack/repos/builtin/packages/py-epydoc/package.py | Python | lgpl-2.1 | 516 | 0.001938 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyEpydoc(PythonPackage):
"""Epydoc is a tool for generating API documentation documentatio... | ased on their docstrings."""
pypi = "epydoc/epydoc-3.0.1.tar.gz"
version('3.0.1', sha256='c81469b853fab06ec42b39e35 | dd7cccbe9938dfddef324683d89c1e5176e48f2')
|
usc-isi/extra-specs | nova/db/sqlalchemy/migrate_repo/versions/097_quota_usages_reservations.py | Python | apache-2.0 | 4,073 | 0.000491 | # Copyright 2012 OpenStack LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
mysql_charset='utf8',
)
try:
quota_usages.create()
except Exception:
LOG.error(_("Table |%s| not created!"), repr(quota_usages))
raise
reservations = Table('reservations', meta,
Column('created_at', DateTime(timezone=False)),
Column(... | (timezone=False)),
Column('deleted_at', DateTime(timezone=False)),
Column('deleted', Boolean(create_constraint=True, name=None)),
Column('id', Integer(), primary_key=True),
Column('uuid',
String(length=36, convert_unicode=True,
... |
google/megalista | megalista_dataflow/uploaders/google_ads/customer_match/mobile_uploader.py | Python | apache-2.0 | 1,938 | 0.006708 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | list_name = destination_metadata[0]
app_id = account_config.app_id
#overwrite app_id from default to custom
i | f len(destination_metadata) >=4 and len(destination_metadata[3]) > 0:
app_id = destination_metadata[3]
return {
'membership_status': 'OPEN',
'name': list_name,
'description': 'List created automatically by Megalista',
'membership_life_span': 10000,
'crm_based_user_list': {
... |
utkarsh009/anita | anita.py | Python | isc | 82,722 | 0.004872 | #
# This is the library part of Anita, the Automated NetBSD Installation
# and Test Application.
#
import os
import pexpect
import re
import string
import subprocess
import sys
import time
import urllib
import urlparse
__version__='1.43'
# Your preferred NetBSD FTP mirror site.
# This is used only by the obsolete co... | directory tree
# rooted at "urlbase" into a mirror tree rooted at "dirbase". The
# file name to download is "relfile", which is relative to both roots.
def download_if_missing(urlbase, dirbase, relfile, optional = False):
url = urlbase + relfile
file = os.path.join(dirbase, relfile)
return download_if_mi... | (url, file, optional)
def download_if_missing_3(urlbase, dirbase, relpath, optional = False):
url = urlbase + "/".join(relpath)
file = os.path.join(*([dirbase] + relpath))
return download_if_missing_2(url, file, optional)
# Map a URL to a directory name. No two URLs should map to the same
# directory.
d... |
anatolikalysch/VMAttack | lib/VmInstruction.py | Python | mit | 33,455 | 0.004125 | # -*- coding: utf-8 -*-
"""
@author: Tobias Krauss
"""
from lib.Instruction import Instruction
import lib.PseudoInstruction as PI
import lib.StartVal as SV
from lib.PseudoInstruction import (PseudoInstruction,
PseudoOperand)
from lib.Register import (get_reg_class,
... | 0xffff0000 + catch_value
| elif SV.dissassm_type == SV.ASSEMBLER_64:
catch_value = 0xffffffffffff0000 + catch_value
elif reg_size == 32 and catch_value > 0x79000000:
#there is nothing to do for 32bit
if SV.dissassm_type == SV.ASSEMBLER_64:
catch_value = 0xffffffff00000000... |
bitemyapp/ganeti | test/py/ganeti.tools.node_daemon_setup_unittest.py | Python | bsd-2-clause | 2,901 | 0.002068 | #!/usr/bin/python
#
# Copyright (C) 2012 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of... | in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE C | OPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SP... |
lemonad/my-django-skeleton | setup.py | Python | bsd-2-clause | 930 | 0.029032 | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "my-django-skeleton",
version = "0.1",
url = 'http://github.com/lemonad/my-django-skeleton',
license = 'BSD',
description = "A skeleton setup ... | 'src'},
install_requires = ['setuptools'],
classifiers = [
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Pytho... | ',
'Topic :: Internet :: WWW/HTTP',
]
)
|
alexandermendes/pybossa-gravatar | tests/test_plugin.py | Python | bsd-3-clause | 3,949 | 0 | # -*- coding: utf8 -*-
import os
import hashlib
import pybossa_gravatar
from mock import patch, MagicMock
from factories import UserFactory
from default import Test, with_context
from helper import web
class TestEventListener(Test):
@with_context
@patch('pybossa_gravatar.event_listeners.gravatar.set', retur... | thorized_to', return_value=True)
@patch('pybossa_gravatar.view.user_repo')
@patch('pybossa_gravatar.view.gravatar.set', return_value=True)
def test_authorised_user_can_set_gravatar(self, mock_set, mock_repo,
ensure_authorized_to):
mock_user = MagicMock()... | mat(self.name),
follow_redirects=True)
assert mock_set.called_with(mock_user)
class TestGravatar(Test):
@with_context
@patch('pybossa_gravatar.gravatar_client.secure_filename',
return_value=True)
@patch('pybossa_gravatar.gravatar_client.user_repo')
@patc... |
shuhuage/fts | eroption/query_symbol.py | Python | bsd-3-clause | 7,555 | 0.019457 |
import datetime
from bs4 import BeautifulSoup
import urllib2
import sys, traceback, getopt
import re
#**********************************
#Exception classes
#**********************************
class Error(Exception): """Base class for exceptions in this module."""; pass
class DateNotAvailableError(Error): pass
cla... | mpany_name = self.soup_table('tr')[i].td.string
tp_index += 1
if tp_index > 100:
break
except:
company_name = "N.A."
try:
symbol_ticker = self.soup_table('tr')[i].a.string
except:
symb... | before_after = "N.A."
except:
before_after = "N.A."
if symbol_ticker.isalpha() and not symbol_ticker.__contains__("."):
self.earnings_data.append(((company_name),(symbol_ticker),(before_after),(self._today),(self._date_earnings)))
... |
danithaca/berrypicking | django/mysite-1.6/mysite/views.py | Python | gpl-2.0 | 241 | 0.008299 | from django.contrib.auth.models imp | ort User
from django.contrib.auth.views import login
from django.http impor | t HttpResponse
import json
def home(request):
return HttpResponse("hello, %s" % str(request.user))
#return login(request) |
djt5019/episode_renamer | eplist/__init__.py | Python | unlicense | 477 | 0 | # | -*- coding: utf-8 -*-
from __future__ import unicode_literals
__author__ = 'Dan Tracy'
__email__ = 'djt5019 at gmail dot com'
__version__ = '0.1.7'
import atexit
import os
from eplist import utils
from eplist import logger
from eplist import constants
if not os.path.exists(constants.resource_path):
utils.init_... | )
|
ChrisHirsch/robotframework | src/robot/running/usererrorhandler.py | Python | apache-2.0 | 1,478 | 0.000677 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | l
tests in affected test case file from executing. Instead UserErrorHandler
is created and if it is ever run DataError is raised then.
"""
type = 'error'
def __init__(self, name, error, libname=None):
self.name = name
self.libname = libname
self.doc = self.shortdoc = ''
... |
@property
def longname(self):
return '%s.%s' % (self.libname, self.name) if self.libname else self.name
def init_keyword(self, varz):
pass
def run(self, *args):
raise DataError(self.error)
|
mvaled/sentry | src/sentry/web/frontend/base.py | Python | bsd-3-clause | 20,548 | 0.001655 | from __future__ import absolute_import
import logging
import six
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.http import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseNotFound,
HttpResponseRedirect,
)
from django.middleware.csrf import... |
2. If self.csrf_protect is set, we will re-run the CSRF check ourselves
using CsrfViewMiddleware().process_view | ()
3. But first we must remove the csrf_exempt attribute that was set by
the decorator so that the middleware doesn't shortcut and pass the
check unconditionally again.
"""
if self.csrf_protect:
if hasattr(self.dispatch.__func__, "csrf_exempt"):
... |
indictranstech/biggift-erpnext | erpnext/hooks.py | Python | agpl-3.0 | 4,979 | 0.016067 | from __future__ import unicode_literals
from frappe import _
app_name = "erpnext"
app_title = "ERPNext"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = """ERP made simple"""
app_icon = "icon-th"
app_color = "#e74c3c"
app_version = "6.13.1"
app_email = "info@erpnext.com"
app_license = "GNU General Pub... | "Price List": {
"on_update": "erpnext.shopping_cart.doctype.shopping_cart_settings.shopping_cart_settings.validate_cart_settings"
},
"Address": {
"validate": "erpnext.shopping_cart.cart.set_customer_in_address"
}
}
scheduler_events = {
"hourly": [
"erpnext.controllers.recurring_document.create_recurring_docu... | m",
"erpnext.setup.doctype.email_digest.email_digest.send",
"erpnext.support.doctype.issue.issue.auto_close_tickets",
"erpnext.accounts.doctype.fiscal_year.fiscal_year.auto_create_fiscal_year",
"erpnext.hr.doctype.employee.employee.send_birthday_reminders",
"erpnext.projects.doctype.task.task.set_tasks_as_ove... |
iamweilee/pylearn | os-spawn-example-2.py | Python | mit | 778 | 0.007712 | '''
spawn º¯Êý»¹¿ÉÓÃÓÚÔÚºǫ́ÔËÐÐÒ»¸ö³ÌÐò. ÏÂÀýÖÐ ¸ø run º¯ÊýÌí¼ÓÁËÒ»¸ö¿ÉÑ¡µÄ mode ²ÎÊý;
µ±ÉèÖÃΪ os.P_NOWAIT ʱ, Õâ¸ö½Å±¾²»»áµÈ´ý×Ó³ÌÐò½áÊø, ĬÈÏÖµ os.P_WAIT ʱ spawn »áµÈ´ý×Ó½ø³Ì½áÊø.
ÆäËüµÄ±êÖ¾³£Á¿»¹ÓÐ os.P_OVERLAY ,ËüʹµÃ spawn µÄÐÐΪºÍ exec ÀàËÆ, ÒÔ¼° os.P_DETACH , ËüÔÚºǫ́ÔËÐ | Ð×Ó½ø³Ì, Ó뵱ǰ¿ØÖÆÌ¨ºÍ¼üÅ̽¹µã¸ôÀë.
'''
import os
import string
def run(program, *args, **kw):
# find executable
mode = kw.get("mode", os.P_WAIT)
for path in string.split(os.environ["PATH"], os.pathsep):
file = os.path.join(path, program) + ".exe"
try:
return os.spawnv(mode, f... | NOWAIT)
print "goodbye" |
treasure-data/td-client-python | tdclient/user_model.py | Python | apache-2.0 | 860 | 0 | #!/usr/bin/env python
from tdclient.model import Model
class User(Model):
"""User on Treasure Data Service
"""
def __init__(self, client, name, org_name, role_names, email, **kwargs):
super(User, self).__init__(client)
self._name = name
self._org_name = org_name
self._rol... | name(self):
"""
Returns: name of the user
"""
return self._name
@pr | operty
def org_name(self):
"""
Returns: organization name
"""
return self._org_name
@property
def role_names(self):
"""
TODO: add docstring
"""
return self._role_names
@property
def email(self):
"""
Returns: e-mail add... |
pnwairfire/blueskyutils | blueskyutils/bsf2wrfchem/speciation.py | Python | gpl-3.0 | 5,442 | 0.000184 | BSF2FINN_SPECIATION_FACTORS = {
"1": {
"MOZ4_Species": "Savanna/ Grasslands",
"NO": "0.26",
"NO2": "0.74",
"BIGALD": "0.02",
"BIGALK": "0.2",
"BIGENE": "0.45",
"C10H16": "0.01",
"C2H4": "2.27",
"C2H5OH": "0.02",
"C2H6": "0.82",
... | "BIGALD": "0.01",
"BIGALK": "0.13",
"BIGENE": "0.52",
"C10H16": "0.04",
"C2H4": "1.38",
"C2H5OH": "0.01",
"C2H6": "0.82",
"C3H6": "0.56",
"C3H8": "0.1",
"CH2O": "2.08",
"CH3CHO": "1.27",
"CH3CN": "0.36",
"CH3COCH3": "0... | "0.56",
"HYAC": "0.55",
"ISOP": "0.07",
"MACR": "0.08",
"MEK": "0.85",
"MVK": "0.2",
"TOLUENE": "2.06",
"HCOOH": "0.44",
"C2H2": "0.36"
},
"4": {
"MOZ4_Species": "Temperate Forest",
"NO": "0.16",
"NO2": "0.84",
"BIG... |
pombredanne/milk | milk/tests/fast_classifier.py | Python | mit | 821 | 0.007308 | import numpy as np
from milk.supervised.base import supervised_model
class fast_classifier(object):
def __init__(self):
pass
def set_option(self, _k, _v):
pass
def train(self, features, labels, **kwargs):
examples = {}
for f,lab in zip(features, labels):
if lab ... | t_model(supervised_model):
def __init__(self, examples):
self.examples = examples
assert len(self.examples)
def apply(self, f):
best = None
best_val = +np.inf
for k,v in self.examples.items():
d = v-f
dist = np.dot(d,d)
if dist < best_... | best = k
best_val = dist
return best
|
scholer/cadnano2.5 | cadnano/views/pathview/strand/endpointitem.py | Python | mit | 22,478 | 0.002046 | # -*- coding: utf-8 -*-
from math import floor
from typing import (
Tuple,
Any
)
from PyQt5.QtCore import (
QPointF,
QRectF,
Qt
)
from PyQt5.QtGui import (
QBrush,
QPen,
QPainterPath,
QPolygonF,
QMouseEvent,
QPainter
)
from PyQt5.QtWidgets import (
qApp,
QGraphicsIte... | WIDTH, 0))
POLY_53.append(QPointF(_BASE_WIDTH, 0.5 * _BASE_WIDTH))
POLY_53.append(QPointF(0.5 * _BASE_WIDTH, _BASE_WIDTH))
PP_53.addPolygon(POLY_53)
# single base left 3'<-5'
PP_35.addRect(0.50 * _BASE_WIDTH,
0.125 * _BASE_WIDTH,
0.5 * _BASE_WIDTH,
0.75 * _BASE_WIDTH)
P | OLY_35 = QPolygonF()
POLY_35.append(QPointF(0.5 * _BASE_WIDTH, 0))
POLY_35.append(QPointF(0, 0.5 * _BASE_WIDTH))
POLY_35.append(QPointF(0.5 * _BASE_WIDTH, _BASE_WIDTH))
PP_35.addPolygon(POLY_35)
_DEFAULT_RECT = QRectF(0, 0, _BASE_WIDTH, _BASE_WIDTH)
_NO_PEN = QPen(Qt.NoPen)
MOD_RECT = QRectF(.25*_BASE_WIDTH, -.25*_BA... |
Invoicy/invoicy | wsgi.py | Python | mit | 138 | 0.014493 | import sys
sys.path.append('/var/www/invoicy/app/')
from main import app_facto | ry
import con | fig_prod
app = app_factory(config_prod.Prod)
|
kristinriebe/django-prov_vo | prov_vo/renderers.py | Python | apache-2.0 | 19,137 | 0.001568 | from __future__ import unicode_literals
import json
from django.utils.xmlutils import SimplerXMLGenerator
from django.utils.six.moves import StringIO
from django.utils.encoding import smart_text
from django.utils.encoding import smart_unicode
from django.utils import timezone
from rest_framework.renderers import Base... | nderer):
def render(self, entity):
| string = "entity(" + self.get_value(entity, "id") + ")"
string = self.add_optional_attributes(string, entity)
return string
class AgentPROVNRenderer(PROVNBaseRenderer):
def render(self, agent):
string = "agent(" + self.get_value(agent, "id") + ")"
string = self.add_optional... |
algorun/algomanager | api_v1/migrations/0003_auto_20170126_2019.py | Python | gpl-3.0 | 442 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017- | 01-26 20:19
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api_v1', '0002_availablealgorithms'),
]
operations = [
migrations.RenameField(
model_name='runningcontainer',
old_name='... | new_name='node_id',
),
]
|
cedriclaunay/gaffer | python/GafferUI/AboutWindow.py | Python | bsd-3-clause | 5,545 | 0.040216 | ##########################################################################
#
# Copyright (c) 2011-2013, John Haddon. All rights reserved.
# Copyright (c) 2012, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... | h self :
with GafferUI.TabbedContainer() :
with GafferUI.ListContainer(
GafferUI.ListContainer.Orientation.Vertical,
spacing=10,
borderWidth=10,
parenting = { "label" : "Gaffer" },
) :
GafferUI.Spacer(
IECore.V2i( 1 ),
parenting = { "expand" : True }
)
Gaff... | small>" % (
about.url(),
about.url(),
about.versionString(),
)
self.__label(
text,
horizontalAlignment = GafferUI.HorizontalAlignment.Center,
parenting = { "horizontalAlignment" : GafferUI.Label.HorizontalAlignment.Center },
)
GafferUI.Spacer(
IECore.V2i( ... |
fintech-circle/edx-platform | lms/djangoapps/commerce/tests/test_signals.py | Python | agpl-3.0 | 13,662 | 0.002416 | # coding=UTF-8
"""
Tests for signal handling in commerce djangoapp.
"""
from __future__ import unicode_literals
import base64
import json
from urlparse import urljoin
import ddt
import httpretty
import mock
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.test import T... | TTP request/user: auth to commerce service as the unenrolled | student.
self.send_signal()
self.assertTrue(mock_refund_seat.called)
self.assertEqual(mock_refund_seat.call_args[0], (self.course_enrollment,))
# HTTP user is the student: auth to commerce service as the unenrolled student.
mock_get_request_user.return_value = self.student
... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/doc/source/conf.py | Python | gpl-3.0 | 8,789 | 0.007282 | # -*- coding: utf-8 -*-
#
# Galaxy documentation build configuration file, created by
# sphinx-quickstart on Tue Mar 6 10:44:44 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | TML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Galaxydoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The p... | stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Galaxy.tex', u'Galaxy Code Documentation',
u'Galaxy Team', 'manual'),
]
# The name of an i... |
bmcguirk/djangoprojectapp | polls/views.py | Python | mit | 1,962 | 0.006116 | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import | reverse
from django.views import | generic
from django.utils import timezone
from .models import Question, Choice
# Create your views here.
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""
Return the last 5 question by order publis... |
BytesGalore/RIOT | tests/lwip/tests/01-run.py | Python | lgpl-2.1 | 11,453 | 0.000524 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Martine Lenders <mail@martine-lenders.eu>
#
# Distributed under terms of the MIT license.
from __future__ import print_function
import os
import sys
import random
import subprocess
import time
import types
import pexpect
DEFAULT_TIM... | ))
def to_env(self):
| env = {}
if self.name:
env['BOARD'] = self.name
if self.port:
env['PORT'] = self.port
if self.serial:
env['SERIAL'] = self.serial
return env
def clean(self, application=os.getcwd(), env=None):
self.build_strategy.execute(applicatio... |
enthought/etsproxy | enthought/envisage/extension_point_changed_event.py | Python | bsd-3-clause | 107 | 0 | # prox | y module
from __future__ import absolute_import
f | rom envisage.extension_point_changed_event import *
|
mongodb/mongo-python-driver | bson/max_key.py | Python | apache-2.0 | 1,470 | 0 | # Copyright 2010-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr | eed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Representation for the MongoDB internal Ma... | tstate__(self) -> Any:
return {}
def __setstate__(self, state: Any) -> None:
pass
def __eq__(self, other: Any) -> bool:
return isinstance(other, MaxKey)
def __hash__(self) -> int:
return hash(self._type_marker)
def __ne__(self, other: Any) -> bool:
return not ... |
zrax/moul-scripts | Python/xLinkingBookDefs.py | Python | gpl-3.0 | 29,706 | 0.021275 | # -*- coding: utf-8 -*-
""" *==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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... | Stamp2*1#0.hsm" '
DRCPos2 = 'pos=190,60 blend=alpha>'
DRCPos3 = 'pos=220,240 blend=alpha>'
YeeshaStamp = '<img src | ="xYeeshaBookStampVSquish*1#0.hsm" pos=140,255 resize=no blend=alpha>'
kBookMarkID = 0
#BookMark = '<img src="xBookJourneyClothBookmark*1#0.hsm" pos=120,0 resize=yes blend=alpha link=%d><pb><pb>' % kBookMarkID
JCBookMark = '<img src="xBookJourneyClothBookmark*1#0.hsm" pos=120,0 resize=yes blend=alpha link=%d><pb><pb>... |
GermanoGuerrini/django-featurette | tests/settings.py | Python | mit | 597 | 0.001675 | from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test',
}
}
ROOT_URLCONF = 'urls'
SITE_ID = 1
INSTALLED_APPS = (
'django.contrib.contenttypes',
'dja | ngo.contrib.auth',
'django.contrib.sessions',
'django_featurette',
)
TEMPLA | TE_CONTEXT_PROCESSORS += ("django.core.context_processors.request",)
SECRET_KEY = 'sk'
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
) |
p5py/p5 | profiling/main.py | Python | gpl-3.0 | 971 | 0 | import importlib
import time
import cProfile
import p5
filenames = [
'arcs',
'custom_shapes',
'triangle_strip',
'custom_shapes2',
'curves',
'primitives']
max_frames = 100
e = SystemExit()
for name in filenames:
p5 = importlib.import_module('p5')
module = importlib.import_module(name)
... |
def draw():
global curr_frames
curr_frames += 1
if curr_frames > max_frames:
p5.exit()
module.draw()
pr = cProfile.Profil | e()
pr.enable()
start_time = time.process_time()
try:
p5.run(sketch_draw=draw, sketch_setup=module.setup)
except BaseException as curr_e:
elapsed_time = time.process_time() - start_time
print(
"{0} took {1} seconds to render {2} frames".format(
name,
... |
rr-/szurubooru | server/szurubooru/migrations/versions/9ef1a1643c2a_update_user_table_for_hardened_passwords.py | Python | gpl-3.0 | 2,667 | 0 | """
Alter the password_hash field to work with larger output.
Particularly libsodium output for greater password security.
Revision ID: 9ef1a1643c2a
Created at: 2018-02-24 23:00:32.848575
"""
import sqlalchemy as sa
import sqlalchemy.ext.declarative
import sqlalchemy.orm.session
from alembic import op
revision = "9e... | a.VARCHAR(length=64),
type_=sa.Unicode(length=128),
existing_nullable=Fal | se,
)
op.add_column(
"user",
sa.Column(
"password_revision", sa.SmallInteger(), nullable=True, default=0
),
)
session = sa.orm.session.Session(bind=op.get_bind())
if session.query(User).count() >= 0:
for user in session.query(User).all():
pass... |
centrumholdings/cthulhubot | tests/example_project/urls.py | Python | bsd-3-clause | 507 | 0.011834 | from django.conf.urls.defaults import patterns, url, include
from django.co | nf import settings
from django | .contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, 'show_indexes': True }),
url(r'^admin/(.*)', admin.site.root),
url(r'^', include('cthulhubot.urls')),
url(r'^accounts/login/$', 'djang... |
shoopio/shoop | shuup_tests/campaigns/test_multiple_campaigns.py | Python | agpl-3.0 | 4,185 | 0.004062 | # This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from decimal import Decimal
from django.test import override_settings
from ... | n = CategoryProductsBas | ketCondition.objects.create(operator=ComparisonOperator.EQUALS, quantity=1)
condition.categories.add(category)
basket_campaign = BasketCampaign.objects.create(shop=shop, public_name="test", name="test", active=True)
basket_campaign.conditions.add(condition)
effect = DiscountFromProduct.objects.create(c... |
publica-io/django-publica-widgets | widgets/tests.py | Python | bsd-3-clause | 2,084 | 0 | # -*- coding: utf-8 -*-
from django.test import TestCase
from .models import Widget, WidgetMailChimpSignup
class WidgetsTestCase(TestCase):
def setUp(self):
widget = Widget.objects.create(
title='This is my long widget title',
short_title='A neat short title',
text='so... | s.get(
list_name='here should be a long string for the widget mail signup'
)
self.assertEqual(widget_mailchimp_signup.widget, widget)
def test_widget_mailchimp_signup_list_name(self):
widget_mailchimp_signup = WidgetMailChimpSignup.objects.get(
list_name='here should... | widget_mailchimp_signup.list_name,
'here should be a long string for the widget mail signup'
)
|
cchurch/ansible-modules-core | cloud/openstack/_quantum_network.py | Python | gpl-3.0 | 10,283 | 0.010697 | #!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, Benno Joy <benno@ansible.com>
#
# This module 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 ... | try:
networks = neutron.list_networks(**kwargs)
except Exception as e:
| module.fail_json(msg = "Error in listing neutron networks: %s" % e.message)
if not networks['networks']:
return None
return networks['networks'][0]['id']
def _create_network(module, neutron):
neutron.format = 'json'
network = {
'name': module.params.get('name'),
... |
NorfairKing/sus-depot | shared/shared/vim/dotvim/bundle/YouCompleteMe/python/ycm/youcompleteme.py | Python | gpl-2.0 | 23,433 | 0.030683 | # Copyright (C) 2011, 2012 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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 late... | st import SendCommandRequest
from ycm.client.completion_request import ( CompletionRequest,
ConvertCompletionDataToVimData )
from ycm.client.omni_completion_request import OmniCompletionRequest
from ycm.client.event_ | notification import ( SendEventNotificationAsync,
EventNotification )
from ycmd.responses import ServerError
try:
from UltiSnips import UltiSnips_Manager
USE_ULTISNIPS_DATA = True
except ImportError:
USE_ULTISNIPS_DATA = False
def PatchNoProxy():
current_value = os.... |
johanfrisk/Python_at_web | notebooks/code/oauth.py | Python | mit | 21,034 | 0.002757 | """
The MIT License
Copyright (c) 2007 Leah Culver
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 rights
to use, copy, modify, merge, publis... | them
params = dict(self.parameters)
try:
# Exclude the signature if it exists.
del params['oauth_signature']
except:
pass
# Escape key values before sorting.
key_values = [(escape(_utf8_str(k)), escape(_utf8_str(v))) \
for k,v in pa... | exicographically, first after key, then after value.
key_values.sort()
# Combine key value pairs into a string.
return '&'.join(['%s=%s' % (k, v) for k, v in key_values])
def get_normalized_http_method(self):
"""Uppercases the http method."""
return self.http_method.upper()
... |
sharkerz/deluge-yarss-plugin | setup.py | Python | gpl-3.0 | 2,973 | 0.001009 | #
# setup.py
#
# Copyright (C) 2015 Dario Blanco
#
# Based on work by:
# Copyright (C) 2013-2014 Bro <bro.development@gmail.com>
# Copyright (C) 2009 Camillo Dell'mour <cdellmour@gmail.com>
#
# Basic plugin template created by:
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
# Copyright (C) 2007-2009 Andrew R... | ption, the copyright holders give
# permission to link the code of portions of this program with the OpenSSL
# library.
# You must obey the GNU General Public License in all respects for all of
# the code used other than OpenSSL. If you modify file(s) with this
# exception, you may extend this exception ... | s exception statement from your version. If you delete this exception
# statement from all source files in the program, then also delete it here.
#
from setuptools import setup, find_packages
__plugin_name__ = "YaRSS2"
__author__ = "Dario Blanco"
__author_email__ = "dario@darioblanco.com"
__version__ = "1.3.4"
__u... |
mecax/pyrobotlab | toSort/InMoov2.minimal.py | Python | apache-2.0 | 2,008 | 0.023904 | #file : InMoov2.minimal.py
# this will run with versions of MRL above 1695
# a very minimal script for InMoov
# although this script is very short you can still
# do voice control of a right hand or finger box
# for any command which you say - you will be required to say a confirmation
# e.g. you say -> open hand, InM... | startEar()
i01.startMouth()
#to tweak the default voice
i01.mouth.setGoogleURI("http://thehackettf | amily.org/Voice_api/api2.php?voice=Ryan&txt=")
##############
i01.startRightHand(rightPort)
# tweaking defaults settings of right hand
#i01.rightHand.thumb.setMinMax(55,135)
#i01.rightHand.index.setMinMax(0,160)
#i01.rightHand.majeure.setMinMax(0,140)
#i01.rightHand.ringFinger.setMinMax(48,145)
#i01.rightHand.pinky.set... |
rs2/pandas | pandas/core/window/online.py | Python | bsd-3-clause | 3,789 | 0.000528 | from typing import (
Dict,
Optional,
)
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.util.numba_ import (
NUMBA_FUNC_CACHE,
get_jit_arguments,
)
def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]):
"""
Generate a... | djust,
self.ignore_na,
)
self.old_wt = old_wt
self.last_ewm = result[-1]
return result
def reset(self):
self.old_wt = np.ones(self.shape[self.axis - | 1])
self.last_ewm = None
|
beevek/txamqp | src/txamqp/test/test_broker.py | Python | apache-2.0 | 6,431 | 0.008863 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | except Closed, e:
self.assertConnectionException(504, e.args[0])
@supportedBrokers(QPID, OPENAMQ)
@inlineCallbacks
def test_channel_flow(self):
channel = self.channel
yield channel.queue_declare(queue="flow_test_queue", exclusive=True)
yield channel.basic_consume... | ueue("my-tag")
yield channel.channel_flow(active=False)
channel.basic_publish(routing_key="flow_test_queue", content=Content("abcdefghijklmnopqrstuvwxyz"))
try:
yield incoming.get(timeout=1)
self.fail("Received message when flow turned off.")
except Empt... |
ruohoruotsi/Wavelet-Tree-Synth | nnet/VRNN_nips2015/cle/tutorials/music.py | Python | gpl-2.0 | 3,945 | 0.000253 | import ipdb
import numpy as np
import theano
from cle.cle.cost import NllBin
from cle.cle.data import Iterator
from cle.cle.models import Model
from cle.cle.layers import InitCell
from cle.cle.layers.feedforward import FullyConnectedLayer
from cle.cle.layers.recurrent import LSTM
from cle.cle.train import Training
fro... | 1
model = Model()
train_data = Music(name='train',
| path=data_path,
nlabel=nlabel)
valid_data = Music(name='valid',
path=data_path,
nlabel=nlabel)
# Choose the random initialization method
init_W = InitCell('randn')
init_U = InitCell('ortho')
init_b = InitCell('zeros')
x, y, mask = train_data.thean... |
jeremiahyan/odoo | odoo/addons/test_lint/tests/test_eslint.py | Python | gpl-3.0 | 1,842 | 0.005429 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import re
import subpr | ocess
from unittest import skipIf
from odoo import tools
from . import lint_case
RULES = ('{'
'"no-undef": "error",'
'"no-restricted-globals": ["error", "event", "self"],'
'"no-const-assign": ["error"],'
'"no-debugger": ["error"],'
'"no-dupe- | class-members": ["error"]'
'}'
)
PARSER_OPTIONS = '{ecmaVersion: 2019, sourceType: module}'
GLOBAL = ','.join([
'owl',
'odoo',
'$',
'jQuery',
'_',
'Chart',
'fuzzy',
'QWeb2',
'Popover',
'StackTrace',
'QUnit',
'luxon',... |
hackersql/sq1map | comm1x/src/utils/session_handler.py | Python | gpl-3.0 | 17,851 | 0.018542 | #!/usr/bin/env python
# encoding: UTF-8
"""
This file is part of Commix Project (http://commixproject.com).
Copyright (c) 2014-2017 Anastasios Stasinopoulos (@ancst).
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 Soft... | E TABLE IF NOT EXISTS " + table_name(url) + "_ip" + \
"(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR," \
"shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, "\
"TAG V | ARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, "\
"timesec INTEGER, how_long INTEGER, output_length INTEGER, is_vulnerable VARCHAR);")
conn.execute("INSERT INTO " + table_name(url) + "_ip(url, technique, injection_type, se... |
radinformatics/whatisit | scripts/upload_demo.py | Python | mit | 5,956 | 0.010745 | #!/bin/python
# This script will upload the data from @mlungren's project, including basic reports and labels
# (see README.md for full instructions). In the long run we want a standard data format for importing.
# AllowedAnnotation objects store a label name and allowed value, and an Annotation combines one of these ... | annotation=annotation_object)
if created==True:
annotation.save()
annotation.reports.add(new_report)
annotation.save()
#Annotation.objects.count()
#7
#AllowedAnnotation.objects.count()
#11
#Report.objects.count()
#117816
else:
... | |
youtube/cobalt | third_party/llvm-project/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py | Python | bsd-3-clause | 24,254 | 0.014554 | """
Test lldb-mi -var-xxx commands.
"""
from __future__ import print_function
import lldbmi_testcase
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class MiVarTestCase(lldbmi_testcase.MiTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
... | )
self.expect("\^done,value=\"3\"")
self.runCmd("-var | -update --all-values var3")
# self.expect("\^done,changelist=\[\{name=\"var3\",value=\"3\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]")
# FIXME -var-update doesn't work
self.runCmd("-var-delete var3")
self.expect("\^done")
self.runCmd("-var-create var3 * s_MyVar"... |
mossmatters/HybPiper | fasta_merge.py | Python | gpl-3.0 | 5,712 | 0.017857 | #!/usr/bin/env python
helptext ='''This script will take a list of FASTA files and concatenate them for use in
phylogenetic inference. The sequence headers (up until the first space) must be identical
in each individual FASTA file.
Individual gene sequences should be aligned prior to running this script!
This scrip... | ,"3",codon3_start,codon3_end))
gene_start = codon3_end + 1
else:
for g in range(len(fastafiles)):
gene_end = gene_start + partition_lengths[g] - 1
partit | ion_file.write("{},{}={}-{}\n".format(partition_type,fastafiles[g],gene_start,gene_end))
gene_start = gene_end + 1
partition_file.close()
def main():
parser = argparse.ArgumentParser(description=helptext,formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--fastafiles... |
Mafarricos/Mafarricos-modded-xbmc-addons | plugin.video.xbmctorrentV2/resources/site-packages/xbmctorrentV2/scrapers/bitsnoop.py | Python | gpl-2.0 | 1,646 | 0.001823 | from xbmctorrentV2 import plugin
from xbmctorrentV2.scrapers import scraper
from xbmctorrentV2.ga import tracked
from xbmctorrentV2.caching import cached_route
from xbmctorrentV2.utils import ensure_fanart
from xbmctorrentV2.library import library_context
BASE_URL = "%s/" % plugin.get_setting("base_bitsnoop")
HEADERS... | url_get
content_type = plugin.request.args_dict.get("content_type")
if content_type:
plugin.set_content(content_type)
page = int(page)
page_data = url_get(urljoin(BASE_URL, "%s/%d/" % (root, page)), headers=HEADERS, params={
"fmt": "rss",
"sort": "n_s",
"dir": "desc",
... | t.args_dict.pop("query", None)
if not query:
query = plugin.keyboard("", "xbmctorrentV2 - Bitsnoop - Search")
if query:
plugin.redirect(plugin.url_for("bitsnoop_page", root="/search/video/%s/c/d/" % urllib.quote("%s safe:no" % query, safe=""), page=1, **plugin.request.args_dict))
|
thread/django-directed-edge | django_directed_edge/export.py | Python | bsd-3-clause | 813 | 0.00369 | import contextlib
from directed_edge import Exporter, Item
from .utils import ident, get_database
@contextlib.contextmanager
def get_exporter(target=None):
if target is None:
target = get_database()
exporter = DjangoExporter(target)
yield exporter
exporter.finish()
class DjangoExporter(Ex... | nt(instance))
item.add_tag(ident(type(instance)))
return item
class DjangoItem(Item):
def link_to(self, other, *args, **kwargs):
super(DjangoItem, self).lin | k_to(ident(other), *args, **kwargs)
|
acercado/jd-ph-cms | jd-ph-cms/policies/migrations/0001_initial.py | Python | bsd-3-clause | 2,519 | 0.006352 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-04 05:22
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
depe... | cy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('news_duration_date_start', models.DateTimeField(blank=True, null=True)),
('news_duration_date_end', models.DateTimeField(blank=True, null=True)),... | d(blank=True, null=True)),
('max_answers_per_question', models.PositiveSmallIntegerField(default=1, validators=[django.core.validators.MinValueValidator(1)])),
('map_radius', models.PositiveSmallIntegerField(default=500, validators=[django.core.validators.MinValueValidator(1)])),
... |
YoQuieroSaber/yournextrepresentative | candidates/management/commands/candidates_import_statements_of_persons_nominated.py | Python | agpl-3.0 | 3,359 | 0.002382 | import csv
import errno
import hashlib
import magic
import mimetypes
import os
from os.path import dirname, join, exists
import requests
from django.core.management.base import BaseCommand
from django.core.files.storage import FileSystemStorage
from candidates.election_specific import MAPIT_DATA
from official_docume... | application/vnd.openxmlformats-officedocument.wordprocessingml.document',
])
def download_file_cached(url):
url_hash = hashlib.md5(url).hexdigest()
directory = join(dirname(__file__), '.noms-cache')
try:
os.mkdir(directory)
except OSError as e:
if e.errno != errno.EEXIST:
ra... | rite(r.content)
return filename
class Command(BaseCommand):
def handle(self, **options):
mime_type_magic = magic.Magic(mime=True)
storage = FileSystemStorage()
r = requests.get(CSV_URL, stream=True)
reader = csv.DictReader(r.raw)
for row in reader:
... |
fortesit/data-structure | Data Stream Algorithm/Heavy Hitters.py | Python | mit | 1,605 | 0.001869 | #!/usr/bin/env python
import sys
from collections import defaultdict
import itertools
import operator
from operator import itemgetter
counters = defaultdict(int)
trueCounters = defaultdict(int)
fr = open('allworks','r')
wc = 0
for line in fr:
line = line.strip()
words = ''.join(c for c in line if c.isalpha(... | y] -= 1
| if counters[key] == 0:
delCounters.append(key)
for word in delCounters:
del counters[word]
# 2nd Pass: True count, Delete by thresold
fr.seek(0)
for line in fr:
line = line.strip()
words = ''.join(c for c in line if c.isalpha() or c.isspace()).split()... |
dmitriz/zipline | zipline/utils/events.py | Python | apache-2.0 | 17,605 | 0 | #
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | def add_event(self, event, prepend=False):
"""
Adds an event to the manager.
"""
if prepend:
self._events.insert(0, event)
else:
self._events.append(event)
def handle_data(self, context, data, dt):
with self._create_context(data):
... | context.trading_environment,
)
class Event(namedtuple('Event', ['rule', 'callback'])):
"""
An event is a pairing of an EventRule and a callable that will be invoked
with the current algorithm context, data, and datetime only when the rule
is triggered.
"""
def ... |
robocomp/learnbot | learnbot_dsl/functions/proprioceptive/base/is_moving_right.py | Python | gpl-3.0 | 154 | 0.032468 |
def is_moving_right(lbot):
rot = lbot.getRot()
a | dv = lbot.getAdv()
if ro | t is not None and adv is not None:
return rot > 0 and adv > 0
return False
|
hoechenberger/psychopy | psychopy/tests/test_events/test_keyboard_events.py | Python | gpl-3.0 | 11,035 | 0.000363 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from builtins import object
import pytest
from psychopy import event, core
from psychopy.preferences import prefs
from psychopy.visual import Window
from pyglet.window.key import (MOD_SHIFT,
MOD_CTRL,
MOD_ALT,
... | assert len(global_keys) == 0
def test_getitem(self):
key = 'escape'
modifiers = ('ctrl', 'alt')
func = self._func
global_keys = event._GlobalEventKeys()
global_keys.add(key=key, modifiers= | modifiers, func=func)
assert global_keys[key, modifiers] == global_keys._events[key, modifiers]
def test_getitem_string(self |
Ecpy/ecpy | tests/instruments/test_plugin.py | Python | bsd-3-clause | 12,982 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... | not res and 'instance' in msg
st.starter = BaseStarter()
res, ms | g = validate_starter(st)
assert not res and 'implement' in msg
# Positive cases are tested test_plugin_lifecycle
def test_plugin_lifecycle(exopy_qtbot, instr_workbench):
"""Test the plugin lifecycle (initial registration and later on).
"""
instr_workbench.register(InstrContributor1())
# Tes... |
smendes/django-andablog | andablog/views.py | Python | bsd-2-clause | 921 | 0.003257 | from django.db.models import Q
from django.views.generic import ListView, DetailView
from . import models
class EntriesList(ListView):
model = models.Entry
template_name = 'andablog/entry_list.html'
context_object_name = 'entries'
pag | inate_by = 10
paginate_orphans = 5
def get_queryset(self):
queryset = super(EntriesList, self).get_queryset().filter(
Q(is_published=True) | Q(author__isnull=False, author=self.request.user.id))
return queryset.order_by('is_published', '-published_timestamp') # Put 'drafts' first.
... | ml'
context_object_name = 'entry'
slug_field = 'slug'
def get_queryset(self):
return super(EntryDetail, self).get_queryset().filter(
Q(is_published=True) | Q(author__isnull=False, author=self.request.user.id))
|
LennonChin/Django-Practices | MxOnline/extra_apps/xadmin/plugins/passwords.py | Python | apache-2.0 | 4,992 | 0.004407 | # coding=utf-8
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth.views import password_reset_confirm
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as ... | form.save(**opts)
context = super(ResetPasswordSendView, self).get_context()
| return TemplateResponse(request, self.password_reset_done_template, context,
current_app=self.admin_site.name)
else:
return self.get(request, form=form)
site.register_view(r'^xadmin/password_reset/$', ResetPasswordSendView, name='xadmin_password_reset')
c... |
annual-client-report/Annual-Report | report/models.py | Python | mit | 8,050 | 0.010435 | from django.db import models
import datetime
def get_choices(lst):
return [(i, i) for i in lst]
#
# Person
#
pprint_pan = lambda pan: "%s %s %s" % (pan[:5], pan[5:9], pan[9:])
class Person(models.Model):
name = models.CharField(max_length=255, db_index=True)
fathers_name = models.CharField(max_length=2... | nd_amount_143_3 = models.Decimal | Field("Refund amount", max_digits=12, decimal_places=2, null=True, blank=True)
demand_raised_amount_143_3 = models.DecimalField("Demand raised for", max_digits=12, decimal_places=2, null=True, blank=True)
refund_received_on_143_3 = models.DateField("Refund received on", null=True, blank=True)
#Appeal befo... |
danieldeveloper001/Learning | Python/02_DesignPatterns/Behavioral/Command/Request.py | Python | mit | 137 | 0 | class Request(object):
def __init__(s | elf, value):
self.__value = value
def get_value(self) | :
return self.__value
|
griimick/feature-mlsite | app/static/hindi-dependency-parser-2.0/hindi-pos-tagger/bin/lemmatiser.py | Python | mit | 1,258 | 0.016693 | #!/usr/bin/env python
'''
Usage: python lemmatiser.pl lemmaFile < input > output
The input should have two colums
<html>
word1 tag1
word2 tag2
.
'''
import sys
import re
lemmaDict= {} # word : { pos : lemma}
def loadLemmatiser(file):
for line in open(file):
line=line.strip()
word= line.split('\t... | {}
for t in tags:
(tag, lemma)= t.split(' ')
if tag in lemmaDict[word]:
continue
if lemma.strip()!="":
lemmaDict[word][tag]= lemma
def lemmat | ise(f):
for line in f:
line= line.strip()
if line=="":
print(line)
elif line[0]=='<':
print(line)
else:
#line.sub("\t+")
cols= line.split()
if len(cols)!=2:
#print cols
print(line)
... |
farizrahman4u/keras-contrib | keras_contrib/tests/regularizers.py | Python | mit | 1,414 | 0 | import numpy as np
from keras.datasets import mnist
from keras.layers import Activation
from keras.layers import Dense
from keras.models import Sequential
from keras.utils import np_utils
np.random.seed(1337)
nb_classes = 10
batch_size = 128
nb_epoch = 5
weighted_class = 9
standard_weight = 1
high_weight = 5
max_trai... | shape(10000, 784)[:max_test_samples]
X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32') / 255
# con | vert class vectors to binary class matrices
y_train = y_train[:max_train_samples]
y_test = y_test[:max_test_samples]
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
test_ids = np.where(y_test == np.array(weighted_class))[0]
return (X_t... |
thaim/ansible | lib/ansible/modules/cloud/google/gcp_resourcemanager_project.py | Python | mit | 12,612 | 0.003092 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | sociated with a given resource.
- Clients should store labels in a representation such as JSON that does not depend
on specific characters being disallowed .
required: false
type: dict
parent:
description:
- A parent organization.
required: false
type: dict
suboptions:
type... | - Must be organization.
required: false
type: str
id:
description:
- Id of the organization.
required: false
type: str
id:
description:
- The unique, user-assigned ID of the Project. It must be 6 to 30 lowercase letters,
digits, or hyphens. It must ... |
Yelp/paasta | paasta_tools/deployd/metrics.py | Python | apache-2.0 | 4,472 | 0.001342 | import time
from typing import List
from paasta_tools.deployd.common import DelayDeadlineQueueProtocol
from paasta_tools.deployd.common import PaastaThread
from paasta_tools.deployd.workers import PaastaDeployWorker
from paasta_tools.metrics.metrics_lib import BaseMetrics
class MetricsThread(PaastaThread):
def _... | adline_gauge = self.metrics.create_gauge(
"sum_time_past_deadline", paasta_cluster=cluster
)
self.workers = workers
self.workers_busy_gauge = self.metrics.create_gauge(
"workers_busy", paasta_cluster=cluster
)
self.workers_idle_gauge = self.metrics.creat... | er=cluster
)
self.workers_dead_gauge = self.metrics.create_gauge(
"workers_dead", paasta_cluster=cluster
)
def run_once(self) -> None:
currently_available_instances = tuple(
self.queue.get_available_service_instances(fetch_service_instances=False)
)
... |
dthain/cctools | weaver/src/examples/arguments.py | Python | gpl-2.0 | 56 | 0 | #!/usr/bi | n/env | python
print(CurrentScript().arguments)
|
hitsumabushi/windows_start_guide | source/conf.py | Python | mit | 9,370 | 0.005763 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Windows Start Guide documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 12 02:52:30 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible c | onfiguration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# | If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -------------... |
pombredanne/tahoe-lafs | src/allmydata/immutable/downloader/status.py | Python | gpl-2.0 | 9,220 | 0.003145 |
import itertools
from zope.interface import implements
from allmydata.interfaces import IDownloadStatus
class ReadEvent:
def __init__(self, ev, ds):
self._ev = ev
self._ds = ds
def update(self, bytes, decrypttime, pausetime):
self._ev["bytes_returned"] += bytes
self._ev["decryp... | elf.first_timestamp = when
r = { "segment_number": segnum,
"start_time": when,
"active_time": None,
"finish_time": None,
"success": None,
"decode_time": None,
"segment_start": None,
"segment_length": None,
... | }
self.segment_events.append(r)
return SegmentEvent(r, self)
def add_dyhb_request(self, server, when):
r = { "server": server,
"start_time": when,
"success": None,
"response_shnums": None,
"finish_time": None,
}
s... |
Puyb/sixhdp | inscriptions/templatetags/stats.py | Python | gpl-3.0 | 1,467 | 0.005453 | from django import template
import sys
register = template.Library()
@register.filter
def get(dictionary, key):
return dictionary.get(key)
@register.filter
def pertinent_values(dictionary, key):
limit = '10'
if ',' in key:
| key, limit = key.split(',')
keys = dictionary.keys()
total = reduce(lambda a, b: a + dictionary[b][key], keys, 0)
if limit[-1:] == '%':
limit = total * float(limit[:-1]) / 100.0
else:
limit = int(limit)
print >>sys.stderr, limit
keys.sort(lambda a, b: cmp(dictionary[b][key]... | hile dictionary[keys[index]][key] < limit and index > 10:
index -= 1
return keys[:index + 1]
@register.filter
def other_values(dictionary, key):
limit = '10'
if ',' in key:
key, limit = key.split(',')
keys = dictionary.keys()
total = reduce(lambda a, b: a + dictionary[b][key], key... |
securestate/king-phisher | tests/client/gtk_builder.py | Python | bsd-3-clause | 2,305 | 0.006508 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/client/gtk_builder_lint.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice,... | TORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL T | HE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILI... |
lutris/lutris | lutris/util/cookies.py | Python | gpl-3.0 | 2,811 | 0.001067 | # Standard Library
import time
from http.cookiejar import Cookie, MozillaCookieJar, _warn_unhandled_exception
class WebkitCookieJar(MozillaCookieJar):
"""Subclass of MozillaCookieJar for compatibility with cookies
coming from Webkit2.
This disables the magic_re header which is not present and adds
co... | domain,
domain_specified,
initial_dot,
path,
False,
secure,
expir | es,
discard,
None,
None,
{},
)
if not ignore_discard and c.discard:
continue
if not ignore_expires and c.is_expired(now):
continue
self.... |
iniverno/RnR-LLC | simics-3.0-install/simics-3.0.31/home/scripts/ia64-linux.py | Python | gpl-2.0 | 21,269 | 0.022333 |
## Copyright 2001-2007 Virtutech AB
##
## The contents herein are Source Code which are a subset of Licensed
## Software pursuant to the terms of the Virtutech Simics Software
## License Agreement (the "Agreement"), and are being distributed under
## the Agreement. You should have received a copy of the Agreem... | ,
1041 : [ "getpid", ":d"],
1042 : [ "getppid", ""],
1043 : [ "mount", ""],
1044 : [ "umount", ""],
1045 : [ "setuid", ""],
1046 : [ "getuid", ""],
1047 : [ "geteuid", ""],
1048 : [ "ptrace", ""],
1049 : [ "access", "sd:d"],
1050 : [ "sync", ""],
... | [ "rename", ""],
1055 : [ "mkdir", ""],
1056 : [ "rmdir", ""],
1057 : [ "dup", "d:d"],
1058 : [ "pipe", ("x", fmt_pipe_ret)],
1059 : [ "times", ""],
1060 : [ "brk", "x:x"],
1061 : [ "setgid", ""],
1062 : [ "getgid", ""],
1063 : [ "getegid", ""],
1064... |
vaidik/ReTweeter | retweeter/urls.py | Python | agpl-3.0 | 1,538 | 0.010403 | from django.conf.urls.defaults import patterns, include, url
from retweeter import views
from retweeter import login
from retweeter import tweetmanager
from retweeter import users
from django.contrib.auth.views import logout
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin... | # | Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
|
liuyang1/euler | 042.py | Python | mit | 566 | 0.015901 | def triNum(thresh):
a, n = 1, 1
l = [a]
while 1:
n += 1
a += n
l.append(a)
if a > thresh:
break
return l
def getData():
with open("data.042") as f:
for l in f.readlines():
l = l.split(',')
l = [i[1:-1] for i in l]
... | return sum([Char2Order(c) for c in w])
data = getData()
data = [Word2Val(w) for w in data]
m = max(d | ata)
l = triNum(m)
print len([1 for i in data if i in l])
|
PyPSA/PyPSA | examples/unit-commitment.py | Python | mit | 5,541 | 0.021296 | ## Demonstrate PyPSA unit commitment with a one-bus two-generator example
#
#
#This tutorial runs through examples of unit commitment for generators at a single bus. Examples of minimum part-load, minimum up time, minimum down time, start up costs, shut down costs and ramp rate restrictions are shown.
#
#To enable unit... | ramp_limit_down=0.2,
p_nom=10000)
nu.add("Generator","gas",bus="bus",
marginal_cost=70,
p_nom=4000)
nu.add("Load","load",bus="bus",p_set=[4000,7000,7000,7000,7000,3000])
nu.lopf(nu.snapshots)
nu.generators_t.p
nu = pypsa.Network()
nu.set_snapshots(range(6))
nu.add("Bus","bus")
nu.add("Gen... | e=True,
capital_cost=1e2)
nu.add("Generator","gas",bus="bus",
marginal_cost=70,
p_nom=4000)
nu.add("Load","load",bus="bus",p_set=[4000,7000,7000,7000,7000,3000])
nu.lopf(nu.snapshots)
nu.generators.p_nom_opt
nu.generators_t.p
nu = pypsa.Network()
nu.set_snapshots(range(7))
nu.add("Bus","bu... |
DarkFenX/Pyfa | gui/fitCommands/gui/cargo/remove.py | Python | gpl-3.0 | 1,273 | 0.001571 | import math
import wx
import eos.db
import gui.mainFrame
from gui import globalEvents as GE
from gui.fitCommands.calc.cargo.remove import CalcRemoveCargoCommand
from gui.fitCommands.helpers import CargoInfo, InternalCommandHistory
from service.market import Market
class GuiRemoveCargosCommand(wx.Command):
def ... | tID,)))
return success
def Undo(self):
success = self.internalHistory.undoAll()
eos.db.commit()
wx.PostEvent(gui.mainFrame.MainFram | e.getInstance(), GE.FitChanged(fitIDs=(self.fitID,)))
return success
|
dkarakats/edx-platform | common/djangoapps/util/keyword_substitution.py | Python | agpl-3.0 | 2,555 | 0.000391 | """
keyword_substitution.py
Contains utility functions to help substitute keywords in a text body with
the appropriate user / course data.
Supported:
LMS:
- %%USER_ID%% => anonymous user id
- %%USER_FULLNAME%% => User's full name
- %%COURSE_DISPLAY_NAME%% => display name of the course
... | ubstitutor())
return string
def substitute_keywords_with_data(string, context):
| """
Given an email context, replaces all %%-encoded words in the given string
`context` is a dictionary that should include `user_id` and `course_title`
keys
"""
# Do not proceed without parameters: Compatibility check with existing tests
# that do not supply these parameters
user_id = cont... |
saifrahmed/DjangoBB | djangobb_forum/middleware.py | Python | bsd-3-clause | 2,395 | 0.002088 | from datetime import timedelta
from django.core.cache import cache
from django.utils import translation, timezone
from django.conf import settings as global_settings
import pytz
from djangobb_forum import settings as forum_settings
class LastLoginMiddleware(object):
def process_request(self, request):
if... | language = translation.get_language_from_request(request)
if not profile.language:
profile.language = language
profile.save()
if profile.language and profile.language != | language:
request.session['django_language'] = profile.language
translation.activate(profile.language)
request.LANGUAGE_CODE = translation.get_language()
class UsersOnline(object):
def process_request(self, request):
now = timezone.now()
delta = now ... |
ubergeek42/scribe | setup.py | Python | mit | 917 | 0.001091 | import codecs
import os
import re
from setuptools import setup
def read(*parts):
return codecs.open(os.path.join(os.path.dirname(__file__), *parts)).read()
def find_version(*file_paths):
version_ | file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='scribe',
description=('Au | tomatically create pages and upload images to a confluence '
'page'),
long_description=read('README.md'),
version=find_version('scribe.py'),
scripts=['scribe.py'],
author='TrepHub',
author_email='',
url='https://github.com/ubergeek42/scribe',
license='MIT License',
insta... |
sigmoidanalytics/spark_gce | spark_gce.py | Python | apache-2.0 | 20,428 | 0.033532 | #!/usr/bin/env python
###
# This script sets up a Spark cluster on Google Compute Engine
# Sigmoidanalytics.com
###
from __future__ import with_statement
import logging
import os
import pipes
import random
import shutil
import subprocess
import sys
import tempfile
import time
import commands
import urllib2
from optp... | ort getpass
import threa | ding
import json
###
# Make sure gcutil is installed and authenticated
# Usage: spark_gce.py <project> <no-slaves> <slave-type> <master-type> <identity-file> <zone> <cluster-name>
# Usage: spark_gce.py <project> <cluster-name> destroy
###
identity_file = ""
slave_no = ""
slave_type = ""
master_type = ""
zone = ""
cl... |
Jaemu/advent-of-code | python/day-3.py | Python | mit | 918 | 0.043573 | im | port sys
def solve():
moveList = sys.stdin.read().strip()
moves = {}
houseGrid = []
houseGrid.append([1])
moves['^'] = [-1, 0]
moves['v'] = [1, 0]
moves['<'] = [0, -1]
moves['>'] = [0, 1]
santa = {}
santa['x'] = 0
santa['y'] = 0
robo = {}
robo['x'] = 0
robo['y'] = 0
santaList = [(0,0)]
isSanta = True... | or move in moveList:
currentMove = moves[move]
if(isSanta):
isSanta = False
santa['y'] = santa['y'] + currentMove[0]
santa['x'] = santa['x'] + currentMove[1]
currentPosition = (santa['y'], santa['x'])
if not currentPosition in santaList:
santaList.append(currentPosition)
else:
isSanta = True... |
nchammas/asyncssh | asyncssh/crypto/pyca/rsa.py | Python | epl-1.0 | 2,084 | 0.00048 | # Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart. | net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation... | ceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
from cryptography.hazmat.primitives.hashes import SHA1
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
from cryptography.hazmat... |
alfasin/st2 | st2common/st2common/config.py | Python | apache-2.0 | 8,282 | 0.003985 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | [
cfg.StrOpt('host', default='0.0.0.0', help='host of db server'),
cfg.IntOpt('port', default=27017, help='port o | f db server'),
cfg.StrOpt('db_name', default='st2', help='name of database'),
cfg.StrOpt('username', help='username for db login'),
cfg.StrOpt('password', help='password for db login'),
cfg.IntOpt('connection_retry_max_delay_m', help='Connection retry total time (minutes).',
... |
tinloaf/home-assistant | tests/components/light/test_rflink.py | Python | apache-2.0 | 18,573 | 0 | """Test for RFLink light components.
Test setup of RFLink lights component/platform. State tracking and
control of RFLink switch devices.
"""
from homeassistant.components.light import ATTR_BRIGHTNESS
from homeassistant.components.rflink import EVENT_BUTTON_PRESSED
from homeassistant.const import (
ATTR_ENTITY_I... | _call(DOMAIN, SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: DOMAIN + '.test'}))
# wait for commands and repetitions to finish
await hass.async_block_till_done()
assert protocol.send_command_ack.call_count == 2
# test if default apply to configured devices
hass.async_create_t... | {ATTR_ENTITY_ID: DOMAIN + '.test1'}))
# wait fo |
zhaozhilong1993/demon | scripts/online_action/reset_zabbix_hosts.py | Python | apache-2.0 | 942 | 0.006369 | #!/usr/bin/python
from pyzabbix import ZabbixAPI
import sys
username="wentian"
password="65107318"
zapi = ZabbixAPI("http://zabbix.ustack.com")
zapi.login(username, password)
print "Connected To Zabbix API Version %s" % zapi.api_version()
hostgroup_id = sys.argv[1]
status = int(sys.argv[2])
def get_hostgroup_id(h... | i.hostgroup.get(search=search)
if len(hostgroups) > 0:
return hostgroups[0]['groupid']
def get_hosts(groupid):
groupids = [groupid]
hosts = zapi.host.get(groupids=groupids)
return hosts
def update_machine_set_status(hosts, status=0):
result_hosts = []
for host in hos | ts:
result_hosts.append({"hostid": host["hostid"]})
zapi.host.massupdate(hosts=result_hosts, status=status)
if __name__ == "__main__":
hosts = get_hosts(get_hostgroup_id(hostgroup_id))
update_machine_set_status(hosts, status)
|
SahilTikale/haas | hil/migrations/env.py | Python | apache-2.0 | 3,211 | 0 | """
This file is boilerplate generated by Alembic; see the alembic
documentation for more information:
https://alembic.readthedocs.org/en/latest/
The Flask-Migrate extension may also be of interest:
https://flask-migrate.readthedocs.org/en/latest/
"""
from __future__ import with_statement
from alembic import context... | available.
Calls to context.execut | e() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need... |
davmre/matrizer | tests/test_generated_python.py | Python | gpl-2.0 | 2,452 | 0.005302 | import numpy as np
import scipy
import scipy.linalg
import time
import os
import sys
def run_loaded_test(symbolcode, code1, code2, max_seconds=0.1):
env = {"np": np, "scipy": scipy, "scipy.linalg": scipy.linalg}
exec(symbolcode, env)
targets = env['targets']
env1 = env.copy()
env2 = env.copy()
... | name, "optimized.py")) as f:
optimized_code = f.read()
targets, errs, relerrs, naive_time, opt_time, env1, env2 = run_loaded_test(symbolcode, naive_code, optimized_code)
print "%s: naive %.0fus optimized %.1fus (%.1f%% speedup)." % (dirname, naive_time*1000000, opt_time*1000000, (1 - opt_time/naive_tim... | target, err, relerr in zip(targets, errs, relerrs):
print " %s: absolute %f relative %f" % (target, err, relerr)
t1 = np.asarray(env1[target])
if len(t1.shape) < 2:
t1 = t1.reshape((1, -1))
t2 = np.asarray(env2[target])
if len(t2.shape) < 2:... |
beakman/droidlab | droidlab/experiments/migrations/0003_auto_20161013_2021.py | Python | bsd-3-clause | 625 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-13 18:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('experiments', '0002_auto_20161013_1140'),
]
o | perations = [
migrations.AddField(
model_name='result',
name='height',
field=models.IntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='result',
name='width',
field=models.IntegerField(bla | nk=True, null=True),
),
]
|
michaelhowden/eden | modules/s3db/cap.py | Python | mit | 86,498 | 0.007861 | # -*- coding: utf-8 -*-
""" Sahana Eden Common Alerting Protocol (CAP) Model
@copyright: 2009-2015 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to dea... | #"cap_gis_location_xml_post_parse",
#"cap_gis_l | ocation_xml_post_render",
)
import datetime
import urllib2 # Needed for quoting & error handling on fetch
try:
from cStringIO import StringIO # Faster, where available
except:
from StringIO import StringIO
from gluon import *
from gluon.storage import Storage
from gluon.tools import fet... |
dennybaa/st2contrib | packs/slack/actions/post_message.py | Python | apache-2.0 | 1,186 | 0.001686 | import json
import httplib
import requests
from st2actions.runners.pythonrunner import Action
__all__ = [
'PostMessageAction'
]
class PostMessageAction(Action):
def run(self, message, username=None, icon_emoji=None, channel=None):
config = self.config['post_message_action']
username = usern... | 'icon_emoji': icon_emoji,
'text': message
}
if channel:
body['channel'] = channel
data = 'payload=%s' % (json.dumps(body))
response = requests.post(url=config['webhook_url'],
headers=headers, data=data)
if respon... | ger.exception('Failed to post message: %s' % (response.text))
return True
|
r0balo/pelisalacarta | python/main-classic/channels/documentalesonline.py | Python | gpl-3.0 | 5,391 | 0.00557 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# ------------------------------------------------------------
import re
from core import httptools
from core import logger
from core import scr... | ccion = '<h4 class="widget-title">Destacados</h4><div class="textwidge | t"><ul>(.*?)</ul>'
action = "findvideos"
else:
patron_seccion = '<h4 class="widget-title">Series destacadas</h4><div class="textwidget"><ul>(.*?)</ul>'
action = "listado"
data = scrapertools.find_single_match(data, patron_seccion)
matches = re.compile('<a href="([^"]+)">(.*?)</a>',... |
fandemonium/code | tiedje-scripts/insert_cog_desc.py | Python | mit | 604 | 0.02649 | #!/usr/bin/python
import sys
if le | n(sys.argv) != 4:
print "USAGE: insert_cog_desc.py <desc_file> <in_cog> <out_cog>"
sys.exit(1)
descriptions = dict()
for line in open(sys.argv[1], 'rU'):
data = line.strip().split(' ', 2)
c | og_id = data[1]
cog_abbrev = data[0][1:-1]
cog_descr = data[2]
descriptions[cog_id] = [cog_abbrev, cog_descr]
out = open(sys.argv[3], "w")
for n, line in enumerate(open(sys.argv[2], 'rU')):
if n == 0:
out.write('%s' % line)
if n > 0:
data2 = line.strip().split(',')
data2.insert(1, descriptions[data2[0]][0])... |
damianavila/nikola | nikola/data/themes/base/messages/messages_ca.py | Python | mit | 823 | 0 | # -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"Also available in": "També disponibles en",
"Archive": "Arxiu",
"Categories": "",
"LANGUAGE": "Català",
"More posts about": "Més entrades sobre",
"Newer posts": "Entrades posteriors",
| "Next post": "Entrada següent",
"Older posts": "Entrades anteriors",
"Original site": "Lloc original",
"Posted": "Publicat",
"Posts about %s": "Entrades sobre %s",
"Posts for year %s": "Entrades de l'any %s",
"Posts for {month} {year}": "",
"Previous post": "Entrada anterior",
"Read i... | -ho en català",
"Read more": "Llegeix-ne més",
"Source": "Codi",
"Tags and Categories": "",
"Tags": "Etiquetes",
"old posts page %d": "entrades antigues pàgina %d",
}
|
Schevo/kiwi | tests/Proxies/CheckButton.py | Python | lgpl-2.1 | 1,404 | 0.009259 | #!/usr/bin/env python
import sys
sys.path.insert(0, "../..")
DEBUG = 0
if len(sys.argv) > 1:
DEBUG = 1
from Kiwi.initgtk import gtk
from Kiwi.Proxies import Proxy
from Kiwi.Models import Model
class Foo(Model):
A = 1
B = 0
class CheckProxy(Proxy):
widgets = [":B", ":A"]
def __init__(self, model)... | ndow()
self.A = gtk.ToggleButton("This is A")
self.B = gtk.ToggleButton("This is B")
vbox = gtk.VBox()
vbox.add(self.A)
vbox.add(self.B)
self.win.add(vbox)
f = Foo()
c = CheckProxy(f)
assert f.A == 1
assert f.B == 0
c.A.clicked()
c.B.clicked()
assert f.A == 0, f.A
assert... | .B == 0, f.B
c.A.clicked()
c.B.clicked()
assert f.A == 0, f.A
assert f.B == 1, f.B
if DEBUG: c.show_all_and_loop(); print f.__dict__
print "ToggleButton OK"
|
zjj/trac_hack | trac/db/sqlite_backend.py | Python | bsd-3-clause | 11,446 | 0.001136 | # -*- coding: utf-8 -*-
#
# Copyright (C)2005-2010 Edgewall Software
# Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.e... | ac, please use "
"2.5.5 or higher")
yield ('sqlite', self.error and -1 or 1)
def get_connection(self, path, log=None, params={}):
if not self._version:
self._version = get_pkginfo(sqlite).get(
'version', '%d.%d.%s' % sqlite.version_info)
... | steminfo.extend([('SQLite', sqlite_version_string),
('pysqlite', self._version)])
self.required = True
# construct list of sqlite extension libraries
if self._extensions is None:
self._extensions = []
for extpath in self.extensi... |
kgogineni/gigon | setup.py | Python | isc | 1,914 | 0.002612 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pip
from pip.req import parse_requirements
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
hist... | anguage :: English',
"Programming Language :: Python :: | 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
tests_require=test_requirements
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.