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 |
|---|---|---|---|---|---|---|---|---|
leeyiw/dnspod_ddns | config.py | Python | apache-2.0 | 163 | 0.006135 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
LOGIN_EMAIL = 'your@email.here' |
LOGIN_PASSWORD = 'your_ | password_here'
SUB_DOMAIN = 'www'
DOMAIN = 'your-domain.here'
|
emvigo/pyctactoe | pttengine/gamefactory.py | Python | gpl-3.0 | 1,238 | 0.002423 | # gamefactory.py - GameFactory class implementation
#
# Copyright (C) 2009 CptPicard
# Copyright (C) 2008 David Futcher
# Copyright (C) 2008, 2009, 2010, 2011 Eugenio M. Vigo
#
# This file is part of PycTacToe
#
# PycTacToe is free software: you can redistribut | e 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.
#
# PycTacToe 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 General Public License along with
# PycTacToe. If not, see <http://www.gnu.org/licenses/>.
class GameFactory(objec... |
python-constraint/python-constraint | examples/sudoku/sudoku.py | Python | bsd-2-clause | 2,675 | 0.001121 | #
# Sudoku puzzle solver by by Luigi Poderico (www.poderico.it).
#
import sys
from constraint import Problem, AllDifferentConstraint
def solve():
problem = Problem()
# Define the variables: 9 rows of 9 variables rangin in 1...9
for i in range(1, 10):
problem.addVariables(range(i * 10 + 1, i * 10 ... | , 10):
for j in range(1, 10):
| index = i * 10 + j
sys.stdout.write("%s " % solution[index])
print("")
print("")
if __name__ == "__main__":
main()
|
openstack/horizon | horizon/templatetags/form_helpers.py | Python | apache-2.0 | 2,432 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | field.field.widget.attrs['class'] = ' '.join(field_classes)
return field
@register.filter
def autocomplete(field, value='on'):
field.field.widget.attrs['autocomplete'] = value
return field
@register.filter
def is_checkbox(field):
return isinstance(field.field.widget, django.forms.Ch | eckboxInput)
@register.filter
def is_multiple_checkbox(field):
return isinstance(field.field.widget, django.forms.CheckboxSelectMultiple)
@register.filter
def is_radio(field):
return isinstance(field.field.widget, django.forms.RadioSelect)
@register.filter
def is_file(field):
return isinstance(field.f... |
elcodigok/WebHardening | core/api/console.py | Python | gpl-3.0 | 1,818 | 0.006071 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import cmd
from .plugins import Plugins
class Console(cmd. | Cmd):
prompt = "WebHardening> "
|
_colors = {'red': '#FF0000',
'white': '#FFFFFF',
'black': '#000000'}
def __init__ (self):
"""Constructor"""
cmd.Cmd.__init__(self)
self._plugins = Plugins()
def do_hello (self, name):
"""Says hello to someone"""
print "Hello %s... |
zestrada/nova-cs498cc | nova/db/api.py | Python | apache-2.0 | 56,325 | 0.000391 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (t... | e given properties on a service and update it.
Raises NotFound if service does not exist.
"""
return IMPL.service_update(context, service_id, values)
###################
def compute_node_get(context, compute_id):
"""Get | a computeNode."""
return IMPL.compute_node_get(context, compute_id)
def compute_node_get_all(context):
"""Get all computeNodes."""
return IMPL.compute_node_get_all(context)
def compute_node_search_by_hypervisor(context, hypervisor_match):
"""Get computeNodes given a hypervisor hostname match string.... |
fertozudo/umatoo | savings/migrations/0004_auto_20160918_2224.py | Python | bsd-3-clause | 2,652 | 0.002262 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-09-18 22:24
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('savings', '0003_auto_20160918... | go.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='kimonitransaction',
name='amount',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='kimonitransaction',
| name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='profileuser',
name='risky',
field=models.IntegerField(choices=[(1, 'very low'), (2, 'low'), (3, 'med... |
davidwhogg/LensTractor | lenstractor/model.py | Python | gpl-2.0 | 28,818 | 0.0093 | '''
This f | ile is part of the lenstractor project.
Copyright 2012 David W. Hogg (NYU) and Phil Marshall (Oxford).
Description
-----------
Model class, to package up srcs and enable initialization.
To-do
-----
- debug, test
'''
import numpy as np
import pylab as plt
import tractor
import lenst | ractor
deg2rad = 0.017453292
resetre = 0.5 # MAGIC: effective radius for the galaxy reset, 0.5 for PS1 and 1.0 for SQLS
# ============================================================================
class Model():
'''
PURPOSE
Define a named model that can be initialized, passed to a tractor etc.
C... |
feroda/lessons-python4beginners | src/gestionale/managers02/base.py | Python | agpl-3.0 | 1,676 | 0.008353 |
class BaseManager(object):
def __init__(self, debug=False):
"""Init with debug mode on/off."""
self.debug = debug
def _do_export(self, rows):
"""
Do the import job from the specific backend
WARNING: self.f MUST be an object that
supports the "write()" method... | "To be implemented in subclasses")
def debug_export(self, rows):
if self.debug:
print(self.get_output(rows)
def debug_import(self, rows):
if self.debug:
print(rows)
class BaseFileManager(BaseManager):
def __init__(self, fname, debug=False):
... | r(BaseFileManager, self).__init__(debug=debug)
def do_export(self, rows):
"""
Do the export operation.
Print data output if object is in debug mode.
"""
self.debug_export(rows)
with open(self.fname, "wb") as self.f:
return self._do_export(rows)
def... |
JonathonReinhart/pykvm | test.py | Python | mit | 3,324 | 0.009326 | #!/usr/bin/env python
# pykvm
# https://github.com/JonathonReinhart/pykvm
# (C) 2015 Jonathon Reinhart
import sys
import os, os.path
import mmap
import struct
import pykvm
from pykvm.exitreason import *
def dump_extensions(kvm):
for ext, sup in kvm.get_extensions():
print '{:<40}: {}'.format(ext, sup)
... | str(regs)
def test_sregs(vcpu):
sregs = vcpu.get_sregs()
print 'Special Registers:'
print sregs
sregs.cr0 |= ((1<<31) | (1<<30))
vcpu.set_sregs(sregs)
sregs = vcpu.get_sregs()
print 'Special Registers (ag | ain):'
print sregs
def map_file_to_guest(vm, filename, guest_phys_addr, size, readonly):
# Unfortunately, ctypes doesn't support readonly memmaps, so we can't
# really get the address of the memmap.
with open(filename, 'rb') as f:
data = f.read()
assert(len(data) == size)
return map_t... |
Hybrid-Cloud/cinder | cinder/api/v3/group_specs.py | Python | apache-2.0 | 5,882 | 0 | # Copyright (c) 2016 EMC 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 o... | f, req, group_type_id, id, body=None):
context = req.environ['cinder.context']
self._check_policy(context)
if not body:
expl = _('Request body empty')
raise webob.exc.HTTPBadRequest(explanation=expl)
self._check_type(context, group_type_id)
if id not in b... |
expl = _('Request body and URI mismatch')
raise webob.exc.HTTPBadRequest(explanation=expl)
if len(body) > 1:
expl = _('Request body contains too many items')
raise webob.exc.HTTPBadRequest(explanation=expl)
self._check_key_names(body.keys())
utils... |
abogeorge/simpleTicket | simpleTicket/siteEngine/views.py | Python | mit | 15,240 | 0.012598 | from django.shortcuts import render, render_to_response
from django.contrib import auth
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required
from .models import Ticket, UserProfile, Order, TicketType, OrderType
from django.core.mail import send_mail
from django.templ... | :False})
# Logout view
def logout(request):
auth.logout(request)
return render(request, "login.html", {'change_succeded':True})
# Account Page
@login_required
def myaccount(request):
# User Auth object
user = request.user
# Retrieving User
user_profile = | get_profile_for_user(user)
# Retrieving Tickets
tickets = get_tickets_for_user_profile(user_profile)
# Retrieving orders
orders = get_orders_for_user_profile(user_profile)
return render(request, "myaccount.html", {'user':user, 'user_profile':user_profile, 'tickets':tickets, 'orders':orders})
# Con... |
ctools/ctools | test/test_csiactobs.py | Python | gpl-3.0 | 13,064 | 0.007655 | #! /usr/bin/env python
# ==========================================================================
# This scripts performs unit tests for the csiactobs script
#
# Copyright (C) 2016-2018 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General... | ' outobs="csiactobs_obs_cmd2.xml"'+ \
' outmodel="csiactobs_bgd_cmd2.xml"'+ \
' logfile="csiactobs_cmd2.log" de | bug=yes debug=yes'+ \
' chatter=1'
# Check if execution failed
self.test_assert(self._execute(cmd, success=False) != 0,
'Check invalid input datapath when executed from command line')
# Setup csiactobs command
cmd = csiactobs+' datapath="'+s... |
ianastewart/cwltc-admin | public/views/enquiry_views.py | Python | mit | 3,800 | 0.000263 | import logging
from datetime import datetime
from openpyxl import Workbook
from django.http import HttpResponse
from django.shortcuts import redirect, reverse
from django.views.generic import CreateView, UpdateView, TemplateView
from braces.views import StaffuserRequiredMixin
from mysite.common import Button, LinkB... | s.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
enquiry = Enquiry.objects.get(pk=kwargs.pop("pk"))
context["person"] = enquiry.person
context["adult"] = enquiry.adult_tennis
| context["children"] = enquiry.person.person_set.all()
return context
|
sbg/sevenbridges-python | sevenbridges/meta/transformer.py | Python | apache-2.0 | 10,566 | 0 | from datetime import datetime
from sevenbridges.errors import SbgError
class Transform:
@staticmethod
def to_resource(resource):
from sevenbridges.meta.resource import Resource
if not resource:
raise SbgError('Invalid id value!')
elif isinstance(resource, Resource) and has... | p):
retur | n billing_group.id
elif isinstance(billing_group, str):
return billing_group
else:
raise SbgError('Invalid billing group parameter!')
@staticmethod
def to_volume(volume):
"""Serializes volume to id string
:param volume: object to serialize
:return... |
pericles-project/TechnicalAppraisalTool | pericles-ibuilder/ScienceBuilder/main.py | Python | apache-2.0 | 17,935 | 0.008865 | # Copyright King's College London, 2017.
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership. King's College London licences this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the Lic... | yTable.items():
entityid = entity.replace(' ', '_')
line = 'exp:' + str(entityid) + ' rdf:type owl:NamedIndividual , \n'
line = line + '\t'+ E.entityTypetoDVA[entityType] + ' ; \n'
line = line + ' exp:hasGoogleName "' + refs['Google Trends'] + '" ; \n'
line ... | asGithubName "' + refs['Github'] + '" ; \n'
else:
line = line + ' exp:hasGithubName ' + '"" ; \n'
if 'SourceForge' in refs.keys():
line = line + ' exp:hasSourceForgeName "' + refs['SourceForge'] + '" ; \n'
else:
line = line + ' exp:... |
chrisbarber/dask | dask/array/rechunk.py | Python | bsd-3-clause | 19,776 | 0.000354 | """
The rechunk module defines:
intersect_chunks: a function for
converting chunks to new dimensions
rechunk: a function to convert the blocks
of an existing dask array to new chunks or blockshape
"""
from __future__ import absolute_import, division, print_function
import heapq
from itertools ... |
Parameters
----------
old_chunks : iterable of tuples
block sizes along each dimension (conve | rt from old_chunks)
new_chunks: iterable of tuples
block sizes along each dimension (converts to new_chunks)
"""
cmo = cumdims_label(old_chunks, 'o')
cmn = cumdims_label(new_chunks, 'n')
sums = [sum(o) for o in old_chunks]
sums2 = [sum(n) for n in old_chunks]
if not sums == sums2:
... |
madbook/reddit-plugin-gold | setup.py | Python | bsd-3-clause | 418 | 0.014354 | #!/usr/bin/env pytho | n
from setuptools import setup, find_packages
setup(name='reddit_gold',
description='reddit gold',
version='0.1',
author='Chad Birch',
author_email='chad@reddi | t.com',
packages=find_packages(),
install_requires=[
'r2',
],
entry_points={
'r2.plugin':
['gold = reddit_gold:Gold']
},
include_package_data=True,
zip_safe=False,
)
|
laurentva/Pozyx-Python-library | pypozyx/definitions/bitmasks.py | Python | lgpl-3.0 | 939 | 0.001065 | #!/usr/bin/env python
"""pypozyx.definitions.bitmasks - contains all bitmasks used in Pozyx functionality, such as interrupt flags."""
# Bit mask for POZYX_ST_RESULT
POZYX_ST_RESU | LT_ACC = 0x01
POZYX_ST_RESULT_MAGN = 0x02
POZYX_ST_RESULT_GYR = 0x04
POZYX_ST_RESULT_MCU = 0x08
POZYX_ST_RESULT_PRES = 0x10
POZYX_ST_RESULT_UWB = 0x20
# Bit mask for POZYX_INT_STATUS
POZYX_INT_STATUS_ERR = 0x01
POZYX_INT_STATUS_POS = 0x02
POZYX_INT_STATUS_IMU = 0x04
POZYX_INT_STATUS_RX_DATA = 0x08
POZYX_INT_STATUS_FUN... | 0x10
# Bit mask for POZYX_INT_MASK
POZYX_INT_MASK_ERR = 0x01
POZYX_INT_MASK_POS = 0x02
POZYX_INT_MASK_IMU = 0x04
POZYX_INT_MASK_RX_DATA = 0x08
POZYX_INT_MASK_FUNC = 0x10
POZYX_INT_MASK_TDMA = 0x40
POZYX_INT_MASK_PIN = 0x80
POZYX_INT_MASK_ALL = 0x1F
# Bit mask for POZYX_LED_CTRL
POZYX_LED_CTRL_LED1 = 0x01
POZYX_LED_CT... |
edx-solutions/edx-platform | cms/djangoapps/contentstore/proctoring.py | Python | agpl-3.0 | 5,635 | 0.001952 | """
Code related to the handling of Proctored Exams in Studio
"""
import logging
import six
from django.conf import settings
from edx_proctoring.api import (
create_exam,
create_exam_review_policy,
get_all_exams_for_course,
get_exam_by_content_id,
remove_review_policy,
update_exam,
update... | uential',
},
settings={
'is_time_limited': True,
}
)
# filter out any potential dangling sequences
timed_exams = [
timed_exam
for timed_exam in _timed_exams
if is_item_in_course_tree(timed_exam)
]
# enumerate over list of sequences which ... | toring
for timed_exam in timed_exams:
msg = (
u'Found {location} as a timed-exam in course structure. Inspecting...'.format(
location=six.text_type(timed_exam.location)
)
)
log.info(msg)
exam_metadata = {
'exam_name': timed_exam.di... |
Roboartitsts/PiPaintingServer | findMixerWires.py | Python | mit | 384 | 0.018229 | from stepper import S | tepperBasic
import itertools
import time
import RPi.GPIO as GPIO
wires = [12,6,13,19]
for wire in wires:
GPIO.output(wire,GPIO.HIGH)
#time.sleep(30)
permutations = itertools.permutations(wires)
for perm in permutations:
print("Testing wires {}".format(perm))
mixerMotor = StepperBasic(*perm)
mixer... | leep(5)
|
sehlen/modforms-db | wmf/web_modform_space_computing.py | Python | gpl-3.0 | 18,193 | 0.00863 | # -*- coding: utf-8 -*-
#*****************************************************************************
# Copyright (C) 2010 Fredrik Strömberg <fredrik314@gmail.com>,
# Stephan Ehlen <>
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distributed in the hope that it will be us... | e:
self._newform_factors = self._get_newform_factors()
return self._newform_factors
def character_orbit_rep(self,k=None):
r"""
Returns canonical representative | of the Galois orbit nr. k acting on the ambient space of self.
"""
if self._character_orbit_rep is None:
x = self.character().character().galois_orbit()[0]
self._character_orbit_rep = WebChar(x.modulus(),x.number())
return self._character_orbit_rep
## Dat... |
sserrot/champion_relationships | venv/Lib/site-packages/jedi/settings.py | Python | mit | 3,527 | 0.000567 | """
This module contains variables with global |jedi| settings. To change the
behavior of |jedi|, change the variables defined in :mod:`jedi.settings`.
Plugins should expose an interface so that the user can adjust the
configuration.
Example usage::
from jedi import settings
settings.case_insensitive_comple... | tc. on arrays: [], {}, () as well as list/set calls.
"""
dynamic_params = T | rue
"""
A dynamic param completion, finds the callees of the function, which define
the params of a function.
"""
dynamic_params_for_other_modules = True
"""
Do the same for other modules.
"""
dynamic_flow_information = True
"""
Check for `isinstance` and other information to infer a type.
"""
auto_import_modules = ... |
seppi91/priceScheduler | config/settings/local.py | Python | mit | 2,241 | 0.000446 | # -*- coding: utf-8 -*-
"""
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
"""
import socket
import os
from .base import * # noqa
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool... | r.middleware.DebugToolbarMiddleware', ]
INSTALLED_ | APPS += ['debug_toolbar', ]
INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ]
# tricks to have debug toolbar when developing with docker
if os.environ.get('USE_DOCKER') == 'yes':
ip = socket.gethostbyname(socket.gethostname())
INTERNAL_IPS += [ip[:-1] + '1']
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'... |
maurelio79/pyConnection_Manager | setup.py | Python | gpl-3.0 | 1,662 | 0.00361 | #!/usr/bin/env python
import sys, shutil
try:
from gi.repository import Gtk, Gdk, Vte, GLib, Pango, GConf, GdkPixbuf
import json, os, getpass
from pycm.pycm_globals import *
except ImportError as e:
print "Error during importing of necessaries modules.\nError is '%s'" % e
sys.exit()
python_path =... | int "You need to be root to install pyConnection Manager"
sys.exit()
try:
remove_old()
except OSError, IOError:
print "ERROR removing old stuff"
sys.exit()
try:
create_new()
except OSError, IOError:
print "ERROR installing pyConnection Manager"
s... | if os.path.exists(GLADE_DIR):
shutil.rmtree(GLADE_DIR)
if os.path.exists(IMAGE_DIR):
shutil.rmtree(IMAGE_DIR)
if os.path.exists(bin_exe):
os.remove(bin_exe)
if os.path.exists(launcher):
os.remove(launcher)
def create_new():
shutil.copytree('pycm', module_path)
... |
eduNEXT/edx-platform | openedx/core/djangoapps/django_comment_common/migrations/0003_enable_forums.py | Python | agpl-3.0 | 849 | 0.003534 | from django.db import migrations, models
def add_default_enable(apps, schema_editor):
ForumsCo | nfig = apps.get_model("django_comment_common", "ForumsConfig")
settings_count = ForumsConfig.objects.count()
if settings_count == 0:
# By default we want the comment client enabled, but this is *not* enabling
# discussions themselves by default, as in showing | the Disucussions tab, or
# inline discussions, etc. It just allows the underlying service client to work.
settings = ForumsConfig(enabled=True)
settings.save()
def reverse_noop(apps, schema_editor):
return
class Migration(migrations.Migration):
dependencies = [
('django_co... |
NSAmelchev/ignite | modules/ducktests/tests/ignitetest/tests/__init__.py | Python | apache-2.0 | 2,355 | 0.000849 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | prefix = digest + '@'
return prefix + args if with_args else prefix
def patched_test_name(self):
"""
Monkey patched test_name property function.
"""
name_components = [self.module_name,
self.cls_name,
self.function_name,
... |
def patched_results_dir(test_context, test_index):
"""
Monkey patch results_dir.
"""
results_dir = test_context.session_context.results_dir
if test_context.cls is not None:
results_dir = os.path.join(results_dir, test_context.cls.__name__)
if test_context.function is not None:
... |
nudles/incubator-singa | examples/cnn/autograd/mnist_cnn.py | Python | apache-2.0 | 10,259 | 0.000682 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | spars=0,
topK=False,
| corr=True):
# Define the hypermeters good for the mnist_cnn
max_epoch = 10
batch_size = 64
sgd = opt.SGD(lr=0.005, momentum=0.9, weight_decay=1e-5)
# Prepare training and valadiation data
train_x, train_y, test_x, test_y = load_dataset()
IMG_SIZE = 28
num_classes = 10
train_... |
catapult-project/catapult | third_party/gsutil/third_party/apitools/apitools/base/protorpclite/messages.py | Python | bsd-3-clause | 67,559 | 0 | #!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | not in _POST_INIT_ATTRIBUTE_NAMES:
raise AttributeError('May not change values: %s' % name)
else:
type.__setattr__(cls, name, value)
de | f __delattr__(cls, name):
"""Overridden so that cannot delete varaibles on definition classes."""
raise TypeError('May not delete attributes on definition class')
def definition_name(cls):
"""Helper method for creating definition name.
Names will be generated to include the classes... |
sigbus/personal-file-sharing-center | web/net.py | Python | gpl-2.0 | 6,202 | 0.007578 | """
Network Utilities
(from web.py)
"""
__all__ = [
"validipaddr", "validip6addr", "validipport", "validip", "validaddr",
"urlquote",
"httpdate", "parsehttpdate",
"htmlquote", "htmlunquote", "websafe",
]
import urllib, time
try: import datetime
except ImportError: pass
import re
import socket
def validip6ad... | turn (match.group(1),port) |
else:
if validip6addr(ip): return (ip,port)
#end ipv6 code
ip = ip.split(":", 1)
if len(ip) == 1:
if not ip[0]:
pass
elif validipaddr(ip[0]):
addr = ip[0]
elif validipport(ip[0]):
port = int(ip[0])
else:
raise Valu... |
samabhi/pstHealth | venv/lib/python2.7/site-packages/gunicorn/app/djangoapp.py | Python | mit | 3,881 | 0.001804 | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
from gunicorn.app.base import Application
from gunicorn import util
def find_settings_module(path):
path = os.path.abspath(path)
project_path = None
settings... | th, settings_name = find_settings_module(
os.path.abspath(args[0]))
if not project_path:
raise RuntimeError("django project not found")
pythonpath, project_name = os.path.split(project_path)
self.cfg.set("django_settings", "%s... | ath", pythonpath)
def load(self):
# set settings
make_default_env(self.cfg)
# load wsgi application and return it.
mod = util.import_module("gunicorn.app.django_wsgi")
return mod.make_wsgi_application()
class DjangoApplicationCommand(Application):
def __init__(self,... |
wjlei1990/pytomo3d | pytomo3d/adjoint/__init__.py | Python | lgpl-3.0 | 573 | 0 | #!/usr/bin/env python
# -*- cod | ing: utf-8 -*-
"""
:copyright:
Wenjie Lei (lei@princeton.edu), 2016
:license:
GNU General Public License, Version 3
(http://www.gnu.org/copyleft/gpl.html)
"""
from __future__ import (absolute_import, division, print_function) # NOQA
from .adjoint_source import calculate_adjsrc_on_stream # NO... | te_and_process_adjsrc_on_stream # NOQA
from .adjoint_source import calculate_adjsrc_on_trace # NOQA
from .adjoint_source import measure_adjoint_on_stream # NOQA
|
knolza/gamblr | share/qt/extract_strings_qt.py | Python | mit | 2,044 | 0.003914 | #!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess | import Popen, PIPE
import glob
import operator
import os
OUT_CPP="src/qt/gamblrstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Return a list of (msgid,msgs | tr) tuples.
"""
messages = []
msgid = []
msgstr = []
in_msgid = False
in_msgstr = False
for line in text.split('\n'):
line = line.rstrip('\r')
if line.startswith('msgid '):
if in_msgstr:
messages.append((msgid, msgstr))
in_msgstr =... |
JasonHanG/tensor-gallery | basic-operation/basic_op.py | Python | apache-2.0 | 1,589 | 0 | # -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
x = tf.add(a, b)
with tf.Session() as sess:
writer = tf.summary.FileWriter('./graphs', sess.graph)
print(sess.run(x))
writer.close()
a = tf.constant([2, 2], name='a')
b = tf.constant([[0, 1], [2, 3]], name... | as_graph_def())
with tf.Session() as sess:
y = sess.run(y)
with tf.Session() as sess:
print(sess.run(tf.linspace(10.0, 13.0, 4)))
print(sess.run(tf.range(5)))
for i in np.arange(5):
print(i)
samples = tf.multinomial(tf.constant([[1., 3., 1]]), 5)
with tf.Session() as sess:
for _ in range(... | tf.zeros_like(t_1)
t_2 = [[True, False, False],
[False, False, True],
[False, True, False]]
x = tf.zeros_like(t_2)
y = tf.ones_like(t_2)
with tf.Session() as sess:
print(sess.run([x, y]))
with tf.variable_scope('meh') as scope:
a = tf.get_variable('a', [10])
b = tf.get_variable('b', [100])
w... |
ElDeveloper/american-gut-web | amgut/handlers/sample_overview.py | Python | bsd-3-clause | 3,991 | 0 | import os
import json
from tornado.web import authenticated
import requests
from amgut.lib.config_manager import AMGUT_CONFIG
from amgut.connections import ag_data
from amgut.handlers.base_handlers import BaseHandler
from amgut import media_locale
def _format_data_path(base, dir, barcode, ext):
filepath = os.pa... | n is No | ne:
sample_origin = sample_data['environment_sampled']
notes = sample_data['notes']
if notes is None:
notes = ''
self.render('sample_overview.html', skid=self.current_user,
barcode_pdf=web_barcode_pdf, barcode_txt=web_barcode_txt,
... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_developer_tools/profile_fibonacci_raw.py | Python | apache-2.0 | 367 | 0.002725 | import profile
def fib(n):
# from literateprograms.org
# http://bit.ly/hlOQ5m
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
def fib_seq(n):
seq = []
| if n > 0:
seq.extend(fib_seq(n - 1))
seq.append(f | ib(n))
return seq
profile.run('print(fib_seq(20)); print()')
|
BFriedland/systorian | systorian/metrics/models.py | Python | mit | 425 | 0 | f | rom __future__ import unicode_literals
from django.db import models
from django.contrib.postgres.fields import JSONField
class Entry(models.Model):
created = models.DateTimeField(auto_now_add=True, editable=False)
command = models.CharField(max_length=255)
data = JSONField()
class Meta:
orde... | lf.created)
|
sudeep-melekar/google-pthon-excercises | sudicustom/vowel.py | Python | apache-2.0 | 193 | 0.051813 | vowels = ['a','e','i','o','u']
s = 'sudeep'
count = 0
for i in s:
for q in vowels:
| if s[i] == vowels[q]:
print 'vowel found'
count = count + 1
print "number of vowels:",str(count) | |
eharney/nova | nova/conductor/rpcapi.py | Python | apache-2.0 | 21,580 | 0.000232 | # Copyright 2013 IBM Corp.
# Copyright 2013 Red Hat, 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 r... | upgrade_levels')
class ConductorAPI(object):
"""Client side of the conductor RPC API
API version history:
1.0 - Initial version.
| 1.1 - Added migration_update
1.2 - Added instance_get_by_uuid and instance_get_all_by_host
1.3 - Added aggregate_host_add and aggregate_host_delete
1.4 - Added migration_get
1.5 - Added bw_usage_update
1.6 - Added get_backdoor_port()
1.7 - Added aggregate_get_by_host, aggregate_metadata_add,... |
Code4SA/pmg-cms-2 | migrations/versions/3d723944025f_adding_email_templates.py | Python | apache-2.0 | 1,337 | 0.012715 | """Adding Email Templates
Revision ID: 3d723944025f
Revises: 148ca74a6d3
Create Date: 2015-01-23 12:28:20.581924
"""
# revision identifiers, used by Alembic.
revision = '3d723944025f'
down_revision = '148ca74a6d3'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():... | lable=False),
sa.Column('description', sa.String(length=1024), nullable=True),
sa.Column('subject', sa.String(length=100), nullable=True),
sa.Column('body', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text(u'now()'), nullable=False),
sa.Column('up... | )
op.create_index(u'ix_email_template_created_at', 'email_template', ['created_at'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index(u'ix_email_template_created_at', table_name='email_template')
op.drop_table('e... |
mrhmouse/xcolors | tests/test_regex.py | Python | gpl-3.0 | 1,647 | 0.001214 | import unittest
from xcolor.xparser import Xparser
class TestXcolorRegex(unittest.TestCase):
# expected output for the tested patterns
expected = dict(name='color5', value='aabbcc')
def test_comments(self):
line = ";*color5: rgb:aa/bb/cc"
self.assertFalse(Xparser.valid(line))
line... | t*color5: rgb:aa/bb/cc"
self.assertTrue(Xparser.valid(line))
output = Xparser.rgb(line)
self.assertEqual(output, self.expected)
def test_urxvt_hex(self):
line = "URxvt*color5: #aabbcc"
self.assertTrue(Xparser.valid(line))
output = Xparser.hex(line)
self.asser... | Xparser.rgb(line)
self.assertEqual(output, self.expected)
def test_urxvt_dot_hex(self):
line = "URxvt.color5: #aabbcc"
self.assertTrue(Xparser.valid(line))
output = Xparser.hex(line)
self.assertEqual(output, self.expected)
if __name__ == "__main__":
unittest.main()
|
yosshy/nova | nova/api/openstack/compute/certificates.py | Python | apache-2.0 | 3,279 | 0.000305 | # Copyright (c) 2012 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 ... | FileNotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
return {'certificate': _translate_certificate_view(cert)}
| # NOTE(gmann): Here should be 201 instead of 200 by v2.1
# +microversions because the resource certificate has been created
# completely when returning a response.
@extensions.expected_errors(())
def create(self, req, body=None):
"""Create a certificate."""
context = req.environ['nova.c... |
DEK11/SP500 | svm.py | Python | apache-2.0 | 3,588 | 0.006968 | import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, preprocessing
import pandas as pd
from matplotlib import style
import statistics
style.use("ggplot")
FEATURES = ['DE Ratio',
'Trailing P/E',
'Price/Sales',
'Price/Book',
'Profit Margin',
... | processing.scale(X)
# Z = data_df["Ticker"].values.tolist()
# | invest_list = []
# for i in range(len(X)):
# p = clf.predict(X[i])[0]
# if p == 1:
# print(Z[i])
# invest_list.append(Z[i])
# print(len(invest_list))
# print(invest_list)
Analysis()
|
dhongu/l10n-romania | l10n_ro_invoice_report/__manifest__.py | Python | agpl-3.0 | 887 | 0 | # © 2008-2020 Dorin Hongu <dhongu(@)gmail(.)com
# See READ | ME.rst file on addons root folder for license details
{
"name": "Romania - Invoice Report ",
"summary": "Localizare Terrabit",
"version": "14.0.3.0.3",
"author": "Dori | n Hongu," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-romania",
"license": "AGPL-3",
"category": "Generic Modules",
"depends": [
"base",
"account",
"l10n_ro_config",
"purchase",
# "deltatech_watermark"
],
"data": [
"... |
seanbell/opensurfaces | server/photos/management/commands/add_special.py | Python | mit | 1,191 | 0.00084 | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from photos.models import PhotoSceneCategory
from photos.add import add_photo
#from licenses.models import License
class Command(BaseCommand):
args = '<flickr_dir>'
help = ' | Adds photos from flickr'
def handle(self, *args, **options):
admin_user = User.objects.get_or_create(
username='admin')[0].get_profile()
print 'user:', admin_user
name = 'kitchen'
scene_category, _ = PhotoSceneCategory.objects \
.get_or_create(name=name)
... | print 'No path'
return
try:
photo = add_photo(
path=path,
user=admin_user,
scene_category=scene_category,
flickr_user=None,
flickr_id=None,
license=None,
exif='',
... |
pndurette/viatools | viatools/__init__.py | Python | mit | 320 | 0.009375 | fr | om .version import __version__
import os
# Load configuration
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open(os.path.join(os.path.dirname(__file__), "conf/via.conf")))
# Logging
import logging.config
logging.config.fileConfig | (os.path.join(os.path.dirname(__file__),'conf/logging.conf'))
|
tundebabzy/frappe | frappe/email/smtp.py | Python | mit | 7,732 | 0.025996 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
from six import reraise as raise_
import frappe
import smtplib
import email.utils
import _socket, sys
from frappe import _
from frappe.utils import cint, parse_addr
def send(emai... | update({
"smtp_server": frappe.conf.get("mail_server"),
"smtp_port": frappe.conf.get("mail_port"),
# legacy: use_ssl was used in site_config instead of use_tls, but meant the same thing
"use_tls": cint(frappe.conf.get("use_tls") or 0) or cint(frappe.conf.get("use_ssl") or 0),
"login_id": frappe.conf.get... | com',
"password": frappe.conf.get("mail_password"),
"always_use_account_email_id_as_sender": frappe.conf.get("always_use_account_email_id_as_sender", 0)
})
email_account.from_site_config = True
email_account.name = frappe.conf.get("email_sender_name") or "Frappe"
if not email_account and not raise_excepti... |
red-green/broscanner | file_scanning.py | Python | gpl-2.0 | 1,354 | 0.016248 | ## simple file type detection.
## if i had unlimited api access, i would send every single md5 to something like VirusTotal
forbidden_ty | pes = ['text/x-bash', 'text/scriptlet', 'application/x-opc+zip', 'application/com', 'application/x-msmetafile', 'application/x-shellscript', 'text/x-sh', 'text/x-csh', 'application/x-com', 'application/x-helpfile', 'application/hta', 'application/x-bat', 'application/x | -php', 'application/x-winexe', 'application/x-msdownload', 'text/x-javascript', 'application/x-msdos-program', 'application/bat', 'application/x-winhelp', 'application/vnd.ms-powerpoint', 'text/x-perl', 'application/x-javascript', 'application/x-ms-shortcut', 'application/vnd.msexcel', 'application/x-msdos-windows', 't... |
jdal/Argus-cape | capeTests/suicide.py | Python | mit | 349 | 0 | #!/usr/bin/env python
import os
import time
import sys
try:
w = open("/dev/argus_ups", "w", 0)
except Exception, e:
print "Failed to open watchdog"
rais | e
pid = os.fork()
if pid == 0:
print "Petting watchdog quickly to force suicide shutdown"
while 1:
w.write("\ | n")
time.sleep(0.01)
print "Process ID:", pid
|
jbogarin/ciscosparkapi | examples/pyramidSparkBot/pyramidSparkBot/__init__.py | Python | mit | 254 | 0.003937 | """Main entry point
"""
from pyramid.config import Configurator
def main(global_config, **settings):
config = Configurator(settings=settings)
config.include(" | cornice")
config.scan("pyramidSparkBot.views")
return config.make | _wsgi_app()
|
jmathai/elodie | elodie/tests/helper.py | Python | apache-2.0 | 5,170 | 0.010251 | from __future__ import division
from __future__ import unicode_literals
from builtins import range
from past.utils import old_div
import hashlib
import os
import random
import string
import tempfile
import re
import time
import urllib
from datetime import datetime
from datetime import timedelta
from elodie.compatabil... | )
os.makedirs(folder)
for x in range(0, number_of_files):
ext = 'jpg' if x % 2 == 0 else 'txt'
fname = '%s/%s.%s' % (folder, x, ext)
with open(fname, 'a'):
os.utime(fname, None)
if include_invalid:
fname = '%s/%s' % (folder, 'invalid.invalid')
| with open(fname, 'a'):
os.utime(fname, None)
return folder
def random_string(length, format=None):
format_choice = string.ascii_uppercase + string.digits
if format == 'int':
format_choice = string.digits
elif format == 'str':
format_choice = string.asci_uppercase
... |
hunch/hunch-gift-app | django/conf/locale/ta/formats.py | Python | mit | 459 | 0.021786 | # -*- encoding: utf-8 -*-
# This file is distributed | under the same license as the Django package.
#
DATE_FORMAT = 'j F, Y'
TIME_FORMAT = 'g:i:s A'
# DATETIME_FORMAT =
# YEAR_MONTH_FORMAT =
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j M, Y'
# SHORT_DATETIME_FORMAT = |
# FIRST_DAY_OF_WEEK =
# DATE_INPUT_FORMATS =
# TIME_INPUT_FORMATS =
# DATETIME_INPUT_FORMATS =
# DECIMAL_SEPARATOR =
# THOUSAND_SEPARATOR =
# NUMBER_GROUPING =
|
dontnod/weblate | weblate/auth/utils.py | Python | gpl-3.0 | 3,510 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2019 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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, eith... | instance.roles.set(
role_model.objects.filter(name__in=roles),
clear=True
)
if update:
for key, value in defaults.items():
setattr(instance, key, value)
instance.save()
def create_anonymous(model, group_model, update=True):
... | nymous',
'email': 'noreply@weblate.org',
'is_active': False,
'password': make_password(None),
}
)
if user.is_active:
raise ValueError(
'Anonymous user ({}) already exists and enabled, '
'please change ANONYMOUS_USER_NAME setting.'.forma... |
koblas/modelplus | modelplus/__init__.py | Python | mit | 552 | 0.003623 | __all__ = ['setup', 'get_db']
from modelplus.store import redis_db, sqlite_db
store = None
def s | etup(params):
"""
'redis' : { host, port, db }
'sqlite' : { file }
'mysql' : { host, port, db }
'riak' : { host, port, bucket }
'mongodb' : { host, port, bucket }
"""
global store
kwargs = param | s.get('redis')
if kwargs:
store = redis_db.setup(**kwargs)
kwargs = params.get('sqlite')
if kwargs:
store = sqlite_db.setup(**kwargs)
def get_db():
return store
|
lixun910/pysal | pysal/explore/giddy/components.py | Python | bsd-3-clause | 4,697 | 0.000213 | """
Checking for connected components in a graph.
"""
__author__ = "Sergio J. Rey <srey@asu.edu>"
__all__ = ["check_contiguity"]
from operator import lt
def is_component(w, ids):
"""Check if the set of ids form a single connected component
Parameters
----------
w : spatial weights boject
id... | connected = set(connected)
for node in connected:
if node in nodes:
nodes.remove(node)
subgraph = Graph()
| subgraph.nodes = connected
subgraph.no_link = self.no_link
for s in subgraph.nodes:
for k, v in list(self.edges.get(s, {}).items()):
if k in subgraph.nodes:
subgraph.edges.setdefault(s, {}).update({k: v})
... |
peterhil/prism | prism/test/grep_test.py | Python | bsd-3-clause | 738 | 0.005427 | #!/usr/bin/env python -u
# encoding: utf-8
#
# Copyright (c) 2012, Peter Hillerström <peter.hillerstrom@gmail.com>
# All rights reserved. This software is licensed under 3-clause BSD license.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code. |
import pytest
from prism.grep import pattern, search
def log_lines():
return [
"[Sun Apr 08 12:51:52 2012] [notice] Digest: done",
"[Mon Jul 11 09:26:13 2011] Error: [client ::1] File does not exist: /Library/WebServer/Documents/favicon.ico",
]
def test_search():
for line in log_lines():... | ch(line), "Regexp pattern '{0}' didn't match line '{1}'".format(pattern, line)
|
miraheze/puppet | modules/monitoring/files/bot/ircecho.py | Python | gpl-3.0 | 9,009 | 0.000999 | #!/usr/bin/python3 -u
# vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab textwidth=80 smarttab
#
# stdin -> IRC echo bot, with optional file input support.
#
# Written by Kate Turner <kate.turner@gmail.com>, source is in the public
# domain.
# Modified by Ryan Lane <rlane@wikimedia.org> for watching and taking i... | outputs = [s[0 + i:450 + i] for i in range(0, len(s), 450)]
for out in outputs:
bot.connection.privmsg(chans, out)
except (irc.client.ServerNotConnectedError, irc.client.MessageTooLong,
UnicodeDecodeError) as e:
print(('Error w... | rint('Reopening file: ' + event.pathname)
reader.files[event.pathname] = open(event.pathname)
except IOError:
print('Failed to reopen file: ' + event.pathname)
pass
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser(conflict_handler='resolve... |
MattParr/python-atws | atws/helpers.py | Python | mit | 9,052 | 0.009943 | '''
Created on 27 Sep 2015
@author: matt
'''
from __future__ import absolute_import
from future.utils import iteritems
import logging
import math
from suds import WebFault
from .constants import (AUTOTASK_API_QUERY_RESULT_LIMIT,
AUTOTASK_API_TIMEZONE,
LOCAL_TIMEZONE,
... | udf = get_udf(wrapper,entity, name, value)
udf.Value = value
def del_user_defined_fields_attribute(entity):
if hasattr(entity,'UserDefinedFields'):
delattr(entity,'UserDefinedFields')
def can_multiupdate_entities(entities):
Tru | e
def entities_have_userdefined_fields(entities):
for entity in entities:
if has_udfs(entity):
return True
return False
def entities_have_userdefined_fields_with_values(entities):
for entity in entities:
if has_udfs(entity):
for udf in get_udfs(entity):
... |
Openandgit/2014cpb_final_project- | std/b40323208.py | Python | gpl-3.0 | 9,435 | 0.006008 | #@+leo-ver=5-thin
#@+node:lee.20141223114246.40: * @file example2.py
#@@language python
#@@tabwidth -4
import cherrypy
import random
from std.asciisymbol import asciiImage
#@+others
#@+node:lee.20141223114246.41: ** class Application
class Application(object):
#@+others
#@+node:lee.20141223114246.42: *3* def i... | <div class="one-half column">
<div class="headline">
About Me
</div>
<div class="photo">
<img src="{photo_url:s}" alt="photo">
</div>
<div class="meta">
<ul>
<li>Name: {name:s}</li>
<li>ID NO. : {ID:s}</li>
<li>C... | line">
Self Evaluation
</div>
<div>
<table class="u-full-width">
<thead>
<tr>
<th>Project Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{evaluation:s}
</tbody... |
kpn-digital/py-timeexecution | time_execution/decorator.py | Python | apache-2.0 | 2,501 | 0.0008 | """
Time Execution decorator
"""
import socket
import time
from fqn_decorators import Decorator
from fqn_decorators.asynchronous import AsyncDecorator
from pkgsettings import Settings
SHORT_HOSTNAME = socket.gethostname()
settings = Settings()
settings.configure(backends=[], hooks=[], duration_field="value")
def w... |
metric = {"name": self.fqn, settings.duration_field: duration, "hostname": SHORT_HOSTNAME}
origin = getattr(settings, "origin", None)
if origin:
metric["origin"] = origin
hooks = self.params.get("extra_hooks", [])
disable_default_hooks = self.params.get("disable_de... | hooks = settings.hooks + hooks
# Apply the registered hooks, and collect the metadata they might
# return to be stored with the metrics
metadata = _apply_hooks(
hooks=hooks,
response=self.result,
exception=self.get_exception(),
metric=m... |
opennode/nodeconductor-assembly-waldur | src/waldur_openstack/openstack_tenant/tests/test_flavor_change.py | Python | mit | 11,479 | 0.002701 | from ddt import data, ddt
from rest_framework import status, test
from waldur_core.structure.models import ProjectRole
from waldur_openstack.openstack.models import Tenant
from waldur_openstack.openstack_tenant.models import Instance
from . import factories, fixtures
@ddt
class FlavorChangeInstanceTestCase(test.API... | assertEqual(
response.status_code, status.HTTP_400_BAD_REQUEST, response.data
)
# check for vcpu
many_c | ore_flavor = factories.FlavorFactory(
settings=settings,
cores=quotas_holder.quotas.get(name='vcpu').limit + self.instance.cores + 1,
)
data = {'flavor': factories.FlavorFactory.get_url(many_core_flavor)}
response = self.client.post(
factories.InstanceFactory.... |
kultprok/pythonista-drafts-recipes | postal_codes/city_by_postalcode.py | Python | mit | 1,463 | 0.031442 | # -*- coding: utf-8 -*-
from console import alert
from json import loads
from sys import argv, exit
from urllib import urlopen, quote
import webbrowser
def error_dialog(title, message):
'''
a diaolog box for error messages.
'''
try:
alert(title, message)
except KeyboardInterrupt:
pass
webbrowser.open('drafts... | country_= [item.strip() for item in data.split(',')]
except Exception as err:
error_dialog(str(err.__class__), err.message)
try:
response = urlopen(api_url_base.format(country=country_, postcode=postcode_))
except IOError:
error_dialog('Connection Error', 'Unable to perform request.')
if response.getcode() ... | a = handle_data(response.read())
webbrowser.open('drafts://x-callback-url/create?text={0}'.format(quote(postcode_data)))
else:
error_dialog('Error', 'Status code: {0} - Message: {1}'.format(response.getcode(), response.read()))
if __name__ == '__main__':
get_by_postalcode(argv[1]) |
zwChan/VATEC | ~/eb-virt/Lib/site-packages/pymysql/constants/FLAG.py | Python | apache-2.0 | 214 | 0 | NOT_NULL = 1
PRI_KEY = 2
UNIQUE_KEY = 4
MULTIPLE_KE | Y = 8
BLOB = 16
UNSIGNED = 32
ZEROFILL = 64
BINARY = 128
ENUM = 256
AUTO_INCREMENT = 512
TIMESTAMP | = 1024
SET = 2048
PART_KEY = 16384
GROUP = 32767
UNIQUE = 65536
|
JonatanEnes/metrics-to-time-series | src/java_hadoop_snitch/read_java_maps.py | Python | gpl-3.0 | 394 | 0.002538 | import pickle
process_files = ["NameNode", "SecondaryNameNode", "DataNode", "ResourceManager", "NodeManager", "YarnChild",
"MRAppMaster"]
for f in process_files:
try:
with open('../pipelines/java_mappings/' + f + '. | txt', 'rb') as fp:
itemlist = pickle.load( | fp)
print(f + "->" + str([int(x) for x in itemlist]))
except IOError:
pass
|
ctrlaltdel/neutrinator | vendor/openstack/tests/functional/cloud/test_identity.py | Python | gpl-3.0 | 10,600 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | le_name, user=user['id'], project='demo', wait=True))
assignments = self.operator_cloud.list_role_assignments({
'role': role['id'],
'user': user['id'],
'project': self.operator_cloud.get_project('demo')['id']
})
self.assertIsInstance(assignments, list)
... | ):
self.skipTest("Identity service does not support group")
role_name = self.role_prefix + '_grant_group_project'
role = self.operator_cloud.create_role(role_name)
group_name = self.group_prefix + '_group_project'
group = self.operator_cloud.create_group(
name=gro... |
hurricup/intellij-community | python/testData/inspections/PyTypeCheckerInspection/FunctionReturnType.py | Python | apache-2.0 | 1,000 | 0.045 | from typing import Optional, List
def a(x):
# type: (List[int]) -> List[str]
return <warning descr="Expected type 'List[str]', got 'List[List[int]]' instead">[x]</warning>
def b(x):
# type: (int) -> List[str]
return <warning descr="Expected type 'List[str]', got 'List[int]' instead">[1,2]</warning>
d... | () -> Optional[str]
x = int(input())
if x > 0:
return <warning descr="Expected type 'Optional[str]', got 'int' instead">42</warning>
elif x == 0:
return 'abc'
else:
return
def g(x):
# type: (Any) -> int
if x:
return <warning descr="Expected type 'int', got 'str'... | pected type 'int', got 'dict' instead">{}</warning> |
Learningtribes/edx-platform | cms/djangoapps/contentstore/courseware_index.py | Python | agpl-3.0 | 28,024 | 0.00314 | """ Code to allow module store to interface with courseware index """
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
from datetime import timedelta
import logging
import re
from six import add_metaclass
from django.conf import settings
from django.utils.translation import ugettext_lazy,... | used in order to build a query to remove those items not in this
# list - those are ready to be destroyed
indexed_items = set()
# items_index is a list of all the items index dictionaries.
# it is used to collect all indexes and index them using bulk API,
# instead of per item i... | m):
"""
Gets the version agnostic item location
"""
return item.location.version_agnostic().replace(branch=None)
def prepare_item_index(item, skip_index=False, groups_usage_info=None):
"""
Add this item to the items_index and indexed_items... |
eharney/nova | nova/api/openstack/compute/views/limits.py | Python | apache-2.0 | 3,639 | 0 | # Copyright 2010-2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except i | n compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licen | ses/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 limitat... |
jswetzen/sie-parse | petra_output.py | Python | gpl-3.0 | 6,907 | 0.002606 | #!/usr/bin/env python3
"""Output a CSV file that can be imported to Petra"""
import os
import sys
import calendar
import csv
from csv_dict import CSVDict, CSVKeyMissing
def split_csv(table_file='Tabell.csv'):
"" | "Split account, cost center and project into three tables"""
account = []
cost_center = []
project = []
with open(table_file, newline='') as tablefile:
tablereader = csv.reader(tablefile, delimiter=';')
for row in tablereader:
if row[0] != '' and row[1] != '':
... | :
project.append([row[6], row[7]])
with open('Konto.csv', 'w', newline='') as accountfile:
accountwriter = csv.writer(accountfile, delimiter=';')
for row in account:
accountwriter.writerow(row)
with open('Costcenter.csv', 'w', newline='') as ccfile:
ccwriter =... |
dana-i2cat/felix | expedient/src/python/expedient/common/timer/tests.py | Python | apache-2.0 | 4,609 | 0.005858 | '''
Created on Feb 16, 2011
@author: jnaous
'''
from django.test import TestCase
from datetime import datetime
from expedient.common.timer.models import Job
from time import sleep
from expedient.common.timer.exceptions import JobAlreadyScheduled,\
JobNotScheduled
from django.core.management import call_command
imp... | 5_call)
Job.objects.schedule_post_syncdb(4, job6_call)
class Tests(TestCase):
def te | st_methods(self):
Job.objects.exclude(
callable_name__regex=r'expedient.common.timer.tests.job.?_call$',
).delete()
# create jobs
Job.objects.schedule(4, job1_call)
Job.objects.schedule(4, job2_call)
Job.objects.schedule(4, job3_call)
Job.objects.sched... |
DreamN/Pic-storage | app.py | Python | mit | 1,843 | 0.004883 | from flask import Flask, render_template, send_from_directory, request
from settings import getDatabaseString
import os
import time
import psycopg2
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
def genFilename(s):
arr_s = s.split('.')
t = time.strftime("%d-%m-%Yh%Hm%Ms%S", time.localtime())
... | e)
if file:
#Save file to server
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
file_url = request.url + 'uploads/' + file.filename
#Insert file url into | the database
conn = psycopg2.connect(getDatabaseString())
cur = conn.cursor()
query = "INSERT INTO picture (pic) VALUES ('{}')"
query = query.format(file.filename)
print query
cur.execute(query)
conn.commit()
#Render on the page
return 'Your pic pa... |
Godley/Music-Library | implementation/primaries/GUI/tests/testHelpers.py | Python | gpl-2.0 | 3,217 | 0.001554 | import unittest
import sys
import os
from implementation.primaries.GUI import helpers
class testStylesheet(unittest.TestCase):
def setUp(self):
self.theme_folder = os.path.join(helpers.get_base_dir(True), 'themes')
def testCleanPath(self):
path = 'themes/item.png'
if sys.platform == ... | expected_path = os.path.join(
helpers.get_base_dir(True), 'themes', "zoom-out.png")
| if sys.platform == 'win32':
expected = "background: url('" + \
expected_path + '\') center no-repeat;'
else:
expected = "background: url(" + \
expected_path + ') center no-repeat;'
cleaned_path = helpers.cleanPath(line)
self.assertEqua... |
martinhoefling/fretutils | lib/FRETUtilsTests/TransferMatrixTests.py | Python | bsd-3-clause | 12,953 | 0.013665 | '''
Created on 18.12.2012
@author: mhoefli
'''
from __future__ import division
import unittest
from FRETUtils.TransferMatrices import TransferMatrix, GlobalAVGKappaTransferMatrix, DistanceAVGKappaTransferMatrix, DistanceKappaTransferMatrix, genEffIndex, generateBinMid, modifyR0
from FRETUtils.Helpers import rToEff, ... | tm.generateMatrix()
self.assertEqual(tm.RRange[0], 5)
self.a | ssertEqual(tm.RRange[1], 6)
self.assertAlmostEqual(tm.getMatrix()[9][5], 1., delta = 0.01)
tmref = GlobalAVGKappaTransferMatrix( |
phillxnet/rockstor-core | src/rockstor/smart_manager/views/nfs_share_client_distrib.py | Python | gpl-3.0 | 1,051 | 0 | """
Copyright (c) 20 | 12-2020 RockStor, Inc. <http://rockstor.com>
This file is par | t of RockStor.
RockStor 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.
RockStor is distributed in the hope that it will be useful, but
WIT... |
ToonTownInfiniteRepo/ToontownInfinite | toontown/safezone/GSSafeZoneLoader.py | Python | mit | 4,633 | 0.004317 | from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from pandac.PandaModules import *
from toontown.hood import ZoneUtil
from toontown.launcher import DownloadForceAcknowledge
from toontown.safezone.SafeZoneLoader import SafeZoneLoader
from toontown.s... |
def startSmokeEffect(self):
if base.config.GetBool('want-crashedLeaderBoard-Smoke', 1):
leaderBoard = self.geom.find('**/*crashed*')
locator = leaderBoard.find('**/*locator_smoke*')
if locator != None:
self.smoke = CarSmoke(locator)
self.s... | 1):
if self.smoke != None:
self.smoke.stop()
self.smoke.destroy()
self.smoke = None
return
|
NMTHydro/Recharge | zobs/configuration/cli_configurer.py | Python | apache-2.0 | 1,828 | 0.000547 | # ===============================================================================
# Copyright 2016 ross
#
# 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 License.
# ==... |
damonchen/chan | chan/core/templates/config.py | Python | bsd-2-clause | 109 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
imp | ort os
P | ATH = os.path.dirname(os.path.abspath(__file__))
|
bird-house/pywps-proxy | twitcher/oauth2.py | Python | apache-2.0 | 10,573 | 0.001608 | # coding: utf-8
"""
twitcher.oauth2
---------------
This module implements the `OAuth2 <https://oauthlib.readthedocs.io/en/latest/oauth2/oauth2.html>`_
model to generate access tokens.
These tokens are used to access the compute services (*scope=compute*).
The compute services are accessed via the OWS proxy.
The impl... | The validation validates:
1) if t | he token is available
2) if the token has expired
3) if the scopes are available
"""
query = request.dbsession.query(models.Token)
tok = query.filter(models.Token.access_token == token).first()
if not tok:
return False
# validate expires
... |
KT26/PythonCourse | 1. Getting Started/11.py | Python | mit | 322 | 0.018634 | # Created by PyCharm Community | Edition
# User: Kaushik Talukdar
# Date: 22-03-2017
# Time: 03:52 PM
#python doesn't allow you to mix strings and numbers directly. numbers must be converted | to strings
age = 28
print("Greetings on your " + str(age) + "th birthday") |
opengeogroep/NLExtract | bag/src/bagextract.py | Python | gpl-3.0 | 8,349 | 0.003593 | __author__ = "Stefan de Konink"
__date__ = "$Jun 11, 2011 3:46:27 PM$"
"""
Naam: bagextract.py
Omschrijving: Universe starter voor de applicatie, console
Auteurs: Stefan de Konink (initial), Just van den Broecke
"""
import argparse # apt-get install python-argparse
import sys
import os
f... | )
if not ans:
return resp
if ans not in ['j', 'J', 'n', 'N']:
print('Geef j of n.')
continue
if ans == 'j' or ans == | 'J':
return True
if ans == 'n' or ans == 'N':
return False
# end of http://code.activestate.com/recipes/541096/ }}}
def main():
"""
Voorbeelden:
1. Initialiseer een database:
python bagextract.py -H localhost -d bag -U postgres -W postgres -c
... |
elba7r/system | erpnext/config/hr.py | Python | gpl-3.0 | 5,192 | 0.047573 | from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Employee and Attendance"),
"items": [
{
"type": "doctype",
"name": "Employee",
"description": _("Employee records."),
},
{
"type": "doctype",
"name": "Employee Attendance To... | : "Employment Type",
"description": _("Types of employment (permanent, contract, intern etc.).")
},
{
"type": "doctype",
"name": "Branch",
"description": _("Organization branch master.")
},
{
"type": "doctype",
"name": "Department",
"description": _("Organization unit ... | . CEO, Director etc.).")
},
{
"type": "doctype",
"name": "Daily Work Summary Settings"
},
]
},
{
"label": _("Reports"),
"icon": "fa fa-list",
"items": [
{
"type": "report",
"is_query_report": True,
"name": "Employee Leave Balance",
"doctype": "Leave Applicat... |
unt-libraries/django-controlled-vocabularies | controlled_vocabularies/migrations/0002_auto_20180924_1938.py | Python | bsd-3-clause | 3,376 | 0.003555 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-09-24 19:38
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('controlled_vocabularies', '0001_initial'),
]
opera... | mail'),
),
migrations.AlterField(
model_name='vocabulary',
name='name',
field=models.CharField(help_text=b'The name or key that uniquely identifies the vocabulary.', max_length=50, unique=True),
),
migrations.AlterField(
model_name='vocabul... | field=models.CharField(choices=[(b'name', b'name'), (b'label', b'label'), (b'order', b'order')], help_text=b'The preferred order for viewing the UNTL list of controlled vocabularies.', max_length=10),
),
]
|
kaspermunch/CoalhmmPipeline | CoalhmmPipeline/IngroupSplitter.py | Python | gpl-2.0 | 5,732 | 0.007153 | from MAF import MAF
class IngroupSplitter:
def __init__(self, ingroup, splitdist, junkchars='Nn'):
self.ingroup = ingroup
self.splitdist = splitdist
self.junkchars = junkchars
assert "-" not in self.junkchars
#return a list of mafs representing the old mafs that have split... | %s %i %i %s %i %s\n" % (maf.name(ind), maf.chromosome(ind), start, size, maf.strand(ind), maf.srcLength(ind), maf.data(ind)[i:])
gapcount = 0
tmpmaf = MAF(maf1)
res = []
# print "## 1 ##"
# print tmpmaf
for x in range(... | s.append(tmpmaf)
tmpmaf2 = MAF(maf2)
# print "## 2 ##"
# print tmpmaf2
for x in range(tmpmaf2.count()):
assert tmpmaf2.start(x) <= tmpmaf2.start(x), (tmpmaf2.start(x), tmpmaf2.end(x))
if(len(tmpmaf2.dat... |
urisimchoni/samba | python/samba/provision/kerberos.py | Python | gpl-3.0 | 2,601 | 0.000384 | # Unix SMB/CIFS implementation
#
# Backend code for provisioning a Samba AD server
#
# Copyright (c) 2015 Andreas Schneider <asn@samba.org>
#
# 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;... | B5_KDC_PROFILE' in os.environ:
return
# We are in selftest
if | 'SAMBA_SELFTEST' in os.environ and 'MITKRB5' in os.environ:
return
assert kdcconf is not None
assert domain is not None
domain = domain.upper()
assert realm is not None
realm = realm.upper()
f = open(kdcconf, 'w')
try:
f.write("[kdcdefaults]\n")
f.write("\tkdc_po... |
akiyamiyamoto/Tutorial | isrbs/src/python/circe2plot.py | Python | gpl-3.0 | 2,954 | 0.013879 | #!/bin/env python
# Basic example to call fortran subroutine, using cpython interface.
# See further comments below.
from ctypes import *
import math
import time
import ROOT
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Print beamstrahlung spectrum generat... | c_char_p, POINTER(c_double), POINTER(c_int), c_int, c_int ]
bslib.circe2_setseed_.argtypes = [ POINTER(c_int) ]
bslib.circe2_genbeam_.argtypes = [ POINTER(c_double) ]
# initialize circe2
lcirce2_file = len(circe2_file)
ldesign = len(design)
aroots = c_double(roots)
ierror = 0
aierro... | r.value != 0:
print "Error : failed to initialize circe2 file."
print " circe2_file="+circe2_file
print " design="+design
exit()
iseed = int(time.time())
aiseed = c_int(iseed)
bslib.circe2_setseed_( byref(aiseed) )
# ROOT initialize
tfile = ROOT.TFile(rootfile, "RECREAT... |
sherlockcoin/Electrum-NavCoin | lib/commands.py | Python | mit | 32,053 | 0.003806 | #!/usr/bin/env python
#
# Electrum - lightweight NavCoin client
# Copyright (C) 2011 thomasv@gitorious
#
# 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 witho... | urn a configuration variable. """
return self.config.get(key)
@command('')
def setconfig(self, key, value):
"""Set a configuration variable. 'value' may be a string or a Python expression."""
try:
value = ast | .literal_eval(value)
except:
pass
self.config.set_key(key, value)
return True
@command('')
def make_seed(self, nbits=128, entropy=1, language=None):
"""Create a seed"""
from mnemonic import Mnemonic
s = Mnemonic(language).make_seed(nbits, custom_entro... |
onyxfish/leather | tests/test_grid.py | Python | mit | 2,182 | 0 | #!/usr/bin/env python
import os
import leather
TEST_SVG = '.test.svg'
class TestGrid(leather.LeatherTestCase):
def setUp(self):
self.data1 = [
(0, 3),
(4, 5),
| (7, 9),
(8, 4)
]
self.data2 = [
(0, 4),
(1, 3),
(2, 5),
(5, 6),
(9, 10)
]
def tearDown(self):
if os.path.exists(TEST | _SVG):
os.remove(TEST_SVG)
def test_add_one(self):
chart1 = leather.Chart()
chart1.add_dots(self.data1)
chart2 = leather.Chart()
chart2.add_dots(self.data2)
grid = leather.Grid()
grid.add_one(chart1)
grid.add_one(chart2)
svg = self.rend... |
rhaps0dy/os-experiments | p1/RWNums.py | Python | bsd-3-clause | 516 | 0.021318 | #!/usr/bin/python3
import sys
if len(sys.argv)!=4:
print("Usage: | %s infile outfile num"%sys.argv[0])
sys.exit(0)
infile = open(sys.argv[1], "r")
outfile = open(sys.argv[2], "w")
num = float(sys.argv[3])
cont = True
while cont:
curnum = ""
c = infile.read(1)
while c!=" " and c!="":
curnum+=c
c = infile.read(1)
if c=="":
cont = False
try... | outnum)
except:
pass
infile.close()
outfile.close()
|
Debian/dak | daklib/upload.py | Python | gpl-2.0 | 20,230 | 0.001434 | # Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This pr... | ted, self.actual)
class InvalidFilenameException(UploadException):
def __init__(self, filename):
self.filename = filename
def __str__(self):
return "Invalid filename '{0}'.".format(self.filename)
class FileDoesNotExist(UploadException):
def __init__(self, filename):
self.filenam... | .format(self.filename)
class HashedFile:
"""file with checksums
"""
def __init__(self, filename, size, md5sum, sha1sum, sha256sum, section=None, priority=None, input_filename=None):
self.filename = filename
"""name of the file
@type: str
"""
if input_filename is N... |
posborne/mlcollection | mlcollection/lib/collaborativefiltering/pearson.py | Python | mit | 3,340 | 0.007784 | """Implementation of Pearson collaborative filtering algorithm"""
from math import sqrt, pow
from mlcollection.lib.collaborativefiltering.collaborativefilterbase import \
AbstractCollaborativeFilter
from operator import itemgetter
from scipy import stats, isnan
__author__ = 'Paul Osborne <osbpau@gmail.com>'
class... | where the keys are the items
and the values are ratings for the movie for the individual. The
higher the rating, the more likely it is that the individual may like
the movie.
"""
dataset = self.ranked_dataset
totals = {}
sim_sums = {}
ind_items = set(dat... | keys())
for other in (x for x in dataset if x != individual):
shared_items = ind_items & set(dataset[other].keys())
# get a measure of how similar individual and other are
if len(shared_items) == 0:
continue
x = [dataset[individual][i]... |
nowsword/ProjectEuler | p009.py | Python | gpl-3.0 | 424 | 0.007075 | import datetime
def main(num) | :
for a in range(1, num // 3):
for b in range(a + 1, num // 2 if num % 2 == 0 else num // 2 + 1):
c = num - a - b
if a ** 2 + b ** 2 == c ** 2:
return a * b * c
try:
para = int(input())
except:
para = 1000
beg = datetime.datetime.now()
ans = main(para)
end =... | g)
|
Kami/libcloud | libcloud/test/compute/test_kili.py | Python | apache-2.0 | 1,525 | 0.000656 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | nse is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from libcloud.compute.drivers.kili import KiliCloudNodeDriver, ENDPOINT_ARGS
from li... | f.openstack_connection_kwargs()
kwargs['get_endpoint_args'] = ENDPOINT_ARGS
# Remove keystone from the URL path so that the openstack base tests work
kwargs['ex_force_auth_url'] = 'https://api.kili.io/v2.0/tokens'
kwargs['ex_tenant_name'] = self.tenant_name
return kwargs
KiliCloudNodeDriver._ex_co... |
marinkaz/orange3 | Orange/widgets/widget.py | Python | bsd-2-clause | 35,874 | 0.000585 | import contextlib
import sys
import time
import os
import warnings
import types
from functools import reduce
from PyQt4.QtCore import QByteArray, Qt, pyqtSignal as Signal, pyqtProperty,\
QEventLoop, QSettings, QUrl
from PyQt4.QtGui import QDialog, QPixmap, QLabel, QVBoxLayout, QSizePolicy, \
qApp, QFrame, QSta... | lay to the user.
#: When a widget is first shown a message | from this list is selected
#: for display. If a user accepts (clicks 'Ok. Got it') the choice is
#: recorded and the message is never shown again (closing the message
#: will not mark it as seen). Messages can be displayed again by pressing
#: Shift + F1
#:
#: :type: list of :class:`Message`
... |
sniemi/SamPy | sandbox/src2/bdaycalculator.py | Python | bsd-2-clause | 1,045 | 0.019139 | #! /usr/bin/env python
#This is just a test program
#It calculates an age at days from input and prints it
#SMN
from datetime import date
import sys
try:
if (sys.argv[1] == "-h"):
print """
First Python program of SMN
Usage: year month date
-h Display this usage message
... | ()
birthday = date(year, month, day)
age = now - birthday
print "\n Your age at days: ", age.days
else:
print "wrong number of parameters..."
sys.exit()
except IndexError:
print """need some values or too many values...
try running with -h to see help \n"""
except ValueError:
print "nonse... | or option"
|
Agent007/deepchem | contrib/one_shot_models/multitask_classifier.py | Python | mit | 9,985 | 0.009614 | """
Implements a multitask graph convolutional classifier.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = "Han Altae-Tran and Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import warnings
imp... | 1=self.optimizer_beta1,
beta2=self.optimizer_beta2,
epsilon=self.ep | silon)
else:
raise ValueError("Optimizer type not recognized.")
# Get train function
self.train_op = self.optimizer.minimize(self.loss_op)
def construct_feed_dict(self, X_b, y_b=None, w_b=None, training=True):
"""Get initial information about task normalization"""
# TODO(rbharath): I belie... |
nickgentoo/scikit-learn-graph | scripts/cross_validation_from_matrix_AUC_norm.py | Python | gpl-3.0 | 3,283 | 0.026196 | import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '',''))
import numpy as np
#from skgraph import datasets
from sklearn import svm
#from skgraph.ioskgraph import *
from math import sqrt
import sys
from sklearn.metrics import roc_auc_score
#"sys.path.append('..\\..\\Multiple Kernel Learning\\... | # gram[i,j]=gram[i,j]/sqrt(gram[i,i]+gram[j,j])
sc=[]
for train_index, test_index in kf:
#print("TRAIN:", train_index, "TEST:", test_index)
#generated train and test lists, incuding indices of the examples in training/test
| #for the specific fold. Indices starts from 0 now
clf = svm.SVC(C=c, kernel='precomputed',probability=True)
train_gram = [] #[[] for x in xrange(0,len(train))]
test_gram = []# [[] for x in xrange(0,len(test))]
#generate train matrix and test matrix
index=-1 ... |
theia-log/theia | theia/cli/__main__.py | Python | apache-2.0 | 1,067 | 0.004686 | """Theia CLI entrypoint.
"""
from theia.cli.parser import get_parent_parser
from theia.cli.watcher import get_parser as get_watcher_parser, run_watcher
from theia.cli.collector import get_parser as get_collector_parser, run_collector |
from theia.cli.query import get_parser as get_query_parser, run_query
def run_cli():
"""Run theia CLI.
"""
parser = get_parent_parser('theia', 'Theia CLI')
subparsers = parser.add_subparsers(dest='command', title='command', help='CLI commands')
get_watcher_parser(subparsers)
get_collector_par... | subparsers)
get_query_parser(subparsers)
args = parser.parse_args()
if args.version:
from theia.metadata import version
import sys
print('theia', version)
sys.exit(0)
if args.verbose:
from logging import basicConfig, DEBUG
basicConfig(level=DEBUG)
... |
sandan/sqlalchemy | test/ext/declarative/test_inheritance.py | Python | mit | 54,549 | 0.000018 |
from sqlalchemy.testing import eq_, assert_raises, \
assert_raises_message, is_
from sqlalchemy.ext import declarative as decl
import sqlalchemy as sa
from sqlalchemy import testing
from sqlalchemy import Integer, String, ForeignKey
from sqlalchemy.testing.schema import Table, Column
from sqlalchemy.orm import rel... | 'include_properties': ['id', 'a', 'b'],
}
assert class_mapper(Person).version_id_col == 'a'
assert class_mapper(Person).include_properties == set(['id', 'a', 'b'])
def test_custom_join_condition(self):
class Foo(Base):
__tablena... | id = Column('id', Integer, primary_key=True)
class Bar(Foo):
__tablename__ = 'bar'
bar_id = Column('id', Integer, primary_key=True)
foo_id = Column('foo_id', Integer)
__mapper_args__ = {'inherit_condition': foo_id == Foo.id}
# compile succeed... |
sumsted/mempy-async | mempyasync/resourcehelper.py | Python | apache-2.0 | 1,197 | 0.006683 | __author__ = 'scottumsted'
import gc
import resource
import time
cla | ss ResourceHelper():
def __init__(self, module=None):
self.module = '' if module is None else '\nmodule:\t'+module+'\n'
gc.disable()
self.reset()
def reset(self):
self.start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
self.start_utim | e = resource.getrusage(resource.RUSAGE_SELF).ru_utime
self.start_stime = resource.getrusage(resource.RUSAGE_SELF).ru_stime
self.start_time = time.time()
def usage(self):
stop_utime = resource.getrusage(resource.RUSAGE_SELF).ru_utime
stop_stime = resource.getrusage(resource.R... |
codetestcode/pyintdemo | python2/koans/about_tuples.py | Python | mit | 2,480 | 0.00121 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three =... | ea 51', (37, 14, 6, 'N'), (115, 48, 40, 'W')), place)
def test_tuples_are_good_for_representing_records(self):
locations = [
("Illuminati HQ", (38, 52, 15.56, 'N'), (77, 3, 21.46, 'W')),
("Stargate B", (41, 10, 43.92, 'N'), (1, 49, 34.29, 'W')),
]
locations.append(
... | assertEqual("Cthulhu", locations[2][0])
self.assertEqual(15.56, locations[0][1][2])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.