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 |
|---|---|---|---|---|---|---|---|---|
nwjs/chromium.src | third_party/mako/mako/ast.py | Python | bsd-3-clause | 6,789 | 0 | # mako/ast.py
# Copyright 2006-2020 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""utilities for analyzing expressions and blocks of Python
code, as well as generating Python from AST no... | 1],
**exception_kwargs
)
def get_argument_expressions(self, as_call=False):
"""Return the argument declarati | ons of this FunctionDecl as a printable
list.
By default the return value is appropriate for writing in a ``def``;
set `as_call` to true to build arguments to be passed to the function
instead (assuming locals with the same names as the arguments exist).
"""
namedecls =... |
MrZigler/UnderdogMilitia | charactors.py | Python | gpl-3.0 | 628 | 0.025478 |
import random
class Livingbeing():
def __init__(self, name, health, armor, mindset, emotion, skills, inventory):
self.name = name
self.health = he | alth
self.armor = armor
self.mindset = mindset
self.emotion = emotion
self.skills = skills
self.inventory = inventory
self | .hunger = random.randrange(1, 5)
self.thirst = 0
def takeDamage(self, dmgAmount):
if dmgAmount > self.armor:
self.health = self.health - (dmgAmount - self.armor)
quit()
|
lukas-hetzenecker/home-assistant | tests/components/api/test_init.py | Python | apache-2.0 | 18,138 | 0.001103 | """The tests for the Home Assistant API component."""
# pylint: disable=protected-access
import json
from unittest.mock import patch
from aiohttp import web
import pytest
import voluptuous as vol
from homeassistant import const
from homeassistant.bootstrap import DATA_LOGGING
import homeassistant.core as ha
from home... | "test_entity.that_does_not_exist").state == new_state
# pylint: disable=invalid-name
async def test_api_state_change_with_bad_data(hass, mock_api_client):
"""Test i | f API sends appropriate error if we omit state."""
resp = await mock_api_client.post(
"/api/states/test_entity.that_does_not_exist", json={}
)
assert resp.status == 400
# pylint: disable=invalid-name
async def test_api_state_change_to_zero_value(hass, mock_api_client):
"""Test if changing a s... |
ToonTownInfiniteRepo/ToontownInfinite | otp/friends/AvatarFriendsManager.py | Python | mit | 4,080 | 0.001471 | from direct.distributed.DistributedObjectGlobal import DistributedObjectGlobal
from direct.directnotify.DirectNotifyGlobal import directNotif | y
from otp.uberdog.RejectCode import RejectCode
from otp.otpbase import OTPGlobals
from otp.otpbase import OTPLocalizer
class AvatarFriendsManager(DistributedObjectGlobal):
notify = directNotify | .newCategory('AvatarFriendsManager')
def __init__(self, cr):
DistributedObjectGlobal.__init__(self, cr)
self.reset()
def reset(self):
self.avatarFriendsList = set()
self.avatarId2Info = {}
self.invitedAvatarsList = []
self.ignoredAvatarList = []
def addIgno... |
potolock/proverca | test/test_add_group.py | Python | apache-2.0 | 690 | 0.017391 |
from model.group import Group
import pytest
def test_add_group(app, db, json_grou | ps):
group = json_groups
with pytest.allure.step('Given a group list'):
old_groups = db.get_group_list()
with pytest.allure.step('When I add a group %s to the list' % group):
app.group.create(group)
#assert len (old_groups) + 1 == app.group.count()
with py... | t.allure.step('Then the new group list is equal to the old list with the added group'):
new_groups = db.get_group_list()
old_groups.append(group)
assert sorted (old_groups, key=Group.id_or_max ) == sorted (new_groups, key=Group.id_or_max)
|
oakeyc/azure-cli-shell | azclishell/az_completer.py | Python | mit | 14,854 | 0.001548 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | logic(text):
""" validates parameter values for dynamic completion """
is_param = False
started_param = False
prefix = ""
param = ""
txtspt = text.split()
if txtspt:
param = txtspt[-1]
if param.startswith("-"):
is_param = True
elif len(txtspt) > 2 and txts... | param = txtspt[-2]
started_param = True
prefix = txtspt[-1]
return is_param, started_param, prefix, param
def reformat_cmd(text):
""" reformat the text to be stripped of noise """
# remove az if there
text = text.replace('az', '')
# disregard defaulting symbols
i... |
iradicek/clara | tests/utils.py | Python | gpl-3.0 | 498 | 0.006024 | import os
dir_path = os.path.dirname(os.path.realpath(__file__))
def get_full_data_filename(f, reldir='data'):
| """
Gets the full path to the data file `f`.
"""
return os.path.join(dir_path, reldir, f)
def parse_file(fname, parser):
"""
Parses the file `fname` using the parser `parser` and returns the resulting model.
"""
with open(fname, encoding="utf-8") as f:
code = f.read()
model = p... | |
rpm-software-management/dnf | dnf/transaction_sr.py | Python | gpl-2.0 | 24,701 | 0.003603 | # Copyright (C) 2020 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in ... | Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute | _import
from __future__ import print_function
from __future__ import unicode_literals
import libdnf
import hawkey
from dnf.i18n import _
import dnf.exceptions
import json
VERSION_MAJOR = 0
VERSION_MINOR = 0
VERSION = "%s.%s" % (VERSION_MAJOR, VERSION_MINOR)
"""
The version of the stored transaction.
MAJOR version... |
Debian/openjfx | modules/web/src/main/native/Tools/QueueStatusServer/handlers/releasepatch.py | Python | gpl-2.0 | 2,670 | 0.000749 | # Copyright (C) 2013 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 of conditions and the ... | IGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILI | TY OF SUCH DAMAGE.
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import template
from handlers.updatebase import UpdateBase
from loggers.recordpatchevent import RecordPatchEvent
from model.attachment import Attachment
from model.queues import Queue
class ReleasePatch(UpdateBase):
... |
grueni75/GeoDiscoverer | Source/Platform/Target/Android/core/src/main/jni/gdal-3.2.1/swig/python/samples/get_soundg.py | Python | gpl-3.0 | 3,997 | 0.00025 | #!/usr/bin/env python3
###############################################################################
# $Id: get_soundg.py 428d6fbc987332afb0ba6c7b6913390f7386e864 2020-01-17 22:19:28 +0100 Even Rouault $
#
# Project: OGR Python samples
# Purpose: Extract SOUNDGings from an S-57 dataset, and write them to
# ... | MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###############################################################################
import sys
from osgeo import ogr
#############################################################################
def Usage():
print('Usage: get_soundg.py... |
mm22dl/MeinKPS | uploader.py | Python | gpl-3.0 | 3,745 | 0.005874 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Title: uploader
Author: David Leclerc
Version: 0.1
Date: 01.07.2017
License: GNU General Public License, Version 3
(http://www.gnu.org/licens... | ~~~~~~~~~~~~~~~~~~~~~~~
MAIN
~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Define uploader
uploader = Uploader()
# Run it
uploader.run()
# Run this when script is called from terminal
if __name__ == "__main__":
main() |
philchristensen/modu | src/twisted/plugins/modu_web.py | Python | mit | 1,455 | 0.029553 | # | modu
# Copyright (c) 2006-2010 Phil Christensen
# http://modu.bubblehouse.org
#
#
# See LICENSE for details
"""
Twisted plugin to launch a modu web application container.
"""
from zope.interface import implements
from twisted.py | thon import usage
from twisted.plugin import IPlugin
from twisted.application import internet, service
from twisted.internet import reactor
from twisted.web import server, resource, wsgi
from modu.web import app
from modu.persist import dbapi
import os
class Options(usage.Options):
"""
Implement usage parsing for ... |
PapenfussLab/Srtools | bin/old/filterMaqMapview.py | Python | artistic-2.0 | 1,020 | 0.027451 | #!/usr/bin/env python
"""
filterMapview.py <input mapview file> <output filename>
Author: Tony Papenfuss
Date: Mon Jun 16 14:31:42 EST 2008
"""
import os, sys
from useful import progressMessage
iFilename = sys.argv[1]
oFilename = sys.argv[2]
mQ_cutoff = 40
nSeqs = 280000000
oFile = open(oFilename, 'w')
headers ... | s[2])
strand = tokens[3]
numTied = int(tokens[10])
score = int(tokens[11])
numZeroMismat | ches = int(tokens[12])
print >> oFile, format % (name,chrom,start,strand,mQ,numTied,score,numZeroMismatches)
if (i % 1000)==0: progressMessage('# maq hits %s', i, nSeqs)
oFile.close()
|
polyaxon/polyaxon | traceml/traceml/artifacts/__init__.py | Python | apache-2.0 | 727 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2 | .0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific | language governing permissions and
# limitations under the License.
from traceml.artifacts.kinds import V1ArtifactKind
from traceml.artifacts.schemas import RunArtifactSchema, V1RunArtifact
|
demonshreder/pirate | pirate/urls.py | Python | apache-2.0 | 2,735 | 0.007313 | """pirate URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... | er.views.policy, name='policy'),
url(r'^about$', user.views.about, name='about'),
#Files
url(r'^upload$', files.views.upload, name='upload'),
url(r'^search$', files.views.search, name='search'),
url(r | '^file_delete$', files.views.file_delete, name='file_delete'),
url(r'^file_delete_all$', files.views.file_delete_all, name='file_delete_all'),
url(r'^file_update$', files.views.file_update, name='file_update'),
#Communities
url(r'^comm/(?P<name>[a-z0-9A-Z \.\,\_\-\$\~\'\@\!\#\%\^\&\*]+)$', user.views.co... |
Huyuwei/tvm | python/tvm/relay/op/image/image.py | Python | apache-2.0 | 2,130 | 0.000939 | # 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... | align_corners=True,
out_dtype=None):
"""Image resize operator.
This operator takes data as input and does 2D scaling to the given scale factor.
In the default case, where the data_layout is `NCHW`
with data of shape (n, c, h, w)
out will have a shape (n, c, size[0], | size[1])
method indicates the algorithm to be used while calculating ghe out value
and method can be one of ("bilinear", "nearest_neighbor", "bicubic")
Parameters
----------
data : relay.Expr
The input data to the operator.
size: Tuple of Expr
The out size to which the image ... |
sparkslabs/kamaelia_ | Sketches/JL/Sequencer/__init__.py | Python | apache-2.0 | 23 | 0.043478 | ## Seq | uencer init | file
|
jjdmol/LOFAR | SAS/ResourceAssignment/SystemStatusService/SSDBrpc.py | Python | gpl-3.0 | 2,363 | 0.005501 | #!/usr/bin/python
from lofar.messaging.RPC import RPC, RPCException, RPCWrapper
import logging
import sys
logger = logging.getLogger(__name__)
from lofar.sas.systemstatus.service.config import DEFAULT_SSDB_BUSNAME
from lofar.sas.systemstatus.service.config import DEFAULT_SSDB_SERVICENAME
class SSDBRPC(RPCWrapper):
... | ------------------'
print 'getstatenames'
states = ssdb.getstatenames()
pprint.pprint(states)
print '\n------------------'
print 'getactivegroupnames'
groups = ssdb.getactivegroupnames()
pprint.pprint(ssdb.getactivegroupnames())
for gid, groupname in gr... |
for sid, statename in states.items():
print '\n------------------'
print 'counthostsforgroups'
pprint.pprint(ssdb.counthostsforgroups({gid:groupname}, {sid:statename}))
print '\n------------------'
print 'listall'
pprint.pprint(ssdb.l... |
pirata-cat/agora-ciudadana | agora_site/accounts/forms.py | Python | agpl-3.0 | 24,702 | 0.003481 | # Copyright (C) 2012 Eduardo Robles Elvira <edulix AT wadobo DOT com>
#
# This 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 ve... | from django.contrib.auth import authenticate, login
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth import forms as auth_forms
from django.contrib.sites.models import Site
from django import forms as django_forms
from django.utils import transla | tion
from django.core.mail import EmailMultiAlternatives, EmailMessage, send_mass_mail
from django.utils import simplejson as json
from django.utils import timezone
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Hidden, Layout, Fieldset
from userena import forms as userena_forms
fr... |
Javid-Izadfar/TaOonja | taOonja/game/models.py | Python | mit | 444 | 0.006757 | import os
from django.db import models
from django import forms
class Location(models.Model):
name = models.CharField(max_length=250)
local_name = mode | ls.CharField(max_length=250)
visited = models.BooleanField(default=False)
coordinates = models.CharField(ma | x_length=250)
detail = models.TextField()
img = models.ImageField(upload_to = "media/", blank=True, null=True)
def __str__(self):
return self.name
|
pombredanne/Octopus | octopus/backends/docker.py | Python | gpl-3.0 | 4,587 | 0.000218 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2015 Bitergia
#
# 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 ... | platform = self._fetch(self.owner, platform)
| return platform
def _fetch(self, owner, platform):
project = self._fetch_project(owner, platform)
platform.projects.append(project)
return platform
def _fetch_project(self, owner, platform):
url = urlparse.urljoin(self.base_url, DOCKER_OWNER_PATH)
url = urlparse.url... |
wbsoft/frescobaldi | frescobaldi_app/documentstructure.py | Python | gpl-2.0 | 3,353 | 0.003579 | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2013 - 2014 by Wilbert Berendsen
#
# 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
... | ".format(new_name))
else:
groups[name] = 0
new_rx.append(e)
rx = '|'.join(new_rx)
return re.compile(rx, re.MULTILINE | re.UNICODE)
class DocumentStructure(plugin.DocumentPlugin):
def __init__(self, document):
| self._outline = None
def invalidate(self):
"""Called when the document changes or the settings are changed."""
self._outline = None
app.settingsChanged.disconnect(self.invalidate)
self.document().contentsChanged.disconnect(self.invalidate)
def outline(self):
"""... |
kramer314/1d-vd-test | convergence-tests/cleanup.py | Python | mit | 229 | 0 | import os |
input_dir = "./convergence_inputs/"
output_dir = "./convergence | _outputs/"
print("Removing input files")
os.system("rm -rf " + input_dir)
print("Removing output directories / files")
os.system("rm -rf " + output_dir)
|
Jgarcia-IAS/SAT | openerp/addons-extra/odoo-pruebas/odoo-server/addons/stock_landed_costs/stock_landed_costs.py | Python | agpl-3.0 | 19,099 | 0.004189 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | #Create a | ccount move lines for quants already out of stock
if qty_out > 0:
debit_line = dict(debit_line,
name=(line.name + ": " + str(qty_out) + _(' already out')),
quantity=qty_out)
credit_line = dict(credit_line,
... |
mm10ws/ImPy | ImAdd.py | Python | gpl-3.0 | 1,485 | 0.002694 | __author__ = 'Mayur M'
import ImgIO
def add(image1, image2): # add two images together
if image1.width == image2.width and image1.height == image2.height:
return_red = []
return_green = []
return_blue = []
for i in range(0, len(image1.red)):
tmp_r = ima | ge1.red[i] + | image2.red[i] # adding the RGB values
tmp_g = image1.green[i] + image2.green[i]
tmp_b = image1.blue[i] + image2.blue[i]
if 0 <= tmp_r <= 255:
return_red.append(tmp_r)
else:
return_red.append(tmp_r % 255) # loop values around if saturatio... |
fdibaldassarre/mload | src/Utils/Browser.py | Python | gpl-3.0 | 1,525 | 0.019016 | #!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk
from gi.repository import WebKit2 as WebKit
from src.Utils import Browser
COOKIES_TEXT = 0
COOKIES_SQLITE = 1
class MLBrowser():
def __init__(self):
self.window = Gtk.Window()... | = lambda _ : True
self.view.connect('load_changed', self.onLoadChanged)
def _interfaceInit(self):
scroll = Gtk.ScrolledWindow()
scroll.add_with_viewport(self.view)
self.window.add(scroll)
def saveCookiesTo(self, s | avepath):
context = self.view.get_context()
cookie_manager = context.get_cookie_manager()
storage = WebKit.CookiePersistentStorage(COOKIES_TEXT)
cookie_manager.set_persistent_storage(savepath, storage)
def show(self):
self.window.show_all()
def close(self):
self.close_callback(self)
... |
pattarapol-iamngamsup/projecteuler_python | problem_041.py | Python | gpl-3.0 | 1,724 | 0.034803 | """ Copyright 2014, March 21
Written by Pattarapol (Cheer) Iamngamsup
E-mail: IAM.PATTARAPOL@GMAIL.COM
Pandigital prime
Problem 41
We shall say that an n-digit number is pandigital
if it makes use of all the digits 1 to n exactly once.
For example, 2143 is a 4-digit pandigital and is also prime... | ime
startingDateTime = datetime.datetime.utcnow()
|
print( 'startingDateTime = {0} UTC'.format( startingDateTime ) )
# call main function
main()
# get ending date time
endingdateTime = datetime.datetime.utcnow()
print( 'endingdateTime = {0} UTC'.format( endingdateTime ) )
# compute delta date time
deltaDateTime = endingdateTime - startingDate... |
debalance/hp | hp/conversejs/views.py | Python | gpl-3.0 | 878 | 0.006834 | # -*- coding: utf-8 -*-
#
# This file is part of the jabber.at homepage (https://github.com/jabber-at/hp).
#
# This project 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 (... | CULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with django-xmpp-account.
# If | not, see <http://www.gnu.org/licenses/>.
from django.views.generic.base import TemplateView
class ConverseJsView(TemplateView):
template_name = 'conversejs/main.html'
|
saurabh6790/frappe | frappe/tests/test_exporter_fixtures.py | Python | mit | 8,665 | 0.030467 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import frappe.defaults
from frappe.core.doctype.data_import.data_import import export_csv
import unittest
import os
class TestDataImportFixtures(unittest.TestCase):... | ppe.scrub(fixture[0]) + "_simple_name_equal_default.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_simple_name_equal(self):
fixture = ["Custom Field", {"name":["Item-vat"],"op":"="}]
path = frappe.scrub(fixture[0]) + "_simple_name_equal.c | sv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_simple_name_not_equal(self):
fixture = ["Custom Field", {"name":["Item-vat"],"op":"!="}]
path = frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os... |
locaweb/netl2api | netl2api/l2api/hp/flex10res.py | Python | apache-2.0 | 1,378 | 0.002177 | #!/usr/bin/python
# -*- coding: utf-8; -*-
#
# 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
#
# Unles... | )\sManagement CLI.+\r\nBuild:\s+(?P<build>.+)\r\n")
# show domain
RE_SH_DOMAIN = re.compile(r"Domain Name\s+:\s+(.+)\r\n")
# show interconnect-mac-table encX:ID
RE_SH_INTERCONN_MAC = re.compile(r"^d(\d+)\s+((?:[a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2})\s")
| RE_SH_UPLINKPORT_status = re.compile(r"^Linked(?:\ \((Active|Standby)\))?", re.IGNORECASE)
RE_SH_UPLINKPORT_duplex = re.compile(r"\((\d+[KMG]b)/(.+)\)$", re.IGNORECASE)
|
HPNetworking/HP-Intelligent-Management-Center | build/lib/pyhpeimc/plat/device.py | Python | apache-2.0 | 23,430 | 0.004609 | #!/usr/bin/env python3
# author: @netmanchris
# This section imports required libraries
import json
import requests
HEADERS = {'Accept': 'application/json', 'Content-Type':
'application/json', 'Accept-encoding': 'application/json'}
#auth = None
"""
This section contains functions which operate at the system... | t requests.exceptio | ns.RequestException as e:
return "Error:\n" + str(e) + " get_dev_series: An Error has occured"
"""
This section contains functions which operate at the device level.
"""
def get_all_devs(auth, url, network_address= None):
"""Takes string input of IP address to issue RESTUL call to HP IMC\n
:param aut... |
reellz/django-statify | statify/views.py | Python | bsd-3-clause | 12,635 | 0.00372 | # -*- coding: utf-8 -*-
#
import ftplib
import os
import re
import shutil
import tarfile
import time
from pathlib import Path
from subprocess import call
from socket import gaierror
import paramiko
from paramiko.ssh_exception import SSHException, AuthenticationException
import requests
from django.conf import setting... | est,
template_name = 'admin/statify/release/deploy_form.html',
context = {
'form': form,
'release_id': release_id
}
)
@login_required()
def deploy_release(request, release_id, deploymenthost_id):
release = get_object_or_404(R | elease, pk=release_id)
deploymenthost = get_object_or_404(DeploymentHost, pk=deploymenthost_id)
archive = os.path.join(settings.MEDIA_ROOT, u'%s' % release.archive)
directory = deploymenthost.path.split('/')[-1]
tmp_path = os.path.join(settings.MEDUSA_DEPLOY_DIR, '..', 'deploy', release.timestamp)
... |
nbkr/blog3 | blogthree/util.py | Python | gpl-2.0 | 3,541 | 0.001977 | import os
import math
from datetime import datetime
def indexGenerator(articleList, paths, env, language, folder='',
article_per_page=3, future=False):
filenumber = 0
count = 0
# Counting the actual number of articles we are going to publish
# we have to do this in advance, otherw... | formatedfilenumber))
numpages = int(math.ceil(numarticles / float(article_per_page)))
pagenumber = filenumber + 1
prev = ''
if filenumber == 1:
prev = 'index.html'
if filenumber > 1:
prev = 'i | ndex{}.html'.format(filenumber - 1)
nxt = ''
if pagenumber < numpages:
nxt = 'index{}.html'.format(filenumber + 1)
if not os.path.exists(os.path.join(paths['output'], folder)):
os.makedirs(os.path.join(paths['output'], folder))
# Writing... |
jackzhao-mj/ok | server/tests/integration/test_api_course.py | Python | apache-2.0 | 1,100 | 0.02 | #!/usr/bin/env python
# encoding: utf-8
#pylint: disable=no-member, no-init, too-many-public-methods
#pylint: disable=attribute-defined-outside-init
# This disable is because the tests need to be name such that
# you can understand what the test is doing from the method name.
#pylint: disable=missing-docstring
"""
test... | utils
from ddt import ddt, data, unpack
from app.exceptions import *
from integration.test_api_base import APITest
class CourseAPITest(APITest, APIBaseTestCase):
model = models.Course
name = 'course'
num = 1
access_token = 'dummy_admin'
def get_basic_instance(self, mutate=True):
name = 'testcourse'
if mutat... | ake_fake_course(self.user)
rval.name = name
return rval |
wildchildyn/autism-website | yanni_env/lib/python3.6/site-packages/sqlalchemy/dialects/mssql/__init__.py | Python | gpl-3.0 | 1,081 | 0.000925 | # mssql/__ini | t__.py
# Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy.dialects.mssql import base, pyodbc, adodbapi, \
pymssql, zxjdbc, mxodbc
ba... | RCHAR, NVARCHAR, CHAR, \
NCHAR, TEXT, NTEXT, DECIMAL, NUMERIC, FLOAT, DATETIME,\
DATETIME2, DATETIMEOFFSET, DATE, TIME, SMALLDATETIME, \
BINARY, VARBINARY, BIT, REAL, IMAGE, TIMESTAMP,\
MONEY, SMALLMONEY, UNIQUEIDENTIFIER, SQL_VARIANT, dialect
__all__ = (
'INTEGER', 'BIGINT', 'SMALLINT', 'TINYINT'... |
dzamie/weasyl | weasyl/test/test_collection.py | Python | apache-2.0 | 1,760 | 0.000568 | import unittest
import pytest
from libweasyl import ratings
from weasyl.error import WeasylError
from weasyl.test import db_utils
from weasyl import collection
@pytest.mark.usefixtures('db')
class CollectionsTestCase(unittest.TestCase):
def setUp(self):
self.creator = db_utils.create_user()
self... | ting=ratings.GENERAL.code):
return len(collection.select_manage(self.collector, rating, 10, pending))
def test_offer_and_accept(self):
self.offer()
self.assertEqual(1, self.count_collections(True))
collection.pending_accept(self.col | lector, [(self.s, self.collector)])
self.assertEqual(1, self.count_collections(False))
def test_offer_with_errors(self):
self.assertRaises(WeasylError, collection.offer,
db_utils.create_user(), self.s, self.collector)
def test_offer_and_reject(self):
self.offe... |
singulared/aiohttp | aiohttp/http.py | Python | apache-2.0 | 1,163 | 0 | from .http_exceptions import HttpProcessingError
from .http_message import (RESPONSES, SERVER_SOFTWARE, HttpMessage,
HttpVersion, HttpVersion10, HttpVersion11,
PayloadWriter, Request, Response)
from .http_parser import (HttpParser, HttpRequestParser, HttpResponsePar... | uestMessage, RawResponseMessage)
from .http_websocket import (WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE, WS_KEY,
WebSocketError, WebSocketReader, WebSocketWriter,
WSCloseCode, WSMessage, WSMsgType, do_handshake)
__all | __ = (
'HttpProcessingError',
# .http_message
'RESPONSES', 'SERVER_SOFTWARE',
'HttpMessage', 'Request', 'Response', 'PayloadWriter',
'HttpVersion', 'HttpVersion10', 'HttpVersion11',
# .http_parser
'HttpParser', 'HttpRequestParser', 'HttpResponseParser',
'RawRequestMessage', 'RawRespons... |
PARINetwork/pari | article/views.py | Python | bsd-3-clause | 8,919 | 0.001345 | import calendar
from bs4 import BeautifulSoup
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.conf import settings
from django.http import Http404
from django.core.cache import caches
from django.contrib.contenttypes.models import ContentType
from wagtail.core.... | ss GalleryArticleList(P | age1Redirector, ListView):
context_object_name = "articles"
model = Article
paginate_by = 12
template_name = 'includes/gallery_article_list.html'
def get_queryset(self):
url_name = self.request.resolver_match.url_name
if url_name == "author-detail":
live_articles_by_auth... |
sleepinghungry/wwif | students/parker/practice 3.py | Python | mit | 766 | 0.050914 | Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
RESTART: Z:\Coding Cla | sses\Python Text Adventures\wwif\students\parker\practice 2.py
I will spell the word "one"
o
n
e
>>>
RESTART: Z:\Coding Classes\Python Text Adventures\wwif\students\parker\practice 2.py
I will spell the word "one"
one
>>>
RESTART: Z:\Coding | Classes\Python Text Adventures\wwif\students\parker\practice 2.py
what is your name?parker
6
>>> semi
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
semi
NameError: name 'semi' is not defined
>>>
RESTART: Z:\Coding Classes\Python Text Adventures\wwif\students\parker\practice 2.py
... |
soulmachine/scikit-learn | examples/cluster/plot_kmeans_digits.py | Python | bsd-3-clause | 4,526 | 0.001989 | """
===========================================================
A demo of K-Means clustering on the handwritten digits data
===========================================================
In this example with compare the various initialization strategies for
K-means in terms of runtime and quality of the results.
As the ... | the quality of the VQ.
h = .02 # point in the mesh [x_min, m_max]x[y_min, y_max].
# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = reduced_data[:, 0].min() + 1, reduced_data[:, 0].max() - 1
y_min, y_max = reduced_data[:, 1].min() + 1, reduced_data[:, 1].max() - 1
xx, yy = np.me... | Obtain labels for each point in mesh. Use last trained model.
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=plt.cm.P... |
betrisey/home-assistant | homeassistant/components/sensor/scrape.py | Python | mit | 3,388 | 0 | """
Support for getting data from websites with scraping.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.scrape/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.component... | name, select, value_template, unit)
])
# pylint: disable=to | o-many-instance-attributes
class ScrapeSensor(Entity):
"""Representation of a web scrape sensor."""
# pylint: disable=too-many-arguments
def __init__(self, hass, rest, name, select, value_template, unit):
"""Initialize a web scrape sensor."""
self.rest = rest
self._name = name
... |
pfalcon/ScratchABlock | script_func_returns.py | Python | gpl-3.0 | 346 | 0 | from xform import *
from dataflow import *
import xform_inter
import script_preserveds
cg = None
def init():
global cg
cg = xform_inter.build_c | allgraph()
def apply(cfg):
script_preserveds.apply(cfg)
collect_call_live_out(cfg)
xform_inter | .calc_callsites_live_out(cg, cfg.props["name"])
xform_inter.collect_returns()
|
yandex/yandex-tank | yandextank/stepper/__init__.py | Python | lgpl-2.1 | 129 | 0 | #
from .main imp | ort Stepper, StepperWrapper # noqa
from .info import StepperInfo # noqa
from .format import StpdReader # no | qa
|
kret0s/gnuhealth-live | tryton/server/trytond-3.8.3/trytond/ir/model.py | Python | gpl-3.0 | 39,540 | 0.002099 | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import re
import heapq
from sql import Null
from sql.aggregate import Max
from sql.conditionals import Case
from collections import defaultdict
try:
import simplejson as j... | t):
pool = Pool()
Property = pool.get('ir.property')
res = super(Model, cls).create(vlist)
# Restart the cache of models_get
Property._models_get_cache.clear()
return res
@classmethod
def write(cls, models, values, *args):
pool = Pool()
Property =... |
# Restart the cache of models_get
Property._models_get_cache.clear()
@classmethod
def delete(cls, models):
pool = Pool()
Property = pool.get('ir.property')
super(Model, cls).delete(models)
# Restart the cache of models_get
Property._models_get_cache.clea... |
alfredgamulo/cloud-custodian | tests/test_lookup.py | Python | apache-2.0 | 2,809 | 0 | # Copyright 2019 Microsoft Corp
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from .common import BaseTest
from c7n.lookup import Lookup
class LookupTest(BaseTest):
def test_lookup_type(self):
number_schema = {'type': 'number'}
lookup_default_number = Look | up.lookup_type(number_schema)
string_schema = {'type': 'string'}
lookup_default_string = Lookup.lookup_type(string_schema)
self.assertEqual(number_schema, lookup_default_number['oneOf'][1])
self.assertEqual(number_schema,
lookup_defa | ult_number['oneOf'][0]['oneOf'][0]
['properties']['default-value'])
self.assertEqual(string_schema, lookup_default_string['oneOf'][1])
self.assertEqual(string_schema,
lookup_default_string['oneOf'][0]['oneOf'][0]
['properties'][... |
Architektor/PySnip | venv/lib/python2.7/site-packages/twisted/internet/test/test_posixbase.py | Python | gpl-3.0 | 9,553 | 0.003036 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.internet.posixbase} and supporting code.
"""
from __future__ import division, absolute_import
from twisted.trial.unittest import TestCase
from twisted.internet.defer import Deferred
from twisted.internet.posixbase import ... | osixReactorBase._removeAll}.
"""
reactor = TrivialReactor()
extra = object()
reactor._inter | nalReaders.add(extra)
reactor.addReader(extra)
reactor._removeAll(reactor._readers, reactor._writers)
self._checkWaker(reactor)
self.assertIn(extra, reactor._internalReaders)
self.assertIn(extra, reactor._readers)
def test_removeAllReturnsRemovedDescriptors(self):
"... |
PyCQA/pylint | tests/functional/c/consider/consider_using_dict_items.py | Python | gpl-2.0 | 3,585 | 0.003905 | """Emit a message for iteration through dict keys and subscripting dict with key."""
# pylint: disable=line-too-long,missing-docstring,unsubscriptable-object,too-few-public-methods,redefined-outer-name,use-dict-literal,modified-iterating-dict
def bad():
a_dict = {1: 1, 2: 2, 3: 3}
for k in a_dict: # [con... |
b_dict = {}
for k2 in b_dict: # Should not emit warning, key access necessary
b_dict[k2] = 2
for k2 in b_dict: # Should not emit warning, key access necessary (AugAssign)
b_dict[k2] += 2
|
# Warning should be emitted in this case
for k6 in b_dict: # [consider-using-dict-items]
val = b_dict[k6]
b_dict[k6] = 2
for k3 in b_dict: # [consider-using-dict-items]
val = b_dict[k3]
for k4 in b_dict.keys(): # [consider-iterating-dictionary,consider-using-dict-items]
val = b_dict[k4]
... |
kodki/cortext | cortext/text.py | Python | mit | 1,056 | 0.000947 | import nltk
class Text:
def __init__(self, raw_text):
self.raw_text = raw_text
def parse(self):
sentences = nltk.sent_tokenize(self.raw_text)
tokens = [nltk.word_tokenize(sentence) for sentence in sentences]
self.tagged_sentences = [self.tag(words) for words in tokens]
... | gged_word[1].startsw | ith('NNP'):
consecutive_names.append(tagged_word[0])
last_tag = tagged_word[1]
else:
if consecutive_names:
tagged_words.append((' '.join(consecutive_names), last_tag))
consecutive_names = []
tagged_words.... |
m3wolf/scimap | tests/test_pawley_refinement.py | Python | gpl-3.0 | 6,933 | 0.002021 | # -*- coding: utf-8 -*-
#
# Copyright © 2018 Mark Wolf
#
# This file is part of scimap.
#
# Scimap 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 lat... | th warnings.catch_warn | ings(record=True) as w:
warnings.simplefilter('always')
result = predict_diffractogram(
two_theta=two_theta,
wavelengths=wavelengths,
background_coeffs=(0,),
u=0.01, v=0, w=0,
reflections=reflections,
... |
dawehner/root | geom/gdml/writer.py | Python | lgpl-2.1 | 11,603 | 0.038955 | # @(#)root/gdml:$Id$
# Author: Witold Pokorski 05/06/2006
# This is the application-independent part of the GDML 'writer' implementation.
# It contains the 'writeFile' method (at the end of the file) which does the actual
# formating and writing out of the GDML file as well as the specialized 'add-element'
# methods ... | self.materials = ['m | aterials',{},[]]
self.solids = ['solids',{},[]]
self.structure = ['structure',{},[]]
self.document = ['gdml',{'xmlns:gdml':"http://cern.ch/2001/Schemas/GDML",
'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance",
'xsi:noNamespa... |
dimagi/commcare-hq | corehq/apps/sms/migrations/0004_add_sqlivrbackend_sqlkookoobackend.py | Python | bsd-3-clause | 624 | 0 | from django.db import migrations
class Migration(mi | grations.Migration):
dependencies = [
('sms', '0003_add_backend_models'),
]
operations = [
migrations.CreateModel(
name='SQLIVRBackend',
fields=[
],
options={
'proxy': True,
},
bases=('sms.sqlmobileback... |
fields=[
],
options={
'proxy': True,
},
bases=('sms.sqlivrbackend',),
),
]
|
SarahJaine/mo-cli | mo.py | Python | mit | 1,542 | 0.001297 | from cookiecutter.main import cookiecutter
import click
impo | rt requests
import sys
@click.group()
def cli():
'''Command-line utility to work with cookiecutter templates from GitHub repos.
Search https://github.com/istrategylabs 'mo' projects
to see available ISL cookiecutters.'''
pass
@cli.command()
@click.argument('framework', type=click.STRING)
@click.opti... | ser):
'''initialize a new cookiecutter template'''
# Check that cookiecutter template exists for requested framework
git_url = 'https://github.com/'
framework = framework.lower().replace(' ', '-')
mo_url = git_url+user+'/mo-'+framework
try:
response = requests.head(mo_url)
statu... |
oscarbranson/tools | tools/chemistry.py | Python | gpl-3.0 | 3,869 | 0.005686 | """
The periodic table, and all it's info! And functions for doing chemical things.
"""
import os
import re
import pickle
import pandas as pd
def elements(all_isotopes=True):
"""
Loads a DataFrame of all elements and isotopes.
Scraped from https://www.webelements.com/
Returns
-------
pandas ... | ttps://www.nodc.noaa.gov/ocads/oceans/Handbook_2007.html",
ISBN="1-897176-07-4"}
Parameters
----------
Sal : float
Salinity, default is 35
unit : str
| Either 'mol/kg' or 'g/kg'.
Returns
-------
Seawater composition in chosen units at specified salinity : dict
"""
sw = {"Cl": 0.54586,
"SO4": 0.02824,
"Br": 0.00084,
"F": 0.00007,
"Na": 0.46906,
"Mg": 0.05282,
"Ca": 0.01028,
... |
gotostack/swift | test/unit/common/middleware/test_slo.py | Python | apache-2.0 | 65,372 | 0.000031 | # -*- coding: utf-8 -*-
# Copyright (c) 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | tEquals(
self.slo.handle_multipart_put(req, fake_start_response),
['passed'])
def test_handle_multipart_put_success(self):
req = Request.blank(
'/v1/AUTH_test/c/man?multipart-manifest=put',
environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'},
... | args):
gen_etag = '"' + md5('etagoftheobjectsegment').hexdigest() + '"'
self.assertTrue(('Etag', gen_etag) in args[1])
self.slo(req.environ, my_fake_start_response)
self.assertTrue('X-Static-Large-Object' in req.headers)
def test_handle_multipart_put_success_allow_small_las... |
fingeronthebutton/RIDE | src/robotide/lib/robot/libraries/BuiltIn.py | Python | apache-2.0 | 140,502 | 0.001224 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | h, it is padded with zeros.
Examples:
| ${result} = | Convert To Binary | 10 | | | # Result is 1010 |
| ${result} = | Convert To Binary | F | base=16 | prefix=0b | # Result is 0b1111 |
| ${result} = | Convert To Binary | -2 | prefix=B | length=4 | # Result is -B0010... | See also `Convert To Integer`, `Convert To Octal` and `Convert To Hex`.
"""
return self._convert_to_bin_oct_hex(bin, item, base, prefix, length)
def convert_to_octal(self, item, base=None, prefix=None, length=None):
"""Converts the given item to an octal string.
The ``item``, wi... |
devsar/ae-people | apps/users/forms.py | Python | apache-2.0 | 6,966 | 0.014355 | import re
from django import forms
from django.core.urlresolvers import reverse
| from django.contrib.formtools.wizard import FormWizard
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.utils.translation import ugettext_lazy as _
from google.appengine.ext.db import djangoforms
from google.appengine.api.labs import taskqueue
from uni_form.hel... | ers import Layout, Fieldset, Row
from models import Developer
from users.utils import LocationField
from country.models import COUNTRIES
class DeveloperForm(djangoforms.ModelForm):
#geolocation = LocationField()
about_me = forms.CharField(widget=forms.Textarea,
help_text="ac... |
hbuschme/TextGridTools | tgt/tests/test_core.py | Python | gpl-3.0 | 33,889 | 0.00059 | # -*- coding: utf-8 -*-
# TextGridTools -- Read, write, and manipulate Praat TextGrid files
# Copyright (C) 2013-2014 Hendrik Buschmeier, Marcin Włodarczak
#
# 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... | e)
self.assertTrue(ao2_retr[0] == ao2)
# - time equals start time of object
ao3_retr = t.get_annotations_by_time(ao3.start_time)
self.assertTrue(ao3_retr[0] == ao3)
# - time equals start time of one object and end_ | time of another
ao12_retr = t.get_annotations_by_time(ao1.end_time)
|
hlzz/dotfiles | graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/python/dist.py | Python | bsd-3-clause | 15,309 | 0.000914 | # -*- test-case-name: twisted.python.test.test_dist -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Distutils convenience functionality.
Don't use this outside of Twisted.
Maintainer: Christopher Armstrong
"""
from distutils.command import build_scripts, install_data, bui... | ntainer="Glyph Lefkowitz",
maintainer_email="glyph@twistedmatrix.com",
url="http://twistedmatrix.com/",
license="MIT",
long_description="""\
An extensible framework for Python programming, with special f | ocus
on event-based network programming and multiprotocol integration.
""",
classifiers=[
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
],
)
t... |
arosswilson/rossreckons | rossreckons/wsgi.py | Python | mit | 400 | 0 | """
WSGI config for rossreckons project.
It exposes the WSGI callable as a module-level variable | named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rossreckons.settings")
| application = get_wsgi_application()
|
GiulioRossetti/ndlib | ndlib/models/epidemics/UTLDRModel.py | Python | bsd-2-clause | 28,297 | 0.003216 | from ..DiffusionModel import DiffusionModel
import numpy as np
import future
__author__ = ["Giulio Rossetti"]
__license__ = "BSD-2-Clause"
class UTLDRModel(DiffusionModel):
def __init__(self, graph, seed=None):
super(self.__class__, self).__init__(graph, seed)
self.params['nodes']['vaccinated'... | ": {
"descr": "Death probability - Severe not in ICU",
"range": [0, 1],
"optional": True,
"default": 0
},
"phi_e": {
"descr": "Testing probability if Exposed",
"range":... | , 1],
"optional": True,
"default": 0
},
"phi_i": {
"descr": "Testing probability if Infected",
"range": [0, 1],
"optional": True,
"default": 0
},
... |
fiete201/qutebrowser | qutebrowser/utils/__init__.py | Python | gpl-3.0 | 830 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | arranty of
# MERCHANTABILITY or FITNESS F | OR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""Misc utility functions."""
|
MountainMan22/Boto-Automation | tests/test_vi_virtual_machine.py | Python | gpl-2.0 | 11,730 | 0.005627 | import os
import random
import time
import ConfigParser
from unittest import TestCase
from pysphere import VIServer, VMPowerState, ToolsStatus
class VIVirtualMachineTest(TestCase):
@classmethod
def setUpClass(cls):
config_path = os.path.join(os.path.dirname(__file__), "config.ini")
cls.config... | ()
if cls.vm_tools.get_status(basic_status=True) != VMPowerState.POWERED_OFF:
cls.vm_tools.power_off()
if cls.vm_toy.get_status(basic_status=True) != VMPowerState.POWERED_OFF:
cls.vm_toy.power_off()
| cls.server2.disconnect()
def test_get_resource_pool_name(self):
for mor in self.server.get_resource_pools().iterkeys():
vms = self.server.get_registered_vms(resource_pool=mor)
if not vms:
continue
path = random.choice(vms)
print "picked:",... |
mar10/wsgidav | wsgidav/samples/hg_dav_provider.py | Python | mit | 22,535 | 0.00071 | # -*- coding: utf-8 -*-
# (c) 2009-2022 Martin Wendt and contributors; see WsgiDAV https://github.com/mar10/wsgidav
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
DAV provider that publishes a Mercurial repository.
Note: This is **not** production code!
The repository is rend... | tp://mercurial.berkwood.com/binaries/mercurial-1.4.win32-py2.6.exe
"""
import os
import sys
import time
from hashlib import md5
from pprint import pprint
from wsgidav import util
from wsgidav.dav_error import HTTP_FORBIDDEN, DAVError
from wsgidav.dav_provider import DAVProvider, _DAVResource
from wsgidav.samples.dav_p... | from mercurial import util as hgutil
except ImportError:
print(
"Could not import Mercurial API. Try 'easy_install -U mercurial'.",
file=sys.stderr,
)
raise
__docformat__ = "reStructuredText en"
_logger = util.get_module_logger(__name__)
BUFFER_SIZE = 8192
# ============================... |
JulyKikuAkita/PythonPrac | cs15211/IsSubsequence.py | Python | apache-2.0 | 5,737 | 0.002789 | __source__ = 'https://leetcode.com/problems/is-subsequence/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/is-subsequence.py
# Time: O(n)
# Space: O(1)
#
# Description: Leetcode # 392. Is Subsequence
#
# Given a string s and a string t, check if s is subsequence of t.
#
# You may assume that th... | list, T key)
// Returns index of key in sorted list sorted in
// order defined by Comparator c.
public static int binarySearch(List slist, T key, Comparator c) |
If key is not present, the it returns "(-(insertion point) - 1)".
The insertion point is defined as the point at which the key
would be inserted into the list.
public static void main(String[] args)
{
List al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(10);
... |
microelly2/freecad-objecttree | objecttree.py | Python | lgpl-3.0 | 28,721 | 0.057066 | # -*- coding: utf-8 -*-
#-------------------------------------------------
#-- object tree
#--
#-- microelly 2015
#--
#-- GNU Lesser General Public License (LGPL)
#-------------------------------------------------
import FreeCAD
import PySide
from PySide import QtCore, QtGui, QtSvg
global QtGui,QtCore
global fullRef... | Object.DisplayMode = "Shaded"
if context.has_key(self.obj) and context[self.obj]:
pass
self.obj.ViewObject.Visibility=True
except:
sayexc("hu44")
FreeCAD.ActiveDocument.recompute()
| def mousePressEvent(self, ev):
#FreeCAD.Console.PrintMessage("k mouse press")
say("mouse Press A " + self.obj.Label)
#FreeCAD.Console.PrintMessage("Label clicked " + ot['obj'].Label + "\n")
FreeCADGui.Selection.clearSelection()
## FreeCADGui.Selection.addSelection(self.ot['obj'])
FreeCADGui.Selection.ad... |
eriktaubeneck/ordbok | ordbok/exceptions.py | Python | mit | 3,492 | 0 | class OrdbokException(Exception):
pass
class OrdbokKeyException(OrdbokException):
def __init__(self, key, config_file):
self.key = key
self.config_file_path = config_file.config_file_path
class OrdbokMissingConfigFileException(OrdbokKeyException):
def __repr__(self):
return ('{0}... | (self):
return (' | {} config key should be specified in {} but was not found.'
''.format(self.key, self.config_filename))
class OrdbokSelfReferenceException(OrdbokKeyException):
def __repr__(self):
return ('Cannot require {} to be required in its own file ({}).'
''.format(self.key, self.confi... |
tuxar-uk/Merlyn | x/slave.py | Python | mit | 3,181 | 0.038981 | #!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
from fuzzywuzzy import fuzz
from time import ctime
import time
import os
from subprocess import Popen
from gtts import gTTS
import sys
import pyjokes
import SR
import sys
#stderr = open('slave.log', 'w')
#sys.stderr = stderr
devnu... | it()
w = words[0]
if w not in cmds:
(new, d) = nearest_word(w, cmds.keys())
if d > 66:
w = new
speak("Correcting to " + w)
if w not in cmds:
max = 0
for word in words:
(alt, d) = nearest_word(word, cmds.keys())
if d > max:
| new = alt
max = d
if max > 66:
w = new
speak(w)
if w in cmds:
t = cmds[w][0]
p = cmds[w][1]
if t == web:
for i in range(1,len(words)):
p += words[i]+' '
Popen([browser, p])
elif t == say:
speak(p)
elif t == exe:
speak(p())
elif t == fun:
p()
elif t == run:
Popen(... |
flass/agrogenom | pipeline/scripts_agrogenom/3_Ananalysis_of_genome_histories/phyloprofile_to_db.py | Python | gpl-3.0 | 757 | 0.025099 | #!/usr/bin/python
"""to build genome.phylogenetic_profile table in agrogenomdb"""
import sys, os, tree2
nfphyloprofile = sys.argv[1]
nfout = sys.argv[2]
fphyloprofile = open(nfphyloprofile, 'r')
fout = open(nfout, 'w')
dboolstr = {True:'T', False:'F', '1':'T', '0':'F'}
header = fphylopro | file.readline().rstrip('\n').split('\t')[1:]
for line in fphyloprofile:
lsp = line.rstrip('\n').split('\t')
subfam = lsp[0]
profile = lsp[1:]
for i in range(len(profile)):
try:
fout.write('\t'.join([subfam, header[i], dboolstr[bool(int(profile[i]))], profile[i]])+'\n')
#~ fout.wr | ite('\t'.join([subfam, header[i], profile[i]])+'\n')
except KeyError, e:
print [subfam, header[i], profile[i]]
raise KeyError, e
fphyloprofile.close()
fout.close()
|
WALR/taiga-back | taiga/base/api/request.py | Python | agpl-3.0 | 14,953 | 0.000669 | # Copyright (C) 2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com>
# This 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 F... | thod, content type and content
"""
from django.conf import settings
from django.http import QueryDict
| from django.http.multipartparser import parse_header
from django.utils.datastructures import MultiValueDict
from django.utils.six import BytesIO
from taiga.base import exceptions
from . import HTTP_HEADER_ENCODING
from .settings import api_settings
def is_form_media_type(media_type):
"""
Return True if the ... |
Lazar-T/blic_news | storiesText.py | Python | mit | 2,806 | 0 | import urllib
from bs4 import BeautifulSoup
page_url = 'http://www.blic.rs/'
page = urllib.urlopen(page_url)
soup = BeautifulSoup(page)
a = soup.find(id="cat_boxes")
b = a.find_all('a')
def firstHeadline():
text1 = soup.select("#home_main_article_text")[0].h1.text
href1 = soup.select("#home_main_article_te... | ")[0].a.get('href')
return text1, href1
def secondHeadline():
text2 = soup.select("#home_main_article_text")[1].h1.text
href2 = soup.select("#home_main_article_text")[1].a.get('href')
return text2, href2
def thirdHeadline():
| text3 = soup.select("#home_main_article_text")[2].h1.text
href3 = soup.select("#home_main_article_text")[2].a.get('href')
return text3, href3
def fourthHeadline():
text4 = soup.select("#home_main_article_text")[3].h1.text
href4 = soup.select("#home_main_article_text")[3].a.get('href')
return tex... |
aptivate/ckanext-mapactiontheme | ckanext/mapactiontheme/controllers/package.py | Python | agpl-3.0 | 1,023 | 0.001955 | import ckan.controllers.package as package
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.model as model
from ckan.common import c
class MapactionPackageController(package.PackageController):
def groups(self, id):
q = model.Session.query(model.Group) \
.filter(model.... |
'auth_user_obj': c.userobj, 'use_cache': False}
group_list = model_dictize.group_list_dictize(groups, context)
c.event_dropdown = [[group['id'], group['display_name']]
fo | r group in group_list]
return super(MapactionPackageController, self).groups(id) |
conorsch/securedrop | molecule/testinfra/mon/test_mon_network.py | Python | agpl-3.0 | 3,154 | 0.000317 | import io
import os
import difflib
import pytest
from jinja2 import Template
import testutils
securedrop_test_vars = testutils.securedrop_test_vars
testinfra_hosts = [securedrop_test_vars.monitor_hostname]
@pytest.mark.skip_in_prod
def test_mon_iptables_rules(host):
local = host.get_host("local://")
time_... | p_test_vars.dns_server)
# Required for testing under Qubes.
if local.interface("eth0").exis | ts:
kwargs["ssh_ip"] = local.interface("eth0").addresses[0]
# Build iptables scrape cmd, purge comments + counters
iptables = r"iptables-save | sed 's/ \[[0-9]*\:[0-9]*\]//g' | egrep -v '^#'"
environment = os.environ.get("SECUREDROP_TESTINFRA_TARGET_HOST", "staging")
iptables_file = "{}/iptable... |
srinathv/bokeh | bokeh/tests/test_resources.py | Python | bsd-3-clause | 6,016 | 0.001828 | from __future__ import absolute_import
import unittest
import bokeh.resources as resources
from bokeh.resources import _get_cdn_urls
WRAPPER = """Bokeh.$(function() {
foo
});"""
WRAPPER_DEV = '''require(["jquery", "main"], function($, Bokeh) {
Bokeh.set_log_level("info");
Bokeh.$(function() {
foo
... | eError, setattr, r, "log_level", "foo")
def test_module_attrs(self):
| self.assertEqual(resources.CDN.mode, "cdn")
self.assertEqual(resources.INLINE.mode, "inline")
def test_inline(self):
r = resources.Resources(mode="inline")
self.assertEqual(r.mode, "inline")
self.assertEqual(r.dev, False)
self.assertEqual(len(r.js_raw), 3)
self.a... |
GNOME-MouseTrap/mousetrap | src/mousetrap/vision.py | Python | gpl-2.0 | 6,987 | 0.001288 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
'''
All things computer vision.
'''
import cv2
from mousetrap.i18n import _
from mousetrap.image import Image
import mousetrap.plugins.interface as interface
import logg... | lf._config = config
self._haar_files = config['haar_files']
self._haar_cache = {}
| def from_name(self, name):
if not name in self._haar_files:
raise HaarNameError(name)
haar_file = self._haar_files[name]
haar = self.from_file(haar_file, name)
return haar
def from_file(self, file_, cache_name=None):
import os
if cache_name in self._... |
flgiordano/netcash | +/google-cloud-sdk/lib/surface/auth/application_default/revoke.py | Python | bsd-3-clause | 1,851 | 0.003241 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | ooglecloudsdk.calliope import exceptions as c_exc
from googlecloudsdk.core.credentials import store as c_store
class Revoke(base.Command):
"""Revoke Application Default Credentials.
Revokes Application Defau | lt Credentials that have been set up by commands
in the Google Cloud SDK. The credentials are revoked remotely only if
they are user credentials. In all cases, the file storing the credentials is
removed.
This does not effect any credentials set up through other means,
for example credentials referenced by t... |
ifduyue/sentry | src/sentry/api/endpoints/organization_integration_repos.py | Python | bsd-3-clause | 1,418 | 0.002821 | from __future__ import absolute_import
from django.http import Http404
from sentry.constants import ObjectStatus
from sentry.api.bases.organization import (
OrganizationEndpoint, OrganizationIntegrationsPermission
)
from sentry.integrations.exceptions import IntegrationError
from sentry.integrations.repositories ... | ):
try:
integration = Integration.objects.get(id=integration_id, organizations=organization)
except Integration.DoesNotExist:
raise Http404
if integration.status == ObjectStatus.DISABLED:
c | ontext = {'repos': []}
return self.respond(context)
install = integration.get_installation(organization.id)
if isinstance(install, RepositoryMixin):
try:
repositories = install.get_repositories(request.GET.get('search'))
except IntegrationError as e:... |
googleapis/python-compute | samples/ingredients/instances/custom_hostname/get.py | Python | apache-2.0 | 1,531 | 0.002613 | # Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | UT WARRANTIES OR CONDITIONS OF ANY KIND, either | express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets
# folder for complete code samples that are ready to be used.
# Disabling flake8 for the ingredient... |
catalyst/patch-friend | patch/manage.py | Python | gpl-3.0 | 918 | 0 | #!/usr/bin/env pytho | n
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "patch.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is rea... | jango is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did y... |
WilliamMayor/scytale.xyz | scripts/encrypt/caesar.py | Python | mit | 222 | 0 | from scytale.ciphers import Caesar
i | f __name__ == '__main__':
plaintext = input('Plaintext: ')
key = int(input('Key: '))
ciphertext = Caesar(key=key).encrypt(plaintext)
print(f'Ciphertext: { | ciphertext}')
|
lmann4/cis526-final-project | resource_management/apps/employees/urls.py | Python | mit | 807 | 0.007435 | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from apps.employees import ajax
from . import vie | ws
urlpatterns = (
url(r'^home/$', login_required(views.home), name="employee_home_redirect"),
url(r'^(?P<pk>[\d]+)/$', login_required(views.EmployeeDetail.as_view()), name="employee_detail"),
url(r'^schedule/add$', login_required(views.ScheduleAdd.as_view()), name="employee_schedule_add"),
url(r'^sche... | -board/$', login_required(views.SubBoard.as_view()), name="sub_board"),
url(r'^ajax/take_slip/$', login_required(ajax.SubSlipAjax.as_view()), name="take_slip"),
)
|
hnakamur/saklient.python | saklient/cloud/errors/mustbeofsamezoneexception.py | Python | mit | 731 | 0.010292 | # -*- coding:utf-8 -*-
from ...errors.httpbadrequestexception import Ht | tpBadRequestException
import saklient
# module saklient.cloud.errors.mustbeofsamezoneexception
class MustBeOfSameZoneEx | ception(HttpBadRequestException):
## 不適切な要求です。参照するリソースは同一ゾーンに存在しなければなりません。
## @param {int} status
# @param {str} code=None
# @param {str} message=""
def __init__(self, status, code=None, message=""):
super(MustBeOfSameZoneException, self).__init__(status, code, "不適切な要求です。参照するリソースは同一ゾーンに... |
adsabs/adsabs-pyingest | examples/ex_atel.py | Python | mit | 401 | 0 | #!/usr/bin/env python
import os
impor | t sys
from pyingest.parsers.atel import ATelParser
from pyingest.serializers.classic import Tagged
rss_url = 'http://www.astronomerstelegram.org/?adsbiblio'
parser = ATelParser()
documents = parser.parse(rss_url, data_tag='item')
outputfp = open('atel.tag', 'a')
for d in documents:
serializer = Tagged()
| serializer.write(d, outputfp)
outputfp.close()
|
kuz/BrainActivity3D | lib/__init__.py | Python | gpl-3.0 | 39 | 0.025641 | """
Pull | third-party libraries here |
""" |
JaapJoris/bps | bps/utils.py | Python | agpl-3.0 | 267 | 0.011236 | import random
def read(file):
with op | en(file) as f:
return f.read()
HUMAN_FRIENDLY_CHARS = '234679ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
def random_string(length):
return ''.join(random.choice(HUMAN_FRIENDLY_CHARS) f | or x in range(length))
|
linuxlewis/channels | channels/binding/websockets.py | Python | bsd-3-clause | 5,020 | 0.000398 | import json
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
from .base import Binding
from ..generic.websockets import WebsocketDemultiplexer
from ..sessions import enforce_ordering
class WebsocketBinding(Binding):
"""
Websocket-specific outgoing binding subcla... | slight=False)
elif cls.slight_ordering:
return enforce_ordering(handler, slight=True)
else:
return handler
def deserialize(self, message):
"""
You must hook this up behind a Deserializer, so we expect the JSON
already dealt with.
"""
a... | sage.get('data', None)
return action, pk, data
def _hydrate(self, pk, data):
"""
Given a raw "data" section of an incoming message, returns a
DeserializedObject.
"""
s_data = [
{
"pk": pk,
"model": self.model_label,
... |
afrolov1/nova | nova/openstack/common/network_utils.py | Python | apache-2.0 | 5,553 | 0 | # Copyright 2012 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... | host = _host
if ':' in _port:
port = _port.split(':')[1]
else:
port = default_port
else:
if address.count(':') == 1:
host, port = address.split(':')
e | lse:
# 0 means ipv4, >1 means ipv6.
# We prohibit unescaped ipv6 addresses with port.
host = address
port = default_port
return (host, None if port is None else int(port))
class ModifiedSplitResult(parse.SplitResult):
"""Split results class for urlsplit."""
... |
cipriantarta/python-capture | capture.py | Python | bsd-3-clause | 2,890 | 0.001038 | import os
import socket
import subprocess
import time
import sys
class Streamer:
command = 'ffmpeg ' \
'-y ' \
'-f avfoundation ' \
'-r 30 ' \
'-pixel_format bgr0 ' \
' | -s 640x480 ' \
'-video_device_index 0 ' \
'-i ":0" ' \
'-c:v libvpx ' \
'-b:v 1M ' \
| '-c:a libvorbis ' \
'-b:a 96k ' \
'-deadline realtime ' \
'-flags +global_header ' \
'-cpu-used 1 ' \
'-threads 8 ' \
'-f segment ' \
'-f webm ' \
'-'
__connected = False
def __init__(s... |
synctree/synctree-awsebcli | ebcli/objects/environment.py | Python | apache-2.0 | 1,422 | 0.000703 | # Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with t | he License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHO | UT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
class Environment(object):
def __init__(self, version_label=None, status=None, app_name=None,
health=None, id=None, date_updat... |
alaudo/coderdojo-python | code/11 - empty.py | Python | cc0-1.0 | 126 | 0 | text = input("Enter something ") |
if (text.strip()):
print("This text is not empty")
| else:
print("This text is EMPTY")
|
gnmiller/craig-bot | craig-bot/lib/python3.6/site-packages/discord/colour.py | Python | mit | 7,005 | 0.003712 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
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 u... | r(self):
"""Returns the r | ed component of the colour."""
return self._get_byte(2)
@property
def g(self):
"""Returns the green component of the colour."""
return self._get_byte(1)
@property
def b(self):
"""Returns the blue component of the colour."""
return self._get_byte(0)
def to_r... |
2achary/sequencehelpers | setup.py | Python | mit | 467 | 0.002141 | from distutils.core im | port setup
setup(
name='sequencehelpers',
py_modules=['sequencehelpers'],
version='0.2.1',
description="A library consisting of functions for interacting with sequences and iterables.",
author='Zach Swift',
author_email='cras.zswift@gmail.com',
url='https://github.com/2achary/sequencehelpers',
download... |
classifiers=[],
)
|
seecr/meresco-solr | meresco/solr/__init__.py | Python | gpl-2.0 | 1,228 | 0.001629 | ## begin license ##
#
# "Meresco Solr" is a set of components and tools
# to integrate Solr into "Meresco."
#
# Copyright (C) 2011-2013 Seecr (Seek You Too B.V.) http://seecr.nl
# Copyright (C) 2012 SURF http://www.surf.nl
# Copyright (C) 2013 Stichting Kennisnet http://www.kennisnet.nl
#
# This file is part of "Meres... | ither version 2 of the License, or
# (at your option) any later version.
#
# "Meresco S | olr" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with "Mere... |
avedaee/DIRAC | TransformationSystem/Client/TransformationClient.py | Python | gpl-3.0 | 22,189 | 0.040786 | """ Class that contains client access to the transformation DB handler. """
__RCSID__ = "$Id$"
import types
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Base.Client import Client
from DIRAC.Core.Utilities.List ... | sformations = transformations + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformations )
def getTransformation( self, transName, extraParams = False, rpc = '', url = '', timeout = None ):
rpcClient = self._getRPC( rpc = rpc, url = ur... | pdate',
orderAttribute = None, limit = 10000, rpc = '', url = '', timeout = 1800 ):
""" gets all the transformation files for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout ... |
artreven/pp_api | pp_api/gs_calls.py | Python | mit | 11,664 | 0.000343 | import logging
from requests.exceptions import HTTPError
from pp_api import utils as u
from pp_api import pp_calls
module_logger = logging.getLogger(__name__)
class GraphSearch:
timeout = None
def __init__(self, server, auth_data=None, session=None, timeout=None):
self.server = server
ses... | dest_url = self.server + suffix
r = self.session.post(
dest_url,
json=data,
timeout=self.timeout
)
try:
r.raise_for_status()
except Exception as e:
msg = 'JSON data of the failed POST request: {}\n'.format(data)
ms... | at(r.text)
module_logger.error(msg)
raise e
return r
def clean(self, search_space_id):
"""
Remove first 100000 document from GraphSearch.
"""
r = self.search(
count=100000,
search_space_id=search_space_id
)
for ... |
sharad/calibre | src/calibre/ebooks/html/to_zip.py | Python | gpl-3.0 | 4,758 | 0.003993 | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import textwra... | 'include: cp1252, cp1251, latin1 and utf-8.')
def do_user_config(self, parent=None):
'''
This method shows a configuration dialog for this plugin. It returns
True if the user clicks OK, False otherwise. The changes are
automatically applied.
'''
from PyQt5.Qt import... |
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
v = QVBoxLayout(config_dialog)
def size_dialog():
config_dialog.resize(config_dialog.sizeHint())
button_box.accepted.connect(config_dialog.accept)
button_box.rejected.connect(config_dialog... |
jmargeta/scikit-learn | sklearn/linear_model/bayes.py | Python | bsd-3-clause | 15,486 | 0.000904 | """
Various bayesian regression
"""
from __future__ import print_function
# Authors: V. Michel, F. Pedregosa, A. Gramfort
# License: BSD 3 clause
from math import log
import numpy as np
from scipy import linalg
from .base import LinearModel
from ..base import RegressorMixin
from ..utils.extmath import fast_logdet, p... | te_score:
s = lambda_1 * log(lambda_) - lambda_2 * lambda_
s += alpha_1 * log(alpha_) - alpha_2 * alpha_
s += 0.5 * (n_fea | tures * log(lambda_)
+ n_samples * log(alpha_)
- alpha_ * rmse_
- (lambda_ * np.sum(coef_ ** 2))
- logdet_sigma_
- n_samples * log(2 * np.pi))
self.scores_.append(s... |
levilucio/SyVOLT | GM2AUTOSAR_MM/backward_matchers/models/ConnVirtualDevice2Distributable_Back_SCTEMc2Distributable_MDL.py | Python | mit | 19,240 | 0.010083 | """
__ConnVirtualDevice2Distributable_Back_SCTEMc2Distributable_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: levi
Modified: Mon Aug 26 09:54:59 2013
_________________________________________________________________________________... |
# MT_pivotIn__
self.obj48.MT_pivotIn__.setValue('')
self.obj48.MT_pivotIn__.setNone()
self.obj48.graphClass_= graph_MT_pre__ApplyModel
if self.genGraphics:
new_obj = graph_MT_pre__ApplyModel(72.0,240.0,self.obj48)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag(... | lf.obj48.graphObject_ = new_obj
# Add node to the root: rootNode
rootNode.addNode(self.obj48)
self.globalAndLocalPostcondition(self.obj48, rootNode)
self.obj48.postAction( rootNode.CREATE )
self.obj49=MT_pre__Distributable(self)
self.obj49.isGraphObjectVisual = True
if(hasattr(self.obj49,... |
martinstastny/django-simplestore | simplestore/checkout/migrations/0011_auto_20170831_1618.py | Python | mit | 654 | 0.001529 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-08-31 14:18
from __future__ import unicode_literals
fro | m django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('check | out', '0010_auto_20170614_1434'),
]
operations = [
migrations.DeleteModel(
name='Payment',
),
migrations.AlterField(
model_name='orderitem',
name='product',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, r... |
lbybee/okc_project | okc_scraper_no_q.py | Python | gpl-2.0 | 8,941 | 0.000783 | """okc_scraper includes all the functions needed to scrape profiles from
OKCupid"""
import requests
import cPickle as pickle
import time
from BeautifulSoup import BeautifulSoup
def authorize(username, password):
"""Log into OKCupid to scrape profiles"""
user_info = {"username": username, "password": passwor... | .find("p",
{"class":
"answer target clearfix | "}).text
question_list.append({"question_table":
{"user_id": profile_id,
"question_id": question_id,
"question_text": qtext,
"user_answer": atext,
... |
louyihua/edx-platform | lms/djangoapps/badges/api/tests.py | Python | agpl-3.0 | 9,405 | 0.002446 | """
Tests for the badges API views.
"""
from ddt import ddt, data, unpack
from django.conf import settings
from django.test.utils import override_settings
from nose.plugins.attrib import attr
from badges.tests.factories import BadgeAssertionFactory, BadgeClassFactory, RandomBadgeClassFactory
from openedx.core.lib.api.... | r=self.user, bad | ge_class=BadgeClassFactory(course_id=self.course.location.course_key))
# Should not be included.
for dummy in range(3):
self.create_badge_class(False)
response = self.get_json(self.url())
# pylint: disable=no-member
self.assertEqual(len(response['results']), 4)
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.