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 |
|---|---|---|---|---|---|---|---|---|
602p/orth | os/kernel/font/font.py | Python | lgpl-3.0 | 19,506 | 0.000103 | #adapted from ColorWall by jesstesstest
_font = (
(
("########"),
("##....##"),
("#.#..#.#"),
("#..##..#"),
("#..##..#"),
("#.#..#.#"),
("##....##"),
("########")
),
(
("########"),
("##....##"),
("#.#..#.#"),
("#..##..#"),
("#..##..#"),
("#.#..#.#"),
("... | #######")
),
(
("########"),
("##....##"),
("#.#..#.#"),
("#..##..#"),
("#..##..#"),
("#.#..#.#"),
("##....##"),
| ("########")
),
(
("........"),
("........"),
("........"),
("........"),
("........"),
("........"),
("........"),
("........")
),
(
("....#..."),
("....#..."),
("....#..."),
("....#..."),
("....#..."),
("........"),
("....#..."),
("........")... |
rohitranjan1991/home-assistant | homeassistant/components/plex/media_player.py | Python | mit | 19,911 | 0.000904 | """Support to interface with the Plex API."""
from __future__ import annotations
from functools import wraps
import json
import logging
import plexapi.exceptions
import requests.exceptions
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN, MediaPlayerEntity
from homeassistant.components.media_pla... | n(name_parts))
def force_idle(self):
"""Force client to idle."""
self._attr_state = STATE_IDLE
if self.player_source == "session":
self.device = None
self.session_device = None
| self._attr_available = False
@property
def session(self):
"""Return the active session for this player."""
return self._session |
hkariti/ansible | lib/ansible/modules/network/enos/enos_config.py | Python | gpl-3.0 | 9,930 | 0.000604 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2017 Red Hat Inc.
# Copyright (C) 2017 Lenovo.
#
# GNU General Public License v3.0+
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied w | arranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# Module to configure Lenovo Switches.
# Lenovo Networking
#
from __future__ import absolute_import, division, print_function
__metacl... | = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: enos_config
version_added: "2.5"
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
short_description: Manage Lenovo ENOS configuration se... |
idosekely/python-lessons | lesson_1/variables.py | Python | mit | 403 | 0 | __author__ = 'sekely'
'''
we are | using variables almost everywhere in the code.
variables are used to store results, calculations and many more.
this of it as the famous "x" from high school
x = 5, right?
the only thing is, that in Python "x" can store anything
'''
# try this code:
x = 5
y = x + 3
print(y)
# what about this? will it work?
x = 'he... | orld!'
w = x + y + z
print(w)
|
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/topology_parameters.py | Python | mit | 1,697 | 0.001768 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | etw | ork
self.target_subnet = target_subnet
|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_02_01/operations/_usages_operations.py | Python | mit | 5,274 | 0.004361 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('U | sagesListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
... |
ostrokach/biskit | Biskit/Model.py | Python | gpl-3.0 | 10,389 | 0.02108 | ##
## Biskit, a toolkit for the manipulation of macromolecular structures
## Copyright (C) 2004-2012 Raik Gruenberg & Johan Leckner
##
## 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 v... | if k in self.chains:
return self.chains.set( k, v )
if k in self.info:
self.info[ k ] = v
raise ProfileError, \
'Value cannot clearly be assigned to either atom or '+\
| 'residue or chain profiles'
if type( k ) is tuple:
key, infokey = k
if key in self.atoms:
self.atoms[key, infokey] = v
return
if key in self.residues:
self.residues[key, infokey] = v
retur... |
develru/RobotControlCenterKivy | main.py | Python | gpl-3.0 | 210 | 0 | from kivy. | app import App
from kivy.uix.button import Button
class RobotControlApp(App):
def build(self):
return Button(text='Hello World')
if __name__ == '__main__':
RobotControlApp().run( | )
|
nobodyinperson/python3-numericalmodel | tests/test_data.py | Python | gpl-3.0 | 794 | 0.011335 | #!/usr/bin/env python3
# internal modules
import numericalmodel
# external modules
import numpy as np
EMPTY_ARRAY = np.array([])
class LinearDecayEquation(numericalmodel.equations.PrognosticEquation):
"""
Class for the linear decay equation
"""
def linear_factor(self, time = None ):
# take th... | dend(self, *args, **kwargs):
return 0 # nonlinear addend is always zero (LINEA | R decay equation)
|
USStateDept/geonode | geonode/groups/models.py | Python | gpl-3.0 | 9,016 | 0.001331 | import datetime
import hashlib
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.db import models, IntegrityError
from django.utils.translation import ugettext_lazy as _
from django.db.models import signals
from taggit.managers imp... | lf.slug})
@property
def class_name(self):
return self.__clas | s__.__name__
class GroupMember(models.Model):
group = models.ForeignKey(GroupProfile)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
role = models.CharField(max_length=10, choices=[
("manager", _("Manager")),
("member", _("Member")),
])
joined = models.DateTimeField(default=da... |
gooddata/openstack-nova | nova/objects/cell_mapping.py | Python | apache-2.0 | 10,122 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | rimitive, target_version):
super(CellMapping, self).obj_make_compatible(primitive, target_version)
target_version = versionutils.convert_version_to_tuple(target_version)
if target_version < (1, 1):
if 'disabled' in primitive:
del primitive['disabled']
@property
... | return self.uuid
@staticmethod
def _format_url(url, default):
default_url = urlparse.urlparse(default)
subs = {
'username': default_url.username,
'password': default_url.password,
'hostname': default_url.hostname,
'port': default_url.p... |
DLR-SC/tigl | thirdparty/nsiqcppstyle/nsiqunittest/nsiqcppstyle_unittestbase.py | Python | apache-2.0 | 2,439 | 0.00451 | # Copyright (c) 2009 NHN 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 follow... | this list of | conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of NHN Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOF... |
DanielleWingler/UnderstandingDjango | TestSite/blog/__init__.py | Python | mit | 85 | 0.023529 | #Intentionall | y left blank. There should be a .pyc file by the same name at cre | ation.
|
b4ux1t3/adventofcode2015 | day1/generate.py | Python | mit | 366 | 0.005464 | import random, sys
if len(sys.argv)!= 2:
print "Usage: python generate.py <how many instructions you want>"
sys.exit()
choices = ("(", ")")
output = ""
| for x in range(int(sys.argv[1])):
output += random.choice(choices)
f = open("randout", "w")
f.write(output)
f.close
print "Created an instruction set that is " + sys.argv[1] + " characters lon | g"
|
jameslivulpi/socketprogramming | udpServer.py | Python | gpl-3.0 | 872 | 0.001147 | #!/usr/bin/python
# UDPPingerServer.py
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bi... | Capitalize the message from the client
message = message.upper()
# If rand is less is than 4, we consider the packet lost and do not respond
if rand < 4:
continue
# | Otherwise, the server responds
serverSocket.sendto(message, address)
|
apache/libcloud | libcloud/test/compute/test_dimensiondata_v2_4.py | Python | apache-2.0 | 160,650 | 0.001332 | # 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 ... | ataMockHttp.type = None
ret = self.driver.list_nodes()
| self.assertTrue(
isinstance(ret[0].extra["vmWareTools"], DimensionDataServerVMWareTools)
)
self.assertTrue(
isinstance(ret[0].extra["cpu"], DimensionDataServerCpuSpecification)
)
self.assertTrue(isinstance(ret[0].extra["disks"], list))
self.assertTrue(... |
xaque208/dotfiles | bin/init.py | Python | mit | 239 | 0 | #! /usr/ | bin/env python
import os
from dotfiles import Dotfiles
def main():
homedir = os.environ['HOME']
dotfilesRoot = homedir + '/dotfiles'
d = Dotfiles(dotfilesRoot)
d.setup()
if __name__ = | = "__main__":
main()
|
thalamus/Flexget | flexget/plugins/plugin_sftp.py | Python | mit | 14,868 | 0.003228 | from __future__ import unicode_literals, division, absolute_import
from urlparse import urljoin, urlparse
from collections import namedtuple
from itertools import groupby
import logging
import os
import posixpath
from functools import partial
import time
from flexget import plugin
from flexget.event import event
from ... | partial(handle_node, size_handler=dir_size, is_dir=True) |
def handle_unknown(path):
"""
Skip unknown files
"""
log.warn('Skipping unknown file: %s' % path)
# the business end
for dir in dirs:
try:
sftp.walktree(dir, handle_file, handle_dir, handle_unknown, recursive)
... |
pennersr/django-allauth | allauth/socialaccount/providers/patreon/views.py | Python | mit | 2,047 | 0.001466 | """
Views for PatreonProvider
https://www.patreon.com/platform/documentation/oauth
"""
import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import API_URL, USE_API_V2, PatreonProvider
class PatreonOAuth2Adapter(O... | get(
self.profile_url,
headers={"Authorization": "Bearer " + token.token},
)
| extra_data = resp.json().get("data")
if USE_API_V2:
# Extract tier/pledge level for Patreon API v2:
try:
member_id = extra_data["relationships"]["memberships"]["data"][0]["id"]
member_url = (
"{0}/members/{1}?include="
... |
ybdarrenwang/DuplicatedPhotoFinder | main.py | Python | bsd-3-clause | 2,866 | 0.008374 | import sys, Tkinter, tkFont, ttk
sys.path.insert(0, "./src/")
import button, database
from config import *
# Note: need to set size for bg_canvas here; otherwise it will grow disregard the size set while created!
def AuxscrollFunction(event):
bg_canvas.configure(scrollregion=bg_canvas.bbox("all"), height=THUMB_HEI... | ction)
# Note: don't pack batch_photo_frame here, otherwise scroll bar won't show!!!
# create photo database and loading progress bar
progress_bar = ttk.Progressbar(root, orient=Tkinter.HORIZONTAL, length=PROGRESS_BAR_LENGTH, mode='determinate')
progress_bar.grid(row=2, column=2, columnspan=2, sticky=Tkinter.E+Tkinter... | tton_cfg = button.ConfigButton(root, db, 2, 3)
button_next = button.NextBatchButton(root, batch_photo_frame, display_photo_frame, display_photo_info_frame, db, 2, 1)
button_open = button.OpenFolderButton(root, batch_photo_frame, db, button_next, 2, 0)
root.mainloop()
|
alexlo03/ansible | contrib/inventory/zabbix.py | Python | gpl-3.0 | 4,795 | 0.002086 | #!/usr/bin/env python
# (c) 2013, Greg Buehler
#
# 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 ve... | groupname = group['name']
if groupname not in data:
data[groupname] = self.hoststub()
data[groupname]['hosts'].append(hostname)
# Prevents Ansible from calling this script for each server with --host
data['_meta'] = {'hostvars': self.met... | rname = None
self.zabbix_password = None
self.validate_certs = True
self.meta = {}
self.read_settings()
self.read_cli()
if self.zabbix_server and self.zabbix_username:
try:
api = ZabbixAPI(server=self.zabbix_server, validate_certs=self.valida... |
cpennington/edx-platform | openedx/core/djangoapps/credit/migrations/0006_creditrequirement_alter_ordering.py | Python | agpl-3.0 | 387 | 0 | # -*- coding: utf-8 -*-
from __future__ impor | t unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('credit', '0005_creditrequirement_sort_value'),
]
operations = [
migrations.AlterModelOptions(
name='creditrequirement',
options={'ordering': ['sort_value | ']},
),
]
|
zerok/django-zsutils | django_zsutils/templatetags/zsutils/taghelpers.py | Python | bsd-3-clause | 1,704 | 0.005282 | """
:Requirements: django-tagging
This module contains some additional helper tags for the django-tagging
project. Note that the functionality here might already be present in
django-tagging but perhaps with some slightly different behaviour or
usage.
"""
from django import template
from django.core.urlresolvers imp... | )
@register.tag('object_tags')
def tags_for_object | (parser, token):
"""
Simple tag for rendering tags of an object
Usage::
{% object_tags object.tags blog-tag ", " " and " %}
The last two arguments determine the junctor between the tag names with
the last being the last junctor being used.
"""
variables = token.split_c... |
leeclarke/homePi | src/python/zipInstall.py | Python | gpl-3.0 | 2,124 | 0.013183 | """
Manages downloading and updating applications throught he use of a zip file hosted on HomePi server.
"""
import datetime
import os.path
import zipfile
import urllib2
#Test call to verify thins work.
def print_info(archive_name):
zf = zipfile.ZipFile(archive_name)
for info in zf.infolist():
print... | )'
print '\tZIP version:\t', info.create_version
print '\tCompressed:\t', info.compress_size, 'bytes'
print '\tUncompressed:\t', info.file_size, 'bytes'
print
# Extracts files from given archive into targetlocation. Preserves archive folder structure.
def extractFiles(archive_name,targe... | zf.extractall(path=targetLocation)
# Download archive file for unpacking.
def retrieveZipfile(saveLocation, archiveURI, currentVersion = -1):
fileName = os.path.basename(archiveURI)
print 'downloading file: %s' % fileName
try:
response = urllib2.urlopen(archiveURI)
#Check to see if new ver... |
sargas/scipy | scipy/optimize/tests/test_minpack.py | Python | bsd-3-clause | 13,744 | 0.006694 | """
Unit tests for optimization routines from minpack.py.
"""
from __future__ import division, print_function, absolute_import
from numpy.testing import assert_, assert_almost_equal, assert_array_equal, \
assert_array_almost_equal, TestCase, run_module_suite, assert_raises, \
assert_allclose
import num... |
P = k * flow_rates**2
F = np.hstack((P[1:] - P[0], flow_rates.sum() - Qtot))
return F
def pressure_network_jacobian(flow_rates, Qtot, k):
"""Return the jacobian of the equation system F(flow_rates)
computed by `pressure_network` with respect to
*flow_rates*. See `pressure_network` for the deta... | and *f_i* and *Q_i* are described in the doc for `pressure_network`
"""
n = len(flow_rates)
pdiff = np.diag(flow_rates[1:] * 2 * k[1:] - 2 * flow_rates[0] * k[0])
jac = np.empty((n, n))
jac[:n-1, :n-1] = pdiff * 0
jac[:n-1, n-1] = 0
jac[n-1, :] = np.ones(n)
return jac
def pressure... |
stratis-storage/stratis-cli | tests/whitebox/monkey_patching/test_keyboard_interrupt.py | Python | apache-2.0 | 1,934 | 0 | # Copyright 2016 Red Hat, 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... | rdInterrupt and exits with an error message.
The KeyboardInterrupt is most likely raised in the dbus-python
method which is actually communicating on the D-Bus, but it is
fairly difficult to get at that method. Instead settle for getti | ng
at the calling method generated by dbus-python-client-gen.
"""
def raise_keyboard_interrupt(_):
"""
Just raise the interrupt.
"""
raise KeyboardInterrupt()
# pylint: disable=import-outside-toplevel
# isort: LOCAL
from s... |
lorisercole/thermocepstrum | sportran/md/tools/resample.py | Python | gpl-3.0 | 1,531 | 0.001306 | # -*- coding: utf-8 -*-
import numpy as np
from scipy.signal import lfilter
def filter_and_sample(y_big, W, DT, window='rectangular', even_NSTEPS=True, detrend=False, drop_first=True):
"""Filter signal with moving average window of width W and then sample it
with time step DT."""
if (W > 1):
if ... | =0)
else:
raise NotImplementedError('Not implemented window type.')
| # drop first W steps (initial conditions)
if drop_first:
y = y_f[(W - 1)::DT]
else:
y = y_f[::DT]
else:
y = y_big[::DT]
# remove the mean
if detrend:
y = y - np.mean(y, axis=0)
# keeps an even number of points
if even_NSTEPS:
... |
nickmcummins/misc-tools | piwigo/piwigo_symlink_local_album.py | Python | gpl-3.0 | 1,897 | 0.005799 | import pathlib
import argparse
import os
IMGFORMAT = 'JPG'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Symlink a local album directory to the "galleries" subdirecto | ry in a local Piwigo instance.')
parser.add_argument('src_album', type=str, help='Location of album to symlink, relative to ALBUMS_ROOT')
parser.add_argument('piwigo_dir', type=str, help='Location of local Piwigo instance (e.g. /srv/http/piwigo)')
parser.add_argument('--sudo', '-su', action='store_true', he... | s()
src_album, piwigo_dir, use_sudo = args.src_album, args.piwigo_dir, args.sudo
minrange = int(args.range.split('-')[0]) if args.range is not None else 0
maxrange = int(args.range.split('-')[1]) if args.range is not None else 1000000
albums_root = os.getenv('ALBUMS_ROOT', f'{str(pathlib.Path.home())}/... |
sigdotcom/acm.mst.edu | ACM_General/tools/tests.py | Python | gpl-3.0 | 857 | 0 | """
Contains all unit tests for the Tools app.
"""
# Django
# from django.conf import settings
# from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.urls import reverse
# from django.utils import timezone
# local Django
# from accounts.models import User
# from e... | t Event
class HomeViewCase(TestCase):
"""
A class that tests whether tools functions work
"""
def test_view_responses(self):
"""
Makes requests to each page of the site and asserts a 200 response code
(or succe | ss)
"""
response = self.client.get(reverse('tools:membership'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'tools/membership.html')
|
datagutten/comics | comics/comics/gws.py | Python | agpl-3.0 | 839 | 0 | from co | mics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = 'Girls With Slingshots'
language = 'en'
url = 'http://www.girlswithslingshots.com | /'
start_date = '2004-09-30'
rights = 'Danielle Corsetto'
class Crawler(CrawlerBase):
history_capable_days = 30
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = 'US/Eastern'
def crawl(self, pub_date):
feed = self.parse_feed('http://www.girlswithslingshots.com/feed/')
for entry in feed.... |
sometallgit/AutoUploader | Python27/Lib/test/test_ensurepip.py | Python | mit | 9,313 | 0 | import unittest
import os
import os.path
import contextlib
import sys
import test._mock_backport as mock
import test.test_support
import ensurepip
import ensurepip._uninstall
class TestEnsurePipVersion(unittest.TestCase):
def test_returns_version(self):
self.assertEqual(ensurepip._PIP_VERSION, ensurepip... | f.assertRaises(ValueError):
ensurepip.bootstrap(altinstall=True, default_pip=True)
self.assertFalse(self.run_pip.called)
def test_pip_environment_variables_removed(self):
# ensurepip deliberately ignores all pip environment variables
# See http://bugs.python.org/issue19734 for d... | st fodder"
ensurepip.bootstrap()
self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ)
def test_pip_config_file_disabled(self):
# ensurepip deliberately ignores the pip config file
# See http://bugs.python.org/issue20053 for details
ensurepip.bootstrap()
self.... |
hoechenberger/psychopy | psychopy/tests/test_compatibility/test_compatibility.py | Python | gpl-3.0 | 1,242 | 0.000805 | # -*- coding: utf-8 -*-
"""Tests for psychopy.compatibility"""
from builtins import objec | t
import os
from psychopy import constants, compatibility
import pytest
pytestmark = pytest.mark.skipif(
cons | tants.PY3,
reason='Python3 cannot import the old-style pickle files')
thisPath = os.path.split(__file__)[0]
fixtures_path = os.path.join(thisPath, '..', 'data')
class _baseCompatibilityTest(object):
def test_FromFile(self):
dat = compatibility.fromFile(self.test_psydat)
class TestOldTrialHandler(_ba... |
andela-sjames/django-bucketlist-application | bucketlistapp/bucketlistapi/tests/test_bucketlistitems.py | Python | gpl-3.0 | 1,569 | 0.01211 | ''' Script used to test bucketlistitem response and request.'''
from rest_framework.authtoken.models import Token
from rest_framework.tes | t import APIClient
from django.core.urlresolvers import reverse_lazy
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from .test_bucketlist import ApiHeaderAuthorization
clas | s ApiUserBucketlistItems(ApiHeaderAuthorization):
def test_user_can_addbucketlist(self):
data={'name': 'item', 'done': True }
url= reverse_lazy('addbucketitem', kwargs={'id':19})
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
... |
silveregg/moto | tests/test_dynamodb2/test_dynamodb_table_with_range_key.py | Python | apache-2.0 | 47,256 | 0.000825 | from __future__ import unicode_literals
from decimal import Decimal
import boto
import boto3
from boto3.dynamodb.conditions import Key
import sure # noqa
from freezegun import freeze_time
from moto import mock_dynamodb2
from boto.exception import JSONResponseError
from tests.helpers import requires_boto_gte
try:
... | threads_index',
parts=[
HashKey('forum_name', data_type=STRING),
RangeKey('threads', data_type=NUMBER),
]
)
]
)
return table
def iterate | _results(res):
for i in res:
pass
@requires_boto_gte("2.9")
@mock_dynamodb2
@freeze_time("2012-01-14")
def test_create_table():
table = create_table()
expected = {
'Table': {
'AttributeDefinitions': [
{'AttributeName': 'forum_name', 'AttributeType': 'S'},
... |
flaing/gemrb | gemrb/GUIScripts/iwd2/Start.py | Python | gpl-2.0 | 6,550 | 0.027176 | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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) ... | dow.GetControl(0x0fff0000)
VersionLabel.SetText(GEMRB_VERSION)
ProtocolButton. | SetStatus(IE_GUI_BUTTON_ENABLED)
NewGameButton.SetStatus(IE_GUI_BUTTON_ENABLED)
LoadGameButton.SetStatus(IE_GUI_BUTTON_ENABLED)
GemRB.SetVar("SaveDir",1)
Games=GemRB.GetSaveGames()
#looking for the quicksave
EnableQuickLoad = IE_GUI_BUTTON_DISABLED
for Game in Games:
Slotname = Game.GetSaveID()
# quick sav... |
calamares/calamares | src/modules/bootloader/main.py | Python | gpl-3.0 | 28,413 | 0.001901 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# === This file is part of Calamares - <https://calamares.io> ===
#
# SPDX-FileCopyrightText: 2014 Aurélien Gâteau <[email protected]>
# SPDX-FileCopyrightText: 2014 Anke Boersma <[email protected]>
# SPDX-FileCopyrightText: 2014 Daniel Hillenbrand <[email protected]... | t_kernel_line(kernel_type)
libcalamares.utils.debug("Configure: \"{!s}\"".format(kernel_line))
if kernel_type == "fallback":
img = libcalamares.job.configuration["fallback"]
entry_name = entry_name + "-fallback"
else:
img = libcalamares.job.configuration["i | mg"]
conf_path = os.path.join(install_path + efi_dir,
"loader",
"entries",
entry_name + ".conf")
# Copy kernel and initramfs to a subdirectory of /efi partition
files_dir = os.path.join(install_path + efi_dir, entry_nam... |
jordens/sensortag | influx_udp.py | Python | lgpl-3.0 | 2,082 | 0 | import logging
import asyncio
logger = logging.getLogger(__name__)
class InfluxLineProtocol(asyncio.DatagramProtocol):
def __init__(self, loop):
self.loop = loop
self.transport = None
def connection_made(self, transport):
self.transport = transport
@staticmethod
def fmt(meas... | nce(v, float):
msg += "{:g}".format(v)
elif isinstance(v, bool):
msg += "{:s}".format(v)
elif isinstance(v, str):
msg += '"{:s}"'.format(v.replace('"', '\\"'))
else:
raise TypeError(v)
msg += ","
if f... | mat(timestamp)
return msg
def write_one(self, *args, **kwargs):
msg = self.fmt(*args, **kwargs)
logger.debug(msg)
self.transport.sendto(msg.encode())
def write_many(self, lines):
msg = "\n".join(lines)
logger.debug(msg)
self.transport.sendto(msg.encode()... |
ikoula/cloudstack | tools/marvin/marvin/lib/common.py | Python | gpl-2.0 | 67,873 | 0.002328 | # 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... | StorageNetworkIpRange,
TrafficType)
from marvin.lib.vcenter import Vcenter
from netaddr import IPAddress
import random
import re
import itertools
import random
import hashlib
# Import System modules
import time
def is_config_suitable(apiclient, name, value):
"""
Ensure if the de... | for the global setting `name'
@return: true if value is set, else false
"""
configs = Configurations.list(apiclient, name=name)
assert(
configs is not None and isinstance(
configs,
list) and len(
configs) > 0)
return configs[0].value == value
def wait_fo... |
eladnoor/small-molecule-regulation | python/topology.py | Python | mit | 3,400 | 0.000882 | # Pre-compute the shortest path length in the stoichiometric matrix
# NB: check some of the shortest path calcs?
import pdb
import settings
import networkx as nx
import pandas as pd
import numpy as np
import os
METS_TO_REMOVE = ['h', 'h2o', 'co2', 'o2', 'pi', 'atp', 'adp', 'amp',
'nad', 'nadh', 'na... | _dist['distance'] = pd.np.nan
for | i, row in smrn_dist.iterrows():
source = row['bigg.metabolite'] # remember we dropped it before
target = row['bigg.reaction']
if source.lower() in METS_TO_REMOVE:
continue
if target in spl[source]:
smrn_dist.at[i, 'distance'] = (spl[source][target] - 1.0) / 2.0
... |
ikn/farragone | farragone/__init__.py | Python | gpl-3.0 | 418 | 0.002392 | """Farragone.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Pu | blic License as | published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version."""
import gettext
from . import coreconf as _conf
gettext.install(_conf.IDENTIFIER, _conf.PATH_LOCALE, names=('ngettext',))
from . import util, conf, core, ui
|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_02_01/operations/_network_interface_load_balancers_operations.py | Python | mit | 5,808 | 0.004304 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | s class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2019_02_01.models
| :param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._clie... |
Moshiasri/learning | Python_dataCamp/Map()LambdaFunction.py | Python | gpl-3.0 | 474 | 0 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 30 20:12:17 2017
@author: Mohtashim
"""
# Create a list of strings: spells
spells = ["protego", "accio", "expecto patronum", "legilimens"]
# Use map() to apply a lambda function over spells: shout_spells
shout_spells = map(lambda item: item + '!! | !', spells)
# Con | vert shout_spells to a list: shout_spells_list
shout_spells_list = list(shout_spells)
# Convert shout_spells into a list and print it
print(shout_spells_list)
|
obi-two/Rebelion | data/scripts/templates/object/tangible/deed/corellia/player_house_deed/shared_corellia_house_large_deed.py | Python | mit | 490 | 0.044898 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLIN | E DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/deed/corellia/player_house_deed | /shared_corellia_house_large_deed.iff"
result.attribute_template_id = 2
result.stfName("deed","corellia_house_large_deed")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
111t8e/h2o-2 | py/test_config_basic.py | Python | apache-2.0 | 597 | 0.005025 | import h2o, h2o_config
l = h2o_config.setup_test_config(test_config_json='test_config.json')
print "\nsetup_test_config returns list o | f test config objs:", l
# Here are some ways to reference the config state that the json created
print "\nHow to reference.."
for i, obj in enumerate(h2o_config.configs):
print "keys in config", i, ":", obj.__dict__.keys()
prin | t h2o_config.configs[0].trees
for t in h2o_config.configs:
print "\nTest config_name:", t.config_name
print "trees:", t.trees
print "params:", t.params
print "params['timeoutSecs']:", t.params['timeoutSecs']
|
allure-framework/allure-python | allure-robotframework/examples/status/status_library.py | Python | apache-2.0 | 129 | 0 |
from robot.libraries.BuiltIn import BuiltIn
def fail_with_traceback(traceback | _message):
BuiltIn().f | ail(traceback_message)
|
ManInAGarden/PiADCMeasure | tkwindow.py | Python | lgpl-3.0 | 4,958 | 0.010286 | # -*- coding: utf-8 *-*
# made for python3!
from tkinter import *
from tkinter.ttk import *
class TkWindow():
registers = {}
def __init__(self, parent, title, width=400, height=300):
self.parent = parent #Tk or toplevel
self.w = width
self.h = height
self.make_gui(ti... | entry.insert(0, value)
def settextvalue(self, entry, value):
entry.delete(0.0,END);
entry.insert(0.0, value);
def setbuttontext(self, button, txt):
button['text'] = txt
def makecombo(self, parent, ccol=1, c | row=0, lcol=0, lrow=0, caption='',
width=None, **options):
if caption!='':
Label(parent, text=caption).grid(row=lrow, column=lcol, sticky=E)
cbox = Combobox(parent, **options)
if width:
cbox.config(width=width)
cbox.gr... |
SINGROUP/pycp2k | pycp2k/classes/_davidson2.py | Python | lgpl-3.0 | 666 | 0.003003 | from pycp2k.inputsection import InputSection
from ._each112 import _each112
class _davidson2(InputSection):
def __init__(self):
InputSection._ | _init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
self.Log_print_key = None
self.EACH = _each112()
self._name = "DAVIDSON"
self._keywords = {'Log_print_key': 'LOG_PRINT_KEY', 'Filenam... | ': 'COMMON_ITERATION_LEVELS'}
self._subsections = {'EACH': 'EACH'}
self._attributes = ['Section_parameters']
|
robocomp/robocomp-robolab | experimental/dumbGlobalTrajectory/src/trajectoryrobot2dI.py | Python | gpl-3.0 | 1,815 | 0.019835 | #
# Copyright (C) 2016 by YOUR NAME HERE
#
# This file is part of RoboComp
#
# RoboComp 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... | nment variable not set, using the default value /opt/robocomp'
ROBOCOMP = '/opt/robocomp'
if len(ROBOCOMP)<1:
print 'ROBOCOMP environment variable not set! Exiting.'
sys.exit()
preStr = "-I"+ROBOCOMP+"/interfaces/ --all "+ROBOCOMP+"/interfaces/"
Ice.loadSlice(preStr+"TrajectoryRobot2D.ice")
from RoboCompTrajecto... | obot2D import *
class TrajectoryRobot2DI(TrajectoryRobot2D):
def __init__(self, worker):
self.worker = worker
def getState(self, c):
return self.worker.getState()
def goBackwards(self, target, c):
return self.worker.goBackwards(target)
def stop(self, c):
return self.worker.stop()
def goReferenced(self, t... |
luotao1/Paddle | python/paddle/fluid/dygraph/profiler.py | Python | apache-2.0 | 886 | 0 | # Copyright (c) 2018 PaddlePaddle 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
#
# Unless required by app... | License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_functio | n
from .. import core
__all__ = [
'start_gperf_profiler',
'stop_gperf_profiler',
]
def start_gperf_profiler():
core.start_imperative_gperf_profiler()
def stop_gperf_profiler():
core.stop_imperative_gperf_profiler()
|
b-com/watcher-metering | watcher_metering/agent/agent.py | Python | apache-2.0 | 5,245 | 0 | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# 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 o... | pdate_endpoint
else:
self.nanoconfig_update_endpoint = nn_config_updates
def run(self):
self.setup_socket()
super(Agent, self).run()
def stop(self):
self.socket.close()
super(Agent, self).stop()
LOG.debug("[Agent] Stopped")
def update(self, noti... | ted by: %s", notifier)
LOG.debug("[Agent] Preparing to send message %s", msgpack.loads(data))
try:
LOG.debug("[Agent] Sending message...")
# The agent will wait for the publisher server to be listening on
# the related publisher_endpoint before continuing
... |
TzuChieh/Photon-v2 | BlenderAddon/PhotonBlend/bmodule/common/__init__.py | Python | mit | 73 | 0.013699 |
def mangled_node_tree_name(b_mate | rial):
return "PH_" + b_material | .name
|
fbcom/project-euler | 018_maximum_path_sum_1.py | Python | mit | 1,351 | 0.000741 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# A Solution to "Maximum path sum I" – Project Euler Problem No. 18
# by Florian Buetow
#
# Sourcecode: https://github.com/fbcom/project-euler
# Problem statement: http | s://projecteuler.net/problem=18
#
def g | et_triangular_list(str):
ret = []
tmp = []
i = j = 1
for n in str.split():
tmp.append(int(n))
j = j + 1
if j > i:
ret.append(tmp)
tmp = []
j = 1
i = i + 1
return ret
def find_max_path(nums, row, col):
if row == len(nums):
... |
vulcansteel/autorest | AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/auto_rest_swagger_bat_array_service/models/product.py | Python | mit | 931 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. | See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import... | = {
'integer': {'key': 'integer', 'type': 'int'},
'string': {'key': 'string', 'type': 'str'},
}
def __init__(self, *args, **kwargs):
"""Product
:param int integer
:param str string
"""
self.integer = None
self.string = None
super(Produc... |
markstoehr/structured_gaussian_mixtures | structured_gaussian_mixtures/mdn_experiment_one_ahead.py | Python | apache-2.0 | 5,886 | 0.002039 | from __future__ import print_function, division
import cPickle
import gzip
import os
import sys
import timeit
import numpy
import theano
from theano import tensor
import mdn_one_ahead
# parameters
batch_size = 100
L1_reg=0.00
L2_reg=0.0001
n_epochs=200
learning_rate = 0.001
momentum = 0.9
sigma_in = 320
mixing_in = ... | alidation_loss = numpy.mean(validation_losses)
print(
'epoch %i, minibatch %i/%i, validation error %f %%' %
(
epoch,
minibatch_index + 1,
n_train_batches,
this_validation_loss * 100.
... | mprove patience if loss improvement is good enough
if (
this_validation_loss < best_validation_loss *
improvement_threshold
):
patience = max(patience, iter * patience_increase)
best_validation_loss = this_valida... |
adafruit/micropython | ports/nrf/examples/ubluepy_scan.py | Python | mit | 923 | 0.005417 | from ubluepy import Scanner, constants
def bytes_to_str(bytes):
st | ring = ""
for b in bytes:
string += chr(b)
return string
def get_device_names(scan_entries):
dev_names = []
for e in scan_entries:
scan = e.getScanData()
if scan:
for s in scan:
if s[0] == constants.ad_types.AD_TYPE_COMPLETE_LOCAL_NAME:
... | device_names = get_device_names(scan_res)
for dev in device_names:
if name == dev[1]:
return dev[0]
# >>> res = find_device_by_name("micr")
# >>> if res:
# ... print("address:", res.addr())
# ... print("address type:", res.addr_type())
# ... print("rssi:", res.rssi())
# ...
# ...
#... |
why2pac/dp-tornado | example/controller/tests/view/ui_methods/mmdd.py | Python | mit | 1,216 | 0.004934 | # -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
class MmddController(Controller):
def get(self):
self.model.tests.helper_test.datetime.switch_timezone('Asia/Seoul')
ts = 1451671445
ms = ts * 1000
dt = self.helper.datetime.convert(timestamp=ts)
... | g('tests/view/ui_method | s/mmdd.html', {'args': args_dt}) == '01.02')
assert(self.render_string('tests/view/ui_methods/mmdd.html', {'args': args_ms}) == '01.02')
assert(self.render_string('tests/view/ui_methods/mmdd.html', {'args': args_ts}) == '01.02')
assert(self.render_string('tests/view/ui_methods/mmdd.html', {'arg... |
tiborsimko/jsonalchemy | jsonalchemy/jsonext/functions/util_split.py | Python | gpl-2.0 | 1,313 | 0.000762 | # -*- coding: utf-8 -*-
#
# This file is part of JSONAlchemy.
# Copyright (C) 2013, 2014, 2015 CERN.
#
# JSONAlchemy 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.
#
# JSONAlchemy 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 receive... | 0, Boston, MA 02111-1307, USA.
"""Function for tokenizing strings in models' files."""
def util_split(string, separator, index):
"""
Helper function to split safely a string and get the n-th element.
:param string: String to be split
:param separator:
:param index: n-th part of the split string ... |
jonparrott/google-cloud-python | spanner/google/cloud/spanner_admin_database_v1/types.py | Python | apache-2.0 | 1,907 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "Licens | e");
# 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARR... | issions and
# limitations under the License.
from __future__ import absolute_import
import sys
from google.api import http_pb2
from google.iam.v1 import iam_policy_pb2
from google.iam.v1 import policy_pb2
from google.iam.v1.logging import audit_data_pb2
from google.longrunning import operations_pb2
from google.protob... |
WorldBank-Transport/DRIVER | app/black_spots/tasks/calculate_black_spots.py | Python | gpl-3.0 | 4,985 | 0.004814 | import datetime
import os
import shutil
import tarfile
import tempfile
from django.conf import settings
from django.utils import timezone
from celery import shared_task
from celery.utils.log import get_task_logger
from grout.models import RecordType
from black_spots.tasks import (
forecast_segment_incidents,
... | tput = get_training_noprecip(
segments_shp_uuid,
records_csv_obj_id,
roads_srid
)
# - Run Rscript to output CSV
segments_csv = BlackSpotTrainingCsv.objects.get(pk=blackspots_output).csv.path
return forecast_segment_incidents(segments_csv, '/var/www/media/forecasts.csv')
@share... | k
def calculate_black_spots(history_length=datetime.timedelta(days=5 * 365 + 1), roads_srid=3395):
"""Integrates all black spot tasks into a pipeline
Args:
history_length (timedelta): Length of time to use for querying for historic records.
Note: the R script will fai... |
sivertkh/gtrackcore | gtrackcore/test/track_operations/FlankTest.py | Python | gpl-3.0 | 3,882 | 0.000258 | import unittest
import numpy as np
from collections import OrderedDict
from gtrackcore.metadata import GenomeInfo
from gtrackcore.track.core.GenomeRegion import GenomeRegion
from gtrackcore.track.format.TrackFormat import TrackFormat
from gtrackcore.track_operations.operations.Flank import Flank
from gtrackcore.track... | f._createTrackContent(starts, ends)
f = Flank(track)
# Result track type is Segments as d | efault
f.setFlankSize(nrBP)
f.setAfter(after)
f.setBefore(before)
tc = f()
for (k, v) in tc.getTrackViews().items():
print expStarts
print v.startsAsNumpyArray()
print expEnds
print v.endsAsNumpyArray()
if cmp(k, se... |
Dr762/PythonExamples3.4 | Python3/restraunt_finder.py | Python | gpl-2.0 | 6,651 | 0.001504 | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__ = "alex"
__date__ = "$Jun 1, 2015 10:46:55 PM$"
from math import radians, sin, cos, sqrt, asin
from bs4 import BeautifulSoup
from ty... | point1
lat_2, lon_2 = point2
delta_lat = radians(lat_2 - lat_1)
delta_lon = radians(lon_2 - lon_1)
lat_1 = radians(lat_1)
lat_2 = radians(lat_2)
a = sin(delta_lat / 2) ** 2 + cos(lat_1) * cos(lat_2) * sin(delta_lon / 2) ** 2
c = 2 * asin(sqrt(a))
return R * c
def get_food_list_by_na... | h = "/Clients/VDH/Norfolk/Norolk_Website.nsf/Food-List-ByName"
form = {
"OpenView": "",
"RestrictToCategory": "faa4e68b1bbbb48f008d02bf09dd656f",
"count": "400",
"start": "1",
}
query = urllib.parse.urlencode(form)
with urllib.request.urlopen(scheme_host + path + "?" + q... |
Comunitea/CMNT_00040_2016_ELN_addons | eln_reports/report/invoice/invoice_report_parser.py | Python | agpl-3.0 | 2,501 | 0.0012 | # -*- coding: utf-8 -*-
# Copyright 2021 El Nogal - Pedro Gómez <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import registry
from openerp.addons import jasper_reports
def parser(cr, uid, ids, data, context):
parameters = {}
name = 'report.invoice_report_j... | e = 'model'
uom_obj = registry(cr.dbname).get('product.uom')
invoice_obj = registry(cr.dbname).get('account.invoice')
invoice_ids = invoice_obj.browse(cr, uid, ids, context)
language = list(set(invoice_ids.mapped('partner_id.lang')))
if len(language) == 1:
context['lang'] = language[0]
i... | e_id.id)] = []
for line in invoice_id.invoice_line:
product_id = line.product_id.with_context(lang=language)
uom_id = product_id.uom_id
uos_id = line.uos_id.with_context(lang=language)
uos_qty = line.quantity
uom_qty = uom_obj._compute_qty(cr, uid, uos... |
HelloLily/hellolily | lily/cases/migrations/0019_auto_20170418_1243.py | Python | agpl-3.0 | 425 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies | = [
('cases', '0018_auto_20170418_1220'),
]
operations = [
migration | s.AlterField(
model_name='case',
name='type',
field=models.ForeignKey(related_name='cases', to='cases.CaseType'),
),
]
|
PaulGregor/crowdin-cli | crowdin/methods.py | Python | mit | 19,747 | 0.003393 | # -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
try:
from crowdin.connection import Connection, Configuration
except ImportError:
from connection import Connection, Configuration
import six
import logging
import json
import zipfile
import shutil
import io
import os
l... | ormat(sources): f}
return self.true_connection(url, params, api_files, additional_parameters)
except(OSError, IOError) as e:
print(e, "\n Skipped")
def update_files(self, files, export_patterns, parameters, item):
# POST https://api.crowdin.com/api/project/{project-ident... | roject-key}
url = {'post': 'POST', 'url_par1': '/api/project/', 'url_par2': True,
'url_par3': '/update-file', 'url_par4': True}
if item[0] == '/':
sources = item[1:]
else:
sources = item
params = {'json': 'json', 'export_patterns[{0}]'.format(sou... |
bourneagain/pythonBytes | cloneGraph_BFS.py | Python | mit | 1,080 | 0.012037 | class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
#using DFS
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node): |
seen={}
visited=[]
seen[None] = None |
head = UndirectedGraphNode(node.label)
seen[node] = head
visited.append(node)
while len(visited) != 0:
refNode = visited.pop()
for n in refNode.neighbors:
if n not in seen:
neighBorNode = UndirectedGraphNode(n.label)
... |
tsileo/blobstash-python-docstore | blobstash/docstore/query.py | Python | mit | 4,218 | 0.000711 | """Query utils."""
class LuaScript:
def __init__(self, script):
self.script = script
class LuaStoredQuery:
def __init__(self, name, query_args):
self.name = name
self.args = query_args
class LogicalOperator:
def __init__(self, *args):
self.clauses = args
def __str_... | "get_path(doc, '{}') == {}".format(self.path(), _lua_repr(value))
for value in values
]
)
)
def not_any(self, values):
| return LuaShortQueryComplex(
" or ".join(
[
"get_path(doc, '{}') ~= {}".format(self.path(), _lua_repr(value))
for value in values
]
)
)
def contains(self, q):
if isinstance(q, LuaShortQuery):
... |
bfontaine/wptranslate | tests/test_mediawiki.py | Python | mit | 1,013 | 0.002962 | # -*- coding: UTF-8 -*-
import responses
from helpers import TestCase
from wptranslate.mediawiki import query
class TestMediaWiki(TestCase):
def setUp(self):
self.lang = 'foo'
self.url = 'https://%s.wikipedia.org/w/api.php' % self.lang
@responses.activate
def test_query_return_none_on_... | one(query({}, lang=self.lang))
self.assertEquals(1, len(responses.calls))
@responses.activate
def test_query_return_query_param(self):
responses.add(responses.GET, self.url, body='{"query": 42}', status=200)
self.assertEquals(42, query({}, lang=self.lang))
self.assertEquals(1, l... | |
nmgeek/npTDMS | nptdms/tdmsinfo.py | Python | lgpl-3.0 | 1,875 | 0 | from __future__ import print_function
from argparse import ArgumentParser
import logging
from nptdms import tdms
def main():
parser = ArgumentParser(
description="List the contents of a LabView TDMS file.")
parser.add_argument(
'-p', '--properties', action="store_true",
help="Include... | '-d', '--debug', action="store_true",
help="Print debugging information to stderr.")
parser.add_argument(
'tdms_file',
hel | p="TDMS file to read.")
args = parser.parse_args()
if args.debug:
logging.getLogger(tdms.__name__).setLevel(logging.DEBUG)
tdmsfile = tdms.TdmsFile(args.tdms_file)
level = 0
root = tdmsfile.object()
display('/', level)
if args.properties:
display_properties(root, level)
... |
dennissergeev/pyveccalc | pyveccalc/__init__.py | Python | mit | 314 | 0 | # -*- coding: utf-8 -*-
"""
Wind vector calculations in finite differences
"""
from . import | iris_api
from . import standard
from . import tools
from . import utils
# List to define the behaviour of imports of the form:
# from pyveccalc import *
__all__ = []
# Package version number.
__version_ | _ = '0.2.9'
|
xpharry/Udacity-DLFoudation | tutorials/reinforcement/gym/gym/tests/test_core.py | Python | mit | 353 | 0.005666 | from gym import core
class ArgumentEnv(core.Env): |
calls = 0
def __init__(self, arg):
self.calls += 1
self.arg = arg
def test_env_instantiatio | n():
# This looks like a pretty trivial, but given our usage of
# __new__, it's worth having.
env = ArgumentEnv('arg')
assert env.arg == 'arg'
assert env.calls == 1
|
vjFaLk/frappe | frappe/patches/v9_1/add_sms_sender_name_as_parameters.py | Python | mit | 651 | 0.021505 | # Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("core", "doctype", "sms_parameter")
sms_sender_name = frappe.db.get_single_value("SMS Settings", "sms_sender_name")
if sms_s... | "SMS Settings")
sms_settings.append("parameters", {
"parameter": "sender_name",
"value": sms_sender_name
})
sms_settings.flags.ignore_mandatory = True
sms_settings.flags.ignore_permissions = True
| sms_settings.save()
|
ultrabug/uhashring | uhashring/ring.py | Python | bsd-3-clause | 11,224 | 0.000178 | from bisect import bisect
from uhashring.ring_ketama import KetamaRing
from uhashring.ring_meta import MetaRing
class HashRing:
"""Implement a consistent hashing ring."""
def __init__(self, nodes=[], **kwargs):
"""Create a new HashRing given the implementation.
:param nodes: nodes used to c... | if vnodes is None:
vnodes = 160
self.runtime = MetaRing(hash_fn)
self._default_vnodes = vnodes
self.hashi = self.runtime.hashi
if weight_fn and not hasattr(weight_fn, "__call__"):
raise TypeError("weight_fn should be a callable function")
s... | des(self, nodes):
"""Parse and set up the given nodes.
:param nodes: nodes used to create the continuum (see doc for format).
"""
if isinstance(nodes, str):
nodes = [nodes]
elif not isinstance(nodes, (dict, list)):
raise ValueError(
"nodes... |
gammu/wammu | Wammu/App.py | Python | gpl-3.0 | 2,021 | 0.000993 | # -*- coding: UTF-8 -*-
#
# Copyright © 2003 - 2018 Michal Čihař <[email protected]>
#
# This file is part of Wammu <https://wammu.eu/>
#
# 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 ve... | (wx.LANGUAGE_DEFAULT)
self.SetAppName('Wammu')
vendor = StrConv('Michal Čihař')
if vendor.find('?') != -1:
vendor = 'Michal Čihař'
self.SetVendorName(vendor)
frame = Wammu.Main.WammuFrame(None, -1)
Wammu.Error.HANDLER_PARENT = frame
frame.Show(True)
... | f.SetTopWindow(frame)
# Return a success flag
return True
def Run():
'''
Wrapper to execute Wammu. Installs graphical error handler and launches
WammuApp.
'''
try:
sys.excepthook = Wammu.Error.Handler
except:
print(_('Failed to set exception handler.'))
app ... |
jordan9001/CABS | Source/Broker/CABS_server.py | Python | apache-2.0 | 32,754 | 0.009007 | #!/usr/bin/python
## CABS_Server.py
# This is the webserver that is at the center of the CABS system.
# It is asynchronous, and as such the callbacks and function flow can be a bit confusing
# The basic idea is that the HandleAgentFactory and HandleClienFactory make new HandleAgents and Handle Clients
# There is one p... | tor, endpoints, defer, task
from twisted.protocols.basic import LineOnlyReceiver
from twisted.protocols.policies import TimeoutMixin
from twisted.enterprise import adbapi
from twisted.names import client
from twisted.pyt | hon import log
import ldap
import sys
import logging
import random
import os
from time import sleep
#global settings dictionary
settings = {}
#global database pool
dbpool = adbapi.ConnectionPool
#global blacklist set
blacklist = set()
#make a logger
logger=logging.getLogger()
random.seed()
## Handles each Agent c... |
jhavstad/model_runner | src/ScrollListViewTest.py | Python | gpl-2.0 | 469 | 0.006397 | import PyQtExtras
from PyQt5.QtWidgets import QFrame, QAppli | cation
import sys
def main(args):
app = QApplication([])
main_frame = QFrame()
list_view = PyQtExtras.ListScrollArea(main_frame)
list_view.add_item_by_string('Item 1')
list_view.add_item_by_string('Item 2')
list_view.add_item_by_string('Item 3')
list_view.remove_item_by_string('Item 1'... | sys.argv) |
jigarkb/CTCI | LeetCode/015-M-3Sum.py | Python | mit | 1,646 | 0.00486 | # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets
# in the array which gives the sum of zero.
#
# Note: The solution set must not contain duplicate triplets.
#
# For example, given array S = [-1, 0, 1, 2, -1, -4],
#
# A solution set is:
# [
# [-1, 0, 1... | > 0:
| r -= 1
else:
res.append((nums[i], nums[l], nums[r]))
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
... |
Azure/azure-sdk-for-python | sdk/formrecognizer/azure-ai-formrecognizer/tests/test_dac_analyze_general_document_async.py | Python | mit | 8,184 | 0.004399 | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import pytest
import functools
from devtools_testutils.aio import recorded_by_proxy_async
from azure.ai.formrecognizer._generated.models import AnalyzeRe... | ef test_document_specify_pages(self, client):
with open(self.multipage_invoice_pdf, "rb") as fd:
document = fd.read()
async with client:
poller = await client.begin_analyze_document("prebuilt-document", document, pages="1")
result = await poller.result()
... | sult()
assert len(result.pages) == 2
poller = await client.begin_analyze_document("prebuilt-document", document, pages="1-2")
result = await poller.result()
assert len(result.pages) == 2
poller = await client.begin_analyze_document("prebuilt-document", docum... |
apahomov/django-sphinx | djangosphinx/apis/api281/__init__.py | Python | bsd-3-clause | 30,427 | 0.052059 | #
# $Id: sphinxapi.py 2970 2011-09-23 16:50:22Z klirichek $
#
# Python version of Sphinx searchd client (Python API)
#
# Copyright (c) 2006, Mike Osadnik
# Copyright (c) 2006-2011, Andrew Aksyonoff
# Copyright (c) 2008-2011, Sphinx Technologies Inc
# All rights reserved
#
# This program is free software; you can redist... | ATTR_BIGINT,
SPH_ATTR_STRING,
SPH_ATTR_MULTI,
SPH_ATTR_MULTI64)
# known grouping functions
SPH_GROUPBY_DAY = 0
SPH_GROUPBY_WEEK = 1
SPH_GROUPBY_MONTH = 2
SPH_GROUPBY_YEAR = 3
SPH_GROUPBY_ATTR = 4
SPH_GROUPBY_ATTRPAIR = 5
class SphinxClient:
def __init__ (self):
"""
Create a new client o... | 2 # searchd port (default is 9312)
self._path = None # searchd unix-domain socket path
self._socket = None
self._offset = 0 # how much records to seek from result-set start (default is 0)
self._limit = 20 # how much records to return from result-set starting at offset (default is ... |
j-windsor/cs3240-f15-team21-v2 | accounts/urls.py | Python | mit | 876 | 0.004566 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^groups | /$', views.groups, name='groups'),
url(r'^sitemanager/$', views.sitemanager, name='sitemanager'),
url(r'^(?P<user_id>[0-9]+)/user_view/$', views.user_view, name='user_view'),
url(r'^(?P<user_id>[0-9]+)/deactivate/$', views.deactivate, name='deactivate'),
url(r'^(?P<user_id>[0-9]+)/activate/$', views.act... | anager, name='makeSiteManager'),
url(r'^(?P<user_id>[0-9]+)/unmakeSiteManager/$', views.unmakeSiteManager, name='unmakeSiteManager'),
url(r'^groups/sitemanager/$', views.groupsSM, name='groupsSM'),
]
|
hephaestus9/Ironworks | modules/plugins/nzbget.py | Python | mit | 3,148 | 0.002224 | from flask import render_template, jsonify, request
from jsonrpclib import jsonrpc
import b | ase64
import urllib
from maraschino import app, logger
from maraschino.tools import | *
def nzbget_http():
if get_setting_value('nzbget_https') == '1':
return 'https://'
else:
return 'http://'
def nzbget_auth():
return 'nzbget:%s@' % (get_setting_value('nzbget_password'))
def nzbget_url():
return '%s%s%s:%s' % (nzbget_http(), \
nzbget_auth(), \
get_... |
cmry/ebacs | corks.py | Python | bsd-3-clause | 2,583 | 0 | import bottle
from cork import Cork
from utils import skeleton
aaa = Cork('users', email_sender='[email protected]',
smtp_url='smtp://smtp.magnet.ie')
authorize = aaa.make_auth_decorator(fail_redirect='/login', role="user")
def postd():
return bottle.request.forms
def post_get(name, default=''):... | aaa.create_role(post_get('role'), post_get('level'))
return dict(ok | =True, msg='')
except Exception as e:
return dict(ok=False, msg=e.message)
@bottle.post('/delete_role')
def delete_role():
try:
aaa.delete_role(post_get('role'))
return dict(ok=True, msg='')
except Exception as e:
return dict(ok=False, msg=e.message)
# Static pages
@bott... |
mrcslws/nupic.research | src/nupic/research/frameworks/vernon/mixins/sync_batchnorm.py | Python | agpl-3.0 | 1,943 | 0.001544 | # --------------------------------------- | -------------------------------
# Numenta Platfo | rm for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
vimalkvn/riboseqr_wrapper | riboseqr/ribosome_profile.py | Python | gpl-2.0 | 4,816 | 0.000208 | #!/usr/bin/env python
import os
import sys
import glob
import argparse
import logging
import rpy2.robjects as robjects
import utils
rscript = ''
R = robjects.r
def run_rscript(command=None):
"""Run R command, log it, append to rscript"""
global rscript
if not command:
return
logging.debug(com... | _args = (
'"{transcript_name}", main="{transcript_name}",'
'coordinates=ffCs@CDS, riboData=riboDat,'
| 'length={transcript_length}'.format(**options))
if transcript_cap:
cmd_args += ', cap={transcript_cap}'.format(**options)
plot_file = os.path.join(output_path, 'Ribosome-profile-plot')
for fmat in ('pdf', 'png'):
if fmat == 'png':
cmd = 'png(file="{... |
henryroe/xenics_pluto | nihts_xcam/__init__.py | Python | mit | 77 | 0 | from __future__ imp | ort absolute_import
from .nihts_xcam im | port XenicsCamera
|
aGHz/structominer | tests/test_document.py | Python | mit | 1,199 | 0.003336 | from mock import patch, Mock
from nose.tools import istest
from unittest import TestCase
from structominer import Document, Field
class DocumentTests(TestCase):
@istest
def creating_document_object_with_string_should_automatically_parse(self):
html = '<html></html>'
with patch('structom... | ent_should_only_parse_fields_with_auto_parse_attributes(self):
html = '<html></html>'
class Doc(Document):
one = Mock(Field, _field_counter=1, auto_parse=True)
two = Mock(Field, _field_counter=2 | , auto_parse=False)
doc = Doc(html)
self.assertTrue(doc.one.parse.called)
self.assertFalse(doc.two.parse.called)
|
endlessm/chromium-browser | third_party/llvm/llvm/bindings/python/llvm/disassembler.py | Python | bsd-3-clause | 5,918 | 0.002028 | #===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#===---------------------------------... | t__(self, triple):
"""Create a new disassembler i | nstance.
The triple argument is the triple to create the disassembler for. This
is something like 'i386-apple-darwin9'.
"""
_ensure_initialized()
ptr = lib.LLVMCreateDisasm(c_char_p(triple), c_void_p(None), c_int(0),
callbacks['op_info'](0), callbacks['symbol_l... |
mganeva/mantid | scripts/Diffraction/isis_powder/routines/run_details.py | Python | gpl-3.0 | 5,875 | 0.005447 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, divi... | number = common.get_first_run_number(run_number_string=run_number_string)
cal_mapping_dict = yaml_parser.get_run_dictionary(run_number_string=run_number,
file_path=cal_mapping_path)
return cal_mapping_dict
class _RunDetails(obje | ct):
"""
This class holds the full file paths associated with each run and various other useful attributes
"""
def __init__(self, empty_run_number, file_extension, run_number, output_run_string, label,
offset_file_path, grouping_file_path, splined_vanadium_path, vanadium_run_number,
... |
broadinstitute/hellbender | src/main/python/org/broadinstitute/hellbender/gcnvkernel/io/io_vcf_parsing.py | Python | bsd-3-clause | 4,367 | 0.002977 | import logging
import vcf
from typing import List, Tuple
_logger = logging.getLogger(__name__)
# TODO: for now I'm going to do the lazy thing and just traverse the VCF each time for each sample
def read_sample_segments_and_calls(intervals_vcf: str,
clustered_vcf: str,
... | contig: str) -> List[Tuple[int, int, int]]:
"""
Get the segmentation "path" to use for calculating qualities based on the VCF with clustered breakpoints
:param intervals_vcf:
:param clustered_vcf:
:param sample_name:
:param contig:
:return: {copy number, start index, stop index (inclusiv... | als = vcf.Reader(filename=intervals_vcf)
intervals2 = vcf.Reader(filename=intervals_vcf)
segments = vcf.Reader(filename=clustered_vcf)
path: List[Tuple[int, int, int]] = []
segment_start_index = 0
segment_end_index = 0
# A record corresponds to [CHROM,POS,REF,ALT]
try:
interval_sta... |
monkeesuit/school | Network Security/ARP/arp suite/py/arp.py | Python | mit | 7,562 | 0.031605 | # ARP Suite - Run ARP Commands From Command Line
import sys
import arp_mitm as mitm
import arp_sslstrip as sslstrip
import arp_listen as listen
import arp_request as request
import arp_cache as cache
import arp_reconnaissance as recon
import arp_interactive as interactive
if __name__ == "__main__":
arguments = sys.ar... | re is an instance of arpclient in listen mode'
print '\tto handle ARP messages and manipulate ARP table ("arp.py -l").'
print ''
print '[USAGE] arp.py -r --ip [ip]\n'
print '[ARGUMENTS]'
print '\t"--ip" = IP Address You Wish To Resolve'
print ''
sys.exit(1)
if '--ip' in arguments:
option_inde... | .send(ip)
sys.exit(1)
if '-c' in arguments or '--cache' in arguments:
if '--h' in arguments:
print '[INFO]\tWork with the ARP Cache\n'
print '[USAGE] arp.py -c --d/l/a/r --i [ip] --m [mac]\n'
print '[ARGUMENTS]'
print '"--d" = Display ARP Cache.'
print '"--l" = Look Up ARP Cache. Must Specify Eithe... |
cdcq/jzyzj | syzoj/views/problem.py | Python | mit | 4,193 | 0.00477 | import sys
reload(sys)
sys.setdefaultencoding("utf8")
from urllib import urlencode
from flask import jsonify, redirect, url_for, abort, request, render_template
from syzoj import oj, controller
from syzoj.models import User, Problem, File, FileParser
from syzoj.controller import Paginate, Tools
from .common import n... | else:
return render_template("edit_problem.html", tool=Tools, problem=problem)
@oj.route("/problem/<int:problem_id>/upload", methods=["GET", "POST"])
d | ef upload_testdata(problem_id):
user = User.get_cur_user()
if not user:
return need_login()
problem = Problem.query.filter_by(id=problem_id).first()
if not problem:
abort(404)
if problem.is_allowed_edit(user) == False:
return not_have_permission()
if request.method == "P... |
tistaharahap/ds-for-me | extractor.py | Python | mit | 7,464 | 0.004555 | # -*- coding: utf-8 -*-
from text.classifiers import NaiveBayesClassifier
from textblob import TextBlob
import feedparser
import time
import redis
import hashlib
import json
TIMEOUT = 60*60
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
def feature_extractor(text):
if not isinstance(text, TextBlob):
text =... | stik dan Pengiriman Layanan E-Commerce', 'ko'),
('Transformasi Portal Informasi Kecantikan Female Daily Disambut Positif, Beberkan Rencana-Rencana 2014', 'ko'),
('Visa Gelar Promosi Diskon Setiap Jumat Bekerja Sama dengan Enam Layanan E-Commerce Lokal', 'ko'),
('Kerjasama Strategis, Blue Bird Group Benamkan... | Hadir Tawarkan Promo Flash Sale', 'ko'),
('Bidik Citizen Journalism, Detik Hadirkan Media Warga PasangMata', 'ko'),
('Asia Pasifik Jadi Kawasan E-Commerce B2C Terbesar di Dunia Tahun 2014', 'ko'),
('CTO Urbanesia Batista Harahap Mengundurkan Diri', 'ok'),
('Tees Indonesia Alami Peningkatan Traffic Hingg... |
FeodorM/Computer-Graphics | util/matrix.py | Python | mit | 2,886 | 0.000704 | from typing import Sequence
from numbers import Number
from tabulate import tabulate
class Matrix(Sequence):
def __init__(self, matrix: Sequence[Sequence[float]]):
assert (isinstance(matrix, Sequence) and
isinstance(matrix, Sequence)), "Wrong data"
self.__matrix = [[float(x) for x ... | p(self, other)
])
@property
def shape(self):
return len(self.__matrix), len(self.__mat | rix[0])
if __name__ == '__main__':
m = Matrix([[1, 2, 1], [2, 3, 0]])
a = Matrix([[1, 0, 0], [2, 1, 0], [1, 1, 0]])
# print(m, m.shape)
# print(a, a.shape)
print(m * a)
|
mailund/IMCoalHMM | src/IMCoalHMM/CTMC.py | Python | gpl-2.0 | 2,581 | 0.001937 | """Code for constructing CTMCs and computing transition probabilities
in them."""
from numpy import zeros
from scipy import matrix
from scipy.linalg import expm
class CTMC(object):
"""Class representing the CTMC for the back-in-time coalescent."""
def __init__(self, state_space, rates_table):
"""Cre... | transition rates can be looked up.
:type rates_table: dict
"""
cache_key = (state_space, tuple(rates_table.items()))
if not cache_key in CTMC_CACHE:
CTMC_CACHE[cache_key] = CTMC(state_space, rates_table)
return CTMC_CACHE[cache_ | key]
|
rahulunair/nova | nova/tests/unit/api/openstack/compute/test_keypairs.py | Python | apache-2.0 | 27,057 | 0 | # Copyright 2011 Eldar Nugaev
# 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 ... | ir': {'name': ' test '}}
self.req.set_legacy_v2()
res_dict = self.controller.create(self.req, body=body)
self.assertEqual('test', res_dict['keypair']['name'])
def test_keypair_create_with_non_alphanumeric_name(self):
body = {
'keypair': {
' | name': 'test/keypair'
}
}
self._test_keypair_create_bad_request_case(body,
webob.exc.HTTPBadRequest)
def test_keypair_import_bad_key(self):
body = {
'keypair': {
'name': 'create_test',
... |
teracyhq/flask-boilerplate | app/api_1_0/args.py | Python | bsd-3-clause | 308 | 0 | from webargs import fields
from ..api.validators import Email, passwo | rd
user_args = {
'email': fields.Str(validat | e=Email, required=True),
'password': fields.Str(validate=password, required=True)
}
role_args = {
'name': fields.Str(required=True),
'description': fields.Str(required=True)
}
|
alon/polinax | libs/external_libs/gdata.py-1.0.13/src/gdata/contacts/service.py | Python | gpl-2.0 | 5,972 | 0.009377 | #!/usr/bin/python
#
# Copyright (C) 2008 Google 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 ... | ts/default/base', url_params=None,
escape_params=True):
"""Adds an event to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new event which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) ... | ters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server, ... |
goyal-sidd/BLT | website/migrations/0038_issue_upvotes.py | Python | agpl-3.0 | 447 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-08-17 01:43
from __future__ import unicode_literals
from django.db i | mport migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0037_auto_20170813_0319'),
]
operations = [
migrations.AddField(
model_name='issue',
name='upvotes',
field=models.IntegerField(default=0) | ,
),
]
|
GoogleCloudPlatform/covid-19-open-data | src/england_data/standardize_data.py | Python | apache-2.0 | 21,282 | 0.010384 | # pylint: disable=g-bad-file-header
# Copyright 2020 DeepMind Technologies Limited. 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/... | -> pd.DataFrame:
"""Loads and formats daily deaths data."""
sheet_name = "Tab4 Deaths by trust"
header = 15
df = pd.read_excel(filepath, sheet_name=sheet_name, header=header)
# Drop rows and columns which are all nans.
df.dropna(axis=0, how="all", inplace=True)
df.dropna(axis=1, how="all", inplace=True)
... | "
if sum(i for i in df[up_to_mar_1_index] if isinstance(i, int)) == 0.0:
drop_columns.append(up_to_mar_1_index)
df.drop(columns=drop_columns, inplace=True)
df = df[df["Code"] != "-"]
# Melt the death counts by date into "Date" and "Death Count" columns.
df = df.melt(
id_vars=["NHS England Region", "... |
stephen144/odoo | addons/website_portal_sale/controllers/main.py | Python | agpl-3.0 | 1,940 | 0.001546 | # -*- coding: utf-8 -*-
import datetime
from openerp import http
from openerp.http import request
from openerp.addons.website_portal.controllers.main import website_account
class website_account(website_account):
@http.route(['/my/home'], type='http', auth="user", website=True)
def account(self, **kw):
... | st.env['sale.order']
res_invoices = request.env['account.invoice']
quotations = res_sale_order.search([
('state', 'in', ['sent', 'cancel'])
])
orders = res_sale_order.search([
('state', 'in', ['sale', 'done'])
])
invoices = res_invoices.search([
| ('state', 'in', ['open', 'paid', 'cancelled'])
])
response.qcontext.update({
'date': datetime.date.today().strftime('%Y-%m-%d'),
'quotations': quotations,
'orders': orders,
'invoices': invoices,
})
return response
@http.rou... |
js0701/chromium-crosswalk | tools/perf/page_sets/key_search_mobile.py | Python | bsd-3-clause | 2,523 | 0.003567 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
from telemetry import story
class KeySearchMobilePage(page_modul... | # Why: A search for a known actor
'http://www.google.com/search?q=tom+hanks',
# Why: A search for weather
'https://www.google.com/search?q=weather+94110',
# Why: A search for a stock
'http://www.google.com/search?q=goog',
# Why: Charts
'https://www.google.com/search?q=populat... | fo+jfk+flights',
# Why: Movie showtimes
'https://www.google.com/search?q=movies+94110',
# Why: A tip calculator
'http://www.google.com/search?q=tip+on+100+bill',
# Why: Time
'https://www.google.com/search?q=time+in+san+francisco',
# Why: Definitions
'http://www.google.com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.