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 |
|---|---|---|---|---|---|---|---|---|
magcius/sweettooth | sweettooth/extensions/migrations/0008_new_icon_default.py | Python | agpl-3.0 | 6,118 | 0.007192 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
new_default = orm.Extension._meta.get_field_by_name('icon')[0].default
for ... | 'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), |
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta'... |
tmetsch/graph_stitcher | stitcher/vis.py | Python | mit | 5,618 | 0 |
"""
Visualize possible stitches with the outcome of the validator.
"""
import math
import random
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import stitcher
SPACE = 25
TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'}
def show(graphs, request, title... |
dotted_line.append((src, trg))
else:
normal_line.append((src, trg))
nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted',
ax=axes)
| nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes)
# draw labels
nx.draw_networkx_labels(graph, pos, ax=axes)
def show_3d(graphs, request, titles, prog='neato', filename=None):
"""
Show the candidates in 3d - the request elevated above the container.
"""
fig = plt.figure(figsi... |
waveform80/gpio-zero | docs/examples/button_camera_1.py | Python | bsd-3-clause | 327 | 0.006116 | from gpiozero import Button
from picamera import PiCamera
from datetime import datetime
from signal import pause
button = Button(2)
camera = PiCamera()
def capture():
timestamp = datetime.now().isoformat()
camera.capture('/home/pi/{timest | amp}.jpg'.format(timestamp=timestamp))
button.when_pressed = capture
pause()
| |
earthreader/web | earthreader/web/exceptions.py | Python | agpl-3.0 | 1,387 | 0 | """:mod:`earthreader.web.exceptions` --- Exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from flask import jsonify
from werkzeug.exceptions import HTTPException
class IteratorNotFound(ValueError):
"""Raised when the iterator does not exist"""
class JsonException(HTTPException):
"""Base e... | return r
class InvalidCategoryID(ValueError, JsonException):
"""Raised when the category ID is not valid."""
error = 'category-id-invalid'
message = 'Given category id is not valid'
class FeedNotFound(ValueError, JsonException):
"""Raised when the feed is not reachable."""
error = 'feed... |
class EntryNotFound(ValueError, JsonException):
"""Raised when the entry is not reachable."""
error = 'entry-not-found'
message = 'The entry you request does not exist'
class WorkerNotRunning(ValueError, JsonException):
"""Raised when the worker thread is not running."""
error = 'worker-not-ru... |
daj0ker/BinPy | BinPy/examples/source/ic/Series_7400/IC7433.py | Python | bsd-3-clause | 1,247 | 0.001604 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# Usage of IC 7433
# <codecell>
from __future__ import print_function
from BinPy import *
# <codecell>
# Usage of IC 7433:
ic = IC_7433()
print(ic.__doc__)
# <codecell>
# The Pin configuration is:
inp = {2: 0, 3: 0, 5: 0, 6: 0, 7: 0, ... | .setIC(inp)
# Draw the IC with the current configuration\n
ic.drawIC()
# <codecell>
# Run the IC with the current configuration using -- print ic.run() --
# Note that the ic.run() returns a dict of pin configuration similar to
print (ic.run())
# <codecell>
# Seting the outputs to the current IC configuration us... | )
# <codecell>
# Seting the outputs to the current IC configuration using --
# ic.setIC(ic.run()) --
ic.setIC(ic.run())
# Draw the final configuration
ic.drawIC()
# Run the IC
print (ic.run())
# <codecell>
# Connector Outputs
c = Connector()
# Set the output connector to a particular pin of the ic
ic.setOutpu... |
City-of-Helsinki/kore | kore/settings.py | Python | agpl-3.0 | 4,485 | 0.000892 | """
Django settings for kore 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, ...)
impor... | processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
CORS_ORIGIN_ALLOW_ALL = True
# local_settings.py can be used to override environment-specific settings
# like database and email that differ between development and production.
try:
from local... | import *
except ImportError:
pass
|
plotly/python-api | packages/python/plotly/plotly/validators/funnelarea/_textfont.py | Python | mit | 1,867 | 0.000536 | import _plotly_utils.basevalidators
class TextfontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="textfont", parent_name="funnelarea", **kwargs):
super(TextfontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | in which to
apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only | a
select number of fonts are installed and
supported. These include "Arial", "Balto",
"Courier New", "Droid Sans",, "Droid Serif",
"Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narro... |
shakamunyi/neutron-dvr | neutron/plugins/bigswitch/plugin.py | Python | apache-2.0 | 51,022 | 0.000098 | # Copyright 2012 Big Switch Networks, 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... | return port
def get_port_and_sgs(self, port_id):
"""Get port from database with security group info."""
LOG.debug(_("get_port_and_sgs() called for port_id %s"), port_id)
session = db.get_session()
sg_binding_port = sg_db.SecurityGr | oupPortBinding.port_id
with session.begin(subtransactions=True):
query = session.query(
models_v2.Port,
sg_db.SecurityGroupPortBinding.security_group_id
)
query = query.outerjoin(sg_db.SecurityGroupPortBinding,
... |
gotropo/gotropo | create/efs.py | Python | gpl-3.0 | 2,807 | 0.006769 | from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output
from troposphere.efs import FileSystem, MountTarget
from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet
from create import export_ref, import_ref
from create.network import AclFactory, assoc_nacl_subnet
... | setup['ports'],
out_ports=ops.out_ports,
| out_networks=[val for key, val in sorted(ops.app_networks.items())],
ssh_hosts=ops.get("deploy_hosts"),
)
export_ref(
template,
export_name=efs_acl,
value=Ref(efs_acl),
desc="{}{} stack".format("NetACL for", stack_name)
)
# Create Subnets for Mount Targets
... |
msdogan/pyvin | calvin/calvin.py | Python | mit | 16,224 | 0.013745 | import os
import sys
import logging
from pyomo.environ import *
from pyomo.opt import TerminationCondition
import numpy as np
import pandas as pd
class CALVIN():
def __init__(self, linksfile, ic=None, log_name="calvin"):
"""
Initialize CALVIN model object.
:param linksfile: (string) CSV file containin... | n
:param log_name: A name for a logger - will be used to keep logs from different model runs separate in files.
Defaults to "calvin", which results in a log file in the current working directory named "calvin.log".
You can change this each time you instantiate the CALVIN class if you... | gs
for different runs. Otherwise, all results will be appended to the log file (not overwritten). If you
run multiple copies of CALVIN simultaneously, make sure to change this, or you could get errors writing
to the log file.
Do not provide a full path to... |
wangjohn/wallace | wallace/categorical_variable_encoder.py | Python | mit | 1,836 | 0.003268 | from collections import defaultdict
class CategoricalVariableEncoder(object):
def convert_categorical_variables(self, data_matrix, category_indices, category_value_mapping=None):
if len(category_indices) == 0:
return data_matrix
if category_value_mapping == None:
category_v... | index] = self.create_value_map(values_set)
return category_value_mapping
def get_category_values(self, data_matrix, category_indices):
categories = {}
for category_index in category_indices:
categories[catego | ry_index] = set()
for i in xrange(len(data_matrix)):
for category_index in category_indices:
category_value = data_matrix[i][category_index]
categories[category_index].add(category_value)
return categories
@classmethod
def create_value_map(self, val... |
JoshuaSkelly/lunch-break-rl | ai/actions/moveaction.py | Python | mit | 385 | 0 | from ai import action
class MoveAction(action.Action):
def __init__(self, performer, direction):
| super().__init__(performer)
self.direction = direction
def prerequisite(self):
if not self.direction:
return False
return self.performer.can_move(*self.di | rection)
def perform(self):
self.performer.move(*self.direction)
|
peplin/astral | astral/api/handlers/ticket.py | Python | mit | 4,822 | 0.002489 | from tornado.web import HTTPError
import datetime
import threading
from astral.api.client import TicketsAPI
from astral.api.handlers.base import BaseHandler
from astral.api.handlers.tickets import TicketsHandler
from astral.models import Ticket, Node, Stream, session
import logging
log = logging.getLogger(__name__)
... | eam.get_by(slug=stream_slug)
if not destination_uuid:
return Ticket.get_by(stream=stream, destination=Node.me())
node = Node.get_by(uuid=destination_uuid)
return Ticket.query.filter_by(stream=stream, destination=node).first()
def delete(self, stream_slug, destination_uuid=None)... | g the stream to the requesting node."""
ticket = self._load_ticket(stream_slug, destination_uuid)
if not ticket:
raise HTTPError(404)
ticket.delete()
session.commit()
TicketDeletionPropagationThread(ticket, self.request).start()
def get(self, stream_slug, destina... |
YU6326/YU6326.github.io | code/photogrammetry/inner_orientation.py | Python | mit | 3,899 | 0.020569 | import tkinter.filedialog as tkFileDialog
import numpy as np
from numpy import sin,cos
import os
def InnerOrientation(mat1,mat2):
"""
mat1 为像素坐标,4*2,mat2为理论坐标4*2,
h0,h1,h2,k0,k1,k2,这六个参数由下列矩阵定义:
[x]=[h0]+[h1 h2] [i]
[y]=[k0]+[k1 k2] [j]
返回6个定向参数的齐次矩阵,x方向单位权方差,y方向单位权方差
[h1 h2 h0]
[k1 k2 ... | 齐次坐标:即每列第三个元素为1,每个坐标均为列向量。列数不限。
# 返回:转换后的坐标
# """
# return mat@coormat
# def openaofile():
# fname = tkFileDialog.askopenfilename(title=u"选择文件",filetypes=[("ao.txt file", "*.txt"), ("all", "*.*")],initialdir=r"D:\学习\摄影测量\摄影测量实验数据-后方交会、前方交会")
# f=open(fname,mode='r')
# lines=f.readlines()
# f... | round=[]
# for line in lines[1:]:
# t=line.split()
# matimage.append([float(t[0]),float(t[1])])
# matground.append([float(t[2]),float(t[3]),float(t[4])])
# return(np.matrix(matimage),np.matrix(matground))
# def resection():
# matimage,matground=openaofile()
# dist=np.linalg.norm... |
ta2-1/pootle | pootle/apps/accounts/__init__.py | Python | gpl-3.0 | 328 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This fi | le is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
default_app_config = 'accounts.apps.AccountsConfig | '
|
BilalDev/HolyScrap | src/hsimage.py | Python | apache-2.0 | 1,247 | 0.000802 | import sys
from PIL import Image
img = Image.open(sys.argv[1])
width, height = img.size
xblock = 5
yblock = 5
w_width = width / xblock
w_height = height / yblock
blockmap = [(xb*w_width, yb*w_height, (xb+1)*w_width, (yb+1)*w_height)
for xb in xrange(xblock) for yb in xrange(yblock)]
newblockmap = list(bloc... | map[20]
newblockmap[10] = blockmap[4]
newblockmap[11] = blockmap[3]
newblockmap[12] = blockmap[2]
newblockmap[13] = blockmap[1]
newblockmap[14] = blockmap[0]
newblockmap[15] = blockmap[19]
newblockmap[16] = blockmap[18]
newblockmap[17] = blockmap[17]
newblockmap[18] = blockmap[16]
newblockmap[19] = blockmap[15]
newbloc... | = blockmap[6]
newblockmap[24] = blockmap[5]
result = Image.new(img.mode, (width, height))
for box, sbox in zip(blockmap, newblockmap):
c = img.crop(sbox)
result.paste(c, box)
result.save(sys.argv[1])
|
LilithWittmann/froide | froide/foisite/models.py | Python | mit | 1,944 | 0.001029 | from django.db import models
from django.conf import settings
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class FoiSite(models.Model):
country_code = models.CharField(_('Coun... | _code = self.country_code.upper()
super(FoiSite, self).save(* | args, **kwargs)
try:
from django.contrib.gis.geoip import GeoIP
except ImportError:
GeoIP = None # noqa
class SiteAdivsor(object):
def __init__(self):
self.geoip = GeoIP()
self.sites = None
def update(self):
sites = FoiSite.objects.filter(enabled=True)
self.sites = d... |
matt77hias/FileUtils | src/name.py | Python | gpl-3.0 | 249 | 0.02008 | import os
def remove_fname_extension(fname | ):
return os.path.splitext(fname)[0]
def change_fname_extension(fname, extension):
return remove_fname_extension(fname) + '.' + ex | tension
def concat(path, fname):
return path + '/' + fname |
jamesnw/HelpfulAppStoreBot | kill_bot.py | Python | gpl-2.0 | 277 | 0.00361 | #!/usr/bin/python
import psutil
import signal
| #From https://github.com/getchar/rbb_article
target = "HelpfulAppStore"
# scan through processes
for proc | in psutil.process_iter():
if proc.name() == target:
print(" match")
proc.send_signal(signal.SIGUSR1)
|
amenonsen/ansible | test/lib/ansible_test/_internal/provider/layout/ansible.py | Python | gpl-3.0 | 1,396 | 0.002149 | """Layout provider for Ansible source."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ... import types as t
from . import (
ContentLayout,
LayoutProvider,
)
class AnsibleLayout(LayoutProvider):
"""Layout provider for Ansible source."""
@sta... | paths,
plugin_paths=plugin_paths,
integration_path='test/integration',
unit_path='test/units',
unit_module_path='test/units/modules',
unit_module_utils_path='test/u... | )
|
bswartz/cinder | cinder/volume/rpcapi.py | Python | apache-2.0 | 15,156 | 0 | # Copyright 2012, Intel, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | group=group,
add_volumes=add_volumes,
remov | e_volumes=remove_volumes)
def create_consistencygroup_from_src(self, ctxt, group, cgsnapshot=None,
source_cg=None):
cctxt = self._get_cctxt(group.host, '2.0')
cctxt.cast(ctxt, 'create_consistencygroup_from_src',
group=group,
... |
ossifrage/dynamicforms | dynamicforms/settings.py | Python | bsd-3-clause | 1,384 | 0.002168 | # -*- coding: utf-8 -*-
import os
os_env = os.environ
class Config(object):
SECRET_KEY = os_env.get('DYNAMICFORMS_SECRET', 'secret-key') # TODO: Change me
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
BCRYPT_LOG... | .join(Config.PROJECT_ROOT, DB_NAME)
SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH)
DEBUG_TB_ENABLED = Tru | e
ASSETS_DEBUG = True # Don't bundle/minify static assets
CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc.
class TestConfig(Config):
TESTING = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite://'
BCRYPT_LOG_ROUNDS = 1 # For faster tests
WTF_CSRF_ENABLED = False # Allows for... |
nagyistoce/devide | external/wxPyPlot.py | Python | bsd-3-clause | 57,752 | 0.015844 | #!/usr/bin/env python2.2
#-----------------------------------------------------------------------------
# Name: wxPyPlot.py
# Purpose:
#
# Author: Gordon Williams
#
# Created: 2003/11/03
# RCS-ID: $Id$
# Copyright: (c) 2002
# Licence: Use as you wish.
#----------------------------------... | idth'= 1, - Pen width
'size'= 2, - Marker size
'fillcolour'= same as colour, | - wxBrush Colour any wxNamedColour
'fillstyle'= wx.SOLID, - wxBrush fill style (use wxTRANSPARENT for no fill)
'marker'= 'circle' - Marker shape
'legend'= '' - Marker Legend to display
Marker Shapes:
... |
CTSRD-SOAAP/chromium-42.0.2311.135 | v8/tools/testrunner/local/pool_unittest.py | Python | bsd-3-clause | 1,222 | 0.00982 | #!/usr/bin/env python
# Copyright 2014 the V8 project 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 unittest
from pool import Pool
def Run(x):
if x == 10:
raise Exception("Expected exception triggered by test.")
retu... | (3)
for result in pool.imap_unordered(Run, [[x] for x in range(0, 12)]):
# Item 10 will not appear in results due to an internal exception.
results.add(result)
expect = set(range(0, 12))
expect.remove(10)
self.as | sertEquals(expect, results)
def testAdd(self):
results = set()
pool = Pool(3)
for result in pool.imap_unordered(Run, [[x] for x in range(0, 10)]):
results.add(result)
if result < 30:
pool.add([result + 20])
self.assertEquals(set(range(0, 10) + range(20, 30) + range(40, 50)),
... |
andersk/zulip | zerver/lib/remote_server.py | Python | apache-2.0 | 7,292 | 0.00192 | import logging
import urllib
from typing import Any, Dict, List, Mapping, Tuple, Union
import orjson
import requests
from django.conf import settings
from django.forms.models import model_to_dict
from django.utils.translation import gettext as _
from analytics.models import InstallationCount, RealmCount
from version ... | oads(res.content)
def send_json_to_push_bouncer(
method: str, endpoint: str, post_data: Mapping[str, object]
) -> Dict[str, object]:
return send_to_push_bouncer(
method,
endpoint,
orjson.dumps(post_data),
extra_headers={"Content-type": "application/json"},
)
REALMAUDITLOG... | PUSHED_FIELDS = [
"id",
"realm",
"event_time",
"backfilled",
"extra_data",
"event_type",
]
def build_analytics_data(
realm_count_query: Any, installation_count_query: Any, realmauditlog_query: Any
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]:
# We limit ... |
QuentinJi/pyuiautomation | initial_work.py | Python | mit | 193 | 0 | import subprocess
import os
def start_service():
subprocess.Popen("ipy start_ | srv.py", stdout=subprocess.PIPE)
return 0
def close_service():
os.system("taskki | ll /im ipy.exe /f")
|
facetothefate/contrail-controller | src/discovery/disc_cassdb.py | Python | apache-2.0 | 14,755 | 0.009353 | #
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import re
from cfgm_common import jsonutils as json
import time
import gevent
import disc_consts
import disc_exceptions
from datetime import datetime
from gevent.coros import BoundedSemaphore
import pycassa
import pycassa.util
from pycassa.system_ma... | cept Exception as e:
raise
return error_handler
# return all publisher entries
@cass_error_handler
def service_entries(self, service_type = None):
col_name = ('service',)
try:
data = self._disco_cf.get_range(column_start = col_ | name, column_finish = col_name)
for service_type, services in data:
for col_name in services:
col_value = services[col_name]
entry = json.loads(col_value)
col_name = ('subscriber', entry['service_id'],)
entry['in... |
ricardogsilva/PyWPS | pywps/inout/formats/lists.py | Python | mit | 1,471 | 0.00068 | """List of supported formats
"""
from collections import namedtuple
_FORMAT = namedtuple('FormatDefinition', 'mime_type,'
'extension, schema')
_FORMATS = namedtuple('FORMATS', 'GEOJSON, JSON, SHP, GML, GEOTIFF, WCS,'
'WCS100, WCS110, WCS20, WFS, WFS100,'
... | RMAT('application/x-ogc-wcs; version=1.0.0', '.xml', None),
_FORMAT('application/x-ogc-wcs; version=1.1.0', '.xml', None),
_FORMAT('application/x-ogc-wcs; version=2.0', '.xml', None),
_FORMAT('application/x-ogc-wfs', '.xml', None),
_FORMAT('application/x-ogc-wfs; version=1.0.0', '.xml', None),
_FORM... | cation/x-ogc-wfs; version=1.1.0', '.xml', None),
_FORMAT('application/x-ogc-wfs; version=2.0', '.xml', None),
_FORMAT('application/x-ogc-wms', '.xml', None),
_FORMAT('application/x-ogc-wms; version=1.3.0', '.xml', None),
_FORMAT('application/x-ogc-wms; version=1.1.0', '.xml', None),
_FORMAT('applica... |
mariofg92/ivmario | web2.py | Python | gpl-3.0 | 286 | 0.013986 | from flask import Flask,request, jsonify
import json
app = Flask(__name__)
@app.route("/")
def rutaStatus():
return jsonify(status='OK')
@app. | route("/status")
def rutaStatusDocker():
return jsonify(status='OK')
if _ | _name__ == "__main__":
app.run(host='0.0.0.0', port=80)
|
supermari0/ironic | ironic/dhcp/none.py | Python | apache-2.0 | 1,015 | 0 | # Copyright 2014 Rackspace, 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 by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS... | nse for the specific language governing permissions and limitations
# under the License.
from ironic.dhcp import base
class NoneDHCPApi(base.BaseDHCP):
"""No-op DHCP API."""
def update_port_dhcp_opts(self, port_id, dhcp_options, token=None):
pass
def update_dhcp_opts(self, task, options, vif... |
kevinadda/dmn-chatbot | dmn_plus.py | Python | mit | 15,738 | 0.004384 | import sys
import time
import numpy as np
from copy import deepcopy
import tensorflow as tf
import babi_input
class Config(object):
"""Holds model hyperparams and data information."""
batch_size = 100
embed_size = 80
hidden_size = 80
max_epochs = 256
early_stopping = 20
dropout = 0.9
... |
def get_question_representation(self, embeddings):
"""Get question vectors via embedding and GRU"""
questions = tf.nn.embedding_lookup(embeddings, self.question_placehol | der)
questions = tf.split(1, self.max_q_len, questions)
questions = [tf.squeeze(q, squeeze_dims=[1]) for q in questions]
_, q_vec = tf.nn.rnn(self.gru_cell, questions, dtype=np.float32, sequence_length=self.question_len_placeholder)
return q_vec
def get_input_representation(self,... |
baxeico/pyworkingdays | workingdays/__init__.py | Python | mit | 947 | 0.006336 | from datetim | e import timedelta
from math import copysign
def is_workingday(input_date):
return input_date.isoweekday() < 6
def add(datestart, days):
sign = lambda x: int(copysign(1, x))
dateend = datestart
while days:
dateend = dateend + timedelta(days=sign(days))
if is_workingday(dateend):
... | ate = date1
else:
min_date = date1
max_date = date2
diff = 0
current_date = min_date
while current_date != max_date:
current_date = current_date + timedelta(days=1)
if is_workingday(current_date):
diff += 1
return diff
def next(datestart):
while True:... |
mogproject/mog-commons-python | tests/mog_commons/test_unittest.py | Python | apache-2.0 | 3,948 | 0.003214 | # -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import, unicode_literals
import sys
import os
import six
from mog_commons import unittest
class TestUnitTest(unittest.TestCase):
def test_assert_output(self):
def f():
print('abc')
print('123')
... | ut() as (out, err):
out.write(b'\xff\xfe')
out.write('あいうえお'.encode('utf-8'))
err.write(b'\xfd\xfc')
self.assertEqual(out.getvalue(), b'\xff\xfe' + 'あいうえお'.encode('utf-8'))
self.assertEqual(err.getvalue(), b'\xfd\xfc')
def test_with_bytes_output_types | (self):
# accepts unicode
def f(data, expected):
with self.withBytesOutput() as (out, err):
for d in data:
out.write(d)
self.assertEqual(out.getvalue(), expected)
f(['あいうえお'], 'あいうえお'.encode('utf-8'))
f([b'\xff', 'あいうえお'], b'\x... |
niavlys/kivy | kivy/uix/carousel.py | Python | mit | 21,776 | 0.000092 | '''
Carousel
========
.. versionadded:: 1.4.0
The :class:`Carousel` widget provides the classic mobile-friendly carousel view
where you can swipe between slides.
You can add any content to the carousel and use it horizontally or verticaly.
The carousel can display pages in loop or not.
Example::
class Example1(... | om the right towards the
left to get to the second slide.
:attr:`direction` is a :class:`~kivy.properties.OptionProperty` and
defaults to 'right'.
'''
min_move = NumericProperty(0.2)
'''Defines the minimal distance from the edge where the movement is
considered a swipe gesture and the Caro... | lue, then the movement is
cancelled and the content is restored to its original position.
:attr:`min_move` is a :class:`~kivy.properties.NumericProperty` and
defaults to 0.2.
'''
anim_move_duration = NumericProperty(0.5)
'''Defines the duration of the Carousel animation between pages.
:at... |
fin/froide | froide/bounce/signals.py | Python | mit | 236 | 0 | from django.dispatch import Signal
user_email_bounc | ed = Signal() # a | rgs: ['bounce', 'should_deactivate']
email_bounced = Signal() # args: ['bounce', 'should_deactivate']
email_unsubscribed = Signal() # args: ['email', 'reference']
|
tzuria/Shift-It-Easy | webApp/shift-it-easy-2015/web/pages/MainManager.py | Python | mit | 87,797 | 0.038361 | #!/usr/bin/env python
#
# Copyright 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | t'] = want
if dont_care:
| template_variables['NurseWhoDontCareSunday0Night'] = dont_care
if prefer_not:
template_variables['NurseWhoPreferNotSunday0Night'] = prefer_not
if cant:
template_variables['NurseWhoCantSunday0Night'] = cant
# Sunday0 morning info:
head_nurse_want = Constrain.getShiftHeads(sunda... |
pthatcher/psync | src/exp/watch.py | Python | bsd-3-clause | 2,850 | 0.005965 | # Copyright (c) 2011, Peter Thatcher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditi... | D BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# ME | RCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INT... |
schelleg/PYNQ | pynq/lib/logictools/tests/test_boolean_generator.py | Python | bsd-3-clause | 14,127 | 0.000354 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | Z1_LOGICTOOLS_SPECIFICATION
__author__ = "Yun Rock Qu"
__copyright__ = "Copyright 2016, Xilinx"
__email__ = "[email protected]"
try:
ol = Overlay('logictools.bit', download=False)
flag0 = True
except IOError:
flag0 = False
flag1 = user_answer_ | yes("\nTest boolean generator?")
if flag1:
mb_info = ARDUINO
flag = flag0 and flag1
@pytest.mark.skipif(not flag, reason="need correct overlay to run")
def test_bool_state():
"""Test for the BooleanGenerator class.
This test will test configurations when all 5 pins of a LUT are
specified. Users need... |
sdpython/ensae_teaching_cs | _unittests/ut_dnotebooks/test_1A_notebook_soft_sql.py | Python | mit | 1,241 | 0.002417 | # -*- coding: utf-8 -*-
"""
@brief test log(time=92s)
"""
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import get_temp_folder, add_missing_development_version
import ensae_teaching_cs
class TestNotebookRunner1a_soft_sql(unittest.TestCase):
def setUp(self):
add_m... | n keepnote:
fLOG(n)
execute_notebooks(temp, keepnote,
lambda i, n: "csharp" not in n and "cython" not in n,
| fLOG=fLOG,
clean_function=clean_function_1a,
dump=ensae_teaching_cs)
if __name__ == "__main__":
unittest.main()
|
pawkoz/dyplom | blender/build_files/cmake/cmake_consistency_check_config.py | Python | gpl-2.0 | 4,572 | 0.006124 | import os
IGNORE = (
"/test/",
"/tests/gtests/",
"/BSP_GhostTest/",
"/release/",
"/xembed/",
"/TerraplayNetwork/",
"/ik_glut_test/",
# specific source files
"extern/Eigen2/Eigen/src/Cholesky/CholeskyInstantiations.cpp",
"extern/Eigen2/Eigen/src/Core/CoreInstantiations.cpp",
... | audaspace/SRC/AUD_SRCResampleFactory.h",
"intern/audaspace/SRC/AUD_SRCResampleRea | der.h",
"intern/cycles/render/film_response.h",
"extern/carve/include/carve/config.h",
"extern/carve/include/carve/external/boost/random.hpp",
"extern/carve/patches/files/config.h",
"extern/carve/patches/files/random.hpp",
)
UTF8_CHECK = True
SOURCE_DIR = os.path.normpath(os.path.abspath(os.pa... |
David-Wobrock/django-fake-database-backends | tests/test_project/test_project/urls.py | Python | mit | 776 | 0 | """linter_test_project URL Configuration
The `urlpatterns` list routes URLs to views. For more infor | mation please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to url... | nf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
|
mtitinger/libsigrok | bindings/swig/doc.py | Python | gpl-3.0 | 4,655 | 0.005371 | ##
## This file is part of the libsigrok project.
##
## Copyright (C) 2014 Martin Ling <[email protected]>
##
## 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 Lice... | t = param.find('parameternamelist')
| name = namelist.find('parametername').text
description = get_text(param.find('parameterdescription'))
if description:
parameters[name] = description
if brief:
if language == 'python' and kind == 'public-... |
SummerLW/Perf-Insight-Report | dashboard/dashboard/stored_object.py | Python | bsd-3-clause | 6,638 | 0.008888 | # Copyright 2015 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.
"""A module for storing and getting objects from datastore.
This module provides Get, Set and Delete functions for storing pickleable
objects in datastore, ... | lues[key] is not None:
serialized += cache_values[key]
return pickle.loads(serialized)
@classmethod
def Set(cls, key, value):
"""Sets a value in memcache."""
serialized_parts = _Serialize(value)
if len(serialized_parts) > _MAX_NUM_PARTS:
logging.error('Max number of | parts reached.')
return
cached_values = {}
cached_values[cls._GetCacheKey(key)] = len(serialized_parts)
for i in xrange(len(serialized_parts)):
cached_values[cls._GetCacheKey(key, i)] = serialized_parts[i]
memcache.set_multi(cached_values)
@classmethod
def Delete(cls, key):
"""Dele... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractLittlebambooHomeBlog.py | Python | bsd-3-clause | 622 | 0.028939 | def ex | tractLittlebambooHomeBlog(item):
'''
Parser for 'littlebamboo.home.blog'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('FW', 'Fortunate Wife', 'translated'),
('PRC'... | eturn buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
coursemdetw/2015wcms | wsgi/openshift/openshiftlibs.py | Python | gpl-2.0 | 3,730 | 0.008043 | #@+leo-ver=5-thin
#@+node:2014spring.20140628104046.1746: * @file openshiftlibs.py
#@@language python
#@@tabwidth -4
#@+others
#@+node:2014spring.20140628104046.1747: ** openshiftlibs declarations
#!/usr/bin/env python
import hashlib, inspect, os, random, sys
#@+node:2014spring.20140628104046.1748: ** get_openshift_s... | = key_info['hash']
key = key_info['variable']
original = key_info['original']
# These are the legal password characters
# as pe | r the Django source code
# (django/contrib/auth/models.py)
chars = 'abcdefghjkmnpqrstuvwxyz'
chars += 'ABCDEFGHJKLMNPQRSTUVWXYZ'
chars += '23456789'
# Use the hash to seed the RNG
random.seed(int("0x" + hashcode[:8], 0))
# Create a random string the same length as the default
rand_key... |
evereux/flicket | scripts/users_import_from_json.py | Python | mit | 2,390 | 0.00251 | #! usr/bin/python3
# -*- coding: utf8 -*-
import datetime
import json
import os
from flask_script import Command
from scripts.users_export_to_json import json_user_file
from application import db
from application.flicket.models.flicket_user import FlicketUser
class JsonUser:
def __init__(self,... | e, name, email, password.
]
"""
@staticmethod
def run():
# check if file exists
if not os.path.isfile(json_user_file):
print('Could not find json file "{}". Exiting ....'.format(json_user_file))
exit()
# read json file
with open... | ', 'email', 'password']
for user in json_users:
if not all(f in user for f in valid_json_fields):
print('json file not formatted correctly. Exiting.')
exit()
# add users to database.
for user in json_users:
# encode password to b... |
AgapiGit/RandomPasswordGenerator | RandomPasswordGenerator/manage.py | Python | mit | 843 | 0.001186 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "RandomPasswordGenerator.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other... | is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did... | mand_line(sys.argv)
|
camflan/agro | agro/sources/__init__.py | Python | bsd-3-clause | 1,319 | 0.006823 | from datetime import datetime
import logging
import sys
from django.conf import settings
log = logging.getLogger('agro.sources')
tree_modules_to_try = [ "xml.etree.cElementTree", "elementtree.ElementTree", "cElementTree", ]
element_tree = None
for tree in tree_modules_to_try:
try:
try:
eleme... | except:
s = __import__("agro.sources.%s" % source, {}, | {}, ['%s%s' % (source, class_name)])
if s:
sources.append(s)
except Exception, e:
log.error('unable to load %s: %s', source, e)
return sources
|
sdpython/pyquickhelper | src/pyquickhelper/helpgen/notebook_exporter.py | Python | mit | 4,770 | 0.001048 | # -*- coding: utf-8 -*-
"""
@file
@brief Customer notebook exporters.
"""
import os
from textwrap import indent
from traitlets import default
from traitlets.config import Config
from jinja2 import DictLoader
from nbconvert.exporters import RSTExporter
from nbconvert.filters.pandoc import convert_pandoc
def convert_pa... | nizable when adding a menu.
"""
def __init__(self, *args, **kwargs):
"""
Overwrites the extra loaders to get the right template.
| """
filename = os.path.join(os.path.dirname(__file__), 'rst_modified.tpl')
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
filename = os.path.join(os.path.dirname(__file__), 'rst.tpl')
with open(filename, 'r', encoding='utf-8') as f:
con... |
bjodah/finitediff | finitediff/grid/rebalance.py | Python | bsd-2-clause | 4,269 | 0.000937 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import math
import numpy as np
from scipy.interpolate import interp1d
def _avgdiff(x):
dx = np.diff(x)
dx2 = np.zeros_like(x)
dx2[0], dx2[-1] = dx[0], dx[-1]
dx2[1:-1] = 0.5 * (dx[1:] + dx[:-1])
return dx2
... | np.linspace(
grid[-2], grid[-1], resolution_factor + 1
)
smoothed = smooth_err(finegrid) + base * area_err / (grid[-1] - grid[0])
assert np.all(smoothed > 0)
assert np.all(_avgdiff(finegrid) > 0)
interr = np.cumsum(smoothed * _avgdiff(finegrid))
cb = interp1d(interr, finegrid)
return... | tol*gridvalue + atol`` will
be pruned. In general the value on the right is removed unless it is
the last point in the grid.
Parameters
----------
grid : array
rtol : float
atol : float
Returns
-------
NumPy array of ``numpy.bool_`` (to be used as mask).
"""
if np.any(... |
torypages/luigi | test/contrib/pig_test.py | Python | apache-2.0 | 5,241 | 0.001336 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | return ['-x', 'local']
class SimplePigTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
@patch('subprocess.Popen')
def test_run__success(self, mock):
arglist_result = []
p = subprocess.Popen
subprocess.Popen = _get_fake_Popen(argli... | )
finally:
subprocess.Popen = p
@patch('subprocess.Popen')
def test_run__fail(self, mock):
arglist_result = []
p = subprocess.Popen
subprocess.Popen = _get_fake_Popen(arglist_result, 1)
try:
job = SimpleTestJob()
job.run()
... |
simonspa/django-datacollect | datacollect/survey/management/commands/edit_relations.py | Python | gpl-3.0 | 2,980 | 0.00906 | from django.core.management.base import BaseCommand, CommandError
from survey.models import Record
from fuzzywuzzy import fuzz
class Command(BaseCommand):
help = 'Finds fuzzy name matches and allows to alter their relation'
def add_arguments(self, parser):
parser.add_argument('start', nargs='?', type=... | erson_id,r2.person_id)
print u"Follow-up: {0!r:<30}{1}".format(r1.follow_up_case,r2.follow_up_case)
print u"Date intervention: {0:30}{1}".format(str(r1.date_intervention),str(r2.date_intervention))
print u"Issue area: {0:30}{1}".format(r1.issue_area,r2.issu... | levant_activities)
if Record.objects.filter(pk=r1.pk, follow_ups__pk=r2.pk).exists():
print u"Relation exists? ************** YES ****************"
else:
print u"Relation exists? .............. NO ................"
whil... |
95ellismle/FinancesApp2 | Gui/App.py | Python | gpl-3.0 | 3,438 | 0.013089 | # Importing Modules from PyQt5
from PyQt5.QtWidgets import QSizePolicy, QPushButton, QFrame, QWidget, QStackedWidget
from PyQt5.QtGui import QColor
# Importing Modules from the App
from Gui import Table, Plot, Funcs, Budget
from Settings import StyleSheets as St
def smallerNumber(number1, number2):
if number1 < n... | = []
but_funcs = [self.onTabButton, self.onPlotButton, self.onBudgetButton ]
but_funcs = fill_a_list(but_funcs, self.emptyFunc, St.number_of_buttons_on_sidebar-len(but_funcs))
for i in range(St.number_of_buttons_on_sidebar):
button = QPushButton(button_titles[i])
butto... | cy.Expanding)
button.setCheckable(True)
self.buttons.append(button)
Funcs.AllInOneLayout(sidebar_frame, self.buttons, VH='V')# add button and button2 to the sidebar_frame vertically, aligning them at the top.
#frame_layout.setSizeLayout(QSizePolicy.E... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/scripts/api/history_delete_history.py | Python | gpl-3.0 | 389 | 0.03856 | #!/usr/bin/env python
import os, sys |
sys.path.insert( 0, os.path.dirname( __file__ ) )
from common import delete
try:
assert sys.argv[2]
except IndexError:
print 'usage: %s key url [purge (true/false)] ' % os.path.basename( sys.argv[0] )
sys.exit( 1 )
try:
data = {}
data[ 'purge' ] = sys.argv[3]
except IndexError:
pass
delete( s... | ], data )
|
Becksteinlab/BornProfiler | scripts/apbs-bornprofile-init.py | Python | gpl-3.0 | 1,462 | 0.008208 | #!/usr/bin/env python
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# BornProfiler --- A package to calculate electrostatic free energies with APBS
# Written by Kaihsu Tai, Lennard van der Feltz, and Oliver Beckstein
# Released under th... | nce (but it will not cause any damage to run this script again).
"""
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser(usage=usage)
opts, args = parser.parse_args()
bornprofiler.start_logging()
bornprofiler.config.setup()
if bornprofiler.config.check_setu | p():
logger.info("Init successful: you now have the template directories under %r.",
bornprofiler.config.configdir)
logger.info("The package can also be customized by editing %r.",
bornprofiler.config.CONFIGNAME)
logger.info("Questions and feedback: Oliver Beckstein <obeckste... |
regardscitoyens/nosfinanceslocales_scraper | localfinance/spiders/localfinance_spider.py | Python | mit | 7,108 | 0.004361 | # -*- coding: utf-8 -*-
import re
import pandas as pd
from scrapy.spiders import Spider
from scrapy.selector import Selector
from ..parsing.zone import (
CityZoneParser,
EPCIZoneParser,
DepartmentZoneParser,
RegionZoneParser
)
from ..item import LocalFinance
from ..utils import DOM_DEP_MAPPING, unifo... | 3.txt"
data = pd.io.parsers.read_csv(insee_code_file, '\t')
data['DEP'] = uniformize_code(data, 'DEP')
data['DEP'] = convert_dom_code(data)
baseurl = "%s/departements/detail.php?dep=%%(DEP)s&exercice=%s" % (self.domain, year)
return [baseurl % row for __, row in data.iterrows()]
... | _code_file = "data/locality/reg2013.txt"
data = pd.io.parsers.read_csv(insee_code_file, '\t')
data['REGION'] = uniformize_code(data, 'REGION')
# Special case for DOM as usual
def set_dom_code(reg):
if reg == '001':
return '101'
elif reg == '002':
... |
kodexlab/eleve | eleve/segment.py | Python | lgpl-3.0 | 6,623 | 0.004379 | """ :mod:`eleve.segment`
==========================
The segmenter is available by importing ``eleve.Segmenter``. It is used to
segment sentences (regroup tokens that goes together).
"""
import logging
from math import isnan
logger = logging.getLogger(__name__)
class Segmenter:
def __init__(self, storage, max_... | bies.append(chartoks[-1] + "-E")
return " ".join(bies)
def segmentSentenceBIES(self, sent: str) -> str:
tokens = tuple(sent.split(" "))
words = self.segment(tokens)
bies = []
for w in words:
if len(w) == 1:
bies.append(w[0] + "-S")
... | bies.append(w[-1] + "-E")
return " ".join(bies)
|
kiddinn/plaso | tests/cli/helpers/output_modules.py | Python | apache-2.0 | 2,511 | 0.002788 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the output modules CLI arguments helper."""
import argparse
import unittest
from plaso.cli import tools
from plaso.cli.helpers import output_modules
from plaso.lib import errors
from tests.cli import test_lib as cli_test_lib
class OutputModulesArgumentsHe... | [-w OUTPUT_FILE] [--fields FIELDS]
[--additional_fields ADDITIONAL_FIELDS]
Test argument parser.
optional arguments:
--additional_fields ADDITIONAL_FIELDS, --additional-fields ADDITIONAL_FIELDS
Defines extra fields to be included in the output, in
... | FIELDS Defines which fields should be included in the output.
-o FORMAT, --output_format FORMAT, --output-format FORMAT
The output format. Use "-o list" to see a list of
available output formats.
-w OUTPUT_FILE, --write OUTPUT_FILE
Output... |
pacoqueen/upy | formularios/consulta_ventas_ticket.py | Python | gpl-2.0 | 19,273 | 0.009814 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (C) 2005-2008 Francisco José Rodríguez Bogado #
# ([email protected]) #
# ... | sqlobject
import sys, os
try:
import pclases
except ImportError:
sys.path.append(os.path.join('..', 'framework'))
import pc | lases
import datetime
try:
import geninformes
except ImportError:
sys.path.append(os.path.join('..', 'informes'))
import geninformes
try:
from treeview2pdf import treeview2pdf
except ImportError:
sys.path.append(os.path.join("..", "informes"))
from treeview2pdf import treeview2pdf
try:
from ... |
peto2006/sortiment-frontent | sortimentGUI/__init__.py | Python | mit | 104 | 0.009615 | __ | all__ = ['gtk_element_editor', 'main_window_handler', 'sortiment', 'window_creat | or', 'error_handler']
|
tylertian/Openstack | openstack F/nova/nova/tests/cert/test_rpcapi.py | Python | apache-2.0 | 3,147 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... | self.a | ssertEqual(retval, expected_retval)
self.assertEqual(self.call_ctxt, ctxt)
self.assertEqual(self.call_topic, FLAGS.cert_topic)
self.assertEqual(self.call_msg, expected_msg)
self.assertEqual(self.call_timeout, None)
def test_revoke_certs_by_user(self):
self._test_cert_api('re... |
rtfd/readthedocs.org | readthedocs/analytics/apps.py | Python | mit | 224 | 0 | """Django app config for the analytics app."""
from django.apps import AppConfig
class AnalyticsAppConfig(AppCon | fig):
"""Analytics app init code."""
name = 'readthedocs.analytics'
verbose_name = 'Ana | lytics'
|
Anthony25/barython | barython/hooks/audio.py | Python | bsd-3-clause | 363 | 0 | #!/usr/bin/env python3
import logging
from . import SubprocessHook
logger = logging.getLogger("barython")
class PulseAudioHook(SubprocessHook):
"""
Listen on pulseaudio events with pactl
"""
def __init__(self, cmd=["pactl", "subscribe", "-n", "barython"],
*args, **kwargs):
... | gs, cmd=cmd)
| |
sondree/Master-thesis | Python Simulator/simulator/FMM.py | Python | gpl-3.0 | 2,479 | 0.020976 | import numpy as np
import pygame
from sklearn.mixture import GMM
from math import sqrt, atan, pi
def emFit(results, numComponents):
if len(results) == 0:
return None
m =np.matrix(results)
gmm = GMM(numComponents,covariance_type='full', n_iter= 100, n_init = 4)
gmm.fit(results)
component... |
for color,(mu,cov, proba) in zip(colors[:len(components)],components):
eigenvalues, eigenvectors = np.linalg.eig(cov)
major = 2.0 * sqrt(5.991 * eigenvalues.max())
minor = 2.0 * sqrt(5.991 * eigenvalues.min())
angle1 = atan(eigenvectors[1][0]/eigenvectors[0][0])
angle2 ... | angle = angle2
mu_x,mu_y = mu
if major < 1.0 or minor < 1.0:
continue
s = pygame.Surface((major*scaleFactor[0], minor*scaleFactor[1]),pygame.SRCALPHA, 32)
ellipse = pygame.draw.ellipse(s, color, (0, 0, major*scaleFactor[0], minor*scaleFactor[0]))
... |
kiyukuta/chainer | tests/chainer_tests/initializer_tests/test_uniform.py | Python | mit | 1,548 | 0 | import unittest
from chainer import cuda
from chainer import initializers
from chainer import testing
from chainer.testing import attr
import numpy
@testing.parameterize(*testing.product({
'target': | [
initializers.Uniform,
initializers.LeCunUniform,
initializers.HeUniform,
initializers.GlorotUniform,
],
'shape': [(2, 3), (2, 3, 4)],
'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
class TestUniform(unittest.TestCase):
scale = 0.1
def check_initializ... | .target(scale=self.scale)
initializer(w)
self.assertTupleEqual(w.shape, self.shape)
self.assertEqual(w.dtype, self.dtype)
def test_initializer_cpu(self):
w = numpy.empty(self.shape, dtype=self.dtype)
self.check_initializer(w)
@attr.gpu
def test_initializer_gpu(self)... |
spanner888/madparts | setup.py | Python | gpl-3.0 | 3,599 | 0.012781 | #!/usr/bin/env python
#
# (c) 2013 Joost Yervante Damad <[email protected]>
# License: GPL
VERSION='1.2.1'
import glob, sys, platform
from setuptools import setup
with open('README.md') as file:
long_description = file.read()
arch = platform.uname()[4]
extra_data_files = []
if sys.platform == 'darwin':
OPTION... | }
extra_options = dict(
setup_requires=['py2app'],
app=['madparts'],
# Cross-platform applications generally expect sys.argv to
# be used for opening files.
options=dict(py2app=OPTIONS),
)
elif sys.platform == 'win32':
import py2exe
OPTIONS = {
'includes': [
"... | nGL.arrays.arraydatatype",
"OpenGL.arrays.arrayhelpers",
"OpenGL.arrays.buffers",
"OpenGL.arrays.ctypesarrays",
"OpenGL.arrays.ctypesparameters",
"OpenGL.arrays.ctypespointers",
"OpenGL.arrays.formathandler",
"OpenGL.arrays.lists",
"OpenGL.... |
AndreMiras/pycaw | examples/volume_callback_example.py | Python | mit | 950 | 0 | """
IAudioEndpointVolumeCallback.OnNotify() example.
The OnNotify() | callback method gets called on volume change.
"""
from __future__ import print_function
from ctypes impor | t POINTER, cast
from comtypes import CLSCTX_ALL, COMObject
from pycaw.pycaw import (AudioUtilities, IAudioEndpointVolume,
IAudioEndpointVolumeCallback)
class AudioEndpointVolumeCallback(COMObject):
_com_interfaces_ = [IAudioEndpointVolumeCallback]
def OnNotify(self, pNotify):
... |
avtomato/HackerRank | Algorithms/_03_Strings/_04_Caesar_Cipher/solution.py | Python | mit | 233 | 0 | # | !/bin/python3
import sys
n = int(input().strip())
s = input().strip()
k = int(input().strip())
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+k) % 26 + c)
print(''.join([d.get(c, c) for c in s]))
| |
MagicStack/httptools | setup.py | Python | mit | 7,252 | 0 | import sys
vi = sys.version_info
if vi < (3, 5):
raise RuntimeError('httptools require Python 3.5 or greater')
else:
import os.path
import pathlib
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as build_ext
CFLAGS = ['-O2']
ROOT = pathlib.Path(__file_... | y be called multiple times on the
# same command object, so make sure not to override previously
# set options.
if getattr(self, '_initialized', False):
return
super().initialize_options()
self.use_system_llhttp = False
self.use_system_http_parser = Fal | se
self.cython_always = False
self.cython_annotate = None
self.cython_directives = None
def finalize_options(self):
# finalize_options() may be called multiple times on the
# same command object, so make sure not to override previously
# set options.
if getat... |
sfu-fas/coursys | faculty/event_types/position.py | Python | gpl-3.0 | 2,366 | 0.000845 | from django import forms
from faculty.event_types.base import BaseEntryForm
from faculty.event_types.base import CareerEventHandlerBase
from faculty.event_types.choices import Choices
from faculty.event_types.base import TeachingAdjust
from faculty.event_types.fields import TeachingCreditField
from faculty.event_types... | .event_types.search import ChoiceSearchRule
from faculty.event_types.search import ComparableSearchRule
class AdminPositionEventHandler(CareerEventHandlerBase, TeachingCareerEvent):
"""
Given admin position
"""
EVENT_TYPE = 'ADMINPOS'
NAME = 'Admin Position'
TO_HTML_TEMPLATE = """
{ | % extends "faculty/event_base.html" %}{% load event_display %}{% block dl %}
<dt>Position</dt><dd>{{ handler|get_display:'position' }}</dd>
<dt>Teaching Credit</dt><dd>{{ handler|get_display:'teaching_credit' }}</dd>
{% endblock %}
"""
class EntryForm(BaseEntryForm):
POSITIONS ... |
thaim/ansible | lib/ansible/modules/cloud/kubevirt/kubevirt_template.py | Python | mit | 14,884 | 0.004367 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | penshift cluster.
type: dict
icon_class:
description:
- "An icon to be displayed with your template in the web console. Choose from our existing logo
icons when possible. You can also use icons from FontAwesome. Alternatively, provide icons through
CSS customizati... | ner Platform cluster that uses your template.
You must specify an icon class that exists, or it will prevent falling back to the generic icon."
type: str
parameters:
description:
- "Parameters allow a value to be supplied by the user or generated when the template is instanti... |
diegojromerolopez/djanban | src/djanban/apps/hourly_rates/forms.py | Python | mit | 1,137 | 0.001759 | # -*- coding: utf-8 -*-
from __future__ | import unicode_literals
from django.core.exceptions import ValidationError
from django.forms import models
from djanban.apps.hourly_rates.models import HourlyRate
from django import forms
# Hourly rate creation and edition form
class HourlyRateForm(models.ModelForm):
class Meta:
model = HourlyRa | te
fields = ["name", "start_date", "end_date", "amount", "is_active"]
widgets = {
'start_date': forms.SelectDateWidget(),
'end_date': forms.SelectDateWidget(empty_label=u"Until now"),
}
def __init__(self, *args, **kwargs):
super(HourlyRateForm, self).__init__... |
JoeJimFlood/NFLPrediction2014 | matchup.py | Python | mit | 10,272 | 0.007496 | import os
import sys
import pandas as pd
import numpy as np
from numpy.random import poisson, uniform
from numpy import mean
import time
import math
po = True
teamsheetpath = sys.path[0] + '/teamcsvs/'
compstat = {'TDF': 'TDA', 'TDA': 'TDF', #Dictionary to use to compare team stats with opponent stats
'F... | yoff:
win_1 = 0.5
win_2 = 0.5
draw_1 = 0
draw_2 = 0
else:
win_1 = 0
win_2 = 0
draw_1 = 1
draw_2 = 1
summary = {team_1: [win_1, draw_1, score_1]}
summary.update({team_2: [win_2, draw_2, | score_2]})
return summary
def get_expected_scores(team_1_stats, team_2_stats, team_1_df, team_2_df): #Get the expected scores for a matchup based on the previous teams' performances
expected_scores = {}
for stat in team_1_stats:
expected_scores.update({'TD': mean([team_1_stats['TDF'] + team_2_df['T... |
chrisspen/asklet | asklet/management/commands/asklet_load_conceptnet.py | Python | lgpl-3.0 | 9,742 | 0.005646 | #!/usr/bin/python
from __future__ import print_function
import random
import re
import datetime
import os
import sys
import time
from optparse import make_option
import urllib2
import tarfile
from multiprocessing import cpu_count
from django.conf import settings
from django.core.management.base import BaseCommand
from... | art=part_name)
if fi.total_lines is None:
tar = tarfile.open(fn, 'r')
fin = tar.extractfile(part_name)
print('%s | : Counting lines...' % part_name)
total = fin.read().decode('utf8').count('\n')
fi.current_line = 0
fi.total_lines = total
fi.save()
elif fi.done:
print('%s: Already complete.' % part_name)
return
else:
total = fi.total_lines
print('%s: %i lines f... |
sparkslabs/kamaelia_ | Sketches/RJL/Packages/Examples/P2PStreamPeer/p2pstreampeer.py | Python | apache-2.0 | 10,507 | 0.007233 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... | # See the License for the specific language governing permissions and
# limitations under the License.
# -------------------------------------------------------------------------
# Licensed to the BBC under a Contributor Agreement: RJL
"""\
===========================================
Peer-to-Peer | Streaming System (client part)
===========================================
This example demonstrates the use of BitTorrent and HTTP to download, share
reconstruct a data stream in real-time.
It expects a webserver hosting a folder that contains:
- meta.txt (a file containing the number of chunks/torrents in the strea... |
magnunleno/Rurouni | tests/test_table_migration.py | Python | gpl-3.0 | 2,788 | 0.002869 | #!/usr/bin/env python
# encoding: utf-8
import pytest
from conftests import *
from rurouni.exceptions import *
from rurouni.types import *
from rurouni import Database, Column, Table
def test_column_appending(ldb):
'''
Checks column appending. To simulate this behaviour just adds two different
classes po... | For this is needed to set the db.autoremove_columns flag as True.
'''
ldb.db.autoremove_columns = True
# First declaration
class Cli | ent(Table):
__db__ = ldb.db
firstname = Column(String)
lastname = Column(String)
ldb.flush()
# Second declaration
class NewClient(Table):
__db__ = ldb.db
__tablename__ = 'client'
firstname = Column(String)
# Check logs
logs = ldb.getLog()
assert ... |
sysoevss/WebApps17 | data.py | Python | mit | 2,774 | 0.004326 | # coding=UTF-8
'''
Created on 24.09.2017
@author: sysoev
'''
from google.appengine.ext import db
from google.appengine.api import users
import datetime
import time
import logging
from myusers import MyUser
def force_unicode(string):
if type(string) == unicode:
return string
return string.decode('ut... | one:
return []
query = UserProject.all().filter('user_key = ', user.key())
return [user_project.project_key for user_project in query]
# return [Project.get(user_project.project_key) for user_project in query]
class Request(db.Model):
number = int
name = db.StringProperty() |
description = db.StringProperty(multiline=True)
state = int
perfomer = db.ReferenceProperty() #???
def addRequests(project_key, name, description):
print("log")
req = Request(parent=project_key)
req.name = name
req.description = description
req.perfomer = ""
req.state = 1
req.... |
tiffanyj41/hermes | src/utils/save_load.py | Python | apache-2.0 | 3,756 | 0.004526 | import csv
import gzip
def save_vector(vector, output_fname):
"""
Save the any type of vector for future use.
This could be ratings, predictions or the content vector
Results need to be collected to the local history before being read out
Args:
vector: either user ratings, predictions or t... | tent_vector
def save_uv_to_hadoop(vector, output_name):
vector.map(lambda x: ','.join(map(str,x))).saveAsTextFile(output_name)
def load_uv_from_hadoop(input_name, sc, num_partitions=20):
uv = sc.textFile(input_name).map(parseText)\
.repartition(num_partitions)
return uv
def parseText(row):
ro... | import subprocess
cmd_output = subprocess.check_output(cmd, shell=True)
return cmd_output
def save_to_hadoop(vector, output_name):
import subprocess
try:
# overwrite the past vector that was saved
rm_hdfs_dir(output_name)
except subprocess.CalledProcessError as e:
# hdfs d... |
TryExceptElse/pysheetdata | eval/parser.py | Python | mit | 4,789 | 0 | """
functions for evaluating spreadsheet functions
primary function is parse, which the rest revolves around
evaluate should be called with the full string by a parent program
A note on exec:
This uses the exec function repeatedly, and where possible, use of it
should be minimized, but the intention of this ... | + 1: parent_close]
formula = '{}({})'.format(prefix, body)
replace[formula] = str(parse(prefix, body))
verbose('replacing | {} with {}'.format(formula,
replace[formula]))
it += 1
# replace strings
for entry in replace:
s = s.replace(entry, replace[entry])
# depending on the presence of a function, either simply evaluate,
# or use a function from funct... |
JeremyGrosser/python-eventlet | tests/stdlib/test_urllib2_localnet.py | Python | mit | 410 | 0.007317 | from eventlet import patcher
| from eventlet.green import BaseHTTPServer
from eventlet.green import threading
from eventlet.green import socket
from eventlet.green import urllib2
patcher.inject('test.test_urllib2_localnet',
globals(),
| ('BaseHTTPServer', BaseHTTPServer),
('threading', threading),
('socket', socket),
('urllib2', urllib2))
if __name__ == "__main__":
test_main() |
DemocracyClub/UK-Polling-Stations | polling_stations/apps/data_importers/management/commands/import_wyre_forest.py | Python | bsd-3-clause | 949 | 0.001054 | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "WYE"
addresses_name = "2021-03-29T13:16: | 10.236797/Democracy_Club__06May2021.tsv"
stations_name = "2021-03-29T13:16:10.236797/Democracy_Club__06May2021.tsv"
elections = ["2021-05-06"]
csv_delimiter = "\t"
def address_record_to_dict(self, record):
uprn = record.property_urn.strip().lstrip("0")
if uprn in [
"1000338... | "DY10 3HJ",
"DY10 2QD",
"DY10 3TF",
"DY11 5QT",
"DY10 3HH",
"DY10 1SB",
"DY10 1LS",
"DY10 3EL",
]:
return None
return super().address_record_to_dict(record)
|
jgrandguillaume/vertical-ngo | logistic_budget/wizard/cost_estimate.py | Python | agpl-3.0 | 1,462 | 0 | # -*- co | ding: utf-8 -*-
#
# Author: Joël Grand-Guillaume
# 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
# 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 useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty... |
dmccloskey/SBaaS_rnasequencing | SBaaS_rnasequencing/stage01_rnasequencing_analysis_postgresql_models.py | Python | mit | 2,579 | 0.027918 | from SBaaS_base.postgresql_orm_base import *
class data_stage01_rnasequencing_analysis(Base):
__tablename__ = 'data_stage01_rnasequencing_analysis'
id = Column(Integer, Sequence('data_stage01_rnasequencing_analysis_id_seq'), primary_key=True)
analysis_id = Column(String(500))
experiment_id = Column(Str... | reviation
sample_name = Column(String(500)) # equivalent to sample_name_abbreviation
time_point = Column(String(10)) # converted to intermediate in lineage analysis
analysis_type = Column(String(100)); # time-course (i.e., multiple time points), paired (i.e., control compared to multiple replicates), group ... | = (
UniqueConstraint('experiment_id','sample_name_abbreviation','sample_name','time_point','analysis_type','analysis_id'),
)
def __init__(self,
row_dict_I,
):
self.analysis_id=row_dict_I['analysis_id'];
self.experiment_id=row_dict_I['experime... |
CodaMais/CodaMais | CodaMais/user/managers.py | Python | gpl-3.0 | 1,179 | 0 | # standard library
import logging
# Django
from django.contrib.auth.models import BaseUserManager
# logger instance
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class UserManager(BaseUserManager):
def create_user(self, email, password, username, first_name, **kwargs):
log... | username=username,
first_name=first_name,
is_active=False,
**kwargs)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, email, password,
... | first_name=first_name,
is_staff=True,
is_active=True,
is_superuser=True,
**kwargs)
user.set_password(password)
user.save(using=self.db)
return user
|
shakna-israel/rst2pdf | gui/Ui_configdialog.py | Python | mit | 7,900 | 0.003418 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'configdialog.ui'
#
# by: PyQt4 UI code generator 4.5.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dia... | idget(self.container)
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 241, 399))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.verticalLay | out_3 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents)
self.verticalLayout_3.setMargin(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.layout = QtGui.QVBoxLayout()
self.layout.setObjectName("layout")
self.verticalLayout_3.addLayout(self.layout)
self.cont... |
netconstructor/django-activity-stream | actstream/views.py | Python | bsd-3-clause | 3,684 | 0.011129 | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import Co... | stance=RequestContext(request))
def actor(request, content_type_id, object_id):
"""
``Actor`` focused activity stream for actor defi | ned by ``content_type_id``, ``object_id``
"""
ctype = get_object_or_404(ContentType, pk=content_type_id)
actor = get_object_or_404(ctype.model_class(), pk=object_id)
return render_to_response('activity/actor.html', {
'action_list': actor_stream(actor), 'actor':actor,'ctype':ctype
}, cont... |
eXistenZNL/SickRage | sickbeard/clients/deluged_client.py | Python | gpl-3.0 | 6,499 | 0.005539 | # Author: Paul Wollaston
# Contributions: Luke Mullan
#
# This client script allows connection to Deluge Daemon directly, completely
# circumventing the requirement to use the WebUI.
import json
from base64 import b64encode
import sickbeard
from sickbeard import logger
from .generic import GenericClient
from synchron... | return None
options = {
'add_paused': sickbeard.TORRENT_PAUSED
}
remote_torrent = self.drpc.add_torrent_file(result.name + '.torrent', result.content, options, resul | t.hash)
if not remote_torrent:
return None
result.hash = remote_torrent
return remote_torrent
def _set_torrent_label(self, result):
label = sickbeard.TORRENT_LABEL
if result.show.is_anime:
label = sickbeard.TORRENT_LABEL_ANIME
if ' ' in la... |
hep-gc/repoman | server/repoman/repoman/lib/storage/storage.py | Python | gpl-3.0 | 204 | 0.009804 | import os
from pylons import app_globals
def | delete_image(image):
paths = image.path.split(';')
for p in paths:
path = os.path.join(app_globals.image_storage | , p)
os.remove(path)
|
WuNL/mylaptop | install/lib/python2.7/dist-packages/mapping_dlut/msg/_Map.py | Python | bsd-3-clause | 10,485 | 0.017167 | """autogenerated by genpy from mapping_dlut/Map.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import mapping_dlut.msg
import std_msgs.msg
class Map(genpy.Message):
_md5sum = "e6ab6c8862bf55f4e1b5fd48f03f1a7d"
_type = "mapping_dlut/Map"
_has_h... | tr``
"""
try:
if self.header is None:
self.header = std_msgs.msg.Header()
if self.map is None:
self.map = None
end = 0
_x = self
start = end
end += 12
(_x.header.seq, _x.heade | r.stamp.secs, _x.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.header.frame_id = str[start:end].decode('utf-8')
else:
self.header.frame_id = s... |
elopio/snapcraft | snapcraft/plugins/go.py | Python | gpl-3.0 | 8,148 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015-2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | local_main_packages(self):
search_path = './{}/...'.format(self._get_local_go_package())
packages = self._run_output(['go', 'list', '-f',
'{{.ImportPath}} {{.Name}}' | ,
search_path])
packages_split = [p.split() for p in packages.splitlines()]
main_packages = [p[0] for p in packages_split if p[1] == 'main']
return main_packages
def build(self):
super().build()
tags = []
if self.options.go_build... |
SINGROUP/pycp2k | pycp2k/classes/_each286.py | Python | lgpl-3.0 | 1,114 | 0.001795 | from pycp2k.inputsection import InputSection
class _each286(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = Non | e
self.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Metadynamics = None
self.Geo_opt = None
self.Rot_opt = None
self.Cell_opt = None
self.Band = None
self.Ep_lin_solver = None
self.Spline_find_coeffs = None... | elf._keywords = {'Bsse': 'BSSE', 'Cell_opt': 'CELL_OPT', 'Just_energy': 'JUST_ENERGY', 'Band': 'BAND', 'Xas_scf': 'XAS_SCF', 'Rot_opt': 'ROT_OPT', 'Replica_eval': 'REPLICA_EVAL', 'Tddft_scf': 'TDDFT_SCF', 'Shell_opt': 'SHELL_OPT', 'Md': 'MD', 'Pint': 'PINT', 'Metadynamics': 'METADYNAMICS', 'Geo_opt': 'GEO_OPT', 'Spline... |
Aurous/Magic-Discord-Bot | discord/opus.py | Python | gpl-3.0 | 8,162 | 0.003798 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2016 Rapptz
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 wit | hout restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to | the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PAR... |
SaMnCo/charm-dashing | lib/charmhelpers/fetch/bzrurl.py | Python | agpl-3.0 | 1,463 | 0.001367 | import os
from bzrlib.branch import Branch
from charmhelpers.fetch import (
BaseFetchHandler,
Unhandled | Source
)
from charmhelpers.core.host import mkdir
class BzrUrlFetchHandler(BaseFetchHandler):
"""Handler for bazaar branches via generic and lp URLs"""
def can_handle(self, source):
url_parts = self.parse_url(source)
if url_parts.scheme not in ('bzr+ssh', 'lp'):
re | turn False
else:
return True
def branch(self, source, dest):
url_parts = self.parse_url(source)
# If we use lp:branchname scheme we need to load plugins
if not self.can_handle(source):
raise UnhandledSource("Cannot handle {}".format(source))
if url_pa... |
CristianCantoro/wikipedia-tags-in-osm | extract_templates.py | Python | gpl-3.0 | 4,620 | 0.000433 | #! /usr/bin/python
# -*- coding: utf-8 -*-
import requests
import wikipedia_template_parser as wtp
from lxml import etree
import re
import json
def templates_including_coords():
LINKSCOORD = "http://it.wikipedia.org/w/index.php?title="\
"Speciale:PuntanoQui/Template:Coord&namespace=10&limit=500"... | dei template",
dest='no_add',
action="store_true"
)
parser.add_argument("-r", "--read",
help="leggi il file invece di scriverlo",
action="store_true"
)
args = parser.... | write(args.file)
else:
write(args.file, args.add)
if __name__ == '__main__':
import argparse
import os
main()
|
bhansa/fireball | pyvenv/Lib/site-packages/pygame/tests/run_tests__tests/infinite_loop/fake_1_test.py | Python | gpl-3.0 | 977 | 0.008188 | if __name__ == '__main__':
import sys
import os
pkg_dir = (os.path.split(
os.path.split(
os.path.split(
os.path.abspath(__file__))[0])[0])[0])
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
... | e:
pass
def test_get_pressed(self):
self.assert_(True)
def test_name(self):
| self.assert_(True)
def test_set_mods(self):
self.assert_(True)
def test_set_repeat(self):
self.assert_(True)
if __name__ == '__main__':
unittest.main()
|
jgrocha/QGIS | tests/src/python/test_qgsvectorlayer.py | Python | gpl-2.0 | 159,533 | 0.001793 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsVectorLayer.
From build dir, run:
ctest -R PyQgsVectorLayer -V
.. note:: 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 Lic... | 200, NULL, 'NuLl', '5', QDateTime(QDate(2020, 5, 4), QTime(12, 13, 14)), QDate(2020, 5, 2), QTime(12, 13, 1)])
f1.setGeometry(QgsGeometry.fromWkt('Point (-71.123 78.23)'))
f2 = QgsFeature()
f2.setAttributes([3, 300, 'Pear', 'PEaR', '3', NULL, NULL, NULL])
f3 = QgsFeature()
f3.s... | butes([1, 100, 'Orange', 'oranGe', '1', QDateTime(QDate(2020, 5, 3), QTime(12, 13, 14)), QDate(2020, 5, 3), QTime(12, 13, 14)])
f3.setGeometry(QgsGeometry.fromWkt('Point (-70.332 66.33)'))
f4 = QgsFeature()
f4.setAttributes([2, 200, 'Apple', 'Apple', '2', QDateTime(QDate(2020, 5, 4), QTime(12, ... |
qedsoftware/commcare-hq | corehq/messaging/smsbackends/telerivet/migrations/0002_add_index_on_webhook_secret.py | Python | bsd-3-clause | 464 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from | django.db import models, migrat | ions
class Migration(migrations.Migration):
dependencies = [
('telerivet', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='incomingrequest',
name='secret',
field=models.CharField(max_length=255, null=True, db_index=True),
... |
CTSNE/NodeDefender | NodeDefender/manage/setup/database.py | Python | mit | 2,533 | 0.001974 | from NodeDefender.manage.setup import (manager, print_message, print_topic,
print_info)
from flask_script import prompt
import NodeDefender
@manager.command
def database():
print_topic('Database')
print_info("Database is used to store presistant data.")
print_info("By... | upported_databases:
engine = None
host = None
port = None
username = None
password = None
database = None
if engine == "mysql":
while not host:
host = prompt('Enter Server Address')
while not port:
port = prompt('Enter Server Port')
... | username = prompt('Enter Username')
while not password:
password = prompt('Enter Password')
while not database:
database = prompt("Enter Database Name")
filepath = None
if engine == "sqlite":
while not filepath:
print_info("Filename for SQLite... |
joakim-hove/ert | ert_gui/ertwidgets/validationsupport.py | Python | gpl-3.0 | 3,928 | 0.001018 | from qtpy.QtCore import Qt, QPoint, QObject, Signal
from qtpy.QtGui import QColor
from qtpy.QtWidgets import QWidget, QVBoxLayout, QSizePolicy, QFrame, QLabel
import html
class ErrorPopup(QWidget):
error_template = (
"<html>"
"<table style='background-color: #ffdfdf;'width='100%%'>"
"<tr><... | r_widget.setTextFormat(Qt.RichText)
layout.addWidget(self._error_widget)
self.setLayout(layout)
def presentError(self, widget, error):
assert isinstance(widget, QWidget)
self._error_widget.setText(ErrorPopup.error_template % html.escape(error))
self.show()
size_hi... | self.setGeometry(
p.x(), p.y() - size_hint.height() - 5, size_hint.width(), size_hint.height()
)
self.raise_()
class ValidationSupport(QObject):
STRONG_ERROR_COLOR = QColor(255, 215, 215)
ERROR_COLOR = QColor(255, 235, 235)
INVALID_COLOR = QColor(235, 235, 255)
WARNING = ... |
woutdenolf/wdncrunch | wdncrunch/modulea/tests/test_all.py | Python | mit | 1,623 | 0.002465 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Wout De Nolf ([email protected])
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software")... | Suite()
testSuite.addTest(test_classa.test_suite())
return testSuite
if __name__ == '__main__':
import sys
mysuite = test_su | ite()
runner = unittest.TextTestRunner()
if not runner.run(mysuite).wasSuccessful():
sys.exit(1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.