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 |
|---|---|---|---|---|---|---|---|---|
sofianehaddad/ot-svn | python/test/t_ClaytonCopulaFactory_std.py | Python | mit | 1,214 | 0.000824 | #! /usr/bin/env python
from openturns import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
distribution = ClaytonCopula(1.5)
size = 1000
sample = distribution.getSample(size)
factory = ClaytonCopulaFactory()
estimatedDistribution = factory.build(sample)
print "distribution=", repr(distribu... | istribution
print "Estimated claytonCopula=", estimatedClaytonCopula
estimatedClaytonCopula = factory.buildAsClaytonCopula()
print "Default claytonCopula=", estimatedClaytonCopula
estimatedClaytonCopula = factory.buildAsClaytonCopula(
distribution.getParametersCollection())
print "ClaytonCop... | rt sys
print "t_ClaytonCopulaFactory_std.py", sys.exc_type, sys.exc_value
|
Unitech/Skytoop | controllers/widget.py | Python | mit | 3,369 | 0.006827 | # -*- coding: utf-8 -*-
#
# Copyright 2011, Alexandre Strzelewicz
# Licensed under the MIT Version
#
#########################################################
#
# Widget generic controller
#
#########################################################
xss = local_import('xss')
def can_modify():
if session.can_mo... | title=request.vars.title)
return response.json({'success':'true'})
#
# entr widgets to share widget (to put in desk.py)
#
# widgets = | db((db.desktop.id==db.entr_desktop_widgets.desktop_link)
# & (db.widgets_entr.id==db.entr_desktop_widgets.widget_link)
# & (db.desktop.id==desktop.id))\
# .select(db.widgets_entr.ALL)
# logger.debug(widgets)
#
#
#
# def new_widget_entr():
# widget = db.widgets_entr.insert(x=... |
danielsunzhongyuan/my_leetcode_in_python | convert_a_number_to_hexadecimal_405.py | Python | apache-2.0 | 1,152 | 0.005208 | """
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two's complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not conta | in extra leading 0s.
If the number is zero, it is represented by a single zero character '0'; otherwise,
the first character in the hexadecimal string will not be the zero character.
The given n | umber is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
"""
class Solution(object):
def toHex(self, num):
"""... |
bardin-lab/readtagger | tests/test_pysamtools_view.py | Python | mit | 404 | 0 | import pysam
from readtagger.pysamtools_view import view
INPUT = 'tagged_dm6.bam'
def test_pysamtoolsview(datadir_copy, tmpdir): # noqa: D103
input_bam = str(datadir_copy[INPUT])
output_b | am = tmpdir.join('out.bam').strpath
region = '3R:81 | 21625-8121731'
view(input_bam=input_bam, output_bam=output_bam, region=region)
assert len(pysam.AlignmentFile(output_bam).header['SQ']) == 1
|
CFDEMproject/LIGGGHTS-PUBLIC | python/examples/plot.py | Python | gpl-2.0 | 1,885 | 0.015385 | #!/usr/bin/env python | -i
# preceeding line should have path for Python on your machine
# plot.py
# Purpose: plot Temp of running LIGGGHTS simulation via GnuPlot in Pizza.py
# Syntax: plot.py in.liggghts Nfreq Nsteps compute-ID
# in.liggghts = LIGGGHTS input script
# Nfreq = plot data point every this many steps
# ... | other scalar quantity)
import sys
sys.path.append("./pizza")
from gnu import gnu
# parse command line
argv = sys.argv
if len(argv) != 5:
print "Syntax: plot.py in.liggghts Nfreq Nsteps compute-ID"
sys.exit()
infile = sys.argv[1]
nfreq = int(sys.argv[2])
nsteps = int(sys.argv[3])
compute = sys.argv[4]
me = 0
# ... |
Mapotempo/mapotempo-qgis-plugin | urllib3/filepost.py | Python | gpl-2.0 | 2,256 | 0.000887 | import codecs
from uuid import uuid4
from io import BytesIO
import six
from six import b
from .fields import RequestField
writer = codecs.lookup('utf-8')[3]
def choose_boundary():
"""
Our embarassingly-simple replacement for mimetools.choose_boundary.
"""
return uuid4().hex
def iter_field_objects... | of
:class:`~urllib3.fields.RequestField`.
"""
if isinstance(fields, dict):
i = six.iteritems(fields)
else:
i = iter(fields)
for field in i:
if isinstance(field, RequestField):
yield field
else:
yield RequestField.from_tuples(*field)
def it... | :func:`iter_field_objects`, which returns
:class:`~urllib3.fields.RequestField` objects.
Supports list of (k, v) tuples and dicts.
"""
if isinstance(fields, dict):
return ((k, v) for k, v in six.iteritems(fields))
return ((k, v) for k, v in fields)
def encode_multipart_formdata(fields, b... |
ONSdigital/eq-survey-runner | app/helpers/schema_helpers.py | Python | mit | 4,296 | 0.002793 | from functools import wraps
from uuid import uuid4
from app.globals import get_session_store
from app.utilities.schema import load_schema_from_session_data
def with_schema(function):
"""Adds the survey schema as the first argument to the function being wrapped.
Use on flask request handlers or methods called... | if driver_id in schema.get_group_dependencies_block_drivers():
driver_answer_ids = schema.get_answer_ids_for_block(driver_id)
| group_instance_ids.extend(_get_group_instance_ids_for_block(answer_store, driver_answer_ids))
return group_instance_ids[group_instance]
def _get_group_instance_ids_for_group(answer_store, group_answer_ids):
group_instance_ids = []
group_instances = 0
for answer in list(answer_store.filter(answer_... |
moertle/_.py | _/web/auth/__init__.py | Python | mit | 318 | 0.003145 |
# login methods are dynamically imported if auth is enabled
import logging
from .logout | import Logout
import tornado.web
import _
@_.c | omponents.Register('auth')
class Authentication(tornado.web.RequestHandler):
@classmethod
def _pyConfig(cls, config):
cls.URL = config.pop('login_page', '/login')
|
kastnerkyle/crikey | ishaan_model/ishaan_baseline.py | Python | bsd-3-clause | 13,070 | 0.000995 | from __future__ import print_function
import numpy as np
import theano
from theano import tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from scipy.io import wavfile
import os
import sys
from kdllib import audio_file_iterator
from kdllib import numpy_one_hot, apply_quantize_preproc
from kd... | ram_search, print_param_info
from kdllib import LearnedInitHidden
from kdllib import Linear
from kdllib import Embedding
from kdllib import Igor
from kdllib | import load_checkpoint, theano_one_hot, concatenate
from kdllib import fetch_fruitspeech, list_iterator
from kdllib import np_zeros, GRU, GRUFork
from kdllib import make_weights, make_biases, relu, run_loop
from kdllib import as_shared, adam, gradient_clipping
from kdllib import get_values_from_function, set_shared_va... |
bally12345/enigma2 | lib/python/Plugins/SystemPlugins/TempFanControl/plugin.py | Python | gpl-2.0 | 10,581 | 0.019941 | from Components.ActionMap import ActionMap
from Components.Sensors import sensors
from Components.Sources.Sensor import SensorSource
from Components.Sources.StaticText import StaticText
from Components.ConfigList import ConfigListScreen
from Components.config import getConfigListEntry
from Screens.Screen import Screen... | rce="SensorFanText4" render="Label" position="290,230" zPosition="1" size="90,40" font="Regular;20" halign="left" valign="top" backgroundColor="#9f1313" transparent="1" />
<widget sour | ce="SensorFan4" render="Label" position="380,230" zPosition="1" size="150,20" font="Regular;19" halign="right">
<convert type="SensorToText"></convert>
</widget>
<widget source="SensorFanText5" render="Label" position="290,250" zPosition="1" size="90,40" font="Regular;20" halign="left" valign="top" background... |
KellyChan/python-examples | python/aldebaran/hana/hana/motion/cartesian/motion_hulaHoop.py | Python | mit | 2,824 | 0.009561 | # -*- encoding: UTF-8 -*-
import sys
import motion
import almath
from naoqi import ALProxy
def StiffnessOn(proxy):
# We use the "Body" name to signify the collection of all joints
pNames = "Body"
pStiffnessLists = 1.0
pTimeLists = 1.0
proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLi... | dwx, 0.0, 0.0], # point 02 : right / bend left
[-dx, 0.0, 0.0, 0.0, dwy, 0.0], # point 03 : backward / bend forward
[0.0, +dy, 0.0, dwx, 0.0, 0.0], # point 04 : left / bend right
[+dx, 0.0, 0.0, 0.0, -dwy, 0.0], # point 01 : forward / bend backward
... | point 02 : right / bend left
[-dx, 0.0, 0.0, 0.0, dwy, 0.0], # point 03 : backward / bend forward
[0.0, +dy, 0.0, dwx, 0.0, 0.0], # point 04 : left / bend right
[+dx, 0.0, 0.0, 0.0, -dwy, 0.0], # point 05 : forward / bend backward
[0.0, 0.0, 0.0, 0.... |
saurabhkumar1989/programming_question_python | my_question/all-valid-bracket-permutation.py | Python | apache-2.0 | 545 | 0.029358 | '''
Input : n=1
Output: {}
Input : n=2
Output:
{}{}
{{}}
https://www.geeksforgeeks.org/print-all- | combinations-of-balanced-parentheses/
'''
def printParenthesis(string, openP, closeP):
if(openP==0 and closeP==0):
# all opening and closing are done
print string
else:
if(openP>closeP):
return
if(closeP>0):
printParenthesis(string+'}',openP,closeP-1)... | arenthesis("", n,n)
|
MinnowBoard/minnow-maker | setup.py | Python | mit | 1,963 | 0.028018 | from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from distutils import core
from distutils.command.install import install
import sys, os, subprocess
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def git(*args):
return subproce... | ory)
subprocess.call(["insmod", "low-speed-spidev.ko"])
os.chdir("..")
class install_all(install):
def run(self):
current_directory = subprocess.Popen(["pwd"],stdout=subprocess.PIPE)
| current_directory, err = current_directory.communicate()
subprocess.call(["sh","depends.sh"])
subprocess.call(["pip install -r requirements.txt --no-clean"], shell=True)
install.run(self)
setup(name = 'Maker project package',
version = '0.4',
author = 'Adafruit ... |
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/eventhubs/tests/latest/test_eventhub_commands_namespace_premium_test.py | Python | mit | 4,228 | 0.004257 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | nits}',
checks=[self.check('maximumThroughputUnits', '{maximumthroughputunits}')])
self.kwargs.update({
'maximumthroughputunits': 16})
# Create Namespace - premium
self.cmd(
'eventhubs namespace create --resource-group {rg} --name {namespacename1} --loc... | skupremium} --disable-local-auth {isfalse}',
checks=[self.check('disableLocalAuth', '{isfalse}'),
self.check('sku.name', '{skupremium}')])
# Update Namespace
self.cmd('eventhubs namespace update --resource-group {rg} --name {namespacename1} --disable-local-auth {istrue} ... |
paninetworks/neutron | neutron/db/db_base_plugin_common.py | Python | apache-2.0 | 12,074 | 0.000166 | # Copyright (c) 2015 OpenStack Foundation.
# 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... | nable_dhcp'],
'ipv6_ra_mode': subnet['ipv6_ra_mode'],
'ipv6_address_mode': subnet['ipv6_address_mode'],
'dns_nameservers': [dns['address']
for dns in subnet['dns_nameservers']],
'host_routes': | [{'destination': route['destination'],
'nexthop': route['nexthop']}
for route in subnet['routes']],
}
# The shared attribute for a subnet is the same as its parent network
res['shared'] = self._make_network_dict(subnet.network... |
santiagolopezg/MODS_ConvNet | test_lillabcrossval_network.py | Python | mit | 4,398 | 0.033197 | import keras
from keras.optimizers import SGD, adadelta, rmsprop, adam
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils
from keras.metrics import matthews_correlation, precision, recall
import keras.backend as K
import cPickle
import numpy as np
import getpass
username = getpa... | aining_data = data[1]
t_data = training_data[0]
t_label = training_data[1]
test_data = validation_data[0]
test_label = validation_data[1]
t_data = np.array(t_data)
t_label = np.array(t_label)
test_data = np.array(test_data)
test_label = np.array(test_label)
t_data = t_data.resha... | , 1, 224, 224)
test_data = test_data.reshape(test_data.shape[0], 1, 224, 224)
#less precision means less memory needed: 64 -> 32 (half the memory used)
t_data = t_data.astype('float32')
test_data = test_data.astype('float32')
return (t_data, t_label), (test_data, test_label)
def test_net(... |
dvt32/cpp-journey | Python/CodingBat/big_diff.py | Python | mit | 220 | 0.027273 | # http://coding | bat.com/prob/p184853
def big_diff(nums):
max_num = nums[0]
min_num = nums[0]
for num in nums:
max_num = max(num, max_num)
min_num = min(num, min_num)
return abs(max_num | - min_num)
|
Edraak/edx-ora2 | openassessment/assessment/api/peer.py | Python | agpl-3.0 | 37,163 | 0.001453 | """Public interface managing the workflow for peer assessments.
The Peer Assessment Workflow API exposes all public actions required to complete
the workflow for a given submission.
"""
import logging
from django.db import DatabaseError, IntegrityError, transaction
from django.utils import timezone
from dogapi impo... | ent__submission_ | uuid=submission_uuid,
assessment__score_type=PEER_TYPE
).order_by('-assessment')
submission_finished = items.count() >= peer_requirements["must_be_graded_by"]
if not submission_finished:
return None
# Unfortunately, we cannot use update() after taking a slice,
# so we need to updat... |
Chirayu-sopho/Hindi-DateTime-Parser | functions.py | Python | mit | 4,957 | 0.047004 | import datetime
from dateutil.relativedelta import *
## give final date and time after parsing by changing current date-time
def change_datetime ( c="0", y=0, mt=0, w=0, d=0, h=0, m=0, s=0):
#mt = mt + 12*y
#d = d + 30*mt
now = datetime.datetime.now()
change = relativedelta( years =+ y, months =+ mt, weeks... | rd = abbr.replace(abbr[len(abbr)-1], "")
str = str.replace(abbr, new_word)
#print (new_str)
## str.replace(abbr[len(abbr)-1], " ")
## Do directly in string without using words
for word in words:
if re.findall(r'\.(.)+\.', word):
| new_word = word.replace('.','')
str = str.replace(word, new_word)
#print (word)
#print (new_word)
#print (new_str2)
if '.' in word[0:len(word)-2]:
new_word = word.replace('.', '[dot]')
str = str.replace(word, new_word)
for letter in str:
if letter == '.':
SentenceType.append("Assertive"... |
jeremyflores/cocosCairo | oldTests/maze.py | Python | mit | 9,600 | 0.030417 | from cocosCairo.cocosCairo import * # Convenience module to import all other modules
from splash import *
BACKGROUND_COLOR = Color(0.1, 0.3, 0.7)
MAZE_PATHS = ["maze01.maze", "maze02.maze", "maze03.maze"] # an ordered list of the maze files
PATH_INDEX = 0 # the index of the next maze file to load
class MazeScene(Sce... | n == "left":
if col-1 < 0 or self._modelArray[row][col-1] != 1:
return
else:
self._playerLocation = [col-1, row]
self.didChange()
elif direction == "right":
if col+1 >= len(self._modelArray[0]) or self._modelArray[row][col+1] != 1:
return
else:
self._playerLocation = [col+1, row]
| self.didChange()
elif direction == "up":
if row-1 < 0 or self._modelArray[row-1][col] != 1:
return
else:
self._playerLocation = [col, row-1]
self.didChange()
elif direction == "down":
if row+1 >= len(self._modelArray) or self._modelArray[row+1][col] != 1:
return
else:
self._playerLoc... |
endlessm/chromium-browser | net/data/path_builder_unittest/validity_date_prioritization/generate-certs.py | Python | bsd-3-clause | 1,833 | 0.001091 | #!/usr/bin/python
# Copyright (c) 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.
"""
A chain with four possible intermediates with different notBefore and notAfter
dates, for testing path bulding prioritization.
"""
... |
target = gencerts.create_end_entity_certificate('Target', int_ac)
target.set_validity_range(DATE_A, DATE_D)
gencerts.write_chain('The root', [root], out_pem='root.pem')
gencerts.write_chain('Intermediate with validity range A..C',
[int_ac], out_pem='int_ac.pem')
gencerts.write_chain('Intermedia... | out_pem='int_ad.pem')
gencerts.write_chain('Intermediate with validity range B..C',
[int_bc], out_pem='int_bc.pem')
gencerts.write_chain('Intermediate with validity range B..D',
[int_bd], out_pem='int_bd.pem')
gencerts.write_chain('The target', [target], out_pem='target.pem')
|
twilio/twilio-python | twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py | Python | mit | 16,185 | 0.00451 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... | o.rest.api.v2 | 010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList
"""
super(IpAccessControlListMappingList, self).__init__(version)
# Path Solution
s... |
yakupc/Artificial-Intelligence | Algorithms/SolveTSPSimulatedAnnealing/SolveTSPSimulatedAnnealing.py | Python | mit | 4,196 | 0.023832 | #==============================================================================
#description : Solves travelling salesman problem by using Hill Climbing.
#author : Yakup Cengiz
#date : 20151121
#version : 0.1
#notes :
#python_version : 3.5.0
#Reference : http://www.psy... | (len(tour)):
if i != j:
| copy=tour[:]
if i < j:
copy[i:j+1]=reversed(tour[i:j+1])
else:
copy[i+1:]=reversed(tour[:j])
copy[:j]=reversed(tour[i+1:])
if copy != tour: # no point returning the same tour
yield copy
def kirkpatrick_cooling... |
cortesi/mitmproxy | mitmproxy/tools/console/flowview.py | Python | mit | 8,005 | 0.001749 | import math
import sys
from functools import lru_cache
from typing import Optional, Union # noqa
import urwid
from mitmproxy import contentviews
from mitmproxy import http
from mitmproxy.tools.console import common
from mitmproxy.tools.console import layoutwidget
from mitmproxy.tools.console import flowdetailview
fr... | changed(self):
cols, _ = self.master.ui.get_cols_rows()
if self.master.view.focus.flow:
self._w = common.format_flow(
self.master.view.focus.flow,
False,
extended=True,
hos | theader=self.master.options.showhost,
max_url_len=cols,
)
else:
self._w = urwid.Pile([])
class FlowDetails(tabs.Tabs):
def __init__(self, master):
self.master = master
super().__init__([])
self.show()
self.last_displayed_body = None
... |
MSeifert04/numpy | numpy/distutils/cpuinfo.py | Python | bsd-3-clause | 23,013 | 0.00491 | #!/usr/bin/env python
"""
cpuinfo
Copyright 2002 Pearu Peterson all rights reserved,
Pearu Peterson <pearu@cens.ioc.ee>
Permission to use, modify, and distribute this software is given under the
terms of the NumPy (BSD style) license. See LICENSE.txt that came with
this distribution for specifics.
NO WARRANTY IS EXP... | u']=='i486'
def _is_i586(self):
return self.is_Intel() and self.info[0]['cpu family'] == '5'
def _is_i686(self):
return self.is_Intel() and self.info[0]['cpu family'] == '6'
def _is_Celeron(self):
return re.match(r'.*?Celeron',
self.info | [0]['model name']) is not None
def _is_Pentium(self):
return re.match(r'.*?Pentium',
self.info[0]['model name']) is not None
def _is_PentiumII(self):
return re.match(r'.*?Pentium.*?II\b',
self.info[0]['model name']) is not None
def _is_Penti... |
mumuxme/vim-config | test/test.py | Python | gpl-3.0 | 2,612 | 0.005393 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Above the run-comment and file encoding comment.
# TODO FIXME XXX
# Keywords
with break continue del exec return pass print raise global assert lambda yield
for while if elif else import from as try except finally and in is not or
yield from
def functionname
class ... | ticmethod str sum super tuple type unichr unicode vars
xrange zip
# Builtin exceptions and warnings.
Base | Exception Exception StandardError ArithmeticError LookupError
EnvironmentError
AssertionError AttributeError EOFError FloatingPointError GeneratorExit IOError
ImportError IndexError KeyError KeyboardInterrupt MemoryError NameError
NotImplementedError OSError OverflowError ReferenceError RuntimeError
StopIteration Synt... |
CMPUT404F16T06/CMPUT404Project | mysite/socialnet/migrations/0030_author_displayname.py | Python | apache-2.0 | 480 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-22 | 22:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('socialnet', '0029_auto_20161121_0543'),
]
opera | tions = [
migrations.AddField(
model_name='author',
name='displayname',
field=models.CharField(blank=True, max_length=255, null=True),
),
]
|
themartorana/python-postmark | postmark/django_backend.py | Python | mit | 6,739 | 0.00089 | from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import EmailMessage, EmailMultiAlternatives
import base64
from postmark.core import PMMail, PMBatchMail
class PMEmailMessage(EmailMessage):
de... | rs = message.extra_headers
attachments = []
if message.attachments and isinstance(message.attachments, list):
if len(message.attachments):
| for item in message.attachments:
if isinstance(item, tuple):
(f, content, m) = item
if isinstance(content, str):
content = content.encode()
content = base64.b64encode(content)
... |
cogniteev/easy-upgrade | easy_upgrade/lib/stow.py | Python | apache-2.0 | 2,651 | 0 |
import os
import os.path as osp
import shutil
import subprocess
from .. api import Installer, parse_version
from .. toolbox import find_executable, pushd
class StowInstaller(Installer):
name = 'stow'
def __init__(self, provider, release, config):
super(StowInstaller, self).__init__(provider, releas... | version=''):
return '{}-{}'.format(self.release.pkg_name, version)
def get_local_versions(self):
| versions = []
if not osp.isdir(self.pkg_path):
return versions
for p in os.listdir(self.pkg_path):
fp = osp.join(self.pkg_path, p)
if osp.isdir(fp) and p.startswith(self.release_dir_name()):
versions.append(p[len(self.release_dir_name()):])
... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/opus_gui/general_manager/controllers/dependency_viewer.py | Python | gpl-2.0 | 1,509 | 0.003976 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 Univers | ity of Washington
# See opus_core/LICENSE
import os
from PyQt4 import QtGui, Qt, QtCore
from opus_gui.general_manager.views.ui_dependency_viewer import Ui_DependencyViewer
class DependencyViewer(QtGui.QDialog, Ui_DependencyViewer):
def __init__(self, parent_window):
flags = QtCore.Qt.WindowTitleHint | Qt... | )
self.setModal(True) #TODO: this shouldn't be necessary, but without it the window is unresponsive
def show_error_message(self):
self.lbl_error.setVisible(True)
self.scrollArea.setVisible(False)
def show_graph(self, file_path, name):
self.lbl_error.setVisible(False)
s... |
networks-lab/metaknowledge | metaknowledge/medline/__init__.py | Python | gpl-2.0 | 458 | 0.004367 | """
These are the functions used to p | rocess medline (pubmed) f | iles at the backend. They are meant for use internal use by metaknowledge.
"""
from .recordMedline import MedlineRecord, medlineRecordParser
from .medlineHandlers import isMedlineFile, medlineParser
from .tagProcessing.tagNames import tagNameDict, authorBasedTags, tagNameConverterDict
from .tagProcessing.specialFunctio... |
ladybug-analysis-tools/ladybug-core | ladybug/datatype/__init__.py | Python | gpl-3.0 | 901 | 0.00111 | # coding=utf-8
"""Module of Data Types (eg. Temperature, Area, etc.)
Possesses capabilities for unit conversions and range checks.
It also includes descriptions of the data types and the units.
Properti | es:
TYPES: A tuple indicating all currently supported data types.
BASETYPES: A tuple indicating all base types. Base types are the
data types on which unit systems are defined.
UNITS: A dictionary containing all currently supported units. The
keys of this dictionary are the base type names (eg. 'T... | : A dictionary containing pointers to the classes of each data type.
The keys of this dictionary are the data type names.
"""
from .base import _DataTypeEnumeration
_data_types = _DataTypeEnumeration(import_modules=True)
TYPES = _data_types.types
BASETYPES = _data_types.base_types
UNITS = _data_types.units
TYPESD... |
isard-vdi/isard | engine/engine/start.py | Python | agpl-3.0 | 2,127 | 0.007522 | from engine.services.lib.debug import check_if_debugging
check_if_debugging()
import inspect
import logging
import os
import sys
import traceback
from logging.handlers import RotatingFileHandler
from subprocess import check_call, check_output
from flask import Flask
## Moved populate & upgrade from webapp
from init... | ("api.log", maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
# register blueprints
from engine.api import api as api_blueprint
app.regist | er_blueprint(api_blueprint, url_prefix="") # url_prefix /api?
# run(app)
if os.environ.get("LOG_LEVEL") == "DEBUG":
app.run(debug=True, host="0.0.0.0")
else:
app.run(host="0.0.0.0")
|
liangtianyou/ST | stclient/menus.py | Python | gpl-3.0 | 3,290 | 0.024443 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
impo | rt settings
#----------------------------------------
# globals
#----------------------------------------
web = settings.web
stow = web.utils.storage
#----------------------------------------
# 初始化菜单 权限控制
#----------------------------------------
d | ef init_menus():
_ = web.config.get('_gettext')
menus = [
stow({
'id':'base',
'title':_("menu_system_base"),
'menus':[
#stow({
# 'id':'menusystemstatus', #系统状态
# 'icon_class':'icon-speedometer',
# ... |
bytedance/fedlearner | fedlearner/fedavg/cluster/__init__.py | Python | apache-2.0 | 90 | 0 |
fro | m .cluster_pb2 import FLNodeDef, FLClusterDef
from .clust | er_spec import FLClusterSpec
|
woozyking/tidehunter | tidehunter/__init__.py | Python | mit | 858 | 0.002331 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP streaming toolbox with flow control, written in Python.
:copyright: (c) 2014 Runzhou Li (Leo)
:license: The MIT License (MIT), see LICENSE for details.
"""
__title__ = 'tidehunter'
__version__ = '1.0.1'
VERSION = tuple(map(int, __version__.split('.')))
__author_... | default logging handler to avoid "No handler found" warnings.
import logging
try: # Py | thon 2.7+
from logging import NullHandler
except ImportError: # pragma: no cover
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
|
ylitormatech/terapialaskutus | therapyinvoicing/customers/forms.py | Python | bsd-3-clause | 7,087 | 0.001978 | from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Customer, Session, CompanyProfile
class CustomerUpdateForm(forms.ModelForm):
"""
Update Customer form
Field enhancements:
* therapyCategory uses forms.TypedChoiceField.
"""
class Meta:
... | CHOICES
"""
class Meta:
model = CompanyProfile
fields = [
'companyName',
'firstName',
'additionalName',
'lastName',
'address',
'zipCode',
'city',
'country',
'telephone',
'email... | 'bic',
'serviceproviderType',
'invoiceRefType',
'taxAdvanceType'
]
labels = {
'companyName': _("Oman yrityksen nimi"),
'firstName': _("Etunimi"),
'additionalName': _("Muut etunimet"),
'lastName': _("Sukunimi"),
... |
pratikmallya/heat | heat/engine/resources/openstack/keystone/role_assignments.py | Python | apache-2.0 | 15,791 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | properties.Schema.STRING,
_('Keystone project'),
constraints=([constraints.
CustomConstraint('keystone.project')])
),
DOMAIN: properties.Schema(
properties.Schema.STRI... | nstraint('keystone.domain')])
),
}
),
update_allowed=True
)
}
def _add_role_assignments_to_group(self, group_id, role_assignments):
for role_assignment in self._normalize_to_id(role_assignments):
if role_assignment.get(self... |
antoniodemora/git-cola | cola/qtutils.py | Python | gpl-2.0 | 30,765 | 0.000163 | # Copyright (C) 2007-2018 David Aguilar and contributors
"""Miscellaneous Qt utility functions."""
from __future__ import division, absolute_import, unicode_literals
import os
from qtpy import compat
from qtpy import QtGui
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore i... | layout.setStretchFactor(idx, 1)
# Workaround for Qt not setting the WA_Hover property for QSplitter
# Cf. https://bugreports.qt.io/browse/QTBUG-1376 | 8
layout.handle(1).setAttribute(Qt.WA_Hover)
return layout
def label(text=None, align=None, fmt=None, selectable=True):
"""Create a QLabel with the specified properties"""
widget = QtWidgets.QLabel()
if align is not None:
widget.setAlignment(align)
if fmt is not None:
widget.s... |
victorkeophila/alien4cloud-cloudify3-provider | src/test/resources/outputs/blueprints/openstack/tomcat/wrapper/Tomcat/tosca.interfaces.node.lifecycle.Standard/create/artifacts/tomcat-war-types/scripts/_a4c_tomcat_install.py | Python | apache-2.0 | 14,972 | 0.004542 |
from cloudify import ctx
from cloudify.exceptions import NonRecoverableError
from cloudify.state import ctx_parameters as inputs
import subprocess
import os
import re
import sys
import time
import threading
import platform
from StringIO import StringIO
from cloudify_rest_client import CloudifyClient
from cloudify impo... | e):
result_map = {}
# get all | instances data using cfy rest client
# we have to get the node using the rest client with node_instance.node_id
# then we will have the relationships
node = client.nodes.get(ctx.deployment.id, entity.node.id)
all_node_instances = client.node_instances.list(ctx.deployment.id, entity.node.id)
for nod... |
nlloyd/SubliminalCollaborator | libs/twisted/test/test_usage.py | Python | apache-2.0 | 19,879 | 0.001811 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.usage}, a command line option parsing library.
"""
from twisted.trial import unittest
from twisted.python import usage
class WellBehaved(usage.Options):
optParameters = [['long', 'w', 'default', 'and a docstri... | re(self, value):
"""
This option has an underscore in its name to exercise the _ to -
translation.
"""
self.underscoreValue = value
opt_u = opt_under_score
class TypedTestCase(unittest.TestCase):
"""
Test Options.parseArgs for options with forced types.
"""
... | """
Test parsing of default values.
"""
argV = []
self.usage.parseOptions(argV)
self.assertEqual(self.usage.opts['fooint'], 392)
self.assert_(isinstance(self.usage.opts['fooint'], int))
self.assertEqual(self.usage.opts['foofloat'], 4.23)
self.assert_(is... |
chrsrds/scikit-learn | sklearn/utils/tests/test_fixes.py | Python | bsd-3-clause | 2,534 | 0 | # Authors: Gael Varoquaux <gael.varoquaux@normalesup.org>
# Justin Vincent
# Lars Buitinck
# License: BSD 3 clause
import pickle
import numpy as np
import pytest
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.fixes import MaskedArray
from sklearn.utils.fixes import _joblib... | sk, marr_pickled.mask)
@pytest.mark.parametrize('joblib_version', ('0.11', '0.12.0'))
def test_joblib_parallel_args(monkeypatch, joblib_version):
import joblib
monkeypatch.setattr(joblib, '__version__', joblib_version)
if joblib_version == '0.12.0':
# arguments are s | imply passed through
assert _joblib_parallel_args(prefer='threads') == {'prefer': 'threads'}
assert _joblib_parallel_args(prefer='processes', require=None) == {
'prefer': 'processes', 'require': None}
assert _joblib_parallel_args(non_existing=1) == {'non_existing': 1}
eli... |
macosforge/ccs-calendarserver | txdav/who/augment.py | Python | apache-2.0 | 18,083 | 0.000608 | # -*- test-case-name: txdav.who.test.test_augment -*-
##
# Copyright (c) 2013-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/li... | me = shortName.decode("utf-8")
record = yield self._directory.recordWithShortName(
recordType, shortName, timeoutSeconds=timeoutSeconds
)
record = yield self._augment(record)
returnValue(record)
@timed
@inlineCallbacks
def recordsWithEmailAddress(
self, ... | imeoutSeconds=None
):
# MOVE2WHO, REMOVE THIS:
if not isinstance(emailAddress, unicode):
# log.warn("Need to change emailAddress to unicode")
emailAddress = emailAddress.decode("utf-8")
records = yield self._directory.recordsWithEmailAddress(
emailAddress... |
radare/bitcointools | deserialize.py | Python | mit | 11,831 | 0.021384 | #
#
#
from BCDataStream import *
from enumeration import Enumeration
from base58 import public_key_to_bc_address, hash_160_to_bc_address
import logging
import socket
import time
from util import short_hex, long_hex
def parse_CAddress(vds):
d = {}
d['nVersion'] = vds.read_int32()
d['nTime'] = vds.read_uint32()
... | d['auxpow'] = parse_AuxPow(vds)
nTransactions = vds.read_compact_size()
for i in xrange(nTransactions):
d['transactions'].append(parse_Transaction(vds))
return d
def deserialize_Block(d):
result = "Time: "+time.ctime(d['nTime'])+" Nonce: "+str(d['nNonce'])
result += "\nnBits: 0x"+hex(d['nBits'])
... | lt += "\nPrevious block: "+d['hashPrev'][::-1].encode('hex_codec')
result += "\n%d transactions:\n"%len(d['transactions'])
for t in d['transactions']:
result += deserialize_Transaction(t)+"\n"
result += "\nRaw block header: "+d['__header__'].encode('hex_codec')
return result
def parse_BlockLocator(vds):
... |
Yukarumya/Yukarum-Redfoxes | testing/web-platform/mach_commands.py | Python | mpl-2.0 | 13,041 | 0.00207 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Integrates the web-platform-tests test runner with mach.
from __future__ import absolute_import, unicode_literals, pr... | s."""
def setup_kwargs(self, kwargs):
from wptrunner import wptcommandline
build_path = os.path.join(self.topobjdir, 'build')
if build_path not in sys.path:
sys.path.append( | build_path)
if kwargs["config"] is None:
kwargs["config"] = os.path.join(self.topsrcdir, 'testing', 'web-platform', 'wptrunner.ini')
if kwargs["binary"] is None:
kwargs["binary"] = self.get_binary_path()
if kwargs["prefs_root"] is None:
kwargs["prefs_root"]... |
wooga/airflow | airflow/providers/facebook/ads/hooks/ads.py | Python | apache-2.0 | 5,572 | 0.001436 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | sync_status]
percent = request[AdReportRun.Field.async_percent_completion]
self.log.info("%s %s completed, async_status: %s", percent, "%", async_status)
if async_status == JobStatus.COMPLETED.value:
self.log.info("Job run completed")
break
... | raise AirflowException(message)
time.sleep(sleep_time)
report_run_id = _async.api_get()["report_run_id"]
report_object = AdReportRun(report_run_id, api=api)
insights = report_object.get_insights()
self.log.info("Extracting data from returned Facebook Ads Iterators")
... |
501code/Fletcher-Street-Urban-Riding-Club | pages/migrations/0007_auto_20160221_1533.py | Python | mit | 473 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-21 15:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '00 | 06_auto_20160221_1241'),
]
operations = [
migrations.AlterField(
model_name='page',
| name='image',
field=models.ImageField(default='none.jpg', upload_to='uploads/'),
),
]
|
CS205IL-sp15/workbook | demo_colorFreq_start/py/compute.py | Python | mit | 594 | 0.065657 | # imports/modules
import os
import random
import json
import collections
| from PIL import Image
# Convert (r, g, b) into #rrggbb color
def getRGBstring( (r, g, b) ):
s = "#"
s = s + format(r, '02x')
s = s + format(g, '02x')
s = s + format(b, '02x')
return s
def do_compute():
# Open the image
origImgFile = 'res/bryce.jpg'
origImg = Image.open(origImgFile)
# Process the im... | 'freq': freq }
f = open("res/freq.json",'w')
s = json.dumps(output, indent = 4)
f.write(s)
|
patverga/torch-relation-extraction | bin/analysis/plot-pr-curve.py | Python | mit | 1,479 | 0.01217 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.colors
import sys
matplotlib.rc('text', usetex=True)
fontsize = 22
font = {'family' : 'serif',
'serif' : 'Times Roman',
'size' : fontsize}
matplotlib.rc('font', **font)
output_dir = "doc/naacl201... | x1.set_xlabel("Recall")
ax1.set_ylabel("Precision")
plt.xlim((0.075, 0.5,))
plt.ylim((0.075, 0.7,))
plt.yticks((0. | 1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7))
plt.xticks((0.1, 0.2, 0.3, 0.4, 0.5))
for i in range(len(labels)):
indices = np.where(data[:,model_idx] == i)
ax1.plot(data[indices,recall_idx][0], data[indices,precision_idx][0], label=labels[i], color=colors[i], lw=width)
ax1.yaxis.set_major_formatter(ticker.FuncFormatter(lambda ... |
martindurant/misc | congrid.py | Python | mit | 3,851 | 0.014801 | import numpy as n
import scipy.interpolate
import scipy.ndimage
def congrid(a, newdims, method='linear', centre=False, minusone=False):
'''Arbitrary resampling of source array to new dimension sizes.
Currently only supports maintaining the same number of dimensions.
To use 1-D arrays, first promote them to... | specify old dims
olddims = [n.arange(i, dtype = n.float) for i in list( a.shape )]
# first interpolation - for ndims = any
mint = scipy.interpolate.interp1d( olddims[-1], a, kind=method )
newa = mint( dimlist[-1] )
trorder = [ndims - 1] + range( ndims - 1 )
for i in ran... | wa = newa.transpose( trorder )
mint = scipy.interpolate.interp1d( olddims[i], newa,
kind=method )
newa = mint( dimlist[i] )
if ndims > 1:
# need one more transpose to return to original dimensions
newa = newa.transpose( trorder )
return newa
elif m... |
googleapis/python-dialogflow | samples/generated_samples/dialogflow_generated_dialogflow_v2_documents_reload_document_async.py | Python | apache-2.0 | 1,621 | 0.000617 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ogle-cloud-dialogflow
# [START dialogflow_generated_dialogflow_v2_Documents_ReloadDocument_async]
from google.cloud import dialogflow_v2
async def sample_reload_document():
# Cre | ate a client
client = dialogflow_v2.DocumentsAsyncClient()
# Initialize request argument(s)
request = dialogflow_v2.ReloadDocumentRequest(
content_uri="content_uri_value",
name="name_value",
)
# Make the request
operation = client.reload_document(request=request)
print("Wa... |
OptimalDesignLab/Kona | src/kona/linalg/matrices/preconds/idf_schur.py | Python | lgpl-3.0 | 5,770 | 0.00312 | from kona.linalg.matrices.hessian.basic import BaseHessian
class ReducedSchurPreconditioner(BaseHessian):
"""
An IDF-Schur preconditioner designed to precondition the KKT system for
multidisciplinary design optimization problems formulated using the IDF
architecture.
The preconditioner solves a sy... | stem.
Unlike the complete KKT system, this solution can be performed using FGMRES.
Attributes
----------
krylov : KrylovSolver
cnstr_jac : TotalConstraintJacobian
"""
def __init__(self, vector_factories, optns=None):
super(ReducedSchurPreconditioner, self).__init__(
ve... | self.eq_factory.request_num_vectors(1)
else:
raise RuntimeError(
"ReducedSchurPreconditioner >> " +
"Problem must have equality constraints!")
if self.ineq_factory is not None:
self.ineq_factory.request_num_vectors(1)
# initial... |
rogerhil/flaviabernardes | flaviabernardes/flaviabernardes/artwork/migrations/0012_auto_20160831_2148.py | Python | apache-2.0 | 376 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dep | endencies = [
('artwork', '0011_auto_20160217_1921'),
]
operations = [
migrations.Al | terModelOptions(
name='artwork',
options={'ordering': ('name', 'id')},
),
]
|
openstack/barbican | functionaltests/api/v1/functional/test_acls_rbac.py | Python | apache-2.0 | 13,953 | 0 | # Copyright (c) 2015 Cisco Systems
#
# 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... | atus_code)
if expected_return == 200:
self.assertIn('reader1', resp.model.read['users'])
else: |
self.assertIsNone(resp.model)
@utils.parameterized_dataset(test_data_update_secret_acl)
def test_update_secret_acl(self, user, expected_return):
secret_ref = self.store_secret()
status = self.set_secret_acl(secret_ref, get_acl_one())
self.assertEqual(200, status)
st... |
obsoleter/suds | suds/mx/typer.py | Python | lgpl-3.0 | 4,234 | 0.003779 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser 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 ... | s or the class of the node's text. Then adds the r | eferenced
prefix(s) to the node's prefix mapping.
@param node: An XML node
@type node: L{sax.element.Element}
@param tval: The name of the schema type.
@type tval: str
@param ns: The XML namespace of I{tval}.
@type ns: (prefix, uri)
@return: The sp... |
Huai-Xv/CSU_FreeClassroom | setup.py | Python | gpl-3.0 | 322 | 0 | #!/usr/bin/env python
# -*- | coding: utf-8 -*-
from setuptools i | mport setup
setup(name='my_project',
version='0.1.0',
packages=['my_project'],
entry_points={
'console_scripts': [
'my_project = crawler.__main__:main'
]
},
install_requires='requests'
)
|
kollad/turbo-ninja | tools/bootstrap.py | Python | mit | 1,403 | 0.001426 | from distutils.dir_util import copy_tree, remove_tree
import os
import shutil
def _copy_function(source, d | estination):
print('Bootstrapping project at %s' % destination)
copy_tree(source, destination)
def create_app():
cwd = os.getcwd()
game_logic_path = os.path.join(cwd, 'game_logic')
game_app_interface = os.path.join(cwd, 'game_ | app.py')
app_template = os.path.join(cwd, 'engine', 'app_template')
_game_logic_path_exists = os.path.exists(game_logic_path)
_game_app_interface_exists = os.path.exists(game_app_interface)
if _game_logic_path_exists or _game_app_interface_exists:
answer = input(
'game_app.py or game... |
sixuanwang/SAMSaaS | wirecloud-develop/src/wirecloud/fiware/marketAdaptor/views.py | Python | gpl-2.0 | 5,496 | 0.00455 | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2014 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud 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 v... | the GNU Affero General Public License
# along with Wirecloud. If not, see <http://www.gnu.org/licenses/>.
import json
from dj | ango.http import HttpResponse
from django.shortcuts import get_object_or_404
from wirecloud.commons.baseviews import Resource
from wirecloud.commons.utils.http import get_absolute_reverse_url
from wirecloud.fiware.marketAdaptor.marketadaptor import MarketAdaptor
from wirecloud.platform.models import Market, MarketUser... |
MauHernandez/cyclope | cyclope/apps/locations/migrations/0001_initial.py | Python | gpl-3.0 | 2,676 | 0.007848 | # encoding: 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 model 'Country'
db.create_table('locations_country', (
('id', self.gf('django.db.mode... | )
models = {
'locations.city': {
'Meta': {'object_name': 'City'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'region': ('django.db.models.fields.related.... | 'locations.country': {
'Meta': {'object_name': 'Country'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'locations.region': {
'Meta': {'object_name': '... |
pparacch/PlayingWithPython | computationAndProgrammingUsingPython/src/classesAndObjects/week6_L11_part05.py | Python | mit | 1,393 | 0.010768 | class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each integer in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def __str__(self):
"""Returns... | '.join([str(e) for e in self.vals]) + '}'
def __len__(self):
return len(self.vals)
def intersect(self, other):
result = intSet()
for e in self.vals:
if e in other.vals:
result.insert(e)
return result
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
... | lse otherwise"""
return e in self.vals
def remove(self, e):
"""Assumes e is an integer and removes e from self
Raises ValueError if e is not in self"""
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
s = intSet()
print s
s.... |
aniversarioperu/django-manolo | scrapers/tests/test_mincu_spider.py | Python | bsd-3-clause | 1,379 | 0.002913 | # -*- coding: utf-8 -*-
import os
import unittest
from manolo_scraper.spiders.mincu import MincuSpider
from utils import fake_response_from_file
class TestMincuSpider(unittest.TestCase):
def setUp(self):
self.spider = MincuSpider()
def test_parse_item(self):
filename = os.path.join('data/mi... | m.get('title'), u'[SERVICIOS DE UN ASISTENTE EN COMUNICACIONES]')
self.assertEqual(item.get('office'), u'QHAPAQ ÑAN')
self.assertEqual(item.get('time_end'), u'16:53')
self.assertEqual(item.get('date'), u'2015-08-18')
number_of_items = 1 + sum(1 for x in items)
self.assertEqual(... | r_of_items, 15)
|
djaodjin/djaodjin-survey | survey/urls/api/__init__.py | Python | bsd-2-clause | 1,664 | 0.000601 | # Copyright (c) 2020, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... | VIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIE | D WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMI... |
TMiguelT/PandasSchema | test/test_column.py | Python | gpl-3.0 | 2,051 | 0.003901 | import unittest
import pandas as pd
from pandas_schema import Column
from pandas_schema.validation import CanConvertValidation, LeadingWhitespaceValidation, TrailingWhitespaceValidation
class SingleValidationColumn(unittest.TestCase):
"""
Test a column with one single validation
"""
NAME = 'col1'
... | lf.col.validate(self.ser)
# There should be 6 errors, 2 for each row
self.assertEqual(len(results), 2 * len(self.ser), 'A Column produces the wrong number of errors')
for i in range(2):
in_row = [r for r in results if r.row == i]
self.assertEqual(len(in_row), 2, 'A Colum... | rrors for every row')
class AllowEmptyColumn(unittest.TestCase):
"""
Test a column with one single validation that allows empty columns
"""
NAME = 'col1'
col = Column(NAME, [CanConvertValidation(int)], allow_empty=True)
ser = pd.Series([
'',
])
def test_outputs(self):
... |
home-assistant/home-assistant | homeassistant/util/executor.py | Python | apache-2.0 | 3,555 | 0 | """Executor util helpers."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import contextlib
import logging
import queue
import sys
from threading import Thread
import time
import traceback
from .thread import async_raise
_LOGGER = logging.getLogger(__name__)
MAX_LOG_ATTEMPTS ... | with contextlib.suppress(SystemError):
# SystemError at this stage is usually a race condition
# where the thread happens | to die right before we force
# it to raise the exception
async_raise(thread.ident, SystemExit)
return joined
class InterruptibleThreadPoolExecutor(ThreadPoolExecutor):
"""A ThreadPoolExecutor instance that will not deadlock on shutdown."""
def shutdown(self, *args, **kwargs) -> N... |
CallMeMhz/megablog | src/blog/urls.py | Python | gpl-3.0 | 235 | 0 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
u | rl(r'^new', views.add_post_fo | rm, name='add'),
url(r'^post/(?P<slug>[\w-]+)/$', views.post_view, name='post'),
]
|
radproject/protocols | script.py | Python | cc0-1.0 | 3,299 | 0.036072 | #!/usr/bin/env python
#coding: utf8
#get the list of the scanned election results papers ( proces verbaux )
# sudo apt-get install python-setuptools
# easy_install beautifulsoup4
import urllib2
from bs4 import BeautifulSoup
from string import maketrans
from string import whitespace
import csv
import time
import json... | Proces Verbal which in english means protocol -- in election lexique
for pv in files:
pv_link = pv.findChild('a', href=True)
pv_ref = pv_link['href']
file_link = "http://isie.tn"+ pv_ref
fullurl = urllib2.quote(file_link.encode('utf-8'), safe="%/:=&?~#+!$,;'@()*[]")
download... | olling_center_name
download_command= "wget -P " + download_path + " " + fullurl
os.system(download_command)
|
johnsonc/OTM2 | opentreemap/otm1_migrator/migration_rules/philadelphia.py | Python | gpl-3.0 | 3,768 | 0.000531 | from otm1_migrator.migration_rules.standard_otm1 import MIGRATION_RULES
from treemap.models import ITreeCodeOverride, ITreeRegion, User
UDFS = {
'plot': {
'owner_additional_id': {
'udf.name': 'Owner Additional Id'
},
'owner_additional_properties': {
'udf.name': 'Own... | ary_obj
MIGRATION_RULES['boundary']['presave_actions'] = (MIGRATION_RULES['boundary']
.get('presave_actions', [])
+ [mutate_boundary])
MIGRATION_RULES['species']['missing_fields'] |= {'other'}
# these fields don't exis... | ets discarded. Remove them.
MIGRATION_RULES['species']['removed_fields'] -= {'family'}
MIGRATION_RULES['tree']['removed_fields'] -= {'pests', 'url'}
# this field doesn't exist, so can no longer have a to -> from def
del MIGRATION_RULES['species']['renamed_fields']['other_part_of_name']
|
kun--hust/sccloud | test/probe/test_object_failures.py | Python | apache-2.0 | 7,804 | 0 | #!/usr/bin/python -u
# Copyright (c) 2010-2012 OpenStack Foundation
#
# 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 ap... | e(container, obj,
'VERIFY')
metadata = read_metadata(data_file)
metadata['ETag'] = 'badetag'
write_metadata(data_file, metadata)
odata = direct_client.direct_get_object(
onode, opart, self.account, container, obj, heade... | 'X-Backend-Storage-Policy-Index': self.policy.idx})[-1]
self.assertEquals(odata, 'VERIFY')
try:
direct_client.direct_get_object(
onode, opart, self.account, container, obj, headers={
'X-Backend-Storage-Policy-Index': self.policy.idx})
rais... |
MatthieuDartiailh/pyvisa | visa.py | Python | mit | 1,581 | 0.003163 | # -*- coding: utf-8 -*-
"""
pyvisa.visa
~~~~~~~~~~~
Module to provide an import shortcut for the most common VISA operations.
This file is part of PyVISA.
:copyright: 2014 by PyVISA Authors, see AUTHORS for more details.
:license: MIT, see COPYING for more details.
"""
from __future__ import... | ('info', help='print information to diagnose PyVISA')
console_parser = subparsers.add_parser('shell', help='start the PyVISA console')
args = parser.parse_args()
if args.command == 'info':
from pyvisa import util
util.get_debug_info()
elif args.c | ommand == 'shell':
from pyvisa import shell
shell.main('@' + args.backend if args.backend else '')
|
renalreg/radar | radar/api/serializers/medications.py | Python | agpl-3.0 | 4,625 | 0.002162 | from cornflake import fields
from cornflake.exceptions import ValidationError
from cornflake.sqlalchemy_orm import ModelSerializer, ReferenceField
from cornflake.validators import max_length, min_, none_if_blank, optional, required
from radar.api.serializers.common import (
MetaMixin,
PatientMixin,
SourceM... | ITS, required=False)
frequency = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(1000)])
route = StringLookupField( | MEDICATION_ROUTES, required=False)
drug_text = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(10000)])
dose_text = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(10000)])
class Meta(object):
model_class = Medication
... |
PalmDr/XRD-Data-Analysis-Toolkit | Beta1.3/Builder.py | Python | apache-2.0 | 2,100 | 0.012857 | __author__ = 'j'
from tkinter import ttk
from tkinter import *
from TreeView import *
def buildFrame(root):
sub_1 = Frame(root)
sub_1.pack(side=LEFT,anchor = 'w', fill='both', expand=True)
sub_1_1 = Frame(sub_1)
sub_1_1.pack(side=TOP, anch | or='n',fill='both',expand=True)
sub_1_2 = Frame(sub_1 | )
sub_1_2.pack(side=BOTTOM,anchor = 's',expand=False,fill='x')
sub_2 = Frame(root)
sub_2.pack(side=RIGHT, anchor='w', fill='both', expand=True)
sub_2_1 = Frame(sub_2)
sub_2_1.pack(side=LEFT, anchor='w',expand=False)
sub_2_2 = Frame(sub_2)
sub_2_2.pack(side=RIGHT,anchor='e',fill='both',exp... |
deisi/home-assistant | homeassistant/components/device_tracker/unifi.py | Python | mit | 2,645 | 0 | """
Support for Unifi WAP controllers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.unifi/
"""
import logging
import urllib
from homeassistant.components.device_tracker import DOMAIN
from homeassistant.const import CONF_HOST, CONF_USERN... | pdate()
return self._clients.keys()
def get_device_name(self, mac):
"""Return the name (if known) of the device.
If a name has been set in Unifi, then return that, else
return the hostname if i | t has been detected.
"""
client = self._clients.get(mac, {})
name = client.get('name') or client.get('hostname')
_LOGGER.debug('Device %s name %s', mac, name)
return name
|
antoinecarme/pyaf | tests/artificial/transf_Logit/trend_MovingAverage/cycle_12/ar_12/test_artificial_128_Logit_MovingAverage_12_12_100.py | Python | bsd-3-clause | 267 | 0.086142 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform = "Logit", sigma = 0.0, exog_count = 100, ar_order = 12) | ; | |
eedf/becours | becours/settings.py | Python | mit | 3,562 | 0.001123 | """
Django settings for becours project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os... | dators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValida... | password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'Europe/Paris'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10... |
dparks1134/STAMP | stamp/plugins/samples/plots/SeqHistogram.py | Python | gpl-3.0 | 9,822 | 0.032376 | #=======================================================================
# Author: Donovan Parks
#
# Sequence histogram plot.
#
# Copyright 2011 Donovan Parks
#
# This file is part of STAMP.
#
# STAMP is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publi... | ], patches[1][0]], (profile.sampleNames[0], profile.sampleNames[1]), loc=self.legendPos)
legend.get_frame().set_linewidth(0)
for a in axesHist.yaxis.majorTicks:
a.tick1On=True |
a.tick2On=False
for a in axesHist.xaxis.majorTicks:
a.tick1On=True
a.tick2On=False
for line in axesHist.yaxis.get_ticklines():
line.set_color(axesColour)
for line in axesHist.xaxis.get_ticklines():
line.set_color(axesColour)
for loc, spine in axesHist.spines.iteritems():
if ... |
miurahr/seahub | seahub/wopi/settings.py | Python | apache-2.0 | 1,424 | 0.005618 | # Copyright (c) 2012-2016 Seafile Ltd.
import seahub.settings as settings
# OfficeOnlineServer, OnlyOffice, CollaboraOffice
OFFICE_SERVER_TYPE = getattr(settings, 'OFFICE_SERVER_TYPE', '')
OFFICE_WEB_APP_BASE_URL = getattr(settings, 'OFFICE_WEB_APP_BASE_URL', '')
WOPI_ACCESS_TOKEN_EXPIRATION = getattr(settings, 'WOPI... | OFFICE_WEB_APP_DISCOVERY_EXPIRATION', 7 * 24 * 60 * 60)
ENABLE_OFFICE_WEB_APP = getattr(settings, 'ENABLE_OFFICE_WEB_APP', False)
OFFICE_WEB_APP_FILE_EXTENSION = getattr(settings, 'OFFICE_WEB_APP_FILE_EXTENSION', ())
ENABLE_OFFICE_WEB_APP_EDIT = getattr(settings, 'ENABLE_OFFICE_WEB_APP_EDIT', False)
OFFICE_WEB_APP_ED... | when use client authentication
OFFICE_WEB_APP_CLIENT_CERT = getattr(settings, 'OFFICE_WEB_APP_CLIENT_CERT', '')
# path to client.key when use client authentication
OFFICE_WEB_APP_CLIENT_KEY = getattr(settings, 'OFFICE_WEB_APP_CLIENT_KEY', '')
# path to client.pem when use client authentication
OFFICE_WEB_APP_CLIENT_P... |
fp7-netide/Tools | traffem/apps/http/serverPUT.py | Python | epl-1.0 | 819 | 0.006105 | import sys
import signal
from threading import Thread
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler |
class PUTHandler(BaseHTTPRequestHandler):
def do_PUT(self):
print "----- SOMETHING WAS PUT!! ------"
print self.headers
length = int(self.headers['Content-Length'])
content = self.rfile.read(length)
self.send_response(200)
print content
def run_on(p | ort):
print("Starting a server on port %i" % port)
server_address = ('localhost', port)
httpd = HTTPServer(server_address, PUTHandler)
httpd.serve_forever()
if __name__ == "__main__":
server = Thread(target=run_on, args=[81])
server.daemon = True # Do not make us wait for you to exit
server... |
persandstrom/home-assistant | homeassistant/components/device_tracker/xiaomi_miio.py | Python | apache-2.0 | 2,487 | 0 | """
Support for Xiaomi Mi WiFi Repeater 2.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/device_tracker.xiaomi_miio/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.device_tra... | elf.device = device
async def async_scan_devices(self):
"""Scan for devices and return a list containing found device ids."""
from miio impor | t DeviceException
devices = []
try:
station_info = await self.hass.async_add_job(self.device.status)
_LOGGER.debug("Got new station info: %s", station_info)
for device in station_info.associated_stations:
devices.append(device['mac'])
except... |
chetan51/neon | neon/layers/__init__.py | Python | apache-2.0 | 1,116 | 0.001792 | # ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems 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.o... | , BatchNorm, BatchNormAutodiff,
Deconv, GeneralizedCostMask)
from neon.layers.merge import Merge, MergeSum, MergeConcat, MergeConcatSequence
from neon.layers.recurrent import Recurrent, | LSTM, GRU
|
yssk22/gaecouch | couch/models/document.py | Python | apache-2.0 | 708 | 0.011299 | from datetime import datetime
from google.appengine.ext import db
from django.utils import simplejson as json
from couch import errors
from couch.models.util import gen_uuid
class DocumentRoot(db.Model):
''' Controls document '''
revno = db.IntegerProperty(default = 0)
revsuffix = db.StringPropert | y()
deleted = db.BooleanProperty(default = False)
def rev(self):
return '%s-%s' % (self.revno, self.revsuffix)
class Document(db | .Model):
id = db.StringProperty()
rev = db.StringProperty()
dbname = db.StringProperty()
docstring = db.TextProperty()
deleted = db.BooleanProperty(default = False)
def to_dict(self):
return json.loads(self.docstring)
|
GastonLab/ddb-mongodb | vcf_parsing.py | Python | mit | 11,779 | 0.000679 | import sys
from cyvcf2 import VCF
from collections import defaultdict
def parse_caller_vcfs(sample_dict, caller_list):
caller_vcf_records = defaultdict(lambda: dict())
for caller in caller_list:
parse_vcf(sample_dict[caller], caller, caller_vcf_records)
return caller_vcf_records
def parse_vcf(v... | d.FILTER),
'AC': str(record.INFO.get('AC')),
'RO': str(record.INFO.get('RO')),
'AO': str(record.INFO.get('AO')),
'PRO': str(record.INFO.get('PRO')),
'PAO': str(record.INFO.get('PAO')),
'QR': str(recor | d.INFO.get('QR')),
'QA': str(record.INFO.get('QA')),
'PQR': str(record.INFO.get('PQR')),
'PQA': str(record.INFO.get('PQA')),
'SRF': str(record.INFO.get('SRF')),
'SRR': str(record.INFO.get('SRR')),
'SAF': str(record.INFO.get('SAF')),
'SA... |
airbnb/airflow | airflow/providers/google/cloud/example_dags/example_dataflow_sql.py | Python | apache-2.0 | 2,471 | 0.000809 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | """,
options={
"bigquery-project": GCP_PROJECT_ID,
"bigquery-dataset": BQ_SQL_DATASET,
"bigq | uery-table": BQ_SQL_TABLE_OUTPUT,
"bigquery-write-disposition": "write-truncate",
"parameter": "state_id_min:INT64:2",
},
location=DATAFLOW_SQL_LOCATION,
do_xcom_push=True,
)
|
datalogics/scons | test/option/srcdir.py | Python | mit | 1,950 | 0.006667 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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,
... | ch things from a repository.
"""
import TestSCons
|
test = TestSCons.TestSCons()
test.subdir('repository', 'work1')
repository = test.workpath('repository')
test.write(['repository', 'SConstruct'], r"""
env = Environment()
env.Command('file.out', 'file.in', Copy('$TARGET', '$SOURCE'))
""")
test.write(['repository', 'file.in'], "repository/file.in\n")
opts = '--src... |
SuyashD95/python-assignments | Assignment 3/odd.py | Python | mit | 403 | 0.044665 | """
Q4- Write a Python function, odd, that takes in one number and returns True when the number is odd and False otherwise. You should us | e the % (mod) operator, not if. This function takes in one number and returns a boolean
"""
def odd( numb | er ):
return number % 2 == 1
number = int( input( "Enter a number: ") )
print( "Is the number " + str( number ) + " odd? Answer: " + str( odd( number) ) )
|
nanshe-org/nanshe_workflow | nanshe_workflow/util.py | Python | apache-2.0 | 733 | 0.001364 | import contextlib
import gzip
import hashlib
import io
import mmap
from builtins import (
map as imap,
)
def gzip_compress(data, compresslevel=6):
compressed = io.BytesIO()
with gzip.GzipFile(fileobj=compressed,
mode="wb",
compresslevel=compresslevel) as comp... | )
with open(fn, "r") as fh:
with contextlib.closing(mmap.mmap(fh.fileno(), 0, prot=mmap.PROT_READ)) as mm:
h.update(mm)
return h.digest()
def inde | nt(text, spaces):
spaces = " " * int(spaces)
return "\n".join(imap(lambda l: spaces + l, text.splitlines()))
|
manhhomienbienthuy/pythondotorg | pages/urls.py | Python | apache-2.0 | 142 | 0 | from .views import PageView
from django.urls import path
urlpatterns = [
path('<path:path>/', PageView.as_view(), name='page_detail'),
] | ||
anhstudios/swganh | data/scripts/templates/object/creature/npc/droid/crafted/shared_droideka_advanced.py | Python | mit | 474 | 0.046414 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLE | S
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/creature/npc/droid/crafted/shared_droideka_advanced.iff"
result.attribute_template_id = 3
result.stfName("droid_name","droideka_crafted_advanced") |
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
MichalMaM/ella | test_ella/test_app/models.py | Python | bsd-3-clause | 487 | 0 | from django.db import models
from django.util | s.translation import ugettext_lazy as _
from ella.core.models import Publishable
class XArticle(Publishable):
"""
``XArticle`` is extra publishable descendant for testing.
Is used for possibility testing descendants of publishable
with different content type
"""
content = models.TextField(_('... | verbose_name = _('XArticle')
verbose_name_plural = _('XArticles')
|
rmelchorv/TDD-Cuervos | lists/forms.py | Python | mit | 435 | 0.034483 | from | django import forms
from lists.models import Item
EMPTY_LIST_ERROR = "You can't have an empty list item"
class ItemForm(forms.models.ModelForm):
class Meta:
model = Item
fields = ('text',)
widgets = {
'text': forms.fields.TextInput(attrs={
'placeholder': 'Enter a to-do item',
'class': 'form-cont... | ': "You can't have an empty list item"}
} |
agustinhenze/logbook.debian | logbook/_fallback.py | Python | bsd-3-clause | 6,767 | 0.000591 | # -*- coding: utf-8 -*-
"""
logbook._fallback
| ~~~~~~~~~~~~~~~~~
Fallb | ack implementations in case speedups is not around.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
from itertools import count
from logbook.helpers import get_iterator_next_method
from logbook.concurrency import (thread_get_ident, greenlet_get_ident,
... |
kou/arrow | cpp/src/arrow/util/bpacking_simd_codegen.py | Python | apache-2.0 | 6,630 | 0.001056 | #!/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 ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... | int32_t* in, uint32_t* out) {")
print(" memset(out, 0x0, 32 * sizeof(*out));")
print(" out += 32;")
print("")
print(" return in;")
print("}")
def print_unpack_bit32_func(self):
print(
"inline static const uint32_t* unpack32_32(const uint32_t* in, uint... |
print("}")
def print_unpack_bit_func(self, bit):
def p(code):
print(indent(code, prefix=' '))
shift = 0
shifts = []
in_index = 0
inls = []
mask = (1 << bit) - 1
bracket = "{"
print(f"inline static const uint32_t* unpack{bit}_32... |
yosi-dediashvili/SubiT | src/SubChoosers/FirstInCertainSubStagesChooser.py | Python | gpl-3.0 | 2,895 | 0.005181 | from SubChoosers.ISubStagesChooser import ISubStagesChooser
from SubRankers.ByFullNameSubStagesRanker import ByFullNameSubStagesRanker
from Utils import WriteDebug
class FirstInCertainSubStagesChooser(ISubStagesChooser):
""" Implementation of ISubStagesChooser. This chooser return results after
ranki... | WriteDebug('Got Versions in version_sub_stages, sending them to the ranker')
(version_sub_stages, first_is_ceratin) = ByFullNameSubStagesRanker\
.rankVersionSubStages(version_sub_stages, query)
WriteDebug('Ranker returned %s for first_is_certain, but we dont care' % firs... | bug('VersionSubStage: %s' % version_sub_stage.info())
else:
WriteDebug('There is not results in version_sub_stages, returning None')
return version_sub_stage
|
lilydjwg/you-get | src/you_get/extractors/acfun.py | Python | mit | 3,211 | 0.005308 | #!/usr/bin/env python
__all__ = ['acfun_download']
from ..common import *
from .letv import letvcloud_download_by_vu
from .qq import qq_download_by_vid
from .sina import sina_download_by_vid
from .tudou import tudou_download_by_iid
from .youku import youku_download_by_vid
import json, re
def get_srt_json(id):
... |
urls = s['data']['files'][-1]['url']
size = urls_size(urls)
print_info(site_info, title, 'mp4', size)
if not info_only:
download_urls(urls, title, 'mp4', size,
output_dir=output_dir, merge=merge)
else:
raise NotImplementedError(sourceTyp... | le = get_filename(title)
print('Downloading %s ...\n' % (title + '.cmt.json'))
cmt = get_srt_json(vid)
with open(os.path.join(output_dir, title + '.cmt.json'), 'w', encoding='utf-8') as x:
x.write(cmt)
except:
pass
def acfun_download(url, output_d... |
therealpyro/slave | slave/test/test_lakeshore.py | Python | gpl-3.0 | 488 | 0 | # -*- coding: utf-8 -*-
#
# Slave, (c) 2 | 014, see AUTHORS. Licensed under the GNU GPL.
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from future.builtins import *
from slave.lakeshore import LS340, LS370
from slave.transport import SimulatedTransport
def te | st_ls340():
# Test if instantiation fails
LS340(SimulatedTransport())
def test_ls370():
# Test if instantiation fails
LS370(SimulatedTransport())
|
kaarolch/ansible | lib/ansible/modules/system/osx_defaults.py | Python | gpl-3.0 | 14,430 | 0.003119 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, GeekChimp - Franck Nijhof <franck@geekchimp.com>
#
# 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 you... | value = float(value)
except ValueError:
raise OSXDefaultsException("Invalid float value: {0}".format(repr(value)))
return value
elif type == "array":
if not isinstance(value, list):
raise OSXDefaultsException("Invalid value. Expec... | turns a normalized list of commandline arguments based on the "host" attribute """
def _host_args(self):
if self.host is None:
return []
elif self.host == 'currentHost':
return ['-currentHost']
else:
return ['-host', self.host]
""" Returns a list cont... |
Johnetordoff/osf.io | api_tests/conftest.py | Python | apache-2.0 | 378 | 0.002646 | from __future__ import print_function
import pytest
from website.app import init_app
from tests.json_api_test_app import JSONAPITestApp
@pytest.fixture()
def app():
return JSONAPITestApp()
# NOTE: autouse so that ADDONS_REQUESTED gets set on website.settings
@pytest.fixture(autouse=True, scope='session')
def a... | p_init() | :
init_app(routes=False, set_backends=False)
|
TelematicaUSM/EduRT | src/wsclass.py | Python | agpl-3.0 | 8,134 | 0 | # -*- coding: UTF-8 -*-
# COPYRIGHT (c) 2016 Cristóbal Ganter
#
# GNU AFFERO GENERAL PUBLIC LICENSE
# Version 3, 19 November 2007
#
# 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, eit... | 'w': self.handler.ws_pub_sub,
'd': mb,
'l': self.handler.local_pub_sub,
}
for attr_name in dir(self):
attribute = getattr(self, attr_name)
if hasattr(attribute, 'msg_types'):
for _type, channels in a | ttribute.msg_types:
msg.code_debug(
_path,
'Adding action: %r ...' % attribute
)
self.register_action_in(
msg_type=_type, action=attribute,
channels=channels)
... |
CompassionCH/compassion-switzerland | partner_communication_switzerland/__init__.py | Python | agpl-3.0 | 468 | 0 | ##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# | @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from . import models
from . import wizards
from . import controllers
f | rom . import forms
|
retoo/pystructure | s101g/examples/simple/simple.py | Python | lgpl-2.1 | 195 | 0.025641 |
class Foo(o | bject):
def set(self, value):
self.field = value
def get(self):
return self.field
a = Foo()
a.set("hello world")
z = a.get()
pri | nt z
z
a
|
atodorov/anaconda | pyanaconda/ui/gui/xkl_wrapper.py | Python | gpl-2.0 | 15,372 | 0.003578 | #
# Copyright (C) 2012-2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it wi... | ch_language(self._get_language_variants, None)
self.configreg.foreach_country(self._get_country_variants, None)
#'grp' means that we want layout (group) switching options
self.configreg.foreach_option('grp', self._get_switch_option, None)
def _get_lang_variant(self, c_reg, item, subi | tem, lang):
if subitem:
name = item.get_name() + " (" + subitem.get_name() + ")"
description = subitem.get_description()
else:
name = item.get_name()
description = item.get_description()
#if this layout has already been added for some other langua... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.