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 |
|---|---|---|---|---|---|---|---|---|
andyofmelbourne/crappy-crystals | utils/phasing_3d/src/mappers.py | Python | gpl-3.0 | 8,434 | 0.018852 | import numpy as np
import sys
import copy
def isValid(thing, d=None):
"""
checks if 'thing' is valid. If d (a dictionary is not None) then
check if d['thing'] is valid.
"""
valid = False
if d is not None :
if thing not in d.keys():
return valid
else :
... | add__(self, value):
out = self.copy()
for k in self.keys():
if type(value) == Modes :
out[k] = self[k] + value[k]
else :
out[k] = self[k] + value
return out
def __iadd__(self, value):
for k in self.keys():
if type(v... | lf, value):
out = self.copy()
for k in self.keys():
if type(value) == Modes :
out[k] = self[k] - value[k]
else :
out[k] = self[k] - value
return out
def __isub__(self, value):
for k in self.keys():
if type(value) ==... |
NoctuaNivalis/qutebrowser | qutebrowser/commands/cmdexc.py | Python | gpl-3.0 | 1,545 | 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... | when a command encounters an error while running."""
pass
class NoSuchCommandError(Error):
"""Raised when a command wasn't found."""
pass
class ArgumentTypeError(Error):
"""Raised when an argument had an invalid type."""
pass
class PrerequisitesError(Error):
"""Raised when a cmd can'... | e executing the
command, or we need javascript enabled but don't have done so.
"""
pass
|
sakura-internet/saklient.python | tests/test_enum.py | Python | mit | 1,117 | 0.016115 | # -*- coding:utf-8 -*-
import unittest, sys, os
sys.path[:0] = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from saklient.cloud.enums.eserverinstancestatus import EServerInstanceStatus
class TestEnum(unittest.TestCase):
def test_should_be_defined(self):
self.assertEqual(EServerInstance... | up", "up"), 0);
self.assertEqual(EServerInstanceStatus.compare("up", "down"), 1);
self.assertEqual(EServerInstanceStatus.compare("down", "up"), -1);
self.assertEqual(EServerInstanceStatus.compare("UNDEFINED-SYMBOL", "up"), None);
self.assertEqual(EServerInstanceStatus.compare("up", "UNDE... | self.assertEqual(EServerInstanceStatus.compare("up", None), None);
self.assertEqual(EServerInstanceStatus.compare(None, None), None);
if __name__ == '__main__':
unittest.main()
|
jucacrispim/toxicbuild | toxicbuild/master/signals.py | Python | agpl-3.0 | 1,360 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Juca Crispim <juca@poraodojuca.net>
# This file is part of toxicbuild.
# toxicbuild 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 Li... | 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 with toxicbuild. If not, see <http://www.gnu.org/licenses/>.
from asyncblink import signal
revision_added = signal('revision-added')
step_started = signal('step-started')
step_finished = signal('step-finished')
step_output_arrived = signal(... |
bcorfman/stage | const.py | Python | mit | 301 | 0.003322 | __author__ = 'brandon.corfman'
# Global constants used across the application.
AVERAGED_OVER_ALL_AZIMUTHS = -1
AVERAGED_ON_NON_ZERO_AVS = 0
BY_AZIMUTH = 1
GYPSY_PINK = (0.6745, 0.196, 0.3882) # color coveted by JJS; used for blast volumes
W | HITE = (1.0, 1.0, 1.0)
CMPID, R1, R2, R3, Z1, Z2 = range | (6)
|
fichtner/libucl | python/setup.py | Python | bsd-2-clause | 1,142 | 0.024518 | try:
fro | m setuptools import setup, Extension
except ImportError:
from distutils.core import setup, Extension
import os
import sys
tests_require = []
if sys.version < '2.7':
tests_require.append('unittest2')
uclmodule = Extension(
'ucl', |
libraries = ['ucl'],
sources = ['src/uclmodule.c'],
language = 'c'
)
setup(
name = 'ucl',
version = '0.8',
description = 'ucl parser and emmitter',
ext_modules = [uclmodule],
test_suite = 'tests',
tests_require = tests_require,
author = "Eitan Adler, Denis Volpato Martins",
... |
ntymtsiv/tempest | tempest/api/network/base_security_groups.py | Python | apache-2.0 | 2,428 | 0 | # Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | r agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.network imp... | tempest.common.utils import data_utils
class BaseSecGroupTest(base.BaseNetworkTest):
@classmethod
def setUpClass(cls):
super(BaseSecGroupTest, cls).setUpClass()
def _create_security_group(self):
# Create a security group
name = data_utils.rand_name('secgroup-')
resp, grou... |
ddico/odoo | addons/website_mass_mailing/models/website_mass_mailing.py | Python | agpl-3.0 | 635 | 0.00315 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class MassMailingPopup(models.Model):
_name = 'website.mass_mailing.popup'
_description = "Mailing list popup"
def _de | fault_popup_content(self):
return self.env['ir.ui.view']._render_template('website_mass_mailing.s_newsletter_subscribe_popup_content')
mailing_list_id = fields.Many2one('mailing.list')
website_id = fields.Many2one('website')
| popup_content = fields.Html(string="Website Popup Content", default=_default_popup_content, translate=True, sanitize=False)
|
marvel-explorer/marvel-explorer | m_explorer/m_profile/permissions.py | Python | mit | 439 | 0 | from rest_framework import permissions
class IsObjectOwner(permissions.BasePermission):
"""
Custom permission to only allow
owners of an | object to view and edit it. Returns
true if user is owner
"""
def has_object_permission(self, request, view, obj):
"""Return Bool representing object permissions."""
| if request.method == "POST":
return True
return obj.user == request.user
|
luci/luci-py | appengine/components/components/auth/machine_auth.py | Python | apache-2.0 | 7,005 | 0.007566 | # Copyright 2016 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Implements authentication based on LUCI machine tokens.
LUCI machine tokens are short lived signed protobuf blobs that (among other
informatio... | def optional_machine_authentication(request):
"""It's like machine_authentication except it ignores broken tokens.
Usable during development and initial roll out when machine tokens may not
be working all the time.
"""
try:
return machine_authentication(request)
except BadTokenError:
return None, N... | "Decodes standard unpadded base64 encoded string."""
mod = len(data) % 4
if mod:
data += '=' * (4 - mod)
return base64.b64decode(data)
def log_error(request, token_body, exc, msg, *args):
"""Logs details about the request and the token, along with error message."""
lines = [('machine_auth: ' + msg) % ar... |
MarvinTeichmann/tensorflow_examples | input/input.py | Python | mit | 8,318 | 0.013104 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 17 11:50:47 2015
@author: teichman
"""
import tensorflow as tf
from tensorflow.python | .framework import ops
from tensorflow.python.framework impo | rt dtypes
from tensorflow.python.training import queue_runner
import os
import numpy as np
# Global constants describing out car data set.
IMAGE_SIZE = 32
NUM_CLASSES = 2
def input_pipeline(filename, batch_size, num_labels,
processing_image=lambda x:x,
processing_label=lambda y:... |
cesc-park/CRCN | doc2vec_training.py | Python | mit | 1,588 | 0.0233 |
from gensim import corpora, models, similarities
import json
import os
# from cpython cimport PyCObject_AsVoidPtr
# from scipy.li | nalg.blas import cblasfrom scipy.linalg.blas import cblas
# ctypedef void (*saxpy_ptr) (const int *N, const float *alpha, const float *X, const int *incX, float *Y, const int *incY) nogil
# cdef saxpy_ptr saxpy=<saxpy_ptr>PyCObject_AsVoidPtr(cblas.saxpy._cpointer)
jsonfile = open('./da | ta/example.json', 'r')
json_data=jsonfile.read()
jsondata=json.loads(json_data)
json_imgs=jsondata['images']
sentences=[]
for i,jsonimg in enumerate(json_imgs):
concatpara=""
for sentence in jsonimg['sentences']:
ensent=sentence['raw'].encode('ascii','ignore')
if ensent not in concatpara:
concatpara+=ensent
k... |
flavoi/diventi | diventi/products/migrations/0073_remove_product_order_index.py | Python | apache-2.0 | 337 | 0 | # Genera | ted by Django 2.2.24 on 2021-10-02 14:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0072_product_order_index'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='order_index',
... | |
wilsonssun/baseball-gamethread | build/lxml/src/lxml/html/tests/test_clean.py | Python | bsd-3-clause | 1,225 | 0.008163 | import unittest, sys
from lxml.tests.common_imports import make_doctest
from lxml.etree import LIBXML_VERSION
import lxml.html
from lxml.html.clean import Cleaner
class CleanerTest(unittest.TestCase):
def test_allow_tags(self):
html = """
<html>
< | head>
</head>
<body>
<p>some text</p>
<table>
<tr>
<td>hello</td><td>world</td>
</tr>
<tr>
<td>hello</td><td>world</td>
</tr>
</table>
<img>
</body>
</h... | Cleaner(
remove_unknown_tags = False,
allow_tags = ['table', 'tr', 'td'])
result = cleaner.clean_html(html_root)
self.assertEquals(12-5+1, len(list(result.iter())))
def test_suite():
suite = unittest.TestSuite()
if sys.version_info >= (2,4):
suite.addTests([make... |
ad-m/django-atom | atom/models.py | Python | bsd-3-clause | 587 | 0.001704 | from os.path import basename
from django.db import models
from django.utils.translation import ugettext_lazy as _
class AttachmentBase(models.Model):
attachment = models.File | Field(upload_to="letters/%Y/%m/%d", verbose_name=_("File"))
@prope | rty
def filename(self):
return basename(self.attachment.name)
def __unicode__(self):
return "%s" % (self.filename)
def get_absolute_url(self):
return self.attachment.url
class Meta:
abstract = True
verbose_name = _('Attachment')
verbose_name_plural = _(... |
mediatum/mediatum | mediatum.py | Python | gpl-3.0 | 257 | 0.003891 | #! /usr/bi | n/env nix-shell
#! nix-shell -i python
import sys
if __nam | e__ == '__main__':
from bin.mediatum import main
try:
main()
except KeyboardInterrupt:
print(" - Mediatum stopped by KeyboardInterrupt.")
sys.exit(1)
|
lucasdavid/grapher | grapher/environment.py | Python | mit | 638 | 0 | import abc
from flask import Flask
from . import settings
class Environment(metaclass=abc.ABCMeta):
instance | = None
def __init__(self, name):
if self.instance is not None:
raise RuntimeError('The environment %s is already running. '
'Only one instance is allowed.'
% Environment.instance.name)
self.name = name
self.settings... | gs)
self.user_artifacts = {}
self.schemas = {}
Environment.instance = self
|
EndPointCorp/lg_ros_nodes | lg_nav_to_device/src/lg_nav_to_device/background_stopper.py | Python | apache-2.0 | 2,636 | 0 | import rospy
import threading
import types
from lg_common.helpers import load_director_message, find_window_with_activity
from lg_msg_defs.msg import ApplicationState
class BackgroundStopper:
def __init__(self, disable_activities, device_writer):
self.disable_activities = disable_activities
self.d... | ider_disabled_states(self):
if self._activity_disabled or self._slug_disabled:
return
for topic, visible in list(self._states.items()):
if visible:
self._set_writer_state(False)
return
self._set_writer_state(True)
def handle_scene(se... | ne(self, msg):
self._states = {}
data = load_director_message(msg)
self._current_scene_slug = data.get('slug')
self._consider_scene_slugs()
for activity in self.disable_activities:
window = find_window_with_activity(data, activity)
if len(window) > 0:
... |
antoinecarme/pyaf | tests/model_control/detailed/transf_BoxCox/model_control_one_enabled_BoxCox_PolyTrend_NoCycle_SVR.py | Python | bsd-3-clause | 147 | 0.047619 | import tests.model_control.test_ozone_custom_models_enabled | as testmod
testmod.build_model( ['BoxCox'] , ['PolyTrend'] , ['NoCycle'] , ['SV | R'] ); |
harshilasu/GraphicMelon | y/google-cloud-sdk/platform/gsutil/third_party/boto/boto/ec2/elb/instancestate.py | Python | gpl-3.0 | 2,657 | 0 | # Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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, modi... | te of an EC2 Load Balancer Instance
"""
def __init__(self, load_balancer=None, description=None,
state=None, instance_id=None, reason_code=None):
"""
:ivar boto.ec2.elb.loadbalancer.LoadBalancer load_balancer: The
load balancer this instance is registered to.
... | ion about the cause of
an OutOfService instance. Specifically, it indicates whether the
cause is Elastic Load Balancing or the instance behind the
LoadBalancer.
:ivar str state: Specifies the current state of the instance.
"""
self.load_balancer = load_balance... |
simvisage/oricreate | oricreate/hu/__init__.py | Python | gpl-3.0 | 50 | 0 | from .hu_psi_constraints import HuPsiConstraint | s
| |
AdaptiveApplications/carnegie | tarc_bus_locator_client/numpy-1.8.1/numpy/doc/broadcasting.py | Python | mit | 5,576 | 0.000179 | """
========================
Broadcasting over arrays
========================
The term broadcasting describes how numpy treats arrays with different
shapes during arithmetic operations. Subject to certain constraints,
the smaller array is "broadcast" across the larger array so that they
have compatible shapes. Broadc... | x 3
When either | of the dimensions compared is one, the larger of the two is
used. In other words, the smaller of two axes is stretched or "copied"
to match the other.
In the following example, both the ``A`` and ``B`` arrays have axes with
length one that are expanded to a larger size during the broadcast
operation::
A (4d ... |
pozar87/apts | apts/objects/objects.py | Python | apache-2.0 | 1,992 | 0.006024 | import ephem
import numpy
import pytz
import datetime
from datetime import timedelta
from ..constants import ObjectTableLabels
class Objects:
def __init__(self, place):
self.place = place
def get_visible(self, conditions, start, stop, hours_margin=0, sort_by=[ObjectTableLabels.TRANSIT]):
visible = self.... | mpute_tranzit(self, body):
# Return transit time in local time
self.place.date = datetime.datetime.now()
return self.place.next_transit(body).datetime().replace(tzinfo=pytz.UTC).astimezone(self.place.local_timezone)
def _compute_setting(self, body):
# Return setting time in local time
self.place.... | return self.place.next_setting(body).datetime().replace(tzinfo=pytz.UTC).astimezone(self.place.local_timezone)
def _compute_rising(self, body):
# Return rising time in local time
self.place.date = datetime.datetime.now()
return self.place.next_rising(body).datetime().replace(tzinfo=pytz.UTC).astimezo... |
drorlab/dabble | test/runtests.py | Python | gpl-2.0 | 233,788 | 0.000038 | #! /usr/bin/env python
# Hi There!
# You may be wondering what this giant blob of binary data here is, you might
# even be worried that we're up to something nefarious (good for you for being
# paranoid!). This is a base64 encoding of a zip file, this zip file contains
# a fully functional basic pytest script.
#
# Pyt... | 13SAGlTuLNKLGFsQAyDRjt2NVLe4LLdv6sga1nKTOV9UHFl+hy5uS9rGcz3bP
i7bhk7N5ni0dcHSuhWdEJPoq47GSTx/q4aVh2yl05kbZvFxSkhODG4s1dd6TwjuJekXAJKESIp5G
0JipNaEJTTuHZPiTWCRn17YdLhQkcklZtlWcQ | onuOsMqquiYCtrA0572hcqspm+0/WkiNNhT1daK
nPphrQfhWV/TtHdfN/z7xtiNgqcinj9UARuo5gYgCFpNsBm02cDOkmj4vKOlY7syVrMZqqXRkrze
gt6aNMsCvh+m/iCkFXbgos0IIMLDTufJWql5cbGEFaA4XzlZZqvzeRbdHNOc3oy13JnehSHhcpnB
PpoB0ePYmogWnr/iQZzBJR9dbMoZMSBafSj+GjupsjiP7KaeAUx3GUjTI+JZbC5w5GKy4uKqxe6o
AqBLZzA4l77EtGRNFMl6DAGQ0mGngMYMz5SIf/E4iY+5YJ4RG... |
gallenmu/MoonGen | libmoon/deps/tbb/build/build.py | Python | mit | 8,400 | 0.009167 | #!/usr/bin/env python
#
# Copyright (c) 2017-2018 Intel Corporation
#
# 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 a... | find prebuilt files')
parser.add_argument('--no-rebuild', default=False, action='store_true', help='do not rebuild')
parser.add_argument('--install', default=False, action='store_true', help='install all')
parser.add_argument('--install-libs', default=False, action='store_true', help=' | install libs')
parser.add_argument('--install-devel', default=False, action='store_true', help='install devel')
parser.add_argument('--install-docs', default=False, action='store_true', help='install docs')
parser.add_argument('--install-python',default=False, action='store_true', help='install python module')
parser.... |
andrius-momzyakov/grade | web/migrations/0009_auto_20170730_0156.py | Python | gpl-3.0 | 735 | 0.002809 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-07-30 01:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(m | igrations.Migration):
dependencies = [
('web', '0008_contactphone_place_on_header'),
]
operations = [
migrations.AddField(
model_name='contactemail',
name='place_on_header',
field=models.BooleanField(default=False, verbose_name='Размещать в заголовке'),
... | ,
name='photo',
field=models.ImageField(blank=True, null=True, upload_to='', verbose_name='Фото'),
),
]
|
philanthropy-u/edx-platform | openedx/features/partners/migrations/0008_auto_20201203_0918.py | Python | agpl-3.0 | 1,673 | 0.002989 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2020-12-03 14:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('partners', '0007_auto_20201203_0823'),
]
operations = [
migrations.AlterFi... | me='partner',
name='heading1_description',
field=models.TextField(blank=True, help_text='max 500 characters', max_length=500),
),
migrations.AlterField(
model_name='partner',
name='heading2',
| field=models.CharField(blank=True, max_length=100),
),
migrations.AlterField(
model_name='partner',
name='heading2_description',
field=models.TextField(blank=True, help_text='max 500 characters', max_length=500),
),
migrations.AlterField(
... |
DailyActie/Surrogate-Model | 01-codes/numpy-master/numpy/polynomial/tests/test_polynomial.py | Python | mit | 19,204 | 0 | """Tests for polynomial module.
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import numpy.polynomial.polynomial as poly
from numpy.testing import (
TestCase, assert_almost_equal, assert_raises,
assert_equal, assert_, run_module_suite)
def trim(x):
return poly.p... | [1, 0, -8, 0, 8]
T | 5 = [0, 5, 0, -20, 0, 16]
T6 = [-1, 0, 18, 0, -48, 0, 32]
T7 = [0, -7, 0, 56, 0, -112, 0, 64]
T8 = [1, 0, -32, 0, 160, 0, -256, 0, 128]
T9 = [0, 9, 0, -120, 0, 432, 0, -576, 0, 256]
Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]
class TestConstants(TestCase):
def test_polydomain(self):
assert_equal(pol... |
stewartsmith/bzr | bzrlib/tests/test_diff.py | Python | gpl-2.0 | 65,261 | 0.005225 | # Copyright (C) 2005-2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... | f.overrideEnv('PATH', '')
self.assertRaises(errors.NoDiff, diff.external_diff,
'old', ['boo\n'], 'new', ['goo\n'],
StringIO(), diff_opts=['-u'])
def test_internal_diff_default(self):
# Default internal diff encoding is utf | 8
output = StringIO()
diff.internal_diff(u'old_\xb5', ['old_text\n'],
u'new_\xe5', ['new_text\n'], output)
lines = output.getvalue().splitlines(True)
self.check_patch(lines)
self.assertEquals(['--- old_\xc2\xb5\n',
'+++ new_\x... |
geobricks/geobricks_dockerizer | geobricks_common_settings.py | Python | gpl-2.0 | 684 | 0.001462 | import logging
settings_app = {
"settings": {
# base url used by nginx
"base_url": "",
# Logging configurations
"logging": {
"level": logging.WARN,
"format": "%(asctime)s | %(levelname)-8s | %(name)-20s | Line: %(lineno)-5d | %(message)s",
"dat... | "distribution_sld": "/distribution_sld/",
"st | orage": "/storage/",
"workspace_layer_separator": ":"
}
}
}
|
RyanChinSang/ECNG3020-ORSS4SCVI | BETA/TestCode/OpenCV/imutils-test/imultils-test2.py | Python | gpl-3.0 | 2,355 | 0.000425 | from threading import Thread
import winsound
import cv2
class WebcamVideoStream:
def __init__(self, src=0):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
(self.grabbed, self.frame) = self.stream.read()
# ... | te if the thread should
# be stopped
self.stopped = False
def start(self):
# start the thread to read frames from the video stream
t = Thread(target=self.update, args=())
t.daemon = True
| t.start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
return
# otherwise, read the next frame from the stream
... |
nwcrazysword/reversalcode | src/test.py | Python | apache-2.0 | 233 | 0.030043 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017- | 07-21 18:15:11
import os
import tensorflow as tf
import numpy as np
x_data=np.float32(np.random.rand(2,100))
y_data=np.dot([0.100,0.200],x | _data)+0.300
b=tf.Variable() |
MSusik/invenio | invenio/ext/admin/__init__.py | Python | gpl-2.0 | 3,353 | 0.003877 | # -*- coding: utf-8 -*-
#
## This file is part of Invenio.
## Copyright (C) 2013, 2014 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 opti... | class MyModelAdmin(InvenioModelView):
acc_edit_action = 'cfgmymodel'
_can_create = False
_can_edit = True
_can_delete = False
# ... Flaks-Admin options ...
# column_list = ( ... )
def __init__(self, model, session, **kwargs):
super(MyModelAdmin,... | min.add_view(MyModelAdmin(MyModel, db.session, name='My model',
category="My Category"))
"""
from __future__ import absolute_import
from flask.ext.admin import Admin
from flask.ext.registry import ModuleAutoDiscoveryRegistry
from .views import AdminIndexView
#
# Utility method
#... |
bmcage/centrifuge-1d | centrifuge1d/modules/base/options.desc.py | Python | gpl-2.0 | 16,567 | 0.002294 | # This file contains the description of base options
CONFIG_OPTIONS = {
'general': {'g': "Gravitational constant. Default is 981 cm/s^2. Type:float."},
'experiment': \
{'exp_type': ("Identifier of type of experiment do determine which "
"module should be used. Type: string"),
... | "
"time in cm. Type: array of floats or None"),
'ww1': ("Measured weight of water above the soil at given (measured) "
"time, in gramms. Type: array of floats or None"),
'wl_out': ("Measured length of water in the outflow chamber at given "
"(meas... | . Units: array of floats or None",
'rm1': "Measured rotational momentum. Units: array of floats or None",
'measurements_scale_coefs': \
("When running inverse problem, multiple meaurements can be "
"given, potentially with different scales (e.g. MO ~ 0.5 whereas "
... |
jhseu/tensorflow | tensorflow/python/training/rmsprop.py | Python | apache-2.0 | 10,430 | 0.002972 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | n is enabled, `learning_rate`, `decay`, `momentum`, and
`epsilon` can each be a callable that takes no arguments and returns the
actual value to use. This can be useful for changing these values across
different invocations of optimizer functions.
@end_compatibility
"""
super(RMSPropOptimizer, s... | use_locking, name)
self._learning_rate = learning_rate
self._decay = decay
self._momentum = momentum
self._epsilon = epsilon
self._centered = centered
# Tensors for learning rate and momentum. Created in _prepare.
self._learning_rate_tensor = None
self._decay_tensor = None
self._mo... |
almcc/cinder-data | example/server/app/settings.py | Python | mit | 4,215 | 0.001423 | """
Django settings for app project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Bui... | ages',
'django.contrib.staticfiles',
'rest_framework',
'cars',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'dja... | trib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.tem... |
chirilo/mozillians | mozillians/users/api/v1.py | Python | bsd-3-clause | 7,048 | 0.001419 | from urllib2 import unquote
from urlparse import urljoin
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db.models import Q
from funfactory import utils
from tastypie import fields, http
from tastypie.authorization import ReadOnlyAuthorization
from tastypie.bundle import Bund... | ers=None):
database_filters = {}
valid_filters = [f for f in filters if f in
['email', 'country', 'r | egion', 'city', 'ircname',
'username', 'groups', 'skills',
'is_vouched', 'name', 'accounts']]
getvalue = lambda x: unquote(filters[x].lower())
if 'accounts' in valid_filters:
database_filters['accounts'] = Q(
externalaccoun... |
Karuji/GMProjectImporter | PythonToGMX.py | Python | mit | 493 | 0.022312 | import xml.etree.ElementTree as ET
import | os
from Element import Element
class PythonToGMX(object):
def __init__(self, pythonTree):
self.pythonroot = python | Tree
self.root = ET.Element(eval(self.pythonroot.tag))
for child in self.pythonroot.children:
self.process(child, self.root)
def process(self, element, parent):
elem = ET.SubElement(parent, eval(element.tag), element.attrib)
elem.text = eval(element.text)
for child in element.children:
self.process(c... |
tanglu-org/laniakea | src/admin/lkadmin/cli.py | Python | gpl-3.0 | 2,762 | 0.000362 | # Copyright (C) 2018 Matthias Klumpp <matthias@tenstral.net>
#
# Licensed under the GNU Lesser General Public License Version 3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Gen | eral Public License as published by
# the Free Software Foundation, either version 3 of the license, or
# (at your option) any later version.
#
# This software i | 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along wi... |
google-research/google-research | es_maml/zero_order/adaptation_optimizers.py | Python | apache-2.0 | 6,752 | 0.007701 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | ,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Collection of adapters for Zero-Order ES-MAML."""
# pylint: disable=g-doc-return-or-yield,missing-docstring,g-doc-args,line-too-long,inv... | _function
import abc
from absl import logging
import numpy as np
from es_maml.util.dpp.dpp import DPP
from es_maml.util.log_util import AlgorithmState
class Adaptation:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def adaptation_step(self, policy_params, adaptation_params, task, **kwargs):
raise NotImp... |
agraubert/Beymax | beymax/bots/game_systems/story.py | Python | mit | 13,971 | 0.001432 | import re
from string import printable
import os
import queue
import subprocess
import discord
import asyncio
import threading
import time
from ...utils import DBView
from .base import GameSystem, GameError, JoinLeaveProhibited, GameEndException
from math import ceil, floor
printable_set = set(printable)
printable_byt... | dException("Unable to restore") from e
@property
def played(self):
return (
'transcript' in self.state and
len(self.state['transcript'])
)
def is_playing(self, user):
return user.id in self.state['players']
async def on_input(self, user, channel, messag... | content = message.content.strip().lower()
if content == 'save':
await self.bot.send_message(
self.bot.fetch_channel('games'),
"Unfortunately, saved games are not supported by "
"the story system at this time."
)
... |
xavitorne/mountain-rehub | config.py | Python | mit | 490 | 0.012245 | im | port os
basedir = os.path.abspath(os.path.dirname(__file__))
# if you have postgres use this uri:
SQLALCHEMY_DATABASE_URI = "postgresql://rehub:rehub@localhost/rehub"
# if you want to use sqlite, use this one:
# SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'rehub.db')
SQLALCHEMY_MIGRATE_REPO = os.p... | in'
SECRET_KEY='$cippalippa!'
CSRF_ENABLED=True
|
glarue-ol/sensorlab-observer | observer/m_sensorlab/sensorlab.py | Python | mpl-2.0 | 20,640 | 0.003004 | # -*- coding: utf-8 -*-
"""
`author` : Quentin Lampin <quentin.lampin@orange.com>
`license` : MPL
`date` : 2015/10/05
SensorLab Encapsulation Library
--------------------------
This module provides utility functions to generate SensorLab formatted event reports.
`Requires python 3.2 or above`
"""
i... | s_count)
return header
def entity_property_update_header(entity_id, properties_count):
"""
Builds a Entity Property Update Header.
An entity property is updated using the Node Property Update Header (event ID: EVENT_ENTITY_PROPERTY_UPDATE).
If propertiesCount > 0, the NodePropertyUpdate header mu... | ntityPropertyAdd header structure is:
- entityID : 1-byte. ID of the entity.
- propertiesCount : 1-byte. Number of properties describing the entity node_state.
Args:
entity_id (unsigned char):
properties_count (unsigned char)
Returns:
bytes: the Entity Pr... |
Akuli/editor | porcupine/plugins/run/terminal.py | Python | mit | 5,179 | 0.001159 | """Run commands in a new terminal window."""
from __future__ import annotations
import logging
import os
import shlex
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from tkinter import messagebox
from porcupine import get_main_window, utils
log = logging.getLogger(__name__)
_thi... | nal.app")
assert shutil.which("bash") is not None
with tempfile.NamedTemporaryFile("w", delete=False, prefix="porcupine-run-") as file:
print("#!/usr/bin/env bash", file=file)
print("rm", shlex.quote(file.name), file=file) # runs even if command is interrupted
print(
shlex.... | uote(str(run_script)),
"--dont-wait",
shlex.quote(str(cwd)),
shlex.quote(command),
file=file,
)
os.chmod(file.name, 0o755)
subprocess.Popen(["open", "-a", "Terminal.app", file.name])
# the terminal might be still opening when we get here, that's why
... |
cosven/pat_play | classics/test_quick_sort.py | Python | gpl-3.0 | 103 | 0 | def quick_sort(array):
p | ass
def test_quick_sort():
assert quick_sort([1 | , 3, 2]) == [1, 2, 3]
|
indico/indico | indico/modules/events/surveys/forms.py | Python | mit | 7,812 | 0.006272 | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import time
from flask import request
from markupsafe import escape
from wtforms.fields imp... | .pop('allow_reschedule_start')
self.timezone = survey.event.timezone
super().__init__(*args, **kwargs)
if not survey.start_notification_sent or not self.allow_reschedule_start:
del self.resend_start_notification
class SectionForm(IndicoForm):
display_as_section = BooleanField(_... | er this is going to be displayed as a section or standalone'))
title = StringField(_('Title'), [HiddenUnless('display_as_section', preserve_data=True), DataRequired()],
description=_('The title of the section.'))
description = TextAreaField(_('Description'), [HiddenUnless('display_as_sec... |
mher/pymongo | pymongo/son.py | Python | apache-2.0 | 600 | 0 | # | Copyright 2009-2010 10gen, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | nse is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from bson.son import *
|
willingc/portal | systers_portal/membership/admin.py | Python | gpl-2.0 | 111 | 0 | from | django.contrib import admin
from membership.models import JoinRequest
admin.site.register(JoinRe | quest)
|
noroutine/ansible | lib/ansible/modules/network/cumulus/_cl_bond.py | Python | gpl-3.0 | 15,451 | 0.000647 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, Cumulus Networks <ce-ceng@cumulusnetworks.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_versio... | ulus Linux 2.5 only LACP bond mode is
supported.
default: '802.3ad'
min_links:
description:
- Minimum number of links.
default: 1
lacp_bypass_allow:
description:
- Enable LACP bypass.
lacp_bypass_period:
description:
- | Period for enabling LACP bypass. Max value is 900.
lacp_bypass_priority:
description:
- List of ports and priorities. Example I("swp1=10, swp2=20").
lacp_bypass_all_active:
description:
- Activate all interfaces for bypass.
It is recommended to configure al... |
chemelnucfin/tensorflow | tensorflow/python/keras/layers/cudnn_recurrent.py | Python | apache-2.0 | 20,970 | 0.003386 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | else:
return output
def get_config(self):
config = {
'return_sequences': self.return_sequences,
'return_state': self.return_state,
'go_backwards': self.go_backwards,
'stateful': self.stateful,
'time_major': self.time_major,
}
base_config = super( # pylin... |
return cls(**config)
@property
def trainable_weights(self):
if self.trainable and self.built:
return [self.kernel, self.recurrent_kernel, self.bias]
return []
@property
def non_trainable_weights(self):
if not self.trainable and self.built:
return [self.kernel, self.recurrent_kerne... |
rloliveirajr/sklearn_transformers | trans4mers/feature_extraction/relative_location_fingerprint.py | Python | gpl-2.0 | 463 | 0 | import numpy as np
from .fingerprint import Fingerprint
class RelativeLocationFingerprint(Fingerprint):
def trans_func_(self, row):
values = row
max_value = max(values)
features = []
for i in range(0, len(values)):
for j in range(0, len(values | )):
if i == j:
continue
r = values[i] / float(values[j])
| features.append(r)
return features
|
NLViewJeroen/NLView-Repository | plugin.video.NLVIEW/foxsports.py | Python | gpl-3.0 | 17,021 | 0.021033 | import urllib, urllib2, re, cookielib, os, sys, socket
import xbmc, xbmcplugin, xbmcgui, xbmcaddon
import utils, sqlite3
def Main():
utils.addDir('Zoeken','http://www.foxsports.nl/search/videos/?q=',230,'https://raw.githubusercontent.com/doki1/repo/master/NLView%20XML/fs.png','',fanart='https://raw.githubusercon... | oxsports.nl/video/filter/fragments/1/alle/overige/',228,'https://raw.githubusercontent.com/doki1/rep | o/master/NLView%20XML/fs.png',1,fanart='https://raw.githubusercontent.com/doki1/repo/master/NLView%20XML/fanart.jpg')
utils.addDir('Aanbevolen','http://www.foxsports.nl/video/filter/fragments/1/aanbevolen/',228,'https://raw.githubusercontent.com/doki1/repo/master/NLView%20XML/fs.png',1,fanart='https://raw.githubus... |
alexisflesch/texamator | partielatormods/guis/guiquit.py | Python | gpl-3.0 | 3,316 | 0.003317 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'quitter.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObject... | alog", "Do you really want to quit TeXamator ?"))
self.pushButton_cancel.setText(_translate("Dialog", "Cancel"))
self.pushButton_ok.setText(_translate("Dialog", "Ok"))
from . import icones_rc
if __name__ == "__main__":
import sys
app = | QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
|
kenhys/sphinxcontrib-openstreetmap | sphinxcontrib/__init__.py | Python | bsd-2-clause | 365 | 0 | # -*- coding: utf-8 -*-
"""
sphinxcontrib
~~~~~~~~~~~~~
This package is a namespace package that contains all extensions
distributed in the ``sphinx-contrib`` distribution.
:copyright: Copyright 2015 by HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see | LICENSE for details.
"""
__import__('pkg_resources').declar | e_namespace(__name__)
|
pfschwartz/openelisglobal-core | liquibase/OE4.2/testCatalogCI_Regional_labs/scripts/populateNames.py | Python | mpl-2.0 | 1,560 | 0.005128 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
test_names = []
guids = []
populateNames = []
name_results = []
name_file = open('englishTestName.txt','r')
sample_type_file = open("sampleType.txt")
guid_file = open("guid.txt")
result_file = open("../populateNames.sql", "w")
for line in name_file:
t... | ere guid ='"
updateReportingStri | ng = "update clinlims.test set reporting_name_localization_id = lastval() where guid ='"
for row in range(0, len(guids)):
if guids[row]:
name_results.append(insertString)
name_results.append("\tVALUES ( nextval('localization_seq'), 'test name', '" + test_names[row] + "', (select name fro... |
BroukPytlik/volunteer-organiser | organiser/board/migrations/0017_auto_20150804_2008.py | Python | gpl-3.0 | 430 | 0.002326 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('board', '0016_auto_20150804_1938'),
]
o | perations = [
migrations.Alt | erField(
model_name='holiday',
name='until',
field=models.DateField(verbose_name='until', blank=True, null=True),
),
]
|
danwent/Perspectives-Server | notary_util/threaded_scanner.py | Python | gpl-3.0 | 10,401 | 0.030382 | # This file is part of the Perspectives Notary Server
#
# Copyright (C) 2011 Dan Wendlandt
#
# 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, version 3 of the License.
#
# This progra... | r += 1
def run(self):
"""
Scan a remote service and retrieve the fingerprint for its TLS certificate.
The fingerprint is appended to the global results list.
"""
try:
fp = attempt_observation_for_service(self.sid, self.timeout_sec, self.sni)
if (fp != None):
results.add((self.sid, fp))
else:
... | = 1
except Exception, e:
self._record_failure(e)
logging.error("Error scanning '{0}' - {1}".format(self.sid, e))
logging.exception(e)
self.global_stats.num_completed += 1
self.global_stats.active_threads -= 1
if self.sid in self.global_stats.threads:
del self.global_stats.threads[self.sid]
clas... |
chen2aaron/TangoWithDjangoProject | rango/urls.py | Python | gpl-2.0 | 646 | 0.008621 | # -*- coding:utf-8 -*-
from django.conf.urls import url, patterns
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r' | ^about/$', views.about, name='about'),
# 匹配URL斜杠前所有的字母数字
# 例如 a-z, A-Z, 或者 0-9)和连字符(-
# 然后把这个值作为category_name_slug参数传递给views.category(),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$',views.category, name='category'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^c... | ),
)
|
blue-yonder/bonfire | bonfire/_version.py | Python | bsd-3-clause | 8,274 | 0 | #! -*- coding: utf-8 -*-
"""
Retrieval of version number
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 s... | haves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us distingui | sh
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '{}',... |
haoyuchen1992/osf.io | website/addons/googledrive/serializer.py | Python | apache-2.0 | 1,189 | 0 | from website.addons.base.serializer import OAuthAddonSerializer
from website.addons.googledrive.exceptions import ExpiredAuthError
class GoogleDriveSerializer(OAuthAddonSerializer):
@property
def addon_serialized_urls(self):
node = self.node_settings.owner
return {
'files': node.... | er_auth'),
'importAuth': node.api_url_for('googledrive_import_user_auth'),
'folders': node.api_url_for('googledrive_folders'),
'accounts': node.api_url_for('list_googledrive_user_accounts')
}
@property
def serialized_node_settings(self):
result = super(Google... | valid_credentials = True
if self.node_settings.external_account is not None:
try:
self.node_settings.fetch_access_token()
except ExpiredAuthError:
valid_credentials = False
result['validCredentials'] = valid_credentials
return {'result': ... |
kstaniek/fiblary | examples/info.py | Python | apache-2.0 | 1,435 | 0.000697 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Klaudiusz Staniek
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | s:
| print device.name
devices = hc2.devices.list(id=1)
for device in devices:
print device.name
if __name__ == '__main__':
main()
|
anhstudios/swganh | data/scripts/templates/object/tangible/ship/components/engine/shared_eng_moncal_ifs32.py | Python | mit | 477 | 0.046122 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE | IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/engine/shared_eng_moncal_ifs32.iff"
result.att | ribute_template_id = 8
result.stfName("space/space_item","eng_moncal_ifs32_n")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
tanujs22/crowdsource-platform | crowdsourcing/viewsets/project.py | Python | mit | 18,897 | 0.005239 | from rest_framework import status, viewsets
from rest_framework.response import Response
from crowdsourcing.serializers.project import *
from crowdsourcing.serializers.task import TaskWorkerSerializer
from rest_framework.decorators import detail_route, list_route
from crowdsourcing.models import Module, Category, Proje... | roject_serializer.is_valid():
project_serializer.update(project, project_serializer.validated_data)
return Response({'status': 'updated project'})
else:
| return Response(project_serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
def list(self, request, *args, **kwargs):
requester_id = -1
if hasattr(request.user.userprofile, 'requester'):
requester_id = request.user.userprofile.requester.id
... |
Yellowpal/django | life/bill/migrations/0002_auto_20161111_1113.py | Python | gpl-3.0 | 1,237 | 0.002425 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-11 03:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.delet | ion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('bill', '0001_initial'),
]
operations = [
m | igrations.CreateModel(
name='Type',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20)),
('status', models.IntegerField()),
('update_d... |
kg-bot/SupyBot | plugins/UrbanDict/plugin.py | Python | gpl-3.0 | 4,100 | 0.000488 | ###
# Copyright (c) 2004-2005, Kevin Murphy
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of condit... | provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors 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 CONTRIB... | HANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ... |
trivoldus28/pulsarch-verilog | tools/local/bas-release/bas,3.9/lib/python/lib/python2.3/bsddb/test/test_compat.py | Python | gpl-2.0 | 3,862 | 0.002589 | """
Test cases adapted from the test_bsddb.py module in Python's
regression test suite.
"""
import sys, os, string
import unittest
import tempfile
from test_all import verbose
try:
# For Python 2.3
from bsddb import db, hashopen, btopen, rnopen
except ImportError:
# For earlier Pythons w/distutils pybsdd... |
self.assertRaises(KeyError, noRec, f)
def badKey(f):
rec = f[15]
self.assertRaises(TypeError, badKey, f)
f.close()
#----------------------------------------------------------------------
def test_suite():
return unittest.makeSuite(CompatibilityTestCase)
if __name... | tTest='test_suite')
|
purushothamc/myibitsolutions | hashing/list_anagrams.py | Python | gpl-3.0 | 430 | 0.009302 | def anagrams(A):
mapper = dict()
for index, string in enumer | ate(A):
string = "".join(sorted(string))
print mapper
if not mapper.get(string, 0):
mapper | [string] = [index + 1]
else:
mapper[string].append(index + 1)
result = []
for key, val in mapper.iteritems():
result.append(val)
return result
A = [ "cat", "dog", "god", "tca" ]
print anagrams(A) |
mattbasta/perfalator | tests/js/test_traversal.py | Python | bsd-3-clause | 1,900 | 0 | from js_helper import TestCase
class TestFunctionTraversal(TestCase):
"""
Consider the following tree:
- body
|-function a()
| |- foo
| |- bar
|-zip
|-function b()
| |-abc
| |-def
|-zap
In the old traversal technique, it would be evaluated in the order... | m prefix notation
traversal where all | non-function nodes are traversed before all function
nodes.
"""
def test_function_declaration_order(self):
"""Test that function declarations happen in the right time."""
self.run_script("""
foo = "first";
function test() {
foo = "second";
}
bar ... |
Ledoux/ShareYourSystem | Pythonlogy/build/lib/ShareYourSystem/Standards/Itemizers/Teamer/09_ExampleDoc.py | Python | mit | 228 | 0.039474 |
#ImportModules
import | ShareYourSystem as SYS
#define
MyTeamDict=SYS.Teamer.TeamDict([('a',1),('b',2)])
#print
print('MyTeamDict is ')
SYS._print(MyTeamDict)
#get
print(MyTeamDict.get | Value(0))
print(MyTeamDict.getValue(1))
|
azumimuo/family-xbmc-addon | plugin.video.phstreams/resources/lib/resolvers/veehd.py | Python | gpl-2.0 | 1,792 | 0.006138 | # -*- coding: utf-8 -*-
'''
Genesis Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 | of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but 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 ... | .lib.modules import client
domains = ['veehd.com']
def resolve(url):
try:
headers = '|%s' % urllib.urlencode({'User-Agent': client.agent(), 'Referer': url})
result = client.request(url, close=False)
result = result.replace('\n','')
url = re.compile('function\s*load_download.+?s... |
google/clusterfuzz | src/clusterfuzz/_internal/tests/appengine/handlers/issue_redirector_test.py | Python | apache-2.0 | 2,102 | 0.002379 | # 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.apac | he.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is | distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the issue redirector handler."""
import unittest
import mock
import webtest
from clusterfuzz.... |
seung-lab/cloud-volume | cloudvolume/datasource/precomputed/image/__init__.py | Python | bsd-3-clause | 18,157 | 0.009748 | """
The Precomputed format is a neuroscience imaging format
designed for cloud storage. The specification is located
here:
https://github.com/google/neuroglancer/tree/master/src/neuroglancer/datasource/precomputed
This datasource contains the code for manipulating images.
"""
from functools import reduce
import iter... | er:
raise ValueError("renumber is only supported for non-shared volume | s.")
scale = self.meta.scale(mip)
spec = sharding.ShardingSpecification.from_dict(scale['sharding'])
return rx.download_sharded(
bbox, mip,
self.meta, self.cache, self.lru, spec,
compress=self.config.compress,
progress=self.config.progress,
fill_missing=self.f... |
lichengshuang/createvhost | python/asher/getcmdbinfo/bin/getcmdbinfo.py | Python | apache-2.0 | 5,242 | 0.012292 | #!/usr/bin/python
#coding: utf-8
#auth: asher
#date: 20171027
#purpose: get usefulinfo from jsonfile
import ConfigParser
import time
import datetime
import requests
import fileinput
import sys
import os
import codecs
import json
import getWarranty
reload(sys)
sys.setdefaultencoding( "utf-8" )
def getConfig():
"... | lls['MachineDescription'] = newinfos['MachineDescription']
dells['StartD | ate'] = newinfos['StartDate']
dells['EndDate'] = newinfos['EndDate']
expiretime = dells['EndDate']
nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
expire1 = datetime.datetime.strptime(expiretime,"%Y-%m-%d %H:%M:%S")
nowtime1 = datet... |
L34p/HeXA-CTF-2015 | gameboard/management/commands/gamestop.py | Python | mit | 513 | 0.013645 | from django.core.management import BaseCommand
from gameboard.models import Entries
#The class must be named Command, and subclass BaseCommand
class Comm | and(BaseCommand):
# Show this when the user | types help
help = "Stop CTF! Disable all problem entries... (set is_active=False)"
# A command must define handle()
def handle(self, *args, **options):
self.stdout.write("Stop CTF!")
prob_entries = Entries.objects.all()
for entry in prob_entries:
entry.is_active = False
entry.save()
|
NS2LPS/pyslave | test/pydata/test_datadict.py | Python | mit | 574 | 0.013937 | from pydata import Data, h5todata
import numpy as np
impo | rt os
import h5py
def test_Data(tmpdir):
o = Data(x=np.ones(3), y=np.ones(3), a=5, b='hh')
assert o.b=='hh'
assert o['a']==5
o.append(np.ones(5),np.ones(5))
o.save(os.path.join(tmpdir, 'test.txt'))
o.save(os.path.join(tmpdir, 'test.h5'))
de | f test_h5todata(tmpdir):
o = Data(x=np.ones(3), y=np.ones(3), a=5, b='hh')
o.save(os.path.join(tmpdir, 'test.h5'))
f = h5py.File(os.path.join(tmpdir, 'test.h5'),'r')
d = h5todata(f['data0000'])
assert d.a==5
assert d.x[0]==1
|
srinathv/bokeh | bokeh/plot_object.py | Python | bsd-3-clause | 11,126 | 0.002696 | from __future__ import absolute_import, print_function
import logging
logger = logging.getLogger(__file__)
from six import add_metaclass, iteritems
from .properties import Any, HasProps, List, MetaHasProps, Instance, String
from .query import find
from .exceptions import DataIntegrityException
from .util.serializati... | roperties_with_refs():
if p in attrs:
ref_props[p] = attrs.pop(p)
instan | ce._ref_props = ref_props
instance.update(**attrs)
return instance
def layout(self, side, plot):
try:
return self in getattr(plot, side)
except:
return []
def finalize(self, models):
"""Convert any references into instances
models is a d... |
samatdav/zulip | zerver/views/messages.py | Python | apache-2.0 | 50,615 | 0.003695 | from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.conf import settings
from django.core import validators
from django.core.exceptions import ValidationError
from django.db import connection
from django.db.models import Q
from django.... | # We have to be careful here because we're letting users call a method
# by name! The prefix 'by_' prevents it from colliding with builtin
# Python __magic__ stuff.
operator = term['operator']
operand = term['operand']
negated = term.get('negated', False)
method... | raise BadNarrowOperator('unknown operator ' + operator)
if negated:
maybe_negate = not_
else:
maybe_negate = lambda cond: cond
return method(query, operand, maybe_negate)
def by_has(self, query, operand, maybe_negate):
# type: (Query, str, Conditi... |
ElDeveloper/qiita | qiita_db/support_files/patches/python_patches/75.py | Python | bsd-3-clause | 7,784 | 0 | from qiita_db.user import User
from json import loads, dumps
from qiita_core.qiita_settings import r_client
from qiita_db.sql_connection import TRN
from qiita_db.software import Software, Command
from qiita_db.exceptions import QiitaDBError, QiitaDBDuplicateError
from qiita_db.util import convert_to_id
# one of the ... | %s, %s)
RETURNING command_id"""
sql_params = [name, software.id, description, analysis_only]
TRN.add(sql, sql_params)
c_id = TRN.execute_fetchlast()
# Add the parameters to the DB
sql = """INSERT INTO qiita.command_parameter
(command_id, para... | default_value)
VALUES (%s, %s, %s, %s, %s)
RETURNING command_parameter_id"""
sql_params = [[c_id, pname, p_type, reqd, default]
for pname, p_type, reqd, default in sql_param_values]
TRN.add(sql, sql_params, many=True)
TRN.exe... |
immo/pyTOM | df/df_ontology.py | Python | gpl-3.0 | 3,602 | 0.028318 | # coding: utf-8
#
# drums-backend a simple interactive audio sampler that plays vorbis samples
# Copyright (C) 2009 C.D. Immanuel Albrecht
#
# 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 Fou... |
return f
def meetleft(features, partners):
"""meetleft(features, partners) meet features with partners"""
f = { | }
for x in features:
if x in partners:
f[x] = features[x]
return f
def joinleft(defaultfeatures, newfeatures):
"""joinleft(defaultfeatures, newfeatures) join features with partners"""
f = newfeatures
for x in defaultfeatures:
f[x] = defaultfeatures[x]
return f
def get_atomic_d... |
michalbachowski/pycontentbits | test/factory_test.py | Python | bsd-3-clause | 5,366 | 0.000373 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
##
# python standard library
#
import unittest
from functools import partial
##
# test helper
#
from testutils import mock, IsA
##
# content bits modules
#
from contentbits.factory import CollectionFactory
class CollectionFactoryTestCase(unittest.TestCase):
def se... | k.MagicMock()
self.cf = CollectionFactory(self.collection, self.item)
def test_init_requires_no_arguments(self):
err = False
try:
| CollectionFactory()
except TypeError:
err = True
self.assertFalse(err)
def test_init_allows_2_arguments(self):
err = False
try:
CollectionFactory(None)
CollectionFactory(None, None)
except TypeError:
err = True
se... |
bhermanmit/openmc | openmc/mgxs/__init__.py | Python | mit | 147 | 0 | from openmc | .mgxs.groups import EnergyGroups
from openmc.mgxs.library import Library
from openmc.mgxs.mgxs import *
from openmc.mgxs.mdgxs imp | ort *
|
opencorato/sayit | speeches/utils/base32.py | Python | agpl-3.0 | 778 | 0 | digits = "0123456789abcdefghjkmnpqrstvwxyz"
class MistypedIDException(Exception):
pass
def int_to_base32(i):
"""Converts | an integer to a base32 string"""
enc = ''
while i >= 32:
i, mod = divmod(i, 32)
enc = digits[mod] + enc
enc = digits[i] + enc
return enc
def base32_to_int(s):
"""Convert a base 32 string to an integer"""
mistyped = False
if s.find('o') > -1 or s.find('i') > -1 or s.find('l'... | ex(s[-1:])
multi = multi * 32
s = s[:-1]
if mistyped:
raise MistypedIDException(decoded)
return decoded
|
vericoin/vericoin-core | contrib/bitrpc/bitrpc.py | Python | mit | 9,384 | 0.002984 | from jsonrpc import ServiceProxy
import sys
import string
import getpass
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:8332")
e... |
except:
print access.getreceivedbyaccount()
except Exception as inst:
print inst
elif cmd == "getreceivedbyaddress":
try:
addr = raw_input("Enter a VeriCoin address (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print ac... | access.getreceivedbyaddress()
except Exception as inst:
print inst
elif cmd == "gettransaction":
try:
txid = raw_input("Enter a transaction ID: ")
print access.gettransaction(txid)
except Exception as inst:
print inst
elif cmd == "getwork":
try:
data = raw_inpu... |
amwelch/a10sdk-python | a10sdk/core/cgnv6/cgnv6_lsn_alg_ftp_stats.py | Python | apache-2.0 | 2,390 | 0.008787 | from a10sdk.common.A10BaseClass import A10BaseClass
class Stats(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param lpsv_replies: {"description": "LPSV Replies From Server", "format": "counter", "type": "number", "oid": "6", "optional": true, "size": "8"}
:param p... |
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cgnv6/lsn/alg/ftp/stats`.
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
| self.required=[]
self.b_key = "ftp"
self.a10_url="/axapi/v3/cgnv6/lsn/alg/ftp/stats"
self.DeviceProxy = ""
self.stats = {}
for keys, value in kwargs.items():
setattr(self,keys, value)
|
Kalvar/python-GreyTheory | greytheory/packages/models/grey_class.py | Python | mit | 2,945 | 0.008829 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import copy
import numpy as np
from ..libs.grey_lib import GreyLib
from ..libs.grey_math import GreyMath
from .grey_factory import GreyFactory
from .grey_forecast import GreyForecast
class GreyClass (object):
_TAG_FORECAST_NEXT_MOMENT = "forecasted_next_moment"
_TAG... | self( | )
for forecast in self.analyzed_results:
print("K = %r" % forecast.k)
if forecast.tag == self._TAG_FORECAST_HISTORY:
# History.
print("From original value %r to forecasted value is %r" % (forecast.original_value, forecast.forecast_value))
p... |
pqpo/appiumn_auto_re-develope | common/basePickle.py | Python | apache-2.0 | 885 | 0.00339 | __author__ = "shikun"
import pickle
import os
from common import operateFile
from common.variable import Constants
def write_pickle(dict_data, path="data.pickle"):
read = read_pickle(path)
result = []
if len(read) > 0:
read.append(dict_data)
result = read
else:
result.append(di... | le.dump(result, f, 0)
def read_pickle(path):
| pickle_data = {}
if operateFile.OperateFile(path).check_file():
with open(path, 'rb') as f:
try:
pickle_data = pickle.load(f)
except EOFError:
pass
return pickle_data
if __name__ == "__main__":
data = {"log":"132"}
write_pickle(data, pat... |
googleapis/python-bigquery-storage | samples/generated_samples/bigquerystorage_v1beta2_generated_big_query_write_append_rows_sync.py | Python | apache-2.0 | 1,884 | 0.000531 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | orage_v1beta2
def sample_append_rows():
# Create a client
client = bigquery_storage_v1beta2.BigQueryWriteClient()
# Initialize request argument(s)
request = bigquery_storage_v1beta2.AppendRowsRequest(
write_stream="write_stream_value",
)
# This method expects an iterator which contai... |
def request_generator():
for request in requests:
yield request
# Make the request
stream = client.append_rows(requests=request_generator())
# Handle the response
for response in stream:
print(response)
# [END bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRo... |
heuer/segno | tests/test_png_plte.py | Python | bsd-3-clause | 1,978 | 0.002528 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2022 -- Lars Heuer
# All rights reserved.
#
# License: BSD License
#
"""\
Tests if the PNG serializer does not add more colors than needed.
See also issue <https://github.com/heuer/segno/issues/62>
"""
from __future__ import unicode_literals, absolute_import
import io
i... | ro('RAIN')
dark = 'red'
buff_1 = io.BytesIO()
buff_2 = io.BytesIO()
qr.save(buff_1, kind='png', dark=dark, finder_dark=dark, alignment_dark='green')
qr.save(buff | _2, kind='png', dark=dark)
assert buff_1.getvalue() == buff_2.getvalue()
def test_plte_micro2():
qr = segno.make_micro('RAIN')
dark = 'red'
buff_1 = io.BytesIO()
buff_2 = io.BytesIO()
qr.save(buff_1, kind='png', dark=dark, finder_dark=dark, dark_module='green')
qr.save(buff_2, kind='png', ... |
itbabu/saleor | saleor/dashboard/product/views.py | Python | bsd-3-clause | 18,025 | 0 | from __future__ import unicode_literals
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.http import is_safe_url
from django.utils.translation import pgettext... | method == 'POST':
product_class.delete()
messages.success(
request,
pgettext_lazy(
'Dashboard message',
'Deleted product type %s') % product_class)
return redirect('dashboard:product-class-list')
return TemplateResponse(
request... | product_class, 'products': products})
@staff_member_required
def product_list(request):
products = Product.objects.prefetch_related('images')
product_classes = ProductClass.objects.all()
form = forms.ProductClassSelectorForm(
request.POST or None, product_classes=product_classes)
if form.is_va... |
wateraccounting/SEBAL | interpolation/QGIS_.py | Python | apache-2.0 | 3,702 | 0.012426 | #!/usr/bin/env python
import os
import numpy as np
from scipy import interpolate
from osgeo import gdal, osr
#functions
def GetGeoInfo(filename, | Subdataset = 0):
"""Gives geo-information derived from a georeferenced map
filename: file to be scrutinized
subdataset: layer to be used in case of HDF4 format
"""
SourceDS = gdal.Open(filename, gdal.GA_ReadOnly)
Type = SourceDS.GetDriver().ShortName
if Type == 'HDF4' or Type == 'netCD... | rceDS.GetSubDatasets()[Subdataset][0])
NDV = SourceDS.GetRasterBand(1).GetNoDataValue()
xsize = SourceDS.RasterXSize
ysize = SourceDS.RasterYSize
GeoT = SourceDS.GetGeoTransform()
Projection = osr.SpatialReference()
Projection.ImportFromWkt(SourceDS.GetProjectionRef())
#DataType = SourceDS.G... |
deepaklukose/grpc | tools/run_tests/artifacts/package_targets.py | Python | apache-2.0 | 4,688 | 0.000213 | #!/usr/bin/env python
# Copyright 2016 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ,
timeout_retries=timeout_retries)
return jobspec
def create_jobspec(name,
cmd | line,
environ=None,
cwd=None,
shell=False,
flake_retries=0,
timeout_retries=0):
"""Creates jobspec."""
jobspec = jobset.JobSpec(
cmdline=cmdline,
environ=environ,
cwd=cwd,
shortname='bu... |
lightbase/LBSociam | lbsociam/model/crimes.py | Python | gpl-2.0 | 15,820 | 0.001517 | #!/usr/env python
# -*- coding: utf-8 -*-
__author__ = 'eduardo'
import logging
import datetime
import requests
import json
from requests.exceptions import HTTPError
from lbsociam import LBSociam
from liblightbase import lbrest
from liblightbase.lbbase.struct import Base, BaseMetadata
from liblightbase.lbbase.lbstruct... | 'Taxonomy related images',
alias='images',
datatype='File',
indices=[],
multivalued=True,
required=False
))
default_token = Field(**dict(
name='default_token',
description='Default token for this category',
... | indices=['Ordenado'],
multivalued=False,
required=False
))
color = Field(**dict(
name='color',
description='Color to be shown on interface',
alias='Color',
datatype='Text',
indices=[],
multivalued=False... |
rlenglet/openfaucet | src/openfaucet/test_ofstats.py | Python | apache-2.0 | 12,672 | 0 | # Copyright 2011 Midokura KK
#
# 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, ... | "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unittests for ofstats.py.
"""
import struct
import unittest2
from openfaucet import buffer
from openfaucet import ofacti... | elf.buf = buffer.ReceiveBuffer()
self.mfr_desc = 'Dummy Manufacturer Inc.'
self.hw_desc = 'DummySwitch'
self.sw_desc = 'DummyOS'
self.serial_num = '0000000042'
self.dp_desc = 'unittest switch'
self.desc_stats = ofstats.DescriptionStats(
mfr_desc=self.mfr_desc,... |
Hispar/pycraft | tests/test_configuration.py | Python | mit | 3,042 | 0.001315 | """
Unit tests for the configuration loader module.
"""
import os
import json
from pycraft.configuration import ConfigurationLoader
DEFAULT_CONFIG = {
"window": {
"width": 800,
"height": 600,
"ticks_per_second": 60,
"resizeable": True,
"exclusive_mouse": True,
},
"... | },
"controls": {
"forward": "Z",
"backward": "S",
"r | ight": "D",
"left": "Q",
"jump": "LSHIFT",
"down": "TAB",
"fly": "SPACE",
},
"world": {
"gravity": 234.0,
"player_height": 123,
"max_jump_height": 34.1,
"terminal_velocity": 431,
"walking_speed": ... |
rg3915/orcamentos | orcamentos/core/management/commands/conclude_proposal.py | Python | mit | 1,080 | 0 | from django.core.management.base import BaseCommand
from optparse import make_option
from django.utils import timezone
from orcamentos.proposal.models import Proposal
class Command(BaseCommand):
help = ''' Conclui orçamento. '''
option_list = BaseCommand.option_list + (
make_option('--num', help='núme... | _option('--price', help='preço'),
)
def handle(self, num, price, *args, **kwargs):
proposal = Proposal.objects.get(num_prop=num)
# Se o status for 'aprovado', então não pode concluir.
if proposal.status == 'a':
print('Este orçamento já virou contrato.')
else:
... | # verifica se o novo valor é positivo.
if float(price) <= 0 or float(price) is None:
print('O valor deve ser positivo.')
else:
proposal.price = price
proposal.status = 'co'
proposal.date_conclusion = timezone.now()
... |
tensorflow/tensorflow | tensorflow/python/ops/ragged/ragged_tensor_value.py | Python | apache-2.0 | 4,366 | 0.006413 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 1=["ragged.RaggedTensorValue"])
@dispatch.register_dispatchable_type
class RaggedTensorValue:
"""Represents the value of a `RaggedTensor`.
Warning: `RaggedTensorValue` should only be used in graph mode; in
eager mode, the `tf.RaggedTen | sor` class contains its value directly.
See `tf.RaggedTensor` for a description of ragged tensors.
"""
def __init__(self, values, row_splits):
"""Creates a `RaggedTensorValue`.
Args:
values: A numpy array of any type and shape; or a RaggedTensorValue.
row_splits: A 1-D int32 or int64 numpy ... |
sdispater/pendulum | tests/conftest.py | Python | mit | 2,211 | 0 | import pytest
import pendulum
@pytest.fixture(autouse=True)
def setup():
pendulum.set_local_timezone(pendulum.timezone("America/Toronto"))
yield
pendulum.set_test_now()
pendulum.set_locale("en")
pendulum.set_local_timezone()
pendulum.week_starts_at(pendulum.MONDAY)
pendulum.week_ends_at... | .months
actual["months"] = months
if weeks is not None:
expected["weeks"] = dur.weeks
actual["weeks"] = weeks
if days is not None:
expected["days"] = dur.remaining_days
actual["days"] = days
if hours is not None:
expected[ | "hours"] = dur.hours
actual["hours"] = hours
if minutes is not None:
expected["minutes"] = dur.minutes
actual["minutes"] = minutes
if seconds is not None:
expected["seconds"] = dur.remaining_seconds
actual["seconds"] = seconds
if microseconds is not None:
e... |
akbarpn136/inventaris-dj | reformasi/views.py | Python | apache-2.0 | 290 | 0 | from django.shortcuts import render
from .models import KumpulanDokumen
# Create your views here.
def index(request):
data_dokumen = KumpulanDokumen.objects.all()
data = {
'dokumen': | data_dokumen
}
return render(request, 'reformasi/daftar_reformasi.ht | ml', data)
|
tensorflow/lucid | lucid/recipes/image_interpolation_params.py | Python | apache-2.0 | 2,768 | 0.006142 | # Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | A [n_objectives, n_objectives, n_interp_steps, width, width, channel]
shaped tensor, t, where the final [width, width, channel] should be
seen as images, such that the following properties hold:
t[a, b] = t[b, a, ::-1]
t[a, i, 0] = t[a, j, 0] for all i, j
t[a, a, i] = t[a, a, j] for all i, j... | s, n_interp_steps, width, channels
const_term = sum([lowres_tensor([W, W, Ch], [W//k, W//k, Ch])
for k in [1, 2, 4, 8]])
const_term = tf.reshape(const_term, [1, 1, 1, W, W, Ch])
example_interps = [
sum([lowres_tensor([M, W, W, Ch], [2, W//k, W//k, Ch])
for k in [1, 2, 4, 8]]... |
nuance/GoTools | gotools_oracle.py | Python | mit | 3,748 | 0.004536 | import sublime
import sublime_plugin
import os
from .gotools_util import Buffers
from .gotools_util import GoBuffers
from .gotools_util import Logger
from .gotools_util import ToolRunner
import golangconfig
class GotoolsOracleCommand(sublime_plugin.TextCommand):
def __init__(self, *args, **kwargs):
super... | le " + mode + " output: " + output.rstrip())
if rc != 0:
Logger.status("oracle call failed (" + str(rc) + "): " + output.strip())
| return
Logger.status("oracle " + mode + " finished")
panel = self.view.window().create_output_panel('gotools_oracle')
panel.set_scratch(True)
panel.settings().set("result_file_regex", regex)
panel.run_command("select_all")
panel.run_command("right_delete")
panel.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.