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 |
|---|---|---|---|---|---|---|---|---|
t794104/ansible | lib/ansible/plugins/filter/ipaddr.py | Python | gpl-3.0 | 32,458 | 0.000924 | # (c) 2014, Maciej Delmanowski <drybjed@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ... | return str(v.ip)
if v.size > 1:
# /31 networks in netaddr have no broadcast address
if v.ip != v.network or not v.broadcast:
return str(v.ip)
def _gate | way_query(v):
if v.size > 1:
if v.ip != v.network:
return str(v.ip) + '/' + str(v.prefixlen)
def _address_prefix_query(v):
if v.size > 1:
if v.ip != v.network:
return str(v.ip) + '/' + str(v.prefixlen)
def _bool_ipaddr_query(v):
if v:
return True
def _br... |
aclindsa/asink-python | src/shared/daemon.py | Python | gpl-2.0 | 3,138 | 0.007648 | #!/usr/bin/env python
# Copyright (C) 2011 Aaron Lindsay <aaron@aclindsay.com>
#
# 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 op... | s.stderr.flush()
null = os.open('/dev/null', os.O_RDWR)
os.dup2(null, sys.stdin.fileno())
os.dup2(null, sys.stdout.fileno())
os.dup2(null, sys.stderr.fileno())
os.close(null)
#store our current pid in the given pidfile
atexit.register(rm_pid_file) #delete pid file when current process exits... | e at %s" %
(pid_filename))
os._exit(0)
#run the function with "real work" in it
daemon_fn()
def rm_pid_file():
global pid_file
os.remove(pid_file)
def aengelize(pid_filename):
"""Make the daemonized process represented by the given filename 'go to
heaven'."""
... |
JenkinsDev/pelican-readtime | setup.py | Python | mit | 2,230 | 0.000897 | import os
import codecs
try:
from setuptools import (setup, find_packages)
except ImportError:
from distutils.core import (setup, find_packages)
VERSION = (0, 2, 0)
__version__ = '.'.join(map(str, VERSION[:3])) + "".join(VERSION[3:])
__package_name__ = 'pelican-readtime'
__description__ = 'Plugin for Pelica... | ory_url__ = 'https://github.com/JenkinsDev/pelican-readtime'
__download_url__ = 'https://github.com/JenkinsDev/pelican-readtime'
__docformat__ = 'markdown'
__license__ = 'MIT'
__keywords__ = 'pelican blogg | ing blog static webdevelopment plugin pelican-plugin readtime python python3 python2'
here = os.path.abspath(os.path.dirname(__file__))
if os.path.exists('README.rst'):
# codec is used for consistent encoding
long_description = codecs.open(
os.path.join(here, 'README.rst'), 'r', 'utf-8').read()
else:
... |
LethusTI/supportcenter | vendor/django/tests/regressiontests/forms/tests/util.py | Python | gpl-3.0 | 3,154 | 0.008566 | # -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.forms.util import flatatt, ErrorDict, ErrorList
from django.test import TestCase
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy
class FormsUtilTestCase(TestCase):
# Tests fo... | example.com/">example</a></li></ul>')
self.assertHTMLEqual(str(ErrorList([mark_safe(exam | ple)])),
'<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul>')
self.assertHTMLEqual(str(ErrorDict({'name': example})),
'<ul class="errorlist"><li>nameExample of link: <a href="http://www.example.com/"&... |
pcolmant/repanier | repanier/views/logout_view.py | Python | gpl-3.0 | 1,016 | 0.000984 | from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.signals import user_logged_out
from d | jango.dispatch import receiver
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.decorat | ors.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from repanier.auth_backend import RepanierAuthBackend
@login_required()
@csrf_protect
@never_cache
def logout_view(request):
"""
Logs out the user and displays 'You are logged out' message.
"""
logout(request)
# pa... |
kapteyn-astro/kapteyn | doc/source/EXAMPLES/kmpfit_voigt.py | Python | bsd-3-clause | 4,841 | 0.021483 | #!/usr/bin/env python
#------------------------------------------------------------
# Script which demonstrates how to find the best-fit
# parameters of a Voigt line-shape model
#
# Vog, 26 Mar 2012
#------------------------------------------------------------
import numpy
from matplotlib.pyplot import figure, show, r... | 6.15751018003,6.25985588506,6.35063433647,6.41795488447,\
6.42002335563,6.35883554071,6.36915982142])
N = len(y)
err = numpy.ones(N)
A = -2
alphaD = 0.5
alphaL = 0.5
a = 6
b = 0
nu_0 = 855
p0 = [alphaD, alphaL, nu_0, A, a, b]
# Do the fit
fitter = kmpfit.Fitter(residuals=residualsV, data=... | it(params0=p0)
print("\n========= Fit results Voigt profile ==========")
print("Initial params:", fitter.params0)
print("Params: ", fitter.params)
print("Iterations: ", fitter.niter)
print("Function ev: ", fitter.nfev)
print("Uncertainties: ", fitter.xerror)
print("dof: ", fitter.dof)
print("chi... |
ella/django-versionedcache | versionedcache/middleware.py | Python | bsd-3-clause | 647 | 0.004637 | from django.core import cache
from django.core.exceptions import MiddlewareNotUsed
from versionedcache.debug import CacheClass
class CacheDebugMiddleware(object | ):
def __init__(self):
if not isinstance(cache.cache, CacheClass):
raise MiddlewareNotUsed()
def process_request(self, request):
if request.user.is_superuser and 'cache_debug' in request.GET:
action = request.GET['cache_debug']
# only two actions allowed
... | getattr(cache.cache, action)()
|
zhaochao/fuel-web | fuel_agent/fuel_agent/objects/partition.py | Python | apache-2.0 | 11,745 | 0.000085 | # Copyright 2014 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... | elf.devices.append(device)
def add_spare(self, device):
if device in self.devices or device in self.spares:
raise errors.MDDeviceDuplicationError(
'Error while attaching device to md: '
'device %s is already | attached' % device)
self.spares.append(device)
class Fs(object):
def __init__(self, device, mount=None,
fs_type=None, fs_options=None, fs_label=None):
self.device = device
self.mount = mount
self.type = fs_type or 'xfs'
self.options = fs_options or ''
... |
tongpa/tgext.pylogservice | tgext/pylogservice/models/__init__.py | Python | mit | 623 | 0.008026 | # -*- coding: utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from | zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.orm import scoped_session, sessionmaker
DeclarativeBase = declarative_base()
maker = sessionmaker(autoflush=True, autocommit=False,
extension=ZopeTransactionExtension())
DBSession = scoped_session(maker)
metadata = DeclarativeBa... | ure(bind=engine1)
metadata.bind = engine1
from .logsurvey import LogSurvey |
olgabrani/synnefo | snf-tools/synnefo_tools/burnin/cyclades_common.py | Python | gpl-3.0 | 30,688 | 0 | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed i... | ef _get_server_details(self, server, quiet=False):
"""Get details for a server"""
if not quiet:
self.info("Getting details for server %s with id %s",
| server['name'], server['id'])
return self.clients.cyclades.get_server_details(server['id'])
# pylint: disable=too-many-arguments
def _create_server(self, image, flavor, personality=None,
network=False, project_id=None):
"""Create a new server"""
if network:
... |
ingted/crmsh | modules/ui_history.py | Python | gpl-2.0 | 23,658 | 0.001395 | # Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# Copyright (C) 2013 Kristoffer Gronlund <kgronlund@suse.com>
# See COPYING for license information.
import os
import sys
import time
import re
import bz2
from . import config
from . import command
from . import completers as compl
from . import utils
... | self._init_source()
detail_num = utils.convert2ints(detail_lvl)
if detail_num is None or detail_num not in (0, 1):
context.fatal_error("Expected '0' or '1' (was '%s')" % (detail_lvl))
return crm_report().set_detail(detail_lvl)
@command.skill_level('administrator')
@co... | ...]"
self._init_source()
if options.history != "live":
common_info("setting nodes not necessary for existing reports, proceeding anyway")
return crm_report().set_nodes(*args)
@command.skill_level('administrator')
def do_info(self, context):
"usage: info"
se... |
ESOedX/edx-platform | lms/djangoapps/experiments/utils.py | Python | agpl-3.0 | 17,007 | 0.003763 | """
Utilities to facilitate experimentation
"""
from __future__ import absolute_import
import logging
from decimal import Decimal
import six
from django.utils.timezone import now
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from course_modes.models import format_course_price, g... | 199 (START)
def get_program_price_and_skus(courses):
"""
Get the total program price and purchase skus from these courses in the program
"""
program_price = 0
skus = []
for course in courses:
course_price, course_sku = get_course_entitlement_price_and_sku(course)
if course_price... | l(course_price)
skus.append(course_sku)
if program_price <= 0:
program_price = None
skus = None
else:
program_price = format_course_price(program_price)
program_price = six.text_type(program_price)
return program_price, skus
def get_course_entitlement_price_an... |
julfla/plugin.video.freplay | resources/lib/channels/arte.py | Python | gpl-2.0 | 5,259 | 0.034417 | #-*- coding: utf-8 -*-
import urllib2
import json
import CommonFunctions
common = CommonFunctions
from xml.dom import minidom
from resources.lib import utils
from resources.lib import globalvar
title=['ARTE']
img=['arte']
readyForUse=True
def fix_text(text):
return text.replace('&','&').encode('utf-... | rl']
#SD RTMP
else:
url=jsoncat['videoJsonPlayer']['VSR']['RTMP_MQ_1']['streamer'] + jsoncat['videoJsonPlayer']['VSR']['RTMP_MQ_1']['url']
url=jsoncat['videoJsonPlayer']['VSR']['HLS_SQ_1']['url']
return url
def list_videos(channel,show_title):
videos=[] ... | url=common.parseDOM(xml, "url")
for i in range(0, len(url)):
titleTab=common.parseDOM(url[i], "video:title")
if len(titleTab)>0:
title=fix_text(titleTab[0])
if(title==show_title):
name=''
image_url=''
date=''
durat... |
tchellomello/home-assistant | tests/components/switcher_kis/test_init.py | Python | apache-2.0 | 5,602 | 0.000893 | """Test cases for the switcher_kis component."""
from datetime import timedel | ta
from typing import TYPE_CH | ECKING, Any, Generator
from pytest import raises
from homeassistant.components.switcher_kis import (
CONF_AUTO_OFF,
DATA_DEVICE,
DOMAIN,
SERVICE_SET_AUTO_OFF_NAME,
SERVICE_SET_AUTO_OFF_SCHEMA,
SIGNAL_SWITCHER_DEVICE_UPDATE,
)
from homeassistant.const import CONF_ENTITY_ID
from homeassistant.co... |
130s/bloom | setup.py | Python | bsd-3-clause | 2,778 | 0.00036 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='bloom',
version='0.4.4',
packages=find_packages(exclude=['test']),
package_data={
'bloom.generators.debian': [
'bloom/generators/debian/templates/*',
'bloom/generators/debian/templates/source... | aseGenerator',
'rosrelease = bloom.generators.rosrelease:RosReleaseGenerator',
'debian = | bloom.generators.debian:DebianGenerator',
'rosdebian = bloom.generators.rosdebian:RosDebianGenerator'
],
'bloom.generate_cmds': [
'debian = bloom.generators.debian.generate_cmd:description',
'rosdebian = bloom.generators.rosdebian:description'
]
}
)
|
endlessm/chromium-browser | build/apply_locales.py | Python | bsd-3-clause | 1,497 | 0.011356 | #!/usr/bin/env python
# Copyright (c) 2009 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.
# TODO: remove this script when GYP has for loops
from __future__ import print_function
import sys
import optparse
def main(argv... | st) = parser.parse_args(argv)
if len(arglist) < 3:
print('ERROR: need string and list of locales')
return 1
str_template = arglist[1]
locales = arglist[2:]
results = []
for locale in locales:
# F | or Cocoa to find the locale at runtime, it needs to use '_' instead
# of '-' (http://crbug.com/20441). Also, 'en-US' should be represented
# simply as 'en' (http://crbug.com/19165, http://crbug.com/25578).
if options.dash_to_underscore:
if locale == 'en-US':
locale = 'en'
locale = local... |
locomatix/locomatix-python | locomatix/cli/__init__.py | Python | apache-2.0 | 3,074 | 0.006181 | ###############################################################################
#
# Copyright 2010 Locomatix, 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.or... | tion', \
'search_nearby', 'query_search_nearby', \
'search_region', 'query_search_region', \
'create_zone', 'activate_zone', 'get_zone', 'deactivate_zone', \
'delete_zone', 'delete_all_zones', 'list_zones', \
'create_fence', 'activate_fence','get_fence','deactivat... | 'delete_fence', 'delete_all_fences', 'list_fences' \
'get_location_history', 'query_location_history', \
'get_space_activity', 'query_space_activity', \
'get_histogram', 'query_histogram'
]
from create_feed import create_feed
from delete_feed import delete_feed
from list_feeds imp... |
ipanova/pulp_puppet | pulp_puppet_plugins/test/unit/test_install_distributor.py | Python | gpl-2.0 | 24,167 | 0.002814 | from cStringIO import StringIO
import os
import tarfile
import unittest
import tempfile
import shutil
import errno
import mock
from pulp.devel.unit.util import touch
from pulp.plugins.conduits.repo_publish import RepoPublishConduit
from pulp.plugins.config import PluginCallConfiguration
from pulp.plugins.model import ... | est_not_present(self):
config = PluginCallConfiguration({}, {})
result, message = self.distributor.validate_config(self.repo, config, [])
self.assertTrue(result)
def test_relative_path(self):
config = PluginCallConfiguration({}, {constants.CONFIG_INSTALL_PATH: 'a/b/c'})
r... | self.assertFalse(result)
self.assertTrue(len(message) > 0)
def test_with_permission(self):
config = PluginCallConfiguration({}, {constants.CONFIG_INSTALL_PATH: '/tmp'})
result, message = self.distributor.validate_config(self.repo, config, [])
self.assertTrue(result)
class TestP... |
remybaranx/qtaste | tools/jython/lib/Lib/repr.py | Python | gpl-3.0 | 3,151 | 0.009838 | """Redo the `...` (representation) but with limits on most sizes."""
__all__ = ["Repr","repr"]
class Repr:
def __init__(self):
self.maxlevel = 6
self.maxtuple = 6
self.maxlist = 6
self.maxdict = 4
self.maxstring = 30
self.maxlong = 40
self.maxother = 20
... | if s: s = s + ', '
s = s + self.repr1(x[i], level-1)
if n > self.maxtuple: s = s + ', ...'
elif n == 1: s = s + ','
return '(' + s + ')'
def repr_list(self, x, level):
n = len(x)
if n == 0: return '[]'
if level <= | 0: return '[...]'
s = ''
for i in range(min(n, self.maxlist)):
if s: s = s + ', '
s = s + self.repr1(x[i], level-1)
if n > self.maxlist: s = s + ', ...'
return '[' + s + ']'
def repr_dict(self, x, level):
n = len(x)
if n == 0: return '{}'
... |
marduk191/plugin.video.movie25 | resources/libs/sports/skysports.py | Python | gpl-3.0 | 35,627 | 0.028012 | import urllib,urllib2,re,cookielib,string,os,sys
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
from resources.libs import main
#Mash Up - by Mash2k3 2012.
from t0mm0.common.addon import Addon
from resources.universal import playbackengine, watchhistory
addon_id = 'plugin.video.movie25'
selfAddon = xbmcaddon.Addon(id=ad... | ')
main.addDir('Primera Liga','primera-liga',180,art+'/skysports.png')
| main.addDir('Champions League','http://www1.skysports.com/watch/video/sports/football/competitions/champions-league',176,art+'/skysports.png')
main.addDir('Capital One Cup','http://www1.skysports.com/watch/video/sports/football/competitions/capital-one-cup',176,art+'/skysports.png')
if mu... |
aokolnychyi/spark | python/pyspark/sql/context.py | Python | apache-2.0 | 24,880 | 0.002854 | #
# 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 us... | step value ``step``.
:param start: the start value
:param end: the end value (exclusive)
:param step: the incremental step (default: 1)
:param numPartitions: the number of partitions of the DataFrame
:return: :class:`DataFrame`
>>> sqlContext.range(1, 7, 2).collect... |
>>> sqlContext.range(3).collect()
[Row(id=0), Row(id=1), Row(id=2)]
"""
return self.sparkSession.range(start, end, step, numPartitions)
@ignore_unicode_prefix
@since(1.2)
def registerFunction(self, name, f, returnType=StringType()):
"""Registers a python function (i... |
ryantierney513/capirca | lib/speedway.py | Python | apache-2.0 | 1,410 | 0.00922 | # Copyright 2011 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# unless required by applicable law or agr... | = 'watson@google.com (Tony Wa | tson)'
from string import Template
from lib import iptables
class Error(Exception):
pass
class Term(iptables.Term):
"""Generate Iptables policy terms."""
_PLATFORM = 'speedway'
_PREJUMP_FORMAT = None
_POSTJUMP_FORMAT = Template('-A $filter -j $term')
class Speedway(iptables.Iptables):
"""Generates fi... |
queria/my-tempest | tempest/services/compute/xml/aggregates_client.py | Python | apache-2.0 | 5,059 | 0 | # Copyright 2013 NEC Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in c | ompliance 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 K... | pest.common import rest_client
from tempest.common import xml_utils
from tempest import config
from tempest import exceptions
CONF = config.CONF
class AggregatesClientXML(rest_client.RestClient):
TYPE = "xml"
def __init__(self, auth_provider):
super(AggregatesClientXML, self).__init__(auth_provider)... |
sssllliang/edx-analytics-pipeline | edx/analytics/tasks/util/vertica_target.py | Python | agpl-3.0 | 5,187 | 0.003085 | """luigi target for writing data into an HP Vertica database"""
import logging
import luigi
logger = logging.getLogger('luigi-interface') # pylint: disable-msg=C0103
try:
import vertica_python
except ImportError:
logger.warning("Attempted to load Vertica interface tools without the vertica_python package; w... | schema=self.marker_schema, marker_table=self.marker_table),
(self.update_id, "{schema}.{table}".format(schema=self.schema, table=self.table))
)
# make sure update is properly marked
assert self.exists(connection)
def exists(self, connection=None): # | pylint: disable-msg=W0221
if connection is None:
connection = self.connect()
connection.autocommit = True
cursor = connection.cursor()
try:
cursor.execute("""SELECT 1 FROM {marker_schema}.{marker_table}
WHERE update_id = %s
LIMI... |
blacksph3re/alastair | alastair_cookie/forms.py | Python | gpl-2.0 | 1,349 | 0.029652 | from django import forms
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from crispy_forms.bootstrap import FormActions, AppendedText, StrictButton, InlineField
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Button, Field, Hidden, HTML, Div
clas... | lper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.form_method = 'post'
self.helper.form_action = ''
self.helper.label_class = 'col-lg-3'
self.helper.field_class = 'col-lg-6'
se | lf.helper.layout = Layout(
'username',
Field('password'),
FormActions(Submit('login', 'Login', css_class='btn btn_success')),
)
class MyPasswordChangeForm(PasswordChangeForm):
def __init__(self, *args, **kwargs):
super(MyPasswordChangeForm, self).__init__(*args, **kwargs)
self.helper = FormHelper... |
hjwp/cookiecutter-example-project | config/wsgi.py | Python | mit | 1,632 | 0 | """
WSGI config for PythonAnywhere test project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_AP... | file. This includes Django's development server, if the WSGI_APPLICATION
# setting points h | ere.
application = get_wsgi_application()
# Use Whitenoise to serve static files
# See: https://whitenoise.readthedocs.org/
application = DjangoWhiteNoise(application)
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
rosmo/ansible | lib/ansible/modules/network/nxos/nxos_hsrp.py | Python | gpl-3.0 | 15,408 | 0.001493 | #!/usr/bin/python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = r'''
---
module: nxos_hsrp
extends_documentation_frag... | None,
'priority': '100',
'auth_type': 'text',
'auth_string': 'cisco',
}
def apply_key_map(key_map, table):
new_dict = {}
for key in table:
new_key = key_m | ap.get(key)
if new_key:
value = table.get(key)
if value:
new_dict[new_key] = str(value)
else:
new_dict[new_key] = value
return new_dict
def get_interface_mode(interface, intf_type, module):
command = 'show interface {0} | json'.format... |
c2corg/v6_api | c2corg_api/scripts/es/es_batch.py | Python | agpl-3.0 | 1,426 | 0 | from elasticsearch import helpers
from c2corg_api.scripts.migration.batch import Batch
from elasticsearch.helpers import BulkIndexError
import logging
log = logging.getLogger(__name__)
class ElasticBatch(Batch):
"""A batch implementation to do bulk inserts for ElasticSearch.
Example usage:
batch =... | size)
self.client = client
self.actions = []
def add(self, action):
self.actions.append(action)
self.flush_or_not()
def should_flush(self):
return len(self.actions) > self.batch_size
def flush(self):
| if self.actions:
try:
helpers.bulk(self.client, self.actions)
except BulkIndexError:
# when trying to delete a document that does not exist, an
# error is raised, and other documents are not inserted
log.warning(
... |
Etxea/gestioneide | gestioneide/apps.py | Python | gpl-3.0 | 217 | 0 | from importlib import import_module
from django.apps im | port AppConfig as BaseAppConfig
class AppConfig(BaseAppConfig):
name = "gestioneide"
def ready(self):
import_module("gestioneide.receivers | ")
|
nachandr/cfme_tests | cfme/tests/services/test_service_performance.py | Python | gpl-2.0 | 1,275 | 0.001569 | from timeit import timeit
import pytest
from cfme import test_requirements
from cfme.base.ui import navigate_to
from cfme.services.myservice import MyService
from cfme.tests.test_db_migrate import download_and_migrate_db
from cfme.utils.conf import cfme_data
@pytest.fixture
def appliance_with_performance_db(temp_ap... | 88937
1686433
"""
app = appliance_with_performance_db
assert 50000 == app.rest_api.collections.services.count
my_service = MyService(app)
# Timeit seems to accept callable as well as string of Python code on cPython.
assert timeit(lambda: navigate_to(my_service, 'All', use_resetter=Fal... | er=1) < 180
|
clembou/PCWG | pcwg/core/status.py | Python | mit | 1,242 | 0.017713 | import pandas as pd
class Status:
Instance = None
@classmethod
def add(cls, message, red = False, verbosity = 1):
cls.get().add_message(message, red, verbosity)
@classmethod
def initialize_status(cls, status_method, verbosity = 1):
# Note: verbosity must be pa... | e reference
status = cls.get()
status.status_method = status_method
status.verbosity = verbosity
@classmethod
def get(cl | s):
if cls.Instance == None:
cls.Instance = Status()
return cls.Instance
def __init__(self):
self.verbosity = 1
def add_message(self, message, red, verbosity):
if verbosity <= self.verbosity:
if isinstance(... |
uclouvain/osis_louvain | assessments/signals/subscribers.py | Python | agpl-3.0 | 2,029 | 0.001479 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | e, 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 General Public License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/... |
billyoverton/demerit-manager | run_server.py | Python | gpl-2.0 | 33 | 0 | f | rom server im | port app
app.run()
|
adviti/melange | thirdparty/google_appengine/google/appengine/ext/ndb/eventloop.py | Python | apache-2.0 | 7,479 | 0.009226 | """An event loop.
This event loop should handle both asynchronous App Engine RPC objects
(specifically urlfetch, memcache and datastore RPC objects) and arbitrary
callback functions with an optional time delay.
Normally, event loops are singleton objects, though there is no
enforcement of this requirement.
The API h... | self.inactive = 0
callback, args, kwds = self.current.popleft()
lo | gging_debug('nowevent: %s', callback.__name__)
callback(*args, **kwds)
return 0
if self.run_idle():
return 0
delay = None
if self.queue:
delay = self.queue[0][0] - time.time()
if delay <= 0:
self.inactive = 0
_, callback, args, kwds = self.queue.pop(0)
l... |
foundit/Piped | contrib/zmq/piped_zmq/__init__.py | Python | mit | 173 | 0.00578 | # See http://www.python.org/dev/peps/pep | -0386/ for versio | n numbering, especially NormalizedVersion
from distutils import version
version = version.LooseVersion('0.7.1-dev')
|
renmengye/imageqa-public | src/nn/map.py | Python | mit | 4,455 | 0.004265 | from stage import *
import os
use_gpu = os.environ.get('GNUMPY_USE_GPU', 'yes') == 'yes'
if use_gpu:
import gnumpy as gpu
import gnumpy as gnp
class Map(Stage):
def __init__(self,
outputDim,
activeFn,
inputNames=None,
| initRange=1.0,
bias=True,
biasInitConst=-1.0,
initSeed=2,
needInit=True,
initWeights=0,
| initType='zeroMean',
learningRate=0.0,
learningRateAnnealConst=0.0,
momentum=0.0,
deltaMomentum=0.0,
weightClip=0.0,
gradientClip=0.0,
weightRegConst=0.0,
outputdE... |
SU-ECE-17-7/ibeis | ibeis/algo/hots/match_chips4.py | Python | apache-2.0 | 15,985 | 0.001564 | # -*- coding: utf-8 -*-
"""
Runs functions in pipeline to get query reuslts and does some caching.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import utool as ut
import six # NOQA
from os.path import exists
#from ibeis.algo.hots import query_request
#from ibeis.algo.hots impo... | ath, bc_fname, bc_cfgstr)
cm_list = [qaid2_cm[qaid] for qaid in qaid_list]
except (IOError, AttributeError):
pass
else:
ret | urn cm_list
# ------------
# Execute query request
qaid2_cm = execute_query_and_save_L1(ibs, qreq_, use_cache, save_qcache, verbose=verbose)
# ------------
if save_qcache and len(qaid_list) > MIN_BIGCACHE_BUNDLE:
ut.save_cache(bc_dpath, bc_fname, bc_cfgstr, qaid2_cm)
cm_list = [qaid2_cm... |
spketoundi/CamODI | waespk/core/migrations/0023_merge.py | Python | mit | 399 | 0.002506 | # | -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-05-12 11:51
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ossuo', '0021_merge'),
('ossuo', '0022_signupformpage_signupformpagebullet_signupformpagelogo_s... |
]
|
julianwang/cinder | cinder/volume/drivers/netapp/dataontap/block_base.py | Python | apache-2.0 | 37,442 | 0 | # Copyright (c) 2012 NetApp, Inc. All rights reserved.
# Copyright (c) 2014 Ben Swartzlander. All rights reserved.
# Copyright (c) 2014 Navneet Singh. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Andrew Ker... | un_name, 'pool': pool_name})
self._mark_qos_policy_group_for_deletion(qos_policy_group_info)
msg = _("Volume %s could not be created.")
raise exception.VolumeBackendAPIException(data=msg % (
volume['name']))
LOG.debug('Created LUN with name %(name)s and QoS in... | s': qos_policy_group_info})
metadata['Path'] = '/vol/%s/%s' % (pool_name, lun_name)
metadata['Volume'] = pool_name
metadata['Qtree'] = None
handle = self._create_lun_handle(metadata)
self._add_lun_to_table(NetAppLun(handle, lun_name, size, metadata))
def _setup_qos_for_vol... |
itsthejoker/Pokemon-Homage | lemonyellow/core/__init__.py | Python | mit | 1,110 | 0 | from datetime import datetime
# pokemon lottery
global_lotto_last_run = datetime(1969, 12, 31, 23, 59, 59, 999999)
lotto_new_run = None
print_speed_base = 0.03 # delay between printed characters
""" Graphics Notes:
The screen is 15x11 squares in dimension. Each square is 16x16 pixels. Total
screen is 240x176. Sinc... | escape.
The o | nly reason that the start button fly away Trainer works is because
enemy trainers face south for one frame before turning back and starting the
fight sequence. Obviously, the trick does not work with trainers that are
already facing south.
Three Steps: After a battle, wild or Trainer, a wild battle cannot be triggered... |
jamespcole/home-assistant | homeassistant/components/esphome/binary_sensor.py | Python | apache-2.0 | 2,003 | 0 | """Support for ESPHome binary sensors."""
import logging
from typing import TYPE_CHECKING, Optional
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import EsphomeEntity, platform_async_setup_entry
if TYPE_CHECKING:
# pylint: disable=unused-import
from aioesphomeapi import BinaryS... | orInfo':
return super()._static_info
@property
def _state(self) -> Optional['BinarySensorState']:
return super()._state
@property
def is_on(self):
"""Return true if the binary sensor is on."""
if self._static_info.is_status_binary_sensor:
# Status binary sen... | tate is None:
return None
return self._state.state
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._static_info.device_class
@property
def available(self):
"""Return True if entity is availa... |
rzanluchi/keyard-client | tests/test_client_integration.py | Python | mit | 890 | 0.001124 | # -*- coding: utf-8 -*-
import json
import pytest
from keyard_client import KeyardClient, testutils
@pytest.mark.skipif(not testutils.keyard_is_available(), reason="keyard is missing")
class TestKeyardClient(object):
def setup_method(self, method):
self.client = KeyardClient('http://127.0.0.1:8000')
... | localhost:8002')
assert response is True
def test_health_check(self):
response = self.client.health_check('app', '0.1', 'localhost:8002')
assert response is True
def test_unregister(self):
response = self.client.unregister('app', '0.1', 'localhost:8002')
assert response... | result = {"result": ['localhost:8080']}
value = self.client.get_service('app')
assert result == value
|
qiuzhong/crosswalk-test-suite | misc/webdriver-w3c-tests/navigation/forward.py | Python | bsd-3-clause | 962 | 0.002079 | # -*- mode: python; fill-column: 100; comment-column: 100; -*-
import unittest
import sys
import os
sys.path.append(
os.pa | th.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import base_test
class ForwardTest(base_test.WebDriverBaseTest):
# Get a static page that must be the same upon refresh
def test_forward(self):
self.driver.get(
self.webserver.where_is('navigation/res/forwardStart.html'... | "body").get_text()
self.driver.go_back()
currbody = self.driver.find_element_by_css("body").get_text()
self.assertNotEqual(nextbody, currbody)
self.driver.go_forward()
currbody = self.driver.find_element_by_css("body").get_text()
self.assertEqual(nextbody, currbody)
if _... |
cpenv/cpenv | cpenv/cli/create.py | Python | mit | 1,854 | 0 | import os
from cpenv import api, paths
from cpenv.cli import core
from cpenv.module import parse_module_path
class Create(core.CLI):
'''Create a new Module.'''
def setup_parser(self, parser):
parser.add_argument(
'where',
help='Path to new module',
)
def run(self... | ule = api.create(
where=where,
name=name or default_name,
version=version or defaul | t_version.string,
description=description,
author=author,
email=email,
)
core.echo('OK!')
core.echo()
core.echo(' ' + module.path)
core.echo()
core.echo('Steps you might take before publishing...')
core.echo()
core.ec... |
PennyDreadfulMTG/Penny-Dreadful-Discord-Bot | decksite/data/person.py | Python | gpl-3.0 | 17,080 | 0.004859 | from typing import List, Optional, Sequence, Union
from decksite.data import achievements, deck, preaggregation, query
from decksite.data.models.person import Person
from decksite.database import db
from shared import dtutil, guarantee, logger
from shared.container import Container
from shared.database import sqlescap... | h.
# See https://discordapp.com/developers/docs/reference#snowflakes
# Unix timestamp (ms) for 2015-01-01T00:00:00.0000 = 1420070400000
# Unix timestamp (ms) for 2015-01-01T00:00:00.0001 = 1420070400001
# Unix timestamp (ms) for 2015-02-01T00:00:00.0000 = 14227 | 48800000
# Unix timestamp (ms) for 2100-01-01T00:00:00.0000 = 4102444800000
# Discord timestamp (ms) for 2015-01-01T00:00:00.0000 = 0
# Discord timestamp (ms) for 2015-01-01T00:00:00.0001 = 1
# Discord timestamp (ms) for 2015-02-01T00:00:00.0000 = 26... |
sjjhsjjh/blender-driver | applications/demonstration.py | Python | mit | 2,992 | 0.003676 | #!/usr/bin/python
# (c) 2018 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT
# Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver
"""Python module for Blender Driver demonstration application.
Abstract base class for demonstration applications.
This module can only be used from ... | Only printed if all its own
# imports run OK.
print('"'.join(('Application module ', __name__, '.')))
class Application(blender_driver.application.thread.Application):
_instructions = "Press ESC to crash BGE, or any other key to te | rminate."
_bannerName = 'banner'
_bannerObject = None
@property
def bannerObject(self):
return self._bannerObject
# Overriden.
def data_initialise(self):
#
# Do common initialisation for subclasses.
self._bannerObject = self.data_add_banner()
sel... |
MrSenko/Nitrate | tcms/core/contrib/auth/migrations/0001_initial.py | Python | gpl-2.0 | 867 | 0.002307 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from | django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
| ]
operations = [
migrations.CreateModel(
name='UserActivateKey',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('activation_key', models.CharField(max_length=40, null=True, blank=True)),
... |
mr555ru/orbotor | orbotor/gameprofile.py | Python | gpl-3.0 | 8,679 | 0.004378 | # Orbotor - arcade with orbit mechanics
# Copyright (C) 2014 mr555ru
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... |
self.stats1 = SimpleStats(self.team1, self.team2, self.player1)
if self.p2:
self.stats2 = SimpleStats(self.team1, self.team2, self.player2)
def game_key_listen(self, | event):
if event.type == KEYDOWN and event.key == K_F1:
self.PROFILESTEP = True
self.game_step()
elif event.type == KEYDOWN and event.key == K_F2:
print len(GCD_Singleton.orbitables)
elif event.type == KEYDOWN and event.key == K_F5:
self.soundsys.... |
openstack/tripleo-common | tripleo_common/image/exception.py | Python | apache-2.0 | 991 | 0 | # Copyright 2015 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | n):
pass
class ImageRateLimitedException(Exception): |
"""Rate Limited request"""
class ImageSpecificationException(Exception):
pass
class ImageUploaderException(Exception):
pass
class ImageUploaderThreadException(Exception):
"""Conflict during thread processing"""
pass
class ImageNotFoundException(Exception):
pass
|
takluyver/terminado | terminado/management.py | Python | bsd-2-clause | 12,822 | 0.000468 | """Terminal management for exposing terminals to a web interface using Tornado.
"""
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
# Distributed under the terms of the Simplified BSD License.
from __future__ import absolute_import, print_function
import asyncio... | rm_settings={},
extra_env=None, ioloop=None):
self.shell_command = shell_command
self.server_url = server_url
self.term_settings = term_settings
self.extra_env = extra_env
self.log = logging.getLogger(__name__)
self.ptys_by_fd = {}
if ioloop is ... | f"Setting {self.__class__.__name__}.ioloop is deprecated and ignored",
DeprecationWarning,
stacklevel=2,
)
def make_term_env(self, height=25, width=80, winheight=0, winwidth=0, **kwargs):
"""Build the environment variables for the process in the terminal."""
... |
rebost/django | django/contrib/localflavor/it/util.py | Python | bsd-3-clause | 1,800 | 0.001667 | from django.utils.encoding import smart_unicode
def ssn_check_digit(value):
"Calculate Italian social security number check digit."
ssn_even_chars = {
'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
'9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7,
... | for i in range(0, 1 | 0, 2):
total += int(normalized_vat_number[i])
for i in range(1, 11, 2):
quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10)
total += quotient + remainder
return smart_unicode((10 - total % 10) % 10)
|
aleksl05/IS-206 | ex31.py | Python | gpl-3.0 | 982 | 0.037678 | print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There`s a giant bear here eating a chees cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear e... | off. Good job!"
elif bear == "2":
print "The bear eats your legs off. Good | job!"
else:
print "Well, doing %s is probably better. Bear runs away." %bear
elif door =="2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1. Blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
insanity = raw_input("> ")
if ins... |
virantha/pypdfocr | pypdfocr/pypdfocr_pdffiler.py | Python | apache-2.0 | 2,902 | 0.004824 |
# Copyright 2013 Virantha Ekanayake All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | r matching keywords against
# if there is no match in the text
self.file_using_filename = False
def iter_pdf_page_text(self, filename):
| self.filename = filename
reader = PdfFileReader(filename)
logging.info("pdf scanner found %d pages in %s" % (reader.getNumPages(), filename))
for pgnum in range(reader.getNumPages()):
text = reader.getPage(pgnum).extractText()
text = text.encode('ascii', 'ign... |
EricssonResearch/calvin-base | calvinextras/calvinsys/data/buffer/PersistentBuffer.py | Python | apache-2.0 | 7,704 | 0.005582 | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | should be unique - will be used as part of filename",
"type": "string",
"pattern": "^[a-zA-Z0-9]+"
},
"reporting": {
"description": "Log some statistics on buffer at given interval (in seconds)",
"type": "nu | mber"
}
},
"required": ["buffer_id"],
"description": "Initialize buffer"
}
can_write_schema = {
"description": "Returns True if buffer ready for write, otherwise False",
"type": "boolean"
}
write_schema = {
"description": "Push data to buffer... |
keithhendry/treadmill | treadmill/sproc/appcfgmgr.py | Python | apache-2.0 | 452 | 0 | """Treadmill app configurator daemon, subscribes to eventmgr events.
"""
import click
from .. import appcfgmgr
def init():
"""Top level command handler."""
@click.command()
@click.option('--approot', type=click.Path(exists=Tru | e),
| envvar='TREADMILL_APPROOT', required=True)
def top(approot):
"""Starts appcfgmgr process."""
mgr = appcfgmgr.AppCfgMgr(root=approot)
mgr.run()
return top
|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_02_01/aio/operations/_express_route_circuit_peerings_operations.py | Python | mit | 21,960 | 0.005237 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | ure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse] | , T, Dict[str, Any]], Any]]
class ExpressRouteCircuitPeeringsOperations:
"""ExpressRouteCircuitPeeringsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: ... |
relh/cathhacks | app.py | Python | mit | 626 | 0.038339 | #!/usr/bin/env python
import time
import json
import random
import re
from bottle import route, hook, response, run, static_ | file
@route('/')
def index():
return static_file('index.html', root = '.')
@route('/maptweets.js')
def index_css():
return static_file('maptweets.js', root = '.')
@route('/cross.jpg')
def index_css():
return static_file('cross.jpg', ro | ot = '.')
@route('/light.png')
def index_css():
return static_file('light.png', root = '.')
@route('/event.png')
def index_css():
return static_file('event.png', root = '.')
run(host = '0.0.0.0', port = 80, server = 'tornado', debug = True)
|
Shaswat27/sympy | sympy/core/mod.py | Python | bsd-3-clause | 4,488 | 0.000223 | from __future__ import print_function, division
from sympy.core.numbers import nan
from .function import Function
class Mod(Function):
"""Represents a modulo operation on symbolic expressions.
Receives two arguments, dividend p and divisor q.
The convention used is the same as Python's: the remainder a... | t(p.args):
p = Add(*args)
else:
# handle coefficients if they are not Rational
# since those are not handled by factor_terms
# e.g. Mod(.6*x, .3*y) -> 0.3*Mod(2*x, y)
cp, p = p.as_coeff_Mul()
cq, q = q.as_coeff_Mul()
ok = | False
if not cp.is_Rational or not cq.is_Rational:
r = cp % cq
if r == 0:
G *= cq
p *= int(cp/cq)
ok = True
if not ok:
p = cp*p
q = cq*q
# simple -1 extraction
... |
theskyinflames/bpulse-go-client | vendor/github.com/youtube/vitess/test/initial_sharding_bytes.py | Python | apache-2.0 | 553 | 0.003617 | #!/usr/bin/env python
#
# Copyright 2013, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
"""Re-runs initial_sharding.py with a varbinary keyspace_id."""
from vtdb import keyrange_constants
import base_sharding
import initial_shar... | e_id
if __name__ == '__main__':
base_sharding.keyspa | ce_id_type = keyrange_constants.KIT_BYTES
utils.main(initial_sharding)
|
bytedance/fedlearner | web_console_v2/api/fedlearner_webconsole/workflow/cronjob.py | Python | apache-2.0 | 3,936 | 0.000254 | # 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 th... | resh to get the latest info
| # otherwise it'll use the indentity map locally
session.refresh(workflow)
if workflow.state == WorkflowState.STOPPED:
break
sleep(5)
else:
... |
hortonworks/hortonworks-sandbox | desktop/core/ext-py/Twisted/doc/core/benchmarks/timer.py | Python | apache-2.0 | 401 | 0.009975 |
"""Helper stuff for things"""
| import gc
gc.disable()
print 'Disabled GC'
def timeit(func, iter = 1000, *args, **kwargs):
"""timeit(func, iter = 1000 *args, **kwargs) -> elapsed time
calls func iter times with args and kwargs, returns time elapsed
"""
import time
r = range(iter)
t = time.time()
for i in r:
... | s)
return time.time() - t
|
Mlieou/oj_solutions | leetcode/python/ex_631.py | Python | mit | 1,437 | 0.004175 | class Excel(object):
def __init__(self, H, W):
"""
:type H: int
:type W: str
"""
self.table = [[{'v': 0, 'sum': None} for _ in ra | nge(ord(W) - 64)] for __ in range(H)]
def set(self, r, c, v):
"""
:type r: int
:type c: str
:type v: int
:rtype: void
"""
self.table[r - 1][ord(c) - 65] = {'v': v, 'sum': Non | e}
def get(self, r, c):
"""
:type r: int
:type c: str
:rtype: int
"""
cell = self.table[r - 1][ord(c) - 65]
if not cell['sum']: return cell['v']
return sum(self.get(*pos) * cell['sum'][pos] for pos in cell['sum'])
def sum(self, r, c, strs):... |
ytjia/coding-practice | algorithms/python/leetcode/MergeIntervals.py | Python | mit | 1,167 | 0 | # -*- coding: utf-8 -*-
# Authors: Y. Jia <ytjia.zju@gmail.com>
"""
Given a collection of intervals, merge all overlapping intervals.
https://leetcode.com/problems/merge-intervals/description/
"""
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
| self.end = e
def __eq__(self, other):
return self.start == other.start and self.end == other.end
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
lens = len(intervals)
if lens <= 1:
... | interval.start)
i = 0
j = i + 1
while j < lens:
if intervals[i].end >= intervals[j].start:
intervals[i].end = max(intervals[i].end, intervals[j].end)
j += 1
else:
merged_intervals.append(intervals[i])
i = j
... |
FreeOpcUa/python-opcua | opcua/ua/status_codes.py | Python | lgpl-3.0 | 38,535 | 0.005969 | #AUTOGENERATED!!! Date: 2020-06-19 19:44:10.693270
from opcua.ua.uaerrors import UaStatusCodeError
class StatusCodes:
Good = 0
Uncertain = 0x40000000
Bad = 0x80000000
BadUnexpectedError = 0x80010000
BadInternalError = 0x80020000
BadOutOfMemory = 0x80030000
BadResourceUnavailable = 0x800400... | EndpointUrlInvalid = 0x80830000
BadRequestInterrupted | = 0x80840000
BadRequestTimeout = 0x80850000
BadSecureChannelClosed = 0x80860000
BadSecureChannelTokenUnknown = 0x80870000
BadSequenceNumberInvalid = 0x80880000
BadProtocolVersionUnsupported = 0x80BE0000
BadConfigurationError = 0x80890000
BadNotConnected = 0x808A0000
BadDeviceFailure = 0x... |
kdeldycke/meta-package-manager | meta_package_manager/tests/test_cli_install.py | Python | gpl-2.0 | 2,682 | 0.001864 | # Copyright Kevin Deldycke <kevin@deldycke.com> and contributors.
# All Rights Reserved.
#
# 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 Founda | tion; either version 2
# of the License, or (at yo | ur 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 General Public License for more details.
#
# You should have received a copy of the GNU... |
colinbrislawn/scikit-bio | skbio/sequence/_sequence.py | Python | bsd-3-clause | 83,555 | 0.000108 | # ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... | rs']
['Alice', 'Bob']
This behavior can also occur when manipulating a sequence that has been
derived from another sequence:
>>> subseq = seq[1:3]
>>> subseq
Sequence
-----------------------------
Metadata:
'authors': <class 'list'>
'desc': 'seq desc'
'id': 'new... | ,
'desc': 'seq desc',
'id': 'new-id',
'pubmed': 12345}
The subsequence has inherited the metadata of its parent sequence. If we
update the subsequence's author list, we see the changes propagated in the
parent sequence and original metadata dictionary:
>>> subseq.metadata['authors'].app... |
Jumpscale/jumpscale6_core | lib/JumpScale/baselib/cmdrouter/CmdRouter.py | Python | bsd-2-clause | 264 | 0.018939 | from JumpScale import j
import JumpScale.baselib.redis
import JumpScale.grid.jumpscripts
class CmdRouter(object):
def __init__(self, path=None):
j.core.jumpscripts.load(path)
def | route(self,organization,actor,name,**args):
| pass
|
akanuragkumar/tensorflow-basics | ex1.py | Python | gpl-3.0 | 110 | 0.009091 | import pandas as pd
adv = pd.read_csv('Advertising.csv')
tv_budget | _x = adv.TV.to | list()
print(tv_budget_x)
|
spyoungtech/behave-webdriver | behave_webdriver/steps/__init__.py | Python | mit | 77 | 0 | from .actions impo | rt *
from .actions_r | e import *
from .expectations import *
|
mikaelboman/home-assistant | homeassistant/remote.py | Python | mit | 15,888 | 0 | """
Support for an interface to work with a remote instance of Home Assistant.
If a connection error occurs while communicating with the API a
HomeAssistantError will be raised.
For more details about the Python API, please refer to the documentation at
https://home-assistant.io/developers/python_api/
"""
from dateti... | re forwarded to API
if origin == ha.EventOrigin.local and \
event_type != ha.EVENT_TIME_CHANGED:
fire_event(self._api, event_type, event_data)
else:
super().fire(event_type, event_data, origin)
class EventForwarder(object):
"""Listens for events and forwards to... | .hass = hass
self.restrict_origin = restrict_origin
# We use a tuple (host, port) as key to ensure
# that we do not forward to the same host twice
self._targets = {}
self._lock = threading.Lock()
def connect(self, api):
"""Attach to a Home Assistant instance and fo... |
rom1sqr/miasm | miasm2/arch/mips32/regs.py | Python | gpl-2.0 | 1,927 | 0.00467 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from miasm2.expression.expression import ExprId
from miasm2.core.cpu import gen_reg, gen_regs
gen_reg('PC', globals())
gen_reg('PC_FETCH', globals())
gen_reg('R_LO', globals())
gen_reg('R_HI', globals())
exception_flags = ExprId('exception_flags', 32)
PC_init = ExprId("... | "CPR0_%d"%x for x in xrange(0x100)]
cpr0_str[0] = "INDEX"
cpr0_str[16] = "ENTRYLO0"
cpr0_str[24] = "ENTRYLO1"
cpr0_str[40] = "PAGEMASK"
cpr0_str[72] = "COUNT"
cpr0_str[80] = "ENTRYHI"
cpr0_str[104] = "CAUSE"
cpr0_str[112] = "EPC"
cpr0_str[128] = "CONFIG"
cpr0_str[152] = "WATCHHI"
regs_cpr0_e | xpr, regs_cpr0_init, regs_cpr0_info = gen_regs(cpr0_str, globals())
gpregs_expr, gpregs_init, gpregs = gen_regs(regs32_str, globals())
regs_flt_expr, regs_flt_init, fltregs = gen_regs(regs_flt_str, globals(), sz=64)
regs_fcc_expr, regs_fcc_init, fccregs = gen_regs(regs_fcc_str, globals())
all_regs_ids = [PC, PC_FETC... |
pkaifosh/sima | sima/motion/motion.py | Python | gpl-2.0 | 10,210 | 0 | from __future__ import absolute_import
from __future__ import division
from builtins import next
from builtins import zip
from builtins import range
from past.utils import old_div
from builtins import object
import itertools as it
import abc
import numpy as np
import sima
from . import _motion as mc
from future.utils... | a.masked for x in shift)
for shift in it.chain.from_iterable(shifts))
shifts = self._make_nonnegative(shifts)
assert np.any(np.all(x is not np.ma.masked for x in shift)
for shift in it.chain.from_ | iterable(shifts))
assert np.all(
np.all(x is np.ma.masked for x in shift) or
not np.any(x is np.ma.masked for x in shift)
for shift in it.chain.from_iterable(shifts))
return shifts
def correct(self, dataset, savedir, channel_names=None, info=None,
... |
mganeva/mantid | scripts/test/Muon/frequency_domain_context_test.py | Python | gpl-3.0 | 2,194 | 0.002735 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
import sys
from Muon.GUI.Common.muon_load_dat... | I.Common.muon_data_context import MuonDataContext
from Muon.GUI.FrequencyDomainAnalysis.frequency_context import FrequencyContext
from mantid.api import AnalysisDataService
import unittest
from Muon.GUI.Common.observer_pattern import Observer
from mantid.api import FileFinder
import copy
if sys.version_info.major | < 2:
from unittest import mock
else:
import mock
class MuonDataContextTest(unittest.TestCase):
def setUp(self):
self.loaded_data = MuonLoadData()
self.context = MuonDataContext(self.loaded_data)
self.frequency_context = FrequencyContext(self.context)
self.gui_variable_obse... |
tyrjola/robotframework-wiremock | resources/scripts/setup.py | Python | mit | 320 | 0 | from distutils.core import setup
setup(name='robot | framework-wiremock',
packages=['WireMockLibrary'],
package_dir={'': 'src'},
version='development',
des | cription='Robot framework library for WireMock',
author='Timo Yrjola',
author_email='timo.yrjola@gmail.com',
classifiers=[])
|
Sorsly/subtle | google-cloud-sdk/lib/googlecloudsdk/third_party/apis/bigtableadmin/v2/bigtableadmin_v2_messages.py | Python | mit | 40,478 | 0.004595 | """Generated message classes for bigtableadmin version v2.
"""
# NOTE: This file is autogenerated and should not be edited by hand.
from apitools.base.protorpclite import messages as _messages
from apitools.base.py import encoding
from apitools.base.py import extra_types
package = 'bigtableadmin'
class Bigtablead... | cesListRequest object.
Fields:
pageToken: The value of `next_page_token` returned by a previous call.
parent: The unique name of the project for which a list of instances is
requested. Values are of the form `pr | ojects/<project>`.
"""
pageToken = _messages.StringField(1)
parent = _messages.StringField(2, required=True)
class BigtableadminProjectsInstancesTablesCreateRequest(_messages.Message):
"""A BigtableadminProjectsInstancesTablesCreateRequest object.
Fields:
createTableRequest: A CreateTableRequest resou... |
biomodels/MODEL1006230013 | MODEL1006230013/model.py | Python | cc0-1.0 | 427 | 0.009368 | import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL1006230013.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
ret... | :
import libsbml
sbml = libsbml.r | eadSBMLFromString(sbmlString) |
whav/hav | src/hav/apps/tags/apps.py | Python | gpl-3.0 | 92 | 0 | from django.apps import | AppConfig
class TagsConfig(AppConfig):
| name = "hav.apps.tags"
|
psistats/linux-client | psistats/libsensors/lib/sensors.py | Python | mit | 8,525 | 0.002346 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# MODIFIED FROM ORIGINAL VERSION
#
# This file is not the same as in pypi. It includes a pull request to fix py3
# incompabilities that never ended up getting merged.
###########################... |
# TODO sensors_set_value()
# TODO sensors_do_chip_sets()
#
_get_detected_chips = SENSORS_LIB.sensors_get_detected_chips
_get_detected_chips.arg | types = [CHIP_P, POINTER(c_int)]
_get_detected_chips.restype = CHIP_P
_get_features = SENSORS_LIB.sensors_get_features
_get_features.argtypes = [CHIP_P, POINTER(c_int)]
_get_features.restype = FEATURE_P
_get_all_subfeatures = SENSORS_LIB.sensors_get_all_subfeatures
_get_all_subfeatures.argtypes = [CHIP_P, FEATURE_P, |
Ahmad31/Web_Flask_Cassandra | flask/lib/python2.7/site-packages/pony/orm/dbapiprovider.py | Python | apache-2.0 | 33,878 | 0.009947 | from __future__ import absolute_import, print_function, division
from pony.py23compat import PY2, basestring, unicode, buffer, int_types
import os, re, json
from decimal import Decimal, InvalidOperation
from datetime import datetime, date, time, timedelta
from uuid import uuid4, UUID
import pony
from pony.ut... | r
return '.'.join(provider.quote_name(item) for item in name)
def normalize_vars(provider, vars, vartypes):
pass
def ast2sql(provider, ast):
builder = provider.sqlbuilder_cls(provider, ast)
re | turn builder.sql, builder.adapter
def should_reconnect(provider, exc):
return False
@wrap_dbapi_exceptions
def connect(provider):
return provider.pool.connect()
@wrap_dbapi_exceptions
def set_transaction_mode(provider, connection, cache):
pass
@wrap_dbapi... |
joequant/algobroker | algobroker/dispatcher.py | Python | bsd-2-clause | 1,618 | 0.000618 | #!/usr/bin/python3
# Copyright (C) 2015 Bitquant Research Laboratories (Asia) Limited
# Released under the Simplified BSD License
import my_path
import time
import zmq.green as zmq
import pprint
import algobroker
import msgpack
class Dispatcher(algobroker.Broker):
def __init__(self):
algobroker.Broker._... | __(self, "dispatcher")
# send work
self.sms_sender = self.socket(zmq.PUSH)
self.sms_sender.connect(algobroker.ports['data']['broker_plivo'])
self.bitmex_sender = self.socket(zmq.PUSH)
| self.bitmex_sender.connect(algobroker.ports['data']['broker_bitmex'])
self.web_sender = self.socket(zmq.PUSH)
self.web_sender.connect(algobroker.ports['data']['broker_web'])
def process_data(self, data):
if (data['cmd'] == "log"):
self.warning(pprint.pformat(data))
eli... |
Svolcano/python_exercise | dianhua/worker/crawler/china_telecom/neimenggu/main.py | Python | mit | 17,659 | 0.003293 | # -*- coding: utf-8 -*-
import re
import json
import traceback
import sys
import time
import datetime
import random
# 这段代码是用于解决中文报错的问题
reload(sys)
sys.setdefaultencoding("utf8")
from datetime import date
from scrapy.selector import Selector
from dateutil.relativedelta import relativedelta
if __name__ == '__main__':
... | return 'SMS'
def login(self, **kwargs):
ProvinceID = '07'
code, key = login_unity(self, ProvinceID, **kwargs)
if code != 0:
return code, key
cookie_url = 'http://nm.189.cn/selfservice/service/userLogin'
cookie_data = {
"number" : kwargs['tel'],
... | "password":"",
"randomPass":"",
"noCheck":"N",
"isSSOLogin":"Y",
"sRand":"SSOLogin"
}
code, key, resp = self.post(cookie_url, data=json.dumps(cookie_data))
if code != 0:
return code, key
personal_info_url = 'http://www.189.... |
mikuyves/fashion-finder | flickr/settings.py | Python | gpl-3.0 | 298 | 0 | # -*- coding: utf-8 -*-
import sys
import os
from os.path import d | irname
# Set the directory for using the modules in the same project such as eshop.
PROJECT_PATH = dirname(os.path.abspath(os.path.dirname(__file__)))
ESHOP_PATH = os.path.join(PROJECT_PATH, 'eshop/')
sys.path.append(PROJECT_PATH)
| |
pitunti/alfaPitunti | plugin.video.alfa/channels/anitoonstv.py | Python | gpl-3.0 | 6,699 | 0.005526 | # -*- coding: utf-8 -*-
import re
from channels import renumbertools
from channelselector import get_thumb
from core import httptools
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
from channels import autoplay
IDIO... | list.append(Item(channel=item.channel, action="lista", title="Pokemon", url=host,
thumbnail=thumb_series))
itemlist = renumbertools.show_option(item.channel, itemli | st)
autoplay.show_option(item.channel, itemlist)
return itemlist
def lista(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|\s{2}| ", "", data)
if 'Novedades' in item.title:
patron_cat = '<div class="activos"><h3>(.+?)<... |
tbeadle/django | tests/model_fields/test_booleanfield.py | Python | bsd-3-clause | 4,416 | 0.000226 | from django.core.exceptions import ValidationError
from django.db import IntegrityError, models, transaction
from django.test import SimpleTestCase, TestCase
from .models import BooleanModel, FksToBooleans, NullBooleanModel
class BooleanFieldTests(TestCase):
def _test_get_prep_value(self, f):
self.assert... | Model.objects.create(bfield=False)
b2.refresh_from_db()
self.assertEqual(b2.bfield, False)
b3 = NullBooleanModel.objects.create(nbfield=True)
b3.refresh_from_db()
self.assertEqual(b3.nbfield, True)
b4 = NullBooleanModel.objects.create(nbfield=False)
b4.refresh_f... | clause exists, the boolean conversions are applied with
# an offset (#13293).
b5 = BooleanModel.objects.all().extra(select={'string_col': 'string'})[0]
self.assertNotIsInstance(b5.pk, bool)
def test_select_related(self):
"""
Boolean fields retrieved via select_related() shou... |
dairdr/voteapp | voteapp/apps/vote/mixing.py | Python | mit | 1,724 | 0.020894 | # -*- coding: utf-8 -*-
"""Defines mixing class.
You can use it for inherit from Class Base Views, it was
developed by Timothée Peignier https://gist.github.com/cyberdelia/1231560
"""
from django.con | trib.auth.decorators import login_required
from django.utils.cache import patch_response_headers
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page, never_cache
from django.views.decorators.csrf import csrf_exempt
class NeverCacheMixin(object):
| @method_decorator(never_cache)
def dispatch(self, *args, **kwargs):
return super(NeverCacheMixin, self).dispatch(*args, **kwargs)
class LoginRequiredMixin(object):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
class CSRF... |
sprinkler/rainmachine-developer-resources | sdk-parsers/RMUtilsFramework/rmTimeUtils.py | Python | gpl-3.0 | 12,413 | 0.01007 | # Copyright (c) 2014 RainMachine, Green Electronics LLC
# All rights reserved.
# Authors: Nicu Pavel <npavel@mini-box.com>
# Codrin Juravle <codrin.juravle@mini-box.com>
from datetime import datetime, timedelta, tzinfo
from math import sin, cos, asin, acos, sqrt
import time, calendar
import ctypes,os, fcntl,... | tFormat)
def rmDayRange(startDayTimestamp, numDays):
d = datetime.fromtimestamp(startDayTimestamp)
if numDays >=0:
dateList = [int(time.mktime( (d + timedelta(days=x)).timetuple() )) for x in range(0, numDays)]
else:
numDays = -numDays
dateList = [int(time.mktim | e( (d - timedelta(days=x)).timetuple() )) for x in range(0, numDays)]
return dateList
def rmDeltaDayFromTimestamp(startDayTimeStamp, deltaDays):
d = datetime.fromtimestamp(startDayTimeStamp)
if deltaDays < 0:
d = d - timedelta(days=-deltaDays)
else:
d = d + timedelta(days=deltaDays)
... |
Micronaet/micronaet-production | working_bom/__openerp__.py | Python | agpl-3.0 | 1,492 | 0.00067 | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: yo | u can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY... | ls.
#
# 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/>.
#
###############################################################################
{
'name': 'BOM for working process',
'version': '0.1',
'category':... |
open-dai/bcn-lleida-opendai-pilots | web-geo-server/admin_web/wsgi.py | Python | lgpl-3.0 | 1,160 | 0.001724 | """
WSGI config for opendai_lleida_web project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APP... | ication object is used by any WSGI server configured to use this
# file. This includes | Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
great-expectations/great_expectations | great_expectations/data_asset/__init__.py | Python | apache-2.0 | 77 | 0 | from .data_ass | et import DataAs | set
from .file_data_asset import FileDataAsset
|
doubleO8/versionone-sdk-spoon | versio9/tests/__init__.py | Python | bsd-3-clause | 49 | 0 | impo | rt connect_tests
import string_utils_tests
| |
bjweiqm/Sele | school/pachong/video_db.py | Python | gpl-2.0 | 534 | 0.002 | #!/usr/bin/env python
# encoding:utf-8
"""
@software: PyCharm
@file: video_db.py
@time: 2016 | /8/4 16:56
"""
import sqlite3
class Create_DB():
def __init__(self):
self.conn = sqlite3.connect('video.db')
self.cn = self.conn.curs | or()
def create_table(self, table):
# 创建表格 table == 创建表命令
self.cn.execute(table)
def insert_db(self):
# 插入数据
pass
def select_db(self):
# 查询数据
pass
if __name__ == '__main__':
pass
|
j5shi/Thruster | pylibs/test/test_site.py | Python | gpl-2.0 | 15,991 | 0.001688 | """Tests for 'site'.
Tests assume the initial paths in sys.path once the interpreter has begun
executing have not been removed.
"""
import unittest
from test.test_support import run_unittest, TESTFN, EnvironmentVarGuard
from test.test_support import captured_output
import __builtin__
import os
import sys
... | code for testing results of reading a .pth file"""
self.assertIn(pth_file.imported, sys.modules,
"%s not in sys.modules" % pth_file.imported)
self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
self.assertFalse(os.path.exists(pth_file.bad_dir_path))
... | h for any line in the file that is not a
# comment or import that is a valid directory name for where the .pth
# file resides; invalid directories are not added
pth_file = PthFile()
pth_file.cleanup(prep=True) # to make sure that nothing is
# p... |
uclouvain/OSIS-Louvain | education_group/tests/ddd/factories/domain/campus.py | Python | agpl-3.0 | 1,589 | 0.00063 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculti | es, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyri | ght (C) 2015-2020 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... |
wolfiex/ipython-dev-reload | setup.py | Python | mit | 529 | 0.009452 | from setuptools import setup
def readme():
| with open('README.md') as f:
return f.read()
## test with python setup.py develop
setup(
name='ipyreload',
packages=['ipyreload'],
version= 1.2,
description='ipython productivity tools',
long_description=readme(),
url="https://github.com/wolfiex/ipython-dev-reload",
... | ail='daniel.ellis.research@gmail.com',
license='MIT',
zip_safe=False)
|
dslackw/slpkg | slpkg/url_read.py | Python | gpl-3.0 | 1,692 | 0.000591 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# url_read.py file is part of slpkg.
# Copyright 2014-2021 Dimitris Zlatanidis <d.zlatanidis@gmail.com>
# All rights reserved.
# Slpkg is a user-friendly package manager for Slackware installation | s
# https://gitl | ab.com/dslackw/slpkg
# Slpkg is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be... |
chinmaygarde/flutter_engine | tools/dia_dll.py | Python | bsd-3-clause | 2,094 | 0.011939 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This script is based on chromium/chromium/master/tools/clang/scripts/update.py.
It is used on Windows platforms to copy the co... | R = os.path.abspath(os.path.dirname(__file__))
LLVM_BUILD_DIR = os.path.abspath(os.path.join(THIS_DIR, '..', '..', 'third_party',
'llvm-build', 'Release+Asserts'))
def GetDiaDll():
"""Get the location of msdia*.dll for the platform."""
# Bump after VC updates.
DIA_... | ,
'2019': 'msdia140.dll',
}
# Don't let vs_toolchain overwrite our environment.
environ_bak = os.environ
sys.path.append(os.path.join(THIS_DIR, '..', '..', 'build'))
import vs_toolchain
win_sdk_dir = vs_toolchain.SetEnvironmentAndGetSDKDir()
msvs_version = vs_toolchain.GetVisualStudioVersion()
if... |
fintech-circle/edx-platform | openedx/core/djangoapps/auth_exchange/views.py | Python | agpl-3.0 | 7,236 | 0.002349 | """
Views to support exchange of authentication credentials.
The following are currently implemented:
1. AccessTokenExchangeView:
3rd party (social-auth) OAuth 2.0 access token -> 1st party (open-edx) OAuth 2.0 access token
2. LoginWithAccessTokenView:
1st party (open-edx) OAuth 2.0 access token -... | django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from edx_oauth2_provider.constants import SCOPE_VALUE_DICT
| from oauth2_provider.settings import oauth2_settings
from oauth2_provider.views.base import TokenView as DOTAccessTokenView
from oauthlib.oauth2.rfc6749.tokens import BearerToken
from provider import constants
from provider.oauth2.views import AccessTokenView as DOPAccessTokenView
from rest_framework import permissions... |
wallarelvo/eneza-server | smsserver/poolmember.py | Python | apache-2.0 | 584 | 0.001712 |
import android
class SMSPoolMember:
def __init__(self, query):
self.droid = android.Android()
self.query = str(query).lstrip().rstrip()
def wifiConnected(self):
none = "<unknown ssid>"
return not self.droid.wifiGetConnectionInfo().result["ssid"] == none
def dataConnected... | on":
return "pool:" + str(self.wifiConnected() | or self.dataConnected())
else:
return "pool: None"
|
xialeiliu/RankIQA | src/MyLossLayer/netloss_tid2013.py | Python | mit | 1,910 | 0.013613 | import caffe
import numpy as np
import pdb
class MyLossLayer(caffe.Layer):
"""Layer of Efficient Siamese loss function."""
def setup(self, bottom, top):
self.margin = 10
print '*********************** SETTING UP'
pass
def forward(self, bottom, top):
"""The parameters here ... | 0].num,dtype=np.float32)
for k in range(dis) | :
for i in range(SepSize*k,SepSize*(k+1)-batch):
for j in range(SepSize*k + int((i-SepSize*k)/batch+1)*batch,SepSize*(k+1)):
if self.loss[index]>0:
self.ref[i] += -1
self.ref[j] += +1
index +=1
#... |
qwercik/brainfuckOS | utils/align-to-full-sector.py | Python | mit | 467 | 0 | #!/usr/bin/env python3
import sys
if len(sys.argv) != 2:
raise SystemExit('Incorrect usage. Use: ' + sys.argv[0] + ' <image.img>')
image_filename = sys.argv[1]
content = ''
with open(image_filename, 'rb') as f:
content = bytearray(f.read())
bytes_to_append = 512 - | len(content) % 512
for i in range(bytes_to_append):
content.append(0)
with open(image_filename, 'wb') as f:
f.write(content)
print('Successfully | aligned to sector')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.