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 |
|---|---|---|---|---|---|---|---|---|
rev2004/android2cloud.app-engine | google_appengine/google/appengine/ext/db/__init__.py | Python | mit | 101,475 | 0.005932 | #!/usr/bin/env python
#
# Copyright 2007 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 o... | ing provided
kind.
Args:
kind: Entity kind string.
Returns:
Cl | ass implementation for kind.
Raises:
KindError when there is no implementation for kind.
"""
try:
return _kind_map[kind]
except KeyError:
raise KindError('No implementation for kind \'%s\'' % kind)
def check_reserved_word(attr_name):
"""Raise an exception if attribute name is a reserved word.
... |
spektom/incubator-airflow | tests/providers/snowflake/operators/test_s3_to_snowflake.py | Python | apache-2.0 | 3,634 | 0.001376 | #
# 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... | rt_equal_ignore_multiple_spaces(self, mock_run.call_args[0][0], copy_query)
@mock.patch("airflow.providers.snowflake.hooks.snowflake.SnowflakeHook.run")
de | f test_execute_with_columns(self, mock_run):
s3_keys = ['1.csv', '2.csv']
table = 'table'
stage = 'stage'
file_format = 'file_format'
schema = 'schema'
columns_array = ['col1', 'col2', 'col3']
S3ToSnowflakeTransfer(
s3_keys=s3_keys,
table=... |
lefthandedroo/Cosmo-models | zprev versions/Models_py_backup/setup.py | Python | mit | 243 | 0.012346 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Ju | l 23 13:23:20 2018
@author: BallBlueMeercat
"""
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_m | odules = cythonize('firstderivs_cython.pyx')) |
ctlewitt/Invisible-Keyboard | find_intersecting_words.py | Python | mit | 417 | 0.002398 | with open("dictionary.txt", "r") as one_gram_f:
with open("old_dictionary.txt", "r") as internet_list_f:
with open("intersecting_words.txt", "w") as intersecting_words_f:
one_grams = one_gram_f.readlines()
internet_words = internet_list_f | .readlines()
for word in one_grams:
if word in internet_words:
intersecting_words_f.write(word) | |
pawelad/BLM | Players/admin.py | Python | mit | 851 | 0.0047 | from django.contrib import ad | min
from Players.models import Player
@admin.register(Player)
class PlayerAdmin(admin.ModelAdmin):
view_on_site = True
| list_display = ('pk', 'first_name', 'last_name', 'number', 'team', 'position', 'age', 'height', 'weight')
list_filter = ['team', 'position']
search_fields = ['first_name', 'last_name']
# Disable delete when team has 5 players
def has_delete_permission(self, request, obj=None):
try:
... |
dinoperovic/django-shop-wspay | shop_wspay/forms.py | Python | bsd-3-clause | 536 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
class WSPayForm(forms.Form):
ShopID = forms.CharField(widget=forms.HiddenInput)
ShoppingCartID = forms.CharField(widget=forms.HiddenInput)
TotalAmount = forms.CharField(widget=forms.HiddenInput)
Signature = forms... | ms.HiddenInput)
CancelURL = forms.CharField(widget=forms.HiddenInput)
ReturnErrorURL = forms.CharField(widg | et=forms.HiddenInput)
|
Ezopt/Fear-Shadows | cst.py | Python | gpl-3.0 | 796 | 0.003783 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 20 16:01:21 2016
@author: KB
"""
#Listes des images du jeu
import pygame
dossier = "./Img_FS/"
extension1 = ".png"
extension2 = ".jpg"
image_accueil = dossier + "accueil" + extension1
image_fond = dossier + "back1" + extension2
im | age_mur = dossier + "mur | " + extension1
image_persos = dossier + "persos" + extension1
image_monstres = dossier + "monstres" + extension1
image_fin = dossier + "fin" + extension1
image_pause = dossier + "pause" + extension1
image_tache = dossier + "tache" + extension1
image_credit = dossier + "credit" + extension1
#Paramètres de la fenê... |
Smart-Torvy/torvy-home-assistant | homeassistant/components/zone.py | Python | mit | 4,669 | 0 | """
Support for the definition of zones.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zone/
"""
import logging
import voluptuous as vol
from homeassistant.const import (
ATTR_HIDDEN, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_NAME, CONF_LATITUDE,
C... | DIUS = 100
DOMAIN = 'zone'
ENTITY_ID_FORMAT = 'zone.{}'
ENTITY_ID_HOME = ENTITY_ID_FORMAT.format('home')
ICON_HOME = 'mdi:home'
ICON_IMPORT = 'mdi:import'
STATE = 'zoning'
# The config that zone accepts is the same as if it has platforms.
PLATFORM_SCHEMA = vol.Schema({
vol.Optional(CONF_NAME, default=DEFAULT_NA... | red(CONF_LONGITUDE): cv.longitude,
vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS): vol.Coerce(float),
vol.Optional(CONF_PASSIVE, default=DEFAULT_PASSIVE): cv.boolean,
vol.Optional(CONF_ICON): cv.icon,
})
def active_zone(hass, latitude, longitude, radius=0):
"""Find the active zone for given latitud... |
appsembler/mayan_appsembler | apps/registration/models.py | Python | gpl-3.0 | 2,647 | 0.002267 | from __future__ import absolute_import
import requests
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.simplejson import dumps, loads
from common.models import Singleton
from lock_manager import Lock, LockError
from .literals import FORM_SUBMIT_URL, FORM_KEY, F... | return instance.is_registered
@classmethod
def registered_name(cls):
if cls._cached_name:
return cls._cached_name
else | :
instance = cls.objects.get()
try:
dictionary = loads(instance.registration_data)
except ValueError:
dictionary = {}
name_value = dictionary.get('company') or dictionary.get('name')
if name_value:
cls._cached_na... |
MDAnalysis/mdanalysis | testsuite/MDAnalysisTests/core/test_fragments.py | Python | gpl-2.0 | 7,995 | 0.000125 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#... | assert len(fragindices) == len(u.atoms)
# number of unique fragindices must correspond to number of fragments | :
assert len(np.unique(fragindices)) == len(fragments)
# check fragindices dtype:
assert fragindices.dtype == np.intp
#check n_fragments
assert u.atoms.n_fragments == len(fragments)
@pytest.mark.parametrize('u', (
case1(),
case2()
))
def test_... |
luosch/leetcode | python/Word Break.py | Python | mit | 333 | 0 | class Solution(object):
def wordBreak(self, s, wordDict):
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in xrange(1, n + 1):
for j in xrange(0, i):
if dp[j] and s[j:i] in wor | dDict:
dp[i] = True
| break
return dp[-1]
|
stormi/tsunami | src/primaires/salle/commandes/chercherbois/__init__.py | Python | bsd-3-clause | 5,680 | 0.000883 | # -*-coding:Utf-8 -*
# Copyright (c) 2012 NOEL-BARON Léo
# 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... | PROCUREMEN | T
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY O... |
tyagow/FacebookBot | src/bot/tests_bot/test_view.py | Python | mit | 870 | 0.001149 | from unittest import skip
from django.shortcuts import resolve_url as r
from django.test import TestCase
@skip
class BotViewTest(TestCase):
def setUp(self):
fake_message = {
'data': [{
| 'entry': [
{
'messaging': {
'message': {
'text': 'Texto Mensagem'
},
'sender': {
'id': 123,
}... | }]
}
import json
data = json.dumps(str(fake_message))
print(data)
self.response = self.client.post(r('bot:main'), fake_message)
def test_get(self):
self.assertEqual(200, self.response.status_code)
|
SebastienPeillet/PisteCreator | gui/option_Dock.py | Python | gpl-3.0 | 8,879 | 0.001126 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
PisteCreatorDockWidget_OptionDock
Option dock for Qgis plugins
Option dock initialize
-------------------
begin : 2017-07-25
... | *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any... | *
* *
***************************************************************************/
"""
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
import os
from qg... |
tboyce021/home-assistant | homeassistant/components/cloudflare/config_flow.py | Python | apache-2.0 | 5,495 | 0.000546 | """Config flow for Cloudflare integration."""
import logging
from typing import Dict, List, Optional
from pycfdns import CloudflareUpdater
from pycfdns.exceptions import (
CloudflareAuthenticationException,
CloudflareConnectionException,
CloudflareZoneException,
)
import voluptuous as vol
from homeassista... | elf.async_show_form(
step_id="zone",
data_schema=_zone_schema(self.zones),
errors=errors,
)
async def async_step_records(self, user_input: Optional[Dict] = None):
"""Handle the picking the zone records."""
errors = {}
if user_input is not None:
... | return self.async_create_entry(title=title, data=self.cloudflare_config)
return self.async_show_form(
step_id="records",
data_schema=_records_schema(self.records),
errors=errors,
)
async def _async_validate_or_error(self, config):
errors = {}
... |
iksteen/jaspyx | jaspyx/visitor/return_.py | Python | mit | 299 | 0 | from jaspyx.visitor import BaseVisitor
clas | s Return(BaseVisitor):
def visit_Return(self, node):
self.indent()
if node.value is not None:
self.output('return ')
self.visit(node.value)
else:
self.output('return')
| self.finish()
|
zordsdavini/qtile | test/test_config.py | Python | mit | 3,631 | 0.001377 | # Copyright (c) 2011 Florian Mounier
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 Tycho Andersen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without... | h.join(tests_dir, "confi | gs", "basic.py"))
f.keys[0].modifiers = ["nonexistent"]
with pytest.raises(confreader.ConfigError):
f.validate(xc)
f.keys[0].modifiers = ["shift"]
def test_syntaxerr():
xc = xcore.XCore()
with pytest.raises(confreader.ConfigError):
confreader.Config.from_file(xc, os.path.join(tests... |
micromagnetics/magnum.fe | examples/current_wall_motion/run.py | Python | lgpl-3.0 | 2,142 | 0.022409 | """
Current driven domain-wall motion with constant current and spin accumulation.
"""
# Copyright (C) 2011-2015 Claas Abert
#
# This file is part of magnum.fe.
#
# magnum.fe 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 Fre... | = 1e-3,
beta = 0.9,
beta_prime = 0.8,
lambda_sf = 10e-9,
lambda_j = 4e-9,
c = 3.125e-3
),
m = Expression(('1.0 - 2*(x[0] < 0.0)', 'x[0] > -10.0 && x[0] < 10.0', '0.0')),
s = Constant((0.0, 0.0, 0.0)),
j = Constant((0.0, 0.0, 0.0))
)
# normalize since ini... | gField("FK"),
SpinTorque()
])
spindiff = SpinDiffusion()
# relax
for j in range(200): state.step(llg, 1e-12)
# apply constant current
state.j = Constant((3e12, 0, 0))
state.t = 0.0
# prepare log files
mfile = File("data/m.pvd")
sfile = File("data/s.pvd")
for j in range(1000):
# save fields every 10th step
i... |
baverman/vial-pytest | vial-plugin/vial_pytest/plugin.py | Python | mit | 3,367 | 0.001188 | import sys
import time
import os.path
from collections import Counter
from vial import vfunc, vim, dref
from vial.utils import redraw, focus_window
from vial.widgets import make_scratch
collector = None
def get_collector():
global collector
if not collector:
collector = ResultCollector()
return... | rom multiprocessing.connection import Client, arbitrary_address
addr = arbitrary_address('AF_UNIX')
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pt.py | ')
executable = executable or sys.executable
args = [executable, filename, addr, '-q']
if match:
args.append('-k %s' % match)
environ = None
if env:
environ = os.environ.copy()
environ.update(env)
log = open('/tmp/vial-pytest.log', 'w')
if files:
args.exte... |
Yelp/paasta | paasta_tools/monitoring/check_mesos_active_frameworks.py | Python | apache-2.0 | 1,748 | 0 | #!/usr/bin/env python
# Copyright 2015-2016 Yelp 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 ... | ons under the License.
import argparse
import | sys
from a_sync import block
from paasta_tools.mesos.exceptions import MasterNotAvailableException
from paasta_tools.mesos_tools import get_mesos_master
from paasta_tools.metrics.metastatus_lib import assert_frameworks_exist
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
... |
JonnyWong16/plexpy | lib/websocket/tests/test_url.py | Python | gpl-3.0 | 14,537 | 0.002958 | # -*- coding: utf-8 -*-
#
"""
test_url.py
websocket - WebSocket client library for Python
Copyright 2021 engn33r
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/... | self.assertEqual(p[1], 8080)
self.assertEqual(p[2], "/r")
self.assertEqual(p[3], False)
| p = parse_url("ws://www.example.com:8080/")
self.assertEqual(p[0], "www.example.com")
self.assertEqual(p[1], 8080)
self.assertEqual(p[2], "/")
self.assertEqual(p[3], False)
p = parse_url("ws://www.example.com:8080")
self.assertEqual(p[0], "www.example.com")
s... |
open-synergy/opnsynid-stock-reporting | opnsynid_stock_inventory_result_aeroo_report/__openerp__.py | Python | agpl-3.0 | 629 | 0.00159 | # -*- cod | ing: utf-8 -*-
# Copyright 2016 OpenSynergy Indonesia
# Copyright 2022 PT. Simetri Sinergi Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Stock Inventory Result Aeroo Report",
"version": "8.0.1.0.0",
"summary": "Adds Stock Inve | ntory Result Report",
"website": "https://simetri-sinergi.id",
"author": "OpenSynergy Indonesia, PT. Simetri Sinergi Indonesia",
"category": "Stock",
"depends": ["stock", "report_aeroo"],
"data": ["reports/stock_inventory_result.xml", "views/stock_inventory_view.xml"],
"license": "AGPL-3",
"... |
centrifugal/examples | python_django_chat_tutorial/mysite/chat/urls.py | Python | mit | 391 | 0 | from django.urls import path, re_path
from . import views
urlpatterns = [
path('', views.index, name='index'),
re_path('room/(?P<room_name>[A-z0-9_-]+)/', views.room, name='room'),
path('centrifugo/connect/', views.connect, name='connect'),
path( | 'centrifugo/subscribe/', views.subscribe, name='subscribe'),
path('centrifugo/publish/', views.publ | ish, name='publish'),
]
|
beckastar/django | tests/generic_views/test_list.py | Python | bsd-3-clause | 10,510 | 0.001142 | from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, override_settings
from django.views.generic.base import View
from django.utils.encoding import force_str
from .models import Author, Artist
class ListViewTests(TestCase):
fixtures = ... | 'view'], View)
self.assertIs(res.context['author_list'], res.context['object_list'])
self.assertIsNone(res.context['paginator'])
self.assertIsNone(res.context['page_obj'])
self.assertFalse(res.context['is_paginated'])
def test_paginated_queryset(self):
self._make_authors(100... | /')
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
self.assertEqual(len(res.context['object_list']), 30)
self.assertIs(res.context['author_list'], res.context['object_list'])
self.assertTrue(res.context['is_paginated'])
... |
JorjMcKie/PyMuPDF-Utilities | animations/quad-show2.py | Python | gpl-3.0 | 4,283 | 0.000467 | """
Created on Thu Jan 3 07:05:17 2019
@author: Jorj
@copyright: (c) 2019 Jorj X. McKie
@license: GNU GPL 3.0
Purpose
--------
Visualize function "drawOval" by using a quadrilateral (tetrapod) as parameter.
For demonstration purposes, oval creation is placed in a function, which
accepts an integer parameter. This v... | of the page
# ------------------------------------------------------------------------------
# main program
# ------------------------------------------------------------------------------
png = make_oval(0.0) # create first picture
img = sg.Image(data=png) # def | ine form image element
layout = [[img]] # minimal layout
form = sg.FlexForm(
"drawOval: left-right points exchange", layout, finalize=True
) # define form
loop_count = 1 # count the number of loops
t0 = mytime() # start a timer
i = 0
add = 1
while True: # loop forever
event, values = form.Read(timeout=0)... |
tobspr/panda3d | direct/src/leveleditor/LevelEditor.py | Python | bsd-3-clause | 1,521 | 0.000657 | """
This is just a sample code.
LevelEditor, ObjectHandler, ObjectPalette should be rewritten
to be game specific.
"""
from .LevelEditorUI import *
from .LevelEditorBase import *
from .ObjectMgr impo | rt *
from .AnimMgr import *
from .ObjectHandler import *
from .ObjectPalette import *
from .ProtoPalette import *
class LevelEditor(LevelEditorBase):
""" Class for Panda3D LevelEditor """
def __init__(self):
LevelEditorBase.__init__(self)
# define your own config | file similar to this
self.settingsFile = os.path.dirname(__file__) + '/LevelEditor.cfg'
# If you have your own ObjectPalette and ObjectHandler
# connect them in your own LevelEditor class
self.objectMgr = ObjectMgr(self)
self.animMgr = AnimMgr(self)
self.objectPalette = ... |
prymitive/upaas-common | upaas/builder/exceptions.py | Python | gpl-3.0 | 890 | 0 | # -*- coding: utf-8 -*-
"""
:copyright: Copyright 2013-2014 by Łukasz Mierzwa
:contact: [email protected]
"""
class InvalidConfiguration(Exception):
| """
Raised if upaas-builder configuration is invalid.
"""
pass
class BuildError(Exception):
"""
General clas | s for catching any build error.
"""
pass
class OSBootstrapError(BuildError):
"""
Raised in case of errors during os image bootstraping.
"""
pass
class PackageSystemError(BuildError):
"""
Raised in case of system errors during package build. This does not cover
errors caused by pa... |
palashahuja/myhdl | myhdl/test/conversion/general/test_interfaces1.py | Python | lgpl-2.1 | 2,907 | 0.020984 |
import sys
from myhdl import *
from myhdl import ConversionError
from myhdl.conversion._misc import _error
from myhdl.conversion import analyze, verify
class MyIntf(object):
def __init__(self):
self.x = Signal(intbv(2,min=0,max=16))
self.y = Signal(intbv(3,min=0,max=18))
def m_one_level(clock,re... | e():
clock = Signal(bool(0))
reset = ResetSignal(0,active=0,async=True)
ia = MyIntf()
ib = MyIntf()
tb_dut = m_one_level(clock,reset,ia,ib)
@instance
def tb_clk():
clock.next = False
yield delay(10)
while True:
clock.next = not clock
yield de... | tb_stim():
reset.next = False
yield delay(17)
reset.next = True
yield delay(17)
for ii in range(7):
yield clock.posedge
assert ia.x == 3
assert ia.y == 4
print("%d %d %d %d"%(ia.x,ia.y,ib.x,ib.y))
raise StopSimulation
return tb_dut... |
trevorstephens/gplearn | gplearn/tests/test_examples.py | Python | bsd-3-clause | 10,059 | 0 | """Testing the examples from the documentation."""
# Author: Trevor Stephens <trevorstephens.com>
#
# License: BSD 3 clause
import numpy as np
from sklearn.datasets import load_boston, load_breast_cancer
from sklearn.datasets import m | ake_moons, make_circles, make_classification
from sklearn.linear_model import Ridge
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Stan | dardScaler
from sklearn.utils._testing import assert_equal, assert_almost_equal
from sklearn.utils.validation import check_random_state
from gplearn.genetic import SymbolicClassifier, SymbolicRegressor
from gplearn.genetic import SymbolicTransformer
from gplearn.functions import make_function
def test_symbolic_regre... |
refweak/refweak_scripts | ncbifetch/tests/test_basic.py | Python | gpl-3.0 | 451 | 0.006652 | # -*- coding: utf-8 -*-
import sys
sys.path.append('..')
from ncbifetch import main
import uni | ttest
class BasicTestSuite(unittest.TestCase):
"""Basic test cases."""
def test_absolute_truth_and_meaning(self):
assert True
def test_test(self):
assert main.x() == 'ping'
def test_sal_wgs(self):
main.fetch_wgs(organism='Salmonella enterica')
assert True
if __name... | unittest.main() |
akelm/YAMS | yams/em_int.py | Python | gpl-3.0 | 715 | 0.06014 | import numpy as np
def em_int(wspE,wspM,k,RB,xp2inv,d_el,d_m,Dd_el,cc4,cc3,Cepsilon):
fi_el=(wspE[0]*RB[2] + wspE[1]*RB[0])/k
Dfi_el=(wspE[0]*RB[3] + wspE[1]*RB[1])/k
fi_m=(wspM[0]*RB[2] + wspM[1]*RB[0])/k
Dfi_m=(wspM[0]*RB[3] + wspM[1]*RB[1])/k
int_perp = xp2inv**2* np.matmul(np.nan_to_num(-Dfi_el*fi_el.conj()*d_... | nj())*int_para).real
return (perp,para)
def wsp(M,T,RB):
T=list(np.rollaxis(T,2,0))
M=list(np.rollaxis(M,2,0))
w= (T[0]*RB[0]+T[1]*RB[1])/(T[0]*M[0]-T[1]*M[1])
return np.nan_to_num(w.con | j()*w)
|
piotrek-golda/CivilHubIndependantCopy | places_core/admin.py | Python | gpl-3.0 | 596 | 0 | # -*- coding: utf-8 -*-
from django.contrib import | admin
from django.utils.translation import ugettext as _
from .models import AbuseReport, SearchTermRecord
admin.site.register(AbuseReport)
class SearchTermAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'ip_address', 'get_user_full_name', )
search_fields = ('term', )
| def get_user_full_name(self, obj):
if obj.user is None:
return "(%s)" % _(u"None")
return obj.user.get_full_name()
get_user_full_name.short_description = "user"
admin.site.register(SearchTermRecord, SearchTermAdmin)
|
eneldoserrata/marcos_openerp | addons/account_periodical_invoicing/periodical_invoicing.py | Python | agpl-3.0 | 23,307 | 0.006608 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2012 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com) All Rights Reserved.
# Pedro M. Baeza <pedro.baeza@serviciosbaeza... | return date + timedelta(days = interval)
elif unit == 'weeks':
return date + timedelta(weeks=interval)
elif unit == 'months':
return date + relativedelta(months=interval)
elif unit == 'years':
return date + relativedelta(years=interval)
def... | _previous_term_date(self, date, unit, interval):
"""
Get the date that results on decrementing given date an interval of time in time unit.
@param date: Original date.
@param unit: Interval time unit.
@param interval: Quantity of the time unit.
@rtype: date
@retur... |
pqtoan/mathics | mathics/core/definitions.py | Python | gpl-3.0 | 25,568 | 0.001252 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
import six
import six.moves.cPickle as pickle
import os
import base64
import re
import bisect
from collections import defaultdict
from mathics.core.expression import Expression, Symbol, Stri... | )
self.builtin.update(self.user)
self.user = {}
self.clear_cache()
def clear_cache(self, name=None):
# the definitions cache (self.definitions_cache) caches (incomplete and complete) names -> Definition(),
# e.g. "xy" -> d and "MyContext`xy" -> d. we need to clea... | combined from a builtin and a user definition and some content in the
# user definition is updated) or if the lookup rules change and we could end up at a completely different
# Definition.
# the lookup cache (self.lookup_cache) caches what lookup_name() does. we only need to update this if som... |
frankk00/realtor | scripts/batch/live_interactive.py | Python | bsd-3-clause | 828 | 0 | #!/usr/bin/python2.5
#
# Copyright 2009 Roman Nurik
#
# 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... | ributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permission | s and
# limitations under the License.
"""Local interactive console for a remote app, using the remote API."""
__author__ = '[email protected] (Roman Nurik)'
import code
import remote_client
code.interact('App Engine interactive console', None, locals())
|
xmnlab/minilab | labtrans/daq/MultiChannelAnalogInput.py | Python | gpl-3.0 | 2,739 | 0.013874 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 16:11:48 2013
@author: ivan
"""
import numpy
import time
from PyDAQmx.DAQmxFunctions import *
from PyDAQmx.DAQmxConstants import *
terminals = {}
terminals['Dev1'] = ['Dev1/ai%s' % line for line in range(0, 2)]
terminals['Dev2'] = ['Dev2/ai%s' % line for line in ra... | elf.limit = dict([(name, limit) for name in self.physicalChannel])
else:
self.limit = dict([(name, limit[i]) for i,name in enumerate(self.physicalChannel)])
if reset:
DAQmxResetDevice(physicalChannel[0].split('/')[0] )
def configure(self):
# Create one task handle pe... | ysicalChannel:
DAQmxCreateTask("",byref(taskHandles[name]))
DAQmxCreateAIVoltageChan(taskHandles[name],name,"",DAQmx_Val_RSE,
self.limit[name][0],self.limit[name][1],
DAQmx_Val_Volts,None)
self.taskHandles = taskHa... |
infothrill/flask-socketio-dbus-demo | sensors/tdbus_upower.py | Python | mit | 7,190 | 0.002643 | # -*- coding: utf-8 -*-
'''
This module presents a little code to deal with battery status using DBUS and
UPower on Linux
@author: pkremer
'''
import sys
import logging
from six.moves import filter
from functools import partial
import six
import tdbus
# 'constants'
UPOWER_NAME = 'org.freedesktop.UPower'
UPOWER_DEV... | return convert_DBUS_to_python(
conn.call_method(device,
member='Get',
interface=DBUS_PROP_NAME,
destination=UPOWER_NAME,
format='ss',
| args=(UPOWER_DEVICE_IFACE, attribute)
).get_args()[0]
)
class UPowerDeviceHandler(tdbus.DBusHandler):
def __init__(self, connect, devices):
'''
A DBUS signal handler class for the org.freedesktop.UPower.Device
'C... |
bundgus/python-playground | matplotlib-playground/examples/pylab_examples/tricontour_demo.py | Python | mit | 4,613 | 0.004552 | """
Contour plots of unstructured triangular grids.
"""
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
import math
# Creating a Triangulation without specifying the triangles results in the
# Delaunay triangulation of the points.
# First create the x and y coordinates of the points.
n... | 4, 73, 45],
[72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40],
[72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, | 73, 40],
[42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38],
[33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]])
# Rather than create a Triangulation object, can simply pass x, y and triangles
# arrays to tripcolor directly. It would be better to use a Triangulation
# object if the same... |
philipn/sycamore | Sycamore/i18n/fi.py | Python | gpl-2.0 | 2,372 | 0.038786 | # -*- coding: iso-8859-1 -*-
# Text translations for Suomi (fi).
# Automatically generated - DO NOT EDIT, edit fi.po instead!
meta = {
'language': 'Suomi',
'maintainer': '***vacant***',
'encoding': 'iso-8859-1',
'direction': 'ltr',
}
text = {
'''Create this page''':
'''Luo tämä sivu''',
'''Edit "%(pagename)s"''... | ot''',
'''Revision History''':
'''Versiohistoria''',
'''Date''':
'''Päivämäärä''',
'''Size''':
'''Koko''',
'''Editor''':
'''Editori''',
'''Comment''':
'''Huomautus''',
'''view''':
'''näytä''',
'''revert''':
'''palauta''',
'''Show "%(title)s"''':
'''Näytä "%(title)s"''',
'''You are not allowed to revert this page!''':
'... | rsio''',
'''Sycamore Version''':
'''Sycamore Versio''',
'''4Suite Version''':
'''4Suite Versio''',
'''del''':
'''poista''',
'''get''':
'''hae''',
'''edit''':
'''muokkaa''',
'''No attachments stored for %(pagename)s''':
'''Sivulla %(pagename)s ei ole liitteitä''',
'''attachment:%(filename)s of %(pagename)s''':
'''liite:... |
pandas-dev/pandas | pandas/tests/indexes/categorical/test_category.py | Python | bsd-3-clause | 14,639 | 0.000615 | import numpy as np
import pytest
from pandas._libs import index as libindex
from pandas._libs.arrays import NDArrayBacked
import pandas as pd
from pandas import (
Categorical,
CategoricalDtype,
)
import pandas._testing as tm
from pandas.core.indexes.api import (
CategoricalIndex,
Index,
)
from pandas.... | : np.zeros(shape=(3), dtype=np.bool_),
False: np.zeros(shape=(3), dtype=np.bool_),
| },
),
(
list("abb"),
list("abc"),
{
"first": np.array([False, False, True]),
"last": np.array([False, True, False]),
False: np.array([False, True, True]),
},... |
RNAer/Calour | calour/tests/test_amplicon_experiment.py | Python | bsd-3-clause | 7,382 | 0.001761 | # ----------------------------------------------------------------------------
# Copyright (c) 2016--, Calour development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------------------------------... | samp,
min_reads=1000, normalize=10000)
def test_filter_by_taxonomy(self):
# default - substring and keep matching
exp = self.test1.filter_by_taxonomy('proteobacteria')
self.assertEqual(exp.shape[1], 2)
self.assertEqual(set(exp.feature_metadata.i... | est1.sample_metadata)
# test with list of values and negate
exp = self.test1.filter_by_taxonomy(['Firmicutes', 'proteobacteria'], negate=True)
# should have all these sequences
fids = ['AA', 'AT', 'TT', 'TG', 'GG', 'badfeature']
self.assertListEqual(fids, exp.feature_metadata.in... |
niwinz/djorm-ext-pgjson | testing/pg_json_fields/forms.py | Python | bsd-3-clause | 169 | 0 | # -*- coding: utf-8 -*-
from django.forms.models import ModelForm
| from .models import IntModel
class IntArrayForm(ModelForm):
class Meta:
model = In | tModel
|
iulian787/spack | var/spack/repos/builtin.mock/packages/dtbuild3/package.py | Python | lgpl-2.1 | 455 | 0 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project D | evelopers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Dtbuild3(Packa | ge):
"""Simple package which acts as a build dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/dtbuild3-1.0.tar.gz"
version('1.0', '0123456789abcdef0123456789abcdef')
|
imincik/pkg-qgis-1.8 | python/plugins/db_manager/db_plugins/plugin.py | Python | gpl-2.0 | 32,055 | 0.035314 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QuantumGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.... | (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ..db_plugins import create... | bPlugin
from .html_elems import HtmlParagraph, HtmlTable
class BaseError(Exception):
"""Base class for exceptions in the plugin."""
def __init__(self, e):
msg = e if isinstance(e, (str,unicode,QString)) else e.message
try:
msg = unicode( msg )
except UnicodeDecodeError:
msg = unicode( msg, 'utf-8' )
E... |
mjtamlyn/django | tests/template_tests/filter_tests/test_escapejs.py | Python | bsd-3-clause | 2,409 | 0.002906 | from django.template.defaultfilters import escapejs_filter
from django.test import SimpleTestCase
from django.utils.functional import lazy
from ..utils import setup
class EscapejsTests(SimpleTestCase):
@setup({'escapejs01': '{{ a|escapejs }}'})
def test_escapejs01(self):
output = self.engine.render_... | tput, 'testing\\u000D\\u000Ajavascript '
'\\u0027string\\u0022 \\u003Cb\\u003E'
'escaping\\u003C/b\\u003E')
@setup({'escapejs02': '{% autoescape off %}{{ a|escapejs }}{% endautoesca | pe %}'})
def test_escapejs02(self):
output = self.engine.render_to_string('escapejs02', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'})
self.assertEqual(output, 'testing\\u000D\\u000Ajavascript '
'\\u0027string\\u0022 \\u003Cb\\u003E'
... |
JoaoRodrigues/pdb-tools | tests/test_pdb_chain.py | Python | apache-2.0 | 4,623 | 0.000649 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 João Pedro Rodrigues
#
# 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
#
# Unl... | , 'dummy.pdb')]
# Execute the script
self.exec_module()
# Validate results
self.assertEqual(self.retcode, 0) # ensure the program exited OK.
self.assertEqual(len(self.stdout), 204) # no lines deleted
self.assertEqual(len(self.stderr), 0) # no errors
records ... | lf.assertEqual(unique_chain_ids, [' '])
def test_two_options(self):
"""$ pdb_chain -X data/dummy.pdb"""
sys.argv = ['', '-X', os.path.join(data_dir, 'dummy.pdb')]
self.exec_module()
self.assertEqual(self.retcode, 0)
self.assertEqual(len(self.stdout), 204)
self.ass... |
crossroadchurch/paul | openlp/plugins/alerts/lib/alertsmanager.py | Python | gpl-2.0 | 4,307 | 0.002322 | # -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection | #
# ------------------------------------------------------ | --------------------- #
# Copyright (c) 2008-2015 OpenLP Developers #
# --------------------------------------------------------------------------- #
# This program is free software; you can redistribute it and/or modify it #
# under the terms of the GNU General Public License as p... |
JoeLaMartina/aima-python | submissions/Karman/vacuum2Runner.py | Python | mit | 6,342 | 0.00678 | import agents as ag
import envgui as gui
# change this line ONLY to refer to your project
import submissions.Karman.vacuum2 as v2
# ______________________________________________________________________________
# Vacuum environment
class Dirt(ag.Thing):
pass
class VacuumEnvironment(ag.XYEnvironment):
"""The... | ------------------------------------')
testVacuum('Two Cells, Agent on Left:')
testVacuum('Two Cells, Agent on Right:', vloc=(2,1))
testVacuum('Two Cells, Agent on Top:', w=3, h=4,
dloc=[(1,1), (1,2)], vloc=(1,1) )
testVacuum('Two Cells, Agent on Bottom:', w=3, h=4,
| dloc=[(1,1), (1,2)], vloc=(1,2) )
testVacuum('Five Cells, Agent on Left:', w=7, h=3,
dloc=[(2,1), (4,1)], vloc=(1,1), limit=12)
testVacuum('Five Cells, Agent near Right:', w=7, h=3,
dloc=[(2,1), (3,1)], vloc=(4,1), limit=12)
testVacuum('Five Cells, Agent on Top:', w=3, h=7,
dloc=[(1,2... |
google/clusterfuzz | src/clusterfuzz/_internal/bot/untrusted_runner/remote_process.py | Python | apache-2.0 | 3,341 | 0.010177 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | est.env_copy:
args['env_copy'] = request.env_copy
protobuf_utils.get_protobuf_field(args, request, 'testcase_run')
protobuf_utils.get_protobuf_field(args, request, 'ignore_children')
return_code, execution_time, output = process_handler.run_process(**args)
response = untrusted_runner_pb2.RunProcessRespons... | =output)
return response
|
plotly/python-api | packages/python/plotly/plotly/graph_objs/layout/yaxis/title/_font.py | Python | mit | 8,542 | 0.000585 | from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType
import copy as _copy
class Font(_BaseLayoutHierarchyType):
# class properties
# --------------------
_parent_path_str = "layout.yaxis.title"
_path_str = "layout.yaxis.title.font"
_valid_props = {"color", "family"... | it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cl | oud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT"... |
SINGROUP/pycp2k | pycp2k/classes/_qm_non_adaptive1.py | Python | lgpl-3.0 | 686 | 0.001458 | from pycp2k.inputsection import InputSection
from ._qm_kind1 import _qm_kind1
class _qm_non_adaptive1(InputSection):
def __init__(self):
InputSection.__init__(self)
self.QM_KIND_list = []
self._name = "QM_NON_ADAPTIVE"
self._repeated_subsections = {'QM_KIND': '_qm_kind1'}
s... | rameters=None) | :
new_section = _qm_kind1()
if section_parameters is not None:
if hasattr(new_section, 'Section_parameters'):
new_section.Section_parameters = section_parameters
self.QM_KIND_list.append(new_section)
return new_section
|
hpcloud-mon/monasca-perf | influx_test/influxparawrite.py | Python | apache-2.0 | 1,308 | 0.017584 | from multiprocessing import Process
import time
import sys
count = 1000 #Note!!!!!: This needs to be a multiple of env.numThreads, else tests will likely fail with the wrong count(s)
actionWaitTime = 5
class InfluxParaWrite(object):
def __init__(self,env):
self.env = env
self.count = count
... | .env.numThreads != 0:
print "influxparawrite.count is not a multiple of env.numThreads"
sys.exit(1)
self.actionWaitTime = actionWaitTime
def start(self,write_node,action_node,action,tsname):
self.write_node = write_node
self.action_node = action_node
self.acti... | = tsname
p_write = Process(target=self.doWrites,args=(write_node,tsname))
p_write.start()
p_action = Process(target=self.doAction, args=(action_node,action))
p_action.start()
p_action.join()
p_write.join()
def doAction(self,node,action):
if len(action) == 0: r... |
dana-i2cat/felix | optin_manager/src/python/openflow/common/permissions/tests/views.py | Python | apache-2.0 | 3,108 | 0.002574 | '''
Created on Jun 8, 2010
Contains views for permissions tests
@author: jnaous
'''
from django.shortcuts import get_object_or_404
from models import PermissionTestClass
from ..decorators import require_objs_permissions_for_view
from ..utils import get_user_from_req, get_queryset
from django.http import HttpResponse,... | T":
give_permission_to(user, permission, target)
redirect_to = redirect | _to or reverse("test_view_crud")
return HttpResponseRedirect(redirect_to)
else:
return HttpResponse(
"""
Do you want to get %s permission for obj %s?
<form action="" method="POST">
<input type="submit" value="Yes" />
<input type="button" value="No" onclick="document.location='%s'" />
</form>
""" % (... |
rentalita/django-layoutdemo | src/python/layoutdemo/default/urls.py | Python | mit | 276 | 0.003623 | # -*- coding: utf-8 -*-
from djan | go.conf.urls.defaults import patterns, url
from . import tasks
from . import views
urlpatterns = patterns('',
url(r'^$', views.index | , name='layoutdemo_index'),
)
# Local Variables:
# indent-tabs-mode: nil
# End:
# vim: ai et sw=4 ts=4
|
unicef/un-partner-portal | backend/unpp_api/apps/externals/urls.py | Python | apache-2.0 | 707 | 0.002829 | from django.conf.urls import url
from externals.views import (
PartnerVendorNumberAPIView,
PartnerExternalDetailsAPIView,
PartnerBasicInfoAPIView,
)
urlpatterns = [
url(r'^vendor-number/partner/$', PartnerVendorNumberAPIView.as_view(), name="vendor-number-create"),
url(r'^vendor-number/partner/(?... | r'^partner-details/(?P<agency_id>\d+)/(?P<partner_id>\d+)/$',
PartnerExternalDetailsAPIView.as_view(),
| name="partner-external-details"
),
url(
r'^partner-basic-info/$',
PartnerBasicInfoAPIView.as_view(),
name="partner-basic-info"
),
]
|
rushter/MLAlgorithms | examples/nnet_rnn_binary_add.py | Python | mit | 2,518 | 0.001589 | import logging
from itertools import combinations, islice
import numpy as np
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from mla.metrics import accuracy
from mla.neuralnet import NeuralNet
from mla.neuralnet.layers impor... | y_test = y_test[0:test_b]
return X_train, X_test, y_train, y_test
def addition_problem(ReccurentLayer):
X_train, X_test, y_train, y_test = addition_dataset(8, 5000)
print(X_train.shape, X_test.shape)
model = NeuralNet(
layers=[ReccurentLayer, TimeDistributedDense(1), Activation("sigmoid")],... | ain)
predictions = np.round(model.predict(X_test))
predictions = np.packbits(predictions.astype(np.uint8))
y_test = np.packbits(y_test.astype(np.int))
print(accuracy(y_test, predictions))
# RNN
# addition_problem(RNN(16, parameters=Parameters(constraints={'W': SmallNorm(), 'U': SmallNorm()})))
# LSTM
... |
hypernicon/pyec | pyec/tests/test_history.py | Python | mit | 1,736 | 0.011521 | """
Copyright (C) 2012 Alan J Lockett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,... | URPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import numpy as np
from pyec.config import Config
import unittest
class TestHistory(unittest.TestCase):
def test_base(self):
cfg = Config()
history = History(cfg)
self.assertEqual(history.evals, 0)
self.assertEqual(history.printEvery, 10000... |
mibitzi/pwm | test/test_workspaces.py | Python | mit | 8,632 | 0 | # Copyright (c) 2013 Michael Bitzi
# Licensed under the MIT license http://opensource.org/licenses/MIT
import unittest
from unittest.mock import create_autospec, patch
from pwm.ffi.xcb import xcb
import pwm.bar
import pwm.workspaces
import pwm.windows
from pwm.config import config
import test.util as util
class Tes... | ), 0)
def test_switch(self):
pwm.workspaces.switch(1)
self.assertEqual(pwm.workspaces.current(),
| pwm.workspaces.workspaces[1])
def test_switch_focus(self):
util.create_window()
pwm.workspaces.switch(1)
self.assertEqual(pwm.windows.focused, None)
def test_opened(self):
# Create window on current workspace (idx=0)
util.create_window()
pwm.workspaces.swit... |
vgonisanz/piperoScripts | python2/usage/usage-withconf-sample.py | Python | mit | 803 | 0.011208 | from configur | ation import *
import argparse
def print_configuration_vars():
"This prints confi | guration variables"
print "This prints configuration variables:"
print "-------------------------------------"
print "var_foo value is: " + var_foo
print "var_var value is: " + var_var
print "var_home value is: " + var_home
return
parser = argparse.ArgumentParser(description="Load easy configuration"... |
drdoctr/doctr | doctr/_version.py | Python | mit | 15,755 | 0 |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains t... | if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
# if there is a tag, this yields TAG-NUM-gHEX[-dirty]
# if there are no tags, | this yields HEX[-dirty] (no NUM)
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long"],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' faile... |
youtube/cobalt | build/android/test_wrapper/logdog_wrapper.py | Python | bsd-3-clause | 4,633 | 0.00885 | #!/usr/bin/env vpython
# Copyright 2016 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.
"""Wrapper for adding logdog streaming support to swarming tasks."""
import argparse
import contextlib
import logging
import os
impor... | _args
else:
test_cmd = extra_cm | d_args
test_env = dict(os.environ)
logdog_cmd = []
with tempfile_ext.NamedTemporaryDirectory(
prefix='tmp_android_logdog_wrapper') as temp_directory:
if not os.path.exists(args.logdog_bin_cmd):
logging.error(
'Logdog binary %s unavailable. Unable to create logdog client',
arg... |
CospanDesign/nysa-gui | NysaGui/common/nysa_bus_view/wishbone_controller.py | Python | gpl-2.0 | 21,215 | 0.009522 | # -*- coding: utf-8 -*-
# Distributed under the MIT licesnse.
# Copyright (c) 2013 Dave McCoy ([email protected])
#Permission is hereby granted, free of charge, to any person obtaining a copy of
#this software and associated documentation files (the "Software"), to deal in
#the Software without restriction,... | keys():
self.model.set_default_board_project(config_dict["board"])
else:
self.model.load | _config_dict(config_dict)
#self.model.initialize_graph(debug = True)
self.model.initialize_graph(debug = False)
#self.initialize_view()
def initialize_view(self):
self.s.Debug( "Add Master")
m = Master(scene = self.scene)
self.boxes["master"] = m
self.s.Debu... |
vatslav/perfectnote | keepnote/gui/editor_richtext.py | Python | gpl-2.0 | 52,254 | 0.00733 | """
KeepNote
Editor widget in main window
"""
#
# KeepNote
# Copyright (c) 2008-2009 Matt Rasmussen
# Author: Matt Rasmussen <[email protected]>
#
# 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... | filename) and ("\\" not in filename)
class NodeIO (RichTextIO):
"""Read/Writes the contents of a RichTextBuffer to disk"""
def __init__(self):
RichTextIO.__init__(self)
self._node = None
self._image_files = set()
self._saved_image_files = set()
def set_node(self, node):
... | , filename, title)
def load(self, textview, textbuffer, filename):
RichTextIO.load(self, textview, textbuffer, filename)
def _load_images(self, textbuffer, html_filename):
"""Load images present in textbuffer"""
self._image_files.clear()
RichTextIO._load_image... |
meta-it/misc-addons | account_invoice_dates/__openerp__.py | Python | lgpl-3.0 | 601 | 0 | # -*- coding: utf-8 -*-
{
"name": """Start-End dates in invoice and analytic lines""",
"summary": """Technical core for other modules""",
"category": "Accounting",
"images": [],
"version": "1.0.0",
"author": "IT-Projects LLC, Ivan Yelizariev",
| "website": "https://it-projects.info",
"license": "LGPL-3",
# "price": | 9.00,
# "currency": "EUR",
"depends": [
"account",
],
"external_dependencies": {"python": [], "bin": []},
"data": [
"views.xml",
],
"demo": [
],
"installable": False,
"auto_install": False,
}
|
cbeing/remoteSlideShow | third_party/pypoppler-qt4/configure.py | Python | mit | 7,528 | 0.009033 | import os, sys
import commands
import optparse
import shutil
INSTALL_DIR = ""
BASE_DIR = os.path.dirname(__file__)
SIP_FILE = "poppler-qt4.sip"
BUILD_DIR = "build"
SBF_FILE = "QtPoppler.sbf"
def _cleanup_path(path):
"""
Cleans the path:
- Removes traling / or \
"""
path = path.rstrip('/')
... | os.path.join(BASE_DIR, BUILD_DIR)
if os.path.exists(dir):
return
try:
os.mkdir(dir)
except:
print >> sys.stderr, "ERROR: Unable to create the build directory (%s)" % dir
sys.exit(1)
def run_sip(pyqtcfg):
create_build_dir()
cmd = [pyqtcfg.sip_bin,
| "-c", os.path.join(BASE_DIR, BUILD_DIR),
"-b", os.path.join(BUILD_DIR, SBF_FILE),
"-I", pyqtcfg.pyqt_sip_dir,
pyqtcfg.pyqt_sip_flags,
os.path.join(BASE_DIR, SIP_FILE)]
os.system( " ".join(cmd) )
def generate_makefiles(pyqtcfg, popplerqtcfg, opts):
from PyQt4... |
Kaggle/docker-python | tests/test_tensorflow_addons.py | Python | apache-2.0 | 665 | 0.003008 | import unittest
import tensorflow as tf
import tensorflow_addons as tfa
class TestTensorflowAddons(unittest.TestCase):
def test_tfa_image(self):
img_raw = tf.io.read_file('/input/tests/data/dot.png')
img = tf.io.decode_image(img_raw)
img = tf.image.convert_image_dtype(img, tf.float32)
... | self.assertEqual([1, 1, 3], mean.shape)
# This test exercises TFA Custom Op. See: b/145555176
def test_gelu(self):
x = tf.constant([[0.5, 1.2, -0.3]])
layer = tfa.layers.G | ELU()
result = layer(x)
self.assertEqual((1, 3), result.shape) |
hryamzik/ansible | test/units/conftest.py | Python | gpl-3.0 | 783 | 0.001277 | """Monkey patch os._exit when running under coverage so we don't lose co | verage data in forks, such as with `pytest - | -boxed`."""
import gc
import os
try:
import coverage
except ImportError:
coverage = None
try:
test = coverage.Coverage
except AttributeError:
coverage = None
def pytest_configure():
if not coverage:
return
coverage_instances = []
for obj in gc.get_objects():
if isinstan... |
lavalamp-/ws-backend-community | wselasticsearch/query/dns/enumeration.py | Python | gpl-3.0 | 1,098 | 0.002732 | # -*- coding: utf-8 -*-
from __ | future__ import absolute_import
from .base import BaseDomainNameScanQuery
class SubdomainEnumerationQuery(BaseDomainNameScanQuery):
"""
This is an Elasticsearch query class for querying SubdomainEnumerationModel objects.
"""
@classmethod
def get_queried_class(cl | s):
from wselasticsearch.models import SubdomainEnumerationModel
return SubdomainEnumerationModel
def filter_by_enumeration_method(self, method):
"""
Apply a filter to this query that restricts results to only those results found by
the given method.
:param method: T... |
samuelmaudo/yepes | tests/datamigrations/tests_fields.py | Python | bsd-3-clause | 89,595 | 0.001184 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
import csv
from datetime import date, datetime, time
from decimal import Decimal
from io import open
import os
from unittest import expectedFailure
import warnings
from django import test
from django.test.utils import override_settings
from django.utils ... | Model.objects.all())
self.assertEqual(len(objs), len(self.expectedResults))
for obj, result in zip(objs, s | elf.expectedResults):
self.assertEqual(obj.boolean, result[0])
self.assertEqual(obj.boolean_as_string, result[0])
self.assertEqual(obj.null_boolean, result[1])
self.assertEqual(obj.null_boolean_as_string, result[1])
# Export data to a file.
with export_se... |
brandonw/personal-site | personal-site/blog/views.py | Python | bsd-3-clause | 1,941 | 0.003606 | from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from blog.models import Post
from t... | (Feed):
title = "Brandon Waskiewicz's blog"
link = '/blog/'
description = 'Inside my head'
def items(self):
return Post.objects.filter(is_published=True).order_by('-pub_date')
def item_title(self, item):
return item.name
def item_description(self, item) | :
return item.get_preview()
class BlogAtomFeed(BlogRssFeed):
feed_type = Atom1Feed
subtitle = BlogRssFeed.title
|
marcosfede/algorithms | linkedlist/reverse.py | Python | gpl-3.0 | 679 | 0 | """
Reverse a singly linked list.
"""
#
# Iterative solution
# T | (n)- O(n)
#
def reverse_list(head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
prev = None
while head:
current = head
head = head.next
current.next = prev
prev = c | urrent
return prev
#
# Recursive solution
# T(n)- O(n)
#
def reverse_list_recursive(head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
p = head.next
head.next = None
revrest = reverse_list_recursive(p)
p.next = head
... |
anarang/robottelo | robottelo/cli/base.py | Python | gpl-3.0 | 14,874 | 0 | # -*- encoding: utf-8 -*-
"""Generic base class for cli hammer commands."""
import logging
from robottelo import ssh
from robottelo.cli import hammer
from robottelo.config import settings
class CLIError(Exception):
"""Indicates that a CLI command could not be run."""
class CLIReturnCodeError(Exception):
""... | "
def __init__(self, return_code, stderr, msg):
self.return_code = return_code
self.stderr = stderr
self.msg = msg
def __str__(self):
return self.msg
class Base(object):
"""
@param command_base: base command of hammer.
Output of recent `hammer --help`::
ac... | nipulate architectures.
auth Foreman connection login/logout.
auth-source Manipulate auth sources.
bootdisk Download boot disks
capsule Manipulate capsule
compute-resource Manipulat... |
flegald/django-imager | imagersite/imager_profile/handler.py | Python | mit | 1,201 | 0 | # -*- coding: utf-8 -*-
"""signal handlers registered by the imager_profile app"""
from __future__ import unicode_literals
from django.conf import settings
from django.db.models.signals import post_save
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from imager_profile.models impor... | e after every new User is created."""
if kwargs.get('created', False):
try:
new_profile = ImagerProfile(user=kwargs['instance'])
new_profile.save()
except (KeyError, ValueError):
logger.error('Unable to create ImagerProfile for User instance.')
@receiver(pre_del... |
msg = (
"ImagerProfile instance not deleted for {}. "
"Perhaps it does not exist?"
)
logger.warn(msg.format(kwargs['instance']))
|
pviafore/rcfc | rcfc/input_methods.py | Python | mit | 1,204 | 0 | """ A collection of input methods that aren't necessarily buttons """
from rcfc.server import register_post_with_state, register_post_with_input
from rcfc.groups import convertGroup
class DIRECTIONAL:
LEFT = "left"
RIGHT = "right"
def slider(text, getter, input_range=(0, 100), group=None):
min_value, m... | oup=None):
def wrapper(setter):
colorpicker = {
"text": text | ,
"type": "input.colorpicker",
"groups": convertGroup(group)
}
register_post_with_state(colorpicker, getter, setter)
return wrapper
|
matpalm/malmomo | p/reward_freqs.py | Python | mit | 605 | 0.018182 | #!/usr/bin/env python
import json
import sys
import numpy as np
rewards = []
for line in sys.stdin:
if not line.startswith("REWARD"): continue
cols = line.strip().split("\t")
data = json.loads(cols[1])
rewards.append(data['reward'])
rmin, rmax = np.min(rewards), np.max(rewards)
rrange = rmax - rmin
num_bins ... | 1
for i, h in enumerate(histo):
print rmin + (i*(rrange/num_bins)), "\t", h
#grep ^REWARD $1 | cut -f2 | jq '.reward' | sort | uniq | -c | normalise.py | sort -k3 -nr
|
mbilalzafar/fair-classification | preferential_fairness/synthetic_data_demo/plot_synthetic_boundaries.py | Python | gpl-3.0 | 3,067 | 0.024128 | import matplotlib
import matplotlib.pyplot as plt # for plotting stuff
import os
import numpy as np
matplotlib.rcParams['text.usetex'] = True # for type-1 fonts
def get_line_coordinates(w, x1, x2):
y1 = (-w[0] - (w[1] * x1)) / w[2]
y2 = (-w[0] - (w[1] * x2)) / w[2]
return y1,y2
def plot_data(X, y, x_... | 'x', s=70, linewidth=2)
plt.scatter(X_s_0[y_s_0==-1.0][:, -2], X_s_0[y_s_0==-1.0][:, -1], | color='red', marker='x', s=70, linewidth=2)
plt.scatter(X_s_1[y_s_1==1.0][:, -2], X_s_1[y_s_1==1.0][:, -1], color='green', marker='o', facecolors='none', s=70, linewidth=2)
plt.scatter(X_s_1[y_s_1==-1.0][:, -2], X_s_1[y_s_1==-1.0][:, -1], color='red', marker='o', facecolors='none', s=70, linewidth=2)
... |
googleapis/python-api-common-protos | google/api/log_pb2.py | Python | apache-2.0 | 2,402 | 0.001665 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | GDESCRIPTOR = DESCRIPTOR.message_types_by_name["LogDescriptor"]
LogDescriptor = _reflection.GeneratedProtocolMessageType(
"LogDescriptor",
(_message.Message,),
{
"DESCRIPTOR": _LOGDESCRIPTOR,
"__module__": "google.api.log_pb2"
# @@protoc_insertion_point(class_scope:google.api.LogDesc... | iB\010LogProtoP\001ZEgoogle.golang.org/genproto/googleapis/api/serviceconfig;serviceconfig\242\002\004GAPI"
_LOGDESCRIPTOR._serialized_start = 60
_LOGDESCRIPTOR._serialized_end = 177
# @@protoc_insertion_point(module_scope)
|
gaborvecsei/Color-Tracker | color_tracker/utils/camera/base_camera.py | Python | mit | 3,526 | 0.001702 | import threading
import cv2
class Camera(object):
"""
Base Camera object
"""
def __init__(self):
self._cam = None
self._frame = None
self._frame_width = None
self._frame_height = None
self._ret = False
self._auto_undistortion = False
self._cam... | tortion_coefficients is None:
import warnings
warnings.warn("Undistortion has no effect because <camera_matrix>/<distortion_coefficients> is None!")
return image
h, w = image | .shape[:2]
new_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(self._camera_matrix,
self._distortion_coefficients, (w, h),
1,
... |
iulian787/spack | lib/spack/spack/operating_systems/mac_os.py | Python | lgpl-2.1 | 2,263 | 0 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform as py_platform
from spack.architecture import OperatingSystem
from spack.version import Version
from spac... | _sdk_path():
"""Return SDK path
"""
xcrun = Executable('xcrun')
return xcrun('--show-sdk-path', output=str, error=str).rstrip()
class MacOs(OperatingSystem):
"""This class represents the macOS operating syste | m. This will be
auto detected using the python platform.mac_ver. The macOS
platform will be represented using the major version operating
system name, i.e el capitan, yosemite...etc.
"""
def __init__(self):
"""Autodetects the mac version from a dictionary.
If the mac version is too... |
sanja7s/CI_urban_rural | CI_urban_rural/__main__.py | Python | mit | 1,723 | 0.006384 | '''
Created on June 09, 2014
@author: sscepano
'''
# This one serves for the starting point
import logging
import traceback
import multiprocessing
#####################################################
# imports distributor
#####################################################
from distribute import task_manager as D... | test():
print 'cpu_count() = %d\n' % multiprocessing.cpu_count()
if __name__ == '__main__' | :
logging.basicConfig(level=logging.INFO, format='%(name)s: %(levelname)-8s %(message)s')
test()
# data1 will be the read in from all 10 parallel processes
# data2 will be processed & arranged from those
data1 = None
data2 = None
while True:
raw_input("Press enter to ... |
tBaxter/tango-happenings | happenings/templatetags/event_tags.py | Python | mit | 3,870 | 0.00155 | import datetime
from django import template
register = template.Library()
today = datetime.date.today()
@register.simple_tag
def get_upcoming_events_count(days=14, featured=False):
"""
Returns count of upcoming events for a given number of days, either featured or all
Usage:
{% get_upcoming_events_... | None
try:
previous = Update.objects.filter(
event=event,
| pub_time__lt=time
).order_by('-pub_time').only('title')[0]
except:
previous = None
return {'next': next, 'previous': previous, 'event': event}
|
IT-SeanWANG/CodeJam | 2016_1st/Refer2_Q3.py | Python | apache-2.0 | 2,440 | 0.007377 | #!flask/bin/python
from flask import Flask, jsonify, abort
from flask import make_response
from flask import request
app = Flask(__name__)
#simulated data i | n list
vnfs = [
{
'vnf_id':1,
'vnf_name': u'vnf01',
'description': u'vnf03 description'
},
{
'vnf_id':2,
'vnf_name': u'vnf02',
'description': u'Test of nvf03 descritption'
},
{
'vnf_id':3,
'vnf_name': u'vnf03',
'description': u'... | make_response(jsonify({'error': 'Sorry, Nothing Found'}),404)
#GET, Get all the VNFs info
@app.route('/todo/api/v1.0/vnfs', methods=['GET'])
def get_vnfs():
return jsonify({'vnfs': vnfs}), 200
#GET, Get a VNF info
@app.route('/todo/api/v1.0/vnfs/<int:vnf_id>', methods=['GET'])
def get_vnf(vnf_id):
vnf = fil... |
deadc0de6/cidr | setup.py | Python | gpl-3.0 | 337 | 0 | #!/usr/bin/env python
from distutils.core import setup
setup(
name='cidr',
version='0.1',
description='CIDR ranges helper',
license='GPLv3',
author='deadc0de6',
url='https://github.com/deadc0de6/cidr',
py_modules=['cidr'],
scripts=['cidr.py'],
install_requires=['docopt', 'netaddr',... | ipaddress'],
)
| |
romeotestuser/lc5_form_customizations | sale_order.py | Python | gpl-2.0 | 28,437 | 0.008088 | # -*- 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... |
'name':fields.char('Payment Method', size=64),
}
lc5_ | sale_order_pm()
class lc5_sale_order_top(osv.osv):
_name = 'lc5.sale.order.top'
_description = "Terms of Payment"
_columns = {
'name':fields.char('Terms of Payment', size=64),
}
lc5_sale_order_top()
class lc5_sale_order_sig(osv.osv):
_name = 'lc5.sale.order.signature'
_description = "Messa... |
treehopper-electronics/treehopper-sdk | Python/treehopper/api/__init__.py | Python | mit | 976 | 0.003074 | """Base Treehopper API for Python.
This module provides digital and analog I/O, hardware and software PWM, I2C, SPI, and UART support.
"""
## @namespace treehopper.api
from treehopper.api.interfaces import *
from treehopper.api.pin import Pin, PinMode, ReferenceLevel
from treehopper.api.device_commands import DeviceC... | Wire',
| 'HardwarePwm', 'HardwarePwmFrequency',
]
|
strycore/megascops | video/tasks.py | Python | agpl-3.0 | 1,094 | 0 | # -*- coding: utf8 -*-
from __future__ import absolute_import
import os
import logging
from celery import task, current_task
from django.conf import settings
from .models import Video
from .quvi import Quvi
from .utils import download_thumbnail, celery_download, encode_videos
LOGGER = logging.getLogger(__name__)
... | DIA_ROOT, video.path)
celery_download(quvi.stream.url, dest_path, current_task)
video.state = "READY"
video.save()
@task
def encode_task(video_id):
"""Encode video using avconv"""
try:
video = Video.objects.get(pk=video_id)
except Video.DoesNotExist:
print "The requested video ... | (video)
|
openstack/cinder | cinder/volume/drivers/huawei/huawei_driver.py | Python | apache-2.0 | 23,610 | 0 | # Copyright (c) 2016 Huawei Technologies Co., Ltd.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | (view_id,
portgroup_id):
self.client.delete_portgroup_mapping_view(view_id,
portgroup_id)
if view_id and | (int(left_lunnum) <= 0):
self.client.remove_chap(initiator_n |
randomdude999/mcinfo | mcinfo/recipes.py | Python | mit | 5,016 | 0.000199 | from __future__ import unicode_literals
class SmeltingRecipe:
def __init__(self, data):
self.input = data["input"]
def __str__(self):
return "Smelt {0}".format(self.input)
class BrewingRecipe:
def __init__(self, data):
self.base = data["base"]
self.modifier = data["modif... | ".format(self.price_min, self.price_max)
if self.has_secondary_item:
out += " and {0} {1}.".format(self.secondary_count,
| self.secondary_item)
else:
out += "."
if not self.single_out:
out += " Yields {0}-{1}.".format(self.out_count_min,
self.out_count_max)
return out
class ChestLootRecipe:
def __init__(self, data):
... |
ThomasHabets/python-pyhsm | Tests/test_yubikey_validate.py | Python | bsd-2-clause | 5,120 | 0.007227 | # Copyright (c) 2011, Yubico AB
# All rights reserved.
import os
import sys
import string
import struct
import unittest
import pyhsm
from Crypto.Cipher import AES
from pyhsm.yubikey import modhex_encode, modhex_decode
import test_common
class YubiKeyEmu():
"""
Emulate the internal memory of a YubiKey.
""... | n_counter, timestamp, session_use)
def crc16(data):
"""
Calculate an ISO13239 CRC checksum of the input buffer.
"""
m_crc = 0xffff
for this in data:
m_crc ^= ord(this)
for _ in range(8):
j = m_crc & 1
m_crc >>= 1
if j:
m_crc ^= 0x... | e.setUp(self)
self.yk_key = 'F' * 16 # 128 bit AES key
self.yk_uid = '\x4d\x01\x4d\x02\x4d\x4d'
self.yk_rnd = YubiKeyRnd(self.yk_uid)
self.yk_public_id = '4d4d4d4d4d4d'.decode('hex')
secret = pyhsm.aead_cmd.YHSM_YubiKeySecret(self.yk_key, self.yk_uid)
self.hsm.load_secr... |
manassolanki/erpnext | erpnext/healthcare/doctype/physician_service_unit_schedule/physician_service_unit_schedule.py | Python | gpl-3.0 | 280 | 0.007143 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, ple | ase see license.txt
from __f | uture__ import unicode_literals
from frappe.model.document import Document
class PhysicianServiceUnitSchedule(Document):
pass
|
grafke/Drone-workflow-controller | drone/job_runner/job_runner.py | Python | apache-2.0 | 3,220 | 0.00559 | import sys
from drone.actions.emr_launcher import launch_emr_task
from drone.actions.ssh_launcher import launch_ssh_task
from drone.job_runner.dependency_manager import dependencies_are_met
from drone.job_runner.job_progress_checker import check_running_job_progress
from drone.metadata.metadata import get_job_info, job... | config, schedule_time, s | ettings)
elif status == job_status.get('succeeded'):
continue
elif status == job_status.get('not_ready'):
if dependencies_are_met(job_config, schedule_time, settings):
set_ready(job_config.get('id'), schedule_time, db_name=settings.metadata)
settin... |
ndp-systemes/odoo-addons | stock_no_recompute/__openerp__.py | Python | agpl-3.0 | 1,399 | 0 | # -*- coding: utf8 -*-
#
# Copyr | ight (C) 2017 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later v... | 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along w... |
Naeka/vosae-app | www/contacts/models/embedded/address.py | Python | agpl-3.0 | 2,877 | 0.000695 | # -*- coding:Utf-8 -*-
from django.utils.translation import pgettext_lazy
from mongoengine import EmbeddedDocument, fields
__all__ = (
'Address',
)
class Address(EmbeddedDocument):
"""An address wrapper which can be embedded in any object."""
TYPES = (
("HOME", pgettext_lazy("address type", "H... | s
- Extended address, post office box
- Postal code, City
- State, Country
"""
ret = [
self.street_address,
Address.concat_fields(self.extended_address, self.postoffice_box),
Address.concat_fields(self.postal_code, self.city),
Addre... | n ret if line]
|
sharvanath/cassandra | bin/cqlsh.py | Python | apache-2.0 | 104,917 | 0.002678 | #!/bin/sh
# -*- mode: Python -*-
# 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.... | ndra tarball, and after a proper package install.
cqlshlibdir = os.path.join(CASSANDRA_PATH, 'pylib')
if os.path.isdir(cqlshlibdir):
sys.path.insert(0, cqlshlibdir)
from cqlshlib import cql3handling, cqlhandling, pylexotron, sslhandling
from cqlshlib.copyutil import ExportTask, ImportTask
from cqlshlib.displaying ... | RED, WHITE, FormattedValue, colorme)
from cqlshlib.formatting import (DEFAULT_DATE_FORMAT, DEFAULT_NANOTIME_FORMAT,
DEFAULT_TIMESTAMP_FORMAT, CqlType, DateTimeFormat,
format_by_type, formatter_for)
from cqlshlib.tracing import print_... |
dchaplinsky/declarations.com.ua | declarations_site/cms_pages/models.py | Python | mit | 7,901 | 0.001194 | # coding: utf-8
from django.db import models
from django.utils.translation import get_language
from modelcluster.fields import ParentalKey
from wagtail.core.fields import RichTextField
from wagtail.core.models import Page, Orderable
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.admin.edit_ha... | nu_links', label="Меню зверху"),
InlinePanel('bottom_menu_links', label="Меню знизу"),
]
class Met | aData(models.Model):
region = models.ForeignKey(Region, blank=True, null=True, on_delete=models.SET_NULL)
office = models.ForeignKey(Office, blank=True, null=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=255, blank=True)
description = models.TextField(blank=True)
class Meta:
... |
killerbat00/pyclock | vars.py | Python | mit | 809 | 0.003708 | clock = [
" __ __________",
"/ \\____/ __ / /\\______",
"-==- -/ /=/`/ / / .\\- -/\\",
"=- -=-/ _` ` / /## .\\=-/\\\\",
"-- =-/ /_/`/ / / ### /_///\\",
" -= / /_/`/ / /## ##/ /\\/\\",
"___/ /_/`/ / / ### /=/// \\",
"==/ /_/`/ / /##'##/ /\\/",
"_/ _`_`_ / / ###'/-/// ",
... | \\',
' \\',
' ',
'/\\',
' / ',
'\\/',
'/\\',
' /\\',
' /',
' \\',
'\\/\\',
' ',
'/ ' | ,
'\\/\\',
' /',
'/ ',
'\\/\\',
'\\/',
'/\\',
' \\',
' ',
'/\\',
'\\/\\',
' \\/',
'/\\',
'\\/\\',
' /'
]
|
forman/dectree | dectree/transpiler.py | Python | mit | 7,950 | 0.001887 | import os
import os.path
from collections import OrderedDict
from typing import List, Dict, Any, Tuple, Union
# noinspection PyPackageRequirements
import yaml # from pyyaml
import dectree.propfuncs as propfuncs
from .codegen import gen_code
from .types import TypeDefs
def transpile(src_file, out_file=None, **optio... | e, str):
raw_rule = _load_raw_rule(raw_rule)
return _parse_raw_rule(raw_rule)
def _parse_raw_rule(raw_rule: List[Union[Dict, List]]) -> List[Union[Tuple, List]]:
# print(raw_rule)
n = len(raw_rule)
parsed_rule = []
for i in range(n):
item = raw_rule[i]
stmt_part, stmt_body... | gnment = None, None, None
if isinstance(item, dict):
stmt_part, stmt_body = dict(item).popitem()
else:
assignment = item
if stmt_part:
stmt_tokens = stmt_part.split(None, 1)
if len(stmt_tokens) == 0:
raise ValueError('illegal rule ... |
davidbgk/udata | udata/search/result.py | Python | agpl-3.0 | 3,239 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import logging
from bson.objectid import ObjectId
from flask import request
from werkzeug.urls import Href
from elasticsearch_dsl.result import Response
from udata.utils import Paginable
log = logging.getLogger(__name__)
class SearchRes... | Fetch an aggregation result given its name
As there is no way at this point know the aggregation type
(ie. bucket, pipeline or metric)
we guess it from the response attributes.
Only bucket and metric types are handled
'''
agg = self.aggregations[name]
if ... | if name not in self.query.facets:
return None
return self.query.facets[name].labelize
def labelize(self, name, value):
func = self.label_func(name)
return func(value) if func else value
|
openstack/python-openstacksdk | openstack/image/_base_proxy.py | Python | apache-2.0 | 9,912 | 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 under t... | None:
container = self._connection._OBJECT_AUTOCREATE_CONTAINER
if not meta:
meta = {}
if not disk_format:
disk_format = self._connection.c | onfig.config['image_format']
if not container_format:
# https://docs.openstack.org/image-guide/image-formats.html
container_format = 'bare'
if data and filename:
raise exceptions.SDKException(
'Passing filename and data simultaneously is not supported... |
zuck/prometeo-erp | core/taxonomy/migrations/0001_initial.py | Python | lgpl-3.0 | 8,429 | 0.008067 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Result'
db.create_table('taxonomy_result', (
('id', self.gf('django.db.models.... | _together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.... | True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.mod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.