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 |
|---|---|---|---|---|---|---|---|---|
rushter/MLAlgorithms | mla/pca.py | Python | mit | 1,758 | 0.000569 | # coding:utf-8
import logging
import numpy as np
from scipy.linalg import svd
from mla.base import BaseEstimator
np.random.seed(1000)
class PCA(BaseEstimator):
y_required = False
def __init__(self, n_components, solver="svd"):
"""Principal component analysis (PCA) implementation.
Transfor... | f self.solver == "eigen":
s, Vh = np.linalg.eig(np.cov(X.T))
Vh = Vh.T
s_squared = s ** 2
variance_ratio | = s_squared / s_squared.sum()
logging.info("Explained variance ratio: %s" % (variance_ratio[0: self.n_components]))
self.components = Vh[0: self.n_components]
def transform(self, X):
X = X.copy()
X -= self.mean
return np.dot(X, self.components.T)
def _predict(self, X=N... |
kimgea/simple_twitter_functions | twitter_functions/twitter/whitelisted_users.py | Python | mit | 119 | 0.016807 | " | ""
Add user scren name to whitelist if it is not to be unfollowed
"""
whitelist = [
| ] |
didzis/CAMR | graphstate.py | Python | gpl-2.0 | 68,252 | 0.013406 | #!/usr/bin/python
# parsing state representing a subgraph
# initialized with dependency graph
#
from __future__ import absolute_import
import copy,sys,re
import cPickle
from parser import *
from common.util import *
from constants import *
from common.SpanGraph import SpanGraph
from common.AMRGraph import *
import num... | sent[children[idx_order+1]] if idx_order < len(children)-1 else NOT_ASSIGNED
sr2sb = GraphState.sent[children[idx_order+2]] if idx_order < len(children)-2 else NOT_ASSIGNED
else:
slsb = EMPTY
srsb = EMPTY
sr2sb = EMPTY
'''
# left first par... | idx].parents[0] < self.idx else NOT_ASSIGNED
# right last child of current child
brc1 = GraphState.sent[self.deptree.nodes[self.cidx].children[-1]] if self.cidx and self.A.nodes[self.cidx].children and self.A.nodes[self.cidx].children[-1] > self.cidx else NOT_ASSIGNED
# left first parent of cur... |
nagyistoce/netzob | src/netzob/Common/Models/L3NetworkMessage.py | Python | gpl-3.0 | 4,102 | 0.008787 | # -*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocol... | |
#| (at your option) any later version. |
#| |
#| This program is distributed in the hope that it will be useful, |
#| but WITHOUT | ANY WARRANTY; without even the implied warranty of |
#| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
#| GNU General Public License for more details. |
#| |
#| You should have ... |
christopherjbly/calendar-indicator | src/calendarindicator.py | Python | gpl-3.0 | 17,542 | 0.039813 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
__author__='atareao'
__date__ ='$25/04/2011'
#
# Remember-me
# An indicator for Google Calendar
#
# Copyright (C) 2011 Lorenzo Carbonell
# lorenzo.carbonell.cerezo@gmail.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the ... | flags = Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
type = Gtk.MessageType.ERROR,
buttons = Gtk.ButtonsType.OK_CANCEL,
message_format = _('You have to authorize Calendar-Indicato | r to manage your Google Calendar.\n Do you want to authorize?'))
if md.run() == Gtk.ResponseType.CANCEL:
exit(3)
md.destroy()
else:
self.googlecalendar = GoogleCalendar(token_file = comun.TOKEN_FILE)
if self.googlecalendar.do_refresh_authorization() is None:
error = False
else:
... |
trezor/trezor-crypto | tests/test_wycheproof.py | Python | mit | 21,271 | 0.000658 | #!/usr/bin/env python
import ctypes
import json
import os
from binascii import hexlify, unhexlify
import pytest
from pyasn1.codec.ber.decoder import decode as ber_decode
from pyasn1.codec.der.decoder import decode as der_decode
from pyasn1.codec.der.encoder import encode as der_encode
from pyasn1.type import namedtype... | :
raise ParseError("Not a valid DER encoded ECDSA signature")
try:
r = int(signature["r"]).to_bytes(32, byteorder="big")
s = int(signature["s"]).to_bytes(32, byteorder="big")
signature = r + s
except Exception:
raise ParseError("Not a valid DER encoded 256 bit ECDSA signa... | gnature
def parse_digest(name):
if name == "SHA-256":
return 0
else:
raise NotSupported("Unsupported hash function: {}".format(name))
def get_curve_by_name(name):
lib.get_curve_by_name.restype = ctypes.c_void_p
curve = lib.get_curve_by_name(bytes(name, "ascii"))
if curve is None:... |
vlfedotov/django-business-logic | tests/rest/test_reference.py | Python | mit | 4,996 | 0.001401 | # -*- coding: utf-8 -*-
from .common import *
class ReferenceDescriptorTest(TestCase):
def setUp(self):
self.reference_descriptor = ReferenceDescriptor.objects.create(
content_type=ContentType.objects.get_for_model(Model))
self.client = JSONClient()
def test_reference_descriptor... | ic:rest:reference-list', kwargs=dict(model=model)), descriptor['url'])
def test_unregistered_reference_list_not_found(self):
model = 'business_logic.ReferenceDescriptor'
url = reverse('business-logic:rest:reference-list', kwargs=dict(model=model))
response = self.client.get(url)
sel... | ot_found(self):
for model in ('ooo.XXX', 'password'):
url = reverse('business-logic:rest:reference-list', kwargs=dict(model=model))
response = self.client.get(url)
self.assertEqual(404, response.status_code)
class ReferenceListTest(TestCase):
def setUp(self):
s... |
MeeseeksBox/MeeseeksDev | meeseeksdev/commands.py | Python | mit | 6,864 | 0.002477 | """
Define a few commands
"""
from .meeseeksbox.utils import Session, fix_issue_body, fix_comment_body
from .meeseeksbox.scopes import admin, write, everyone
from textwrap import dedent
def _format_doc(function, name):
if not function.__doc__:
doc = " "
else:
doc = function.__doc__.splitli... | epo}/labels".format(
org=org, repo=repo
),
None,
).json()
available_labels = [l["name"] for l in available_labels]
migrate_ | labels = [l for l in original_labels if l in available_labels]
not_set_labels = [l for l in original_labels if l not in available_labels]
new_response = target_session.create_issue(
org,
repo,
issue_title,
fix_issue_body(
issue_body,
original_poster,
... |
atphalix/eviltoys | tools/myscripts/mdl_export.py | Python | gpl-2.0 | 38,523 | 0.052384 | #!BPY
"""
Name: 'MDL (.mdl)'
Blender: 244
Group: 'Export'
Tooltip: 'Export to Quake file format (.mdl).'
"""
__author__ = 'Andrew Denner'
__version__ = '0.1.3'
__url__ = ["Andrew's site, http://www.btinternet.com/~chapterhonour/",
"Can also be contacted through http://celephais.net/board", "blender", "elysiun"]
... |
# Export globals
g_filename=Create("default.mdl")
g_frame_filename=Create("default")
g_filename_search=Create("")
g_frame_search=Create("default")
user_frame_list=[]
|
#Globals
g_scale=Create(1.0)
g_fixuvs=Create(0)
g_flags=Create(0)
# Events
EVENT_NOEVENT=1
EVENT_SAVE_MDL=2
EVENT_CHOOSE_FILENAME=3
EVENT_CHOOSE_FRAME=4
EVENT_EXIT=100
######################################################
# Callbacks for Window functions
######################################################
def fi... |
Tendrl/node_agent | tendrl/node_agent/node_sync/disk_sync.py | Python | lgpl-2.1 | 18,338 | 0.000327 | import os
import unicodedata
from tendrl.commons.event import Event
from tendrl.commons.message import ExceptionMessage
from tendrl.commons.utils import cmd_utils
from tendrl.commons.utils import etcd_utils
from tendrl.commons.utils import log_utils as logger
def sync():
try:
_keep_alive_for = int(NS.con... | block_devices(disk_map)
for disk in disks:
if disk_map[disks[disk]['disk_name']]:
disks[disk]['ssd'] = disk_map[disks[disk][
'disk_name']]['ssd'] |
if "virtio" in disks[disk]["driver"]:
# Virtual disk
NS.tendrl.objects.VirtualDisk(**disks[disk]).save(
ttl=_keep_alive_for
)
else:
# physical disk
NS.tendrl.objects.Disk(**disks[disk]).save(ttl... |
sergeeva-olga/decree-server | setup.py | Python | gpl-3.0 | 3,119 | 0.002886 | # This is your "setup.py" file.
# See the following sites for general guide to Python packaging:
# * `The Hitchhiker's Guide to Packaging <http://guide.python-distribute.org/>`_
# * `Python Project Howto <http://infinitemonkeycorps.net/docs/pph/>`_
from setuptools import setup, find_packages
import sys
import os
#... | EB Semantics JavaScript',
author='Evgeny Cherkashin',
author_email='eugeneai@irnok.net',
url='https://github.com/sergeeva-olga/decree-server',
license='GPL>=2',
packages=find_packages("src"),
package_dir={'': "src"},
namespace_packages=['isu'],
include_package_data=True,
zip_safe=Fal... | },
test_suite='tests',
entry_points="""\
[paste.app_factory]
main=isu.aquarium.server:main
""",
#ext_modules = cythonize(ext_modules),
#test_suite = 'nose.collector',
# setup_requires=['nose>=1.0','Cython','coverage']
)
|
saleem-latif/GeoCode | tests/unittest_geocode.py | Python | gpl-2.0 | 1,541 | 0 | from testscenarios import TestWithScenarios
import unittest
from geocode.geocode import GeoCodeAccessAPI
class GeoCodeTests(TestWithScenarios, unittest.TestCase):
scenarios = [
(
"Scenario - 1: Get latlng from address",
{
'address': "Sydney NSW",
'l... | ss
expected_lat = self.latlng[0]
expected_lng = self.latlng[1]
geocode = self.api.get_geocode(expected_address)
self.assertAlmostEqual(geocode.lat, expected_lat | , delta=5)
self.assertAlmostEqual(geocode.lng, expected_lng, delta=5)
self.assertIn(expected_address, geocode.address)
else:
expected_address = self.address
expected_lat = self.latlng[0]
expected_lng = self.latlng[1]
address = self.api.ge... |
visipedia/tf_classification | tfserving/client.py | Python | mit | 2,561 | 0.0164 | """
A simple client to query a TensorFlow Serving instance.
Example:
$ python client.py \
--images IMG_0932_sm.jpg \
--num_results 10 \
--model_name inception \
--host localhost \
--port 9000 \
--timeout 10
Author: Grant Van Horn
"""
from __future__ import absolute_import
from __future__ import division
from __futur... | parser.add_argument('--timeout', dest='timeout',
help='Amount of time to wait before fail | ing.',
required=False, type=int, default=10)
args = parser.parse_args()
return args
def main():
args = parse_args()
# Read in the image bytes
image_data = []
for fp in args.image_paths:
with open(fp) as f:
data = f.read()
image_data.append(data)
# Get the predicti... |
nateprewitt/pipenv | pipenv/vendor/backports/shutil_get_terminal_size/__init__.py | Python | mit | 338 | 0 | """A backport of the get_termina | l_size function from Python 3.3's shutil."""
__title__ = "bac | kports.shutil_get_terminal_size"
__version__ = "1.0.0"
__license__ = "MIT"
__author__ = "Christopher Rosell"
__copyright__ = "Copyright 2014 Christopher Rosell"
__all__ = ["get_terminal_size"]
from .get_terminal_size import get_terminal_size
|
welliam/imagersite | user_profile/tests.py | Python | mit | 2,830 | 0 | from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from .models import UserProfile
from imagersite.tests import AuthenticatedTestCase
# Create your tests here.
class ProfileTestCase(TestCase):
"""TestCase for Profile"""
def setUp(self):
"""Set... | )
def | test_profile_page_has_photo_count(self):
self.log_in()
self.assertIn(
b'Photos uploaded:',
self.client.get('/profile/').content
)
def test_profile_page_has_album_count(self):
self.log_in()
self.assertIn(b'Albums created:', self.client.get('/profile/'... |
alphagov/notifications-api | migrations/versions/0146_add_service_callback_api.py | Python | mit | 2,779 | 0.010076 | """
Revision ID: 0146_add_service_callback_api
Revises: 0145_add_notification_reply_to
Create Date: 2017-11-28 15:13:48.730554
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = '0146_add_service_callback_api'
down_revision = '0145_add_notification_reply_to'
de... | (op.f('ix_service_callback_api_history_service_id'), 'service_callback_api_history',
['service_id'], unique=False)
op.create_index(op.f('ix_service_callback_api_history_updated_by_id'), 'service_callback_api_history',
['updated_by_id'], unique=False)
op.create_table('serv... | olumn('url', sa.String(), nullable=False),
sa.Column('bearer_token', sa.String(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('updated_by_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('vers... |
kragniz/mypaint | brushlib/doc/source/conf.py | Python | gpl-2.0 | 8,376 | 0.007283 | # -*- coding: utf-8 -*-
#
# libmypaint documentation build configuration file, created by
# sphinx-quickstart2 on Wed Jun 13 23:40:45 2012.
#
# 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.
#
#... | ----
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'libmypaint', u'libmypaint Documentation',
u'MyPaint Development Team', 'libmypaint', 'One line description of project.',... |
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'foo |
tongpa/pypollmanage | pypollmanage/controllers/__init__.py | Python | apache-2.0 | 119 | 0.008403 | # -*- coding: utf-8 -*-
"""Controllers for the pypollmanage pluggab | le application | ."""
from .root import RootController |
Comunitea/CMNT_00098_2017_JIM_addons | jim_invoice/models/general_ledger_wizard.py | Python | agpl-3.0 | 545 | 0.003676 | # -*- coding: utf-8 -*-
# © 2016 Comunitea
# L | icense AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, fields, models
class GeneralLedgerReportWizard(models.TransientModel):
_inherit = "general.ledger.report.wizard"
@api.onchange('company_id')
def onchange_company_id(self):
res = super(GeneralLedgerReportWizard, se... | turn res |
yatinkumbhare/openstack-nova | nova/virt/configdrive.py | Python | apache-2.0 | 9,964 | 0.000401 | # Copyright 2012 Michael Still and Canonical 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
#
# ... | '-allow-lowercase',
'-allow-multidot',
'-l',
'-publisher',
publisher,
'-quiet',
'-J',
'-r',
| '-V', 'config-2',
tmpdir,
attempts=1,
run_as_root=False)
def _make_vfat(self, path, tmpdir):
# NOTE(mikal): This is a little horrible, but I couldn't find an
# equivalent to genisoimage for vfat filesystems.
... |
cytex124/celsius-cloud-backend | src/addons/management_user/admin.py | Python | mit | 408 | 0 | from djan | go.contrib.admin.models import LogEntry
from django.contrib.auth.models import User, Group, Permission
from simple_history import register
from celsius.tools import register_for_permission_handling
register(User | )
register(Group)
register_for_permission_handling(User)
register_for_permission_handling(Group)
register_for_permission_handling(Permission)
register_for_permission_handling(LogEntry)
|
RobSpectre/garfield | garfield/voice/tests/test_models.py | Python | mit | 499 | 0 | from django.test import TestCase
from voice.models import Call
class CallModelTestCase(TestCase):
de | f setUp(self):
self.call = Call(sid="CAxxx",
from_number="+15558675309",
to_number="+15556667777")
self.call.save()
def test_string_representation(self):
self.assertEqual(str(self.call),
"{0}: from +1555867530 | 9 to "
"+15556667777".format(self.call.date_created))
|
TAMU-CPT/galaxy-tools | tools/phage/phage_annotation_table.py | Python | gpl-3.0 | 19,472 | 0.004725 | #!/usr/bin/env python
# vim: set fileencoding=utf-8
import os
import argparse
from gff3 import genes, get_gff3_id, get_rbs_from, feature_test_true, feature_lambda, feature_test_type
from cpt_gffParser import gffParse, gffWrite
from Bio import SeqIO
from jinja2 import Environment, FileSystemLoader
import logging
from ma... | rn "None"
else:
resp = []
for rbs in rbss:
cdss = list(genes(feature.sub_features, feature_type="CDS", sort=True))
if len(cdss) == 0:
return "No CDS"
if rbs.location.strand > 0:
distance = min(
... | )
distance_val = str(distance.location.start - rbs.location.end)
resp.append(distance_val)
else:
distance = min(
cdss, key=lambda x: x.location.end - rbs.location.start
)
... |
ntt-sic/nova | nova/tests/api/openstack/compute/plugins/v3/test_scheduler_hints.py | Python | apache-2.0 | 12,196 | 0.000246 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apac... | pass
def project_get_networks(context, user_id):
return dict(id='1', host='localhost')
def queue_get_for(context, *args):
return 'network_topic'
fakes.stub_out_rate_limiting(self.stubs)
fakes.stub_out_key_ | pair_funcs(self.stubs)
fake.stub_out_image_service(self.stubs)
fakes.stub_out_nw_api(self.stubs)
self.stubs.Set(uuid, 'uuid4', fake_gen_uuid)
self.stubs.Set(db, 'instance_add_security_group',
return_security_group)
self.stubs.Set(db, 'project_get_networks',... |
guaix-ucm/numina | numina/array/combine.py | Python | gpl-3.0 | 9,851 | 0.000203 | #
# Copyright 2008-2018 Universidad Complutense de Madrid
#
# This file is part of Numina
#
# SPDX-License-Identifier: GPL-3.0+
# License-Filename: LICENSE.txt
#
"""Different methods for combining lists of arrays."""
import numpy
import numina.array._combine as intl_combine
CombineError = intl_combine.CombineErro... | es,
weights=weights)
def median(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None,
weights=None):
"""Combine arrays using the median, with masks.
Arrays and masks are a list of array objects. All input arrays
have the same shape. If present... | t[1] the variance and out[2] the number of points used.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:return: median, variance of the median an... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.5/django/db/models/constants.py | Python | bsd-3-clause | 118 | 0.008475 | """
Constants used across the ORM in general.
"""
# Separato | r used to split filter | strings apart.
LOOKUP_SEP = '__'
|
douggeiger/gnuradio | gr-blocks/python/blocks/qa_multiply_matrix_ff.py | Python | gpl-3.0 | 4,810 | 0.009356 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 versio... | if A2 is not None:
self.multiplier.set_A(A2)
A = A2
A_matrix = numpy.matrix(A)
for i in xrange(N):
if tags is None:
these_tags = ()
else:
these_tags = (tags[i],)
self.tb.connect(blocks.vector_source_f(X... | ):
sinks.append(blocks.vector_sink_f())
self.tb.connect((self.multiplier, i), sinks[i])
# Run and check
self.tb.run()
for i in xrange(X_in.shape[1]):
Y_out_exp[:,i] = A_matrix * X_in[:,i]
Y_out = [list(x.data()) for x in sinks]
if tags is not N... |
oyajiro/l2bot | hf/wl.py | Python | artistic-2.0 | 2,661 | 0.007516 | import pyautogui, win32api, win32con, ctypes, autoit
from PIL import ImageOps, Image, ImageGrab
from numpy import *
import os
import time
import cv2
import random
from Bot import *
def main():
bot = Bot()
autoit.win_wait(bot.title, 5)
counter = 0
poitonUse = 0
cycle = True
fullCounter = 0
... | ot.title, '', '{F8}', 0)
# counter = 0
counter += 1
print 'cnt ' | + str(counter)
pass
if __name__ == '__main__':
main()
|
AlienCowEatCake/ImageViewer | src/ThirdParty/Exiv2/exiv2-0.27.5-Source/tests/bugfixes/github/test_CVE_2017_17722.py | Python | gpl-3.0 | 409 | 0 | # -*- coding: utf-8 -*-
import system_tests
class TestCvePoC(metaclass=system_tests.CaseMeta):
url = "https://github.com/Exiv2/exiv2/issues/208"
filename = "$data_path/2018-01-09-exiv2-crash-001.tiff"
commands = ["$exiv2 " + filename]
retval = [1]
stdout = [""]
stderr = [
"""$exiv2_... | FileContain | sUnknownImageType
"""]
|
vFense/vFenseAgent-nix | agent/watcher_mac.py | Python | lgpl-3.0 | 4,731 | 0.001057 | import subprocess
import sys
import os
import time
from collections import namedtuple
sys.path.append(os.path.join(os.getcwd(), "src"))
from utils import settings
from utils import logger
settings.initialize('watcher')
original_plist = '/opt/TopPatch/agent/daemon/com.toppatch.agent.plist'
osx_plist = '/System/Libra... | ,
stderr=subprocess.PIPE)
raw_output, error_output = process.communicate()
for line in raw_output.splitlines():
pid, run, pname = line.split('\t')
ps_info.append((pname, | run, pid))
for p in ps_info:
if daemon_label == p[0]:
# p[1] can either be:
# : '0' meaning not running.
# : '-' meaning its running.
loaded = True
if p[1] == '-':
running = True
break
elif p[1] ... |
Karthikeyan-kkk/ooni-probe | ooni/utils/hacks.py | Python | bsd-2-clause | 3,059 | 0.000654 | # When some software has issues and we need to fix it in a
# hackish way, we put it in here. This one day will be empty.
import copy_reg
from twisted.web.client import SchemeNotSupported
from txsocksx.http import SOCKS5Agent as SOCKS5AgentOriginal
def patched_reduce_ex(self, proto):
"""
This is a hack to ov... | t = self.__dict__
except AttributeError:
dict = None
else:
dict = get | state()
if dict:
return copy_reg._reconstructor, args, dict
else:
return copy_reg._reconstructor, args
class SOCKS5Agent(SOCKS5AgentOriginal):
"""
This is a quick hack to fix:
https://github.com/habnabit/txsocksx/issues/9
"""
def _getEndpoint(self, scheme_or_uri, host=None,... |
ateska/striga2-pocs | greenev/pyge/__init__.py | Python | unlicense | 147 | 0.020408 | try:
import _py | geapi
except ImportError as e:
e.msg += ' (this module can be imported only from greenev)'
raise
from .evlo | op import event_loop
|
desaster/uusipuu | modules/google.py | Python | bsd-2-clause | 1,007 | 0.005958 | # -*- coding: ISO-8859-15 -*-
from twisted.web import client
from twisted.internet.defer import inlineCallbacks
from core.Uusipuu import UusipuuModule
import urllib, simplej | son
class Module(UusipuuModule):
def startup(self):
self.log('google.py loaded')
@inlineCallbacks
def cmd_google(self, user, target, params):
self.log('Querying google for "%s"' % params)
data = yield client.getPage(
'http://ajax.googleapis.com/ajax/services/searc... | json = simplejson.loads(data)
results = json['responseData']['results']
if not results:
self.log('No results found matching "%s"' % keyword)
self.chanmsg('No results found matching "%s"' % keyword)
return
self.chanmsg('%s: %s' % \
(results[0][... |
googleapis/python-security-private-ca | samples/generated_samples/privateca_v1beta1_generated_certificate_authority_service_update_certificate_authority_async.py | Python | apache-2.0 | 2,081 | 0.002403 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl | e law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#... | ions to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-private-ca
# [START privateca_v1beta1_generated_CertificateAuthorityService_UpdateCertificateAuthority_async]
from google.cloud.security import privateca_v1beta1
as... |
emgirardin/compassion-modules | partner_communication/models/email.py | Python | agpl-3.0 | 908 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.p... | ##############################################################
from openerp import models, fields
class MailMessage(model | s.Model):
""" Add relation to communication configuration to track generated
e-mails.
"""
_inherit = 'mail.mail'
##########################################################################
# FIELDS #
############################... |
rbrecheisen/pyminer | pyminer/pyminer.py | Python | apache-2.0 | 1,957 | 0.001533 | __author__ = 'Ralph'
from ui.app import Application
if __name__ == '__main__':
from ui.app import Example
import wx
app = wx.App()
Example(None, title='Example')
app.MainLoop()
# application = Application()
# application.run()
# node1 = ImportARFF()
# node2 = SelectAttributes()... | n(
# # ImportARFF -> SelectAttributes
# node1.get_output_port('output'), node2.get_input_port('input'))
# Connection(
# # SelectAttributes -> SVM
# node2.get_output_port('output'), node3.get_input_port('input'))
# Connection(
| # # SelectAttributes -> SelectAttributes
# node2.get_output_port('output'), node4.get_input_port('input'))
# Connection(
# # SelectAttributes -> ApplyModel
# node4.get_output_port('output'), node5.get_input_port('input'))
# Connection(
# # SVM -> ApplyModel
# node3.ge... |
z0rr0/t34.me | configs/api_python.py | Python | agpl-3.0 | 328 | 0.015244 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys, urllib2
def main():
if len(sys.argv) < 2:
| print("Error, usage: {0} <your url>".format(sys.argv[0]))
return 1
url = sys.argv[1]
print(urllib2.urlopen('http://t34.me/api/?u=' + url).read())
| return 0
if __name__ == '__main__':
main()
|
pagekite/PyPagekite | pagekite/proto/filters.py | Python | agpl-3.0 | 8,412 | 0.011531 | """
These are filters placed at the end of a tunnel for watching or modifying
the traffic.
"""
##############################################################################
from __future__ import absolute_import
LICENSE = """\
This file is part of pagekite.py.
Copyright 2010-2020, the Beanstalks Project ehf. and Bja... | if info:
if not info.get(self.ENABLE, False):
pass
elif info[self.ENABLE] in ("1", True):
remote_ip = info['remote_ip']
| if '.' in remote_ip:
remote_ip = remote_ip.rsplit(':', 1)[1]
data = 'PROXY TCP%s %s 0.0.0.0 %s %s\r\n%s' % (
'4' if ('.' in remote_ip) else '6',
remote_ip, info['remote_port'], info['port'], data or '')
else:
logging.LogError(
'FIXME: Unimplemented PR... |
victorlin/pyramid-handy | pyramid_handy/tweens/__init__.py | Python | mit | 177 | 0 | fro | m .allow_origin import allow_origin_tween_factory # noqa
from .api_headers import api_headers_tween_factory # noqa
from . | basic_auth import basic_auth_tween_factory # noqa
|
UManPychron/pychron | pychron/git_archive/diff_editor.py | Python | apache-2.0 | 9,035 | 0.001107 | # ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... | QColor(0, 100, 0, 100)
self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed,
QSizePolicy.Ignored))
self.setFixedWidth(30)
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
qp.setRenderHint(QPainter.Antialiasing)
qp.setBru... | x = rect.x()
w = rect.width()
lineheight = 16
print('-------------------')
print('lefts', self.lefts)
print('rights', self.rights)
print('-------------------')
ly = self._left_y + 5
ry = self._right_y + 5
rs=self.rights[:]
# offset=1
... |
v-iam/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/route_table.py | Python | mit | 2,557 | 0.000782 | # coding=u | tf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause ... | ior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class RouteTable(Resource):
"""Route table resource.
Variables are only populated by the server, and will be ignored when
sending a request.
... |
RobMackie/robiverse | python/echo_client/echo_client.py | Python | gpl-2.0 | 323 | 0 | #!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the s | erver
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as | s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
|
tensorflow/lingvo | lingvo/tasks/car/waymo/waymo_decoder.py | Python | apache-2.0 | 13,038 | 0.004295 | # Lint as: python3
# Copyright 2019 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 ... | mo_metric_bev_p.Instantiate()
# Convert the list of class names to a dictionary mapping class_id -> name.
class_id_to_name = dict(enumerate(class_names))
# TODO(vrv): This uses the same top down transform as for KITTI;
# re-visit these settings since detections can happen all around
# the car.
... | image_ref_y=1408.,
flip_axes=True)
decoder_metrics = py_utils.NestedMap({
'top_down_visualization':
(detection_3d_metrics.TopDownVisualizationMetric(
top_down_transform,
image_height=1536,
image_width=1024,
class_id_to... |
not-na/fritzctl | fritzctl/ooapi/general_hosts.py | Python | gpl-2.0 | 9,883 | 0.012344 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# general_hosts.py
#
# Copyright 2016-2020 fritzctl Contributors>
#
# 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 t... | getOOAPI("general_hosts")`` or ``session.getOOAPI("urn:dslforum-org:servic | e:Hosts:1")``\ .
Same parameters and attributes as :py:class:`fritzctl.ooapi.base.API_base()`\ .
"""
def getHostByIndex(self,index,ext=True):
"""
Returns the Host associated with the given Index.
:param int index: The Index of the Host
:param bool ext: Optional ... |
gianina-ingenuity/titanium-branch-deep-linking | testbed/x/mobilesdk/osx/5.5.1.GA/common/css/ply/lex.py | Python | mit | 40,747 | 0.011633 | # -----------------------------------------------------------------------------
# ply: lex.py
#
# Copyright (C) 2001-2009,
# David M. Beazley (Dabeaz LLC)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions ar... | newtab = { }
for key, ritem in self.lexstatere.items():
newre = []
for cre, findex in ritem:
newfindex = []
for f in findex:
if not f or not f[0]:
newfindex.append(f)
... | ] = newre
c.lexstatere = newtab
c.lexstateerrorf = { }
for key, ef in self.lexstateerrorf.items():
c.lexstateerrorf[key] = getattr(object,ef.__name__)
c.lexmodule = object
return c
# ------------------------------------------------------------... |
CHBMB/LazyLibrarian | lib/fuzzywuzzy/fuzz.py | Python | gpl-3.0 | 8,419 | 0.00095 | #!/usr/bin/env python
# encoding: utf-8
"""
fuzz.py
Copyright (c) 2011 Adam Cohen
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 u... | all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 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 FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import unicode_literals
import platform
import warnings
try:
... |
ilastikdev/ilastik | tests/test_applets/objectCounting/testObjectCountingMultiImageGui.py | Python | gpl-3.0 | 31,053 | 0.010756 | ###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# mod... | LE_DATA[1], data2.astype(numpy.uint8))
@classmethod
def teardownClass(cls):
# Call our base class so the app quits!
super(TestObjectCountingGuiMultiImage, cls).teardownClass()
# Clean up: Delete any test files we generated
removeFiles = [ TestObjectCountingGuiMultiImage.PROJECT... | for f in removeFiles:
try:
os.remove(f)
except:
pass
def test_1_NewProject(self):
"""
Create a blank project, manipulate few couple settings, and save it.
"""
def impl():
projFilePath = self.PROJECT_FILE
... |
WillieMaddox/scipy | benchmarks/benchmarks/optimize.py | Python | bsd-3-clause | 10,537 | 0.000949 | from __future__ import division, print_function, absolute_import
import time
from collections import defaultdict
import numpy as np
try:
import scipy.optimize
from scipy.optimize.optimize import rosen, rosen_der, rosen_hess
from scipy.optimize import leastsq
except ImportError:
pass
from . import te... | )))
print("averaged over %d starting configurations" % (results[0].ntrials))
print(" Optimizer nfail nfev njev nhev time")
print("---------------------------------------------------------")
for res in results:
print("%11s | %4d | %4d | %4d | %4d | %.6g" %
... | and average over the runs"""
grouped_results = defaultdict(list)
for res in self.results:
grouped_results[res.name].append(res)
averaged_results = dict()
for name, result_list in grouped_results.items():
newres = scipy.optimize.OptimizeResult()
newres... |
siosio/intellij-community | python/testData/multipleArgumentsCompletion/noExceptionIfMoreArgumentsThanParameters.py | Python | apache-2.0 | 61 | 0.065574 | def foo(x): |
pass
x = 42
| y = 42
z = 42
foo(x, y, <caret>) |
ddurieux/alignak | test/test_star_in_hostgroups.py | Python | agpl-3.0 | 3,007 | 0.000665 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
#
# Thi | s file is part of Alignak.
#
# Alignak 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 ver | sion 3 of the License, or
# (at your option) any later version.
#
# Alignak 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 sh... |
esdalmaijer/PyGaze | examples/simple_experiment/constants.py | Python | gpl-3.0 | 4,461 | 0.014795 | ## This file is part of PyGaze - the open-source toolbox for eye tracking
##
## PyGaze is a Python module for easily creating gaze contingent experiments
## or other software (as well as non-gaze contingent experiments/software)
## Copyright (C) 2012-2013 Edwin S. Dalmaijer
##
## This program is free... | MODE = True # False for gaze contingent display, True for dummy mode (using mouse or joystick)
LOGFILENAME = 'default' # logfilename, without path
LOGFILE = LOGFILENAME[:] # .txt; adding path before logfilename is optional; logs responses (NOT eye movements, these are stored in an EDF file!)
TRIALS = 5
# DISPLAY
... | ut not the constant's names
SCREENNR = 0 # number of the screen used for displaying experiment
DISPTYPE = 'pygame' # either 'psychopy' or 'pygame'
DISPSIZE = (1920, 1080) # resolution
SCREENSIZE = (34.5, 19.7) # physical display size in cm
MOUSEVISIBLE = False # mouse visibility
BGC = (125,125,125) # backgroundco... |
nicorellius/pdxpixel | pdxpixel/core/mailgun.py | Python | mit | 1,073 | 0.002796 | def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org/messages",
auth=("api", "key-679dc79b890e700f11f001a6bf86f4a1"),
data={"from": "Mailgun Sandbox <postmaster@sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org>",
... | d of this email in your logs: https://mailgun.com/cp/log . You can send up to 300 emails/day from this sandbox server. Next, you should add your own domain so you can send 10,000 emails/month for free."})
# cURL command to send mail aith API key
# curl -s --user 'api:key-679dc79b890e700f11f001a6bf86f4a1' \
# ht... | >' \
# -F to=nick@pdxpixel.com \
# -F subject='Hello' \
# -F text='Testing some Mailgun awesomness!'
|
scieloorg/citedby | citedby/__init__.py | Python | bsd-2-clause | 1,974 | 0.000507 | import os
from pyramid.config import Configurator
from pyramid.renderers import JSONP
from pyramid.settings import aslist
from citedby import controller
from citedby.controller import cache_region as controller_cache_region
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application... | _EXPIRATION_TIME',
settings.get('memcached_expiration_time', 2592000) # a month cache
)
if 'memcached_host' is not None:
cache_config = {}
cache_config['expiration_time'] = int(memcached_expiration_time)
cache_config['arguments'] = {'url': memcached_host, 'binary': True}
... | ure('dogpile.cache.pylibmc', **cache_config)
else:
controller_cache_region.configure('dogpile.cache.null')
config.scan()
return config.make_wsgi_app()
|
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/test/test_startfile.py | Python | gpl-3.0 | 1,193 | 0.000838 | # Ridiculously simple test of the os.startfile function for Windows.
#
# empty.vbs is an empty file (except for a comme | nt), which does
# nothing when run with cscript or wscript.
#
# A possible improvement would be to have empty.vbs do something that
# we can detect here, to make sure that not only the os.startfile()
# call succeeded, but also the script actually has run.
import unittest
from test import support
import os
import sys
f... | ase):
def test_nonexisting(self):
self.assertRaises(OSError, startfile, "nonexisting.vbs")
def test_empty(self):
# We need to make sure the child process starts in a directory
# we're not about to delete. If we're running under -j, that
# means the test harness provided director... |
highweb-project/highweb-webcl-html5spec | tools/perf/page_sets/typical_25.py | Python | bsd-3-clause | 4,012 | 0.004487 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import shutil
from profile_creators import profile_generator
from profile_creators import small_profile_extender
from telemetry.page import page as page_mod... | ""
def __init__(self, test, finder_options, story_set):
super(Typical25ProfileSharedState, self).__init__(
test, finder_options, story_set)
generator = profile_generator.ProfileGenerator(
small_profile_extender.SmallProfileExtender,
'small_profile')
self._out_dir, self._owns_out_d... | wser_options.dont_override_profile = True
def TearDownState(self):
"""Clean up generated profile directory."""
super(Typical25ProfileSharedState, self).TearDownState()
if self._owns_out_dir:
shutil.rmtree(self._out_dir)
class Typical25Page(page_module.Page):
def __init__(self, url, page_set, r... |
cmc333333/regulations-parser | tests/commands_clear_tests.py | Python | cc0-1.0 | 2,301 | 0 | import os
from unittest import TestCase
from click.testing import CliRunner
from regparser.commands.clear import clear
from regparser.index import entry
class CommandsClearTests(TestCase):
def setUp(self):
self.cli = CliRunner()
def test_no_errors_when_clear(self):
"""Should raise no errors... | lf.cli.invoke(clear, ['delroot', 'root/delsub'])
self.assertItemsEqual(['top-level-file', 'root', 'other-root'],
| list(entry.Entry()))
self.assertItemsEqual(['othersub', 'aaa'],
list(entry.Entry('root')))
self.assertItemsEqual(['aaa'],
list(entry.Entry('other-root')))
|
nickfrostatx/polyrents-challenge | tests/test_phase2.py | Python | mit | 4,200 | 0 | from util import app
import hashlib
import os
phase2_url = '/phase2-%s/' % os.environ.get('PHASE2_TOKEN')
admin_password = u'adminpass'
admin_hash = hashlib.sha1(admin_password.encode('utf-8')).hexdigest()
session_key = 'sessionkey'
admin_session_key = 'adminsessionkey'
def init_data(redis):
redis.set('user:test... | board/abc/def/'):
rv = app.get(phase2_url + url)
assert rv.status_code == 403
rv = app.get(phase2_url + url, headers={'Cookie': 'session=asdf'})
assert rv.status_code == 403
def test_post_405(app):
"""Be sure this returns 405, instead of 404 or 403."""
for url in ('', 'dashboar... | rl + 'login/'
init_data(app.application.redis)
rv = app.post(url)
assert 'dashboard' not in rv.headers.get('Location')
assert rv.status_code == 303
rv = app.post(url, data={'username': 'abcdef', 'password': 'abcdef'})
assert 'dashboard' not in rv.headers.get('Location')
assert rv.status_co... |
meltmedia/the-ark | tests/test_rhino_client.py | Python | apache-2.0 | 3,445 | 0.00029 | import unittest
from mock import patch, Mock
from the_ark import rhino_client
__author__ = 'chaley'
rhino_client_ojb = None
class UtilsTestCase(unittest.TestCase):
def setUp(self):
self.rhino_client_obj = rhino_client.RhinoClient('test_name',
'... | l(True, self.rhino_client_obj.posted)
@patch('requests.put')
def test_send_test_put(self, requests_put):
self.rhino_client_obj.test_data['test_id'] = 156465465
self.rhino_client_obj.posted = True
request_json = Mock()
request_json.status_code = 201
requests_put.return_... | tEqual(True, self.rhino_client_obj.posted)
if __name__ == '__main__':
unittest.main()
|
dsimandl/teamsurmandl | gallery/forms.py | Python | mit | 1,431 | 0.002096 | import zipfile
import imghdr
from django import forms
from .models import Image, ImageBatchUp | load, Album
class AlbumAdminForm(forms.ModelForm):
class Meta:
model = Album
fields = '__all__'
def clean(self):
cleaned_data = self.cleaned_data
| if cleaned_data.get('authorized_users') is None:
pass
else:
if cleaned_data.get('all_users') and cleaned_data.get('authorized_users').count() != 0:
cleaned_data['all_users'] = False
return cleaned_data
class ImageAdminForm(forms.ModelForm):
class Meta:
... |
Spiderlover/Toontown | toontown/catalog/CatalogNametagItem.py | Python | mit | 3,528 | 0.001701 | import CatalogItem
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from otp.otpbase import OTPLocalizer
from direct.interval.IntervalGlobal import *
from direct.gui.DirectGui import *
class CatalogNametagItem(CatalogItem.CatalogItem):
sequenceNumber = 0
def makeNewItem(... | etagFrilly
def recordPurchase(self, avatar, optional):
if avatar:
avatar.b_setNametagStyle(self.nametagStyle)
return ToontownGlobals.P_ItemAvailable
def getPicture(self, avatar):
frame = self.makeFrame()
if self.nametagStyle == 100:
inFont = ToontownGlob... | nt()
else:
inFont = ToontownGlobals.getNametagFont(self.nametagStyle)
nameTagDemo = DirectLabel(parent=frame, relief=None, pos=(0, 0, 0.24), scale=0.5, text=base.localAvatar.getName(), text_fg=(1.0, 1.0, 1.0, 1), text_shadow=(0, 0, 0, 1), text_font=inFont, text_wordwrap=9)
self.hasPi... |
paulmartel/voltdb | lib/python/voltcli/voltadmin.d/pause.py | Python | agpl-3.0 | 9,312 | 0.00494 | # This file is part of VoltDB.
# Copyright (C) 2008-2016 VoltDB Inc.
#
# 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 ver... | # first look for streaming (export) tables
if str(r[6]) == 'StreamedTable':
pendingData = r[8]
tablename = str(r[5])
pid = r[4]
hostname = str(r[2])
if pendingData > 0:
if not tablename in export_tables_with_data:
... | [tablename]
if not hostname in tabledata:
tabledata[hostname] = set()
tabledata[hostname] |
chergert/libgit2-glib | tools/coverage.py | Python | lgpl-2.1 | 6,733 | 0.003864 | #!/usr/bin/env python3
import os, sys, glob, pickle, subprocess
sys.path.insert(0, os.path.dirname(__file__))
from clang import cindex
sys.path = sys.path[1:]
def configure_libclang():
llvm_libdirs = ['/usr/lib/llvm-3.2/lib', '/usr/lib64/llvm']
try:
libdir = subprocess.check_output(['llvm-config', '... | = glob.glob(os.path.join(d, 'libclang.so*'))
if len(files) != 0:
cindex.Config.set_library_file(files[0])
return
class Call:
def __init__(self, cursor, decl):
self.ident = cursor.displayname.decode('utf-8')
self.filename = cursor.location.file.name.decode('utf-8')
... | elf.start_column = ex.start.column
self.end_line = ex.end.line
self.end_column = ex.end.column
self.decl_filename = decl.location.file.name.decode('utf-8')
class Definition:
def __init__(self, cursor):
self.ident = cursor.spelling.decode('utf-8')
self.display = cursor.disp... |
blutjens/perc_neuron_ros_ur10 | pn_ros/bjorn_ws/build/rosserial/rosserial_mbed/catkin_generated/pkg.installspace.context.pc.py | Python | gpl-3.0 | 511 | 0.001957 | # generated from c | atkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/bjornl/ros/workspaces/bjorn_ws/install/include".split(';') if "/home/bjornl/ros/workspaces/bjorn_ws/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "message_runtime".replace(';', ' ')
PKG_CONFIG_LIBRARIES_... | T_SPACE_DIR = "/home/bjornl/ros/workspaces/bjorn_ws/install"
PROJECT_VERSION = "0.7.6"
|
Protocol-X/script.video.funimationnow | resources/lib/modules/menunav.py | Python | gpl-3.0 | 6,384 | 0.01911 | # -*- coding: utf-8 -*-
'''
Funimation|Now Add-on
Copyright (C) 2016 Funimation|Now
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 yo... | CODE = REST_CODE;
try:
| #xbmc.executebuiltin('Addon.OpenSettings(%s)' % utils.getAddonInfo('id'));
utils.addon.openSettings();
utils.lock();
utils.sleep(2000);
utils.unlock();
addon_data = xbmc.translatePath(utils.getAddonInfo('profile')).decode('utf-8');
tokens = xbmc.translatePath(os.path... |
Spiderlover/Toontown | toontown/hood/FishAnimatedProp.py | Python | mit | 2,348 | 0.002129 | import AnimatedProp
from direct.actor import Actor
from direct.interval.IntervalGlobal import *
from toontown.effects.Splash import *
from toontown.effects.Ripples import *
import random
class FishAnimatedProp(AnimatedProp.AnimatedProp):
def __init__(self, node):
AnimatedProp.AnimatedProp.__init__(self, n... | 0.0, 1.24, 0.0, 0.0, 0.0, 0.7, 0.7, 0.7)
self.splash = Splash(self.geom, wantParticles=0)
| self.splash.setPosHprScale(-1, 0.0, 1.23, 0.0, 0.0, 0.0, 0.7, 0.7, 0.7)
randomSplash = random.choice(self.splashSfxList)
self.track = Sequence(FunctionInterval(self.randomizePosition), Func(self.node.unstash), Parallel(self.fish.actorInterval('jump'), Sequence(Wait(0.25), Func(self.exitRipples.play, ... |
dacb/viscount | viscount/tasks/models.py | Python | bsd-2-clause | 2,077 | 0.01637 | """
viscount.task.models
Task models
"""
from ..core import db
from ..utils import JSONSerializer
class TaskInputFile(JSONSerializer, db.Model):
__tablename__ = 'tasks_input_files'
id = db.Column(db.Integer, primary_key=True)
task_id = db.Column(db.Integer, db.ForeignKey('tasks.id'), nullable=False)
file_type_... | id=event.id) for event in events],
'inputs': lambda inputs, _: [dict(id=input.id) for input in inputs],
'outputs': lambda outputs, _: [dict(id=output.id) for output in outputs],
'task_instances': lambda task_instances, _: [dict(id=task_instance.id) for task_instance in task_instances],
}
class Task(TaskJSONSe... | e__ = 'tasks'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), unique=True)
owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
description = db.Column(db.Text, index=False, unique=False, nullable=False)
source_file = db.Column(db.Integer, db.ForeignKey('files.i... |
neldom/qessera | careers/models.py | Python | mit | 2,634 | 0.015186 | from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.text import... | h=12,
choices=RO | LE_CATEGORY_CHOICES,
default=FULLTIME,
)
# Role
role = models.CharField(max_length = 120)
# Location
city = models.CharField(max_length=255)
# Plain text and urlify slug
career_slug = models.SlugField(unique = True)
career_offer_title = models.CharField(max_length=255, default... |
gh0std4ncer/doit | doc/tutorial/tutorial_02.py | Python | mit | 276 | 0 | def task_hello():
"""hello py """
def python_hello(times, text, targets):
with open(targets[0], "a") as output:
output.write(times * text)
return {'actions': [(python_hello, [3, "py!\ | n"])],
| 'targets': ["hello.txt"],
}
|
smorad/ast119 | hw5.py | Python | gpl-2.0 | 2,857 | 0.00805 | from numpy import *
from matplotlib.pyplot import *
import scipy.constants as sc
import copy
import scipy.integrate as integ
# test sun/earth with hw5(1.989e30,5.972e24,149.6e6,0.0167,1000)
def hw5(m1, m2, a, e, tmax, tstep=0.001, tplot=0.025, method='leapfrog'):
if method != 'leapfrog' and method != 'odeint':
... | m2)))
dt = period*tstep
# initialize objects at time 0
q = m1 / m2
r0 = (1-e)*a/(1+q)
v0 = (1/(1+q))*sqrt((1+e)/(1-e))*sqrt(sc.G*(m1+m2)/a)
rv = array([r0, 0, 0, v0, -q*r0, 0, 0, -q*v0])
# set up figure
figure(1)
gca().set_aspect('equal')
xlim([-2*a, 2*a])
ylim([-2*a, ... | 0
while timeCounter < tmax:
# plot positions if tplot time has passed
if frameCounter >= tplot:
frameCounter = 0
rv_list.append(copy.deepcopy(rv))
# calc positions
rv[0] = rv[0] + rv[2]*dt
rv[1] = rv[1]... |
Spicery/ginger | apps/fetchgnx/design/conf.py | Python | gpl-3.0 | 9,404 | 0.005955 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# FetchGNX design notes documentation build configuration file, created by
# sphinx-quickstart on Fri Oct 9 13:29:00 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are presen... | ue
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created usi | ng Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of ... |
betonreddit/betonreddit | betonreddit/player/migrations/0003_auto_20160509_2322.py | Python | apache-2.0 | 427 | 0 | # -*- coding: utf-8 -*-
# Generated by Dj | ango 1.9.6 on 2016-05-09 23:22
from __future__ import unicode_lit | erals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('player', '0002_auto_20160505_0350'),
]
operations = [
migrations.RenameField(
model_name='player',
old_name='username',
new_name='email',
),
]... |
tonyczeh/vootstrap | vootstrap/__init__.py | Python | mit | 5,176 | 0.001546 | #!/usr/bin/env python
import sys
import textwrap
try:
import virtualenv # @UnresolvedImport
except:
from .lib import virtualenv # @Reimport
from . import snippits
__version__ = "0.9.1"
def file_search_dirs():
dirs = []
for d in virtualenv.file_search_dirs():
if "vootstrap" not in d:
... | l_requirements",
help="Install requirements.txt after vootstrapping")
parser.add_option(
"--path",
action="append",
dest="path",
help="Directory to add to vootstrapped sys.path. You can add any "
"number of additional --path paths. Relative directories are relative "... | rectory")
return parser
def adjust_options(options):
out_str = "def adjust_options(options, args):\n"
opts = [
"verbose",
"quiet",
"python",
"clear",
"no_site_packages",
"system_site_packages",
"unzip_setuptools",
"relocatable",
"use... |
zerothi/sisl | sisl/io/molden.py | Python | mpl-2.0 | 1,873 | 0.001068 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# f | ile, You can obtain one at https://mozilla.org/MPL/2.0/.
# Import sile objects
from .sile import *
from sisl._internal import set_module
from sisl import Geometry
__all__ = ['moldenSile']
@set_module("sisl.io")
class moldenSile(Sile):
""" Molden file object """
@sile_fh_open()
def write_supercell(self... | write to the file
sile_raise_write(self)
# Write the number of atoms in the geometry
self._write('[Molden Format]\n')
# Sadly, MOLDEN does not read this information...
@sile_fh_open()
def write_geometry(self, geometry, fmt='.8f'):
""" Writes the geometry to the contai... |
meredith-digops/awsops | amicreation/amicreation.py | Python | mit | 1,866 | 0.001608 | #!/usr/bin/env python
from __future__ import print_function
import boto3
import time
from botocore.exceptions import ClientError
from datetime import datetime
def get_unix_timestamp():
"""
Generate a Unix timestamp string.
"""
d = datetime.now()
t = time.mktime(d.timetuple())
return str(int... | # instead of the instance_id.
for tag in instance.tags:
if tag['Key'] == 'Name' and tag['Value'] != '':
instance_name = tag['Value']
| else:
instance_tags.append(tag)
try:
# Create the AMI
image_name = instance_name + '-' + get_unix_timestamp()
image = instance.create_image(
Name=image_name,
NoReboot=True,
DryRun=... |
melrief/Hadoop-Log-Tools | hadoop/util/stats.py | Python | apache-2.0 | 1,993 | 0.024586 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import numpy as N
import os
import sys
def parse_args(args): |
p = argparse.ArgumentParser()
p.add_argument('-i', '--input-files', default=[sys.stdin], nargs="+",
type=argparse.FileType('rt'),
help='input file or empty (stdin)')
p.add_argument('-d', '--decorate',default=False,action='store_true'
,help='put the stat name befo... | l-stats',action='store_true',default=False)
h = p.add_argument_group('stat')
h.add_argument('-a', '--mean', action='store_true', default=False)
h.add_argument('-D', '--median', action='store_true', default=False)
h.add_argument('-s', '--standard_deviation',action='store_true',default=False)
h.add_argument('-... |
materialsvirtuallab/megnet | megnet/utils/descriptor.py | Python | bsd-3-clause | 6,396 | 0.002502 | """
This module implements atom/bond/structure-wise descriptor calculated from
pretrained megnet model
"""
import os
from typing import Dict, Union
import numpy as np
from tensorflow.keras.models import Model
from megnet.models import GraphModel, MEGNetModel
from megnet.utils.typing import StructureOrMolecule
DEFAU... | = True):
"""
Args:
model_name (str or MEGNetModel): trained model. If it is
str, then only models in mvl_models are used.
use_cache (bool): whether to use cache for structure
| graph calculations
"""
if isinstance(model_name, str):
model = MEGNetModel.from_file(model_name)
elif isinstance(model_name, GraphModel):
model = model_name
else:
raise ValueError("model_name only support str or GraphModel object")
... |
zwarren/morse-car-controller | user/map.py | Python | mit | 7,092 | 0.006204 | #!/usr/bin/env python
import sys
import json
import logging
from logging import warning, error, info
from math import pi, degrees
from PyQt4 import Qt, QtCore, QtGui
from connection import Connection
arrow_points = (
Qt.QPoint(-1, -4),
Qt.QPoint(1, -4),
Qt.QPoint(1, 4),
Qt.QPoint(4, 4),
Qt.QPoin... | 0, -10)
elif e.key() == Qt.Qt.Key_Left:
self.plot.translate(10, 0)
elif e.key( | ) == Qt.Qt.Key_Right:
self.plot.translate(-10, 0)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
app = Qt.QApplication([])
demo = MainWindow()
demo.resize(800, 600)
demo.show()
sys.exit(app.exec_())
|
visdesignlab/TulipPaths | demos/simpleNodeCompleteness.py | Python | mit | 928 | 0.002155 | """ Example of reasoning about the approximate node completeness. """
from tulip import *
from tulipgui import *
import tulippaths as tp
# Load graph
graphFile = '../data/514_4hops.tlp'
graph = tlp.loadGraph(graphFile)
# Compute completeness for each node label
completeness = tp.utils.getApproximateAnnotationComplet... | mpleteness <= 1.0 and currCompleteness > 0.75:
numComplete += 1
elif currCompleteness <= 0.75 and currCompleteness > 0.25:
numAlmostComplete += 1
else:
graph.delNode(node)
| numIncomplete += 1
print('num complete, num almost complete, num incomplete')
print((str(numComplete) + ', ' + str(numAlmostComplete) + ', ' + str(numIncomplete)))
nodeLinkView = tlpgui.createNodeLinkDiagramView(graph) |
XeCycle/indico | indico/MaKaC/webinterface/rh/trackModif.py | Python | gpl-3.0 | 39,643 | 0.016195 | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | = { \
_ContribTypeFilterField.getId(): _ContribTypeFilterField, \
_StatusFilterField.getId(): _StatusFilterField, \
_MultipleTrackFilterField.getId(): _MultipleTrackFilterField, \
_CommentsTrackFilterField.getId(): _CommentsTrackFilterField,
... | def __init__(self,track,crit={}):
self._track = track
filters.FilterCriteria.__init__(self,track.getConference(),crit)
def _createField(self,klass,values ):
return klass(self._track,values)
def satisfies( self, abstract ):
for field in self._fields.values():
if not ... |
tomjelinek/pcs | pcs_test/tier0/lib/test_env.py | Python | gpl-2.0 | 6,324 | 0 | import logging
from functools import partial
from unittest import (
TestCase,
mock,
)
from pcs.common import file_type_codes
from pcs.common.reports import ReportItemSeverity as severity
from pcs.common.reports import codes as report_codes
from pcs.lib.env import LibraryEnvironment
from pcs_test.tools.asserti... | _conf_data=None):
return LibraryEnvironment(
self.mock_logger,
self.mock_reporter,
cib_d | ata=cib_data,
corosync_conf_data=corosync_conf_data,
)
def test_nothing(self):
self.assertEqual(self._fixture_get_env().ghost_file_codes, [])
def test_corosync(self):
self.assertEqual(
self._fixture_get_env(corosync_conf_data="x").ghost_file_codes,
[... |
btcspry/3d-wallet-generator | gen_3dwallet/base.py | Python | mit | 24,069 | 0.008226 | #!/usr/bin/python3
try:
import qr_tools as qrTools # Module for this project
except:
import gen_3dwallet.qr_tools as qrTools
try:
import TextGenerator as textGen # Module for this project
except:
import gen_3dwallet.TextGenerator as textGen
import bitcoin # sudo pip3 install bitcoin
import argpar... | Keys after)")
parser.add_argument('-wi', '--width', dest='walletWidth', type=float, default=54.0, help='The width of the wallet in mm. The length is calculated automatically. Default option is approximately standard credit card legnth and width. \n(Default: 54.0)')
parser.add_arg | ument('-he', '--height', dest='walletHeight', type=float, default=8.0, help='The height of the wallet in mm. \n(Default: 8)')
parser.add_argument('-bo', '--black-offset', dest='blackOffset', type=int, default=-30, help='The percentage of the height that the black part of the QR code, and the text, will be raised or... |
upiq/plonebuild | python/src/test-python.py | Python | mit | 873 | 0.004582 | def test(options, buildout):
from subprocess import Popen, PIPE
import os
import sy | s
python = options['python']
if not os.path.exists(python):
raise IOError("There is no file at %s" % python)
if sys.platform == 'darwin':
output = Popen([python, "-c", "import platform; print (platform.mac_ver())"], stdout=PIPE).communicate()[0]
if not output.startswith("('10."):
... | oesn't return proper data for platform.mac_ver(), got: %s" % (python, output))
elif sys.platform == 'linux2' and (2, 4) <= sys.version_info < (2, 5):
output = Popen([python, "-c", "import socket; print (hasattr(socket, 'ssl'))"], stdout=PIPE).communicate()[0]
if not output.startswith("True"):
... |
sot/mica | mica/archive/cda/services.py | Python | bsd-3-clause | 23,345 | 0.001157 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Python interface to the Chandra Data Archive (CDA) web services and an
interface to a local disk copy of the Observation Catalog (Ocat).
"""
from pathlib import Path
import re
import warnings
import time
import requests
import numpy as np
import tables... | umn
from astropy.coordinates import SkyCoord
from mica.common import MICA_ARCHIVE
__all__ = ['get_archive_file_list', 'get_proposal_abstract',
'get_ocat_web', 'get_ocat_local']
OCAT_TABLE_PATH = Path(MICA_ARCHIVE) / 'ocat_target_table.h5'
OCAT_TABLE_CACHE = {}
URL_CDA | _SERVICES = "https://cda.harvard.edu/srservices"
CDA_SERVICES = {
'prop_abstract': 'propAbstract',
'ocat_summary': 'ocatList',
'ocat_details': 'ocatDetails',
'archive_file_list': 'archiveFileList'}
# Units copied from https://github.com/jzuhone/pycda/blob/
# 5a4261328eab989bab91bed17f426ad17d876988/pyc... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_mynock.py | Python | mit | 426 | 0.049296 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOS | T IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_mynock.iff"
result.attribute_template_id = 9
result.stfName("monster_name","mynock")
#### BEGIN MODIFICATIONS | ####
#### END MODIFICATIONS ####
return result |
InsightSoftwareConsortium/ITKExamples | src/IO/ImageBase/GenerateSlicesFromVolume/Code.py | Python | apache-2.0 | 1,976 | 0.001012 | #!/usr/bin/env python
# Copyright NumFOCUS
#
# 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.txt
#
# Unless required by applicable law or ... | Type, RescaleImageType]
rescale = RescaleFilterType.New()
rescale.SetInput(reader.GetOutput())
rescale.SetOutputMinimum(0)
rescale.SetOutputMaximum(255)
rescale.UpdateLargestPossibleRegion()
region = reader.GetOutput().GetLargestPossibl | eRegion()
size = region.GetSize()
fnames = itk.NumericSeriesFileNames.New()
fnames.SetStartIndex(0)
fnames.SetEndIndex(size[2] - 1)
fnames.SetIncrementIndex(1)
fnames.SetSeriesFormat(fileNameFormat)
OutputImageType = itk.Image[OutputPixelType, 2]
WriterType = itk.ImageSeriesWriter[RescaleImageType, OutputImageType]
... |
erudit/zenon | eruditorg/erudit/migrations/0087_auto_20180321_0853.py | Python | gpl-3.0 | 481 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 o | n 2018-03-21 13:53
from __future__ import unico | de_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('erudit', '0086_auto_20180321_0717'),
]
operations = [
migrations.RemoveField(
model_name='articleabstract',
name='article',
),
migrations.Delete... |
mycodeday/crm-platform | web_view_editor/__openerp__.py | Python | gpl-3.0 | 326 | 0.006135 | {
'name': 'View Editor',
'category': 'Hidden',
'description': """
OpenERP Web to edit views.
==================== | ======
| """,
'version': '2.0',
'depends':['web'],
'data' : [
'views/web_view_editor.xml',
],
'qweb': ['static/src/xml/view_editor.xml'],
'auto_install': True,
}
|
DsixTools/python-smeftrunner | smeftrunner/classes.py | Python | mit | 11,842 | 0.001773 | """Defines the SMEFT class that provides the main API to smeftrunner."""
from . import rge
from . import io
from . import definitions
from . import beta
from . import smpar
import pylha
from collections import OrderedDict
from math import sqrt
import numpy as np
import ckmutil.phases, ckmutil.diag
class SMEFT(object)... | basis = wcxf.Basis['SMEFT', 'Warsaw']
d = {k: v for k, v in d.items() if k in basis.all_wcs and v != 0}
keys_dim5 = ['llphiphi']
keys_dim6 = list(set(definitions.WC_keys_0f + definitions.WC_keys_2f
+ definitions.WC_keys_4f) - set(keys_dim5))
| for k in d:
if k.split('_')[0] in keys_dim5:
d[k] = d[k] / self.scale_high
for k in d:
if k.split('_')[0] in keys_dim6:
d[k] = d[k] / self.scale_high**2
d = wcxf.WC.dict2values(d)
wc = wcxf.WC('SMEFT', 'Warsaw', scale_out, d)
retu... |
turon/mantis | src/tools/tenodera/net_view.py | Python | bsd-3-clause | 15,234 | 0.006302 | # This file is part of MANTIS OS, Operating System
# See http://mantis.cs.colorado.edu/
#
# Copyright (C) 2003-2005 University of Colorado, Boulder
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the mos license (see file LICENSE)
import wx, thread
import net_model
cla... | a node
self.node_color = 'GREEN' | # TODO not currently used
self.node_outline = 'BLACK' # TODO not currently used
# Setting this flag prevents drawing this node and links while dragging
self.dragging = False
self.model = model
# Now setup the node's bitmap so we can just blit to the screen
# ... |
compas-dev/compas | src/compas_blender/artists/lineartist.py | Python | mit | 2,962 | 0.003038 | from typing import Any
from typing import List
from typing import Optional
from typing import Union
import bpy
import compas_blender
from compas.artists import PrimitiveArtist
from compas.geometry i | mport Line
from compas.colors import Color
from compas_blender.artists import BlenderArtist
class LineArtist(BlenderArtist, PrimitiveArtist):
"""Artist fo | r drawing lines in Blender.
Parameters
----------
line : :class:`~compas.geometry.Line`
A COMPAS line.
collection : str | :blender:`bpy.types.Collection`
The Blender scene collection the object(s) created by this artist belong to.
**kwargs : dict, optional
Additional keyword... |
amol9/hackerearth | hackerrank/practice/cavity_map/solution.py | Python | mit | 500 | 0.006 |
n = int(inp | ut())
grid = [[int(c) for c in input()] for i in range (0, n)]
cavities = []
for i in range(0, n):
if i > 0 and i < n - 1:
for j in range(0, n):
if j > 0 and j < n - 1:
v = grid[i][j]
if grid[i - 1][j] < v and grid[i + 1][j] < v and grid[i][j - 1] < v and grid[... | d))
|
amosnier/python_for_kids | course_code/13_039_animated_ball.py | Python | gpl-3.0 | 562 | 0.003559 | import tkinter
tk = tkinter.Tk()
tk.title("Bounce")
tk.resizable | (0, 0)
# Keep the window on the top
tk.wm_attributes("-topmost", 1)
canvas = tkinter.Canvas(tk, width=500, height=400)
# Remove border. Apparently no effect on Linux, but good on Mac
canvas.configure(bd=0)
# Make the 0 horizontal and vertical line apparent
canvas.configure(highlightthickness=0)
canvas.pack()
ball = ca... | inloop()
|
Boy-314/winner-winner-bidget-sbinner | examples/playlist.py | Python | mit | 8,569 | 0.002451 | import asyncio
import discord
from discord.ext import commands
if not discord.opus.is_loaded():
# the 'opus' library here is opus.dll on windows
# or libopus.so on linux in the current directory
# you should replace this with the location the
# opus library is located in and with the proper filename.
... | state.skip()
else:
await self.bot.say('Skip vote added, currently at [{}/3]'.format(total_votes))
else:
await self.bot.say('You have already voted to skip this song.')
@commands.command(pass_context=True, no_pm=True)
async def playing(self, ctx):
... | _voice_state(ctx.message.server)
if state.current is None:
await self.bot.say('Not playing anything.')
else:
|
valentine20xx/portal | converter/utils.py | Python | gpl-3.0 | 2,852 | 0.001052 | import csv
import os
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.db import models
from converter.exceptions import UploadException
from .models import SystemSource, Reference, Referenc... | ence_id=reference)
content.save()
else:
raise UploadException("Parse error")
# raise ValidationError('Invalid value', code= | 'invalid')
os.remove(filepath)
def safe_get(_list, _index, _default=""):
try:
return _list[_index]
except IndexError:
return _default |
googleapis/python-datacatalog | samples/generated_samples/datacatalog_generated_datacatalog_v1_policy_tag_manager_serialization_import_taxonomies_sync.py | Python | apache-2.0 | 1,711 | 0.001753 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ob | tain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for th... | r the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for ImportTaxonomies
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m ... |
elan17/irc-terminal | server/main.py | Python | gpl-3.0 | 927 | 0.002157 | import multiprocessing
import Library.interfaz
import Library.config
import handler
import server
try:
config = Library.config.read()
except:
import sys
print("FAILED TO OPEN CONFIG FILE, EXITING")
sys.exit()
man = multiprocessing.Manager()
adios = man.Value(bool, False)
interfaz = Library.interfaz.Int... | ])
hand.pantalla("GENERATING_KEY", args=(key_bits,), prompt=False)
server = server.Server(adios, hand, Library.Encriptacion.genera(key_bits), ip=config["host"], port=int(config["port"]))
g = multiprocessing.Process(target=server.listen)
p = multiprocessing.Process(target=server.server_handler | )
p2 = multiprocessing.Process(target=hand.listen, args=(server, ))
p.start()
g.start()
hand.listen(server)
adios.value = True
p.join()
g.join()
server.handler.exit()
|
LMSlay/wiper | docs/source/conf.py | Python | bsd-3-clause | 7,714 | 0.007519 | # -*- coding: utf-8 -*-
#
# Viper documentation build configuration file, created by
# sphinx-quickstart on Mon May 5 18:24:15 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 c... | placing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patt... | reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_mo... |
minlexx/pyevemon | esi_client/models/get_opportunities_tasks_task_id_ok.py | Python | gpl-3.0 | 5,602 | 0.001071 | # coding: utf-8
"""
EVE Swagger Interface
An OpenAPI for EVE Online
OpenAPI spec version: 0.4.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class GetOpportunitiesTasksTaskIdOk(object):
"""
NOTE: T... | value.to_dict()
eli | f isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return resu... |
VirusTotal/misp-modules | misp_modules/modules/expansion/threatfox.py | Python | agpl-3.0 | 2,146 | 0.001864 | # -*- coding: utf-8 -*-
import requests
import json
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5', 'sha1', 'sha256', 'domain', 'url', 'email-src', 'ip-dst|port', 'ip-src|port'], 'output': ['text']}
moduleinfo = {'version': '0.1', 'author': 'Corsin Camichel', 'description': 'Module to search for an ... | ce_level_to_tag(result["data"][0]["confidence_level"])
ret_val = {'results': [{'types': mispattributes['output'], 'values': [result["data"][0]["threat_type_desc"]], 'tags': [result["data"][0]["malware"], result | ["data"][0]["malware_printable"], confidence_tag]}]}
return ret_val
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
codeMarble/codeMarble_Web | codeMarble_Web/codeMarble_py3des.py | Python | gpl-3.0 | 649 | 0.007704 | # -*- coding: utf-8 -*-
from py3Des.pyDes import triple_des, ECB, PAD_PKCS5
class TripleDES:
__triple_des = None
@staticmethod
def in | it():
TripleDES.__triple_des = triple_des('1234567812345678',
mode=ECB,
IV = '\0\0\0\0\0\0\0\0',
pad=None,
padmode = PAD_PKCS5)
@st... | pleDES.__triple_des.decrypt(data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.