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 |
|---|---|---|---|---|---|---|---|---|
pseudomuto/kazurator | kazurator/read_write_lock.py | Python | mit | 3,177 | 0 | from kazoo.exceptions import NoNodeError
from sys import maxsize
from .mutex import Mutex
from .internals import LockDriver
from .utils import lazyproperty
READ_LOCK_NAME = "__READ__"
WRITE_LOCK_NAME = "__WRIT__"
class _LockDriver(LockDriver):
def sort_key(self, string, _lock_name):
string = super(_LockD... | (
client,
path,
| max_leases,
name=name,
driver=driver,
timeout=timeout
)
def get_participant_nodes(self):
nodes = super(_Mutex, self).get_participant_nodes()
return list(filter(lambda node: self.name in node, nodes))
class ReadWriteLock(object):
def __init__(self,... |
AlericInglewood/3p-google-breakpad | src/tools/gyp/pylib/gyp/generator/scons.py | Python | bsd-3-clause | 34,839 | 0.00643 | # Copyright (c) 2012 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 gyp
import gyp.common
import gyp.SCons as SCons
import os.path
import pprint
import re
# TODO: remove when we delete the last WriteList() call in this mo... | with quoting by naively putting double-quotes around
command-line arguments containing space or tab, which is broken for all
but trivial cases, so we undo it. (See quote_spaces() in Subst.py)"""
if ' ' in s or '\t' in s:
| # Then SCons will put double-quotes around this, so add our own quotes
# to close its quotes at the beginning and end.
s = '"' + s + '"'
return s
def EscapeSConsVariableExpansion(s):
"""SCons has its own variable expansion syntax using $. We must escape it for
strings to be interpreted literally. F... |
aurule/Sociogram | src/sociogram.py | Python | apache-2.0 | 60,889 | 0.008836 | #!/usr/bin/env python2
'''
Copyright (c) 2012 Peter Andrews
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by app... | f.canvas.mouseover_callback = self.update_pointer
#TODO once the prefs dialog is implemented, this should be moved to a separate default style update function
| #populate our default styling
sheet = self.canvas.edge_default_stylesheet
sheet.stroke_color = 0x000000ff
sheet.set_fontdesc('sans normal 11')
sheet.sel_color = 0xff0000ff
sheet.sel_width = 1
sheet.text_color = 0x000000ff
sheet.set_fontdesc('sans normal 11')
... |
verdyanna/new_troika | fixture/platform_helper.py | Python | apache-2.0 | 2,490 | 0.002477 |
class PlatformHelper:
def __init__(self, app):
self.app = app
def fill_contact_form(self, contact_model):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_link_text("add new").click()
self.fillin_contact_form(contact_model)
def fillin_contact_form(sel... | me").click()
wd.find_element_by_name("home").send_keys(contact_model.hom | e)
wd.find_element_by_name("mobile").click()
wd.find_element_by_name("mobile").send_keys(contact_model.mobile)
wd.find_element_by_name("work").click()
wd.find_element_by_name("work").send_keys(contact_model.work)
wd.find_element_by_name("phone2").click()
wd.find_element_b... |
scienceopen/pyrinex | src/georinex/nav2.py | Python | mit | 8,213 | 0.001461 | #!/usr/bin/env python
from pathlib import Path
from datetime import datetime
from typing import Dict, Union, Any, Sequence
from typing.io import TextIO
import xarray
import numpy as np
import logging
from .rio import opener, rinexinfo
from .common import rinex_string_to_float
#
STARTCOL2 = 3 # column where numerical... | TE: time must be datetime64[ns] or .to_netcdf will fail
nav = xarray.Dataset(coords={"time": timesu.astype("datetime64[ns]"), "sv": svu})
for i, k in enumerate(fields):
if k is None:
continue
nav[k] = (("time", "sv"), data[i, :, :])
| # GLONASS uses kilometers to report its ephemeris.
# Convert to meters here to be consistent with NAV3 implementation.
if svtype == "R":
for name in ["X", "Y", "Z", "dX", "dY", "dZ", "dX2", "dY2", "dZ2"]:
nav[name] *= 1e3
# %% other attributes
nav.attrs["version"] = header["version... |
cajone/pychess | lib/pychess/System/cairoextras.py | Python | gpl-3.0 | 2,930 | 0.000341 | # from: http://cairographics.org/freetypepython/
import ctypes
import cairo
class FreeTypeLibInitializationFailed(Exception):
pass
class PycairoContext(ctypes.Structure):
_fields_ = [("PyObject_HEAD", ctypes.c_byte * object.__basicsize__),
("ctx", ctypes.c_void_p), ("base", ctypes.c_void_p)... | " + filename)
_ca | iro_so.cairo_set_font_face(cairo_t, cr_face)
if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_status(cairo_t):
raise Exception("Error creating cairo font face for " + filename)
face = cairo_ctx.get_font_face()
return face
if __name__ == '__main__':
face = create_cairo_font_face_for_file("../../../... |
Mdlkxzmcp/various_python | Alpha & Beta/Django/WaifuTracker/main_app/apps.py | Python | mit | 90 | 0 | from dj | ango.apps import AppConfig
class MainAppConfig | (AppConfig):
name = 'main_app'
|
ghorn/debian-casadi | docs/examples/python/simulation.py | Python | lgpl-3.0 | 4,875 | 0.01641 | #
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
# K.U. Leuven. All rights reserved.
# Copyright (C) 2011-2014 Greg Horn
#
# CasADi is free software; you can... | ntrols_ = controls.repeated(csim.getInput("u"))
controls_[0,"u"] = 1 # Kick the system with u=1 at the start
controls_[N/2,"v"] = 2 # Kick the system with v=2 at half the simulatio | n time
# Pure simulation
csim.setInput(x0,"x0")
csim.setInput(parameters_,"p")
csim.setInput(controls_,"u")
csim.evaluate()
output = states.repeated(csim.getOutput())
# Plot all states
for k in states.keys():
plot(tgrid,output[vertcat,:,k])
xlabel("t")
legend(tuple(states.keys()))
print "xf=", output[-1]
# The r... |
duke8253/trafficserver | tests/gold_tests/proxy_protocol/proxy_serve_stale_dns_fail.test.py | Python | apache-2.0 | 3,341 | 0.002095 | '''
Test proxy serving stale content when DNS lookup fails
'''
# 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 un... |
# 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.
Test.ContinueOnFail = True
# Set up hierarchical caching processes
ts_child = Test.MakeATSProcess("ts_child")
ts_parent = Test.MakeATSPro... | ate({
'proxy.config.url_remap.pristine_host_hdr': 1,
'proxy.config.http.cache.max_stale_age': 10,
'proxy.config.http.parent_proxy.self_detect': 0,
})
ts_child.Disk.parent_config.AddLine(
f'dest_domain=. parent=localhost:{ts_parent.Variables.port} round_robin=consistent_hash go_direct=false'
)
ts_child.D... |
mhrivnak/pulp | server/pulp/server/webservices/controllers/repositories.py | Python | gpl-2.0 | 7,350 | 0.000952 | """
This module contains the web controllers for Repositories.
"""
import logging
import sys
import web
from pulp.common import dateutils
from pulp.server.auth.authorization import READ
from pulp.server.db.model.criteria import UnitAssociationCriteria
from pulp.server.webservices import se | rialization
fro | m pulp.server.webservices.controllers.base import JSONController
from pulp.server.webservices.controllers.decorators import auth_required
from pulp.server.webservices.controllers.search import SearchController
import pulp.server.exceptions as exceptions
import pulp.server.managers.factory as manager_factory
_logger =... |
mushtaqak/edx-platform | common/djangoapps/enrollment/views.py | Python | agpl-3.0 | 21,774 | 0.004225 | """
The Enrollment API Views should be simple, lean HTTP endpoints for API access. This should
consist primarily of authentication, request validation, and serialization.
"""
import logging
from ipware.ip import get_ip
from django.core.exceptions import ObjectDoesNotExist
from django.utils.decorators import method_de... | keys import CourseKey
from embargo import api as embargo_api
from cors_csrf.authentication import SessionAuthenticationCrossDomainCsrf
from cors_csrf.decorators import ensure_csrf_cookie_cross_domain
from openedx.core.lib.api.authentication import (
SessionAuthenticationAllowInactiveUser,
OAuth2AuthenticationAl... | limit
from enrollment import api
from enrollment.errors import (
CourseNotFoundError, CourseEnrollmentError,
CourseModeNotFoundError, CourseEnrollmentExistsError
)
from student.models import User
log = logging.getLogger(__name__)
class EnrollmentCrossDomainSessionAuth(SessionAuthenticationAllowInactiveUser, ... |
rh-marketingops/dwm | dwm/test/test_normIncludes.py | Python | gpl-3.0 | 407 | 0.007371 | normIncludes = [
| {"fieldName": "field1", "includes": "GOOD,VALUE", | "excludes": "BAD,STUFF", "begins": "", "ends": "", "replace": "goodvalue"},
{"fieldName": "field1", "includes": "", "excludes": "", "begins": "ABC", "ends": "", "replace": "goodvalue"},
{"fieldName": "field1", "includes": "", "excludes": "", "begins": "", "ends": "XYZ", "replace": "goodvalue"},
{"fieldName... |
martynovp/edx-platform | openedx/core/djangoapps/util/testing.py | Python | agpl-3.0 | 8,831 | 0.002038 | """ Mixins for setting up particular course structures (such as split tests or cohorted content) """
from datetime import datetime
from pytz import UTC
from openedx.core.djangoapps.course_groups.models import CourseUserGroupPartitionGroup
from openedx.core.djangoapps.course_groups.tests.helpers import CohortFactory
f... | "passing_grade": 0,
"weight": 1.0
}]
}
)
chapter = ItemFactory.create(parent_location=self.course.location,
| display_name='Chapter')
# add a sequence to the course to which the problems can be added
self.problem_section = ItemFactory.create(parent_location=chapter.location,
category='sequential',
metadat... |
peace098beat/pyside_cookbook | 10_MatplotlibVSPygraph/mplcanvas/__init__.py | Python | gpl-3.0 | 104 | 0 |
from .SignalDataCanvas import SignalDataCanvas
from .SignalDataCanvas import S | ignalDataCanvasFast
| |
RedHatInsights/insights-core | insights/combiners/ceph_version.py | Python | apache-2.0 | 2,860 | 0.001399 | """
Ceph Version
============
Combiner for Ceph Version information. It uses the results of
the ``CephVersion``, ``CephInsights`` and ``CephReport`` parsers.
The order from most preferred to least preferred is `CephVersion``, ``CephInsights``, ``CephReport``.
"""
from insights import combiner
from insights.parsers.c... | .major = cv.major
self.minor = cv.minor
self.is_els = cv.is_els
self.downstream_release = cv.downstream_release
self.upstream_version = cv.upstream_version
else:
con | text = Context(content=cr["version"].strip().splitlines())
cv = CephV(context)
self.version = cv.version
self.major = cv.major
self.minor = cv.minor
self.is_els = cv.is_els
self.downstream_release = cv.downstream_release
self.upstream_v... |
derekjchow/models | research/feelvos/utils/video_input_generator.py | Python | apache-2.0 | 24,003 | 0.006208 | # Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | r.get([key])
object_label = None
video_id, = data_provider.get(['video_id'])
return image, label, object_label, image_name, height, width, video_id
def _has_foreground_and_backgr | ound_in_first_frame(label, subsampling_factor):
"""Checks if the labels have foreground and background in the first frame.
Args:
label: Label tensor of shape [num_frames, height, width, 1].
subsampling_factor: Integer, the subsampling factor.
Returns:
Boolean, whether the labels have foreground and ... |
wcooley/python-gryaml | tests/test_gryaml.py | Python | mit | 18,899 | 0.000106 | """Tests for `gryaml` module."""
from __future__ import print_function
from textwrap import dedent
from typing import Callable, List, Union
import pytest
import yaml
from boltons.iterutils import first
import gryaml
import py2neo_compat
# noinspection PyProtectedMember
from gryaml.pyyaml import _unregister as gryam... | nd = foremost(match_all_nodes(graphdb))
assert node_loaded == node_found
node_data = yaml.load(sample_yaml.replace('!gryaml.node', ''))
assert node_data[0]['properties'] == py2neo_compat.to_dict(node_loaded)
assert node_data[1]['labels'] == list(node_loaded.labels)
@pytest.mark.unit
def test_node_c... | with "simple" representation.
The "simple" representation should return the same structure that would
be created if the '!gryaml.node' tag were absent or the implicit type.
"""
gryaml.register_simple()
sample_yaml = """
!gryaml.node
- properties:
name: Babs_Jensen
... |
drphilmarshall/IntroBot | introbot.py | Python | gpl-2.0 | 594 | 0.005051 | import introbot
# Connect to twitter, using your own account...
try: from introbot import connection
except:
print "IntroBot: unable t | o connect to to Twitte | r"
sys.exit()
print "IntroBot: connected to Twitter: ",connection.line
# Instantiate a host, who will do the introductions:
jeeves = introbot.Host()
# Pass it the data it needs to figure out what to say:
# database = 'example/SHD_users_bios.csv'
database = 'example/pie.csv'
jeeves.listen(database)
# Pass the ... |
dansimau/pystringattr | stringattr.py | Python | bsd-3-clause | 5,928 | 0.000506 | import re
from collections import namedtuple, deque
from .regex import RE_SPLIT, RE_KEY, RE_INDEX
from .utils import Enum, _missing
StackItem = namedtuple('StackItem', ['name', 'a | ccess_method'])
# Accessor methods:
# INDEX means this accessor is index or key-based, eg. [1] or ['foo']
# DEFAULT means property
AccessorType = Enum(['INDEX', 'DEFAULT'])
def first(*vals):
"""Return the first value that's not _missing."""
for val in vals:
if val is not _missing:
return ... | """Retrieve index or key from the specified obj, or return
_missing if it does not exist.
"""
try:
return obj[index]
except (KeyError, IndexError, TypeError):
return _missing
def get_attribute(obj, attr):
"""Retrieve attribute from the specified obj, or return
_missing if it do... |
agrover/targetd | setup.py | Python | gpl-3.0 | 358 | 0 | #!/usr/bin/env python
from distu | tils.core import setup
setup(
name='targetd',
version='0.8.8',
description='Linux remote storage API daemon', |
license='GPLv3',
maintainer='Andy Grover',
maintainer_email='agrover@redhat.com',
url='http://github.com/open-iscsi/targetd',
packages=['targetd'],
scripts=['scripts/targetd']
)
|
antoinecarme/pyaf | tests/artificial/transf_Anscombe/trend_Lag1Trend/cycle_30/ar_/test_artificial_1024_Anscombe_Lag1Trend_30__0.py | Python | bsd-3-clause | 264 | 0.087121 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D' | , seed = 0, trendtype = "Lag1Trend", | cycle_length = 30, transform = "Anscombe", sigma = 0.0, exog_count = 0, ar_order = 0); |
MasterOdin/forseti | main.py | Python | mit | 702 | 0.001425 | """
A brief demonstration | of using the prover within Forseti
"""
from __future__ import print_function
from forseti.prover import Prover
# pylint: disable=duplicate-code
prover = Prover()
prover.add_formula("or(iff(G,H),iff(not(G),H))")
prover.add_goal("or(iff(not(G),not(H)),not(iff(G,H)))")
print(prover.run_prover())
print("\n".join(prover.... | ,forall(z,iff(B(z,y),and(B(z,x),B(z,z))))))))")
prover.add_formula("forall(x,not(B(x,x)))")
prover.add_formula("exists(x,S(x))")
prover.add_goal("exists(x,and(S(x),forall(y,not(B(y,x)))))")
print(prover.run_prover())
print("\n".join(prover.get_proof()))
|
rootfs/ctdb | tests/takeover/simulation/node_group.py | Python | gpl-3.0 | 1,299 | 0.004619 | #!/usr/bin/env python
# This demonstrates a node group configurations.
#
# Node groups can be defined with the syntax "-g N@IP0,IP1-IP2,IP3".
# This says to create a group of N nodes with IPs IP0, IP1, ..., IP2,
# IP3. Run it with deterministic IPs causes lots of gratuitous IP
# reassignments. Running with --nd fixe... | nt "Error: no node groups de | fined."
sys.exit(1)
for g in ctdb_takeover.options.groups:
add_node_group(g)
c.recover()
c.random_iterations()
|
FAForever/client | src/model/player.py | Python | gpl-3.0 | 4,165 | 0 | from PyQt5.QtCore import pyqtSignal
from model.modelitem import ModelItem
from model.rating import RatingType
from model.transaction import transactional
class Player(ModelItem):
newCurrentGame = pyqtSignal(object, object, object)
"""
Represents a player the client knows about.
"""
def __init__... | def global_estimate(self):
return self.rating_estimate()
@property
def ladder_estimate(self):
return self.rating_estimate(RatingType.LADDER.value)
@property
def global_rating_mean(self):
return self.rating_mean()
@property
def global_rating_deviation(self):
... | (self):
return self.rating_mean(RatingType.LADDER.value)
@property
def ladder_rating_deviation(self):
return self.rating_deviation(RatingType.LADDER.value)
@property
def number_of_games(self):
count = 0
for rating_type in self.ratings:
count += self.ratings[... |
petermalcolm/osf.io | framework/tasks/__init__.py | Python | apache-2.0 | 1,133 | 0.004413 | # -*- coding: utf-8 -*-
"""Asynchronous task queue module."""
from celery import Celery
from celery.utils.log import get_task_logger
from raven import Client
from raven.contrib.celery import register_signal
from website import settings
app = Celery()
# TODO: Hardcoded settings module. Should be set using framework... | k_logger(__name__)
# query the broker for the AsyncResult
result = app.Asyn | cResult(task_id)
excep = result.get(propagate=False)
# log detailed error mesage in error log
logger.error('#####FAILURE LOG BEGIN#####\n'
'Task {0} raised exception: {0}\n\{0}\n'
'#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))
|
buddyli/private2w | libs/pony/orm/__init__.py | Python | apache-2.0 | 28 | 0 | from pony.orm.core im | port * | |
ruchee/vimrc | vimfiles/bundle/vim-python/submodules/autopep8/test/suite/out/E21.py | Python | mit | 222 | 0 | #: E211
spam(1)
#: E211 E211
dic | t['key'] = list[index]
#: E211
dict['key']['subkey'] = list[index]
#: Okay
spam(1)
dict['key'] = list[index]
# This is not prohibit | ed by PEP8, but avoid it.
class Foo (Bar, Baz):
pass
|
tualatrix/django-alipay | alipay/trade_create_by_buyer/ptn/signals.py | Python | gpl-3.0 | 149 | 0 | from django.dispatch import S | ignal
# Sent when a payment is successfully processed.
alipay_ptn_successful = Signal()
alip | ay_ptn_flagged = Signal()
|
redmeros/Lean | Algorithm.Python/BasicTemplateAlgorithm.py | Python | apache-2.0 | 2,223 | 0.010806 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | the License for the specific language governing permissions and
# limitations under the License.
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect | .Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
import numpy as np
### <summary>
### Basic template algorithm simply initializes the date range and cash. This is a skeleton
### framework you can use for designing an algorithm.
### </summary>
### <meta name="tag" content=... |
arxcruz/tempest-tool | tempestmail/utils.py | Python | gpl-3.0 | 2,611 | 0.001532 | import datetime
import re
import requests
import tempestmail.constants as constants
from six.moves.urllib.parse import urljoin
def compare_tests(failures):
''' Detect fails covered by bugs and new'''
covered, new = [], []
for fail in failures:
for test in constants.TESTS:
if re.searc... | earch(l).group(1)
for l in console.splitlines() if constants.ERROR in l]
# all_skipped = [TESTRE.search(l).group(1)
# for l in console.splitlines() if SKIPPED in l]
return failed, ok, errors
def get_console(job_url):
''' Get console page of job'''
def _good_result(res):... | ()
# find last line with timestamp
for l in text[::-1]:
if constants.TIMEST.match(l):
return datetime.datetime.strptime(
constants.TIMEST.search(l).group(1),
"%Y-%m-%d %H:%M")
return None
url = urljoin(job_url, "console.htm... |
JohnLZeller/dd-agent | checks.d/mysql.py | Python | bsd-3-clause | 15,405 | 0.003505 | # stdlib
import subprocess
import os
import sys
import re
import traceback
# project
from checks import AgentCheck
from util import Platform
# 3rd party
import pymysql
GAUGE = "gauge"
RATE = "rate"
STATUS_VARS = {
'Connections': ('mysql.net.connections', RATE),
'Max_used_connections': ('mysql.net.max_connec... | passwd=password)
self.log.debug("Connected to MySQL")
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK, tags=service_check_tags)
except Exception:
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags)
raise
re... | W /*!50002 GLOBAL */ STATUS;")
status_results = dict(cursor.fetchall())
self._rate_or_gauge_statuses(STATUS_VARS, status_results, tags)
cursor.execute("SHOW VARIABLES LIKE 'Key%';")
variables_results = dict(cursor.fetchall())
cursor.close()
del cursor
#Compute ke... |
tecan/xchat-rt | plugins/scripts/encryption/supybot-code-6361b1e856ebbc8e14d399019e2c53a35f4e0063/plugins/MoobotFactoids/__init__.py | Python | gpl-2.0 | 2,507 | 0.000399 | ###
# Copyright (c) 2003-2005, Daniel DiPaolo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of cond... | is reloaded. Don't forget t | o import them as well!
if world.testing:
import test
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 softtabstop=8 expandtab textwidth=78:
|
lopesivan/blackjack | cartas/nipe.py | Python | gpl-2.0 | 169 | 0 | class Nipe(object):
def __init__(self, nome, simb | olo):
| self.nome = nome
self.simbolo = simbolo
def __repr__(self):
return self.simbolo
|
gfgtdf/wesnoth-old | utils/dockerbuilds/mingw/get_dlls.py | Python | gpl-2.0 | 470 | 0.002128 | #!/usr/bin/env python3
import pefile, pathlib, shutil
dlls = set()
dllpath = pathlib.Path('/windows/mingw64/bin')
pe_modules = set([pefile.P | E('wesnoth.exe')])
while pe_modules:
pe = pe_modules.pop()
for entry in pe.DIRECTORY_ENTRY_IMPORT:
path = dllpath / pathlib.Path(entry.dll | .decode())
if path not in dlls and path.exists():
dlls.add(path)
pe_modules.add(pefile.PE(path))
for dll in dlls:
shutil.copy(dll, ".")
|
Ripsnorta/pyui2 | docs/demos/widgetdemo/widgetdemo.py | Python | lgpl-2.1 | 7,972 | 0.005394 | ###################################################################################
# Copyright (c) 2005 John Judd
#
# 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, inclu... | nuitem):
self.logList.clearAllItems()
#########################################################################################################
##
#########################################################################################################
def addToLog(self, text):
self.log... | ext, None)
#########################################################################################################
##
#########################################################################################################
def onThemeChange(self, menuitem):
self.currentTheme = menuitem.text
... |
AaronWatters/inferelator_strawman | inferelator_strawman/design_response_R.py | Python | bsd-2-clause | 3,334 | 0.003599 | """
Compute design and response by calling R subprocess.
"""
import os
import subprocess
import pandas as pd
my_dir = os.path.dirname(__file__)
R_dir = os.path.join(my_dir, "R_code")
DR_module = os.path.join(R_dir, "design_and_response.R")
R_template = r"""
source('{module}')
meta.data <- read.table('{meta_file}'... | esponse.tsv', design_file='design.tsv'):
assert os.path.exists(DR_module), "doesn't exist " + repr(DR_module)
text = R_templ | ate.format(delTmin=delTmin, delTmax=delTmax, tau=tau,
meta_file=meta_file, exp_file=exp_file, module=module,
response_file=response_file, design_file=design_file)
with open(to_filename, "w") as outfile:
outfile.write(text)
return (to_filename, design_file, response_file)
... |
axelleonhart/TrainingDjango | materiales/apps/contratos/migrations/0003_auto_20170330_1333.py | Python | lgpl-3.0 | 432 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-30 19:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('contratos', '0002_auto_20170330_1328'),
]
operations = [
migrations.RenameField(
... | ,
]
| |
jguelat/BirdChooser | bird_chooser_dialog.py | Python | gpl-2.0 | 3,907 | 0.003327 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
BirdChooserDialog
A QGIS plugin
Show bird observations
-------------------
begin : 2015-11-05
git sha : $Fo... | Gui.QDialog, FORM_CLASS):
def __init__(self, iface, parent=None):
"""Constructor."""
super(BirdChooserDialog, self).__init__(parent)
# Set up the user interface from Designer.
# After setupUI you can access any designer object by doing
# self.<objectname>, and you can use aut... | # #widgets-and-dialogs-with-auto-connect
self.setupUi(self)
self.iface = iface
# Connecter les slots
self._connectSlots()
#self.conn = psycopg2.connect(database = "jguelat", user = "jguelat", password = "")
self.conn = psycopg2.connect(service = "local_jguelat")
def... |
punchagan/zulip | zerver/tests/test_custom_profile_data.py | Python | apache-2.0 | 35,581 | 0.002108 | from typing import Any, Dict, List, Union
from unittest import mock
import orjson
from zerver.lib.actions import (
do_remove_realm_custom_profile_field,
do_update_user_custom_profile_data_if_changed,
try_add_realm_custom_profile_field,
try_reorder_realm_custom_profile_fields,
)
from zerver.lib.externa... | ,
)
class CustomProfileFieldTestCase(ZulipTestCase):
def setUp(self) -> None:
super().setUp()
self.realm = get_realm("zuli | p")
self.original_count = len(custom_profile_fields_for_realm(self.realm.id))
def custom_field_exists_in_realm(self, field_id: int) -> bool:
fields = custom_profile_fields_for_realm(self.realm.id)
field_ids = [field.id for field in fields]
return field_id in field_ids
class Create... |
pombredanne/pythran | pythran/tests/openmp.legacy/omp_parallel_for_lastprivate.py | Python | bsd-3-clause | 279 | 0.003584 | def omp_parallel_for_lastprivate():
sum = 0
i0 = -1
'omp parallel for reduction(+:sum) schedule(static,7) lastprivate(i0)'
for i in range(1,1001):
sum += i
i0 = i
| known_sum = (1000 * (1000 + 1)) / 2
return | known_sum == sum and i0 == 1000
|
jonathanslenders/pyvim | pyvim/commands/completer.py | Python | bsd-3-clause | 1,985 | 0.001008 | from __future__ import unicode_literals
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.completion import WordCompleter, PathCompleter
from prompt_toolkit.contrib.completers.system import SystemCompleter
from prompt_toolkit.contrib.regular_languages.completion import GrammarCompleter
f... |
commands = [c + ' ' for c in get_commands()]
return GrammarCompleter(COMMAND_GRAMMAR, {
'command': WordCompleter(commands),
'location': PathCompleter(expanduser=True),
'set_option': WordCompleter(sorted(SET_COMMANDS)),
'buffer_name': BufferNameCompleter(editor),
'colors... | is sufficient when the input appears anywhere in the buffer name, to
trigger a completion.
"""
def __init__(self, editor):
self.editor = editor
def get_completions(self, document, complete_event):
text = document.text_before_cursor
for eb in self.editor.window_arrangement.edit... |
cloudfoundry-incubator/bosh-vsphere-cpi-release | scripts/pyvmomi_to_ruby/gen_server_objects.py | Python | apache-2.0 | 219 | 0.013699 | #!/usr/bin/env python
print("""# ******* WARNING - AUTO GENERATED CODE - DO NOT EDIT *******
module VimSdk
module VmomiSupport
"" | ")
import ServerObjects
import PbmObjects
import SmsObjects
print(""" en | d
end
""")
|
Trophime/singularity | libexec/python/tests/test_json.py | Python | bsd-3-clause | 9,089 | 0.022335 | '''
test_json.py: Singularity Hub testing functions for Singularity in Python
Copyright (c) 2016-2017, Vanessa Sochat. All rights reserved.
"Singularity" Copyright (c) 2016, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from ... | 'message']
if isinstance(output,bytes):
output = output.decode(encoding='UTF-8')
self.assertEqual('rigatoni!',output.strip('\n').split('\n')[-1])
print('Case 2: Get non-existing key exits')
if VERSION == 2:
testing_ | command = ["python2",script_path,'--key','LASAGNA','--file',self.file]
else:
testing_command = ["python3",script_path,'--key','LASAGNA','--file',self.file]
output = Popen(testing_command,stderr=PIPE,stdout=PIPE)
t = output.communicate()[0],output.returncode
result = {'messag... |
lucastheis/c2s | scripts/c2s-leave-one-out.py | Python | mit | 3,513 | 0.022773 | #!/usr/bin/env python
"""
Measure the performance of STM based spike prediction by repeatedly
using all but one cell for training and the remaining cell for testing.
"""
import os
import sys
from argparse import ArgumentParser
from pickle import dump
from scipy.io import savemat
from numpy import mean, std, corrcoef... | del entry['calcium']
# save results
if args.output.lower().endswith('.mat'):
savemat(args.output, convert({'data': data}))
elif args.output.lower().endswith('.xpck'):
experiment['args'] = args
experiment['data'] = | data
experiment.save(args.output)
else:
with open(args.output, 'w') as handle:
dump(data, handle, protocol=2)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
Alecto3-D/testable-greeter | bb-master/sandbox/lib/python3.5/site-packages/autobahn/wamp/types.py | Python | mit | 36,554 | 0.003146 | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Crossbar.io Technologies GmbH
#
# 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 ... | use case would be
to hold a shared database connection pool.
:type shared: dict or None
"""
assert(realm is None or type(realm) == six.text_type)
# assert(keyring is None or ...) # FIXME
self.realm = realm
self.extra = extra
self.keyring = keyring
... | r__(self):
return u"ComponentConfig(realm=<{}>, extra={}, keyring={}, controller={}, shared={})".format(self.realm, self.extra, self.keyring, self.controller, self.shared)
@public
class HelloReturn(object):
"""
Base class for ``HELLO`` return information.
"""
@public
class Accept(HelloReturn):
... |
oldani/nanodegree-blog | app/models/comment.py | Python | mit | 422 | 0 | from datetime import datetime
from .base import BaseModel
class Comment(BaseModel):
def __init__(self, **kwargs):
# Add created and updated attrs by default.
| self.created = self.updated = datetime.now()
super().__i | nit__(**kwargs)
def update(self):
""" Extends update method to update some fields before saving. """
self.updated = datetime.now()
super().update()
|
jaredmcqueen/hot-wheels-radar-gun | getSerialData.py | Python | mit | 779 | 0 | import serial
import time
import datetime
import csv
ser = serial.Serial('/dev/c | u.usbmodem1411', 9600, timeout=0)
my_file = 'data.csv'
f = open(my_file, 'wt')
writer = csv.writer(f)
writer.writerow(('dateTime', 'analogValue')) # csv column headers
while True:
try:
# write a csv row
writer.writerow((datetime.datetime.now(), ser.readline().strip()))
# print out to scr... | if analog_value:
line = '%s,%s\n' % (datetime.datetime.now(), analog_value)
print line.strip()
time.sleep(.001)
except ser.SerialTimeoutException:
print('Data could not be read')
time.sleep(1)
|
pferreir/indico-backup | indico/MaKaC/plugins/EPayment/yellowPay/__init__.py | Python | gpl-3.0 | 882 | 0.013605 | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free s | oftware; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Ind | ico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with ... |
moreus/hadoop | hadoop-0.11.2/src/contrib/abacus/examples/pyAbacus/JythonAbacus.py | Python | apache-2.0 | 2,577 | 0.014358 | #
# Copyright 2006 The Apache Software Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht | tp://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 the specific language governing permission... | ations under the License.
#
from org.apache.hadoop.fs import Path
from org.apache.hadoop.io import *
from org.apache.hadoop.mapred import *
from org.apache.hadoop.abacus import *
from java.util import *;
import sys
class AbacusMapper(ValueAggregatorMapper):
def map(self, key, value, output, reporter):
... |
pombredanne/mopidy-webhooks | mopidy_webhooks/__init__.py | Python | apache-2.0 | 877 | 0 | from __future__ im | port unicode_literals
import logging
import os
from mopidy import config, ext
__version__ = '0.3.0'
logger = logging.getLogger(__name__)
class Extension(ext.Extension):
dist_name = 'Mopidy-Webhooks'
ext_name = 'webhooks'
version = __version__
def get_default_config(self):
conf_file = os.... | n config.read(conf_file)
def get_config_schema(self):
schema = super(Extension, self).get_config_schema()
schema['api_key'] = config.String()
schema['api_key_header_name'] = config.String()
schema['status_update_interval'] = config.Integer()
schema['webhook_url'] = config.St... |
zachary-williamson/ITK | Modules/ThirdParty/pygccxml/src/pygccxml/parser/etree_scanner.py | Python | apache-2.0 | 1,759 | 0.000569 | # Copyright 2014-2015 Insight Software Consortium.
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0.
# See http://www.boost.org/LICENSE_1_0.txt
from . import scanner
# keep py2exe happy
import xml.etree.ElementTree
import xml.etree.cElementTree as ElementTree
class... | :
tree = ElementTree.parse(self.xml_file)
saxifier = etree_saxifier_t(tree, self)
saxifier.saxify()
class ietree_scanner_t(scanner.scanner_t):
def __init__(self, xml_file, decl_factory, *args):
scanner.scanner_t.__init__(self, xml_file, decl_factory, *args)
def read(self):
... | event, elem in context:
if event == 'start':
self.startElement(elem.tag, elem.attrib)
else:
self.endElement(elem.tag)
elem.clear()
self.endDocument()
etree_scanner_t = ietree_scanner_t
|
v-iam/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2016_12_01/models/ip_configuration.py | Python | mit | 2,982 | 0.001677 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | nit__(self, id=None, private_ip_address=None, private_ip_allocation_method=None, subnet=None, public_ip_address=None, provisioning_s | tate=None, name=None, etag=None):
super(IPConfiguration, self).__init__(id=id)
self.private_ip_address = private_ip_address
self.private_ip_allocation_method = private_ip_allocation_method
self.subnet = subnet
self.public_ip_address = public_ip_address
self.provisioning_s... |
loopingz/nuxeo-drive | nuxeo-drive-client/nxdrive/updater.py | Python | lgpl-2.1 | 17,952 | 0.001337 | """Application update utilities using esky"""
import sys
import errno
import json
from urlparse import urljoin
from urllib2 import URLError
from urllib2 import HTTPError
import socket
from esky import Esky
from esky.errors import EskyBrokenError
from nxdrive.logging_config import get_logger
from nxdrive.engine.workers... | DATE_CHECK_DELAY
from nxdriv | e.utils import version_compare
from PyQt4 import QtCore
log = get_logger(__name__)
# Update statuses
UPDATE_STATUS_UPGRADE_NEEDED = 'upgrade_needed'
UPDATE_STATUS_DOWNGRADE_NEEDED = 'downgrade_needed'
UPDATE_STATUS_UPDATE_AVAILABLE = 'update_available'
UPDATE_STATUS_UPDATING = 'updating'
UPDATE_STATUS_UP_TO_DATE = 'u... |
ciechowoj/minion | output.py | Python | mit | 6,974 | 0.004158 | import sublime, sublime_plugin
def clean_layout(layout):
row_set = set()
col_set = set()
for cell in layout["cells"]:
row_set.add(cell[1])
row_set.add(cell[3])
col_set.add(cell[0])
col_set.add(cell[2])
row_set = sorted(row_set)
col_set = sorted(col_set)
rows =... | ])
elif cell != group_cell:
new_cells.append(cell)
layout["cells"] = new_cells
window.set_layout(clean_layout(layout))
class OutputView:
content = ""
position = 0.0
id = None
def __init__(self, view):
self.view = view
def __getattr__(self, name):
... | if output:
self.view = output.view
return getattr(self.view, name)
def clear(self):
OutputView.content = ""
self.run_command("output_view_clear")
def append(self, text):
OutputView.content += text
self.run_command("output_view_append", { "text" : t... |
elephanter/mongoengine | mongoengine/base/datastructures.py | Python | mit | 15,294 | 0.001504 | import weakref
import functools
import itertools
from mongoengine.common import _import_class
from mongoengine.errors import DoesNotExist, MultipleObjectsReturned
__all__ = ("BaseDict", "BaseList", "EmbeddedDocumentList")
class BaseDict(dict):
"""A special dict so we can watch any changes"""
_dereferenced =... | , **kwargs):
"""
Filters the list by excluding embedded documents with the given
keyword arguments.
:param kwargs: The keyword arguments corresponding to the fields to
exclude on. * | Multiple |
HybridF5/hybrid-jacket | nova_jacket/virt/jacket/vcloud/vcloud.py | Python | apache-2.0 | 51,929 | 0.003216 | # VMware vCloud Python helper
# Copyright (c) 2014 Huawei, 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
#
# Unl... | return self._network_name
@property
def fence_mode(self):
return self._fence_mode
@property
def href(self):
return self._href
class NetworkConnection(object):
def __init__(self, network_name=None, ip_allocation_mode=None, ip_address=None, mac_address=None):
self._netw... | self._mac_address = mac_address
@property
def network_name(self):
return self._network_name
@property
def ip_allocation_mode(self):
return self._ip_allocation_mode
@property
def ip_address(self):
return self._ip_address
@property
def mac_address(self):
... |
zrluety/penguin | penguin/scripts/penguin_cli.py | Python | mit | 1,738 | 0.004028 | import click
import os
| import penguin.pdf as pdf
import penguin.utils as utils
def check_src(src):
if not all((map(utils.is_valid_source, src))):
raise click.BadParameter("src arguments must be either a valid directory"
" or pdf file.")
@click.group()
def penguin():
pass
@penguin.command(... | k.argument('dst')
@click.option('--bookmark', 'bookmark', flag_value='include-bookmarks',
default=True)
@click.option('--remove-blank-pages', 'rmblanks', flag_value='remove-blanks-pages',
default=False)
def combine(src, dst, bookmark, rmblanks):
"""Combine Pdf files from the source provi... |
AjabWorld/ajabsacco | ajabsacco/core/migrations/0002_auto_20150508_0542.py | Python | apache-2.0 | 1,088 | 0.000919 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
cla | ss Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='loanproduct',
name='accounting_rules',
),
migrations.RemoveField(
model_name='loanproduct',
na... | anproduct',
name='fees',
),
migrations.RemoveField(
model_name='loanproduct',
name='meta',
),
migrations.RemoveField(
model_name='security',
name='meta',
),
migrations.AlterField(
model_name='member',... |
andrewjton/SHOUT | app/shout/yell/urls.py | Python | mit | 435 | 0.013793 | from django.conf.urls import url
from yell import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^testing/$', views.testing, name=' | testing'),
url(r'^results/$', views.restaurants, name | ='restaurants'),
url(r'^api/yelp_api/$', views.yelp_api, name="yelp_api"),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) |
johnnoone/meuh-python | meuh/commands/distro.py | Python | mit | 2,649 | 0.000378 | """
meuh.commands.distro
~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import, print_function, unicode_literals
__all__ = ['InitCommand',
'DestroyAllCommand',
'DestroyCommand',
'ShowCommand']
import logging
from cliff.command import Command
from meuh.action import ... | ser = super(InitCommand, self).get_parser(prog_name)
parser.add_argument( | 'distro')
parser.add_argument('--force', action='store_true')
return parser
def take_action(self, parsed_args):
data = distro_init(parsed_args.distro, parsed_args.force)
print('created %s %s' % (parsed_args.distro, data))
class ShowCommand(Command):
'show distribution'
lo... |
lm-tools/situational | situational/apps/sectors/forms.py | Python | bsd-3-clause | 2,817 | 0 | from django import forms
from django.forms.forms import BoundField
from .helpers import LMIForAllClient
from .fields import MultiCharField
class FieldSet(object):
"""
Taken from stackoverflow.com/questions/10366745/django-form-field-grouping
Helper class to group BoundField objects together.
"""
... | elds_from_keywords(self, keywords):
for keyword in keywords:
if keyword:
soc_codes = []
lmi_data = self.lmi_client.keyword_search(keyword)
count = 6
for item in lmi_data[:count]:
soc_code = str(item['soc'])
... | (
widget=forms.CheckboxInput,
label=item['title'],
help_text=item['description'],
required=False,
)
self.fields[soc_code] = field
self.fieldsets... |
scode/pants | contrib/spindle/src/python/pants/contrib/spindle/tasks/spindle_gen.py | Python | apache-2.0 | 10,402 | 0.007402 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import re
... | epends on at runtime.',
)
cls.register_jvm_tool(register,
'spindle-codegen',
classpath=[
JarDependency(org='com.foursquare',
name='spindle-codegen-binary_2.10',
... | round_manager)
round_manager.require_data('jvm_build_tools_classpath_callbacks')
@property
def spindle_classpath(self):
return self.tool_classpath('spindle-codegen')
@property
def synthetic_target_extra_dependencies(self):
return set(
dep_target
for dep_spec in self.get_options().runt... |
thomashuang/Lilac | lilac/controller/__init__.py | Python | lgpl-3.0 | 136 | 0.007353 | #!/usr/bin/env python
import logging
LOGGER = logging.getLogger('controller') | USER = 'user'
ROOT = 'root'
ADMIN = 'administrator'
| |
arventwei/django_test | mysite/mysite/view.py | Python | mit | 589 | 0.010187 | from django.http imp | ort HttpResponse
import datetime
def hel | lo(request):
return HttpResponse("Hello world")
def home(request):
datetime.datetime.now()
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueErro... |
Prokuma/cafe-order-system | register.py | Python | mit | 598 | 0.006356 | #-*- coding: utf-8 -*-
import hashlib
import getpass
from pymongo import MongoClient
id = raw_input("등록할 아이디를 입력하 | 세요: ")
pw = getpass.getpass("등록할 비밀번호를 입력하세요(입력하는 것은 보이지 않습니다): ")
client = MongoClient('localhost', 27017)
db = client.RnBCafe
member_collection = db.member |
if member_collection.find_one({'id': id}) is None:
member_collection.insert({'id': id, 'password': hashlib.sha512(pw).hexdigest()})
print "성공적으로 등록이 완료되었습니다!"
else:
print "이미 있는 아이디입니다." |
ANU-Linked-Earth-Data/middleware | batch-demo/import_agdc_data.py | Python | apache-2.0 | 12,109 | 0.000165 | #!/usr/bin/env python3
"""Loads an HDF5 file representing Landsat data into a triple store via
SPARQL."""
from argparse import ArgumentParser
from base64 import b64encode
from io import StringIO, BytesIO
from itertools import islice, chain
from dateutil.parser import parse as date_parse
import h5py
import numpy as n... | sensor data"@en ;
rdfs:comment "Some data from LandSat, retrieved from AGDC"@en ;
qb:structure :landsatDSD ;
:instrument gcmd-instrument:SCANNER ;
:satellite gcmd-platform:LANDSAT-7 ;
:dggs "rHEALPix WGS84 Ellipsoid" .
:instrumentComponent a qb:ComponentSpecification ;
qb:attribute :instrument... | :ComponentSpecification ;
qb:dimension :location .
:satelliteComponent a qb:ComponentSpecification ;
qb:attribute :satellite .
:timeComponent a qb:ComponentSpecification ;
qb:dimension :time .
:dataComponent a qb:ComponentSpecification ;
qb:measure :imageData .
:etmBandComponnet a qb:ComponentSpecif... |
pombredanne/ompc | ompclib/gplot/PlotItems.py | Python | bsd-3-clause | 24,085 | 0.001412 | # $Id: PlotItems.py,v 2.13 2003/08/18 22:33:00 mhagger Exp $
# Copyright (C) 1998-2003 Michael Haggerty <mhagger@alum.mit.edu>
#
# This file is licensed under the GNU Lesser General Public License
# (LGPL). See LICENSE.txt for details.
"""PlotItems.py -- Objects that can be plotted by Gnuplot.
This module contains ... | ing the elementary argument that
must be passed to gnuplot's `plot' command for this item;
e.g., 'sin(x)' or '"filename.dat"'.
'_options' -- a dictionary of ( | <option>,<string>) tuples
corresponding to the plot options that have been set for
this instance of the PlotItem. <option> is the option as
specified by the user; <string> is the string that needs to
be set in the command line to set that option (or None if no
string i... |
VA3SFA/rpi_hw_demo | hc-sr04/distance.py | Python | gpl-2.0 | 82 | 0.012195 | #!/usr/bin/p | ython
# -*- coding: utf-8 -*-
# | Copyright 2015, Syed Faisal Akber
#
|
pvtodorov/indra | indra/tests/test_lincs_drug.py | Python | bsd-2-clause | 980 | 0 | from __future__ import absolute_import, print_function, unicode_literals
import unittest
from nose.plugins.attrib import attr
from indra.databases.lincs_client import get_drug_target_data
from indra.sources.lincs_drug import process_from_web
@attr('webservice')
@unittest.skip('LINCS web service very unreliable.')
de... | from_web():
lincs_p = process_from_web()
assert lincs_p is not None
assert lincs_p.statements
data_len = len(get_drug_target_data())
num_stmts = len(lincs_p.statements)
# Note that due to an erroneous entry in the HMS LINCS protein table,
# one Statement is not extracted from the table, henc... | tements: expected %d, got %d."
% (data_len, num_stmts))
assert all(len(s.evidence) > 0 for s in lincs_p.statements),\
"Some statements lack evidence."
|
SmartPeople/zulip | zerver/webhooks/crashlytics/view.py | Python | apache-2.0 | 1,910 | 0.002618 | # Webhooks for external integrations.
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
fr... | lytics_webhook(request, user_profile, client, payload=REQ(argument_type='body'),
stream=REQ(default='crashlytics')):
# type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text) -> HttpResponse
try:
event = payload['event']
if event == VERIFICATION_EVENT:
... | bject = CRASHLYTICS_SUBJECT_TEMPLATE.format(
display_id=issue_body['display_id'],
title=issue_body['title']
)
body = CRASHLYTICS_MESSAGE_TEMPLATE.format(
impacted_devices_count=issue_body['impacted_devices_count'],
url=issue_body['u... |
kburts/django-playlist | django_playlist/django_playlist/wsgi.py | Python | mit | 1,578 | 0.001267 | """
WSGI config for django_playlist project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLIC... | dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MOD... | "
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_playlist.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
applic... |
azurefang/flask-zheye | app/main/verbs.py | Python | lgpl-3.0 | 163 | 0.006135 | from feedly.verbs import register
from | feedly.verbs.base import Verb
class Pin(Verb):
id = 5
infinitive = 'pin'
past_tense = 'pinned'
registe | r(Pin)
|
jiadaizhao/LeetCode | 1601-1700/1637-Widest Vertical Area Between Two Points Containing No Points/1637-Widest Vertical Area Between Two Points Containing No Points.py | Python | mit | 193 | 0 | class Solution:
def maxWidthOfVerticalArea(self, points: | List[List[int]]) -> int:
xs = sorted(x for x, y in | points)
return max(xs[i] - xs[i - 1] for i in range(1, len(xs)))
|
seasonfif/python | learning/classmodule/Parent.py | Python | apache-2.0 | 1,829 | 0.03897 | # coding=utf-8
class Parent(object):
__parentAttr = 100
_parentAttr = 100
parentAttr = 100
def __init__(self):
print "父类构造函数"
def parentMethod(self):
print "父类方法"
def _protectedMet | hod(self):
print "我是protected方法"
def __privateMethod(self):
print "我是private方法"
def overWriteMethod(self):
print "父类方法重写"
class Father(object):
__parentAttr = 200
_parentAttr = 200
parentAttr = 200
def __init_ | _(self):
print "Father类构造函数"
def parentMethod(self):
print "Father类方法"
def _protectedMethod(self):
print "Father protected方法"
def __privateMethod(self):
print "Father private方法"
def overWriteMethod(self):
print "Father类方法重写"
class Child (Father,Parent):
childAttr = "100"
def __init__(self):
# ... |
beblount/Steer-Clear-Backend-Web | steerclear/__init__.py | Python | mit | 723 | 0.006916 | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
#initialize flask app wi | th correct configurations
app = Flask(__name__)
app.config.from_object('steerclear.settings.windows_settings')
app.config.from_envvar('STEERCLEAR_SETTINGS')
db = SQLAlchemy(app)
from flask.ext.login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
from steerclear.api.views import api_bp
... | iver_portal_bp
from steerclear.login.views import login_bp
# register all blueprints to the app
app.register_blueprint(api_bp)
app.register_blueprint(driver_portal_bp)
app.register_blueprint(login_bp)
# :TODO: generate actual secret key
app.secret_key = 'secret'
|
ctrlaltdel/neutrinator | vendor/openstack/tests/unit/block_storage/v2/test_type.py | Python | gpl-3.0 | 1,577 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | base_path)
self.assertTrue(sot.allow_create)
self.assertTrue(sot.allow_fetch)
self.assertTrue(sot.allow_delete)
self.assertTrue(sot.allow_list)
self.assertFalse(sot.allow_commit)
def test_new(self):
sot | = type.Type.new(id=FAKE_ID)
self.assertEqual(FAKE_ID, sot.id)
def test_create(self):
sot = type.Type(**TYPE)
self.assertEqual(TYPE["id"], sot.id)
self.assertEqual(TYPE["extra_specs"], sot.extra_specs)
self.assertEqual(TYPE["name"], sot.name)
|
sonofeft/ODSCharts | docs/sphinxy.py | Python | gpl-3.0 | 4,251 | 0.008469 | #!/usr/bin/env python
# sphinxy: commandline continuous integration sphinx documentation
#
# Copyright (C) 2015 Charlie Taylor <ctatsourceforge@gmail.com>
#
# 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... | y(TARGET_DIR, touch_first=True)
| subprocess.call(command.split())
print_instructions()
time.sleep(1)
if kb.kbhit():
c = kb.getch()
if ord(c) == 27: # ESC
sys.exit()
elif ord(c) == ord('b'): # launch brow... |
sivaprakashniet/push_pull | p2p/lib/python2.7/site-packages/celery/backends/base.py | Python | bsd-3-clause | 19,323 | 0.000052 | # -*- coding: utf-8 -*-
"""
celery.backends.base
~~~~~~~~~~~~~~~~~~~~
Result backend base classes.
- :class:`BaseBackend` defines the interface.
- :class:`KeyValueStoreBackend` is a common base class
using K/V semantics like _get and _put.
"""
from __future__ import absolute_import
import... | r(payload)
return loads(payload,
content_type=self.content_type,
content_encoding=self.content_encoding,
accept=self.accept)
def wait_for(self, task_id, timeout=None, propagate=True, interval=0.5):
"""Wait for task and return its result... | f the task raises an exception, this exception
will be re-raised by :func:`wait_for`.
If `timeout` is not :const:`None`, this raises the
:class:`celery.exceptions.TimeoutError` exception if the operation
takes longer than `timeout` seconds.
"""
time_elapsed = 0.0
... |
robhudson/kuma | kuma/wiki/constants.py | Python | mpl-2.0 | 12,819 | 0.000546 | import re
import bleach
from tower import ugettext_lazy as _lazy
ALLOWED_TAGS = bleach.A | LLOWED_TAGS + [
'div', 'span', 'p', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'pre', 'code', 'cite',
'dl', 'dt', 'dd', 'small', 'sub', 'sup', 'u', 'strike', 'samp', 'abbr',
'ul', 'ol', 'li',
'nobr', 'dfn', 'caption', 'var', 's',
'i', 'img', 'hr',
'input', 'label', 'select', 'option', 'textar... | lgroup', 'col',
'section', 'header', 'footer', 'nav', 'article', 'aside', 'figure',
'figcaption',
'dialog', 'hgroup', 'mark', 'time', 'meter', 'command', 'output',
'progress', 'audio', 'video', 'details', 'summary', 'datagrid', 'datalist',
'table', 'address', 'font',
'bdi', 'bdo', 'del', 'ins', ... |
xuru/pyvisdk | pyvisdk/do/host_license_connect_info.py | Python | mit | 1,053 | 0.009497 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def HostLicenseConnectInfo(vim, *args, **kwargs):
'''This data object type describes lice... | ' % len(args))
required = [ 'evaluation', 'license' ]
optional = [ 'resource', 'dynamicProperty', 'dynamicType' ]
for name, arg in zip(required+optional, args):
setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, va... | obj
|
FEniCS/dolfin | doc/generate_api_rst.py | Python | lgpl-3.0 | 8,783 | 0.001708 | #!/usr/bin/env python
#
# Read doxygen xml files to find all members of the dolfin
# name space and generate API doc files per subdirectory of
# dolfin
#
# Written by Tormod Landet, 2017
#
from __future__ import print_function
import sys, os
import parse_doxygen
DOXYGEN_XML_DIR = 'doxygen/xml'
API_GEN_DIR = 'generate... | odule_py_name, full_module_py_name))
out.write('sys.modules["%s"] = %s\n' % (full_module_py_name, module_py_name))
out.write('\n')
print(' Generating module', full_module_py_name)
for member in namespace_members:
# Check if this member is included in t... | continue
out.write(member.to_mock(modulename=module_py_name))
out.write('\n\n')
def parse_doxygen_xml_and_generate_rst_and_swig(xml_dir, api_gen_dir, swig_dir, swig_file_name,
swig_header='', mock_py_module=''):
# Read doxyg... |
axltxl/zenfig | zenfig/log.py | Python | mit | 1,553 | 0.001288 | # -*- coding: ut | f-8 -*-
"""
zenfig.log
~~~~~~~~~~~~~
Nice output
:copyright: (c) 2016 by Alejandro Ricoveri
:license: MIT, see LICENSE for more details.
"""
import sys
from clint.textui.colored import white, red, cyan, yellow, green
from clint.textui import puts
# Globals
_stdout = False
def init(*, quiet_stdout=True):
"""... | essages under this level won't be issued/logged
:param to_stdout: activate stdout log stream
"""
# create stout handler
if not quiet_stdout:
global _stdout
_stdout = True
def to_stdout(msg, *, colorf=green, bold=False, quiet=True):
if not quiet or _stdout:
print(colorf(msg... |
bath-hacker/binny | binny/db/models.py | Python | mit | 1,478 | 0.004736 | from django.db import models
from django.contrib.auth.models import User
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self,... | return 'ID:{0} {1}'.format(self.pk, self.description)
class Found(models.Model):
user = models.ForeignKey(User)
bin = models.ForeignKey(Bin)
date_added = mo | dels.DateField(auto_now_add=True)
difficulty = IntegerRangeField(min_value=1, max_value=5)
overflowing = models.BooleanField(default=False)
notes = models.CharField(max_length=140)
def __str__(self):
return '{0} found {1} on {2}'.format(self.user.username, self.bin.asset, self.date_added)
|
timoMa/vigra | vigranumpy/examples/boundary_gui/bv_feature_selection.py | Python | mit | 3,993 | 0.013023 | import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy#
from pyqtgraph.parametertree import Parameter, ParameterTree, ParameterItem, registerParameterType
class FeatureSelectionDialog(QtGui.QDialog):
def __init__(self,viewer, parent):
super(FeatureSelectionDialog, self).__init... | l=True):
return {
'name': name,
'type': 'bool',
'value': val,
#'tip': "This is a checkbox",
}
sigmaOpt = {'name': 'sigma', 'type': 'str', 'value': '[0.0, 1.0, | 2.0, 4.0]' }
wardOpts = {'name': 'wardness', 'type': 'str', 'value': '[0.0, 0.1, 0.2]' }
filterChild = [
makeCheckBox("computeFilter"),
sigmaOpt,
{
'name':'UCM',
'children': [
makeCheckBox("ucmFilters"),
... |
MaayanLab/clustergrammer-widget | clustergrammer_widget/clustergrammer/load_data.py | Python | mit | 2,352 | 0.022109 | import io, sys
import json
import pandas as pd
from . import categories
from . import proc_df_labels
from . import data_formats
from . import make_unique_labels
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
def load_file(net, filename):
# reset network when loaing file, prev... | s = f.readlines()
f.close()
gmt = {}
for i in range(len(lines)):
inst_line = lines[i].rstrip()
inst_term = inst_line.split('\t')[0]
inst_elems = inst_line.split('\t')[2:]
gmt[inst_term] = inst_elems
return gmt
def load_data_to_net(net, inst_net):
''' load data into nodes and mat, also conver... | t['mat']
data_formats.mat_to_numpy_arr(net) |
g2p/xtraceback | xtraceback/tracebackcompat.py | Python | mit | 3,453 | 0.001158 | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equival... | self).__init__()
self.defaults = defaults
# register patches for methods that wrap traceback functions
for key in dir(traceback):
if hasattr(self, key):
| self._register_patch(traceback, key, getattr(self, key))
#def __exit__(self, etype, evalue, tb):
#if etype not in self.NOPRINT:
#self.print_exception(etype, evalue, tb)
#super(TracebackCompat, self).__exit__(etype, evalue, tb)
def _factory(self, etype, value, tb, limit=No... |
chromium/chromium | third_party/tensorflow-text/src/tensorflow_text/python/ops/regex_split_ops.py | Python | bsd-3-clause | 10,403 | 0.003557 | # coding=utf-8
# Copyright 2021 TF.Text Authors.
#
# 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 ag... | s)
begin_offsets_rt = input.with_flat_values(begin_offsets)
end | _offsets_rt = input.with_flat_values(end_offsets)
return tokens_rt, begin_offsets_rt, end_offsets_rt
delim_regex_pattern = b"".join(
[b"(", delim_regex_pattern.encode("utf-8"), b")"])
keep_delim_regex_pattern = b"".join(
[b"(", keep_delim_regex_pattern.encode("utf-8"), b")"])
# reshape to a flat... |
dandesousa/lapis | tests/test_slugs.py | Python | cc0-1.0 | 2,165 | 0.000924 | #!/usr/bin/env python
# encoding: utf-8
import os
import tempfile
import unittest
class TestSlug(unittest.TestCase):
"""tests features related to creating slugs"""
def setUp(self):
self.tempd_path = tempfile.mkdtemp()
def tearDown(self):
import shutil
shutil.rmtree(self.tempd_p... | lapis.slug import slugify
slug = slugify("The World's Greatest Title")
self.assertTrue("the-world's-greatest-title", slug)
def test_unique_slug_with_date(self):
from lapis | .slug import unique_path_and_slug
from lapis.slug import slugify
from lapis.formats import default_format
from datetime import datetime
title = "My Unique Title"
path, slug = unique_path_and_slug(title, self.tempd_path, date=datetime.now())
expected_fn = "{}-{}.{}".format... |
comic/comic-django | app/grandchallenge/github/migrations/0004_auto_20210916_0746.py | Python | apache-2.0 | 769 | 0 | # Generated by Django 3.1.13 on 2021-09-16 07:46
from django.db imp | ort migrations, models
class Migration(migrations.Migration):
dependencies = [
("github", "0003_githubusertoken"),
]
operations = [
migrations.AddField(
| model_name="githubwebhookmessage",
name="error",
field=models.TextField(blank=True),
),
migrations.AddField(
model_name="githubwebhookmessage",
name="has_open_source_license",
field=models.BooleanField(default=False),
),
... |
harsha5500/pytelegrambot | bots/doloresBot.py | Python | gpl-3.0 | 3,494 | 0.002862 | __author__ = 'harsha'
import telegram_methods.getMe
import telegram_methods.getUpdates
import telegram_methods.sendMessage
import telegram.Update
import telegram.Message
import telegram.User
import telegram.Gr | oupChat
import bot_utilities.tgtwitter
import re
base_url = "https://api.tele | gram.org/bot"
auth_file_name = "../bots/doloresBot.auth"
auth_file = open(auth_file_name, 'r')
auth_token = auth_file.readline()
consumer_key = auth_file.readline()
consumer_secret = auth_file.readline()
access_token = auth_file.readline()
access_token_secret = auth_file.readline()
auth_file.close()
# Remove the newli... |
galtay/data_sci_ale | code_kata_04/kata_04.py | Python | gpl-3.0 | 2,540 | 0.000787 | import pandas
WEATHER_FNAME = 'weather.dat'
FOOTBALL_FNAME = 'football.dat'
def read_weather(fname=WEATHER_FNAME):
"""Read the weather file into a DataFrame and return it.
Pandas has many input routines (all prefixed with "read")
- http://pandas.pydata.org/pandas-docs/stable/io.html
Examining t... | list of strings
# into the square bracket operator
print( | weather_df['WxType'])
print
print(weather_df[['HDDay', 'AvSLP']])
print
# "loc" and "iloc" are ways to index into the DataFrame
|
fpeyre/shinken | shinken/daemons/brokerdaemon.py | Python | agpl-3.0 | 33,165 | 0.002503 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redist... | k':
# For brok, we TAG brok with our instance_id
elt.instance_id = 0
self.broks_internal_raised.append(elt)
return
elif cls_type == 'externalcommand':
logger.debug("Enqueuing an external command '%s'", str(ExternalCommand.__dict__))
self.ex... | al_commands.append(elt)
# Maybe we got a Message from the modules, it's way to ask something
# like from now a full data from a scheduler for example.
elif cls_type == 'message':
# We got a message, great!
logger.debug(str(elt.__dict__))
if elt.get_type() == '... |
bauerj/electrum-server | src/storage.py | Python | mit | 22,202 | 0.003288 | #!/usr/bin/env python
# Copyright(C) 2011-2016 Thomas Voegtlin
#
# 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, m... | .has(c):
self.remove(c)
x = self.indexof(c)
self.s = self.s[0:x] + item + self.s[x:]
self.k |= (1<<ord(c) | )
assert self.k != 0
def remove(self, c):
x = self.indexof(c)
self.k &= ~(1<<ord(c))
self.s = self.s[0:x] + self.s[x+40:]
def get_hash(self, x, parent):
if x:
assert self.k != 0
skip_string = x[len(parent)+1:] if x != '' else ''
x = 0
... |
MayankAgarwal/euler_py | 024/euler024.py | Python | mit | 991 | 0.009082 | def __init_break_indices__(num):
indices = [1]*num
for i in xrange(1, num):
indices[num-1-i] = indices[num-i]*i
return indices
def get_lex_permutation (N, base_string, break_indices):
stringPermutation = []
divident = []
base_string = list(base_string)
divident_prefix = 0
f... | p = ( N - 1 )/break_indices[i]
temp_int = int(temp)
stringPermutation.append(base_string[temp_int])
base_string.pop(temp_int)
divident_prefix += temp_int*break_indices[i]
return ''.join(stringPermutation)
__STRING = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', ... | tation(N, __STRING, __BREAK_INDICES) |
cslarsen/vev | vev/server_py3.py | Python | lgpl-2.1 | 180 | 0.011111 | import http.server
i | mport urllib.parse
class BaseServer(http.server.BaseHTTPRequestHandler):
pass
HTTPServer = http.server.HTTPServer
urlli | b_urlparse = urllib.parse.urlparse
|
ArthurZey/toyproblems | projecteuler/0007_10001st_prime.py | Python | mit | 1,337 | 0.016455 | #!/usr/bin/env python
'''
https://projecteuler.net/problem=7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
'''
import math
def prime(n):
# we start with the knowledge of at least one prime
primes = [2]
# and the next po... | True
# since, by construction, all the primes less than number_to_test have already been found,
# we need only test the possible_divisors in primes up to the square root of number_to_test
# to see if they divide number_to_test before confirming or disproving that number_to_test
# is indeed prime
fo... | ble_divisor >= math.floor(math.sqrt(number_to_test)) + 1:
is_prime = True
break
if number_to_test%possible_divisor == 0:
is_prime = False
break
if is_prime:
primes.append(number_to_test)
# in any event, move on to the next candidate (the next odd nu... |
awacha/cct | cct/core2/instrument/components/datareduction/__init__.py | Python | bsd-3-clause | 115 | 0 | from .datareduction import Data | Reduction
from .datareductionpipeline import DataReductionPipeLine, Proces | singError
|
csirtgadgets/csirtg-mail-py | csirtg_mail/constants.py | Python | lgpl-3.0 | 72 | 0 | import | sys
PYVERSION = 2
if sys.version_info > | (3,):
PYVERSION = 3
|
jamesward-demo/air-quick-fix | AIRQuickFixServer/pyamf/tests/test_sol.py | Python | apache-2.0 | 6,453 | 0.004029 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2007-2008 The PyAMF Project.
# See LICENSE for details.
"""
Tests for Local Shared Object (LSO) Implementation.
@author: U{Nick Joyce<mailto:nick@boxdesign.co.uk>}
@since: 0.1.0
"""
import unittest, os.path, warnings
import pyamf
from pyamf import sol
warnings.simplefilte... | 00\x05hello\x00\x00\x00\x00'
try:
sol.decode(bytes)
except:
raise
self.fail("Error decoding stream")
def test_invalid_header(self):
bytes = '\x00\x00\x00\x00\x00\x15TCSO\x00\x04\x00\x00\x00\x00\x00\x05hello\x00\x00\x00\x00'
self.assertRaises | (pyamf.DecodeError, sol.decode, bytes)
def test_invalid_header_length(self):
bytes = '\x00\xbf\x00\x00\x00\x05TCSO\x00\x04\x00\x00\x00\x00\x00\x05hello\x00\x00\x00\x00'
self.assertRaises(pyamf.DecodeError, sol.decode, bytes)
def test_strict_header_length(self):
bytes = '\x00\xbf\x00\x0... |
nvoron23/TextBlob | textblob/translate.py | Python | mit | 2,924 | 0.00171 | # -*- coding: utf-8 -*-
"""
Translator module that uses the Google Translate API.
Adapted from Terry Yin's google-translate-python.
Language detection added by Steven Loria.
"""
from __future__ import absolute_import
import json
import re
import codecs
from textblob.compat import PY2, request, urlencode
from textblob.... | it/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19')}
def translate(self, source, from_lang=None, to_lang='en', host=None, type_=None):
"""Translate the source text from one | language to another."""
if PY2:
source = source.encode('utf-8')
data = {"client": "p", "ie": "UTF-8", "oe": "UTF-8",
"sl": from_lang, "tl": to_lang, "text": source}
json5 = self._get_json5(self.url, host=host, type_=type_, data=data)
return self._get_translati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.