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
fogcitymarathoner/djfb
facebook_example/django_facebook/settings.py
Python
bsd-3-clause
3,806
0.001839
from django.conf import settings # these 3 should be provided by your app FACEBOOK_APP_ID = getattr(settings, 'FACEBOOK_APP_ID', None) FACEBOOK_APP_SECRET = getattr(settings, 'FACEBOOK_APP_SECRET', None) FACEBOOK_DEFAULT_SCOPE = getattr(settings, 'FACEBOOK_DEFAULT_SCOPE', [ 'email', 'user_about_me', 'user_...
if you want to store friends or likes FACEBOOK_CELERY_STORE = getattr(settings, 'FACEBOOK_CELERY_STORE', False) # use celery for updating tokens, recommended since it's quite slow FACEBOOK_CELERY_TOKEN_EXTEND = getattr( settings, 'FACEBOOK_CELERY_TOKEN_EXTEND', False) FACEBOOK_DEBUG_REDIRECTS = getattr(setti...
attr(settings, 'FACEBOOK_READ_ONLY', False) # check for required settings required_settings = ['FACEBOOK_APP_ID', 'FACEBOOK_APP_SECRET'] locals_dict = locals() for setting_name in required_settings: setting_available = locals_dict.get(setting_name) is not None assert setting_available, 'Please provide s...
thomasballinger/trellocardupdate
trellocardupdate/local.py
Python
isc
1,142
0.007881
from clint import resources import json resources.init('thomasballinger', 'trello-card-updater') #being used as though they have in-memory caches class LocalStorage(object): def __init__(self, name): object.__setattr__(self, 'res', getattr(resources, name)) def __getattr__(self, att): s = self...
= json.loads(s) return data def __setattr__(self, att, data): s = json.dumps(data) self.res.write(att, s) def __getitem__(self, key): return getattr(self, key) def __setitem__(self, key, value): setattr(self, key, value) class LocalObfuscatedStorage(LocalStorage): ...
use, but should avoid card names being indexed""" def __getattr__(self, att): s = self.res.read(att) if s is None: return None data = json.loads(s.encode('rot13')) return data def __setattr__(self, att, data): s = json.dumps(data).encode('rot13') self...
mrquim/repository.mrquim
repo/plugin.video.live.ike/websocket/tests/.py.py
Python
gpl-2.0
123
0.01626
[{"url": "https://raw.github
usercontent.com/ikesuncat/listas/master/Addon.xml", "fanart": ".\\fanart.jpg", "title": "Ike"}
]
chengjun/iching
setup.py
Python
mit
3,708
0.00027
"""iching. See: https://packaging.python.org/en/latest/distributing.html https://github.com/chengjun/iching """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) ...
ption=long_description, # The project's main homepage. url='https://github.com/chengjun/iching',
# Author details author='Cheng-Jun Wang', author_email='wangchj04@gmail.com', # Choose your license license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta ...
azavea/nyc-trees
src/nyc_trees/apps/core/migrations/0017_group_affiliation.py
Python
agpl-3.0
470
0
# -*- coding: utf-8 -*- from __future__ import unicode_liter
als from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0016_remove_user_is_census_admin'), ] operations = [ migrations.AddField( model_name='group', name='affiliation', field=models.CharField(def...
erve_default=True, ), ]
fqez/JdeRobot
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_relay.py
Python
gpl-3.0
3,625
0.007172
#!/usr/bin/env python '''relay handling module''' import time from pymavlink import mavutil from MAVProxy.modules.lib import mp_module class RelayModule(mp_module.MPModule): def __init__(self, mpstate): super(RelayModule, self).__init__(mpstate, "relay") self.add_command('relay', self.cmd_relay, "...
print("Usage: relay <set|repeat>") return if args[0] == "set": if len(args) < 3: print("Usage: relay set <RELAY_NU
M> <0|1>") return self.master.mav.command_long_send(self.target_system, self.target_component, mavutil.mavlink.MAV_CMD_DO_SET_RELAY, 0, int...
jardiacaj/finem_imperii
account/tests.py
Python
agpl-3.0
8,495
0.001766
from django.contrib import auth from django.contrib.auth.models import User from django.test import TestCase from django.urls.base import reverse class TestAccountRegistration(TestCase): def setUp(self): # create one user for convenience response = self.client.post( reverse('account:re...
'Alice2000', 'email': 'alice
@localhost', 'password': 'supasecret', 'password2': 'supasecret', }, follow=True ) self.assertEqual(response.redirect_chain[0][1], 302) self.assertEqual(response.redirect_chain[0][0], reverse('account:register')) self.assertEqual(re...
edonyM/toolkitem
fileprocess/mergefile/filebuf.py
Python
mit
5,258
0.003233
# -*- coding: utf-8 -*- r""" # .---. .----------- # / \ __ / ------ # / / \( )/ ----- (`-') _ _(`-') <-. (`-')_ # ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .-> # //// / // : : --- (,------. \ .'_ (`-')----. ,...
lay model';'foreground';'background'm DETAILS:
FOREGROUND BACKGOUND COLOR --------------------------------------- 30 40 black 31 41 red 32 42 green 33 43 yellow 34 44 ...
RayYu03/pysoccer
soccer/data/leagueproperties.py
Python
mit
1,439
0.004864
__all__ = ['LEAGUE_PROPERTIES'] LEAGUE_PROPERTIES = { "PL": { "rl": [18, 20], "cl": [1, 4], "el": [5, 5], }, "EL1": { "rl": [21, 24], "cl": [1, 2], "el": [3, 6] }, "EL2": { "rl": [21, 24], "cl": [1, 2], "el": [3, 6] }, ...
"FL2": { "rl": [18, 20], "cl": [1, 3], "el": [0, 0] }, "SB": { "rl": [19, 22], "cl": [1, 2], "el": [3, 6] }, "ENL": { "rl": [22, 24], "cl": [1,2],
"el": [3,6] }, }
ooici/coi-services
ion/services/sa/observatory/test/test_observatory_negotiation.py
Python
bsd-2-clause
2,839
0.00951
#from interface.services.icontainer_agent import ContainerAgentClient #from pyon.ion.endpoint import ProcessRPCClient from pyon.public import Container, log, IonObject from pyon.util.containers import DotDict from pyon.util.int_test import IonIntegrationTestCase from interface.services.coi.iresource_registry_service i...
ManagementServiceClient from pyon.util.context import LocalContextMixin from pyon.core.exception import BadRequest, NotFound, Conflict, Inconsistent from pyon.public import RT, PRED #from mock import Mock, patch from pyon.util.unit_test import PyonTestCase from nose.plugins.attrib import attr import unittest from ooi....
apabilities not yet available') class TestObservatoryNegotiation(IonIntegrationTestCase): def setUp(self): # Start container self._start_container() self.container.start_rel_from_url('res/deploy/r2deploy.yml') self.rrclient = ResourceRegistryServiceClient(node=self.container.node) ...
stableShip/tornado_chatRoom
TcpServer.py
Python
mit
1,361
0.005878
# coding=utf-8 import time import datetime __author__ = 'JIE' #! /usr/bin/env python #coding=utf-8 from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop class Conn
ection(object): clients = set() def __init__(self, stream, address): Connection.clients.add(self) self._stream = stream self._address = address self._stream.set_close_callback(self.on_close) self.read_message() print "A new user has entered the chat room.", addr
ess def read_message(self): self._stream.read_until('\n', self.broadcast_messages) def broadcast_messages(self, data): print "User said:", data[:-1], self._address for conn in Connection.clients: conn.send_message(data) self.read_message() def send_message(self...
niknow/BankCSVtoQif
setup.py
Python
gpl-2.0
1,329
0
# -*- coding: utf-8 -*- # BankCSVtoQif - Smart conversion of csv files from a bank to qif # Copyright (C) 2015-2016 Nikolai Nowaczyk # # 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 v...
T 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 General Public
License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from setuptools import setup, find_packages version = "0.0.1" setup( name='bankcsvtoqif', version=version, description='Smart conversion of csv files fro...
bvisness/the-blue-alliance
tests/test_add_match_times.py
Python
mit
3,491
0.002292
import datetime import unittest2 from google.appengine.ext import testbed from consts.event_type import EventType from datafeeds.usfirst_matches_parser import UsfirstMatchesParser from helpers.match_helper import MatchHelper from models.event import Event from models.match import Match class TestAddMatchTimes(unitt...
start_date=datetime.datetime(2014, 3, 8, 0, 0), end_date=datetime.datetime(2014, 3, 9, 0, 0), # chosen to span DST change year=2014, timezone_id="America/Los_Angeles", ) def match_dict_to_matches(self, match_dicts): return [Match( id=Match.render...
match_dict.get("match_number", 0)), event=self.event.key, year=self.event.year, set_number=match_dict.get("set_number", 0), match_number=match_dict.get("match_number", 0), comp_level=match_dict.get("comp_level", None), team_key_names=match_di...
czhengsci/veidt
veidt/potential/tests/name/get_data.py
Python
bsd-3-clause
312
0.003205
from pymacy.db import get_db f
rom bson.json_util import dumps db = get_db() results = [] count = 0 for i in db.benchmark.find({"element": "Ni"}): count += 1 if count > 100: break results.append(i) print(results[0]) with open("Ni.json", 'w') as f: file = dumps(results)
f.write(file)
orezpraw/partycrasher
partycrasher/config_loader.py
Python
gpl-3.0
1,971
0.002029
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2017 Joshua Charles Campbell # 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 o...
tance(o, dict), isinstance(o, float), isinstance(o, list), isinstance(o, int), isinstance(o, string_types) ), o return o def resti
fy(self): d = {} for k, v in self._config.items(): if '__' not in k: x = self.restify_class(v) d[k] = x return d
CodeSheng/LPLHW
ex16-3.py
Python
apache-2.0
619
0.003231
from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want
that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename,'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1:") line2 = raw_input("line 2:") line3 = raw_in...
int "And finally, we close it." target.close()
alexis-roche/nipy
nipy/modalities/fmri/tests/test_hrf.py
Python
bsd-3-clause
3,668
0.000545
""" Testing hrf module """ from __future__ import absolute_import from os.path import dirname, join as pjoin import numpy as np from scipy.stats import gamma import scipy.io as sio from ..hrf import ( gamma_params, gamma_expr, lambdify_t, spm_hrf_compat, spmt, dspmt, ddspmt, ) from ...
get values L1t = gf(t) L2t = lambdify_t(g_exp)(t) # they are the same bar a scaling factor nz = np.abs(L1t) > 1e-15 sf = np.mean(L1t[nz] / L2t[nz]) assert_almost_equal(L1t , L2t*sf) def test_spm_hrf(): # Regression tests for spm hrf, time derivative and dispersion derivative # Ch
eck that absolute values don't change (much) with different dt, and that # max values are roughly the same and in the same place in time for dt in 0.1, 0.01, 0.001: t_vec = np.arange(0, 32, dt) hrf = spmt(t_vec) assert_almost_equal(np.max(hrf), 0.21053, 5) assert_almost_equal(t_v...
UCSC-nanopore-cgl/nanopore-RNN
nanotensor/visualization/plot_raw_read_alignment.py
Python
mit
7,635
0.002489
#!/usr/bin/env python """Plot information needed file""" ######################################################################## # File: plot_raw_read_alignment.py # executable: plot_raw_read_alignment.py # # Author: Andrew Bailey # History: Created 12/01/17 ###########################################################...
esegment)) for j, segment in enumerate(old_events): x0 = segment["start"]
x1 = x0 + segment["length"] if dna: x0 = (x0 - (start_time / sampling_freq)) * sampling_freq x1 = (x1 - (start_time / sampling_freq)) * sampling_freq if start < x0 < (start + window_size): kmer = segment["model_state"] mean = segment['mean'] ...
JoelBender/bacpypes
py34/bacpypes/object.py
Python
mit
139,323
0.026715
#!/usr/bin/python """ Object """ import sys from copy import copy as _copy from collections import defaultdict from .errors import ConfigurationError, ExecutionError, \ InvalidParameterDatatype from .debugging import bacpypes_debugging, ModuleLogger from .primitivedata import Atomic, BitString, Boolean, Charact...
Policy, AuthenticationStatus, \ AuthorizationException, AuthorizationMode, BackupState, BDTEntry, BinaryPV, \ COVSubscription, CalendarEntry, ChannelValue, ClientC
OV, \ CredentialAuthenticationFactor, DailySchedule, DateRange, DateTime, \ Destination, DeviceObjectPropertyReference, DeviceObjectReference, \ DeviceStatus, DoorAlarmState, DoorSecuredStatus, DoorStatus, DoorValue, \ EngineeringUnits, EventNotificationSubscription, EventParameter, \ EventState, Ev...
gadsbyfly/PyBioMed
PyBioMed/Pymolecule.py
Python
bsd-3-clause
16,673
0.00036
# -*- coding: utf-8 -*- # Copyright (c) 2016-2017, Zhijiang Yao, Jie Dong and Dongsheng Cao # All rights reserved. # This file is part of the PyBioMed. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the PyBioMed source tree. """ #####...
######################################################## """ res = getmol.GetMolFromCAS(casid=ID) return res def GetMolFromKegg(self, ID=""): """ ################################################################# Get a molecule by kegg id (e.g., D02176). Usag...
###################################################### """ res = getmol.GetMolFromKegg(kid=ID) return res def GetMolFromDrugbank(self, ID=""): """ ################################################################# Get a molecule by drugbank id (e.g.,DB00133). ...
nicolargo/pymdstat
docs/conf.py
Python
mit
8,164
0.006247
# -*- coding: utf-8 -*- # # pymdstat documentation build configuration file, created by # sphinx-quickstart on Sat Dec 20 16:43:07 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated
file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os #
If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration -------------...
youtube/cobalt
third_party/v8/test/debugging/wasm/gdb-server/memory.py
Python
bsd-3-clause
3,599
0.015004
# Copyright 2020 the V8 project authors. All rights r
eserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Flags: -expose-wasm --wasm-gdb-remote --wasm-pause-waiting-for-debugger test/debugging/wasm/gdb-server/test_files/test_memory.js import struct import sys import unittest import gdb_rsp import test_files.t...
n(). COMMAND = None class Tests(unittest.TestCase): # Test that reading from an unreadable address gives a sensible error. def CheckReadMemoryAtInvalidAddr(self, connection): mem_addr = 0xffffffff result = connection.RspRequest('m%x,%x' % (mem_addr, 1)) self.assertEquals(result, 'E02') def RunToWasm...
VishvajitP/readthedocs.org
readthedocs/privacy/backend.py
Python
mit
6,504
0.000461
from django.db import models from guardian.shortcuts import get_objects_for_user from readthedocs.builds.constants import LATEST from readthedocs.builds.constants import LATEST_VERBOSE_NAME from readthedocs.builds.constants import STABLE from readthedocs.builds.constants import STABLE_VERBOSE_NAME from readthedocs.p...
t() def public(self, user=None, project=None, only_active=True, *args, **kwargs): queryset = self.filter(project__privacy_level=constants.PUBLIC, privacy_level=constants.PUBLIC) if user: queryset = self._add_user_repos(queryset, user) if project: ...
queryset = queryset.filter(active=True) return queryset def api(self, user=None, *args, **kwargs): return self.public(user, only_active=False) def create_stable(self, **kwargs): defaults = { 'slug': STABLE, 'verbose_name': STABLE_VERBOSE_NAME, 'm...
702nADOS/sumo
tools/projects/TaxiFCD_Krieg/src/fcdQuality/ParamEffectsOLD.py
Python
gpl-3.0
7,647
0.001308
#!/usr/bin/env python # -*- coding: Latin-1 -*- """ @file ParamEffectsOLD.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-07-26 @version $Id: ParamEffectsOLD.py 22608 2017-01-17 06:28:54Z behrisch $ Creates files with a comparison of speeds for each edge between the taxis...
.find("<interval") != -1 and int(words[1]) >= simStartTime: interval = int(words[1]) begin = True if begin and words[0].find("<edge id") != -1: edge = words[1] speed = float(words[13]) edgeDumpDict.setdefault(interval, []).append((edge, speed)) inp...
Dict def readVtype(): """Gets all necessary information of all vehicles.""" vtypeDict = {} timestep = 0 begin = False inputFile = open(vtypePath, 'r') for line in inputFile: words = line.split('"') if words[0].find("<timestep ") != -1 and int(words[1]) >= simStartTime: ...
endlessm/chromium-browser
tools/swarming_client/third_party/pyasn1/pyasn1/compat/binary.py
Python
bsd-3-clause
698
0
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pyasn1/license.html # from sys import version_info if version_info[0:2] < (2,
6): def bin(value): bitstring = [] if value > 0: prefix = '0b' elif value < 0: prefix = '-0b' value = abs(value) else: prefix = '0b0' while value: if value & 1 == 1: bitstring.append('1') ...
return prefix + ''.join(bitstring) else: bin = bin
oriel-hub/api
django/idsapi/openapi/tests/search_wrapper.py
Python
gpl-2.0
14,005
0.003499
import pytest import unittest from os import path from django.test import SimpleTestCase from django.conf import settings from rest_framework.renderers import BaseRenderer import sunburnt from openapi.search_builder import ( SearchBuilder, SearchWrapper, InvalidFieldError, InvalidQueryError, Unkno...
field_list) def test_request_score_pseudo_field(self): sw = SearchWrapper('Unlimited', 'eldis', self.msi) sw.restrict_fields_returned('short', {'extra_fields': 'score'}) self.a
ssertTrue(self.msi.query.score) class SearchWrapperAddSortTests(unittest.TestCase): def setUp(self): self.msi = MockSolrInterface() settings.SORT_MAPPING = {'dummy': 'dummy_sort'} def test_add_sort_method_disallows_mixed_asc_and_desc_sort(self): sw = SearchWrapper('General User', 'eld...
FederatedAI/FATE
python/fate_client/flow_sdk/client/api/base.py
Python
apache-2.0
1,520
0
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
t: return self._handle_result(self._client.get(url, **kwargs)) else: return self._client.get(url, **kwargs) def _post(self, url, handle_result=True, **kwargs): if handle_result
: return self._handle_result(self._client.post(url, **kwargs)) else: return self._client.post(url, **kwargs) def _handle_result(self, response): return self._client._handle_result(response) @property def session(self): return self._client.session @prope...
espressopp/espressopp
src/integrator/CapForce.py
Python
gpl-3.0
2,764
0.006874
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the t
erms 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. # # ESPResSo++ 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 re...
google/timesketch
api_client/python/timesketch_api_client/credentials.py
Python
apache-2.0
5,272
0.000379
# Copyright 2020 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 a...
erialize(self): """Return serialized bytes object.""" data = self.to_bytes() type_string = bytes(self.TYPE, 'utf-8').rjust(10)[:10] return type_string + data def deserialize(self, data): """Deserialize a credential object from bytes. Args: data (bytes):...
g): raise TypeError('Not the correct serializer.') self.from_bytes(data[10:]) def to_bytes(self): """Convert the credential object into bytes for storage.""" raise NotImplementedError def from_bytes(self, data): """Deserialize a credential object from bytes. ...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/ip_configuration_py3.py
Python
mit
2,962
0.005064
# 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 ...
, 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, *, id: str=None, private_ip_address: str=None, private_ip_allocation_method=None, subnet=None, public_ip_address=None, provisioning_state: str=None, name: str=None, etag: str=N...
id=id, **kwargs) self.private_ip_address = private_ip_address self.private_ip_allocation_method = private_ip_allocation_method self.subnet = subnet self.public_ip_address = public_ip_address self.provisioning_state = provisioning_state self.name = name self.etag =...
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/NV/register_combiners.py
Python
lgpl-3.0
5,260
0.043536
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _...
p.types(None,_cs.GLenum,arrays.GLintArray) def glCombinerParameterivNV(pname,params):pass @_f @_p.types(None,_cs.GLenum,_cs.GLenum,
_cs.GLenum,_cs.GLenum) def glFinalCombinerInputNV(variable,input,mapping,componentUsage):pass @_f @_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLenum,_cs.GLenum,arrays.GLfloatArray) def glGetCombinerInputParameterfvNV(stage,portion,variable,pname,params):pass @_f @_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLenum,_cs.GLenum,a...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/request_state.py
Python
bsd-3-clause
2,810
0.008897
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
ks until
all threads for this request finish.""" thread_id = threading.current_thread().ident with self._condition: self._threads.remove(thread_id) while self._threads: self._condition.wait() def inject_exception(self, exception): """Injects an exception to all threads running as part of this...
midonet/midonet-sandbox
src/midonet_sandbox/logic/composer.py
Python
apache-2.0
9,157
0.000655
# Copyright (c) 2015 Midokura SARL, All Rights Reserved. # # @author: Antonio Sagliocco <antonio@midokura.com>, Midokura import logging import subprocess from collections import Counter import os from injector import inject, singleton from requests.exceptions import ConnectionError from yaml import load from midonet_s...
ne, no_recreate=False, ve
rbose=False): """ :param flavour: The flavour name :param name: The sandbox name :param force: Force restarting without asking :param override: An override path :param provision: A provisioning script path :param no_recreate: Do not recreate containers if they exi...
DayGitH/Python-Challenges
DailyProgrammer/20120430B.py
Python
mit
1,804
0.005543
""" Consider this game: Write 8 blanks on a sheet of paper. Randomly pick a digit 0-9. After seeing the digit, choose one of the 8 blanks to place that digit in. Randomly choose another digit (with replacement) and then choose one of the 7 remaining blanks to place it in. Repeat until you've filled all 8 blanks. You wi...
i = int(d * (len(p)) / 10) pri
nt(p[i]) l[p[i]] = d p.pop(i) print(l) if que_sort(l): win += 1 print('{}/{} - {}%'.format(win, TRIALS, win/TRIALS*100))
Ritiek/Spotify-Downloader
spotdl/__init__.py
Python
mit
84
0.011905
from spotdl.version import __version__ from spotdl.com
mand_line.c
ore import Spotdl
astagi/taiga-back
taiga/projects/api.py
Python
agpl-3.0
20,069
0.001495
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014 David Barragán <bameda@dbarragan.com> # 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 F...
option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of th...
this program. If not, see <http://www.gnu.org/licenses/>. import uuid from django.db.models import signals from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ from taiga.base import filters from taiga.base import response from taiga.base import exceptions as exc fro...
TomBurnett/BlenderGameEngineJavabot
Scripts/Camera-Scripts/Mouselook.py
Python
gpl-2.0
5,772
0.04851
###################################################### # # MouseLook.py Blender 2.55 # # Tutorial for using MouseLook.py can be found at # # www.tutorialsforblender3d.com # # Released under the Creative Commons Attribution 3.0 Unported License. # # If you use this code, please include this information ...
False # get controller controller = bge.logic.getCurrentController() # get the object this script is attached to obj = controller.owner # get the size of the game screen gameScreen = gameWindow() # get mouse movement move = mouseMove(gameScreen, controller,
obj) # change mouse sensitivity? sensitivity = mouseSen(Sensitivity, obj) # invert mouse pitch? invert = mousePitch(Invert, obj) # upDown mouse capped? capped = mouseCap(Capped, move, invert, obj) # use mouse look useMouseLook(controller, capped, move, invert, sensitivity) # Center mouse in game w...
plotly/plotly.py
packages/python/plotly/plotly/validators/bar/marker/_colorbar.py
Python
mit
12,732
0.000079
import _plotly_utils.basevalidators class ColorbarValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="colorbar", parent_name="bar.marker", **kwargs): super(ColorbarValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
showtickprefix If "all", all tick labels are displayed with a prefix. If
"first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness ...
samirelanduk/molecupy
atomium/pdb.py
Python
mit
23,845
0.001636
"""Contains functions for dealing with the .pdb file format.""" from datetime import datetime import re from itertools import groupby, chain import valerius from math import ceil from .data import CODES from .structures import Residue, Ligand from .mmcif import add_secondary_structure_to_polymers def pdb_string_to_pd...
tion_dict["classification"] = line[10:50].strip() def extract_title(pdb_dict, description_dict): """Takes a ``dict`` and adds header information to it by parsing the TITLE lines. :param dict pdb_dict: the ``dict`` to read. :param dict description_dict: the ``dict`` to update.""" if pdb_dict.get(...
ords(pdb_dict, description_dict): """Takes a ``dict`` and adds header information to it by parsing the KEYWDS line. :param dict pdb_dict: the ``dict`` to read. :param dict description_dict: the ``dict`` to update.""" if pdb_dict.get("KEYWDS"): text = merge_lines(pdb_dict["KEYWDS"], 10) ...
drewcsillag/skunkweb
pylibs/DT/dtrun.py
Python
gpl-2.0
911
0.024149
# # Copyright (C) 2001 Andrew T. Csillag <drew_csillag@geocities.com> # # You may distribute under the terms of either the GNU General # Public License or the SkunkWeb License, as specified in the # README file. # import os import DT import sys import time import marshal import stat def phf...
= time.t
ime() print text print 'elapsed time:', et - bt
thauser/pnc-cli
test/integration/test_projects_api.py
Python
apache-2.0
2,376
0.001684
import pytest from pnc_cli import projects from pnc_cli.swagger_client.apis.projects_api import ProjectsApi from test import testutils import pnc_cli.user_config as uc @pytest.fixture(scope='function', autouse=True) def get_projects_api(): global projects_api projects_api = ProjectsApi(uc.user.get_api_client...
lete_specific(new_project.id) proj_ids = [x.id for x in projects_api.get_all(page_size=
1000000).content] assert new_project.id not in proj_ids
etkirsch/Tensorflow-Learn
introduction.py
Python
gpl-2.0
1,175
0
''' Non-original introduction script, added solely for the sake of familiarizing myself with Tensorflow. I, Evan Kirsch, do not claim credit whatsoever for this code. It is taken directly from https://www.tensorflow.org/ ''' import tensorflow as tf import numpy as np # Create 100 phony x, y data points in NumPy, y = ...
and b that compute y_data = W * x_data + b # (We know that W should be 0.1 and b 0.3, but Tensorflow will # figure that out for us.) W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) b = tf.Variable(tf.zeros([1])) y = W * x_data + b # Minimize the mean squared errors. loss = tf.reduce_mean(tf.square(y - y_data)) opt...
# Before starting, initialize the variables. We will 'run' this first. init = tf.initialize_all_variables() # Launch the graph. sess = tf.Session() sess.run(init) # Fit the line. for step in xrange(201): sess.run(train) if step % 20 == 0: print(step, sess.run(W), sess.run(b)) # Learns best fit is W...
zacharytamas/django-chelsea
chelsea/views/__init__.py
Python
isc
94
0.010638
from view import CView from template_view import CTemplateView from f
orm_
view import CFormView
temmeand/scikit-rf
qtapps/skrf_qtwidgets/networkPlotWidget.py
Python
bsd-3-clause
14,303
0.001678
from collections import OrderedDict from math import sqrt import numpy as np import pyqtgraph as pg from qtpy import QtWidgets import skrf from . import smith_chart, util class NetworkPlotWidget(QtWidgets.QWidget): S_VALS = OrderedDict(( ("decibels", "db"), ("magnitude", "mag"), ("phase ...
ate_plot) self.comboBox_traceSelector.currentIndexChanged.connect(self.update_plot) self.plot = self.plot_layout.addPlot() # type: pg.PlotItem self.
_ntwk = None self._ntwk_corrected = None self._corrected_data_enabled = True self._use_corrected = False self.corrected_data_enabled = kwargs.get('corrected_data_enabled', True) self.plot.addLegend() self.plot.showGrid(True, True) self.plot.setLabel("bottom", "fr...
DarthBubi/fallout-pnp-character-creator
character-creator/config.py
Python
mit
11,633
0.006804
from character import Trait, Perk __author__ = "Johannes Hackbarth" ALL_RACES = {"Deathclaw", "Dog", "Ghoul", "Half Mutant", "Human", "Robot", "Super Mutant"} ANIMALS = {"Deathclaw", "Dog"} ROBOTS = {"Robot"} # TODO: Add all effects to traits TRAIT_LIST = [ Trait("Fast Metabolism", "Your metabolic rate...
attack, because you attack faster than normal people. It costs you one " "less action point to use a weapon. You cannot perform targeted shots, but all weapons take one less action " "point to use. Note that the Fast Shot trait has no effect on HtH or Melee attacks. Animals cannot choose " ...
Trait("Bloody Mess", "By some strange twist of fate, people around you die violently. You always see the worst way a person can " "die. This does not mean you kill them any faster or slower, but when they do die, it will be dramatic. " "Just how dramatic is up to the Gamemaster.", ...
derekmoyes/opsy
opsy/shell.py
Python
mit
1,995
0
import os from flask import current_app from flask.cli import FlaskGroup, run_command from opsy.db import db from opsy.app import create_app, create_scheduler from opsy.utils import load_plugins DEFAULT_CONFIG = '%s/opsy.ini' % os.path.abspath(os.path.curdir) def create_opsy_app(info): return create_app(config=o...
ry: from IPython import embed embed(user_ns=shell_ctx, banner1=banner) return except ImportError: import code code.interact(banner, local=shell_ctx) @cli.command('init-cache') def init_cache(): """Drop everything in cache database and rebuild the schema.""" current_...
info('Creating cache database') db.drop_all(bind='cache') db.create_all(bind='cache') db.session.commit() def main(): with create_opsy_app(None).app_context(): for plugin in load_plugins(current_app): plugin.register_cli_commands(cli) cli()
jinyu121/HowOldAreYou
HowOldWebsite/process/process_estimate_sex.py
Python
gpl-3.0
1,099
0
# -*- coding: UTF-8 -*- from HowOldWebsite.estimators.estimator_sex import EstimatorSex from HowOldWebsite.models import RecordSex __author__ = 'Hao Yu' def sex_estimate(database_face_array, feature_jar): success = False database_record = None try: n_faces = len(database_face_array) re...
tabase_record def __do_estimate(feature_jar, n_faces): feature = EstimatorSex.feature_combine(feature_jar) feature = EstimatorSex.feature_reduce(feature) result = EstimatorSex.estimate(feature) return result def __do_save_to_
database(database_face, sex): database_record = [] for ith in range(len(database_face)): record = RecordSex(original_face=database_face[ith], value_predict=sex[ith]) database_record.append(record) return database_record
acsone/alfodoo
cmis_field/models/__init__.py
Python
agpl-3.0
57
0
fr
om . import cmis_backend from . import ir_model_fie
lds
CognitionGuidedSurgery/msml
src/msml/io/mapper/abaqus2string_mapping.py
Python
gpl-3.0
3,374
0.024896
__author__ = 'suwelack' from msml.io.mapper.base_mapping import * import msml.model.generated.msmlScene as mod import msml.model.generated.abaqus as ab import msml.model.generated.msmlBase as mbase from jinja2 import Template, Environment, PackageLoader class Abaqus2StringMapping(BaseMapping): def __init__(sel...
ap_pre(ab.Part) def map_Part_pre(self, element,parent_source,parent_target, source,target): template = self._env.get_template('Part_template.html') returnStr = template.render(id=element.id) target.append(returnStr) return target, mod.MeshDataObject @complet
e_map_post(ab.Part) def map_Part_post(self, element,parent_source,parent_target,source,target): return None,None @complete_map_pre(mod.MeshDataObject) def map_MeshDataObject_pre(self, element,parent_source,parent_target, source,target): template = self._env.get_template('MeshDataObject_te...
SafPlusPlus/pyweek19
run_game.py
Python
apache-2.0
73
0
import pw19.__main__ if _
_na
me__ == "__main__": pw19.__main__.main()
PercussiveRepair/elastatus
app/views.py
Python
mit
6,380
0.002821
from flask import * import os from decorators import validate_account_and_region from aws import connect from sgaudit import get_reports, add_description from app.models import IPWhitelist elastatus = Blueprint('elastatus', __name__) @elastatus.route('/') def index(): default_account = current_app.config['CONFI...
ec2') instances = c.get_only_instances() return
render_template('ec2.html', region=region, instances=instances) @elastatus.route('/<account>/<region>/ami') @validate_account_and_region def ami(account, region): c = connect(account,region, 'ec2') amis = c.get_all_images(owners = ['self']) ami_list = {ami: c.get_image(ami.id) for ami in amis} return ...
Erotemic/local
misc/file_organizer.py
Python
gpl-3.0
15,764
0.001015
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import utool as ut from os.path import join, basename, splitext, exists, dirname # from utool import util_inject # print, rrr, profile = util_inject.inject2(__file__) @ut.reloadable_class class SourceDir(ut.Nice...
e=['full_path', 'dname']) def find_internal_duplicates(self): # First find which files take up the same amount of spa
ce nbytes = self.get_prop('nbytes') dups = ut.find_duplicate_items(nbytes) # Now evaluate the hashes of these candidates cand_idxs = ut.flatten(dups.values()) data = ut.ColumnLists({ 'idx': cand_idxs, 'fname': self.get_prop('fname', cand_idxs), ...
wangtaoking1/found_website
项目代码/bs4/tests/test_builder_registry.py
Python
gpl-2.0
5,374
0.001861
"""Tests of the builder registry.""" import unittest from bs4 import BeautifulSoup from bs4.builder import ( builder_registry as registry, HTMLParserTreeBuilder, TreeBuilderRegistry, ) try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError: HTML5LIB_PRESENT =...
has_the_other = self.builder_for_features('bar') has_both_early = self.builder_for_features('foo', 'bar', 'baz') has_both_late = self.builder_for_features('foo', 'bar', 'quux') lacks_one = self.builder_for_features('bar') has_the_other = self.builder_for_features('foo')
# There are two builders featuring 'foo' and 'bar', but # the one that also features 'quux' was registered later. self.assertEqual(self.registry.lookup('foo', 'bar'), has_both_late) # There is only one builder featuring 'foo', 'bar', and 'baz'. self.assertEqual...
rickerc/cinder_audit
cinder/tests/test_vmware_vmdk.py
Python
apache-2.0
78,544
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2013 VMware, 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.or...
"""Test failed wait_for_task.""" m = self.mox m.StubOutWithMock(api.VMwareAPISession, 'vim') self._session.vim = self._vim failed_t
ask_info = FakeTaskInfo('failed') m.StubOutWithMock(vim_util, 'get_object_property') vim_util.get_object_property(self._session.vim, mox.IgnoreArg(), 'info').AndReturn(failed_task_info) m.ReplayAll() self.assertRa...
sverchkov/ivancic-panel-selection
python/analysis_utilities.py
Python
mit
12,954
0.029643
#Serge Aleshin-Guendel #Utilities!!! # # import numpy import matplotlib.pyplot as plt import roc_ci from sklearn.metrics import roc_curve, auc from sklearn.cross_validation import LeaveOneOut from sklearn import preprocessing from matplotlib.backends.backend_pdf import PdfPages #Generate an ROC Curve def plotROC( fp...
10,linestyle="",markerfacecolor="k") plt.plot(0.05,0.74,marker='^',label="FIT",markersize=10,linestyle="",markerfacecolor="k") plt.plot(0.20,0.68,marker='s',label="Epi proColon",markersize=10,linestyle="",markerfacecolor="k") plt.plot(0.22,0.81,marker='p',label="SimplyPro Colon",markersize
=10,linestyle="",markerfacecolor="k") plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xticks(numpy.arange(0, 1.05, 0.1)) plt.yticks(numpy.arange(0, 1.05, 0.1)) plt.xlabel('1 - Specificty', fontsize=16) plt.ylabel('Sensitivity', fontsize=16) plt.title('Cross Va...
zhuyue1314/archinfo
setup.py
Python
bsd-2-clause
169
0.011834
from distu
tils.core import setup setup( name='archinfo', version='0.03', packages=['archinfo'], install_requires=[ 'capstone', 'pyelftools',
'pyvex' ] )
lucperkins/heron
heron/tools/tracker/src/python/handlers/metadatahandler.py
Python
apache-2.0
2,280
0.007456
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2017 Twitter. 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...
tornado.gen import tornado.web from
heron.common.src.python.utils.log import Log from heron.tools.tracker.src.python.handlers import BaseHandler # pylint: disable=attribute-defined-outside-init class MetaDataHandler(BaseHandler): """ URL - /topologies/metadata Parameters: - cluster (required) - environ (required) - role - (optional) Role...
xhan-shannon/SystemControlView
base/engine.py
Python
gpl-2.0
1,534
0.008541
#--*-- coding:utf-8 --*-- ''' Created on 2015��5��8�� @author: stm ''' from utils import DebugLog from base.msgcodec import MsgCodec from abc import abstractmethod from base.vdstate import CR
EATEVIOSLPAR_STAT, StateBase from base.cmdmsg import CMDMsg class EngineBase(object): ''' The engine would deal with the command from UI or command line. And it would respond the result to UI or command listener. ''' # o
bjs = {} # def __new__(cls, *args, **kv): # if cls in cls.objs: # return cls.objs[cls] # cls.objs[cls] = super(EngineBase, cls).__new__(cls) # def __init__(self, vd_comm_cnt, vd_config): ''' Constructor ''' DebugLog.info_print("En...
jhseu/tensorflow
tensorflow/python/ops/image_grad.py
Python
apache-2.0
15,566
0.015033
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ice # The first term in the addition is the case when the corresponding color # from (r,g,b) was "MAX" # -> derivative = MIN/square(MAX), MIN could be one of the other two colors # Th
e second term is the case when the corresponding color from # (r,g,b) was "MIN" # -> derivative = -1/MAX, MAX could be one of the other two colours. ds_dr = math_ops.cast(reds > 0, dtypes.float32) * \ math_ops.add(red_biggest * \ math_ops.add(green_smallest * greens, blue_smallest * ...
devcartel/pyrfa
examples/symbollist.py
Python
mit
814
0.001229
#!/usr/bin/
python # # Request for symbolList. Currently RFA only support refresh messages # for symbolList. Hence, polling is required and symbolListRequest is called # internally by getSymbolList. # # IMAGE/REFRESH: # ({'MTYPE':'REFRESH','RIC':'0#BMD','SERVICE':'NIP'}, # {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC'...
ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC':'0#BMD','KEY':'FKLM'}) # import pyrfa p = pyrfa.Pyrfa() p.createConfigDb("./pyrfa.cfg") p.acquireSession("Session3") p.createOMMConsumer() p.login() p.directoryRequest() p.dictionaryRequest() RIC = "0#BMD" symbolList = p.getSymbolList(RIC) print("\n=======\n" + RIC + "\n=====...
democracyworks/dog-catcher
south_carolina.py
Python
mit
12,842
0.027176
import sys import mechanize import re import json import time import urllib import dogcatcher import HTMLParser import os h = HTMLParser.HTMLParser() cdir = os.path.dirname(os.path.abspath(__file__)) + "/" tmpdir = cdir + "tmp/" voter_state = "SC" source = "State" result = [("authory_name", "first_name", "last_nam...
ail = "cholland@aikencountysc.gov" county.replace("cholland@aikencountysc.go
v","") phone = dogcatcher.find_phone(phone_re, county) for item in phone_re.findall(county): county = county.replace(item, "") #Many of the fax numbers don't have area codes. So we grab the first area code we find in the block of phone numbers and give it to the fax number. area_code = area_code_re.findall(pho...
martincochran/score-minion
list_id_bimap.py
Python
apache-2.0
4,643
0.005815
#!/usr/bin/env python # # Copyright 2015 Martin Cochran # # 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 la...
AgeBracket.NO_RESTRICTION: AUDL_LIST_ID, }, }, League.MLU: { Division.OPEN: { AgeBracket.NO_RESTRICTION: MLU_LIST_ID, }, }, } LIST_ID_TO_DIVISION = { USAU_COLLEGE_OPEN_LIST_ID: Division.OPEN, USAU_COLLEGE_WOMENS_LIST_ID: Division.WOMENS, USAU...
Division.MIXED, AUDL_LIST_ID: Division.OPEN, MLU_LIST_ID: Division.OPEN, } LIST_ID_TO_AGE_BRACKET = { USAU_COLLEGE_OPEN_LIST_ID: AgeBracket.COLLEGE, USAU_COLLEGE_WOMENS_LIST_ID: AgeBracket.COLLEGE, USAU_CLUB_OPEN_LIST_ID: AgeBracket.NO_RESTRICTION, USAU_CLUB_WOMENS_LIST_ID: Age...
mahabs/nitro
nssrc/com/citrix/netscaler/nitro/resource/config/appfw/appfwprofile_contenttype_binding.py
Python
apache-2.0
9,811
0.040261
# # Copyright (c) 2008-2015 Citrix 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.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
e return updateresource.update_resource(client) else :
if resource and len(resource) > 0 : updateresources = [appfwprofile_contenttype_binding() for _ in range(len(resource))] for i in range(len(resource)) : updateresources[i].name = resource[i].name updateresources[i].comment = resource[i].comment updateresources[i].state = resource[i].state ...
kevinsung/OpenFermion
src/openfermion/chem/pubchem_test.py
Python
apache-2.0
3,870
0.000258
# 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 # distribu...
h_1, self.water_bond_length_2, places=4) water_bond_length_low = 0.9 water_bond_length_high = 1.1 self.assertTrue(water_bond_leng
th_low <= self.water_bond_length_1) self.assertTrue(water_bond_length_high >= self.water_bond_length_1) water_bond_angle_low = 100. / 360 * 2 * numpy.pi water_bond_angle_high = 110. / 360 * 2 * numpy.pi self.assertTrue(water_bond_angle_low <= self.water_bond_angle) self.assertTr...
vijos/vj4
vj4/model/token.py
Python
agpl-3.0
3,999
0.012253
import binascii import datetime import hashlib import os from pymongo import ReturnDocument from vj4 import db from vj4.util import argmethod TYPE_REGISTRATION = 1 TYPE_SAVED_SESSION = 2 TYPE_UNSAVED_SESSION = 3 TYPE_LOSTPASS = 4 TYPE_CHANGEMAIL = 5 def _get_id(id_binary): return hashlib.sha256(id_binary).digest...
_type': {'$in': [TYPE_SAVED_SESSION, TYPE_UNSAVED_SESSION]}}, sort=[('update_at', -1)]
) return doc @argmethod.wrap async def get_session_list_by_uid(uid: int): """Get the session list by uid.""" coll = db.coll('token') return await coll.find({'uid': uid, 'token_type': {'$in': [TYPE_SAVED_SESSION, TYPE_UNSAVED_SESSION]}}, sort=[('create_at', 1)...
t3dev/odoo
addons/im_livechat/tests/test_get_mail_channel.py
Python
gpl-3.0
2,152
0.003253
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase class TestGetMailChannel(TransactionCase): def setUp(self): super(TestGetMailChannel, self).setUp() self.operators = self.env['res.users'].create([{ ...
nels 5 times (25 channels total). For every 5 channels opening, we check that all operators were assigned. """ for i in range(5): mail_channels = self._get_mail_channels() channel_operators = [chan
nel_info['operator_pid'] for channel_info in mail_channels] channel_operator_ids = [channel_operator[0] for channel_operator in channel_operators] self.assertTrue(all(partner_id in channel_operator_ids for partner_id in self.operators.mapped('partner_id').ids)) def _get_mail_channels(self):...
TheCamusean/DLRCev3
rick/rick/mc_please_github_donot_fuck_with_this_ones.py
Python
mit
16,563
0.059711
import numpy as np import math import time import random import sys from rick.A_star_planning import * from math import pi import matplotlib.pyplot as plt def compute_euclidean_path(pos_rob,pos_obj, points = 5): #pos_rob is a 1x3 matrix with(x,y,teta) & pos_obj is a 1x2 matrix with(x,y) x = np.linspace(pos_rob[0]...
t(path) return path ## Now this functionc compute a piecewise euclidean path with the intermediate point pos_1 def compute_piecewise_path(pos_rob,pos_1,pos_obj,points=10): x1=np.linspace(pos_rob[0],pos_1[0],num=round(points/2)) y1=np.linspace(pos_rob[1],pos_1[1],num=round(points/2)) x2=np.linspace(pos_1[0],pos_ob...
) angle1=math.atan2(pos_1[1]-pos_rob[1],pos_1[0]-pos_rob[0]) angle2=math.atan2(pos_obj[1]-pos_1[1],pos_obj[0]-pos_1[0]) angle1=math.degrees(angle1) angle2=math.degrees(angle2) if angle1<0: angle1=360-angle1 if angle2<0: angle2=360-angle2 angle_vec1 = np.ones(x1.shape) angle_vec2=np.ones(x2.shape) angl...
joke2k/django-environ
tests/fixtures.py
Python
mit
3,765
0.001328
# This file is part of the django-environ. # # Copyright (c) 2021, Serghei Iakovlev <egrep@protonmail.ch> # Copyright (c) 2013-2021, Daniele Faraglia <daniele.faraglia@gmail.com> # # For the full copyright and license information, please view # the LICENSE.txt file that was distributed with this source code. from envi...
0', BOOL_TRUE_STRING_LIKE_INT='1', BOOL_TRUE_INT=1, BOOL_TRUE_STRING_LIKE_BOOL='True', BOOL_TRUE_STRING_1='on',
BOOL_TRUE_STRING_2='ok', BOOL_TRUE_STRING_3='yes', BOOL_TRUE_STRING_4='y', BOOL_TRUE_STRING_5='true', BOOL_TRUE_BOOL=True, BOOL_FALSE_STRING_LIKE_INT='0', BOOL_FALSE_INT=0, BOOL_...
dekom/threepress-bookworm-read-only
bookworm/django_evolution/management/__init__.py
Python
bsd-3-clause
4,908
0.000407
try: import cPickle as pickle except ImportError: import pickle as pickle from django.core.management.color import color_style from django.db.models import signals, get_apps, get_app from django_evolution import is_multi_db, models as django_evolution from django_evolution.evolve import get_evolution_sequence...
test_version = django_evolution.Version(signature=signature) latest_version.save(**using_args) for a in get_apps(): install_baseline(a, latest_version, using_args, verbosity) unapplied = get_unapplied_evolutions(app, db) if unapplied: print style.NOTICE('There are unapplie...
me__.split('.')[-2]) # Evolutions are checked over the entire project, so we only need to check # once. We do this check when Django Evolutions itself is synchronized. if app == django_evolution: old_proj_sig = pickle.loads(str(latest_version.signature)) # If any models or apps have been a...
suutari/shoop
shuup/admin/modules/system/views/telemetry.py
Python
agpl-3.0
1,503
0.001331
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.http.response import HttpResponse, HttpResponseRedirec...
"opt_in": not telemetry.is_opt_out(), "is_grace": telemetry.is_in_grace_period(), "last_submission_time": telemetry.get_last_submission_time(), "submissio
n_data": telemetry.get_telemetry_data(request=self.request, indent=2), "title": _("Telemetry") }) return context def get(self, request, *args, **kwargs): if "last" in request.GET: return HttpResponse(telemetry.get_last_submission_data(), content_type="text/plain; cha...
vvinuv/HaloModel
plotting_scripts/compare_battaglia_vinu.py
Python
gpl-3.0
1,283
0.01325
import numpy as np import pylab as pl from astropy.io import fits from scipy.interpolate import interp1d sigma_y = 0 * np.pi / 2.355 / 60. /180. #angle in radian sigmasq = sigma_y
* sigma_y #f = fits.open('/media/luna1/flen
der/projects/gasmod/maps/OuterRim/cl_tsz150_Battaglia_c05_R13.fits')[1].data #l = np.arange(10000) #pl.semilogx(l, l*(l+1)*f['TEMPERATURE'][1:]/2./np.pi, label='Simulation') bl, bcl = np.genfromtxt('/media/luna1/vinu/github/HaloModel/data/battaglia_analytical.csv', delimiter=',', unpack=True) Bl = np.exp(-bl*bl*sigmasq...
384782946/MyBlog
migrations/versions/4cefae1354ee_modify.py
Python
mit
720
0.009722
"""modify Revision ID: 4cefae1354ee Revises: 51f5ccfba190 Create Date: 2016-07-23 13:16:09.9323
65 """ # revision identifiers, used by Alembic. revision = '4cefae1354ee' down_revision = '51f5ccfba190'
from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('posts', sa.Column('title', sa.String(length=128), nullable=True)) op.create_index('ix_posts_title', 'posts', ['title'], unique=False) ### end Alembic commands ### ...
kimjaejoong/nova
nova/tests/unit/virt/hyperv/test_vmops.py
Python
apache-2.0
51,872
0.000019
# Copyright 2014 IBM Corp. # # 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 ...
alue self.assertRaises(vmutils.VHDResizeException,
self._vmops._create_root_vhd, self.context, mock_instance) self.assertFalse(self._vmops._vhdutils.resize_vhd.called) self._vmops._pathutils.exists.assert_called_once_with( fake_root_path) self._vmops._pathutils.remove.assert_called_once_...
larsks/cloud-init
tests/unittests/test_ds_identify.py
Python
gpl-3.0
39,041
0.000026
# This file is part of cloud-init. See LICENSE file for license information. from collections import namedtuple import copy import os from uuid import uuid4 from cloudinit import safeyaml from cloudinit import util from cloudinit.tests.helpers import ( CiTestCase, dir2dict, populate_dir, populate_dir_with_ts) fr...
"SMP Wed Jan 18 14:10:15 UTC 2017 x86_64 GNU/Linux") UNAME_PPC64EL = ("Linux diamond 4.4.0-83-generic #106-Ubuntu SMP " "Mon Jun 26 17:53:54 UTC 2017 " "ppc64le ppc64le ppc64le GNU/Linux") BLKID_EFI_ROOT = """ DEVNAME=/dev/sda1 UUID=8B36-5390 TYPE=vfat PARTUUID=30d7c715
-a6ae-46ee-b050-afc6467fc452 DEVNAME=/dev/sda2 UUID=19ac97d5-6973-4193-9a09-2e6bbfa38262 TYPE=ext4 PARTUUID=30c65c77-e07d-4039-b2fb-88b1fb5fa1fc """ # this is a Ubuntu 18.04 disk.img output (dual uefi and bios bootable) BLKID_UEFI_UBUNTU = [ {'DEVNAME': 'vda1', 'TYPE': 'ext4', 'PARTUUID': uuid4(), 'UUID': uuid4()...
xiangel/hue
apps/beeswax/src/beeswax/server/dbms.py
Python
apache-2.0
24,355
0.011948
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
principal(HIVE_SERVER_HOST.get()) query_server = { 'server_name': 'beeswax', # Aka HiveServer2 now 'server_host': HIVE_SERVER_HOST.g
et(), 'server_port': HIVE_SERVER_PORT.get(), 'principal': kerberos_principal, 'http_url': '%(protocol)s://%(host)s:%(port)s/%(end_point)s' % { 'protocol': 'https' if hiveserver2_use_ssl() else 'http', 'host': HIVE_SERVER_HOST.get(), 'port': hive_site.hiveserve...
cbernet/cpyroot
tools/DataMC/Histogram.py
Python
gpl-2.0
8,121
0.010344
import copy class Histogram( object ): '''Histogram + a few things. This class does not inherit from a ROOT class as we could want to use it with a TH1D, TH1F, and even a 2D at some point. Histogram contains the original ROOT histogram, obj, and a weighted version, weigthed, originally set equal...
weighted histogram to 1. In other words, the original histogram stays untouched.''' self.Scale( 1/self.Integral() ) def RemoveNegativeValues(self, hist=None): # what about errors?? if hist is None: self.RemoveNegativeValues(self.weighted) self.RemoveNegative...
hist.SetBinContent(ibin, 0) def Blind(self, minx, maxx): whist = self.weighted uwhist = self.weighted minbin = whist.FindBin(minx) maxbin = min(whist.FindBin(maxx), whist.GetNbinsX() + 1) for bin in range(minbin, maxbin): whist.SetBinContent(bi...
mjlong/openmc
tests/test_statepoint_batch/test_statepoint_batch.py
Python
mit
654
0.003058
#!/usr/bin/env python import os import sys sys.path.insert(0, os.pardir) from testing_harness import TestHarness class StatepointTestHarness(TestHarness): def __init_
_(self): self._sp_name = None self._tallies = False self._opts = None self._args = None def _test_output_created(self): """Make sure statepoint files have been created.""" sps = ('statepoint.03.*', 'statepoint.06.*', 'statepoint.09.*') for sp in sps: ...
n()
Spindel/python-deployments
mypyramid/mypyramid/views.py
Python
agpl-3.0
1,090
0.001835
from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import ( DBSession, MyModel, ) @view_config(route_name='home', renderer='templates/mytemplate.pt') def my_view(request): try: one = DBSession.query(MyModel).filter(My...
cept DBAPIError: return Response(conn_err_msg, content_type='text/plain', status_int=500) return {'one': one, 'project': 'mypyramid'} conn_err_msg = """\ Pyramid is having a problem using your SQL database. The problem might be caused by one of the following things: 1. You may need to run the "initiali...
ur virtual environment's "bin" directory for this script and try to run it. 2. Your database server may not be running. Check that the database server referred to by the "sqlalchemy.url" setting in your "development.ini" file is running. After you fix the problem, please restart the Pyramid application ...
siketh/ASR
catkin_ws/build/hector_slam/hector_imu_tools/catkin_generated/pkg.develspace.context.pc.py
Python
mit
382
0
# ge
nerated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "hector_imu_tools" PROJECT_SPACE_DIR = "
/home/trevor/ROS/catkin_ws/devel" PROJECT_VERSION = "0.3.3"
AndrewSamokhvalov/python-telegram-bot
telegram/user.py
Python
gpl-3.0
2,099
0
#!/usr/bin/env python # pylint: disable=C0103,W0622 # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public ...
**kwargs: Ar
bitrary keyword arguments. Keyword Args: last_name (Optional[str]): username (Optional[str]): """ def __init__(self, id, first_name, **kwargs): # Required self.id = int(id) self.first_name = first_name # Opt...
itoed/anaconda
pyanaconda/ui/gui/xkl_wrapper.py
Python
gpl-2.0
14,761
0.002574
# # 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...
namedtuple for information about a keyboard layout (its language and description) LayoutInfo = namedtuple("LayoutInfo", ["lang", "desc"]) class XklWrapperError(KeyboardConfigError): """Exception class for reporting libxklavier-related problems""" pass class XklWrapper(object): """ Class wrapping the...
because it provides read-only data and initialization (that takes quite a lot of time) reads always the same data. It doesn't have sense to make multiple instances """ _instance = None _instance_lock = threading.Lock() @staticmethod def get_instance(): with XklWrapper._instance_lo...
Julian/cardboard
cardboard/cards/sets/homelands.py
Python
mit
22,873
0.000044
from cardboard import types from cardboard.ability import ( AbilityNotImplemented, spell, activated, triggered, static ) from cardboard.cards import card, common, keywords, match @card("Feroz's Ban") def ferozs_ban(card, abilities): def ferozs_ban(): return AbilityNotImplemented return ferozs_ba...
@card("Feast of the Unicorn") def feast_of_the_unicorn(card, abilities): def feast_of_the_unicorn(): return AbilityNotImplemented def feast_of_the_unicorn(): return AbilityNotImplemented return feast_of_the_unicorn,
feast_of_the_unicorn, @card("Ambush Party") def ambush_party(card, abilities): def ambush_party(): return AbilityNotImplemented return ambush_party, @card("Black Carriage") def black_carriage(card, abilities): def black_carriage(): return AbilityNotImplemented def black_carriage...
LumaPictures/rez
src/rezgui/widgets/ContextSettingsWidget.py
Python
lgpl-3.0
6,497
0.000308
from rezgui.qt import QtGui from rezgui.util import create_pane from rezgui.mixins.ContextViewMixin import ContextViewMixin from rezgui.models.ContextModel import ContextModel from rez.config import config from rez.vendor import yaml from rez.vendor.yaml.error import YAMLError from rez.vendor.schema.schema import Schem...
update_text() def discard_changes(self, prompt=False): if prompt: ret = QtGui.QMessageBox.warning( self, "The context settings have been modified.",
"Your changes will be lost. Are you sure?", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel) if ret != QtGui.QMessageBox.Ok: return self._update_text() def set_defaults(self): packages_path = config.packages_path implicits = ...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/gio/_gio/InetSocketAddress.py
Python
gpl-2.0
1,078
0.007421
# encoding:
utf-8 # module gio._gio # from /usr/lib/python2.7/dist-packages/gtk-2.0/gio/_gio.so # by generator 1.135 # no doc # imports import gio as __gio import glib as __glib import gobject as __gobject import gobject._gobject as __gobject__gobject class InetSocketAddress(__gio.SocketAddress): """ Object GInetSocket...
s -> GInetAddress: Address The address port -> guint: Port The port flowinfo -> guint: Flow info IPv6 flow info scope-id -> guint: Scope ID IPv6 scope ID Properties from GSocketAddress: family -> GSocketFamily: Address family The family of the soc...
gentoo/grss
grs/MountDirectories.py
Python
gpl-2.0
6,242
0.004005
#!/usr/bin/env python # # MountDirectories.py: this file is part of the GRS suite # Copyright (C) 2015 Anthony G. Basile # # 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 ...
'usr/portage/packages'] ] # Once initiated, we only work with one portage_configroot self.portage_configroot = portage_configroot self.package = package self.portage = portage self.logfile = logfile # We need to umount in the r
everse order self.rev_directories = deepcopy(self.directories) self.rev_directories.reverse() def ismounted(self, mountpoint): """ Obtain all the current mountpoints. Since python's os.path.ismount() fails for for bind mounts, we obtain these ourselves from /proc/mounts. ...
chenc10/Spark-PAF
python/docs/conf.py
Python
apache-2.0
10,462
0.006117
# -*- coding: utf-8 -*- # # pyspark documentation build configuration file, created by # sphinx-quickstart on Thu Aug 28 15:17:47 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
orrect entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional
templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_domain_indices = False # If false, no index is generated. html_use_index = False # If true, the index is split into individual pages for each letter. #html_spli...
Frky/scat
src/shell/command/i_command.py
Python
mit
968
0.003099
#-*- coding: utf-8 -*- import sys from abc import ABCMeta, abstractmethod from src.shell.std import Std class ICommand(Std): """
Interface for a scat command """ def __init__(self, verbose=2): self.__verbose = verbose return def stdout(self, msg, crlf=True): if self.__verbose > 1: sys.stdout.write("[*] " + msg) if crlf:
sys.stdout.write("\n") def stderr(self, msg): """ Print message on standard error, with formatting. @param msg message to print """ if self.__verbose > 0: sys.stderr.write("*** " + msg + "\n") @abstractmethod def run(self, *arg...
rohitranjan1991/home-assistant
homeassistant/components/demo/fan.py
Python
mit
8,773
0.000228
"""Demo fan platform that has a fake fan.""" from __future__ import annotations from homeassistant.components.fan import ( SUPPORT_DIRECTION, SUPPORT_OSCILLATE, SUPPORT_PRESET_MODE, SUPPORT_SET_SPEED, FanEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import H...
PRESET_MODE_AUTO, PRESET_MODE_SMART, PRESET_MODE_SLEEP, PRESET_MODE_ON, ], ), AsyncDemoPercentageFan( hass,
"fan5", "Preset Only Limited Fan", SUPPORT_PRESET_MODE, [ PRESET_MODE_AUTO, PRESET_MODE_SMART, PRESET_MODE_SLEEP, PRESET_MODE_ON, ], ), ] ) asyn...
ddserver/ddserver
ddserver/__main__.py
Python
agpl-3.0
1,674
0.006571
''' Copyright 2013 Sven Reissmann <sven@0x80.io> This file is part of ddserver. ddserver is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later vers...
ublic License along with ddserver. If not, see <http://www.gnu.org/licenses/>. ''' from ddserver.utils.deps import require import ddserver.interface.pages.index # @UnusedImport: for web app
lication import ddserver.interface.pages.signup # @UnusedImport: for web application import ddserver.interface.pages.lostpasswd # @UnusedImport: for web application import ddserver.interface.pages.login # @UnusedImport: for web application import ddserver.interface.pages.user.account # @UnusedImport: for web applic...
xtao/code
tests/test_project_conf.py
Python
bsd-3-clause
2,543
0
from tests.base import TestCase from vilya.models.project import CodeDoubanProject from vilya.models.project_conf import PROJECT_CONF_FILE from nose.tools import raises class TestProjectConf(TestCase): def test_create_project_without_conf(self): self.clean_up() project = CodeDoubanProject.add( ...
: prj = CodeDoubanProject.get_by_name(
'tp') if prj: prj.delete()
hlin117/statsmodels
statsmodels/sandbox/examples/try_gmm_other.py
Python
bsd-3-clause
5,387
0.01188
import numpy as np from scipy import stats from statsmodels.regression.linear_model import OLS from statsmodels.tools import tools from statsmodels.sandbox.regression.gmm import IV2SLS, IVGMM, DistQuantilesGMM, spec_hausman from statsmodels.sandbox.regression import gmm if __name__ == '__main__': import stats...
e / res.bse * 100 - 100) print('OLS ', resols.bse) print('GMMOLS', resgmmols.bse) #print 'GMMiv', modgmmiv.bse print("Hausman's specification test") print(resls.spec_hausman()) print(spec_h
ausman(resols.params, res.params, resols.cov_params(), res.cov_params())) print(spec_hausman(resgmmols.params, res.params, resgmmols.cov_params(), res.cov_params())) if 'distquant' in examples: #estimating distribution parameters from quantil...
armagetronad-xtw/0.4-armagetronad-xtw
batch/checkbugle.py
Python
gpl-2.0
3,156
0.012674
#!/usr/bin/python """checks bugle trace log for OpenGL problems""" from __future__ import print_function import sys count = 0 lineNo = 0 inList = False inBlock = False legalLists = {} setLists = {} usedInList = {} usedInBlock = {} usedOutBlock = {} def error(error, lineNo, *args): print("Error:", error.format(*...
l) if function == 'glDeleteLists': l=args[0:args.find(',')] if not legalLists[l]: err
or("list {} used, but not generated.", lineNo, l) legalLists[l]=False setLists[l]=False print("Used in display lists:") for f in usedInList: print(f, usedInList[f]) print() print("Used in glBegin/End:") for f in usedInBlock: print(f, usedInBlock[f]) print() print("Used outside glBegin/End:") ...
liuqr/edx-xiaodun
common/test/acceptance/pages/lms/course_info.py
Python
agpl-3.0
619
0
""" Course info page. """ from .course_page import CoursePage class CourseInfoPage(CoursePage): """ Course info. """ url_path = "info"
def is_browser_on_page(self): return self.is_css_present('section.updates') @property def num_updates(self): """ Return the num
ber of updates on the page. """ return self.css_count('section.updates section article') @property def handout_links(self): """ Return a list of handout assets links. """ return self.css_map('section.handouts ol li a', lambda el: el['href'])
alantian/polyglot
polyglot/load.py
Python
gpl-3.0
4,095
0.013187
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import path import os from tempfile import NamedTemporaryFile import numpy as np import morfessor from six import PY2 from six.moves import cPickle as pickle from . import polyglot_path from .decorators import memoize from .downloader import downloader from .map...
wiki_vocab": "counts2", "sentiment": "sentiment2", } def locate_resource(na
me, lang, filter=None): """Return filename that contains specific language resource name. Args: name (string): Name of the resource. lang (string): language code to be loaded. """ task_dir = resource_dir.get(name, name) package_id = u"{}.{}".format(task_dir, lang) p = path.join(polyglot_path, task_...
KT12/hands_on_machine_learning
convnets.py
Python
mit
1,271
0.013375
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from sklearn.datasets import load_sample_image from sklearn.datasets import load_sample_images # Utility functions def plot_image(image): plt.imshow(image, cmap="gray", interpolation="ne
arest") plt.axis("off") def plot_color_image(image): plt.imshow(image.astype(np.uint8),interpolation="nearest") plt.axis("off") # Load sample images china = load_sample_image('china.jpg') flower = load_sample_image('flower.jpg') image = china[150:220, 130:250] height, width, channels = image.shape image_g...
ize, height, width, channels = dataset.shape # Create 2 filters fmap = np.zeros(shape=(7, 7, channels, 2), dtype=np.float32) fmap[:, 3, 0, 0] = 1 fmap[3, :, 0, 1] = 1 plot_image(fmap[:,:,0,0]) plt.show() plot_image(fmap[:,:,0,1]) plt.show() X = tf.placeholder(tf.float32, shape=(None, height, width, channels)) convolu...
hchen1202/django-react
virtualenv/lib/python3.6/site-packages/rest_framework/permissions.py
Python
mit
6,655
0.00015
""" Provides a set of pluggable permission policies. """ from __future__ import unicode_literals from django.http import Http404 from rest_framework import exceptions from rest_framework.compat import is_authenticated SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class BasePermission(object): """ A base class ...
issions): """ Similar to DjangoModelPermissions, except that anonymous users are allowed read-only access. """ authenticated_users_only = False class DjangoObjectPermissions(DjangoModelPermissions): """ The request is authenticated usi
ng Django's object-level permissions. It requires an object-permissions-enabled backend, such as Django Guardian. It ensures that the user is authenticated, and has the appropriate `add`/`change`/`delete` permissions on the object using .has_perms. This permission can only be applied against view clas...
cbertinato/pandas
pandas/tests/indexes/test_setops.py
Python
bsd-3-clause
2,362
0
''' The tests in this package are to ensure the proper resultant dtypes of set operations. ''' import itertools as it import numpy as np import pytest from pandas.core.dtypes.common import is_dtype_equal import pandas as pd from pandas import Int64Index, RangeIndex from pandas.tests.indexes.conftest import indices_l...
on-monotonic index raises error # This applies to the boolean index idx1 = idx1.sort_values() idx2 = idx2.sort_values() assert idx1.union(idx2).dtype == np.dtype('O') assert
idx2.union(idx1).dtype == np.dtype('O') @pytest.mark.parametrize('idx_fact1,idx_fact2', COMPATIBLE_INCONSISTENT_PAIRS.values()) def test_compatible_inconsistent_pairs(idx_fact1, idx_fact2): # GH 23525 idx1 = idx_fact1(10) idx2 = idx_fact2(20) res1 = idx1.union(idx2) res2...
inkerra/cinder
cinder/volume/rpcapi.py
Python
apache-2.0
7,605
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012, Intel, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
r.openstack.common.rpc.proxy.RpcProxy): '''Client side of the volume rpc API. API version history: 1.0 - Initial version. 1.1 - Adds clone volume option to create_volume. 1.2 - Add publish_
service_capabilities() method. 1.3 - Pass all image metadata (not just ID) in copy_volume_to_image. 1.4 - Add request_spec, filter_properties and allow_reschedule arguments to create_volume(). 1.5 - Add accept_transfer. 1.6 - Add extend_volume. 1.7 - Adds host_name ...
zpurcey/bestbuy-demo
runbackend.py
Python
mit
112
0.008929
from backend import app if
__name__ == '__main__': app.run('0.0.0.0',port=8080, threaded=T
rue, debug=True)
snaury/copper
contrib/python-copper/lib/copper/frames.py
Python
mit
10,238
0.001856
# -*- coding: utf-8 -*- import time import struct from .errors import ( CopperError, UnknownFrameError, InvalidFrameError, InternalError, ) from collections import deque from .util import take_from_deque __all__ = [ 'Frame', 'PingFrame', 'DataFrame', 'ResetFrame', 'WindowFrame', ...
count = header.payload_size // 6 values = {} while count > 0: sid, value = cls.FMT.unpack(reader.read(6)) values[sid] = value count -= 1 return cls(header.flags, values) def dump(self, writer): Header(0, 6 * len(self.value...
alue)) class Fram