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 |
|---|---|---|---|---|---|---|---|---|
PersianWikipedia/pywikibot-core | scripts/isbn.py | Python | mit | 11,670 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This script reports and fixes invalid ISBN numbers.
Additionally, it can convert all ISBN-10 codes to the ISBN-13 format, and
correct the ISBN format by placing hyphens.
These command line parameters can be used to specify which pages to work on:
¶ms;
Furthermore, t... | claim.setTarget(new_isbn)
if self.isbn_13_prop_id in item.claims:
item.claims[self.isbn_13 | _prop_id].append(claim)
else:
item.claims[self.isbn_13_prop_id] = [claim]
change_messages.append('Changing {0} ({ |
qrealka/skia-hc | tools/buildbot_spec.py | Python | apache-2.0 | 13,404 | 0.012534 | #
# Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
#!/usr/bin/env python
usage = '''
Write buildbot spec to outfile based on the bot name:
$ python buildbot_spec.py outfile Test-Ubuntu-GCC-GCE-CPU-AVX2-x86-Debug
Or run self-tests:... | _neon',
'Nexus9': 'arm64',
'NexusPlayer': 'x86',
}[builder_dict['model']]
# ChromeOS.
if 'CrOS' in builder_dict.get('extra_config', ''):
if 'Link' in builder_dict['extra_config']:
return 'link'
if 'Daisy' in builder_dict['extra_config']:
return 'daisy'
| elif builder_dict.get('os') == 'ChromeOS':
return {
'Link': 'link',
'Daisy': 'daisy',
}[builder_dict['model']]
# iOS.
if 'iOS' in builder_dict.get('os', ''):
return {
'iPad4': 'iPad4,1',
}[builder_dict['model']]
return None
cov_skip.extend([lineno(), lineno() + 1])
def produ... |
cajone/pychess | lib/pychess/Utils/TimeModel.py | Python | gpl-3.0 | 8,916 | 0.001795 | from time import time
from gi.repository import GLib, GObject
from pychess.Utils.const import WHITE, BLACK
from pychess.System.Log import log
class TimeModel(GObject.GObject):
__gsignals__ = {
"player_changed": (GObject.SignalFlags.RUN_FIRST, None, ()),
"time_changed": (GObject.SignalFlags.RUN_... | is not None) and \
not self.zero_listener_source.is_destroyed():
GLib.source_remove(self.zero_listener_id)
self.zero_listener_time = remaining_time
self.zero_listener_id = GLib.timeout_add(10, self.__checkzero,
| color)
default_context = GLib.main_context_get_thread_default(
) or GLib.main_context_default()
if hasattr(default_context, "find_source_by_id"):
self.zero_listener_source = default_context.find_source_by_id(
self.zero_listener_id)
de... |
danirus/django-inviteme | demo/urls.py | Python | bsd-2-clause | 299 | 0.003344 | from django.conf.urls.defaults | import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('views',
url(r'^admin/', include(admin.site.urls)),
url(r'^invite/ | ', include('inviteme.urls')),
url(r'^$', 'homepage_v', name='homepage'),
)
|
Maaphoo/Retr3d | xEndZRodHolder.py | Python | gpl-3.0 | 53,275 | 0.053102 | # Copyright 2015 Matthew Rogge
#
# This file is part of Retr3d.
#
# Retr3d 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.
#
# Retr3... |
xShift = +gv.xRodLength/2+gv.xRodCl | ampWidth-gv.xRodClampPocketDepth
else:
xShift = -gv.xRodLength/2-gv.xRodClampWidth+gv.xRodClampPocketDepth
yShift = (gv.extruderNozzleStandoff
- gv.zRodStandoff
- gv.xEndZRodHolderFaceThickness
- gv.xEndZRodHolderMaxNutFaceToFace/2)
zShift = 0
App.ActiveDocument=App.getDocument("PrinterAssem... |
ArchangelX360/EnvironmentalEventsDetector | computation/imagefetcher/examples/ndvi_difference.py | Python | mit | 2,028 | 0 | #!/usr/bin/env python2
"""Example of server-side computations used in global forest change analysis.
In this example we will focus on server side computation using N | DVI and EVI
data. This both metrics are computed bands created by third party companies
or directly taken by the satellites.
NDVI and EVI are two metrics used in global forest change analysis. They
represent the forest concentration in a specific area. We will us | e the
MOD13A1 vegetation indice provided by the NASA [1].
The goal is to generate an RGB image, where reds stands for deforestation,
gree for reforestation and blue for masked data (e.g. rivers, oceans...).
[1] https://code.earthengine.google.com/dataset/MODIS/MOD13A1
"""
import ee
# Initialize the Earth Engine
e... |
gustavomazevedo/tbackup-client | client/models/Backup.py | Python | mit | 5,953 | 0.014115 | # -*- coding: utf-8 -*-
from hashlib import sha1 as SHA
from django.db import models
from datetime import datetime
from django.utils import timezone
from django.core.urlresolvers import reverse
from client.conf.settings import TBACKUP_DATETIME_FORMAT, settings
from django.utils.html import format_html
fro... | ted(self):
return self.file is | not None
@property
def remote_completed(self):
return self.remote_backup_date is not None
@property
def restore(self):
return 'Restaurar'
#meta config
class Meta:
#app_label required when scathering models in multiple files
app_label = 'client'
... |
ngpestelos/ansible | lib/ansible/plugins/connection/ssh.py | Python | gpl-3.0 | 28,684 | 0.002789 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe... | ept ImportError:
from ansible.utils.display import Display
display = Display()
SSHPASS_AVAILABLE = None
class Connection(ConnectionBase):
''' ssh based connections '''
transport = 'ssh'
has_pipelining = True
become_methods = frozenset(C.BECOME_METHODS).difference(['runas'])
def __init__... | gs, **kwargs)
self.host = self._play_context.remote_addr
# The connection is created by running ssh/scp/sftp from the exec_command,
# put_file, and fetch_file methods, so we don't need to do any connection
# management here.
def _connect(self):
return self
@staticmethod
def _... |
calebmadrigal/trackerjacker | setup.py | Python | mit | 1,865 | 0.016086 | # pylint: disable=C0103, C0111, C0326, W0122
from setuptools import setup
with open('requirements.txt', 'r') as f:
requirements = f.read().splitlines()
def get_version():
version = {}
with open("trackerjacker/version.py") as fp:
exec(fp.read(), version)
return version['__version__']
def ge... | = ['trackerjacker', 'trackerjacker/plugins'],
url = 'https://github.com/calebmadrigal/trackerjacker',
version = get_version(),
description = 'Finds and tracks wifi devices through raw 802.11 monitoring',
lon | g_description = get_readme(),
author = 'Caleb Madrigal',
author_email = 'caleb.madrigal@gmail.com',
license = 'MIT',
keywords = ['hacking', 'network', 'wireless', 'packets', 'scapy'],
install_requires = requirements,
tests_require = requirements,
test_suite='tests',
entry_points={'consol... |
ccervigon/codigo_pfc | otros_scripts/author_clasif.py | Python | gpl-2.0 | 2,056 | 0.008755 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
from datetime import *
#Creador de una matriz vacia
def Matriz_vacia(filas, columnas):
A = []
for i in range(0,filas):
A.append([0]*columnas)
return A
#Muestra la informacion del reparto de la actividad temporal del autor elegido
def acti... | []
for author in authors:
#OH=Office Hour, AO=After Office, LN=Late Night
activity = [0, 0, 0] # [OH, AO, LN]
for commit in author:
if commit[1].hour >= 9 and commit[1].hour < 17: #OH
activity[0] += 1
elif co | mmit[1].hour >= 1 and commit[1].hour < 9: #LN
activity[2] += 1
else: #AO
activity[1] += 1
list_commits_author.append(activity)
author = 42
activity_info(list_commits_author, authors, author)
cursor.close()
con.close()
|
byt3bl33d3r/CrackMapExec | cme/modules/runasppl.py | Python | bsd-2-clause | 542 | 0.012915 | class CMEModule:
name = 'runasppl'
description = "Check if th | e registry value RunAsPPL is set or not"
supported_protocols = ['smb']
opsec_safe = True
multiple_hosts = True
def options(self, context, module_options):
'''
'''
def on_admin_login(self, context, connection):
command = 'reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSe... | e(command, True)
context.log.highlight(p) |
sstebbins/pppcpro | pppcemr/migrations/0009_room.py | Python | agpl-3.0 | 595 | 0.001681 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from djang | o.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pppcemr', '0008_auto_20150901_1317'),
]
operations = [
migrations.CreateModel(
name='Room',
fields=[
('id', models.AutoField(serialize=False, auto_created=True... | eignKey(to='pppcemr.Office')),
],
),
]
|
dana-i2cat/felix | vt_manager/src/python/vt_manager/tests/deleteVM.py | Python | apache-2.0 | 538 | 0.009294 | import os
import sys
#PYTHON_DIR = join(dirname(__file__), '/opt/ofelia/vt_manager/src/python/')
PYT | HON_DIR = os.path.join(os.path.dirname(__file__), "../..")
# This is needed because wsgi disallows using stdout
sys.stdout = sys.stderr
os.environ['DJANGO_SETTINGS_MODULE'] = 'vt_manager.settings.settingsLoader'
sys.path.insert(0,PYTHON_DIR)
from vt_manager.models.VirtualMachine import VirtualMachine
vmid = str(sy... | Server.get()
server.deleteVM(vm)
|
dhuang/incubator-airflow | tests/operators/test_subdag_operator.py | Python | apache-2.0 | 12,984 | 0.002157 | #
# 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... | subdag_task._get_dagrun = Mock()
subdag_task._get_dagrun.side_effect = [None, self.dag_run_failed, self.dag_run_failed]
with pytest.raises(AirflowException):
subdag_task.pre_execute(context={'execution_date': DEFAULT_DATE})
| |
fp7-netide/Engine | loader/loader/util.py | Python | epl-1.0 | 10,483 | 0.007154 | import fcntl
import logging
import os
import shutil
import tempfile
import tarfile
import yaml
import pybars
import json
import io
import random
import re
import subprocess as sp
from subprocess import check_output, PIPE
from functools import reduce
from pybars import Compiler
dataroot = "/tmp/netide"
extractPath = ... | tr(c[2])])
if len(c) >= 4:
ssh.extend(["-i", str(c[3])])
ssh.extend(["-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile={}".format(tempfile.mktemp())]) # XXX
ssh.append(c[ | 1])
return ssh
def spawn_logged(cmd):
print(cmd)
p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.STDOUT)
for l in p.stdout:
l = l.decode('utf-8').rstrip()
logging.debug(l)
return p.wait()
def write_ansible_hosts(clients, path):
# Tuple layout:
# (name, ssh host, ssh port, ss... |
marklee77/vpack | vectorpack/openopt/__init__.py | Python | gpl-3.0 | 34 | 0 | from .solvers import pack_ | vectors
| |
bt3gl/Python-and-Algorithms-and-Data-Structures | First_edition_2014/other_resources/Project-Euler/019-counting_sundays.py | Python | mit | 1,794 | 0.022854 | #!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
'''
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisi... | elif m == 4 or m == 6 or m == 9 or m == 11:
days_count += 30
else:
days_count += 31
if leap_year: first_day = (first_day +2)%days_week
else: first_day = (first_day +1)%days_week
return count_sundays
... | '__main__':
main()
|
paultag/python-fluidsynth | setup.py | Python | mit | 346 | 0 | from setuptools import setup
long_description = ""
setup(
name="fluidsynth",
version="0.1",
packages=[
'flui | dsynth',
],
author="Paul Tagliamonte",
author_email="tag@pault.ag",
long_description=long_description,
description='n/a',
license="Expat",
url="http://pault. | ag/",
platforms=['any']
)
|
shivansh-pro/Sights | customTrainer.py | Python | mit | 7,757 | 0.008122 | from clarifai_basic import ClarifaiCustomModel
import os
import urllib2, socket
# instantiate clarifai client
clarifai = ClarifaiCustomModel()
p=os.getcwd()
p=p.replace('\\','/')
#XXXXXXXXXXXXXXXXXXX CAR XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
POSITIVES = []
pos=p+"/images/cars.txt"
with open(pos) as f:
POSITIVES = [x.stri... | (neg) as f:
NEGATIVES.extend([x.strip('\n') for x in f.readlines()])
for i in POSITIVES:
try:
urllib2.urlopen(i)
except urllib2.HTTPError, e:
POSITIVES.remove(i)
except urll | ib2.URLError, e:
POSITIVES.remove(i)
for i in NEGATIVES:
try:
urllib2.urlopen(i)
except urllib2.HTTPError, e:
NEGATIVES.remove(i)
except urllib2.URLError, e:
NEGATIVES.remove(i)
concept_name = 'people'
for positive_example in POSITIVES:
clarifai.positive(positive_e... |
RedhawkSDR/integration-gnuhawk | components/add_const_ss/tests/test_add_const_ss.py | Python | gpl-3.0 | 4,531 | 0.006621 | #!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by ... | tend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
props = self.comp.query([])
props = dict((x.id, any.from_any(x.value)) for x in props)
# Query may return more than expected, but not less
for expectedProp in expectedProps:
self.assertEquals(p... | available
for port in self.scd.get_componentfeatures().get_ports().get_uses():
port_obj = self.comp.getPort(str(port.get_usesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a("IDL:CF/Port... |
kamodev/8x8x8_RPi_Zero_LED_Cube | rpi_zero_ledcube/cube.py | Python | mit | 343 | 0 | class cube():
| CUBE_STATUS = "Off"
PATTERN = "Hello"
def __init__(self):
pass
@staticmethod
def status():
"""
Return dictionary of details about the cube
:return: Dictionary
"""
return {
'pattern': cube.PATTERN,
'status': cube.CUBE_STAT | US
}
|
pschmitt/hass-config | scripts/arlo-mode.py | Python | gpl-3.0 | 1,367 | 0 | #!/usr/bin/env python
# coding: utf-8
import argparse
import sys
import yaml
from pyarlo import PyArlo
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--username', '-u')
parser.add_argument('--password', '-p')
parser.add_argument('--config', '-c',
ty... | CONFIG = yaml.load(ARGS.config)
| USERNAME = CONFIG.get('arlo_username')
PASSWORD = CONFIG.get('arlo_password')
if not PASSWORD:
print("Credentials are required, set them either via -u "
"and -p or a secrets file (-c)", file=sys.stderr)
sys.exit(2)
else:
arlo_mode(USERNAME, PASSWORD, ARGS.MODE)... |
yeti/signals | signals/generators/base/base_parameters.py | Python | mit | 332 | 0.003012 | """
| Creates list of Objective-C or Swift specific method parameter names and types.
"""
class Parameter(object):
def __init__(self, name):
self.name = name
@staticmethod
def has_id_field(request_object):
return request_object and reduce(lambda x, y: x or y.name == 'id', request_object.field | s, False)
|
michalliu/chromium-depot_tools | gn.py | Python | bsd-3-clause | 1,319 | 0.004549 | #!/usr/bin/env python
# Copyright 2013 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.
"""This script is a wrapper around the GN binary that is pulled from Google
Cloud Storage when you sync Chrome. The binaries go into pl... | arding to the correct platform's
binary. It will also automatically try to find the gn binary when run inside
the chrome source tree, so users can just type "gn" on the | command line
(normally depot_tools is on the path)."""
import gclient_utils
import os
import subprocess
import sys
def main(args):
bin_path = gclient_utils.GetBuildtoolsPlatformBinaryPath()
if not bin_path:
print >> sys.stderr, ('gn.py: Could not find checkout in any parent of '
'th... |
bertothunder/coursera-algorithms | ShellSort.py | Python | gpl-3.0 | 1,843 | 0.005969 | #!/usr/bin/env python3
class ShellSort(object):
def __init__(self, elements, gaps):
self._elements = elements
self._gaps = gaps
def sort(self):
size = len(self._elements)
for gap in reversed(self._gaps):
if (gap > size):
continue
| for idx in range(gap,size):
#print("Idx: {}".format(idx))
idx2 = idx
while (idx2 >= gap and self._elements[idx2] < self._elements[idx2-gap]):
self._exchange(idx2, idx2-gap)
idx2 = idx2 - gap
def _exchange(self, idx1, idx2):... | .format(idx1,self._elements[idx1], idx2, self._elements[idx2]))
self._elements[idx2] = self._elements[idx1]
self._elements[idx1] = old
if __name__ == '__main__':
from sort_resources import hundred_random_unsorted, hundred_sorted, thousand_random_unsorted, thousand_sorted, ten_k_random_unsorted, te... |
AISpace2/AISpace2 | aispace2/jupyter/search/searchbuilder.py | Python | gpl-3.0 | 1,809 | 0.001106 | from ipywidgets import DOMWidget, register
from traitlets import Bool, Dict, Instance, Integer, Unicode, observe, Float
from aipython.searchProblem import Search_problem_from_explicit_graph
from ... import __version__
from .searchjsonbridge import (json_to_search_problem, search_problem_to_json,
... | ce(klass=Search_problem_from_explicit_graph, allow_none=True).tag(sync=True, from_json=json_to_search_problem, to_json=search_problem_to_json)
# True if the visualization should show edge costs.
show_edge_costs = Bool(True).tag(sync=True)
# True if a node's heuristic value should be shown.
show_node_he... | ync=True)
def __init__(self, search_problem=None):
super().__init__()
self.graph = search_problem
def py_code(self, need_positions=False):
"""Prints the search problem represented by Python code.
"""
print(search_problem_to_python_code(self.graph, need_positions))
|
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_3_0_0/models/compartmentdefinition_tests.py | Python | bsd-3-clause | 3,668 | 0.004362 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 on 2017-03-22.
# 2017, SMART Health IT.
import io
import json
import os
import unittest
from . import compartmentdefinition
from .fhirdate import FHIRDate
class CompartmentDefinitionTests(unittest.TestCase):
def instantiate_fro... | on[0].coding[0].display, "United States of America (the)")
self.assertEqual(inst.jurisdiction[0].coding[0].system, "urn:iso:std:iso:3166")
self.assertEqual(inst.name, "EXAMPLE")
| self.assertEqual(inst.publisher, "Health Level Seven International (FHIR Infrastructure)")
self.assertEqual(inst.purpose, "Provides an example of a FHIR compartment definition based on the Device resource type.")
self.assertEqual(inst.resource[0].code, "Communication")
self.assertEqual(inst.r... |
ray525/djangular | backend/oauth_test/books/permissions.py | Python | gpl-3.0 | 496 | 0.002016 | from rest_framework import permi | ssions
from pyuser.models import (USER_TYPE_ADMIN,
USER_TYPE_NORMAL,
USER_TYPE_VISITOR)
class IsAdminOrReadOnly(permissions.BasePermission):
def has_permission(self, request, view):
return request.user.pyuser.type == USER_TYPE_ADMIN
class IsPyUserOrR... | .user.pyuser.type != USER_TYPE_VISITOR
|
wanderine/nipype | nipype/interfaces/semtools/segmentation/specialized.py | Python | bsd-3-clause | 35,561 | 0.004696 | # -*- coding: utf8 -*-
"""Autogenerated file - DO NOT EDIT
If you spot a bug, please report it on the mailing list and/or change the generator."""
from nipype.interfaces.base import CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath
i... | a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is | some background constraints to match the edges of the head better.", argstr="--ROIAutoDilateSize %f")
outputVolumePixelType = traits.Enum("float", "short", "ushort", "int", "uint", "uchar", desc="The output image Pixel Type is the scalar datatype for representation of the Output Volume.", argstr="--outputVolumePix... |
tedunderwood/20cgenres | createtrainingset.py | Python | mit | 768 | 0.023438 | #!/usr/bin/env python3
# Create training sets. This short function does no | thing
# but combine confidentvolumes (created by inferfromreaders)
# and taggedvolumes (created by manualtagging).
import csv, os, sys, random
from collections import Counter
import numpy as np
import pandas as pd
# import utils
currentdir = os.path.dirname(__file__)
libpath = os.path.join(currentdir, '../lib')
sys.p... | v', dtype = 'object', index_col = 'docid', na_filter = False)
newlytagged = pd.read_csv('taggedvolumes.csv', dtype = 'object', index_col = 'docid', na_filter = False)
both = pd.concat([alreadyhave, newlytagged])
both.to_csv('maintrainingset.csv', index_label = 'docid')
|
RoboticsClubatUCF/RoboSub | ucf_sub_catkin_ros/src/sub_utils/src/linefinder.py | Python | mit | 1,400 | 0.048571 | impor | t cv2
import numpy as np
import time
image = cv2.imread('test.png')
image = cv2.flip(image,2)
rows, cols,_ = image.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),40,1)
image = cv2.warpAffine(image,M,(cols,rows))
mask=cv2.inRange(image, np.array([0, 180, 255],dtype='uint8'),np.array([0, 180, 255],dtype='uint8'))
_... | np.zeros(mask.shape,np.uint8)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(20,20))
done = False
while( not done):
eroded = cv2.erode(mask,element)
temp = cv2.dilate(eroded,element)
temp = cv2.subtract(mask,temp)
skel = cv2.bitwise_or(skel,temp)
img = eroded.copy()
done = True
zeros... |
frappe/frappe | frappe/website/doctype/web_template_field/web_template_field.py | Python | mit | 212 | 0.009434 | # -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# License: MIT. See LICENSE
# im | port frapp | e
from frappe.model.document import Document
class WebTemplateField(Document):
pass
|
bpeschier/django-preflight-checks | preflight/checks/email.py | Python | mit | 2,086 | 0.001438 | from django.core.checks import register, Error, Warning, Info
from django.core import mail
from django.conf import settings
E001 = Error(
'EMAIL_BACKEND i | s set to a testing/debug backend.',
id='preflight_email.E001'
)
E002 = Error(
"DEFAULT_FROM_EMAIL is set to an @localhost address.",
id='preflight_em | ail.E002'
)
W001 = Warning(
'Can not send email, check your email settings.',
id='preflight_email.W001'
)
I001 = Info(
"SERVER_EMAIL is still set to 'root@localhost'.",
id='preflight_email.I001'
)
# noinspection PyUnusedLocal
@register('preflight', deploy=True)
def check_email(app_configs, **kwargs)... |
the-zebulan/CodeWars | katas/incomplete/deja_vu_duplicates.py | Python | mit | 948 | 0 | class Employee:
def __init__(self, f_name, l_name, u_name):
self.first_name = f_name
self.last_name = l_name
self.user_name = u_name
def find_duplicates(employees):
duplicates = []
seen = set()
for i, employee in enumerate(employees):
current = tuple(sorted(employee.__d... | items())) # sort?
print current
if current in seen:
duplicates.append(employee)
employees.pop(i | )
# employees.remove(employee)
else:
seen.add(current)
return duplicates
guys = [["Johnathan", "Joestar", "JoJo"], ["Dio", "Brando", "DIO"],
["Joseph", "Joestar", "JoJo"], ["Kars", "", "the ultimate being"]]
employees = []
length = len(guys)
for guy in xrange(5):
g = gu... |
djrobstep/sqlakeyset | sqlakeyset/__init__.py | Python | unlicense | 569 | 0 | from .paging import get_page, select_page, InvalidPage
from .res | ults import (
Page,
Paging,
custom_bookmark_type,
serialize_bookmark,
unserialize_bookmark,
)
from .serial import (
BadBookmark,
ConfigurationError,
PageSerializationError,
UnregisteredType,
)
__all__ = [
"get_page",
"select_page",
"serialize_bookmark",
"unserialize_... | SerializationError",
"UnregisteredType",
]
|
joopert/home-assistant | tests/components/zwave/test_node_entity.py | Python | apache-2.0 | 18,310 | 0.000382 | """Test Z-Wave node entity. | """
import unittest
from unittest.mock import patch, MagicMock
import tests.mock.zwave as mock_zwave
import pytest
from homeassistant.components.zwave import node_entity, const
from homeassistant.const import ATTR_ENTITY_ID
async def test_maybe_schedule_update(hass, mock_openzwave):
"""Test maybe schedule update.... | ZWaveBaseEntity()
base_entity.hass = hass
with patch.object(hass.loop, "call_later") as mock_call_later:
base_entity._schedule_update()
assert mock_call_later.called
base_entity._schedule_update()
assert len(mock_call_later.mock_calls) == 1
do_update = mock_call_later.... |
exter/pycover | droptarget.py | Python | mit | 1,525 | 0.002623 | __author__ = 'Exter, 0xBADDCAFE'
import wx
class FTDropTarget(wx.DropTarget):
"""
Implements drop target functionality to receive files and text
receiver - any WX class that can bind to events
evt - class that comes from wx.lib.newevent.NewCommandEvent call
class variable ID_DROP_FILE
class... | les/text """
| if self.GetData():
drop_type = self.composite.GetReceivedFormat().GetType()
if drop_type in (wx.DF_TEXT, wx.DF_UNICODETEXT):
wx.PostEvent(self.receiver, self.evt(id=self.ID_DROP_TEXT, text=self.text_do.GetText()))
elif drop_type == wx.DF_FILENAME:
... |
arocchi/Klampt | Python/control/roscontroller.py | Python | bsd-3-clause | 11,505 | 0.010169 | """This controller accepts ROS JointTrajectory messages
from the ROS topic '/[robot_name]/joint_trajectory' and writes out
JointState messages to the ROS topic '/[robot_name]/joint_state'.
It also acts as a ROS clock server.
"""
import controller
import rospy
from klampt.trajectory import Trajectory,HermiteTrajectory... | e] = index
def output(self,**inputs):
res = {}
for msg in self.jointTrajectoryRosMsgQueue:
#parse in the message -- are | positions, velocities, efforts specified?
self.currentTrajectoryStart = inputs['t']
self.currentTrajectoryNames = msg.joint_names
#read in the start time according to the msg time stamp, as
#specified by the ROS JointTrajectoryActionController
starttime = msg.... |
Haynie-Research-and-Development/jarvis | deps/lib/python3.4/site-packages/plexapi/media.py | Python | gpl-2.0 | 19,248 | 0.002391 | # -*- coding: utf-8 -*-
from plexapi import log, utils
from plexapi.base import PlexObject
from plexapi.exceptions import BadRequest
from plexapi.utils import cast
@utils.registerPlexObject
class Media(PlexObject):
""" Container object for all MediaPart objects. Provides useful data about the
video this m... | part this stream belongs to.
codec (str): Codec of this stream (ex: srt, ac3, mpeg4).
codecID (str): Codec ID (ex: XVID).
id (int): Unique stream ID on this server.
index (int): Unknown
language (str): Str | eam language (ex: English, ไทย).
languageCode (str): Ascii code for language (ex: eng, tha).
selected (bool): True if this stream is selected.
streamType (int): Stream type (1=:class:`~plexapi.media.VideoStream`,
2=:class:`~plexapi.media.AudioStream`, 3=:class:`~plexa... |
orlenko/bccf | src/mezzanine/forms/signals.py | Python | unlicense | 138 | 0 |
from django.dispatch import Signal
fo | rm_invalid = Signal(provid | ing_args=["form"])
form_valid = Signal(providing_args=["form", "entry"])
|
MSusik/invenio | invenio/modules/records/testsuite/functions/get_modification_date.py | Python | gpl-2.0 | 1,109 | 0.011722 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2013 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) a... | ll 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
def get_modification_date(recid):
"""
Returns creation date for given record.
@param recid:
@return: Creation date
"""
fro... |
poiesisconsulting/openerp-restaurant | poi_pos_table_designer/report/pos_rest_report.py | Python | agpl-3.0 | 4,732 | 0.005072 | # -*- 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... | c'
def init(self, cr):
tools.drop_view_if_exists(cr, 'report_pos_rest')
cr.execute("""
create or replace view report_pos_rest as (
select
min(l.id) as id,
count(*) as nbr,
s.date_order as date,
... | sum(l.price_subtotal_incl) as total_incl,
sum((l.qty * l.price_unit) * (l.discount / 100)) as total_discount,
(sum(l.qty*l.price_unit)/sum(l.qty * u.factor))::decimal(16,2) as average_price,
sum(cast(to_char(date_trunc('day',s.date_order) - ... |
trnewman/VT-USRP-daughterboard-drivers_python | gnuradio-core/src/python/gnuradio/blks2impl/stream_to_vector_decimator.py | Python | gpl-3.0 | 2,500 | 0.024 | #
# Copyright 2008 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
#... | e Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr
class stream_to_vector_decimator(gr.hier_block2) | :
"""!
Convert the stream to a vector, decimate the vector stream to achieve the vector rate.
"""
def __init__(self, item_size, sample_rate, vec_rate, vec_len):
"""!
Create the block chain.
@param item_size the number of bytes per sample
@param sample_rate the rate of incoming samples
@param vec_r... |
armpc/repo | subcmds/init.py | Python | apache-2.0 | 7,741 | 0.009043 | #
# Copyright (C) 2008 The Android Open Source Project
#
# 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 la... | repo/ directory in the
current working directory.
The optional -b argument can be used to select the manifest branch
to checkout and use. If no branch is specified, master is assumed.
The optional -m argument can be used to specify an alternate manifest
to be used. If no manifest is specified, the manifest default.x... | make the working
directory use as much data as possible from the local reference
directory when fetching from the server. This will make the sync
go a lot faster by reducing data traffic on the network.
Switching Manifest Branches
---------------------------
To switch to another manifest branch, `repo init -b otherb... |
pjg101/SickRage | sickbeard/providers/yggtorrent.py | Python | gpl-3.0 | 7,141 | 0.002802 | # coding=utf-8
# Author: adaur <adaur.underground@gmail.com>
# Contributor: PHD <phd59fr@gmail.com>
#
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | 'id': self.username,
'pass': self.password,
}
response = self.get_url(self.urls['login'], p | ost_data=login_params, returns='response')
# The login is now an AJAX call (401 : Bad credentials, 200 : Logged in, other : server failure)
if not response or response.status_code != 200:
logger.log('Unable to connect to provider', logger.WARNING)
return False
else:
... |
openbermuda/karmapi | karmapi/currie.py | Python | gpl-3.0 | 3,935 | 0.00305 | """
Currie -- you can do magic.
Goal here is to have a thread launching piglets.
And curio controlling the operation.
Aim to use joy to control which widget loop to use.
No piglets known to be harmed with this code.
So there is a pig farm and piglets running everywhere.
And currie doing magic.
"""
from collection... | parser.parse_args()
# import from pig stuff here, after talking to joy
from karmapi import joy
joy.set_backend(args.pig)
from karmapi import piglet
from karmapi import widgets
from karmapi import sonogram
# what's this doing here?
#import tkinter
farm = pigfarm.PigFarm()
pr... | import TankRain
from karmapi import diceware as dice
from karmapi import talk
if args.monitor:
from karmapi import milk
farm.add(milk.Curio)
images = [
dict(image='climate_karma_pi_and_jupyter.png', title=''),
dict(image='gil_ly_.png', title=''),
dict(image='pr... |
RussTedrake/director | src/python/ddapp/viewbehaviors.py | Python | bsd-3-clause | 31,473 | 0.004226 | import PythonQt
from PythonQt import QtCore, QtGui
import re
import ddapp.objectmodel as om
import ddapp.visualization as vis
from ddapp.timercallback import TimerCallback
from ddapp import affordanceitems
from ddapp import lcmUtils
from ddapp import callbacks
from ddapp import cameracontrol
from ddapp import midi
from... | edObject(displayPoint, view)
try:
robotModel.model.getLinkNameForMesh
except AttributeError:
return Fals | e
model = robotModel.model
pickedPoint, _, polyData = vis.pickProp(displayPoint, view)
linkName = model.getLinkNameForMesh(polyData)
if not linkName:
return False
fadeValue = 1.0 if linkName == self.selectedLink else 0.05
for name in model.getLinkNames():... |
hasgeek/lastuser | lastuser_ui/forms/profile.py | Python | bsd-2-clause | 5,174 | 0.001546 | # -*- coding: utf-8 -*-
from baseframe import _, __
from coaster.auth import current_auth
from coaster.utils import nullstr
from lastuser_core.models import UserEmail, UserEmailClaim, UserPhone, UserPhoneClaim
from lastuser_core.utils import strip_phone, valid_phone
import baseframe.forms as forms
__all__ = [
'Em... | (__("Work"), __("Work")),
(__("Other"), _ | _("Other")),
],
)
# TODO: Move to function and place before ValidEmail()
def validate_email(self, field):
field.data = field.data.lower() # Convert to lowercase
existing = UserEmail.get(email=field.data)
if existing is not None:
if existing.user == current_auth.... |
splice/spacewalk-splice-tool | src/spacewalk_splice_tool/katello_sync.py | Python | gpl-2.0 | 13,965 | 0.003652 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or impli... | arketing_product_usage):
enriched_mpu = utils.queued_work(self._mpu_enrich_worker, marketing_product_usage, self.num_threads)
return enriched_mpu
def update_owners(self, orgs, prefix):
"""
ensure that the katello owner set matches what's in spac | ewalk
"""
owners = self.katello_client.get_owners()
# we need to iterate over a sorted list, to ensure org #1
# is created before others
org_ids = sorted(orgs.keys())
owner_label_map = {}
for owner in owners:
owner_label_map[owner['label']] = owner
... |
lahwaacz/qutebrowser | qutebrowser/keyinput/modeman.py | Python | gpl-3.0 | 13,365 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2017 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... | f._releaseevents_to_pass.add(KeyEvent(event))
if curmode != usertypes.KeyMode.insert:
focus_widget = QApplication.instance().focusWidget()
log.modes.debug("handled: {}, forward-unbound-keys: {}, "
"passthrough: {}, is_non_alnum: {} | --> "
"filter: {} (focused: {!r})".format(
handled, self._forward_unbound_keys,
parser.passthrough, is_non_alnum, filter_this,
focus_widget))
return filter_this
def _eventFilter_keyr... |
siosio/intellij-community | python/testData/codeInsight/mlcompletion/underscoreTypeTwoStart.py | Python | apache-2.0 | 199 | 0.015075 | class MyClass(object):
def __init__(self):
self.__private_ | var = 42
self._private_var = 11
self.instance_var = 12
def foo(self):
| self.<caret>
obj = MyClass() |
luke0922/celery_learning | application/models/__init__.py | Python | apache-2.0 | 63 | 0 | # | !/usr/bin/env python
# encoding: utf-8
from .user import User | |
blancltd/blanc-basic-pages | setup.py | Python | bsd-3-clause | 1,204 | 0 | #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='blanc-basic-pages',
version='0.3.7',
description='Blanc Basic Pages for Django',
long_description=readme,
url='https://github.... | (),
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming La | nguage :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
license='BSD',
)
|
lyw07/kolibri | kolibri/core/content/migrations/0002_channelmetadatacache_last_updated.py | Python | mit | 476 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017-06-06 17:16
from __future__ import unicode_literals
from django.db import migrations
imp | ort kolibri.core.fields
class Migration(migrations.Migration):
dependencies = [("content", "0001_initial")]
operations = [
migrations.AddField(
model_name="channelmetadatacache",
name="l | ast_updated",
field=kolibri.core.fields.DateTimeTzField(null=True),
)
]
|
bluecube/pysystemfan | pysystemfan/harddrive.py | Python | mit | 5,952 | 0.004874 | from . import config_params
from . import thermometer
from . import util
import subprocess
import shlex
import os
import collections
import logging
logger = logging.getLogger(__name__)
def _iterate_command_output(self, command):
process = subprocess.Popen(command,
stdout=subprocess... | de {}".format(_list_to_shell(c | ommand),
process.returncode))
def _list_to_shell(l):
return " ".join(shlex.quote(x) for x in l)
class Harddrive(thermometer.Thermometer, config_params.Configurable):
_params = [
("path", None, "Device file of the disk. For examp... |
grantsewell/nzbToMedia | core/__init__.py | Python | gpl-3.0 | 33,961 | 0.021819 | import locale
import os
import re
import subprocess
import sys
import platform
import time
# init libs
PROGRAM_DIR = os.path.dirname(os.path.normpath(os.path.abspath(os.path.join(__file__, os.pardir))))
LIBS_ | DIR = os.path.join(PROGRAM_DIR, 'libs')
sys.path.insert(0, LIBS_DIR)
# init preliminaries
SYS_ARGV = sys.argv[1:]
APP_FILENAME = sys.argv[0]
APP_NAME = os.path.basename(APP_FILENAME)
LOG_DIR = os.path.join(PROGRAM_DIR, 'logs')
LOG_FILE = os.path.join(LOG_DIR, 'nzbtomedia.log')
PID_FILE = os.path.join(LOG_DIR, 'nzbtome... | utoProcessMedia.cfg')
CONFIG_SPEC_FILE = os.path.join(PROGRAM_DIR, 'autoProcessMedia.cfg.spec')
CONFIG_MOVIE_FILE = os.path.join(PROGRAM_DIR, 'autoProcessMovie.cfg')
CONFIG_TV_FILE = os.path.join(PROGRAM_DIR, 'autoProcessTv.cfg')
TEST_FILE = os.path.join(os.path.join(PROGRAM_DIR, 'tests'), 'test.mp4')
MYAPP = None
fro... |
riyoth/Script | RezConso/RezConso.py | Python | mit | 876 | 0.004566 | #!/home/poclement/Prog/Perso/RezConso/venv/bin/python
from bs4 import BeautifulSoup
import urllib2
import base64
from datetime import date
import math
BASE_URL = "http://www2.cooptel.qc.ca/services/temps/?mois={0}&cmd=Visualiser".format(date.today().month)
req = urllib2.Request(BASE_URL)
base64string = base64.encod... | houldn't fail if the username/password is right
print "It | looks like the username or password is wrong."
sys.exit(1)
thepage = handle.read()
soup = BeautifulSoup(thepage, "lxml")
data_use = float(soup.find_all("tr")[-3].find_all("td")[-1].text)/1024
data_available = float(soup.find_all("tr")[-1].find_all("td")[-1].text)/1024
print int(math.floor(data_use))
|
mozilla/caseconductor-ui | ccui/static/models.py | Python | gpl-3.0 | 2,951 | 0.00305 | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011 uTest Inc.
#
# This file is part of Case Conductor.
#
# Case Conductor 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... | s 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 Case Condu | ctor. If not, see <http://www.gnu.org/licenses/>.
"""
Core objects for accessing staticData API.
"""
import urlparse
import remoteobjects
from ..core.conf import conf
from ..core.api import ObjectMixin, fields
class CodeValue(ObjectMixin, remoteobjects.RemoteObject):
id = fields.Field()
description = fie... |
batra-mlp-lab/DIGITS | digits/dataset/tasks/create_db.py | Python | bsd-3-clause | 11,328 | 0.001589 | # Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
import sys
import os.path
import re
import operator
import digits
from digits import utils
from digits.utils import subclass, override
from digits.task import Task
# NOTE: Increment this everytime the pickled version changes
PICKLE_VERSION = 3
@su... | if self.image_dims[2] == 1:
self.image_channel_order = None
elif self.encod | e:
self.image_channel_order = 'BGR'
else:
self.image_channel_order = 'RGB'
if self.pickver_task_createdb <= 2:
if hasattr(self, 'encode'):
if self.encode:
self.encoding = 'jpg'
else:
s... |
TamiaLab/carnetdumaker | apps/bugtracker/models.py | Python | agpl-3.0 | 27,771 | 0.003025 | """
Models for the bug tracker app.
"""
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from apps.tools.models import Mode... |
internal_name = models.CharField(_('Name (for internal use)'),
max_length=255)
description = models.TextField(_('Descript | ion'),
default='',
blank=True)
class Meta:
verbose_name = _('Application component')
verbose_name_plural = _('Application components')
def __str__(self):
return self.name
class IssueTicket(ModelDiffMixin, models.Mo... |
bintlabs/pygal-nostatics | pygal/graph/frenchmap.py | Python | lgpl-3.0 | 10,495 | 0.000096 | # -*- coding: utf-8 -*-
# This file is part of pygal
#
# A python svg graph plotting library
# Copyright © 2012-2014 Kozea
#
# This library is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version... | rovence-Alpes-Côte d'Azur"),
'94': u("Corse"),
'01': u("Guadeloupe"),
'02': u("Martinique"),
'03': u("Guyane"),
'04': u("Réunion"),
# Not a region anymore but in case of...
'05': u("Saint Pierre et Miquelon"),
'06': u("Mayotte")
}
DPT_MAP = fr_departments_svg.contents
REG_MAP = fr_re... | ""French department map"""
_dual = True
x_labels = list(DEPARTMENTS.keys())
area_names = DEPARTMENTS
area_prefix = 'z'
kind = 'departement'
svg_map = DPT_MAP
@cached_property
def _values(self):
"""Getter for series values (flattened)"""
return [val[1]
fo... |
pytonc/upluschat | main.py | Python | mit | 15,674 | 0.00823 | import os
import hashlib
import urllib
import logging
import re
import json
import webapp2
import jinja2
from google.appengine.api import channel as channel_api # 'channel' is kind of ambiguous in context
from google.appengine.ext import db
from google.appengine.api import memcache
# This section will eventually get ... | name # Use actual name
channel = get_channel(channelname)
if not channel:
if channelname and not re.compile(r'^#[\w]{3,20}$').match(channelname):
channelerror="Ch | annel must consist of 3-20 alpha_numeric characters and start with a #"
channel_api.send_message(username, "NOTICE "+channelerror)
return
channel = ChatChannel(key_name=channelname.lower(),
channelname=channelname,
users=json.du... |
AMXAUNZ/Magic-DXLink-Configurator | scripts/telnet_class.py | Python | mit | 23,853 | 0.000587 | """ Telnets to devices to preform tasks"""
import telnetlib
from pydispatch import dispatcher
from threading import Thread
import datetime
import subprocess
# import serial
# import io
import time
from dataclasses import dataclass, field
@dataclass
class MSEValues:
report_time: datetime = datetime.datetime.now()... | job):
obj = job[1]
self.set_status(obj, "Connecting")
try:
telnet_session = self.establish_telnet(obj.ip_address)
telnet_session.read_until(b'>', int(job[2]))
telnet_session.write(b'reboot\r')
telnet_session.read_until(b'Rebooting....', int(job[2]... | except Exception as error:
self.error_processing(obj, error)
def set_device_config(self, job):
# print job
obj = job[1]
delay = int(job[2])
setdhcp = job[3]
hostname = job[4]
# ip_org = job[5]
ip_new = job[6]
subnet = job[7]
gatew... |
seadsystem/ShR2 | Web Stack/farmer/models.py | Python | mit | 1,851 | 0.020529 | from django.db import models
from microdata.models import Device
# Create your models here.
class DeviceSettings(models.Model):
"""
Describes the settings associated with a device.
This is what is returned by a REST call to /api | /settings-api/{serial}/.
"""
device = models.OneToOneField(Device)
""" Relational field to connect the settings to a device."""
device_serial | = models.IntegerField(unique=True, primary_key=True, editable=False)
""" The serial of the device this model is linked to."""
CHANNEL_CHOICES = (
(1, 'Channel 1'),
(2, 'Channel 2'),
(3, 'Channel 3'),
(4, 'Channel 4'),
)
main_channel = models.IntegerField(choices=CHANNEL_CHOICES,... |
vholland/schemaorg | SchemaPages/example-code/simpleTermList/simpleExpandedTermList.py | Python | apache-2.0 | 3,486 | 0.019793 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor > 5):
print("Python version %s.%s not supported version 3.6 or above required - exiting" % (sys.version_info.major,sys.version_info.minor))
sys.exit(1)
# To be executed in the SchemaPages/... | t %s" % (ind,len(term.properties)))
for p in term.properties:
| showTerm(p,ind=ind +" ")
print("%sExpected Type for count %s" % (ind,len(term.expectedTypeFor)))
for t in term.expectedTypeFor:
showTerm(t,ind=ind +" ")
else:
print("%sProperties: %s" % (ind,term.properties))
print("%sExpected Type for... |
jnayak1/osf-meetings | meetings/mail/tests.py | Python | apache-2.0 | 1,412 | 0 | from django.test import TestCase
import mock
from mail.mails import create_mailgun_conference_route
class TestMail(TestCase):
@mock.patch('mail.mails.requests.post')
def test_create_mailgun_conference_route_poster(self, mock_post):
create_mailgun_conference_route('this', 'poster')
mock_post.a... | /inbound/')",
'stop()'
],
'expression': "match_recipient('this-talk@osf.io')",
'desc | ription': 'Conference submission by email'
}
)
|
clarko1/Cramd | appengine/standard/background/main_test.py | Python | apache-2.0 | 1,554 | 0 | # 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 a... | ody == 'Dog'
app.get('/cat')
# no stub for system so manually set
main.val = 'Cat'
response = app.get('/')
assert response.status_int == 200
assert response.body == 'Cat'
@patch("main.background_thread")
def test_background_auto_start(thread, app):
app | .get('/dog')
response = app.get('/')
assert response.status_int == 200
assert response.body == 'Dog'
app.get('/cat?auto=True')
# no stub for system so manually set
main.val = 'Cat'
response = app.get('/')
assert response.status_int == 200
assert response.body == 'Cat'
|
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/authentication/authenticationradiuspolicy_systemglobal_binding.py | Python | apache-2.0 | 5,395 | 0.03633 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | , name) :
"""Name of the RADIUS authentication policy.<br/>Minimum length = 1
"""
try :
self._name = name
except Exception as e:
raise e
@property
def boundto(self) :
"""The entity name to which policy is bound.
"""
try :
return self._boundto
except Exception as e:
raise e
@boundto.set... | y
def priority(self) :
try :
return self._priority
except Exception as e:
raise e
@property
def activepolicy(self) :
try :
return self._activepolicy
except Exception as e:
raise e
def _get_nitro_response(self, service, response) :
""" converts nitro response into object and returns the objec... |
imakin/SLAM | nodes/dynamixel_joint_state_publisher.py | Python | gpl-2.0 | 3,507 | 0.007984 | #!/usr/bin/env python
"""
dynamixel_joint_state_publisher.py - Version 1.0 2010-12-28
Publish the dynamixel_controller joint states on the /joint_states topic
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2010 Patrick Goebel. All rights reserved.
This program is... | # Start controller state subscribers
[rospy.Subscriber(c + '/state', JointStateDynamixel, self.controller_state_handler) for c in self.controllers]
| # Start publisher
self.joint_states_pub = rospy.Publisher('/joint_states', JointStatePR2)
rospy.loginfo("Starting Dynamixel Joint State Publisher at " + str(rate) + "Hz")
while not rospy.is_shutdown():
self.publish_joint_states()
r.sleep()
... |
mwri/snns | python/setup.py | Python | lgpl-2.1 | 618 | 0.056634 | #!/usr/bin/python
from distutils.core import setup, Extension, extension_keywords
#print extension_keywords
module1 = Extension('krui',
sources = ['snns/krui.c'],
| include_dirs = ['../kernel/sources'],
library_dirs = ['../kernel/sources'],
lib | raries = ['kernel','func','fl'])
setup (name = 'snns-kernel',
ext_package='snns',
version = '0.1',
author='Patrick Kursawe',
author_email='Patrick.Kursawe@web.de',
description = 'SNNS kernel functions',
packages = ['snns'],
ext_modules = [module1],
py_modules = [... |
WojtekReu/Politikon | politikon/settings/base.py | Python | gpl-2.0 | 13,721 | 0.000583 | # -*- coding: utf-8 -*-
import os
import sys
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from django.utils.translation import ugettext_lazy as _
from celery.schedules import crontab
from constance import config
from datetime import timedelta
from path import path
DJANGO_PROJECT... | END': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(DJANGO_PROJECT_ROOT, 'templates'),
DJANGO_PROJECT_ROOT
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
| # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.request',
... |
wiltonlazary/arangodb | 3rdParty/V8/gyp/generator/analyzer.py | Python | apache-2.0 | 30,587 | 0.007879 | # Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This script is intended for use as a GYP_GENERATOR. It takes as input (by way of
the generator flag config_path) the path of a json file that dictates the file... | ailing '/' so that _AddSources() can easily build paths.
if len(base_path):
base_path += '/'
if debug:
print('ExtractSources', target, base_path)
results = []
if 'sources' in target_dict:
_AddSources(target_dict['sources'], base_path, base_path_c | omponents,
results)
# Include the inputs from any actions. Any changes to thes |
drewdru/AOI | roadLaneFinding/calibration.py | Python | gpl-3.0 | 1,559 | 0.025657 | import glob
import pickle
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
#corners
nx, ny = 9, 6
channels = 3
#calibration image list
image_names = glob.glob('./camera_cal/calibration*.jpg')
#imgpoints and objpoints
imgpoints = [] #2D in image plane
objpoints = [] #3D i... | cal_img)
#print("Saved corners for image ", str(idx))
#load image for reference
img = cv | 2.imread('./camera_cal/calibration11.jpg')
img_size = (img.shape[1], img.shape[0])
#camera calibration
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None, None)
#save camera calibration results for later
calibration = {}
calibration['mtx'] = mtx
calibration['dist'] = dist
pickle.d... |
botswana-harvard/getresults-order | getresults_order/forms.py | Python | gpl-2.0 | 514 | 0.001946 | from django import forms
from getresults_aliquot.models import Aliquot
from .mod | els import Order
class OrderForm(forms.ModelForm):
def clean_aliquot_identifier(self):
aliquot_identifier = self.cleaned_data.get('aliquot_identifier')
try:
Aliquot.objects.get(aliquot_identifier=aliquot_identifier)
except Aliquot.DoesNotExist:
raise forms.Validati... | d Aliquot Identifier. Got {}'.format(aliquot_identifier))
class Meta:
model = Order
|
naucoin/VTKSlicerWidgets | Wrapping/Python/vtk/io.py | Python | bsd-3-clause | 217 | 0 | """ This module loads all the classes from the VTK IO library into its
namespace. This is a requir | ed module."""
import os
|
if os.name == 'posix':
from libvtkIOPython import *
else:
from vtkIOPython import *
|
VitalPet/report-print-send | __unported__/printer_tray/ir_report.py | Python | agpl-3.0 | 2,414 | 0.000829 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Vaucher
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | rinting_printer_id)]"),
}
def set_print_options(self, cr, uid, report_id, format, context=None):
"""
Hook to define Tray
"""
printing_act_obj = self.pool.get('printing.report.xml.action')
options = super(ReportXML, | self).set_print_options(cr, uid, report_id, format, context=context)
# Retrieve user default values
user = self.pool.get('res.users').browse(cr, uid, context)
tray = user.printer_tray_id
report = self.browse(cr, uid, report_id, context=context)
# Retrieve report default values
... |
GreenBlast/Linger | LingerManagers/ActionsManager.py | Python | mit | 908 | 0.004405 | from LingerManagers.LingerBaseManager import LingerBaseManager
class ActionsManager(LingerBaseManager):
"""ActionsManager loads linger actions,
and manages instances of them according to configuration"""
def __init__(self, configuration):
super(ActionsManager, sel | f).__init__(configuration['dir_paths']['Actions'])
self.configuration = configuration
self.manager_type = "Actions"
def create_action(self, configuration):
self.logger.debug("Creating action")
configuration_to_send = configuration.copy()
configuration_to_send.update(self.con... | s[configuration["uuid"]] = action_instance
def get_action(self, uuid_of_action):
return self.plugin_instances[uuid_of_action] |
Jumpscale/jumpscale6_core | apps/agentcontroller/processmanager/loghandling/1_init.py | Python | bsd-2-clause | 527 | 0.034156 | import time
import JumpScale.baselib.redis
from JumpScale import j
def main(q, args, params, tags, tasklet):
log=args["logobj"]
redis=j.clients.redis.getRedisClient("127.0.0.1",9999)
log.gid = int(log.gid)
if log.epoch==0:
log. | epoch=int(time.time())
incrkey="%s_%s"%(log.gid,log.nid)
log.order=redis.incr | ("logs:incr:%s"%incrkey,1)
log.guid = "%s_%s_%s"%(log.gid,log.nid,log.order)
params.result=log
return params
def match(q, args, params, tags, tasklet):
return True
|
sfloresk/nso-dashboard-demo | web_app/ncclientextensions/operations.py | Python | apache-2.0 | 930 | 0 | """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed ... | Cisco Systems inc.
"""
from ncclient.operations.rpc import RPC
class Sen | dCommand(RPC):
"""
Create a new class that inherit from ncclient.operations.rpc.RPC
"""
__author__ = 'Santiago Flores Kanter (sfloresk@cisco.com)'
# Override request method from RPC
def request(self, xml):
# Send request
return self._request(xml)
|
ianfelzer1/ifelzer-advprog | Last Year/python files /new1.py | Python | gpl-3.0 | 400 | 0.035 | def main():
num=input("Enter a # and I'll tell you all perfect numbers up to that #: ")
for i in range(1,num+1):
sum=0
for j in range(1,(i/2)+1): # why +1?
if i%j==0: # check if remainder is 0
sum=sum+j
# print "factor: ",i
if | sum==i:
| print sum,"is Perfect!"
print "That's all there are!"
main()
|
rddimon/test-product-scanner | testproductscanner/settings.py | Python | mit | 3,396 | 0.001472 | """
Django settings | for testproductscanner project.
Generated by 'django-admin startproject' using Django 1.11.6.
For more information on this file, see
https://docs.djangoproject.c | om/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development ... |
QISKit/qiskit-sdk-py | docs/conf.py | Python | apache-2.0 | 4,087 | 0.000245 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | The name of the Pygments (syntax highlighting) style to use.
pygments_style = None
# A boolean that decides whether module names are prepended to all object names
# (for object types where a “module” of some kind is defined), e.g. for
# py:function directives.
add_module_names = False
# A list of prefixes that are ig... | f this is set to ['foo.'], then foo.bar is shown under B, not F).
# This can be handy if you document a project that consists of a single
# package. Works only for the HTML builder currently.
modindex_common_prefix = ['qiskit.']
# -- Configuration for extlinks extension ------------------------------------
# Refer to ... |
judithfan/graphcomm | experiments/draw/python/download_all_eitz_synsets.py | Python | mit | 250 | 0.016 | #!/usr/local/bin/python
## wrapper script to download 1 | 00 photos from all | the eitz synsets to a photos folder
import imagenet_datasets as id
eitz_synsets = id.get_list_of_eitz_synsets()
id.download_images_by_synset(eitz_synsets,num_per_synset=100) |
ethantang95/DIGITS | digits/extensions/view/imageSegmentation/forms.py | Python | bsd-3-clause | 633 | 0 | # Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from flask.ext.wtf import Form
from digits import utils
from digits.utils import subclass
@subclass
class ConfigForm(Form):
"""
A form used to display the network output as an image
"""
colorm... | rms.SelectField(
'Colormap',
choices=[
('dataset', 'From dataset'),
('paired', 'Paired (matplotlib)'),
('none', 'None (g | rayscale)'),
],
default='dataset',
tooltip='Set color map to use when displaying segmented image'
)
|
mattvonrocketstein/smash | smashlib/ipy3x/testing/__init__.py | Python | mit | 1,341 | 0.003729 | """Testing support (tools to test IPython itself).
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2009-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this so... | ------------------------
# User-level entry point for testing
def test(**kwargs):
"""Run the entire IPython test suite.
Any of the options for run_iptestall() may be passed as keyword arguments.
For example::
IPython.test(testgroups=['lib', 'config', 'utils'], fast=2)
will run those three... | ller import run_iptestall, default_options
options = default_options()
for name, val in kwargs.items():
setattr(options, name, val)
run_iptestall(options)
# So nose doesn't try to run this as a test itself and we end up with an
# infinite test loop
test.__test__ = False
|
telstra/open-kilda | src-python/grpc-stub/server.py | Python | apache-2.0 | 6,031 | 0.000166 | # Copyright 2020 Telstra Open Source
#
# 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 agre... | r 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 unde | r the License.
#
from concurrent import futures
import logging
import grpc
import noviflow_pb2
import noviflow_pb2_grpc
class Greeter(noviflow_pb2_grpc.NoviFlowGrpcServicer):
def __init__(self):
self.storage = Storage()
def ShowStatsPacketInOut(self, request, context):
resp = noviflow_pb2... |
courtarro/gnuradio-wg-grc | gnuradio-runtime/examples/volk_benchmark/volk_math.py | Python | gpl-3.0 | 5,334 | 0.004124 | #!/usr/bin/env python
from gnuradio import gr
from gnuradio import blocks
import argparse
from volk_test_funcs import *
try:
from gnuradio import blocks
except ImportError:
sys.stderr.write("This example requires gr-blocks.\n")
def multiply_const_cc(N):
k = 3.3
op = blocks.multiply_const_cc(k)
tb... | nt('--list', action='store_true',
help='List the available tests')
parser.add_argument('--all', action='store_true',
help='Run all tests')
args = parser.parse_args()
if(args.li | st):
print "Available Tests to Run:"
print "\n".join(["\t{0}: {1}".format(i,f.__name__) for i,f in enumerate(avail_tests)])
sys.exit(0)
N = int(args.nitems)
iters = args.iterations
label = args.label
conn = create_connection(args.database)
new_table(conn, label)
if arg... |
yoon-gu/Mozart | tests/test_mesh_cube.py | Python | mit | 4,587 | 0.027469 | import numpy as np
import numpy.testing as npt
def test_3d_uniform_cube_degree_one():
from mozart.mesh.cube import cube
x1, x2, y1, y2, z1, z2, Mx, My, Mz, N = (0, 1, 0, 1, 0, 1, 2, 2, 2, 1)
c4n, ind4e, n4e, n4Db = cube(x1,x2,y1,y2,z1,z2,Mx,My,Mz,N)
ref_c4n = np.matrix('[0 0 0;0.5 0 0;1 0 0;0 0.5 0;0.5 0.5 0;1 0.5... | assert_almost_equal(c4n, ref_c4n, decimal=8)
npt.assert_almost_equal(ind4e, ref_ind4e , decimal=8)
npt.assert_almost_equal(n4e, ref_n4e, decimal=8)
npt.assert_almost_equal(n4Db, ref_n4Db, decimal=8)
def test_3d_uniform_cube_degree_two():
from mozart.mesh.cube import cube
x1, x2, y1, y2, z1, z2, Mx, My, Mz, N = (0... | 2, 2)
c4n, ind4e, n4e, n4Db = cube(x1,x2,y1,y2,z1,z2,Mx,My,Mz,N)
ref_c4n = np.matrix('[0 0 0;0.25 0 0;0.5 0 0;0.75 0 0;1 0 0;0 0.25 0;0.25 0.25 0;0.5 0.25 0;0.75 0.25 0;1 0.25 0;\
0 0.5 0;0.25 0.5 0;0.5 0.5 0;0.75 0.5 0;1 0.5 0;0 0.75 0;0.25 0.75 0;0.5 0.75 0;0.75 0.75 0;\
1 0.75 0;0 1 0;0.25 1 0;0.5... |
mpmc/HS602 | hs602/controller.py | Python | gpl-3.0 | 26,909 | 0 | # Copyright (C) 2019 Mark Clarkstone <mpmc@disroot.org>
#
# This file is part of hs602.
#
# hs602 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 late... | d value, requires a string of 1-255 '
'in length'))
@staticmethod
def int(value):
"""Value is int 0 - 255.
:par | am value: Value to check.
"""
value = round(int(value))
if value in range(0, 256):
return value
raise ValueError(_('invalid value, requires a number between '
'0 and 255'))
@staticmethod
def port(value):
"""Value is int 0 - 65535.
... |
irmen/Pyro4 | examples/proxysharing/client.py | Python | mit | 3,104 | 0.002899 | from __future__ import print_function
import sys
import time
import threading
import Pyro4.naming
import Pyro4.core
if sys.version_info < (3, 0):
current_thread = threading.currentThread
else:
current_thread = threading.current_thread
stop = False
def myThread(nsproxy, proxy):
global stop
name = cu... | n thread %s: {%s} %s" % (name, type(x), x))
nsproxy = Pyro4.naming.locateNS()
proxy = Pyro4.core.Proxy("PYRONAME:example.proxysharing")
# now create a handful of threads and give each of them the same two proxy objects
threads = []
for i in range(5):
thread = threading.Thread(target=myThread, args=(nsproxy, prox... | mon(True)
thread.setDaemon(False)
threads.append(thread)
thread.start()
print("Running a bunch of threads for 5 seconds.")
print("They're hammering the name server and the test server using the same proxy.")
print("You should not see any exceptions.")
time.sleep(5)
stop = True
for thread in threads:
th... |
brain-tec/stock-logistics-workflow | stock_dropshipping_dual_invoice/tests/test_need_two_invoices.py | Python | agpl-3.0 | 4,106 | 0 | # Author: Leonardo Pistone
# Copyright 2015 Camptocamp SA
#
# 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 la... | d_two_invoices())
def test_so_on_delivery_need_one_invoice(self):
self.so.order_policy = 'picking'
self.so.action_button_confirm()
po = self.so.procurement_group_id.procurement_ids.purchase_id
self.assertTrue(po)
po.signal_workflow('purchase_confirm')
picking = po.p... | 'active_id': picking.id,
'active_ids': [picking.id],
}).create({})
self.assertIs(False, wizard._need_two_invoices())
def test_so_mto_need_one_invoice(self):
self.so.order_policy = 'picking'
self.sol.route_id = self.mto_route.id
self.so.action_button_confirm... |
cneill/designate | designate/manage/database.py | Python | apache-2.0 | 1,879 | 0 | # Copyright 2012 Managed I.T.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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 r... | ate.storage.impl_sqlalchemy',
group='storage:sqlalchemy')
CONF = cfg.CONF
INIT_VERSION = 37
def get_manager():
return utils.get_migration_manager( |
REPOSITORY, CONF['storage:sqlalchemy'].connection, INIT_VERSION)
class DatabaseCommands(base.Commands):
def version(self):
current = get_manager().version()
latest = versioning_api.version(repository=REPOSITORY).value
print("Current: %s Latest: %s" % (current, latest))
def sy... |
chfoo/wpull | wpull/proxy/client.py | Python | gpl-3.0 | 5,519 | 0.000544 | '''Proxy support for HTTP requests.'''
import asyncio
import base64
import io
import logging
import wpull.string
from wpull.errors import NetworkError
from wpull.network.pool import ConnectionPool
from wpull.protocol.http.request import RawRequest
from wpull.protocol.http.stream import Stream
_logger = logging.getLog... | tworkError(
'Proxy does not support CONNECT: {} {}'
.format(response.status_code,
wpull.string.printable_str(response.reason))
)
def add_a | uth_header(self, request):
'''Add the username and password to the HTTP request.'''
if self._authentication:
request.fields['Proxy-Authorization'] = self._auth_header_value
|
FedeMPouzols/Savu | savu/core/utils.py | Python | gpl-3.0 | 4,449 | 0.000225 | # Copyright 2015 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
| # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www. | apache.org/licenses/LICENSE-2.0
#
# Unless required by 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
# l... |
Ban3/Limnoria | plugins/BadWords/__init__.py | Python | bsd-3-clause | 2,470 | 0.000405 | ###
# Copyright (c) 2005, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provi | ded that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaim... | to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHAN... |
ableev/Zabbix-in-Telegram | zbxtg.py | Python | mit | 38,641 | 0.003364 | #!/usr/bin/env python
# coding: utf-8
import sys
import os
import time
import random
import string
import requests
import json
import re
import stat
import hashlib
import subprocess
#import sqlite3
from os.path import dirname
import zbxtg_settings
class Cache:
def __init__(self, database):
self.database ... | r_need_to_contact(self, to):
if self.type == "private":
print_message("User '{0}' needs to send some text bot in private".format(to))
if self.type == "group":
print_message("You need start a conver | sation with your bot first in '{0}' group chat, type '/start@{1}'"
.format(to, self.get_me()["result"]["username"]))
def update_cache_uid(self, name, uid, message="Add new string to cache file"):
cache_string = "{0};{1};{2}\n".format(name, self.type, str(uid).rstrip())
# F... |
bigblindbais/pytk | tests/geo/test_quat.py | Python | mit | 10,747 | 0.01647 | import unittest
import pytk.geo as geo
class GeoQuatTest(unittest.TestCase):
def test_shape(self):
self.assertRaises(geo.GeoException, geo.quat, [])
self.assertRaises(geo.GeoException, geo.quat, [0])
self.assertRaises(geo.GeoException, geo.quat, [0, 1])
self.assertRaises(geo.GeoE... | ssertEqual(( y ).as_rquat, rquat([0, 0, 1, 0]))
self.assertEqual(( z).as_rquat, rquat([0, 0, 0, 1]))
self.as | sertEqual((w + x ).as_rquat, rquat([1, 1, 0, 0]))
self.assertEqual((w + y ).as_rquat, rquat([1, 0, 1, 0]))
self.assertEqual((w + z).as_rquat, rquat([1, 0, 0, 1]))
self.assertEqual(( x + y ).as_rquat, rquat([0, 1, 1, 0]))
self.assertEqual(( x + z).as_rqu... |
reinout/django | django/contrib/gis/db/backends/mysql/operations.py | Python | bsd-3-clause | 3,664 | 0.000546 | from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from django.contrib.gis.db.backends.base.operations import (
BaseSpatialOperations,
)
from django.contrib.gis.db.backends.utils import SpatialOperator
from django.contrib.gis.db.models import aggregates
from django.contrib.gis.geos.geometry import G... | allowed on '
'geodetic distance queries.'
)
dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection)))
else:
dist_param = value
return [dist_param]
def get_geometry_converter(self, expression):
read = wkb_r(... | _class
def converter(value, expression, connection):
if value is not None:
geom = GEOSGeometryBase(read(memoryview(value)), geom_class)
if srid:
geom.srid = srid
return geom
return converter
|
endlessm/chromium-browser | third_party/angle/infra/config/PRESUBMIT.py | Python | bsd-3-clause | 431 | 0.00464 | # Copyright 2019 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def CheckChangeOnUpload(input_api, output_api):
re | turn input_api.canned_checks.CheckChangedLUCIConfigs(input_api, output_api)
def CheckChangeOnCommit(input_api, output_api):
ret | urn input_api.canned_checks.CheckChangedLUCIConfigs(input_api, output_api)
|
imtapps/authorize | authorize/gen_xml.py | Python | mit | 18,407 | 0.005052 | # -*- encoding: utf-8 -*-
import re
import decimal
from xml.etree.cElementTree import fromstring, tostring
from xml.etree.cElementTree import Element, iselement
from authorize import responses
API_SCHEMA = 'https://api.authorize.net/xml/v1/schema/AnetApiSchema.xsd'
API_SCHEMA_NS = "AnetApi/xml/v1/schema/AnetApiSchem... | i/xml/v1/schema/AnetApiSchema.xsd}"
INDIVIDUAL = u"individual"
BUSINESS = u"business"
ECHECK_CCD = u"CCD"
ECHECK_PPD = u"PPD"
ECHECK_TEL = u"TEL"
ECHECK_WEB = u"WEB"
BANK = u"bank"
CREDIT_CARD = u"cc"
ECH | ECK = u"echeck"
DAYS_INTERVAL = u"days"
MONTHS_INTERVAL = u"months"
VALIDATION_NONE = u"none"
VALIDATION_TEST = u"testMode"
VALIDATION_LIVE = u"liveMode"
ACCOUNT_CHECKING = u"checking"
ACCOUNT_SAVINGS = u"savings"
ACCOUNT_BUSINESS_CHECKING = u"businessChecking"
AUTH_ONLY = u"auth_only"
CAPTURE_ONLY = u"capture_only... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.