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
ctoher/pymatgen
pymatgen/core/composition.py
Python
mit
31,215
0.000993
# coding: utf-8 from __future__ import division, unicode_literals """ This module implements a Composition class to represent compositions, and a ChemicalPotential class to represent potentials. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "0.1" __maintainer...
ctionality takes in a standard string as a convenient input. For example, even though the internal representation of a Fe2O3 composition is {Element("Fe"): 2, Element("O"): 3}, you can obtain the amount of Fe simply by comp["Fe"] instead of the more verbose comp[Element("Fe")]. >>> comp = Co
mposition("LiFePO4") >>> comp.get_atomic_fraction(Element("Li")) 0.14285714285714285 >>> comp.num_atoms 7.0 >>> comp.reduced_formula 'LiFePO4' >>> comp.formula 'Li1 Fe1 P1 O4' >>> comp.get_wt_fraction(Element("Li")) 0.04399794666951898 >>> comp.num_atoms 7.0 """ ...
AutorestCI/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2017_03_30/models/run_command_document_base.py
Python
mit
1,874
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See Li
cense.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model...
ss RunCommandDocumentBase(Model): """Describes the properties of a Run Command metadata. :param schema: The VM run command schema. :type schema: str :param id: The VM run command id. :type id: str :param os_type: The Operating System type. Possible values include: 'Windows', 'Linux' :t...
nickcoutsos/thuum
thuum/tests/utils.py
Python
mit
1,134
0.000882
import mock from tornado import ( httpclient, testing, web, ) class Base(testing.AsyncHTTPTestCase): def get_app(self): class Nothing(web.RequestHandler): def nothing(self): pass delete = get = head = options = post = put = nothing return web.Appl...
eady=mock.MagicMock(), start=mock.MagicMock(), finish=mock.MagicMock(), ) runner.events.on("request
_ready", events["ready"]) runner.events.on("request_started", events["start"]) runner.events.on("request_finished", events["finish"]) return events, runner def get_request(self, *args, **kwargs): return httpclient.HTTPRequest( self.get_url("/foo"), "GET", ...
vincepandolfo/django
tests/auth_tests/test_models.py
Python
bsd-3-clause
10,053
0.000995
from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth import get_user_model from django.contrib.auth.hashers import get_hasher from django.contrib.auth.models import ( AbstractUser, Group, Permission, User, UserManager, ) from django.contrib.contenttypes.models import ContentType from dj...
),
] # Now we create the test UserPermission Permission.objects.db_manager("default").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=default_objects[1], ) Permission.objects.db_manager("other").create( ...
WeftWiki/phetools
hocr/hocr_request.py
Python
gpl-3.0
6,859
0.007581
# -*- coding: utf-8 -*- # # @file prepare_request.py # # @remark Copyright 2014 Philippe Elie # @remark Read the file COPYING # # @author Philippe Elie import sys import db import os sys.path.append(os.path.expanduser('~/wikisource')) from ws_namespaces import index as index, namespaces as namespaces import hocr sys.p...
old = old_cache_path(title) new = new_cache_path(title, lang) if True: print "echo " + str(count) print "mkdir -p " + new print "mv " + old + '* ' + new print "rmdir -p --ignore-fail-on-non-empty " + old else: if not os.path.exists(new): print "#
misssing data", new elif not os.path.exists(new + "sha1.sum"): print "#misssing sha1.sum data", new if os.path.exists(old): print "#old data", old print "rm " + old + '*' print "rmdir -p --ignore-fail-on-non-empty " + old def move_tree(lang, count): n...
SwordYoung/cutprob
hackerrank/contest/w13/a-super-hero/a.py
Python
artistic-2.0
1,849
0.003786
#!/usr/bin/env python def run_test(n, m, power, bullet): prev_dict = {} cur_dict = {} for i in xrange(n): ri = n-1-i for j in xrange(m): if i == 0: c
ur_dict[power[ri][j]] = power[ri][j] else: new_k = power[ri][j] for k, v in prev_dict.items(): all_bullet = new_k + k - min(v, bullet[ri][j]) if cur_dict.has_key(all_bullet): cur_dict[all_bullet] = min(new_k, cur...
cur_dict[all_bullet] = new_k prev_dict = {} for c, t in cur_dict.items(): small = True for c1, t1 in cur_dict.items(): if c1 < c and t1 < t: small = False break if small: prev_dict[c] ...
hjjeon0608/mbed_for_W7500P
workspace_tools/singletest.py
Python
apache-2.0
11,885
0.005721
#!/usr/bin/env python2 """ mbed SDK Copyright (c) 2011-2014 ARM Limited 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 applicabl...
se True use_supported_toolchains = 'all' in opts.toolchains_filter.split(',') if opts.toolchains_filter is not None else False toolchain_filter = opts.toolchains_filter platform_name_filter = opts.general
_filter_regex.split(',') if opts.general_filter_regex is not None else opts.general_filter_regex # Test specification with information about each target and associated toolchain test_spec = get_autodetected_TEST_SPEC(muts_list, use_default_toolchain=use_def...
pingortle/collate_hospitals_kludge
match_hospitals.py
Python
mit
2,609
0.014565
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from pprint import pprint import re from fileinput import input import csv from fuzzywuzzy import fuzz from fuzzywuzzy import process articles = ['the', 'a'] prepositions = ['at', 'of'] hospital_words = ['hospital', 'medical', 'center'] word_exclusions = articles + pr...
"", name.casefold().replace("-", " ")).split())) def fetch_hospitals(lines): return list(filter(None, [re.findall(r"\".*?\"", line)[-1].str
ip('"') for line in lines])) def extract_hospital(line): words = line.split() return Hospital(" ".join(words[1:-2]), " ".join(words[-2:])) def fetch_hospital_data(lines): return [extract_hospital(line) for line in lines] def write_table_to_file(filename, table): with open(filename, 'w') as f: tablewriter...
airbnb/streamalert
tests/unit/streamalert/shared/test_alert.py
Python
apache-2.0
20,111
0.001044
""" Copyright 2017-present Airbnb, 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, sof...
tools import ( assert_equal, assert_false, assert_is_instance, assert_not_in, assert_raises, assert_true ) from streamalert.shared.alert import Alert, AlertCreationError class TestAlert: """Test shared Alert class.""" # pylint: disable=no-self-use,protected-access,too-many-public-meth...
n Alert('test_rule', {'abc': 123}, {'aws-firehose:alerts', 'aws-sns:test-output'}) @staticmethod def _customized_alert(): return Alert( 'test_rule', {'abc': 123}, {'aws-firehose:alerts', 'aws-sns:test-output', 'aws-s3:other-output'}, alert_id='abc-123', ...
shapiromatron/amy
workshops/management/commands/export_airports.py
Python
mit
319
0.003135
import yam
l from django.core.management.base import BaseCommand, CommandError from workshops.views import _export_instructors class Command(BaseCommand): args = 'no arguments' help = 'Displa
y YAML for airports.' def handle(self, *args, **options): print(yaml.dump(_export_instructors()).rstrip())
wavesoft/LiveQ
liveq-jobmanager/jobmanager/io/teamqueue.py
Python
gpl-2.0
1,361
0.008082
################################################################ # LiveQ - An interactive volunteering computing batch system # Copyright (C) 2013 Ioannis Charalampidis # # 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 ...
SS 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. ####################...
port Config from peewee import fn from liveq.models import Agent, AgentGroup, Jobs # Setup logger logger = logging.getLogger("teamqueue") def processTeamQueue(): """ This should be called periodically to check and schedule jobs pending for the particular team """ pass
adaptive-learning/proso-apps
proso/svg.py
Python
mit
2,180
0.00367
class Printer: def __init__(self): self._output = '' def print_output(self, output): self._output += output def print_line(self, x1, y1, x2, y2, color=0, width=1): self
.prin
t_output(_svg_line(x1, y1, x2, y2, color=color, width=width)) def print_circle(self, x, y, r, color=0, width=1, border_color=0): self.print_output(_svg_circle(x, y, r, color=color, width=width, border_color=border_color)) def print_square(self, x, y, a, color=0, width=1, border_color=0): self....
akaszynski/vtkInterface
tests/test_init.py
Python
mit
1,317
0.001519
import os import sys import pytest import vtk import pyvista developer_note = """ vtk has been directly imported in vtk>=9 Please see: https://github.com/pyvista/pyvista/pull/1163 """ @pytest.mark.skipif(not pyvista._vtk.VTK9, reason='``vtk`` can be loaded directly on vtk<9') def test_vtk_not_lo...
han 0 indicates an error assert not os.system(f'{sys.executable} -c "{exe_str}"'), developer_note # validate all lazy loads lazy_readers = ['vtkGL2PSExporter', 'vtkFacetReader', 'vtkPDataSetReader', 'vtkMultiBlockPLOT3DReader', 'vtkPlot3DMe
taReader'] if pyvista._vtk.VTK9: lazy_readers.append('vtkSegYReader') @pytest.mark.parametrize("cls_", lazy_readers) def test_lazy_loads(cls_): lazy_class = getattr(pyvista._vtk, 'lazy_' + cls_)() actual_class = getattr(vtk, cls_)() # can't use isinstance here because these are classes assert type...
vinta/sublimall-server
sublimall/donations/models.py
Python
mit
1,788
0
# -*- coding: utf-8 -*- from __future__ import division import stripe from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from ..accounts.models import Member if hasattr(settings, 'STRIPE_SECRET_KEY'): stripe.api_key = settings.STRIPE_SECRET_KEY class...
else: return 'Paypal' def get_payment_url(self): if self.get_pro
vider().lower() == 'paypal': return 'https://www.paypal.com/fr/vst/id=%s' % self.token_id else: return 'https://manage.stripe.com/payments/%s' % self.charge_id
parejkoj/AstroHackWeek2015
inference/straightline_log_likelihood.py
Python
gpl-2.0
604
0.001656
def straight_line_log_likelihood(theta, x, y, sigmay): ''' Returns the log-likelihood of drawing data values *y* at known values *x* given Gaussian measurement noise with standard deviation with known *sigmay*, where the "true" y values are *y_t = m * x + b* x: list of x coordinates y: list...
s: scalar log likelihood ''' m,b = theta return (np.sum(np.log(1./(np.sqrt(2.*np.pi) * sigmay))) + np.sum(-0.5 * (y - (m*x + b
))**2 / sigmay**2))
knupouls/extremefeedbacklamp
jenkins_discovery.py
Python
mit
1,818
0.035204
#!/usr/bin/env python # Jenkins server UDP based discovery # Based on original work by Gordon McGregor gordon.mcgregor@verilab.com # # Author Aske Olsso
n aske.olsson@switch-gears.dk from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from twisted.application.internet import MulticastServer from twist
ed.internet import task import xml.etree.ElementTree as ET MULTICAST_ADDR = "239.77.124.213" UDP_PORT = 33848 DELAY = 60 class JenkinsDiscovery(DatagramProtocol): def __init__(self): self.instances = {} self.ping_str = 'Hello Jenkins, Where are you' def startProtocol(self): # print 'Host discovery: l...
phorust/howmanygiven
howmanyapp/views.py
Python
mit
982
0.01222
# what each page will look like from howmanyapp import app from flask import render_template, flash, redirect, request from howmany import * from random import choice from urlparse import urlparse @app.route('/') @app.route('/index.html') def index(): return render_template("index.html") @app.route('/fuck/<path...
= "http://" + path return render_template("fquery.html", count=count_in_page(path, 'fuck'), queryurl=path) @app.route('/<path:path>') def analyze(path): print "PATH", path if urlparse(path).scheme == '': path = "http://" + path return render_template("query.html", query...
Aw shucks.', 'Golly.', 'Damn'] return render_template("404.html", msg=choice(msgs)), 404
itaymendel/taurus
tests/modules/test_functionalAggregator.py
Python
apache-2.0
3,428
0.004959
from bzt.modules.functional import FunctionalAggregator, FunctionalAggregatorListener, FunctionalSample from tests import BZTestCase from tests.mocks import MockFunctionalReader class MockListener(FunctionalAggregatorListener): def __init__(self): self.results = [] def aggregated_results(self, resul...
test2", test_suite="Tests1", status="PASSED", start_time=4, duration=1, error_msg=None, error_trace=None, extras=
None), FunctionalSample(test_case="test3", test_suite="Tests2", status="FAILED", start_time=6, duration=1, error_msg="Really failed", error_trace=None, extras=None), FunctionalSample(test_case="test1", test_suite="Tests1", status="PASSED", start_time=6, duration=1, ...
Netflix/lemur
lemur/authorizations/models.py
Python
apache-2.0
1,090
0.000917
""" .. module: lemur.authorizations.models :platform: unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Netflix Secop
s <secops@netflix.com> """ from sqlalchemy import Column, Integer, String from sqlalchemy_utils import JSONType from lemur.database import db from lemur.plugins.base import plugins class
Authorization(db.Model): __tablename__ = "pending_dns_authorizations" id = Column(Integer, primary_key=True, autoincrement=True) account_number = Column(String(128)) domains = Column(JSONType) dns_provider_type = Column(String(128)) options = Column(JSONType) @property def plugin(self):...
tijptjik/thegodsproject
plugins/linker/linker.py
Python
mit
4,995
0.004404
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import re from six.moves.urllib.parse import urlparse, urlunparse from pelican import signals, contents from linker import content_objects logger = logging.getLogger("linker") class Link(object): """Represents an HTML link including...
r existing registration of that cmd current_linker_class = self.linkers[cmd].__class__ logger.warning( "%s is stealing the linker command %s from %s.", linker_class.__name__, cmd, current_linker_class.__name__ ) self.linkers[cmd] = linker_class...
ect(self, context, content_object): # replace Link matches (with side effects on content and content_object) def replace_link_match(match): link = Link(context, content_object, match) if link.cmd in LinkerBase.builtins: pass # builtin commands not handled here ...
JudoWill/glue
glue/core/registry.py
Python
bsd-3-clause
2,587
0
from __future__ import absolute_import, division, print_function from collections import defaultdict from functools import wraps from .decorators import singleton from .util import disambiguate @singleton class Registry(object): """ Stores labels for classes of objects. Ensures uniqueness The registry ens...
>>> r = Registry() >>> x, y, z = 3, 4, 5 >>> w = list() >>> r.register(x, 'Label') 'Label' >>> r.register(y, 'Label') # duplicate label disambiguated 'Label_01' >>> r.register(w, 'Label') # uniqueness only enforced within groups 'Label' >>>...
try 'Label_02' """ def __init__(self): self._registry = defaultdict(dict) self._disable = False def register(self, obj, label, group=None): """ Register label with object (possibly disamgiguating) :param obj: The object to label :param label: The desired la...
facebookexperimental/eden
eden/hg-server/edenscm/mercurial/treedirstate.py
Python
gpl-2.0
19,795
0.001364
# Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. """tree-based dirstate""" from __future__ import absolute_import import binascii import errno import heapq import itertools import random import strin...
hedproperty(self, "dirfoldmap") def __len__(self): """Returns the number of files, including removed files.""" return self._rmap.filecount() def itertrackeditems(self): """Returns an iterator over (filename, (state, mode, size, mtime)).""" return treedirstatemap
iterator(self._rmap, removed=False) def iterremoveditems(self): """ Returns an iterator over (filename, (state, mode, size, mtime)) for files that have been marked as removed. """ return treedirstatemapiterator(self._rmap, removed=True) def iteritems(self): retu...
centaurialpha/ninja-ide
ninja_ide/core/encapsulated_env/plugins_manager.py
Python
gpl-3.0
3,254
0
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE 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 # any later version. # # NIN...
def load_all_plugins(self): to_activat
e = self.get_to_activate_plugins() for each_plugin in to_activate: self.__activate_plugin(__import__(each_plugin), each_plugin) def __activate_plugin(self, plugin, plugin_name): """ Receives the actual plugin module and tries activate or marks as failure """ ...
jamesporter/InternationalTrade
countryutils/transformations.py
Python
mit
7,163
0.011448
# various converters between country codes and names # including the possibility to look up the continent # a country belongs to. # # source: ISO 3166 and # http://en.wikipedia.org/wiki/List_of_countries_by_continent_(data_file) import data import types def ccn_to_ccn(code): """Normalize the numeric country code...
return data.cca2_to_ccn[code.upper()] def cca3_to_ccn(code): """Given the ISO 3166 t
hree letter country code of the country return the corresponding numeric country code. The code passed in can be of string or unicode type. Raises KeyError if code does not exist. """ return data.cca3_to_ccn[code.upper()] def ccn_to_ctca2(code): """Given an ISO 3166 numeric count...
PyBargain/ice-mud-game
server.py
Python
gpl-3.0
3,444
0.003683
#!/usr/bin/python3 # encoding=utf-8 import time from socket import socket from s
elect import select from hashlib import sha1 import pygame from pygame.locals import * from game import Player, Game TICKET_SHA1SUM = '7aa8398d0e80429a3380540b86f08987d0fb3e77' ''' 客户端发往服务器端的消息前缀: N 设置昵称 S 验证身份特权 K 按键事件 服务器端发往客户端的消息前缀: T startTime C 当前在线人数 [ 数据 ...
__init__(self, saddr): self.s_socket = socket() self.s_socket.bind(('127.0.0.1', 10667)) def start(self): self.s_socket.listen(2) self.cs_socket = [self.s_socket.accept()[0]] self.players = [Player()] self.startTime = time.time() + 35 stopAcceptTime =...
ArthurZey/dvrhelper
tests_dvrhelper.py
Python
mit
2,446
0.016353
import dvrhelper import unittest class TestDVRHelperMethods(unittest.TestCase): def test_DVRFile_init(self): examples = { # format of result: # [x.path["filename"], x.path["ext"], x.show_name["raw"], x.season["num"]["int"], x.season["num"]["disp"], x.
episode["num"]["int"], x.episode["num"]["disp"] "12.Monkeys.S01E0
4.HDTV.x264-KILLERS.mp4": ["12.Monkeys.S01E04.HDTV.x264-KILLERS.mp4", ".mp4", "12.Monkeys.", 1, "01", 4, "04"], "/volume2/Downloads/Archer.2009.S05E07.HDTV.x264-2HD.mp4": ["Archer.2009.S05E07.HDTV.x264-2HD.mp4", ".mp4", "Archer.2009.", 5, "05", 7, "07"], "/volume1/Dropbox/Media/DVR/Bobs.Burg...
epitron/youtube-dl
youtube_dl/extractor/go90.py
Python
unlicense
5,640
0.001064
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( determine_ext, ExtractorError, int_or_none, parse_age_limit, parse_iso8601, ) class Go90IE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?go90\.com/videos/(?P<id>[0-9a...
o90.com/videos/84BUqjLpf9D', 'md5': 'efa7670dbbbf21a7b07b360652b24a32', 'info_dict': { 'id': '84BUqjLpf9D', 'ext': 'mp4', 'tit
le': 'Daily VICE - Inside The Utah Coalition Against Pornography Convention', 'description': 'VICE\'s Karley Sciortino meets with activists who discuss the state\'s strong anti-porn stance. Then, VICE Sports explains NFL contracts.', 'timestamp': 1491868800, 'upload_date': '20170411'...
FDio/vpp
test/test_cdp.py
Python
apache-2.0
4,468
0.000224
#!/usr/bin/env python3 """ CDP tests """ from scapy.packet import Packet from scapy.all import ShortField, StrField from scapy.layers.l2 import Dot3, LLC, SNAP from scapy.contrib.cdp import CDPMsgDeviceID, CDPMsgSoftwareVersion, \ CDPMsgPlatform, CDPMsgPortID, CDPv2_HDR from framework import VppTestCase from ...
>= 1, "CDP didn't drop bad packet") def send_packet(self, packet): self.logger.debug(ppp("Sending packet:", packet)) self.interface.
add_stream(packet) self.pg_start() def create_base_packet(self): packet = (Dot3(src=self.interface.remote_mac, dst="01:00:0c:cc:cc:cc") / LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) / SNAP()/CDPv2_HDR()) return packet def create_packe...
rohitranjan1991/home-assistant
homeassistant/components/tado/water_heater.py
Python
mit
9,720
0.000823
"""Support for Tado hot water zones.""" import logging import voluptuous as vol from homeassistant.components.water_heater import ( SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, WaterHeaterEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_TEMPERATURE...
return entities def create_water_heater_entity(tado, name: str, zone_id: int, zone: str): """Create a Tado water heater device.""" capabilities = tado.get_capabilities(zone_id) supports_temperature
_control = capabilities["canSetTemperature"] if supports_temperature_control and "temperatures" in capabilities: temperatures = capabilities["temperatures"] min_temp = float(temperatures["celsius"]["min"]) max_temp = float(temperatures["celsius"]["max"]) else: min_temp = None ...
purism/pdak
dak/new_security_install.py
Python
gpl-2.0
6,680
0.004341
#!/usr/bin/env python """ Do whatever is needed to get a security upload released @contact: Debian FTP Master <ftpmaster@debian.org> @copyright: 2010 Joerg Jaspert <joerg@debian.org> @license: GNU General Public License version 2 or later """ # This program is free software; you can redistribute it and/or modify # i...
atient" os.environ['configdir'] = '/srv/security-master.debian.org/dak/config/debian-security' spawn("/srv/security-master.debian.org/dak/config/debian-security/cronscript unchecked-dinstall") print "Triggering metadata export for packages.d.o and other consumers"
spawn("/srv/security-master.debian.org/dak/config/debian-security/export.sh") ######################################################################## ######################################################################## def main(): global Options, Logger, Queue, changes cnf = Config() Arguments =...
joachimmetz/dfvfs
tests/file_io/hfs_file_io.py
Python
apache-2.0
3,508
0.003421
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Extended File System (HFS) file-like object.""" import unittest from dfvfs.file_io import hfs_file_io from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context fr...
lf): """Test the read functionality."""
path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_HFS, location='/passwords.txt', identifier=self._IDENTIFIER_PASSWORDS_TXT, parent=self._raw_path_spec) file_object = hfs_file_io.HFSFile(self._resolver_context, path_spec) self._TestRead(file_object) def te...
tsadm/desktop
lib/tsdesktop/siteman/__init__.py
Python
bsd-3-clause
2,873
0.000696
import re import sys from os import path from tsdesktop import config from tsdesktop.dockman import services from configparser import NoSectionError, NoOptionError class Site: name = None docroot = None webserver = None def __init__(self, name, docroot): self.name = name self.docroot ...
ot): if config.cfg.has_section('site:'+name): return 'site already exists' err = _dupDocroot(docroot) if err is not None: return err config.cfg.add_section('site:'+name) config.cfg.set('site:'+name, 'docroot', docroot) return None # -- remove site from config def siteRemove(nam...
return None # -- get site from config def siteGet(name): try: docroot = config.cfg.get('site:'+name, 'docroot') except NoSectionError: return None except NoOptionError: return None return Site(name, docroot) # -- get all sites from config def sitesAll(): rl = list() f...
kovidgoyal/html5-parser
genencodings.py
Python
apache-2.0
1,197
0.000835
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals import json import os try: from urllib.request import urlopen except ImportError: from urllib import u...
teg
ory in data: for encoding in category['encodings']: name = encoding['name'].lower() for label in encoding['labels']: yield label.lower(), name def main(): os.chdir(os.path.dirname(self_path)) data = get_data() ans = dict(get_mapping(data)) keys = sorted(...
ncliam/serverpos
openerp/custom_modules/pos_shop/shop.py
Python
agpl-3.0
3,525
0.008227
# -*- coding: utf-8 -*- ################################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Julius Network Solutions SARL <contact@julius.fr> # # This program is free software: you can redistribute it and/or modify # it under th...
Journal', domain=[('type', '=', 'sale')]), 'address': fields.char('Address'), 'hotline': fields.char('Hotline'), 'email': fields.char('Email'), } def _default_sale_journal(self, cr, uid, con
text=None): company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id res = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'sale'), ('company_id', '=', company_id)], limit=1, context=context) return res and res[0] or False def _default_pric...
toenuff/treadmill
tests/metrics_test.py
Python
apache-2.0
3,085
0
"""Test for treadmill.metrics.""" import unittest from collections import namedtuple # Disable W0611: Unused import import tests.treadmill_test_deps # pylint: disable=W0611 import mock from treadmill import metrics from treadmill import sysinfo STATINFO = """cache 0 rss 0 mapped_file 0 pgpgin 0 pgpgout 0 swap 0 i...
cpu_usage = 100 cpu_ratio = .5 time_delta = 10 cpu_count = 1 cpu_shares = 10 total_bogomips = 100 requested_ratio = cpu_ratio * 100 usage_ratio = ((cpu_usage * total_bogomips) / (time_delta * cpu_shares) / cpu_count) usage ...
(time_delta * sysinfo.BMIPS_PER_CPU) / cpu_count * 100) self.assertEquals( (usage, requested_ratio, usage_ratio), cpumetrics ) @mock.patch('__builtin__.open', mock.mock_open(read_data='1.0 2.0 2.5 12/123 12345\n')) @mock.patch(...
liyocee/job_hunt
backend/employee/migrations/0001_initial.py
Python
mit
1,960
0.002041
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('common', '0002_job'), migrations.swappable_dependency(settings.AUTH_USE...
ateTimeField(default=django.utils.timezone.now)), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrat
ions.CreateModel( name='Employee', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_on', models.DateTimeField(default=django.utils.timezone.now)), ('phone_number', models.CharFiel...
JudoWill/glue
glue/qt/widgets/edit_subset_mode_toolbar.py
Python
bsd-3-clause
2,391
0
from __future__ import absolute_import, division, print_function from ...external.qt import QtGui from ...core.edit_sub
set_mode import (EditSu
bsetMode, OrMode, AndNotMode, AndMode, XorMode, ReplaceMode) from ..actions import act from ..qtutil import nonpartial def set_mode(mode): edit_mode = EditSubsetMode() edit_mode.mode = mode class EditSubsetModeToolBar(QtGui.QToolBar): def __init__(self, title="Subs...
dmitry-sinina/samba4-manager
plugins/tree.py
Python
gpl-2.0
3,478
0.000288
# -*- coding: utf-8 -*- # Copyright (C) 2012-2015 Stéphane Graber # Author: Stéphane Graber <stgraber@ubuntu.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 Licens...
ranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You can
find the license on Debian systems in the file # /usr/share/common-licenses/GPL-2 from libs.common import iri_for as url_for from flask import g, render_template from libs.ldap_func import ldap_auth, ldap_get_entries, ldap_in_group TREE_BLACKLIST = ["CN=ForeignSecurityPrincipals", "OU=sudoers"] de...
timj/scons
test/option-b.py
Python
mit
1,453
0.003441
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, ...
onditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF AN
Y # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING...
Grunny/zap-cli
zapcli/log.py
Python
mit
1,840
0.002174
""" Logger classes for the ZAP CLI. .. moduleauthor:: Daniel Grunwell
(grunny) """ import logging import sys from termcolor import colored class ColorStreamHandler(logging.StreamHandler): """ StreamHandler that prints color. This is used by the console client. """ level_map = { logging.DEBUG: ('magenta', ['bold']), logging.INFO: ('cyan', ['bold']), ...
def is_tty(self): """is the stream a tty?""" isatty = getattr(self.stream, 'isatty', None) return isatty and isatty() def emit(self, record): colorize = 'console' in globals() and getattr(console, 'colorize', False) if self.is_tty and colorize: color, attr =...
SoftwareKing/zstack-dashboard
zstack_dashboard/api_messages.py
Python
apache-2.0
16,024
0.000874
api_names = [ 'org.zstack.test.multinodes.APISilentMsg', 'org.zstack.test.identity.FakePolicyAllowMsg', 'org.zstack.test.identity.FakePolicyDenyMsg', 'org.zstack.test.identity.FakePolicyAllowHas2RoleMsg', 'org.zstack.core.config.APIQueryGlobalConfigMsg', 'org.zstack.core.config.APIGetGlobalConfi...
apshot.APIRevertVolumeFromSnapshotMsg', 'org.zstack.header.storage.snapshot.APIBackupVolumeSnapshotMsg', 'org.zstack.header.storage.snapshot.APIGetVolumeSnapshotTreeMsg', 'org.zstack.header.storage.backup.APIQueryBackupStorageMsg',
'org.zstack.header.storage.backup.APIAttachBackupStorageToZoneMsg', 'org.zstack.header.storage.backup.APIGetBackupStorageTypesMsg', 'org.zstack.header.storage.backup.APIChangeBackupStorageStateMsg', 'org.zstack.header.storage.backup.APIScanBackupStorageMsg', 'org.zstack.header.storage.backup.APIGetBack...
phantomnat/my-cf-client-python
lib/cfclient/ui/tabs/AITab.py
Python
gpl-2.0
12,600
0.004286
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
ontroller.PositionUpdated.connect(self._data_received) self.controller.OutputUpdated.connect(self._output_controller_updated) self.controller.ErrorUpdated.connect(self._slot_error_updated) self.btnErrorRe
set.released.connect(self.controller.slot_reset_error) # # # self._plot.set_title('Position') # color_selector = 0 # self._plot.add_curve('actual.x', self.colors[color_selector % len(self.colors)]) # color_selector += 1 # self._plot.add_curve('actual.y', self.colo...
tuukkao/sananmuunnos
sananmuunnos.py
Python
mit
4,465
0.007427
#!/usr/bin/envpython #-*- coding: utf-8 -*- """ Sananmuunnos: Transforming Finnish spoonerisms made easy (and systematic). """ __author__ = "Tuukka Ojala" __email__ = "tuukka.ojala@gmail.com" __version__ = "2015.0918" __license__ = "MIT" import re #Regular expressions for detecting different types of sananmuunnose...
return False def _is_initial_consonant(word1, word2): """Test word1 and word2 against the "initial consonant" rule.
""" if _initial_consonant.search(word1): transformed1 = word2[:2] +word1[2:] transformed2 = word1[:2] +word2[2:] return (transformed1, transformed2) else: return False def _vowel_harmony(word): """Attempts to make the given word comply with Finnish vowel harmony. If...
Jet-Streaming/gyp
test/actions/src/subdir1/counter.py
Python
bsd-3-clause
1,151
0.010426
#!/usr/bin/env python # Copyright (c) 2010 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. import sys import time output = sys.argv[1] persistoutput = "%s.persist" % sys.argv[1] count = 0 try: count = open(persist...
the count in a file that is undeclared, and thus hidden, to gyp. We need # to do this because, prior to running commands, some build systems deletes # any declared outputs, so we would lose our count i
f we just wrote to the # given output file. open(persistoutput, 'w').write('%d' % (count)) # Only write the given output file if the count has changed. if int(oldcount) != count: open(output, 'w').write('%d' % (count)) # Sleep so the next run changes the file time sufficiently to make the build # detect ...
MicroTrustRepos/microkernel
src/l4/pkg/python/contrib/Doc/includes/sqlite3/complete_statement.py
Python
gpl-2.0
670
0
# A minimal SQLite shell for experiments import sqlite3 con = sqlite3.connect(":memory:") con.isolation_level = None cur = con.cursor() buffer = "" print "Enter your SQL commands to execute in sqlite3." print "Enter a blank line to exit." while True: line = raw_input() if line == "": break buff...
= buffer.strip() cur.execute(buffer) if buffer.lstrip().upper().startswith("SELECT"): print cur.fetchall() except sqlite3.Error, e: print "An error occurred:", e.ar
gs[0] buffer = "" con.close()
ShovanSarker/sense_v4_withLocal
template_manager/views.py
Python
gpl-2.0
113,348
0.00532
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from subscriber.models import Consumer, Con...
The username and password you have entered is not correct. Please retry'}) else: res = render(request, 'pages/login.html', {'wrong': False}) res['Access-Control-Allow-Origin'] = "*" res['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept" res['Access-Control-Allow-...
'/login/') def home(request): transcriber_name = request.session['user'] print request.session['user'] if ACL.objects.filter(loginID=transcriber_name).exists(): login_user = ACL.objects.get(loginID=transcriber_name) print(login_user.loginUser.name) transcriber_name = login_user.login...
miqui/python-hpOneView
examples/scripts/get-profiles.py
Python
mit
4,576
0.001311
#!/usr/bin/env python ### # (C) Copyright (2012-2015) Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limita...
from __f
uture__ import absolute_import from builtins import range from future import standard_library standard_library.install_aliases() import sys PYTHON_VERSION = sys.version_info[:3] PY2 = (PYTHON_VERSION[0] == 2) if PY2: if PYTHON_VERSION < (2, 7, 9): raise Exception('Must use Python 2.7.9 or later') elif PYTH...
kernc/pelican
pelican/tests/default_conf.py
Python
agpl-3.0
1,314
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function AUTHOR = 'Alexis Métaireau' SITENAME = "Alexis' log" SITEURL = 'http://blog.notmyidea.org' TIMEZONE = 'UTC' GITHUB_URL = 'http://github.com/ametaireau/' DISQUS_SITENAME = "blog-notmyidea" PDF_GENERATOR = False REVERSE_CATEGORY_ORDER = True...
: {'path': 'robots.txt'}, } # static paths will be copied without parsing their contents STATIC_PATHS = [
'pictures', 'extra/robots.txt', ] # foobar will not be used, because it's not in caps. All configuration keys # have to be in caps foobar = "barbaz"
z-uo/pixeditor
dock_tools.py
Python
gpl-3.0
2,923
0.004105
#!/usr/bin/env python3 #-*- coding: utf-8 -*- from PyQt4 import QtCore from PyQt4 import Q
tGui from widget import Button, Label class ToolsWidget(QtGui.QWidget): """ widget cantaining tools buttons """ def __init__(self, project): QtGui.QWidget.__init__(self) self.project = project ### coordinates ### self.coords = Label("Cursor coordinates") self.coords.se...
.setChecked(True) self.project.toolSetPenSign.connect(self.penClicked) self.pipetteB = Button("pipette (2)", "icons/tool_pipette.png", self.pipetteClicked, True) self.fillB = Button("fill (3)", "icons/tool_fill.png", self.fillClicked, True) self.moveB = Button("move (4)", "icons/tool_mov...
kaushik94/sympy
sympy/physics/mechanics/models.py
Python
bsd-3-clause
6,458
0.000465
#!/usr/bin/env python """This module contains some sample symbolic models used for testing and examples.""" # Internal imports from sympy.core import backend as sm import sympy.physics.mechanics as me
def multi_mass_spring_damper(n=1, apply_gravity=False, apply_external_forces=False): r"""Returns a system containing the symbolic equations of motion and associated variables for a simple multi-degree of freedom point mass, spring, damper system with optional gravitational and...
em under the influence of gravity and external forces looks like: :: ---------------- | | | | g \ | | | V k0 / --- c0 | | | | x0, v0 --------- V | m0 | ----- --------- | | | | | \ v ...
Samsung/ADBI
idk/cachebuilder/dwarftools.py
Python
apache-2.0
6,162
0.003895
from elftools.dwarf.ranges import RangeEntry, BaseAddressEntry from elftools.dwarf import constants def get_die_offset_by_reference(referer_die, attrname, use_abstract_origin=True): '''Return the offset of the DIE referred by the given attribute in the referrer DIE.''' ref = referer_die.attributes.get(attrname...
f
or entry in ranges: if isinstance(entry, BaseAddressEntry): base = entry.base_adress elif isinstance(entry, RangeEntry): yield base + entry.begin_offset, base + entry.end_offset else: raise ValueError('Invalid el...
markcwill/obspy_ext
antelope/dbobjects.py
Python
gpl-3.0
5,306
0.007727
#! /usr/bin/env python # # dbobjs.py # # obspy antelope dbatabase objects module # by Mark Williams 2012.013 # Oregon State University # # Contains basic classes to interect with (read) data from Antelope # Datascope database tables into ObsPy using the Antelope Python interface. # # These classes load data from the da...
>>> dbopen('demo','r') >>> db.lookup(table='arrival') >>> db.record = 0 >>> pick = Dbrecord(db) """ if db: if db.record == dbALL: raise ValueError("Rec # is 'dbALL', for multiple records, use Dbview().") self.Ptr = Dbpt...
f.Table = db.query(dbTABLE_NAME) self.PrimaryKey = db.query(dbPRIMARY_KEY) self._fields_unsorted = db.query(dbTABLE_FIELDS) self._tables = db.query(dbVIEW_TABLES) # NOTE: in some cases, the query will return a valid field name, # but ...
interhui/py-sys
py_sys/execute.py
Python
apache-2.0
477
0.012579
#
coding=utf-8 import os def run(cmd, decoding = None, clean = False): if cmd: result = [] output = os.popen(cmd).readlines() for line in output: if decoding: line = line.decode(decoding) if clean: line = line.strip() ...
mikehulluk/morphforge
src/morphforgecontrib/fake_namespaces/postsynaptictypes.py
Python
bsd-2-clause
1,976
0.002024
#!/usr/bin/python # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Copyright (c) 2012 Michael Hull. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are m...
IGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVE...
qpxu007/Flask-AppBuilder
flask_appbuilder/security/forms.py
Python
bsd-3-clause
3,248
0.004926
from wtforms import StringField, BooleanField, PasswordField from flask_wtf.recaptcha import RecaptchaField from flask_babelpkg import lazy_gettext from wtforms.validators import DataRequired, EqualTo, Email from ..fieldwidgets import BS3PasswordFieldWidget, BS3TextFieldWidget from ..forms import DynamicForm class Lo...
(lazy_gettext('User Name')) remember_m
e = BooleanField(lazy_gettext('Remember me'), default=False) class LoginForm_db(DynamicForm): username = StringField(lazy_gettext('User Name'), validators=[DataRequired()]) password = PasswordField(lazy_gettext('Password'), validators=[DataRequired()]) class ResetPasswordForm(DynamicForm): password = Pa...
sniemi/SamPy
sandbox/src1/examples/mathtext_examples.py
Python
bsd-2-clause
2,927
0.0041
#!/usr/bin/env python import os, sys, re import gc stests = [ r'Kerning: AVA $AVA$', r'\$100.00 $\alpha \_$', r'$\frac{\$100.00}{y}$', r'$x y$', r'$x+y\ x=y\ x<y\ x:y\ x,y\ x@y$', r'$100\%y\ x*y\ x/y x\$y$', r'$x\leftarrow y\ x\forall y\ x-y$', r'$x \sf x \bf x {\cal X} \rm x$', ...
vec{q}$', r'$_i$', r"$\arccos((x^i))$", r"$\gamma = \frac{x=\frac{6}{8}}{y} \delta$", r'$\limsup_{x\to\infty}$', r'$\oint^\infty_0$', r"$f^'$"
, r'$\frac{x_2888}{y}$', r"$\sqrt[3]{\frac{X_2}{Y}}=5$", r"$\sqrt[5x\pi]{\prod^\frac{x}{2\pi^2}_\infty}$", r"$\sqrt[3]{x}=5$", r'$\frac{X}{\frac{X}{Y}}$', # From UTR #25 r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \...
diego-d5000/MisValesMd
env/lib/python2.7/site-packages/django/utils/functional.py
Python
mit
16,501
0.000788
import copy import operator import sys import warnings from functools import wraps from django.utils import six from django.utils.deprecation import RemovedInDjango19Warning from django.utils.six.moves import copyreg # You can't trivially replace this with `functools.partial` because this binds # to clas...
st a # collection of functions. So we don't need to do anything # complicated for copying. memo[id(self)] = self return self @wraps(func) def __wrapper__(*args, **kw): # Creates the pr
oxy object, instead of the actual value. return __proxy__(args, kw) return __wrapper__ def _lazy_proxy_unpickle(func, args, kwargs, *resultclasses): return lazy(func, *resultclasses)(*args, **kwargs) def allow_lazy(func, *resultclasses): """ A decorator that allows a function to...
silly-wacky-3-town-toon/SOURCE-COD
toontown/pgui/DirectEntryScroll.py
Python
apache-2.0
4,075
0.011779
__all__ = ['DirectEntryScroll'] from pandac.PandaModules import * import DirectGuiGlobals as DGG from DirectScrolledFrame import * from DirectFrame import * from DirectEntry import * class DirectEntryScroll(DirectFrame): def __init__(self, entry, parent = None, **kw): optiondefs = ( ('pgFunc',...
(clipExtent * 0.5): self.moveToCenterCursor() def moveToCenterCursor(self): cursorX = self.entry.guiItem.getCursorX() * self.entry['text_scale'][0] canvasX = self.canvas.getX() visXMin = self.clipXMin - canvasX visXMax = self.cli
pXMax - canvasX visXCenter = (visXMin + visXMax) * 0.5 distanceToCenter = visXCenter - cursorX newX = canvasX + distanceToCenter clipExtent = self.clipXMax - self.clipXMin entryExtent = self.entry['text_scale'][0] * self.entry['width'] entryWiggle = entryExtent...
rsnakamura/theape
setup.py
Python
mit
1,343
0.016381
try: from se
tuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages with open('readme.rst') as reader: long_description = reader.read() setup(name='theape', long_description=long_description, version=...
se = "MIT", install_requires = 'pudb numpy paramiko configobj docopt'.split(), packages = find_packages(), include_package_data = True, package_data = {"theape":["*.txt", "*.rst", "*.ini"]}, entry_points = """ [console_scripts] theape=theape.main:main [theape.subcommands] ...
victormatheus/simulated_annealing
tests/test_random.py
Python
gpl-3.0
694
0.024496
#!/usr/bin/env python import sys sys.path.append("..") import sys import getopt from time import time from simulannealing import SimulatedAnnealing as SimulAnn import graph as Graph from graph_utils import GraphGen # Tamanho previsto para as instancias aleatorias. instances = [10, 50, 100, 200, 500, 700, 1000, 1500]...
= GraphGen.generate(nodes_number=i, steiner=True) print 'Tempo de geracao: ', time()-tempo print 'Numero de termin
ais: ', len(terminals) tempo = time() steiner = SimulAnn(graph, terminals).get_min_steiner_tree() print 'Tempo de execucao da heuristica: ', time()-tempo
sdestercke/classifip
classifip/models/knn.py
Python
gpl-2.0
5,129
0.015988
from ..dataset.arff import ArffFile from scipy.spatial import kdtree, distance from ..representations.intervalsProbability import IntervalsProbability import numpy as np from math import exp class IPKNN(object): """IPKNN implements a K-nearest neighbour method using lower previsions. If data are all preci...
=[] for i in testdataset: resulting_int=np.zeros((2,len(self.classes))) query=self.tree.query(i,knn_nb_neigh) #ensure query returns li
st of array if query[0].__class__.__name__!='ndarray': query=list(query) query[0]=[query[0]] query[1]=[query[1]] for k in range(len(query[0])): #retrieve class index of kth neighbour neigh_class=self.classes.index(se...
BrainTech/openbci
obci/analysis/balance/raw_analysis.py
Python
gpl-3.0
8,820
0.031633
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl def test_signal(T=100, fs=1): dt = 1/fs x = np.arange(0, T, dt) y = np.ones(x.shape) return np.vstack((x,y)) def test_signal1(T=16.0, fs=10.0): dt = 1/fs x = np.arange(-T/2, T/2, dt) y = np.arange(-T/2, T/2, dt...
[cm]') # ax_y.set_xlim(0,30) ax_xy = f.add_subplot(122) plot_graph(ax_xy, 'COP position', signal[0][:int(fs*30)], signal[1][:int(fs*30)], 'position COPx [cm]', 'position COPy [cm]') f.canvas.draw() #f.savefig(str(file_name)+'.png') def calculate_distance(position_1, position_2): """ Returns distan...
vectors input: position1 -- int or 1-dim or 2-dim matrix position2 -- int or 1-dim or 2-dim matrix position1 and position2 must have the same dimension """ distance = position_2 - position_1 try: return (distance[0]**2+distance[1]**2)**0.5 except IndexError: return np.abs(distance) def max_sway_AP_ML(s...
smmribeiro/intellij-community
python/helpers/typeshed/tests/mypy_test.py
Python
apache-2.0
12,194
0.002952
#!/usr/bin/env python3 """Test runner for typeshed. Depends on mypy being installed. Approach: 1. Parse sys.argv 2. Compute appropriate arguments for mypy 3. Stuff those arguments into sys.argv 4. Run mypy.main('') 5. Repeat steps 2-4 for other mypy runs (e.g. --py2) """ import argparse import os import re import s...
flags + files if args.verbose: print("
running", " ".join(sys.argv)) if not args.dry_run: try: mypy_main("", sys.stdout, sys.stderr) except SystemExit as err: return err.code return 0 def get_mypy_flags(args, major: int, minor: int, temp_name: str, *, custom_typeshed: bool = False) ->...
lino-framework/book
lino_book/projects/20100206/models.py
Python
bsd-2-clause
1,674
0.007766
""" Allow empty non-nullable ForeignKey fields until save() Django Ticket #12801 (http://code.d
jangoproject.com/ticket/12801) Follow-up to Django Ticket #12708 (http://code.djangoproject.com/ticket/12708) When a model has non-nullable fields (that don't have `null=True`), then Django still accepts to instantiate objects of that model where these fields are empty. An exception is raised only when you try to
save such an (invalid) instance. Unfortunately this is not true for ForeignKey fields. If you leave a non-nullable ForeignKey field empty, Django behaves strangely: your instance is then like a time bomb, causing an exception when you only consult that field. We create an Order without a Journal: >>> o = Orde...
niwinz/Green-Mine
src/greenmine/questions/urls.py
Python
bsd-3-clause
564
0.007092
# -*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, include, url from .views import * urlpatterns = patterns('', url(r'^$', QuestionsListView.as_view(), name='questions'), url(r'^create/$', QuestionsCreateView.as_view(), name='questions-create'), url(r'^(?P<qslug>[\w\d\-]+)/view/$', Q...
url(r'^(?P<qslug>[\w\d\-]+)/delet
e/$', QuestionsDeleteView.as_view(), name='questions-delete'), )
sendgridlabs/ddbmock
tests/functional/pyramid/test_scan.py
Python
lgpl-3.0
4,332
0.001385
import json import unittest TABLE_NAME1 = 'Table-1' TABLE_RT = 45 TABLE_WT = 123 TABLE_NAME = 'Table-HR' TABLE_RT = 45 TABLE_WT = 123 TABLE_RT2 = 10 TABLE_WT2 = 10 TABLE_HK_NAME = u'hash_key' TABLE_HK_TYPE = u'N' TABLE_RK_NAME = u'range_key' TABLE_RK_TYPE = u'S' HK_VALUE1 = u'123' HK_VALUE2 = u'456' HK_VALUE3 = u'7...
E_HK_TYPE: HK_VALUE2}, TABLE_RK_NAME: {TABLE_RK_TYPE: RK_VALUE3}, u'relevant_data': {u'S': u'titi'}, } ITEM4 = { TABLE_HK_NAME: {TABLE_HK_TYPE: HK_VALUE3}, TABLE_RK_NAME: {TABLE_RK_TYPE: RK_VALUE4
}, u'relevant_data': {u'S': u'toto'}, } ITEM5 = { TABLE_HK_NAME: {TABLE_HK_TYPE: HK_VALUE3}, TABLE_RK_NAME: {TABLE_RK_TYPE: RK_VALUE5}, u'relevant_data': {u'S': u'tutu'}, } HEADERS = { 'x-amz-target': 'dynamodb_20111205.Scan', 'content-type': 'application/x-amz-json-1.0', } # Goal here is not...
deepfire/partus
cl.py
Python
gpl-3.0
412,627
0.016662
# Builtins management def python_builtins_dictionary(): import builtins as _builtins return _builtins.getattr(__builtins__, "__dict__", __builtins__) import collections class dictator(collections.UserDict): def __hasattr__(self, name): return name in self.data def __getattr__(self...
(":", "", 1, None) if maybe_keyword else ("", "", 0, len(cs) - 1) if tailed else ("", "", 0, None)) return (pre + "".join("
-" if c == "_" else c for c in cs[start:end]) + post) ret = sub(x).upper() return ret # Default values for optional/key arguments def defaulted(x, value, type = None): if x is not None and type is not None: check_type(x, type) # Not a macro, so cannot ac...
haphaeu/yoshimi
EulerProject/Sqrt2.py
Python
lgpl-3.0
1,087
0.0092
''' !!! THIS IS A MODIFICATION OF AN EULER PROBLEM !!! Instead of doing what the problem asks, this just iterates and solves sqrt(2) Project Euler - Problem 57 It is possible to show that the square root of two can
be e
xpressed as an infinite continued fraction. 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... By expanding this for the first four iterations, we get: 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... The next three expans...
laurentb/weboob
modules/apec/job.py
Python
lgpl-3.0
1,051
0
# -*- coding: utf-8 -*- # Copyright(C) 2016 Bezleputh # # This file is part of a weboob module. # # This weboob module 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, o...
long with this weboob module. If not, see <http://www.gnu.org/licenses/>. APEC_CONTRATS = { ' ': u'-- Indifférent --', '101888': u'CDI', '101887': u'CDD',
'101889': u'Interim', } APEC_EXPERIENCE = { '101882': u'Tous niveaux d\'expérience', '101881': u'Débutant', '101883': u'Expérimenté', }
dkotfis/NeuRL
src/nn.py
Python
apache-2.0
5,301
0.015846
import numpy as np class NeuralNet: def __init__(self, layers, epsilon=0.154, learningRate = 0.1): ''' Constructor Arguments: layers - a numpy array of L integers (L is # layers in the network) epsilon - one half the interval around zero for setting the initial weights ...
ector theta theta = np.empty((length-1),dtype=object) theta_vec = self.theta flag = 0 for i in range(0,length-1): s
ize = layers[i+1] * (layers[i]+1) theta[i]=theta_vec[flag:(flag+size)].reshape(layers[i+1],-1) flag = flag+size # record vector for converge condition grad = np.empty((length-1), dtype=object) derivative = np.empty((length-1),dtype=object) # perf...
rawdlite/mopidy
mopidy/mpd/protocol/music_db.py
Python
apache-2.0
16,389
0
from __future__ import absolute_import, unicode_literals import functools import itertools from mopidy.internal import deprecation from mopidy.models import Track from mopidy.mpd import exceptions, protocol, translator _SEARCH_MAPPING = { 'album': 'album', 'albumartist': 'albumartist', 'any': 'any', ...
_query_from_mpd_search_parameters(args, _SEARCH_MAPPING) except ValueError: return with deprecation.ignore('core.library.search:empty_query'): results = context.core.library.search(query=query, exact=True).get() result_tracks = [] if ('artist' not in query and 'albumartist'...
'performer' not in query): result_tracks += [_artist_as_track(a) for a in _get_artists(results)] if 'album' not in query: result_tracks += [_album_as_track(a) for a in _get_albums(results)] result_tracks += _get_tracks(results) return translator.tracks_to_mpd_format(result_tracks) @...
spiside/cqlsh
cqlshlib/copyutil.py
Python
apache-2.0
95,453
0.003499
# cython: profile=True # 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 # "...
self.writer.send(obj) def recv(self): with self.rlock: return self.reader.recv() def close(self): self.reader.close() self.writer.close() class OneWayChannels(object): """ A group of one way channels. """ def __init__(self, num_channels): se...
_ in xrange(num_channels)] self._readers = [ch.reader for ch in self.channels] self._rlocks = [ch.rlock for ch in self.channels] self._rlocks_by_readers = dict([(ch.reader, ch.rlock) for ch in self.channels]) self.num_channels = num_channels self.recv = self.recv_select if IS_L...
etingof/pysnmp
pysnmp/smi/mibs/PYSNMP-USM-MIB.py
Python
bsd-2-clause
14,623
0.000068
# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pysnmp/license.html # # ASN.1 source http://mibs.snmplabs.com:80/asn1/PYSNMP-USM-MIB # Produced by pysmi-0.4.0 at Thu Feb 14 23:15:36 2019 # if 'mibBuilder' not in globals(): impor...
B.setContactInfo("""\ E-mail: Ilya Etingof <etingof@gmail.com> GitHub: https://github.com/etingof/pysnmp """) if mibBuilder.loadTexts: pysnmpUsmMIB.setDescription("""\ This MIB module defines objects specific to User Security Model (USM) implementation at PySNMP. """) _PysnmpUsmMIBObjects_ObjectIdentity = ObjectId...
ectIdentity( (1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1) ) _PysnmpUsmCfg_ObjectIdentity = ObjectIdentity pysnmpUsmCfg = _PysnmpUsmCfg_ObjectIdentity( (1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1) ) class _PysnmpUsmDiscovery_Type(Integer32): defaultValue = 1 subtypeSpec = Integer32.subtypeSpec subtypeSpec +=...
appsembler/edx-platform
lms/djangoapps/teams/tests/test_api.py
Python
agpl-3.0
16,102
0.003167
# -*- coding: utf-8 -*- """ Tests for Python APIs of the Teams app """ from uuid import uuid4 import ddt import mock from opaque_keys.edx.keys import CourseKey from course_modes.models import CourseMode from lms.djangoapps.teams import api as teams_api from lms.djangoapps.teams.models import CourseTeam from lms.djan...
sertTrue(teams_api.discussion_visible_by_user(self.team2.discussion_topic_id, self.user2)) self.assertTrue(teams_api.discussion_visible_by_user('DO_NOT_EXISTS', self.user3)) @ddt.unpack @ddt.data( (COURSE_KEY1, TOPIC1, ['team1', 'team1', None, 'team1a']), (COURSE_KEY1, TOPIC2, [None, No...
ne, None, None]), (COURSE_KEY2, TOPIC2, [None, None, 'team2', 'team2a']), ) def test_get_team_for_user_course_topic(self, course_key, topic_id, expected_team_ids): user1_team = teams_api.get_team_for_user_course_topic(self.user1, str(course_key), topic_id) user2_team = teams_api.get_team...
bhdouglass/agui
agui/backends/gtk/widgets/button.py
Python
gpl-3.0
1,417
0.003529
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # Copyright (C) 2014 Brian Douglass bhdouglass@gmail.com # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Softwa...
vent', self.emit_pressed) @AButton.text.gette
r def text(self): self._text = self.item.get_label() return self._text @text.setter def text(self, value): self.item.set_label(value) self._text = value @AButton.icon.setter def icon(self, value): self.item.set_image(value.icon()) self._icon = value
jadams/rarbg-get
rarbg-get.py
Python
mit
409
0.007335
#!env /usr/bin/python3 import sys import urllib.parse import urllib.
request def main(): search = sys.argv[1] url = 'http://rarbg.to/torrents.php?order=seeders&by=DESC&search='
url = url + search print(url) req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) resp = urllib.request.urlopen(req) respData = resp.read() if __name__ == '__main__': main()
PublicaMundi/pycsw
pycsw/log.py
Python
mit
3,506
0
# -*- coding: iso-8859-15 -*- # ================================================================= # # Authors: Tom Kralidis <tomkralidis@gmail.com> # # Copyright (c) 2011 Tom Kralidis # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files...
.loglevel).') if not config.has_option('server', 'logfile'): raise RuntimeError( 'Invalid server configuration (server.loglevel set,\ but server.logfile missing).') if config.has_option('server', 'logfile'): if not config.has_option('server', 'loglevel')...
nfiguration (server.logfile set,\ but server.loglevel missing).') logfile = config.get('server', 'logfile') if loglevel != 'NOTSET' and logfile is None: raise RuntimeError( 'Invalid server configuration \ (server.loglevel set, but server.logfile is not).') ...
otherway/sepa-tools
account_payment_export/model/payment_mode.py
Python
agpl-3.0
1,830
0.001093
# -*- coding: utf-8 -*- ########################################
###################################### # # Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>). # (C) 2011 - 2013 Therp BV (<http://therp.nl>). # # All other contributions are (C) by their respective contributo
rs # # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program i...
ttakamura/chainer
examples/imagenet/train_imagenet.py
Python
mit
9,557
0.002616
#!/usr/bin/env python """Example code of learning a large scale convnet from ILSVRC2012 dataset. Prerequisite: To run this example, crop the center of ILSVRC2012 training and validation images and scale them to 256x256, and make two lists of space- separated CSV whose first column is full path to image and second colu...
egin_at throughput = val_count / duration sys.stderr.write( '\rval {} batches ({} samples) time: {} ({} images/sec)' .format(val_count / ar
gs.val_batchsize, val_count, timedelta(seconds=duration), throughput)) val_loss += loss val_accuracy += accuracy if val_count == 50000: mean_loss = val_loss * args.val_batchsize / 50000 mean_error = 1 - val_accuracy * args.val...
alladdin/plugin.video.primaplay
libPrimaPlay/PrimaPlay_unittest.py
Python
gpl-2.0
12,829
0.006255
# -*- coding: utf-8 -*- import unittest import os, sys import PrimaPlay import urllib2 os.chdir(os.path.dirname(sys.argv[0])) user = 'text@example.com'; password = 'password'; class mockTime: def time(self): return 1450875766 class mockUserAgent: def __init__(self, url_map = {}): self.ua = ...
ssertEqual(len(page.video_lists[0].item_list), 20) self.assertEqual(page.video_lists[0].item_list[0].title, u'Prostřeno! Sezóna 12: Epizoda 9') self.
assertEqual(page.video_lists[0].item_list[0].link, 'http://play.iprima.cz/prostreno/videa/prostreno-xii-9') def test_get_page__player_page_2(self): prima_play = PrimaPlay.Parser(mockUserAgent(), mockTime()) page = prima_play.get_page('http://play.iprima.cz/cestovani-cervi-dirou-s-morgan...
atarola/pyjojo
pyjojo/util.py
Python
mit
1,563
0.006398
#!/usr/bin/env python import os import pkgutil import logging import sys import tornado.web from pyjojo.config import config from pyjojo.scripts import create_collection log = logging.getLogger(__name__) class route(object): """ decorates RequestHandlers and builds up a list of routables handlers ...
name = self.name and self.name or _handler.__name__ self._routes.append(tornado.web.url(self._uri, _handler, name=name)) return _handler @classmethod def get_routes(self): return self._routes def setup_logging(): """ setup the logging system """ base_log = logging.getLogg...
_log.addHandler(handler) base_log.setLevel(logging.DEBUG) return handler def create_application(debug): # import the handler file, this will fill out the route.get_routes() call. import pyjojo.handlers application = tornado.web.Application( route.get_routes(), scripts=create_colle...
BitWriters/Zenith_project
zango/lib/python3.5/site-packages/pip/_vendor/html5lib/_inputstream.py
Python
mit
32,532
0.0004
from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type, binary_type from pip._vendor.six.moves import http_client, urllib import codecs import re from pip._vendor import webencodings from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase from .con...
in previous chunks self.prevNumLines = 0 # number of columns in the last line of the previous chunk self.prevNumCols = 0 # Deal with CR LF and surrogates split over chunk boundaries self._bufferedCharacter = None def openStream(self, source): """Produces a file obje...
): stream = source else: stream = StringIO(source) return stream def _position(self, offset): chunk = self.chunk nLines = chunk.count('\n', 0, offset) positionLine = self.prevNumLines + nLines lastLinePos = chunk.rfi
JBmiog/IOT
server_script/tests/email_handler_tests.py
Python
gpl-3.0
279
0.003584
import unittest import email_hand
ler class EmailHandlerTest(unittest.TestCase): def test_tx_email(self): message = "Subject: License plates scan results\n\n" ms = email_handler.Emailer() result = ms.tx_email(message)
self.assertTrue(result)
LyleMi/Trafficker
Trafficker/packets/packet.py
Python
mit
5,253
0.000381
#!/usr/bin/env python # -*- coding: utf-8 -*- import time from Trafficker.layer.arp import ARP from Trafficker.layer.cldap import CLDAP from Trafficker.layer.dns import DNS from Trafficker.layer.http import HTTP from Trafficker.layer.icmp import ICMP from Trafficker.layer.igmp import IGMP from Trafficker.layer.ip imp...
eader['GMTtime'], self.header['MicroTime'], self.header['caplen'], self.header['len'] = header.unpack("IIII") print(self.header) data = Buffer(data) mac = ETHER.unpack(data.get(14)) self.len = len(data) self.mac = mac self.layers = [mac] se
lf.srcip = "" self.dstip = "" self.protocol = "" self.srcp = 0 self.dstp = 0 ntype = mac.type if mac.type == ETHER.ethertypes["VLAN"]: vlan = VLAN.unpack(data.get(4)) self.layers.append(vlan) ntype = vlan.type if ntype == ETHE...
calpeyser/google-cloud-python
trace/google/cloud/trace/client.py
Python
apache-2.0
6,103
0
# Copyright 2017 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 or agreed to in writing, ...
me_to_pb_timestamp(end_time) return self.trace_api.list_traces( project_id=project_id, view=view, page_size=page_size, st
art_time=start_time, end_time=end_time, filter_=filter_, order_by=order_by, page_token=page_token)
NetASM/PyDatapath
pydatapath/utils/__init__.py
Python
gpl-3.0
5,607
0.000535
__author__ = 'shahbaz' # ############################################################################### # Utility functions # # ############################################################################### import sys from functools import wraps from logg...
""" :return: """ return self._dict.values() def items(self): """ :return: """ return self._dict.items() def iterkeys(self): """ :return: """ return self._dict.iterkeys() def itervalues(self): """...
""" return self._dict.itervalues() def iteritems(self): """ :return: """ return self._dict.iteritems() def get(self, key, default=None): """ :param key: :param default: :return: """ return self._dict.get(key, def...
orhaneee/machineLearning
MLE1.py
Python
gpl-3.0
7,728
0.024586
import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import os print(os.getcwd()) # Part 1: Load the data and separate it into three arrays; one for each class data = np.loadtxt("MLE1_iris.data") data0 = data[0:50,:] data1 = data[50:100,:] data2 = d...
ta_test[:,4]==0] data_test1 = data_test[data_test[:,4]==1] data_test2 = data_test[data_test[:,4]==2] data_train0 = data_train[data_train[:,4]==0] data_train1 = data_train[data_train[:,4]==1] data_train2 = data_train[data_train[:,4]==2] ''' Second part of homework.
Calculations : @mean, @cov''' mx0_train = np.mean(data_train0[:,2]) my0_train = np.mean(data_train0[:,3]) mx1_train = np.mean(data_train1[:,2]) my1_train = np.mean(data_train1[:,3]) mx2_train = np.mean(data_train2[:,2]) my2_train = np.mean(data_train2[:,3]) cov0_train = np.cov(dat...
lssfau/walberla
tests/lbm/codegen/InplaceStreamingCodegen.py
Python
gpl-3.0
4,302
0.006044
from dataclasses import replace from lbmpy_walberla import generate_alternating_lbm_sweep, generate_boundary, generate_alternating_lbm_boundary from pystencils_walberla import CodeGeneration, generate_sweep, generate_info_header from pystencils import Target, CreateKernelConfig from lbmpy import LBMConfig, LBMOptimis...
generate_alternating_lbm_boundary(ctx, 'InPlaceOutflow', outflow_inplace, lb_method, streaming_pattern=inplace_pattern, after_collision=True, target=target, namespace=namespace) generate_sweep(ctx, 'InPlaceInit', init_kernel_inplace, t...
_info_header(ctx, "InplaceStreamingCodegen.h", stencil_typedefs=stencil_typedefs, field_typedefs=field_typedefs)
chouseknecht/ansible
lib/ansible/modules/cloud/google/gcp_container_node_pool.py
Python
gpl-3.0
38,588
0.003706
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
str name: description: - The name of the node pool. required: false type: str config: description: - The node configuration of the pool. required: false type: dict suboptions: machine_type: description: - The name of a Google Compute Engine machine type (e.g...
alse type: str disk_size_gb: description: - Size of the disk attached to each node, specified in GB. The smallest allowed disk size is 10GB. If unspecified, the default disk size is 100GB. required: false type: int oauth_scopes: description: ...
Menollo/menosic
client/main.py
Python
gpl-3.0
2,756
0
import json import random import ssl import string import threading import time import websocket import settings from player import Player class WebsocketPlayerControl(object): def __init__(self, player, server=settings.WS_SERVER): websocket.enableTrace(settings.DEBUG) rand_chars = string.ascii_...
nd(json.dumps(data)) def start(self): while True: if settings.DEBUG: print('opening websocket connection...') sslopt = {"cert_reqs": ssl.CERT_NONE} self.ws.run_forever(ping_interval=60, sslopt=sslopt) time.sleep(10) def quit(self): ...
T_NAME except AttributeError: name = 'Client' data = { 'action': 'register', 'player': self.player_id, 'key': settings.CLIENT_TOKEN, 'playlist': settings.PLAYLIST_ID, 'name': name } ws.send(json.dumps(data)) ...
rocky/python2-trepan
trepan/inout/base.py
Python
gpl-3.0
5,570
0.000359
# -*- coding: utf-8 -*- # Copyright (C) 2009, 2014-2015 Rocky Bernstein <rocky@gnu.org> # # 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...
s an abstract class that specifies debugger output. """ def __init__(self, out=None, opts=None): self.output = None return def close(self): if self.output: self.output.close()
pass return def flush(self): raise NotImplementedError(NotImplementedMessage) def write(self, output): """Use this to set where to write to. output can be a file object or a string. This code raises IOError on error. """ raise NotImplementedError(NotImp...
dhamaniasad/urbandefinition
setup.py
Python
unlicense
568
0.001761
from setuptools im
port setup install_requires = [ 'reques
ts', 'beautifulsoup4' ] setup( name='urbandefinition', install_requires=install_requires, version=0.3, description='Get Urban Dictionary definitions from the terminal', author='Asad Dhamani', author_email='dhamaniasad+code@gmail.com', url='https://github.com/dhamaniasad/urbandefinition'...
OpenSmalltalk/vm
processors/ARM/gdb-8.3.1/gdb/python/lib/gdb/command/frame_filters.py
Python
mit
16,256
0.002461
# Frame-filter commands. # Copyright (C) 2013-2019 Free Software Foundation, Inc. # 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 late...
ts: cmd_name: Name of the command invoking this function. args: The argument as a string. Returns: A tuple containing the dictionary, and the argument, or just the dictionary in the case of "all". """ arg
v = gdb.string_to_argv(arg); argc = len(argv) if argc == 0: raise gdb.GdbError(cmd_name + " requires an argument") if argv[0] == "all": if argc > 1: raise gdb.GdbError(cmd_name + ": with 'all' " \ "you may not specify a filter.") elif argc != 2:...
flyingoctopus/three.js
utils/exporters/cinema4d/export_to_three.js.py
Python
mit
8,574
0.013296
''' author : "George Profenza" url : ("disturb", "disturbmedia.com/blog","My blog, http://tomaterial.blogspot.com") Export meshes the three.js 3D Engine by mr.doob's et al. More details on the engine here: https://github.com/mrdoob/three.js Currently supports UVs. If the model doesn't display correctly you might ...
or(0, 1, 0)} code += '\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f);\n' % (uv['a'].x, uv['a'].y, uv['b'].x, uv['b'].y, uv['b
'].x, uv['b'].y, uv['c'].x, uv['c'].y) else: code += '\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f);\n' % (uv['a'].x, uv['a'].y, uv['b'].x, uv['b'].y, uv['c'].x, uv['c'].y) ncount += 1 uvcount += 1 code +='\n\tthis.computeCentroids();\n\tthis.compu...
OpenNFT/OpenNFT
opennft/plugins/onp_roiswglm.py
Python
gpl-3.0
3,813
0.002098
# -*- coding: utf-8 -*- """ # Plugins Plugins allow flexible modification and execution of OpenNFT without touching the core codebase. Plugins can access data, process them in a specific way, and they can be switched on and off according to the user's need. Each plugin has to be a subclass of *Process class specified...
e execution code of the plugin, and it is usually calls the plugin's load_data method to transfer some data to the plugin. *Process classes pyniexp.mlplugins has an abstract/placeholder method called process, which should be overwritten to specify the operation on the data. - the input to the process method of dataPro...
rocess (called image) is a multi-dimensional (usually 3D) numpy array as specified during initialization # ROI step-wise GLM This plugin demonstrates how to add you own approach (this one is a step-wise addition of each block) for ROI analysis. _________________________________________________________________________...
MaximKsh/web_1sem
repository/askkashirin/askservice/models.py
Python
unlicense
3,753
0.000576
from django.db import models from django.contrib.auth.models import User from django.db.models import Sum, Q # Create your models here. class Profile(models.Model): avatar = models.ImageField( verbose_name=u'Аватар', blank=True ) description = models.TextField( verbose_name=u'Описа...
e = u'Лайк' verbose_name_plural = u'Лайки' def __str__(self): return str(self.rating) class QuestionManager(models.Manager): def newest(self): return self.order_by('-creation_date') def hot(self): return self.annotate(Sum('like__rating')).order_by('-like__rating__sum')
def byTag(self, tag): return self.filter(tags__tag=tag) def find(self, query): return self.filter(Q(title__contains=query) | Q(content__contains=query)) class Question(Post): title = models.CharField( max_length=255, verbose_name=u'Название' ) content = models.Te...
jahan-addison/gridpaste
pastes/migrations/0001_initial.py
Python
mit
638
0.001567
# Generated by Django 2.1.7 on 2019-04-26 07:20 from django.db import migrations, mod
els from django.contrib.postgres.fields import JSONField class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Pastes', fields=[ ('id', models.AutoField(primary_key=True, serialize=True)),...
Field()), ], ), ]
bobbypaton/GoodVibes
goodvibes/__main__.py
Python
mit
485
0
# let guys could run Goodvibes by python -m goodvibe
s <args> # Copied from __main__.py in pip from __future__ import absolute_import import os import sys # If we are run
ning from a wheel, add the wheel to sys.path # This allows the usage python pip-*.whl/pip install pip-*.whl if __package__ == '': path = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, path) from goodvibes import GoodVibes # noqa if __name__ == '__main__': sys.exit(GoodVibes.main())
nilver/MiniProyecto
utils.py
Python
apache-2.0
693
0.010101
import numpy as np def softmax(x): xt = np.exp(x - np.max(x)) return
xt / np.sum(xt) def save_model_parameters_theano(outfile, model): U, V, W = model.U.get_value(), model.V.get_value(), model.W.get_
value() np.savez(outfile, U=U, V=V, W=W) print "Saved model parameters to %s." % outfile def load_model_parameters_theano(path, model): npzfile = np.load(path) U, V, W = npzfile["U"], npzfile["V"], npzfile["W"] model.hidden_dim = U.shape[0] model.word_dim = U.shape[1] model.U.set_value(U...
GHOSTnew/HelpBot
HelpBot.py
Python
gpl-3.0
5,517
0.010332
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################# Copyright ################################ # Author: GHOSTnew # 2014 # ######################################################################## # This file is part of HelpBot. ...
'.join(data.split (':')[2:])).split( )[0] channe
l = ''.join (data.split(':')[:2]).split (' ')[-2] nick_source = (data.split (':')[1]).split('!')[0] arg = data.split(" ") args = '' for index,item in enumerate(arg) : if index > 3 : if args == '': args = item ...