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 |
|---|---|---|---|---|---|---|---|---|
kn/ensembl | ensembl/info/analysis.py | Python | mit | 1,205 | 0 | # Copyright (c) 2014 Katsuya Noguchi
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis... | 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND ... | OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import http_client
def get_by_species(species):
path = '/info/analysis/%s' % species
return http_client.get(path)
|
michaelneu/threesixty | threesixty/windows/control.py | Python | mit | 4,203 | 0.003569 | import xinput
from .. import icontroller
from .. import constants
from .. import events
cl | ass Controller(icontroller.IController):
def __init__(self, device):
self.__device = device
self.eventhandlers = {}
self.get()
self.__updater = events.ControllerUpdater(self)
self.__updater.start()
def __mask(self, number, i):
"""Masks a given number ... | dictionary"""
button_config = {
constants.A: self.__mask(buttons, 12),
constants.B: self.__mask(buttons, 13),
constants.X: self.__mask(buttons, 14),
constants.Y: self.__mask(buttons, 15)
}
button_config[constants.MSLP] = self.__mask(buttons, 6)
... |
laufercenter/meld | meld/test/test_remd/test_slave_runner.py | Python | mit | 6,967 | 0.003014 | #
# Copyright 2015 by Justin MacCallum, Alberto Perez, Ken Dill
# All rights reserved
#
import unittest
import mock
from meld.remd import slave_runner, master_runner
from meld.system import runner
from meld import comm
sentinel = mock.sentinel
class TestSlaveInitFromMaster(unittest.TestCase):
"Initialize slave... | = [mock.call(s) for s in self.fake_states_after_run]
self.mock_system_runner.get_energy.assert_has_calls(calls)
def test_sends_energies_back_to_master(self):
"should send energies back to the master"
self.runner.run(self.mock_comm, self.mock_system_runner)
self.mock_comm.send_ener... | [sentinel.E1, sentinel.E2, sentinel.E3, sentinel.E4])
class TestSlaveMultiple(unittest.TestCase):
"Make sure the SlaveReplicaExchangeRunner works for a multiple rounds"
def setUp(self):
self.mock_comm = mock.Mock(spec_set=comm.MPICommunicator)
self.mock_comm.receive_states_for_energy_calc... |
PapenfussLab/MHC-clogs | bin/extract_hmmer2_genome_match3.py | Python | artistic-2.0 | 22,865 | 0.004024 | #!/usr/bin/env python
"""
extract_hmmer2_genome_match.py [options] <data_dir> <input_protein_dir> <output_genome_dir>
Previously DP.py
Author: Tony Papenfuss
Date: Fri Nov 10 21:45:25 EST 2006
"""
import os
import sys
from argparse import ArgumentParser
import numpy
from mungolite.sequence import translate
from mung... | :
name = ""
return name
def split_and_sort(data, reverse_neg_strand=True):
split_data = {}
for d in data:
key = (d.accession, d.strand)
try:
split_data[key].append(d)
except KeyError:
split_data[key] = [d]
for key in split_data:
if revers... | _data
def match_score(domain, state):
if domain.domain == state:
# Match
score = score_rescale_dict[state]*domain.score
else:
# Mis-match
score = -10000
return score
def gap_penalty_fn(d):
free = GAP_FN_FREE
scale = GAP_FN_SCALE
if d < free:
penalty = ... |
tadebayo/myedge | myvenv/Scripts/painter.py | Python | mit | 2,141 | 0.000934 | #!c:\users\adebayo\myedge\myvenv\scripts\python.exe
#
# The Python Imaging Library
# $Id$
#
# this demo script illustrates pasting into an already displayed
# photoimage. note that the current version of Tk updates the whole
# image every time we paste, so to get decent performance, we split
# the image into a set of ... | )
def paint(self, event):
xy = event.x - 10, event.y - 10, event.x + 10, event.y + 10
im = self.image.crop(xy)
# process the image in some fashion
im = im.convert("L")
self.image.paste(im, xy)
self.repair(xy)
def repair(self, b | ox):
# update canvas
dx = box[0] % self.tilesize
dy = box[1] % self.tilesize
for x in range(box[0]-dx, box[2]+1, self.tilesize):
for y in range(box[1]-dy, box[3]+1, self.tilesize):
try:
xy, tile = self.tile[(x, y)]
tile.... |
shubhamgupta123/erpnext | erpnext/hr/doctype/salary_slip/salary_slip.py | Python | gpl-3.0 | 34,301 | 0.024285 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, erpnext
import datetime, math
from frappe.utils import add_days, cint, cstr, flt, getdate, rounded, date_diff, money_in_words
from frapp... | slip_to_employee")) and not frappe.flags.via_payroll_entry:
self.email_salary_slip()
def on_cancel(self):
self.set_status()
self.update_status()
self.update_salary_slip_in_additional_salary()
def on_trash(self):
from frappe.model.naming import revert_series_if_last
revert_series_if_last(self.series, s... | lif self.docstatus == 1:
status = "Submitted"
elif self.docstatus == 2:
status = "Cancelled"
return status
def validate_dates(self):
if date_diff(self.end_date, self.start_date) < 0:
frappe.throw(_("To date cannot be before From date"))
def check_existing(self):
if not self.salary_slip_based_on_tim... |
fkmclane/MCP | mcp/api/server.py | Python | mit | 10,415 | 0.002592 | import os
import signal
import fooster.web
import fooster.web.query
import mcp.error
import mcp.common.http
import mcp.model.server
class Index(mcp.common.http.AuthHandler):
group = 0
def do_get(self):
return 200, [dict(server) for server in mcp.model.server.items() if server.server in self.auth.... | .NoLogLine:
return 201, mcp.model.server.log_get(self.groups[0])
except mcp.error.NoServerError:
raise fooster.web.HTTPError(404)
class Script(mcp.common.http.PlainAuthHandler):
group = 1
def do_get(self):
try:
if not self.auth.admin | and self.auth.username not in mcp.model.server.get(self.groups[0]).users:
raise fooster.web.HTTPError(404)
except AttributeError:
raise fooster.web.HTTPError(404)
self.response.headers['Content-Type'] = 'application/x-python-code'
try:
return 200, mcp.m... |
DXCanas/kolibri | docs/conf.py | Python | mit | 7,987 | 0.001878 | # -*- coding: utf-8 -*-
#
# Kolibri 'developer docs' build configuration file
#
# This file is execfile()d with the current directory set to its containing dir.
import inspect
import os
import sys
from datetime import datetime
import django
from django.utils.encoding import force_text
from django.utils.html import str... | le.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = 'logo.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.... | n = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Wide, responsive tables not supported until th... |
griffy/sikwidgets | sikwidgets/widgets/page.py | Python | mit | 2,250 | 0.001778 | import types
from sikwidgets.widgets.widget import Widget
from sikwidgets.widgets.widget import WidgetError
from sikwidgets.util import to_snakeca | se
def gen_widget_method(widget_class):
def widget_method(self, *args, **kwargs):
return self.create_widget(widget_class, *args, **kwargs)
return widget_method
class Page(Widget):
| def __init__(self, parent, source_widget, name=None):
if not name:
name = to_snakecase(self.__class__.__name__)
Widget.__init__(self, parent, name)
# Note: source_widget must have a selected attribute.
# eg, a radio button
self.source_widget = source_widget
... |
SantiagoValdez/hpm | src/hpm/app_item/views.py | Python | gpl-2.0 | 37,100 | 0.00283 | from principal.models import Fase
from principal.models import Item
from principal.models import VersionItem
from principal.models import AtributoItem
from principal.models import TipoItem
from principal.models import Relacion
from principal.models import ArchivoForm, Archivo
from principal.models import HistorialItem
... | re]
atributos[atributo.nombre] = valor
try:
newItem(request.POST["nombre"], request.POST[
"numero"], fase.id, tipo_item.id, atributos)
historialItem("crear", fase.id, user.id)
| except Exception, e:
print e
return render(request, 'nuevo-item.html', {'usuario': u, 'fase': fase, 'tipo_item': tipo_item, 'mensaje': 'Ocurrio un error al crear el item. Verifique los datos.'})
return redirect('item:index', id_fase)
... |
petrjasek/superdesk-core | superdesk/io/feed_parsers/ana_mpe_newsml.py | Python | agpl-3.0 | 6,386 | 0.003664 | # -*- 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 datet... | d_el = self.parse_elements(tree.find("NewsItem/NewsComponent/NewsLines"))
# Set the date component of the dateline assuming that the date is in the Athens timezone
local_dt = date_parser(parsed_el.get("DateLine", ""), fuzzy=True, da | yfirst=True)
local_tz = pytz.timezone("Europe/Athens")
aus_dt = local_tz.localize(local_dt, is_dst=None)
item.setdefault("dateline", {})
item["dateline"]["date"] = aus_dt.astimezone(pytz.utc)
item["headline"] = parsed_el.get("HeadLine", "").strip()
item["slugline"] = par... |
djkonro/client-python | kubernetes/client/models/v1_binding.py | Python | apache-2.0 | 6,246 | 0.001441 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... | to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
:return: The kind of this V1Binding.
:rtyp | e: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""
Sets the kind of this V1Binding.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. ... |
linzhonghong/zapi | zapi/core/__init__.py | Python | mit | 26 | 0.038462 | __author__ = 'zh | onghong'
| |
nburn42/tensorflow | tensorflow/contrib/optimizer_v2/adadelta_test.py | Python | apache-2.0 | 6,887 | 0.00363 | # Copyright 2015 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... | se(slot_update[0] in variables.trainable_variables())
slot[1] = adadelta_opt.get_slot(var1, "accum")
self.assertEquals(slot[1].get_shape(), var1.get_shape())
self.assertFalse(slot[1] in variables.trainable_variables())
slot_update[1] = adadelta_opt.get_slot(var1, "accum... | ariables.trainable_variables())
# Fetch params to validate initial values
self.assertAllClose(var0_init, var0.eval())
self.assertAllClose(var1_init, var1.eval())
update = [None] * num_updates
tot_update = 0
for step in range(num_updates):
... |
Teagan42/home-assistant | homeassistant/data_entry_flow.py | Python | apache-2.0 | 9,791 | 0.000919 | """Classes to help gather user submissions."""
import abc
import logging
from typing import Any, Dict, List, Optional, cast
import uuid
import voluptuous as vol
from .core import HomeAssistant, callback
from .exceptions import HomeAssistantError
_LOGGER = logging.getLogger(__name__)
RESULT_TYPE_FORM = "form"
RESULT... | if cur_step["step_id"] != result.get("step_id"):
# Tell frontend to reload the flow state.
self.h | ass.bus.async_fire(
EVENT_DATA_ENTRY_FLOW_PROGRESSED,
{"handler": flow.handler, "flow_id": flow_id, "refresh": True},
)
return result
@callback
def async_abort(self, flow_id: str) -> None:
"""Abort a flow."""
if self._progress.pop... |
enricopesce/ec2_snap | ec2_snap_invoke.py | Python | gpl-3.0 | 1,640 | 0.005488 | import boto3
import logging
import json
simulate = False
retention_days = 15
logger = logging.getLogger()
logger.setLe | vel(logging.INFO)
cli_lambda = boto3.client('lambda')
cli_ec2 = boto3.client('ec2')
#lambda call
def ec2_snap_invoke(event, context):
filters = [{'Name': 'tag:Backup', 'Values': ['NO | REBOOT']}]
reservations = cli_ec2.describe_instances(Filters=filters).get('Reservations', [])
instances = sum([[i for i in r['Instances']]for r in reservations], [])
logging.info("Found %d instances that need backing up in HOT mode" % len(instances))
for instance in instances:
#call lambda fu... |
aabbox/kbengine | kbe/tools/server/webconsole/WebConsole/urls.py | Python | lgpl-3.0 | 4,443 | 0.033311 | """KBEWebConsole URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | ss_cmd, name = "watcher_process_cmd" ),
url(r'^status/show_components',views_status.show_components, name = "status_show_components" ),
url(r'^status/connect',views_status.connect | , name = "status_connect" ),
url(r'^status/process_cmd$', views_status.process_cmd, name = "status_process_cmd" ),
url(r'^spaceviewer/show',views_spaceviewer.show_components, name = "show_components" ),
url(r'^spaceviewer/process_cmd$', views_spaceviewer.process_cmd, name = "spaceviewer_process_cmd" ),
... |
LeeBergstrand/pygenprop | pygenprop/testing/test_tree.py | Python | apache-2.0 | 12,594 | 0.003335 | #!/usr/bin/env python
"""
Created by: Lee Bergstrand (2018)
Description: A simple unittest for testing the genome_property_tree module.
"""
import json
import unittest
from copy import deepcopy
from pygenprop.database_file_parser import parse_genome_property
from pygenprop.database_file_parser import parse_genome_p... | ('RQ', '0'),
('EV', 'GenProp0066;')
]
property_rows_two = [
('AC', 'GenProp0003'),
('DE', 'Coenzyme F420 utilization'),
| ('TP', 'GUILD'),
('--', ''),
('SN', '1'),
('ID', 'Selfish genetic elements'),
('RQ', '0'),
('EV', 'GenProp0066;')
]
property_rows_three = [
('AC', 'GenProp0066'),
('DE', 'Coenzyme F420 utilization'),
('TP', ... |
nvazquez/Turtlebots | plugins/plugin.py | Python | mit | 1,754 | 0 | #!/usr/bin/env python
# Copyright (c) 2011 Walter Bender
# Copyright (c) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
#
# 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 t... | ou should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
| # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import gobject
class Plugin(gobject.GObject):
def __init__(self):
gobject.GObject.__init__(self)
def setup(self):
""" Setup is called once, when the Turtle Window is created. """
pass
def start(self):
... |
dbbhattacharya/kitsune | vendor/packages/pylint/gui.py | Python | bsd-3-clause | 2,790 | 0.004301 | """Tkinker gui for pylint"""
from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar
from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH
import os
import sys
if sys.platform.startswith('win'):
PYLINT = 'pylint.bat'
else:
PYLINT = 'pylint'
class LintGui:
"""Build and control a wi... | =BOTTOM)
#self.root.bind('<ctrl-q>', self.quit)
self.txtModule.focus | _set()
def mainloop(self):
"""launch the mainloop of the application"""
self.root.mainloop()
def quit(self, _=None):
"""quit the application"""
self.root.quit()
def run_lint(self, _=None):
"""launches pylint"""
colors = {'W:':'red1', 'E:': 'red4',
... |
neilhan/python_cv_learning | 01-image/run_me.py | Python | bsd-3-clause | 1,033 | 0.001936 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Testing read image, wait, show image, save image.
Author: Neil Han
"""
from __future__ import absolute_import, division, \
print_function, unicode_literals
import cv2
cv2.namedWindow('WorkAroundTheCoreDump')
cv2.destroyWindow('WorkAroundTheCoreDump')
import num... | SIZE)
image = cv2.imread("../images/pic1.jpg")
x = 20
y = 550
cv2.putText(image, "Hi, pibbles, snow. ", (x, y),
cv2.FONT_HERSHEY_COMPLEX, fontScale=1, color=255)
cv2.imshow("The window", image)
cv2.waitKey(10 * 1000)
# flip an image
image = cv2.imread('../images/pi | c1.jpg', cv2.CV_LOAD_IMAGE_COLOR)
image = cv2.flip(image, 0)
cv2.imshow('Flipped', image)
cv2.waitKey(0)
# gray image
image = cv2.imread('../images/pic1.jpg', cv2.CV_LOAD_IMAGE_COLOR)
imgGray = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
cv2.imshow('colorhist', imgGray)
cv2.waitKey(0)
#cv.SaveImage("../pic1-cop... |
elricgit/django-social-launch | manage.py | Python | bsd-3-clause | 276 | 0.003623 | #! | /usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_social_launch_test_project.settings")
from django.core.management import execute_from_command_line
execute_from_ | command_line(sys.argv)
|
great-expectations/great_expectations | tests/test_definitions/test_expectations_cfe.py | Python | apache-2.0 | 17,894 | 0.001844 | import glob
import json
import os
import random
import string
import pandas as pd
import pytest
from great_expectations.execution_engine.pandas_batch_data import PandasBatchData
from great_expectations.execution_engine.sparkdf_batch_data import SparkDFBatchData
from great_expectations.execution_engine.sqlalchemy_batc... | [
random.choice(
string.ascii_letters + string.digits
)
for _ in range(8)
]
| )
+ ".db",
)
)
for dataset in d["data"]:
datasets.append(
get_test_validator_with_data(
... |
william-richard/moto | tests/test_dynamodb/test_dynamodb_table_with_range_key.py | Python | apache-2.0 | 13,935 | 0.000861 | from __future__ import unicode_literals
import boto
import sure # noqa
from freezegun import freeze_time
from moto import mock_dynamodb_deprecated
from boto.dynamodb import condition
from boto.dynamodb.exceptions import DynamoDBKeyNotFoundError, DynamoDBValidationError
from boto.exception import DynamoDBR... | ody": "http://url_to_lolcat.gif",
"forum_name": "LOLCat Forum",
"ReceivedTime": "12/9/2011 11:36:03 PM",
"SentBy": "User A",
"subject": "Check this out!",
},
| "ConsumedCapacityUnits": 0.5,
}
)
table.refresh()
table.item_count.should.equal(0)
item.delete.when.called_with().should.throw(DynamoDBResponseError)
@mock_dynamodb_deprecated
def test_delete_item_with_undeclared_table():
conn = boto.connect_dynamodb()
conn.layer1.de... |
DataDog/integrations-extras | riak_repl/datadog_checks/riak_repl/riak_repl.py | Python | bsd-3-clause | 5,738 | 0.00366 | import json
import unicodedata
from requests.exceptions import ConnectionError, Timeout
from six import iteritems
from datadog_checks.base import AgentCheck
from datadog_checks.base.errors import CheckException
class RiakReplCheck(AgentCheck):
REPL_STATS = {
"server_bytes_sent",
"server_bytes_r... | d_clusters', '')
tags = instance.get('tags', [])
if not url:
raise CheckException("Configuration error, please fix conf.yaml")
try:
r = self.http.get(url)
except Timeout:
raise CheckException('URL: {} timed out after {} seconds.'.format(url, self.htt... | ns['timeout']))
except ConnectionError as e:
raise CheckException(e)
if r.status_code != 200:
raise CheckException('Invalid Status Code, {} returned a status of {}.'.format(url, r.status_code))
try:
stats = json.loads(r.text)
except ValueError:
... |
Hammer2900/SunflowerX | application/plugins/default_toolbar/bookmarks_button.py | Python | gpl-3.0 | 703 | 0 | import gtk
class Button(gtk.ToolButton):
"""Toolbar control used to | popup bookmarks menu"""
def __init__(self, application, name, config):
gtk.ToolButton.__init__(self)
# store parameters locally
self._name = name
self._config = config
self._application = application
# configure
self.set_label(_('Bookmarks'))
self.s... | ed', self._clicked)
def _clicked(self, widget, data=None):
"""Handle click"""
self._application.show_bookmarks_menu(widget=self)
|
mgaborit/pyven | source/pyven/steps/step.py | Python | mit | 3,958 | 0.0048 | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from ... | .replace('_', ' ').upper() | + ' : SUCCESSFUL')
Step.log_delimiter()
else:
self.status = pyven.constants.STATUS[1]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : FAILED')
Step.log_delimiter()
return ok
return _intern
@sta... |
cs98jrb/Trinity | mysite/mysite/paypal.py | Python | gpl-2.0 | 3,013 | 0.003319 | import paypalrestsdk
import logging
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from settings import PAYPAL_MODE, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET
def paypal_create(request):
"""
MyApp ... | _id": PAYPAL_CLIENT_ID,
"client_s | ecret": PAYPAL_CLIENT_SECRET })
payment = paypalrestsdk.Payment.find(payment_id)
payment_name = payment.transactions[0].description
if payment.execute({"payer_id": payer_id}):
# the payment has been accepted
return HttpResponse('<p>the payment "'+payment_name+'" has been accepted</p>')
... |
moodpulse/l2 | api/directions/sql_func.py | Python | mit | 16,657 | 0.006248 | from django.db import connection
from laboratory.settings import TIME_ZONE
from utils.db import namedtuplefetchall
def get_history_dir(d_s, d_e, card_id, who_create_dir, services, is_serv, iss_pk, is_parent, for_slave_hosp):
with connection.cursor() as cursor:
cursor.execute(
"""WITH
... | ions_napravleniya.client_id = %(card_id)s
when %(who_create)s > -1 THEN
directions_napravleniya.doc_who_create_id = %(who_create)s
END),
t_tubes AS (SELECT tubesregistration_id, issledovaniya_id as tubes_iss_id
FROM directions_issledova | niya_tubes
WHERE issledovaniya_id IN (SELECT iss_id FROM t_iss)),
t_iss_tubes AS (SELECT * from t_iss
LEFT JOIN t_tubes
ON t_iss.iss_id = t_tubes.tubes_iss_id),
t_recive AS (SELECT time_recive, id as id_t_recive FROM directions_tubesregistration
WHERE di... |
s20121035/rk3288_android5.1_repo | cts/apps/CameraITS/tests/inprog/test_3a_remote.py | Python | gpl-3.0 | 2,817 | 0.00142 | # Copyright 2013 The Android Open Source Project
#
# 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 a... | mitations under the License.
import its.image
i | mport its.device
import its.objects
import os.path
import pprint
import math
import numpy
import matplotlib.pyplot
import mpl_toolkits.mplot3d
def main():
"""Run 3A remotely (from this script).
"""
NAME = os.path.basename(__file__).split(".")[0]
with its.device.ItsSession() as cam:
props = cam... |
kubevirt/client-python | test/test_v1alpha1_persistent_volume_claim.py | Python | apache-2.0 | 1,015 | 0.002956 | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_imp | ort
import os
import sys
import unittest
import kubevirt
from kubevirt.rest import ApiException
from kubevirt.models.v1alpha1_persistent_volume_claim import V1alpha1PersistentVolumeClaim
class TestV1alpha1PersistentVolumeClaim(unittest.TestCase):
""" V1alpha1PersistentVolumeClaim unit test stubs """
def se... | tentVolumeClaim
"""
# FIXME: construct object with mandatory attributes with example values
#model = kubevirt.models.v1alpha1_persistent_volume_claim.V1alpha1PersistentVolumeClaim()
pass
if __name__ == '__main__':
unittest.main()
|
Microsoft/pxt | tests/pyconverter-test/cases/array_generics_map.py | Python | mit | 103 | 0.019417 | def f1():
| x = ["a", "b", "c"]
while True:
b = x.map(mapf)
def mapf(a):
ret | urn True |
BuildingLink/sentry | tests/sentry/api/endpoints/test_project_processingissues.py | Python | bsd-3-clause | 4,405 | 0.000227 | from __future__ import absolute_import
from datetime import datetime
from django.utils import timezone
from django.core.urlresolvers import reverse
from sentry.models import (
ProcessingIssue, EventError, RawEvent, EventProcessingIssue
)
from sentry.testutils import APITestCase
class ProjectProjectProcessingIss... | eResolveableIssues'] is False
assert response.data['numIssues'] == 0
ass | ert response.data['issuesProcessing'] == 0
|
caio2k/RIDE | src/robotide/editor/formatters.py | Python | apache-2.0 | 786 | 0 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obta | in 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 IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific la... |
GaretJax/mddns | fabfile.py | Python | mit | 514 | 0.001946 | from | os.path import join, dirname
from glob import glob
from fabric.api import env
env.package_name = 'mddns'
env.user = ''
env.hosts = [
]
# Assets pipeline configuration (may not be needed if the project does not
# make use of assets and/or static files for web development)
env.assets_dir = join(env.package_name, 'ass... | ')
for f in glob(join(dirname(__file__), 'fabtasks', '*.py')):
execfile(f) |
hajicj/safire | test/test_utils.py | Python | gpl-3.0 | 6,745 | 0.001038 | """
Testing the utility functions.
"""
import gzip
import logging
import math
import os
import unittest
import gensim
from gensim.models import TfidfModel
import operator
from safire.data import VTextCorpus, FrequencyBasedTransformer
from safire.data.filters.positionaltagfilter import PositionalTagTokenFilter
from s... | self.assertEqual(freq_vt_word, tfidf_freq_vt_word)
self.assertEqual(vt_word, tfidf_vt_word)
wordlist = [vt_word, freq_vt_word, tfidf_vt_word, tfidf_freq_vt_word,
freq_tfidf_vt_word]
print wordlist
def test_bottom_corpus(self):
| vtcorp = VTextCorpus(self.vtlist_file, input_root=self.data_root,
token_filter=self.token_filter,
pfilter=0.3, pfilter_full_freqs=True)
freq_transform = FrequencyBasedTransformer(vtcorp, 110, 10)
freq_vtcorp = freq_transform[vtcorp]
tf... |
liyi-david/dblpmining | lib/fptree.py | Python | apache-2.0 | 3,263 | 0.000919 | """ in this file, we describe the data type of fp-tree nodes and present
an algorithm to build a fp-tree from existing datasets """
import fpgrowth
import Queue
def supfilter(dataset, minsup):
"""
supfilter : scan the items and drop the infrequent elements
:param dataset: dataset could be in two available ... |
rec[elem] = 0
rec[elem] += 1
# filter: find the infrequent keywords
if '' in rec:
del rec['']
inf = filter(lambda i: i[1] >= minsup, rec.items())
inf = map(lambda i: i[0], inf)
# remove the infrequent elements from the dataset
dataset = map(
lambda ... | sort by the support of items
dataset = map(
lambda i: sorted(
i,
# we use support of elements as sorting keys
key=lambda ele: rec[ele],
reverse=True
),
dataset
)
return dataset
class Node:
def __init__(self, name=None, parent=Non... |
nexdatas/writer | nxswriter/Types.py | Python | gpl-3.0 | 7,676 | 0 | #!/usr/bin/env python
# This file is part of nexdatas - Tango Server for NeXus data writer
#
# Copyright (C) 2012-2017 DESY, Jan Kotanski <jkotan@mail.desy.de>
#
# nexdatas is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... | ank = 0
if type(array) in [numpy.string_, numpy.str_]:
pythonDType = "str"
elif hasattr(array, "dtype"):
pythonDType = str(array.dtype)
else:
pythonDType = type(array.tolist()).__name__
... | else:
rank = 1
shape.append(len(array))
else:
if type(array) in [numpy.string_, numpy.str_]:
pythonDType = "str"
elif hasattr(array, "dtype"):
pythonDType = str(array.dtype)
elif hasattr(array, "tolist")... |
zacharytamas/django-chelsea | chelsea/testing/__init__.py | Python | isc | 32 | 0.03125 | from | .test_case import CTestC | ase |
laperry1/android_external_chromium_org | tools/telemetry/telemetry/value/histogram.py | Python | bsd-3-clause | 4,090 | 0.007824 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
from telemetry import value as value_module
from telemetry import perf_tests_helper
from telemetry.value import histogram_util
class HistogramVa... | tput_context):
return 'histogram'
return 'unimportant-histogram'
def GetBuildbotValue(self):
# Mor | e buildbot insanity: perf_tests_results_helper requires the histogram
# to be an array of size one.
return [self.ToJSONString()]
def ToJSONString(self):
# This has to hand-JSONify the histogram to ensure the order of keys
# produced is stable across different systems.
#
# This is done because... |
demisto/content | Packs/CortexXDR/Scripts/EntryWidgetPieAlertsXDR/EntryWidgetPieAlertsXDR.py | Python | mit | 1,252 | 0.002396 | import demistomock as demisto
incident = demisto.incidents()
data = {
"Type": 17,
"ContentsFormat": "pie",
"Contents": {
"stats": [
{
"data": [
int(incident[0].get('CustomFields', {}).get('xdrhighseverityalertcount', 0))
],
... | "low",
"label": "incident.severity.low",
"color": "rgb(0, 205, 51)"
},
| ],
"params": {
"layout": "horizontal"
}
}
}
demisto.results(data)
|
pierrelb/RMG-Py | rmgpy/pdep/collisionTest.py | Python | mit | 4,609 | 0.008245 | #!/usr/bin/python
# -*- coding: utf-8 -*-
########################################### | #####################################
#
# RMG - Reaction Mechanism Generator |
#
# Copyright (c) 2002-2009 Prof. William H. Green (whgreen@mit.edu) and the
# RMG Team (rmg_dev@mit.edu)
#
# 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, inc... |
ashwinm76/alienfx | alienfx/core/controller.py | Python | gpl-3.0 | 11,875 | 0.003453 | #
# controller.py
#
# Copyright (C) 2013-2014 Ashwin Menon <ashwin.menon@gmail.com>
# Copyright (C) 2015-2018 Track Master Steve <trackmastersteve@gmail.com>
#
# Alienfx is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
... | elf)
def _get_no_zone_code(self):
""" Return a zone code corresponding to all non-visible zones."""
zone_codes = [self.zone_map[x] for x in self.zone_map]
return ~reduce(lambda x,y: x|y, zone_codes, 0)
def _get_zone_codes(self, zone_names):
""" Given zone names... | zones |= self.zone_map[zone]
return zones
def _get_reset_code(self, reset_name):
""" Given the name of a reset action, return its code. """
for reset in self.reset_types:
if reset_name == self.reset_types[reset]:
return reset
logging.wa... |
henaras/sahara | sahara/service/validations/cluster_templates.py | Python | apache-2.0 | 2,985 | 0 | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | ge_registered(data['default_image_id'])
b.check_required_image_tags(data['plugin_name'],
data['hadoop_version'],
data['default_image_id'])
b.check_all_configurations(data)
if data.get('anti_affinity'):
b.check_node_process... | tron_management_network'):
b.check_network_exists(data['neutron_management_network'])
def check_cluster_template_usage(cluster_template_id, **kwargs):
users = []
for cluster in api.get_clusters():
if cluster_template_id == cluster.cluster_template_id:
users.append(cluster.name)
... |
chrismeyersfsu/ansible-modules-core | cloud/google/gc_storage.py | Python | gpl-3.0 | 16,863 | 0.008421 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | ry_list if x.scope.type == 'AllAuthenticatedUsers']
if not grant:
obj.set_acl('authenticated-read')
module.exit_json(changed=True, result="The objects permission as been set to authenticated-read")
except gs.provider.storage_response_error as e:
module.fail_json(... | n True
def key_check(module, gs, bucket, obj):
try:
bucket = gs.lookup(bucket)
key_check = bucket.get_key(obj)
except gs.provider.storage_response_error as e:
module.fail_json(msg= str(e))
if key_check:
grant_check(module, gs, key_check)
return True
els... |
ic-hep/DIRAC | tests/DISET_HTTPS_migration/TestClientReturnedValuesAndCredentialsExtraction.py | Python | gpl-3.0 | 3,802 | 0.004997 | """
In this test we want to check if Tornado generate the same credentials dictionnary as DIRAC.
It also test if the correct certificates are sended by client.
To run this test you must have the handlers who returns credentials dictionnary.
Handlers are diracCredDictHandler and tornadoCredDictHandler j... | turns credentials
assert repDirac["Value"] == repTornado["Value"]
@parametrize("UseServerCertificate", ("True", "False"))
def test_rpcStubs_are_equals(UseServerCertificate):
"""
Test if Clients returns the same rpcStubs
Navigating through array is a bit complicated in this test...
repDirac and re... | rgs: dict{
*** kwargs used to instanciate client ***
}
methodName: str
arguments: list
}
Value: dict { # NOT USED IN THIS TEST
*** Credentials dictionnary extracted by server ***
}
}
"""
gConfigurationData.setOptionInCFG("/DIRAC/Security/UseServer... |
gmonce/bioscope | thesis/src/scripts/update_discontinuous_hc.py | Python | mit | 6,790 | 0.013261 | # -*- coding: utf-8 -*-
# Actualiza el valor de los hedge cue discontinuos como either..or
# están marcados ambos como B-SPECCUE, pero si aparecen en el mismo scope
# tengo que cambiar al segundo para que diga D-SPECCUE
# lo hago directamente en las tablas
# Uso: python update_discontinuous_hc.py working_dir
import ... | ['token_ | num']]
c1.execute('update bioscope_train set hedge_cue2=\'D-SPECCUE\', hedge_cue=\'D-SPECCUE\' where document_id=? and sentence_id=? and token_num=?',[row['document_id'],row['sentence_id'],row['token_num']])
c.execute('select * from bioscope_train b1 where hedge_cue3=\'B-SPECCUE\' and exists (select * from bioscop... |
RubenSchmidt/giscademy | courses/migrations/0013_auto_20161216_1359.py | Python | mit | 845 | 0.002367 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 | .3 on 2016-12-16 12:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('courses', '0012_userlesson'),
]
operations = [
migrations.AddField(
model_name='... | SCADE, related_name='next', to='courses.Exercise'),
),
migrations.AddField(
model_name='exercise',
name='prev_exercise',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='prev', to='courses.Exercise'),
... |
MyRookie/SentimentAnalyse | venv/lib/python2.7/site-packages/nltk/test/unit/test_json2csv_corpus.py | Python | mit | 8,153 | 0.004048 | # -*- coding: utf-8 -*-
# Natural Language Toolkit: Twitter client
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Lorenzo Rubio <lrnzcig@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
Regression tests for `json2csv()` and `json2csv_entities()` in Twitter
package.
"... | ,
gzip_compress=False)
self.assertTrue(are_files_identical(outfn, ref_fn), msg=self.msg)
def test_retweet_original_tweet(self): |
ref_fn = os.path.join(self.subdir, 'tweets.20150430-223406.retweet.csv.ref')
with TemporaryDirectory() as tempdir:
outfn = os.path.join(tempdir, 'tweets.20150430-223406.retweet.csv')
json2csv_entities(self.infile, outfn, ['id'], 'retweeted_status',
... |
keflavich/image_registration | image_registration/iterative_zoom.py | Python | mit | 8,555 | 0.008884 | from .fft_tools import zoom
import numpy as np
import matplotlib.pyplot as pl
def iterative_zoom(image, mindiff=1., zoomshape=[10,10],
return_zoomed=False, zoomstep=2, verbose=False,
minmax=np.min, ploteach=False, return_cen | ter=True):
"""
Iteratively zoom in on the *minimum* position in an image until the
delta-peak value is below `mindiff`
Parameters
----------
| image : np.ndarray
Two-dimensional image with a *minimum* to zoom in on (or maximum, if
specified using `minmax`)
mindiff : float
Minimum difference that must be present in image before zooming is done
zoomshape : [int,int]
Shape of the "mini" image to create. Smaller is faster,... |
JamisHoo/Distributed-Image-Search-Engine | src/storage_node/storage_node.py | Python | mit | 2,071 | 0.029454 | #!/usr/bin/env python3
###############################################################################
# Copyright (c) 2015 Jamis Hoo
# Distributed under the MIT license
# (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#
# Project: Distributed Image Search Engine
# Filename:... | agenet/"
local_fs_paths = [ "/mnt", "/mnt2" ]
local_addr = "59.66.130.16"
tcp_port = 10010
http_ports = [ 10011, 10012, 10013, 10014, 10015, 10016, 10017, 10018, 10019, 10020,
#10021, 10022, 10023, 10024, 10025, 10026, 10027, 10028, 10029, 10030,
#10031, 10032, 10033, 10034, 10035, 100 | 36, 10037, 10038, 10039, 10040,
#10041, 10042, 10043, 10044, 10045, 10046, 10047, 10048, 10049, 10050,
]
master_addr = "192.168.1.103"
master_port = 3000
if __name__ == "__main__":
#ImageServer.init(hdfs_host, hdfs_image_path, None)
ImageServer.init(None, None, local_fs_paths)
... |
DesertBot/DesertBot | desertbot/modules/utils/StringUtils.py | Python | mit | 3,807 | 0.003415 | import json
import re
from collections import OrderedDict
from typing import List
from pyxdameraulevenshtein import normalized_damerau_levenshtein_distance as ndld
from twisted.plugin import IPlugin
from zope.interface import implementer
from desertbot.message import IRCMessage
from desertbot.moduleinterface import I... | "
if message.command and message.command.lower() in self.bot.moduleHandler.mappedTriggers:
# ignore bot commands
return
if 'tracking' in message.metadata:
# ignore internal messages from alias processing
if any(m in message.metadata['tracki | ng'] for m in ['Sub', 'Chain', 'Alias']):
return
self.messages[message.replyTo] = message
def _prevmsg(self, message: IRCMessage):
"""returns the previous message from the current channel"""
if message.replyTo not in self.messages:
return IRCResponse("No previou... |
fujunswufe/YelpDataChallenge | src/summarize/baseline.py | Python | apache-2.0 | 1,052 | 0.003802 | __author__ = 'fujun'
from nltk import sent_tokenize
import json
import io
if __name__ == "__main__":
review_file = io.open("/Users/fujun/GitHub/YelpDataChallenge/data/tip_review.json", 'r', encoding='utf8')
index = 1
for line in review_file:
json_decode = json.loads(line.strip("\n"))
re... | # print "type:" + str(type(review))
tip = json_decode.get("tip")
sentences = sent_tokenize(review)
# print str(sentences[0])
first = sentences[0]
system = "system/task" + str(index) + "_englishSyssum" + str(index) + ".txt"
reference = "reference/task" + str(index) + "_e... | system_output = io.open(system, "w", encoding='utf8')
reference_output = io.open(reference, "w", encoding='utf8')
system_output.write(unicode(first))
reference_output.write(unicode(tip))
system_output.close()
reference_output.close()
index += 1
review_file.clos... |
jjdredd/ljd | ljd/ast/validator.py | Python | mit | 8,322 | 0.02944 | #
# Copyright (C) 2013 Andrian Nord. See Copyright Notice in main.py
#
import ljd.ast.nodes as nodes
import ljd.ast.traverse as traverse
class TypeRestriction():
def __init__(self, default, specific):
if isinstance(default, dict) and specific == {}:
specific = default
default = None
self.default = defaul... | StatementsList
})
# ##
def visit_block(self, node):
self._set_restrictions(STATEMENT_TYPES, {
node.warp: WARP_TYPES
})
assert node.index >= 0
assert node.first_address >= 0 \
and node.first_address <= node.last_address
# if false produce a statements without warps in
# assert node.warpins_c... | == nodes.UnconditionalWarp.T_FLOW
def visit_conditional_warp(self, node):
self._set_restrictions({
node.condition: EXPRESSION_TYPES
})
assert node.true_target is not None
assert node.false_target is not None
# It might happen in case of if blabla or true stuff
# or in case of a = a and foo(a) or a ty... |
teichopsia-/take_brake | movies.py | Python | mpl-2.0 | 147 | 0.020408 | # title
# storyline
de | f show_trailer(t | itle, youtube_url):
# Open browser and play trailer
def show_info():
# Print movie information
|
iamjstates/django-formsfive | formsfive/attributes.py | Python | bsd-3-clause | 596 | 0.008389 | #!/usr/bin/env python
EMPTY_VALUES = (None, '', 'NoneType', False)
UNIVERSAL = ('auto | complete', 'required')
TEXT_SEARCH = (
'dirname', 'list', 'maxlength',
'pattern', 'placeholder', 'readonly',
'size', 'spellcheck')
EMAIL = ('multiple')
SELECT = ('multiple', 'name', 'size')
PASSWORD = ('maxlength', 'pattern', 'list', 'placeholder', 'readonly')
TIME_NUMERIC = ('min', 'ma | x', 'readonly', 'step', 'list')
RANGE = ('min', 'max', 'list', 'step')
CHOICE = ('value', 'choices', 'check_test')
WIDGETS = ('is_required', 'autofocus', 'disabled', 'placeholder', 'pattern', 'spellcheck') |
txdev/nuage_shim | nuage_shim/model.py | Python | bsd-3-clause | 3,042 | 0.000657 | # Copyright (c) 2016 Nokia, 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... | 'returns simple dict representation of the mapping'''
return str(self.__dict__)
def __repr__(self):
'''echoes class, id, & reproducible representation in the REPL'''
return '{}, | {}'.format(super(ObjBase, self).__repr__(), self.__dict__)
def update_attrs(self, new_attributes):
changes = ChangeData()
for key in new_attributes:
if key in self.__dict__:
if new_attributes[key] != self.__dict__[key]:
changes.prev[key] = self.__dic... |
cornell-zhang/datuner | cfg/custom.py | Python | bsd-3-clause | 464 | 0.012931 | space = [
['EnumParameter', 'x', range(100)],
['EnumParameter', 'y', range( | 100)],
['EnumParameter', 'z', range(100)]
]
dbfilename = # NAME_OF_RESULTS_DATABASE (e.g. 'results')
dbtablename = # NAME_OF_SWEEP_TABLE_IN_DATABASE (e.g. ' | shift')
designdir = # PATH_TO_CUSTOM_FOLDER (e.g. '$DATUNER_HOME/flows/sample-3d')
workspace = # PATH_TO_WORKSPACE_FOLDER
machines = # [ MACHINE_ADDR1, MACHINE_ADDR2, ... ]
server_address = # ( SERVER_ADDR, PORT_NUMBER )
|
dstenb/game-cover-fetcher | fetcher.py | Python | gpl-2.0 | 3,623 | 0.001104 | from os.path import splitext, join, isfile
from urllib.parse import urljoin
from urllib.parse import urlparse
import urllib.request
from lxml import html
BASE_URL = "https://en.wikipedia.org"
url = BASE_URL + "/wiki/Category:Nintendo_GameCube_game_covers"
def wiki_category_url(category):
return "https://en.wiki... | ame and url:
print("Found %s" % name)
return (name, url)
def get_filename(self, name, url):
o = urlparse(url)
_, ext = splitext(o.path.split("/")[-1])
filename = "%s%s" % (name, ext)
filename = filename.replace(" (video game)", "")
filename = filename.r... | ls = {}
for image_page in image_pages:
try:
name, url = self.parse_image_page(image_page)
if name and url:
yield (name, url)
except urllib.error.HTTPError as e:
print(e)
def download_covers(self, output, overwrite... |
MjAbuz/django-social-auth | social_auth/backends/contrib/behance.py | Python | bsd-3-clause | 2,328 | 0.000859 | """
Behance OAuth2 support.
This contribution adds support for the Behance OAuth service. The settings
BEHANCE_CLIENT_ID and BEHANCE_CLIENT_SECRET must be defined with the values
given by Behance application registration process.
Extended permissions are supported by defining BEHANCE_EXTENDED_PERMISSIONS
setting, it ... | hanceBackend(OAuthBackend):
"""Behance OAuth authentication backend"""
name = | 'behance'
# Default extra data to store (in addition to access_token)
EXTRA_DATA = [
('username', 'username'),
]
def get_user_id(self, details, response):
return response['user']['id']
def get_user_details(self, response):
"""Return user details from Behance account"""
... |
martinohanlon/microbit-micropython | examples/mcfly/serial/serialwin32.py | Python | mit | 18,300 | 0.002623 | #! python
# Python Serial Port Extension for Win32, Linux, BSD, Jython
# serial driver for win32
# see __init__.py
#
# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Initial patch to use ctypes by Giovanni Bajo <rasky@develer.com>
import ctypes
import time
from serial i... | ._rs485_mode.delay_before_tx is not None:
raise Valu | eError(
'Unsupported value for RS485Settings.delay_before_tx: %r' % (
self._rs485_mode.delay_before_tx,))
if self._rs485_mode.delay_before_rx is not None:
raise ValueError(
|
UMUNC/UMUNC | umunc_iris/models.py | Python | gpl-2.0 | 5,707 | 0.05491 | #coding=utf-8
from django.db import models
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import simplejson
from umunc.settings import COMMITEE_DIR, COMMITEE_DIR2
class group(models.Model):
Name=models.CharField(max_length=255,verbose_name="名称")
School=models.Cha... | lt=False,verbose_name='集体团队/个人团队',choices=(
(True,'集体团队'),
(False,'个人团队'),))
class Meta:
ordering = ['-id']
def __unicode__(self):
return u'%s' % (self.Name)
class system(models.Model):
Name=models.CharField(max_length=255,verbose_name="名称")
class Meta:
ordering = ['id']
def __unicode__(sel | f):
return u'%s' % (self.Name)
class country(models.Model):
Name=models.CharField(max_length=255,verbose_name="名称")
System=models.ForeignKey(system,verbose_name='所属体系',null=True,blank=True)
class Meta:
ordering = ['id']
def __unicode__(self):
return u'%s-%s' % (self.System, self.Name)
class ident... |
revaldinho/opc | opc6/opc6emu.py | Python | gpl-3.0 | 6,597 | 0.038502 | import sys, re
mnemonics="mov,and,or,xor,add,adc,sto,ld,ror,jsr,sub,sbc,inc,lsr,dec,asr,halt,bswp,putpsr,getpsr,rti,not,out,in,push,pop,cmp,cmpc".split(",")
op = dict([(opcode,mnemonics.index(opcode)) for opcode in mnemonics])
dis = dict([(mnemonics.index(opcode),opcode) for opcode in mnemonics])
pred_dict = {0:"",1:"0... | == (op["halt"]):
print("Stopped on halt instruction at %04x with halt number 0x%04x" % (regfile[15]-(instr_len), operand) )
| break
elif opcode == (op["rti"]) and (dest==15):
(regfile[pcreg], flag_save, preserve_flag ) = (pc_int, (0,psr_int[1],psr_int[2],psr_int[3],psr_int[4]), True )
elif opcode in (op["and"], op["or"]):
regfile[dest] = ((regfile[dest] & ea_ed) if opcode==op["... |
osuripple/lets | constants/scoreOverwrite.py | Python | agpl-3.0 | 17 | 0 | P | P = 0
SCORE | = 1
|
c86j224s/memorize | kvstorelocal.py | Python | apache-2.0 | 1,438 | 0.082754 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib, json, os, os.path, shutil
class KVStoreLocal (object):
def __init__ (self, path = u"./"):
self._path = path
def __del__ (self):
pass
def set_binary (self, key, value):
try:
with op | en (self._get_key (key), "wb") as s:
s.write (value)
except:
return False
return True
def set_text (self, key, value):
try:
with open (self._get_key (key), "w") as s:
s.write (value)
except:
return False
return True
def set_json (self, key, value):
try:
with open (self._get_key (key... | t:
# return False
return True
def get_binary (self, key):
v = None
try:
with open (self._get_key (key), "rb") as s:
v = s.read ()
except:
pass
return v
def get_json (self, key):
v = None
try:
with open (self._get_key (key), "r") as s:
v = json.loads (s.read ())
except:
pass
... |
Wooden-Robot/pop | mtime.py | Python | mit | 865 | 0.003699 | import requests
import re
import json
url = 'http://service.library.mtime.com/Movie.api'
data = {'Ajax_CallBack': 'true',
'Ajax_CallBackType': 'Mtime.Library.Services',
'Ajax_CallBackMethod': 'GetMovieOverviewRating',
'Ajax_CrossDomain': '1',
'Ajax_CallBackArgument0': '156682'}
# 网页... | url, data=data).text
return res
# 解析器
def parser(contents):
# 将所要的信息筛选出来
content = ''.join(re.findall(r'{.*}', contents))
# 将dat | a从Json形式转换为字典
datas = json.loads(content)
star = datas['value']['movieRating']['RatingFinal']
name = datas['value']['movieTitle']
print(star, name)
def main():
contents = html_downloader(url)
print(contents)
parser(contents)
if __name__ == '__main__':
main() |
wilsonkichoi/zipline | zipline/utils/tradingcalendar_bmf.py | Python | apache-2.0 | 7,576 | 0.000528 | #
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | Y,
byeaster=-46,
cache=True,
dtstart=start,
until=end
)
def get_early_closes(start, end):
# TSX closed at 1:00 PM on december 24th.
start = canonicalize_datetime(start)
end = canonicalize_datetime(end)
early_close_rules = []
early_close_rules.append(quarta_cinzas)
early_clo... | .sort()
return pd.DatetimeIndex(early_closes)
early_closes = get_early_closes(start, end)
def get_open_and_close(day, early_closes):
# only "early close" event in Bovespa actually is a late start
# as the market only opens at 1pm
open_hour = 13 if day in quarta_cinzas else 10
market_open = pd.Tim... |
openprocurement/openprocurement.tender.competitivedialogue | openprocurement/tender/competitivedialogue/tests/stage1/lot_blanks.py | Python | apache-2.0 | 44,808 | 0.005048 | #-* | - coding: utf-8 -*-
from copy import deepcopy
# CompetitiveDialogueEU(UA)LotBidderResourceTest
def create_tender_bidder_invalid(self):
request_path = '/tenders/{}/bids'.format(self.tender_id)
re | sponse = self.app.post_json(request_path, {'data': {'selfEligible': True, 'selfQualified': True,
'tenderers': self.test_bids_data[0]['tenderers']}},
status=422)
self.assertEqual(response.status, '422 Unprocessable Entity')
... |
dasadc/conmgr | adc2018/server/adcutil.py | Python | bsd-3-clause | 23,866 | 0.009131 | # -*- coding: utf-8 -*-
#
# アルゴリズムデザインコンテストのさまざまな処理
#
# Copyright (C) 2015 Fujitsu
import numberlink
from datastore import *
from hashlib import sha1, sha256
from flask import make_response, render_template
import random
import datetime
from tz import gae_datetime_JST
from define import DEFAULT_YEAR
def adc_response... | results = []
for i in q:
if delete | :
tmp = { 'date': gae_datetime_JST(i.date) }
i.key.delete()
else:
tmp = { 'date': gae_datetime_JST(i.date),
'username': i.username,
'what': i.what }
results.append( tmp )
return results
def adc_login(salt, username, passwo... |
alexa-infra/pil-lite | test/test_basic.py | Python | mit | 3,573 | 0 | import os
from io import BytesIO
from tempfile import TemporaryDirectory
import pytest
from PilLite import Image
BASE_DIR = os.path.dirname(__file__)
SIZE = (256, 184)
@pytest.fixture(scope='function')
def tmpdir():
with TemporaryDirectory() as folder:
yield folder
@pytest.fixture(params=[
'.png', ... | mg = Image.open(outfile)
assert img.size == SIZE
def test_bytes_io(png_file):
with open(png_file, 'rb') as fd:
data = BytesIO(fd.read())
img = Image.open(data)
assert img.size == SIZE
@pytest.fixture(params=[(128, 90), (512, 36 | 0)])
def resize(request):
yield request.param
def test_resize(png_file, resize):
img = Image.open(png_file)
img2 = img.resize(resize)
assert img2 is not img
assert img2.size == resize
assert img.size == SIZE
def test_thumbnail(png_file):
img = Image.open(png_file)
img.thumbnail((128,... |
justinslee/Wai-Not-Makahiki | makahiki/apps/widgets/quests/tests/__init__.py | Python | mit | 19 | 0 | """test | s module | """
|
pombredanne/netlib | test/http/http2/test_frames.py | Python | mit | 21,418 | 0.000233 | from io import BytesIO
from nose.tools import assert_equal
from netlib import tcp, tutils
from netlib.http.http2.frame import *
def hex_to_file(data):
data = data.decode('hex')
return tcp.Reader(BytesIO(data))
def test_invalid_flags():
tutils.raises(
ValueError,
DataFrame,
flags... | ame_human_readable():
f = HeadersFrame(
length=7,
flags=(HeadersFrame.FLAG_PADDED | HeadersFrame.FLAG_PRIORITY),
stream_id=0x1234567,
header_block_fragment=b'',
pad_length= | 3,
exclusive=False,
stream_dependency=0x7654321,
weight=42)
assert f.human_readable()
f = HeadersFrame(
length=14,
flags=(HeadersFrame.FLAG_PADDED | HeadersFrame.FLAG_PRIORITY),
stream_id=0x1234567,
header_block_fragment='668594e75e31d9'.decode('hex'),
... |
tscohen/chainer | cupy/reduction.py | Python | mit | 19,169 | 0 | import collections
import string
import numpy
import six
import cupy
from cupy import carray
from cupy import elementwise
from cupy import util
six_range = six.moves.range
six_zip = six.moves.zip
_broadcast = elementwise._broadcast
_check_args = elementwise._check_args
_decide_params_type = elementwise._decide_par... | .size( | );
_j += _out_ind.size(), _J++) {
_in_ind.set(_j);
${input_expr}
_type_reduce _a = ${pre_map_expr};
_s = REDUCE(_s, _a);
}
_out_ind.set(_i);
${output_expr}
POST_MAP(_s);
}
} else {
extern __share... |
joy12398/Sub_Net | subNet.py | Python | apache-2.0 | 1,430 | 0.024476 |
in_file = open("PPI_Network_Kept.txt")
in_file2 = open("MFO_LABELS.txt")
out_file = open("PPI_Nodes.json", "w")
#step 1: find uniq nodes
unq = []
for line in in_file:
clen = line.strip().split("\t")
if clen[0] not in unq:
unq.append(clen[0])
if clen[1] not in unq:
unq.append(clen[1])
ii=0
dic = {}
for item... | close()
in_file = open("PPI_Network_Kept.txt")
claus = []
for line in in_file:
claus.append(line.strip().split("\t"))
in_file.close()
in_file = open("PPI_Network_Kept.txt")
claus2 = []
for line in in_file:
claus2.append(line.strip().split("\t"))
clster = {}
kk=0
for item in claus:
item_curr = item[0]
for item2 in... | tem in unq:
if item in goterm:
out_file.write('{\n"children": null,\n"cluster": '+str(clster[item])+',\n"id": '+str(dic[item])+',\n"count": '+'"'+str(goterm[item])+'"'+',\n"size": 125.0,\n"text": "'+str(item)+'"\n},'+"\n")
jj+=1
|
skyylex/Luminous-proof-of-concept | core/source_transformer.py | Python | mit | 9,513 | 0.003259 | import command_line
import ast
import os
import traceback
from operator import attrgetter
import settings
from execution_tree_builder import build_execution_tree
# TODO move classes to separate files
class DataCollectorCall(object):
def __init__(self, var_name="", indentation=0, line_position=0, need_stacktrace... | n_call = FunctionCall()
items = []
for arg in node.args:
# ast.Name
if isinstance(arg, ast.Name):
items.append(arg.id)
function_call.func_name = node.func.id
function_call.arguments = items
function_call.line_position = node.lineno
function_call.indentation = node.c... | onDeclaration()
function_args = []
for arg in node.args.args:
# ast.Name
function_args.append(arg.id)
declaration.name = node.name
declaration.args = function_args
declaration.start_position = node.lineno
for element in node.body:
if element.lineno > declaration.end_pos... |
sio2project/oioioi | oioioi/problems/migrations/0019_algorithmtagproposal_difficultyproposal.py | Python | gpl-3.0 | 1,893 | 0.003698 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-06-24 23:35
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('difficulty', models.CharField(max_length=10)),
('problem', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, | to='problems.Problem')),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'difficulty proposal',
'verbose_name_plural': 'difficulty proposals',
... |
bprinty/quorra | docs/conf.py | Python | apache-2.0 | 8,593 | 0.004888 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# quorra documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... | your custom
# ones.
extensions = [
'sphinx.ext.pngmath',
'sphinx.ext.autodoc',
'sphinx.ext.napoleon'
]
# Napoleon settings
napoleon_google_docstring = | True
napoleon_numpy_docstring = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use... |
enovance/hardware | hardware/bios_hp.py | Python | apache-2.0 | 1,742 | 0 | # Copyright (C) 2019 Criteo
#
# 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, ... | ._get_candidate_names())
status, output = cmd("hp-conrep --save -f {}".format(output_file))
if status != 0:
sys.stderr.write("Unab | le to run hp-conrep: %s\n" % output)
return False, ""
return_value = open(output_file).read()
os.remove(output_file)
return True, return_value
def dump_hp_bios(hwlst):
# handle output injection for testing purpose
valid, hpconfig = get_hp_conrep(hwlst)
if not valid:
return Fals... |
emenendez/gpxutils | setup.py | Python | agpl-3.0 | 1,587 | 0.00189 | from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
setup(
name='gpxutils',
version='3.0.0',
description='Tools for working with GPX files... | indows, with the help of the USB Drive Letter Manager (http://www.uwe-sieber.de/usbdlm_e.html), gpxpull can automatically download and clean GPX files from a USB-connected Garmin GPS.
""",
url='https://github.com/emenendez/gpxutils',
author='Eric M | enendez',
author_email='ericmenendez@gmail.com',
license='AGPLv3+',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Other Audience',
'Topic :: Utilities',
'License :: OSI Approved ::... |
osuripple/pep.py | pubSubHandlers/updateSilenceHandler.py | Python | agpl-3.0 | 397 | 0.030227 | from common.redis import generalPubSubHandler
from objects import glob
class handler(generalPubSubHandler.generalPubSubHandler):
def __init__(se | lf):
super().__init__()
self.type = "int"
def handle(self, userID):
userID = super().parseData(userID)
if userID is None:
return
| targetToken = glob.tokens.getTokenFromUserID(userID)
if targetToken is not None:
targetToken.silence() |
shanot/imp | modules/integrative_docking/test/test_cross_links.py | Python | gpl-3.0 | 2,964 | 0.002362 | from __future__ import print_function
import IMP.test
import sys
import os
import re
class CrossLinksApplicationTest(IMP.test.ApplicationTestCase):
def test_simple_interface(self):
"""Simple test of interface cross links generation application"""
print(self.get_input_file_name('static.pdb'))
... | of_lines, 4)
os.unlink('cross_links.dat')
os.unlink('cxms2.dat')
os.unlink('cxms_all.dat')
def test_simple_single_structure_score(self):
"""Simple test of interface cross links single structure score application"""
destination = open('complex.pdb', 'w')
file1 = open(... | write(file1.read())
destination.write(file2.read())
destination.close()
p = self.run_application('cross_links_single_score',
['complex.pdb',
self.get_input_file_name('cxms.dat')])
out, err = p.communicate()
sys.s... |
mtmiller/hy | hy/lex/parser.py | Python | mit | 8,249 | 0 | # Copyright (c) 2013 Nicolas Dandrimont <nicolas.dandrimont@crans.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use,... | if p.startswith("*") and p.endswith("*") and p not in ("*", "**"):
p = p[1:-1].upper()
if "-" in p and p != "-":
p = p.replace("-", "_")
if p.endswith("?") and p != "?":
p = "is_%s" % (p[:-1]) |
return p
obj = ".".join([mangle(part) for part in obj.split(".")])
return HySymbol(obj)
@pg.error
def error_handler(token):
tokentype = token.gettokentype()
if tokentype == '$end':
raise PrematureEndOfInput("Premature end of input")
else:
raise LexException(
... |
yohanko88/gem5-DC | util/style/repo.py | Python | bsd-3-clause | 9,560 | 0.003033 | #!/usr/bin/env python
#
# Copyright (c) 2016 ARM Limited
# All rights reserved
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementatio... |
"""Get the absolute path to a file relative within the repository. The
input file name must be a valid path within the repository.
"""
return os.path.join(self.repo_base(), fname)
def in_repo(self, fname):
"""Check if a path points to something within the repository base. ... |
the file system.
"""
fname = os.path.abspath(fname)
repo_path = os.path.abspath(self.repo_base())
return os.path.commonprefix([repo_path, fname]) == repo_path
def repo_path(self, fname):
"""Get the path of a file relative to the repository base. The input
... |
catapult-project/catapult | tracing/tracing/metrics/discover_unittest.py | Python | bsd-3-clause | 685 | 0.005839 | # Copyright (c) 2016 The Chromium Authors. | All rights reserved.
# Use of this source code is governed by a BSD-style license that c | an be
# found in the LICENSE file.
import unittest
from tracing.metrics import discover
class MetricsDiscoverUnittest(unittest.TestCase):
def testMetricsDiscoverEmpty(self):
self.assertFalse(discover.DiscoverMetrics([]))
def testMetricsDiscoverNonEmpty(self):
self.assertEqual(['sampleMetric'], discover.... |
hazelnusse/sympy-old | sympy/thirdparty/pyglet/pyglet/gl/glext_nv.py | Python | bsd-3-clause | 581,882 | 0.007385 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2007 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... | 2790 # GL/glext.h:138
GL_CONVOLUTION_FORMAT = 32791 # GL/glext.h:139
GL_CONVOLUTION_WIDTH = 32792 # GL/glext.h:140
GL_CONVOLUTION_HEIGHT = 32793 # GL/glext.h:141
GL_MAX_CONVOLUTION_WIDTH = 32794 # GL/glext.h:142
GL_MAX_CONVOLUTION_HEIGHT = 32795 # GL/glext.h:143
GL_POST_CONVOLUTION_RED_SC | ALE = 32796 # GL/glext.h:144
GL_POST_CONVOLUTION_GREEN_SCALE = 32797 # GL/glext.h:145
GL_POST_CONVOLUTION_BLUE_SCALE = 32798 # GL/glext.h:146
GL_POST_CONVOLUTION_ALPHA_SCALE = 32799 # GL/glext.h:147
GL_POST_CONVOLUTION_RED_BIAS = 32800 # GL/glext.h:148
GL_POST_CONVOLUTION_GREEN_BIAS = 32801 # GL/glext.h:149
GL_PO... |
JianmingXia/StudyTest | KnowledgeQuizTool/MillionHeroes/test/hero.py | Python | mit | 2,588 | 0.021259 | import urllib.request, sys,base64,json,os,time,string,re
from PIL import Image
from aip import AipOcr
from aitext import Ai
start = time.time()
os.system("adb shell /system/bin/screencap -p /sdcard/screenshot.png")
os.system("adb pull /sdcard/screenshot.png ./screenshot.png")
'''
汉王ocr 涨价涨价了。。
host = 'http://text.ali... | 案
keyword = issue | #识别的问题文本
ai=Ai(issue,answer)
ai.search()
'''
convey = 'n'
if convey == 'y' or convey == 'Y':
results = baiduSearch.search(keyword, convey=True)
elif convey == 'n' or convey == 'N' or not convey:
results = baiduSearch.search(keyword)
else:
print('输入错误')
exit(0)
count = 0
for result in results:
... |
ombre42/robotframework-sudslibrary | src/SudsLibrary/factory.py | Python | apache-2.0 | 2,975 | 0.003025 | # Copyright 2012 Kevin Ormbrek
#
# 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... | SDL objects may have attribute names that are illegal in Python,
necessitating this k | eyword.
Example:
| ${sale record}= | Call Soap Method | getLastSale | |
| ${price}= | Get Wsdl Object Attribute | ${sale record} | Price |
"""
self._assert_is_suds_object(object)
return getattr(object, name)
def create_wsdl_object(self, type,... |
lukestarchief/cs3240-labdemo | goodbye.py | Python | mit | 39 | 0.025641 | __autho | r__ = 'las3wh'
print('goodb | ye') |
zhehaowang/ndn-cxx | .waf-tools/sqlite3.py | Python | gpl-3.0 | 1,318 | 0.003035 | #! /usr/bin/env python
# encoding: utf-8
from waflib import Options
from waflib.Configure import conf
def options(opt):
opt.add_option('--with-sqlite3', type='string', default=Non | e,
dest='with_sqlite3', help='''Path to SQLite3, e.g., /usr/local''')
@conf
def check_sqlite3(self, *k, **kw):
root = k and k[0] or kw.get('path', None) or Options.options.with_sqlite3
mandatory = kw.get('mandatory', True)
var = kw.get('uselib_store', 'SQLITE3')
if root: |
self.check_cxx(lib='sqlite3',
msg='Checking for SQLite3 library',
define_name='HAVE_%s' % var,
uselib_store=var,
mandatory=mandatory,
includes="%s/include" % root,
libpath="... |
sarvex/tensorflow | tensorflow/compiler/tests/image_ops_test.py | Python | apache-2.0 | 53,739 | 0.005936 | # 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... | Test(xla_test.XLATestCase):
def _testContrast(self, x_np, y_np, contrast_factor):
with self.session():
x = array_ops.placeholder(x_np.dtype, shape=x_np.shape)
flt_x = image_ops.convert_image_dt | ype(x, dtypes.float32)
with self.test_scope():
y = image_ops.adjust_contrast(flt_x, contrast_factor)
y = image_ops.convert_image_dtype(y, x.dtype, saturate=True)
y_tf = y.eval({x: x_np})
self.assertAllClose(y_tf, y_np, 1e-6)
def testFloatContrast(self):
x_shape = [1, 2, 2, 3]
... |
brodeau/barakuda | python/modules/barakuda_tool.py | Python | gpl-2.0 | 22,856 | 0.025026 |
import sys
import os
import numpy as nmp
# #Lfinite = nmp.isfinite(XF)
# #Lshit = nmp.logical_not(Lfinite)
# #idx_bad = nmp.where(Lshit)
ris2 = 1./nmp.sqrt(2.)
def chck4f(cf, script_name=''):
cmesg = 'ERROR: File '+cf+' does not exist !!!'
if script_name != '': cmesg = 'ERROR in script '+scri... | eturn int(base * round(float(x)/base))
def lon_180_180(x):
rsign = 1.
if 180.-x < 0.: rsign=-1.
return rsign*min(x,abs(x-360.))
def get_sections_from_file(cfile):
list_sections = []
f = open(cfile, 'r') ; cread_lines = f.readlines() ; f.close()
jl=0 ; l_stop=False
while not l_stop: ... | F' and cc[0:13] != 'ref_temp_sali':
print ls
list_sections.append(cc)
jl=jl+1 ; # to skip coordinates line
else:
print ' .... '
jl=jl+1
return list_sections
def iaxe_tick(ny):
# I want 20 ticks on the absciss axe and multiple of... |
drougge/wellpapp-pyclient | wellpapp/shell/fusefs.py | Python | mit | 14,933 | 0.032478 | from __future__ import print_function
import fuse
import stat
import errno
import os
import sys
from wellpapp import Client, Tag, raw_exts
import re
from time import time, sleep
from hashlib import md5
from struct import pack, unpack
from zlib import crc32
from xml.sax.saxutils import escape as xmlescape
from os.path ... | nk(p)
st = os.stat(dest)
self._stat_cache[m] = _stat_t(0, st.st_size, st.st_mtime, dest, 0)
return self._stat_cache[m]
def getattr(self, path):
path = pathfix(path)
spath = path.split("/")[1:]
mode = stat.S_IFDIR | 0o555
nlink = 2
size = 0
m = md5re.match(spath[-1])
metam = metamd5re.match(spath... | h[-3:-1] in _thumbpaths:
if not m or not m.group(2) != ".png": NOTFOUND()
search = self._path2search("/" + " ".join(spath[:-3]))
if not search: NOTFOUND()
if search.order or self._raw2jpeg: # order specified or potentially unwrapped
orgmd5 = self._resolve_thumb(search, spath[-1])
if not orgmd5: NOTF... |
vegeclic/django-regularcom | suppliers/migrations/0003_auto__add_field_supplier_fee_per_weight.py | Python | agpl-3.0 | 13,726 | 0.007358 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Supplier.fee_per_weight'
db.add_column('suppliers_supplier', 'fee_per_weight',
... | [], {'unique': 'True', 'max_length': '100'})
},
'common.currency': {
'Meta': {'object_name': 'Currency'},
'exchange_rate': ('django.db.models.fields.FloatField', [], {'default': '1'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
... | ue', 'max_length': '30'})
},
'common.image': {
'Meta': {'object_name': 'Image'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'related_name': "'+'"}),
'id': ('django.db.models.fields.AutoField', [], {'pri... |
markus-antero/Stock | data/finance/addins/main.py | Python | apache-2.0 | 8,181 | 0.025303 | '''
Created on 12.4.2017
@author: Markus.Walden
'''
from data.finance.LoadDataYahoo import LoadDataFromSQL, StocksStatistics
from data.finance.addins.mlToFinance1 import LinkQuandl
from data.finance.addins.neuralNetTestModified import NeuralNetForward, plotSleepStudy, generateSampleData
import matplotlib.p... | ion OR cov - covariance
'''
_, _, df = LoadDataFromSQL.retrieve_ALLCompanyData()
print (df.head())
if type == 'corr':
df_corr = df.corr()
print (df_corr.head())
else:
print ('not implemented')
return
data = df_corr.values
fig =... | ax.set_xticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1]) + 0.5, minor=False)
column_labels = df_corr.columns
row_labels = df_corr.index
ax.set_xticklabels(column_labels)
ax.set_yticklabels(row_labels)
plt.xticks(rotation=90)... |
Petr-By/qtpyvis | network/resize.py | Python | mit | 6,414 | 0.001247 | '''
.. module:: resize
This module defines the :py:class:`ShapeAdaptor` and
:py:class:`ResizePolicy` classes which can be used to wrap a
:py:class:`datasource.Datasource` object so that the items it yields
contain a resized version of the original image.
.. moduleauthor:: Rasmus Diederichsen
'''
from network import N... | one):
'''
Parameters
----------
resize : ResizePolicy
Policy to use for resizing images
network : network.Network
Network to adapt to
'''
self._resize = resize_policy
s | elf.setNetwork(network)
def setNetwork(self, network: Network):
'''Change the network to adapt to.
Parameters
----------
network : network.Network
'''
if network is not None:
self._resize.setShape(network.get_input_shape(include_batch=False))
def ... |
shareactorIO/pipeline | cli/test.py | Python | apache-2.0 | 15 | 0 | impo | rt pi | o.pio
|
jorsea/odoo-addons | project_issue_solutions/project_issue.py | Python | agpl-3.0 | 445 | 0.008989 | #-*- coding: utf-8 -*-
from openerp.osv import fields, osv
class project_issue(osv.osv):
_inherit = 'project.issue'
_columns = {
'project_issue_sol | ution_id': fields.many2one('project.issue.solution', 'Linked Solution'),
'issue_description': fields.html('Issue Description'),
'solution_description': fields.html('Solution Description'),
}
# vim:expandtab:smartindent:tabstop=4 | :softtabstop=4:shiftwidth=4:
|
WoLpH/EventGhost | eg/WinApi/HID.py | Python | gpl-2.0 | 23,231 | 0.004176 | # -*- coding: utf-8 -*-
#
# This file is part of EventGhost.
# Copyright © 2005-2016 EventGhost Project <http://www.eventghost.net/>
#
# EventGhost 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 versio... | ctypes.windll.hid
#setupapiDLL = ctypes.windll.setupapi
#get preparsed data
preparse | dData = c_ulong()
hidDLL.HidD_GetPreparsedData(
int(handle),
ctypes.byref(preparsedData)
)
#getCaps
hidpCaps = HIDP_CAPS()
hidDLL.HidP_GetCaps(preparsedData, ctypes.byref(hidpCaps))
n = hidpCaps.InputReportByteLength
if n == 0:
... |
PabloCastellano/bormeparser | docs/conf.py | Python | gpl-3.0 | 11,422 | 0.006742 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# bormeparser documentation build configuration file, created by
# sphinx-quickstart on Sat Jun 27 16:25:25 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... | r HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#html_theme = 'alabaster'
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}... | of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = No... |
robwarm/gpaw-symm | gpaw/test/proton.py | Python | gpl-3.0 | 334 | 0 | from ase import Atoms
from gpaw import GPAW
a = 4. | 5
H = Atoms('H', [(a / 2, a / 2, a / 2)],
pbc=0,
cell=(a, a, a))
calc = GPAW(nbands=1, h=0.2, charge=1)
H.set_calculator(calc)
print H.get_potential_energy() + calc.get_reference_energy()
assert abs(H.get_potential_energy( | ) + calc.get_reference_energy()) < 0.014
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.