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 |
|---|---|---|---|---|---|---|---|---|
ewandor/home-assistant | homeassistant/components/sensor/tahoma.py | Python | apache-2.0 | 1,957 | 0 | """
Support for Tahoma sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.tahoma/
"""
import logging
from datetime import timedelta
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import ENTITY_ID_FORMAT... | :LightIOSystemSensor':
return 'lux'
elif self.tahoma_device.type == 'Humidity Sensor':
return '%'
def update(self):
"""Update the state."""
self.controller.get_states([self.tahoma_device])
if self.tahoma_device.type == 'io:LightIOSystemSensor':
se... | 'core:LuminanceState']
|
bleepbloop/Pivy | examples/Mentor/05.3.TriangleStripSet.py | Python | isc | 4,616 | 0.015815 | #!/usr/bin/env python
###
# Copyright (c) 2002-2007 Systems in Motion
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS I... | ow == None: sys.exit(1)
root = makePennant()
myViewer = SoGuiExaminerViewer(myWindow)
myViewer.setSceneGraph(root)
myViewer.setTitle("Triangle Strip Set: Pennant")
myViewer.show()
myViewer.viewAll()
SoGui.show(myW | indow)
SoGui.mainLoop()
if __name__ == "__main__":
main()
|
nkmk/python-snippets | notebook/dict_keys_values_items.py | Python | mit | 1,226 | 0 | d = {'key1': 1, 'key2': 2, 'key3': 3}
for k in d:
print(k)
# key1
# key2
# key3
for k in d.keys():
print(k)
# key1
# key2
# key3
keys = d.keys()
print(keys)
print(type(keys))
# dict_keys(['key1', 'key | 2', 'key3'])
# <class 'dict_keys'>
k_list = list(d.keys())
print(k_list)
print(type(k_list))
# ['key1', 'key2', 'key3']
# <class 'list'>
for v in d.values():
print(v)
# 1
# 2
# 3
value | s = d.values()
print(values)
print(type(values))
# dict_values([1, 2, 3])
# <class 'dict_values'>
v_list = list(d.values())
print(v_list)
print(type(v_list))
# [1, 2, 3]
# <class 'list'>
for k, v in d.items():
print(k, v)
# key1 1
# key2 2
# key3 3
for t in d.items():
print(t)
print(type(t))
print(t[... |
vsajip/django | django/db/models/options.py | Python | bsd-3-clause | 21,628 | 0.00148 | import re
from bisect import bisect
from django.conf import settings
from django.db.models.related import RelatedObject
from django.db.models.fields.related import ManyToManyRel
from django.db.models.fields import AutoField, FieldDoesNotExist
from django.db.models.fields.proxy import OrderWrt
from django.db.models.loa... | contribute_to_class(self, cls, name):
from django.db import connection
from django.db.backends.util import truncate_name
cls._meta = self
self.insta | lled = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS
# First, construct the default values for these options.
self.object_name = cls.__name__
self.module_name = self.object_name.lower()
self.verbose_name = get_verbose_name(self.object_name)
# Next, apply any... |
genodeftest/yumex-dnf | setup.py | Python | gpl-2.0 | 1,372 | 0.001458 | #!/usr/bin/python3
from distutils.core import setup
from distutils.util import convert_path
from distutils.command.build_scripts import build_scripts
from distutils import log
import os
from os.path import join, basename, split
RENAME_SCRIPTS = {'main.py': 'yumex-dnf',
'update.py': 'yumex-dnf-updat... | ENAME_SCRIPTS[fn])
log.info("renaming %s -> %s", outfile, basename(newfile))
os.rename(outfile, newfile)
setup(name="yumex-dnf",
version="4.3.2",
description="Graphical package management tool",
long_description="",
author="Tim Lauridsen",
author_em... | ],
package_dir={'': 'src'},
scripts=['src/main.py', 'src/update.py'],
data_files=[('', ['src/yumex.ui'])],
cmdclass={
'build_scripts': BuildScripts,
})
|
nschloe/maelstrom | examples/problems/my_materials/__init__.py | Python | mit | 57 | 0 | # -*- co | ding: utf-8 -*-
#
from | . import ek90, porcelain
|
mozman/ezdxf | tests/test_04_dxf_high_level_structs/test_414_block_reference_content.py | Python | mit | 16,637 | 0.00024 | # Copyright (c) 2020-2021, Manfred Moitzi
# License: MIT License
from typing import cast, Union, List
import pytest
import ezdxf
import math
from ezdxf.entities import Ellipse, Point, Arc, DXFEntity, Insert
from ezdxf.math import Vec3
@pytest.fixture(scope="module")
def doc():
d = ezdxf.new()
blk = d.blocks... | ngle=0, end_angle=math.degrees(math.pi / 2)
)
else:
blk.add_ellipse(
(0, 0),
major_axis=(1, 0),
ratio=1,
start_param=0,
end_param=math.pi / 2,
)
assert | blk[0].start_point.isclose(Vec3(1, 0, 0))
assert blk[0].end_point.isclose(Vec3(0, 1, 0))
blk.add_point((1, 0))
blk.add_point((0, 1))
block_ref = doc.modelspace().add_blockref(
"block",
insert=(0, 0),
dxfattribs={
"xscale": scale_factors.x,
"yscale": scal... |
ledusledus/elevator | tiff_size.py | Python | apache-2.0 | 729 | 0.009602 | from osgeo import gdal
import unittest
def GetTiffSize(filename):
"""
returns sixtet of (width, height, minx, miny, maxx, maxy)
from stackoverflow, somewhere
"""
ds = gdal.Open(filename)
width = ds.RasterXSize
height = ds.RasterYSize
gt = ds.GetGeoTransform()
minx = gt[0]
miny =... | 0] + width*gt[1] + height*gt[2]
maxy = gt[3]
return (width, height, minx, miny, maxx, maxy)
class TestTiffSize(unittest.TestCase):
def test_back_tiff(self):
self.assertEqual((7390, 3832, 399539.4683832784, 6334007.500456138, 406929.4683832784, 6337839.500456138), GetTiffSize("back.tif") )
if __nam... | __":
unittest.main() |
lepistone/vertical-ngo | __unported__/framework_agreement_sourcing/__openerp__.py | Python | agpl-3.0 | 2,442 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Nicolas Bessi
# 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
# publi... | ###########################################################################
{'name': 'Framework | agreement integration in sourcing',
'version': '0.1',
'author': 'Camptocamp',
'maintainer': 'Camptocamp',
'category': 'NGO',
'complexity': 'normal',
'depends': ['framework_agreement', 'logistic_requisition'],
'description': """
Automatically source logistic order from framework agreement
========================... |
lento/cortex | test/IECore/LayeredDictTest.py | Python | bsd-3-clause | 5,259 | 0.073588 | ##########################################################################
#
# Copyright (c) 2008-2010, Image Engine Design 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:
#
# * Redis... | ECore.IntData( 1 )
}
)
layers = [ dict1, dict2 ]
d = IECore.LayeredDict( layers )
self.failUnless( d.layers is layers )
| self.assertEqual( d["a"], 10 )
layers.insert( 0, { "a" : 100 } )
self.assertEqual( d["a"], 100 )
if __name__ == "__main__":
unittest.main()
|
patklaey/ZermattReservationAPI | main.py | Python | mit | 1,957 | 0.004599 | import atexit
from flask import Flask, jsonify, g, request, make_response
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_jwt_extended import JWTManager, set_access_cookies, jwt_required, unset_jwt_cookies
from apscheduler.schedulers.background import Bac... | r.verify | _password(password):
return False
g.user = user
return True
@app.route('/logout', methods=['POST'])
def logout():
resp = jsonify({'logout': True})
unset_jwt_cookies(resp)
return resp, 200
|
aj-michael/Hailstorm | server/hailmetricsresource.py | Python | mit | 413 | 0.004843 | import json
from twisted.web.resource import Resource
class HailMetricsResource(Resource):
def __init__(self, population, status):
Resource.__init__(self)
self.population = population
self.status = status
def render_GET(self, request):
hails | = [h for h in self.population.hails.values() if h.status == self.status]
return json.dumps([h.fields() for h in hails] | )
|
moses-rolston/err | errbot/templating.py | Python | gpl-3.0 | 1,524 | 0.001312 | import logging
import os
from jinja2 import Environment, FileSystemLoader
from bottle import TEMPLATE_PATH
def make_templates_path(root):
return root + os.sep + 'templates'
system_templates_path = make_templates_path(os.path.dirname(__file__))
template_path = [system_templates_path]
TEMPLATE_PATH.insert(0, syst... | :
logging.debug("Templates directory found for this plugin [%s]" % tm | pl_path)
template_path.append(tmpl_path) # for webhooks
TEMPLATE_PATH.insert(0, tmpl_path) # for webviews
# Ditch and recreate a new templating environment
env = Environment(loader=FileSystemLoader(template_path))
return
logging.debug("No templates directory found for this ... |
asydorchuk/robotics | python/robotics/sensors/sharp_ir_distance_sensor.py | Python | mit | 443 | 0 | class SharpIrDistanceSensor(object):
def __init__(self | , spi_interface, pin_id):
self.spi_interface = spi_interface
self.pin_id = pin_id
def _voltageToMeters(self, voltage):
return 67.84 / (voltage - 3) - 0.04
def readDistance(self):
'''Returns distance in meters.'''
voltage = self.spi_interface.read(self.pin_id)
di... | e
|
sunlightlabs/openstates | scrapers/id/people.py | Python | gpl-3.0 | 4,319 | 0.000463 | import re
import lxml.html
from openstates.scrape import Scraper, Person
BASE_URL = "https://legislature.idaho.gov/%s/membership/"
CHAMBERS = {"upper": "senate", "lower": "house"}
PARTY = {"(R)": "Republican", "(D)": "Democratic"}
phone_patterns = {
"office": re.compile(r"Statehouse"),
"business": re.compile(... | type="email", value=email, note="District Office"
)
if office_phone:
person.add_contact_detail(
type="voice", value=office_phone, note="Capitol Office"
)
person.add_sou | rce(url)
person.add_link(person_url)
yield person
|
jobiols/management-system | mgmtsystem_action/mgmtsystem_action.py | Python | agpl-3.0 | 3,754 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it und... | ublished 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 of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########... |
vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/apps/sqoop/src/sqoop/client/connector.py | Python | gpl-2.0 | 2,640 | 0.010985 | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | 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 language governing permissions and
# limitations ... | name, version, link_config, job_config, config_resources={}, **kwargs):
self.id = id
self.name = name
self.version = version
self.job_config = job_config
self.link_config = link_config
self.config_resources = config_resources
setattr(self, 'class', kwargs['class'])
@staticmethod
def fro... |
pculture/mirocommunity | localtv/migrations/0047_populate_calculated_source_type.py | Python | agpl-3.0 | 18,280 | 0.008096 | # encoding: utf-8
import datetime
import re
from south.db import db
from south.v2 import DataMigration
from django.db import models
import logging
VIDEO_SERVICE_REGEXES = (
('YouTube', r'http://gdata\.youtube\.com/feeds/'),
('YouTube', r'http://(www\.)?youtube\.com/'),
('blip.tv', r'http://(.+\.)?blip\.tv... | tion(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for feed in orm['localtv.Feed'].objects.all():
video_service = None
for service, regexp in V | IDEO_SERVICE_REGEXES:
if re.search(regexp, feed.feed_url, re.I):
video_service = service
break
if video_service is None:
feed.calculated_source_type = 'Feed'
else:
feed.calculated_source_type = 'User: %s' % ... |
ekivemark/BlueButtonFHIR_API | accounts/forms/user.py | Python | apache-2.0 | 813 | 0.00246 | """
developeraccount
FI | LE: user
Created: 7/6/15 10:16 PM
"""
__author__ = 'Mark Scrimshire:@ekivemark'
from django import forms
from accounts.models import User
from accounts.choices import AC | TIVITY_NOTIFY_CHOICES
class User_EditForm(forms.ModelForm):
class Meta:
model = User
fields = ['email',
'first_name',
'last_name',
'mobile',
'carrier',
'mfa',
'notify_activity']
class Veri... |
heticor915/ProgrammingContest | HackerRank/Challenges/VerybigSum.py | Python | lgpl-3.0 | 193 | 0.041451 | #!/bin/python
#hf | jimenez@utp.edu.co
import | sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' ')) #Map the input
suma=0
for i in arr:
suma=suma+i
print(suma)
|
tiangolo/fastapi | tests/test_dependency_security_overrides.py | Python | mit | 1,463 | 0.000684 | from typing import List, Tuple
from fastapi import Depends, FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
app = FastAPI()
def get_user(required_scopes: SecurityScopes):
return "john", required_scopes.scopes
def get_user_override(required_scopes: Securi... | ar"]),
data: List[int] = Depends(get_data),
):
ret | urn {"user": user_data[0], "scopes": user_data[1], "data": data}
client = TestClient(app)
def test_normal():
response = client.get("/user")
assert response.json() == {
"user": "john",
"scopes": ["foo", "bar"],
"data": [1, 2, 3],
}
def test_override_data():
app.dependency_ov... |
DavidCain/mitoc-trips | ws/tests/lottery/test_run.py | Python | gpl-3.0 | 8,051 | 0.001118 | from datetime import date, datetime
from textwrap import dedent
from unittest.mock import patch
from freezegun import freeze_time
from mitoc_const import affiliations
import ws.utils.dates as date_utils
from ws import enums, models, settings
from ws.lottery import run
from ws.tests import TestCase, factories
class ... | # See lottery.rank for more details
@freeze_time("2019-10-22 10:30:00 EST")
def test_run(self):
"""Test a full run of a single trip's lottery, demonstrating deterministic seeding.
See lottery.rank for more detail on how the random seeding works.
"""
trip = factories.TripFactory.... | ttery',
maximum_participants=2,
program=enums.Program.CLIMBING.value,
)
alice = factories.SignUpFactory.create(
participant__pk=1021, # Will factor into seed + ordering
participant__name="Alice Aaronson",
participant__affiliation=affiliations... |
jmesteve/saas3 | openerp/addons_extra/l10n_es_account_asset/account_asset.py | Python | agpl-3.0 | 8,681 | 0.00888 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2012 Servicios Tecnológicos Avanzados (http://www.serviciosbaeza.com)
# Pedro Manuel Baeza <pedro.baeza@serviciosbaeza.com>
#
... | amount *= days / total_days
return amount
else:
return super(account_asset_asset, self)._compute_board_amount(cr, uid, asset, i, residual_amount, amount_to_depr, undone_dotation_number, posted_depreciation_line_ids, total_days, depreciation_date, context=context)
def compute_d... | in self.browse(cr, uid, ids, context=context):
if asset.move_end_period:
# Reescribir la fecha de la depreciación
depreciation_lin_obj = self.pool.get('account.asset.depreciation.line')
new_depreciation_line_ids = depreciation_lin_obj.search(cr, uid, [('asset_... |
williamjturkel/Digital-History-Hacks--2005-08- | clean-copy-trials.py | Python | mit | 2,219 | 0.010816 | # clean-copy-trials.py
# old bailey
#
# given a directory of trial files each marked with XML
# create a parallel directory o | f files with all tagging stripped
import os, sys, re
# given a directory string, return a list of file names
def getFileNames(dirstr):
dircommand = 'dir ' + dirstr + ' /B'
filelist = os.popen(dircommand).readlines()
filelist = [x.rstrip() for x in filelist]
return filelist
# given a | string containing XML, remove all characters
# between matching pairs of angled brackets, inclusive
def stripTags(xml):
inside = 0
text = ''
for char in xml:
if char == '<':
inside = 1
continue
elif (inside == 1 and char == '>'):
inside = 0
... |
zouppen/simulavr | regress/modules/gdb_rsp.py | Python | gpl-2.0 | 7,633 | 0.047557 | #! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of th... | ead_regs()
print rsp.read_reg(12)
rsp.write_reg(12,0xaa)
print rsp.read_reg(12)
| print rsp.read_reg(34) # PC
# Try to read/write memory
addr = 0x0
_len = 10
mem = rsp.read_mem(addr,_len)
print mem
mem[4] = 10
rsp.write_mem(addr,len(mem),mem)
print rsp.read_mem(addr,_len)
# Write zero's (NOP's) to first 60 bytes of flash
arr = array.array('B', [ 0x0 for i in range(60) ])
rsp.write_... |
KeepSafe/aiohttp | aiohttp/payload.py | Python | apache-2.0 | 13,689 | 0.000657 | import asyncio
import enum
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from itertools import chain
from typing import (
IO,
TYPE_CHECKING,
Any,
ByteString,
Dict,
Iterable,
Optional,
TextIO,
Tuple,
Type,
Union,
)
from m... | ) -> None:
if not isinstance(value, (bytes, bytearray, memoryview)):
raise TypeError(f"value argument must be b | yte-ish, not {type(value)!r}")
if "content_type" not in kwargs:
kwargs["content_type"] = "application/octet-stream"
super().__init__(value, *args, **kwargs)
if isinstance(value, memoryview):
self._size = value.nbytes
else:
self._size = len(value)
... |
Thestar3Preservation/ScriptPack | Python Script/python_module/mkdesktoplink.py | Python | gpl-3.0 | 1,695 | 0.053945 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import imp
import os.path
GlobalEnv = imp.load_source('', os.path.expanduser('~/.GlobalEnv.py'))
import re
import ufp
import codecs
def makeDesktopLink(src, dest=u'.'):
"""
.desktop파일로 된 링크를 생성합니다. 폴더를 dest에 지정할 경우 자동으로 해당 경로에 적절한 이름을 가진 링크 파일을 생성시킵니다.
생성된 파일의 경로를 반환합니... | icon = 'gnome-fs-bookmark'
else :
icon = 'emblem-symbolic-link'
#파일명
filename = os.path.basename(src)
#바로가기 경로 설정
if os.path.isdir(dest):
buffer = filename + u'.desktop'
buffer = os.path.join(d | est, buffer)
dest = ufp.generateUniqueName(buffer)
#바로가기 이름
buffer = filename.replace('\\', r'\\')
#buffer = buffer.maketrans('[:cntrl:]', ' ')
buffer = ufp.stripControlChar(buffer)
#buffer = re.sub('[:cntrl:]', ' ', buffer, flags=re.UNICODE)
shortcutTitle = buffer + '의 바로가기'
#file URL
buffer = os.path.ab... |
tdyas/pants | src/python/pants/core_tasks/reporting_server_run.py | Python | apache-2.0 | 2,593 | 0.002314 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
from pants.base.exceptions import TaskError
from pants.reporting.reporting_server import ReportingServerManager
from pants.task.task import QuietTaskMixin, Task
from pants.... | erRun(QuietTaskMixin, | Task):
"""Run the reporting server."""
@classmethod
def register_options(cls, register):
super().register_options(register)
register(
"--port",
type=int,
default=0,
help="Serve on this port. Leave unset to choose a free port "
"aut... |
YuanYuLin/PackMan_IOPC | pyiopc/iopc_genlist.py | Python | mit | 742 | 0.002695 | import imp
import | sys
import os
import subprocess
import pprint
import iopc
import ops_git
def Main(args):
account = iopc.getAccount(args)
cfg = iopc.getCfg(args)
params = iopc.getParams(args)
is_single_package = iopc.isSinglePackage(args)
single_package_name = iopc.getSinglePackageName(args)
packages_dir = os.p... | es:
pkg_name = pkg['name']
pkg_enabled = pkg['enabled']
local_repo_path = os.path.abspath(packages_dir + os.sep + pkg_name)
remote_repo_path = account["URL"] + pkg_name
pkg_name_list.append(pkg_name)
iopc.genPackagesList(packages_dir, pkg_name_list)
|
apache/phoenix | bin/pherf-standalone.py | Python | apache-2.0 | 2,910 | 0.002062 | #!/usr/bin/env python
############################################################################
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The A... | ['cmd.exe', '/c', 'call %s & set' % hbase_env_path]
if not hbase_env_path or not hbase_env_cmd:
sys.stderr.write("hb | ase-env file unknown on platform {}{}".format(os.name, os.linesep))
sys.exit(-1)
hbase_env = {}
if os.path.isfile(hbase_env_path):
p = subprocess.Popen(hbase_env_cmd, stdout = subprocess.PIPE)
for x in p.stdout:
(k, _, v) = tryDecode(x).partition('=')
hbase_env[k.strip()] = v.strip()
if 'J... |
mondalaci/usb-temperature-sensor | host-utils/TemperatureSensor.py | Python | gpl-3.0 | 1,132 | 0.0053 | import serial
import sys
import math
VCC = 5.0 # Supplied voltage in volts
R0 = 10000.0 # Nominal resistance of the thermistor in ohms
T0_C = 25.0 # Temperature for nominal resistance in Celsius (almost always 25)
BETA = 3950.0 # Beta coefficient of the thermistor
R_FIX = 9650.0 # Resis | tance of the fixed resistor of the voltage divider circuit in ohms
def get_adc():
ser = serial.Serial('/dev/temperature-sensor')
ser.write('c')
(adc_symbol, adc_value) = ser.readline().strip().split()
if adc_symbol != 'c':
raise Exception('The received measurement symbol is not "c" !')
ret... | er_of_samples
def get_temperature():
adc = get_smoothed_adc()
KELVIN_DIFF = 273.15
T0_K = T0_C + KELVIN_DIFF
voltage = adc*VCC/1023
resistance = R_FIX*VCC/voltage - R_FIX
temperature_k = 1 / (1/T0_K + 1/BETA * math.log(resistance/R0))
temperature_c = temperature_k - KELVIN_DIFF
return t... |
MutahirKazmi/geomesa | docs/common.py | Python | apache-2.0 | 13,144 | 0.005478 | # -*- coding: utf-8 -*-
#
# GeoMesa documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 7 10:39:14 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
# autogenerated file.
#
# A... | Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set tod | ay to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST defaul... |
krischer/LASIF | conftest.py | Python | gpl-3.0 | 1,387 | 0.005768 | #!/usr/bin/env p | ython
# -*- coding: utf-8 -*-
"""
This file has a two purpose:
1. Force the use of the "Agg" matplotlib backend for the tests. Otherwise lots
of windows pop up.
2. Force OpenBLAS to use single threading. Otherwise it will deadlock in some
cases.
It will be run by pytest, as specified in the pytest.ini file.
"""
#... | is is executed before any test. Otherwise the import order is not
# really clear.
# This is also specified in all __init__.py's
import os
os.environ["OPENBLAS_NUM_THREADS"] = "1"
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
plt.switch_backend("agg")
# Fixtures will be available in the whole... |
Tset-Noitamotua/_learnpython | LearnPythonTheHardWay/ex15_reading_files.py | Python | gpl-2.0 | 1,354 | 0.005189 | # -- coding: utf-8 --
# Das Modul argv aus Packet sys wird importiert
| from sys import argv
# Die Variablen script und filename werden entpackt
# sie müssen dem Script als Argumente mitgegeben werden beim ausführen
# z.B so: python ex15_reading_files.py ex15_sample.txt
script, filename = argv
# Der Inhalt der Datei ex15_sample.txt, der
# dem Script beim Ausführen a | ls Argument mitgegeben wurde,
# wird in die Variable txt geschrieben
txt = open(filename)
# Der Dateiname von ex15_sample.txt wird ausgegeben
print "Here's your file %r:" % filename
# Der Inhalt von txt (und damit der Inhalt von ex15_sample.txt) wird ausgegeben
print txt.read()
# Man könnte denken, dass man es auch so... |
JuliaWinchester/morphotester | tests/test_Morpho.py | Python | gpl-2.0 | 8,605 | 0.007902 | '''
Created on Jan 10, 2016
@author: Julia M. Winchester
'''
import unittest
import Morpho
from PyQt4.QtTest import QTest
from PyQt4.QtCore import Qt, QPoint
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._App = Morpho.MainWidget()
def set_form_to_zero(self):
Ap... | on.setText('')
App.DNEOptionsWindow.dnestepsize.setText('')
App.DNEOptionsWindow.visvgroup.setChecked(0)
App.DNEOptionsWindow.dnerelvischeck.setChecked(1)
| App.DNEOptionsWindow.dneabsmaxval.setText('')
App.DNEOptionsWindow.dneabsminval.setText('')
App.OPCROptionsWindow.visualizeopcrcheck.setChecked(0)
App.OPCROptionsWindow.opcrminpatch.setText('')
def test_defaults(self):
App = Morpho.MainWidget()
... |
tquilian/exeNext | exe/webui/reflectionblock.py | Python | gpl-2.0 | 4,875 | 0.008205 | # ===========================================================================
# eXe
# Copyright 2004-2006, University of Auckland
#
# 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 ... | feedback = self.answerElement.renderView()
#added lernmodule.net
html += '<div class="Reflection" id="Reflection%s"> | ' % (self.id)
html += '<textarea id="ReflectionText%s" class="ReflectionText" name="ReflectionText%s"' % (self.id, self.id)
html += ' rows=5 style="width:99%"></textarea></div>'
html += common.feedbackBlock(self.id,feedback)
return html
from exe.engine.reflectionidevice ... |
abhikeshav/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ipv4_acl_datatypes.py | Python | apache-2.0 | 19,321 | 0.021945 | """ Cisco_IOS_XR_ipv4_acl_datatypes
This module contains a collection of generally useful
derived YANG data types.
Copyright (c) 2013\-2015 by Cisco Systems, Inc.
All rights reserved.
"""
import re
import collections
from enum import Enum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBi... | .. data:: HOST_REDIRECT = 327681
Host redirect
.. data:: NET_TOS_REDIRECT = 327682
Network redirect for TOS
.. data:: HOST_TOS_REDIRECT = 327683
Host redire | ct for TOS
.. data:: REDIRECT = 393215
All redirects
.. data:: ALTERNATE_ADDRESS = 458751
Alternate address
.. data:: ECHO = 589823
Echo (ping)
.. data:: ROUTER_ADVERTISEMENT = 655359
Router discovery advertisements
.. data:: ROUTER_SOLICITATION = 720895
Router dis... |
skuda/client-python | kubernetes/test/test_v1_status_details.py | Python | apache-2.0 | 859 | 0.002328 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codege | n https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.6.1
Generated | by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1_status_details import V1StatusDetails
class TestV1StatusDetails(unittest.... |
getsentry/zeus | zeus/api/resources/revision_jobs.py | Python | apache-2.0 | 894 | 0.001119 | from sqlalchemy.orm import subqueryload_all
from zeus.models import Job, Revision
from zeus.utils.builds import fetch_build_for_revision
from .base_revision import BaseRevisionResource
from ..schemas import JobSchema
job_schema = JobSchema()
jobs_schema = JobSchema(many=True)
class RevisionJobsResource(BaseRevisio... | vision(revision)
if not build:
return self.respond(status=404)
build_ids = [original.id for origina | l in build.original]
query = (
Job.query.options(subqueryload_all("stats"), subqueryload_all("failures"))
.filter(Job.build_id.in_(build_ids))
.order_by(Job.number.asc())
)
return self.respond_with_schema(jobs_schema, query)
|
demharters/git_scripts | binning_two_files_two_columns.py | Python | apache-2.0 | 2,034 | 0.014258 | #! /usr/local/bin/python3
# Usage: binning.py filter_data data_to_extract_from column1 column2 cutoff1 cutoff2
import sys
import os
def main(*argv):
fn = sys.argv[1]
my_data = sys.argv[2]
my_column1 = int(sys.argv[3])-1
my_colum | n2 = int | (sys.argv[4])-1
my_cutoff1 = float(sys.argv[5])
my_cutoff2 = float(sys.argv[6])
# generate filename for output
fout_tmp = my_data
if fout_tmp.endswith('.dat'):
fout_tmp = fout_tmp[:-4]
fout_higher_name = fout_tmp + '_higher2col_' + str(my_cutoff1) + "_" + str(my_cutoff2)+ '.dat... |
veer66/cdec | realtime/rt/decoder.py | Python | apache-2.0 | 2,899 | 0.003794 | import logging
import os
import subprocess
import threading
import util
logger = logging.getLogger('rt. | decoder')
class Decoder:
def close(self, force=False):
if not force:
self.lock.acquire()
self.decoder.stdin.close()
self.decoder.wait()
if not force:
se | lf.lock.release()
def decode(self, sentence, grammar=None):
'''Threadsafe, FIFO'''
self.lock.acquire()
input = '<seg grammar="{g}">{s}</seg>\n'.format(s=sentence, g=grammar) if grammar else '{}\n'.format(sentence)
self.decoder.stdin.write(input)
hyp = self.decoder.stdout.rea... |
seanastephens/communityshare | update_scripts/update_search.py | Python | mpl-2.0 | 3,386 | 0.004135 | import os
import sys
# Put communityshare in sys
this_directory = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.abspath(os.path.join(this_directory, '..')))
from community_share import config, store, Base
from community_share.models.user import User, TypedLabel
from community_share.models.search... | els with Users | instead of with searches.
for user in users:
cp_search = user.community_partner_profile_search
if cp_search:
for label in cp_search.labels:
typed_label = store.session.query(TypedLabel).filter(TypedLabel.name==label.name).first()
user.labels.append(typed_... |
akrherz/pyIEM | src/pyiem/nws/products/vtec.py | Python | mit | 29,451 | 0 | """A NWS TextProduct that contains VTEC information."""
# Standard Library Imports
from datetime import timedelta
fro | m pyiem.nws.product import TextProduct, TextProductException
from pyiem.nws.ugc import ugcs_to_text
from pyiem.reference import TWEET_CHARS
from pyiem.nws.products._vtec_util import (
_associate_vtec_year,
_check_unique_ugc,
_resent_match,
_do_sql_vtec_new,
_do_sql_vtec_cor,
_do_sql_vtec_can,
... | TECProductException(TextProductException):
"""Something we can raise when bad things happen!"""
class VTECProduct(TextProduct):
"""A TextProduct that contains VTEC information."""
def __init__(
self, text, utcnow=None, ugc_provider=None, nwsli_provider=None
):
"""constructor"""
... |
pblottiere/QGIS | tests/src/python/test_qgsvectorfilewriter.py | Python | gpl-2.0 | 61,172 | 0.002468 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsVectorFileWriter.
.. 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 License, or
(at your option) any later version.
"... | QgsPointXY,
QgsCoordinateReferenceSystem,
QgsVectorFileWriter,
QgsFeatureR | equest,
QgsProject,
QgsWkbTypes,
QgsRectangle,
QgsCoordinateTransform,
QgsMultiPolygon,
QgsTriangle,
QgsPoint,
QgsFields,
... |
gas1121/JapanCinemaStatusSpider | scrapyproject/showingspiders/korona.py | Python | mit | 7,922 | 0 | # -*- coding: utf-8 -*-
import re
import json
import scrapy
from scrapyproject.showingspiders.showing_spider import ShowingSpider
from scrapyproject.items import (ShowingLoader, init_show_booking_loader)
from scrapyproject.utils import KoronaUtil
class KoronaSpider(ShowingSpider):
"""
korona spider.
"""
... | self.get_time_from_text(
end_hour, end_minute))
showing_data_proto.add_value('seat_type', | 'NormalSeat')
# query screen number from database
showing_data_proto.add_total_seat_count()
# check whether need to continue crawl booking data or stop now
if not self.crawl_booking_data:
result_list.append(showing_data_proto.load_item())
return
booking... |
pbmanis/acq4 | acq4/modules/Module.py | Python | mit | 1,133 | 0.012357 | # -*- coding: utf-8 -*-
from __future__ import print_function
from acq4.util import Qt
class Module(Qt.QObject):
# User-readable name for this module
moduleDisplayName = None
# Override this class attribute to have this module appear
# under different category sections in the manager window's module ... | ce):
#"""Return True if this module implements the named interface.
#Examples: 'DataSource', 'Canvas'"""
#return False
def window(self):
"""Return the Qt window for this module"""
if hasattr(self, 'win'):
return self.win
return None
def q... | |
Amande-WP5/formalarg | setup.py | Python | mit | 1,036 | 0.01834 | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.di... | _email = "emmanuel.hadoux@gmail.com",
description = ("Library for formal argumentation systems."),
license = "MIT",
keywords = "argumentation library artificial intelligence",
url = "http://packages.python.org/formalarg",
packages=['formalarg', 'tests'],
install_requires=["graphviz"],
long_d... | ",
"License :: OSI Approved :: MIT License",
"Topic :: Scientific/Engineering :: Artificial Intelligence"
],
) |
huntxu/fuel-web | nailgun/nailgun/test/integration/test_cluster_plugin_links_handler.py | Python | apache-2.0 | 4,662 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the L... | ionTest
from nailgun.utils import reverse
from oslo_serialization import jsonutils
class TestHandlers(BaseIntegrationTest):
def setUp(self):
super(TestHandlers, self).setUp()
self.cluster = self.env.create_cluster(api=False)
self.cluster_plugin_link = self.env \
.create_cluste... |
oerp-odoo/service-management | hr_dc_extend/models/hr.py | Python | agpl-3.0 | 1,858 | 0.005385 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Management Solution
#
# Author: Andrius Laukavičius. Copyright: JSC NOD Baltic
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | he 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 of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU... | Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, fields
from openerp import api
class hr_employee(models.Model):
_name = 'hr.employee'
_inher... |
hrashk/sympy | sympy/assumptions/handlers/calculus.py | Python | bsd-3-clause | 8,090 | 0.000247 | """
This module contains query handlers responsible for calculus queries:
infinitesimal, bounded, etc.
"""
from __future__ import print_function, division
from sympy.logic.boolalg import conjuncts
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler
class AskInfinitesimalHandler(... | tions):
"""
Infinitesimal*Bounded -> Infinitesimal
"""
if expr.is_number:
return AskInfinitesimalHandler._number(expr, assumptions)
result = False
for arg in expr.args:
if ask(Q.infinitesimal(arg), assumptions):
result = True
... | eak
else:
return result
Add, Pow = [Mul]*2
@staticmethod
def Number(expr, assumptions):
return expr == 0
NumberSymbol = Number
ImaginaryUnit = staticmethod(CommonHandler.AlwaysFalse)
class AskBoundedHandler(CommonHandler):
"""
Handler for key 'bounded'.
... |
ahmedaljazzar/edx-platform | openedx/core/lib/token_utils.py | Python | agpl-3.0 | 4,328 | 0.002542 | """Utilities for working with ID tokens."""
import json
from time import time
from django.conf import settings
from django.utils.functional import cached_property
from jwkest import jwk
from jwkest.jws import JWS
from student.models import UserProfile, anonymous_id_for_user
class JwtBuilder(object):
"""Utility ... | if handler:
handler(payload)
return self.encode(payload)
@cached_property
def claim_handlers(self):
"""Returns a dictionary mapping scopes to methods that will add claims to the JWT payload."""
return {
'email': self.attach_email_claim,
'profil... | ile_claim
}
def attach_email_claim(self, payload):
"""Add the email claim details to the JWT payload."""
payload['email'] = self.user.email
def attach_profile_claim(self, payload):
"""Add the profile claim details to the JWT payload."""
try:
# Some users (e.... |
inventree/InvenTree | InvenTree/InvenTree/management/commands/rebuild_thumbnails.py | Python | mit | 1,919 | 0.001042 | """
Custom management command to rebuild thumbnail images
- May be required after importing a new dataset, for example
"""
import os
import logging
from PIL import UnidentifiedImageError
from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import OperationalError... | """
Rebuild the thumbnail specified by the "image" field of the provided model
"""
if not model.image:
return
img = model.image
url = img.thumbnail.name
loc = os.path.join(settings.MEDIA_ROOT, url)
if not os.path.exists(loc):
logger.i... | el.image.render_variations(replace=False)
except FileNotFoundError:
logger.warning(f"Warning: Image file '{img}' is missing")
except UnidentifiedImageError:
logger.warning(f"Warning: Image file '{img}' is not a valid image")
def handle(self, *args, **kwargs):... |
hydrosolutions/irrigation-calc | file_watch.py | Python | mit | 2,693 | 0.003342 | #!/usr/bin/python
import sys
import logging
import time
import subprocess
import shlex
import os
import StringIO
import tempfile
from watchdog.observers import Observer
from watchdog.events import FileCreatedEvent, RegexMatchingEventHandler
class CreatedFilesHandler(RegexMatchingEventHandler):
def on_created(sel... | with open(os.path.join(output_dir, 'error.log'), 'w') as flog:
readable_file = os.fdopen(out_buffer, 'r')
readable_file.seek(0)
flog.write(readable_file.read())
readable_file.close()
| finally:
os.remove(out_path)
logging.info('Command executed, continuing the watch.')
def main():
path = sys.argv[1] if len(sys.argv) > 1 else '.'
logging.basicConfig(level=logging.INFO)
event_handler = CreatedFilesHandler(regexes=[r'.*/INPUT/.*\.kml$'], ignore_directories=... |
cmvac/demagorgon.repository | plugin.video.hyperiononraspbian/addon.py | Python | gpl-2.0 | 330 | 0.021212 | import xbmcaddon
import xbmcgui
import os
addo | n = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
# kill hyperiond and rename config files
cmd = "sudo systemctl start hyperion.service 2>/dev/null ; sudo /etc/init.d/hyperion start 2>/dev/null ; sudo /sbin/initctl start hyperion 2>/dev/null"
| os.system(cmd) |
open-synergy/opnsynid-hr | hr_employee_training_experience/models/__init__.py | Python | agpl-3.0 | 197 | 0 | # -*- coding: utf-8 -*-
# Copyri | ght 2018 OpenSynergy Indonesia
# License AGPL-3.0 or later (http:// | www.gnu.org/licenses/agpl).
from . import hr_certification
from . import hr_training_participant
|
ArrenH/Securitas | symantec_package/lib/managementService/__init__.py | Python | gpl-3.0 | 139 | 0.021583 | """ The Symantec | Python class that handles all the Symantec VIP API SOAP calls for ma | nagement services.
.. moduleauthor:: Allen Huynh
""" |
ptisserand/portage | pym/portage/tests/ebuild/test_config.py | Python | gpl-2.0 | 10,679 | 0.032681 | # Copyright 2010-2014 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
from __future__ import unicode_literals
import io
import tempfile
import portage
from portage import os, shutil, _encodings
from portage.const import USER_CONFIG_PATH
from portage.dep import Atom
from portage.p... | esolverPlaygroundTestCase(
["=dev-libs/A-2"],
mergelist= ["dev-libs/A-2"],
success = True),
)
playground = ResolverPlayground(ebuilds=ebuilds,
repo_configs=repo_configs, distfiles=distfiles)
settings = playground.settings
new_repo_config = settings.repositor | ies["new_repo"]
old_repo_config = settings.repositories["old_repo"]
self.assertTrue(len(new_repo_config.masters) > 0, "new_repo has no default master")
self.assertEqual(new_repo_config.masters[0].user_location, playground.settings.repositories["test_repo"].location,
"new_repo default master is not test_repo")
... |
ginstrom/scheduler | manage.py | Python | mit | 1,385 | 0 | """
Performs management commands for the scheduler app
"""
import hashlib
from flask.ext.script import Manager
from sqlalchemy import exc
# Importing routes causes our URL routes to be registered
from src import routes
from src import models
from src import scheduler
scheduler.app.config.from_object(scheduler.Config... | ght',
username='sandy',
password=has | hlib.md5('secret').hexdigest())
coach_2 = models.Coach(
id='efad3330-9c8f-11e5-9654-d895b95699bb',
user_id=user_2.id)
try:
scheduler.db.session.add(user_1)
scheduler.db.session.add(user_2)
scheduler.db.session.add(coach_1)
scheduler.db.session.add(coach_2)
... |
open-mmlab/mmdetection | mmdet/core/bbox/assigners/uniform_assigner.py | Python | apache-2.0 | 5,556 | 0 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from ..builder import BBOX_ASSIGNERS
from ..iou_calculators import build_iou_calculator
from ..transforms import bbox_xyxy_to_cxcywh
from .assign_result import AssignResult
from .base_assigner import BaseAssigner
@BBOX_ASSIGNERS.register_module()
class Uni... | _gt_index = torch.arange(
0, C1.size(1),
device=bbox_pred.device).repeat(self.match_times * 2)
pos_ious = anchor_overlaps[indexes, pos_gt_index]
pos_ignore_idx = pos_ious < self.pos_ignore_thr
pos_gt_index_with_ignore = pos_gt_index + 1
pos_gt_index_with_ignore[p... | _labels is not None:
assigned_labels = assigned_gt_inds.new_full((num_bboxes, ), -1)
pos_inds = torch.nonzero(
assigned_gt_inds > 0, as_tuple=False).squeeze()
if pos_inds.numel() > 0:
assigned_labels[pos_inds] = gt_labels[
assigned_... |
iarwain8a/pydlbot | httpscrap.py | Python | mit | 328 | 0.045732 | from bs4 import Beautifu | lSoup
from urllib | .request import urlopen
class BeautifulScrap:
def __init__(self,url):
self.soup = BeautifulSoup(urlopen(url),"html.parser")
def request_soup(self):
return self.soup
def get_tag(self,tag,atributes,className):
return self.soup.body.find(tag, attrs={atributes:className})
|
ESGF/esgf-drslib | drslib/__init__.py | Python | bsd-3-clause | 256 | 0 | # BSD Licence
# Copyright (c) 2010, Science & Technology Facilitie | s Council (STFC)
# All rights reserved.
#
# See the LICENSE file in the source distribution | of this software for
# the full license text.
"""
Top level drslib documentation.
TODO ...
"""
|
kirchenreich/osm-api-cache | osmcache.py | Python | mit | 69 | 0 | from osmcache.cli import base
if __name__ == '__main__':
| base()
| |
grigouze/gandi.cli | gandi/cli/tests/compat.py | Python | gpl-3.0 | 463 | 0 |
try:
from unittest import mock
except ImportError:
import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
import configparser as C | onfigParser
except ImportError:
import ConfigParser
try:
from StringIO import StringIO
exc | ept ImportError:
from io import StringIO
try:
from cStringIO import StringIO as ReasonableBytesIO
except ImportError:
from io import BytesIO as ReasonableBytesIO
|
GoogleCloudPlatform/asl-ml-immersion | notebooks/tfx_pipelines/guided_projects/guided_project_2_solution/models/estimator/constants.py | Python | apache-2.0 | 795 | 0 | # Lint as: python2, python3
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Lic | ensed 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 Lic... | OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Constants of the taxi model.
These values can be tweaked to affect model training performance.
"""
HIDDEN_UNITS = [16, 8]
TRAIN_BATCH_SIZE = 40
EVAL_BATCH_S... |
olduvaihand/ProjectEuler | src/python/problem404.py | Python | mit | 944 | 0.002132 | # -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem404.py
#
# Crisscross Ellipses
# ===================
# Published on Sunday, 2nd December 2012, 01:00 am
#
# Ea is an ellipse with an equation of the for | m x2 + 4y2 = 4a2. Ea' is the
# rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0)
# for 0° θ 90°. b is the distance to the origin | of the two intersection
# points closest to the origin and c is the distance of the two other
# intersection points. We call an ordered triplet (a, b, c) a canonical
# ellipsoidal triplet if a, b and c are positive integers. For example, (209,
# 247, 286) is a canonical ellipsoidal triplet. Let C(N) be the number... |
GoelDeepak/dcos | gen/tests/test_validate.py | Python | apache-2.0 | 1,923 | 0.00312 | import logging
import pytest
import gen
import pkgpanda.util
from gen.build_deploy.bash import onprem_source
# TODO(cmaloney): Should be able to pass an exact tree to gen so that we can test
# one little piece at a time rather than having to rework this every time that
# DC/OS parameters change.
@pytest.mark.skipif... | rs',
'errors': {
'bootstrap_url': {'message': ' | Should be a url (http://example.com/bar or file:///path/to/local/cache)'},
},
'unset': set()
}
|
watchdogpolska/poradnia | poradnia/users/views.py | Python | mit | 4,703 | 0.001063 | from atom.views import ActionMessageMixin, ActionView
from braces.views import LoginRequiredMixin, StaffuserRequiredMixin, UserFormKwargsMixin
from dal import autocomplete
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.urls import reverse
from django.utils.translation import ugettext_lazy as... | IS_STAFF_FILTER) < num:
return 0
return num
def get_queryset(self, *args, **kwargs):
qs = super().get_queryset(*args, **kwargs)
qs = qs.filter(**self.IS_STAFF_FILTER[self.get_is_staff_choice()][1])
qs = qs.with_case_count()
if self.request.user.has_perm("cases.ca... | ssigned()
return qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["is_staff"] = dict(
choices=enumerate(self.IS_STAFF_FILTER), selected=self.get_is_staff_choice()
)
return context
class UserAutocomplete(
Permissi... |
dart-lang/sdk | tools/dom/scripts/generator.py | Python | bsd-3-clause | 84,809 | 0.000932 | #!/usr/bin/env python3
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""This module provides shared functionality for systems to generate
Dart APIs from ... | "
import copy
import json
import monitored
import os
import re
from functools import cmp_to_key
from itertools import zip_longest
from htmlrenamer import custom_html_constructors, html_interface_renames, \
typed_array_renames
_pure_interfaces = monitored.Set('generator._pure_interfaces', [
'AbstractWorker',
... | ntXPathEvaluator',
'ElementAnimation',
'ElementFullscreen',
'EventListener',
'GlobalEventHandlers',
'ImageBitmapFactories',
'MediaQueryListListener',
'MouseEventHitRegion',
'MutationCallback',
'NavigatorCPU',
'NavigatorEvents',
'NavigatorID',
'NavigatorLanguage',
'Nav... |
KelSolaar/sIBL_GUI | sibl_gui/components/addons/database_operations/database_operations.py | Python | gpl-3.0 | 19,077 | 0.00456 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
**database_operations.py**
**Platform:**
Windows, Linux, Mac Os X.
**Description:**
Defines the :class:`DatabaseOperations` Component Interface class and others helper objects.
**Others:**
"""
from __future__ import unicode_literals
import os
from PyQt4.Q... | erences_manager.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingE | rror)
def preferences_manager(self):
"""
Deleter for **self.__preferences_manager** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "preferences_manager"))
@property
def ibl_... |
RetailMeNotSandbox/dart | src/python/dart/schema/engine.py | Python | mit | 3,658 | 0.002734 | from dart.schema.base import base_schema, tag_list_schema
from dart.schema.dataset import dataset_schema
from dart.schema.event import event_schema
from dart.schema.subscription import subscription_schema
from dart.schema.workflow import workflow_schema
def engine_schema():
return base_schema({
'type': 'o... | ion_schemas, datastore_schema):
return base_schema({
'type': 'object',
'properties': {
'name': {'type': 'string'},
'description': {'type': 'string'},
'engine_name': {'type': 'string'},
'related_type': {'type': 'strin | g', 'maxLength': 50},
'related_is_a': {'type': 'string', 'maxLength': 50},
'actions': {
'x-schema-form': {'type': 'tabarray', 'title': "{{ value.name }}"},
'type': 'array',
'items': {'anyOf': action_schemas},
'default': []
... |
pbougue/navitia | source/jormungandr/jormungandr/planner.py | Python | agpl-3.0 | 4,389 | 0.001595 | # LICENCE: 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... | epth
return self.instance.send_and_re | ceive(req)
|
dantebarba/docker-media-server | plex/Sub-Zero.bundle/Contents/Libraries/Shared/babelfish/data/get_files.py | Python | gpl-3.0 | 1,554 | 0.001931 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 the BabelFish authors. All rights reserved.
# Use of this source code is governed by the 3-clause BSD license
# that can be found in the LICENSE file.
#
from __future__ import unicode_literals
import os.path
import tempfile
import zipfile
import reque... | country codes)...')
with open(os.path.join(DATA_DIR, 'iso-3166-1.txt'), 'w') as f:
r = requests.get('http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements_txt.htm')
f.write(r.content.strip())
# iso-639-3.tab
print('Downloading ISO-639-3 standard (ISO language codes)...')
with temp... | ile.TemporaryFile() as f:
r = requests.get('http://www-01.sil.org/iso639-3/iso-639-3_Code_Tables_20130531.zip')
f.write(r.content)
with zipfile.ZipFile(f) as z:
z.extract('iso-639-3.tab', DATA_DIR)
# iso-15924
print('Downloading ISO-15924 standard (ISO script codes)...')
with tempfile.TemporaryFile... |
sameerparekh/pants | tests/python/pants_test/backend/core/tasks/test_filter.py | Python | apache-2.0 | 9,825 | 0.003359 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from textwrap import... | uild_file('common/c', 'c')
add_to_build_file('overlaps', 'one', 'common/a', 'common/b')
add_to_build_file('overlaps', 'two', 'common/a', 'common/c')
add_to_build_file('overlaps', 'three', 'common/a', 'overlaps:one')
def test_roots(self):
self.assert_console_output(
'common/a:a',
'common/a... | ommon/c:foo',
targets=self.targets('common/::'),
extra_targets=self.targets('overlaps/::')
)
def test_nodups(self):
targets = [self.target('common/b')] * 2
self.assertEqual(2, len(targets))
self.assert_console_output(
'common/b:b',
targets=targets
)
def test_no_filters(... |
austinhartzheim/madhacks-live | live/urls.py | Python | mit | 140 | 0.007143 | from django | .conf.urls import patterns, url
urlpatterns = patterns('live.views',
url('^fetch/$', 'fetch'),
url('^$', 'main_liv | e')
)
|
bfirsh/syndication-view | syndication/tests/models.py | Python | bsd-3-clause | 486 | 0.010288 | from django. | db import models
class Entry(models.Model):
title = models.CharField(max_length=200)
date = models.DateTimeField()
class Meta:
ordering = ('date',)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/blog/%s/" % self.pk
class Ar | ticle(models.Model):
title = models.CharField(max_length=200)
entry = models.ForeignKey(Entry)
def __unicode__(self):
return self.title
|
scheib/chromium | tools/json_schema_compiler/namespace_resolver.py | Python | bsd-3-clause | 2,904 | 0.009986 | # Copyright 2016 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 os
from cpp_namespace_environment import CppNamespaceEnvironment
from model import Model, UnixName
from schema_loader import SchemaLoader
def _Gene... | attern):
self._root = root
self._include_rules = [(path, cpp_namespace_pattern)] + include_rules
def ResolveNamespace(self, full_namespace):
'''Returns the model.Namespace object associated with the |full_namespace|,
or None if o | ne can't be found.
'''
filenames = _GenerateFilenames(full_namespace)
for path, cpp_namespace in self._include_rules:
cpp_namespace_environment = None
if cpp_namespace:
cpp_namespace_environment = CppNamespaceEnvironment(cpp_namespace)
for filename in reversed(filenames):
f... |
cgpotts/annualreview-complearning | learning.py | Python | gpl-2.0 | 6,866 | 0.004515 | #!/usr/bin/env python
"""
Defines the core learning framework.
The framework defined by `score`, `predict`, and `SGD` is defined in
section 3.2 of the paper. See `evenodd.py` for a simple example
(corresponding to table 3).
This core framework is also all that is needed for simple semantic
parsing: section 4.1 of th... | =None,
test=None,
classes=None,
T=10,
eta=0.1,
output_transform=(lambda x : x)):
"""Generic interface for showing learning weights and train/test
results. optimizer should be `SGD` or `LatentSGD`, `classes` should be
a function of the inputs `x`, and `output_tr... | ed only by
models with latent variables. For examples of use, see `evenodd.py`
and `synthesis.py`."""
print("======================================================================")
print("Feature function: {}".format(phi.__name__))
w = optimizer(
D=train,
phi=phi,
T=T,... |
tommyip/zulip | zerver/webhooks/bitbucket3/view.py | Python | apache-2.0 | 16,451 | 0.004012 | from inspect import signature
from functools import partial
import string
from typing import Any, Dict, Optional, List, Callable
from django.http import HttpRequest, HttpResponse
from zerver.models import UserProfile
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_reques... | :
if include_title:
subject = include_title
else:
subject = "Bitbucket Server Ping"
body = "Congratulations! The Bitbucket Server webhook was configured successfully!"
return [{"subject": subject, "body": body}]
def repo_comment_handler(payload: Dict[str, Any], action: str) -> List[Dict... | ["repository"]["name"]
subject = BITBUCKET_TOPIC_TEMPLATE.format(repository_name=repo_name)
sha = payload["commit"]
commit_url = payload["repository"]["links"]["self"][0]["href"][:-6] # remove the "browse" at the end
commit_url += "commits/%s" % (sha,)
message = payload["comment"]["text"]
if ac... |
cneill/designate | designate/api/v2/controllers/pools.py | Python | apache-2.0 | 4,133 | 0 | # Copyright (c) 2014 Rackspace Hosting
# 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 req... | n')
@utils.validate_uuid('pool_id')
def patch_one(self, pool_id):
"""Update the specific pool"""
request | = pecan.request
context = request.environ['context']
body = request.body_dict
response = pecan.response
if request.content_type == 'application/json-patch+json':
raise NotImplemented('json-patch not implemented')
# Fetch the existing pool
pool = self.central... |
ScaDS/ORC-Schlange | Tutorial/02 DATE, ORCID and WorkSummary Class(Filter 1)/__main__.py | Python | apache-2.0 | 1,679 | 0.047052 | from sqlite3 import connect
class DB:
def __init__(self,path="people.db"):
self.conn = connect(path)
self.c = self.conn.cursor()
def getList(self):
self.c.execute('SELECT * FROM people')
return self.c.fetchall()
def close(self):
self.conn.close()
class Date:
def __init__(self, y, m, d):
self.y = i... | range(4)])
__str__ = lambda self: self.getID() + ": " + str(self.start) + " - " + str(self.stop)
if __name__ == "__main__":
db = DB()
orcs = [OrcID(*t) for t in db.getList()]
db.close()
for orc in | orcs:
print("Do something with",orc)
class WorkSummary:
def __init__(self, path, title, date):
self.path = path
self.title = title
self.date = date
__lt__ = lambda self, other: self.date.y < other.date.y or (self.date.y == other.date.y and self.title < other.title)
__eq__ = lambda self, other: self.date.y ... |
jreback/pandas | pandas/tests/series/methods/test_rank.py | Python | bsd-3-clause | 20,287 | 0.000789 | from itertools import chain, product
import numpy as np
import pytest
from pandas._libs import iNaT
from pandas._libs.algos import Infinity, NegInfinity
import pandas.util._test_decorators as td
from pandas import NaT, Series, Timestamp, date_range
import pandas._testing as tm
from pandas.api.types import Categorica... | exp_keep)
# Test invalid values for na_option
msg = "na_option must be one of 'keep', 'top', or 'bo | ttom'"
with pytest.raises(ValueError, match=msg):
na_ser.rank(na_option="bad", ascending=False)
# invalid type
with pytest.raises(ValueError, match=msg):
na_ser.rank(na_option=True, ascending=False)
# Test with pct=True
na_ser = Series(["first", "second... |
myarjunar/QGIS | python/plugins/processing/algs/qgis/FixGeometry.py | Python | gpl-2.0 | 4,149 | 0.001446 | # -*- coding: utf-8 -*-
"""
***************************************************************************
FixGeometry.py
-----------------------
Date : January 2017
Copyright : (C) 2017 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***********... | 2017'
__copyright__ = '(C) 2017, Alexander Bruy'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$ | '
from qgis.core import QgsWkbTypes, QgsGeometry
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.parameters import ParameterVector
from processing.core.outputs import OutputVector
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from processing.core.... |
chrfrantz/op-papers | oosd/week07/light/pythonlight.py | Python | gpl-3.0 | 737 | 0.002714 | import sys
from PyQt4 im | port QtCore, QtGui, uic
import light
qtCreatorFile = "pythonlight.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class LightApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setu... | lightDisplay.setText(self.light.show())
self.lightSwitch.released.connect(self.toggle)
def toggle(self):
self.light.switch()
self.lightDisplay.setText(self.light.show())
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = LightApp()
window.show()
sys.exi... |
BhallaLab/moose-examples | .ci/execute_travis_serial.py | Python | gpl-2.0 | 6,171 | 0 | #!/usr/bin/env python3
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2017-, Dilawar Singh"
__maintainer__ = "Dilawar Singh"
__email__ = "dilawars@ncbs.res.in"
__status__ = "Development"
import sys
import os
import subprocess
import multiprocessing
import threading
import re
import glob
import datetime
impor... | r = r.decode('utf8')
except Exception as e:
pass
f.write(str(r))
f.write('```\n')
print("[INFO ] Wrote files with status %s to %s.txt " % (k, k))
for k in result_:
print(k)
for f, r in result_[k]:
... | ('```\n%s\n```\n' % r)
quit(1)
def find_scripts_to_run(d):
print("[INFO ] Searching for files in %s" % d)
files = []
for d, sd, fs in os.walk(d):
d = renormalize_path(d)
if d == sdir_:
continue
for f in fs:
fname = renormalize_path(os.path.join(d, f)... |
swaroopgj/Yaafe | src_python/yaafelib/__init__.py | Python | gpl-3.0 | 3,159 | 0.000634 | # -*- coding: utf-8 -*-
#
# Yaafe
#
# Copyright (c) 2009-2010 Institut Télécom - Télécom Paristech
# Télécom ParisTech / dept. TSI
#
# Author : Benoit Mathieu
#
# This file is part of Yaafe.
#
# Yaafe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License a... | the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Main Yaafe module, providing classes to extract features with Yaafe.
. | . testsetup:: *
from yaafelib import *
"""
import os
import sys
from yaafelib.core import (loadComponentLibrary,
isComponentAvailable,
getComponentList,
getComponentParameters,
getOutputFormatList,
... |
thydeyx/LeetCode-Python | Palindrome_Pairs.py | Python | mit | 1,255 | 0.040637 | # -*- coding:utf-8 -*-
#
# Author : TangHanYi
# E-mail : thydeyx@163.com
# Create Date : 2017-01-27 10:43:36 AM
# Last modified : 2017-01-27 01:28:06 PM
# File Name : Palindrome_Pairs.py
# Desc :
class Trie:
def __init__(self, x):
self.val = x
self.child = [None for i in range(26)]
c... | rds[i][j:]
if self.isPalindrome(str1) == True:
str3 = str2[::-1]
if dict_words.has_key(str3) == True and dict_words[str3] != i:
ret.append([dict_words[str3],i])
if self.isPalindrome(str2) == True:
str3 = str1[::-1]
if dict_words.has_key(str3) == True and dict_words[str3] | != i and len(str2) != 0:
ret.append([i, dict_words[str3]])
return ret
if __name__ == "__main__":
s = Solution()
words = ["a",""]
print s.palindromePairs(words)
|
superdesk/superdesk-core | tests/rules/weekdays_test.py | Python | agpl-3.0 | 797 | 0.001255 | import unittest
from datetime import datetime, timedelta
from apps.rules.routing_rules import Weekdays
class WeekdaysTestCase(unittest.TestCase):
def test_is_valid_schedule(self):
self.assertTrue(Weekdays.is_valid_schedu | le(["MON", "TUE"]))
self.assertFalse(Weekdays.is_valid_schedule(["MON", "SRC"]))
def test_is_scheduled(self):
now = datetime.now()
day = now.strftime("%A")[:3]
self.assertFalse(Weekdays.is_scheduled_day(now, []))
self.assertTrue(Weekdays.is_scheduled_day(now, [day]))
... | ].upper()
self.assertEqual(day, Weekdays.dayname(now))
|
lfalvarez/votai | agenda/migrations/0001_initial.py | Python | gpl-3.0 | 1,964 | 0.003063 | # Generated by Django 2.2.7 on 2020-05-07 23:45
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations =... | lank=True, null=True)),
('location', models.TextField(blank=True)),
('description', models.CharField(blank=True, max_length=1024)),
('long_description', models.TextField(blank=True)),
('contact_info', models. | TextField(help_text='Aquí puedes escribir un número telefónico, un email o un whatsapp.', verbose_name='Cómo te pueden contactar las personas interesadas?')),
('important', models.BooleanField(default=False, verbose_name='Es este evento importante?')),
('background_image', models.ImageFi... |
danielwpz/soybean | src/main.py | Python | mit | 3,856 | 0.001556 | import time
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import GradientBoostingRegressor
import matplotlib.pyplot as plt
from prepare.prepare_lin import PrepareDataLin
from p... | 0.003]
layer_values = [(5, 5), (10, 10), (15, 15), (20, 20)]
# layer_values = [(15, 15, 15)]
# loss_curve(mlp, 'hidden_layer_sizes', layer_values, 'MLP')
n_est_number = [100, 150, 200, 300]
l_rate_values = [0.01, 0.03, 0.1]
# loss_curve(gbrt, 'n_estimators', n_est_number, 'Boosting')
loss_curve(gbrt, 'learning_rate',... | del):
model.fit(train_x, train_y)
test_pred = model.predict(test_x)
test_mse = mean_squared_error(test_y, test_pred)
return test_mse
# score = mlp_optimizer.step('alpha', alpha_values).step('hidden_layer_sizes', layer_values).solve(get_score)
# print 'BEST score: ', score
# print 'BEST: ', mlp_optim... |
ares/robottelo | robottelo/cli/capsule.py | Python | gpl-3.0 | 3,537 | 0 | # -*- encoding: utf-8 -*-
"""
Usage::
hammer capsule [OPTIONS] SUBCOMMAND [ARG] ...
Parameters::
SUBCOMMAND subcommand
[ARG] ... subcommand arguments
Subcommands::
| content Manage the capsule content
create Create a capsule
| delete Delete a capsule
import-classes Import puppet classes from puppet Capsule.
info Show a capsule
list List all capsules
refresh-features Refresh capsule features
update Up... |
duke605/RunePy | commands/viswax.py | Python | mit | 2,553 | 0.007442 | from discord.ext import commands
from datetime import datetime
from bs4 import BeautifulSoup
import discord
import re
class VisWax:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, aliases=['wax'],
description='Shows the combination of runes needed f... | Getting html
async with self.bot.whttp.get('http://services.runescape.com/m=forum/forums.ws?75,76,387,65763383') as r:
text = await r.text()
soup = BeautifulSoup(text, 'html.parser')
post = soup.find_all('span', attrs={'class': 'forum-post__body'})[1].text.lower()
day = re.... | - (.+?) slot 2:- (.+?) slot', post).groups()
# Checking if runes updated yet
if int(day) != datetime.utcnow().day:
return None
# Cleaning up the data
slot1 = [VisWax.clean_format(r.strip().capitalize()) for r in slot1.split('-')]
slot2 = [VisWax.clean_format(r.strip... |
PierreBdR/point_tracker | point_tracker/transferfunctiondlg.py | Python | gpl-2.0 | 15,255 | 0.001704 | from __future__ import print_function, division, absolute_import
__author__ = "Pierre Barbier de Reuille <pierre@barbierdereuille.net>"
__docformat__ = "restructuredtext"
from PyQt4 import QtCore, QtGui
from .ui_transferfunctiondlg import Ui_TransferFunctionDlg
from .transferfunction import TransferFunction
from pickle... | ist[fctname].copy()
self.transfer_fct = fct
if | fct.interpolation == "rgb":
self.ui.useRGB.setChecked(True)
elif fct.interpolation == "hsv":
self.ui.useHSV.setChecked(True)
else:
self.ui.useCyclicHSV.setChecked(True)
self.transferFctChanged.emit(self.transfer_fct)
def deleteFunc... |
a-slide/py_NGS_tools | FastqReader.py | Python | gpl-2.0 | 3,073 | 0.01562 | # -*- coding: utf-8 -*-
"""
@package Sekator
@brief Contain an iterator function to read fastq files and return FastqSeq objects
@copyright [GNU General Public License v2](http://www.gnu.org/licenses/gpl-2.0.html)
@author Adrien Leger - 2014
* <adrien.leger@gmail.com>
* <adrien.leger@inserm.fr>
* <adrien... |
self.n_seq = 0
self.fastq_file = fastq_file
def __str__(self):
return ("Fastq File: {}\nNumber of Sequence read: {}".format(self.fastq_file, self.n_seq))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# FUNCTIO... | S
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
def __call__(self):
""" Simple fastq reader returning a generator over a fastq file """
try:
# Open the file depending of the compression status
fastq = gopen(self.fastq_... |
ThomasMoritz/exportlightroomfaces | getfaces.py | Python | mit | 5,178 | 0.001545 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
import os.path
from PIL import Image
import piexif
import argparse
# Commandline Handling
parser = argparse.ArgumentParser(description='Export faces from Lightroom DB')
parser.add_argument('-d', '--database', help='Input Database', required=True)
parser.add_ar... | x_size
else:
| top_x = row['tl_x'] * x_size
top_y = row['tl_y'] * y_size
bottom_x = row['br_x'] * x_size
bottom_y = row['br_y'] * y_size
# Extend the Clipping
while True:
d_top_x = int(top_x - clipping_factor)
d_top_y = int(top_y - clipping_factor)
d_bottom_x = int(bottom_x +... |
commtrack/temp-aquatest | utilities/data_migration/data_export_script_new.py | Python | bsd-3-clause | 4,187 | 0.009792 | None
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
# simple json is a python 2.5 library you need to install
import json
# json comes bundled with python 2.6. use one or the other
#import json
def run():
print "starting"
from receiver.models import Submission
from xformmanager.... | headers = {
"original-submit-time" : str(schema.submit_time),
"original-submit-ip" : str(schema.subm | it_ip),
"bytes-received" : schema.bytes_received,
"form-name" : schema.form_name,
"form-display-name" : schema.form_display_name,
"target-namespace" : schema.target_namespace,
"date-created" : str(schema.date_created),
"doma... |
Nadeflore/dakara-player-vlc | tests/test_dakara_manager.py | Python | mit | 4,895 | 0.000817 | from unittest import TestCase
from unittest.mock import MagicMock
from dakara_player_vlc.dakara_manager import DakaraManager
class DakaraManagerTestCase(TestCase):
"""Test the dakara manager class
"""
def setUp(self):
# create a mock font loader
self.font_loader = MagicMock()
# ... | ttp.update_finished.assert_called_with(42)
self.vlc_player.play_idle_screen.assert_called_with()
def test_do_command_error(self):
"""Test the command | manager for an invalid command
"""
# call the method
with self.assertRaises(AssertionError):
self.dakara_manager.do_command("invalid")
|
partofthething/home-assistant | homeassistant/components/mqtt/switch.py | Python | apache-2.0 | 6,858 | 0.001021 | """Support for MQTT switches."""
import functools
import voluptuous as vol
from homeassistant.components import switch
from homeassistant.components.switch import SwitchEntity
from homeassistant.const import (
CONF_DEVICE,
CONF_ICON,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_O... | TT_RW_PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_DEVICE): MQTT_ENTITY_DEVICE_INFO_SCHEMA,
vol.Optional(CONF_ICON): cv.icon,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean,
... | vol.Optional(CONF_PAYLOAD_ON, default=DEFAULT_PAYLOAD_ON): cv.string,
vol.Optional(CONF_STATE_OFF): cv.string,
vol.Optional(CONF_STATE_ON): cv.string,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
.extend(MQTT_AVAILABILITY_SCHEMA.schema)
.extend(MQTT_JSON_ATT... |
2coding/Codec | thirdparty/gtest-1.6.0/test/gtest_catch_exceptions_test.py | Python | bsd-3-clause | 9,532 | 0.002518 | #!/usr/bin/env python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, th... | RE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEM | PLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN A... |
obulpathi/datascience | neural-networks/src/mnist_loader.py | Python | apache-2.0 | 3,485 | 0.001148 | """
mnist_loader
~~~~~~~~~~~~
A library to load the MNIST image data. For details of the data
structures that are returned, see the doc strings for ``load_data``
and ``load_data_wrapper``. In practice, ``load_data_wrapper`` is the
function usually called by our neural network code.
"""
#### Libraries
# S... | code."""
tr_d, va_d, te_d = load_data()
training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]
training_results | = [vectorized_result(y) for y in tr_d[1]]
training_data = zip(training_inputs, training_results)
validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]
validation_data = zip(validation_inputs, va_d[1])
test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]
test_data = zip(test_inputs,... |
jpypi/dup-image-search | md5/calculate_md5_hashes.py | Python | mit | 1,021 | 0.027424 | #!/usr/bin/env python2
"""
Note: This does not sort the output.
For sorting simply run:
$ sort md5sums.txt > md5sums_sorted.txt
"""
import sys
import glob
import csv
import hashlib
from multiprocessing import Pool
def md5_file(filename):
with open(filename) as f:
return (hashlib.md5(f.rea... | ename)
directories = ["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","the","u","v","w","x","y"]
try:
base_directory = sys.argv[1]
pool = Pool(8)
with open("md5sums.txt","w") as f:
writer = csv.writer(f)
for d in directories:
pr... | es for the {} directory.".format(d)
image_files = glob.iglob("{}/{}/*".format(base_directory,d))
for hash_and_name in pool.imap(md5_file, image_files):
writer.writerow(hash_and_name)
except IndexError:
print "{0}: Syntax: {0} <album covers base directory>".format(sys.argv[0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.