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 |
|---|---|---|---|---|---|---|---|---|
cpcloud/numba | numba/cuda/args.py | Python | bsd-2-clause | 1,978 | 0 | """
Hints to wrap Kernel arguments to indicate how to manage host-device
memory transfers before & after the kernel call.
"""
import abc
from numba.core.typing.typeof import typeof, Purpose
class ArgHint(metaclass=abc.ABCMeta):
def __init__(self, value):
self.value = value
@abc.abstractmethod
de... | from .cudadrv.devicearray import auto_device
devary, conv = auto_device(
self.value,
copy=False,
| stream=stream)
if conv:
retr.append(lambda: devary.copy_to_host(self.value, stream=stream))
return devary
class InOut(ArgHint):
def to_device(self, retr, stream=0):
from .cudadrv.devicearray import auto_device
devary, conv = auto_device(
self.value,
... |
thanatos/lets-encrypt-preview | letsencrypt/plugins/webroot.py | Python | apache-2.0 | 6,187 | 0.000808 | """Webroot plugin."""
import errno
import logging
import os
from collections import defaultdict
import zope.interface
import six
from acme import challenges
from letsencrypt import errors
from letsencrypt import interfaces
from letsencrypt.plugins import common
logger = logging.getLogger(__name__)
@zope.interfac... | n:
if exception.errno == errno.EACCES:
logger.debug("Insufficient permissions to change owner and uid - ignoring")
else:
raise errors.PluginError(
"Couldn't create root for {0} http-01 "
... | if exception.errno != errno.EEXIST:
raise errors.PluginError(
"Couldn't create root for {0} http-01 "
"challenge responses: {1}", name, exception)
finally:
os.umask(old_umask)
def perform(self, achalls): ... |
andrewosh/thunder-streaming | python/thunder_streaming/feeder/core.py | Python | apache-2.0 | 4,148 | 0.004339 | """Core functions used by the Thunder streaming feeder scripts, including asynchronous checking for new files.
"""
import errno
import os
import time
from thunder_streaming.feeder.utils.filenames import getFilenamePostfix, getFilenamePrefix
from thunder_streaming.feeder.utils.logger import global_logger
from thunder_s... | ft -= 1
next_batch_file = None # reset in case of exception on next line
next_batch_file = next(walker)
delta = time.time() - os.stat(next_batch_file).st_mtime
walker_restart_file = next_batch_file
except StopIteration:
# no files lef... | filebatch:
global_logger.get().info("Out of files, waiting...")
walker = uw(source_dir, walker_restart_file, filefilterfunc=filename_predicate)
yield filebatch
def build_filecheck_generators(source_dir_or_dirs, mod_buffer_time, max_files=-1, filename_predicate=None):
if isinst... |
bytesized/Snappy-Symbolication-Server | tests/test_DiskCache.py | Python | mpl-2.0 | 6,210 | 0.002576 | import unittest
import os
import shutil
import json
import memcache
import testUtils
testUtils.addSymServerToPath()
import quickstart
LIB_NAME = "xul.pdb"
BREAKPAD_ID = "44E4EC8C2F41492B9369D6B9A059577C2"
EXPECTED_HASH = "6e5e6e422151b7b557d913c0ff86d7cf"
class testDiskCache(unittest.TestCase):
def setUp(self):... | s'],
"Value is still in cache after eviction")
request['action'] = 'cacheGet'
JSONrequest = json.dumps(request)
response = testUtils.symServerRequest(JSONrequest, ip="127.0.0.1",
port=self.config['DiskCache']['port'])
... | fyGenericResponse(self, response)
self.assertIn('path', response, "No path provided in response to Get")
# Don't test the md5 hash. We didn't get the raw symbol file.
self.assertTrue(os.path.exists(response['path']),
"Cached file does not exist after a cacheGet")
if __na... |
CloudVLab/professional-services | examples/dialogflow-entities-example/main.py | Python | apache-2.0 | 4,374 | 0.000914 | # python3
# ==============================================================================
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.or... | n an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Cloud function to create and update en... | port Dict, List
def entities_builder(request: flask.Request):
"""HTTP Cloud Function that create and update entities in Dialogflow.
Args:
request (flask.Request): The request object. More info:
<http://flask.pocoo.org/docs/1.0/api/#flask.Request>
"""
request_json = request.get_json(silent=True)
... |
partofthething/home-assistant | tests/components/wemo/conftest.py | Python | apache-2.0 | 2,417 | 0 | """Fixtures for pywemo."""
import asyncio
from unittest.mock import create_autospec, patch
import pytest
import pywemo
from homeassistant.components.wemo import CONF_DISCOVERY, CONF_STATIC
from homeassistant.components.wemo.const import DOMAIN
from homeassistant.setup import async_setup_component
MOCK_HOST = "127.0.... | device.name = MOCK_NAME
device.serialnumber = MOCK_SERIAL_NUMBER
device.model_name = pywemo_model
device.get_state.return_value = 0 # Default to Off
url = f"http://{MOCK_HOST}:{MOCK_PORT}/setup.xml"
with patch("pywemo.setup_url_for_address", return_value=url), patch(
"pywemo. | discovery.device_from_description", return_value=device
):
yield device
@pytest.fixture(name="wemo_entity")
async def async_wemo_entity_fixture(hass, pywemo_device):
"""Fixture for a Wemo entity in hass."""
assert await async_setup_component(
hass,
DOMAIN,
{
DOM... |
adamcandy/QGIS-Meshing | scripts/generate_field_xyz_data.py | Python | lgpl-2.1 | 12,891 | 0.035761 | import numpy as np
##########################################################################
#
# QGIS-meshing plugins.
#
# Copyright (C) 2012-2013 Imperial College London and others.
#
# Please see the AUTHORS file in the main source directory for a
# full list of copyright holders.
#
# Dr Adam S. Candy... | op(0)
sinxStr = sinxStr.split(')')
sinxStr[0] = ' '+sinxStr[0]
sinxStr = map(lambda x: x[2:],s | inxStr)
sinxStr.pop()
for i in range(len(sinxStr)):
self.f_add()
sinxStr = map(lambda x: x.split(','), sinxStr)
self.Sinx = map(lambda x: map(lambda y: float(y), x), sinxStr)
def siny_set( self ):
#form "(cont,w,phi),..."
sinyStr = self.ArgList.pop(0)
sinyStr = sinyStr.s... |
ScienceWorldCA/domelights | backend/scripts/checkerboard.py | Python | apache-2.0 | 510 | 0.041176 | # Generates alternating frames of a checkerboard pattern.
Q_STARTING_INDEX = 150
UNIVERSE_LIGHTS = 144 #144 for side 1, #116 for side 2
flip = 0
for i in range(1,200): # 5 seconds * 40 / second (frame)
print "Record Cue " + str(Q_STARTING_INDEX + i)
for j in r | ange (1, UNIVERSE_LIGHTS * 3, 1): # 3 channels / light (channel)
value = 255 if flip else 0
flip = not flip
print "C"+ str(j)+ " @ #"+str(value)+";"
flip = not flip # switch the checkerboard for the next frame
print "Record | Stop"
|
capone212/crashtec | src/crashtec/db/provider/test/testroutines.py | Python | gpl-3.0 | 7,533 | 0.010885 | '''
Created on 12.05.2013
@author: capone
'''
import unittest
from mock import patch
from mock import MagicMock
from crashtec.db.provider.routines import Record
from crashtec.db.provider import routines
from crashtec.utils.exceptions import CtCriticalError
def _get_sample_record():
return {'key1' : 'value2', 'ke... | :
record[key] = value
updated_values = record.updated_values()
self.assertEqual(updated_values, modifier)
# Modify second time
modifier2 = {initial.keys()[0] : 'garbage2: reload',
'mock_key2' : 'mock_value2'}
for key, value in modifier2.... | s = record.updated_values()
self.assertEqual(updated_values, modifier2)
class TestCursor(unittest.TestCase):
def test_fetch_one_returns_record(self):
# Prepare mock object
mock_impl = MagicMock(spec_set = ['fetchone'])
mock_impl.fetchone = MagicMock(return_value = self.get_sample_r... |
iogf/ginger | setup.py | Python | bsd-2-clause | 307 | 0.003257 | #! /usr | /bin/env python
from distutils.core import setup
setup(name="ginger",
version="0.1",
description="HTML/CSS in python.",
packages=["ginger"],
scripts=["ginger-designer"],
author="Iury O. G. Figueiredo",
author_email="[email protected]")
| |
kleintom/dxr | tooling/peep.py | Python | mit | 36,017 | 0.001083 | #!/usr/bin/env python
"""peep ("prudently examine every package") verifies that packages conform to a
trusted, locally stored hash and only then installs them::
peep install -r requirements.txt
This makes your deployments verifiably repeatable without having to maintain a
local PyPI mirror or use a vendor lib. Ju... | m tempfile import mkdtemp
import traceback
try:
from urllib2 import | build_opener, HTTPHandler, HTTPSHandler, HTTPError
except ImportError:
from urllib.request import build_opener, HTTPHandler, HTTPSHandler
from urllib.error import HTTPError
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse # 3.4
# TODO: Probably use six to make u... |
derickr/openstreetbugs | stats/stats.py | Python | gpl-3.0 | 2,957 | 0.016233 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Mitja Kleider
#
# This file is part of Openstreetbugs.
#
# Openstreetbugs 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 t... | ime.strftime(result[0],"%b %Y")
newbugs = result[1]
cursor.execute("""SELECT COUNT(*) as closedbugs FROM bugs WHERE last_changed < DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL """+"%d"%interval+""" MONTH), "%Y-%m-01") AND last_changed >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL """+"%d"%(interval+1)+""" MONTH), "%Y-%m-... | /td><td>%s</td></tr>" % (month, newbugs, closedbugs)
print "</body>\n</html>"
main()
|
healthchecks/healthchecks | hc/front/tests/test_update_timeout.py | Python | bsd-3-clause | 7,228 | 0.000277 | from datetime import timedelta as td
from django.utils import timezone
from hc.api.models import Check
from hc.test import BaseTestCase
class UpdateTimeoutTestCase(BaseTestCase):
def setUp(self):
super().setUp()
self.check = Check(project=self.project, status="up")
self.check.last_ping = ... | .check.status = "up"
self.check.alert_after = self.check.going_down_after()
self.check.save()
# 1 + 1 minute:
payload = {"kind": "simple", "timeout": 60, "grace": 60}
self.client.login(username="[email protected]", password="password")
self.client.post(self.url, data=pa... | elf):
payload = {"kind": "cron", "schedule": "5 * * * *", "tz": "UTC", "grace": 60}
self.client.login(username="[email protected]", password="password")
r = self.client.post(self.url, data=payload)
self.assertRedirects(r, self.redirect_url)
self.check.refresh_from_db()
... |
FreshXOpenSource/wallaby-base | wallaby/pf/peer/sm.py | Python | bsd-2-clause | 4,120 | 0.00267 | # Copyright (c) by it's authors.
# Some rights reserved. See LICENSE, AUTHORS.
from peer import *
class SMPeer(Peer):
def __init__(self, room, statePillow, states=[], initState="Start"):
Peer.__init__(self, room)
self._routings = set()
self._transitions = set()
self._callbacks = s... | self._state._transitionState(*args)
def _callback(self, *args):
self._state._callback(*args)
def switchState(self, stateName):
# Already in correct state
if self._state != None and self._state._name == stateName: return
# print "Switch to state", stateName, "in context", self... | Switched()
class State:
def __init__(self, name=None):
if name:
self._name = name
else:
self._name = self.__class__.__name__
self._stateMachine = None
self._routings = {}
self._transitions = {}
self._callbacks = {}
self._localCallback... |
Castronova/EMIT | gui/examples/xml.py | Python | gpl-2.0 | 877 | 0.036488 | __author__ = 'tonycastronova'
import xml.etree.ElementTree as et
from xml.dom import minidom
def prettify(elem):
"""
Return a pretty-printed XML string for the Element.
"""
rough_string = et.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(inde... | del',attributes)
attributes = {'Name':'mymodel2','path':'/some/path2','x':'20','y':'200'}
et.SubElement(tree,'Model',attributes)
attributes = {'From':'mymodel','To':'mymodel2','FromItem':'variable1','ToItem':'variable2'}
et.SubElement(tree,'Link',attributes)
prettyxml = prettify(tree)
with open('/Users/tonycastrono... | sts/test.xml','w') as f:
f.write(prettyxml)
print 'done' |
declension/squeeze-alexa | squeezealexa/__init__.py | Python | gpl-3.0 | 1,050 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2017-18 Nick Boultbee
# This file is part of squeeze-alexa.
#
# squeeze-alexa is free software: you can re | distribute 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.
#
# See LICENSE for full license
from os.path import dirname
from typing import Dict, Any
ROOT_DIR = dirname(dirname(__fil... |
willkg/socorro-collector | collector/unittest/app/test_socorro_app.py | Python | mpl-2.0 | 8,093 | 0.003336 | import mock
from nose.tools import eq_, ok_, assert_raises
from collector.unittest.testbase import TestCase
from configman import (
class_converter,
Namespace,
command_line,
ConfigFileFutureProxy,
)
from configman.dotdict import DotDict
from collector.app.socorro_app import (
SocorroApp,
Socor... | isinstance(kwargs['values_source_list'], list))
eq_(kwargs['app_name'], SomeOtherApp.app_name)
eq_(kwargs['app_version'], SomeOtherApp.app_version)
eq_(kwargs['app_description'], SomeOtherApp.app_description)
eq_(kwargs['config_pathname'], './config')
... | 3] is ConfigFileFutureProxy)
ok_(isinstance(
kwargs['values_source_list'][0],
ApplicationDefaultsProxy
))
eq_(result, 17)
#--------------------------------------------------------------------------
def test_do_run_with_alte... |
rustyrazorblade/machete | machete/wiki/tests/test_create_page.py | Python | bsd-3-clause | 1,075 | 0.003721 | from unittest import TestCase
from machete.base.tests import IntegrationTestCase
from machete.wiki.models import Wiki, Page
class CreatePageTest(TestCase):
def test_create_page(self):
wiki = Wiki.create()
page = wiki.create_page("test name [Some link]",
"/index.html... | elf.project.vid)
response = self.post(url, {"url":"TestPage",
"name":"Whatever bro",
"text":"this is a test"})
self.assert200(response)
url = "/projects/{}/wiki/TestPage".format(self.project.vid)
response = self.get(u... | sponse)
|
neuromat/nira | person/apps.py | Python | mpl-2.0 | 199 | 0 | # member/apps.py
from django.apps import AppConfig
from django.utils.translation import ugettext_laz | y as _
class MemberConfig(AppConfig):
| name = 'person'
verbose_name = _('Personal Info')
|
weiting-chen/manila | manila/api/urlmap.py | Python | apache-2.0 | 10,165 | 0 | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | ect):
def __init__(self, value):
self._content_types = [parse_options_header(v) for v in
parse_list_header(value)]
def best_match(self, supported_content_types):
# FIXME: Should we have a mor | e sophisticated matching algorithm that
# takes into account the version as well?
best_quality = -1
best_content_type = None
best_params = {}
best_match = '*/*'
for content_type in supported_content_types:
for content_mask, params in self._content_types:
... |
google-research/tensorflow_constrained_optimization | tensorflow_constrained_optimization/python/rates/general_rates.py | Python | apache-2.0 | 52,315 | 0.002772 | # Copyright 2018 The TensorFlow Constrained Optimization Authors. All Rights
# Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... | s in this file take the optional "positive_class" parameter,
which tells us which classes sh | ould be considered "positive" (for e.g. the
positive prediction rate). This parameter *must* be provided for multiclass
contexts, and must *not* be provided for non-multiclass contexts.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow a... |
shrimpboyho/git.js | emscript/emscripten/1.5.6/tools/asm_module.py | Python | gpl-2.0 | 10,782 | 0.013356 |
import sys, re
import shared, js_optimizer
class AsmModule():
def __init__(self, filename):
self.filename = filename
self.js = open(filename).read()
self.start_asm = self.js.find(js_optimizer.start_asm_marker)
self.start_funcs = self.js.find(js_optimizer.start_funcs_marker)
self.end_funcs = s... | lf.pre_js).group(0)
# global initializers
global_inits = re.search(shared.JS.global_initializers_pattern, self.pre_js)
if global_inits:
self.global_inits_js = global_inits.group(0)
self.global_inits = map(lambda init: init.split('{')[2][1:].split('(')[0], global_inits.groups(0)[0].split(','))
... | elf.js.find('var ', self.start_asm)+4)
self.pre_imports_js = self.js[self.start_asm:first_var]
self.imports_js = self.js[first_var:self.start_funcs]
self.imports = {}
for imp in js_optimizer.import_sig.finditer(self.imports_js):
key, value = imp.group(0).split('var ')[1][:-1].split('=', 1)
s... |
chronicle/api-samples-python | service_management/update_gcp_settings_test.py | Python | apache-2.0 | 2,741 | 0.004743 | # Copyright 2021 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, s... | se).status_code = mock.PropertyMock(return_value=400)
mock_response.raise_for_status.side_effect = (
requests.requests.exceptions.HTTPError())
with self.assertRaises(requests.requests.exceptions.HTTPError):
update_gcp_settings.update_gcp_settings(mock_session, 123, True)
|
@mock.patch.object(requests, "AuthorizedSession", autospec=True)
@mock.patch.object(requests.requests, "Response", autospec=True)
def test_happy_path(self, mock_response, mock_session):
mock_session.request.return_value = mock_response
type(mock_response).status_code = mock.PropertyMock(return_value=200)... |
ul-fmf/projekt-tomo | web/web/settings/local.py | Python | agpl-3.0 | 916 | 0.001092 | from .common import *
INSTALLED_APPS += [
'silk',
]
MIDDLEWARE_CLASSES.insert(0, 'silk.middleware.SilkyMiddleware')
SECRET_KEY = '0vb+-_-52phz@ii^cxr+mlgvmn6fctd+v5qpnv&k+-00#u-==0'
DEBUG = True
ALLOWED_HOSTS = []
WSGI_APPLICATION = 'web.wsgi.local.application'
DATABASES = {
'default': {
'ENGINE':... | 'USER': 'matija',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
}
}
STATIC_URL = '/static/'
LOGIN_URL = '/accounts/login/'
LOGOUT_URL = '/accounts/logout/'
LOGIN_REDIRECT_URL = '/'
SUBMISSION_URL = 'http://127.0.0.1:8000'
# Use nose to run all te | sts
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
# Tell nose to measure coverage on the 'problems', 'attemtps', 'courses' and 'users' apps
NOSE_ARGS = [
'--with-coverage',
'--cover-package=problems,attempts,courses,users,utils',
]
|
tgcmteam/tgcmlinux | src/tgcm/ui/windows/PukDialog/__init__.py | Python | gpl-2.0 | 32 | 0 | from PukDialog im | port Puk | Dialog
|
ST-Data-Mining/crater | george/nn.py | Python | mit | 1,547 | 0.032321 | from __future__ import division,print_function
from os import environ
im | port sys
HOME=environ['HOME']
PROJECT_ROOT=HOME+'/Panzer/NCSU/Spatial and Temporal/crater'
EXPTS = PROJECT_ROOT+'/expts'
sys.path.extend([PROJECT_ROOT,EXPTS])
sys.dont_write_bytecode = True
from sklearn.neural_network import BernoulliRBM
from sklearn.linear_model import LogisticRegression |
from sklearn.pipeline import Pipeline
from george.lib import *
from expts.csvParser import parseCSV, randomPoints
import config
def builder(fname = config.TRAIN_FILE, hiddens=256, learn_rate=0.01):
points = parseCSV(fname, False)
rbm = BernoulliRBM(n_components=hiddens,learning_rate=learn_rate,n_iter=30,random_st... |
google-research/google-research | structformer/utils.py | Python | apache-2.0 | 1,703 | 0.008808 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | source, i, batch_size, pad=0):
total_length = 0
data = []
w | hile total_length < batch_size and i < len(source):
data.append(source[i])
total_length += len(source[i])
i += 1
length = [len(seq) for seq in data]
max_l = max(length)
data_padded = []
for seq in data:
data_padded.append(seq + [pad] * (max_l - len(seq)))
data_mat = torch.Lon... |
naresh21/synergetics-edx-platform | lms/djangoapps/grades/api/views.py | Python | agpl-3.0 | 6,482 | 0.001543 | """ API v0 views. """
import logging
from django.http import Http404
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_... | d: A string representation of a Course ID.
* username: A string representation of a user's username.
**GET Response Values**
If the request for information about the course grade
is successful, an HTTP 200 "OK" response is returned.
The HTTP 200 response has the following values.
... | in the request.
* course_id: A string representation of a Course ID.
* passed: Boolean representing whether the course has been
passed according the course's grading policy.
* percent: A float representing the overall grade for the course
* letter_grade: A letter gr... |
tdjordan/tortoisegit | tracelog.py | Python | gpl-2.0 | 4,176 | 0.006705 | #
# A PyGtk-based Python Trace Collector window
#
# Copyright (C) 2007 TK Soh <[email protected]>
#
import pygtk
pygtk.require("2.0")
import gtk
import gobject
import pango
import threading
import Queue
import win32trace
try:
from gitgtk.gitlib import toutf
except ImportError:
import locale
_encoding = ... | ospace"))
scrolledwindow.add(self.textview)
self.textview.set_editable(False)
self.textbuffer = self.textview.get_buffer()
self.vbox.pack_start(scrolledwindow, True, True)
self.vbox.show_all() |
# add buttons
self._button_quit = gtk.Button("Quit")
self._button_quit.connect('clicked', self._on_ok_clicked)
self.action_area.pack_end(self._button_quit, False, False, 5)
self._button_clear = gtk.Button("Clear")
self._button_clear.connect('clicked', self._on_... |
meee1/pymavlink | mavextra.py | Python | lgpl-3.0 | 1,082 | 0.005545 | #!/usr/bin/env python
'''
useful extra functions for use by mavlink clients
Copyright Andrew Tridgell 201 | 1
Released under GNU | GPL version 3 or later
'''
from math import *
def norm_heading(RAW_IMU, ATTITUDE, declination):
'''calculate heading from RAW_IMU and ATTITUDE'''
xmag = RAW_IMU.xmag
ymag = RAW_IMU.ymag
zmag = RAW_IMU.zmag
pitch = ATTITUDE.pitch
roll = ATTITUDE.roll
headX = xmag*cos(pitch) + ymag*si... |
apyrgio/ganeti | lib/impexpd/__init__.py | Python | bsd-2-clause | 17,841 | 0.007679 | #
#
# Copyright (C) 2010 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:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | CommandBuilder(object):
def __init__(self, mode, opts, socat_stderr_fd, dd_stderr_fd, dd_pid_fd):
"""Initializes this class.
@param mode: Daemon mode (import or export)
@param opts: Options object
@type socat_stderr_fd: int
@param socat_stderr_fd: File descriptor socat should write its stderr to... | d write its stderr to
@type dd_pid_fd: int
@param dd_pid_fd: File descriptor the child should write dd's PID to
"""
self._opts = opts
self._mode = mode
self._socat_stderr_fd = socat_stderr_fd
self._dd_stderr_fd = dd_stderr_fd
self._dd_pid_fd = dd_pid_fd
assert (self._opts.magic is ... |
Daphron/project-euler | p39.py | Python | gpl-3.0 | 697 | 0.005739 | #TODO: make under 1 | min.
#SOLVED
import math
MAX_P = 1000
best_p = 120
best_num_sides = 3
for p in range(2, MAX_P+1):
num_sides = 0
if p % 30 == 0:
print(p)
for a in range(1, MAX_P/2 + 2):
for b in range(1, MAX_P/2 + 2):
c = p - a - b
if a > b and b > c and c**2 + b**2 == a**2 and a ... | # print("sides {} {} {}".format(a,b,c))
# print("P={}".format(p))
num_sides += 1
if num_sides > best_num_sides:
# print("Change to p={}".format(p))
# import pdb; pdb.set_trace()
best_num_sides = num_sides
best_p = p
print("Done")
print(b... |
schlos/OIPA-V2.1 | OIPA/iati_synchroniser/models.py | Python | agpl-3.0 | 5,972 | 0.003684 | from django.db import models
import datetime
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from iati_synchroniser.dataset_syncer import DatasetSyncer
from iati_synchroniser.codelist_importer import CodeListImporter
from iati.parser import Parser
from iati_synchron... | time.datetime.today()):
self.sync_dataset_with_iati_api()
elif self.interval == u'DAILY' and (self.date_updated+datetime.timedelta(1) <= datetim | e.datetime.today()):
self.sync_dataset_with_iati_api()
def sync_dataset_with_iati_api(self):
syncer = DatasetSyncer()
syncer.synchronize_with_iati_api(self.type)
class CodelistSync(models.Model):
date_updated = models.DateTimeField(auto_now=True, editable=False)
class Meta:... |
adityahase/frappe | frappe/modules/utils.py | Python | mit | 8,881 | 0.026461 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
"""
Utilities for using modules
"""
import frappe, os, json
import frappe.utils
from frappe import _
from frappe.utils import cint
def export_module_json(doc, is... | doctypes = list(set(map(lambda row: row.get(doctype_fieldname), data[key])))
# sync singl | e doctype exculding the child doctype
def sync_single_doctype(doc_type):
def _insert(data):
if data.get(doctype_fieldname) == doc_type:
data['doctype'] = custom_doctype
doc = frappe.get_doc(data)
doc.db_insert()
if custom_doctype != 'Custom Field':
frappe.db.sql('delete from `tab{0}` whe... |
psi4/psi4meta | conda-recipes/psi4-docs/run_coverage.py | Python | gpl-2.0 | 4,093 | 0.001466 | import os
import copy
import time
from pathlib import Path
import subprocess as sp
from multiprocessing import Pool
objdir = Path(os.environ['SRC_DIR']) / 'build'
cb_threads = int(os.environ['CPU_COUNT'])
coverage_exe = Path(os.environ['PREFIX']) / 'bin' / 'coverage'
lenv = copy.deepcopy(os.environ)
pythonpath = objdi... | e", " | stage/bin/psi4", tpath]
elif tpath.name == "input.py":
cmd = [coverage_exe, "run", "--parallel-mode", tpath]
t = time.time()
outfile.write('<<< #{} {} >>>'.format(tnum, tlabel))
retcode = sp.call(cmd, stdout=outfile, stderr=errfile, env=lenv)
total_time = time.time() - t
if retcode =... |
clouserw/zamboni | mkt/langpacks/tests/test_models.py | Python | bsd-3-clause | 13,411 | 0 | # -*- coding: utf-8 -*-
import json
import os
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.forms import ValidationError
from mock import patch
from nose.tools import eq_, ok_
from lib.crypto.packaged import SigningError
from mkt.files.helpers import co... | 'de': {
'version': '2014110512 | 34',
'apps': {
'app://calendar.gaiamobile.org/manifest.webapp':
'/de/calendar',
'app://email.gaiamobile.org/manifest.webapp':
'/de/email'
},
'name': 'Deutsch'
}
},
... |
googleapis/docuploader | docuploader/tar.py | Python | apache-2.0 | 2,102 | 0 | # Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"--verbose",
" | .",
],
hide_output=False,
)
def decompress(archive: str, destination: str) -> subprocess.CompletedProcess:
"""Decompress the given tarfile to the destination."""
# Note: we don't use the stdlib's "tarfile" module for performance reasons.
# While it can handle creating tarfiles, its not... |
ItsCalebJones/SpaceLaunchNow-Server | api/migrations/0020_launch_new_id.py | Python | apache-2.0 | 860 | 0.001163 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2018-12-04 22:15
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
def create_ids(apps, schema_editor):
Launch = apps.get_model('api', 'Launch')
for m in Launch.objects.all():
m.new_id = uuid.uuid4()
... | api', '0019_auto_20181206_0135'),
]
operations = [
migrations.AddField(
model_name='launch',
name='new_id',
field=models.UUIDField(default=uuid.uuid4),
) | ,
migrations.RunPython(code=create_ids, reverse_code=remove_ids),
]
|
DaanHoogland/cloudstack | plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVmModule.py | Python | apache-2.0 | 22,802 | 0.00614 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | = OvmHost()._vmNameToPath(vmName)
domId = OvmHost()._getDomainIdByName(vmName)
vifs = successToMap(xen_get_vifs(vmPath))
lst = []
for k in vifs:
v = vifs[k]
vifName = 'vif' + domId + '.' + k[len('vif'):]
vif = OvmVif()
(mac, bridge, type) =... | safeSetAttr(vif, 'mac', mac)
safeSetAttr(vif, 'bridge', bridge)
safeSetAttr(vif, 'type', type)
lst.append(vif)
return lst
def _getVifsFromConfig(self, vmPath):
vifs = successToMap(xen_get_vifs(vmPath))
lst = []
for k in vifs:
... |
noam09/deluge-telegramer | telegramer/include/telegram/inline/inlinequeryresultcachedmpeg4gif.py | Python | gpl-3.0 | 3,901 | 0.003076 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Leandro Tol | edo de Souza <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either vers | ion 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should... |
jodal/comics | comics/aggregator/utils.py | Python | agpl-3.0 | 333 | 0 | from comics.comics import get_comic_module
SCHEDULE_DAYS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
def get_comic_schedule(comic):
module = get_comic_module(comic.sl | ug)
schedule | = module.Crawler(comic).schedule
if not schedule:
return []
return [SCHEDULE_DAYS.index(day) for day in schedule.split(",")]
|
bhermanmit/openmc | tests/test_multipole/test_multipole.py | Python | mit | 3,870 | 0.001809 | #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness, PyAPITestHarness
import openmc
from openmc.stats import Box
from openmc.source import Source
class MultipoleTestHarness(PyAPITestHarness):
def _build_inputs(self):
####################
... | =11, fill=dense_fuel, region=-r0)
c11.temperature = [500, 0, 700, 800]
c12 = openmc.Cell(cell_id=12, fill=moderator, region=+r0)
fuel_univ = openmc.Universe(universe_id=11, cells=(c11, c12))
lat = openmc.RectLattice(lattice_id=101)
lat.dimension = [2, 2]
lat.lower_left =... |
lat.pitch = [2.0, 2.0]
lat.universes = [[fuel_univ]*2]*2
lat.outer = mod_univ
x0 = openmc.XPlane(x0=-3.0)
x1 = openmc.XPlane(x0=3.0)
y0 = openmc.YPlane(y0=-3.0)
y1 = openmc.YPlane(y0=3.0)
for s in [x0, x1, y0, y1]:
s.boundary_type = 'reflecti... |
sergiocorato/partner-contact | partner_capital/models/res_partner_turnover_range.py | Python | agpl-3.0 | 431 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Antonio Espinosa <[email protected]>
# Copyright 2015 Jairo Llopis <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResPartnerTurnoverRange(models.Model):
_name = 'res.part... | ion = "Turnover range"
name = fields.Char(required=True, translate | =True)
|
mcrav/XDToolkit | src/splash.py | Python | gpl-3.0 | 1,610 | 0.001863 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'splash.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_splash(object):
def setupUi(self, splash):
splash.setObjectName... |
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.verticalLayout.addWidget(self.progressBar)
self.statusLab = QtWidgets.QLabel(splash)
self.statusLab.setText("")
self.statusLab.setObjectName("statusLab")
self.verticalLay... | def retranslateUi(self, splash):
_translate = QtCore.QCoreApplication.translate
splash.setWindowTitle(_translate("splash", "Initializing"))
|
mozilla/amo-validator | tests/test_unicodehelper.py | Python | bsd-3-clause | 1,282 | 0 | # -*- coding: utf-8 -*- |
import validator.unicodehelper as unicodehelper
COMPARISON = 'täst'.decode('utf-8')
def _do_test(path):
'Performs a test on a JS file'
text = open(path).read()
utext = unicodehelper.decode(text)
print utext.encode('ascii', 'backslashreplace')
assert utext == COMPARISON
def test_latin1():
... | |
ntt-sic/neutron | neutron/openstack/common/notifier/api.py | Python | apache-2.0 | 5,734 | 0 | # Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | ation_driver)
return _drivers.values()
def add_driver(notification_driver):
"""Add a notification driver at runtime."""
# Make sure the driver list is initialized.
_get_drivers()
if | isinstance(notification_driver, basestring):
# Load and add
try:
driver = importutils.import_module(notification_driver)
_drivers[notification_driver] = driver
except ImportError:
LOG.exception(_("Failed to load notifier %s. "
"Thes... |
djc/awmy | zones.py | Python | mit | 1,974 | 0.048632 | #!/usr/bin/env python
import sys, os, re, tarfile, json
FILES = {
'africa', 'antarctica', 'asia', 'australasia',
'europe', 'northamerica', 'southamerica',
}
WS_SPLIT = re.compile("[ \t]+")
def lines(fn):
with tarfile.open(fn, 'r:*') as tar:
for info in tar:
if not info.isfile() or info.name not in FILE... | re
else:
assert False, ln
return {'zones': zones, 'rules': rules}
if __name__ == '__main__':
path = sys.argv[1]
version = re.match('t | zdata(.*)\.tar\.gz$', os.path.basename(path))
if version is None:
raise StandardError('argument must be tzdata archive')
print(json.dumps(parse(path)))
|
nlehuby/osm2gtfs | osm2gtfs/tests/creators/tests_ni_managua.py | Python | gpl-3.0 | 1,515 | 0.00066 | import unittest
import os
import logging
from osm2gtfs.tests.creators.creators_tests import CreatorsTestsAbstract
# Defin | e logging level
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
class TestCreatorsNiManagua(CreatorsTestsAbstract):
def _get_selector(self):
return "ni_managua"
def _get_required_variables(self):
# Define required values for the tests of this provider
return {
... | 'stops_count': 1450,
'stations_count': 547,
'stops_osm_count': 1997,
'route_id_to_check': 111,
'gtfs_files': [
"agency.txt", "calendar.txt", "routes.txt", "shapes.txt",
"stops.txt", "stop_times.txt", "trips.txt"
],
}
... |
grandmasterchef/WhatManager2 | whatify/urls.py | Python | mit | 531 | 0.001883 | from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(r'^$', 'whatify.views.index'),
url(r'^search/(.+)$', 'whatify.views.search'),
url(r | '^torrent_groups/(\d+)$', 'whatify.views.get_torrent_group'),
url(r'^torrent_groups/(\d+)/download$', ' | whatify.views.download_torrent_group'),
url(r'^torrent_groups/random$', 'whatify.views.random_torrent_groups'),
url(r'^torrent_groups/top10$', 'whatify.views.top10_torrent_groups'),
url(r'^artists/(\d+)$', 'whatify.views.get_artist'),
)
|
matrix-org/sydent | sydent/config/sms.py | Python | apache-2.0 | 2,871 | 0.001393 | # Copyright 2021 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | parts = origString.split(":")
if len(parts) != 2:
| raise ConfigError(
"Originators must be in form: long:<number>, short:<number> or alpha:<text>, separated by commas"
)
if parts[0] not in ["long", "short", "alpha"]:
raise ConfigError(
... |
kashiif/ShaniXBMCWork | plugin.video.live.streamspro/oneplay.py | Python | gpl-2.0 | 11,723 | 0.019193 | ## ONLY FOR NOOBS :D
##CONVERSION OF following encryption by shani into python
## only decryption function is implemented
'''
* jQuery JavaScript Library v1.4.2
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
*... | ,16):
v = y; s = k; p = M; g = x;
y = func_L_o(y, k, M, x, S[l + 0], 7, m[4])
x = func_L_o(x, y, k, M, S[l + 1], 12, m[5])
M = func_L_o(M, x, y, k, S[l + 2], 17, m[6])
k = func_L_o(k, M, x, y, S[l + 3], 22, m[7])
y = func_L_o(y, k, M, x, S[l + 4], 7, m[8])
... | 17, m[10])
k = func_L_o(k, M, x, y, S[l + 7], 22, m[11])
y = func_L_o(y, k, M, x, S[l + 8], 7, m[12])
x = func_L_o(x, y, k, M, S[l + 9], 12, m[13])
M = func_L_o(M, x, y, k, S[l + 10], 17, m[14])
k = func_L_o(k, M, x, y, S[l + 11], 22, m[15])
y = func_L_o(y, k, M, x... |
terranum-ch/GraphLink | test/test_gk_graphic.py | Python | apache-2.0 | 1,094 | 0.003656 | #!/urs/bin/python
import os
import sys
import pytest
from .context import graphlink
from .context import OUTPUT_TEST_PATH
from graphlink.core.gk_link import GKLink
from graphlink.core.gk_node import GKNode
from graphlink.core.gk_node import GK_SHAPE_TYPE
from graphlink.core.gk_graphic import GKGraphic
def test_gk_... | est_graphic_result.pdf"))
def test_gk_graphic_image():
node1 = GKNode("Node1", shape=GK_SHAPE_TYPE[2])
node2 = GKNode("Node2")
myl1 = GKLink(node1, node2)
graph = GKGraphic()
assert graph.add_link(myl1) is True
assert graph.render(os.path.join(OUTPUT_TEST_PATH, "test_graphic_result"), extensi... | PUT_TEST_PATH, "test_graphic_result.png"))
|
tdsticks/crontab | py/wiki20/wiki20/controllers/error.py | Python | gpl-2.0 | 1,250 | 0.0008 | # -*- coding: utf-8 -*-
"""Error controller"""
from tg import request, expose
from wiki20.lib.base import BaseController
__all__ = ['ErrorController']
class ErrorController(BaseController):
"""
Generates error documents as and when they are required.
The ErrorDocuments middleware forwards to ErrorContro... | leware in your config/middleware.py file.
"""
@expose('wiki20.templates.error')
def document(self, *args, **kwargs):
"""Render the error document"""
resp = request.environ.get('tg.original_response')
try:
| # tg.abort exposes the message as .detail in response
message = resp.detail
except:
message = None
if not message:
message = ("<p>We're sorry but we weren't able to process "
" this request.</p>")
values = dict(prefix=reque... |
goldmedal/spark | python/pyspark/ml/stat.py | Python | apache-2.0 | 16,949 | 0.002537 | #
# 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 us... | elds:
- `pValue: Double`
- `statistic: Double`
>>> from pyspark.ml.stat import KolmogorovSmirnovTest
>>> dataset = [[-1.0], [0.0], [1.0]]
>>> dataset = spark.createDataFrame(dataset, ['s | ample'])
>>> ksResult = KolmogorovSmirnovTest.test(dataset, 'sample', 'norm', 0.0, 1.0).first()
>>> round(ksResult.pValue, 3)
1.0
>>> round(ksResult.statistic, 3)
0.175
>>> dataset = [[2.0], [3.0], [4.0]]
>>> dataset = spark.createDataFrame(dataset, [' |
digitalocean/netbox | netbox/utilities/validators.py | Python | apache-2.0 | 1,580 | 0.003165 | import re
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import _lazy_re_compile, BaseValidator, URLValidator
class EnhancedURLValidator(URLValidator):
"""
Extends Django's built-in URLValidator to permit the use of hostnames with no domain ext... | # Port number
r'(?:[/?#][^\s]*)?' # Path
r'\Z', re.IGNORECASE)
schemes = settings.ALLOWED_URL_SCHEME | S
class ExclusionValidator(BaseValidator):
"""
Ensure that a field's value is not equal to any of the specified values.
"""
message = 'This value may not be %(show_value)s.'
def compare(self, a, b):
return a in b
def validate_regex(value):
"""
Checks that the value is a valid re... |
buddyd16/Structural-Engineering | Steel/bolt_group_istantaneous_center.py | Python | bsd-3-clause | 8,880 | 0.021284 | '''
BSD 3-Clause License
Copyright (c) 2019, Donald N. Bockoven III
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
l... | ture__ import division
import math as m
def build_bolt_group(numCols, numRows, Colspacing, Rowspacing):
# Given a number of rows and columns
# return the x and y coordinate lists
# starting with the first bolt at (0,0)
xloc = [0]
yloc = [0]
i=0
y=0
for i in ra | nge(numCols):
if i == 0:
y=0
for y in range(numRows-1):
xloc.append(xloc[-1])
yloc.append(yloc[-1]+Rowspacing)
else:
x = xloc[-1] + Colspacing
xloc.append(x)
yloc.append(0)
y=0
... |
gchinellato/Self-Balance-Robot | nfs-server/modules/PanTilt/Test/panTilt-gpio.py | Python | gpl-3.0 | 6,361 | 0.010061 | #!/usr/bin/python
"""
*************************************************
* @Project: Self Balance
* @Description: Pan Tilt - Micro Servo motors API with RPI.GPIO
* @Owner: Guilherme Chinellato
* @Email: [email protected]
**************... | self.pwmH = GPIO.PWM(SERVO_H_GPIO, FREQ)
self.status = 0
logging.info("Pan-Tilt Thread initialized")
#Override method
def run(self):
| self._startPWM(0, 0)
lastTime = 0.0
while not self._stopEvent.wait(self._sleepPeriod):
try:
self._lock.acquire()
currentTime = time.time()
#Calculate time since the last time it was called
#if (self.debug):
... |
jeromeetienne/webglmeeting0 | apprtc/apprtc.py | Python | mit | 6,313 | 0.015207 | #!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.
# pylint: disable-msg=C6310
"""WebRTC Demo
This module demonstrates the WebRTC API by implementing a simple video chat app.
"""
import datetime
import logging
import os
import random
import re
from google.appengine.api import channel
from goog... | a-zA-Z0-9\-]", "-", key);
def make_token(room, user):
return room.key().id_or_name() + '/' + user
def make_pc_config(stun_serve | r):
if stun_server:
return "STUN " + stun_server
else:
return "STUN stun.l.google.com:19302"
class Room(db.Model):
"""All the data we store for a room"""
user1 = db.StringProperty()
user2 = db.StringProperty()
def __str__(self):
str = "["
if self.user1:
str += self.user1
if self.... |
zhangvs1988/zhangyl-Djangodemo | usercenter/migrations/0001_initial.py | Python | gpl-3.0 | 1,078 | 0.001873 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-14 06:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... |
name='ActivateCode',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(max_length=100, verbose_name='激活码')),
| ('expire_timestamp', models.DateTimeField()),
('create_timestamp', models.DateTimeField(auto_now_add=True)),
('last_update_timestamp', models.DateTimeField(auto_now=True)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODE... |
whileLooper/MangaSpider | withCookie.py | Python | mpl-2.0 | 1,694 | 0.004825 | import http.cookiejar
import urllib
import urllib.request
import re
import gzip
__author__ = 'bochen'
def makeMyOpener(head):
header = []
cookieJar = http.cookiejar.CookieJar()
processor = urllib.request.HTTPCookieProcessor(cookieJar)
opener = urllib.request.build_opener(processor)
for key, valu... | ,无需解压')
return data
header = {
'Collection': 'Keep-Alive',
'Accept': 'text/html,application/xhtml+xml,*/*',
'Accept-Language': 'en-US,en;q=0.8,ja;q=0.6,zh-CN;q=0.4,zh;q=0.2,it;q=0.2',
'User-Agent': 'Chrome/45.0.2454.101'
}
url = 'http://www.zhihu.com/'
opener = makeMyOpener(header)
urlopen = ope... | '[email protected]'
password = 'BOboris8878'
postDict = {
'_xsrf': _xsrf,
'email': loginEmail,
'password': password,
'rememberme': 'y'
}
postData = urllib.parse.urlencode(postDict).encode()
op = opener.open(url, postData)
data = op.read()
data = ungzip(data)
print(data.decode()) |
ejoonie/heart_sound | main_waveform_20170517.py | Python | gpl-3.0 | 3,229 | 0.013936 | # coding = utf-8
# import modules
import os
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import my_config
path = my_config.ROOT_ | DIR # Please create your config file
file = my_config.FILE # Please create your config file
# get time series for ch0 and plot
import wave
def time_series(file, i_ch = 0):
with wave.open(file,'r') as wav_file:
# Extract Raw Audio from Wav File
signal = wav_file | .readframes(-1)
signal = np.fromstring(signal, 'Int16')
# Split the data into channels
channels = [[] for channel in range(wav_file.getnchannels())]
for index, datum in enumerate(signal):
channels[index%len(channels)].append(datum)
#Get time from indices
fs... |
marxin/youtube-dl | youtube_dl/extractor/tumblr.py | Python | unlicense | 2,338 | 0.002568 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class TumblrIE(InfoExtractor):
_VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/(?:post|video)/(?P<id>[0-9]+)(?:$|[/?#])'
_TESTS = [{
'url': 'http://tatianamaslanydaily.tumblr.com/post/54... | d the scenes ↳...',
'description': 'md5:37db8211e40b50c7c44e95da14f630b7',
'thumbnail': 're:http://.*\.jpg',
}
}, {
'url': 'http://5sostrum.tumblr.com/post/90208453769/yall-forgetting-the-greatest-keek-of-them-all',
'md5': 'bf348ef8c0ef84fbf1cbd6fa6e000359',
'... | '90208453769',
'ext': 'mp4',
'title': '5SOS STRUM ;]',
'description': 'md5:dba62ac8639482759c8eb10ce474586a',
'thumbnail': 're:http://.*\.jpg',
}
}]
def _real_extract(self, url):
m_url = re.match(self._VALID_URL, url)
video_id = m_url.gro... |
lukecwik/incubator-beam | sdks/python/apache_beam/io/filesystems_test.py | Python | apache-2.0 | 8,401 | 0.005476 | # -*- coding: utf-8 -*-
#
# 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 "L... | t shutil
import tempfile
import unittest
import mock
from apache_beam.io import localfilesystem
from apache_beam.io.filesystem import BeamIOError
from apache_beam.io.filesystems import FileSystems
def _gen_fake_join(separator):
"""Returns a callable that joins paths with the given separator."""
def _join(first_... | st(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmpdir)
def test_get_scheme(self):
self.assertIsNone(FileSystems.get_scheme('/abc/cdf'))
self.assertIsNone(FileSystems.get_scheme('c:\\abc\cdf')) # pylint: disable=anomalous-backslash... |
RagnarDanneskjold/omniwallet | api/user_service.py | Python | agpl-3.0 | 4,740 | 0.016034 | import os
import base64
import werkzeug.security as ws
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from flask import Flask, request, jsonify, abort, json
from simplekv.fs import FilesystemStore
from uuid import UUID
ACCOUNT_CREATION_DIFFICULTY = '0400'
LOGIN_DIF... | not in session'
abort(403)
nonce = request.form['nonce']
public_key = request.form['public_key'].encode('UTF-8')
wallet = request.form['wallet | ']
pow_challenge = session_store.get(session_pow_challenge)
if failed_challenge(pow_challenge, nonce, ACCOUNT_CREATION_DIFFICULTY):
print 'Aborting: Challenge was not met'
abort(403)
if exists(uuid):
print 'UUID already exists'
abort(403)
write_wallet(uuid, wallet)
session_store.delete(sess... |
wanghewen/CommonModules | CommonModules/Log.py | Python | mit | 3,611 | 0.008585 | # -*- coding:utf-8 -*-
""" Provide log related functions. You need to Initialize the logger and use the logger to make logs.
Example:
>>> logger = Initialize()
Use logger.level(\*msg) to log like:
>>> logger.error("Pickle data writing Failed.")
>>> logger.info("Pickle data of ", foo, " written successfu... | setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
if LogLevel == "INFO":
streamHandler = logging.StreamHandler(stream = sys.stdout)
streamHandler.setLevel(logging.INFO)
fileHandler.setLevel(logging.INFO)
logger.setLevel(logging.INFO)
if LogLev | el == "ERROR":
streamHandler = logging.StreamHandler(stream = sys.stderr)
streamHandler.setLevel(logging.ERROR)
fileHandler.setLevel(logging.ERROR)
logger.setLevel(logging.ERROR)
streamHandler.setFormatter(logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelnam... |
davidwhogg/MagicCube | code/projection.py | Python | gpl-2.0 | 5,116 | 0.000391 | import numpy as np
class Quaternion:
"""Quaternion Rotation:
Class to aid in representing 3D rotations via quaternions.
"""
@classmethod
def from_v_theta(cls, v, theta):
"""
Construct quaternions from unit vectors v and rotation angles theta
Parameters
----------
... | =[0, 1, 0]):
"""Project points using a quaternion q and a view v
Parameters
----------
points : array_like
array of last-dimension 3
q : Quaternion
quaternion representation of the rotation
view : array_like
length-3 vector giving the point of view
vertical : array_l... | l to the view.
Returns
-------
proj: array_like
array of projected points: same shape as points.
"""
points = np.asarray(points)
view = np.asarray(view)
xdir = np.cross(vertical, view).astype(float)
if np.all(xdir == 0):
raise ValueError("vertical is parallel to v")
... |
sncosmo/sncosmo | sncosmo/tests/test_spectrum.py | Python | bsd-3-clause | 6,754 | 0 | import numpy as np
import pytest
from astropy.table import Table
from numpy.testing import assert_allclose
import sncosmo
try:
import iminuit
HAS_IMINUIT = True
except ImportError:
HAS_IMINUIT = False
def test_bin_edges_linear():
"""Ensure that we can recover consistent bin edges for a spectrum ... | same.
"""
bandflux_highres = self.spectrum.bandflux('sdssg')
bandflux_lowres = self.bin_spectrum.bandflux('sdssg')
assert_allclose(bandflux_highres, bandflux_lowres, rtol=1.e-3)
def test_bandflux_multi(self):
"""Check synthetic photometry with multiple bands."""
ba... | bandflux_highres = self.spectrum.bandflux(bands)
bandflux_lowres = self.bin_spectrum.bandflux(bands)
assert_allclose(bandflux_highres, bandflux_lowres, rtol=1.e-3)
def test_bandflux_zpsys(self):
"""Check synthetic photometry with a magnitude system."""
bands = ['sdssg', 'sdssr', '... |
shahabedinh/gettor | upload/fetch_latest_torbrowser.py | Python | bsd-3-clause | 4,130 | 0.000484 | # -*- coding: utf-8 -*-
#
# This file is part of GetTor, a Tor Browser distribution system.
#
# :authors: Israel Leiva <[email protected]>
#
# :copyright: (c) 2015, The Tor Project, Inc.
# (c) 2015, Israel Leiva
#
# :license: This is Free Software. See LICENSE for license information.
#
import os
imp... | he mirror
# a folder with the value of 'l | atest_version' will be created
os.system(cmd)
# everything inside upload will be uploaded by the provivers' scripts
shutil.move('latest', 'latest_backup')
shutil.move(latest_version, 'latest')
shutil.rmtree('latest_backup')
# latest version of Tor Browser has been syncro... |
TD22057/T-Home | conf/eagle.py | Python | bsd-2-clause | 953 | 0.007345 | #===========================================================================
#
# Port to use for the web server. Configure the Eagle to use this
# port as it's 'cloud provider' using http://host: | PORT
#
#===========================================================================
httpPort = 22042
#===========================================================================
#
# MQTT topic names
#
#===========================================================================
# Meter reading topi | c (reports current meter reading in kWh)
mqttEnergy = 'power/elec/Home/energy'
# Instantaneous power usage topic (reports power usage in W)
mqttPower = 'power/elec/Home/power'
#===========================================================================
#
# Logging configuration. Env variables are allowed in the file... |
ammarkhann/FinalSeniorCode | lib/python2.7/site-packages/billiard/five.py | Python | mit | 5,421 | 0 | # -*- coding: utf-8 -*-
"""
celery.five
~~~~~~~~~~~
Compatibility implementations of features
only available in newer Python versions.
"""
from __future__ import absolute_import
# ############# py3k #########################################################
import sys
PY3 = sys.version_info[0] == 3
... | ec')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
class WhateverIO(StringIO):
def write(self, data):
if isinstance(data, byt | es):
data = data.encode()
StringIO.write(self, data)
else:
import __builtin__ as builtins # noqa
from Queue import Queue, Empty, Full # noqa
from itertools import imap as map, izip_longest as zip_longest # noqa
from StringIO import StringIO # noqa
string = unicode ... |
apache/incubator-allura | ForgeSVN/forgesvn/tests/model/test_svnimplementation.py | Python | apache-2.0 | 5,921 | 0.000169 | # 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 use t... | a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.... |
MasterAlish/kyrgyz_tili | generator.py | Python | gpl-3.0 | 232 | 0.004386 | # coding=utf-8
import sys
|
from kg.db.generate_words import generate
try:
if len(sys.argv) > 1:
generate(sys.argv[1])
else:
generate()
except Exception as e:
print(u"Ката:")
print( | "\t"+e.message) |
denismakogon/aria-cli | aria_cli/config/parser_config.py | Python | apache-2.0 | 7,852 | 0.001783 | # Copyright (c) 2016 GigaSpaces Technologies Ltd. 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
#
# Un... | }
},
'handler': aria.local.create_requirements
},
'exec | ute': {
'help': 'Execute a workflow locally',
'arguments': {
'-w,--workflow':
argument_utils.remove_completer(
workflow_id_argument(
hlp='The workflow to execute locally')),
... |
OCA/carrier-delivery | delivery_carrier_label_dispatch/__init__.py | Python | agpl-3.0 | 988 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Vaucher
# Copyright 2013 Camptocamp SA
#
# Th | is program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will ... | re details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import picking_dispatch
from . import wizard
|
spasovski/zamboni | mkt/site/tests/test_middleware.py | Python | bsd-3-clause | 15,746 | 0.000191 | import datetime
from django.conf import settings
from django.test.utils import override_settings
import mock
from nose.tools import eq_, ok_
from test_utils import RequestFactory
import amo.tests
from users.models import UserProfile
from mkt.site.middleware import DeviceDetectionMiddleware
from mkt.site.fixtures im... | '/restofworld/?region=brazil')
self.assert3xx(r, '/?region=restofworld', 302)
def test_404_for_bad_prefix(self):
for url in ['/xxx', '/xxx/search/',
'/brazil/', '/BRAZIL/',
'/pt/?lang=de', '/pt-XX/brazil/']:
r = self.client.get(url)
go... | object(settings, 'LANGUAGES', [x.lower() for x in _langs])
@mock.patch.object(settings, 'LANGUAGE_URL_MAP',
dict([x.lower(), x] for x in _langs))
class TestLocaleMiddleware(amo.tests.TestCase):
def test_accept_good_locale(self):
locales = [
('en-US', 'en-US', 'en-US,en-US'),
... |
last-g/pyshop | pyshop/views/xmlrpc.py | Python | bsd-3-clause | 8,468 | 0.001299 | # -*- coding: utf-8 -*-
"""
Implement PyPiXmlRpc Service.
See: http://wiki.python.org/moin/PyPiXmlRpc
"""
import logging
from pyramid_xmlrpc import XMLRPCView
from pyshop.models import DBSession, Package, Release, ReleaseFile
from pyshop.helpers import pypi
log = logging.getLogger(__name__)
# XXX not tested.
cla... | e above list
(except 'stable_version' and 'classifiers'),
for example: {'description': 'spam'} will search description fields.
Within the spec, a field's value can be a string or a list of strings
(the values within the list are combined with an OR),
for example: {'name': [' | foo', 'bar']}.
Valid keys for the spec dict are listed here. Invalid keys are ignored:
name
version
author
author_email
maintainer
maintainer_email
home_page
license
summary
description
... |
kingtaurus/cs224d | assignment3/codebase_release/rnn_tensorarray.py | Python | mit | 22,077 | 0.006749 | import sys
import os
import random
import numpy as np
import matplotlib.pyplot as plt
import math
import time
import itertools
import shutil
import tensorflow as tf
import tree as tr
from utils import Vocab
from collections import OrderedDict
import seaborn as sns
sns.set_style('whitegrid')
def initialize_uninitial... | dynamic_size=True,
# clear_after_read=True,
# infer_shape=True)
# index = tf.placeholder(shape=(), dtype=tf.int32)
# def embed_word(word_index):
# with tf.device('/cpu:0'):
# with tf.variable_scope("Composition", reuse=True):
# ... | et_variable('embedding')
# return tf.expand_dims(tf.gather(embedding, word_index), 0)
# def combine_children(left_location, right_location):
# with tf.variable_scope('Composition', reuse=True):
# W1 = tf.get_variable('W1')
# b1 = tf.get_variable('b1')
# return tf.nn.relu(tf.matmul(tf.concat... |
baroquebobcat/pants | tests/python/pants_test/backend/codegen/wire/java/test_wire_integration.py | Python | apache-2.0 | 4,420 | 0.009955 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import re
... | cess(pants_run)
pattern = 'gen/wire/[^/]*/[^/]*/[^/]*/org/pantsbuild/example/temperature/Temperature.java'
files = exact_files(workdir)
self.assertTrue(any(re.match(pattern, f) is not None for f in files),
'Expected pattern: {} in {}'.format(pattern, files))
def test_bundle_w... | '--deployjar',
'examples/src/java/org/pantsbuild/example/wire/temperatureservice']
) as pants_run:
self.assert_success(pants_run)
out_path = os.path.join(get_buildroot(), 'dist',
('examples.src.jav... |
evax/ansible-modules-core | cloud/amazon/rds.py | Python | gpl-3.0 | 42,330 | 0.005599 | #!/usr/bin/python
# 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, or
# (at your option) any later version.
#
# Ansible is distributed... |
required: false
default: null
region:
description:
- The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used.
required: true
aliases: [ 'aws_region', 'ec2_region' ]
db_name:
description:
- Name of a database to create within... | Used only when command=create.
required: false
default: null
engine_version:
description:
- Version number of the database engine to use. Used only when command=create. If not specified then the current Amazon RDS default engine version is used.
required: false
default: null
parameter_gro... |
sidzan/netforce | netforce_mfg/netforce_mfg/models/bom.py | Python | mit | 3,042 | 0.005588 | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# 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, publ... | class Bom(Model):
_name = "bom"
_string = "Bill of Material"
_name_field = "number"
_key = ["number"]
_fields = {
"number": fields.Char("Number", required=True, search=True),
"product_id": fields.Many2One("product", "Product", required=True, search=True),
"qty": fields.Decima... | fields.Many2One("stock.location", "FG Warehouse"),
"routing_id": fields.Many2One("routing", "Routing"),
"lines": fields.One2Many("bom.line", "bom_id", "Lines"),
"comments": fields.One2Many("message", "related_id", "Comments"),
"documents": fields.One2Many("document", "related_id", "Docum... |
chasemp/sup | suplib/run.py | Python | mit | 152 | 0.006579 | import subprocess
def runBash(cmd):
p = subproc | ess.Popen(cmd, shell=True, stdout=subproces | s.PIPE)
out = p.stdout.read().strip()
return out
|
frossigneux/blazar | climate/openstack/common/config/generator.py | Python | apache-2.0 | 10,412 | 0.000096 | # Copyright 2012 SINA Corporation
# Copyright 2014 Cisco Systems, 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/licens... | ind(".")]
mod_obj = _import_module(mod_str)
if not mod_obj:
raise RuntimeError("Unable to import module %s" % mod_ | str)
for group, opts in _list_opts(mod_obj):
opts_by_group.setdefault(group, []).append((mod_str, opts))
print_group_opts('DEFAULT', opts_by_group.pop('DEFAULT', []))
for group in sorted(opts_by_group.keys()):
print_group_opts(group, opts_by_group[group])
def _import_modu... |
Sanqui/spline-pokedex | splinext/pokedex/controllers/pokedex_gadgets.py | Python | mit | 30,941 | 0.004467 | # encoding: utf8
from __future__ import absolute_import, division
from collections import defaultdict, namedtuple
import colorsys
import logging
import wtforms.validators
from wtforms import Form, ValidationError, fields
from wtforms.ext.sqlalchemy.fields import QuerySelectField
import pokedex.db
import pokedex.db.t... | to the next turn is decreased by the
# probability that we didn't catch it this turn
p_got_here *= 1 - catch_ | chance
return expected_attempts
CaptureChance = namedtuple('CaptureChance', ['condition', 'is_active', 'chances'])
class StatCalculatorForm(Form):
pokemon = PokedexLookupField(u'Pokémon', valid_type='pokemon')
level = fields.IntegerField(u'Level', [wtforms.validators.NumberRange(min=1, max=100)],
... |
endlessm/chromium-browser | third_party/catapult/dashboard/dashboard/oauth2_decorator.py | Python | bsd-3-clause | 648 | 0 | # Copyright 2015 The Chromium Authors. All rig | hts reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides oauth2 decorators in a mockable way."""
from __future__ import print_func | tion
from __future__ import division
from __future__ import absolute_import
from oauth2client.appengine import OAuth2Decorator
from dashboard.common import utils
DECORATOR = OAuth2Decorator(
client_id='425761728072.apps.googleusercontent.com',
client_secret='9g-XlmEFW8ROI01YY6nrQVKq',
scope=utils.EMAIL_S... |
bqlabs/horus | src/horus/gui/engine.py | Python | gpl-2.0 | 1,802 | 0.000555 | # -*- coding: utf-8 -*-
# This file is part of the Horus Project
__author__ = 'Jesús Arroyo Torrens <[email protected]>'
__copyright__ = 'Copyright (C) 2014-2016 Mundo Reader S.L.'
__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
from horus.engine.driver.driver import Driver
from ... | ithms.laser_segmentation import LaserSegmentation
from horus.engine.algorithms.point_cloud_generation import PointCloudGeneration
from horus.engine.algorithms.point_cloud_roi import PointCloudROI
# Instances of engine modules
driver = Driver()
ciclop_scan = CiclopScan()
current_video = CurrentVideo()
pat | tern = Pattern()
calibration_data = CalibrationData()
camera_intrinsics = CameraIntrinsics()
scanner_autocheck = Autocheck()
laser_triangulation = LaserTriangulation()
platform_extrinsics = PlatformExtrinsics()
combo_calibration = ComboCalibration()
image_capture = ImageCapture()
image_detection = ImageDetection()
lase... |
gajim/gajim | gajim/gtk/chat_list_stack.py | Python | gpl-3.0 | 11,132 | 0 | # This file is part of Gajim.
#
# Gajim 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 only.
#
# Gajim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... | isible_child_name == self.get_visible_child_name():
return
if self._last_visible_child_name != 'default':
chat_list = cast(
| ChatList,
self.get_child_by_name(self._last_visible_child_name))
chat_list.set_filter_text('')
last_child = self.get_visible_child_name() or 'default'
self._last_visible_child_name = last_child
def get_chatlist(self, workspace_id: str) -> ChatList:
... |
SpaceWars/spacewars | src/layers/base_layers.py | Python | gpl-3.0 | 1,054 | 0 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Copyright (C) 2015 Luiz Fernando Oliveira, Carlos Oliveira, Matheus Fernandes
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 distributed in the hope that it will be useful,
but WITHOU | T ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
"""
from cocos.layer import Layer
from pyglet import resource
from pyglet.gl import glPushMatrix, glPopMatrix
class BackgroundLayer(Layer):
""" A simple ... |
QingChenmsft/azure-cli | src/command_modules/azure-cli-consumption/azure/cli/command_modules/consumption/__init__.py | Python | mit | 704 | 0.005682 | # -------------------------------------------------------------------- | ------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import azure.cli.command_modules.consumption... | ble=unused-import
def load_params(_):
import azure.cli.command_modules.consumption._params # pylint: disable=redefined-outer-name, unused-variable
def load_commands():
import azure.cli.command_modules.consumption.commands # pylint: disable=redefined-outer-name, unused-variable
|
AlbertoPeon/invenio | modules/miscutil/lib/plotextractor_unit_tests.py | Python | gpl-2.0 | 15,778 | 0.006401 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2010, 2011, 2012 CERN.
##
## Invenio 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 yo... | main_and_two_sub_captions,
single_label,
self.empty_images_and_captions, self.dummy_line_index,
self.empty_lines)
self.assertTrue(images_and_captions == [('main', 'main caption', 'singlelabel'),
... | nglelabel'), \
('sub2', 'main caption : subcap2', 'singlelabel')], \
'didn\'t zip {main,sub}{images,captions} together properly')
def test_with_multiples_3(self):
"""plotextractor - put_it_together with multiples 3"""
single_image = 'singleimage'... |
spencerkclark/aospy-obj-lib | aospy_user/variables/idealized_moist/dynamics.py | Python | gpl-3.0 | 3,317 | 0 | from aospy import Var
from aospy_user import calcs, units
from aospy_user.variables.universal.energy_native import (swdn_sfc, olr,
lwdn_sfc, lwup_sfc)
from aospy_user.variables.idealized_moist.energy import flux_t, flux_lhe
# Model native (or self-coded) diagn... |
def_lon=False,
func=calcs.idealize | d_moist.energy.aht,
units=units.W
)
# Continue supporting these?
dmv_dx_im = Var(
name='dmv_dx_im',
domain='atmos',
description=('Zonal flux divergence of mse.'),
variables=(umse,),
def_time=True,
def_vert=True,
def_lat=True,
def_lon=True,
func=calcs.deprecated.mse_zonal_flux_d... |
jabbalaci/PrimCom | data/python/my_pickle.py | Python | gpl-2.0 | 793 | 0.012642 | try:
import cPickle as pickle # faster
except:
import pickle
data1 = [ { 'a':'one', 'b':2, 'c':3.0 } ]
print 'DATA: ',
print(data1)
data1_string = pickle.dumps(data1) | # here: pickling
print 'PICKLE:', data1_string
data2 = pickle.loads(data1_string) # here: unpickling
print 'UNPICKLED:',
print(data2)
print 'SAME?:', (data1 is data2)
print 'EQUAL?:', (data1 == data2)
# * By default, the pickled byte stream contains ASCII characters only.
# * The pickle format is specific to ... | class definition, thus
# when you want to unpickle instances of a class, don’t forget to import
# the definition of this class!
|
taiwenko/python | acs/acs_cold_start.py | Python | mit | 7,587 | 0.019639 | #!/usr/bin/env python
from time import sleep
import twk_utils
import math
import sys
import xpf6020
import tools.utils as tools
import watlowf4
from tools import shell
from blessings import Terminal
t = Terminal()
franz_num = raw_input('How many Franz are you testing? [1,2,3,or 4]: ').strip()
cycle_num = raw_input('... | esult_count = 0
print 'Franz CH%s @ %sV, %sA....[%s]' %(ch, r_mppt_v, r_mppt_i, result)
print ''
return result_count
def config_acs(pfc_path):
sleep(5)
tom = shell | .Shell(pfc_path)
sleep(1)
sb = shell.Scoreboard(tom,'acs')
sleep(1)
tom.sendline('power on acs')
sleep(3)
print sb.query('power_acs_enabled')
sleep(1)
tom.close()
def clean_acs(pfc_path):
sleep(5)
tom = shell.Shell(pfc_path)
sleep(1)
sb = shell.Scoreboard(tom,'acs')
sleep(1)
tom.sendline('p... |
DarkSand/Sasila | sasila/system_normal/processor/car_processor.py | Python | apache-2.0 | 5,995 | 0.00184 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from bs4 import BeautifulSoup as bs
from sasila.system_normal.spider.spider_core import SpiderCore
from sasila.system_normal.pipeline.console_pipeline import ConsolePipeline
from sasila.system_normal.processor.base_processor import BaseProcessor
from sasila.sys... | ion=brandlist&area=%s' % pinyin,
priority=1, callback=self.process_page_1)
request.meta['province'] = province_name
request.meta['city'] = city_name
yield request
@checkResponse
def process_page_1(self, response):
brand_list = list... | ame = brand_dict['name']
url = response.nice_join(brand_dict['url']) + '/'
request = Request(url=url, priority=2, callback=self.process_page_2)
request.meta['province'] = response.request.meta['province']
request.meta['city'] = response.request.meta['city']
re... |
LePastis/pyload | module/web/cnl_app.py | Python | gpl-3.0 | 4,421 | 0.005202 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import join
import re
from urllib import unquote
from base64 import standard_b64decode
from binascii import unhexlify
from bottle import route, request, HTTPError
from webinterface import PYLOAD, DL_ROOT, JS
try:
from Crypto.Cipher import AES
except:
... | )
urls = filter( | lambda x: x != "", request.POST['urls'].split("\n"))
if package:
PYLOAD.addPackage(package, urls, 0)
else:
PYLOAD.generateAndAddPackages(urls, 0)
return ""
@route("/flash/addcrypted", method="POST")
@local_check
def addcrypted():
package = request.forms.get('referer', 'ClickAndLoad P... |
lxr0827/weChatOrder | weChatOrder/WeInterc/get_access_token.py | Python | gpl-2.0 | 1,465 | 0.007655 | # -*- coding: utf-8 -*-
__author__ = 'lxr0827'
import pymysql,requests,json
import datetime
#定时运行该脚本获取accesstoken,记录到accesstoken modu | le里
#test
APPID = "wx243dd553e7ab9da7"
SECRET = "57f109fd1cce0913a76a1700f94c4e2d"
AccessTokenURL = 'https://api.weixin. | qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID + '&secret=' + SECRET
r = requests.get(AccessTokenURL)
if (r.status_code == requests.codes.ok): # @UndefinedVariable
res = json.loads(r.text)
if res.get('errcode') == None:
accessToken = res['access_token']
conn = pymysql.connec... |
nafitzgerald/allennlp | tests/modules/seq2vec_encoders/boe_encoder_test.py | Python | apache-2.0 | 3,106 | 0.002254 | # pylint: disable=no-self-use,invalid-name
import numpy
from numpy.testing import assert_almost_equal
import torch
from torch.autograd import Variable
from allennlp.common import Params
from allennlp.modules.seq2vec_encoders import BagOfEmbeddingsEncoder
from allennlp.common.testing import AllenNlpTestCase
class Test... | er(input_tensor, mask)
assert_almost_equal(encoder_output.data.numpy(),
numpy.asarray([[(.7 + .1 + .3)/3, (.8 + 1.5 + .6)/3],
[(.5 + 1.4)/2, (.3 + 1.1)/2],
[0., 0.]]))
def test_forward_does_cor... | gsEncoder(embedding_dim=2, averaged=True)
input_tensor = Variable(
torch.FloatTensor([[[.7, .8], [.1, 1.5], [.3, .6]], [[.5, .3], [1.4, 1.1], [.3, .9]]]))
encoder_output = encoder(input_tensor)
assert_almost_equal(encoder_output.data.numpy(),
numpy.asa... |
pomegranited/edx-platform | common/djangoapps/third_party_auth/tests/specs/test_google.py | Python | agpl-3.0 | 6,324 | 0.003637 | """Integration tests for Google providers."""
import base64
import hashlib
import hmac
from django.conf import settings
from django.core.urlresolvers import reverse
import json
from mock import patch
from social.exceptions import AuthException
from student.tests.factories import UserFactory
from third_party_auth import... | auth_entry = 'custom1' # See definition in lms/envs/test.py
login_url = pipeline.get_login_url(self.provider.provider_id, auth_entry)
login_url += "&next=/misc/final-destination"
self.assert_redirect_to_provider_looks_correct(sel | f.client.get(login_url))
def fake_auth_complete_error(_inst, *_args, **_kwargs):
""" Mock the backend's auth_complete() method """
raise AuthException("Mock login failed")
# Next, the provider makes a request against /auth/complete/<provider>.
complete_url = pipeline.ge... |
us-ignite/us_ignite | us_ignite/hubs/migrations/0001_initial.py | Python | bsd-3-clause | 25,457 | 0.007621 | # -*- 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):
depends_on = (
("apps", "0001_initial"),
("organizations", "0001_initial"),
)
def forward... | m['hubs.Hub'])),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('description', self.gf('django.db.models.fields.TextField')(blank=True)),
('url', self.gf('django.db.models.fields.URLField')(max_length=500, blank=True)),
('user', self.gf('django.d... | fields.DateTimeField')(default=datetime.datetime.now, blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, blank=True)),
))
db.send_create_signal(u'hubs', ['HubActivity'])
# Adding model 'HubMembership'
db.create_table(u'... |
overfl0/Bulletproof-Arma-Launcher | dependencies/libtorrent/setup.py | Python | gpl-3.0 | 303 | 0.016502 | from distutils.core import setup
# Dummy setup. | py to install libtorrent for python 2.7 using pip
setup(
name='libtorrent',
version='1.0.9',
packages=['libtorrent',],
data_files=[('Lib', ['libtorrent/libtorrent.pyd']),],
)
# Install in "editable mode" for development: |
# pip install -e .
|
dustincys/rednotebook | rednotebook/util/statistics.py | Python | gpl-2.0 | 3,670 | 0.000545 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------
# Copyright (c) 2009 Jendrik Seipp
#
# RedNotebook 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 vers... | day
return [
[_('Words'), day.get_number_of_words()],
[_('Lines'), len(day.text.splitlines())],
[_('Letters'), len(day.text)],
]
def show_dialog(self, dialog):
self.journal.save_old_day()
self.days | = self.journal.days
day_store = dialog.day_list.get_model()
day_store.clear()
for pair in self.day_pairs:
day_store.append(pair)
overall_store = dialog.overall_list.get_model()
overall_store.clear()
for pair in self.overall_pairs:
overall_store.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.