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 |
|---|---|---|---|---|---|---|---|---|
j00bar/ansible | lib/ansible/modules/cloud/amazon/ec2_ami_copy.py | Python | gpl-3.0 | 6,886 | 0.00305 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
... | ms.get('tags').items()]
)
module.exit_json(changed=True, image_id=image_id)
except WaiterError as we:
module.fail_json(msg='An error occured waiting for the image to become available. (%s)' % we.reason)
except ClientError as ce:
module.fail_json(msg=ce.message)
exce... | Exception as e:
module.fail_json(msg='Unhandled exception. (%s)' % str(e))
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
source_region=dict(required=True),
source_image_id=dict(required=True),
name=dict(default='default'),
description=dict(d... |
lucalianas/ProMort | promort/odin/permissions.py | Python | mit | 1,894 | 0.004224 | # Copyright (c) 2019, CRS4
#
# 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, publish, distribu... | orm queries using Odin toolkit
"""
RESTRICTE | D_METHODS = ['GET']
def has_permission(self, request, view):
if not (request.user and request.user.is_authenticated()):
return False
else:
if request.method in self.RESTRICTED_METHODS:
if request.user.groups.filter(
name__in=[DEFAULT_G... |
biothings/biothings_explorer | biothings_explorer/smartapi_kg/filter.py | Python | apache-2.0 | 917 | 0 | from collections import defaultdict
from .config import FILTER_FIELDS
def filterOps(ops, criteria):
"""filter an array of objects based on the filter criteria"""
all_values = defaultdict(set)
filters = {}
for op in ops:
for field in FILTER_FIELDS:
all_values[field].add(op["associa... | t(c | riteria[field])
res = []
for op in ops:
match = True
for field in FILTER_FIELDS:
if op["association"][field] not in filters[field]:
match = False
break
if match:
res.append(op)
return res
|
rolando-contrib/scrapy | tests/test_utils_url.py | Python | bsd-3-clause | 19,716 | 0.005985 | # -*- coding: utf-8 -*-
import unittest
import six
from six.moves.urllib.parse import urlparse
from scrapy.spiders import Spider
from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider,
add_http_if_no_scheme, guess_scheme,
parse_url, strip_u... | f_no_scheme('username:password@www.example.com:80/some/page/do?a=1&b=2&c=3#frag'),
'http://username:password@www.example.com:80/some/page/do?a=1&b=2&c=3#frag')
def test_preserve_http(self):
self.assertEqual(add_http_if_no_scheme('http://www | .example.com'),
'http://www.example.com')
def test_preserve_http_without_subdomain(self):
self.assertEqual(add_http_if_no_scheme('http://example.com'),
'http://example.com')
def test_preserve_http_path(self):... |
OCA/account-analytic | pos_analytic_by_config/models/pos_config.py | Python | agpl-3.0 | 318 | 0 | # | Copyright 2015 ACSONE SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class PosConfig(models.Model):
_inherit = "pos.config"
account_analytic_id = fields.Many2one(
comodel_name="account.analytic.account", stri | ng="Analytic Account"
)
|
gurneyalex/connector-magento | __unported__/magentoerpconnect_pricing/__openerp__.py | Python | agpl-3.0 | 1,568 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | ],
'author': "MagentoERPconnect Core Editors,Odoo Community Association (OCA)",
'license': 'AGPL-3',
'website': 'http://www.odoo-magento-connector.com',
'description': """
Magento Connector | - Pricing
===========================
Extension for **Magento Connector**.
The prices of the products are managed in OpenERP using pricelists and
are pushed to Magento.
""",
'images': [],
'demo': [],
'data': ['magento_model_view.xml',
],
'installable': False,
'application': False,
}
|
napjon/moocs_solution | robotics-udacity/4.13 Value Program.py | Python | mit | 2,531 | 0.02015 | # ----------
# User Instructions:
#
# Create a function compute_value() which returns
# a grid of values. Value is defined as the minimum
# number of moves required to get from a cell to the
# goal.
#
# If it is impossible to reach the goal from a cell
# you should assign that cell a value of 99.
# --------... |
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0]]
grid = [[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
delta_name... | ----------------------------------------
def compute_value():
value = [[99 for row in range(len(grid[0]))] for col in range(len(grid))]
change = True
#This function will keep running if there's "change" inside the code
while change:
change = False#default to false
for x in ra... |
jakeogh/anormbookmarker | anormbookmarker/test/tests/Word/end_letters_swapped.py | Python | mit | 939 | 0 | #!/usr/bin/env python3
from anormbookmarker.test.test_enviroment import *
with self_contained_session(CONFIG.database_timestamp) as session:
BASE.metadata.create_all(session.bind)
buffalo = Word.construct(session=session, word='Buffalo')
session.commit()
buffalo_swap = Word.construct(session=session,... | ('select COUNT(*) from aliasword;', 0),
('select COUNT(*) from bookmark;', 0),
('select COUNT(*) from filename;', 0),
('select COUNT(*) f | rom tag;', 0),
('select COUNT(*) from tag_relationship;', 0),
('select COUNT(*) from tagbookmarks;', 0),
('select COUNT(*) from tagword;', 0),
('select COUNT(*) from word;', 2),
('select COUNT(*) from wordmisspelling;', 0)]
check_db_result(config=CONFIG,... |
troika-framework/troika-http | setup.py | Python | bsd-3-clause | 2,147 | 0.000466 | #!/usr/bin/env python
import codecs
import setuptools
from troika.http import version
def read_requirements_file(name):
reqs = []
try:
with open(name, 'r') as req_file:
for line in req_file:
if line.startswith('-r'):
continue
elif '#' in... | ment :: Libraries :: Application Frameworks'
],
include_package_data=True,
install_requires=read_requirements_file('requires/installation.txt'),
extras_require={'msgpack': ['u-msgpack-python'], 'yaml': ['pyyaml']},
license='BSD',
namespace_packages=['troika'],
py_modules=['troika.http'],
... | _requirements_file('requires/testing.txt'),
test_suite='nose.collector',
zip_safe=True)
|
phenoxim/cinder | cinder/volume/drivers/coprhd/helpers/urihelper.py | Python | apache-2.0 | 2,759 | 0.000362 | # Copyright (c) 2016 EMC Corporati | on
# All Rights Reserved.
#
# 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 ... | re
# 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.
class URIHelper(object):
"""This map will be a map o... |
BatOnBots-ML/batonbots-ml | BatOnBots-ML.py | Python | gpl-3.0 | 22,017 | 0.00801 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2013 BatOnBots-ML.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(... | R = 5
# ID do timer do keepalive
timerID = -1
# Instância da classe Interface
interface | = ServerInterface()
#
EOL = "\r\n"
def auth_callback(value):
"""
Callback utilizada para a autenticação dos jogadores.
Quando um jogador termina a autenticação com ou sem sucesso, esta função é invocada.
"""
global autenticated
global playerName
global interface
... |
Jeff-Wang93/vent | tests/menu/test_menu.py | Python | apache-2.0 | 12,615 | 0.000396 | # -*- coding: utf-8 -*-
import curses
import npyscreen
from vent.helpers.paths import PathDirs
from vent.menu import VentApp
from vent.menus.main import MainForm
npyscreen.TEST_SETTINGS['CONTINUE_AFTER_TEST_INPUT'] = False
def run_menu(test_input):
""" Actually run the menu and process any input """
# init... | R, CTRL_X, 'c', 'r', TAB, TAB, TAB, TAB, TAB, TAB, TAB, TAB,
RIGHT, ENTER, ENTER, ENTER])
run_menu([ENTER, | CTRL_X, 'c', 'r', ENTER])
run_menu([ENTER, CTRL_X, 'c', 'r', CTRL_Q])
run_menu([ENTER, CTRL_X, 'c', 'r', CTRL_T])
run_menu([ENTER, CTRL_X, 'c', 't', TAB, ENTER, ENTER, ENTER])
# go through the plugins menus
run_menu([ENTER, CTRL_X, 'p', 'a', TAB, TAB, TAB, TAB, TAB, TAB, TAB, TAB,
RIG... |
bnrubin/ubuntu-bots | Lart/plugin.py | Python | gpl-2.0 | 6,326 | 0.001423 | # -*- Encoding: utf-8 -*-
###
# Copyright (c) 2005, Daniel DiPaolo
# (c) 2006, Dennis Kaarsemaker
# All rights reserved.
#
# 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 m... | return False
if user._checkCapability('owner'):
# Owners shouldn | 't ever be ignored.
return False
elif user.ignore:
return True
elif recipient:
if ircutils.isChannel(recipient):
channel = ircdb.channels.getChannel(recipient)
if channel.checkIgnored(hostmask):
return True
else:
return ... |
openstack/octavia | specs-tests/test_titles.py | Python | apache-2.0 | 4,052 | 0 | # 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 writing, software
# distributed under t... | oper impact', titles[proposed])
impl = 'Implementation'
self.assertIn(im | pl, titles)
self.assertEqual(2, len(titles[impl]))
self.assertIn('Assignee(s)', titles[impl])
self.assertIn('Work Items', titles[impl])
deps = 'Dependencies'
self.assertIn(deps, titles)
self.assertEqual(0, len(titles[deps]))
testing = 'Testing'
self.asse... |
rcgee/oq-hazardlib | openquake/hazardlib/tests/source/point_test.py | Python | agpl-3.0 | 31,027 | 0.000322 | from __future__ import division
# The Hazard Library
# Copyright (C) 2012-2016 GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at y... | .hazardlib.tom import PoissonTOM
from | openquake.hazardlib.calc import filters
from openquake.hazardlib.site import \
Site, SiteCollection, FilteredSiteCollection
from openquake.hazardlib.tests.geo.surface import \
_planar_test_data as planar_surface_test_data
from openquake.hazardlib.tests import assert_pickleable
def make_point_source(lon=1.2, ... |
skytrack/tps5 | src/lib/libharu/if/python/hpdf.py | Python | gpl-2.0 | 77,143 | 0.018524 | ##
## * << Haru Free PDF Library 2.0.8 >> -- hpdf.h
## *
## * URL http://libharu.org/
## *
## * Copyright (c) 1999-2006 Takeshi Kanno
## *
## * Permission to use, copy, modify, distribute and sell this software
## * and its documentation for any purpose is hereby granted without fee,
## * provided that the abo... | oc=HPDF_HANDLE
HPDF_Page=HPDF_HANDLE
HPDF_Pages=HPDF_HANDLE
HPDF_Stream=HPDF_HANDLE
HPDF_Image=HPDF_HANDLE
HPDF_Font=HPDF_HANDLE
HPDF_Outline=HPDF_HANDLE
HPDF_Encoder=HPDF_HANDLE
HPDF_Destination=HPDF_HANDLE
HPDF_XObject=HPDF_HANDLE
HPDF_Annotation=HPDF_HANDLE
HPDF_ExtGState=HPDF_HANDLE
#const char * HP... | F_Doc HPDF_NewEx (HPDF_Error_Handler user_error_fn, HPDF_Alloc_Func user_alloc_fn, HPDF_Free_Func user_free_fn, HPDF_UINT mem_pool_buf_size, void *user_data)
HPDF_NewEx=haru.HPDF_NewEx
HPDF_NewEx.restype=HPDF_Doc
#HPDF_Doc HPDF_New (HPDF_Error_Handler user_error_fn, void *user_data)
HPDF_New=haru.HPDF_New
HPDF... |
sanchezz93/Giga-Compiler | Entrega 5/Machine.py | Python | mit | 8,699 | 0.026325 | from Memory import *
from Giga import *
from Cube import *
def executeVirtualMachine(functions, quadruples, constants):
print("Virtual machine running...")
countQuadruples = 0
activeMemory = Memory('module', constVarCount , tempVarCount)
globalMemory = Memory('main', globalVarCount , 0)
while quadruples[c... | nts)
else:
valueVar2 = activeMemory.getVal | ueAtAddress(var2, constants)
resultValue = valueVar1 < valueVar2
activeMemory.storeValue(result, resultValue)
elif quadruple['op'] == '>':
var1 = quadruple['var1']
var2 = quadruple['var2']
result = quadruple['result']
if var1 >= 10000 and var1 < 20000:
valueVar1 = globalMemory.getValueAtAddr... |
jaddison/django-simple-elasticsearch | simple_elasticsearch/management/commands/es_manage.py | Python | bsd-3-clause | 4,680 | 0.003205 | import sys
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from ...utils import get_indices, create_indices, rebuild_indices, delete_indices
try:
raw_input
except NameError:
raw_input = input
class Unbuffered(object):
def __init__(self, stream):
... | ("Creating ES indexes: ")
results, aliases = create_indices(indices=indexes)
sys.stdout.write("complete.\n")
for alias, index in aliases:
print("'{0}' aliased to '{1}'".format(alias, | index))
def subcommand_cleanup(self, indexes=None, no_input=False):
user_input = 'y' if no_input else ''
while user_input != 'y':
user_input = raw_input('Are you sure you want to clean up (ie DELETE) {0} index(es)? [y/N]: '.format('the ' + ', '.join(indexes) if indexes else '**ALL**')).... |
RCOS-Grading-Server/HWserver | migration/migrator/migrations/master/20190528164521_numeric_id.py | Python | bsd-3-clause | 4,956 | 0.003228 | """Migration for the Submitty master database."""
def up(config, database):
"""
Run up migration.
:param config: Object holding configuration details about Submitty
:type config: migrator.config.Config
:param database: Object for interacting with given database for environment
:type database:... | urse_row.semester, course_row.course;
db_conn := format('dbname=submitty_%s_%s', course_row.semester, course_row.course);
query_string := 'UPDATE users SET user_numeric_id=' || quote_nullable(NEW.user_numeric_id) || ', user_firstname=' || quote_literal(NEW.user_firstname) || ', user_preferred_firstname=... | eferred_firstname) || ', user_lastname=' || quote_literal(NEW.user_lastname) || ', user_preferred_lastname=' || quote_nullable(NEW.user_preferred_lastname) || ', user_email=' || quote_literal(NEW.user_email) || ', user_updated=' || quote_literal(NEW.user_updated) || ', instructor_updated=' || quote_literal(NEW.instruct... |
Gateswong/GatesBlog | blog/__init__.py | Python | mit | 724 | 0.001381 | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy | import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
log | in_manager = LoginManager()
login_manager.login_view = "control_panel.login"
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
bootstrap.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .blogs import blogs as blogs_blueprint
app... |
mskovacic/Projekti | raspberrypi/isprobavanje/pyqt5/Toolbar.py | Python | mit | 1,043 | 0.01534 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
This program creates a toolbar.
The toolbar has one action, which
terminates the application, if triggered.
author: Jan Bodnar
website: zetcode.com
las | t edited: January 2015
"""
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
|
def initUI(self):
exitAction = QAction(QIcon('exit24.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
... |
miketwo/pylacuna | pylacuna/caching.py | Python | mit | 434 | 0.002304 | #!/usr/bin/env python
'''
Import this module to have access to a global redis cache named GLOBAL_CACHE.
USAGE:
from caching import GLOBAL_CACHE
GLOB | AL_C | ACHE.store('foo', 'bar')
GLOBAL_CACHE.get('foo')
>> bar
'''
from redis_cache import SimpleCache
try:
GLOBAL_CACHE
except NameError:
GLOBAL_CACHE = SimpleCache(limit=1000, expire=60*60*24, namespace="GLOBAL_CACHE")
else:
# Already defined...
pass
|
coxmediagroup/googleads-python-lib | examples/dfp/v201411/network_service/get_all_networks.py | Python | apache-2.0 | 1,545 | 0.009709 | #!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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 b... | ou have access to with the current login
credentials.
A networkCode should be left out for this request."""
__author__ = ('Nicholas Chen',
'Joseph DiLallo')
# Import appropriate modules from the client library.
from googleads import dfp
def main(client):
# Initialize appropriate service.
network_... | tAllNetworks()
# Display results.
for network in networks:
print ('Network with network code \'%s\' and display name \'%s\' was found.'
% (network['networkCode'], network['displayName']))
print '\nNumber of results found: %s' % len(networks)
if __name__ == '__main__':
# Initialize client objec... |
childe/esproxy | django_cas/middleware.py | Python | mit | 2,415 | 0.002484 | """ Django CAS 2.0 authentication middleware """
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.views import login, logout
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django_cas.exceptions import CasTicketException
fro... | ing to insert 'django.contrib.auth.middleware."
"AuthenticationMiddleware'.")
assert hasattr(request, 'user'), error
def process_view(self, request, view_func, view_args, view_kwargs):
""" Forwards unauthenticated requests to the admin page to the CAS
login URL, as wel... | if view_func == logout:
return cas_logout(request, *view_args, **view_kwargs)
# The rest of this method amends the Django admin authorization wich
# will post a username/password dialog to authenticate to django admin.
if not view_func.__module__.startswith('django.c... |
ArcherSys/ArcherSys | Lib/distutils/dep_util.py | Python | mit | 10,613 | 0.003392 | <<<<<<< HEAD
<<<<<<< HEAD
"""distutils.dep_util
Utility functions for simple, timestamp-based dependency of files
and groups of files; also, function based entirely on such
timestamp dependency analysis."""
import os
from distutils.errors import DistutilsFileError
def newer (source, target):
"""Return true if '... | OSError from inside 'stat()';
if it is "ignore", we silently drop any missing source files; if it is
"newer", any missing source files make us assume that 'target' is
out-of-date (this is handy in "dry-run" mode: it'll make you pretend to
carry out commands that wouldn't work because inputs are missing,... | oesn't even exist, then it's definitely out-of-date.
if not os.path.exists(target):
return 1
# Otherwise we have to find out the hard way: if *any* source file
# is more recent than 'target', then 'target' is out-of-date and
# we can immediately return true. If we fall through to the end
#... |
lmazuel/azure-sdk-for-python | azure-servicebus/azure/servicebus/_common_serialization.py | Python | mit | 18,799 | 0.002766 | #-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved.
#
# 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.apa... | h(name):
element_name = element_name.replace('_', '-_')
return ''.join(name.capitalize() for name in element_ | name.split('_'))
def _convert_class_to_xml(source, xml_prefix=True):
if source is None:
return ''
xmlstr = ''
if xml_prefix:
xmlstr = '<?xml version="1.0" encoding="utf-8"?>'
if isinstance(source, list):
for value in source:
xmlstr += _convert_class_to_xml(value, ... |
TaskEvolution/Task-Coach-Evolution | taskcoach/taskcoachlib/domain/attachment/__init__.py | Python | gpl-3.0 | 878 | 0 | '''
Task Coach - Your friendly task manager
Copyright (C) 2004-2013 Task Coach developers <dev | elopers@taskcoach.org>
Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Task Coach is distributed in the hope that it will be use... | HANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
from attachment import *
from attachmentowner import AttachmentOwner
from a... |
Hazelwire/Hazelwire | src/Mainframe/ClientHandler/P2PSanityCheck.py | Python | gpl-3.0 | 3,894 | 0.00642 | # Copyright (c) 2011 The Hazelwire Team.
#
# This file is part of Hazelwire.
#
# Hazelwire 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... | ul.
@type IP: string
@param IP: the IP of the VM that did the check.
"""
self.writeLock.acquire()
self.allresults.append({'results':results, 'IP':IP})
| self.writeLock.release()
def getResults(self):
"""
Waits for all the checks to finish and returns the list of all the results
@rtype: list
@return: the list of all results
"""
for thread in self.threads:
thread.join()
return self.allresults
... |
qnub/omsk-weather | setup.py | Python | lgpl-3.0 | 5,263 | 0.00399 | #!/usr/bin/env python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2012-2013 qnub <qnub.ru@gmail.com>
# This file is distributed under the license LGPL version 3 or later
### END LICENSE
###################### DO NOT TOUCH THIS (HEAD TO THE SECOND PART) #... | share/applications')
old_desktop_file = old_desktop_path + '/omweather.desktop'
desktop_path = os.path.normpath(root + prefix + '/share/applications')
desktop_file = desktop_path + '/omweather.desktop'
if not os.path.exists(old_desktop_file):
print ("ERROR: Can't find", old_desktop_file)
... | ta != prefix + '/':
# This is an /opt install, so rename desktop file to use extras-
desktop_file = desktop_path + '/extras-omweather.desktop'
try:
os.makedirs(desktop_path)
os.rename(old_desktop_file, desktop_file)
os.rmdir(old_desktop_path)
except OS... |
GeoLabs/QgsWPSClient | streaming.py | Python | gpl-2.0 | 22,331 | 0.015674 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Client for streaming based WPS.
It exploits asynchronous capabilities of WPS and QGIS for visualizing
intermediate results from a WPS
-------------------
copyright : (C) 201... | ypeRaster(self.mimeType, True) != None:
self.__chunksDir = tempfile.mkdtemp(prefix="tmpChunks")
# | Other objects
self.timer = QTimer()
self.timer.setInterval(1 * 1000) # 1 second
self.QNAM4Playlist = QNetworkAccessManager()
self.QNAM4Chunks = QNetworkAccessManager()
self.QNAM4Exception = QNetworkAccessManager()
# SIGNAL/SLOT connections
self.playlistH... |
pambot/SMSBeds | lib/jinja/tests.py | Python | gpl-2.0 | 3,403 | 0.000588 | # -*- coding: utf-8 -*-
"""
jinja.tests
~~~~~~~~~~~
Jinja test functions. Used with the "is" operator.
:copyright: 2007 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import re
number_re = re.compile(r'^-?\d+(\.\d+)?$')
regex_type = type(number_re)
def test_odd():
"""
... | value.__getitem__
except:
return False
return True
return wrapped
def test_matching(regex):
r"""
Test if the variable matches the regular expression given. Note that
you have to escape special c | hars using *two* backslashes, these are
*not* raw strings.
.. sourcecode:: jinja
{% if var is matching @/^\d+$/ %}
var looks like a number
{% else %}
var doesn't really look like a number
{% endif %}
"""
def wrapped(environment, context, value):
... |
ObsidianBlk/GemRB--Unofficial- | gemrb/GUIScripts/DualClass.py | Python | gpl-2.0 | 19,206 | 0.036551 | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003-2004 The GemRB Project
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your opt... | nload ()
return
def DCMainBackPress ():
"""Reverts all current changes and reverts b | ack to the previous step."""
global DCMainStep, DCClass, NewMageSpells
global NewPriestMask
if DCMainStep == 2: # class selected, wait to choose skills
# disable the skills button and re-enable the class button
# the class will be reset when the class button is clicked
DCMainSkillsButton.SetState (IE_GUI_BUTT... |
netdaniels/it_classified | itclassified/migrations/0020_itclog_date_update.py | Python | mit | 557 | 0.001795 | # -*- coding: utf-8 -*-
# | Generated by Django 1.11.6 on 2017-10-25 00:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('itclassified', '0019_auto_20171024_2132'),
]
operations = [
migrations.... | field=models.DateTimeField(default=django.utils.timezone.now, help_text='The date of creation', null=True),
),
]
|
stefanschleifer/kindle-newsfetch | newsfetch.py | Python | bsd-3-clause | 10,161 | 0.025096 | #!/usr/bin/env python
#
# newsfetch.py
#
# kindle-newsfetch is a simple Python script which fetches calibre recipes,
# turns them into Kindle newspapers using 'ebook-convert' and sends them to
# the configured Kindle e-mail adress using 'calibre-smtp'.
#
# (c) 2011 Stefan Schleifer, see LICENSE-file
import sys, os
im... | or while converting recipe %s" % recipe)
except Exception ,e:
print "Could not convert %s: %s." % ( os.path.join(recipes_path, recipe + ".mobi" | ), e)
# send all .mobi-files in defined output-directory
# to user via calibre-smtp
def send_ebooks():
config = ConfigParser.SafeConfigParser()
config.read(CONFIGFILE)
calibre_smtp = config.get('config', 'calibre-smtp')
# get all .mobi-files in output-dir
files = glob.glob(config.get('config', 'output_path') + ... |
teracyhq/flask-boilerplate | app/datastore.py | Python | bsd-3-clause | 4,882 | 0.001639 | # -*- coding: utf-8 -*-
"""
datastore
~~~~~~~~~
base datastore module
How to use:
- with SQLAlchemy:
datastore = SQLAlchemyDatastore(db)
- with MongoDB: (TODO(hoatle): add this)
and use the methods provided from Datastore
"""
from abc import ABCMeta, abstractmethod
from sqlalchem... | model = classes[table_names.index(table[0])]
self.model_registry[inflection.underscore(model.__name__)] = model
def commit(self):
self.db.session | .commit()
def put(self, model):
self.db.session.add(model)
# self.db.session.flush() # TODO(hoatle): do we need this, performance impact?
return model
def delete(self, model):
self.db.session.delete(model)
def get_model_class(self, model_name):
return self.model_r... |
upcounsel/PyRankinity | setup.py | Python | mit | 396 | 0.005051 | from setuptools import setup
setup(name='PyRankinity',
version='0.1',
description='Rankinity API Wrapper - See http://my.rankinity.com/api.en',
auth | or='UpCounsel',
author_email='brad@upcounsel.com',
url='https://www.github.com/upcounsel/pyrankinity',
packages=['pyrankinity'],
install_requires=[
'requests',
| ],
license='MIT'
) |
asajeffrey/servo | tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/sauce.py | Python | mpl-2.0 | 8,309 | 0.000963 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import glob
import os
import shutil
import subprocess
import tarfile
import tempfile
import time
import requests
from ... | e_executor_kwargs
from ..executors.executorselenium import (SeleniumTestharnessExecutor, # noqa: F401
SeleniumRefTestExe | cutor) # noqa: F401
here = os.path.dirname(__file__)
# Number of seconds to wait between polling operations when detecting status of
# Sauce Connect sub-process.
sc_poll_period = 1
__wptrunner__ = {"product": "sauce",
"check_args": "check_args",
"browser": "SauceBrowser",
... |
ilexius/odoo | addons/crm_partner_assign/__openerp__.py | Python | gpl-3.0 | 1,392 | 0.002874 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Partner Assignation & Geolocation',
'version': '1.0',
'category': 'Customer Relations | hip Management',
'description': """
This is the module used by Odoo SA to red | irect customers to its partners, based on geolocation.
======================================================================================================
This modules lets you geolocate Leads, Opportunities and Partners based on their address.
Once the coordinates of the Lead/Opportunity is known, they can be aut... |
pfmoore/blist | blist/test/list_tests.py | Python | bsd-3-clause | 19,502 | 0.005743 | # This file taken from Python, licensed under the Python License Agreement
from __future__ import print_function
"""
Tests common to list and UserList.UserList
"""
import sys
import os
from blist.test import unittest
from blist.test import test_support
from blist.test import seq_tests
from decimal import Decimal
d... | f.assertEqual(a, l)
a2 = a[:]
a2[:i] = a[:i]
| self.assertEqual(a2, a)
a[i:] = l[i:]
self.assertEqual(a, l)
a2 = a[:]
a2[i:] = a[i:]
self.assertEqual(a2, a)
for j in range(-3, 4):
a[i:j] = l[i:j]
self.assertEqual(a, l)
a2 = a[:]
... |
snakeleon/YouCompleteMe-x86 | third_party/ycmd/third_party/JediHTTP/vendor/jedi/jedi/api/helpers.py | Python | gpl-3.0 | 10,756 | 0.000372 | """
Helpers for the API
"""
import re
from collections import namedtuple
from jedi._compatibility import u
from jedi.evaluate.helpers import call_of_leaf
from jedi import parser
from jedi.parser import tokenize
from jedi.cache import time_cache
from jedi import common
CompletionParts = namedtuple('CompletionParts', ... | so
# impossible.
raise OnErrorLeaf(leaf)
else:
if leaf == ';':
user_stmt = leaf.parent
else:
user_stmt = leaf.get_definition()
if user_stmt.parent.type == 'simple_stmt':
user_stmt = user_stmt.parent
if is_after_newline:
| if user_stmt.start_pos[1] > position[1]:
# This means that it's actually a dedent and that means that we
# start without context (part of a suite).
return u('')
# This is basically getting the relevant lines.
return _get_code(code_lines, user_stmt.get_st... |
priestc/autotip.io | autotip_io/autotip_io/admin.py | Python | mit | 731 | 0.005472 | from django.contrib import admin
from .models import Blog, GiveawaySubmission, Article
class GiveawaySubmissionAdmin(admin.ModelAdmin):
list_display = ('date_created', 'address', 'blockchain')
def blockchain(self | , obj):
url = "https://blockchain.info/address/%s" % obj.address
return "<a href='%s' target='_blank'>Link</a>" % url
blockchain.allow_tags = True
class BlogAdmin(admin.ModelAdmin):
list_display = ('date_created', 'title', 'author')
class ArticleAdmin(admin.ModelAdmin):
list_display = ('da... | er(GiveawaySubmission, GiveawaySubmissionAdmin)
admin.site.register(Blog, BlogAdmin)
admin.site.register(Article, ArticleAdmin)
|
rwgdrummer/maskgen | tests/test_utils.py | Python | bsd-3-clause | 288 | 0.020833 | from maskgen.jpeg import utils
import unittest
from test_support import TestSupport
class TestJpegUtils(TestSupport):
def tes | t_load(self):
self.assertEqual(91,utils.estimate_qf(self.locateFile('tests/images/test_project1. | jpg')))
if __name__ == '__main__':
unittest.main()
|
PyBossa/app-darkskies | get_images.py | Python | agpl-3.0 | 1,468 | 0.001362 | # -*- coding: utf-8 -*-
# This file is part of PyBOSSA.
#
# PyBOSSA is free software: you can redistribute it | and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free | Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBOSSA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public Lice... |
pinae/ctSESAM-python-memorizing | tests/test_Crypter.py | Python | gpl-3.0 | 2,162 | 0.006013 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import unittest
from crypter import Crypter
from base64 import b64encode, b64decode
class TestCrypter(unittest.TestCase):
def test_encrypt(self):
message_string = "Important information with quite some length. " + \
"This message is as l... | +gOxOJY5fp4DecNDQnp0HyyUz2VMMh/JUYILS5+67fXq' + \
b'29CbIQ1DOTqDfqRPA62nkRVPY83cKIe/UXw=='
self.assertEqual(0, len(b64decode(ciphertext)) % 16)
password = "secret"
crypter = Crypter(Crypter.createIvKey(password.encode('utf-8'), "pepper".encode('utf-8'), iterations=3))
... | as long as this because otherwise only one cipher block would ' +
b'be encrypted. This long message insures that more than one block is needed.',
crypter.decrypt(b64decode(ciphertext)))
if __name__ == '__main__':
unittest.main()
|
HelloLily/hellolily | lily/cases/api/serializers.py | Python | agpl-3.0 | 9,977 | 0.001704 | import analytics
import anyjson
from channels import Group
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from lily.accounts.api.serializers import RelatedAccountSerializer
from lily.api.fields import SanitizedHtmlCharField
from lily.api.... | description = SanitizedHtmlCharField(
help_text='Any extra text to describe the case (supports Markdown).',
)
# Show string versions of fields.
priority_display = serializers.CharField(
source='get_priority_display',
read_only=True,
help_text='Human readable value of the cas... | contact_id = contact_id.get('id')
account_id = data.get('account', {})
if isinstance(account_id, dict):
account_id = account_id.get('id')
if contact_id and account_id:
if not Function.objects.filter(contact_id=contact_id, account_id=account_id).exists():
... |
red-hood/calendarserver | twistedcaldav/storebridge.py | Python | apache-2.0 | 150,144 | 0.003743 | # -*- test-case-name: twistedcaldav.test.test_wrapping -*-
##
# Copyright (c) 2005-2015 Apple Inc. All rights reserved.
#
# 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.o... | hmentRemoveFailed,
AttachmentDropboxNotAllowed, InvalidComponentTypeError,
TooManyAttendeesError, InvalidCalendarAccessError, ValidOrganizerError,
InvalidPerUserDataMerge,
AttendeeAllowedError, ResourceDeletedError, InvalidAttachmentOperation,
ShareeAllowedError, DuplicatePrivateCommentsError, Inval... | zone, SetComponentOptions)
from txdav.carddav.iaddressbookstore import (
KindChangeNotAllowedError, GroupWithUnsharedAddressNotAllowedError
)
from txdav.common.datastore.sql_tables import (
_BIND_MODE_READ, _BIND_MODE_WRITE,
_BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED
)
from txdav.common.icommondatastore impor... |
michaelBenin/django-jinja | django_jinja/contrib/humanize/templatetags/_humanize.py | Python | bsd-3-clause | 624 | 0.001603 | # -*- coding: utf-8 -*-
from django.contrib.humanize.templatetags import humanize
from django_jinja import l | ibrary
lib = library.Library()
@lib.filter
def ordinal(source):
return humanize.ordinal(source)
@lib.filter
def intcomma(source, use_l10n=True):
return humanize.intcomma(source, use_l10n)
@lib.filter
def intword(source):
return humanize.intword(source)
@lib.filter
def apnumber(source):
return hu... | anize.naturalday(source, arg)
@lib.filter
def naturaltime(source):
return humanize.naturaltime(source)
|
niceguydave/wagtail-cookiecutter-foundation | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/urls.py | Python | mit | 1,301 | 0.002306 | from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailsearch import urls as wagtailsearch_urls
from wagtail.wagtaildocs import urls a... |
from django.views.generic.base import RedirectView
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += [
url(r'^favicon\.ico$', RedirectView.as_view | (url=settings.STATIC_URL + 'favicon.ico', permanent=True))
]
|
hsk81/protobuf-rpc-js | example/server/py/rpc-server.py | Python | bsd-3-clause | 4,325 | 0.003699 | #!/usr/bin/env python
###############################################################################
import argparse, os
import tornado.web
import tornado.websocket
import tornado.ioloop
###############################################################################
#################################################... | )
rpc_res = Rpc.Response()
rpc_res.data = res.Seria | lizeToString()
rpc_res.id = rpc_req.id
return rpc_res.SerializeToString()
###############################################################################
###############################################################################
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def on_mes... |
asifmadnan/protobuf2uml | bin/protobuf/ProtoParser.py | Python | apache-2.0 | 86,857 | 0.010868 | # Generated from java-escape by ANTLR 4.4
from antlr4 import *
from io import StringIO
package = globals().get("__package__", None)
ischild = len(package)>0 if package is not None else False
if ischild:
from .ProtoParserListener import ProtoParserListener
else:
from ProtoParserListener import ProtoParserListene... | 2\2\\_\3\2\2\2][\3\2\2\2]^\3\2\2\2")
buf.write("^`\3\2\2\2_]\3\2\2\2`a\7\2\2\3a\13\3\2\2\2bc\7\7\2\2c")
buf.write("d\5\16\b\2de\7\34\2\2e\r\3\2\2\2fg\5\2\2\2g\17\3\2\2\2")
buf.write("hj\7\b\2\2ik\7\6\2\2ji\3\2\2\2jk\3\2\2\2kl\3\2\2\2lm\5") |
buf.write("\22\n\2mn\7\34\2\2n\21\3\2\2\2op\7 \2\2p\23\3\2\2\2qr")
buf.write("\7\t\2\2rs\5 \21\2st\7\31\2\2tu\5\32\16\2uv\7\34\2\2v")
buf.write("\25\3\2\2\2wx\7\27\2\2x}\5\30\r\2yz\7\33\2\2z|\5\30\r")
buf.write("\2{y\3\2\2\2|\177\3\2\2\2}{\3\2\2\2}~\3\2\2\2~\u0080\3")
buf.write(... |
0vercl0k/rp | src/third_party/beaengine/tests/0fc2.py | Python | mit | 11,629 | 0.005074 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This progra... | 128. | 0F.W0')
Buffer = bytes.fromhex('{}c220{:02x}'.format(myEVEX.prefix(), i))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0xc2)
assert_equal(myDisasm.infos.Instruction.Mnemonic, 'vcmp{}ps'.format(compare[i]).encode())
... |
ayust/kitnirc | kitnirc/__init__.py | Python | mit | 444 | 0 | """KitnIRC - A Python IRC Bot Framework."""
import logging
from kitnirc import client
from kitnirc import events
from kitnirc import modular
from kitnirc import user
__version__ = "0.3.1"
# Prevents output of "no handler found" if n | o other | log handlers are added
_log = logging.getLogger("kitnirc")
_log.addHandler(logging.NullHandler())
__all__ = [
"client",
"events",
"modular",
"user",
]
# vim: set ts=4 sts=4 sw=4 et:
|
saullocastro/pyNastran | pyNastran/bdf/dev_vectorized/cards/elements/solid/chexa20.py | Python | lgpl-3.0 | 13,197 | 0.001667 | from six.moves import zip
from numpy import arange, searchsorted, array, eye, ones
from numpy.linalg import norm
from pyNastran.bdf.field_writer_8 import print_card_8
from pyNastran.bdf.bdf_interface.assign_type import integer, integer_or_blank
from pyNastran.bdf.dev_vectorized.cards.elements.solid.chexa8 import quad... | ode_index_by_node_id(self.node_ids[:, 0])
i2 = self.model.grid.get_node_index_by_node_id(self.node_ids[:, 1])
i3 = self.model.grid.get_node_index_by_node_id(self.node_ids[:, 2])
i4 = self.model.grid.get_node_index_by_node_id(self.node_ids[:, 3])
i5 | = self.model.grid.get_node_index_by_node_id(self.node_ids[:, 4])
i6 = self.model.grid.get_node_index_by_node_id(self.node_ids[:, 5])
i7 = self.model.grid.get_node_index_by_node_id(self.node_ids[:, 6])
i8 = self.model.grid.get_node_index_by_node_id(self.node_ids[:, 7])
else:
... |
realms-team/solmanager | libs/smartmeshsdk-REL-1.3.0.1/libs/VManagerSDK/vmanager/models/notification.py | Python | bsd-3-clause | 4,320 | 0.000926 | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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 applica... | sys_time of this Notification.
Time of notification
:param sys_time: The sys_time of this Notification.
:type: datetime
"""
self._sys_time = sys_time
@property
def type(self):
"""
Gets the type of this Notification.
Notification type
:re... | .
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""
Sets the type of this Notification.
Notification type
:param type: The type of this Notification.
:type: str
"""
allowed_values = ["netStarted", "pathState... |
mlperf/training_results_v0.7 | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/tests/python/unittest/test_contrib_operator.py | Python | apache-2.0 | 21,277 | 0.007943 | # 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 u... | d3 = grad3[(1, 3, 2, 0), :]
expected_in_grad3[(1, 2), :] = 0
test_box_nms_forward(np.array(boxes3), np.array(expected3), force=force, thresh=thresh)
test_box_nms_backward(np.array(boxes3), grad3, expected_in_grad3, force=force, thresh=th | resh)
# case4: non-force
boxes4 = boxes
force = False
expected4 = [[2, 0.6, 0.5, 0.5, 0.7, 0.8], [0, 0.5, 0.1, 0.1, 0.2, 0.2],
[1, 0.4, 0.1, 0.1, 0.2, 0.2], [-1, -1, -1, -1, -1, -1]]
grad4 = np.random.rand(4, 6)
expected_in_grad4 = grad4[(1, 2, 3, 0), :]
expected_in_grad4[2,... |
Coelhon/MasterRepo.repository | plugin.video.psychoxxx/resources/lib/modules/client.py | Python | gpl-2.0 | 14,581 | 0.01015 | # -*- coding: utf-8 -*-
import re,sys,cookielib,urllib,urllib2,urlparse,HTMLParser,time,random,base64
from resources.lib.modules import cache
from resources.lib.modules import workers
def request(url, close=True, redirect=True, error=False, proxy=None, post=None, headers=None, mobile=False, limit=None, referer=Non... | eturn result
elif output == 'chunk':
try: content = int(response.headers['Content-Length'])
except: content = (2049 * 1024)
if content < (2048 * 1024): return
result = response.read(16 * 1024)
if close == True: response.close()
return resu... | imit == '0':
result = response.read(224 * 1024)
elif not limit == None:
result = response.read(int(limit) * 1024)
else:
result = response.read(5242880)
if 'sucuri_cloudproxy_js' in result:
su = sucuri().get(result)
headers['Cookie'] ... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/numpy/core/defchararray.py | Python | mit | 67,393 | 0.000401 | """
This module contains a set of functions for vectorized string
operations and methods.
.. note::
The `chararray` class exists for backwards compatibility with
Numarray, it is not recommended for new development. Starting from numpy
1.4, if one needs arrays of strings, it is recommended to use arrays of
... | r bool
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also
--------
| equal, not_equal, less_equal, greater, less
"""
return compare_chararrays(x1, x2, '>=', True)
def less_equal(x1, x2):
"""
Return (x1 <= x2) element-wise.
Unlike `numpy.less_equal`, this comparison is performed by first
stripping whitespace characters from the end of the string. This
behav... |
teknologkoren/Strequelistan | password_reset_email/migrations/0001_initial.py | Python | mpl-2.0 | 946 | 0.002114 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-11-01 19:27
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... | EL),
]
operations = [
migrations.CreateModel(
name='PasswordResetEmail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.CharField(max_length=100)),
('times... | TimeField(auto_now_add=True)),
('used', models.BooleanField(default=False)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
just-kir/just-kir.github.io | game_test.py | Python | mit | 295 | 0.00678 | import pygame
pygame.init()
WIDTH=600
HEIGHT=480
S | CREEN = pygame.display.set_mode((WIDTH, HEIGHT))
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
pri | nt('this DOES work! :)')
|
Hbrinj/mraa | tests/mock/i2c_checks_read.py | Python | mit | 2,420 | 0.005372 | #!/usr/bin/env python
# Author: Alex Tereschenko <alext.mkrs@gmail.com>
# Copyright (c) 2016 Alex Tereschenko.
#
# 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, includin... | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import mraa as m
import unittest as u
from i2c_checks_shared import *
class I2cChecksRead(u.TestCase):
def setUp(self):
self.i2c = m.I2c(MRAA_I2C_BUS_NUM)
def tearDown(self):
del self.i2c
def test_i2c_read_full_reg_range(self):
self.... | expected_res = bytearray([MRAA_MOCK_I2C_DATA_INIT_BYTE for i in range(MRAA_MOCK_I2C_DATA_LEN)])
res = self.i2c.read(MRAA_MOCK_I2C_DATA_LEN)
self.assertEqual(res, expected_res, "I2C read() of full register range returned unexpected data")
def test_i2c_read_part_reg_range(self):
self.i2c.address(MRAA_MO... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Ops/PyScripts/pythonPreCompiler.py | Python | unlicense | 87 | 0.011494 |
import compile | all
import dsz.lp
compileall.compile_dir(dsz.lp.GetResourcesD | irectory()) |
jkwill87/mapi | mapi/endpoints.py | Python | mit | 13,575 | 0.000221 | # coding=utf-8
from re import match
from mapi.exceptions import (
MapiNetworkException,
MapiNotFoundException,
MapiProviderException,
)
from mapi.utils import clean_dict, request_json
__all__ = [
"omdb_search",
"omdb_title",
"tmdb_find",
"tmdb_movies",
"tmdb_search_movies",
"tvdb_... | iedb.org/3/search/movie"
try:
if year:
year = int(year)
except ValueError:
raise MapiProviderException("year must be numeric")
parameters = {
"api_key": api_key,
"query": title,
"page": page,
"include_adult": adult,
"region": region,
... | eption("invalid API key")
elif status != 200 or not any(content.keys()): # pragma: no cover
raise MapiNetworkException("TMDb down or unavailable?")
elif status == 404 or status == 422 or not content.get("total_results"):
raise MapiNotFoundException
return content
def tvdb_login(api_key):
... |
franciscod/python-telegram-bot | telegram/location.py | Python | gpl-2.0 | 1,534 | 0 | #!/usr/bin/env python
#
# A library that provides a Python | interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <devs@python-telegram- | bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be us... |
jkereako/flask-skeleton | app/templates/__init__.py | Python | mit | 242 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Templates
~~~~~~~~~
View files
|
:author: Jeff Kereakoglow
:date: 2014-11-09
:copyright: (c) 2014 by Alexis Digital
:license: MIT, see LICENSE for more | details
"""
|
brightchen/h2o-3 | h2o-py/tests/testdir_hdfs/pyunit_HDFS_kmeans.py | Python | apache-2.0 | 1,795 | 0.015599 | #----------------------------------------------------------------------
# Purpose: This tests k-means on a large dataset.
#----------------------------------------------------------------------
import sys
sys.path.insert(1, "../../")
import h2o, tests
def hdfs_kmeans():
# Check if we are running inside the... | port_file(url)
n = covtype_h2o.nrow
print "rows: {0}".format(n)
assert n == 581012, "Wrong number of rows. Got {0}. Should have got {1}".format(n, 581012)
print "Running KMeans on covtype"
covtype_km = h2o.kmeans(training_frame = covtype_h2o, x = covtype_h2o[0:55], k = 8, max_it... | ovtype_km
else:
print "Not running on H2O internal network. No access to HDFS."
if __name__ == "__main__":
tests.run_test(sys.argv, hdfs_kmeans)
|
peret/visualize-bovw | util/classifierloader.py | Python | gpl-2.0 | 1,518 | 0.003294 | from sklearn.externals import joblib
import time
from . import folder_name
class ClassifierLoader(object):
"""Handles saving and loading of trained classifiers transparently."""
def __init__(self):
super(ClassifierLoader, self).__init__()
def dump_object(self, obj, classifier, category="", **kwar... | ssifier)
if not os.path.isdir(folder):
self.logger.info("Object's path doesn't exist")
return None
obj = joblib.load(os.path.join(folder, fname))
self.logger.info("% | f seconds\n" % (time.time() - t2))
return obj
except Exception as e:
self.logger.error("Joblib failed: %s" % e)
return None |
jamslevy/gsoc | app/django/forms/forms.py | Python | apache-2.0 | 17,780 | 0.00225 | """
Form classes
"""
from copy import deepcopy
from django.utils.dat | astructures import SortedDict
from django.utils.html import esca | pe
from django.utils.encoding import StrAndUnicode, smart_unicode, force_unicode
from django.utils.safestring import mark_safe
from fields import Field, FileField
from widgets import Media, media_property, TextInput, Textarea
from util import flatatt, ErrorDict, ErrorList, ValidationError
__all__ = ('BaseForm', 'Form... |
mitsuhiko/babel | tests/test_smoke.py | Python | bsd-3-clause | 1,162 | 0 | # -- encoding: UTF-8 --
"""
These tests do not verify any results and should not be run when
looking at improving test coverage. They just verify that basic
operations don't fail due to odd corner cases on any locale that
we ship. |
"""
from datetime import datetime
import pytest
from babel import Locale
from babel import dates
from babel import numbers
from babel._compat import decimal
@pytest.mark.all_locales
def test_smoke_dates(locale):
locale = Locale.parse(locale)
instant = datetime.now()
for width in ("full", "long", "medium... | nstant, format=width, locale=locale)
assert dates.format_time(instant, format=width, locale=locale)
@pytest.mark.all_locales
def test_smoke_numbers(locale):
locale = Locale.parse(locale)
for number in (
decimal.Decimal("-33.76"), # Negative Decimal
decimal.Decimal("13.37"), # Positiv... |
wasit7/book_pae | pae/forcast/src/csv/CS_table_No2_No4.py | Python | mit | 1,865 | 0.017158 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 09 14:51:02 2015
@author: Methinee
"""
import pandas as pd
import numpy as np
from collections import defaultdict
from astropy.table import Table, Column
df = pd.read_csv('../data/CS_table_No2_No4_new.csv',delimiter=";", skip_blank_lines = True,
error_... | key_sub
print "-----------------------------------------------"
#Create dictionary of list students
for std in df[headers[0]]:
if std not in students['studentId']:
students['studentId'].append(std)
countStd = countStd+1
# for keyRow in students['studentId']:
# for y in years:
... | -----"
#create table row are stdId+years+semester, column is key of subjects
column = key_sub
t = Table(column , names=(subjects['courseId']))
firstCol = students
t = Table(firstCol, names=(firstCol))
print t
"""table_No2_No4_out = pd.DataFrame(subjects)
writer = pd.ExcelWriter("table_No2_No4_fomat.x... |
mcasl/AMORE | pyAmore/tests/cython_tests/test_network_predict_strategies.py | Python | gpl-3.0 | 2,946 | 0.001358 | import unittest
from pyAmore.cython.interface import *
from pyAmore.cython.network_predict_strategies import NetworkPredictStrategy
from pyAmore.cython.materials import *
from pyAmore.cython.network_predict_strategies import MlpNetworkPredictStrategy
class TestNetworkPredictStrategy(unittest.TestCase):
def test... | network_predict_strategy = factory.make_network_predict_strategy(neural_network)
self.assertRaises(NotImplementedError, NetworkPredictStrategy.activate_neurons, network_predict_strategy)
class TestMlpPredictStrategy(unittest.TestCase):
""" Unit tests for MLpPredictStrategy
"""
def test_init... | actory()
neural_network = factory.make_primitive_network()
predict_strategy = MlpNetworkPredictStrategy(neural_network)
self.assertEqual(predict_strategy.neural_network, neural_network)
def test_call_wrong_dimensions(self):
neural_network = mlp_network([3, 2, 1], 'tanh', 'tanh')
... |
PyThaiNLP/pythainlp | pythainlp/tag/orchid.py | Python | apache-2.0 | 3,490 | 0 | # -*- coding: utf-8 -*-
"""
Data preprocessing for ORCHID corpus
"""
from typing import List, Tuple
# defined strings for special characters,
# from Table 4 in ORCHID paper
CHAR_TO_ESCAPE = {
" ": "<space>",
"+": "<plus>",
"-": "<minus>",
"=": "<equal>",
",": "<comma>",
"$": "<dollar>",
"."... | "INT": "INTJ",
# PRON
"PRON": "PRON",
"PPRS": "PRON",
"PDMN": "PRON",
"PNTR": "PRON",
# DET
"DET": "DET",
"DDAN": "DET",
"DDAC": "DET",
"DDBQ": "DET",
"DDAQ": "DET",
"DIAC": "DET",
"DIBQ": "DET",
"DIAQ": "DET",
# NUM
"NUM": "NUM",
"NCNM": "NUM",
... | E": "AUX",
# ADP
"ADP": "ADP",
"RPRE": "ADP",
# CCONJ
"CCONJ": "CCONJ",
"JCRG": "CCONJ",
# SCONJ
"SCONJ": "SCONJ",
"PREL": "SCONJ",
"JSBR": "SCONJ",
"JCMP": "SCONJ",
# PART
"PART": "PART",
"FIXN": "PART",
"FIXV": "PART",
"EAFF": "PART",
"EITT": "PART",... |
elmiko/data-goblin | datagoblin/datagoblin/wsgi.py | Python | mit | 397 | 0 | """
WSGI | config for datagoblin project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https: | //docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "datagoblin.settings")
application = get_wsgi_application()
|
ezralanglois/arachnid | arachnid/core/parallel/setup.py | Python | gpl-2.0 | 412 | 0.007282 | ''' Setup for core modules
'''
def configuration(parent | _package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('parallel', parent_package, top_path)
config.set_options(quiet=True)
config.add_subpackage('core')
return config
if __name__ == '__main__':
fro | m numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
Jwely/pivpr | py/controler/__init__.py | Python | mit | 203 | 0 | __author_ | _ = 'Jwely'
from build_tex_figs_by_run import *
from build_tex_tables import *
from synthesize_piv_uncertainty_images import *
from test_piv_dynam | ic_plots import *
from test_piv_plots import *
|
jacksonwilliams/arsenalsuite | python/scripts/conference_logger.py | Python | gpl-2.0 | 1,265 | 0.058498 | #!/usr/bin/python
# -*- coding: koi8-r -*-
import blur.Stone
import PyQt4.QtCore
from xmpp import *
import time,os,sys
app = PyQt4.QtCore.QCoreApplication(sys.argv)
blur.Stone.initConfig( 'conference_logger.ini', 'it@conference.blur.com.log' )
blur.RedirectOutputToLog()
#BOT=(botjid,password)
BOT=('thepipe@jabber.blu... | es):
nick=pres.getFrom().getResource()
text=''
if pres.getType()=='unavailable':
if nick in roster:
text=nick+' offline | '
roster.remove(nick)
else:
if nick not in roster:
text=nick+' online'
roster.append(nick)
if text: LOG(pres,nick,text)
if 1:
cl=Client(JID(BOT[0]).getDomain(),debug=[])
cl.connect()
cl.RegisterHandler('message',messageCB)
cl.RegisterHandler('presence',presenceCB)
cl.auth(JID(BOT[0]).getNode(),BOT[1]... |
fred49/linshare-cli | linsharecli/user/shared_space_audit.py | Python | gpl-3.0 | 7,635 | 0.001048 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""TODO"""
# This file is part of Linshare cli.
#
# LinShare cli 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 ... |
RESOURCE_IDENTIFIER = "uuid"
@Time('linsharecli.shared_spaces.audit', label='Global time : %(time)s')
def __call__(self, args):
super(ListCommand, self).__call__(args)
en | dpoint = self.ls.shared_spaces.audit
tbu = TableBuilder(self.ls, endpoint, self.DEFAULT_SORT)
tbu.load_args(args)
tbu.add_filters(
PartialOr(self.IDENTIFIER, args.identifiers, True),
PartialOr(self.RESOURCE_IDENTIFIER, args.uuids, True, match_raw=True),
Partia... |
GaretJax/storm-erp | cmd.py | Python | mit | 125 | 0.008 | #!/usr/bin/python3
| import sys
import os
sys.path.insert(0, os.getcwd())
from storm.cli import main
mai | n(prog_name='storm')
|
chromium/chromium | content/test/gpu/gpu_tests/maps_integration_test.py | Python | bsd-3-clause | 7,116 | 0.007729 | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
im | port os
import sys
from gpu_tests import common_browser_args as cba
from gpu_tests import color_profile_manager
from gpu_tests import gpu_integration_test
from gpu_tests import pixel_test_pages
from gpu_tests import expected_col | or_test
import gpu_path_util
from py_utils import cloud_storage
from telemetry.util import image_util
_MAPS_PERF_TEST_PATH = os.path.join(gpu_path_util.TOOLS_PERF_DIR, 'page_sets',
'maps_perf_test')
_DATA_PATH = os.path.join(gpu_path_util.GPU_DIR, 'gpu_tests')
_TEST_NAME = 'Maps... |
NorThanapon/dict-definition | definition/readers/wordnet.py | Python | gpl-3.0 | 10,980 | 0 | from neobunch import Bunch
import os
from nltk.corpus import wordnet as wn
import re
from itertools import izip
from definition.words.word_sampler import lemmatize_all
class NLTKWordNetParser(object):
def __init__(self, opt):
self.opt = opt
def to_list(self, entry,
order_keys=['word'... | top_freq = entries[0].lemma_freq
entries = filter(lambda e: e.lemma_freq == top_freq, entries)
entries = self.one_sense_per_pos(entries)
return [entries[0]]
def remove_self_ref(self, word, entries):
new_entries = []
p = re.compile(r' ' + word + r'[ ,:;"\']')
for ent... | None:
new_entries.append(entry)
return new_entries
def preprocess(self, ifp, ofp):
for line in ifp:
word = line.strip()
entries = self.get_entries(word)
entries = self.remove_self_ref(word, entries)
if self.opt.only_first_sense and le... |
mlampros/textTinyPy | setup.py | Python | gpl-3.0 | 3,293 | 0.01822 |
from setuptools import setup, Extension
from Cython.Build import cythonize
#from Cython.Compiler.Options import directive_defaults
#------------------------------------------------------------------------
# http://stackoverflow.com/questions/8106258/cc1plus-warning-command-line-option-wstrict-prototypes-is-valid-for... | yPy/cpp_src/term_matrix.cpp", "textTinyPy/cpp_src/token_big_files.cpp",
"textTinyPy/cpp_src/tokenization.cpp", "textTinyPy/cpp_src/token_stats.cpp"] | ,
extra_compile_args = tmp_comp_args,
extra_link_args = tmp_link_args,
libraries = ['armadillo'],
language="c++",
include_dirs = ['.'])
setup(name="textTinyPy",
version = '0.0.4',
... |
yelizariev/addons-yelizariev | ir_attachment_url/tests/test_product_tmpl_image.py | Python | lgpl-3.0 | 3,397 | 0.002355 | # Copyright 2019 Rafis Bikbov <https://it-projects.info/team/RafiZz>
# Copyright 2019 Alexandr Kolushov <https://it-projects.info/team/KolushovAlexandr>
# Copyright 2019 Eugene Molotov <https://it-projects.info/team/em230418>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import logging
from odo... | "name": "Test product",
"image": False,
"image_medium": | False,
"image_small": False,
"product_tmpl_id": product_tmpl.id,
}
)
odoo_image_url = self._get_odoo_image_url(
"product.product", product_product.id, "image"
)
odoo_image_medium_url = self._get_odoo_image_url(
"produc... |
mycodeday/crm-platform | website_forum/tests/common.py | Python | gpl-3.0 | 3,442 | 0.000291 | # -*- coding: utf-8 -*-
from openerp.tests import common
KARMA = {
'ask': 5, 'ans': 10,
'com_own': 5, 'com_all': 10,
'com_conv_all': 50,
'upv': 5, 'dwv': 10,
'edit_own': 10, 'edit_all': 20,
'close_own': 10, 'close_all': 20,
'unlink_own': 10, 'unlink_all': 20,
'gen_que_new': 1, 'gen_que... | 0,
'gen_ans_upv': 10, 'gen_ans_dwv': -20,
}
class TestForumCommon(common.TransactionCase):
| def setUp(self):
super(TestForumCommon, self).setUp()
Forum = self.env['forum.forum']
Post = self.env['forum.post']
# Test users
TestUsersEnv = self.env['res.users'].with_context({'no_reset_password': True})
group_employee_id = self.ref('base.group_user')
grou... |
OCA/vertical-isp | connector_equipment_service/models/agreement_serviceprofile.py | Python | agpl-3.0 | 7,516 | 0 | # Copyright (C) 2019 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, models
class AgreementServiceProfile(models.Model):
_inherit = ['agreement.serviceprofile']
@api.model
def create(self, vals):
# If SP is created with a managed ... | '))
if equip.managed:
return equip
else:
if self.equipment_id.managed:
return self.equipment_id
return False
# This method returns the appriopriate stage_id
# If there is a stage in vals, use it
# If there is no stage in vals, use the ... | _id', False) == self.env.
ref('agreement_serviceprofile.servpro_stage_draft').id) or
(not vals.get('stage_id', False) and
self.stage_id.id == self.env.
ref('agreement_serviceprofile.servpro_stage_draft').id)):
x = 'draft'
if ((vals.ge... |
novoid/Memacs | memacs/tests/photos_test.py | Python | gpl-3.0 | 888 | 0 | # -*- coding: utf-8 -*-
# Time-stamp: <2014-05-03 17:46:44 vk>
import os
import unittest
from memacs.photos import PhotosMemacs
class TestPhotoMemacs(unittest.TestCase):
def test_from_file(self):
test_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data'
)
... | ath, filename)
)
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(
data[2],
| " :ID: c2833ac1c683dea5b600ac4f303a572d2148e1e7"
)
self.assertEqual(data[3], " :END:")
|
hassaanm/stock-trading | src/pybrain/structure/networks/swiping.py | Python | apache-2.0 | 6,210 | 0.004992 | __author__ = 'Tom Schaul, tom@idsia.ch'
from pybrain.structure.networks.feedforward import FeedForwardNetwork
from pybrain.structure.connections.shared import MotherConnection, SharedFullConnection
from pybrain.utilities import iterCombinations
# TODO: special treatment for multi-dimensional lstm cells: identity conn... | mesh.componentOutdim * hiddenmesh.componentIndim, name='inconn')
if 'outconn' not in self.predefined:
self.predefined['outconn'] = MotherConnection(outmesh.componentIndim * hiddenmesh.co | mponentOutdim, name='outconn')
if 'hconns' not in self.predefined:
self.predefined['hconns'] = {}
for s in range(len(self.dims)):
if self.symmetricdirections:
if s > 0 and self.symmetricdimensions:
self.predefined['hconns'][s] =... |
itsff/Robinhood | example.py | Python | mit | 826 | 0.01816 | from Robinhood import Robinhood
#Setup
my_trader = Robinhood(username="YOUR_USERNAME", password="YOUR_PASSWORD");
#Get stock information
#Note: Sometimes more than one instrum | ent may be retur | ned for a given stock symbol
stock_instrument = my_trader.instruments("GEVO")[0]
#Get a stock's quote
my_trader.print_quote("AAPL")
#Prompt for a symbol
my_trader.print_quote();
#Print multiple symbols
my_trader.print_quotes(stocks=["BBRY", "FB", "MSFT"])
#View all data for a given stock ie. Ask price and size, bid... |
jmanday/Master | SIGE/Practicas/Practica2/resizeImages.py | Python | apache-2.0 | 1,028 | 0.001946 | import sys, os, re, traceback
from PIL import Image
from skimage.io import imread, imsave
from resizeimage import resizeimage
cwd = os.getcwd()
rootDir = cwd + '/imagenes'
for file_name in os.listdir(rootDir):
folderDir = rootDir + '/' + file_name
if (os.path.isdir(folderDir)):
fileImages = os.listdir... | 256x256
print(nameFileDir)
with open(nameFileDir, 'r+b') as f:
with Image.open(f) as image:
| cover = resizeimage.resize_cover(image, [256, 256])
cover.save(nameFileDir, image.format)
else:
with open(folderDir, 'r+b') as f:
with Image.open(f) as image:
cover = resizeimage.resize_cover(image, [256, 256])
cover.sav... |
nke001/attention-lvcsr | libs/blocks/tests/bricks/test_bricks.py | Python | mit | 15,113 | 0 | import numpy
import six
import theano
from numpy.testing import assert_allclose, assert_raises
from theano import tensor
from blocks.bricks import (Identity, Linear, Maxout, LinearMaxout, MLP, Tanh,
Sequence, Random)
from blocks.bricks.base import application, Brick, lazy, NoneAllocation
fro... | ):
application_call.add_auxiliary_variable(shared_floatx(numpy.ones((1,)),
name='test_val'))
return x
class ParentBrick(Brick):
def __init__(self, child=None, **kwargs):
super(ParentBrick, self).__init__(**kwargs)
self.c... | ren = [child]
@application
def apply(self, *args, **kwargs):
return self.child.apply(*args, **kwargs)
@application
def second_apply(self, x):
return x - 1
@second_apply.property('inputs')
def second_apply_inputs(self):
return self.child.second_apply.all
@second_ap... |
ttm/gmaneLegacy | gmaneLegacy/networkDrawer.py | Python | unlicense | 7,293 | 0.029073 | import sys
import collections as c
from scipy import special, stats
import numpy as n, pylab as p, networkx as x
class NetworkDrawer:
drawer_count=0
def __init__(self,metric="strength"):
| self.drawer_count+=1
metric_=self.standardizeName(metric)
self.metric_=metric_
self.draw_count=0
| def standardizeName(self,name):
if name in (["s","strength","st"]+["f","força","forca","fo"]):
name_="s"
if name in (["d","degree","dg"]+["g","grau","gr"]):
name_="d"
return name_
def makeLayout(self,network_measures,network_partitioning=None):
"""Delivers a... |
jonathanendersby/SimpleChat | SimpleChat/SimpleChat/settings.py | Python | gpl-2.0 | 2,172 | 0.00046 | """
Django settings for SimpleChat project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... | tion
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3o-kw!!=*b7o3mz6nmbllne##wiu7m_lz | k%9j&p@@(ecsue&f7'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'djang... |
procangroup/edx-platform | lms/djangoapps/certificates/api.py | Python | agpl-3.0 | 21,092 | 0.002134 | """Certificates API
This is a Python API for generating certificates asynchronously.
Other Django apps should use the API functions defined in this module
rather than importing Django models directly.
"""
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db.model... | k the certificate
generation task. If an error occurs while adding the certificate |
to the queue, the task will have status 'error'.
Args:
student (User)
course_key (CourseKey)
Keyword Arguments:
course (Course): Optionally provide the course object; if not provided
it will be loaded.
grade_value - The grade string, such as "Distinction"
... |
barbour-em/osf.io | tests/test_views.py | Python | apache-2.0 | 162,417 | 0.001102 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Views tests for the OSF.'''
from __future__ import absolute_import
import unittest
import json
import datetime as dt
import mock
import httplib as http
from nose.tools import * # noqa PEP8 asserts
from tests.test_features import requires_search
from modularodm import... | ous_link = PrivateLinkFactory(anonymous=True)
anonymous_link.nodes.append(self.project)
anonymous_link.save()
self.project.set_privacy('public')
self.project.save()
self.project.reload()
| auth = Auth(user=self.user, private_key=anonymous_link.key)
assert_false(has_anonymous_link(self.project, auth))
def test_has_private_link_key(self):
res = self.app.get(self.project_url, {'view_only': self.link.key})
assert_equal(res.status_code, 200)
def test_not_logged_in_no_... |
kvoss/lsystem | example-plant.py | Python | bsd-2-clause | 787 | 0.012706 | import turtle
from lsystem import LSystem
plant = dict(
axiom = 'X',
productions = {'X': 'F-[[X]+X]+F[+FX]-X', 'F':'FF'})
plantL = LSystem(**plant)
q = []
def restore():
pos, angl = q.pop()
turtle.up()
turtle.setposition(pos)
turtle.seth(angl)
turtle.down()
methods = {
'F... | mbda: q.append((turtle.pos(), turtle.heading())),
']': restore,
}
turtle.screensize(8 | 00,1200)
turtle.ht()
turtle.pencolor('green')
turtle.delay(0)
turtle.seth(75)
for c in plantL[6]:
try:
methods[c]()
except KeyError:
pass
ts = turtle.getscreen()
ts.getcanvas().postscript(file='plant6.eps')
#turtle.exitonclick()
|
joegomes/deepchem | examples/uv/UV_tf_singletask.py | Python | mit | 3,308 | 0.013301 | """
Script that trains Tensorflow Multitask models on UV dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import numpy as np
import tempfile
import shutil
import deepchem as dc
from UV_datasets import load_uv
###Load data###
shard_siz... | test_task_scores")
print(test_task_scores)
prin | t("Mean Test score")
print(test_score)
print("####################################################################")
for trial in range(num_trials):
(train_score, train_task_scores, valid_score, valid_task_scores,
test_score, test_task_scores) = all_results[trial]
print("-------------------------------------... |
alanrogers/ldpsiz | src/ini.py | Python | gpl-2.0 | 4,407 | 0.003857 | ###
# @file ini.py
# @page ini
# @author Alan R. Rogers
# @brief Functions for objects of class Ini, which reads parameters
# from an initialization file
#
# @copyright Copyright (c) 2014, Alan R. Rogers
# <rogers@anthro.utah.edu>. This file is released under the Internet
# Systems Consortium License, which can be fo... | f len(line) != 1:
print "Broken command @%s:%d. inPopHist=%d" % (ifname, lineno+1, inPopHist)
sys.exit( | 1)
if line[0] == "PopHist":
inPopHist = True
else:
assignments[line[0]] = "1"
return assignments, ph
if __name__ == '__main__':
a, ph = readIni("ldpsiz.ini")
print "basepairs:", a["basepairs"]
print "blocksize:", a["blocksize"]
print "recombi... |
shubhamgupta123/erpnext | erpnext/accounts/utils.py | Python | gpl-3.0 | 31,708 | 0.025483 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, erpnext
import frappe.defaults
from frappe.utils import nowdate, cstr, flt, cint, now, getdate
from frappe impor... | cost_center and frappe.form_dict.get("cost_center"):
cost_center = frappe.form_dict.get("cost_center")
cond = []
if date:
cond.append("posting_date <= '%s'" % frappe.db.escape(cstr(date)))
else:
# get balance of all entries that exist
date = nowdate()
if account:
acc = frappe.get_doc("Account", accoun... | eater than today
# get fiscal year for today's date and its corresponding year start date
year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
else:
# this indicates that it is a date older than any existing fiscal year.
# hence, assuming balance as 0.0
return 0.0
allow_cost_center_in_entry_of_... |
dschien/energy-aggregator | ep/tests/test_docker.py | Python | mit | 1,639 | 0.00061 | import unittest
import json
import time
from celery import current_app
from django.conf import settings
from django.utils import timezone
from ep.models import DPMeasurements, DeviceParameter
from ep.tasks import send_msg
from django.test import TestCase, modify_settings, override_settings
from ep.tests.static_fac... | s(IODICUS_MESSAGING_HOST='messaging.iodicus.net')
class TaskTest(TestCase):
def test_messaging(self):
print(settings.IODICUS_MESSAGING_HOST)
# print(settings.BROKER_URL)
self.assertTrue(send_msg.delay(json.dumps({'test': 1})))
class LocalTaskTest(TestCase):
def test_messaging(self):
... | st': 1})))
# @override_settings(INFLUXDB_HOST='52.49.171.8')
class InfluxDBTest(TestCase):
@classmethod
def setUpTestData(cls):
SiteFactory.create(name=secure_site_name)
# @unittest.skip
def test_simple_add(self):
print(settings.INFLUXDB_HOST)
m = DPMeasurements(device_paramet... |
valhallasw/phabricator-tools | py/phl/phlsys_signal.py | Python | apache-2.0 | 1,522 | 0 | """Helpers for process signals."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# phlsys_signal
#
# Public Functions:
# set_exit_on_sigterm
#
# ------------------------------------------------... | /www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi | ng, 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.
# ------------------------------ END-OF-FILE ----------------... |
gloaec/trifle | src/trifle/managers/server.py | Python | gpl-3.0 | 3,973 | 0.001007 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from trifle.managers.command import Command
from trifle.managers.option import Option
from trifle.managers.group import Group
class Server(Command):
"""
Runs the Flask development server i.e. app.run()
:param host: server host
:param p... | use_reloader),)
else:
options += (Option('-r', '--reload',
action='store_true',
dest='use_reloader',
| default=self.use_reloader),)
return options
def handle(self, app, host, port, use_debugger, use_reloader,
threaded, processes, passthrough_errors):
# we don't need to run the server in request context
# so just run it directly
app.run(host=hos... |
neurophysik/periodicitytest | tests/periodicitytest_test.py | Python | bsd-3-clause | 4,691 | 0.056065 | #! /usr/bin/env python
# Tests the Python module.
from __future__ import print_function, division
from math import *
import numpy as np
from periodicitytest import periodicitytest
import random
def pertest_noise_wrapper(T, max_tau):
noisy_T = T + np.random.uniform(0.0, nu, len(T))
return periodicitytest(noisy_T, ma... | )
test_varying_periods(lambda x: round(100*sin(x)))
test_varying_periods(lambda x: sin(x)+sin(2*x))
test_random_timeseries()
test_constant_timeseries()
for k in range(2,20):
test_period_k_timeseries(20)
test_varying_amplitude(sin)
test_varying_amplitude(cos)
test_varying_amplitude(nasty_function)
tes... | _amplitude(lambda x: round(100*sin(x)))
test_varying_amplitude(lambda x: sin(x)+sin(2*x))
test_varying_frequency(sin)
test_varying_frequency(cos)
test_varying_frequency(nasty_function)
test_varying_frequency(lambda x: x%(2*pi))
test_varying_frequency(lambda x: round(100*sin(x)))
test_varying_frequency(lambda x... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.