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 |
|---|---|---|---|---|---|---|---|---|
mseclab/PyJFuzz | test/test_pjf_configuration.py | Python | mit | 2,126 | 0.001881 | """
The MIT License (MIT)
Copyright (c) 2016 Daniele Linguaglossa <d.linguaglossa@mseclab.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation f | iles (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above ... | and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHAL... |
achadwick/mypaint | lib/tiledsurface.py | Python | gpl-2.0 | 42,966 | 0.000535 | # This file is part of MyPaint.
# Copyright (C) 2007-2008 by Martin Renold <martinxyz@gmx.ch>
#
# 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 opt... | My | PaintSurface to a separate class
class MyPaintSurface (TileAccessible, TileBlittable, TileCompositable):
"""Tile-based surface
The C++ part of this class is in tiledsurface.hpp
"""
def __init__(self, mipmap_level=0, mipmap_surfaces=None,
looped=False, looped_size=(0, 0)):
supe... |
ksmit799/Toontown-Source | toontown/ai/DistributedScavengerHuntTarget.py | Python | mit | 1,518 | 0.001976 | from direct.dir | ectnotify import DirectNotifyGlobal
from direct.distributed import DistributedObject
from otp.speedchat import SpeedChatGlobals
class DistributedScavengerHuntTarget(DistributedObject.DistributedObject):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedScavengerHuntTarget')
def __init__(self, c... | self.triggered = False
self.triggerDelay = 15
self.accept(SpeedChatGlobals.SCCustomMsgEvent, self.phraseSaid)
def phraseSaid(self, phraseId):
self.notify.debug('Checking if phrase was said')
helpPhrase = 10003
def reset():
self.triggered = False
i... |
nextgis/quickmapservices | src/ds_edit_dialog.py | Python | gpl-2.0 | 10,803 | 0.001574 | from __fut | ure__ import absolute_import
import os
import shutil
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QIcon, Q | Pixmap
from qgis.PyQt.QtWidgets import QDialog, QMessageBox
from os import path
from . import extra_sources
from .data_source_info import DataSourceInfo
from .data_source_serializer import DataSourceSerializer
from .data_sources_list import DataSourcesList
from .group_info import GroupInfo
from .groups_list import Gro... |
yongwen/makahiki | makahiki/apps/managers/log_mgr/admin.py | Python | mit | 1,266 | 0.00237 | """log model admin."""
from django.contrib import admin
from django.db import models
from django.forms.widgets import TextInput
from apps.managers.challenge_mgr import challenge_mgr
from apps.managers.log_mgr.models import MakahikiLog
from apps.admin.admin import challenge_designe | r_site, challenge_manager_site, developer_site
class MakahikiLogAdmin(admin.ModelAdmin):
"""admin"""
list_display = ('request_url', "remote_user", 'remote_ip', 'request_time',
'request_method', 'response_status')
list_filter = ('response_status', 'remote_user')
search_fields = ('re... | ordering = ["-request_time"]
date_hierarchy = "request_time"
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size': '100'})},
}
def has_add_permission(self, request):
return False
admin.site.register(MakahikiLog, MakahikiLogAdmin)
challenge_designer_site.r... |
lerouxb/ni | actions/base.py | Python | mit | 6,191 | 0.002746 | from ni.core.selection import Selection
from ni.core.text import char_pos_to_tab_pos
from ni.core.document import InsertDelta, DeleteDelta
class Action(object):
"""Base class for all view actions."""
def __init__(self, view):
self.grouped = False
self.editor = view.editor
self.view = ... | = self.after_cursor_pos
self.view.last_x_pos = self.after_last_x_pos
self.view.scroll_pos = self.after_ | scroll_pos
self.view.invalidate()
class ToggleComment(EditAction):
def __init__(self, view, comment_string):
self.comment_string = comment_string
super(ToggleComment, self).__init__(view)
def do(self):
view = self.view
doc = view.document
settin... |
wylieswanson/mythutils | mythutils_recfail_alarm/setup.py | Python | gpl-3.0 | 441 | 0.054422 | #!/usr/bin/env python
from glob import glob
from distutils.core import setup
setup( name="mythutils_recfail_alarm",
version="1.0",
description="Autoamtically notify on Recorder Failed via Prowl service",
author="Wylie Swanson",
author_email="wylie@pingzero.net",
url="http://www.pingzero.net",
scripts=glob("bin/... | files=[
( '/etc/mythutils/', glob('etc/mythutils/*') ),
( | '/etc/cron.d/', glob('etc/cron.d/*') ),
]
)
|
nesi/easybuild-framework | easybuild/toolchains/xlmvapich2.py | Python | gpl-2.0 | 573 | 0.001745 | ##
# You should have received a copy of the GNU General Public License
# along w | ith EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBui | ld support for xlmpich compiler toolchain (includes IBM XL compilers (xlc, xlf) and MPICH).
@author: Jack Perdue <j-perdue@tamu.edu> - TAMU HPRC - http://sc.tamu.edu
"""
from easybuild.toolchains.compiler.ibmxl import IBMXL
from easybuild.toolchains.mpi.mvapich2 import Mvapich2
class Xlompi(IBMXL, Mvapich2):
"""... |
CIGNo-project/CIGNo | cigno/metadata/admin.py | Python | gpl-3.0 | 16,379 | 0.01044 | #from django.contrib import admin
from django.contrib.gis import admin
from modeltranslation.admin import TranslationAdmin, TranslationTabularInline
from django.contrib.contenttypes.generic import GenericTabularInline
from cigno.mdtools.models import Connection
from django.utils.translation import ugettext_lazy as _
fr... | css = translation_css
class BaseCodeIsoAdmin(TranslationAdmin):
list_editable = ['label','isoid']
list_display = ['id', 'label', 'isoid']
class Media:
js = translation_js
css = translation_css
class CodeRefSysAdmin(TranslationAdm | in):
list_editable = ['label', 'srid']
list_display = ['id', 'label', 'srid']
class Media:
js = translation_js
css = translation_css
class CodeLicenseAdmin(TranslationAdmin):
list_editable = ['label', 'abstract']
list_display = ['id', 'label', 'abstract']
class Media:
... |
hachreak/invenio-previewer | invenio_previewer/utils.py | Python | gpl-2.0 | 1,963 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# M | ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In ... |
konradxyz/cloudify-manager | rest-service/manager_rest/test/test_provider_context.py | Python | apache-2.0 | 2,268 | 0 | #########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | self.assertEqual(result.json['status'], 'ok')
def | test_get_provider_context(self):
self.test_post_provider_context()
result = self.get('/provider/context').json
self.assertEqual(result['context']['key'], 'value')
self.assertEqual(result['name'], 'test_provider')
def test_post_provider_context_twice_fails(self):
self.test_p... |
Fokko/incubator-airflow | tests/gcp/hooks/test_text_to_speech.py | Python | apache-2.0 | 2,693 | 0.001857 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | icense 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.
#
import unittest
from airflow.gcp.hooks.text_to_speech import CloudTextT | oSpeechHook
from tests.compat import PropertyMock, patch
from tests.gcp.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id
INPUT = {"text": "test text"}
VOICE = {"language_code": "en-US", "ssml_gender": "FEMALE"}
AUDIO_CONFIG = {"audio_encoding": "MP3"}
class TestTextToSpeechHook(unittest.TestCase):
... |
3lnc/elasticsearch-dsl-py | test_elasticsearch_dsl/test_integration/test_examples/test_completion.py | Python | apache-2.0 | 518 | 0.001938 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .completion import Person
def test_person_suggests_on_all_variants_of_name(write_client):
Person.init(using=write_client)
Person(name='Honza Král', popularity=42).save(refresh=True)
s = Person.search().suggest('t', 'kra', completion={'... | onse = s.exe | cute()
opts = response.suggest.t[0].options
assert 1 == len(opts)
assert opts[0]._score == 42
assert opts[0]._source.name == 'Honza Král'
|
napjon/moocs_solution | robotics-udacity/2.4.py | Python | mit | 465 | 0.017204 | #this module here is to compute the formula to calculate the new means and
#new variance.
def update(mean1, var1, mean2, var2):
new_mean = ((mean1 * var2) + (mean2*var1))/(var1 + var2)
new_var = 1/(1/var1 + 1/var2)
return [new_mean, new_var]
def predict(mean1, var1, mean2, var2):
new_mean = mea... | return [new_mean, new_var]
print 'upda | te : 'update(10.,4., 12.,4.)
print predict(10.,4., 12.,4.) |
nicoddemus/pytest | src/_pytest/logging.py | Python | mit | 29,805 | 0.001309 | """Access and control log capturing."""
import logging
import os
import re
import sys
from contextlib import contextmanager
from io import StringIO
from pathlib import Path
from typing import AbstractSet
from typing import Dict
from typing import Generator
from typing import List
from typing import Mapping
from typing ... | if ret:
return ret
def pytest_addoption(parser: Parser) -> None:
"""Add options to control lo | g capturing."""
group = parser.getgroup("logging")
def add_option_ini(option, dest, default=None, type=None, **kwargs):
parser.addini(
dest, default=default, type=type, help="default value for " + option
)
group.addoption(option, dest=dest, **kwargs)
add_option_ini(
... |
rivimey/rwmapmaker | zziplib/docs/zzipdoc/htm2dbk.py | Python | gpl-3.0 | 7,044 | 0.017888 | #! /usr/bin/env python
"""
this file converts simple html text into a docbook xml variant.
The mapping of markups and links is far from perfect. But all we
want is the docbook-to-pdf converter and similar technology being
present in the world of docbook-to-anything converters. """
from datetime import date
import ma... | t>",
m()("(</?)(ol)>") >> "\\1orderedlist>",
m()("(</?)(dl)>") >> "\\1variablelist>",
m()("<dt\b([^<>]*)>","s") >> "<varlistentry\\1><term>",
m()("</dt\b([^<>]*)>","s") >> "</term>",
m()("<dd\b([^<>]*)>","s") >> "<listitem\\1>",
m( | )("</dd\b([^<>]*)>","s") >> "</listitem></varlistentry>",
m()("<table\b([^<>]*)>","s")
>> "<informaltable\\1><tgroup cols=\"2\"><tbody>",
m()("</table\b([^<>]*)>","s") >> "</tbody></tgroup></informaltable>",
m()("(</?)tr(\s[^<>]*)?>","s") >> "\\1row\\2>",
m()("(</?)td(\s[^<>]*)?>... |
sigmavirus24/twine | twine/cli.py | Python | apache-2.0 | 2,154 | 0 | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "Li | cense");
# 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/LIC | ENSE-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 Li... |
flacjacket/sympy | sympy/solvers/polysys.py | Python | bsd-3-clause | 9,192 | 0.001523 | """Solvers of systems of polynomial equations. """
from sympy.polys import Poly, groebner, roots
from sympy.polys.polytools import parallel_poly_from_expr
from sympy.polys.polyerrors import (ComputationFailed,
PolificationFailed, CoercionFailed)
from sympy.utilities import postfixes
from sympy.simplify import rcol... | ional Groebner basis, then there exists an
univariate polynomial in G (in its last variable). This can be
solved by computing its roots. Substituting all computed roots
for the last (eliminate | d) variable in other elements of G, new
polynomial system is generated. Applying the above procedure
recursively, a finite number of solutions can be found.
The ability of finding all solutions by this procedure depends
on the root finding algorithms. If no solutions were found, it
means only that ... |
dudanogueira/microerp | microerp/almoxarifado/migrations/0004_auto_20141006_1957.py | Python | lgpl-3.0 | 6,177 | 0.004371 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('rh', '0001_initial'),
('estoque', '0005_auto_20141001_0953'),
('comercial', '0007_auto_20141006_1852'),
... | ('quantidade_requisitada', models.DecimalField(max_digits=10, de | cimal_places=2)),
('quantidade_ja_atendida', models.DecimalField(max_digits=10, decimal_places=2)),
('criado', models.DateTimeField(default=datetime.datetime.now, verbose_name=b'Criado', auto_now_add=True)),
('atualizado', models.DateTimeField(default=datetime.datetime.no... |
MartinGHub/lvr-sat | SAT/bool.py | Python | bsd-3-clause | 6,053 | 0.000991 | __author__ = "Martin Jakomin, Mateja Rojko"
"""
Classes for boolean operators:
- Var
- Neg
- Or
- And
- Const
Functions:
- nnf
- simplify
- cnf
- solve
- simplify_cnf
"""
import itertools
# functions
def nnf(f):
""" Returns negation normal form """
return f.nnf()
def simplify(f):
""" Simplifies th... | en
ns = []
for x in s:
if isinstance(x,Or):
ns.extend(x.value)
else:
ns.appe | nd(x)
s = ns
snames = [x.simplify().__str__() for x in s]
s2 = []
for i, x in enumerate(s):
if Neg(x).nnf().__str__() in snames[i+1:]:
return Const(True)
elif isinstance(x, Const):
if x.value is True:
return Cons... |
Alafazam/simple_projects | misc/test_tqdm.py | Python | mit | 615 | 0.011382 | from ti | me import sleep
from tqdm import tqdm
import requests
url = "http://raw.githubusercontent.com/Alafazam/lecture_notes/master/Cormen%20.pdf"
response = requests.get(url, stream=True)
with open("10MB", "wb") as handle:
total_length = int(response.headers.get('content-length'))/1024
for data in tqdm(response.iter_cont... | ze=1024),total=total_length, leave=True, unit='KB'):
handle.write(data)
# with open("10MB", 'wb') as f:
# r = requests.get(url, stream=True)
# for chunk in tqdm(r.iter_content()):
# f.write(chunk)
# from tqdm import tqdm
# for i in tqdm(range(10000)):
# sleep(0.01) |
alexanderlz/redash | tests/tasks/test_refresh_schemas.py | Python | bsd-2-clause | 934 | 0 | from mock import patch
from tests import BaseTestCase
from redash.tasks import refresh_schemas
class TestRefreshSchemas(BaseTestCase):
def test_calls_refresh_of_all_data_sources(s | elf):
self.factory.data_source # trigger creation
with patch(
"redash.tasks.queries.maintenance.refresh_schema.delay"
) as refresh_job:
re | fresh_schemas()
refresh_job.assert_called()
def test_skips_paused_data_sources(self):
self.factory.data_source.pause()
with patch(
"redash.tasks.queries.maintenance.refresh_schema.delay"
) as refresh_job:
refresh_schemas()
refresh_job.assert_... |
sidthakur/simple-user-management-api | user_auth/app/create_db.py | Python | gpl-3.0 | 299 | 0.040134 | from pymong | o import MongoClient
from passlib.app import custom_app_context as pwd
client = MongoClient( host = "db" )
ride_sharing = client.ride_sharing
users = ride_sharing.users
users.insert_one( {
'username' : 'sid', |
'password_hash' : pwd.encrypt( 'test' ),
'role' : 'driver' } )
|
tdean1995/HFPythonSandbox | dist/nester/nester.py | Python | apache-2.0 | 481 | 0.008316 | """This module prints lists that may or may not contain nested lists"""
def print_lol(the_list):
"""This function takes a positional argument: called "the_list", which is any
Python list which may i | nclude nested lists. Each data item in the provided | lists
recursively printed to the screen on its own line."""
for each_item in the_list:
if isinstance(each_item,list):
print_lol(each_item)
else:
print(each_item)
|
alansammarone/mandelbrot | mandelbrot_image.py | Python | gpl-3.0 | 2,037 | 0.025037 | import os
import PIL
import math
import PIL
from PIL import Image
class MandelbrotImage:
def __init__(self, folder):
self.folder = folder
self.data_folder = os.path.join(folder, 'data')
self.image_folder = os.path.join(folder, 'image')
if not os.path.isdir(self.image_folder):
os.makedirs(self.image_fo... | names.sort(key=lambda x: int(x.split(".")[0]))
return fnames
def data_file_to_data(self, filepath):
with open(os.path.join(self.data_folder, filepath)) as file:
data = file.read()
data = data.split(" ")
width, height, max_iterations, precision = data[:4]
data = data[4:]
return int(width), in | t(height), int(max_iterations), int(precision), data
def data_to_pixel_data(self, data, coloring_scheme):
pixel_data = []
for i in xrange(0, len(data), 3):
escape_time = data[i]
z_real = data[i+1]
z_imag = data[i+2]
color = coloring_scheme(escape_time, z_real, z_imag, max_iter)
pixel_data.appen... |
anhstudios/swganh | data/scripts/templates/object/draft_schematic/bio_engineer/bio_component/shared_bio_component_food_duration_2.py | Python | mit | 470 | 0.046809 | #### 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 = Intangible()
result.template = "object/draft_schematic/bio_engineer/bio_component/shared_bio_component_food_duration_2.iff"
re... | ## BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
davesnowdon/nao-wanderer | wanderer/src/main/python/wanderer/wanderer.py | Python | gpl-2.0 | 14,410 | 0.005968 | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_enviro... | on(action) and all_done()
'''
class PlanExecutor(object):
def __init__(self, env, actionExecutor):
super(PlanExecutor, self).__init__()
self.env = env
self.actionExecutor = actionExecutor
def perform_next_action(self):
self.env.log("perform next action")
# save completed... | self.env.log("Completed action = {}".format(repr(completedAction)))
if not completedAction is None:
if not isinstance(completedAction, NullAction):
push_completed_action(self.env, completedAction)
# if we have moved, then save current location
if isin... |
CroceRossaItaliana/jorvik | attivita/migrations/0013_partecipazione_centrale_operativa.py | Python | gpl-3.0 | 448 | 0 | # -*- | coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attivita', '0012_attivita_centrale_operativa'),
]
operations = [
migrations.AddField(
model_name='partecipazione',
... | ),
]
|
rero/reroils-app | rero_ils/modules/organisations/api.py | Python | gpl-2.0 | 7,019 | 0 | # -*- coding: utf-8 -*-
#
# RERO ILS
# Copyright (C) 2019 RERO
# Copyright (C) 2020 UCLouvain
#
# 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, version 3 of the License.
#
# This program ... |
@classmethod
def get_record_by_online_harvested_source(cls, source):
"""Get record by online harvested source.
:param source: the record source
:return: Organisation record or None.
""" |
results = OrganisationsSearch().filter(
'term', online_harvested_source=source).scan()
try:
return Organisation.get_record_by_pid(next(results).pid)
except StopIteration:
return None
@property
def organisation_pid(self):
"""Get organisation p... |
HIPS/neural-fingerprint | neuralfingerprint/mol_graph.py | Python | mit | 3,492 | 0.002864 | import numpy as np
from rdkit.Chem import MolFromSmiles
from features import atom_features, bond_features
degrees = [0, 1, 2, 3, 4, 5]
class MolGraph(object):
def __init__(self):
self.nodes = {} # dict of lists of nodes, keyed by node type
def new_node(self, ntype, features=None, rdkit_ix=None):
... | les(s) for s in smiles_tuple]
big_graph = MolGraph()
for subgraph in graph_list:
big_graph.add_ | subgraph(subgraph)
# This sorting allows an efficient (but brittle!) indexing later on.
big_graph.sort_nodes_by_degree('atom')
return big_graph
def graph_from_smiles(smiles):
graph = MolGraph()
mol = MolFromSmiles(smiles)
if not mol:
raise ValueError("Could not parse SMILES string:", s... |
langcog/alignment | parsers/alignment.py | Python | gpl-2.0 | 7,365 | 0.035709 | import csv
import operator
import itertools
import math
import logger1
import re
#main piece of code for calculating & wwriting alignments from processed data
def calculateAlignments(utterances, markers, smoothing, outputFile, shouldWriteHeader, corpusType='CHILDES'):
markers = checkMarkers(markers)
groupedUtterance... | hing))
alignment = powerProb - baseProb
toAppend["alignment"] = alignment
toAppend["ba"] = ba
toAppend["bna"] = bna
toAppend["nba" | ] = nba
toAppend["nbna"] = nbna
return(toAppend)
# Gets us from the meta-data to the final output file
def runFormula(results, markers, smoothing,corpusType):
toReturn = []
categories = allMarkers(markers)
for i, result in enumerate(results):
if(i % 1000 is 10):
logger1.log("On result " + str(i) + " of " + s... |
Orav/kbengine | kbe/src/lib/python/Lib/collections/__init__.py | Python | lgpl-3.0 | 43,096 | 0.003202 | __all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
'UserString', 'Counter', 'OrderedDict', 'ChainMap']
# For backwards compatibility, continue to make the collections ABCs
# available through the collections module.
from _collections_abc import *
import _collections_abc
__all__... | ot.prev
link.prev = last
link.next = root
last.next = root.prev = link
else:
first = root.next
link.prev = root
link.next = first
root.next = first.prev = link
def __sizeof__(self):
sizeof = _sys.getsizeo... |
size += sizeof(self.__map) * 2 # internal dict and inherited dict
size += sizeof(self.__hardroot) * n # link objects
size += sizeof(self.__root) * n # proxy objects
return size
update = __update = MutableMapping.update
keys = MutableMapping.keys
... |
wiggi/huntercore | qa/rpc-tests/txn_clone.py | Python | mit | 7,555 | 0.006353 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test proper accounting with an equivalent malleability clone
#
from test_framework.test_framework im... | ts
# 40 BTC serialized is 00286bee00000000
pos0 = 2*(4+1+36+1+4+1)
hex40 = "00286bee00000000"
output_len = 16 + 2 + 2 * int("0x" + clone_raw[pos0 + 16 : pos0 + 16 + 2], 0)
if (rawtx1["vout"][0]["value"] == 40 and clone_raw[pos0 : pos0 + 16] != hex40 or
rawt | x1["vout"][0]["value"] != 40 and clone_raw[pos0 : pos0 + 16] == hex40):
output0 = clone_raw[pos0 : pos0 + output_len]
output1 = clone_raw[pos0 + output_len : pos0 + 2 * output_len]
clone_raw = clone_raw[:pos0] + output1 + output0 + clone_raw[pos0 + 2 * output_len:]
# Use a d... |
Stargrazer82301/CAAPR | CAAPR/CAAPR_AstroMagic/PTS/pts/modeling/config/initialize_fit.py | Python | mit | 1,745 | 0.005161 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# ... | gth", 2e5)
definition.add_flag("selfabsorption", "enab | le dust self-absorption")
definition.add_optional("dust_grid", str, "the type of dust grid to use (bintree, octtree or cartesian)", "bintree")
# -----------------------------------------------------------------
|
Fewbytes/rubber-docker | levels/04_overlay/rd.py | Python | mit | 5,063 | 0 | #!/usr/bin/env python2.7
"""Docker From Scratch Workshop - Level 4: Add overlay FS.
Goal: Instead of re-extracting the image, use it as a read-only layer
(lowerdir), and create a copy-on-write layer for changes (upperdir).
HINT: Don't forget that overlay fs also requires a workdir.
Read more on overlay FS here... | 'dev'))
def contain(command, image_name, image_dir, container_id, container_dir):
linux.unshare(linux.CLONE_NEWNS) # create a new mount namespace
linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, N | one)
new_root = create_container_root(
image_name, image_dir, container_id, container_dir)
print('Created a new root fs for our container: {}'.format(new_root))
_create_mounts(new_root)
old_root = os.path.join(new_root, 'old_root')
os.makedirs(old_root)
linux.pivot_root(new_root, old_... |
mikekestemont/beckett | code/analysis.py | Python | mit | 6,372 | 0.007062 | #!usr/bin/env python
# -*- coding: utf-8! -*-
from collections import Counter, OrderedDict
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.cluster.hierarchy import ward, dendrogram
from sklearn.decomposition import PCA
from sklearn.metrics.pairwise import euclidean_distances
from s... | color=plt.cm.spectral(cluster_label / 10.),
fontdict={'family': 'Arial', 'size': 10})
# now loadings on twin axis:
ax2 = ax1.twinx().twiny()
l1, l2 = pca_loadings[:,0], pca_loadings[:,1]
ax2.scatter(l1, l2, 100, edgecolors='none', face | colors='none');
for x, y, l in zip(l1, l2, feature_names):
ax2.text(x, y, l ,ha='center', va="center", size=8, color="darkgrey",
fontdict={'family': 'Arial', 'size': 9})
# control aesthetics:
ax1.set_xlabel('')
ax1.set_ylabel('')
ax1.set_xticklabels([])
ax1.set_xticks([... |
jameslyons/pycipher | tests/test_vigenere.py | Python | mit | 1,247 | 0.008019 | from pycipher import Vigenere
import unittest
class TestVigenere(unittest.TestCase):
def test_encipher(self):
keys = ('GERMAN',
'CIPHERS')
plaintext = ('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz',
'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz... | 'abcdefghijklmnopqrstuvwxyzabcde | fghijklmnopqrstuvwxyz')
ciphertext = ('gftpesmlzvkysrfbqeyxlhwkedrncqkjxtiwqpdzocwvjfuicbpl',
'cjrkiwyjqyrpdfqxfywkmxemfdrteltmkyalsatrfhszhaymozgo')
for i,key in enumerate(keys):
dec = Vigenere(key).decipher(ciphertext[i])
self.assertEqual(dec.upper(), plain... |
sio2project/oioioi | oioioi/participants/utils.py | Python | gpl-3.0 | 6,045 | 0.000496 | import unicodecsv
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.utils.encoding import force_text
from six.moves import map
from oioioi.base.permissions import make_request_condition
from oioioi.base.utils import request_cached
from oioioi.participants.controllers import P... | .last_name
if display_email:
value | s['email address'] = participant.user.email
data.append([values.get(key, '') for key in keys])
return {'keys': keys, 'data': data}
def render_participants_data_csv(request, participants, name):
data = serialize_participants_data(request, participants)
response = HttpResponse(content_type='text/cs... |
justyns/home-assistant | homeassistant/components/light/tellstick.py | Python | mit | 3,211 | 0 | """
Support for Tellstick lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.tellstick/
"""
from homeassistant.components import tellstick
from homeassistant.components.light import ATTR_BRIGHTNESS, Light
from homeassistant.components.tellstick... | self.tellstick_device.dim(self._brightness)
else:
raise NotImplementedError(
"Command not implemen | ted: {}".format(command))
def turn_on(self, **kwargs):
"""Turn the switch on."""
from tellcore.constants import TELLSTICK_DIM
brightness = kwargs.get(ATTR_BRIGHTNESS)
if brightness is not None:
self._brightness = brightness
self.call_tellstick(TELLSTICK_DIM, sel... |
pashinin-com/pashinin.com | src/core/models.py | Python | gpl-3.0 | 22,154 | 0.000045 | import json
import hashlib
from django.db import models
from django.db.models import Count, Func
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.utils.translation import gettext_lazy as _
# from social.apps.django_app.default.mod... | (self, email, username, password):
user = self.create_user(email, username, password)
user.is_active = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User( | AbstractBaseUser, PermissionsMixin):
objects = UserManager()
USERNAME_FIELD = 'email'
email = models.EmailField(
verbose_name='Email',
max_length=255,
unique=True,
db_index=True,
blank=True, null=True,
default=None,
)
username = models.CharField(
... |
openseat/ipylayoutwidgets | ipylayoutwidgets/widgets/__init__.py | Python | bsd-3-clause | 88 | 0.011364 | from .widg | et_svg_layout import SVGLayoutBox
from .widget_fullscreen import Fullscr | eenBox |
cuongnb14/bilyric | config/wsgi.py | Python | mit | 1,707 | 0 | """
WSGI config for Bilyric project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` ... | the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
from django.core.wsgi import get_wsgi_application
if os.environ.get('DJANGO_SETTIN... | t.middleware.wsgi import Sentry
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.pro... |
capitalone/cloud-custodian | tests/test_ebs.py | Python | apache-2.0 | 25,361 | 0.000789 | # Copyright 2016-2017 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import logging
from botocore.exceptions import ClientError
import mock
from c7n.exceptions import PolicyValidationError
from c7n.executor import MainThreadExecutor
from c7n.resources.aws impo... | = p.run()
self.assertEqual(len(resources), 1)
client = factory(region="us-east-1").client('ec2')
volumelist = []
volumelist.append(resources[0]['VolumeId | '])
response = client.describe_volumes(VolumeIds=volumelist)
for resp in response['Volumes']:
for attachment in resp['Attachments']:
self.assertTrue(attachment['State'] == "detached" or
attachment['State'] == "detaching")
class SnapshotCopyT... |
mtasic85/dockyard | host.py | Python | mit | 5,231 | 0.006117 | # -*- coding: utf-8 -*-
__all__ = ['host_blueprint']
from datetime import datetime, timedelta
# dateutil
from dateutil.parser import parse as dtparse
# flask
from flask import (
Flask, request, session, g,
redirect, url_for, abort,
render_template, flash, jsonify,
Blueprint, abort,
send_from_direc... | '] = datetime.utcnow()
host = Host(**_host)
db.session.add(host)
db.session.commit()
_host = object_to_dict(host)
data = {
'host': _host,
}
return jsonify(data)
@host_blueprint.route('/host/update', methods=['POST'])
@login_required
def host... | update:', locals()
if usertype != 'super':
data = {}
return jsonify(data)
host = Host.query.get(_host['id'])
assert host is not None
_host['updated'] = datetime.utcnow()
update_object_with_dict(host, _host)
db.session.commit()
_host = object_to_dict(ho... |
bbfamily/abu | abupy/TradeBu/ABuTradeProxy.py | Python | gpl-3.0 | 14,496 | 0.001752 | # -*- encoding:utf-8 -*-
"""
交易执行代理模块
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ impo | rt division
from contextlib import contextmanager
from functools import total_ordering
from enum imp | ort Enum
import numpy as np
import pandas as pd
from . import ABuTradeDrawer
from . import ABuTradeExecute
__author__ = '阿布'
__weixin__ = 'abu_quant'
class EOrderSameRule(Enum):
"""对order_pd中对order判断为是否相同使用的规则"""
"""order有相同的symbol和买入日期就认为是相同"""
ORDER_SAME_BD = 0
"""order有相同的symbol, 买入日期,和卖出日期,即不考... |
mozey/taskmage | taskmage/response.py | Python | mit | 557 | 0.008977 | from tabulate import tabulate
class Response():
message = None;
data = None;
def print(self):
if self.message:
if type(self.message) == "str":
| print(self.message)
elif type | (self.message) == "list":
for message in self.message:
print("{}\n".format(message))
if (self.data):
if len(self.data["rows"]) > 0:
print(tabulate(self.data["rows"], headers=self.data["headers"]))
else:
print("Empty!")
... |
funkybob/rattle | rattle/parser/__init__.py | Python | mit | 1,048 | 0 | import rply
from ..lexer import lexers
__all__ = ('parsers',)
class Parsers(object):
def __init__(self):
self._fpg = None
self._fp = None
self._spg = None
self._sp = None
@property
def fpg(self):
if self._fpg is None:
self._fpg = rply.ParserGenerato... | ,
precedence=[]
)
return self._spg
@property
def sp(self):
if self._sp is None:
self._sp = self.spg.build()
return self._sp
parsers = Parsers()
# Load productions
from .filter import fpg # noqa
from .structure impo | rt spg # noqa
|
Ezhil-Language-Foundation/open-tamil | examples/classifier/modelprocess2.py | Python | mit | 3,817 | 0.001339 | # -*- coding: utf-8 -*-
# (C) 2017 Muthiah Annamalai
# This file is part of open-tamil examples
# This code is released under public domain
import joblib
# Ref API help from : https://scikit-learn.org
import numpy as np
import random
import string
import time
from sklearn.metrics import accuracy_score
from sklearn.met... | transform(X_train)
X_test = scaler.transform(X_test)
###########
## Build training set | for the model
## solver='sgd',activation='logistic',
## We have a 4-layer model
nn = MLPClassifier(hidden_layer_sizes=(15, 15, 10, 5),
activation='logistic',
max_iter=100000, alpha=0.01, solver='lbfgs')
# Try 1-layer simple model with logistic activation
# nn = MLPClassifier(
# ... |
sasha-gitg/python-aiplatform | google/cloud/aiplatform_v1beta1/services/vizier_service/transports/grpc_asyncio.py | Python | apache-2.0 | 29,300 | 0.001365 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | iceGrpcTransport
class VizierServiceGrpcAsyncIOTransport(VizierServiceTransport):
"""gRPC AsyncIO backend transport for VizierService.
Vertex Vizier API.
Vizier service is a GCP service to solve blackbox optimization
problems, such as tuning machine learning hyperparameters and
searching over dee... | g architectures.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends protocol buffers over the wire using gRPC (which is built on
top of HTTP/2); the ``grpcio`` package must be installed.
"""
... |
lfcnassif/MultiContentViewer | release/modules/ext/libreoffice/program/python-core-3.3.0/lib/urllib/response.py | Python | lgpl-3.0 | 3,021 | 0.001324 | """Response classes used by urllib.
The base class, addbase, defines a minimal file-like interface,
including read() and readline(). The typical response object is an
addinfourl instance, which defines an info() method that returns
headers and a geturl() method that returns the url.
"""
class addbase(object):
""... | eaders = headers
def info(self):
return self.headers
class addinfourl | (addbase):
"""class to add info() and geturl() methods to an open file."""
def __init__(self, fp, headers, url, code=None):
addbase.__init__(self, fp)
self.headers = headers
self.url = url
self.code = code
def info(self):
return self.headers
def getcode(self):
... |
rtfd/readthedocs.org | readthedocs/oauth/management/commands/reconnect_remoterepositories.py | Python | mit | 4,783 | 0.002091 | import json
from django.db.models import Q, Subquery
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
from readthedocs.oauth.services import registry
from readthedocs.oauth.services.base import SyncServiceError
from readthedocs.projects.models import Project
fr... | organization = Organization.objects.get(slug=organization)
if force_owners_social_resync:
self._force_owners_soci | al_resync(organization)
self._connect_repositories(organization, no_dry_run, only_owners)
except Organization.DoesNotExist:
print(f'Organization does not exist. organization={organization}')
|
grnet/synnefo | snf-cyclades-app/synnefo/db/migrations/old/0080_nics_to_ips.py | Python | gpl-3.0 | 20,524 | 0.008234 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.mo... | rue'}),
'drained': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'dtotal': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'hash': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'hypervisor': ('django.db.mode... | length': '32'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'index': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'unique': 'True'}),
'mfree': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'... |
mharding01/herbpy | src/herbpy/action/grasping.py | Python | bsd-3-clause | 9,013 | 0.005658 | import logging, openravepy, prpy
from prpy.action import ActionMethod
from prpy.planning.base import PlanningError
from contextlib import contextmanager
logger = logging.getLogger('herbpy')
@ActionMethod
def Grasp(robot, obj, manip=None, preshape=[0., 0., 0., 0.],
tsrlist=None, render=True, **kw_args):
... | :
robot.Rele | ase(obj)
for obj in grabbed_objs:
robot.Grab(obj)
# Create list of any current collisions so those can be disabled
while robot.GetEnv().CheckCollision(robot, creport):
collision_obj = creport.plink2.GetParent()
disabled_objects.append(collision_obj)
collision_obj.Ena... |
joereynolds/Mr-Figs | src/minigames/hunt/game.py | Python | gpl-3.0 | 2,622 | 0.002288 | import pygame
import src.graphics as graphics
import src.colours as colours
import src.config as config
import src.scenes.scenebase as scene_base
from src.minigames.hunt.input_handler import InputHandler
from src.gui.clickable import Clickable
from src.resolution_asset_sizer import ResolutionAssetSizer
from src.tiled_m... | = False
return has_no_enemies
def has_completed_minigame(self): |
return self.has_won() and self.current_stage == 3
def render(self):
self.surface.fill(colours.RED)
self.sprites.draw(self.surface)
def get_player(self):
for sprite in self.sprites:
if isinstance(sprite, Player):
return sprite
def reset(self):
... |
indico/indico | indico/modules/auth/blueprint.py | Python | mit | 2,168 | 0.005996 | # 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 flask import request
from indico.modules.auth.controllers import (RHAccounts, RHAdminImpersonate, RH... | template_folder='templates', virtual_template_folder='auth')
_bp.add_url_rule('/ | login/', 'login', RHLogin, methods=('GET', 'POST'))
_bp.add_url_rule('/login/<provider>/', 'login', RHLogin)
_bp.add_url_rule('/login/<provider>/form', 'login_form', RHLoginForm)
_bp.add_url_rule('/login/<provider>/link-account', 'link_account', RHLinkAccount, methods=('GET', 'POST'))
_bp.add_url_rule('/logout/', 'logo... |
DemocracyClub/EveryElection | every_election/apps/core/migrations/0001_initial.py | Python | bsd-3-clause | 621 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.models import Group, User
def add_moderator_group(apps, schema_editor):
g = Group.objects.create(name="moderators")
g.save()
for user in User.objects.all():
# add any existing... | if user.is_superuser:
g.user_set.add(user)
class Migration(migrations.Migration):
dependencies = [("auth", "0008_alter_user_username_max_length")]
operations = [migrations.RunPython(add_moderator | _group)]
|
mkolar/pyblish-kredenc | pyblish_kredenc/plugins/nuke/extract_scene_save.py | Python | lgpl-3.0 | 313 | 0 | import | nuke
import pyblish.api
class ExtractSceneSave(pyblish.api.Extractor):
"""
"""
hosts = ['nuke']
order = pyblish.api.Extractor.order - 0.45
families = ['scene']
label = 'Scene Save'
def process(self, instance):
| self.log.info('saving scene')
nuke.scriptSave()
|
jkpr/pma-api | pma_api/response.py | Python | mit | 3,061 | 0 | """Responses."""
from io import StringIO
from csv import DictWriter
from flask import Response, jsonify, make_response
from .__version__ import __version__
class ApiResult:
"""A representation of a generic JSON API result."""
def __init__(self, data, metadata=None, **kwargs):
"""Store input argumen... | cords into a response."""
if self.return_format == 'csv' and self.record_list:
return self.csv_response(self.record_list)
elif self.return_f | ormat == 'csv': # and not self.record_list
return make_response('', 204)
# Default is JSON
return self.json_response(self.record_list, self.extra_metadata,
**self.kwargs)
@staticmethod
def csv_response(record_list):
"""CSV Response."""
... |
akvo/akvo-rsr | akvo/iati/checks/fields/related_activities.py | Python | agpl-3.0 | 1,444 | 0.003463 | # -*- coding: utf-8 -*-
# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
def related_activities(project):
... | hecks_passed = True
related_projects_count = p | roject.related_projects.count()
for rp in project.related_projects.prefetch_related('related_project').all():
if not (rp.related_project or rp.related_iati_id):
all_checks_passed = False
checks.append(('error', 'related project or IATI identifier not specified'))
elif rp.re... |
ict-felix/stack | modules/resource/orchestrator/src/core/utils/calls.py | Python | apache-2.0 | 6,238 | 0.00016 | from formatting import print_call
import credentials
import os.path
import re
import xmlrpclib
def _get_ch_params():
# Initialise variables when required
from core.config import FullConfParser
fcp = FullConfParser()
username = fcp.get("auth.conf").get("certificates").get("username")
ch_host = fcp... | f._key_path = key_path
self._cert_path = cert_path
def make_connection(self, host):
"""
This method will automatically be called by the ServerProxy class
when a transport channel is needed.
"""
host_with_cert = (host, {"key_file": self._key_path,
... | l_call(method_name, params, endpoint, key_path=None, cert_path=None,
host=None, port=None):
username, ch_host, ch_port, ch_end = _get_ch_params()
key_path = key_path or ("%-key.pem" % username)
cert_path = cert_path or ("%-cert.pem" % username)
host = host or ch_host
port = port or ch_p... |
XiaJieCom/change | Demo/days10/EchoClient.py | Python | lgpl-2.1 | 658 | 0.018237 | from twisted.internet import reactor,protocol
class EchoClient(protocol.Protocol):
def connectionMade(self):
self.transport.write("hello a ")
def dataReceived(self, data):
print('Server said:',data)
self.transport.loseConnection | ()
def connectionLost(self, reason):
print('connection lost')
class EchoFatoty(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print('Connection lost - goodbye!')
| reactor.stop()
def main():
f = EchoFatoty()
reactor.connectTCP('localhost',9090,f)
reactor.run()
if __name__ == '__main__':
main() |
FEniCS/dolfin | site-packages/dolfin/functions/__init__.py | Python | lgpl-3.0 | 827 | 0.001209 | # -*- coding: utf-8 -*-
"""The function module of dolfin"""
from dolfin.functions import multimeshfunction
from dolfin.functions import functionspace
from dolfin.functions import function
from dolfin.functions import constant
from dolfin.functions import expression
from dolfin.functions import specialfunctions
from .... | tem in DOLFIN requires to _not_ define
# NOTE: classes or functions within this file. Use separate modules for that
# NOTE: purpose.
__all__ = functionspace.__all__ + fu | nction.__all__ + constant.__all__ + \
expression.__all__ + specialfunctions.__all__ + \
multimeshfunction.__all__
|
jgowans/directionFinder_web | directionFinder_web/views/hello_json.py | Python | gpl-2.0 | 400 | 0.0125 | from pyramid.view import view_config
import logging
@view_config(route_name='hello_json', renderer='json')
def hello_json(request):
logger = logging.getLogger(__nam | e__)
logger.info("Got JSON from name: {n}".format(n = __name__))
| request.session['counter'] = request.session.get('counter', 0) + 1
return {
'a': [1,2,request.session['counter']],
'b': ['x', 'y'],
}
|
mondwan/ProjectRazzies | twitter_analyse.py | Python | mit | 9,448 | 0.004128 | #!/usr/bin/env python
"""
File: twitter_analyse.py
Author: Me
Email: 0
Github: 0
Description: Analyse tweets. For the detail, please refer to the document
```twitter_analyse.notes```
"""
# System lib
from __future__ import division
import json
import os
from math import log
import numpy
# 3-rd party lib
# import nltk... | ('followers', followers)
]:
data_name = data_set[0]
data_list = data_set[1]
print '|%s| sd: %f mean: %f min: %d max: %d' % (
data_name,
round(data_list.std(), 2),
round(numpy.average(data_list), 2), |
data_list.min(),
data_list.max(),
)
# ret['avg_followers'] = round(numpy.average(followers_data), 2)
# ret['avg_friends'] = round(numpy.average(friends_data), 2)
ret['avg_polarity'] = round(numpy.average(polarities_data), 2)
# ret['avg_retweet'] = round(numpy.average(re... |
dynaryu/inasafe | safe/gui/tools/minimum_needs/needs_manager_dialog.py | Python | gpl-3.0 | 33,744 | 0 | # coding=utf-8
"""
Impact Layer Merge Dialog.
.. note:: 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.
"""
__... | w
self.profile_editing_buttons = list()
self.profile_editing_buttons.append(self.remove_resource_button)
self.profile_editing_buttons.append(self.add_resource_button)
self.profile_editing_buttons.append(self.edit_resource_button)
self.profile_editing_bu | ttons.append(self.export_profile_button)
self.profile_editing_buttons.append(self.import_profile_button)
self.profile_editing_buttons.append(self.new_profile_button)
self.profile_editing_buttons.append(self.save_profile_button)
self.profile_editing_buttons.append(self.save_profile_as_but... |
stanley-cheung/grpc | src/python/grpcio_tests/tests_aio/unit/_common.py | Python | apache-2.0 | 3,617 | 0 | # Copyright 2020 The 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 a | pplicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIO | NS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
from typing import AsyncIterable
import grpc
from grpc.aio._metadata import Metadata
from grpc.aio._typing import MetadataKey
from grpc.aio._typing import Me... |
vmturbo/nova | nova/virt/hyperv/vmops.py | Python | apache-2.0 | 48,910 | 0 | # Copyright (c) 2010 Cloud.com, Inc
# Copyright 2012 Cloudbase Solutions Srl
# 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/... | I
}
def check_admin_permissions(function):
@functools.wraps(function)
def wrapper(self, *args, **kwds):
# Make sure the windows account has the required admin permissions.
self._vmutils.check_admin_permissions()
return function(self, *args, **kwds)
return wrapper
class VMOps(obj... | # the maximum console log size.
_MAX_CONSOLE_LOG_FILE_SIZE = units.Mi / 2
_ROOT_DISK_CTRL_ADDR = 0
def __init__(self, virtapi=None):
self._virtapi = virtapi
self._vmutils = utilsfactory.get_vmutils()
self._metricsutils = utilsfactory.get_metricsutils()
self._vhdutils = u... |
VUIIS/dax | dax/cluster.py | Python | mit | 11,384 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" cluster.py
Cluster functionality
"""
import os
import time
import logging
import subprocess as sb
from datetime import datetime
from .dax_settings import DAX_Settings
from .errors import ClusterError
__copyright__ = 'Copyright 2013 Vanderbilt University. All Right... | cess(os.path.join(path, cmd), os.X_OK)
for path in os.environ["PATH"].split(os.pathsep)]:
return True
return False
class PBS(object): # The s | cript file generator class
""" PBS class to generate/submit the cluster file to run a task """
def __init__(self, filename, outfile, cmds, walltime_str, mem_mb=2048,
ppn=1, env=None, email=None,
email_options=DAX_SETTINGS.get_email_opts(), rungroup=None,
xnat_h... |
chhsiao90/cheat-ext | cheat_ext/main.py | Python | mit | 1,279 | 0 | import argparse
from cheat_ext.info import info, ls
from cheat_ext.installer import (
install, upgrade, remove
)
from cheat_ext.linker import link, unlink
def _install(args):
install(args.repository)
link(args.repository)
def _upgrade(args):
upgrade(args.repository)
link(args.repository)
d | ef _remove(args):
unlink(args.repository)
remove(args.repository)
def _info(args):
info(args.repository)
def _ls(args | ):
ls()
parser = argparse.ArgumentParser(description="cheat extension")
subparsers = parser.add_subparsers()
install_parser = subparsers.add_parser("install")
install_parser.add_argument("repository", type=str)
install_parser.set_defaults(func=_install)
upgrade_parser = subparsers.add_parser("upgrade")
upgrad... |
mkusz/invoke | sites/shared_conf.py | Python | bsd-2-clause | 1,189 | 0 | from datetime import datetime
from os.path import abspath, join, dirname
import alabaster
# Alabaster theme + mini-extension
html_theme_path = [alabaster.get_path()]
extensions = ['alabaster', 'sphinx.ext.intersphinx', 'sphinx.ext.doctest']
# Paths relative to invoking conf.py - not this shared file
html_theme = 'al... | [
'about.html',
'navigation.html',
'searchbox.html',
'donate.html',
]
}
# Everything intersphinx's to Python
intersphinx_mapping = {
'python': ('https://docs.python.org/2.7/', None),
}
# Doctest settings
doctest_path = [abspath(join(dirname(__file__), '..', 'tests'))]
doctest_g... | r"""
from _util import MockSubprocess
"""
# Regular settings
project = 'Invoke'
year = datetime.now().year
copyright = '{} Jeff Forcier'.format(year)
master_doc = 'index'
templates_path = ['_templates']
exclude_trees = ['_build']
source_suffix = '.rst'
default_role = 'obj'
|
peter17/pijnu | samples/wikiLine.py | Python | gpl-3.0 | 2,097 | 0.007153 | # -*- coding: utf8 -*-
'''
Copyright 2009 Denis Derman <denis.spir@gmail.com> (former developer)
Copyright 2011-2012 Peter Potrowl <peter017@gmail.com> (current developer)
This file is part of Pijnu.
Pijnu is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public Lic... | T = Word('!!')(drop)
MONOSPACE = Word('__')(drop)
rawText = OneOrMore(rawChar)(join)
distinctText = Sequence(DISTINCT, inline, DISTINCT)(liftValue)
importantText = Sequence(IMPORTANT, inline, IMPORTANT)(liftValue)
monospaceText = Sequence(MONOSPACE, inline, MONOSPACE)(liftValue)
styledText = Choice(distinctText, import... | monospaceText)
text = Choice(styledText, rawText)
inline **= OneOrMore(text)
parser = Parser('wikiLine', locals(), 'inline')
|
Azure/azure-sdk-for-python | sdk/netapp/azure-mgmt-netapp/azure/mgmt/netapp/operations/_backup_policies_operations.py | Python | mit | 31,820 | 0.004431 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
"accountName": _SERIALIZER.url("account_name", account_name, 'str'),
"backupPolicyName": _SERIALIZER.url("backup_policy_name", backup_policy_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
... | # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_... |
leliel12/handy | handy/logger.py | Python | bsd-3-clause | 733 | 0.006821 | # -*- coding: utf-8 -*-
import logging, logging.handlers
from django.c | onf import settings
def get_logger(name, level=logging.INFO, format='[%(asctime)s | ] %(message)s', handler=None, filename=None):
new_logger = logging.getLogger(name)
new_logger.setLevel(level)
if not handler:
filename = filename or '%s/logs/%s.log' % (settings.HOME_DIR, name)
handler = logging.FileHandler(filename)
handler.setFormatter(logging.Formatter(format))
... |
jianjunz/online-judge-solutions | leetcode/0750-contain-virus.py | Python | mit | 5,673 | 0.000705 | class Solution:
def containVirus(self, grid: List[List[int]]) -> int:
current_set_number = 1
grid_set = [[0 for i in range(len(grid[0]))] for j in range(len(grid))]
set_grid = {}
threaten = {}
def getAdjacentCellsSet(row, col) -> List[int]:
answer = []
... | grid_set)
# print(answer)
while len(threaten) != 0:
# print(threaten)
largest_infected = sorted(
| threaten.items(), key=lambda x: x[1], reverse=True)[0]
answer += contain(largest_infected[0])
spread()
# print(grid_set)
# print(answer)
threatenCells()
return answer
|
BV-DR/foamBazar | pythonScripts/gmshScript/line.py | Python | gpl-3.0 | 2,331 | 0.014586 | import copy
from .point import Point
from .misc import *
'''
Line is defined using two point(s).
'''
class Line(object):
_ID_NAME = '_LINE_ID'
_DB_NAME = '_EXISTING_LINES'
def __init__(self, geom, p0, p1):
def check(p):
if geom is None: return p
if isinstance(p, Point):
... | Line.fromkey(keystr)"
@classmethod
def fro | mkey(cls, keystr):
pid=cls.dataFromKey(keystr)
return Line(None, pid[0], pid[1])
@classmethod
def masterDBKeys(cls, geom):
subkeys=copy.deepcopy(getDB(geom,cls).keys())
for i in range(0,len(subkeys)):
tmp=subkeys[i].split(',')
subkeys[i]=",".join(tmp[:len(... |
infochimps-forks/ezbake-common-python | support/django/setup.py | Python | apache-2.0 | 1,200 | 0.000833 | #!/usr/bin/env python2
# Copyright (C) 2013-2014 Computer Sciences 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 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 Li... | ion='2.1',
description='Supporting library for integrating Django applications with EzBake.',
license='Apache License 2.0',
author='EzBake Developers',
author_email='developers@ezbake.io',
namespace_packages=['ezbake', 'ezbake.support'],
packages=find_packages('lib', exclude=['test*']),
pack... |
prodicus/dabble | python/decorators/decorate_with_tags.py | Python | mit | 381 | 0.010499 | #!/usr/bin/env python
# encoding: utf-8
"""An example for a funct | ion returning a function"""
def surround(tag1, tag2):
def wraps(content):
return '{}{}{}'.format(tag1, content, tag2)
return wraps
def printer(content, transform):
return transform(content)
print printer("foo bar", surround("<a>", "</a>"))
print printer("foo bar", surround('<p>', ' | </p>'))
|
vicky2135/lucious | oscar/lib/python2.7/site-packages/flake8/main/debug.py | Python | bsd-3-clause | 2,017 | 0 | """Module containing the logic for our debugging logic."""
from __future__ import print_function
import json
import platform
import setuptools
def print_information(option, option_string, value, parser,
option_manager=None):
"""Print debugging information used in bug reports.
:param o... | lugins_from(option_manager),
'dependencies': dependencies(),
'platform': {
'python_implementation': platform.python_implementation(),
'python_version': p | latform.python_version(),
'system': platform.system(),
},
}
def plugins_from(option_manager):
"""Generate the list of plugins installed."""
return [{'plugin': plugin, 'version': version}
for (plugin, version) in sorted(option_manager.registered_plugins)]
def dependencies(... |
PersonalGenomesOrg/open-humans | private_sharing/migrations/0001_squashed_0034_auto_20160727_2138.py | Python | mit | 14,678 | 0.002861 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-01 23:15
import autoslug.fields
import common.utils
import datetime
from django.conf import settings
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
import... | ),
| ),
migrations.CreateModel(
name='OnSiteDataRequestProject',
fields=[
('datarequestproject_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='private_sharing.DataRequestP... |
shonenada/crawler | setup.py | Python | mit | 359 | 0 | from setuptools import setup | , find_packages
setup(
name="simple-crawler",
version="0.1",
url="https://github.com/shonenada/crawler",
author="shonenada",
author_email="shonenada@gmail.com",
description="Simple crawler",
zip_safe=True,
platforms="any",
packages=find_packages(),
| install_requires=["requests==2.2.1"],
)
|
denys-duchier/Scolar | notes_users.py | Python | gpl-2.0 | 1,115 | 0 | # -*- mode: python -*-
# -*- coding: iso8859-15 -*-
##############################################################################
#
# Gestion scolarite IUT
#
# Copyright (c) 2001 - 2006 Emmanuel Viennet. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the term... | s published by
# the Free Software Foundation; either version 2 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
# ... | lic License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Emmanuel Viennet emmanuel.viennet@viennet.net
#
#######################... |
xingjiepan/ss_generator | ss_generator/ca_tracing/alpha_helix.py | Python | bsd-3-clause | 11,909 | 0.005458 | import numpy as np
from ss_generator import geometry
from . import basic
D_MEAN = 3.81
D_STD = 0.02
THETA_MEAN = np.radians(91.8)
THETA_STD = np.radians(3.35)
TAU_MEAN = np.radians(49.5)
TAU_STD = np.radians(7.1)
def theta_tau_to_rotation_matrix(theta, tau):
'''Get the rotation matrix corresponding to the
bo... | t[1], ca_list[2])
M_init = np.dot(geometry.rotation_matrix_from_axis_and_angle(
scr | ew_axes[0], phase_shift), np.transpose(M1))
# Calculate the Ca coordinates
shifted_ca_list = generate_alpha_helix_from_screw_axes(screw_axes, relieve_strain=True, M_init=M_init)
t = np.mean(ca_list, axis=0) - np.mean(shifted_ca_list, axis=0)
for i in range(len(shifted_ca_list)):
shifted_ca_li... |
wesolutki/voter | auth/models.py | Python | gpl-3.0 | 2,125 | 0.000471 | from common.models import *
from common.localization import txt, verbose_names
@verbose_names
class Patient(models.Model): |
# private
first_name = models.CharField(max_length=80)
last_name = models.CharField(max_length=80)
GENDER = (
(txt('M'), txt('male')),
(txt | ('F'), txt('female'))
)
gender = models.CharField(max_length=1, choices=GENDER)
BLOOD_TYPE = (
(txt('0Rh-'), txt('0Rh-')),
(txt('0Rh+'), txt('0Rh+')),
(txt('ARh-'), txt('ARh-')),
(txt('ARh+'), txt('ARh+')),
(txt('BRh-'), txt('BRh-')),
(txt('BRh+'), txt('BRh+')... |
FinnStutzenstein/OpenSlides | server/openslides/assignments/migrations/0016_negative_votes.py | Python | mit | 2,395 | 0.000418 | # Generated by Django 2.2.15 on 2020-11-24 06:44
from decimal import Decimal
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("assignments", "0015_assignmentvote_delegated_user"),
]
operations = [
migrations... | odel_name="assignmentpoll",
name="pollmethod",
field=models.CharField(
choices=[
("votes", "Yes per candidate"),
("N", "No per candidate"),
("YN", "Yes/No per candidate"),
("YNA", "Yes/No/Abstain per ... | ],
max_length=5,
),
),
migrations.AlterField(
model_name="assignmentpoll",
name="onehundred_percent_base",
field=models.CharField(
choices=[
("YN", "Yes/No per candidate"),
("YN... |
gstiebler/odemis | src/odemis/acq/test/spot_alignment_test.py | Python | gpl-2.0 | 10,396 | 0.002982 | # -*- coding: utf-8 -*-
'''
Created on 25 April 2014
@author: Kimon Tsitsikas
Copyright © 2013-2014 Kimon Tsitsikas, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License version 2 as published by the Free Software
F... | f.result() # make sure the move is over
time.slee | p(0.1) # make sure the stream had time to detect position has changed
received = st.image.value
f = acq.acquire([st])
received, _ = f.result()
self.assertTrue(received, "No image received after 30 s")
# if calibration has happened (=good), it has changed the metadata
md... |
south-coast-science/scs_dfe_eng | tests/gas/afe/afe_test.py | Python | mit | 2,350 | 0.000426 | #!/usr/bin/env python3
"""
Created on 15 Aug 2016
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
Note: this script uses the Pt1000 temp sensor for temperature compensation.
"""
import time
from scs_core.data.json import JSONify
from scs_core.gas.afe_baseline import AFEBaseline
from scs_core.gas.afe_ca... | )
print(afe_calib)
print("-")
afe_baseline = AFEBaseline.load(Host)
print(afe_baseline)
print("-")
sensors = afe_calib.sensors(afe_baseline)
print('\n\n'.join(str(sensor) for sensor in sensors))
print("-")
# ------------------------------------------------------------------------... | (afe)
print("-")
start_time = time.time()
temp = afe.sample_pt1000()
elapsed = time.time() - start_time
print(temp)
print("elapsed:%0.3f" % elapsed)
print("-")
start_time = time.time()
sample = afe.sample_station(1)
elapsed = time.time() - start_time
print("SN1: %s" % sam... |
rcatlin/ryancatlin-info | Api/app/migrations/0003_remove_tag_articles.py | Python | mit | 388 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-20 01:22
from __future__ import unicode_literals
from dj | ango.db import | migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20170819_2342'),
]
operations = [
migrations.RemoveField(
model_name='tag',
name='articles',
),
]
|
cnbird1999/ava | ava/core_identity/models.py | Python | gpl-2.0 | 4,406 | 0.001816 | from django.db import models
from django.core.validators import validate_email, validate_slug, validate_ipv46_address
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from ava.core.models import TimeStampedModel
from ava.core_group.models import Group
from ava.core_identi... | e = models.CharField(max_length=10,
choices=IDENTITY_TYPE_CHOICES,
| default=PERSON,
verbose_name='Identity Type')
groups = models.ManyToManyField(Group,
blank=True,
related_name='identities')
def __str__(self):
return self.name or ''
def... |
sebrandon1/nova | nova/tests/unit/test_cinder.py | Python | apache-2.0 | 9,333 | 0.000107 | # Copyright 2011 OpenStack Foundation
#
# 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... | self.assertEqual(retries, self.create_client().client.connect_retries)
def test_cinder_api_ins | ecure(self):
# The True/False negation is awkward, but better for the client
# to pass us insecure=True and we check verify_cert == False
self.flags(insecure=True, group='cinder')
self.assertFalse(self.create_client().client.session.verify)
def test_cinder_http_timeout(self):
... |
jacebrowning/doorstop | doorstop/core/base.py | Python | lgpl-3.0 | 11,112 | 0 | # SPDX-License-Identifier: LGPL-3.0-only
"""Base classes and decorators for the doorstop.core package."""
import abc
import functools
import os
from typing import Dict
import yaml
from doorstop import common, settings
from doorstop.common import DoorstopError, DoorstopInfo, DoorstopWarning
log = common.logger(__na... | if self.auto:
self.save()
return result
return wrapped
class BaseFileObject(metaclass=abc.ABCMeta):
"""Abstract Base Class for objects whose attributes save to a file.
For properties that are saved to a file, decorate their getters
with :func:`auto_load` and their setters with ... | automatic save until explicit save
def __init__(self):
self.path = None
self.root = None
self._data: Dict[str, str] = {}
self._exists = True
self._loaded = False
def __hash__(self):
return hash(self.path)
def __eq__(self, other):
return isinstance(o... |
zhaoace/codecraft | python/projects/learnpythonthehardway.org/ex48/setup.py | Python | unlicense | 434 | 0.002304 | try:
from setuptools import setup
ex | cept ImportError:
from distutils.core import setup
config = {
'description': 'ex48',
'author': 'Zhao, Li',
'url': 'URL to get it at.',
'download_url': 'Where to download it.',
'author_email': 'zhaoace@gmail.com',
'version': '0.1',
'install_requires': ['nose'],
'packages':... | 'name': 'ex48'
}
setup(**config) |
tanglei528/ceilometer | ceilometer/tests/dispatcher/test_file.py | Python | apache-2.0 | 3,762 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <litong01@us.ibm.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | d_metering_data(msg)
# After the method call above, the file should have been created.
self.assertTrue(os.path.exists(handler.baseFilename))
def test_file_dispatcher_with_path_only(self):
# Create a temporaryFile to get a file name
tf = tempfile.NamedTemporaryFile | ('r')
filename = tf.name
tf.close()
self.CONF.dispatcher_file.file_path = filename
self.CONF.dispatcher_file.max_bytes = None
self.CONF.dispatcher_file.backup_count = None
dispatcher = file.FileDispatcher(self.CONF)
# The number of the handlers should be 1
... |
strogo/djpcms | runtests.py | Python | bsd-3-clause | 722 | 0.012465 | #!/usr/bin/env python
import os
import sys
from optparse import OptionParser
def makeoptions():
parser = OptionParser()
parser.add_option("-v", "--verbosity",
| type = int,
action="store",
dest="verbosity",
default=1,
help="Tests verbosity level, one of 0, 1, 2 or 3")
return parser
if __name__ == '__main__':
import djpcms
import sys
options, tags = makeoptio... | t run
run(tags, verbosity = verbosity) |
iamharshit/ML_works | Photo Painter/NN.py | Python | mit | 2,722 | 0.013226 | import tensorflow as tf
import numpy as np
import cv2
img_original = cv2.imread('jack.jpg') #data.camera()
img = cv2.resize(img_original, (64*5,64*5))
# for positions
xs = []
# for corresponding colors
ys = []
for row_i in range(img.shape[0]):
for col_i in range(img.shape[1]):
xs.append([row_i, col_i])
ys.app... | _neurons) else None,
scope='layer_' + str(layer_i))
Y_pred = current_input
cost = tf.reduce_mean(tf.reduce_sum(distance(Y_pred,Y),1) )
optimizer = tf.train.AdamOptimizer(0.001).minimize(cost)
#training Neural Net
n_iterations = 500
batch_size = 50
with tf.Session() as sess:
sess.run(tf.initialize_all_var... | ations):
idxs = np.random.permutation(range(len(xs)))
n_batches = len(idxs) // batch_size
for batch_i in range(n_batches):
idxs_i = idxs[batch_i * batch_size: (batch_i + 1) * batch_size]
sess.run(optimizer, feed_dict={X: xs[idxs_i], Y: ys[idxs_i] })
train... |
alirizakeles/tendenci | tendenci/apps/events/widgets.py | Python | gpl-3.0 | 4,968 | 0.00161 | from django import forms
from django.core.urlresolvers import reverse
from django.forms.widgets import RadioFieldRenderer
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class BootstrapChoiceFieldRenderer(RadioFieldRenderer):
"""... | manage_custom_reg_link = ''
output_html = """
<div id="t-events-use-customreg-box">
<div id="t-events-use-customreg-checkbox" class="checkbox">
<label for="id_%s_%s">%s Use Custom Registration Form</label>
</div>
<div id=... | endered_use_custom_reg_form,
rendered_bind_reg_form_to_conf_only,
manage_custom_reg_link
)
return mark_safe(output_html)
def render_widget(self, widget, name, value, attrs, index=0, id=None):
i = index
id_ = id
if value:
try:
... |
seravok/LPTHW | StudyDrillMath.py | Python | gpl-3.0 | 590 | 0 | # Prints exactly what the script is about to do
print "How many keys are there for the swedish alph | abet?"
# Prints the amount of the top row
print "The top row has 11 letter keys"
# Assigns a value to top
top = 11.0
# Prints the amount of the middle row
print "The middle row has 11 letter keys"
# Assigns a value to middle
middle = 11
# Prints the amount of the bottom row
print "The bottom row has 7 letter keys"... | o bottom
bottom = 7
# Prints text then the combined value of from the three rows
print "The total number of letter keys are ", top + middle + bottom
|
xhava/hippyvm | testing/test_options.py | Python | mit | 3,254 | 0.001537 | import py
import re
from testing.test_interpreter import BaseTestInterpreter
from testing.test_main import TestMain
from hippy.main import entry_point
class TestOptionsMain(TestMain):
def test_version_compare(self, capfd):
output = self.run('''<?php
$versions = array(
'1',
'1.0',
... | conf)
assert self.space.str_w(output[0]) == php_version
assert self.space.str_w(output[1]) == test_value
def test_get_cfg_var2(self):
output = self.run('''
echo get_cfg_var('');
echo get_cfg_var(' ');
echo get_cfg_var('non_existent_var');
echo get_cfg_var(nu... | );
''')
assert all([o == self.space.w_False for o in output])
def test_get_cfg_var3(self):
with self.warnings() as w:
output = self.run('''
echo get_cfg_var(array(1));
class Test {};
echo get_cfg_var(new Test);
''')
ass... |
ereOn/azmq | tests/unit/test_mechanisms/test_base.py | Python | gpl-3.0 | 2,577 | 0 | """
Unit tests for the base mechanism class.
"""
import pytest
from azmq.mechanisms.base import Mechanism
from azmq.errors import ProtocolError
@pytest.mark.asyncio
async def test_expect_command(reader):
reader.write(b'\x04\x09\x03FOOhello')
reader.seek(0)
result = await Mechanism._expect_command(reade... | (b'\x09')
reader.seek(0)
async def on_command(name, data):
assert False
with pytest.raises(ProtocolError):
await Mechanism.read(reader=reader, on_command= | on_command)
|
LaurentClaessens/phystricks | testing/demonstration/phystricksMBWHooeesXIrsz.py | Python | gpl-3.0 | 563 | 0.039146 | # -*- coding: utf8 -*-
from ph | ystricks import *
def MBWHooeesXIrsz():
pspict,fig = SinglePicture("MBWHooeesXIrsz")
pspict.dilatation(0.3)
l=4
A=Point(0,0)
B=Point(l,0)
C=Point(l,l)
trig=Polygon(A,B,C)
trig.put_mark(0.2,pspict=pspict)
trig.edges[0].put_code(n=2,d=0.1,l=0.2,pspict=pspict)
trig.edges[1].put_co... | érifier la longueur des codages."
fig.no_figure()
fig.conclude()
fig.write_the_file()
|
manxueitp/cozmo-test | cozmo_sdk_examples/if_this_then_that/ifttt_gmail.py | Python | mit | 6,646 | 0.003624 | #!/usr/bin/env python3
# Copyright (c) 2016 Anki, 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 in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | tp` to install")
import cozmo
from common impo | rt IFTTTRobot
app = web.Application()
async def serve_gmail(request):
'''Define an HTTP POST handler for receiving requests from If This Then That.
You may modify this method to change how Cozmo reacts to the email
being received.
'''
json_object = await request.json()
# Extract the name ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.