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 |
|---|---|---|---|---|---|---|---|---|
alexliyu/CDMSYSTEM | pyroute2/netns/nslink.py | Python | mit | 10,211 | 0 | '''
NetNS, network namespaces support
=================================
Pyroute2 provides basic network namespaces support. The core
class is `NetNS`.
Please be aware, that in order to run system calls the library
uses `ctypes` module. It can fail on platforms where SELinux
is enforced. If the Python interpreter, loa... | else:
atexit.register(self.close)
def recv(self, bufsize, flags=0):
return self.rcvch.recv()
def close(self):
self.cmdch.send(None)
self.server.join()
def proxy(self, cmd, *argv, **kwarg):
with self.cmdlock:
self.cmdch.s | end((cmd, argv, kwarg))
response = self.cmdch.recv()
if isinstance(response, Exception):
raise response
return response
def fileno(self):
return self.rcvch.fileno()
def bind(self, *argv, **kwarg):
if 'async' in kwarg:
kwarg['async... |
neocogent/electrum | electrum/scripts/block_headers.py | Python | mit | 955 | 0.003141 | #!/usr/bin/env python3
# A simple script that connects to a server and displays block headers
import time
import asyncio
from electrum.network import Network
from electrum.util import print_msg, json_encode, create_and_start_event_loop, log_exceptions
# start network
loop, stopping_fut, loop_thread = create_and_sta... | ueue.get()
print_msg(json_encode(header))
finally:
stopping_fut.set_result(1)
# 2. | send the subscription
asyncio.run_coroutine_threadsafe(f(), loop)
|
supriyasawant/gstudio | gnowsys-ndf/gnowsys_ndf/ndf/models.py | Python | agpl-3.0 | 72,774 | 0.007379 | # imports from python libraries
import os
import hashlib
import datetime
import json
from itertools import chain # Using from_iterable()
# imports from installed packages
from django.contrib.auth.models import User
from django.db import models
from django_mongokit import connection
from django_mongokit import get_d... | TATUS_CHOICES_TU = IS(u'DRAFT', u'HID | DEN', u'PUBLISHED', u'DELETED')
STATUS_CHOICES = tuple(str(qtc) for qtc in STATUS_CHOICES_TU)
QUIZ_TYPE_CHOICES_TU = IS(u'Short-Response', u'Single-Choice', u'Multiple-Choice')
QUIZ_TYPE_CHOICES = tuple(str(qtc) for qtc in QUIZ_TYPE_CHOICES_TU)
# FRAME CLASS DEFINITIONS
@receiver(user_registered)
def user_registered... |
virtualopensystems/neutron | neutron/tests/unit/nec/test_db.py | Python | apache-2.0 | 7,264 | 0 | # Copyright 2012 NEC Corporation. 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 ... | }
yield params
class NECPluginV2DBOfcMappingTest(NECPluginV2DBTestBase):
def test_add_ofc_item(self):
"""test add OFC item."""
| o, q, n = self.get_ofc_item_random_params()
tenant = ndb.add_ofc_item(self.session, 'ofc_tenant', q, o)
self.assertEqual(tenant.ofc_id, o)
self.assertEqual(tenant.neutron_id, q)
def test_add_ofc_item_duplicate_entry(self):
o, q, n = self.get_ofc_item_random_params()
nd... |
kklmn/xrt | examples/withRaycing/14_SoftiMAX/__init__.py | Python | mit | 16,930 | 0.002662 | # -*- coding: utf-8 -*-
r"""
.. _SoftiMAX:
SoftiMAX at MAX IV
------------------
The images below are produced by scripts in
``\examples\withRaycing\14_SoftiMAX``.
The beamline will have two branches:
- STXM (Scanning Transmission X-ray Microscopy) and
- CXI (Coherent X-ray Imaging),
see the scheme provided by K. T... | .
+-----------+--------------- | -----------+--------------------------+
| | 80 µm exit slit | 20 µm exit slit |
+===========+==========================+==========================+
| method 1 | |st_hS80m1| | |st_hS20m1| |
+-----------+--------------------------+--------------------------+
| method... |
mdameenh/elysia | fplassist/update_database.py | Python | bsd-3-clause | 10,609 | 0.010651 | # -*- coding: utf-8 -*-
import requests
from datetime import datetime
from fplassist.models import Team_Info, Player_Info, Player_Basic_Stats, Player_Detailed_Stats, FPL_Config
def get_data(api_url):
api_response = requests.get(api_url)
try:
api_response.raise_for_status()
api_data = api_respon... | etailed = Player_Detailed_Stats.objects.get(player_id=player["id"])
player_detailed.ict_index = player_deep_cumul["ict_index"]
player_detailed.open_play_crosses = player_deep_cumul["open_play_crosses"]
player_detailed.big_chances_created = player_deep_cumul["big_chances_created"]
... | nces_blocks_interceptions = player_deep_cumul["clearances_blocks_interceptions"]
player_detailed.recoveries = player_deep_cumul["recoveries"]
player_detailed.key_passes = player_deep_cumul["key_passes"]
player_detailed.tackles = player_deep_cumul["tackles"]
player_detaile... |
JensTimmerman/radical.pilot | docs/source/conf.py | Python | mit | 12,807 | 0.006637 | # -*- coding: utf-8 -*-
#
# RADICAL-Pilot documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 3 21:55:42 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... | working_dir = "$HOME"
try:
python_interpreter = resource_config["python_interpreter"]
except Exception, ex:
python_interpreter = None
try:
access_schemas = resource_config["schemas"]
except Exception, ex:
... | urces_rst.write("{0}\n".format(host_key.upper()))
resources_rst.write("{0}\n\n".format("*"*len(host_key)))
resources_rst.write("{0}\n\n".format(resource_config["description"]))
resources_rst.write("* **Resource label** : ``{0}``\n".format(resource_key))
resources_rst... |
plotly/python-api | packages/python/plotly/plotly/validators/funnel/_cliponaxis.py | Python | mit | 450 | 0.002222 | import _plotly_utils.basev | alidators
class CliponaxisValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(self, plotly_name="cliponaxis", parent_name="funnel", **kwargs):
| super(CliponaxisValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
mytliulei/Scapy | scapy/layers/sctp.py | Python | apache-2.0 | 17,954 | 0.011474 | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <[email protected]>
## Copyright (C) 6WIND <[email protected]>
## This program is published under a GPLv2 license
"""
SCTP (Stream Control Transmission Protocol).
"""
import struct
from... | crc = 0xffffffff
for c in buf:
crc = (crc>>8) ^ crc32c_table[(crc^(ord(c))) & 0xFF]
crc = (~crc) & 0xffffffff
# reverse endianness
return struct.unpack(">I",struct.pack("<I", crc))[0]
# old checksum (RFC2960)
"""
BASE = 65521 # largest prime smaller than 65536
def update_adler32(adler, buf)... | t ord(c)
s1 = (s1 + ord(c)) % BASE
s2 = (s2 + s1) % BASE
print s1,s2
return (s2 << 16) + s1
def sctp_checksum(buf):
return update_adler32(1, buf)
"""
sctpchunktypescls = {
0 : "SCTPChunkData",
1 : "SCTPChunkInit",
2 : "SCTPChunkInitAck",
3 : "SCTPChunkSACK",
4 : "SC... |
netixx/python-tools | tools/debugger.py | Python | apache-2.0 | 674 | 0.004451 | """Module to debug python programs"""
import sys
import traceback
def getAllStacks():
code = []
for threadId, stack in sys._current_frames().iteritems():
code.append("\n# ThreadID: %s" % threadId)
for | filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename,
lineno, name))
if line:
code.append(" %s" % (line.strip()))
return code
def strStacks():
out = ... | ACKTRACE - END ***\n"
return out
|
mgracer48/panda3d | direct/src/showbase/ProfileSession.py | Python | bsd-3-clause | 12,549 | 0.002789 | from panda3d.core import TrueClock
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.PythonUtil import (
StdoutCapture, _installProfileCustomFuncs,_removeProfileCustomFuncs,
_getProfileResultFileInfo, _setProfileResultsFileInfo)
import __builtin__
import profile
import pstats
... | print f8(ct/cc),
# DCR
#print func_std_string(func)
print PercentStats.func_std_string(func)
class ProfileSession:
# class that encapsulates a profile of a single callable using Python's standard
# 'profile' module
#
# defers formatting of profile results until they are reque... | redirects file output to RAM file for efficiency
TrueClock = TrueClock.getGlobalPtr()
notify = directNotify.newCategory("ProfileSession")
def __init__(self, name, func=None, logAfterProfile=False):
self._func = func
self._name = name
self._logAfterProfile = logAfterProfile
... |
KeyWeeUsr/plyer | plyer/platforms/macosx/filechooser.py | Python | mit | 3,427 | 0 | '''
Mac OS X file chooser
---------------------
'''
from plyer.facades import FileChooser
from pyobjus import autoclass, objc_arr, objc_str
from pyobjus.dylib_manager import load_framework, INCLUDE
load_framework(INCLUDE.AppKit)
NSURL = autoclass('NSURL')
NSOpenPanel = autoclass('NSOpenPanel')
NSSavePanel = autoclass... | if self.mode != "save" and self.multiple:
panel.setAllowsMultipleSelection_(True)
# Mac OS X does not support wildcards unlike the other platforms.
# This tries to convert wildcards to "extensions" when possible,
# ans sets the panel to also allow o | ther file types, just to be safe.
if len(self.filters) > 0:
filthies = []
for f in self.filters:
if type(f) == str:
if not self.use_extensions:
if f.strip().endswith("*"):
continue
... |
dkasak/notify-osd-customizable | examples/summary-body.py | Python | gpl-3.0 | 3,917 | 0.032678 | #!/usr/bin/python
################################################################################
##3456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789
## 10 20 30 40 50 60 70 80
##
## Info:
## Example of how to use libnotify correctl... | nt "\ticon-static"
if capabilities['sound']:
print "\tsound"
if capabilities['image/svg+xml']:
print "\timage/svg+xml"
if capabilities['x-canonical-private-synchronous']:
print "\tx-canonical-private-synchronous"
if capabilities['x-canonical-append']:
print "\tx-canonical-append"
if capabilities['x-canonic... | e-icon-only']:
print "\tx-canonical-private-icon-only"
if capabilities['x-canonical-truncation']:
print "\tx-canonical-truncation"
print "Notes:"
if info["name"] == "notify-osd":
print "\tx- and y-coordinates hints are ignored"
print "\texpire-timeout is ignored"
print "\tbody-markup is accepted but filte... |
sanguinariojoe/FreeCAD | src/Mod/OpenSCAD/InitGui.py | Python | lgpl-2.1 | 5,293 | 0.013603 | # OpenSCAD gui init module
#
# Gathering all the information to start FreeCAD
# This is the second one of three init scripts, the third one
# runs when the gui is up
#***************************************************************************
#* (c) Juergen Riegel ([email protected]) 2002 *... | ,'OpenSCAD_ResizeMeshFeature','OpenSCAD_IncreaseToleranceFeature',
'OpenSCAD_Edgestofaces', 'OpenSCAD_ExpandPlacements','OpenSCAD_ExplodeGroup']
toolbarcommands = ['OpenSCAD_ReplaceObject','OpenSCAD_RemoveSubtree',
'OpenSCAD_ | ExplodeGroup','OpenSCAD_RefineShapeFeature',
'OpenSCAD_IncreaseToleranceFeature']
import PartGui
parttoolbarcommands = ['Part_CheckGeometry','Part_Primitives',
'Part_Builder','Part_Cut','Part_Fuse','Part_Common',
'P... |
bkahlert/seqan-research | raw/workshop11/workshop2011-data-20110925/trunk/misc/seqan_instrumentation/py2exe/dist/classes/__init__.py | Python | mit | 81 | 0 | __a | ll__ = [
'diff', 'dirs', 'flushfile', 'id',
'stats', 'sy | nc'
]
|
google/struct2tensor | struct2tensor/prensor_value.py | Python | apache-2.0 | 9,379 | 0.00853 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | sor_value = sess.run(prensor)
assert isinstance(prensor_value, struct2tensor.PrensorValue)
"""
import collections
from typing import FrozenSet, Iterator, Mapping, Optional, Sequence, Union
import numpy as np
from struct2tensor import path
from struct2tensor import prensor
import te | nsorflow as tf
from tensorflow.python.client import session as session_lib # pylint: disable=g-direct-tensorflow-import
class RootNodeValue(object):
"""The value of the root."""
__slots__ = ["_size"]
def __init__(self, size: np.int64):
"""Creates a root node.
Args:
size: how many root objects... |
airanmehr/bio | Scripts/TimeSeriesPaper/Plot/DirectvsRNN.py | Python | mit | 1,198 | 0.040902 | '''
Copyleft Oct 24, 2015 Arya Iranmehr, PhD Student, Bafna's Lab, UC San Diego, Email: [email protected]
'''
import pandas as pd
import pylab as plt
import matplotlib as mpl
from matplotlib.cm import *
import os,sys;home=os.path.expanduser('~') +'/'
mpl.rc('font', **{'family | ': 'serif', 'serif': ['Computer Modern'], 'size':20}) ;
mpl.rc('text', usetex=True)
x=np.arange(0,1,1e-5)[1:-1]
s=0.01
def sig(z): return 1./(1+np.exp(-z))
fig=plt.figure | (figsize=(30,10), dpi=100)
fig.hold(True)
y_appr=np.log(x)- np.log(1-x)
y=np.log(x)- (1+s)*np.log(1-x)
x.shape
df=pd.DataFrame([x,y,y_appr],index=['x','y','z']).T
plt.subplot(1,2,1)
plt.plot(y_appr,x, color='red',linewidth=2, label='$\sigma(st/2-c)$')
plt.plot(y,x, color='blue',linewidth=2,label='$x_t$')
plt.xlim([-5,... |
ParadropLabs/Paradrop | paradrop/daemon/paradrop/core/chute/chute_storage.py | Python | apache-2.0 | 3,342 | 0.001795 | from __future__ import print_function
###################################################################
# Copyright 2013-2017 All Rights Reserved
# Authors: The Paradrop Team
###################################################################
import sys
from paradrop.base import settings
from paradrop.lib.utils.pd_... | Also since we just received a new chute to hold onto we should save our ChuteList to disk.
"""
# check if there is a version of the chute already
oldch = ChuteStorage.chuteList.get(ch.name, None)
if(oldch != None):
# we should merge these chutes so we don't lose an... | ChuteStorage.chuteList[ch.name] = ch
self.saveToDisk()
def clearChuteStorage(self):
ChuteStorage.chuteList.clear()
self.saveToDisk()
#
# Functions we override to implement PDStorage Properly
#
def attrSaveable(self):
"""Returns True if we should save the C... |
xuweiliang/Codelibrary | openstack_dashboard/dashboards/admin/networks/agents/tables.py | Python | apache-2.0 | 3,868 | 0.001551 | # Copyright 2014 Kylincloud
#
# 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 ... | network_info.name,
record_action.DELETEAGENT)
except Exception as e:
msg = _('Failed to delete agent: %s') % e
LOG.info(msg)
api.nova.systemlogs_create(request, network_info.name, |
record_action.DELETEAGENT, result=False, detail=msg)
redirect = reverse('horizon:admin:networks:detail',
args=[network_id])
exceptions.handle(request, msg, redirect=redirect)
class AddDHCPAgent(tables.LinkAction):
name = "add"
verbose_nam... |
xyproto/gosignal | pyo/examples/effects/03_detuned_waveguides.py | Python | gpl-3.0 | 513 | 0.02729 | #!/usr/bin/env python
# encoding: utf-8
"""
Detuned waveguide bank.
"""
from py | o import *
import random
s = Server(sr=44100, nchnls=2, buffersize=512, duplex=0).boot()
src = SfPlayer("../snds/ounkmaster.aif", loop=True, mul=.1)
lf = Sine(freq=[random.uniform(.005, .015) for i in range(8)],
mul=[.02,.04,.06,.08,.1,.12,.14,.16],
add=[50,100,150,200,250,300,350,400])
lf2 = Sin... | AllpassWG(src, freq=lf, feed=.999, detune=lf2, mul=.25).out()
s.gui(locals())
|
xfouloux/Flexget | flexget/plugins/input/sonarr.py | Python | mit | 5,907 | 0.00237 | from __future__ import unicode_literals, division, absolute_import
from urlparse import urlparse
import logging
from requests import RequestException
from flexget import plugin
from flexget.event import event
from flexget.entry import Entry
log = logging.getLogger('sonarr')
class Sonarr(object):
schema = {
... | pi_key']}
try:
json = task.requests.get(url, headers=headers).json()
except RequestException as e:
raise plugin.PluginError('Unable to connect to Sonarr at %s://%s:%s%s. Error: %s'
% (parsedurl.scheme, parsedurl.netloc, config.get('port'),
... | ,
1: 'sdtv',
2: 'dvdrip',
3: '1080p webdl',
4: '720p hdtv',
5: '720p webdl',
6: '720p bluray',
7: '1080p bluray',
8: '480p webdl',
... |
chillpop/RELAX-HARDER | effects/base.py | Python | mit | 10,042 | 0.004979 | from __future__ import print_function
import numpy
import time
import traceback
import colorsys
import random
class EffectLayer(object):
"""Abstract base class for one layer of an LED light effect. Layers operate on a shared framebuffer,
adding their own contribution to the buffer and possibly blending or o... | nces from EffectLayer:
1) Constructor expects four paramters:
-- re | spond_to: the name of a field in EEGInfo (threads.HeadsetThread.EEGInfo).
Currently this means either 'attention' or 'meditation'
-- smooth_response_over_n_secs: to avoid rapid fluctuations from headset
noise, averages the response metric over this many seconds
-- minimum_response_leve... |
nashif/zephyr | boards/xtensa/intel_adsp_cavs15/tools/adsplog.py | Python | apache-2.0 | 8,018 | 0.000499 | #!/usr/bin/python3
#
# Copyright (c) 2020 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import time
import subprocess
import mmap
# Log reader for the trace output buffer on a ADSP device.
#
# When run with no arguments, it will detect the device, dump the
# contents of the trace buffer... | ata.
last_id = id0
final_slot = start_slot
for i in range(start_slot + 1, NUM_SLOTS):
id, s = read_slot(i, mem)
if id != ((last_id + 1) & 0xffff):
break
msg += s
final_slot = i
last_id = id
final_id = last_id
# Now read backwards from the end to ... | if id < 0:
break
# Race protection: the other side might have clobbered the
# data after we read the ID, make sure it hasn't changed.
id_check = read_slot(i, mem)[0]
if id_check != id:
break
if ((id + 1) & 0xffff) == last_id:
msg = s +... |
vinco/django-socialregistration | socialregistration/views.py | Python | mit | 10,506 | 0.006663 | from django.conf import settings
from django.contrib.auth import logout
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.views.generic.base import View, TemplateView
from socialregistration.clients.oauth import ... | callback views.
:param client: The API client class that should be used.
:param template_name: The error template.
"""
# The OAuth{1,2} client to be used
client = None
# The template to render in case of errors
template_name = None
def get_redirect(self):
"""
... | raise NotImplementedError
def get(self, request):
"""
Called after the user is redirected back to our application.
Tries to:
- Complete the OAuth / OAuth2 flow
- Redirect the user to another view that deals with login, connecting
or user creation.
... |
tiradoe/Giflocker | giflocker/locker/admin.py | Python | lgpl-3.0 | 143 | 0.013986 | from django.contr | ib import admin
from locker.models import Gif
class GifAdmin(admin.ModelAdmin):
pass
admin.site.register(Gif, GifAdmi | n)
|
indictranstech/erpnext | erpnext/education/doctype/assessment_result/test_assessment_result.py | Python | agpl-3.0 | 521 | 0.017274 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
from erpnext.education.api import get_grade
# test_records = frappe.get_test_records('Assessment Result')
class TestAssessmentResult(uni... |
grade = get_grade("_Test Grading Scale", 70)
self.assertEquals("B", gra | de)
|
mikedelong/aarhus | demos/clusters_from_topics.py | Python | apache-2.0 | 9,957 | 0.002913 | # http://stats.stackexchange.com/questions/28904/how-to-cluster-lda-lsi-topics-generated-by-gensim
# coding:utf-8
import cPickle as pickle
import glob
import logging
import os
import scipy
import scipy.sparse
import string
import sys
import time
from collections import defaultdict
import gensim.matutils
import gensim... | pora.MmCorpus(self.conf['fname_corpus'])
| if params is None:
params = {}
logger.info("training TF-IDF model")
self.tfidf = models.TfidfModel(corpus, id2word=self.dictionary)
corpus_tfidf = self.tfidf[corpus]
if method == 'lsi':
logger.info("training LSI model")
self.lsi = models.LsiMod... |
sonntagsgesicht/regtest | .aux/venv/lib/python3.9/site-packages/pygments/styles/abap.py | Python | apache-2.0 | 727 | 0 | """
pygments.styles.abap
~~~~~~~~~~~~~~~~~~~~
ABAP workbench like style.
| :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator
class AbapStyle(Style):
default_style = ""
styles = {
Comment: ... | '#00f',
Operator.Word: '#00f',
Name: '#000',
Number: '#3af',
String: '#5a2',
Error: '#F00',
}
|
ibegleris/Single-mode-FOPO | src/data_plotters_animators.py | Python | bsd-3-clause | 10,230 | 0.006549 | import matplotlib as mpl
#mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
from scipy.constants import c
import h5py
import sys
import warnings
warnings.simplefilter("ignore", UserWarning)
font = {'size': 18}
mpl.rc('font', **font)
def w2dbm(W, floor=-100):
"""This function converts a ... | '$Spectrum (W)$'
filesave = 'output'+pump_wave+'/output' + \
str(index) + '/figures/time/'+filename
plot_multiple_modes(int_fwm.nm, x, y, mode_names,
ylim, xlim, xlabel, ylabel, title, filesave, im)
return None
def saver(self, index, int_fwm, sim_wind... | =None,
im=0, plots=True):
"""Dump to HDF5 for postproc"""
if filename[:4] != 'port':
layer = filename[-1]+'/'+filename[:-1]
else:
layer = filename
if layer[0] is '0':
extra_data = np.array([int_fwm.z, int_fwm.nm,P0_p, P0_s, f_p, f_s, ro]... |
sanxiatianma/spider | src/spider/settings.py | Python | apache-2.0 | 483 | 0.004141 | # -*- coding: utf-8 -*-
# Scrapy settings for spider project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'spider'
SPIDER_MODULES = ['spid | er.s | piders']
NEWSPIDER_MODULE = 'spider.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'spider (+http://www.yourdomain.com)'
|
google/cloudprint_logocert | _log.py | Python | apache-2.0 | 3,118 | 0.003849 | """Copyright 2016 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 agreed to in ... | r.
Args:
name: string, name of logger.
logdir: string, path to a directly to place log files.
loglevel: string, debug level of logger.
stdout: boolean, True = send messages to stdout and logfile.
False = only send messages to log file.
Returns:
initialized logger.
Since ... | ion uses
3 handlers, so if handlers == 0 the logger requires proper configuration
of handlers and log files.
"""
logger = logging.getLogger(name)
if not logger.handlers:
datetime_str = time.strftime('%Y%B%d_%H%M%S', time.localtime())
log_filename = '%s%s%s' % (name, datetime_str, '.log')
if not lo... |
hrayr-artunyan/shuup | shuup_tests/xtheme/test_editor_view.py | Python | agpl-3.0 | 6,457 | 0.002168 | # -*- coding: utf-8 -*-
from contextlib import contextmanager
import pytest
from django.contrib.auth.models import AnonymousUser
from django.test.client import RequestFactory
from shuup.apps.provides import override_provides
from shuup.utils.excs import Problem
from shuup.xtheme import XTHEME_GLOBAL_VIEW_NAME
from sh... | W_CELL_LIMIT):
view_obj.dispatch_add_cell(y=0)
assert len(view_obj.layout.rows[0]) == ROW_CELL_LIMIT
with pytest.raises(ValueError):
view_obj.dispatc | h_add_cell(y=0)
@pytest.mark.django_db
def test_get_global_placeholder():
request = RequestFactory().get("/")
layout, svc = get_test_layout_and_svc()
with initialize_editor_view(svc.view_name, layout.placeholder_name, request=request) as view_obj:
view_name_1 = view_obj.dispatch(view_obj.request).... |
yasoob/PythonRSSReader | venv/lib/python2.7/dist-packages/oneconf/paths.py | Python | mit | 3,861 | 0.000518 | # -*- coding: utf-8 -*-
# Copyright (C) 2011 Canonical
#
# Authors:
# Didier Roche <[email protected]>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# This program is distrib... | load"
HOST_DATA_FILENAME = "host"
LOGO_PREFIX = "logo"
LAST_SYNC_DAT | E_FILENAME = "last_sync"
_datadir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")
# In both Python 2 and 3, _datadir will be a relative path, however, in Python
# 3 it will start with "./" while in Python 2 it will start with just the file
# name. Normalize this, since the path string is used in th... |
Uli1/mapnik | scons/scons-local-2.4.0/SCons/Tool/tar.py | Python | lgpl-2.1 | 2,503 | 0.006392 | """SCons.Tool.tar
Tool-specific initialization for tar.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is hereby granted, free of charge, to... | e rights to use, copy, modify, me | rge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# ... |
Travelport-Czech/apila | tasks/DynamoTable.py | Python | mit | 6,621 | 0.014197 | from Task import Task
import os.path
import yaml
import botocore
import name_constructor
import time
import sys
class DynamoTable(Task):
"""Create or remove a table by yaml definition file"""
known_params = {
'name': 'name of the table to be created or removed',
'source': 'full name of the file with the de... | ])
if 'StreamSpecification' in new_def:
params['StreamSpecification'] = new_def['StreamSpecifi | cation']
try:
client.create_table(**params)
except botocore.exceptions.ClientError as e:
return (False, str(e))
return (True, self.CREATED)
|
willkg/douglas | douglas/tests/test_yeararchives.py | Python | mit | 668 | 0 | from nose.tools import eq_
from douglas.tests import PluginTest
from douglas.plugins import yeararchives
class Test_yeararchives(PluginTest):
def setUp(self):
PluginTest.setUp(self, yeararchives)
def tearDown(self):
PluginTest.tearDown(self)
de | f test_parse_path_info(self):
testdata = [
('', None),
('/', None),
| ('/2003', ('2003', None)),
('/2003/', ('2003', None)),
('/2003/index', ('2003', None)),
('/2003/index.theme', ('2003', 'theme')),
]
for data, expected in testdata:
eq_(yeararchives.parse_path_info(data), expected)
|
IITBinterns13/edx-platform-dev | common/lib/xmodule/xmodule/modulestore/mongo/draft.py | Python | agpl-3.0 | 9,889 | 0.002225 | from datetime import datetime
from xmodule.modulestore import Location, namedtuple_to_son
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.modulestore.inheritance import own_metadata
from xmodule.exceptions import InvalidVersionError
from xmodule.modulestore.mongo.base import MongoModuleStore
... | em.location.revision == DRAFT)
item.location = item.location.replace(revision=None)
return item
class DraftModuleStore(MongoModuleStore):
"""
This mixin modifies a modulestore to give it draft semantics.
That is, edits made to units are stored to locations that have the revision DRAFT,
and whe... | AFT doesn't exist.
This module also includes functionality to promote DRAFT modules (and optionally
their children) to published modules.
"""
def get_item(self, location, depth=0):
"""
Returns an XModuleDescriptor instance for the item at location.
If location.revision is None,... |
nortikin/sverchok | nodes/list_struct/shuffle.py | Python | gpl-3.0 | 3,555 | 0.001125 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | s import BoolProperty, IntProperty, StringProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, changable_sockets
import numpy as np
from numpy import random as np_random, ndarray, array
class ListShuffleNode(bpy.types.Node, SverchCustomTreeNode):
'''
Trig... | name = 'ListShuffleNode'
bl_label = 'List Shuffle'
bl_icon = 'OUTLINER_OB_EMPTY'
sv_icon = 'SV_LIST_SHUFFLE'
level: IntProperty(name='level_to_Shuffle', default=2, min=1, update=updateNode)
seed: IntProperty(name='Seed', default=0, update=updateNode)
typ: StringProperty(name='typ', default='')
... |
eHealthAfrica/LMIS | LMIS/core/api/serializers.py | Python | gpl-2.0 | 3,856 | 0.001815 | """
core/api/serializers.py is the module for core model api data serializers
"""
#import core django module
from django.contrib.auth.models import User, Permission
#import external modules
from rest_framework import serializers
#import project modules
from core.models import (Product, ProductCategory, UnitOfMea... | lSerializer):
"""
REST API serializer for EmployeeCategory
"""
class Meta:
model = EmployeeCategory
class EmployeeSerializer(BaseModelSerializer):
"""
REST API serializer for Employee
"""
class Meta:
model = Employee
class PermissionSerializer(BaseModelSeriali... | Meta:
model = Permission
class ProductPresentationSerializer(BaseModelSerializer):
"""
REST API serializer for ProductPresentation model
"""
class Meta:
model = ProductPresentation
class ModeOfAdministrationSerializer(BaseModelSerializer):
"""
REST API serializer for... |
SalesforceFoundation/CumulusCI | cumulusci/tasks/github/merge.py | Python | bsd-3-clause | 11,772 | 0.003058 | import http.client
from github3 import GitHubError
import github3.exceptions
from cumulusci.core.exceptions import GithubApiNotFoundError
from cumulusci.core.utils import process_bool_arg
from cumulusci.tasks.github.base import BaseGithubTask
class MergeBranch(BaseGithubTask):
task_docs = """
Merges the mos... | nch)
# else not a direct descendent
else:
self.logger.debug(
f"Skipping branch {branch.name}: is not a direct descendent of {self.options['source_branch']}"
)
to_merge = []
if child_branches:
self.logger.debug(
... | rtswith(self.options["branch_prefix"]):
self.logger.debug(
f"No children found for branch {self.options['source_branch']}"
)
if release_branches:
self.logger.debug(
f"Found future release branches to update: {[branch.name for branch in release... |
fnp/fnpdjango | tests/tests/test_utils_settings.py | Python | agpl-3.0 | 398 | 0.005038 | # This file is part of FNPDjango, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See README.md for more information.
#
from django.conf import settings
from django.test import TestCase
class UtilsSettingsTestCase(Test | Case):
def test_lazy_ugettext_lazy(self):
self.assertEqual(str(settings.TEST_LAZY_UGETTEXT_LAZY),
"Lazy setting | .")
|
chronicle/api-samples-python | feeds/create_azure_ad_context_feed.py | Python | apache-2.0 | 4,356 | 0.008494 | #!/usr/bin/env python3
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | which represents Id of the credential to use.
clientsecret: A string which represents secret of the credential to use.
retrievedevices: A boolean to indicate whether to retrieve devices or not.
retrievegroups: A boolean to indicate whether to retrieve groups or not.
Returns:
New Azure AD Feed.
Rai... | ests.exceptions.HTTPError: HTTP request resulted in an error
(response.status_code >= 400).
"""
url = f"{CHRONICLE_API_BASE_URL}/v1/feeds/"
body = {
"details": {
"feedSourceType": "API",
"logType": "AZURE_AD_CONTEXT",
"azureAdContextSettings": {
"authenticat... |
openstack/cloudkitty | cloudkitty/db/sqlalchemy/alembic/versions/464e951dc3b8_initial_migration.py | Python | apache-2.0 | 1,314 | 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... | 55), nullable=False),
sa.Column('state', sa.BigInteger(), nullable=False),
sa.Column('s_metadata', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('name'))
op.create_table(
'modules_state',
sa.Column('name', sa.String(length=255), nullable=False),
sa.Column('state'... | raint('name'))
|
jotes/pontoon | pontoon/test/fixtures/base.py | Python | bsd-3-clause | 3,576 | 0.000559 | import pytest
from pontoon.test import factories
@pytest.fixture
def admin():
"""Admin - a superuser"""
return factories.UserFactory.create(userna | me="admin", is_superuser=True,)
@pytest.fixture
def client_superuser(client, admin):
"""Provides a client with a logged in superuser. """
client.force_login(admin)
return client
@pytest.fixture
def user_a():
return factories.UserFactory(username="user_a")
@pytest.fixture
def user_b():
return f... | ctories.UserFactory(username="user_c")
@pytest.fixture
def member(client, user_a):
"""Provides a `LoggedInMember` with the attributes `user` and `client`
the `client` is authenticated
"""
class LoggedInMember(object):
def __init__(self, user, client):
client.force_login(user)
... |
eReuse/DeviceHub | ereuse_devicehub/resources/device/mobile/settings.py | Python | agpl-3.0 | 722 | 0 | import copy
from ereuse_devicehub.resources.device.schema import Device
from ereuse_devicehub.resources.device. | settings import DeviceSubSettings
class Mobile(Device):
imei = {
'type': 'string',
'unique': True
}
meid = {
'type': 'string',
'unique': True
}
type = {
'type': 'string',
'allowed': {'Smartphone', 'Tablet'},
'required': True
}
manufac... | quired'] = True
model = copy.copy(Device.model)
model['required'] = True
class MobileSettings(DeviceSubSettings):
_schema = Mobile
|
badock/nova | nova/db/discovery/api.py | Python | apache-2.0 | 232,570 | 0.001303 | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file... | consider duplicate host | names '
'invalid within the specified scope, regardless of case. '
'Should be empty, "project" or "global".'),
]
CONF = cfg.CONF
CONF.register_opts(db_opts)
CONF.import_opt('compute_topic', 'nova.compute.rpcapi')
LOG = logging.getLogger(__name__)
_ENGINE_FACADE = None
_LOCK = ... |
pioneers/topgear | python/forseti2/piemos_field_cmd.py | Python | apache-2.0 | 2,272 | 0.007042 | """LCM type definitions
This file automatically generated by lcm.
DO NOT MODIFY BY HAND!!!!
"""
import cStringIO as StringIO
import struct
import header
class piemos_field_cmd(object):
__slots__ = ["header", "isFlash", "isStart", "isLeft", "rfid_uid"]
def __init__(self):
self.header = None
s... | wparents = parents + [piemos_field_cmd]
tmphash = (0x41930ef51bb056ba+ header.header._get_hash_recursive(newparents)) & 0x | ffffffffffffffff
tmphash = (((tmphash<<1)&0xffffffffffffffff) + (tmphash>>63)) & 0xffffffffffffffff
return tmphash
_get_hash_recursive = staticmethod(_get_hash_recursive)
_packed_fingerprint = None
def _get_packed_fingerprint():
if piemos_field_cmd._packed_fingerprint is None:
... |
godlygeek/LightRender | simple_rainbow.py | Python | mit | 807 | 0.006196 | #!/usr/bin/env python
from constants import CARTESIAN_COORDS
import color | sys
import sys
class Pattern(object):
center_x, center_y = 0, 0
i = 0
def next_frame(self):
self.i += 1
def get_color(self, x, y):
d = (x ** 2 + y ** 2) ** 0.5
d *= 0.1 # scale the bands
d -= 0.025 * self.i # frame step size
r, g, b = colorsys.hsv_to_rgb(d%1, 1... | 255 * r
green = 255 * g
blue = 255 * b
c = (int(red), int(green), int(blue))
return c
p = Pattern()
for frame in range(6000):
for x, y in CARTESIAN_COORDS:
color = p.get_color(x, y)
r, g, b = color
sys.stdout.write(chr(r))
sys.stdout.write(chr(g))
... |
Uli1/mapnik | scons/scons-local-2.4.0/SCons/Script/SConscript.py | Python | lgpl-2.1 | 24,468 | 0.002738 | """SCons.Script.SConscript
This module defines the Python API provided to SConscript and SConstruct
files.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), ... | obals
else:
if isinstance(fn, SCons.Node. | Node):
f = fn
else:
f = fs.File(str(fn))
_file_ = None
# Change directory to the top of the source
# tree to make sure the os's cwd and the cwd of
# fs match so we can open the SConscript.
... |
VHAINNOVATIONS/BCDS | Model/scripts/ear_validation/python/aggregateContention.py | Python | apache-2.0 | 9,448 | 0.037786 | import os
import re
import cx_Oracle
import collections
import datetime
earContentionCode = [2200,2210,2220,3140,3150,4130,4210,4700,4920,5000,5010,5710,6850]
#Primary query, Look for all claims/contentions where the participant has at least one contention with an ear-related contention code.
#Organize them based fir... | regateContention.VET_ID, 'CLAIM_ID' :aggregateContention.CLAIM_ID, 'END_PRODUCT_CODE' :aggregateContention.END_PRODUCT_CODE, 'CLAIM_DATE' :aggregateContention.CLAIM_DATE, 'C | ONTENTION_COUNT' :aggregateContention.CONTENTION_COUNT, 'EAR_CONTENTION_COUNT' :aggregateContention.EAR_CONTENTION_COUNT,
'C2200' :counterAggregateContention.C2200, 'C2210' :counterAggregateContention.C2210, 'C2220' :counterAggregateContention.C2220, 'C3140' :counterAggregateContention.C3140, 'C3150' :counterAggreg... |
slarosa/QGIS | python/plugins/sextante/algs/Explode.py | Python | gpl-2.0 | 3,641 | 0.006042 | # -*- coding: utf-8 -*-
"""
***************************************************************************
Explode.py
---------------------
Date : August 2012
Copy | right : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
********** | *****************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foun... |
appsembler/edx-platform | openedx/core/djangoapps/appsembler/settings/settings/production_cms.py | Python | agpl-3.0 | 1,171 | 0.003416 | """
Settings for Appsembler on CMS in Production.
"""
import sentry_sdk
from openedx.core.djangoapps.appsembler.settings.settings import production_common
def plugin_settings(settings):
"""
Appsembler CMS overrides for both production AND devstac | k.
Make sure those are compatible for devstack via defensive coding.
This file, however, won't run in test environments.
"""
production_common.plugin_settings(settings)
settings.APPSEMBLER_SECRET_KEY = settings.AUTH_TOKENS.get("APPSEMBLER_SECRET_KEY")
settings.INTERCOM_APP_ID = settings.AUTH... | OM_APP_ID")
settings.INTERCOM_APP_SECRET = settings.AUTH_TOKENS.get("INTERCOM_APP_SECRET")
settings.FEATURES['ENABLE_COURSEWARE_INDEX'] = True
settings.FEATURES['ENABLE_LIBRARY_INDEX'] = True
settings.ELASTIC_FIELD_MAPPINGS = {
"start_date": {
"type": "date"
}
}
if... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.1/Lib/test/test_bigaddrspace.py | Python | mit | 1,284 | 0.003894 | from test import support
from test.support import bigaddrspacetest, MAX_Py_ssize_t
import unittest
import operator
import sys
class StrTest(unittest.TestCase):
@bigaddrspacetest
def test_concat(self):
s1 = 'x' * MAX_Py_ssize_t
self.assertRaises(OverflowError, operator.add, s1, '?')
@big... | permail/python-dev/2006-July/067774.html)
#@bigaddrspacetest
#def test_repeat(self):
# self.assertRaises(OverflowError, operator.mul, 'x', MAX_Py_ssize_t + 1)
def test_main():
support.run_unittest(StrTest)
if __name__ == '__main__':
if len(sys.argv) > 1:
support.set_memlimit( | sys.argv[1])
test_main()
|
Rediker-Software/litle-sdk-for-python | litleSdkPythonTest/functional/TestAuth.py | Python | mit | 7,012 | 0.011266 | #Copyright (c) 2011-2012 Litle & Co.
#
#Permission is hereby granted, free of charge, to any person
#obtaining a copy of this software and associated documentation
#files (the "Software"), to deal in the Software without
#restriction, including without limitation the rights to use,
#copy, modify, merge, publish, distri... | OnlineRequest(config)
with self.assertRaises(Exception):
litle.sendRequest(authorization)
def testAccountUpdate(self):
authorization = litleXmlFields.authorization()
| authorization.orderId = '12344'
authorization.amount = 106
authorization.orderSource = 'ecommerce'
card = litleXmlFields.cardType()
card.number = "4100100000000000"
card.expDate = "1210"
card.type = 'VI'
card.cardValidationNum = '1213'
auth... |
loanzen/probe-py | probe/tests.py | Python | mit | 1,727 | 0.006369 | import unittest
from probe import SearchApi, CompanyApi
class TestProbeAPI(unittest.TestCase):
def test_search_company_loanzen(self):
api = SearchApi()
companies = api.companies_get('1.1', filters='{"nameStartsWith": "loanzen"}')
#print type(companies.data), companies.data.companies
... | ny = api.companies_cin_get('1.1', 'U24239DL2002PTC114413')
#print company.data.company
self.assertEquals(company.data.company.cin, 'U24239DL2002PTC114413')
def test_get_company_authorized_signatories(self):
api = CompanyApi()
signatories = api.companies_cin_authorized_signatories_ge... | rized_signatories
self.assertFalse(len(signatories.data.authorized_signatories) == 0)
def test_get_company_charges(self):
api = CompanyApi()
charges = api.companies_cin_charges_get('1.1', 'U24239DL2002PTC114413')
#print charges.data.charges
self.assertFalse(len(charges.data.... |
ingenieroariel/inasafe | safe_qgis/keywords_dialog.py | Python | gpl-3.0 | 24,200 | 0.000579 | """
InaSAFE Disaster risk assessment tool developed by AusAid -
**GUI Keywords Dialog.**
Contact : [email protected]
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; ei... | logButtonBox.Ok)
#myButton.setEnabled(False)
self.layer = self.iface.activeLayer()
if self.layer:
self.loadStateFromKeywords()
def showHelp(self):
"""Load the help text for the keywords safe_qgis"""
if not self.helpDialog:
self.helpDialog = Help(self.... | ignature('bool')
def on_pbnAdvanced_toggled(self, theFlag):
"""Automatic slot executed when the advanced button is toggled.
.. note:: some of the behaviour for hiding widgets is done using
the signal/slot editor in designer, so if you are trying to figure
out how the interacti... |
geggo/pyface | pyface/ui/qt4/python_editor.py | Python | bsd-3-clause | 6,248 | 0.004001 | #------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
# However, when used with the GPL version of PyQt the additional terms described in ... | QtGui.QTextCursor.KeepAnchor)
###########################################################################
# Trait handlers.
###########################################################################
def _pa | th_changed(self):
self._changed_path()
def _show_line_numbers_changed(self):
if self.control is not None:
self.control.code.line_number_widget.setVisible(
self.show_line_numbers)
self.control.code.update_line_number_width()
##############################... |
jordanemedlock/psychtruths | temboo/core/Library/Facebook/Actions/Fitness/Walks/UpdateWalk.py | Python | apache-2.0 | 4,891 | 0.005316 | # -*- coding: utf-8 -*-
###############################################################################
#
# UpdateWalk
# Updates an existing walk action.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under th | e 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 distributed on an
# "AS IS" BASIS, WI... |
antoinecarme/pyaf | tests/artificial/transf_Quantization/trend_PolyTrend/cycle_12/ar_12/test_artificial_32_Quantization_PolyTrend_12_12_0.py | Python | bsd-3-clause | 267 | 0.086142 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_ | artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 12, transform = "Quantization", sigma = 0.0, exog_count = 0, ar_order = | 12); |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/traitlets/tests/test_traitlets.py | Python | bsd-2-clause | 66,467 | 0.005793 | # encoding: utf-8
"""Tests for traitlets.traitlets."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
#
# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
# also under the terms of the Modified BSD License.
import pickle
import re
import sys
from ._w... | x = Int(10)
@default('x')
def _default_x(self):
return | 11
class B(A):
x = Int(20)
class C(A):
@default('x')
def _default_x(self):
return 21
a = A()
self.assertEqual(a._trait_values, {})
self.assertEqual(a.x, 11)
self.assertEqual(a._trait_values, {'x': 11})
b = B(... |
sotetsuk/memozo | memozo/memozo.py | Python | mit | 5,664 | 0.002119 | import os
impo | rt functools
import codecs
import pickle
from . import utils
class Memozo(object):
def __init__(self, path='./'):
self.base_path = path
memozo_file | = os.path.join(self.base_path, utils.MEMOZO_FILE_NAME)
if not os.path.exists(memozo_file):
with codecs.open(memozo_file, 'w', encoding=utils.ENCODING) as f:
f.write('datetime\thash\tfile name\tfunction name\tparameters\n')
f.write('--------\t----\t---------\t--------... |
snap-stanford/ogb | ogb/graphproppred/__init__.py | Python | mit | 302 | 0 | from .evaluate import Evaluator
from .dat | aset import GraphPropPredDataset
try:
from .dataset_pyg import PygGraphPr | opPredDataset
except ImportError:
pass
try:
from .dataset_dgl import DglGraphPropPredDataset
from .dataset_dgl import collate_dgl
except (ImportError, OSError):
pass
|
WarmongeR1/feedly-filter | apps/filters/management/commands/load_data.py | Python | mit | 1,534 | 0.001304 | # -*- encoding: utf-8 -*-
import csv
from allauth.socialaccount.models import SocialToken
from django.core.management.base import BaseCommand
from apps.filters.filter import get_api
import os
from django.conf import settings
from yaml import load
from apps.filters.models import Collection, Entry, Category
class Co... | le=item['name'],
)
if not collection.description:
collection.description = item['description']
collection.save()
with open(os.path.join(folde | r, item['file']), 'r') as fio:
reader = csv.DictReader(fio)
for i, row in enumerate(reader):
categories = []
for category in row['category'].split(','):
categories.append(Category.objects.get_or_create(title=category.strip()... |
CtheSky/pycparser | examples/cdecl.py | Python | bsd-3-clause | 6,339 | 0.001893 | #-----------------------------------------------------------------
# pycparser: cdecl.py
#
# Example of the CDECL tool using pycparser. CDECL "explains" C type
# declarations in plain English.
#
# The AST generated by pycparser from the given declaration is traversed
# recursively to build the explanation. Note that th... | """
typ = type(decl)
if typ in (c_ast.Decl, c_ast.TypeDecl, c_ast.PtrDecl, c_ast.ArrayDecl):
decl.type = _expand_in_place(decl.type, file_ast, expand_struct, expand_typedef)
elif typ == c_ast.Struct:
if not decl.decls:
struct = _find_struct(decl.name, file_ast)
i... | raise Exception('using undeclared struct %s' % decl.name)
decl.decls = struct.decls
for i, mem_decl in enumerate(decl.decls):
decl.decls[i] = _expand_in_place(mem_decl, file_ast, expand_struct, expand_typedef)
if not expand_struct:
decl.decls = []
elif (... |
amahabal/PySeqsee | farg/core/exceptions.py | Python | gpl-3.0 | 2,834 | 0.008116 | # Copyright (C) 2011, 2012 Abhijit Mahabal
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later version.
#
# This program is distribu... | When a stopping condition is specified, this indicates that it has been r | eached."""
def __str__(self):
return 'StoppingConditionMet after %d codelets' % self.codelet_count
class SuccessfulCompletion(BatchModeStopException):
"""Raised when the problem has been fully solved.
What fully solved means depends on the application, of course. For Seqsee, this means
currently means "... |
openstack/smaug | karbor/services/operationengine/engine/triggers/timetrigger/__init__.py | Python | apache-2.0 | 1,625 | 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
# d... | ntOpt('trigger_poll_interval',
default=15,
help='Interval, in seconds, in which Karbor will poll for '
| 'trigger events'),
cfg.StrOpt('scheduling_strategy',
default='multi_node',
help='Time trigger scheduling strategy '
)
]
CONF = cfg.CONF
CONF.register_opts(time_trigger_opts)
|
SunPower/pvfactors | pvfactors/geometry/pvrow.py | Python | bsd-3-clause | 31,109 | 0 | """Module will classes related to PV row geometries"""
import numpy as np
from pvfactors.config import COLOR_DIC
from pvfactors.geometry.base import \
BaseSide, _coords_from_center_tilt_length, PVSegment
from shapely.geometry import GeometryCollection, LineString
from pvfactors.geometry.timeseries import \
TsS... | r_illum, with_index=with_surface_index)
def at(self, idx):
"""Generate a PV row geometry for the desired index.
Parameters
----------
idx : int
Index to use to generate PV row geo | metry
Returns
-------
pvrow : :py:class:`~pvfactors.geometry.pvrow.PVRow`
"""
front_geom = self.front.at(idx)
back_geom = self.back.at(idx)
original_line = LineString(
self.full_pvrow_coords.as_array[:, :, idx])
pvrow = PVRow(front_side=front_... |
manasapte/pants | tests/python/pants_test/backend/jvm/tasks/jvm_binary_task_test_base.py | Python | apache-2.0 | 3,154 | 0.006658 | # 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
from pant... | `.
:rtype: :class:`collections.Iterator` of string
| """
for root_dir, _, files in os.walk(dir_path):
for f in files:
yield os.path.relpath(os.path.join(root_dir, f), dir_path)
def ensure_classpath_products(self, context):
"""Gets or creates the classpath products expected by `JvmBinaryTask`.
:API: public
:param context: The pants run c... |
abhiatgithub/shogun-toolbox | examples/undocumented/python_modular/graphical/cluster_kpp.py | Python | gpl-3.0 | 1,891 | 0.050238 | """Graphical example illustrating improvement of convergence of KMeans
when cluster centers are initialized by KMeans++ algorithm.
In this example, 4 vertices of a rectangle are chosen: (0,0) (0,100) (10,0) (10,100).
There are 500 points normally distributed about each vertex.
Therefore, the ideal cluster centers f... | plot(d1[0],d1[1],'rx')
plot(d2[0],d2[1],'bx',hold=True)
plot(d3[0],d3[1],'gx',hold=True)
plot(d4[0],d4[1],'cx',hold=True)
plot(centers[0,:], centers[1,:], 'ko',hold=True)
for i in | xrange(k):
t = linspace(0, 2*pi, 100)
plot(radi[i]*cos(t)+centers[0,i],radi[i]*sin(t)+centers[1,i],'k-', hold=True)
show()
|
mdiller/MangoByte | cogs/utils/logger.py | Python | mit | 962 | 0.025988 | from __main__ import settings
import logging
import datetime
import os
from | pyth | onjsonlogger import jsonlogger
# if we wanna log disnake stuff https://docs.disnake.dev/en/latest/logging.html?highlight=logger
# we can also get the root logger, which will give us a ton of info for all the libraries we have
if not os.path.exists("logs"):
os.makedirs("logs")
def setup_logger():
logger = loggin... |
boooka/GeoPowerOff | venv/lib/python2.7/site-packages/grab/transport/kit.py | Python | apache-2.0 | 4,620 | 0.009307 | # Copyright: 2013, Grigoriy Petukhov
# Author: Grigoriy Petukhov (http://lorien.name)
# License: BSD
from __future__ import absolute_import
#import email
import logging
#import urllib
#try:
#from cStringIO import StringIO
#except ImportError:
#from io import BytesIO as StringIO
#import threading
import random
#... | g(self, grab):
self.request_object['url'] = grab.config['url']
self.request_object['method'] = grab.request_method.lower()
if grab.config['cookiefile']:
grab.load_cookies(grab.config['cookiefile'])
if grab.config['cookies | ']:
if not isinstance(grab.config['cookies'], dict):
raise error.GrabMisuseError('cookies option shuld be a dict')
self.request_object['cookies'] = grab.config['cookies']
if grab.request_method == 'POST':
if grab.config['multipart_post']:
rais... |
thomasleese/gantt-charts | ganttcharts/__init__.py | Python | mit | 56 | 0 | __version__ = '0.1.0'
__de | scription__ = 'Gantt ch | arts!'
|
timbuchwaldt/bundlewrap | bundlewrap/lock.py | Python | gpl-3.0 | 8,144 | 0.002456 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from getpass import getuser
import json
from os import environ
from pipes import quote
from socket import gethostname
from time import time
from .exceptions import NodeLockedException
from .utils import cached_property, temp... | repo.hooks.lock_add(node.repo, node, lock_id, item_selectors, expiry_timestamp, comment)
return lock_id
def softlock_list(node):
if node.os == 'kubernetes':
return []
with io.job(_("{} checking soft locks").format(bold(node.name))):
cat = node.run("cat {}".format(SOFT_LOCK_FILE.format(id... | ecode('utf-8').strip().split("\n"):
try:
result.append(json.loads(line.strip()))
except json.decoder.JSONDecodeError:
io.stderr(_(
"{x} {node} unable to parse soft lock file contents, ignoring: {line}"
).format(
... |
indykish/servo | tests/wpt/harness/wptrunner/executors/process.py | Python | mpl-2.0 | 701 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You c | an obtain one at http://mozilla.org/MPL/2.0/.
from .base import TestExecutor
class ProcessTestExecutor(TestExecutor):
def __init__(self, *args, **kwargs):
TestExecutor.__init__(self, *args, **kwargs)
self.binary = self.browser.binary
self.interactive = self.browser.interactive
def se... | def is_alive(self):
return True
def do_test(self, test):
raise NotImplementedError
|
akademikbilisim/ab-kurs-kayit | abkayit/training/migrations/0005_auto_20160627_1414.py | Python | gpl-3.0 | 1,403 | 0.002851 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('training', '... | blank=True),
),
migrations.AddField(
model_name='trainesscourserecord',
name='modifiedby',
| field=models.ForeignKey(related_name='modifiedby', default=4, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
migrations.AddField(
model_name='trainesscourserecord',
name='modifytimestamp',
field=models.DateField(default=django.utils.timez... |
OCA/server-tools | module_change_auto_install/__init__.py | Python | agpl-3.0 | 29 | 0 | from .patch import pos | t_load
| |
pmart123/censible_links | censible_links/settings.py | Python | bsd-3-clause | 93 | 0 | SPIDER | _MODULES = ['cen | sible_links.spiders']
DEFAULT_ITEM_CLASS = 'censible_links.items.Page'
|
devs1991/test_edx_docmode | common/djangoapps/student/tests/test_login.py | Python | agpl-3.0 | 26,838 | 0.002757 | '''
Tests for student activation and login
'''
import json
import unittest
from django.test import TestCase
from django.test.client import Client
from django.test.utils import override_settings
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.... | self):
# De-activate the user
self.user.is_active = False
self.user.save()
# Should now be unable to login
response, mock_audit_log = self._login_response('[email protected]', 'test_password')
self._assert_response(response, success=False,
value=... | for user'])
@patch.dict("django.conf.settings.FEATURES", {'SQUELCH_PII_IN_LOGS': True})
def test_login_not_activated_no_pii(self):
# De-activate the user
self.user.is_active = False
self.user.save()
# Should now be unable to login
response, mock_audit_log = self._login_... |
bossiernesto/onyx | persistance/documents/json_doc.py | Python | bsd-3-clause | 703 | 0.004267 | try:
import simplejson
except ImportError:
import json as simplejson
from .meta import DocumentMeta, BaseDocumentSession
json_objects = []
class JSONDocument(object):
"""
JSON Document base class
| """
__metaclass__ = DocumentMeta
def __init__(self, **kwargs):
json_objects.append(kwargs)
class Session(BaseDocumentSession):
"""
A class featuring a database session
"""
def commit(self):
"""
Dumps the scraped data to the filesystem
"""
with o... | e, 'w') as f:
simplejson.dump(json_objects, f)
def close(self):
super(Session,self).close()
json_session = Session()
|
teamfx/openjfx-9-dev-rt | modules/javafx.web/src/main/native/Tools/Scripts/webkitpy/layout_tests/servers/web_platform_test_server.py | Python | gpl-2.0 | 9,422 | 0.003927 | # Copyright (c) 2014, Canon Inc. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | in(self._doc_root | , self._filesystem.sep.join(path))).install(url=module["url"], url_subpath=module["url_subpath"], target_name=name)
def _copy_webkit_test_files(self):
_log.debug('Copying WebKit resources files')
for f in self._resources_files_to_copy:
webkit_filename = self._filesystem.join(self._layou... |
fcgravalos/CEES-API-v1.0 | logmessages.py | Python | apache-2.0 | 1,055 | 0.006635 | """
File: logmessages.py
Author: Fernando Crespo Gravalos ([email protected])
Date: 2014/06/16
"""
##############
# LOG MESSAGES
##############
## GENERAL ##
DB_ERROR = 'Database error. Check database log file.'
STORE_NOT_FOUND = 'Could not find store in cees database.'
TOKEN_NOT_FOUND = 'Could not fin... | uest. Schema file not found.'
VALIDATION_ERROR = 'Data not valid.'
## LOGIN ##
LOGGED_IN = 'Shop assistant logged in as '
CREDENTIALS_NOT_FOUND = 'Could not find the email/password provided.'
## ARRIVALS ##
RFID_NOT_FOUND = 'Invalid identifier. RFID not found in cees database.'
CLIENT_NOT_ALLOWED = 'Client does not b... | thentication header in request.'
## GCM AND DEVICE REGISTRATION##
UNKNOWN_DEVICE = 'Device not found in databse.'
REGISTRATION_NOT_FOUND = 'Registration not found in database.' |
kiniou/blender-smooth-slides | tools/lpod/scripts/lpod-style.py | Python | gpl-3.0 | 3,854 | 0.003374 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2009 Ars Aperta, Itaapy, Pierlis, Talend.
#
# Authors: Hervé Cauwelier <[email protected]>
# Romain Gauthier <[email protected]>
#
# This file is part of Lpod (see: http://lpod-project.org).
# Lpod is free software; you can redistribute it and/or m... | 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
#
# Import from the standard library
from optparse import OptionParser
from sys import exit, stdout
# Import from lpod
from lpod import __versi... |
kingoflolz/hearthbreaker | tests/card_tests/shaman_tests.py | Python | mit | 30,173 | 0.002453 | import random
import unittest
from hearthbreaker.cards.spells.neutral import TheCoin
from tests.agents.testing_agents import OneCardPlayingAgent, MinionAttackingAgent, CardTestingAgent, \
PlayAndAttackAgent
from tests.testing_utils import generate_game_for
from hearthbreaker.cards import *
from hearthbreaker.const... | self.assertEqual("Mana Tide Totem", game.players[0].minions[0].card.name)
self.assertEqual(23, game.players[0].deck.left)
game.play_single_turn()
# Silence, we should only draw one card next turn
game.players[0]. | minions[0].silence()
game.play_single_turn()
self.assertEqual(1, len(game.players[0].minions))
self.assertEqual(22, game.players[0].deck.left)
def test_UnboundElemental(self):
game = generate_game_for([UnboundElemental, DustDevil, DustDevil], StonetuskBoar, OneCardPlayingAgent,
... |
cwolferh/heat-scratch | heat/tests/openstack/manila/test_share.py | Python | apache-2.0 | 9,631 | 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
# ... | ol" + message_end)
se | lf.assertEqual(1, kwargs["size"], "Share size" + message_end)
self.assertEqual("basic_test_share", kwargs["name"],
"Share name" + message_end)
self.assertEqual("basic test share", kwargs["description"],
"Share description" + message_end)
self.ass... |
horstjens/ThePythonGameBook | en/python/battleship/chat_server.py | Python | gpl-3.0 | 3,173 | 0.007249 | #!/usr/bin/env python3
"""Server for multithreaded (asynchronous) chat application."""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept() # c... | 8"))
break
if message.lower()=="a2" and Game.turn % 2 == index:
broadcast("mfires at A2", "player{}({})".format(index+1, name))
Game.turn += 1
broadcast("turn {}. It is your turn, player{}".format(Game.turn, index+1))
else:
broadcast(message, "... | converts msg to bytes if necessary"""
msg2 = msg if isinstance(msg, bytes) else bytes(msg, 'utf8')
for sock in clients:
#sock.send(bytes(prefix, "utf8") + msg)
#print("message:", msg, type(msg))
#print("prefix:", prefix)
sock.send(bytes(prefix, "utf8") + msg2)
class Game:
tu... |
tchar/pushbots | pushbots/examples/analytics.py | Python | mit | 1,805 | 0 | # -*- coding: utf-8 -*-
"""
The following examples are used to demonstrate how to get/record
analytics
The method signatures are:
Pushbots.get_analytics()
and
Pushbots.record_analytics(platform=None, data=None)
In which you must specify either platform or data.
"""
from pushbots import Pushbots
def example_get_an... | et = 'my_secret'
# Create a Pushbots instance
pushbots = Pushbots(app_id=my_app_id, secret=my_secret)
# Define data
data = {'platform': '0'} # '0' is Equivalent to Pushbots.PLATFORM_IOS
| code, message = pushbots.record_analytics(data=data)
print('Returned code: {0}'.format(code))
print('Returned message: {0}'.format(message))
|
ddurieux/alignak | alignak/eventhandler.py | Python | agpl-3.0 | 6,318 | 0.002375 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free So... | e'),
'is_snapshot': BoolProp(default=False),
}
# id = 0 #Is common to Actions
def __init__(self, command, id=None, ref=None, timeout=10, env={},
module_type='fork', reactionner_tag='None', is_snapshot=False):
self.is_a = 'eventhandler'
self.type = ''
sel... | ll only
self.id = Action.id
Action.id += 1
self.ref = ref
self._in_timeout = False
self.timeout = timeout
self.exit_status = 3
self.command = command
self.output = ''
self.long_output = ''
self.t_to_go = time.time()
self.che... |
JulienMcJay/eclock | windows/kivy/kivy/tests/test_audio.py | Python | gpl-2.0 | 1,707 | 0.000586 | '''
Audio tests
===========
'''
import unittest
import os
SAMPLE_FILE = os.path.join(os.path.dirname(__file__), 'sample1.ogg')
SAMPLE_LENGTH = 1.402
SAMPLE_LENGTH_MIN = SAMPLE_LENGTH * 0.99
SAMPLE_LENGTH_MAX = SAMPLE_LENGTH * 1.01
class AudioTestCase(unittest.TestCase):
def get_sound(self):
import os
... | (self):
sound = self.get_sound()
volume = sound.volume = 0.75
length = sound.length
assert SAMPLE_LENGTH_MIN <= length <= SAMPLE_LENGTH_MAX
# ensure that the gstreamer play/stop doe | sn't mess up the volume
assert volume == sound.volume
def test_length_playing(self):
import time
sound = self.get_sound()
sound.play()
try:
time.sleep(0.1)
length = sound.length
assert SAMPLE_LENGTH_MIN <= length <= SAMPLE_LENGTH_MAX
... |
wikimedia/pywikibot-core | pywikibot/scripts/version.py | Python | mit | 3,279 | 0 | #!/usr/bin/python3
"""Script to determine the Pywikibot version (tag, revision and date).
.. versionchanged:: 7.0
version script was moved to the framework scripts folder
"""
#
# (C) Pywikibot team, 2007-2021
#
# Distributed under the terms of the MIT license.
#
import codecs
import os
import sys
import pywikibot
... | tr) -> None:
"""Print pywikibot version and important settings."""
pywikibot.output('Pywikibot: ' + getversion())
pywikibot.output('Release version: ' + pywikibot.__version__)
pywikibot.output('setuptools version: ' + setuptools.__version__)
pywikibot.output('mwparserfromhell version: '
... | s_wikimedia_cert = False
if (not hasattr(requests, 'certs')
or not hasattr(requests.certs, 'where')
or not callable(requests.certs.where)):
pywikibot.output(' cacerts: not defined')
elif not os.path.isfile(requests.certs.where()):
pywikibot.output(' cacerts: {} (missing... |
Salamek/DwaPython | tests/UserTest.py | Python | gpl-3.0 | 4,776 | 0.012772 | # Copyright (C) 2014 Adam Schubert <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Th... | lf):
params = {}
params['password'] = self.credential['password']
params['username | '] = self.username
params['nickname'] = DwaTestCase.generateNickname()
params['email'] = self.username + '@divine-warfare.com'
params['active'] = True
#create
message = self.user.create(params)['message']
#delete
userData = self.user.token({'password': params['password'], 'username': pa... |
brnomendes/grader-edx | Core/Ranking.py | Python | mit | 564 | 0.003546 | from Models.Submission i | mport Submission
from Core.Database import Database
from Core.Scorer import Score
from sqlalchemy import func, desc
class Ranking():
@staticmethod
def get_all():
session = Database.session()
scores = session.query(Score).order_by(desc(Score.score)).all()
return [{"student_id": s.stud... | .filter(Submission.student_id == s.student_id).scalar(),
"score": s.score}
for s in scores]
|
hbradleyiii/ww | ww/settings.py | Python | mit | 2,079 | 0.005772 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# name: settings.py
# author: Harold Bradley III
# email: [email protected]
# created on: 01/23/2016
#
# description: The settings file for | ww
#
from __future__ import | absolute_import, print_function
import os
import time
TEMPLATE_PATH = os.path.dirname(os.path.realpath(__file__)) + '/../templates/'
## Change these settings to your hearts content ##
# Site Settings
SITE_ADMIN_EMAIL = '[email protected]'
SITE_ERROR_LOG = 'error.log'
SITE_ACCESS_LOG = 'access.log'
WWW_DIR = '/var/... |
sniemi/SamPy | sandbox/src1/TCSE3-3rd-examples/src/tools/fileaction.py | Python | bsd-2-clause | 3,008 | 0.006981 | #!/usr/bin/env python
"""
fileaction.py 'display' '*.ps' '*.jpg' '*.gif'
creates a GUI with a list of all PostScript, JPEG, and GIF files in
the directory tree with the current working directory as root.
Clicking on one of the filenames in the list launches the display
program, which displays the image file.
As ano... | or 'multiple'
vscrollmode='dynamic', hscrollmode='dynamic',
listbox_width=min(max([len(f) for f in self.files]),40),
listbox_height=min(len(self.files),20),
label_text='files', labelpos='n',
items=self.files,
selectioncommand=self.select)
... | , padx=10, expand=True, fill='both')
self.command = StringVar(); self.command.set(command)
Pmw.EntryField(self.top,
labelpos='w', label_text='process file with',
entry_width=len(command)+5,
entry_textvariable=self.command).pack(side='top',pady=3)
Button(self.... |
gwpy/gwpy.github.io | docs/v0.5/examples/frequencyseries/variance-3.py | Python | gpl-3.0 | 260 | 0.003846 | plot = variance.plot(norm='log', vmin=.5, cmap='plasma')
ax = plot.gca()
ax.grid()
ax.set_xlim(20, 1500)
ax.set_ylim(1e-24, 1e-20)
ax.set_xlabel( | 'Frequency [Hz]')
ax.set_ylabel(r'[strain/\rtHz]')
ax.set_title('LIGO-Living | ston sensitivity variance')
plot.show() |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractXiaoyuusTranslations.py | Python | bsd-3-clause | 244 | 0.028689 | def extractXiaoyuusTranslations(item):
"""
Xiaoyuu's Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp | or vol or frag) or 'preview' in item['title'].lower():
return None
return Fa | lse
|
nikste/visualizationDemo | zeppelin-web/node/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py | Python | apache-2.0 | 3,325 | 0.002105 | # Copyright (c) 2011 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.
"""gypd output module
This module produces gyp input as its output. Output files are given the
.gypd extension to avoid overwriting the .gyp files that they are ... | ons already
performed and the relevant constructs not present in the output; paths to
dependencies may be wrong; and various sections that do not belong in .gyp
files such as such as "included_files" and "*_excluded" will be present.
Output will also be stripped of comments. Thi | s is not intended to be a
general-purpose gyp pretty-printer; for that, you probably just want to
run "pprint.pprint(eval(open('source.gyp').read()))", which will still strip
comments but won't do all of the other things done to this module's output.
The specific formatting of the output generated by this module is su... |
fedelemantuano/thug | thug/ActiveX/modules/SymantecBackupExec.py | Python | gpl-2.0 | 2,143 | 0.0056 | # Symantec BackupExec
# | CVE-2007-6016,CVE-2007-6017
import logging
| log = logging.getLogger("Thug")
def Set_DOWText0(self, val):
self.__dict__['_DOWText0'] = val
if len(val) > 255:
log.ThugLogging.log_exploit_event(self._window.url,
"Symantec BackupExec ActiveX",
"Overflow in property... |
emreg00/biana | biana/ext/networkx/readwrite/edgelist.py | Python | gpl-3.0 | 5,622 | 0.011028 | """
**********
Edge Lists
**********
Read and write NetworkX graphs as edge lists.
"""
__author__ = """Aric Hagberg ([email protected])\nDan Schult ([email protected])"""
# Copyright (C) 2004-2008 by
# Aric Hagberg <[email protected]>
# Dan Schult <[email protected]>
# Pieter Swart <[email protected]>
#... | G.name))
def make_str(t):
if is_string_like(t): return t
return str(t)
for e in G.edges(data=True):
fh.write(delimiter.join(map(make_str,e))+"\n")
#if G.multigraph:
# u,v,datalist=e
# for d in datalist:
# fh.write(delimiter.join(map(make_str... | s="#", delimiter=' ',
create_using=None, nodetype=None, edgetype=None):
"""Read a graph from a list of edges.
Parameters
----------
path : file or string
File or filename to write.
Filenames ending in .gz or .bz2 will be uncompressed.
comments : string, optional
... |
WmHHooper/aima-python | submissions/Flanagin/myKMeans.py | Python | mit | 54,288 | 0.000037 | school_scores = [
[2.2, 1032, 1253, 188, 0],
[1.9, 671, 1622, 418, 12],
[2.1, 3854, 7193, 1184, 16],
[2.2, 457, 437, 57, 0],
[1.8, 25546, 84659, 18839, 240],
[2.2, 2736, 4312, 732, 12],
[2.1, 2646, 17108, 4338, 105],
[1.8, 956, 2718, 731, 19],
[1.8, 316, 1493, 643, 13],
[1.8, 154... | 0],
[2, 32111, 94493, 22337, 337],
[2.3, 2596, 3347, 507, 7],
[2.3, 3342, 18794, 4543, 145],
[1.8, 1131, 3033, 829, 23],
[2.1, 404, 1702, 870, 24],
[1.9, 17485, 45804, 10011, 179],
[1.9, 10676, 30509, 6237, 77],
[2.2, 1260, 3696, 1009, 27],
[2.1, 887, 1012, 189, | 8],
[2.2, 2439, 2629, 344, 17],
[2.4, 7147, 19999, 6524, 168],
[3, 423, 201, 37, 0],
[2.8, 699, 495, 75, 2],
[2.2, 1057, 797, 101, 1],
[2.1, 713, 775, 127, 4],
[2.3, 1833, 6753, 2452, 215],
[2.3, 6848, 21354, 6662, 209],
[2.1, 5585, 30307, 8499, 357],
[2.3, 2054, 1393, 185, 5],
... |
buxx/synergine | tests/src/event/LonelinessSuicideAction.py | Python | apache-2.0 | 402 | 0.002488 | from synergine.synergy.event.Action import Action
from tests.src.event.LonelinessSuicideEvent import LonelinessSuicideEvent
from tests.src.event.TooMuchBeansAction import TooMuchBeansAction
class LonelinessSuicideAction(Action):
_listen = LonelinessSuicideEvent
_depend = | [TooMuchBeansAction]
def run(self, | obj, context, synergy_manager):
obj.get_collection().remove_object(obj) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.