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 |
|---|---|---|---|---|---|---|---|---|
ecell/ecell3 | ecell/frontend/model-editor/ecell/ui/model_editor/ComplexLine.py | Python | lgpl-3.0 | 13,350 | 0.027416 | #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# This file is part of the E-Cell System
#
# Copyright (C) 1996-2016 Keio University
# Copyright (C) 2008-2016 RIKEN
# Copyright (C) 2005-2009 The Molecular Sciences Institute
#
#:::::::::::::::::::::::::::::::::::::::... | neSD) it will overwrite the middle line, I THINK OLI
def createLine( self, aDes | criptor ):
lineSpec = aDescriptor[SD_SPECIFIC]
( X1, X2, Y1, Y2 ) = [lineSpec[0], lineSpec[2], lineSpec[1], lineSpec[3] ]
aGdkColor = self.getGdkColor( aDescriptor )
firstArrow = lineSpec[4]
secondArrow = lineSpec[5]
aLine = self.theRoot.add( gnomecan... |
birkenfeld/rick | test.py | Python | gpl-2.0 | 4,893 | 0.002044 | # -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License... | print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
... | )' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
... |
Passtechsoft/TPEAlpGen | blender/release/scripts/addons_contrib/mesh_snap_utilities_line.py | Python | gpl-3.0 | 41,708 | 0.007025 | ### BEGIN GPL LICENSE BLOCK #####
#
# 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... | is_increment = True
orig, view_vector = region_2d_to_orig_and_view_vector(region, rv3d, mcursor)
end = orig + view_vector
location = intersect_line_line(c | onstrain[0], constrain[1], orig, end)
if location:
self.location = location[0]
else:
self.location = constrain[0]
elif hasattr(self, 'Pperp') and abs(self.Pperp[0]-mcursor[0]) < 10 and abs(self.Pperp[1]-mcursor[1]) < 10:
self.type = 'P... |
awacha/cct | cct/qtgui2/measurement/monitor/monitor.py | Python | bsd-3-clause | 17,577 | 0.003983 | import logging
import time
from typing import Optional, Final, Any
import numpy as np
from PyQt5 import QtWidgets, QtGui, QtCore
from matplotlib.axes import Axes
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT, FigureCanvasQTAgg
from matplotlib.figure import Figure
from matplotlib.lines import Line... | over. Next index to be wri | tten is `self.cursor`.
oldbuffer = self.buffer[:self.cursor]
else:
# we have already looped over
oldbuffer = np.hstack((self.buffer[self.cursor:], self.buffer[:self.cursor]))
# see how much of the old buffer fits in the new one. Prefer the most rec... |
michaellas/streaming-vid-to-gifs | src/mark_frame_service/service.py | Python | mit | 3,218 | 0.016362 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#import modułów konektora msg_strea | m_connector
from ComssServiceDevelopment.connectors.tcp.msg_stream_connector import InputMessageConnector, OutputMessage | Connector
#import modułów klasy bazowej Service oraz kontrolera usługi
from ComssServiceDevelopment.service import Service, ServiceController
import cv2 #import modułu biblioteki OpenCV
import numpy as np #import modułu biblioteki Numpy
import os
import threading
from time import time
OPACITY = 0.4 # rectangle opacit... |
Mariusz1970/enigma2 | lib/python/Plugins/Extensions/Infopanel/sundtek.py | Python | gpl-2.0 | 11,219 | 0.02781 | #
# sundtek control center
# coded by giro77
#
#
from Screens.Screen import Screen
from Screens.Console import Console
from Screens.MessageBox import MessageBox
from Screens.InputBox import InputBox
from Components.ActionMap import ActionMap
from Components.Input import Input
from Components.MenuList import MenuLis... | k/sun_dvb.sh enable_net")
else:
if config.plugins.SundtekControlCenter.dvbtransmission.getValue() == "0":
### dvb-s/ dvb-s2
if config.plugins.SundtekControlCenter.autostart.getValue() == True:
### enable autostart
self.prompt("/usr/sundtek/sun_dvb.sh enable_s2")
elif config.... | sion.getValue() == "1":
### dvb-c
if config.plugins.SundtekControlCenter.autostart.getValue() == True:
### enable autostart
self.prompt("/usr/sundtek/sun_dvb.sh enable_c")
else:
### dvb-t
if config.plugins.SundtekControlCenter.autostart.getValue() == True:
### enable autostart
... |
Mirantis/pumphouse | setup.py | Python | apache-2.0 | 656 | 0 | # Copyright (c) 2014 Mirantis Inc. |
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the L... | ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and#
# limitations under the License.
import setuptools
setuptools.setup(
setup_requires=['pbr'],
pbr=True)
|
tuanvu216/udacity-course | data_wrangling_with_mongodb/Lesson_4_Problem_Set/02-Inserting_into_DB/dbinsert.py | Python | mit | 407 | 0.007371 | import json
d | ef insert_data(data, db):
# Your code here. Insert the data into a collection 'arachnid'
pass
if __name__ == "__main__":
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client.examples
with open('arachnid.json') as f:
data = json.loads(f.r... | print db.arachnid.find_one() |
asm-products/formspree | formspree/settings.py | Python | agpl-3.0 | 2,551 | 0.002744 | import os
import sys
from flask import render_template
# load a bunch of environment
DEBUG = os.getenv('DEBUG') in ['True', 'true', '1', 'yes']
if DEBUG:
SQLALCHEMY_ECHO = True
TESTING = os.getenv('TESTING') in ['True', 'true', '1', 'yes']
SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI') or os.gete... | IPE_TEST_PUBLISHABLE_KEY')
STRIPE_TEST_SECRET | _KEY = os.getenv('STRIPE_TEST_SECRET_KEY')
STRIPE_PUBLISHABLE_KEY = os.getenv('STRIPE_PUBLISHABLE_KEY') or STRIPE_TEST_PUBLISHABLE_KEY
STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY') or STRIPE_TEST_SECRET_KEY
STRIPE_WEBHOOK_SECRET = os.getenv('STRIPE_WEBHOOK_SECRET')
GA_KEY = os.getenv('GA_KEY') or '123456'
RECAPT... |
changsimon/trove | trove/extensions/mgmt/volume/service.py | Python | apache-2.0 | 1,428 | 0 | # Copyright 2011 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 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. Se | e the
# License for the specific language governing permissions and limitations
# under the License.
from trove.common import wsgi
from trove.common.auth import admin_context
from trove.extensions.mgmt.volume import models
from trove.extensions.mgmt.volume import views
from trove.openstack.common import log as ... |
mlperf/training_results_v0.5 | v0.5.0/nvidia/submission/code/object_detection/pytorch/maskrcnn_benchmark/config/defaults.py | Python | apache-2.0 | 11,814 | 0.001354 |
#
# | Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# Copyright (c) 2017-2018, NVIDIA CORPORATION. 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
#
... | s/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 t... |
Sveder/pyweek24 | gamelib/player.py | Python | apache-2.0 | 2,447 | 0.001635 | import pygame
import data
from config import *
import platforms
class Player(pygame.sprite.Spri | te):
def __init__(self):
# Call the parent's constructor
pygame.s | prite.Sprite.__init__(self)
self.image = data.load_image("player.png")
self.rect = self.image.get_rect()
# Set speed vector of player
self.change_x = 0
self.change_y = 0
self.level = None
self.is_jumping = False
def update(self):
self.calc_grav()
... |
DemocracyClub/yournextrepresentative | ynr/apps/results/migrations/0011_resultevent_post_new.py | Python | agpl-3.0 | 539 | 0 | from django.db import migrations, models
class Migration(migrations.Migration):
dependen | cies = [
("popolo", "0002_update_models_from_upstream"),
("results", "0010_resultevent_winner_party_new"),
]
operations = [ |
migrations.AddField(
model_name="resultevent",
name="post_new",
field=models.ForeignKey(
blank=True,
to="popolo.Post",
null=True,
on_delete=models.CASCADE,
),
)
]
|
pmacosta/putil | tests/plot/basic_source.py | Python | mit | 9,026 | 0.001219 | # basic_source.py
# Copyright (c) 2013-2016 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0103,C0111,E0611,R0201,R0204,W0212,W0232,W0612
# PyPI imports
from numpy import array
import pytest
# Putil imports
from putil.plot import BasicSource as FUT
from putil.test import AE, AI, APROP, AROPROP
##... | __init__ path
AI(FUT, 'indep_max', RIVAR, RDVAR, indep_max=indep_max)
# Managed attribute path
obj = FUT(RIVAR, RDVAR)
msg = 'Argument `indep_max` is not valid'
APROP(obj, 'indep_max', indep_max, RuntimeError, msg)
#with pytest.raises(RuntimeError) as exc | info:
# obj.indep_max = indep_max
#assert GET_EXMSG(excinfo) == 'Argument `indep_max` is not valid'
@pytest.mark.basic_source
def test_indep_min_greater_than_indep_max_exceptions(self):
"""
Test behavior when indep_min and indep_max are incongruous
"""
# Assig... |
robocomp/robocomp | tools/cli/robocompdsl/robocompdsl/templates/templateCPP/plugins/base/functions/SERVANT_H.py | Python | gpl-3.0 | 1,893 | 0.005283 | import datetime
from robocompdsl.templates.common.templatedict import TemplateDict
from robocompdsl.templates.templateCPP.plugins.base.functions import function_utils as utils
INTERFACE_METHOD_STR = """
${ret} ${interface_name}I::${method_name}(${input_params})
{
${to_return}worker->${interface_name}_${method_name}... | e)
def interface_methods_definition(self, module, interface_name):
result = ""
for interface in module['interfaces']:
if interface['name'] == interface_name:
for mname in interface['methods']:
method = interface['methods'][mname]
... | get_parameters_string(method, module['name'], self.component.language)
if param_str:
param_str = f"{param_str}, const Ice::Current&"
else:
param_str = "const Ice::Current&"
result += ret + ' ' + name + '(' + para... |
Victory/clicker-me-bliss | functional-tests/buy-item4.py | Python | mit | 727 | 0 | from clickerft.cft import Cft
from time import sleep
class Suite(Cft):
def test | _buy_item_4(self):
while int(self.clicksPerGeneration.text) < 2:
if int(self.clicksOwned.text) < 1:
sleep(.5)
conti | nue
self.increaseClicksPerGeneration.click()
while int(self.tr1.text) < int(self.pi4r1.text):
self.click_r_test('r1')
while int(self.tr2.text) < int(self.pi4r2.text):
self.click_r_test('r2')
self.i4.click()
assert int(self.oi4.text) == 1
sle... |
pcmoritz/ray-1 | python/ray/serve/examples/doc/snippet_custom_metric.py | Python | apache-2.0 | 695 | 0 | import ray
from ray import serve
from ray.util import metrics
import time
ray.init(address="auto")
serve.start()
@serve.deploymen | t
class MyBackend:
def __init__(self):
self.my_counter = metrics.Counter(
"my_counter",
description=("The number of excellent requests to this backend."),
tag_keys=("backend", ))
self.my_counter.set_default_tags({
"backend": serve | .get_current_backend_tag()
})
def call(self, excellent=False):
if excellent:
self.my_counter.inc()
MyBackend.deploy()
handle = MyBackend.get_handle()
while True:
ray.get(handle.call.remote(excellent=True))
time.sleep(1)
|
mgautierfr/devparrot | devparrot/core/ui/statusBar.py | Python | gpl-3.0 | 3,065 | 0.001958 | # This file is part of DevParrot.
#
# Author: Matthieu Gautier <[email protected]>
#
# DevParrot 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
... | blic License
# along with DevParrot. If not, see <http://www.gnu.org/licenses/>.
#
#
# | Copyright 2011-2013 Matthieu Gautier
import tkinter, tkinter.ttk
import logging
from devparrot.core import session, userLogging
class StatusBar(tkinter.Frame, logging.Handler):
def __init__(self, parent):
tkinter.Frame.__init__(self, parent)
logging.Handler.__init__(self)
self.pack(side... |
EssaAlshammri/django-by-example | bookmarks/bookmarks/actions/utils.py | Python | mit | 679 | 0.002946 | import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from .models import Action
def | create_action(user, verb, target=None):
now = timezone.now()
last_minute = now - datetime.timedelta(seconds=60)
similar_actions = Action.objects.filter(user_id=user.id, verb=verb, created__gte=last_minute)
if target:
target_ct = ContentType.objects.get_for_model(target)
similar_actions... | action.save()
return True
return False
|
open-synergy/opnsynid-purchase-workflow | purchase_order_line_product_uom/models/__init__.py | Python | agpl-3.0 | 176 | 0 | # -*- coding: utf-8 -*-
# C | opyright 2019 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import (
purchase_ | order_line,
)
|
tovmeod/anaf | anaf/viewsets.py | Python | bsd-3-clause | 410 | 0.002439 | from rest_f | ramework import viewsets
from rest_framework.exceptions import MethodNotAllowed
class AnafViewSet(viewsets.ModelViewSet):
"""Base Viewset"""
accepted_formats = ('html', 'ajax')
def retrieve(self, request, *args, **kwargs):
| if request.method != 'GET':
raise MethodNotAllowed(request.method)
return super(AnafViewSet, self).retrieve(request, *args, **kwargs) |
odoocn/odoomrp-wip | mrp_product_variants_configurable_timing/models/mrp_production.py | Python | agpl-3.0 | 1,568 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# 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... | es/.
#
##############################################################################
from openerp import models
import math
class MrpProduction(models.Model):
_inherit = 'mrp.production'
def _get_workorder_in_product_lines(
self, workcenter_lines, product_lines, properties=Non | e):
super(MrpProduction, self)._get_workorder_in_product_lines(
workcenter_lines, product_lines, properties=properties)
for workorder in workcenter_lines:
wc = workorder.routing_wc_line
cycle = wc.cycle_nbr and (self.product_qty / wc.cycle_nbr) or 0
if sel... |
hydratk/hydratk-lib-network | src/hydratk/translation/lib/network/email/client/en/messages.py | Python | bsd-3-clause | 1,250 | 0.000801 | # -*- coding: utf-8 -*-
"""This code is a part of Hydra Toolkit
.. module:: hydratk.translation.lib.network.email.client.en.messages
:platform: Unix
:synopsis: English language translation for EMAIL client messages
.. moduleauthor:: Petr Rašek <[email protected]>
"""
language = {
'name': 'English',
'... | m"
HIGHLIGHT_US = chr(27) + chr(91) + "4m"
HIGHLIGHT_END = chr(27) + chr(91) + "0m"
msg = {
'htk_email_unknown_protocol': ["Unknown protocol: '{0}'"],
'htk_email_unknown_method': ["Unknown method for protocol: '{0}'"],
'htk_email_connecting': ["Connecting to server: '{0}'"],
'htk_email_connected': ["Co... | k_email_disconnected': ["Disconnected from server"],
'htk_email_not_connected': ["Not connected to server"],
'htk_email_sending': ["Sending email: '{0}'"],
'htk_email_sent': ["Email sent"],
'htk_email_counting': ["Counting emails"],
'htk_email_count': ["Email count: '{0}'"],
'htk_email_listing':... |
cedexis/cedexis.radar | cedexis/radar/session/errors.py | Python | mit | 424 | 0.007075 |
class InvalidThroughputFileSizeError(Exception):
pass
class UniNotFoundError(Ex | ception):
pass
class UnexpectedStatusError(Exception):
pass
class UnexpectedHttpStatusError(Exception):
def __init__(self, status, text):
self.__status = status
self.__text = text
@property
def status(self):
return self.__st | atus
@property
def text(self):
return self.__text
|
DomNelson/tracts | scripts/tracts_sim.py | Python | gpl-2.0 | 6,478 | 0.017598 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 28 14:33:24 2015
@author: dominic
"""
#import matplotlib.pylab as pylab
import numpy as np
import tracts_ped as ped
import os
import tracts
import sys
import time
import numpy as np
# MigrantProps = [0.2, 0.05] # Proportion of pedigree that will be new migrants
# MigProp... | igPropMat = migmat,
pedfile = pedfile,
ancfile = ancfile,
labels = labels,
split_parents = True)
M_leaflist, M_nodelist = P.SortLeafNode(P.m | other_indlist)
F_leaflist, F_nodelist = P.SortLeafNode(P.father_indlist)
M_TMat = P.BuildTransMatrices(M_leaflist, M_nodelist)
F_TMat = P.BuildTransMatrices(F_leaflist, F_nodelist)
tracts_ind = P.PSMC_ind(M_TMat, F_TMat, M_leaflist, F_leaflist, ChromLengths)
else:
print "Unk... |
Livefyre/pseudonym | pseudonym/__init__.py | Python | mit | 55 | 0 | fro | m errors import *
from manager import SchemaMa | nager
|
azavea/gtfs-feed-fetcher | feed_sources/Massdot.py | Python | mit | 3,164 | 0.000316 | """Fetch Massacheusetts Department of Transportation feeds.
MassDOT supplies the feeds for MA not covered by MBTA (Boston's transit authority).
http://www.massdot.state.ma.us/DevelopersData.aspx
"""
import logging
from FeedSource import FeedSource
BASE_URL = 'http://www.massdot.state.ma.us/Portals/0/docs/developers/... | SE_URL
self.urls = {
'berkshire.zip': berkshire_url,
'brockton.zip': brockton_url,
'cape_ann.zip': cape_ann_url,
'cape_cod.zip': cape_cod_url,
'franklin.zip': franklin_url,
'attleboro.zip': attleboro_url,
'lowell.zip': lowell_u... | ntachusett.zip': montachusett_url,
'nantucket.zip': nantucket_url,
'pioneer_valley.zip': pioneer_valley_url,
'southeastern_ma.zip': southeastern_url,
'vineyard_ma.zip': vineyard_url,
'worchester.zip': worchester_url,
'ma_ferries.zip': ma_ferry_url,... |
OxES/k2sc | src/priors.py | Python | gpl-3.0 | 2,483 | 0.00443 | """ Module defining priors.
Copyright (C) 2016 Suzanne Aigrain
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 ver... | ror()
def __call__(self, x):
return self.logpdf(x)
class UniformPrior(Prior):
def __init__(self, vmin, vmax):
self.vmin = vmin
self.vmax = vmax
self.C = 1./(vmax-vmin)
self.lnC = mt.log(self.C)
self.lims = [vmin,vmax]
def logpdf(self, x):
if x > sel... | lf.lnC
else:
return -inf
class NormalPrior(Prior):
def __init__(self, mu, sigma, lims=None):
self.lims = np.array(lims)
self.vmin, self.vmax = lims
self.mu = float(mu)
self.sigma = float(sigma)
self._f1 = 1./ mt.sqrt(2.*pi*sigma*sigma)
self._l... |
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_unicode_shift_jis.py | Python | bsd-2-clause | 1,538 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, [email protected]
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | coding.
textfile = open(self.txt_filename, mode='r', encoding='shift_jis')
# Create an new Excel file and convert the text data.
| workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 50)
# Start from the first cell.
row = 0
col = 0
# Read the text file and write it to the worksheet.
... |
astronewts/Flight1 | misc/allaloft/groundstation/python/ground_station_base.py | Python | gpl-3.0 | 9,305 | 0.019774 |
import os
from optparse import OptionParser
import io
import time
import random
import thread
import sys
from smtp_stuff import sendMail
from imap_stuff import checkMessages
import datetime
import string
import array
from time import gmtime, strftime
from socket import *
user = ''
recipient = ''
incoming_server = ... | = False
http_post_enabled = False
COMMAND_GET_POS = 0
COMMAND_RELEASE = 1
COMMAND_SET_REPORT_INTERVAL = 2
def send_mo_email(msg):
global email
global incoming_server
global outgoing_server
global password
global imei
#put together body
body = ''
#subject
subject = '%d' % im... | g.sbd'
fd = open(attachment, 'wb')
fd.write(msg)
fd.close()
sendMail(subject, body, user, recipient, password, outgoing_server, attachment)
def log(string):
print string
#TODO logic for text logging
def parse_text_report_no_fix(report):
report = report.split(":")
report = rep... |
QuartetoFantastico/projetoPokemon | batalha.py | Python | gpl-2.0 | 4,953 | 0.032707 | import pokemon
import random
import re
import display
class Batalha:
def __init__(self, pokeList = []):
self.display = display.Displ | ay()
self.pkmn = []
if (len(pokeList) == 0):
self.pk | mn.append(pokemon.Pokemon())
self.pkmn.append(pokemon.Pokemon())
else:
self.pkmn = pokeList
self.turno = self.IniciaTurno()
def IniciaTurno(self):
if (self.pkmn[0].getSpd() > self.pkmn[1].getSpd()):
return 0
elif (self.pkmn[1].getSpd() > self.pkmn[0].getSpd()):
return 1
return random.randint(0, ... |
Stanislav-Rybonka/spaceshop | product/admin.py | Python | gpl-3.0 | 397 | 0 | from django.contrib import admin
from product.models import Category, Product
class CategoryAdmin(admin.ModelAdmin):
fields = ('name', 'description', 'image',)
class ProductAdmin(admin.ModelAdmin):
fields = ('name', ' | description', 'price', 'category', 'image',)
# Reqister models for admin part
admin.site.registe | r(Category, CategoryAdmin)
admin.site.register(Product, ProductAdmin)
|
jolyonb/edx-platform | lms/djangoapps/branding/tests/test_api.py | Python | agpl-3.0 | 10,470 | 0.005349 | # encoding: utf-8
"""Tests of Branding API """
from __future__ import absolute_import, unicode_literals
import mock
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from branding.api import _footer_business_links, get_foo... | ogo_url, cdn | _url)
def test_home_url_with_mktg_disabled(self):
expected_url = get_home_url()
self.assertEqual(reverse('dashboard'), expected_url)
@mock.patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True})
@mock.patch.dict('django.conf.settings.MKTG_URLS', {
"ROOT": "https://e... |
vykhand/pyspark-csv | pyspark_csv.py | Python | mit | 5,353 | 0.016813 | """
The MIT License (MIT)
Copyright (c) 2015 seahboonsiew
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,... | d[col] = a_type
else:
order_a = type_order[a_type]
order_b = type_order[b_type]
if order_a == order_b:
d[col] = a_type
elif order_a > order_b:
d[col] = reduce_map[a_type][or | der_b]
elif order_a < order_b:
d[col] = reduce_map[b_type][order_a]
return d
def evaluateType(rdd_sql,parseDate):
if parseDate:
return rdd_sql.map(getRowType).reduce(reduceTypes)
else:
return rdd_sql.map(getRowTypeNoDate).reduce(reduceTypes)
... |
google/iree-llvm-sandbox | python/examples/reduction/column_reduction_2d_bench.py | Python | apache-2.0 | 3,738 | 0.011236 | # RUN: %PYTHON %s 2>&1 | FileCheck %s
# This file contains small benchmarks with reasonably-sized problem/tiling sizes
# and codegen options.
from ..core.experts import *
from ..core.harness import *
from ..core.transforms import *
from ..contraction.definitions import *
fun_name = 'column_reduction_2d'
op_name = '... | ]
def all_experts(problem_sizes: List[int]):
tile_sizes = [
[4, 8], [6, 8], [8, 8], \
[4, 16], [6, 16], [8, 16], \
[4, 32], | [6, 32], [8, 32], [16, 32], \
[4, 64], [6, 64], [8, 64], [16, 64], \
]
res = []
for ts in tile_sizes:
res.append(
# Note: `\` char at the end of next line prevents formatter reflows, keep it.
Tile(fun_name=fun_name, \
op_name=op_name,
# Don't tile too small dimensions.
... |
arsenovic/galgebra | examples/Old Format/terminal_check.py | Python | bsd-3-clause | 10,702 | 0.037283 | #!/usr/bin/python
from __future__ import print_function
import sys
from sympy import Symbol,symbols,sin,cos,Rational,expand,simplify,collect
from galgebra.printer import enhance_print,Get_Program,Print_Function,Format
from galgebra.deprecated import MV
from galgebra.mv import Nga,ONE,ZERO
from galgebra.ga import Ga
de... | p(alpha*Bhat/2)
print('s = sinh(alpha/2) and c = cosh(alpha/2)')
print('exp(alpha*B/(2*|B|)) =',R)
Z = R*X*R.rev() # D&L 10.155
Z.obj = expand(Z.obj)
Z.obj = Z.obj.collect([Binv,s,c,XdotY])
Z.Fmt(3,'R*X*R.rev()')
W = Z|Y # Extract scalar part of multivector
# From this point forward all... | ive is to determine value of C = cosh(alpha) such that W = 0')
W = W.scalar()
print('Z|Y =',W)
W = expand(W)
W = simplify(W)
W = W.collect([s*Binv])
M = 1/Bsq
W = W.subs(Binv**2,M)
W = simplify(W)
Bmag = sqrt(XdotY**2-2*XdotY*Xdote*Ydote)
W = W.collect([Binv*c*s,XdotY])
#Do... |
maaadc/corbit | plot.py | Python | gpl-2.0 | 3,754 | 0.029036 | #!/usr/bin/env python
#
# Visualization of planet movement via numpy and matplotlib
#
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
# load position data and reshape it
Ndays = 0
N = 0
Nplanets = 0
Tstep = 0
V = np.arr... | c00',
# set trajectories, only | lines get labels
lines = sum( [ax1.plot([], [], [], '-', color=c, label=l) for c, l in zip(colors, n)], [] )
points = sum( [ax1.plot([], [], [], 'o', color=c) for c in colors], [] )
# set plot layout
limit = (-5,5) # axes limits
#limit = (-20,20)
ax1.set_xlim(limit)
ax1.set_ylim(limit)
ax1.set_zlim(limit)
ax1.axi... |
jekhokie/scriptbox | python--advent-of-code/2020/3/solve.py | Python | mit | 757 | 0.029062 | #!/usr/bin/env python3
lines = []
with open('input.txt', 'r') as f:
lines = f.read().splitlines()
#--- challenge 1
def get_trees(lines, right, down):
trees = 0
pos = 0
line_len = len(lines[0])
for line in lines[dow | n::down]:
if (pos + right) >= line_len:
pos = right - (line_len - pos)
else:
pos += right
if line[pos] == '#':
trees += 1
return trees
trees = get_trees(lines, 3, 1)
print("Solution to challenge 1: {}".format(trees))
#--- challenge 2
tree_list = []
sequences = [[1,1], [3,1], [5,1]... | = 1
for trees in tree_list:
product *= trees
print("Solution to challenge 2: {}".format(product))
|
fbradyirl/home-assistant | homeassistant/components/google_assistant/const.py | Python | apache-2.0 | 3,937 | 0.000254 | """Constants for Google Assistant."""
from homeassistant.components import (
binary_sensor,
camera,
climate,
cover,
fan,
group,
input_boolean,
light,
lock,
media_player,
scene,
script,
sensor,
switch,
vacuum,
)
DOMAIN = "google_assistant"
GOOGLE_ASSISTANT_AP... | : TYPE_FAN,
group.DOMAIN: TYPE_SWITCH,
input_boolean.DOMAIN: TYPE_SWITCH,
light.DOMAIN: TYPE_LIGHT,
lock.DOMAIN: TYPE_LOCK,
media_pla | yer.DOMAIN: TYPE_SWITCH,
scene.DOMAIN: TYPE_SCENE,
script.DOMAIN: TYPE_SCENE,
switch.DOMAIN: TYPE_SWITCH,
vacuum.DOMAIN: TYPE_VACUUM,
}
DEVICE_CLASS_TO_GOOGLE_TYPES = {
(cover.DOMAIN, cover.DEVICE_CLASS_GARAGE): TYPE_GARAGE,
(cover.DOMAIN, cover.DEVICE_CLASS_DOOR): TYPE_DOOR,
(switch.DOMAIN... |
hfp/tensorflow-xsmm | tensorflow/contrib/distribute/python/monitor.py | Python | apache-2.0 | 2,505 | 0.005988 | # 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... |
from tensorflow.python.eager import context
from tensorflow.python.framework import errors
from tensorflow.python.ops import variables
class Monitor(object):
"""Executes training steps, recovers and checkpoints.
Note that this class is particularly preliminary, experimental, and
expected to change.
"""
# ... | DO(isaprykin): Support extra arguments to the step function.
# TODO(isaprykin): Support recovery, checkpointing and summaries.
def __init__(self, step_callable, session=None):
"""Initialize the Monitor with components for executing training steps.
Args:
step_callable: a training `Step` that's capabl... |
postlund/home-assistant | homeassistant/components/xiaomi_miio/air_quality.py | Python | apache-2.0 | 7,163 | 0.000419 | """Support for Xiaomi Mi Air Quality Monitor (PM2.5)."""
import logging
from miio import AirQualityMonitor, Device, DeviceException
import voluptuous as vol
from homeassistant.components.air_quality import PLATFORM_SCHEMA, AirQualityEntity
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_TOKEN
from homeassi... |
except DeviceException as ex:
self._available = False
_LOGGER.error("Got exception while fetching the state: %s", ex)
class AirMonitorV1(AirMonitorB1):
"""Air Quality class for Xiaomi cgllc.airmonitor.s1 device."""
async def async_update(self):
"""Fetch state from the... | ER.debug("Got new state: %s", state)
self._air_quality_index = state.aqi
self._available = True
except DeviceException as ex:
self._available = False
_LOGGER.error("Got exception while fetching the state: %s", ex)
@property
def unit_of_measurement(self):
... |
LuanP/futebolistica | futebolistica/games/models.py | Python | gpl-2.0 | 1,773 | 0.000564 | # -*- coding: utf-8 -*-
from django.db import models
from django.core.urlresolvers import reverse
class Stadium(models.Model):
name = models.CharField(max_length=200, unique=True)
def __unicode__(self):
return self.name
class Judge(models.Model):
name = models.CharField(max_length=200, unique=... | self.team_away.a | bbr
)
super(Game, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('games:detail', args=(self.long_slug, ))
|
tech-server/gondul | templating/templating.py | Python | gpl-2.0 | 3,215 | 0.002799 | #!/usr/bin/python3
import argparse
import traceback
import sys
import netaddr
import requests
from flask import Flask, request
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp publ... | 0:
response.cache_control.max_age = 5
response.cache_control.s_maxage = 1
return response
@app.route("/<path>", methods=["GET"])
def root_get(path):
updateData()
try:
template = env.get_template(path)
body = template.render(objects=objects, options=request.args)
except ... | the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400
return body, 200
@app.route("/<path>", methods=["POST"])
def root_post(path):
updateData()
try:
content = request.stream.read(int(request.headers["Content-Length"]))
template = env.from_stri... |
CarlFK/wafer | wafer/talks/views.py | Python | isc | 3,564 | 0 | from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.views.generic import DetailView
f... | ects.filter(status=ACCEPTED)
class TalkView(DetailView):
template_name = 'wafer.talks/talk.html'
model = Talk
def get_object(self, *args, **kwargs):
'''Only talk owners can see talks, unless they've been accepted'''
object_ = super(TalkView, self).get_object(*args, **kwargs)
if ob... | ise PermissionDenied
def get_context_data(self, **kwargs):
context = super(TalkView, self).get_context_data(**kwargs)
context['can_edit'] = self.object.can_edit(self.request.user)
return context
class TalkCreate(LoginRequiredMixin, CreateView):
model = Talk
form_class = TalkForm
... |
apple/coremltools | coremltools/converters/mil/frontend/torch/test/test_internal_graph.py | Python | bsd-3-clause | 67,606 | 0.001686 | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import itertools
import numpy as np
import pytest
torch = pytest.importorskip("torch")
import torc... | ext):
test_val = ops.PYTORCH_MAGIC_DEFAULT
node = InternalTorchIRNode(
attr={"value": test_val}, kind="constant", inputs=[], outputs=["1"]
)
ssa = self._construct_test_graph(context, ops.constant, node, "1")
# We expect the magic default to get converted to None
... | list of internal constant nodes.
Arguments:
size: number of constants to generate
vals: Either a list of values for each constant or one value used for all constants."""
is_list = isinstance(vals, list)
if is_list:
if len(vals) != size:
raise ... |
igogorek/allure-python | allure-pytest/src/helper.py | Python | apache-2.0 | 1,026 | 0.002924 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
import allure_c | ommons
from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX
class AllureTestHelper(object):
def __init__(self, config):
self.config = config
@allure_commons.hookimpl
def decorate_as_label(self, label_type, labels):
allure_label_marker = '{prefix}.{label_type}'.format(p... | .mark, allure_label_marker)
return allure_label(*labels, label_type=label_type)
@allure_commons.hookimpl
def decorate_as_link(self, url, link_type, name):
allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type)
pattern = dict(self.config.option... |
UnrememberMe/pants | src/python/pants/backend/jvm/register.py | Python | apache-2.0 | 10,635 | 0.008275 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.j... | ('jvm-platform-validate')
task(name='bootstrap-jvm-tools', action=BootstrapJvmTools).install('bootstrap' | )
task(name='provide-tools-jar', action=ProvideToolsJar).install('bootstrap')
# Compile
task(name='zinc', action=ZincCompile).install('compile')
# Dependency resolution.
task(name='ivy', action=IvyResolve).install('resolve', first=True)
task(name='coursier', action=CoursierResolve).install('resolve')
ta... |
codeforeurope/Change-By-Us | giveaminute/migrations/versions/004_Add_a_city_leader_model.py | Python | agpl-3.0 | 875 | 0.003429 | """
:copyright: (c) 2011 Local Projects, all rights reserved
:license: Affero GNU GPL v3, see LICENSE for more details.
"""
from sqlalchemy import *
from migrate import *
def upgrade(migrate_engine):
# Upgrade operations go h | ere. Don't create your own engine; bind migrate_engine
# to your metadata
meta = MetaData(migrate_engine)
communityleader = Table('community_leader', meta,
Column('id', Integer, primary_key=True),
Column('display_name', String(256)),
Column('title', String(256)),
Column('im... | ()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
meta = MetaData(migrate_engine)
communityleader = Table('community_leader', meta, autoload=True)
communityleader.drop()
|
MMeent/MANTHIS-terminal | Terminal/ActiveTileHandler.py | Python | lgpl-3.0 | 641 | 0.00156 | __author__ = 'Matthias'
from tkinter import *
from Terminal.Items.ItemStock import ItemStock
from Terminal.Items.Item import Item
class Ac | tive | TileHandler:
def __init__(self):
self.active_tile = ItemStock(Item("", 0), 1).create_item_tile(None)
def set_tile(self, tile: Frame):
tile.winfo_toplevel().slider.set(tile.item_stock.get_amount())
self.active_tile = tile
def set(self, amount: int):
self.active_tile.item_sto... |
uclouvain/OSIS-Louvain | base/migrations/0458_auto_20190613_1614.py | Python | agpl-3.0 | 471 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2019-06-13 16:14
from __future__ import | unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0457_message_template_egys_automatic_postponement_update'),
]
operations = [
migrations.AlterUniqueTogether(
name='academiccalendar',
unique_togeth... | _year', 'title')]),
),
]
|
envoyproxy/envoy | tools/protoxform/protoprint.py | Python | apache-2.0 | 31,369 | 0.003379 | # FileDescriptorProtos pretty-printer tool.
#
# protoprint.py provides the canonical .proto formatting for the Envoy APIs.
#
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file.
#
# Usage: protoprint.py <source file path> <type dat... | block: a string representing the section.
Return | s:
A string with appropriate whitespace.
"""
if block.strip():
return block + '\n'
return ''
def format_comments(comments):
"""Format a list of comment blocks from SourceCodeInfo.
Prefixes // to each line, separates blocks by spaces.
Args:
comments: a list of blocks, ... |
ulno/micropython-extra-ulno | examples/ehdemov3/wifi_config.py | Python | mit | 56 | 0 | name = "ehdemo-iotemp | ire"
password = "internetofthings" | |
sthyme/ZFSchizophrenia | BehaviorAnalysis/HSMovieAnalysis/pyTrack_usingprevmask_updated.py | Python | mit | 448 | 0.013393 | #!/usr/bin/p | ython
import highspeedmovieanalysis
import imageTools
import sys
pixThreshold = 0.005 # enter pixel threshold here
frameRate = 285 # enter frameRate here (usually 30 fps)
videoStream = imageTools.getVideoStream(sys.argv)
#vidInfo = deltaPix.cmdLine(pixThreshold,frameRate,videoStream)
#vidInfo = deltaPix_updated.cmdLi... | rameRate,videoStream)
|
cloudbase/nova-virtualbox | nova/servicegroup/api.py | Python | apache-2.0 | 5,543 | 0 | # Copyright 2012 IBM Corp.
# Copyright (c) | AT&T Labs Inc. 2012 Yun Mao <[email protected]>
#
# 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 agree... | r
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define APIs for the servicegroup access."""
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils
from nova.i18n import _, _LW
LOG = logging.getLogger(_... |
mahabuber/erpnext | erpnext/patches/v6_5/show_in_website_for_template_item.py | Python | agpl-3.0 | 486 | 0.018519 | from __future__ import unicode_literals
import frappe
import frappe.website.render
def execute():
for item_code in frappe.db.sql_list("""select distinct variant_of from `tabItem`
where variant_of is not null and variant_of !='' and show_in_websit | e=1"""):
item = frappe.get_doc("Item", item_code)
item.db_set("show_in_we | bsite", 1, update_modified=False)
item.get_route()
item.db_set("page_name", item.page_name, update_modified=False)
frappe.website.render.clear_cache()
|
couchbaselabs/litmus | lib/couchdb/multipart.py | Python | apache-2.0 | 8,671 | 0.000692 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Support for streamed reading and writing of multipart MIME content."""
from base64 import b64enc... | uctures, call the ``open([headers])`` method on the
respective envelope, and finish each envelope using the ``close()`` method:
>>> buf = StringIO()
>>> envelope = write_multipart(buf, boundary='==123456789==')
>>> part = envelope.open( | boundary='==abcdefghi==')
>>> part.add('text/plain', 'Just testing')
>>> part.close()
>>> envelope.close()
>>> print buf.getvalue().replace('\r\n', '\n') #:doctest +ELLIPSIS
Content-Type: multipart/mixed; boundary="==123456789=="
<BLANKLINE>
--==123456789==
Content-Type: multipart/mixed;... |
NORCatUofC/rainapp | csos/migrations/0001_initial.py | Python | mit | 1,235 | 0.002429 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-04 15:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... | ame', models.TextField()),
('lat', models.FloatField(null=True)),
('lon', models.FloatField(null=True)),
],
),
migrations.AddField(
model_name='rivercso',
name='river_outfall',
field=models.ForeignKey(on_delete=django.db.mod... | |
thethythy/Mnemopwd | mnemopwd/client/uilayer/uicomponents/TitledOnBorderWindow.py | Python | bsd-2-clause | 2,237 | 0.001341 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2017, Thierry Lemeunier <thierry at lemeunier dot net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must reta... | =menu)
self.title = title
self.colourT = colourT
self.colourD = colo | urD
self._create()
def redraw(self):
"""See mother class"""
self._create()
BaseWindow.redraw(self)
def _create(self):
self.window.attrset(self.colourD)
self.window.border()
self.window.addstr(0, 2, '[ ' + self.title + ' ]', self.colourT)
self.win... |
dunkenj/dunkenj.github.io | old/process_ads.py | Python | apache-2.0 | 647 | 0.004637 | # -*- coding: utf-8 -*-
import ads
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader(''))
ads.config.token = '7scWI1Z2A8kPAukKoYUPKyzlQqn3eSY1m4r0QCTo'
all_query = 'author:"duncan, k" year:2013-2020 database:astronomy property:refereed'
first_author = 'author:"^duncan, k" yea... | t"))
template = env.get_template('publications_template.html')
out = template.render(all=allp)
with open("publications.html", | "wb") as f:
f.write(out) |
google/vulncode-db | tests/app_tests/api/test_routes.py | Python | apache-2.0 | 3,216 | 0.002488 | # 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, ... |
@pytest.mark.integration
@pytest.mark.parametrize("query, data, expected_code, expected_response", SAVE_VARIANTS)
def test_save_editor_data_as_admin(
app, client, query, data, expected_code, expected_response
):
as_admin(client)
resp = client.post("/api/save_editor_data", json=data, query_str | ing=query)
assert resp.status_code == expected_code
assert "application/json" in resp.headers["Content-Type"]
assert resp.json == expected_response
@pytest.mark.integration
@pytest.mark.parametrize("query, data, expected_code, expected_response", SAVE_VARIANTS)
def test_save_editor_data_as_user(
app,... |
YcheLanguageStudio/PythonStudy | crpytography/tests/test_finite_field.py | Python | mit | 675 | 0 | from crpyto_tool.libs.finite_field_op import FiniteFieldNumber
if __name__ == '__main__':
magical_number = FiniteFieldNumber(FiniteFieldNumber.magical_number, False)
print 'p(x): ' + str(magical_number)
number2 = FiniteFieldNumber('0')
number3 = FiniteFieldNumber('1000110')
print 'Q5-(1):' + str(n... | Number('1000110')
number1 = FiniteFieldNumber('10001011')
print 'Q5-(2):' + str(number0 + number1)
print 'Q5-(3):' + str(number0 * number1)
number4 = FiniteFieldNumber('10000111111010')
| print number4 / magical_number
print FiniteFieldNumber('11110101') * FiniteFieldNumber('1000110')
|
zuck/prometeo-erp | core/menus/forms.py | Python | lgpl-3.0 | 1,345 | 0.003717 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This file is part of the prometeo project.
This program | is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the Licens | e, 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 should have received a copy of the GNU... |
updownlife/multipleK | dependencies/biopython-1.65/build/lib.linux-x86_64-2.7/Bio/GenBank/Record.py | Python | gpl-2.0 | 23,027 | 0.000478 | # This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""Hold GenBank data in | a straightforward format.
classes:
- Record - All of the information in a GenBank record.
- Reference - hold reference data for a record.
- Feature - Hold the information in a Feature Table.
- Qualifier - Qualifiers on a Feature.
17-MAR-2009: added support for WGS and WGS_SCAFL | D lines. Ying Huang & Iddo Friedberg
"""
# local stuff
import Bio.GenBank
__docformat__ = "restructuredtext en"
def _wrapped_genbank(information, indent, wrap_space=1, split_char=" "):
"""Write a line of GenBank info that can wrap over multiple lines.
This takes a line of information which can potentially w... |
remmihsorp/minicps | minicps/utils.py | Python | mit | 3,381 | 0.000592 | """
utils.py.
MiniCPS use a shared logger called mcps_logger.
It contains testing data objects.
TEST_LOG_LEVEL affects all the tests,
output, info and debug are in increasing order of verbosity.
It contains all the others data objects.
"""
import logging
import logging.handlers
import time
import os
from mininet.u... | != None, "No log path found"
fh = logging.handlers.RotatingFileHandler(
ldir + name + suffix,
maxBytes=bytes_per_file,
backupCount=rotating_files)
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# no thread information
formatter = log... | r)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
return logger
TEMP_DIR = '/tmp'
LOG_DIR = 'logs/'
LOG_BYTES = 20000
LOG_ROTATIONS = 5
# MiniCPS global logger
mcps_logger = build_debug_logger(
name=__name__,
bytes_per_file=LOG_BYTES,
rotating_files=LOG_ROTATION... |
barrand/CTRs | src/lib/flaskext/login.py | Python | mit | 25,927 | 0.00027 | # -*- coding: utf-8 -*-
'''
flask.ext.login
---------------
This module provides user session management for Flask. It lets you log
your users in and out in a database-independent manner.
:c | opyright: (c) 2011 by Matthew Frazier.
:license: MIT/X11, see LICENSE for more details.
'''
__version_info__ | = ('0', '2', '6')
__version__ = '.'.join(__version_info__)
__author__ = 'Matthew Frazier'
__license__ = 'MIT/X11'
__copyright__ = '(c) 2011 by Matthew Frazier'
__all__ = ['LoginManager']
from flask import (_request_ctx_stack, abort, current_app, flash, redirect,
request, session, url_for)
from flask... |
Chilipp/psy-simple | tests/_base_testing.py | Python | gpl-2.0 | 3,925 | 0 | import os
import six
import sys
import shutil
import subprocess as spr
import tempfile
from unittest import TestCase
from get_ref_dir import get_ref_dir
import numpy as np
ref_dir = get_ref_dir()
test_dir = os.path.dirname(__file__)
remove_temp_files = True
# check if the seaborn version is smaller than 0.8 (withou... | return "_".join(identifiers) + '.png'
def compare_figures(self, fname, tol=5, | **kwargs):
"""Saves and compares the figure to the reference figure with the same
name"""
import matplotlib.pyplot as plt
from matplotlib.testing.compare import compare_images
plt.savefig(os.path.join(self.odir, fname), **kwargs)
results = compare_images(
os.... |
flavour/eden | modules/unit_tests/s3db/inv.py | Python | mit | 1,041 | 0.003842 | # -*- coding: utf-8 -*-
#
# Inv Unit Tests
#
# To run this script use:
# python web2py.py -S eden -M -R applications/eden/modules/unit_tests/s3db/inv.py
#
import unittest
import datetime
from gluon import *
from gluon.storage import Storage
from unit_tests import run_suite
# =========================================... | ==========================================================
if __name__ == "__main__":
run_suite(
InvTests,
) |
# END ========================================================================
|
david-martin/atomic-reactor | atomic_reactor/plugins/pre_check_and_set_rebuild.py | Python | bsd-3-clause | 3,476 | 0.000575 | """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import unicode_literals
import json
import os
from osbs.api import OSBS
from osbs.conf import Configuration
from atomic_rea... | iguration, this build is a rebuild. The module-level function
'is_rebuild()' can be used by other plugins to determine this.
After checking for the label, it sets the label in the
metadata, allowing future automated rebuilds to be detected as
rebuilds.
Example configuration:
{
"name": "... | abel_value": "true",
"url": "https://localhost:8443/"
}
}
"""
key = "check_and_set_rebuild"
is_allowed_to_fail = False # We really want to stop the process
def __init__(self, tasker, workflow, label_key, label_value,
url, verify_ssl=True, use_auth=True):
""... |
dbryant4/stelligent | tests/test_default.py | Python | mit | 590 | 0.005085 | def test_nginx_package(Package):
package = Package('nginx')
assert package.is_installed
def | test_nginx_working(Command):
response = Command('curl http://127.0.0.1/')
assert 'Automation for the People' in response.stdout
def test_nginx_service(Service, Socket):
service = Service('nginx')
socket = Socket('tcp://0.0.0.0:80')
assert service.is_running
assert service.is_enabled
asser... | listening
def test_index_html(File):
index = File('/usr/share/nginx/html/index.html')
assert index.content.strip() == 'Automation for the People'
|
examachine/pisi | tests/helloworld/actions.py | Python | gpl-3.0 | 3,200 | 0.00375 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005, TUBITAK/UEKAE
#
# 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 l... | ionsapi import shelltools
from pisi.actionsapi import libtools
from pisi.actionsapi import get
WorkDir = "hello-2.0"
def setup():
autotools.configure()
def build():
autotools.make()
def install():
autotools.install()
'''/opt/helloworld/'''
pisitools.dodir("/opt/helloworld")
... |
'''/usr/share/info/Makefile.am'''
'''/usr/share/info/Makefile.cvs'''
'''/usr/share/info/Makefile.in'''
pisitools.doinfo("Makefile.*")
'''/usr/lib/helloworld.o'''
pisitools.dolib("src/helloworld.o")
'''/opt/hello'''
pisitools.insinto("/opt/", "src/helloworld", "hello")
'''/opt/hi'... |
sunForest/AviPost | e2e/features/steps/crud.py | Python | apache-2.0 | 2,306 | 0.005637 | import json
import re
from | behave import given, when, then
from behave import use_step_matcher
use_step_matcher("re")
# implicitly used
import sure # noqa
# We use this instead of validato | r from json_schema_generator
# because its error reports are far better
from jsonschema import validate
from _lazy_request import LazyRequest
# supress requests logging
import logging
logging.getLogger("requests").setLevel(logging.WARNING)
# (?:xx) changes priority but will not be captured as args
@given('(.+) are... |
paulross/cpip | docs/doc_src/tutorial/demo/cpip_03.py | Python | gpl-2.0 | 376 | 0.010638 | import sys
from cpip.core import PpLexer, IncludeHandler
def main(): |
print('Processing:', sys.argv[1])
myH = IncludeHandler.CppIncludeStdOs(
theUsrDirs=['proj/usr',],
theSysDirs=['proj/sys',],
)
myLex = PpLexer.PpLexer(sys.argv[1], myH)
for tok in myLex.ppTokens():
| print(tok.t, end=' ')
if __name__ == "__main__":
main()
|
crs4/omero.biobank | bl/vl/utils/graph.py | Python | gpl-2.0 | 1,304 | 0.000767 | import bl.vl.kb.config as blconf
from bl.vl.utils import _get_env_variable
def graph_driver():
var = 'GRAPH_ENGINE_DRIVER'
try:
return _get_env_variable(var)
except ValueError:
try:
return getattr(blconf, var)
| except AttributeError:
raise ValueError("Cant't find config valuer for %s" % var)
def graph_uri():
var = 'GRAPH_ENGINE_URI'
try:
| return _get_env_variable(var)
except ValueError:
try:
return getattr(blconf, var)
except AttributeError:
raise ValueError("Cant't find config valuer for %s" % var)
def graph_username():
var = 'GRAPH_ENGINE_USERNAME'
try:
return _get_env_variable(var)
... |
hylje/lbtcex | lbtcex/main/views.py | Python | bsd-3-clause | 1,656 | 0.001208 | import json
from django.shortcuts import render
from django.contrib.auth.forms import AuthenticationForm
from registration.forms import RegistrationForm
from lbtcex.client.utils import api_token_required, api_get, api_post
from lbtcex.main.forms import ApiCallForm
def index(request):
if request.user.is_authent... | "result_pretty_json": json.dumps | (result.json(), indent=4)})
else:
opts = ApiCallForm()
return render(request, "api_call.html", {"form": opts})
|
bsmr-eve/Pyfa | eos/effects/subsystembonusgallenteoffensivedronedamagehp.py | Python | gpl-3.0 | 1,189 | 0.003364 | # subsystemBonusGallenteOffensiveDroneDamageHP
#
# Used by:
# Subsystem: Proteus Offensive - Drone Synthesis Projector
type = "passive"
def handler(fit, src, context):
fit.drones.filteredItemBoost(lambda mod: mod.item.requiresSkill("Drones"),
"armorHP", src.getModifiedItemAttr("su... | eredItemBoost(lambda mod: mod.item.requiresSkill("Drones"),
"hp", src.getModifiedItemAttr("subsystemBonusGallenteOffensive"),
skill="Gallente Offensive S | ystems")
fit.drones.filteredItemBoost(lambda mod: mod.item.requiresSkill("Drones"),
"damageMultiplier", src.getModifiedItemAttr("subsystemBonusGallenteOffensive"),
skill="Gallente Offensive Systems")
fit.drones.filteredItemBoost(lambda mod: mod.i... |
unclejed613/gnuradio-projects-rtlsdr | scanner/scanner.py | Python | gpl-2.0 | 14,567 | 0.008032 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: NFM SCANNER
# Author: JED MARTIN
# Description: NFM SCANNER EXPERIMENT
# Generated: Tue Jan 31 21:07:35 2017
##################################################
if __name__ == '__main... | erfall
False, #plottime
False, #plotconst
)
self.qtgui_sink_x_0.set_update_time(1.0/10)
self._qtgui_sink_x_0_win = sip.wrapinstance(self.qtgui_sink_x_0.pyqwidget(), Qt.QWidget)
self.top_layout.addWidget(self._qtgui_sink_x_0_win)
self.qtgui_sink_x_0. | enable_rf_freq(True)
self.low_pass_filter_0 = filter.fir_filter_ccf(5, firdes.low_pass(
1, r_rate, 7500, 5000, firdes.WIN_HAMMING, 6.76))
self._frequency_tool_bar = Qt.QToolBar(self)
if None:
self._frequency_formatter = None
else:
... |
n3storm/django-dynamic-preferences | dynamic_preferences/__init__.py | Python | bsd-3-clause | 193 | 0.005181 | from .dynamic_prefere | nces_registry import user_preferences_registry, global_preferences_registry
__version__ = "0.5.4"
default_app_config = 'dynam | ic_preferences.apps.DynamicPreferencesConfig'
|
jakevdp/bokeh | sphinx/source/tutorial/exercises/style.py | Python | bsd-3-clause | 2,134 | 0.003749 | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Define some categories
categories = [
'ousia', 'poson', 'poion', 'pros ti', 'pou',
'pote', 'keisthai', 'echein', 'poiein', 'paschein',
]
# Create data
N = 10
data = { cat : np.random.randint(10, 100, size=N) for cat in categories }
# Defin... | e stacked data
ys = stacked(data, categories)
# The x coordinates for each polygon are simply the series concatenated
# with its reverse.
xs = [np.hstack((categories[::-1], categories))] * len(ys)
# Pick out a color palette
colors = brewer["Spectral"][len(ys)]
# EXERCISE: output static HTML file
# EXERCISE: play ar... | - fill_color
# - fill_alpha
# - background_fill
patches(xs, ys, x_range=categories, y_range=[0, 800],
color=colors, alpha=0.8, line_color=None, background_fill="lightgrey",
title="Categories of Brewering")
# EXERCISE: configure all of the following plot properties
ygrid().grid_line_color = ... |
Joergen/zamboni | apps/versions/models.py | Python | bsd-3-clause | 25,586 | 0.000469 | # -*- coding: utf-8 -*-
import datetime
import json
import os
import django.dispatch
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.storage import default_storage as storage
from django.db import models
import caching.base
import commonware.log
import jin... | else:
new_plats.append(p)
| return new_plats
# Platforms are safe as is
return platforms
@property
def path_prefix(self):
return os.path.join(settings.ADDONS_PATH, str(self.addon_id))
@property
def mirror_path_prefix(self):
return os.path.join(settings.MIRROR_STAGE_PATH, str(self.addon_id... |
sheeshmohsin/mozioproj | mozio/wsgi.py | Python | mit | 387 | 0 | """
WSGI config for mozio project.
It exposes th | e WSGI callable as a module-le | vel variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mozio.settings")
application = get_wsgi_application()
|
alexandrucoman/labs | python/solutii/monica_vizitiu/unic/unic.py | Python | mit | 374 | 0 | #!/usr/bin/env python
# *-* coding: UTF-8 *-*
"""Problema unic."""
from __future__ import print_function
def g | aseste_unic(istoric):
"""unic"""
result = istoric.pop()
for numar in istoric:
result = result ^ numar
return result
if __name__ == "__main__":
assert gaseste_unic([1, 2, 3, 2, 1]) == 3
asser | t gaseste_unic([1, 1, 1, 2, 2]) == 1
|
DanielOaks/girc | docs/conf.py | Python | isc | 10,875 | 0.006437 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# girc documentation build configuration file, created by
# sphinx-quickstart on Fri Jul 10 20:20:32 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autog... | hat match files and
# directories to | ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will b... |
iulian787/spack | var/spack/repos/builtin/packages/libuv/package.py | Python | lgpl-2.1 | 1,625 | 0.003692 | # 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)
class Libuv(AutotoolsPackage):
"""Multi-platform library with a focus on asynchronous IO"""
homepage = "http://libu... | 674544b78f416697bd32c')
version('1.25.0', sha256='ce3036d444c3fb4f9a9e2994bec1f4fa07872b01456998b422ce918fdc55c254')
version('1.10.0', sha256='50f4ed57d65af4ab634e2cbdd90c49213020e15b4d77d3631feb633cbba9239f')
version('1.9.0', sha256='f8b8272a0d80138b709d38fad2baf771899eed61e7f9578d17898b07a1a2a5eb')
... | _on('automake', type='build')
depends_on('autoconf', type='build')
depends_on('libtool', type='build')
# Tries to build an Objective-C file with GCC's C frontend
# https://github.com/libuv/libuv/issues/2805
conflicts('%gcc platform=darwin', when='@:1.37.9',
msg='libuv does not compile... |
google-research/google-research | schema_guided_dst/baseline/pred_utils.py | Python | apache-2.0 | 6,649 | 0.005565 | # 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... | tatus"][slot_idx] > REQ_SLOT_THRESHOLD:
requested_slots.append(slot)
state["requested_slots"] = requested_slots
# Add prediction for user goal (slot values).
# Categorical slots.
for slot_idx, slot in enumerate(service_schema.categorical_slots):
slot_sta | tus = predictions["cat_slot_status"][slot_idx]
if slot_status == data_utils.STATUS_DONTCARE:
slot_values[slot] = data_utils.STR_DONTCARE
elif slot_status == data_utils.STATUS_ACTIVE:
value_idx = predictions["cat_slot_value"][slot_idx]
slot_values[slot] = (
... |
technologiescollege/Blockly-rduino-communication | scripts_XP/Lib/site-packages/jedi/evaluate/utils.py | Python | gpl-3.0 | 4,702 | 0.000851 | """ A universal module with functions / classes without dependencies. """
import sys
import contextlib
import functools
import re
import os
from jedi._compatibility import reraise
_sep = os.path.sep
if os.path.altsep is not None:
_sep += os.path.altsep
_path_re = re.compile('(?:\.[^{0}]+|[{0}]__init__\.py)$'.for... | C:\path\to\Lib
path = ''
for s in sys_path:
if (fs_path.startswith(s) and len | (path) < len(s)):
path = s
# - Window
# X:\path\to\lib-dynload/datetime.pyd => datetime
module_path = fs_path[len(path):].lstrip(os.path.sep).lstrip('/')
# - Window
# Replace like X:\path\to\something/foo/bar.py
return _path_re.sub('', module_path).replace(os.path.sep, '.').replace(... |
MTG/dunya-desktop | dunyadesktop_app/widgets/dockwidget.py | Python | gpl-3.0 | 12,917 | 0.000077 | import os
from PyQt5.QtWidgets import (QDockWidget, QSizePolicy, QWidget, QVBoxLayout,
QFrame, QLabel, QToolButton, QHBoxLayout,
QSpacerItem, QDialog)
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QSize, Qt
from .table import TableWidget, TableViewCol... | anding,
QSizePolicy.Preferred)
size_policy.setHorizontalStretch(0)
size_policy.setVerticalStretch(0)
size_policy.setHeightForWidth(
self.frame_downloaded.sizePolicy().hasHeightForWidth())
self.frame_downloaded.setSizePolicy(size_policy)
... | lf.frame_downloaded.setFrameShape(QFrame.StyledPanel)
self.frame_downloaded.setFrameShadow(QFrame.Raised)
def _set_label_downloaded(self):
"""Sets the label 'Downloaded'."""
font = QFont()
font.setFamily("Garuda")
self.label_downloaded.setFont(font)
self.label_downlo... |
miRTop/mirtop | mirtop/bam/bam.py | Python | mit | 15,466 | 0.001552 | """ Read bam files"""
from __future__ import print_function
# from memory_profiler import profile
import os.path as op
import os
import pysam
from collections import defaultdict
import pybedtools
from mirtop.libs import do
from mirtop.libs.utils import file_exists
import mirtop.libs.logger as mylog
from mirtop.mirna... | ed_fn, args.gtf)
logger.info("Loading database.")
# TODO this'll return conn_read | s and conn_counts
conn = _read_lifted_bam_alpha(intersect_fn, bam_fn, args)
rows = sql.select_all_reads(conn)
lines = []
current = None
logger.info("Analyzing database.")
for row in rows:
if not current or current == row[0]:
lines.append(row)
current = row[0]
... |
infobloxopen/heat-infoblox | heat_infoblox/tests/test_ha_pair.py | Python | apache-2.0 | 6,180 | 0 | # Copyright 2015 Infoblox Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | client = mock.MagicMock()
get_first_ip = mock.MagicMock()
ports = {
'vip': {'ip_address': '1.1.1.6', 'subnet_id': 'vip_subnet'},
'node1_lan1': {'ip_address': '1.1.1.4'},
| 'node1_ha': {'ip_address': '1.1.1.2'},
'node2_lan1': {'ip_address': '1.1.1.5'},
'node2_ha': {'ip_address': '1.1.1.3'},
}
get_first_ip.side_effect = create_side_effect(ports)
self.my_ha_pair._get_first_ip = get_first_ip
self.my_ha_pair.node = mock.MagicMoc... |
irl/gajim | src/gui_interface.py | Python | gpl-3.0 | 137,383 | 0.003581 | # -*- coding:utf-8 -*-
## src/gajim.py
##
## Copyright (C) 2003-2014 Yann Leboulanger <asterix AT lagaule.org>
## Copyright (C) 2004-2005 Vincent Hanquez <tab AT snarc.org>
## Copyright (C) 2005 Alex Podaras <bigpod AT gmail.com>
## Norman Rasmussen <norman AT rasmussen.co.za>
## S... | AT pobox.com>
## Nikos Kouremenos <kourem AT gmail.com>
## Copyright (C) 2006 Junglecow J <junglecow AT gmail.com>
## Stefan Bethge <stefan AT lanpartei.de>
## Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org>
## Copyright (C) 2007 Lukas Petrovicky <lukas AT pet... | Pivotto <roidelapluie AT gmail.com>
## Stephan Erb <steve-e AT h3c.de>
## Copyright (C) 2008 Jonathan Schleifer <js-gajim AT webkeks.org>
##
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License ... |
epicf/ef | examples/diode_childs_law/plot.py | Python | mit | 1,764 | 0.037982 | import os, glob
import operator
import h5py
import numpy as np
import matplotlib.pyplot as plt
def get_time_potential_charge_absrbd_on_anode_from_h5( filename ):
h5 = h5py.File( filename, mode="r")
absorbed_charge = h5["/InnerRegions/anode"].attrs["total_absorbed_charge"][0]
time = h5["/TimeGrid"].attrs["c... | = []
cgs_to_v = 300
for (t1,V1,q1), (t2,V2,q2) in zip( prev_step_vals, last_step_vals ):
print( t2 - t1, V2 - V1, q2 - q1 )
current.append( abs( ( q2 - q1 ) ) / ( t2 - t1 ) )
voltage.append( V1 * cgs_to_v )
#print( current, v | oltage )
#A,B = np.polyfit( np.ln( current ), voltage, 1 )
plt.figure()
axes = plt.gca()
axes.set_xlabel( "Voltage [V]" )
axes.set_ylabel( "Current [?]" )
#axes.set_xlim( [0, 1500] )
plt.plot( voltage, current,
linestyle='', marker='o',
label = "Num" )
#plt.plot( current_an, voltage_an,
# ... |
HackerEarth/django-allauth | allauth/socialaccount/providers/oauth/provider.py | Python | mit | 599 | 0.001669 | from django.core.urlresolvers import reverse
from django.utils.http import urlencode
from allauth.socialaccount.providers.base import Provider
class OAuthProvider(Provider):
def get_login_url(self, request, **kwargs):
url = reverse(self.id | + "_login")
if kwargs:
url = url + '?' + urlencode(kwargs)
return url
def get_scope(self):
settings = self.get_settings()
scope = settings.get('SCOPE')
if scope is None:
sco | pe = self.get_default_scope()
return scope
def get_default_scope(self):
return []
|
lrq3000/unireedsolomon | unireedsolomon/tests/test_cpolynomial.py | Python | mit | 9,289 | 0.027775 | import unittest
# Skip this whole module test if running under PyPy (incompatible with Cython)
try:
import __pypy__
# Empty test unit to show the reason of skipping
class TestMissingDependency(unittest.TestCase):
@unittest.skip('Missing dependency - Cython is incompatible with PyPy')
def ... | unction is optimized for monic divisor polynomial)
two = Polynomial(map_GF2int([5,3,1,1,6,8]))
q, r = two._gffastdivmod(one) # optimized for monic divisor polynomial
q2, r2 = two._fastdivmod(one)
self.assertEqual(q, q2)
| self.assertEqual(r, r2)
self.assertEqual(list(q.coefficients), [5, 12, 4])
self.assertEqual(list(r.coefficients), [52, 30, 12])
# Make sure they multiply back out okay
self.assertEqual(q*one + r, two)
def test_div_scalar(self):
"""Tests di... |
mnestis/provglish | provglish/nl/templates/generation_template.py | Python | mit | 3,100 | 0.006129 | from provglish import transform, prov
from provglish.lexicalisation import urn_from_uri as lex
from provglish.lexicalisation import plural_p
from provglish.prov import PROV
from provglish.nl.tools import SETTINGS, realise_sentence
import rdflib
from rdflib.plugins import sparql
from rdflib import RDF
import urllib2
... | sparql.prepareQuery(
"""
SELECT ?entity ?generation ?time ?activity WHERE {
GRAPH <prov_graph> {
{
?entity a prov:Entity .
?entity prov:qualifiedGeneration ?generation .
?generation a prov:Generation .
OPTIONAL { ?generation prov:atTime ?time... | Entity .
?entity prov:wasGeneratedBy ?activity .
?activity a prov:Activity
}
}
}
""",
initNs={"prov":PROV})
def _generation_binding(graph):
results = graph.query(_generation_query)
return results.bindings
def _generation_coverage(bindings, graph):
if ... |
lucky/newf | example_app.py | Python | mit | 559 | 0.014311 | from newf import Application, Response, ResponseRedirect
def foo(request):
return Response("<h1>Hello Worl | d!</h1>")
def bar(request):
return ResponseRedirect("/foo")
def test_debug(request):
raise Exception, 'I am the exception'
urls = (
(r'^/foo$', foo),
(r'^/bar$', bar),
(r'^/test-debug$', test_debug),
)
application = Application(urls, debug=True)
if __name__ == '__main__':
... | iref.simple_server import make_server
server = make_server('', 8000, application)
server.serve_forever()
|
byu-osl/city-issue-tracker | app/views.py | Python | gpl-2.0 | 12,663 | 0.033483 | import json
from flask import render_template, request, jsonify, Response
from app import app, db, ValidationError, genError
from fakeData import service_list, service_def, get_service_reqs, get_service_req, user_data
from models import Service, ServiceAttribute, Keyword, KeywordMapping, ServiceRequest, User, Note
from... | o get
"""
serviceRequest = ServiceRequest.query.get(issue_id)
if serviceRequest == None:
return genError(404, "Issue ID was not found");
return serviceRequest.toCitJSON()
#TODO: Test and deal with user authorization
@app.route('/issues', methods=['POST'])
def createI | ssue():
"""
Create an issue
"""
#TODO: Authoization?
requestJson = request.get_json()
if not requestJson:
return genError(400, JSON_ERR_MSG)
serviceRequest = ServiceRequest()
try:
serviceRequest.fromCitDict(requestJson);
except ValidationError as e:
return genError(400, e.errorMsg)
db.session.add(... |
matthewpklein/battsimpy | docs/extra_files/electrode_ocv_gen.py | Python | gpl-3.0 | 5,199 | 0.025582 | import pickle
from matplotlib import pyplot as plt
plt.style.use('classic')
import matplotlib as mpl
fs = 12.
fw = 'bold'
mpl.rc('lines', linewidth=2., color='k')
mpl.rc('font', size=fs, weight=fw, family='Arial')
mpl.rc('legend', fontsize='small')
import numpy
def grad( x, u ) :
return numpy.gradient(u) / nu... | /'
nmc_rest_523 = numpy.loadtxt( base+'data/Model_nmc/Model_Pars/solid/thermo | dynamics/2012Yang_523NMC_dchg_restOCV.csv', delimiter=',' )
nmc_cby25_111 = numpy.loadtxt( base+'data/Model_nmc/Model_Pars/solid/thermodynamics/2012Wu_NMC111_Cby25_dchg.csv' , delimiter=',' )
nmc_YangWu_mix = numpy.loadtxt( base+'data/Model_nmc/Model_Pars/solid/thermodynamics/YangWuMix_NMC_20170607.csv' , de... |
backupManager/pyflag | src/plugins_old/DiskForensics/FileHandlers/RFC2822.py | Python | gpl-2.0 | 8,766 | 0.013347 | """ This scanner handles RFC2822 type messages, creating VFS nodes for all their children """
# Michael Cohen <[email protected]>
# David Collett <[email protected]>
# Gavin Jackson <[email protected]>
#
# ******************************************************
# Version: FLAG $Version:... | new_fd.close()
count+=1
except Exception,e:
pyflaglog.log(pyflaglog.DEBUG,"RFC2822 Scan: Unable to parse inode %s as an RFC2822 message (%s)" % (self.inode,e))
class RFC2822_File(File):
""" A VFS Driver for reading mail attachments "... | inode):
File.__init__(self, case, fd, inode)
self.cache()
def read(self, length=None):
try:
return File.read(self,length)
except IOError:
pass
if self.readptr > 0:
return ''
self.fd.seek(0)
a=email.message_from_fi... |
apyrgio/ganeti | lib/jqueue/exec.py | Python | bsd-2-clause | 5,254 | 0.006662 | #
#
# Copyright (C) 2014 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | ob_id, new_prio)
r = context.jobqueue.ChangeJobPrio | rity(job_id, new_prio)
logging.debug("Result of changing priority of %d to %d: %s", job_id,
new_prio, r)
except Exception: # pylint: disable=W0703
logging.warning("Informed of priority change, but could not"
" read new priority")
prio... |
kgblll/libresoft-gymkhana | apps/gymkhana/core/api_team_member.py | Python | gpl-2.0 | 3,062 | 0.010451 | #
# Copyright (C) 2009 GSyC/LibreSoft
#
# 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 version.
#
# This ... | m=team)
team_member.save()
#first_proof = FirstProof.objects.get(event=event,team=t | eam)
return True, "ok"
def delete(team_member):
# Esto borraria al usuario de la red social LGS, pero solo quiero eliminar al miembro del equipo.
## => Me corrijo a mi mismo: de momento solo dejo crear nuevos team_member que no pertenezcan ya a LGS,
## asi que cuando borre un team_member, lo borro todo... |
sharkspeed/dororis | scripts/1w_1w.py | Python | bsd-2-clause | 555 | 0.007561 | # -*- encoding = utf-8 -*-
def test(n, flag=8):
return pow(3, n) < 10 ** flag
d | ef main():
n = 0
while test(n):
print(pow(3, n))
n += 1
print(n)
print(pow(3, n))
if __name__ == '__main__':
main()
# 2D:
# 134217728 ---> (17 month) ---> 1024
# Pixel: x y color owner price is_avaliable is_random_choosen is_advanced_color has_tax is_show show_price
# ExchangeReco... | 低于 value 不收取费用]
# User:
# 3D:
# 129140163 ---> (13 month) ---> 81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.