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 |
|---|---|---|---|---|---|---|---|---|
qiita-spots/qiita_client | qiita_client/util.py | Python | bsd-3-clause | 2,813 | 0 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | Parameters
----------
mapping_file : str
The mapping file
Returns
-------
dict
Dict mapping run_prefix to sample id
Raises
------
ValueError
| If there is more than 1 sample per run_prefix
"""
logger.debug('Entered get_sample_names_by_run_prefix()')
qiime_map = pd.read_csv(mapping_file, delimiter='\t', dtype=str,
encoding='utf-8', keep_default_na=False,
na_values=[])
qiime_map.set_index... |
ducksboard/libsaas | libsaas/services/pipedrive/deals.py | Python | mit | 5,710 | 0 | from libsaas import http, parsers
from libsaas.services import base
class Products(base.RESTResource):
path = 'products'
@base.apimethod
def get(self, start=None, limit=None):
"""
Lists products attached to a deal.
Upstream documentation:
https://developers.pipedrive.com... | return http.Request('GET', url, params), parsers.parse_json
@base.apimethod
def files(self, start=None, limit=None):
"""
Lists files associated with a deal.
Upstream documentatio | n:
https://developers.pipedrive.com/v1#methods-Deals
"""
params = base.get_params(None, locals())
url = '{0}/files'.format(self.get_url())
return http.Request('GET', url, params), parsers.parse_json
@base.resource(Products)
def products(self):
"""
Returns... |
VirrageS/io-kawiarnie | caffe/employees/views.py | Python | mit | 2,869 | 0 | """Module with views for the employee feature."""
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required, permission_required
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect, render
from... | 'form': form,
'employee': employee
})
@permission_required('employees.delete_employee')
def employees_delete_employee(request, employee_id):
"""Delete an employee."""
employee = get_object_or_404(
Employee,
id=employee_id,
caffe=request.user.caffe
)
if empl | oyee == request.user:
messages.error(request, u'Nie możesz usunąć siebie.')
return redirect(reverse('employees:navigate'))
employee.delete()
messages.success(request, u'Pracownik został poprawnie usunięty.')
return redirect(reverse('employees:navigate'))
@permission_required('employees.vi... |
CollabQ/CollabQ | vendor/django/conf/global_settings.py | Python | apache-2.0 | 14,562 | 0.00206 | # Default Django settings. Override these with settings in the module
# pointed-to by the DJANGO_SETTINGS_MODULE environment variable.
# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
gettext_noop = lambda s: s
#################... | DEFAULT_CHARSET = 'utf-8'
# Encoding of files read from disk (template and initial SQL file | s).
FILE_CHARSET = 'utf-8'
# E-mail address that error messages come from.
SERVER_EMAIL = 'root@localhost'
# Whether to send broken-link e-mails.
SEND_BROKEN_LINK_EMAILS = False
# Database connection info.
DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_... |
rubik/radon | radon/visitors.py | Python | mit | 14,879 | 0 | '''This module contains the ComplexityVisitor class which is where all the
analysis concerning Cyclomatic Complexity is done. There is also the class
HalsteadVisitor, that counts Halstead metrics.'''
import ast
import collections
import operator
# Helper functions to use in combination with map()
GET_COMPLEXITY = ope... | not self.no | _assert
def visit_AsyncFunctionDef(self, node):
'''Async function definition is the same thing as the synchronous
one.
'''
self.visit_FunctionDef(node)
def visit_Fu |
yangming85/lettuce | tests/functional/language_specific_features/test_ja.py | Python | gpl-3.0 | 6,962 | 0.005402 | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc達o <gabriel@nacaolivre.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import dirname, abspath, join
from nose.tools import with_se | tup
from tests.asserts import prepare_stdout
from tests.asserts import assert_stdout_lines
from lettuce import Runner
current_dir = abspath(dirname(__file__))
join_path = lambda *x: join(current_dir, *x)
@with_setup(prepare_stdout)
def test_output_with_success_colorless():
"Language: ja -> sucess colorless"
... |
dunkhong/grr | grr/server/grr_response_server/output_plugins/__init__.py | Python | apache-2.0 | 668 | 0.002994 | #!/usr/bin/env python
"""Output plugins implementations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_lit | erals
from grr_response_server import output_plugin
# pylint: disable=unused-import,g-import-not-at-top
try:
from grr_response_server.output_plugins import bigquery_plugin
except ImportError:
pass
from grr_response_server.output_plugins import csv_plu | gin
from grr_response_server.output_plugins import email_plugin
from grr_response_server.output_plugins import splunk_plugin
from grr_response_server.output_plugins import sqlite_plugin
from grr_response_server.output_plugins import yaml_plugin
|
aronsky/home-assistant | homeassistant/helpers/storage.py | Python | apache-2.0 | 8,433 | 0.00083 | """Helper to help store data."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from contextlib import suppress
from json import JSONEncoder
import logging
import os
from typing import Any
from homeassistant.const import EVENT_HOMEASSISTANT_FINAL_WRITE
from homeassistant.core i... | self.hass.data:
self.hass.data[STORAGE_SEMAPHORE] = asyncio.Semaphore(MAX_LOAD_CO | NCURRENTLY)
try:
async with self.hass.data[STORAGE_SEMAPHORE]:
return await self._async_load_data()
finally:
self._load_task = None
async def _async_load_data(self):
"""Load the data."""
# Check if we have a pending write
if self._dat... |
superstack/nova | nova/scheduler/api.py | Python | apache-2.0 | 9,884 | 0.001012 | # Copyright (c) 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 requi... | , either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Handles all requests relating to schedulers.
"""
import novaclient
from nova import db
from nova import excep | tion
from nova import flags
from nova import log as logging
from nova import rpc
from eventlet import greenpool
FLAGS = flags.FLAGS
flags.DEFINE_bool('enable_zone_routing',
False,
'When True, routing to child zones will occur.')
LOG = logging.getLogger('nova.scheduler.api')
def _call_scheduler(method, cont... |
qutip/qutip | qutip/tests/test_mkl.py | Python | bsd-3-clause | 3,447 | 0 | import pytest
import numpy as np
import scipy.linalg
import scipy.sparse
import qutip
if qutip.settings.has_mkl:
from qutip._mkl.spsolve import mkl_splu, mkl_spsolve
pytestmark = [
pytest.mark.skipif(not qutip.settings.has_mkl,
reason='MKL extensions not found.'),
]
class Test_spsolve... | 0, 1],
[0, 2, 0],
[0, 0, 0],
| ], dtype=dtype)
sX = mkl_spsolve(sM, N, verbose=True)
X = scipy.linalg.solve(M, N)
np.testing.assert_allclose(X, sX)
def test_rhs_shape_is_maintained(self):
A = scipy.sparse.csr_matrix(np.array([
[1, 0, 2],
[0, 0, 3],
[-4, 5, 6],
]... |
mitchcapper/mythbox | resources/lib/mysql-connector-python/python3/examples/engines.py | Python | gpl-2.0 | 1,836 | 0.002179 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most... | # <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public Lice | nse as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have rece... |
rjw57/edpcmentoring | docs/conf.py | Python | mit | 10,393 | 0.005966 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# EDPC Mentoring Database documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 28 23:28:25 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are pres... | opyright = '2016, EDPC'
author = 'EDPC'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1.0'
# The full version, including alpha/beta/rc tags.
release = ... | 0.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |to... |
superisaac/django-mljson-serializer | django_mljson/serializer.py | Python | mit | 2,206 | 0.001813 | """
Serialize data to/from JSON
"""
# Avoid shadowing the standard library json module
from __future__ import absolute_import, unicode_literals
import datetime
import decimal
import json
import sys
import uuid
from io import BytesIO
from django.core.serializers.base import DeserializationError
from django.core.seria... | lf.options.update({'use_decimal': False})
self._current = None
self.json_kwarg | s = self.options.copy()
self.json_kwargs.pop('stream', None)
self.json_kwargs.pop('fields', None)
def start_serialization(self):
self._init_options()
def end_serialization(self):
'''
Do nothing
'''
def end_object(self, obj):
# self._current has ... |
RevansChen/online-judge | Codewars/7kyu/build-a-square/Python/test.py | Python | mit | 191 | 0.005236 | # Python - 3.6.0
test.assert_equals(generateShape(3), '+++\n+++\n+++')
test.assert_equals(genera | teShape(8), '++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++++++++\n++ | ++++++')
|
jek/flatland | flatland/schema/base.py | Python | mit | 29,692 | 0.000404 | # -*- coding: utf-8; fill-column: 78 -*-
import collections
import itertools
import operator
from flatland.schema.paths import pathexpr
from flatland.signals import validator_validated
from flatland.util import (
Unspecified,
assignable_class_property,
class_cloner,
named_int_factory,
symbol,
)
... | ot be changed by skipping.
Unless otherwise set, the child elements will retain the default value
(:obj:`Unevaluated`). Only meaningful during a decent validation. Functions
as ``False`` on upward validation.
""")
Unevaluated = named_int_factory('Unevaluated', True, doc="""\
A psuedo-boolean representing a presumptiv... | newly created elements that have never been evaluated by
:meth:`Element.validate`. Evaluates to true.
""")
# TODO: implement a lighter version of the xml quoters
xml = None
class _BaseElement(object):
# Required by the genshi support's __bases__ manipulation, unfortunately.
pass
class Element(_BaseElement... |
TribeMedia/synapse | tests/util/test_lrucache.py | Python | apache-2.0 | 7,584 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 applica... | cense.
from .. import unittest
from synapse.util.caches.lrucache import LruCache
from synapse.util.caches.treecache import TreeCache
from mock import Mock
class LruCacheTestCase(unittest.TestCase):
def test_get_set(self):
cache = LruCache(1)
cache["key"] = "value"
self.assertEquals(ca... | self.assertEquals(cache.get(1), 1)
self.assertEquals(cache.get(2), 2)
cache[3] = 3
self.assertEquals(cache.get(1), None)
self.assertEquals(cache.get(2), 2)
self.assertEquals(cache.get(3), 3)
def test_setdefault(self):
cache = LruCache(1)
self.assertE... |
inkfountain/learn-py-a-little | lesson_file/lesson.py | Python | gpl-2.0 | 1,662 | 0.011044 | # 1、`if __name__ == "__main__":`
'''
__name__是指示当前py文件调用方式的方法。
如果它等于"__main__"就表示是直接执行,如果不是,则用来被别的文件调用。
一般写在文件的最后。
查看format.py和wordsCount.py的布局
'''
# 2、函数
'''
查看format.py中的formatLines函数
def xxx():
# 函数体
'''
# 3、if条件语句
'''
if xx:
# xxx
elif xxx:
# xxx
elif xxx:
# xxx
else:
# xxx
`else` 表示剩下的所有情况,该... | 到最后,可以没有该分支
`elif` 可以有多个,也可以只有一个,也可以没有
'''
# 4、列表
'''
列表是中括号包裹,并以逗号分隔的一系列值的集合,举例:
'''
numList = [3, 4, 5, 6, 7]
strList = ['he ', 'is ', 'a ', 'dog']
dList = [[3,4], [5,6]] # 列表组成的类表
# 4、for循环
'''
对列表numList遍历,并打印出所有的值
'''
for i in numList:
print i
# 5、文件读写
infile = open(r'd:\\a.txt', 'r') # 'r' 表示读取文件;infile代表打开... | outfile.txt', 'w') # 'r' 表示读取文件;outfile代表将要写内容的文件
outfile.write('hello world' + '\n') # 向文件中写入内容
outfile.close() # 关闭文件
# 6、练习
'''
对文档words.txt,分别统计以小写字母a、b、c开头的单词的个数, 在wordsCount.py的基础上开发
注:这里涉及到读文件,读出来的内容是一个字符串的数组,然后统计需要通过遍历方式进行
'''
|
stuckj/dupeguru | core/tests/ignore_test.py | Python | gpl-3.0 | 4,306 | 0.019508 | # Created By: Virgil Dupras
# Created On: 2006/05/02
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | red('foo','ba | r')
assert not il.AreIgnored('bar','foo')
eq_(0,len(il))
def test_add_same_twice():
il = IgnoreList()
il.Ignore('foo','bar')
il.Ignore('bar','foo')
eq_(1,len(il))
def test_save_to_xml():
il = IgnoreList()
il.Ignore('foo','bar')
il.Ignore('foo','bleh')
il.Ignore('bleh','bar')
... |
tvictor20/tvictor-advprog | aquaponics/app.py | Python | gpl-3.0 | 1,404 | 0.003561 | import time
import RPi.GPIO as GPIO
from flask import Flask, render_template
# GPIO and Sensors ===== | =======================================================
# Objects to represent sensors used to get water level
class WaterLevelSensor:
# how high the sensor is above the top of the fish tank
| offset = 0
def __init__(self, echo, trig):
self.echo_pin = echo
self.trig_pin = trig
GPIO.setup(self.trig_pin, GPIO.OUT, initial=0)
GPIO.setup(self.echo_pin, GPIO.IN)
# gets the time it took for the sound to return, in microseconds
def pulse_in(self):
GPIO.outpu... |
LeBarbouze/tunacell | tunacell/base/cell.py | Python | mit | 15,188 | 0.00079 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This module defines how cells are stored as tunacell's objects
"""
from __future__ import print_function
import numpy as np
import warnings
import treelib as tlib
from tunacell.base.observable import Observable, FunctionalObservable
from tunacell.base.datatools impo... | st_build(self, obs):
"""Protect current cell against building obs array/value"""
self._protected_against_build.add(obs)
return
def build(self, obs):
"""Builds timeseries"""
if obs in self._protected_against_build:
return
if isinstance(obs, FunctionalObser... | d every single Observable
for item in obs.observables:
self.build(item)
arrays = [self._sdata[item.label] for item in obs.observables]
self._sdata[obs.label] = obs.f(*arrays)
elif isinstance(obs, Observable):
if obs.mode == 'dynamics':
... |
sirk390/coinpy | coinpy-lib/src/coinpy/lib/vm/opcode_impl/disabled.py | Python | lgpl-3.0 | 341 | 0.008798 | from co | inpy.model.scripts.opcodes import OP_2DIV, OP_2MUL, OP_AND, OP_CAT,\
OP_DIV, OP_INVERT, OP_LSHIFT, OP_LEFT, OP_MOD, OP_OR, OP_RIGHT, OP_RSHIFT,\
OP_SUBSTR, OP_XOR, OP_MUL
DISABLED_OPCODES=[OP_CAT, OP_SUBSTR, OP_LEFT, OP_RIGHT, OP_INVERT, OP_AND, O | P_OR, OP_XOR, OP_2MUL, OP_2DIV, OP_MUL, OP_DIV, OP_MOD, OP_LSHIFT, OP_RSHIFT] |
zenoss/ZenPacks.zenoss.Puppet | ZenPacks/zenoss/Puppet/BatchDeviceLoader.py | Python | gpl-2.0 | 26,792 | 0.003844 | ##############################################################################
#
# Copyright (C) Zenoss, Inc. 2009, 2011, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
###############################... | evice: DMD device object
@parameter device_specs: device creation dictionary
@type device_specs: dictionary
"""
self.log.debug( "Applying zProperties..." )
# Returns a list of (key | , value) pairs.
# Convert it to a dictionary.
dev_zprops = dict( device.zenPropertyItems() )
for zprop, val |
ch710798472/GithubRecommended | RecGithub/views.py | Python | mit | 3,774 | 0.014168 | #coding:utf-8
from django.shortcuts import render
# Create your views here.
from django.http import HttpRespons | e
# 引入我们创建的表单类
from models import SearchForm,SearchRepoForm,ConnectForm
import requests
import json
from chgithub import GetSearchInfo,SearchRepo,SocialConnect,SearchConnect,nonSocialConnect
def index(request):
return render(request, 'index.html')
def add(request, a, b):
c = int(a) + int(b)
return HttpResp... | od == 'POST': # 当提交表单时
form = SearchForm(request.POST) # form 包含提交的数据
if form.is_valid(): # 如果提交的数据合法
location = form.cleaned_data['location']
language = form.cleaned_data['language']
Dict = {'filename':location+language}
if GetSearchInfo(location,l... |
SciTools/iris | lib/iris/tests/unit/fileformats/abf/test_ABFField.py | Python | lgpl-3.0 | 1,558 | 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 `iris.fileformats.abf.ABFField` class."""
# Import iris.tests first so that some things can be initialis... | return False
class Test_data(tests.IrisTest):
def test_single_read(self):
path = "0000000000000000ja | n00000"
field = ABFField(path)
with mock.patch("iris.fileformats.abf.np.fromfile") as fromfile:
with MethodCounter("__getattr__") as getattr:
with MethodCounter("_read") as read:
field.data
fromfile.assert_called_once_with(path, dtype=">u1")
... |
guitarmanj/king-phisher | king_phisher/client/mailer.py | Python | bsd-3-clause | 38,476 | 0.023365 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/client/mailer.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, th... | ] = utilities.make_message_uid(
upper=uid_charset['upper'],
lower=uid_charset['lower'],
digits=uid_charset['digits']
)
target = MessageTarget(line=line_no, **raw_target)
# the caller needs to catch and process the missing fields appropriately
yield target
| target_file_h.close()
def count_targets_file(target_file):
"""
Count the number of valid targets that the specified file contains. This
skips lines which are missing fields or where the email address is invalid.
:param str target_file: The path the the target CSV file on disk.
:return: The number of valid target... |
youfoh/webkit-efl | Tools/Scripts/webkitpy/layout_tests/servers/apache_http_server.py | Python | lgpl-2.1 | 8,511 | 0.005522 | #!/usr/bin/env python
# Copyright (C) 2011 Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ... | quence.
# FIXME: I | t's unclear if this is still needed.
self._start_cmd = " ".join(start_cmd)
self._stop_cmd = " ".join(stop_cmd)
def _get_apache_config_file_path(self, test_dir, output_dir):
"""Returns the path to the apache config file to use.
Args:
test_dir: absolute path to the LayoutTes... |
lucasplus/MABDI | scripts/Plot_Depth_Image_To_Z.py | Python | bsd-3-clause | 4,777 | 0.000837 | import vtk
import numpy as np
import matplotlib.pyplot as plt
def vtkmatrix_to_numpy(matrix):
m = np.ones((4, 4))
for i in range(4):
for j in range(4):
m[i, j] = matrix.GetElement(i, j)
return m
"""
Get transformation from viewpoint coordinates to
real-world coordinates. (tmat)
"""
... | tio(),
0.0, 1.0)
vtktmat.Invert()
tmat = vtkmatrix_to_numpy(vtktmat)
""" Plot """
plt.figure(frameon=False, dpi=100)
nvalues = 100
noise = 0.002
# vpc - view point coordinates
# wc - world coordinates
vpc = np.zeros((4, nvalues))
vpc[2, :] = np.linspace(0, 1, nvalues)
vpc[3, :] = np.ones((1, vpc.shape[1]))
wc =... | size=2, markerfacecolor='g')
# nvpc, nwc - same as vpc, wc but with noise
nvpc = vpc.copy()
nvpc[2, :] += noise
nwc = np.dot(tmat, nvpc)
nwc = nwc / nwc[3]
nwz = nwc[2, :]
# plt.plot(vpc[2, :],
# nwz,
# color='r')
# nvpc, nwc - same as vpc, wc but with noise
nvpc = vpc.copy()
nvpc[2, :] -= noise
nw... |
nypdmax/NUMA | tools/qemu-xen/tests/qemu-iotests/qcow2.py | Python | gpl-2.0 | 7,287 | 0.009332 | #!/usr/bin/env python
import sys
import struct
import string
class QcowHeaderExtension:
def __init__(self, magic, length, data):
self.magic = magic
self.length = length
self.data = data
@classmethod
def create(cls, magic, data):
return QcowHeaderExtension(magic, len(da... | , '%d', 'header_length' ],
];
fmt = '>' + ''.join(field[0] for field in fields)
def __init__(self, fd):
buf_size = struct.calcsize(QcowHeader.fmt)
fd.seek(0)
buf = fd.read(buf_size)
header = struct.unpack(QcowHeader.fmt, buf)
self.__dict__ = dict((field[2], hea... | ster_bits
fd.seek(self.header_length)
self.load_extensions(fd)
if self.backing_file_offset:
fd.seek(self.backing_file_offset)
self.backing_file = fd.read(self.backing_file_size)
else:
self.backing_file = None
def set_defaults(self):
if s... |
hectormartinez/rougexstem | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/classify/weka.py | Python | apache-2.0 | 8,796 | 0.004093 | # Natural Language Toolkit: Interface to Weka Classsifiers
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: naivebayes.py 2063 2004-07-17 21:02:24Z edloper $
import time, tempfi... | lf, labels, features):
"""
@param labels: A list of all labels that can be generated.
@param features: A list of feature specifications, whe | re
each feature specification is a tuple (fname, ftype);
and ftype is an ARFF type string such as NUMERIC or
STRING.
"""
self._labels = labels
self._features = features
def format(self, tokens):
return self.header_section() + self.data_section(tok... |
agry/NGECore2 | scripts/mobiles/talus/sickly_decay_mite_queen.py | Python | lgpl-3.0 | 1,557 | 0.026975 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate... |
templates = Vector()
templates.add('object/mobile/shared_bark_mite_hue.iff')
mobileTemplate.setTemplates(templates)
|
weaponTemplates = Vector()
weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic')
weaponTemplates.add(weapontemplate)
mobileTemplate.setWeaponTemplateVector(weaponTemplates)
attacks = Vector()
attacks.add('bm_bite_4')
attacks.a... |
philgyford/django-ditto | ditto/twitter/management/commands/fetch_twitter_accounts.py | Python | mit | 1,562 | 0 | # coding: utf-8
from django.core.management.base import BaseCommand
from ...fetch.fetchers import VerifyFetcher
class Command(BaseCommand):
"""Updates the stored data about the Twitter user for one or all Accounts.
For one account:
./manage.py fetch_accounts --account=philgyford
For all accounts:
... |
# results should be a list of dicts, either:
# { 'account': 'thescreenname',
# 'success': True
# }
# or:
# { 'account': 'thescreenname',
# 'success': False,
# 'messages': ["This screen_name doesn't exist"]
# }
if options.get("verbos... | if result["success"]:
self.stdout.write("Fetched @%s" % result["account"])
else:
self.stderr.write(
"Could not fetch @%s: %s"
% (result["account"], result["messages"][0])
)
|
neilLasrado/erpnext | erpnext/patches/v13_0/update_advance_received_in_sales_order.py | Python | gpl-3.0 | 300 | 0.01 | import frappe
def execute():
frappe.reload_doc("selling", "doctype", "sales_order | ")
docs = frappe.get_all("Sales Order", {
"advance_pa | id": ["!=", 0]
}, "name")
for doc in docs:
frappe.db.set_value("Sales Order", doc.name, "advance_received", 1, update_modified=False) |
Yelp/pyes | docs/_ext/djangodocs.py | Python | bsd-3-clause | 3,769 | 0.011409 | """
Sphinx plugins for Django documentation.
"""
import docutils.nodes
import docutils.transforms
import sphinx
import sphinx.addnodes
import sphinx.directives
import sphinx.environment
import sphinx.roles
from docutils import nodes
def setup(app):
app.add_crossref_type(
directivename = "setting",
... | indextemplate = "pair: %s; template filter",
)
app.add_crossref_type(
directivename = "fieldlookup",
rolename = "lookup",
indextemplate = "pair: %s, field lookup type",
)
app.add_description_unit(
directivename = "django-admin",
rolename = "djadmin",
ind... | app.add_description_unit(
directivename = "django-admin-option",
rolename = "djadminopt",
indextemplate = "pair: %s; django-admin command-line option",
parse_node = lambda env, sig, signode: \
sphinx.directives.parse_option_desc(signode, sig),
)
app.add_config_v... |
wathen/PhD | MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/SplitMatrix/ScottTest/Hartman2D/Laplacian.py | Python | mit | 1,981 | 0.014134 | from dolfin import *
import numpy as np
import pandas as pd
n = 6
Dim = np.zeros((n,1))
ErrorL2 = np.zeros((n,1))
ErrorH1 = np.zeros((n,1))
OrderL2 = np.zeros((n,1))
OrderH1 = np.zeros((n,1))
# parameters['reorder_dofs_serial'] = False
for x in range(1,n+1):
parameters['form_compiler']['quadrature_degree'] = -1
... | solve(a == L, u, bcs=bc,
solver_parameters={"linear_solver": "lu"},
form_compiler_parameters={"optimize": True})
parameters['form_compiler']['quadrature_degree'] = 8
Vexact = VectorFunctionSpace(mesh, "CG", 4)
ue = interpolate(u0, Vexact) |
e = ue - u
Dim[x-1] = V.dim()
ErrorL2[x-1] = sqrt(abs(assemble(inner(e,e)*dx)))
ErrorH1[x-1] = sqrt(abs(assemble(inner(grad(e),grad(e))*dx)))
if (x > 1):
OrderL2[x-1] = abs(np.log2(ErrorL2[x-1]/ErrorL2[x-2]))
OrderH1[x-1] = abs(np.log2(ErrorH1[x-1]/ErrorH1[x-2]))
TableTitles = ["... |
zhaochl/python-utils | utils/thread/time_thread.py | Python | apache-2.0 | 846 | 0.01773 | #!/usr/bin/env python
# coding=utf-8
import threading
import time
class timer(threading.Thread): #The timer class is derived | from the class threading.Thread
def __init__(self, num, interval):
threading.Thread.__init__(self)
self.thread_num = num
self.interval = | interval
self.thread_stop = False
def run(self): #Overwrite run() method, put what you want the thread do here
while not self.thread_stop:
print 'Thread Object(%d), Time:%s/n' %(self.thread_num, time.ctime())
time.sleep(self.interval)
def stop(self):
self.thread... |
caryben/Ubuntu-bug-fixes | hidden_network_workaround.py | Python | mit | 357 | 0.005602 | # My computer was failing to recognize wifi networks after being woken up from sleep so this uses the network manager command
# line tool to force my computer to recognize the network I type in to the | terminal.
import subprocess
network_name = raw_input("What is the name of your network? ")
subprocess.check_call(['nmcli', | 'c', 'up', 'id', network_name])
|
fbradyirl/home-assistant | tests/components/system_log/__init__.py | Python | apache-2.0 | 42 | 0 | """Tests | for the sys | tem_log component."""
|
metis-ai/yowsup | yowsup/structs/protocoltreenode.py | Python | gpl-3.0 | 4,746 | 0.00906 | import binascii
import sys
class ProtocolTreeNode(object):
def __init__(self, tag, attributes = None, children = None, data = None):
self.tag = tag
self.attributes = attributes or {}
self.children = children or []
self.data = data
assert type(self.children) is list, "Childr... | return self.getAttributeValue(key)
def __setitem__(self, key, val):
self.setAttribute(key, val)
def __delitem__(self, key):
self.removeAttribute(key)
def getChild(self,identifier):
if type(identifier) == int:
if len(self.childre | n) > identifier:
return self.children[identifier]
else:
return None
for c in self.children:
if identifier == c.tag:
return c
return None
def hasChildren(self):
return len(self.children) > 0
def addChild(self, chi... |
antoinecarme/pyaf | tests/periodicities/Month/Cycle_Month_200_M_7.py | Python | bsd-3-clause | 81 | 0.049383 | import t | ests.periodicities.period_test as per
per.buildModel((7 , 'M' , 200)); | |
gc3-uzh-ch/django-simple-poll | voting/urls.py | Python | agpl-3.0 | 833 | 0.003601 | from django.conf.urls import patterns, include, url
from django.contrib import admin
from rest_framework import viewsets, routers
from voting_app.models import Topic
from voting_app.views import Vote
from voting_app.serializer import TopicSerializer
admin.autodiscover()
# ViewSets define the view behavior.
class To... | ewsets.ModelViewSet):
model = Topic
serializer_class = TopicSerializer
queryset = Topic.objects.all().filter(hide=False)
router = routers.DefaultRouter()
router.register(r'topics', TopicViewSet)
urlpatterns = patterns('',
url(r'^$', 'voting_app.views.index', name='index'),
url(r'^', include(router... | work')),
url(r'^admin/', include(admin.site.urls)),
)
|
2013Commons/hue | desktop/libs/libsaml/src/libsaml/conf.py | Python | apache-2.0 | 4,427 | 0.005195 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | ypt/sign assertions and as client key in a HTTPS session."))
CERT_FILE = Config(
key="cert_file",
default="",
type=str,
help=_t("This is the public part of the service private/public key pair. cert_file must | be a PEM formatted certificate chain file."))
USER_ATTRIBUTE_MAPPING = Config(
key="user_attribute_mapping",
default={'uid': ('username', )},
type=dict_list_map,
help=_t("A mapping from attributes in the response from the IdP to django user attributes."))
AUTHN_REQUESTS_SIGNED = Config(
key="authn_requests_... |
baalkor/timetracking | opconsole/migrations/0027_device_name.py | Python | apache-2.0 | 468 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-05 20:10
from __future__ import unicode_liter | als
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('opconsole', '0026_auto_20170504_2048'),
]
operations = [
migrations.AddField(
model_name='device',
name='name',
field=models.CharField( | default=b'unnamed', max_length=255),
),
]
|
bt3gl/Plotting-in-Linux | grace/src/symbol_mapping.py | Python | mit | 8,291 | 0.014353 | """
Module to translate various names (unicode, LaTeX & other text) for characters to encodings in the Symbol font standard encodings.
Also, provide grace markup strings for them.
It recognizes unicode names for the greek alphabet and most of the useful symbols in the Symbol font.
Marcus Mendenhall, Vanderbilt Univer... |
_symbols += zip([ord(x) for x in _greekorder], _ugrlower)
_greeklowernames=[x.lower() for x in _greekuppernames]
_greeklowernames[_greeklowernames.index('finalsigma')]='altpi'
_symbols += zip([ord(x) for x in _greekorder], [x.lower() for x in _greeklowernames])
gracedict={}
for tt in _symbols:
if tt[0] > 0x20 a... | ascii="".join([chr(i) for i in range(32,127)])
_normalucode=unicode(_normalascii)
def remove_redundant_changes(gracestring):
"""collapse out consecutive font-switching commands so that \xabc\f{}\xdef\f{} becomes \xabcdef\f{}"""
while(1):
xs=gracestring.find(r"\f{}\x")
if xs<0: break
if ... |
NINAnor/QGIS | tests/src/python/test_qgseditwidgets.py | Python | gpl-2.0 | 2,315 | 0.000864 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for edit widgets.
.. 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; either version 2 of the License, or
(at your option) any later version.
"""
__au... | s Kuhn'
__date__ = '20/05/2015'
__copyright__ = 'Copyright 2015, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import qgis
import os
from qgis.core import QgsFeature, QgsGeometry, QgsPoint, QgsVectorLayer, NULL
from qgis.gui import QgsEditorWidgetRe... | )
from utilities import unitTestDataPath
start_app()
class TestQgsTextEditWidget(unittest.TestCase):
@classmethod
def setUpClass(cls):
QgsEditorWidgetRegistry.initEditors()
def createLayerWithOnePoint(self):
self.layer = QgsVectorLayer("Point?field=fldtxt:string&... |
kozlovsky/ponymodules | main.py | Python | mit | 707 | 0.004243 | # This is the example of main program file which imports entities,
# connects to the database, drops/creates specified tables
# and populate some data to the database
from pony.orm import * # or just import db | _session, etc.
import all_entities # This command m | ake sure that all entities are imported
from base_entities import db # Will bind this database
from db_settings import current_settings # binding params
db.bind(*current_settings['args'], **current_settings['kwargs'])
from db_utils import connect
from db_loading import populate_database
if __name__ == '__main__':... |
zstang/learning-python-the-hard-way | ex4.py | Python | mit | 621 | 0.00161 | # - | *- coding: utf-8 -*-
#
# exercise 4: variables and names
#
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
pri | nt "There are", cars, "cars avaliable."
print "There are only", drivers, "drivers avaliable."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "prople today."
print "We have", passengers, "to carpool today"
print "We need to put about", average_passengers_per_car, ... |
mpasternak/pyglet-fix-issue-552 | pyglet/image/codecs/pypng.py | Python | bsd-3-clause | 41,571 | 0.000385 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... | B
has_alpha - input data has alpha channel (RGBA)
bytes_per_sample - 8-bit or 16-bit input data
com | pression - zlib compression level (1-9)
chunk_limit - write multiple IDAT chunks to save memory
If specified, the transparent and background parameters must
be a tuple with three integer values for red, green, blue, or
a simple integer (or singleton tuple) for a greyscale image.
... |
BrainTech/openbci | obci/control/gui/obci_log_model_dummy.py | Python | gpl-3.0 | 732 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import obci_log_model
class DummyLogModel(obci_log_model.LogModel):
def __init__(self):
super(DummyLogModel, self).__init__()
self._ind = 0
self._peers_log = {'amplifier':
{'peer_id': | 'amplifier', 'logs': []},
| 'mx':
{'peer_id': 'mx', 'logs': []}
} # 'logs keyed by peer id
def next_log(self):
time.sleep(0.05)
self._ind += 1
if self._ind % 2 == 0:
return 'amplifier', 'AMP ' + str(self._ind)
else:
return 'mx', 'M... |
sqlalchemy/sqlalchemy | lib/sqlalchemy/dialects/mysql/expression.py | Python | mit | 4,164 | 0 | # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
import typing
from ... import exc
from ... import util
from ...sql import coercions
from ...sql impo... | select(users_table)
.where(match_expr.in_boolean_mode())
.order_by(desc(match_expr))
)
Would produce SQL resembling::
SELECT id, firstname, lastname
FROM user
WHERE MATCH(firstname, lastname) AGAINST (:param_1 IN BOOL | EAN MODE)
ORDER BY MATCH(firstname, lastname) AGAINST (:param_2) DESC
The :func:`_mysql.match` function is a standalone version of the
:meth:`_sql.ColumnElement.match` method available on all
SQL expressions, as when :meth:`_expression.ColumnElement.match` is
used, but allows to pass multiple c... |
jurkov/Bytebot | plugins/parking.py | Python | mit | 2,182 | 0 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import urllib2
import json
from plugins.plugin import Plugin
from time import time
from bytebot_config import BYTEBOT_HTTP_TIMEOUT, BYTEBOT_HTTP_MAXSIZE
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
class parking(Plugin):
def __init__(self):
pass
d... | 0):
occupied = 0
if(spaces <= 0):
print_str = '{:25s}: not available'.format(name)
else:
print_str = '{:25s}: '.format(name) + \
'{:3.0f} / '.format(spaces - occupied) + ... | }'.format(spaces)
irc.msg(channel, print_str)
irc.last_parking = time()
except Exception as e:
print(e)
irc.msg(channel, 'Error while fetching data.')
else:
irc.msg(channel, "Don't overdo it ;)")
|
dan-f/polypype | tests/test_polypipe.py | Python | mit | 5,061 | 0 | """
TODO:
- Handle if file already exists
"""
import ctypes
import io
import os
import struct
from contextlib import contextmanager
import ddt
import mock
from unittest2 import TestCase
import tempfile
from polypype import _MAX_C_FLOAT, _MAX_C_UINT32, PolyPype
from polypype.exceptions import (
PolyPypeArgumen... | (list(), [list()]),
(dict(), [dict()])
)
@ddt.unpack
def test_bad_types(self, time_delta, params):
with self.assertRaises(PolyPypeTypeException):
self.polypype.write_event(time_delta, params)
@ddt.data(list(), dict(), set())
def test_no_params(self, empty_contain... | r):
time_delta = 1
self.polypype.write_event(time_delta, empty_container)
with self.open_output_file() as f:
self.assert_next_ctype_equal(f, '<f', time_delta)
self.assert_next_ctype_equal(f, '<I', 0)
self.assertEqual(f.read(), '')
def test_too_many_params... |
Conjuro/async | channel.py | Python | bsd-3-clause | 11,309 | 0.041648 | # Copyright (C) 2010, 2011 Sebastian Thiel (byronimo@gmail.com) and contributors
#
# This module is part of async and is released under
# the New BSD License: http://www.opensource.org/licenses/bsd-license.php
"""Contains a queue based channel implementation"""
from Queue import (
Empty,
Full
)
from util import (
... | with a reader"""
raise NotImplementedError()
def close(self):
"""Close the channel. Multiple close calls on a closed channel are no
an error"""
raise NotImplementedError()
def closed(self):
| """:return: True if the channel was closed"""
raise NotImplementedError()
#} END interface
class ChannelWriter(Writer):
"""The write end of a channel, a file-like interface for a channel"""
__slots__ = ('channel', '_put')
def __init__(self, channel):
"""Initialize the writer to use the given channel"""
... |
asposecells/Aspose_Cells_Cloud | Examples/Python/Examples/DeleteHyperlinksFromExcelWorksheet.py | Python | mit | 1,503 | 0.00998 | import asposecellscloud
from asposecellscloud.CellsApi import CellsApi
from asposecellscloud.CellsApi import ApiException
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
apiKey = "XXXXX" #se | pcify App Key
appSid = "XXXXX" #sepcify App SID
apiServer = "http://api.aspose.com/v1.1"
data_folder = "../../data/"
#Instantiate Aspose Storage API SDK
storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True | )
storageApi = StorageApi(storage_apiClient)
#Instantiate Aspose Cells API SDK
api_client = asposecellscloud.ApiClient.ApiClient(apiKey, appSid, True)
cellsApi = CellsApi(api_client);
#set input file name
filename = "Sample_Test_Book.xls"
sheetName = "Sheet2"
hyperlinkIndex = 0
#upload file to aspose cloud storage
st... |
Dante83/lexinomicon | lexinomicon/tests.py | Python | gpl-3.0 | 388 | 0 | i | mport unittest
from pyramid import testing
class ViewTests(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def test_my_view(self):
from .views import my_view
request = testing.DummyRequest()
info = my_view... | )
|
shucommon/little-routine | python/AI/tensorflow/dropout.py | Python | gpl-3.0 | 2,353 | 0.00742 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import sys
sys.path.append('./MNIST_data')
import os.path
from download import download
have_data = os.path.exists('MNIST_data/train-images-idx3-ubyte.gz')
if not have_data:
download('./MNIST_data')
# load data
mnist = input_data.r... | h_size
# in [60000, 28 * 28] out [60000, 10]
x = tf.plac | eholder(tf.float32, [None,784])
y = tf.placeholder(tf.float32, [None,10])
keep_prob = tf.placeholder(tf.float32)
# 神经网络结构 784-1000-500-10
w1 = tf.Variable(tf.truncated_normal([784,1000], stddev=0.1))
b1 = tf.Variable(tf.zeros([1000]) + 0.1)
l1 = tf.nn.tanh(tf.matmul(x, w1) + b1)
l1_drop = tf.nn.dropout(l1, keep_prob)
... |
salilab/cryptosite | lib/cryptosite/predict.py | Python | lgpl-2.1 | 7,574 | 0 | #!/usr/bin/env python
"""Do the final prediction of binding site given all features."""
from __future__ import print_function, absolute_import
import pickle
import os
import optparse
import cryptosite.config
def get_matrix(inputdata, model='linear'):
Res = {'CYS': (0, 0, 1, 0, 0), 'ASP': (0, 0, 0, 1, 1),
... | = [Header.index('CNC'), Header.index('PRT_std_450'),
Header.index('CN5_mean_500')]
visited += [Header.index('Bn'), Header.index('CHRn'),
Header.index('In')]
visited += [Header.index('CNC_std_300'), Header.index('CNS_300'),
| Header.index('SAS14_std_400')]
visited += [Header.index('SASn')]
elif model == 'linear':
# for linear SVM
visited = [Header.index('CNC_mean_300'), Header.index('SQC'),
Header.index('CN5_std_450')]
visited += [Header.index('D2S'), Header.index('CNS_300'),
... |
daniel-araujo/proctal | src/cli/tests/write-binary.py | Python | gpl-3.0 | 1,310 | 0.00458 | #!/usr/bin/env python3
import sys
from util import proctal_cli, sleeper
class Error(Exception):
pass
class TestSingleValue:
def __init__(self, type, value):
self.type = type
self.value = value
pass
def run(self, guinea):
address = proctal_cli.allocate(guinea.pid(), self.v... | try:
value = reader.next_value()
if self.value.cmp(value) != 0:
raise Error("Expected {expected} but got {found}.".format(expected=self.value, found=value))
finally:
reader.stop()
finally:
... | locate(guinea.pid(), address)
int32 = proctal_cli.TypeInteger(32);
int32_test_val = proctal_cli.ValueInteger(int32)
int32_test_val.parse(0x0ACC23AA)
tests = [
TestSingleValue(int32, int32_test_val)
]
guinea = sleeper.run()
try:
for test in tests:
test.run(guinea)
finally:
guinea.stop()
|
DiamondLightSource/ispyb-api | src/ispyb/sp/mxacquisition.py | Python | apache-2.0 | 9,112 | 0.001097 | # mxacquisition.py
#
# Copyright (C) 2014 Diamond Light Source, Karl Levik
#
# 2014-09-24
#
# Methods to store MX acquisition data
#
import copy
from ispyb.sp.acquisition import Acquisition
from ispyb.strictordereddict import StrictOrderedDict
class MXAcquisition(Acquisition):
"""MXAcquisition provides metho... | file_location", None),
("measured_intensity", None),
("jpeg_path", None),
("jpeg_thumb_path", None),
("temperature", None),
("cumulative_intensity", None),
("synchrotron_current", None),
("comments", None),
("machine_msg", N... | arentid", None),
("dxInMm", None),
("dyInMm", None),
("stepsX", None),
("stepsY", None),
("meshAngle", None),
("pixelsPerMicronX", None),
("pixelsPerMicronY", None),
("snapshotOffsetXPixel", None),
("snapshotOffs... |
littleDad/mesLucioles | logger_04.py | Python | gpl-2.0 | 2,415 | 0.003313 | # -*- coding: utf8 -*-
import logging
from logging.handlers import RotatingFileHandler
from babel.dates import format_datetime, datetime
from time import sleep
from traceback import print_exception, format_exception
class LogFile(logging.Logger):
'''rotatively logs erverything
'''
def initself(self):
... | '''
logger = self
if 'error' in kwargs:
print('error YES')
kwargs['level'] = 'error'
if 'exception' in kwargs:
print('exception YES')
kwargs['level'] = 'exception'
if 'level' in kwargs:
level = kwargs['level']
... | = 'error': # or whatever you want with more details
message = ">> " + kwargs['error'][1].message # exc_info()[1].message
eval("logger." + level + "(\"" + message + "\")")
elif level == 'exception':
message = ">> UPRISING OF AN EXCEPTION!"
eval("logger."... |
XBigTK13X/wiiu-memshark | vendor/tcpgecko/octoling.py | Python | mit | 5,604 | 0.010171 | # -*- coding: cp1252 -*-
#Codename Octohax
#To find Octohax offsets on newer versions, dump memory
#in that area, eg 0x10500000 to 0x10700000, open in hex
#editor, search "Tnk_Simple", there are only 2 results
#Also search for Player00
#There should be like a result or two before what you want
#Looks like this:
'''
.k.... | C, b"Rival_Squid")
#tcp.pokemem(0x12CB05A0, 42069)
elif sys | .argv[1] == "130": #for 1.3.0
tcp.writestr(0x105068F0, b"Tnk_Rvl00")
tcp.writestr(0x105D4000, b"Tnk_Rvl00")
tcp.writestr(0x105DC118, b"Rival00")
tcp.writestr(0x105DC124, b"Rival00_Hlf")
tcp.writestr(0x105DC134, b"Rival_Squid")
#tcp.pokemem(0x12CB07A0, 42069)
elif sys.argv[1] == "200": #For 2.0.0... |
dragoon/kilogram | kilogram/entity_linking/mention_rw/__init__.py | Python | apache-2.0 | 7,287 | 0.002196 | from __future__ import division
import math
import numpy as np
import networkx as nx
from sklearn.preprocessing import normalize
from kilogram import NgramService
class Signature(object):
vector = None
mapping = None
def __init__(self, vector, G, candidate_uris):
"""
:type candidate_uris:... | ri_count
return np.matrix(teleport_vector)
def _learn_eigenvector(self, teleport_vector):
pi = np.matrix(np.zeros(teleport_vector.shape))
prev_norm = 0
for _ in range(10000):
pi = self.matrix*pi*ALPHA + teleport_ | vector
cur_norm = np.linalg.norm(pi)
pi /= cur_norm
if prev_norm and abs(cur_norm - prev_norm) < 0.00001:
break
prev_norm = cur_norm
return np.ravel(pi/pi.sum())
def doc_signature(self):
"""compute document signature"""
return ... |
weyw/eulerproject | wey/p1.py | Python | gpl-2.0 | 458 | 0.00655 | # https://projecteuler.net/problem=1
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
# = 233168
import sys
def s | um(n):
total = 0
for i in range(n):
if (i % 3 == 0) or (i % 5 == 0):
total += i
|
return total
n = 20
if len(sys.argv) == 2:
n = int(sys.argv[1])
print(sum(n))
|
aykol/pymatgen | pymatgen/io/tests/test_qchem.py | Python | mit | 81,842 | 0.00033 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
import copy
import glob
import json
import os
import unittest
from pymatgen import Molecule
from pymatgen.io.qchem import QcTask, QcInput, QcOutput
from pymatgen.util.t... | self.from_string_verify(contents=text, ref_dict=qctask.as_dict())
def to_and_from_dict_verify(self, qctask):
"""
Helper function. This function should be called in | each specific test.
"""
d1 = qctask.as_dict()
qc2 = QcTask.from_dict(d1)
d2 = qc2.as_dict()
self.assertEqual(d1, d2)
def from_string_verify(self, contents, ref_dict):
qctask = QcTask.from_string(contents)
d2 = qctask.as_dict()
self.assertEqual(ref_dic... |
andreaso/ansible | lib/ansible/modules/remote_management/wakeonlan.py | Python | gpl-3.0 | 4,077 | 0.004415 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, Dag Wieers <dag@wieers.com>
#
# This file is part of Ansible
#
# Ansible 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, ... | et system was properly configured for Wake-on-LAN (in the BIOS and/or the OS)
- Some BIOSes have a different (configurable) Wake-on-LAN boot order (i.e. PXE first) when turned off
'''
EXAMPLES = '''
- name: Send a magic Wake-on-LAN packet to 00:00:5E:00:53:66
wakeonlan:
mac: '00:00:5E:00:53:66'
broadcast: ... | port: 9
delegate_to: localhost
'''
RETURN='''
# Default return values
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
import socket
import struct
def wakeonlan(module, mac, broadcast, port):
""" Send a magic Wake-on-LAN packet. """
mac... |
google/python_portpicker | src/tests/portpicker_test.py | Python | apache-2.0 | 16,155 | 0.000371 | #!/usr/bin/python
#
# Copyright 2007 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... | ERVER_ADDRESS from os.environ, if
# we can successfully obtain a port, the portserver must be working.
addr = os.environ.pop('PORTSERVER_ADDRESS')
try:
port = portpicker.pick_unused_port(portserver_address=addr)
self.assertTrue(self.IsUnusedTCPPort(por... | (self.IsUnusedUDPPort(port))
finally:
os.environ['PORTSERVER_ADDRESS'] = addr
@unittest.skipIf('PORTSERVER_ADDRESS' not in os.environ,
'no port server to test against')
def testGetPortFromPortServer(self):
"""Exercise the get_port_from_port_server() helper... |
vmg/hg-stable | mercurial/copies.py | Python | gpl-2.0 | 12,819 | 0.001872 | # copies.py - copy detection for Mercurial
#
# Copyright 2008 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import util
import heapq
def _nonoverlap(d1, d2, d3):
"Return list of elements in d1... | for k, v in t.items():
if k in src and v in dst:
del t[k]
return t
def _tracefile(fctx, actx):
'''return file context that is the ancestor of fctx present in actx'''
stop = actx.rev()
am = actx.manifest()
for f in fctx.ancestors():
if am.get(f.path(), None) == f.fi... | :
return f
if f.rev() < stop:
return None
def _dirstatecopies(d):
ds = d._repo.dirstate
c = ds.copies().copy()
for k in c.keys():
if ds[k] not in 'anm':
del c[k]
return c
def _forwardcopies(a, b):
'''find {dst@b: src@a} copy mapping where a is an... |
douban/dpark | dpark/broadcast.py | Python | bsd-3-clause | 24,223 | 0.001238 | from __future__ import absolute_import
import os
import zmq
import uuid as uuid_pkg
import time
import binascii
import random
import socket
import struct
import marshal
import mmap
from multiprocessing import Manager, Condition
from mmap import ACCESS_WRITE, ACCESS_READ
from dpark.utils.log import get_logger
from dpar... | self.guides[uuid] = {addr: bitmap}
self.register_addr[uuid] = addr
sock.send_pyobj(None)
elif type_ = | = GUIDE_REPORT_BAD:
uuid, addr = msg
sources = self.guides[uuid]
if addr in sources:
if addr != self.register_addr[uuid]:
del sources[addr]
else:
logger.war... |
tkrotoff/QuarkPlayer | buildbot/upload_package.py | Python | gpl-3.0 | 2,173 | 0.018408 | """
QuarkPlayer, a Phonon media player
Copyright (C) 2008-2009 Tanguy Krotoff <tkrotoff@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at... |
file = open(file_to_upload, 'rb')
destpath = os.path.join(host_path, os.path.basename(file_to_upload))
ftp.storbinary('STOR ' + destpath, file)
mode = '644'
print 'chmod {0} {1}'.format(mode, file_to_upload)
ftp.voidcmd('SITE CHMOD ' + mode + ' ' + destpath)
ftp.quit()
if __name__ == "__main__":
login... | )
os.remove(loginfile)
files_to_upload = []
for i, pattern in enumerate(sys.argv):
if i > 0:
# Fix a bug under Windows,
# this script gets called with these arguments:
# ['upload_package.py', "'*.exe'", "'*.deb'", "'*.rpm'"]
# instead of ['upload_package.py', '*.exe', '*.deb', '*.rpm']
pattern = p... |
DjangoNYC/squid | squid/core/forms.py | Python | mit | 352 | 0 | from django import forms
from .models import M | emberRSVP
class EventAttendeeForm(forms.ModelForm):
id = forms.IntegerField(widget=forms.HiddenInput)
worked_on = forms.CharField(widget=forms.Textarea(attrs={
'cols': '35',
'rows': '5'
}))
class Meta:
model = MemberRSVP
fields = ('id', 'worked_on',)
| |
alogg/dolfin | demo/undocumented/tensor-weighted-poisson/python/generate_data.py | Python | gpl-3.0 | 1,642 | 0 | """This program is used to generate the coefficients c00, c01 and c11
used in the demo."""
# Copyright (C) 2007-2009 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free S... | sh(32, 32)
# Create mesh functions for c00, c01, c11
c00 = MeshFunction("double", mesh, 2)
c01 = MeshFunction("double", mesh, 2)
c11 = MeshFunction("double", mesh | , 2)
# Iterate over mesh and set values
for cell in cells(mesh):
if cell.midpoint().x() < 0.5:
c00[cell] = 1.0
c01[cell] = 0.3
c11[cell] = 2.0
else:
c00[cell] = 3.0
c01[cell] = 0.5
c11[cell] = 4.0
# Store to file
mesh_file = File("mesh.xml.gz")
c00_file = File("... |
helix84/activae | src/Type.py | Python | bsd-3-clause | 2,833 | 0.003883 | # Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source | code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above cop | yright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specif... |
Galithil/genologics_sql | doc/source/conf.py | Python | mit | 9,443 | 0.006036 | # -*- coding: utf-8 -*-
#
# genologics-sql documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 27 15:17:17 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... | age = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configu | ration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'genologics-sqldoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# Th... |
bamueh/dark-matter | test/test_simplify.py | Python | mit | 1,892 | 0 | from unittest import TestCase
from dark.simplify import simplifyTitle
class SimplifyTitle(TestCase):
"""
Tests for the dark.simplify.simplifyTitle function.
"""
def testEmptyTitle(self):
"""
Simplifying an empty title with a non-empty target should return
an empty title.
... | s the suffix) should be returned.
"""
self.assertEqual(
'Funny sea lion polyomavirus',
simplifyT | itle('Funny sea lion polyomavirus 1 CSL6994', 'virus'))
def testContained(self):
"""
When the target is contained, the title up to the target (including the
prefix of the word that has the target) should be returned.
"""
self.assertEqual(
'Funny sea lion polyoma'... |
javiergarridomellado/ej5 | apu/forms.py | Python | gpl-2.0 | 745 | 0.02953 | from django import forms
from apu.models import Persona
class FormularioContactos(forms.Form):
asunto=forms.CharField()
email=forms.EmailField(required=False)
mensaje=forms.CharField()
class PersonaForm(forms.ModelForm):
nombre = forms.CharField(max_length=50,help_text="nombre Persona")
dni = forms.CharField(max... | ield(max_length=20,help_text="pais Persona")
equipo = forms.CharField(max_length=10,help_text="equipo Persona")
hobbies = forms.TextField(max_length=200,help_text="hobbies Persona")
#password = models.PasswordField(max_length=15)
fondo = forms.IntegerField()
class Meta:
model | = Persona
fields = ('nombre','dni','pais','equipo','hobbies','fondo')
|
nathanielvarona/airflow | airflow/providers/google/cloud/example_dags/example_dataflow_flex_template.py | Python | apache-2.0 | 2,774 | 0.001802 | #
# 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... | get(
'GCP_DATAFLOW_FLEX_TEMPLATE_JOB_NAME', "dataflow-flex-template"
)
# For simplicity we us | e the same topic name as the subscription name.
PUBSUB_FLEX_TEMPLATE_TOPIC = os.environ.get(
'GCP_DATAFLOW_PUBSUB_FLEX_TEMPLATE_TOPIC', "dataflow-flex-template"
)
PUBSUB_FLEX_TEMPLATE_SUBSCRIPTION = PUBSUB_FLEX_TEMPLATE_TOPIC
GCS_FLEX_TEMPLATE_TEMPLATE_PATH = os.environ.get(
'GCP_DATAFLOW_GCS_FLEX_TEMPLATE_TEMP... |
dscorbett/pygments | pygments/lexers/_postgres_builtins.py | Python | bsd-2-clause | 12,184 | 0.000246 | """
pygments.lexers._postgres_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Self-updating data files for PostgreSQL | lexer.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
# Autogenerated: please edit them if you like wasting your time.
KEYWORDS = (
'ABORT',
'ABSOLUTE',
'ACCESS',
'ACTION',
'ADD',
'ADMIN',
| 'AFTER',
'AGGREGATE',
'ALL',
'ALSO',
'ALTER',
'ALWAYS',
'ANALYSE',
'ANALYZE',
'AND',
'ANY',
'ARRAY',
'AS',
'ASC',
'ASSERTION',
'ASSIGNMENT',
'ASYMMETRIC',
'AT',
'ATTACH',
'ATTRIBUTE',
'AUTHORIZATION',
'BACKWARD',
'BEFORE',
'BEGIN',... |
pombreda/swarming | appengine/auth_service/common/importer.py | Python | apache-2.0 | 14,804 | 0.010875 | # Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Imports groups from some external tar.gz bundle or plain text list.
External URL should serve *.tar.gz file with the following file structure:
<ext... | Config(ndb.Model):
"""Singleton entity with group importer configuration JSON."""
config = ndb.JsonProperty()
modified_by = auth.IdentityProperty(indexed=False)
modified_ts = ndb.DateTimeProperty(auto_now=True, indexe | d=False)
def is_valid_config(config):
"""Checks config for correctness."""
if not isinstance(config, list):
return False
seen_systems = set(['external'])
seen_groups = set()
for item in config:
if not isinstance(item, dict):
return False
# 'format' is an optional string describing the fo... |
taigaio/taiga-back | taiga/users/migrations/0029_user_verified_email.py | Python | agpl-3.0 | 391 | 0 | # Generated by Django 2.2.14 on 2020-07-30 12:09
from django.db import migrations, models
class Migration(migrations. | Migration):
dependencies = [
('users', '0028_auto_20200615_0811'),
]
operations = [
migrations.AddField(
model_name='user',
name='verified_email',
field=models.BooleanField( | default=True),
),
]
|
Micronaet/micronaet-quality | quality/etl/import.py | Python | agpl-3.0 | 101,183 | 0.009172 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Modules used for ETL - Create User
# Modules required:
import os
import xmlrpclib, sys, csv, ConfigParser
from openerp.tools.status_history import status
from datetime import datetime
# -----------------------------------------------------------------------------
# ... | or = eval(config.get('log','error')) # log only error in function
# Startup from code:
default_error_data = "2014/07/30"
default_product_id = 1921 # for lot creation (acceptation)
default_lot_id = 92710 # ERR
log_file = os.path.expanduser("~/ETL/generalfood/log/%s.txt" % (datetime.now())) |
log = open(log_file, 'w')
# -----------------------------------------------------------------------------
# XMLRPC connection
# -----------------------------------------------------------------------------
sock = xmlrpclib.ServerProxy(
'http://%s:%s/xmlrpc/common' % (server, port), allow... |
tsarnowski/hamster | wafadmin/Options.py | Python | gpl-3.0 | 6,022 | 0.06277 | #! /usr/bin/env python
# encoding: utf-8
import os,sys,imp,types,tempfile,optparse
import Logs,Utils
from Constants import*
cmds='distclean configure build install clean uninstall check dist distcheck'.split()
commands={}
is_install=False
options={}
arg_line=[]
launch_dir=''
tooldir=''
lockfile=os.environ.get('WAFLOCK... | ction='store_true',default=False,help='ignore the WAFCACHE (if set)',dest='nocache')
p('--zones',action='store',default='',help='debugging zones (task_gen, deps, tasks, etc)',dest='zones')
p('-p','--progress',action='count',default=0 | ,help='-p: progress bar; -pp: ide output',dest='progress_bar')
p('--targets',action='store',default='',help='build given task generators, e.g. "target1,target2"',dest='compile_targets')
gr=optparse.OptionGroup(parser,'configuration options')
parser.add_option_group(gr)
gr.add_option('-b','--blddir',action='store',d... |
injectnique/KnuckleHeadedMcSpazatron | GenericBytecode.py | Python | mit | 46,794 | 0.013506 | #!C:\Python27\python.exe
# Filename: GenericBytecode.py
# -*- coding: utf-8 -*-
import os
import Settings
'''
Generic Bytecode
Simply add, remove or modify bytecode for use in KHMS
'''
createFrame = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1',
'iconst_1', 'iadd', 'putfield', 'il... | ishr', \
'i2b', 'bastore', 'return']
method432 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield | ', 'dup_x1', \
'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \
'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \
'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \
'sipush', 'iadd', 'i2b', 'bastore', 'return']
method433 = ['... |
F0lha/UJunior-Projects | DailyProgrammer/Challenge#318/src.py | Python | mit | 2,546 | 0.008641 | from itertools import permutations
import re
def create_formula(combination,numbers):
formula = ""
index = 0
for op in combination:
formula += str(numbers[index]) + op
index += 1
formula += numbers[index]
return formula
'''
Unnecessary Funtion
'''
def evaluate(form):
result ... | 1
elif form[index] == "-":
result -= int(form[index+1])
index += 1
elif form[index] == "*":
result *= int(form[index+1])
index += 1
elif form[index] == "/":
result //= int(form[index+1])
index += 1
else:
... | len(numbers) - 1)
perms = list(permutations(numbers))
for combination in combinations:
for permut in perms:
formula = create_formula(combination,permut)
#form = re.split("([*+-/])",formula)
#if int(evaluate(form)) == int(finalScore):
if int(eval(formula))... |
wangjun/BT-Share | web/module/module.py | Python | mit | 955 | 0.006283 | #!/usr/bin/env python
# encoding: utf-8
import re
from tornado.web import UIModule
from conf.config import BT_PAGE_SIZE
#TODO it is may not be good to put it here to make the pager class scattered
class Pagination(UIModule):
def render(self, page, ur | i, list_rows=BT_PAGE_SIZE):
def gen_page_list(current_page=1, total_page=1, list_rows=BT_PAGE_SIZE):
#TODO add ajax pager support
return range(1, total_page + 1)
def build_uri(uri, param, value):
regx = re.compile("[\?&](%s=[^\?&]*)" % param)
find = regx... | ot find:
return "%s%s%s=%s" % (uri, split, param, value)
return re.sub(find.group(1), "%s=%s" % (param, value), uri)
return self.render_string("pagination.html", page=page, uri=uri, gen_page_list=gen_page_list, list_rows=list_rows, build_uri=build_uri)
|
shearichard/django-channels-demo | chnnlsdmo/chnnlsdmo/settings_heroku.py | Python | bsd-3-clause | 510 | 0.005882 | import | os
from os.path import abspath, basename, dirname, join, normpath
from sys import path
import dj_database_url
from .settings import *
DEBUG = True
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# E | xtra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
DATABASES['default'] = dj_database_url.config()
ROOT_URLCONF = 'chnnlsdmo.chnnlsdmo.urls'
|
diegojromerolopez/djanban | src/djanban/apps/boards/migrations/0018_list_position.py | Python | mit | 505 | 0.00198 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-17 17:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('boards', '0017_card_blocking_cards'),
]
operations = [
migrations.AddField(
... | odel_name='list',
name='position',
field=models.PositiveIntegerField(default=0, verbose_name='Position of this list in t | he board'),
),
]
|
ctrlaltdel/neutrinator | vendor/requestsexceptions/__init__.py | Python | gpl-3.0 | 2,032 | 0 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | arning
except ImportError:
try:
from urllib3.exceptions import InsecureRequestWarning
except ImportError:
InsecureRequestWarning = None
try:
from requests.packages.urllib3.exceptions import SubjectAltNameWarning
except ImportError:
try:
from urllib3.exceptions import SubjectAltN... | mportError:
try:
from urllib3.exceptions import SNIMissingWarning
except ImportError:
SNIMissingWarning = None
def squelch_warnings(insecure_requests=True):
if SubjectAltNameWarning:
warnings.filterwarnings('ignore', category=SubjectAltNameWarning)
if InsecurePlatformWarning:
... |
ZenSecurity/nassl | src/DebugSslClient.py | Python | gpl-2.0 | 3,283 | 0.009138 | #!/usr/bin/python2.7
from nassl._nassl import SSL
from SslClient import SslClient
class DebugSslClient(SslClient):
"""
An SSL client with additional debug methods that no one should ever use (insecure renegotiation, etc.).
"""
def get_secure_renegotiation_support(self):
return self._ssl.get_... | if not self._handshakeDone:
raise IOError('SSL Handshake was not c | ompleted; cannot renegotiate.')
self._ssl.renegotiate()
return self.do_handshake()
def get_session(self):
"""Get the SSL connection's Session object."""
return self._ssl.get_session()
def set_session(self, sslSession):
"""Set the SSL connection's Session object."""
... |
dburggie/py3D | bodies/Sphere.py | Python | mit | 2,470 | 0.011741 | import bounds
from py3D import | Vector, Ray, Color, Body
class Sphere(Body):
center = Vector()
radius = 0.0
R = 0.0
color = [0.01,0.01,0.01]
def p(self):
"""Returns the name of the type of body this is."""
return 'Sphere'
def set_position(sel | f, c):
self.center = c
return self
def set_radius(self, r):
self.radius = abs(r)
self.R = r ** 2.0
return self
def set_color(self, c):
self.color = c
return self
def get_color(self, point):
"""Returns color of body at given point... |
bashu/fluentcms-twitterfeed | fluentcms_twitterfeed/south_migrations/0001_initial.py | Python | apache-2.0 | 7,116 | 0.00801 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'TwitterRecentEntriesItem'
db.create_table(u'contentitem_f... | 'polymorphic_ctype': ('django.db.models | .fields.related.ForeignKey', [], {'related_name': "'polymorphic_fluent_contents.contentitem_set+'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}),
'sort_order': ('django.db.models.fields.IntegerField', [], {'default': '1', 'db_index': 'True'})
},
'fluent_contents.placeholder': {... |
Bairdo/faucet | tests/faucet_mininet_test_base.py | Python | apache-2.0 | 72,009 | 0.000667 | #!/usr/bin/env python
"""Base class for all FAUCET unit tests."""
# pylint: disable=missing-docstring
# pylint: disable=too-many-arguments
import collections
import glob
import ipaddress
import json
import os
import random
import re
import shutil
import subprocess
import time
import unittest
import yaml
import requ... | elf.switch_map = {}
for i, switch_port in enumerate(dp_ports):
test_port_name = 'port_%u' % (i + 1)
self.port_map[test_port_name] = switch_port
self.switch_map[test_port_name] = dp_ports[switch_port]
def _set_vars(self):
self._set_... | (tmpdir=self.tmpdir), self.debug_log_path, self.dpid, self.hardware),
self.CONFIG % self.port_map))
if self.config_ports:
faucet_config = faucet_config % self.config_ports
with open(self.faucet_config_path, 'w') as faucet_config_file:
faucet_config_file.write(faucet_... |
HeatherHillers/RoamMac | src/configmanager/editorwidgets/numberwidget.py | Python | gpl-2.0 | 1,472 | 0.004076 | import os
from PyQt4.QtCore import pyqtSignal
from PyQt4.QtGui import QComboBox, QDoubleValidator
from configmanager.editorwidgets.core import ConfigWidget
from configmanager.editorwidgets.uifiles.ui_numberwidget_config import Ui_Form
class NumberWidgetConfig(Ui_Form, ConfigWidget):
description = 'Number entry w... | f):
config = {}
config['max'] = self.maxEdit.text()
config['min'] = self.minEdit.text()
config['prefix'] = self.prefixEdit.text()
config['suffix'] = self.suffixEdit.text()
return config
def setconfig(self, config):
self.blockSignals(True)
max = config... | onfig.get('prefix', '')
suffix = config.get('suffix', '')
self.minEdit.setText(min)
self.maxEdit.setText(max)
self.prefixEdit.setText(prefix)
self.suffixEdit.setText(suffix)
self.blockSignals(False)
|
chenjiancan/wechatpy | wechatpy/client/api/wifi.py | Python | mit | 5,576 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from datetime import datetime, date
from optionaldict import optionaldict
from wechatpy.client.api.base import BaseWeChatAPI
class WeChatWiFi(BaseWeChatAPI):
API_BASE_URL = 'https://api.weixin.qq.com/bizwifi/'
def list_shops(s... | te, shop_id=-1):
"""
Wi-Fi数据统计
详情请参考
http://mp.weixin.qq.com/wiki/8/dfa2b756b66fca5d9b1211bc18812698.html
:param begin_date: 起始日期时间,最长时间跨度为30天
:param end_date: 结束日期时间戳,最长时间跨度为30天
:param shop_id: 可选,门店 ID,按门店ID搜索,-1为总统计
:return: 返回的 JSON 数据包
"""
... | ime('%Y-%m-%d')
if isinstance(end_date, (datetime, date)):
end_date = end_date.strftime('%Y-%m-%d')
res = self._post(
'statistics/list',
data={
'begin_date': begin_date,
'end_date': end_date,
'shop_id': shop_id
... |
kirklink/udacity-fullstack-p4 | conference.py | Python | apache-2.0 | 40,994 | 0.000488 | #!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import js... | return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if
non-existent."""
## TODO 2
## step 1: make sure u | ser is authed
## uncomment the following lines:
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
profile = p_key.get()
## step 2... |
GeoCat/QGIS | python/plugins/processing/algs/qgis/ExportGeometryInfo.py | Python | gpl-2.0 | 6,865 | 0.001165 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExportGeometryInfo.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
********************... | metry:
attrs.extend(self.point_attributes(inGeom))
elif inGeom.type() == QgsWkbTypes.PolygonGeometry:
attrs.extend(self.polygon_attributes(inGeom))
else:
attrs.extend(self | .line_attributes(inGeom))
outFeat.setAttributes(attrs)
sink.addFeature(outFeat, QgsFeatureSink.FastInsert)
feedback.setProgress(int(current * total))
return {self.OUTPUT: dest_id}
def point_attributes(self, geometry):
pt = None
if not geometry.isMultip... |
tcporco/SageBoxModels | boxmodel/boxmodel.py | Python | gpl-2.0 | 26,560 | 0.041679 | #*****************************************************************************
# Copyright (C) 2017 Lee Worden <worden dot lee at gmail dot com>
#
# Distributed under the terms of the GNU General Public License (GPL) v.2
# http://www.gnu.org/licenses/
#************************************************... | try: [ d[0] for d in pd ]
except | : self._parameter_dependencies[p] = [ (d,deps.index) for d in pd ]
#print 'parameter dependencies:', self._parameter_dependencies
self._bindings = bindings
if self._graph.get_pos() is None:
pos = { v:(i,0) for i,v in enumerate(self._vars) }
pos.update( { v:(-1,i) for i,v in enumera... |
flyhigher139/mayblog | blog/main/sitemaps.py | Python | gpl-2.0 | 968 | 0.004132 | #!/usr/bin/env pytho | n
# -*- coding: utf-8 -*-
from django.contrib.sitemaps | import Sitemap
from . import models
class BlogSitemap(Sitemap):
changefreq = "daily"
priority = 0.5
def items(self):
return models.Post.objects.filter(is_draft=False)
def lastmod(self, obj):
return obj.update_time
class PageSitemap(Sitemap):
changefreq = "monthly"
priority ... |
joke2k/django-options | django_options/formset.py | Python | bsd-3-clause | 4,546 | 0.00264 | from django import forms
from django.conf import settings
from django.contrib.admin.helpers import normalize_fieldsets, AdminReadonlyField, AdminField
from django.contrib.admin.templatetags.admin_static import static
from django.utils.safestring import mark_safe
class AdminForm(object):
def __init__(self, form, fi... | return self._description if self._description else self.form.descript | ion
def _media(self):
if 'collapse' in self.classes:
extra = '' if settings.DEBUG else '.min'
js = ['jquery%s.js' % extra,
'jquery.init.js',
'collapse%s.js' % extra]
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
... |
hjpwhu/Python | src/hjp.edu.nlp.data.task/semeval.py | Python | mit | 269 | 0.003717 | import codecs
f = codecs.open("/Users/hjp/Downloads/task/ | data/dev.txt", 'r', 'utf-8')
for line | in f.readlines():
print(line)
sents = line.split('\t')
print(sents[1] + "\t" + sents[3])
for i in range(len(sents)):
print(sents[i])
f.close()
|
vangalamaheshh/snakemake | snakemake/exceptions.py | Python | mit | 10,433 | 0.000192 | __author__ = "Johannes Köster"
__copyright__ = "Copyright 2015, Johannes Köster"
__email__ = "koester@jimmy.harvard.edu"
__license__ = "MIT"
import os
import traceback
from tokenize import TokenError
from snakemake.logging import logger
def format_error(ex, lineno,
linemaps=None,
s... | include=None,
| lineno=None,
snakefile=None,
rule=None):
"""
Creates a new instance of RuleException.
Arguments
message -- the exception message
include -- iterable of other exceptions to be included
lineno -- the line the exception origin... |
lordtangent/arsenalsuite | cpp/apps/absubmit/maya/pumpThread.py | Python | gpl-2.0 | 504 | 0.049603 |
import maya.cmds as cmds
import maya.utils as utils
import threading
import time
imp | ort sys
from PyQt4 import QtCore, QtGui
pumpedThread = None
app = None
def pumpQt():
global app
def processor():
app.processEvents()
while 1:
time.sl | eep(0.01)
utils.executeDeferred( processor )
def initializePumpThread():
global pumpedThread
global app
if pumpedThread == None:
app = QtGui.QApplication(sys.argv)
pumpedThread = threading.Thread( target = pumpQt, args = () )
pumpedThread.start()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.