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 |
|---|---|---|---|---|---|---|---|---|
svastm/mbed | tools/export/codered.py | Python | apache-2.0 | 1,779 | 0.001124 | """
mbed SDK
Copyright (c) 2011-2016 ARM Limited
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 writin... | 'name': self.project_name,
'i | nclude_paths': self.resources.inc_dirs,
'linker_script': self.resources.linker_script,
'object_files': self.resources.objects,
'libraries': libraries,
'symbols': self.toolchain.get_symbols()
}
ctx.update(self.flags)
self.gen_file('codered_%s_projec... |
coxmediagroup/googleads-python-lib | examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py | Python | apache-2.0 | 3,318 | 0.006329 | #!/usr/bin/python
#
# Copyright 2015 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... | {
'nam | e': 'appId',
'fieldText': 'com.example.demogame',
'type': 'TEXT'
},
{
'name': 'appStore',
'fieldText': '2',
'type': 'ENUM'
}
]
}
# Create click to download ad.
click_to_download_app_ad = {
'xsi_type': ... |
dcos/dcos-launch | dcos_launch/gcp.py | Python | apache-2.0 | 4,208 | 0.002852 | """ Launcher functionality for the Google Compute Engine (GCE)
"""
import json
import logging
import os
from dcos_launch import onprem, util
from dcos_launch.platforms import gcp
from dcos_test_utils.helpers import Host
from googleapiclient.errors import HttpError
log = logging.getLogger(__name__)
def get_credentia... | public_key = util.generate_rsa_keypair()
self.config['ssh_private_key'] = private_key.decode()
self.config['ssh_public_key'] = public_key.decode()
def get_cluster_hosts(self) -> [Host]:
return list(self.d | eployment.hosts)[1:]
def get_bootstrap_host(self) -> Host:
return list(self.deployment.hosts)[0]
def wait(self):
""" Waits for the deployment to complete: first, the network that will contain the cluster is deployed. Once
the network is deployed, a firewall for the network and an insta... |
Khushbu27/Tutorial | swift/obj/mem_server.py | Python | apache-2.0 | 4,314 | 0 | # Copyright (c) 2010-2013 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 agreed to ... | do for the in-memory version.
:param conf: WSGI configuration parameter
"""
self._filesystem = InMemoryFileSystem()
def get_diskfile(self, device, partition, account, container, obj,
**kwargs):
"""
Utility method for instantiating a DiskFile object supp... | e that
behavior.
"""
return self._filesystem.get_diskfile(account, container, obj, **kwargs)
def async_update(self, op, account, container, obj, host, partition,
contdevice, headers_out, objdevice, policy_idx):
"""
Sends or saves an async update.
... |
manashmndl/LearningPyQt | pyqt/chap05/numberformatdlg2.py | Python | mit | 4,502 | 0.002221 | #!/usr/bin/env python
# Copyright (c) 2008-14 Qtrac Ltd. All rights reserved.
# This program or 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 2 of the License, or
# version 3 of the Lic... | "The thousands separator and the decimal marker "
"must be different.")
self.thousandsEdit.selectAll()
self.thousandsEdit.setFocus()
return
if len(decimal) == 0:
QMessageBox.warning(self, "Format Error",
"The decimal marker ... | |
jayvdb/travis_log_fetch | tests/test_historical.py | Python | mit | 5,569 | 0 | """Test loading historical builds and jobs."""
from __future__ import absolute_import, unicode_literals
from travis_log_fetch.config import _get_travispy
from travis_log_fetch._target import Target
from travis_log_fetch.get import (
get_travis_repo,
get_historical_builds,
get_historical_build,
get_his... | orical_builds(_travis, repo,
_after=12071,
_load_jobs=False) |
ids = []
prev_number = None
for build in builds:
assert build.repository_id == 12962
if int(build.number) in [12069, 12062, 12061, 12054, 12049,
12048, 12041, 12038, 12037, 12033]:
# Many duplicates
#... |
CyCraig/AtariRL | ale_python_interface/ale_python_interface.py | Python | gpl-2.0 | 10,369 | 0.001929 | # ale_python_interface.py
# Author: Ben Goodrich
# This directly implements a python version of the arcade learning
# environment interface.
from ctypes import *
import numpy as np
from numpy.ctypeslib import as_ctypes
import os
ale_lib = cdll.LoadLibrary(os.path.join(os.path.dirname(__file__),
... | reenHeight(self.obj)
screen_data = np.empty((height, width,3), dtype=np.uint8)
ale_lib.getScreenRGB(self.obj, as_ctypes(screen_data[:]))
return screen_data
def getScreenGrayscale(self, screen_data=None):
"""This function fills screen_data with the data in grayscale
scree... | e a numpy array of uint8. This can be initialized like so:
screen_data = np.empty((height,width,1), dtype=np.uint8)
If it is None, then this function will initialize it.
"""
if(screen_data is None):
width = ale_lib.getScreenWidth(self.obj)
height = ale_lib.getScr... |
Annelutfen/gittigidiyor-python | examples/applicationservice.py | Python | mit | 526 | 0.003802 | # Bu kod calismayacak, mantigi anlamak icin yazildi.
from gittigidiyor.applicationservice import *
from gittigidiyor.auth import *
if __name__ == "__main__":
# HTTP B | asic authentication credentials.. It blows up for the wrong credentials..
auth = Auth("testuser", "testpassword", None, None)
api = ApplicationServi | ce(auth)
result = api.createApplication("testdeveloper", "Test Application", "This is the test application",
"C", "W", "", "xml", "xml", "tr")
print result
|
auto-mat/klub | apps/pdf_storage/serializers.py | Python | gpl-3.0 | 1,144 | 0.000874 | from django.db.models.expressions import F, Func
from rest_framework import serializers
fr | om .models import PdfStorage
class PdfStorageListSerializer(serializers.ModelSerializer):
author = serializers.SerializerMethodField("full_name")
class Meta:
model = PdfStorage
fields = [
"id",
"name",
"topic",
"author",
| "created",
]
def full_name(self, pdf):
return pdf.author.person_name()
class PaidPdfDownloadLinkSerializer(serializers.ModelSerializer):
download_url = serializers.SerializerMethodField()
class Meta:
model = PdfStorage
fields = ["download_url"]
def get_downl... |
shamangeorge/beets | test/test_thumbnails.py | Python | mit | 11,414 | 0.000088 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Bruno Cauet
#
# 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 r... | qual(ThumbnailsPlugin().write_metadata, write_metadata_im)
self.assertTrue(ThumbnailsPlugin()._check_local_ok())
# test URI getter function
giouri_inst = mock_giouri.return_value
giouri_inst.available = True
self.assertEqual(ThumbnailsPlu | gin().get_uri, giouri_inst.uri)
giouri_inst.available = False
self.assertEqual(ThumbnailsPlugin().get_uri.__self__.__class__,
PathlibURI)
@patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok')
@patch('beetsplug.thumbnails.ArtResizer')
@patch('beetsplug.thu... |
mic4ael/indico | indico/modules/users/views.py | Python | mit | 1,654 | 0.000605 | # This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask import request
from indico.modules.admin.views import... | d
``user=self.user`` to your `render_template` call.
"""
template_prefix = 'users/'
def __init__(self, rh, active_menu_item, **kwargs):
kwargs['active_menu_item'] = active_menu_item
WPDecorated.__init__(self, rh, **kwargs)
def _get_breadcrumbs(self):
if 'user_id' in req | uest.view_args:
user = User.get(request.view_args['user_id'])
profile_breadcrumb = _('Profile of {name}').format(name=user.full_name)
else:
profile_breadcrumb = _('My Profile')
return render_breadcrumbs(profile_breadcrumb)
def _get_body(self, params):
ret... |
tkettu/rokego | distances/migrations/0011_auto_20170602_1044.py | Python | mit | 513 | 0.001949 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-06-02 | 07:44
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('distances', '0010_auto_20170519_1604'),
]
operations = [
migrations.AlterField(
model_name='dates',
n... | ),
]
|
MADindustries/WhatManager2 | bibliotik/utils.py | Python | mit | 7,895 | 0.002027 | import re
import shutil
import time
import os
import os.path
from pyquery.pyquery import PyQuery
import requests
import requests.utils
from WhatManager2.settings import MEDIA_ROOT
from bibliotik import manage_bibliotik
from bibliotik.models import BibliotikTorrent, BibliotikFulltext
from bibliotik.settings import BIB... | ata['publishers'].append({
'id': href[href.rfind('/') + 1:],
'name': dlink.text() |
})
for tag in row('td:eq(1) > span.taglist > a').items():
href = tag.attr('href')
data['tags'].append({
'id': href[href.rfind('/') + 1:],
'name': tag.text()
})
result.append(data)
return result
class BibliotikClie... |
stewartsmith/bzr | bzrlib/tests/commands/test_cat.py | Python | gpl-2.0 | 1,932 | 0.000518 | # Copyright (C) 2007, 2009, 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is dis... | foo')] | )
wt1.add('foo')
wt1.commit('add foo')
self.start_logging_connections()
cmd = cmd_cat()
cmd.run(self.get_url('branch/foo'))
self.assertEquals(1, len(self.connections))
self.assertEquals('foo', self.outf.getvalue())
|
automatthias/aubio | waflib/fixpy2.py | Python | gpl-3.0 | 1,110 | 0.067568 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os
all_modifs={}
def fixdir(dir):
global all_modifs
for k in all_modifs:
for v in all_modifs[k]:
modif(os.path.join(dir,'waflib'),k,v)
def modif(dir,name,fun):
... |
for x in os.listdir(os.path.join(dir,y)):
if x.endswith('.py'):
lst.append(y+os. | sep+x)
for x in lst:
modif(dir,x,fun)
return
filename=os.path.join(dir,name)
f=open(filename,'r')
try:
txt=f.read()
finally:
f.close()
txt=fun(txt)
f=open(filename,'w')
try:
f.write(txt)
finally:
f.close()
def subst(*k):
def do_subst(fun):
global all_modifs
for x in k:
try:
all_modifs... |
lbryio/lbry | torba/torba/server/text.py | Python | mit | 3,433 | 0 | import time
from torba.server import util
def sessions_lines(data):
"""A generator returning lines for a list of sessions.
data is the return value of rpc_sessions()."""
fmt = ('{:<6} {:<5} {:>17} {:>5} {:>5} {:>5} '
'{:>7} {:>7} {:>7} {:>7} {:>7} {:>9} {:>21}')
yield fmt.format('ID', 'Fl... | // 1024),
'{:,d}'.format(send_count),
'{:,d}'.format(send_size // 1024))
def peers_lines(data):
"""A generator returning lines for a list of peers.
data is the return value of rpc_peers()."""
def time_fmt(t):
if not t:
return 'Never'
... | {:>5} {:>20} {:<15}')
yield fmt.format('Host', 'Status', 'TCP', 'SSL', 'Server', 'Min',
'Max', 'Pruning', 'Last Good', 'Last Try',
'Tries', 'Source', 'IP Address')
for item in data:
features = item['features']
hostname = item['host']
host = feat... |
stargaser/spscviz | spscinspector.py | Python | bsd-3-clause | 15,570 | 0.008157 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vispy: gallery 30
# -----------------------------------------------------------------------------
# Copyright (c) 2015, California Institute of Technology.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# ----------------------------------------... | PanZoomCamera.viewbox_key_event(self, event)
| if event.handled or not self.interactive:
return
if event.type == 'key_press':
if event.key in self._keymap:
val = self._keymap[event.key]
self.update_index(val)
self.update_pan()
self.view_changed()
elif ev... |
Ilias95/lib389 | lib389/cli_conf/plugin.py | Python | gpl-3.0 | 4,136 | 0.005561 | # --- BEGIN COPYRIGHT BLOCK ---
# Copyright (C) 2016 Red Hat, Inc.
# All rights reserved.
#
# License: GPL (version 3 or any later version).
# See LICENSE for details.
# --- END COPYRIGHT BLOCK ---
from lib389.plugins import Plugin, Plugins
import argparse
from lib389.cli_base import (
_generic_list,
_generic... | _warn(dn, msg="Disabling %s %s" % (SINGULAR.__name__, dn))
mc = MANY(inst, basedn)
o = mc.get(dn=dn)
o.disable()
o_str = o.display()
log.info('Disabled %s', o_str)
# Plugin configure?
def plugin_configure(inst, basedn, log, args):
pass
def generic_show(inst, basedn, log, args):
"""Display... | ion."""
plugin = args.plugin_cls(inst)
log.info(plugin.display())
def generic_enable(inst, basedn, log, args):
plugin = args.plugin_cls(inst)
plugin.enable()
log.info("Enabled %s", plugin.rdn)
def generic_disable(inst, basedn, log, args):
plugin = args.plugin_cls(inst)
plugin.disable()
... |
petrjasek/superdesk-server | superdesk/io/commands/update_ingest.py | Python | agpl-3.0 | 9,268 | 0.002266 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | set=None):
all_items = filter_expired_items(provider, items)
items_dict = {doc['guid']: doc for doc in all_items}
for item in [doc for doc in all_items if doc.get('type') != 'composite']:
ingest_item(item, provider, rule_set)
for item in [doc for doc in all_items if doc.get('type | ') == 'composite']:
for ref in [ref for group in item.get('groups', [])
for ref in group.get('refs', []) if 'residRef' in ref]:
ref.setdefault('location', 'ingest')
itemRendition = items_dict.get(ref['residRef'], {}).get('renditions')
if itemRendition:
... |
ocket8888/slackbot | slackbot/modules/math/math.py | Python | gpl-3.0 | 1,975 | 0.022785 | """
Contains a function to generate and upload a LaTeX-rendered math image.
"""
import subprocess
import sys
import typing
def uploadLatex(math: typing.List[str], slackAPI: object, channel: object, users: list) -> str:
"""
| Generates a LaTeX math image from the LaTeX source contained in `math`, and posts it to the
api `slackapi` in channel `channel`.
Returns a string describing any errors that occurred.
"""
toParse = | "".join(math).replace("&","&")
# create a temporary directory
response = subprocess.run(["mktemp", "-d"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# check for errors
if response.returncode != 0 or response.stderr.decode() != '':
return "EE: latex: couldn't make temp. dir: '"+response.stderr.decode()... |
nirgal/ngw | core/migrations/0010_auto_drop_proxy_models.py | Python | bsd-2-clause | 1,407 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ngw', '0009_config_eventdefaultperms'),
]
operations = [
migrat | ions.DeleteModel(
name='ChoiceContactField',
),
migrations.DeleteModel(
name='DateContactField',
),
migrations.DeleteModel(
| name='DateTimeContactField',
),
migrations.DeleteModel(
name='EmailContactField',
),
migrations.DeleteModel(
name='FileContactField',
),
migrations.DeleteModel(
name='ImageContactField',
),
migrations.DeleteModel(
... |
jordanemedlock/psychtruths | temboo/core/Library/Google/Drive/Changes/__init__.py | Python | apache-2.0 | 223 | 0.008969 | from temboo.Library.Google.Drive.Changes.Get import Get, GetInputSet, GetResultSet, GetChoreographyExecution
from temboo.Library.Google.Drive.Changes.List import List, ListInputSet, ListResultSet, ListChoreographyExecuti | on
| |
xdevelsistemas/taiga-back-community | taiga/projects/issues/apps.py | Python | agpl-3.0 | 3,000 | 0.001668 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can r... | ived a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
from django.apps import apps
from django.db.models import signals
def connect_issues_signals():
from taiga.projects.tagging import signals as tagging_hand... | ues", "Issue"),
dispatch_uid="set_finished_date_when_edit_issue")
# Tags
signals.pre_save.connect(tagging_handlers.tags_normalization,
sender=apps.get_model("issues", "Issue"),
dispatch_uid="tags_normalization_issue")
def ... |
pranjan77/narrative | src/scripts/test_data_uploader/populate_mini_ws.py | Python | mit | 6,648 | 0.002106 | from biokbase.workspace.client import Workspace
import requests
import json
import sys
from time import time
from fix_workspace_info import fix_all_workspace_info
from pprint import pprint
kb_port = 9999
mini_ws_url = f"http://localhost:{kb_port}/services/ws"
mini_auth_url = f"http://localhost:{kb_port}/services/auth/... | ce with data and returns a dict about it.
Dict contains:
id = the workspace id
perms = the workspace permissions
correct_meta = the correct workspace metadata (for validation)
"""
print | (ws_data.keys())
narratives = ws_data['narratives']
ws_meta = ws_data['ws_meta']
ws_info = ws.create_workspace({"workspace": "NarrativeWS-{}-{}".format(idx, int(time()*1000))})
ws_id = ws_info[0]
info = {
"ws_id": ws_id,
"ws_info": ws_info,
"nar_info": [],
"perms": ws... |
germn/python-for-android | pythonforandroid/bootstraps/webview/__init__.py | Python | mit | 1,982 | 0.001514 | from pythonforandroid.toolchain import Bootstrap, current_directory, info, info_main, shprint
from pythonforandroid.util import ensure_dir
from os.path import join
import sh
class WebViewBootstrap(Bootstrap):
name = 'webview'
recipe_depends = list(
set(Bootstrap.recipe_depends).union({'genericndkbuil... | bution(self):
info_m | ain('# Creating Android project from build and {} bootstrap'.format(
self.name))
shprint(sh.rm, '-rf', self.dist_dir)
shprint(sh.cp, '-r', self.build_dir, self.dist_dir)
with current_directory(self.dist_dir):
with open('local.properties', 'w') as fileh:
f... |
Anthrocon-Reg/ubersystem | uber/tests/models/test_getter.py | Python | gpl-3.0 | 1,761 | 0.004543 | from uber.tests import *
@pytest.fixture
def attendee_id():
with Session() as session:
return session.query(Attendee).filter_by(first_name='Regular', last_name='Attendee').one().id
@pytest.fixture(autouse=True)
def mock_apply(monkeypatch):
monkeypatch.setattr(Attendee, 'apply', Mock())
return Atte... |
assert session.attendee({'id': attendee_id}).first_name == 'Regular'
assert mock_apply.called
def test_empty_get(mock_apply):
with Session() as session:
assert session.attendee({}).paid == NOT_PAID # basic sanity check
assert mock_apply.called
def test_ignore_csrf(request):
w... | gnore_csrf=True)
session.attendee({'paid': NEED_NOT_PAY}, allowed=['paid'])
request.addfinalizer(lambda: setattr(cherrypy.request, 'method', 'GET'))
cherrypy.request.method = 'POST'
session.attendee({'paid': NEED_NOT_PAY})
|
Williams224/davinci-scripts | ksteta3pi/Consideredbkg/MC_12_11104124_MagUp.py | Python | mit | 12,177 | 0.02825 | #-- GAUDI jobOptions generated on Fri Jul 17 16:39:48 2015
#-- Contains event types :
#-- 11104124 - 106 files - 1087377 events - 233.68 GBytes
#-- Extra information about the data processing phases:
#-- Processing Pass Step-124620
#-- StepId : 124620
#-- StepName : Digi13 with G4 dE/dx
#-- ApplicationN... | ig.v3r206
#-- Visible : Y
#-- Processin | g Pass Step-124834
#-- StepId : 124834
#-- StepName : Reco14a for MC
#-- ApplicationName : Brunel
#-- ApplicationVersion : v43r2p7
#-- OptionFiles : $APPCONFIGOPTS/Brunel/DataType-2012.py;$APPCONFIGOPTS/Brunel/MC-WithTruth.py;$APPCONFIGOPTS/Persistency/Compression-ZLIB-1.py
#-- DDDB : fromPreviousStep
#--... |
anhstudios/swganh | data/scripts/templates/object/mission/base/shared_base_mission.py | Python | mit | 435 | 0.048276 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY |
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Missi | on()
result.template = "object/mission/base/shared_base_mission.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
rhdedgar/openshift-tools | openshift/installer/vendored/openshift-ansible-3.4.12-1/library/modify_yaml.py | Python | apache-2.0 | 3,141 | 0.000955 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: expandtab:tabstop=4:shiftwidth=4
''' modify_yaml ansible module '''
import yaml
DOCUMENTATION = '''
---
module: modify_yaml
short_description: Modify yaml key value pairs
author: Andrew Butcher
requirements: [ ]
'''
EXAMPLES = '''
- modify_yaml:
dest: /etc/origin/... | yaml_data = yaml.safe_load(yaml_file.read())
yaml_file.close()
changes = set_key(yaml_data, yaml_key, yaml_value)
if len(changes) > 0:
if backup:
module.backup_local(dest)
yaml_file = open(dest, 'w')
yaml_string = yaml.dump(yaml_data, ... | file.close()
return module.exit_json(changed=(len(changes) > 0), changes=changes)
# ignore broad-except error to avoid stack trace to ansible user
# pylint: disable=broad-except
except Exception, e:
return module.fail_json(msg=str(e))
# ignore pylint errors related to the module_utils imp... |
gdhungana/desispec | py/desispec/scripts/fiberflat.py | Python | bsd-3-clause | 2,238 | 0.011171 | """
desispec.fiberflat
==================
Utility functions to compute a fiber flat correction and apply it
We try to keep all the (fits) io separated.
"""
from __future__ import absolute_import, division
import numpy as np
from desispec.io import read_frame
from desispec.io import write_fiberflat
from desispec.fibe... | arser.add_argument('--qafile', type=str, default=None, required=False,
help | ='path of QA file')
parser.add_argument('--qafig', type = str, default = None, required=False,
help = 'path of QA figure file')
args = None
if options is None:
args = parser.parse_args()
else:
args = parser.parse_args(options)
return args
def main(args) :
... |
wufangjie/leetcode | 335. Self Crossing.py | Python | gpl-3.0 | 1,217 | 0.012325 | class Solution(object):
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
inf = float('inf')
n = len(x)
if n < 3:
return False
ruld = [0, 0, 0, 0] # right, up, left, down
next_max = inf
current = [-x[1], ... | pn = | 1 if i in {0, 3} else -1
new = current[xy] + pn * elem
if pn * new > pn * ruld[i - 3]:
next_max = inf
else:
if next_max is inf and pn * new >= pn * ruld[i - 1]:
ruld[i - 2] = ruld[i]
next_max = abs(ruld[i - 2] - cu... |
hangarunderground/tiempo | tiempo/__init__.py | Python | gpl-2.0 | 183 | 0 | PROJECT_PATH = __path__[0]
TIEMPO_REGISTRY = {}
REDIS_GROUP_NAMESPACE = 'tiempogroup'
| RECENT_KEY = 'tiempo:recent_tasks'
RESULT_PREFIX = 'tiempo:task_result'
__version__ = "1. | 2.3"
|
Phonebooth/depot_tools | presubmit_canned_checks.py | Python | bsd-3-clause | 40,994 | 0.011538 | # Copyright (c) 2012 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.
"""Generic presubmit checks that can be reused by other presubmit checks."""
import os as _os
_HERE = _os.path.dirname(_os.path.abspath(__file__))
###... |
# Check that the file ends in one and only one newline character.
if len(contents) > 1 and (contents[-1:] != '\n' or contents[-2:-1] == '\n'):
eof_files.a | ppend(f.LocalPath())
outputs = []
if cr_files:
outputs.append(output_api.PresubmitPromptWarning(
'Found a CR character in these files:', items=cr_files))
if eof_files:
outputs.append(output_api.PresubmitPromptWarning(
'These fil |
prescott66/Cnchi | src/encfs.py | Python | gpl-3.0 | 3,865 | 0.001035 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# encfs.py
#
# Copyright 2013 Antergos
#
# 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 opti... | = os.path.join(dest_dir, "etc/pam.d/system-login")
shutil.copy(name, name + ".cnchi")
with open(name, "a") as system_login:
system_login.write("# Added by Cnchi - Antergos Installer\n")
system_login.write("session required\tpam_encfs.so\n")
system_login.write("session optional\tpam_mount... | "etc/pam.d/system-auth")
shutil.copy(name, name + ".cnchi")
with open(name, "a") as system_auth:
system_auth.write("# Added by Cnchi - Antergos Installer\n")
system_auth.write("auth sufficient\tpam_encfs.so\n")
system_auth.write("auth optional\tpam_mount.so\n")
# Setup finished
... |
ctag/cpe453 | JMRI/jython/Jynstruments/Launchers/DecoderPro.jyn/DecoderPro.py | Python | gpl-2.0 | 744 | 0.021505 |
import jmri.jmrit.jython.Jynstrument as Jynstrument
import jmri.jmrit.catalog.NamedIcon as NamedIcon
import jmri.jmrit.symbolicprog.tabbedframe.PaneOpsProgAction as PaneOpsProgAction
import javax.swing.JButton as JButton
class DecoderPro(Jynstrument):
def getExpectedContextClassName(self):
return "javax.s... | eners()[0]) # In order to get the popupmenu on the button too
jbNew.setToolT | ipText( jbNew.getText() )
jbNew.setText( None )
self.add(jbNew)
def quit(self):
pass |
vivekanand1101/pontoon | pontoon/base/__init__.py | Python | bsd-3-clause | 561 | 0 | """Application base, containing global templates."""
default_app_config = 'pontoon.base.apps.BaseConfig'
MOZILLA_REPOS = (
'ssh://hg.mozilla.org/users/m_owca.info/firefox-aur | ora/',
'ssh://hg.mozilla.org/users/m_owca.info/firefox-for-android-aurora/',
'ssh://hg | .mozilla.org/users/m_owca.info/thunderbird-aurora/',
'ssh://hg.mozilla.org/users/m_owca.info/lightning-aurora/',
'ssh://hg.mozilla.org/users/m_owca.info/seamonkey-aurora/',
)
class SyncError(RuntimeError):
"""Error class for errors relating to the project sync process."""
|
danmt/NEO | Codigo_Fuente/etapa4/Instrucciones/Arbol_Sintactico_Abstracto.py | Python | gpl-3.0 | 428 | 0.044393 | from Estructura import espaceado
class Arbol_Sintactico_Abstracto:
def __init__(self,alc | ance,hijos):
self.hijos = hijos
self.alcance = alcance
self.cont = 1
def imprimir(self,tabulacion):
if (len(self.hijos) > 1):
print tabulacion + "SECUENCIA"
for hijo in self.hijos:
hijo.nivel = 1
hijo.imprimir(espaceado(tabulacion))
def ejecutar(self):
for hijo in self.hijos | :
hijo.nivel = 1
hijo.ejecutar() |
IBMStreams/streamsx.health | test/test-builds.py | Python | apache-2.0 | 792 | 0.001263 | import glob
from subprocess import call
test_failures = {}
test_successes = {}
files = [file for file in glob.glob('../**/build.gradle', recursive=True)]
for f in files:
if f.startswith('../test'):
continue
# clean all projects in the platform before executing build
print("Cleaning all projects f... |
print("Executing " + f + "...")
rc = call(['../gradlew', '-b', f, 'build'])
if rc == 0:
test_successes[f] = rc
else:
test_failure | s[f] = rc
print("Return code: " + str(rc))
print("FAILURES:")
for key in test_failures:
print(key + ": " + "FAILED(rc=" + str(test_failures[key]) + ")!")
print("\n\n")
print("SUCCESSES:")
for key in test_successes:
print(key + ": PASS")
|
JulienMcJay/eclock | windows/Python27/Lib/site-packages/pygments/filters/__init__.py | Python | gpl-2.0 | 11,486 | 0.000871 | # -*- coding: utf-8 -*-
"""
pygments.filters
~~~~~~~~~~~~~~~~
Module containing filter lookup functions and default
filters.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.token import String, Comment, Ke... | :
`excclass` : Exception class
The exception class to | raise.
The default is `pygments.filters.ErrorToken`.
*New in Pygments 0.8.*
"""
def __init__(self, **options):
Filter.__init__(self, **options)
self.exception = options.get('excclass', ErrorToken)
try:
# issubclass() will raise TypeError if first argument is not a... |
collingreen/yaib | plugins/baseplugin.py | Python | mit | 5,580 | 0 | class BasePlugin(object):
"""
Extend this/copy its structure to create plugins. Your plugin
class must be `Plugin` to be loaded. Can include commands (command_*),
admin commands (admin_). Additionally, yaib will look functions for
many of the connection events.
Any commands with a docstr... | message
)
def action(self, channel, action):
"""Send an action in the given channel."""
return self.yaib.action(channel, action)
def onPluginsLoaded(self):
"""Called when ALL the plugins are loaded."""
pass
def onNickChange(self, nick, old_nick):
... | """Called when connected to a server."""
pass
def onMessageOfTheDay(self, message):
"""Called with the server's message of the day."""
pass
def onNotification(self, user, nick, channel, message):
"""Called when noticed"""
pass
def onUserAction(self, us... |
DXCanas/content-curation | contentcuration/contentcuration/migrations/0039_auto_20161101_1555.py | Python | mit | 1,022 | 0.001957 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-01 22:55
from __future__ import unicode_literals
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
('contentcuration', '0038_contentnode_author'),
]
operations = [
... | ercise_graphie', 'Exercise Graphie'), ('channel_thumbnail', 'Channel Thumbnail')], max_length=150, primary_key=True, serialize=False),
| ),
]
|
bdang2012/taiga-back-casting | taiga/base/api/urlpatterns.py | Python | agpl-3.0 | 3,316 | 0.000302 | # Copyright (C) 2014-2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014-2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | return ret
|
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
"""
Supplement existing urlpatterns with corresponding patterns that also
include a ".format" suffix. Retains urlpattern ordering.
urlpatterns:
A list of URL patterns.
suffix_required:
If `True`, only ... |
hassaanm/business-articles | downloadReturns.py | Python | apache-2.0 | 3,618 | 0.004422 | #!/usr/local/bin/python
import sys
import urllib
import urllib2
import json
import datetime
YAHOO_URL = 'http://query.yahooapis.com/v1/public/yql?env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json&diagnostics=true&q='
def getJSON(fileName):
f = open(fileName)
jsonData = json.load(f)
f.close()
... | argv[4])
jsonData = getJSON(inputFile)
if sys.argv[1] == 'snippet':
jsonToWrite = returnsJSONSnippet(jsonData, days)
elif sys.argv[1] == 'full':
jsonT | oWrite = returnsJSONFull(jsonData, days)
writeJSON(jsonToWrite, outputFile)
|
tao12345666333/Talk-Is-Cheap | ansible/group.py | Python | mit | 227 | 0 | #!/us | r/bin/env python
# coding=utf-8
import json
import sys
data = {
'g1' | : {
'hosts': [
'172.17.0.2'
]
}
}
with open('w.log', 'w') as f:
f.write(str(sys.argv))
print json.dumps(data)
|
gutosurrex/feed2twister | flask_app/captcha.py | Python | gpl-3.0 | 1,492 | 0.032842 | import random
import Image
import ImageFont
import ImageDraw
import ImageFilter
import hashlib
from random_words import RandomWords
def gen_captcha(text, fnt, fnt_sz, file_name, fmt='JPEG'):
"""Generate a captcha image"""
# randomly select the foreground color
fgcolor = random.randint(0,0xffff00)
# make the backg... | 00 random colored boxes on the background
for num in range(100):
d.rectangle((r(0,x),r(0,y),r(0,x),r(0,y)),fill=r(0,0xffffff))
# add the text to the image
d.text((3,3), text, font=font, fill=fgcolor)
im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
# save the image to a file
im.save(file_name, format=fmt)
def new... | rd():
rw = RandomWords()
word = rw.random_word()
return word, hashlib.sha224(word).hexdigest()
if __name__ == '__main__':
"""Example: This grabs a random word from the dictionary 'words' (one
word per line) and generates a jpeg image named 'test.jpg' using
the truetype font 'porkys.ttf' with a font size of 25.
... |
JTarball/docker-django-polymer | docker/app/app/backend/apps/accounts/test_views.py | Python | gpl-2.0 | 42,275 | 0.005417 | """
accounts.test_views
===================
Tests the REST API calls.
Add more specific social registration tests
"""
import responses
from django.core.urlresolvers import reverse
from django.core import mail
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
... | entials. """
get_user_model().objects.create_user('admin', 'admin@email.com', 'password12')
response = self.client.post(self.login_url, self.reusable_user_data, format='json')
self.assertEquals(response.status_code, status.HTTP_200_OK, "Snap! Basic Login has failed with a helper | function 'create_user_and_login'. Something is really wrong here.")
self.client.credentials(HTTP_AUTHORIZATION='Token ' + response.data['key'])
def _generate_uid_and_token(self, user):
result = {}
from django.utils.encoding import force_bytes
from django.contrib.auth.tokens import d... |
mateoqac/unqTip | language/vgbs/web/forms.py | Python | gpl-3.0 | 6,865 | 0.004661 | import web
import base
import local
def orNone(a, b):
if a is None:
return b
return a
class Field(object):
def __init__(self, name, description, primary=False, validator=None):
self.name = name
self.primary = primary
self.description = description
if validator == ... | ))
if metaself.table is not None and metaself.add_action is None:
local.db.insert(metaself.table, **dictionary)
if metaself.add_action is not None:
metaself.add_action(dictionary)
else:
rais... | metaself = self
class C(parent_class):
role_required = self.role
def request(self):
dictionary = {}
if metaself.remove_action is not None:
metaself.remove_action(dictionary)
return C
|
unintended/Cohen | tests/backends/test_ampache_storage.py | Python | mit | 4,553 | 0.001098 | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2014, Hartmut Goebel <h.goebel@goebel-consult.de>
"""
Test cases for L{backends.ampache_storage}
"""
from lxml import etree
from twisted.trial import unittest
from coherence.backends import ampache... | trate>248916</bitrate>
<mode>vbr</mode>
<mime>audio/mpeg</mime>
<url><![CDATA[http://songserver/ampache/play/index.php?ssid=1e11a4&type=song&oid=3440&uid=4&name=Led%20Zeppelin%20-%20Achilles%20Last%20Stand.mp3]]></url>
<size>19485595</size>
<mbid></mbid>
<album_mbid></album_mbid>
<ar | tist_mbid></artist_mbid>
<art><![CDATA[http://songserver/ampache/image.php?id=359&object_type=album&auth=1e11a40&name=art.]]></art>
<preciserating>0</preciserating>
<rating>0</rating>
<averagerating></averagerating>
</song>
</root>
'''
class DummyStore:
def __init__(self):
pass
proxy = False
... |
r0qs/chubby | Fonte/Command.py | Python | gpl-3.0 | 1,775 | 0.023662 | from pygame import K_UP, K_DOWN, K_LEFT, K_RIGHT
from Caracter import Caracter
class CommandHandler(object):
#0 1 2 3 4 5 6 7 8 9 10 11 12 13
_automata_transitions= [[11,11,0, 4, 0, 0, 11,11,0, 11,0, 11,13,0],#up
[9, 2, 0, 0, 0, 0, 9, 9, 0, 0, 0, 1... | [0, 6, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],#left
[1, 0, 0, 0, 5, 0, 7, 0, 0, 0, 0, 1, 0, 0]]#right
# The final states
final_list = [3,7,9,11,13]
final_state = 0
def __init__(self, caracter):
| self.caracter = caracter
self.actual_state = 0
def refresh_state(self, in_key):
self.final_state = 0
input_code = -1
if in_key == K_UP: input_code = 0
elif in_key == K_DOWN: input_code = 1
elif in_key == K_LEFT: input_code = 2
elif in_key == K_RIGHT: input_... |
goyalsid/phageParser | parserscripts/crispr_db_parser.py | Python | mit | 3,791 | 0.000528 | """
CRISPR_db_parser
Madeleine Bonsma
March 7, 2015
Updated May 3, 2016
This script takes a list of spacers downloaded from the CRISPRdb
website and splits them into individual files, one file per organism.
Result files are saved in "data/spacers".
"""
import linecache
import os
# CRISPR db parser
# MB Mar 07 2015
... | ounter += 1
# this part of the header is the NCBI accession
refseq = line[0:9]
if refseq not in refseq_list:
# open new file if it's a new bacteria
refseq_dict[refseq] = open(
"data/spacers/%s.fasta" % refseq,
"w... | # include in header the locus identifier and spacer
# position identifier
writeline = line[10:i]
writeline2 = writeline.replace('_', '.')
else:
# if it's only one bacteria
writeline = line[10:]
... |
rahulunair/nova | nova/db/sqlalchemy/api_migrations/migrate_repo/versions/059_add_consumer_generation.py | Python | apache-2.0 | 1,178 | 0.000849 | # 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
# d... | er express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sqlalchemy im | port Column
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import text
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
consumers = Table("consumers", meta, autoload=True)
if not hasattr(consumers.c, "generation"):
... |
libo/Enigma2 | lib/python/Screens/ScanSetup.py | Python | gpl-2.0 | 45,681 | 0.032924 | from Screen import Screen
from Screens.DefaultWizard import DefaultWizard
from ServiceScan import ServiceScan
from Components.config import config, ConfigSubsection, ConfigSelection, \
ConfigYesNo, ConfigInteger, getConfigListEntry, ConfigSlider, ConfigEnableDisable
from Components.ActionMap import NumberActionMap, Ac... | cable_search_container = eConsoleAppContainer()
self.cable_search_container.appClosed.append(self.cableTransponderSearchClosed)
self.cable_search_container.dataAvail.append(self.getCableTransponderData)
cableConfig = config.Nims[nim_idx].cable
tunername = nimmanager.getNimName(nim_idx)
try:
bus = nimmanage... | getI2CDevice(nim_idx)
if bus is None:
print "ERROR: could not get I2C device for nim", nim_idx, "for cable transponder search"
bus = 2
except:
# older API
if nim_idx < 2:
if HardwareInfo().get_device_name() == "dm500hd":
bus = 2
else:
bus = nim_idx
else:
if nim_idx == 2:
... |
nikesh-mahalka/nova | nova/tests/unit/virt/libvirt/fake_os_brick_connector.py | Python | apache-2.0 | 1,443 | 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
# d... | 604b019419']
props['wwnns'] = ['200010604b019419']
props['multipath'] = multipath
props['platform'] = 'x86_64'
props['os_type'] = 'linux2'
return props
class ISCSIConnector(object):
"""Mimick the iSCSI connector."""
def __init__(self, root_helper, driver=None,
execute=Non... | or(self):
return "fake_iscsi.iqn"
|
tseaver/google-cloud-python | asset/google/cloud/asset_v1p2beta1/gapic/transports/asset_service_grpc_transport.py | Python | apache-2.0 | 7,923 | 0.001262 | # -*- coding: utf-8 -*-
#
# Copyright 2019 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 obt | ain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CON | DITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import google.api_core.grpc_helpers
import google.api_core.operations_v1
from google.cloud.asset_v1p2beta1.proto import asset_service_pb2_grpc
class AssetServiceGrp... |
letsencrypt/letsencrypt | certbot-nginx/tests/http_01_test.py | Python | apache-2.0 | 10,269 | 0.003019 | """Tests for certbot_nginx._internal.http_01"""
import unittest
import josepy as jose
try:
import mock
except ImportError: # pragma: no cover
from unittest import mock # type: ignore
from acme import challenges
from certbot import achallenges
from certbot.tests import acme_util
from certbot.tests import util ... | ves.call_count, 5*2)
def test_mod_config_insert_bucket_directive(self):
nginx_conf = self.http01.configurator.parser.abs_path('nginx.conf')
| expected = ['server_names_hash_bucket_size', '128']
original_conf = self.http01.configurator.parser.parsed[nginx_conf]
self.assertFalse(util.contains_at_depth(original_conf, expected, 2))
self.http01.add_chall(self.achalls[0])
self.http01._mod_config() # pylint: disable=protected-acc... |
EasyCTF/easyctf-2015 | api/problems/programming/addition/addition_grader.py | Python | mit | 225 | 0.04 | def grade(tid, answer):
if answer.find("'twas_sum_EZ_programming,_am_I_rite?") != -1:
return { "correct": True, "message": "Nice job!" | }
return { " | correct": False, "message": "If you're confused, read some tutorials :)" } |
BrutusTT/pyJD | pyJD/EZModule.py | Python | agpl-3.0 | 8,093 | 0.011121 | ####################################################################################################
# Copyright (C) 2016 by Ingo Keller, Katrin Lohan #
# <brutusthetschiepel@gmail.com> #
# ... | resource_finder = yarp.ResourceFinder()
resource_finder.setVerbose(True)
# resource_finder.configure(argc,argv);
module = module_cls(args.ip, args.port, args.name)
module.runModule(res | ource_finder)
yarp.Network.fini()
|
udoyen/pythonlearning | 1-35/ex14.py | Python | mit | 808 | 0 | from sys import argv
script, user_name = argv
# Decalare text or prompt to be seen by the user
# for all request for inout
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
# The 'prompt = >' is seen by user as the... | asked for some input
computer = raw_input(prompt)
print "" | "
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
|
NervanaSystems/neon | neon/data/text.py | Python | apache-2.0 | 22,858 | 0.001181 | # ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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... | Returns:
str, str : Paths to train file and validation file
"""
text = open(path).read()
# create train and valid paths
filename, ext = os.path.splitext(path)
train_path = filename + '_train' + ext
| valid_path = filename + '_valid' + ext
# split data
train_split = int(len(text) * (1 - valid_split))
train_text = text[:train_split]
valid_text = text[train_split:]
# write train file
with open(train_path, 'w') as train_file:
train_file.write(train_text... |
RalpH-himself/MusicLibrarySyncForMSC | mlsPlaylist.py | Python | gpl-3.0 | 3,927 | 0.003056 | # Playlist.py
#
# reads all available playlists, adjusts song paths, removes not copied songs,
# writes resulting playlist to destination
import mlsSong as sng
import config
import glob
import os
import sys
import codecs
def Playlist():
# get a list of all playlists
playlists = glob.glob(config.SOURCE_PL... | [0] == oldPlaylist:
newPlaylist = lutPlaylist[1]
print "Playlist name conversion: from", oldPlaylist, "to", newPlaylist
break
if newPlaylist == "":
print "No playlist name conversion found for", oldPlaylist
break
# "s" as in Sourc... | try:
s = codecs.open(config.SOURCE_PLAYLISTFOLDER + "\\" + oldPlaylist, 'r', encoding='UTF-8')
## s = open(config.SOURCE_PLAYLISTFOLDER + "\\" + oldPlaylist, 'r')
except:
print "Playlist", oldPlaylist, "could not be read!"
continue
# "d" as in Destination_... |
mozilla/firefox-flicks | vendor-local/lib/python/celery/utils/mail.py | Python | bsd-3-clause | 5,402 | 0 | # -*- coding: utf-8 -*-
"""
celery.utils.mail
~~~~~~~~~~~~~~~~~
How task error emails are formatted and sent.
"""
from __future__ import absolute_import
import sys
import smtplib
import socket
import traceback
import warnings
from email.mime.text import MIMEText
from .functional import maybe_list
from ... | _whitelist', None) or ()
def should_send(self, context, exc):
"""Returns true or false depending on if a task error mail
should be sent for this type of error."""
allow_classes = tuple(map(symbol_by_name, self.error_whitelist))
| return not self.error_whitelist or isinstance(exc, allow_classes)
def format_subject(self, context):
return self.subject.strip() % context
def format_body(self, context):
return self.body.strip() % context
def send(self, context, exc, fail_silently=True):
if self.should_send(c... |
IceflowRE/MR-eBook-Downloader | tests/tools_test.py | Python | gpl-3.0 | 762 | 0 | from unidown.tools import unlink_dir_rec
class TestDeleteDirRec:
def test_non_existence(self, tmp_path):
no_folder = tmp_path.joinp | ath("./donotexist/")
assert not no_folder.exists()
unlink_dir_rec(no_folder)
assert not no_folder.exists()
def test_recursive(self, tmp_path):
for number in range(1, 4):
with tmp_path.joinpath(str(number)).open('w'):
pass
sub_folder = tmp_path.jo... |
with sub_folder.joinpath(str(number)).open('w'):
pass
tmp_path.joinpath("sub2").mkdir()
unlink_dir_rec(tmp_path)
assert not tmp_path.exists()
|
janol77/flask-app | app/libs/validators.py | Python | gpl-3.0 | 775 | 0 | """Validators class."""
# -*- coding: utf-8 -*-
from wtforms import ValidationError
class UniqueValidator(object):
"""Validador para chequear variables unicas."""
def __init__(self, model, field, message=None):
self.model = model
self.fie | ld = field
if not message:
message = u'Existe otro Elemento con el mismo valor.'
self.message = message
def | __call__(self, form, field):
_id = None
params = {self.field: field.data,
'deleted': False}
existing = self.model.objects.filter(**params).first()
if 'id' in form.data:
_id = str(form.id.data)
if existing and (_id is None or _id != str(existing.id)):... |
nathanielvarona/airflow | tests/providers/amazon/aws/hooks/test_s3.py | Python | apache-2.0 | 25,423 | 0.002085 | #
# 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... | )
assert ['dir/b'] == hook.list_keys(s3_bucket, prefix='dir/')
def test_list_keys_paged(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
keys = [str(i) for i in range(2)]
| for key in keys:
bucket.put_object(Key=key, Body=b'a')
assert sorted(keys) == sorted(hook.list_keys(s3_bucket, delimiter='/', page_size=1))
def test_check_for_key(self, s3_bucket):
hook = S3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key='a', Body=b'a'... |
thelabnyc/django-oscar-wfrs | src/wellsfargo/migrations/0008_fraudscreenresult.py | Python | isc | 1,998 | 0.001502 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-10-02 21:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("order", "0004_auto_20160111_1108"),
("wellsfargo", ... | , models.DateTimeField(auto_now=True)),
(
"order",
models.ForeignKey(
on_delete=django.db.models.dele | tion.CASCADE, to="order.Order"
),
),
],
options={
"ordering": ("-created_datetime", "-id"),
},
),
]
|
qinggeng/tools | MatrixSkatch/shell.py | Python | unlicense | 2,810 | 0.041637 | #-*- coding: utf-8 -*-
import os, re
from traceback import format_exc as fme
from exprParser import Parser, ParserContext
class Shell:
echo = False
echoStrs = {
'on': True,
'off': False,
'true': True,
'false': False,
}
commands = {}
history = []
values = []
ops = []
def processEchoCommand(self, args):
... | makeHistoryCommandArgs(self, args):
h = self.history
if len(args) > 0:
arg = args[0]
if arg.isdigit():
return int(arg)
return len(h)
def processHistoryCommand(self, args):
h = self.history
historyLen = self.makeHistoryCommandArgs(args)
for item, i in zip(h, reversed(range(historyLen))):
self... | def msg(self, txt):
print txt
def error(self, msg):
print msg
def installCommands(self):
c = self.commands
c[':echo'] = self.processEchoCommand
c[':exit'] = self.processExitCommand
c[':history'] = self.processHistoryCommand
c[':ops'] = self.processOps
def inputOperation(self, userInput):
parser =... |
bparzella/secsgem | secsgem/secs/variables/u1.py | Python | lgpl-2.1 | 1,183 | 0 | #####################################################################
# u1.py
#
# (c) Copyright 2021, Benjamin Parzella. All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundat... | his software 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 Lesser General Public License for more details.
#####################################################################
"""... | Secs type for 1 byte unsigned data.
:param value: initial value
:type value: list/integer
:param count: number of items this value
:type count: integer
"""
format_code = 0o51
text_code = "U1"
_base_type = int
_min = 0
_max = 255
_bytes = 1
_struct_code = "B"
preferr... |
ansp-2015/arquea | menuextension/models.py | Python | mpl-2.0 | 652 | 0.001534 | # -* | - coding: utf-8 -*-
# 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/.
from django.db import models
from django.utils.transl | ation import ugettext_lazy as _
from django.template import Library
from treemenus.models import MenuItem
register = Library()
class MenuItemExtension(models.Model):
menu_item = models.OneToOneField(MenuItem, related_name="extension")
visivel = models.BooleanField(default=False)
css = models.CharField(_... |
Banjong1990/honey | dpkt/dpkt/icmp.py | Python | gpl-2.0 | 4,112 | 0.034776 | # $Id: icmp.py,v 1.1.1.1 2005/10/29 18:20:48 provos Exp $
from dpkt import Packet, in_cksum as _icmp_cksum
import ip
# Types (icmp_type) and codes (icmp_code) -
# http://www.iana.org/assignments/icmp-parameters
ICMP_CODE_NONE = 0 # for types without codes
ICMP_ECHOREPLY = 0 # echo reply
ICMP_UNREACH = 3 # dest u... | service
ICMP_RTRADVERT = 9 # router advertise, codes:
ICMP_RTRADVERT_NORMAL = 0 # normal
ICMP_RTRADVERT_NOROUTE_COMMON = 16 # selective routing
ICMP_RTRSOLICIT = 10 # router solicitation
ICMP_TIMEXCEED = 11 # time exceeded, code:
ICMP_TIMEXCEED_INTRANS = 0 # ttl==0 in transit
ICMP_TIMEXCEED_REASS = 1 # ttl==0 in... | MPROB_LENGTH = 2 # bad length
ICMP_TSTAMP = 13 # timestamp request
ICMP_TSTAMPREPLY = 14 # timestamp reply
ICMP_INFO = 15 # information request
ICMP_INFOREPLY = 16 # information reply
ICMP_MASK = 17 # address mask request
ICMP_MASKREPLY = 18 # address mask reply
ICMP_TRACEROUTE = 30 # traceroute
ICMP_DATACONVERR... |
dkentw/robotframework | atest/robot/standard_libraries/builtin/listener_printing_start_end_kw.py | Python | apache-2.0 | 306 | 0 | import sys
ROBOT_LISTENER_API_VERSION = 2
def start_keyword(name, attrs):
sys.stdout.write('start keyword %s\n' % name)
sys.stderr.write( | 'start keyword %s\n' % name)
def end_keyword(name, attrs):
sys.stdout.write('end keyword %s\n' % name)
sys.stderr.write('end key | word %s\n' % name)
|
lavish205/olympia | src/olympia/search/middleware.py | Python | bsd-3-clause | 434 | 0 | from elasticsearch import TransportError
import olympia.core.logger
from olympia.amo.utils import render
log = olympia.core.logger.getLogger('z.es')
class ElasticsearchExceptionMiddleware(object):
def proces | s_exception(self, request, exception):
if issubclass(exception.__class__, Transpor | tError):
log.exception(u'Elasticsearch error')
return render(request, 'search/down.html', status=503)
|
kantel/processingpy | sketches/modes/PythonMode/examples/Basics/Objects/CompositeObjects/egg.py | Python | mit | 858 | 0.001166 | class Egg(object):
def __init__(self, xpos, ypos, t, s):
self.x = xpos # x-coordinate
self.y = ypos # y-coordinate
self.tilt = t # Left and right angle offset
self.angle = 0 # Used to define the tilt
self.scalar = s / 100.0 # Height of the egg
def wobble(self):
... | bezierVertex(40, -15 | , 25, 0, 0, 0)
bezierVertex(-25, 0, -40, -15, -40, -40)
bezierVertex(-40, -65, -25, -100, 0, -100)
|
qsnake/gpaw | gpaw/utilities/cg.py | Python | gpl-3.0 | 1,346 | 0.003715 | import numpy as np
def CG(A, X, B, maxiter=20, tolerance=1.0e-10, verbose=False):
"""Solve X*A=B using conjugate gradient method.
``X`` and ``B`` are ``ndarrays```of shape ``(m, nx, ny, nz)``
coresponding to matrices of size ``m*n`` (``n=nx*ny*nz``) and
``A`` is a callable representing an ``n*n`` matr... | tput array ``Y``.
On return ``X`` will be the solution to ``X*A=B`` within
``tolerance``."""
m = len(X)
shape | = (m, 1, 1, 1)
R = np.empty(X.shape, X.dtype.char)
Q = np.empty(X.shape, X.dtype.char)
A(X, R)
R -= B
P = R.copy()
c1 = A.sum(np.reshape([abs(np.vdot(r, r)) for r in R], shape))
for i in range(maxiter):
error = sum(c1.ravel())
if verbose:
print 'CG-%d: %e' % (i, e... |
jaygoswami2303/course_dashboard_api | v2/GradeAPI/urls.py | Python | mit | 492 | 0.006098 | """
Grade API v1 URL specification
"""
from django.conf.urls import url, patterns
import views
urlpatterns = patterns(
'',
url(r'^grades/courses | /$', views.CourseGradeList.as_view()),
url(r'^grades/courses/(?P<org>[A-Za-z0-9_.-]+)[+](?P<name> | [A-Za-z0-9_.-]+)[+](?P<run>[A-Za-z0-9_.-]+)/$', views.CourseGradeDetail.as_view()),
url(r'^grades/students/$', views.StudentList.as_view()),
url(r'^grades/students/(?P<student_id>[0-9]+)/$', views.StudentGradeDetail.as_view()),
) |
iilab/ltfhc-next | system/python-requests/test_requests.py | Python | apache-2.0 | 40,903 | 0.001076 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for Requests."""
from __future__ import division
import json
import os
import pickle
import unittest
import requests
import pytest
from requests.adapters import HTTPAdapter
from requests.auth import HTTPDigestAuth
from requests.compat import (
Morsel, cookie... | get/test%20case'
def test_params_are_added_before_fragment(self):
request = requests.Request('GET',
"http://example.com/path#fragment", params={"a": "b"}).prepare()
assert request.url == "htt | p://example.com/path?a=b#fragment"
request = requests.Request('GET',
"http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()
assert request.url == "http://example.com/path?key=value&a=b#fragment"
def test_mixed_case_scheme_acceptable(self):
s = requests.Sessio... |
chrisspen/homebot | src/ros/src/ros_homebot_python/src/ros_homebot_python/constants.py | Python | mit | 14,480 | 0.003384 | from __future__ import print_function
import os
import threading
import re
import pint
ureg = pint.UnitRegistry()
MM = ureg.millimeter
METER = ureg.meter
SEC = ureg.second
DEG = ureg.degree
RAD = ureg.radian
DRAW_LOCK = threading.RLock()
DEBOUNCE = 1
HEAD = NAME_HEAD = 'HEAD'
TORSO = NAME_TORSO = 'TORSO'
NAME_PA... | int), ('right', int)],
ID_ULTRASONIC: [('index', 'uint8'), ('distance', int)],
# ID_SONAR_POWER: [('state', bool)],
ID_IMU_EULER: [(' | x', float), ('y', float), ('z', float)],
ID_IMU_ACCELEROMETER: [('x', float), ('y', float), ('z', float)],
ID_IMU_GYROSCOPE: [('x', float), ('y', float), ('z', float)],
ID_IMU_MAGNETOMETER: [('x', float), ('y', float), ('z', float)],
ID_IMU_CALIBRATION: [
('system', int),
('gyroscope', i... |
nficano/python-lambda | aws_lambda/aws_lambda.py | Python | isc | 26,779 | 0 | import hashlib
import json
import logging
import os
import subprocess
import sys
import time
from collections import defaultdict
from shutil import copy
from shutil import copyfile
from shutil import copystat
from shutil import copytree
from tempfile import mkdtemp
import boto3
import botocore
import yaml
import sys
... | E en | vironment variable based on `--profile` option.
if profile_name:
os.environ["AWS_PROFILE"] = profile_name
# Load environment variables from the config file into the actual
# environment.
env_vars = cfg.get("environment_variables")
if env_vars:
for key, value in env_vars.items():
... |
bluemini/kuma | vendor/packages/translate/storage/xml_name.py | Python | mpl-2.0 | 2,748 | 0.000364 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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 t... | s a tag of the form
# 'short-namespace:tag'
if tag is None:
try:
namespace_shortcut, tag = namespace_shortcut.split(':')
except ValueError:
# If there is no namespace in namespace_shortcut.
tag = namespace_shortcut.lstrip("{}")
... | f.nsmap[namespace_shortcut], tag)
def namespace(self, namespace_shortcut):
return XmlNamespace(self.nsmap[namespace_shortcut])
|
imposeren/django-messages-extends | test_settings.py | Python | mit | 4,967 | 0.000604 | # Django settings for temp project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {'ENGINE': 'django.db.backends.sqlite3'}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://do... | tore your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES... | ative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make ... |
stiell/hyde | hyde/ext/plugins/folders.py | Python | mit | 1,263 | 0.002375 | # -*- coding: utf-8 -*-
"""
Plugins related to folders and paths
"""
from hyde.plugin import Plugin
from hyde.fs import Folder
class FlattenerPlugin(Plugin):
"""
The plugin class for flattening nested folders.
"""
def __init__(self, site):
super(FlattenerPlugin, self).__init__(site)
| def begin_site(self):
"""
Finds all the folders that need flattening and changes the
relative deploy path of all resources in those folders.
"""
item | s = []
try:
items = self.site.config.flattener.items
except AttributeError:
pass
for item in items:
node = None
target = ''
try:
node = self.site.content.node_from_relative_path(item.source)
target = Fol... |
jonathanmeier5/teamstore | saleor/teamstore/migrations/0004_teamstore_shipping_method.py | Python | bsd-3-clause | 672 | 0.001488 | # -*- codin | g: utf-8 -*-
# Generated by Django 1.10.7 on 2017-06-25 15:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Mig | ration(migrations.Migration):
dependencies = [
('shipping', '0005_auto_20170616_1351'),
('teamstore', '0003_auto_20170624_1533'),
]
operations = [
migrations.AddField(
model_name='teamstore',
name='shipping_method',
field=models.ForeignKey(defaul... |
teoliphant/numpy-refactor | numpy/polynomial/__init__.py | Python | bsd-3-clause | 951 | 0 | """
A sub-package for efficiently dealing with polynomials.
Within the documentation for this sub-package, a "finite power series,"
i.e., a polynomial (also referred to simply as a "series") is represented
by a 1-D numpy array of the polynomial's coefficients, ordered from lowest
order ter | m to highest. For example, array([1,2,3]) represents
``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial
applicable to the specific module in question, e.g., `polynomial` (which
"wraps" the "standard" basis) or `chebyshev`. For optimal performance,
all operations on polynomials, including evaluation... | fic)
information can be found in the docstring for the module of interest.
"""
from polynomial import *
from chebyshev import *
from polyutils import *
from numpy.testing import Tester
test = Tester(__file__).test
bench = Tester(__file__).bench
|
gasabr/AtoD | atod/__init__.py | Python | mit | 806 | 0.001241 | ''' This is the library for getting DotA2 insight information.
Problem:
there was no way to get | dota internal data about heroes, their abilities...
in suitable for further work form.
Solution:
this library allows you to get access to all | the data in the in-game files.
But information about single hero does not have much use, so there is a
way to get stats of selected heroes or get information about certain
match.
'''
from atod.meta import meta_info
from atod.models.interfaces import Member, Group
from atod.models.ability import Ability
fr... |
cypreess/django-plans | plans/urls.py | Python | mit | 2,070 | 0.006763 | from django.conf import settings
from django.conf.urls import url
from plans.views import CreateOrderView, OrderListView, InvoiceDetailView, AccountActivationView, \
OrderPaymentReturnView, CurrentPlanView, UpgradePlanView, OrderView, BillingInfoRedirectView, \
BillingInfoCreateView, BillingInfoUpdateView, Bil... | ew.as_view(), name='current_plan'),
url(r'^account/activation/$', AccountActivationView.as_view(), name='account_activation'),
url(r'^upgrade/$', UpgradePlanView.as_view(), name='upgrade_plan'),
url(r'^order/extend/new/(?P<pk>\d+)/$', CreateOrderView.as_view(), name='create_order_plan'),
url(r'^order/up... | View.as_view(), name='change_plan'),
url(r'^order/$', OrderListView.as_view(), name='order_list'),
url(r'^order/(?P<pk>\d+)/$', OrderView.as_view(), name='order'),
url(r'^order/(?P<pk>\d+)/payment/success/$', OrderPaymentReturnView.as_view(status='success'),
name='order_payment_success'),
url(r'... |
robobrobro/foe | test/command/interpret/test_get_input.py | Python | mit | 153 | 0.006536 | """ Tests for foe.command.interpre | t._setup_readline """
from foe.command.interpret import _get_input
def test_no | _config():
assert not _get_input()
|
JshWright/home-assistant | homeassistant/components/tts/__init__.py | Python | apache-2.0 | 16,893 | 0 | """
Provide functionality to TTS.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/tts/
"""
import asyncio
import ctypes
import functools as ft
import hashlib
import logging
import mimetypes
import os
import re
import io
from aiohttp import web
import vo... | eld from platform.async_get_engine(
hass, p_config)
else:
provider = yield from hass.loop.run_in_executor(
None, platform.get_engine, hass, p_config)
if provider is None: |
_LOGGER.error("Error setting up platform %s", p_type)
return
tts.async_register_engine(p_type, provider, p_config)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Error setting up platform %s", p_type)
return
@as... |
hep-mirrors/herwig | Models/Feynrules/python/ufo2peg/check_lorentz.py | Python | gpl-3.0 | 38,432 | 0.032863 | from __future__ import print_function
import itertools,cmath,re
from .helpers import SkipThisVertex,extractAntiSymmetricIndices
from .converter import py2cpp
from .lorentzparser import parse_lorentz
import string,re
def compare(a,b) :
num=abs(a-b)
den=abs(a+b)
if(den == 0. and 1e-10) :
return True
... | ,2)'], # 3rd swap
['Metric(1,2003)','Metric(2,1003)'], # from mass term
['Metric(1,1003)','Metric(2,2003)'], # from mass term
['Metric(1,2)','Metric(1003,2003)'], # from mass term
['P(1,1)','P(2,1)','Metric(1003,2003)'], # gauge terms
['P(1,2)',... | ['P(1003,1)','P(1,1)','Metric(2,2003)'], # gauge terms
['P(1003,2)','P(2,2)','Metric(1,2003)'], # gauge terms
['P(2003,1)','P(1,1)','Metric(2,1003)'], # gauge terms
['P(2003,2)','P(2,2)','Metric(1,1003)'], # gauge terms
]
signs=[1.,1.,-1.,1.,-1.,-1.... |
mentalsmash/geek-map | mentalsmash/__init__.py | Python | gpl-2.0 | 775 | 0 | '''
Copyright (C) 2012 mentalsmash.org <contact@mentalsmash.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
Thi... | th this library; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
Boston, MA 02110 | -1301, USA.
'''
|
california-civic-data-coalition/django-calaccess-processed-data | calaccess_processed_elections/managers/opencivicdata/core/divisions.py | Python | mit | 1,449 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom managers for the Division model.
"""
from __future__ import unicode_literals
from calaccess_processed.managers import BulkLoadSQLManager
class OCDAssemblyDivisionManager(BulkLoadSQLManager):
"""
Custom manager for state assembly OCD Divisions.
| """
def get_queryset(self):
"""
Filters down to state assembly divisions.
"""
| qs = super(OCDAssemblyDivisionManager, self).get_queryset()
return qs.filter(subid1='ca', subtype2='sldl')
class OCDSenateDivisionManager(BulkLoadSQLManager):
"""
Custom manager for state senate OCD Divisions.
"""
def get_queryset(self):
"""
Filters down to state senate divisio... |
JoaquimPatriarca/senpy-for-gis | gasp/osm2lulc/grs.py | Python | gpl-3.0 | 17,992 | 0.008393 | """
OpenStreetMap to Land Use/Land Cover Maps
"""
def osm_to_sqdb(osmXml, osmSQLITE):
"""
Convert OSM file to SQLITE DB
"""
from gasp.toshp.gdal import ogr_btw_driver
return ogr_btw_driver(osmXml, osmSQLITE, supportForSpatialLite=True)
def osm_project(osmSQLITE, srs_epsg):
"""
R... | ls in roads:
if cls not in mergeOut:
mergeOut[cls] = [roads[cls]]
else:
mergeOut[cls].append(roads[cls])
# ****************** | ****************************************************** #
# 3 - Area Upper than #
# ************************************************************************ #
"""
auOut = {
cls_code : rst_name, ...
}
"""
auOut = area(
osm_db, nomenclature, osmTableData['polygons'], workspace, ... |
mjtamlyn/archery-scoring | entries/migrations/0006_auto_20150612_2307.py | Python | bsd-3-clause | 372 | 0 | # -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('entries', '0005_ | resultsmode_json'),
]
o | perations = [
migrations.AlterField(
model_name='resultsmode',
name='json',
field=models.TextField(default='', blank=True),
),
]
|
mixturemodel-flow/tensorflow | tensorflow/contrib/boosted_trees/python/utils/losses_test.py | Python | apache-2.0 | 3,957 | 0.006823 | # Copyright 2017 The TensorFlow Authors. 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 applica... | "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.
# ==============================================================================
"""Tests for trainer hooks."""
from __future_... | division
from __future__ import print_function
import math
import numpy as np
from tensorflow.contrib.boosted_trees.python.utils import losses
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tensorflow.python.op... |
pgroudas/pants | tests/python/pants_test/tasks/test_list_goals.py | Python | apache-2.0 | 4,088 | 0.009295 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import pytest
from ... | led];\n color = blue;\n label = "alpaca";',
' alpaca_alpaca [label="alpaca"];',
' }',
| ' alpaca_alpaca -> llama_llama [ltail=cluster_alpaca lhead=cluster_llama];',
'}',
options={ 'graph': True }
)
|
dkkline/CanSat14-15 | unused_code/generate_static_json_data.py | Python | mit | 1,797 | 0 | import json
import argparse
import os
from listener.config import MIN_TIME, MAX_TIME, PRESSURE_AVERAGE_AMOUNT
from listener.replayer import Replayer
from listener.utilities import convert_time, average
from listener.calculate import (calculate_temp_NTC, calculate_press,
calculate_height,... | pressure_values)
data_pressure.append([time, pressure])
data_height.append([time, calculate_height(pressure)])
data_gyro.append([time, calculate_gyr(datapoint["GyrZ"])])
all_data = {
"Temp": data_temperature,
"Press": data_pressure,
"Height": data_height,
"Gyro": data_gyro
}
out_handle.w... | |
erdc/proteus | scripts/ppmatlab.py | Python | mit | 3,523 | 0.023843 | ## Automatically adapted for numpy.oldnumeric Apr 14, 2008 by -c
from builtins import range
def writeMeshMatlabFormat(mesh,meshFileBase):
"""
build array data structures for matlab finite element mesh representation
and write to a file to view and play with in matlatb
in matlab can then print mesh wi... | al']):
p[0,nN]=mesh['nodeArray'][nN,0]
p[1,nN]=mesh['nodeArray'][nN,1]
mfile.write('%g %g \n' % tuple(p[:,nN]))
mfile.write(']; \n')
mfile.write("p = p\';\n") #need transpose for | matlab
mfile.write('e = [ ... \n')
for ebN in range(mesh['nElementBoundaries_global']):
e[0,ebN]=mesh['elementBoundaryNodesArray'][ebN,0] + matlabBase #global node number of start node base 1
e[1,ebN]=mesh['elementBoundaryNodesArray'][ebN,1] + matlabBase #global node number of end node base 1
... |
hlzz/dotfiles | graphics/VTK-7.0.0/Filters/Geometry/Testing/Python/TestGhostPoints.py | Python | bsd-3-clause | 2,835 | 0.000705 | import sys
import vtk
from vtk.test import Testing
class TestGhostPoints(Testing.vtkTest):
def testLinear(self):
pts = vtk.vtkPoints()
pts.SetNumberOfPoints(4)
pts.InsertPoint(0, (0, 0, 0))
pts.InsertPoint(1, (1, 0, 0))
pts.InsertPoint(2, (0.5, 1, 0))
pts.... | nt(8, (0 | .75, 0.25, 0.5))
pts.InsertPoint(9, (0.5, 0.75, 0.5))
te = vtk.vtkQuadraticTetra()
ptIds = te.GetPointIds()
for i in range(10):
ptIds.SetId(i, i)
ghosts = vtk.vtkUnsignedCharArray()
ghosts.SetName(vtk.vtkDataSetAttributes.GhostArrayName())
... |
akiokio/centralfitestoque | src/.pycharm_helpers/python_stubs/-1807332816/gi/_gobject/_gobject.py | Python | bsd-2-clause | 21,406 | 0.010511 | # encoding: utf-8
# module gi._gobject._gobject
# from /usr/lib/python2.7/dist-packages/gi/_gobject/_gobject.so
# by generator 1.130
# no doc
# no imports
# Variables with simple values
G_MAXDOUBLE = 1.7976931348623157e+308
G_MAXFLOAT = 3.4028234663852886e+38
G_MAXINT = 2147483647
G_MAXINT16 = 32767
G_MAXINT32 = 2147... | pass
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
def __gt__(self, y): # real signature unknown; restored from _ | _doc__
""" x.__gt__(y) <==> x>y """
pass
def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __le__(self, y): # real signature unknown; res... |
kevin-intel/scikit-learn | sklearn/gaussian_process/_gpr.py | Python | bsd-3-clause | 22,428 | 0 | """Gaussian processes regression."""
# Authors: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>
# Modified by: Pete Green <p.l.green@liverpool.ac.uk>
# License: BSD 3 clause
import warnings
from operator import itemgetter
import numpy as np
from scipy.linalg import cholesky, cho_solve
import scipy.optimize
from .... | g the kernel's
parameters which maximize the log-marginal likelihood. The first run
of the optimizer is performed from the kernel's initial parameters,
the remaining ones (if any) from thetas sampled log-uniform randomly
from the space of allowed theta-values. If greater than 0, all boun... | te. Note that n_restarts_optimizer == 0 implies that one
run is performed.
normalize_y : bool, default=False
Whether the target values y are normalized, the mean and variance of
the target values are set equal to 0 and 1 respectively. This is
recommended for cases where zero-mean, u... |
azaghal/ansible | lib/ansible/modules/debconf.py | Python | gpl-3.0 | 5,533 | 0.002169 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2014, Brian Coca <briancoca+ansible@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module... | value: en_US.UTF-8 UTF-8, fr_FR.UTF-8 UTF-8
vtype: multiselect
- name: Accept oracle license
debconf:
name: oracle-java7-install | er
question: shared/accepted-oracle-license-v1-1
value: 'true'
vtype: select
- name: Specifying package you can register/return the list of questions and current values
debconf:
name: tzdata
'''
from ansible.module_utils._text import to_text
from ansible.module_utils.basic import AnsibleModule
def... |
adoosii/edx-platform | lms/djangoapps/discussion_api/tests/test_views.py | Python | agpl-3.0 | 38,334 | 0.001513 | """
Tests for Discussion API views
"""
from datetime import datetime
import json
from urlparse import urlparse
import ddt
import httpretty
import mock
from pytz import UTC
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
from common.test.utils import disable_signal
from discuss... | rse_id": "non/existent/course"})
)
self.assert_response_correct(
response,
404,
{"developer_message": "Not found."}
)
def test_get_success | (self):
response = self.client.get(self.url)
self.assert_response_correct(
response,
200,
{
"id": unicode(self.course.id),
"blackouts": [],
"thread_list_url": "http://testserver/api/discussion/v1/threads/?course_id=x%2Fy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.