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 |
|---|---|---|---|---|---|---|---|---|
btrihatmaja/AutoSlony | testing/test_insert.py | Python | mit | 443 | 0.049661 | import time
import psycopg2
import | os
import sys
if __name__ == "__main__":
try:
conn = psycopg2.connect("dbname='master' user='postgres' host='localhost' password='postgres'")
except Exception, e:
print "unable to connect"
sys.exit()
cur = conn.cursor()
for x in xrange(1,1000):
print x
cur.execute("INSERT INTO reptable166 (name) VALU... | t" + str(x),))
conn.commit()
time.sleep(1)
cur.close()
conn.close() |
effigies/mne-python | examples/stats/plot_spatio_temporal_cluster_stats_sensor.py | Python | bsd-3-clause | 5,435 | 0.001472 | """
=====================================================
Spatiotemporal permutation F-test on full sensor data
=====================================================
Tests for differential evoked responses in at least
one condition using a permutation clustering test.
The FieldTrip neighbor templates will be used to d... | ilt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id = {'Aud_L': 1, 'Aud_R': 2, 'Vis_L': 3, 'Vis_R': 4}
tmin = -0.2
tmax = 0.5
# Setup for reading the raw data
raw = mne.io.Raw(raw_fname, preload=True)
raw.filter(1, 30)
events = mne.read_events(event_fname)
########## | #####################################################################
# Read epochs for the channel of interest
picks = mne.pick_types(raw.info, meg='mag', eog=True)
reject = dict(mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=None, reject=rejec... |
live-clones/dolfin-adjoint | tests_dolfin/svd_burgers/svd_burgers.py | Python | lgpl-3.0 | 2,284 | 0.002189 | """
Implementation of Burger's equation with nonlinear solve in each
timestep
"""
from __future__ import print_function
import sys
import numpy
import random
from dolfin import *
from dolfin_adjoint import *
import libadjoint.exceptions
dolfin.parameters["adjoint"]["record_all"] = True
dolfin.parameters["adjoint"]["... | main__":
ic = project(Expression("sin(2*pi*x[0])", degree=1), V)
ic_copy = ic.copy(deepcopy=True)
forward = main(ic, annotate=True)
forward_copy = forward.copy(deepcopy=True)
ic = forward
ic.vector()[:] = ic_copy.vector()
perturbation = ic.copy(deepcopy=True)
vec = perturbation.vecto... | (vec)):
vec[i] = random.random()
info_blue("Computing the TLM the direct way ... ")
param = Control(ic, perturbation=perturbation)
for (tlm, var) in compute_tlm(param, forget=False):
pass
final_tlm = tlm
ndof = V.dim()
info_blue("Computing the TLM the SVD way ... ")
try:
... |
gmnamra/python-image-utils | Tools/widgets.py | Python | mit | 1,326 | 0.012821 | """
wrap up widget const | ruction in functions for easier use, making some
assumptions (e.g., expansion); use extras kw args for width, font/color
"""
from Tkinter import | *
def frame(root, side=TOP, **extras):
widget = Frame(root)
widget.pack(side=side, expand=YES, fill=BOTH)
if extras: widget.config(**extras)
return widget
def label(root, side, text, **extras):
widget = Label(root, text=text, relief=RIDGE) # default config
widget.pa... |
Bit-Monkeys/openfaqs | sessions.py | Python | mit | 1,115 | 0.050224 | from flask import Blueprint, request, session, redirect, render_template
from models import User
from utilities import hash_password
sessions = Blueprint('sessions', __name__, template_folder='templates')
def check_login():
try:
if session['UserName']:
return True
except:
return False
@sessions.route... | (request.form['password'])
find_user = User.query.filter_by(UserName=request.form['username'],
Password=password_hashed).first()
if find_user:
session['UserID'] = find_user.ID
session['UserName' | ] = find_user.UserName
session['Email'] = find_user.Email
return redirect('/')
else:
return render_template('error.html', error="Invalid credentials, please try again.")
else:
return render_template('login.html')
@sessions.route('/logout', methods=['GET'])
def logout():
session.pop('UserI... |
phrawzty/ubunolia | npyscreen_test.py | Python | mpl-2.0 | 5,391 | 0.00204 | #!/usr/bin/env python
# pylint: disable=invalid-name
"""
A text-mode interface to the Ubuntu IRC logs as served by Algolia.
The idea is that this is running against live logs, which explains some of
the design decisions (i.e. lots of querying).
"""
from algoliasearch import algoliasearch
import npyscreen
import json
... | ):
"""Execute a search and hold on to the result."""
results = self.index.search(
query,
dict(self.general_search, **criteria)
)
return results
def set_cache(self, data):
"""npyscreen has no shared state, so we have to cache results in order
... | n('cache', 'w') as outfile:
json.dump(data, outfile)
return 0
def get_cache(self):
"""Retreive the cache."""
with open('cache') as json_data:
cache = json.load(json_data)
return cache
# npyscreen makes pylint cry.
class Formy(npyscreen.ActionForm): # pyli... |
person142/scipy | scipy/stats/tests/test_distributions.py | Python | bsd-3-clause | 168,993 | 0.000657 | """ Test functions for stats module
"""
import warnings
import re
import sys
import pickle
import os
from numpy.testing import (assert_equal, assert_array_equal,
assert_almost_equal, assert_array_almost_equal,
assert_allclose, assert_, assert_warns,
... | (h, expected_h)
b = stats.bernoulli(0.0)
h = b.entropy()
assert_equal(h, 0.0)
b = stats.bernoulli(1.0)
h = b.entropy()
assert_equal(h, 0.0)
class TestBradford(object):
# gh-6216
def test_cdf_ppf(self):
c = 0.1
x = np.logspace(-20, -4)
q... | f test_rvs(self):
vals = stats.nbinom.rvs(10, 0.75, size=(2, 50))
assert_(numpy.all(vals >= 0))
assert_(numpy.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllInteger'])
val = stats.nbinom.rvs(10, 0.75)
assert_(isinstance(val, int))
val = stats.nbi... |
Knotis/djangocassandra | tests/test_columnfamily.py | Python | bsd-3-clause | 6,473 | 0 | import warnings
from random import randint
from unittest import TestCase
from .models import (
ColumnFamilyTestModel,
ColumnFamilyIndexedTestModel,
ClusterPrimaryKeyModel,
ForeignPartitionKeyModel,
DictFieldModel
)
from .util import (
connect_db,
destroy_db,
create_model
)
class Colu... | Model
)
| field_names = [
field.name if field.get_internal_type() != 'AutoField' else None
for field in ColumnFamilyIndexedTestModel._meta.fields
]
field_values = [
'foo',
'bar',
'raw',
'awk',
'lik',
'sik',
... |
young-geng/UVaClient | session_store.py | Python | bsd-2-clause | 1,089 | 0.023875 | import pickle
import requests
from hashlib import md5
import os
user_home = os.getenv('USERPROFILE') or os.getenv('HOME')
se | ssion_file_name = os.path.join(user_home, ".uva_session")
session_checksum_name = os.path.join(user_home, ".uva_session_checksum")
def exist_session_file():
try:
open(session_file_name)
open(session_checksum_name)
except Exception:
return False
return True
de | f is_valid_session_file():
session_file = open(session_file_name).read()
hash_code = open(session_checksum_name).read()
return md5(session_file).hexdigest() == md5(session_file).hexdigest()
def get_session():
if not exist_session_file():
return None
elif not is_valid_session_file():
return None
return pickle... |
DeMille/emailhooks | settings.example.py | Python | mit | 103 | 0 | from emailh | ooks.settings import *
# Add a secret:
SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX | XX'
|
tomerfiliba/ctor | setup.py | Python | mit | 1,389 | 0.037437 | #!/usr/bin/env python
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
HERE = os.path.dirname(__file__)
exec(open(os.path.join(HERE, "ctor", "version.py")).read())
setup(name = "construct3",
version = version_string, #@UndefinedVariable
description = "Ct... | om",
license = "MIT",
url = "",
packages = ["ctor"],
platforms = ["POSIX", "Windows"],
provides = ["ctor"],
#scripts = [
# os.path.join("bin", "ctor"),
#],
entry_points = dict(
console_scripts = ["ctor = ctor.main"]
),
requires = ["six", "plumbum"],
install_req... | escription = open(os.path.join(HERE, "README.rst"), "r").read(),
classifiers = [
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.... |
iulian787/spack | lib/spack/spack/test/cmd/versions.py | Python | lgpl-2.1 | 1,677 | 0 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import pytest
from spack.main import SpackCommand
versions = SpackCommand('versions')
def test_safe_only_versions():
... | ons():
"""Test a package for which remote versions should be available."""
version | s('zlib')
@pytest.mark.network
def test_remote_versions_only():
"""Test a package for which remote versions should be available."""
versions('--remote', 'zlib')
@pytest.mark.network
@pytest.mark.usefixtures('mock_packages')
def test_new_versions_only():
"""Test a package for which new versions should b... |
greghogan/flink | flink-python/pyflink/fn_execution/aggregate.py | Python | apache-2.0 | 22,865 | 0.001924 | ################################################################################
# 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... | fields.append(value)
return Row(*fields)
def extract_data_view_specs_from_accumulator(current_index, accumulator):
# for built | in functions we extract the data view specs from their accumulator
i = -1
extracted_specs = []
for field in accumulator:
i += 1
# TODO: infer the coder from the input types and output type of the built-in functions
if isinstance(field, MapView):
extracted_specs.append(Ma... |
fish-bundles/fb | fish_bundles/__init__.py | Python | mit | 307 | 0 | #!/usr/bin/python
| # -*- coding: utf-8 -*-
# This file is part of fish-bundles.
# https://github.com/fish-bundles/fb
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2014 Bernardo Heynemann heynemann@gmail.com
from fish_bund | les.version import __version__
|
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Ops/PyScripts/lib/ops/survey/networking.py | Python | unlicense | 3,116 | 0.005135 |
from __future__ import print_function
import dsz
import dsz.ui
import ops
import ops.survey.ifconfig
import datetime
import ops.networking.route, ops.networking.connections
import ops.networking.netmap
import ops.project
import ops.survey
import ops.system.systemversion
from optparse import OptionParser
from ops.pprin... | ', 'origin'], header=['Dest. network', 'Mask', 'Gateway', 'Interface', 'Metric', 'Origin'])
ops.survey.print_sub_header('ARP table')
try:
arp_data = ops.networking.connections.get_arp_cache(maxage=datetime.timedelta(seconds=options.maxage))
ops.survey.print_agestring(arp_data.dszobjage)
... | torder=['ip', 'type', 'adapter', 'mac'], header=['IP', 'Type', 'Interface', 'MAC'])
except ops.cmd.OpsCommandException as ex:
ops.error('Error occurred running ARP command')
ops.error(ex)
ops.survey.print_sub_header('Getting the pipelist in the background')
pipe_data = ops.networking.connect... |
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/test/test_audioop.py | Python | gpl-3.0 | 28,719 | 0.002159 | import audioop
import sys
import unittest
def pack(width, data):
return b''.join(v.to_bytes(width, sys.byteorder, signed=True) for v in data)
def unpack(width, data):
return [int.from_bytes(data[i: i + width], sys.byteorder, signed=True)
for i in range(0, len(data), width)]
packs = {w: (lambda *d... | self.assertEqual(audioop.bias(b'', w, bias), b'')
self.assertEqual(audioop.bias(bytearray(), w, bias), b'')
self.assertEqual(audioop.bias(memoryview(b''), w, bias), b'')
self.assertEqual(audioop.bias(datas[1], 1, 1),
b'\x01\x13\x46\xbc\x80\x81\x00')... | self.assertEqual(audioop.bias(datas[1], 1, 0x7fffffff),
b'\xff\x11\x44\xba\x7e\x7f\xfe')
self.assertEqual(audioop.bias(datas[1], 1, -0x80000000),
datas[1])
self.assertEqual(audioop.bias(datas[2], 2, 1),
packs[2](1, 0x1235, 0x4568, -0x... |
thuhangnguyen8894/SmartPlug | src/app/processor/cffi_interfaces/__cffi_jsonBuilder.py | Python | mit | 1,272 | 0.011006 | """
File: __cffi_jsonBuilder.py
=========================
Copyright (c) Tien Nguyen Anh
Modified History
--------------- | -
2017-Jan-05 Created tien.nguyenanh94@gmail.com
"""
import cffi
import os
#LIDT declare
LIDT_ROOT = os.getenv('LIDT_ROOT')
LIDT_LIBS = os.path.sep.join((LIDT_ROOT, 'obj', 'libs'))
JSON_BUILDER_FOR_C_INCLUDES = os.path.sep.join((LIDT_ROOT, 'src',
'app', 'utils', 'jsonHelper', 'cWrapper',... | ibraries
BOOST_ROOT = os.getenv('BOOST_ROOT')
BOOST_INCLUDES = os.path.sep.join((BOOST_ROOT, 'include'))
BOOST_LIB_DIR = os.path.sep.join((BOOST_ROOT, 'lib'))
BOOST_LIBS = ["boost_serialization", 'boost_thread', 'stdc++']
jsonBuilder_cffi = cffi.FFI()
jsonBuilder_cffi.cdef("""
bool buildJsonForC(const char* messag... |
eort/OpenSesame | libqtopensesame/misc/__init__.py | Python | gpl-3.0 | 809 | 0.001236 | #-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software | Foundation, either version 3 of the License, or
(at your option) any later version.
OpenSesame is distributed in the hope that it will be useful,
but WITHOUT AN | Y 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 OpenSesame. If not, see <http://www.gnu.org/licenses/>.
"""
from libopensesame.py3co... |
Kobzol/kaira | ptp/base/paths.py | Python | gpl-3.0 | 1,340 | 0 | #
# Copyright (C) 2012 Stanislav Bohm
#
# This file is part of Kai | ra.
#
# Kaira 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, version 3 of the License, or
# (at your option) any later version.
#
# Kaira is distributed in the hope that it will be useful,
# ... | ULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Kaira. If not, see <http://www.gnu.org/licenses/>.
#
import os
KAIRA_PTP = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
KAIRA_ROOT = os.path... |
AddonScriptorDE/plugin.video.break_com | default.py | Python | gpl-2.0 | 9,189 | 0.027098 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib,urllib2,re,xbmcplugin,xbmcgui,sys,xbmcaddon,socket
socket.setdefaulttimeout(30)
pluginhandle = int(sys.argv[1])
xbox = xbmc.getCondVisibility("System.Platform.xbox")
addon = xbmcaddon.Addon(id='plugin.video.break_com')
translation = addon.getLocalizedString
force... | tin('Container.SetViewMode('+viewMode+')')
def listChannel(url):
content = getUrl(url)
match=re.compile("channelId | : (.+?),", re.DOTALL).findall(content)
id=match[0]
listChannelVideos("http://www.break.com/content/GetContentTimeStreamByChannelIdAndFilterBy?channelId="+id+"&filterBy=videos&pageNum=1")
def listChannelVideos(url):
urlMain=url
content = getUrl(url)
match=re.compile('"MaxRecord... |
CMSS-BCRDB/RDSV1.0 | trove/common/base_wsgi.py | Python | apache-2.0 | 27,841 | 0.000862 | # Copyright 2014 Tesora, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | tg.add_thread(self._run, self.application, self._socket)
@property
def backlog(self):
return self._backlog
@property
def | host(self):
return self._socket.getsockname()[0] if self._socket else self._host
@property
def port(self):
return self._socket.getsockname()[1] if self._socket else self._port
def stop(self):
"""Stop serving this API.
:returns: None
"""
super(Service, self... |
marwoodandrew/superdesk-core | superdesk/factory/sentry.py | Python | agpl-3.0 | 924 | 0.002165 |
import logging
from raven.contrib.flask import Sentry
from raven.contrib.celery import register_signal, register_logger_signal
class SuperdeskSentry():
"""Sentry proxy that will do nothing in case sentry is not configured."""
def __init__(self, app):
if app.config.get('SENTRY_DSN'):
app.... | , **kwargs):
| if self.sentry:
self.sentry.captureMessage(message, **kwargs)
|
UCBerkeleySETI/blimpy | tests/test_calcload.py | Python | bsd-3-clause | 535 | 0.007477 | """
Test the calcload.py utility and function calc_max_load()
"""
from tests.data import voyager_h5, voyager_fil
from blimpy.calcload import cmd_tool, calc_max_load
def test_calcload():
r""" Test the calcload command line tool """
args = [voyager_h5]
cmd_tool(args)
args = ['-v', voyager_fil]
cmd_to... | gs)
def test_calc_max_load():
gb1 = calc_max_load(voyager_h5)
gb2 = calc_max_load(voyager_fi | l)
assert(gb1 == gb2 == 1.0)
if __name__ == "__main__":
test_calcload()
test_calc_max_load()
|
hazelnusse/robot.bicycle | data/physicalparameters/RawData/PeriodMeasurements/Rod/populateTable.py | Python | bsd-2-clause | 1,425 | 0.002807 | import psycopg2
import scipy.io
import os
# Set to true if you want to query tables before adding data:
queryConfigs = False
queryTimeSeries = False
# Create a connection to RoboticBicycle database
conn = psycopg2.connect(database="robot_bicycle_parameters", user="hazelnusse")
cur = conn.cursor()
def insert_statemen... | torsiona | l pendulum data:")
print(type(inst))
print(inst)
conn.rollback()
continue
print(cur.statusmessage)
cur.close()
conn.close()
|
chaosct/GestureAgents | Apps/TestComposition/test_TUIO_Gestures.py | Python | mit | 2,810 | 0.000712 | from GestureAgentsTUIO.Gestures2D.RecognizerTap import RecognizerTap
from recognizer_testing import t_r
events_tap = [
('f', 1, (0.5, 0.5), (
(0, 'in'),
(0.1, 'out'))),
]
class TUIOTapTestCase1(t_r(events_tap, RecognizerTap, ("newTap",), 1)):
pass
events_2tap = [
('f', 1, (0.5, 0.5), (
(... | 0.3, 'out'))),
]
class TUIOTapTestCase4(t_r(events_dtap, RecognizerTap, ("newTap",), 2)):
pass
from GestureAgentsTUIO.Gestures2D.RecognizerDoubleTap import RecognizerDoubleTap
class TUIODoubleTapTestCase1(t_r(events_dtap,
RecognizerDoubleTap,
(... | p,
("newDoubleTap",), 0)):
pass
events_nodtap = [
('f', 1, (0.5, 0.5), (
(0, 'in'),
(0.1, 'out'))),
('f', 2, (0.5, 0.5), (
(0.8, 'in'),
(0.9, 'out'))),
]
class TUIODoubleTapTestCase3(t_r(events_nodtap,
RecognizerDouble... |
olovwikberg/OWSyncAPI | api_app/views.py | Python | gpl-2.0 | 1,313 | 0.001523 | import datetime
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from OWSyncAPIApp.models import Artist, Country
from api_app.serializers import ArtistSerializer, CountrySerializer
# class UserViewSet(viewsets.ModelViewSet):... | ueryset
class ArtistViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows Artists to be viewed or edited.
"""
queryset = Artist.objects.all()
serializer_class = ArtistSerializer
def get_queryset(self):
# Get all articles
queryset = Artist.objects.all()
# Filter ... | date is not None:
try:
queryset = queryset.filter(updated_at__gt=date)
except:
# Exception, return empty
queryset = Artist.objects.none()
return queryset
|
seppovic/check_mk-plugins | df_btrfs/web/plugins/perfometer/df_btrfs.py | Python | gpl-2.0 | 59 | 0 |
perfometers[' | check_mk-df_btrfs' | ] = perfometer_check_mk_df
|
SciTools/iris | lib/iris/tests/unit/common/metadata/__init__.py | Python | lgpl-3.0 | 255 | 0 | # Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL | license.
# See COPYING and COPYING.LESSER in the root of | the repository for full
# licensing details.
"""Unit tests for the :mod:`iris.common.metadata` package."""
|
useEvil/flickr-photo-sync | flickrphotosync/photosync/management/commands/copy.py | Python | mit | 4,213 | 0.00356 | import os, errno, sys, pytz, urllib, shutil
import re as regex
import datetime as date
from PIL import Image
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from django.conf import settings
from photosync.models import Phot... | )
def handle(self, *args, **options):
set_options(self, options, ['slug', 'directory', 'folder'])
try:
self.settings = CopySettings.objects.get(slug=self.slug) |
self.set_config()
except CopySettings.DoesNotExist:
raise CommandError('Settings for "{0}" does not exist'.format(self.slug))
try:
self.get_directory_listing(self.card)
self.settings.save()
self.stdout.write('Successfully Copied {0} Photos fr... |
hanxi/mobiletouch_pyhttp | http_server.py | Python | mit | 2,763 | 0.016844 | #!/usr/bin/python
# coding: UTF-8
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from autopy import key, mouse
import urllib
class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
query = urllib.splitquery(self.path)
action = query[0]
queryParams = {}
if ... | wfile.write(content)
# end MyRequestHandler
# 打开主页
def index(queryParams,content_type):
f = open('index.html')
content = f.read()
f.close()
c | ontent_type = "text/html"
return content_type,content
MOVE_LEFT = 0
MOVE_RIGHT = 1
MOVE_UP = 2
MOVE_DOWN = 3
# 双指滑动
def doublemove(queryParams,content_type):
content = "OK"
if queryParams.has_key('direction') and queryParams.has_key('distance'):
direction = int(queryParams['direction'])
... |
cosmiclattes/wikiwomen | editCount/update_json.py | Python | gpl-2.0 | 3,812 | 0.012854 | #!/usr/bin/python
import urllib2
import urllib
import json
import time
import os
rootPath = os.getcwd() + "/wikiWomensStats/"
dataPath = rootPath + 'data.json'
fullDataPath = '/home/ubuntu/wikiWomen_data/data.json'
headers = { 'User-Agent' : 'Womens edit a thon India' }
cmtitle = "Category:Articles_created_or_expa... | ['cmcontinue']
return articleList
def getEdits(title,pageId):
articleData = {
'action' : 'query',
'prop' : 'revisions',
'format' : 'json',
'rvprop' : 'timestamp|user|comment',
'rvstart' : eventStartTimestamp,
... | }
edits = []
while True:
articleData['titles'] = title
req = urllib2.Request(apiUrl, headers=headers, data = urllib.urlencode(articleData))
response = json.loads(urllib2.urlopen(req).read())
print 'url', urllib.urlencode(articleData)
print 'response', response
f... |
akuendig/RxPython | rx/linq/throttle.py | Python | mit | 4,946 | 0.013344 | from rx.disposable import CompositeDisposable, Disposable, SerialDisposable, SingleAssignmentDisposable
from rx.observable import Producer
from rx.observer import Observer
import rx.linq.sink
from threading import RLock
class ThrottleTime(Producer):
def __init__(self, source, dueTime, scheduler):
self.source = ... | rceId
d = SingleAssignmentDisposable()
self.propagatorDisposable.disposable = d
d.disposable = self.parent.scheduler.scheduleWithRelativeAndState(
currentId,
self.parent.dueTime,
self.propagate
)
def propagate(self, scheduler, currentId):
with self.gate:
... | value)
self.hasValue = False
return Disposable.empty()
def onError(self, exception):
self.propagatorDisposable.dispose()
with self.gate:
self.observer.onError(exception)
self.dispose()
self.hasValue = False
self.resourceId += 1
def onCompleted(self)... |
BackupGGCode/qr-code-plugins | blender/add_mesh_qrcode.py | Python | mit | 17,496 | 0.009888 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# QR Code Generator plug-in for Blender 2.5.7+
# plug-in version: 1.1b
# provided by Esponce team
# http://www.esponce.com/
# ***** BEGIN MIT LICENSE BLOCK *****
#
# Copyright (C) 2013 Esponce d.o.o.
#
# Permission is hereby granted, free of charge, to any pe... | *************
# Creates a new mesh.
#**************************************************************************************** | **
def create_mesh_object(context, verts, edges, faces, name):
# Create new mesh
mesh = bpy.data.meshes.new(name)
# Make a mesh from a list of verts/edges/faces.
mesh.from_pydata(verts, edges, faces)
# Remove doubles
#bpy.ops.mesh.remove_doubles(threshold=0.0001, use_unselected=... |
catmaid/CATMAID | scripts/experiment/remove_concepts_after.py | Python | gpl-3.0 | 3,982 | 0.007785 | # -*- coding: utf-8 -*-
# An entirely untested jython script to delete all the concepts in the
# CATMAID database for a particular project.
#
# Mark Longair 2010
#
# flake8: noqa
import os, re, sys, ij
from jarray import array
from java.sql import DriverManager, Connection, SQLException, Types
# Set up the JDBC con... | oject_id = int(gd.getNextNumber())
s = c.createStatement()
rs = s.executeQuery('SELECT id FROM concept WHERE project_id = %d ORDER BY id LIMIT 1' % (project_id,))
rs.next()
first_id = rs.getLong(1)
rs.close()
s.close()
gd = ij.gui.GenericDialog('Remove CATMAID Concepts')
gd.addNumericField("Last conce... | d.getNextNumber())
run(project_id, last_untouched_id)
ij.IJ.showMessage("Finished removing concepts.")
c.close()
|
teeple/pns_server | work/install/Python-2.7.4/PCbuild/build_ssl.py | Python | gpl-2.0 | 8,447 | 0.00296 | from __future__ import with_statement, print_function
# Script for building the _ssl and _hashlib modules for Windows.
# Uses Perl to setup the OpenSSL environment correctly
# and build OpenSSL, then invokes a simple nmake session
# for the actual _ssl.pyd and _hashlib.pyd DLLs.
# THEORETICALLY, you can:
# * Unpack th... | pt)
if debug:
print("OpenSSL debug builds aren't supported.")
| #if arch=="x86" and debug:
# # the do_masm script in openssl doesn't generate a debug
# # build makefile so we generate it here:
# os.system("perl util\mk1mf.pl debug "+configure+" >"+makefile)
if arch == "amd64":
create_makefile64(ma... |
rguillebert/CythonCTypesBackend | Cython/Utils.py | Python | apache-2.0 | 7,177 | 0.004041 | #
# Cython -- Things that don't belong
# anywhere else in particular
#
import os, sys, re, codecs
modification_time = os.path.getmtime
def replace_suffix(path, newsuf):
base, _ = os.path.splitext(path)
return base + newsuf
def open_new_file(path):
if os.path.exists(path):
# Make sur... | ion ('0136')
value = i | nt(value, 8)
else:
value = int(value, 0)
return value
def long_literal(value):
if isinstance(value, basestring):
value = str_to_number(value)
return not -2**31 <= value < 2**31
# all() and any() are new in 2.5
try:
# Make sure to bind them on the module, as they will be accessed as... |
Triv90/Heat | heat/openstack/common/notifier/api.py | Python | apache-2.0 | 5,770 | 0 | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache | License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is... | "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.
import uuid
from oslo.config import cfg
from heat.openstack.common import context
from heat.openstack.common.gettex... |
0hoo/ecogwiki | representations.py | Python | gpl-3.0 | 4,336 | 0.003459 | # coding=utf-8
import os
import re
import main
import json
import jinja2
from google.appengine.api import users
from models import WikiPage, UserPreferences, get_cur_user
class Representation(object):
def __init__(self, content, content_type):
self._content = content
self._content_type = content_t... | plate_path
def respond(self, httpres, head):
html = template(self._httpreq, self._template_path, self._content)
self._respond(httpres, head, self._content_type, html)
class JsonRepresentation(Representation):
def __init__(self, content):
super(JsonRepresentation, self).__init__(conten... | tion(Representation):
def __init__(self, rescode):
super(EmptyRepresentation, self).__init__(None, None)
self._rescode = rescode
def respond(self, httpres, head):
httpres.status = 400
JINJA = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extens... |
bitmovin/bitcodin-python | bitcodin/test/input/testcase_create_input_async.py | Python | unlicense | 1,634 | 0.000612 | from time import sleep
import unittest
from bitcodin import create_input, get_input, get_async_input_status
from bitcodin import delete_input
from bitcodin import S3Input
from bitcodin.test.settings import s3_input_config
from bitcodin.test.bitcodin_test_case import BitcodinTestCase
class CreateS3InputTestCase(Bitco... | f tear | Down(self):
delete_input(self.input.input_id)
super(CreateS3InputTestCase, self).tearDown()
if __name__ == '__main__':
unittest.main()
|
oliveirarodolfo/ipnm | ipnm/format_converter.py | Python | mit | 7,923 | 0.000379 | #
"""
"""
import os
import json
try:
import vtk
has_vtk = True
except ImportError:
has_vtk = False
def convert(data, in_format, out_format='json'):
"""
"""
if in_format == 'json':
pnm = json_to_json(data)
elif in_format == 'dat':
pnm = imperial_to_json(data)
elif in... | xt='dat'):
"""Read PNM models from *_node1, *_node2, *_link1 and *_link2 files
"""
d = {'fprefix': fprefix, 'ext': ext}
code = '{fprefix}{}.{ext}'
npores, size, nodes, coord, pconn, tconn, iflag, oflag = read_node1(
code.format('_node1', **d))
povol, clvol, inrad, | shape = read_node2(code.format('_node2', **d))
nthroats, pind0, pind1, tshap, trad, ttlen = read_link1(
code.format('_link1', **d))
plen0, plen1, tlen, ncvol, clvol = read_link2(code.format('_link2', **d))
pnm = dict({'pores': [], 'throats': [], })
for i in xrange(npores):
pore = {
... |
ejeschke/obsplan | obsplan/entity.py | Python | bsd-3-clause | 23,665 | 0.00224 | #
# entity.py -- various entities used for observation planning
#
# Eric Jeschke (eric@naoj.org)
#
# Some code based on "Observer" module by Daniel Magee
# Copyright (c) 2008 UCO/Lick Observatory.
#
from datetime import datetime
import math
# local imports
from obsplan import misc
# 3rd party imports
import ephem
... | def import_record(self, rec):
code = rec.code.strip()
self.name = rec.name
self.ra = rec.ra
self.dec = rec.dec
# transform equinox, e.g. "J2000" -> 2000
eq = rec.eq
| if isinstance(eq, str):
eq = eq.upper()
if eq[0] in ('B', 'J'):
eq = eq[1:]
eq = float(eq)
eq = int(eq)
self.equinox = eq
self._recalc_body()
return code
def calc(self, observer, time_start):
return CalculationRes... |
romain-intel/bcc | examples/networking/simple_tc.py | Python | apache-2.0 | 846 | 0.001182 | #!/usr/bin/python
# Copyright (c) PLUMgrid, I | nc.
# Licensed under the Apache License, Version 2.0 (the "License")
from bcc import BPF
from pyroute2 import IPRoute
ipr = IPRoute()
text = """
int hello(struct __sk_buff *skb) {
return 1;
}
"""
try:
b = BPF(text=text, debug=0)
fn = b.load_func("hello", BPF.SCHED_CLS)
ipr.link_create(ifname="t1a", ki... | ilter", "bpf", idx, ":1", fd=fn.fd,
name=fn.name, parent="ffff:", action="ok", classid=1)
ipr.tc("add", "sfq", idx, "1:")
ipr.tc("add-filter", "bpf", idx, ":1", fd=fn.fd,
name=fn.name, parent="1:", action="ok", classid=1)
finally:
if "idx" in locals(): ipr.link_remove(idx)
print("BPF t... |
scheib/chromium | third_party/protobuf/python/google/protobuf/internal/enum_type_wrapper.py | Python | bsd-3-clause | 4,495 | 0.004004 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | th the same name as the enum they wrap
on proto classes. For usage, see:
reflection_test.py
"""
__author__ = 'rabsatt@google.com (Kevin Rabsatt)'
import six
class EnumTypeWrapper(object):
"""A utility for finding the names of enum values."""
DESCRIPTOR = None
def __init__(self, enum_type):
"""Inits E... | r): # pylint: disable=invalid-name
"""Returns a string containing the name of an enum value."""
try:
return self._enum_type.values_by_number[number].name
except KeyError:
pass # fall out to break exception chaining
if not isinstance(number, six.integer_types):
raise TypeError(
... |
kilon/sverchok | node_scripts/templates/zeffii/vert_edges_kdtree_range.py | Python | gpl-3.0 | 1,409 | 0 | def sv_main(num_verts=20, radius=5, num_rings=3, rotation=0.3, mdist=0.3):
# in boilerplate, could be less verbose
in_sockets = [
['s', 'num_verts', num_verts],
['s', 'radius', radius],
['s', 'num_rings', num_rings],
['s', 'rotation', rotation],
['s', 'distance', mdist... | ]
# create vertices
| for j in range(num_rings):
radial_offset = rotation * j
for i in range(num_verts):
theta = (angle * i) + radial_offset
tr = r + (0.5 * j)
v.append([cos(theta) * tr, sin(theta) * tr, 0])
# make kd tree
# documentation/blender_python_api_2_70_release/mathutils... |
learningequality/ricecooker | tests/test_settings.py | Python | mit | 2,495 | 0.006012 | import sys
from mock import patch
from ricecooker import chefs
settings = {"generate-missing-thumbnails": True, "compress-videos": True}
def test_settings_unset_default():
chef = chefs.SushiChef()
for setting in settings:
assert chef.get_setting(setting) is None
assert chef.get_setting(se... | for setting in settings:
value = settings[setting]
chef.SETTINGS[setting] = value
assert chef.get_setting(setting) == value
assert chef.get_setting(setting, default=None) == value
def test_cli_args_override_settings():
"""
For settings that can be controlled via the command li... | "sushichef.py", "--compress", "--thumbnails", "--token", "12345"]
with patch.object(sys, "argv", test_argv):
chef = chefs.SushiChef()
chef.SETTINGS["generate-missing-thumbnails"] = False
chef.SETTINGS["compress-videos"] = False
assert chef.get_setting("generate-missing-thumbnails")... |
aquileia/wesnoth | data/tools/campaign2wiki.py | Python | gpl-2.0 | 2,326 | 0.003879 | #!/usr/bin/python3
# encoding: utf-8
"""
A script that autogenerates some information about campaigns for the
CampaignInformation wiki page. The script is a WIP.
"""
import os.path, sys
import argparse
import wesnoth.wmlparser3 as wmlparser3
class Campaign:
"""
A class for a specific campaign.
"""
... | self.parser.get_text_val("name")
self.id = self.parser.get_text_val("id")
self.description = self.parser.get_text_val("description")
| self.levels = len(self.parser.get_all(tag="difficulty"))
self.credits_link = "http://wiki.wesnoth.org/Credits#" + self.id
self.units_link = "http://units.wesnoth.org/trunk/mainline/en_US/%s.html" % self.id
def wiki_output(campaign):
"""
Takes a campaign instance and outputs information ... |
sestrella/ansible | lib/ansible/modules/cloud/google/gcp_pubsub_subscription_info.py | Python | gpl-3.0 | 11,806 | 0.00576 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | , the Push endpoint URL will be used.'
returned: success
type: str
pushEndpoint:
description:
- A URL locating the endpoint to which messages should be pushed.
- For example, a Webhook endpoint might use "U(https://example.com/push").
returned:... | tes that can be used
to control different aspects of the message delivery.
- The currently supported attribute is x-goog-version, which you can use
to change the format of the pushed message. This attribute indicates the
version of the data expected by the endpoint. This co... |
varunarya10/rally | tests/unit/deploy/engines/test_devstack.py | Python | apache-2.0 | 4,325 | 0 | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | stackEngineTestCase(test.TestCase):
def setUp(self):
super(DevstackEngineTestCase, self).setUp()
self.deployment = {
"uuid": "de641026-dbe3-4abe-844a-ffef930a600a",
"config": SAMPLE_CONFIG,
}
self.engine = devstack.DevstackEngi | ne(self.deployment)
def test_invalid_config(self):
self.deployment = SAMPLE_CONFIG.copy()
self.deployment["config"] = {"type": 42}
engine = devstack.DevstackEngine(self.deployment)
self.assertRaises(jsonschema.ValidationError,
engine.validate)
def test... |
wgwoods/python-bugzilla | tests/test_api_authfiles.py | Python | gpl-2.0 | 6,887 | 0.000581 | #
# Copyright Red Hat, Inc. 2012
#
# This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
#
"""
Test miscellaneous API bits
"""
import os
import shutil
import tempfile
import pytest
import requests
import bugzilla
import tests
import tests.mockbackend
import tests.... | one
bzapi.password = None
bzapi.api_key = None
bzapi.cert = None
bzapi.url = "bugzilla.redhat.com"
bzapi.readconfig(temp.name)
_check(None, None, None, None)
# Test confipath overwrite
assert [temp.name] == bzapi.configpath
del(bzapi.configpath)
assert [] == bzapi.configpath
... | __) + "/data/cookies-moz.txt"
inputbz = tests.mockbackend.make_bz(
bz_kwargs={"use_creds": True, "cookiefile": cookiefile})
cookiecache = inputbz._cookiecache # pylint: disable=protected-access
return cookiecache.get_cookiejar()
def test_authfiles_saving(monkeypatch):
tmpdir = tempfile.mkdtem... |
fvantienen/dji_rev | tools/xor.py | Python | gpl-3.0 | 942 | 0.014862 | #!/usr/bin/env python2
######################
# Powershell XOR 2 Files
# xor.py
# Jul 2016
# Website: http://www.Megabeets.net
# Use: ./xor.py file1 file2 outputFile
# Example: ./xor.py C:\a.txt C:\b.txt C:\result.txt
#######################
import sys
# Read two files as byte arrays
file1_ | b = bytearray(open(sys.argv[1], 'rb').rea | d())
file2_b = bytearray(open(sys.argv[2], 'rb').read())
# Set the length to be the smaller one
size = len(file1_b) if file1_b < file2_b else len(file2_b)
xord_byte_array = bytearray(size)
# XOR between the files
byte_cnt = [0] * 256
for i in range(size):
xord_byte_array[i] = file1_b[i] ^ file2_b[i]
byte_cnt[file... |
mozilla/mwc | vendor-local/packages/requests/requests/packages/urllib3/response.py | Python | mpl-2.0 | 6,422 | 0.001246 | # urllib3/response.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import gzip
import logging
import zlib
from io import BytesIO
from .exceptions import HTTPEr... | elf._fp.read(amt)
try:
if decode_content and decoder:
data = decoder(data)
except IOError:
raise HTTPError("Received response with content-encoding: %s, but "
"failed | to decode it." % content_encoding)
if cache_content:
self._body = data
return data
finally:
if self._original_response and self._original_response.isclosed():
self.release_conn()
@classmethod
def from_httplib(ResponseCls, r, **resp... |
TomTranter/OpenPNM | openpnm/io/MARock.py | Python | mit | 5,688 | 0 | import os as os
import numpy as np
import scipy as sp
from pathlib import Path
from openpnm.utils import logging, Project
from openpnm.network import GenericNetwork
from openpnm.io import GenericIO
from openpnm.topotools import trim
logger = logging.getLogger(__name__)
class MARock(GenericIO):
r"""
3DMA-Rock ... | .
"""
@classmethod
def load(cls, path, voxel_size=1, project=None):
r"""
Load data from a 3DMA-Rock extracted network. This format consists of
two files: 'rockname.np2th' and 'rockname.th2pn'. They should be
stored together in a folder which is referred to by the path argu... | d therefore not human readable.
Parameters
----------
path : string
The location of the 'np2th' and 'th2np' files. This can be an
absolute path or relative to the current working directory.
network : OpenPNM Network Object
If an Network object is rec... |
alexAubin/hovercraft | hovercraft/tests/test_template.py | Python | mit | 4,447 | 0.001349 | import os
import unittest
from lxml import etree
from hovercraft.template import (Template, CSS_RESOURCE, JS_RESOURCE,
JS_POSITION_BODY, JS_POSITION_HEADER)
TEST_DATA = os.path.join(os.path.split(__file__)[0], 'test_data')
class TemplateInfoTests(unittest.TestCase):
"""Tests tha... | TemplateInfoNodeTests(unittest.TestCase):
"""Tests that template information is correctly made into an xml nodes"""
def test_minimal_template(self):
template_info = Template(os.path.join(TEST_DATA, 'minimal'))
node = template_info.xml_node()
self.assertEqual(etree.tostring(node), (
... | einfo><header/><body>'
b'<js src="js/impress.js"/><js src="js/hovercraft-minimal.js"/>'
b'</body></templateinfo>'))
def test_maximal_template(self):
template_info = Template(os.path.join(TEST_DATA, 'maximal'))
node = template_info.xml_node()
self.assertEqual(etree.t... |
dannyboi104/SickRage | sickbeard/search.py | Python | gpl-3.0 | 28,682 | 0.004184 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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,... | bestQualities:
logger.log(cur_result.name + " is a quality we know we don't want, rejecting it", logger.DEBUG)
continue
if show.rls_ignore_words and show_name_helpers.containsAtLeastOneWord(cur_result.name, cur_result.show.rls_ignore_words):
logger.log(u"Ignoring " + cur_re... | t.name + " based on ignored words filter: " + show.rls_ignore_words,
logger.INFO)
continue
if show.rls_require_words and not show_name_helpers.containsAtLeastOneWord(cur_result.name, cur_result.show.rls_require_words):
logger.log(u"Ignoring " + cur_result.name + "... |
mitsuhiko/flask-website | flask_website/views/community.py | Python | bsd-3-clause | 824 | 0 | from flask import Blueprint, render_template, jsonify
from flask_website.utils import request_wants_json
from flask_website.listings.projects import projects
mod = Blueprint('community', __name__, url_prefix='/community')
@mod.route('/')
def index():
return render_template('community/index.html')
@mod.route('/... | badges.html')
@mod.route('/poweredby/')
def poweredby():
if request_wants_json():
return jsonify((k, [p.to_json() for p in v])
for k, v in projects.iteritems())
return render_template('community/poweredby | .html', projects=projects)
@mod.route('/logos/')
def logos():
return render_template('community/logos.html')
|
ctag/cpe453 | JMRI/jython/AD4OnOff.py | Python | gpl-2.0 | 1,207 | 0.009114 | # Sample script to show put a button on the screen that
# will enable or disable local control of AD4 accessory decoders.
#
#
# This script has been superceded by the "Lock" capability in
# JMRI 1.9.3 and later. You can directly request that JMRI lock/unlock
# a turnout via the Turnout Table, Routes and Logi
#
# Auth... | , copyright 2007
# Part of the JMRI distribution
#
# The next line is maintained by CVS, please don't change it
# $Revision: 27263 $
import java
import javax.swing
# create the button, and add an action routine to it
b = javax.swing.JCheckBox("Local Control Disabled")
def whenMyButtonClicked(event) :
if (even... | ().isSelected()) :
programmer = programmers.getAddressedProgrammer(True, 2041)
programmer.writeCV(514, 0, None)
else :
programmer = programmers.getAddressedProgrammer(True, 2041)
programmer.writeCV(514, 85, None)
return
b.actionPerformed = whenMyButton... |
sbrichards/rockstor-core | src/rockstor/storageadmin/views/oauth_app.py | Python | gpl-3.0 | 3,028 | 0.000991 | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... | est):
name = request.data['name']
username = request.user.username
if (OauthApp.objects.filter(name=name).exists()):
e_msg = ('application with name: %s already exists.' % name)
handle_exception(Exception(e_msg), request)
try:
... | .get(username=username)
except:
e_msg = ('User with name: %s does not exist' % username)
handle_exception(Exception(e_msg), request)
client_type = OauthApplication.CLIENT_CONFIDENTIAL
auth_grant_type = OauthApplication.GRANT_CLIENT_CREDENTIALS
... |
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/ctypes/__init__.py | Python | gpl-3.0 | 16,848 | 0.005817 | """create and manipulate C data types in Python"""
import os as _os, sys as _sys
__version__ = "1.1.0"
from _ctypes import Union, Structure, Array
from _ctypes import _Pointer
from _ctypes import CFuncPtr as _CFuncPtr
from _ctypes import __version__ as _ctypes_version
from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
from... | mport POINTER, pointer, _pointer_type_cache
class c_wchar_p(_SimpleCData):
_type_ = "Z"
def __repr__(self):
| return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
class c_wchar(_SimpleCData):
_type_ = "u"
def _reset_cache():
_pointer_type_cache.clear()
_c_functype_cache.clear()
if _os.name in ("nt", "ce"):
_win_functype_cache.clear()
# _SimpleCData.c_wchar_p_from_param
... |
tongxindao/shiyanlou | shiyanlou_cs885/pyflk/dbconnector/__init__.py | Python | apache-2.0 | 5,573 | 0.004127 | import pymysql
class DBResult:
'''
database return result object
'''
# execute success or fail
| suc = False
# execute result, usually is querry set, is a list nesting dict structure
result = None
# error information
error = None
# effect row number
rows = None
def index_of(self, index):
''' return appoint location a data in result set '''
# decide if or not execut... | ger, if yes final decide index whether or not in effective range
if self.suc and isinstance(index, int) and self.rows > index >= -self.rows:
# condition establish, return subscript of result
return self.result[index]
return None
def get_first(self):
''' return firs... |
pazzo83/JQuantLib | docs/source/conf.py | Python | mit | 9,399 | 0.006064 | # -*- coding: utf-8 -*-
#
# QuantLib.jl documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 31 00:05:58 2016.
#
# 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.
#... | r places throughout the
# built documents.
#
# The short X.Y version.
version = u'0.0.1'
# The full version, including alpha/beta/rc tags.
release = u'0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translati... | o 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.
# This patterns also effect to html_static_path and ... |
wooga/airflow | airflow/migrations/versions/3c20cacc0044_add_dagrun_run_type.py | Python | apache-2.0 | 3,183 | 0.000943 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | n(UtcDateTime)
_state = Column('state', String(50), default=State.RUNNING)
| run_id = Column(String(ID_LEN))
external_trigger = Column(Boolean, default=True)
run_type = Column(String(50), nullable=False)
conf = Column(PickleType)
def upgrade():
"""Apply Add DagRun run_type"""
run_type_col_type = sa.String(length=50)
# Add nullable column
with op.batch_alter_table(... |
heroku/python-salesforce-client | tests/rest/test_base.py | Python | mit | 386 | 0 | import operator
from betamax import Betamax
from salesforce.rest.base import SalesforceRestClientBase
cassette_name = 'rest.base'
client_class = SalesforceRestClientBase
def test_versions(client):
version | s = client.versions()
assert isinstance(versions, list)
keys = reduce(operator.or_, [set(v.keys()) for v in versions])
assert keys == {'label', 'url', 'version'} | |
lycantropos/cetus | tests/data_access_tests/test_reading.py | Python | mit | 7,314 | 0.000273 | from asyncio import AbstractEventLoop
from typing import List
import pytest
from cetus.data_access import (get_connection,
fetch,
group_wise_fetch,
fetch_records_count,
group_wise_fetch_records_c... | target_column_name=table_primary_key,
groupings=table_non_unique_columns_names,
is_maximum=is_group_wise_maximum,
is_mysql=is_mysql,
conn | ection=connection)
assert records_count == 1
@pytest.mark.asyncio
async def test_fetch(
table: Table,
table_name: str,
table_columns_names: List[str],
table_records: List[RecordType],
is_mysql: bool,
db_uri: URL,
event_loop: AbstractEventLoop) -> None:
... |
pjimmybrcd/campus_ztp_nps | actions/lib/Session.py | Python | apache-2.0 | 12,262 | 0.003588 | import sys
import logging
import pexpect
class Session(object):
NO_SESSION = 1
SESSION_AVAILABLE = 2
PRIVILEDGE_MODE = 3
CONFIGURATION_MODE = 4
def __init__(self, hostname, username='', password='', enable_username='', enable_ | password=''):
''' Sets up configuration to be transfered '''
self.hostname = hostname
self.username = username
self.password = password
self.enable_username = enable_username
self.enable_password = enable_password
| self.session = None
self.session_state = Session.NO_SESSION
self.session_lf = ''
self.session_prompt = ''
self._login_status = False
self._enable_status = False
def login(self):
''' Attempt to Login to Device '''
if(self._login_status):
return Tru... |
morgan-del/urlpathlib | tests/test_dispatch.py | Python | bsd-2-clause | 657 | 0 | import pytest
import urllib.error
from urlpathlib import UrlPath
def test_scheme():
# does not raise NotImplementedError
UrlPath('/dev/null').touch()
def test_scheme_not_supported():
with pytest.raises(NotImple | mentedError):
UrlPath('http:///tmp/test').touch()
def test_scheme_not_listed():
with pytest.raises(NotImplementedError):
UrlPath('test:///tmp/test').touch()
def test_file_additional():
assert UrlPath('.').resolve() == UrlPath.cwd()
def test_scheme_alias():
# does not raise NotImplem... | UrlPath('https://localhost/test').exists()
|
kivhift/pu | src/tests/run-em.py | Python | mit | 101 | 0 | #!/usr/bin/python
#
# Copyright (c) 2012 Joshua Hughes <kivhift@gmail.com>
#
import nose
no | se.main()
| |
red-hat-storage/rhcephcompose | rhcephcompose/gather/__init__.py | Python | mit | 596 | 0 | import requests
def cache(builds, cache_ | dir, ssl_verify=True):
"""
Download all the builds' artifa | cts into our cache directory.
:param set builds: set of Build objects
:param str cache_dir: path to a destination directory
:param ssl_verify: verify HTTPS connection or not (default: True)
"""
session = requests.Session()
session.verify = ssl_verify
for build in builds:
for binary ... |
SusannaMaria/beets | beets/autotag/mb.py | Python | mit | 18,620 | 0.000054 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... | erb, query, tb=None):
self.query = query
if isinstance(reason, musicbrainzngs.WebServiceError):
reason = u'MusicBrainz not reachable'
super(MusicBrainzAPIError, self).__init__(reason, verb, tb)
def get_message(self):
return u'{0} in {1} with query {2}'.format(
... | ._reasonstr(), self.verb, repr(self.query)
)
log = logging.getLogger('beets')
RELEASE_INCLUDES = ['artists', 'media', 'recordings', 'release-groups',
'labels', 'artist-credits', 'aliases',
'recording-level-rels', 'work-rels',
'work-level-rels', 'arti... |
TimVanMourik/OpenFmriAnalysis | GIRAFFE/code/workflow.py | Python | gpl-3.0 | 4,618 | 0.010178 | #This is a Nipype generator. Warning, here be dragons.
#!/usr/bin/env python
import sys
import nipype
import | nipype.pipeline as pe
#Create a workflow to connect all those nodes
analysisflow = nipype.Workflow('MyWorkflow')
analysisflow.connect(tvm_design_empty, "o_DesignMatrix", tvm_design_stimulus, "i_DesignMatrix")
analysisflow.connect(tvm_design_stimulu... | _DesignMatrix")
analysisflow.connect(tvm_design_highpassFilter, "o_DesignMatrix", tvm_design_motionRegression, "i_DesignMatrix")
analysisflow.connect(tvm_design_motionRegression, "o_DesignMatrix", tvm_design_retroicor, "i_DesignMatrix")
analysisflow.connect(tvm_design_retroicor, "o_DesignMatrix", tvm_design_retroico... |
markgw/pimlico | src/python/pimlico/old_datatypes/modules/opennlp/coreference_pipeline/execute.py | Python | gpl-3.0 | 3,946 | 0.003548 | # This file is part of Pimlico
# Copyright (C) 2020 Mark Granroth-Wilding
# Licensed under the GNU LGPL v3.0 - https://www.gnu.org/licenses/lgpl-3.0.en.html
from builtins import str
from builtins import zip
from pimlico.core.external.java import Py4JInterface, JavaProcessError
from pimlico.core.modules.execute import ... | enized":
outputs.append([sentence.split() for sentence in get_field(coref_result, "tokenizedSentences")])
elif output_name == "pos":
tokens = [sentence.split() for sentence in get_field(coref_result, "tokenizedSentences")]
pos_tags = [sentence.split() for sentence in get_fiel... | ref_result.getParseTrees()))
return tuple(outputs)
def start_interface(info):
"""
Start up a Py4J interface to a new JVM.
"""
# Start a parser process running in the background via Py4J
gateway_args=[
info.sentence_model_path, info.token_model_path, info.pos_model_path, info.parse_mod... |
diogocs1/comps | web/addons/payment_paypal/models/__init__.py | Python | apache-2.0 | 58 | 0 | # -*- cod | ing: utf-8 -*-
import pa | ypal
import res_company
|
rindeal/gentoo-overlay | _tools/bump-jetbrains-pkgs.py | Python | gpl-2.0 | 6,258 | 0.004474 | #!/usr/bin/env python3
import os
import traceback
import glob
from multiprocessing import Pool, Process, Lock
import subprocess
import requests
import portage
from terminaltables import AsciiTable
DEBUG=0
if 'DEBUG' in os.environ:
DEBUG = os.environ['DEBUG']
PORTDIR_OVERLAY=os.path.realpath(os.path.dirname(os.... | rem_ver = remote_versions[code][slot]
if | portage.vercmp(loc_ver, rem_ver) < 0:
new_updates.append({
'cat': cat,
'pn': pn,
'loc_slot': slot,
'loc_ver': loc_ver,
'rem_slot': slot,
'rem_ver': rem_ver
})
# now lo... |
dpgoetz/swift | test/unit/proxy/controllers/test_obj.py | Python | apache-2.0 | 33,082 | 0 | #!/usr/bin/env python
# Copyright (c) 2010-2012 OpenStack 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | erver.ObjectController
def handle_request(self, req):
with mock.patch('swift.proxy.server.ObjectController',
new=self.object_controller):
return super(PatchedObjControllerApp, self).handle_request(req)
@patch_policies([Stora | gePolicy(0, 'zero', True,
object_ring=FakeRing(max_more_nodes=9))])
class TestObjControllerWriteAffinity(unittest.TestCase):
def setUp(self):
self.app = proxy_server.Application(
None, FakeMemcache(), account_ring=FakeRing(),
container_ring=FakeRing(), ... |
eResearchSA/reporting-producers | tests/test_plugin_slurm.py | Python | apache-2.0 | 2,011 | 0.002486 | # pylint: disable=missing-docstring
# this fails on Python 2.6 but Slurm environment is 2.7
import unittest
from datetime import datetime
from reporting.plugins.slurm import SlurmInput
class SlurmTestCase(unittest.TestCase):
"""Test cases for slurm module"""
def test_all_heros(self):
"""Slurm plugin:... | , 0)
def test_convert_to_timestamp(self):
"""Slurm plugin: _convert_to_timestamp should convert iso datetime to timestamp string correctly"""
ISO_FORMAT = '%Y-%m-%dT%H:%M:%S'
reference = datetime.utcnow().strftime(ISO_FORMAT)
converted = datetime.utcfromtimestamp(
SlurmI... | onverted)
|
anntzer/seaborn | seaborn/matrix.py | Python | bsd-3-clause | 51,063 | 0.00002 | """Functions to visualize matrices of data."""
import itertools
import warnings
import matplotlib as mpl
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
import pandas as pd
from scipy.cluster import hierarchy
from . import cm
from .a... | mns,
dtype=np.bool)
elif isinstance(mask, pd.DataFrame):
# For DataFrame masks, ensure that semantic labels match data
if not mask.index.equals(data.index) \
and mask.columns.equals(data.columns):
err = "Mask must have the same index and columns as... | the mask
# This works around an issue where `plt.pcolormesh` doesn't represent
# missing data properly
mask = mask | pd.isnull(data)
return mask
class _HeatMapper(object):
"""Draw a heatmap plot of a matrix with nice labels and colormaps."""
def __init__(self, data, vmin, vmax, cmap, center... |
mozilla/kitsune | kitsune/announcements/forms.py | Python | bsd-3-clause | 842 | 0.002375 | from datetime import date
from django import forms
from django.utils.translation import ugettext_lazy as _lazy
class AnnouncementForm(forms.Form):
"""Form for collecting information about an announcement.
This is not a ModelForm, and does not include the group or locale field | s,
because it should only be used in a context where the group or locale is
implicit, and should not be user controllable. If you need a user
controllable locale or group, use the admin interface.
"""
content = forms.CharField(label=_lazy("Content"), max_length=10000, widget=forms.Textarea)
sh... | equired=False, input_formats=["%Y-%m-%d"]
)
|
robertwbrandt/zarafa | zarafa-tools/mailstore/list-userguids.py | Python | gpl-2.0 | 1,363 | 0.010271 | #!/usr/bin/env python
from MAPI.Util import *
session = OpenECSession('SYSTEM','', os.getenv('ZARAFA_SOCKET', 'file:///var/run/zarafa'), flags=0)
def GetGuids(session, users = None, flags = 0):
"""<session> [<users>] [<flags>]
Returns the store guid for given user(s) within the current <session>.
"""
... | (IID_IExchangeManageStore)
if users is None:
users = GetUserList(session)
elif isinstance(users, basestring):
users = [users]
for user in users:
try:
storeid = ems.CreateStoreEntryID(None, user, 0)
store = session.OpenMsgStore(0, st | oreid, IID_IMsgStore, flags)
storeguid = HrGetOneProp(store, PR_STORE_RECORD_KEY).Value.encode('hex').upper()
# The following excepts are mainly to prevent errors in multi-server setups.
# This script will be made SSL capable in the future.
except MAPIErrorNotFound:
cont... |
sde1000/miltonxero | invoicer/models.py | Python | gpl-3.0 | 10,923 | 0.002289 | from django.db import models
from django.db.models import Q
from decimal import Decimal, ROUND_UP
from django.conf import settings
from django.urls import reverse
import decimal
zero = Decimal("0.00")
penny = Decimal("0.01")
fifty_pence = Decimal("0.50")
pound = Decimal("1.00")
class CaseInsensitiveFieldMixin:
"... | =True, blank=True)
invoice_terms = models.CharField(max_length=20, choices=TERMS_CHOICES,
blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('invoice', args=[self.xero_id])
class ProductType(models.Model):
"... |
def __str__(self):
return self.name
class Unit(models.Model):
"""A unit in which products are sold"""
name = models.CharField(max_length=10, help_text="Unit names with spaces "
"in may require code changes to work")
size = models.DecimalField(max_digits=5, decimal_... |
magne-max/zipline-ja | zipline/data/dispatch_bar_reader.py | Python | apache-2.0 | 4,415 | 0 | #
# Copyright 2016 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | eturn min(r.last_available_dt for r in self._readers.values())
@lazyval
def first_trading_day(self):
return max(r.first_trading_day for r in self._readers.values())
def get_value(self, sid, dt, field):
asset = self._asset_finder.retrieve_asset(sid)
r = self._readers[type(asset)]
... | r = self._readers[type(asset)]
return r.get_last_traded_dt(asset, dt)
def load_raw_arrays(self, fields, start_dt, end_dt, sids):
asset_types = self._asset_types
sid_groups = {t: [] for t in asset_types}
out_pos = {t: [] for t in asset_types}
assets = self._asset_finde... |
Eddy0402/Environment | vim/ycmd/third_party/jedi/test/test_evaluate/namespace_package/ns1/pkg/__init__.py | Python | gpl-3.0 | 214 | 0 | foo = 'ns1!'
# this is a namespace package
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
e | xcept ImportError:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name | __)
|
zstackorg/zstack-utility | zstacklib/zstacklib/test/test_xmlobject.py | Python | apache-2.0 | 793 | 0.01261 | '''
@author: Frank
'''
import unittest
from zsta | cklib.utils import jsonobject
from zstacklib.utils import xmlobject
import os.path
import xml.dom.minidom as dom
import re
class Test(unittest.TestCase):
def testName(self):
cfg = os.path.abspath('zstacklib/test/TestCreateVm.xml')
with open(cfg, 'r') as fd:
content = fd.read()
... | ct.loads(content)
xmlstr = xo.dump()
xmldom = dom.parseString(xmlstr)
xmlstr = xmldom.toprettyxml()
text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
prettyXml = text_re.sub('>\g<1></', xmlstr)
print prettyXml
if __nam... |
JoaquimPatriarca/senpy-for-gis | gasp/arcgis/maps/wmap.py | Python | gpl-3.0 | 1,206 | 0.010779 | """
Write Maps with ArcPY
"""
import arcpy
| def mxd_saveas(mxdObj, outMxd):
"""
Save a copy of a MXD | file
"""
mxdObj.saveACopy(outMxd)
return outMxd
def write_map(mxd_obj, outMap, dpi=None):
"""
Export mxd obj to a new file
"""
import os
dpi = 300 if not dpi else dpi if type(dpi) == int else 300
mapFileFormat = os.path.splitext(os.path.basename(outMap))[1]... |
janbender/PositionBasedDynamics | data/scenes/SceneGenerator.py | Python | mit | 12,344 | 0.032572 | import json
import math
######################################################
# add parameters
######################################################
def addParameters(scene, h=0.005, maxIter=5, maxIterVel=5, velocityUpdateMethod=0, contactTolerance=0.05, triangleModelSimulationMethod=2, triangleModelBendingMethod=2... | : omega,
'restitution' : rest,
'friction' : friction,
'collisionObjectType': coType,
'collisionObjectScale': coScale,
'collisionObjectFileName': coFile,
'testMesh': testMesh
}
current_id += 1
scene['RigidBodies'].append(rb)
return current_id-1
#######################... | xis=[1,0,0], angle=0.0, scale=[1,1,1],
rest=0.6, friction=0.3, staticParticles=[]):
global current_id
tri = { 'id': current_id,
'geometryFile': geoFile,
'translation': translation,
'rotationAxis': axis,
'rotationAngle': angle,
'scale': scale,
'staticParticles': ... |
janschulz/igraph | interfaces/python/igraph/app/shell.py | Python | gpl-2.0 | 18,023 | 0.001332 | """Command-line user interface of igraph
The command-line interface launches a Python shell with the igraph
module automatically imported into the main namespace. This is mostly a
convenience module and it is used only by the C{igraph} command line
script which executes a suitable Python shell and automatically import... | #: Move the cursor left one char
RIGH | T = '' #: Move the cursor right one char
# Deletion:
CLEAR_SCREEN = '' #: Clear the screen and move to home position
CLEAR_EOL = '' #: Clear to the end of the line.
CLEAR_BOL = '' #: Clear to the beginning of the line.
CLEAR_EOS = '' #: Clear to the end of the screen
... |
AsianHope/ahem | rest/ahem_REST/restless/serializers.py | Python | agpl-3.0 | 2,007 | 0.023418 | from django.forms import widgets
from rest_framework import serializers
from restless.models import Employee, Document, EmployeeDocument, LANGUAGE_CHOICES, STYLE_CHOICES
from restless.models import DEPARTMENTS, EMPLOYEETYPES, FAITHS, MARITALSTATUSES, GENDERS, DEGREES
from django.contrib.auth.models import User
import ... | ocument
fields = ('documentID', 'description', 'required')
class EmployeeDocumentSerializer(serializers.ModelSerializer):
class Meta:
model = EmployeeDocument
fields = ('uidNumber','documentI | D', 'url', 'updated')
added_by = serializers.ReadOnlyField(source='added_by.username')
|
stryder199/RyarkAssignments | Assignment2/ttt/cseet_paper/min_io.py | Python | mit | 614 | 0.027687 | question_type = 'input_output'
source_language = 'C'
parameter_list = [
[ | '$stdin0','int'],['$stdin1','int'],['$stdout0','int']
]
tuple_list = [
['min_io_forward_', [1,2,None], [4,9,None]],
['min_io_backward_', [None,None,1], [None,None,6]],
]
global_code_template = '''\
d #include <stdio.h>
x #include <stdio.h>
dx
'''
main_code_template = '''\
dx int a,b;
dx scanf("%d",&a);
dx s... | ut_template = '''\
Minimum: $stdout0
'''
|
luotao1/Paddle | python/paddle/fluid/tests/unittests/test_smooth_l1_loss_op.py | Python | apache-2.0 | 4,325 | 0 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed und | er 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 the License is d... | OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest
import paddle.fluid as fluid
def smooth_l1_loss_forward(val... |
dchilds7/Deysha-Star-Formation | vispy/app/backends/ipython/__init__.py | Python | bsd-3-clause | 192 | 0 | # | -*- coding: utf-8 -*-
# Copyright (c) 2014, 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from ._widge | t import VispyWidget # NOQA
|
mwaaas/django-waffle-session | waffle/__init__.py | Python | bsd-3-clause | 5,489 | 0.001822 | from decimal import Decimal
import random
import hashlib
import re
from . import settings
VERSION = (0, 10, 1)
__version__ = '.'.join(map(str, VERSION))
def keyfmt(k, v=None):
if v is None:
return settings.CACHE_PREFIX + k
return settings.CACHE_PREFIX + hashlib.md5((k % v).encode('utf-8')).hexdige... | f user in flag_users:
return True
flag_groups = cache.get(keyfmt(settings.FLAG_GROUPS_CACHE_KEY, flag.name))
if flag_groups is None:
fl | ag_groups = flag.groups.all()
cache_flag(instance=flag)
user_groups = user.groups.all()
for group in flag_groups:
if group in user_groups:
return True
if flag.languages:
languages = flag.languages.split(',')
if (hasattr(request... |
Harvard-ATG/canvas-utils | skeleton/get_users_emails.py | Python | bsd-3-clause | 1,128 | 0.005319 | from settings.secure import OAUTH_TOKEN, CANVAS_URL
from canvas_sdk.methods import courses
from canvas_sdk.utils import get_all_list_data
from canvas_sdk import RequestContext
import sys
# Get the course ID from the command line
course_id = None
if len(sys.argv) == 2:
cou | rse_id = sys.argv[1]
else:
sys.exit("Error: missing course_id")
# Setup the request context with a large pagination limit (minimize # of requests)
request_context = RequestContext(OAUTH_TOKEN, CANVAS_URL, per_page=100)
# NOTE: you must use get_all_list_data() in order to follow the paginated results
# and get all... | r may not include everyone if there are >100 students in the course.
results = get_all_list_data(request_context, courses.list_users_in_course_users, course_id, "email", enrollment_type="student")
# Extract and sort the results we want.
users = sorted([(x['email'], x['name']) for x in results], key=lambda x: x[0])
#... |
IBM-Security/ibmsecurity | ibmsecurity/isds/interfaces.py | Python | apache-2.0 | 1,677 | 0.002385 | import logging
import ibmsecurity.utilities.tools
logger = logging.getLogger(__name__)
def get_all(isdsAppliance, check_mode=False, force=False):
"""
Retrieving all interfaces
:rtype: (str, dict)
"""
return isdsAppliance.invoke_get("Retrieving all interfaces", "/widgets/mgmtinterface")
def get_... | False):
"""
Adding an address to an interface
"""
if check_mode is True:
return isdsAppliance.create_return_object(changed=True)
else:
return isdsAppliance.invoke_post(
"Creating a new address for an interface",
"/application | _interfaces/" + interface + "/addresses",
{
'address': address,
'netmask': netmask,
'type': network_type,
'ipFqdn': ipFqdn
})
def compare(isdsAppliance1, isdsAppliance2):
"""
Compare interfaces between 2 appliances
"""... |
OliGon/pycurse | Version-0.1/Curses-GoL-0.9.py | Python | mit | 28,137 | 0.061663 | import curses
import sys
import time
import os.path
import random
import pickle
from curses import wrapper
gamedims = [5,22]
currPos = [10,10]
currPosList = [1,3]
def main(stdscr):#{
curses.start_color()
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_BLACK, curses.COL... | yx()
while True:#{
stdscr.clear()
stdscr.box()
stdscr.addstr(dims[0]/2-5, dims[1]/2-queLength/2, L[0])
if ansCount == 2:#{
stdscr.addstr(dims[0]/2+2, dims[1]/2-len(L[2])-5, L[2]+'(1)')
stdscr.addstr(dims[0]/2+2, dims[1]/2+5, L[3]+'(2)')
#}
elif ansCount == 3:#{
std | scr.addstr(dims[0]/2+2, dims[1]/2-len(L[2])-4, L[2]+' (1)')
stdscr.addstr(dims[0]/2+2, dims[1]/2+4, L[3]+'(2)')
stdscr.addstr(dims[0]/2+4, dims[1]/2-len(L[4])/2, L[4]+'(3)')
#}
else:#{
for x in range(1,ansCount+1):
stdscr.addstr(dims[0]/2+2*x, dims[1]/2-len(L[x+1])/2, L[x+1]+'('+str(x)+')')
#}
stds... |
jaddison/django-simple-elasticsearch | simple_elasticsearch/utils.py | Python | bsd-3-clause | 7,968 | 0.001506 | import collections
import datetime
import gc
import sys
from django.conf import settings
from django.http import Http404
from elasticsearch import Elasticsearch, NotFoundError
from simple_elasticsearch.search import Result
from . import settings as es_settings
from .signals import post_indices_create, post_indices_reb... | index_name = index_name
# modify index settings to speed up bulk indexing and then restore them after
es.indices.put_settings({'index': {
'number_of_replicas': 0,
'refresh_interval': '-1',
}}, index=index_name)
try:
type_class.bul... | `bulk_index` not implemented on `{}`.\n'.format(type_class.get_index_name()))
continue
else:
change_index()
# return to the norm for db query logging
# db_logger.setLevel(oldlevel)
if set_aliases:
create_aliases(es, aliases)
if es_settings.ELASTICSEARCH_DELETE_OLD_I... |
balajiiyer-ufl-projects/OpenStackVaccine | notify.py | Python | gpl-2.0 | 805 | 0.01118 | class Notifier:
""" Base abstract class for different notifiers like EmailNotifi | er or TextNotifier.
"""
def __i | nit__(self, client, notified_conf, owner):
self.client = client
self.owner_name = owner["name"]
self.owner_email = owner["email"]
self.owner_phone = owner["phone"]
def notify(self, menace, menace_info, applied_at, applied_duration):
self._do_notify(menace.get_name(),
... |
fedspendingtransparency/data-act-broker-backend | tests/unit/dataactbroker/test_settings_handler.py | Python | cc0-1.0 | 17,247 | 0.003653 | import json
import pytest
from sqlalchemy import and_
from tests.unit.dataactcore.factories.domain import CGACFactory, FRECFactory
from dataactcore.models.lookups import FILE_TYPE_DICT_LETTER_ID, RULE_SEVERITY_DICT, RULE_IMPACT_DICT
from dataactcore.models.validationModels import RuleSql, RuleSetting
from dataactcore.... | ql_c2])
# Setup default rules
load_default_rule_settings(sess | )
sess.add_all(db_objects)
sess.commit()
@pytest.mark.usefixtures('job_constants')
@pytest.mark.usefixtures('validation_constants')
def test_list_rule_settings_input_errors(database):
""" Testing list_rule_settings function when invalid parameters are passed in. """
sess = database.session
setup_... |
YanTangZhai/tf | tensorflow/python/kernel_tests/xent_op_test.py | Python | apache-2.0 | 5,860 | 0.004608 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | gits(
np.array([[1.], [-1.], [0.]]).astype(np.float32),
np.array([[-1.] | , [0.], [1.]]).astype(np.float32))
backprop = loss.op.outputs[1]
tf_loss, tf_backprop = sess.run([loss, backprop])
self.assertAllClose([0.0, 0.0, 0.0], tf_loss)
self.assertAllClose([[2.0], [1.0], [0.0]], tf_backprop)
def testSingleClass(self):
self._testSingleClass(True)
self._testSingleC... |
krzysiekfonal/grammaregex | grammaregex/tests/tests.py | Python | mit | 4,970 | 0.003823 | import unittest
from grammaregex import match_tree, find_tokens, verify_pattern, PatternSyntaxException
import spacy
# _sentence will be used throughout the all tests as it is time-consuming to create it.
# The fact of time-consumption is also reason for keeping all tests in single module file
_sentence = None
def s... | tRaises(PatternSyntaxException):
match_tree(_sentence, "*//[]")
def test_find_simple_patterns(self):
self.assertListEqual(["School"],
[x.orth_ for x in find_tokens(_sentence, "VBD/prep/IN/pobj/NNP")])
def test_not_find_simple_patterns(self):
| self.assertListEqual([],
[x.orth_ for x in find_tokens(_sentence, "VBD/prep/IN/pobj/VBD")])
def test_find_pattern_with_stars(self):
self.assertListEqual(["School", "1980"],
[x.orth_ for x in find_tokens(_sentence, "VBD/prep/IN/pobj/*")])
... |
toddpalino/kafka-tools | kafka/tools/protocol/requests/leader_and_isr_v0.py | Python | apache-2.0 | 2,023 | 0.000494 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | e': 'int32'},
{'name': 'leader_epoch', 'type': 'int32'},
{'name': 'isr', 'type': 'array', 'item_type': 'int32'},
{'name': 'zk_version', 'type': 'int32'},
{'name': 'replicas', 'type': 'array', 'item_type': 'int32'},
]},
{'name': 'live_leaders',
... | {'name': 'id', 'type': 'int32'},
{'name': 'host', 'type': 'string'},
{'name': 'port', 'type': 'int32'},
]},
]
|
kuznetz/rabbitvcs | rabbitvcs/debug/ipython_view.py | Python | gpl-2.0 | 16,116 | 0.010921 | '''
Provides IPython console widget.
@author: Eitan Isaacson
@organization: IBM Corporation
@copyright: Copyright (c) 2007 IBM Corporation
@license: BSD
All rights reserved. This program and the accompan | ying materials are made
available under the terms of the BSD which accompanies this distribution, and
is available at U{http://www.opensource.org/licenses/bsd-license.php}
'''
import gtk, gobject
import re
import sys
import os
import pango
from StringIO import StringIO
import thread |
try:
import IPython
except ImportError:
IPython = None
class IterableIPShell:
'''
Create an IPython instance. Does not start a blocking event loop,
instead allow single iterations. This allows embedding in GTK+
without blockage.
@ivar IP: IPython instance.
@type IP: IPython.iplib.InteractiveShell
... |
peichman-umd/newspaper-batchload | classes/oa.py | Python | apache-2.0 | 2,919 | 0.001714 | from rdflib import Literal
from classes import ldp
from namespaces import dcterms, oa, rdf
# alias the RDFlib Namespace
ns = oa
# Annotation resources
class Annotation(ldp.Resource):
def __init__(self):
super(Annotation, self).__init__()
self.motivation = None
def add_body(self, body):
... | thSelector, self).__init__()
s | elf.value = value
self.title = self.value
def graph(self):
graph = super(XPathSelector, self).graph()
graph.add((self.uri, rdf.value, Literal(self.value)))
graph.add((self.uri, rdf.type, oa.XPathSelector))
return graph
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.