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 |
|---|---|---|---|---|---|---|---|---|
SerialShadow/SickRage | sickbeard/db.py | Python | gpl-3.0 | 15,583 | 0.003016 | # Author: Nic Wolfe <[email protected]>
# URL: https://sickrage.tv
# Git: https://github.com/SiCKRAGETV/SickRage.git
#
# This file is part of SickRage.
#
# SickRage 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... | # get out of the connection attempt loop since we were successful
break
except sqlite3.OperationalError, e:
if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]:
logger.log(u"DB error: " + ex(e), logger.WARNIN... | |
lavish205/olympia | src/olympia/amo/templatetags/jinja_helpers.py | Python | bsd-3-clause | 19,484 | 0.000103 | import collections
import json as jsonlib
import os
import random
import re
from operator import attrgetter
from urlparse import urljoin
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.forms import CheckboxInput
from django.template import defaultfilters, loader
from... | s, **kwargs):
| """Helper for Django's ``reverse`` in templates."""
add_prefix = kwargs.pop('add_prefix', True)
host = kwargs.pop('host', '')
src = kwargs.pop('src', '')
url = '%s%s' % (host, urlresolvers.reverse(viewname,
args=args,
... |
seansu4you87/kupo | projects/MOOCs/udacity/ud120-ml/projects/outliers/outlier_cleaner.py | Python | mit | 753 | 0.007968 | #!/usr/bin/python
import math
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of poi | nts that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth, error).
"""
### your code goes here
data = []
for i in xrange(len(ages)):
... | * len(sorted_data))
return sorted_data[0:length]
def _error(expected, actual):
return math.pow(actual - expected, 2)
|
visualfabriq/bqueryd | setup.py | Python | bsd-3-clause | 4,002 | 0.00075 | from __future__ import absolute_import
########################################################################
# File based on https://github.com/Blosc/bcolz
########################################################################
#
# License: BSD
# Created: October 5, 2015
# Author: Carst Vaartjes - cva... | import abspath
from sys import version_info as v
from setuptools.co | mmand.build_ext import build_ext as _build_ext
# Check this Python version is supported
if any([v < (2, 6), (3,) < v < (3, 5)]):
raise Exception("Unsupported Python version %d.%d. Requires Python >= 2.7 "
"or >= 3.5." % v[:2])
class build_ext(_build_ext):
def finalize_options(self):
... |
knoguchi/nadex | nadex/rest_exceptions.py | Python | gpl-2.0 | 1,349 | 0 | # REST API exceptions
class HttpException(Exception):
"""
Class for representing http errors. Contains the response.
"""
def __init__(self, msg, res):
super(Exception, self).__init__(msg)
self.response = res
@property
def status_code(self):
return self.response.status_... | ception):
# pass
# 405 and 501 - still just means the client has to change their request
# class UnsupportedRequest(ClientRequestException, ServerExce | ption):
# pass
# 3xx codes
class RedirectionException(HttpException):
pass
class NotLoggedInException(Exception):
pass
|
poldrack/openfmri | openfmri_paper/8.2_mds_wholebrain.py | Python | bsd-2-clause | 3,290 | 0.026748 | #!/usr/bin/env python
""" tsne_openfmri.py: code to run t-SNE on results from MELODIC ICA applied to the OpenFMRI dataset
requires:
- tsne.py from http://homepage.tudelft.nl/19j49/t-SNE.html
- Numpy
"""
## Copyright 2011, Russell Poldrack. All rights reserved.
## Redistribution and use in source and binary forms, wi... | s/paper_analysis_Dec2012/data_prep/zstat_run1.npy').T
clf = manifold.MDS(n_components=2, n_init=1, max_iter=1000)
#dist=euclidean_distances(X)
| dist=squareform(pdist(X,metric='euclidean'))
t=clf.fit_transform(dist)
taskinfo=N.loadtxt('/corral-repl/utexas/poldracklab/openfmri/analyses/paper_analysis_Dec2012/data_prep/data_key_run1.txt')
tasknums=N.unique(taskinfo[:,0])
# compute scatter for each task
t_eucdist={}
mean_t_obs={}
for k in tasknums:
... |
holdenk/spark | python/pyspark/ml/param/shared.py | Python | apache-2.0 | 24,706 | 0.001376 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | self.getOrDefault(self.maxIter)
class | HasRegParam(Params):
"""
Mixin for param regParam: regularization parameter (>= 0).
"""
regParam: "Param[float]" = Param(
Params._dummy(),
"regParam",
"regularization parameter (>= 0).",
typeConverter=TypeConverters.toFloat,
)
def __init__(self) -> None:
... |
mthh/geopy | geopy/geocoders/mapzen.py | Python | mit | 5,724 | 0 | """
Mapzen geocoder, contributed by Michal Migurski of Mapzen.
"""
from geopy.geocoders.base import (
Geocoder,
DEFAULT_FORMAT_STRING,
DEFAULT_TIMEOUT
)
from geopy.compat import urlencode
from geopy.location import Location
from geopy.util import logger
__all__ = ("Mapzen", )
class Mapzen(Geocoder):
... | rties', {}).get('name')
return Locatio | n(placename, (latitude, longitude), feature)
def _parse_json(self, response, exactly_one):
if response is None:
return None
features = response['features']
if not len(features):
return None
if exactly_one is True:
return self.parse_code(features[0... |
Ebag333/Pyfa | eos/effects/sensorcompensationsensorstrengthbonusradar.py | Python | gpl-3.0 | 270 | 0.003704 | # sen | sorCompensationSensorStrengthBonusRadar
#
# Used by:
# Skill: Radar Sensor Compensation
type = "passive"
def handler(fit, container, context):
fit.ship.boostItemAttr("scanRadarStrength", container.getModifiedItemAttr("sensorStrengthBonus") | * container.level)
|
ATNF/askapsdp | Tools/scons_tools/askapenv.py | Python | gpl-2.0 | 4,699 | 0.005746 | # Copyright (c) 2009 CSIRO
# Australia Telescope National Facility (ATNF)
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# PO Box 76, Epping NSW 1710, Australia
# [email protected]
#
# This file is part of the ASKAP software distribution.
#
# The ASKAP software distribution is free softwar... | tools = ['default', 'askap_package', 'doxybuilder',
'functestbuilder', 'icebuilder', 'cloptions' ]
)
# Importing TERM allows programs (such as clang) to produce colour output
# if the terminal supports it
if | 'TERM' in os.environ:
env['ENV']['TERM'] = os.environ['TERM']
opts = Variables('sconsopts.cfg', ARGUMENTS)
opts.Add(BoolVariable("nompi", "Disable MPI", False))
opts.Add(BoolVariable("openmp", "Use OpenMP", False))
opts.Add(BoolVariable("update", "svn update?", False))
opts.Update(env)
# Standard compiler flags
... |
andrewebdev/django-ostinato | ostinato/tests/statemachine/models.py | Python | mit | 509 | 0.001965 | from djang | o.db import models
from .workflow import TestStateMachine
class TestModel(models.Model):
name = models.CharField(max_length=100)
state = models.CharField(max_length=20, null=True, blank=True)
state_num = models.IntegerField(null=True, blank=True)
other_state = models.CharField(max_length=20, null=Tru... | (max_length=250, null=True, blank=True)
class Meta:
permissions = TestStateMachine.get_permissions('testmodel', 'Test')
|
simonjpartridge/byeBias | main.py | Python | apache-2.0 | 644 | 0.003106 | from flask import Flask
app = Flask(__name__)
app.config['DEBUG'] = True
f | rom scraper import default
from scraper import articleProcess
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
|
@app.route('/')
def hello():
"""Return a friendly HTTP greeting."""
return 'Hello World!'
@app.route('/processArticle')
def lala():
return articleProcess.processArticle()
@app.route('/defa')
def fghrghfh():
return default.return_yo()
@app.errorhandler(404)
def page_not_found(e):
"""Return a ... |
ema/conpaas | conpaas-services/contrib/libcloud/compute/base.py | Python | bsd-3-clause | 33,322 | 0 | # 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 ... | """
return self.driver.des | troy_node(self)
def __repr__(self):
return (('<Node: uuid=%s, name=%s, state=%s, public_ips=%s, '
'provider=%s ...>')
% (self.uuid, self.name, self.state, self.public_ips,
self.driver.name))
class NodeSize(UuidMixin):
"""
A Base NodeSize class t... |
Fokko/incubator-airflow | airflow/sensors/sql_sensor.py | Python | apache-2.0 | 4,819 | 0.003528 | # -*- 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
#... | that takes first_cell
as the only argument and return a boolean (optional).
:type: failure: Optional<Callable[[Any], bool] | >
:param fail_on_empty: Explicitly fail on no rows returned.
:type: fail_on_empty: bool
"""
template_fields = ('sql',) # type: Iterable[str]
template_ext = ('.hql', '.sql',) # type: Iterable[str]
ui_color = '#7c7287'
@apply_defaults
def __init__(self, conn_id, sql, parameters=None, s... |
Lucasfeelix/ong-joao-de-barro | users/migrations/0001_initial.py | Python | mit | 2,597 | 0.004667 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-06-21 04:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Donors',... | s=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Criado em')),
('modified_at', models.DateTimeField(auto_now=True, verbose_name='Modi | ficado em')),
('address', models.CharField(blank=True, max_length=100, verbose_name='Endereço')),
('number', models.IntegerField(verbose_name='Número')),
('complement', models.CharField(blank=True, max_length=100, verbose_name='Complemento')),
('neighborho... |
chuckbasstan123/pyTorch_project | mnist/main.py | Python | bsd-3-clause | 4,528 | 0.001767 | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')... | arget)
| loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.data[0]))
def tes... |
h3llrais3r/Auto-Subliminal | autosubliminal/providers/proxy.py | Python | gpl-3.0 | 1,013 | 0.000987 | from urllib.parse import urlparse
class Proxy(object):
def __init__(self, proxy_type, proxy_address, proxy_port, proxy_login, proxy_password):
self.proxyType = proxy_type
self.proxyAddress = proxy_address
self.proxyPort = proxy_port
self.proxyLogin = proxy_login
self.proxyP... | proxyType': self.proxyType,
'proxyAddress': self.proxyAddress,
'proxyPort': self.proxyPort}
if self.proxyLogin or self.proxyPassword:
result['proxyLogin'] = self.proxyLogin
result['proxyPassword'] = self.proxyPassword
| return result
@classmethod
def parse_url(cls, url):
parsed = urlparse(url)
return cls(proxy_type=parsed.scheme,
proxy_address=parsed.hostname,
proxy_port=parsed.port,
proxy_login=parsed.username,
proxy_password=parsed.p... |
svagionitis/youtube-dl | youtube_dl/extractor/comedycentral.py | Python | unlicense | 9,941 | 0.003018 | from __future__ import unicode_literals
import re
from .mtv import MTVServicesInfoExtractor
from ..utils import (
compat_str,
compat_urllib_parse,
ExtractorError,
float_or_none,
unified_strdate,
)
class ComedyCentralIE(MTVServicesInfoExtractor):
_VALID_URL = r'''(?x)https?://(?:www\.)?cc\.co... | ct(self, url):
mobj = re.match(self._VALID_URL, url)
if mobj.group('shortname'):
if mobj.group('shortname') in ('tds', 'thedailyshow'):
url = 'http://thedailyshow.cc.com/full-episodes/'
else:
url = 'http://thecolbertreport.cc.com/full-epi | sodes/'
mobj = re.match(self._VALID_URL, url, re.VERBOSE)
assert mobj is not None
if mobj.group('clip'):
if mobj.group('videotitle'):
epTitle = mobj.group('videotitle')
elif mobj.group('showname') == 'thedailyshow':
epTitle = mobj.... |
radicalbiscuit/mutcd-getter | mutcd-getter.py | Python | mit | 5,919 | 0.003886 | #!/usr/bin/env python
"""Get MUTCD SVGs from Wikipedia."""
import urllib
import argparse
import os
import json
from lxml import html
import wikipedia
from pyquery import PyQuery
class MUTCDGetterError(Exception):
pass
# Setup arguments.
parser = argparse.ArgumentParser()
parser.add_argument('--title', default... | ld(1)')
column = parsed_args.column
if isinstance(column, str):
# If the provided column is a string, find the column index. While this is probably the same for each table,
# we'll still check every time. | It's cheap and this is an infrequent script.
for i, header_cell in enumerate(first_row.find('th')):
if header_cell.text_content().strip().startswith(column):
column = i
break
if isinstance(column, str):
# We couldn't find it.
raise MUT... |
prometheanfire/cloud-init | tests/unittests/test_handler/test_handler_locale.py | Python | gpl-3.0 | 2,046 | 0 | # Copyright (C) 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Juerg Haefliger <[email protected]>
#
# Based on test_handler_set_hostname.py
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# ... | gObj
from six import BytesIO
import logging
import shutil
import tempfile
LOG = logging.getLogger(__name__)
class TestLocale(t_help.FilesystemMockingTestCase):
def setUp(self):
super(TestLocale, self).setUp()
self.new_root = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.new_roo... | , distro):
self.patchUtils(self.new_root)
paths = helpers.Paths({})
cls = distros.fetch(distro)
d = cls(distro, {}, paths)
ds = DataSourceNoCloud.DataSourceNoCloud({}, d, paths)
cc = cloud.Cloud(ds, paths, {}, d, None)
return cc
def test_set_locale_sles(self... |
michcioperz/shirley | shirley.py | Python | mit | 1,574 | 0.003177 | #!/usr/bin/env python3
import argparse, os, subprocess, json, requests, re, string
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("source_host", type=str)
parser.add_argument("target_path", type=str)
args = parser.parse_args()
print("Now, what do we have here?")
... | oads(r.text)
print("I see %i series with a total of %i episodes" % (len(database["series"]), len(database["videos"])))
for a in database["series"]:
print("Let's look for some %s" % a)
r = requests.get("http://%s/otaku/api/series/%s/find" % (args.source_host, a))
av = json.loads(r.text)
| print("There are %i episodes of it on the server" % len(av["videos"]))
avd = os.path.join(args.target_path, "".join([x if x in frozenset(string.ascii_letters+string.digits) else "" for x in a]))
if len(av["videos"]) > 0 and not os.path.exists(avd):
os.mkdir(avd)
for avi in av[... |
plotly/python-api | packages/python/plotly/plotly/validators/choropleth/colorbar/_outlinecolor.py | Python | mit | 487 | 0.002053 | import _plotly_utils.basevalidators
class OutlinecolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name=" | outlinecolor", parent_name="choropleth.colorbar", **kwargs
):
super(OutlinecolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_ | type=kwargs.pop("edit_type", "colorbars"),
role=kwargs.pop("role", "style"),
**kwargs
)
|
robertojrojas/networking-Go | src/DaytimeServer/daytime-client.py | Python | mit | 162 | 0.006173 | import socket
conn= | socket.create_connection(('localhost', 1200))
input = conn.makefile()
print inpu | t.readline()
conn.close()
# You can use telnet localhost 1200
|
telefonicaid/fiware-facts | tests/acceptance/features/component/steps/multi_tenancy.py | Python | apache-2.0 | 7,996 | 0.006005 | # -*- coding: utf-8 -*-
#
# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# 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:
#
# ... | a_context_update_is_received_for_secondary_tenant(context, server_id):
send_context_notification_step_helper(context, context.secondary_tenant_id, server_id)
@step(u'a new secondary RabbitMQ consumer is looking into the configured | message bus')
def new_secondaty_consumer_looking_for_messages(context):
# Init RabbitMQ consumer
context.secondaty_rabbitmq_consumer = RabbitMQConsumer(
amqp_host=configuration_utils.config[PROPERTIES_CONFIG_RABBITMQ_SERVICE][PROPERTIES_CONFIG_SERVICE_HOST],
amqp_port=configuration_utils.config... |
goddardl/cortex | test/IECoreMaya/FnParameterisedHolderTest.py | Python | bsd-3-clause | 35,854 | 0.071791 | ##########################################################################
#
# Copyright (c) 2008-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... | ###############
node = maya.cmds.createNode( "ieOpHolderNode" )
fnPH = IECoreMaya.FnParameterisedHolder( node )
op = IECore.ClassLoader.defaultOpLoader().load( "parameterTypes", 1 )()
op.parameters().removeParameter( "m" ) # no color4f support in maya
fnPH.setParameterised( op )
# check we have the star... | #######################
self.assertEqual( op["a"].getNumericValue(), 1 )
aPlug = fnPH.parameterPlug( op["a"] )
self.assertEqual( aPlug.asInt(), 1 )
self.assertEqual( op["b"].getNumericValue(), 2 )
bPlug = fnPH.parameterPlug( op["b"] )
self.assertEqual( bPlug.asFloat(), 2 )
self.assertEqual( op["c"].get... |
rohitwaghchaure/frappe | frappe/desk/reportview.py | Python | mit | 8,532 | 0.034341 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
"""build query for doclistview and return results"""
import frappe, json
import frappe.permissions
from frappe.model.db_query import DatabaseQuery
from frappe import _
@frappe.w... | type == "Excel":
from frappe.utils.xlsxutils import make_xlsx
xlsx_file = make_xlsx(data, doctype)
frappe.response['filename'] = doctype + '.xlsx'
frappe.response['filecontent'] = xlsx_file.getvalue()
frap | pe.response['type'] = 'binary'
def append_totals_row(data):
if not data:
return data
data = list(data)
totals = []
totals.extend([""]*len(data[0]))
for row in data:
for i in xrange(len(row)):
if isinstance(row[i], (float, int)):
totals[i] = (totals[i] or 0) + row[i]
data.append(totals)
return data... |
HEG-Arc/Appagoo | appagoo/config/__init__.py | Python | bsd-3-clause | 288 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .local import Local # noqa
f | rom .production import Production # noqa
# This will make sure the app is always im | ported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
|
Vauxoo/website | website_lazy_load_image/models/__init__.py | Python | agpl-3.0 | 25 | 0 | from . | import ir_ | ui_view
|
mohanprasath/Course-Work | data_analysis/uh_data_analysis_with_python/hy-data-analysis-with-python-spring-2020/part05-e02_cycling_weather/src/cycling_weather.py | Python | gpl-3.0 | 1,517 | 0.009967 | #!/usr/bin/env python3
import pandas as pd
def split_date(df):
days = {"ma": "Monday", "ti": "Tuesday", "ke": "Wednesday", "to": "Thuday", "pe": "Friday", "la": "Satday", "su": "Sunday"}
months = {"tammi": 1, "helmi": 2, "maalis": 3, "huhti": 4, "touko": 5, "kesä": 6,
"heinä": 7, "elo": 8, "syys": 9, "lok... | v", sep=",")
wea_df = wea_df.rename(columns = {'m': 'Month', 'd': 'Day'}, index=str)
# merging
| merged_df = pd.merge(pyo_df, wea_df)
merged_df = merged_df.drop(["Time zone", "Time"], axis=1)
return merged_df
def main():
df = cycling_weather()
return
if __name__ == "__main__":
main()
|
diego-carvalho/FAiR | app/src/loadData.py | Python | mit | 5,565 | 0.000719 | # -*- coding: utf-8 -*
import numpy as np
import sys
def load_data_test(file_test, window):
# read the test data and mount the matrix
file_test = open(file_test, 'r')
dic_u_test = {}
dic_i_test = {}
for line in file_test:
try:
line = line.rstrip()
values = line.... | s[i][j].split(":")[1]))
ids.append(id_aux)
ratings.append(ra_aux)
matrix_top_n = np.array(ids)
matrix_ratings = np.array(ratings)
file_top_n.close()
print('read the topN data')
# reading end
return dic_u_top, matrix_top_n, matrix_ratings
def convert_file_mymedialite(file_top_... | trix
file_top_n = open(file_top_n, 'r')
file_out = open(output_file + "file_mymedialite_topn.txt", 'w')
lines = []
ids = []
ratings = []
dic_u_top = {}
cont_u = 0
for line in file_top_n:
aux = line.split()
user = aux[0]
aux = aux[1][1:]
aux = aux[:-1].sp... |
DemocracyClub/yournextrepresentative | ynr/apps/elections/migrations/0009_make_election_slug_unique.py | Python | agpl-3.0 | 356 | 0.002809 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("elections", "000 | 8_remove_artificial_start_and_end_dates")]
operations = [
migrations.AlterField(
model_name="election",
name="slug",
field=models.CharField(un | ique=True, max_length=128),
)
]
|
montenegroariel/sigos | apps/afiliados/forms.py | Python | gpl-3.0 | 5,885 | 0.003569 | import datetime
import qrcode
from django import forms
from django.conf import settings
from apps.complementos.afiliados.models import Plan
from lib.forms import EstiloForm
from apps.personas.models import Sexo
from apps.complementos.personas.models import EstadoCivil
from .models import Titular, Adherente, Parentes... | True, queryset=Empresa.objects.all(), widget=forms.Select())
alta_afiliado = forms.BooleanField(required=False, widget=forms.CheckboxInput())
codigo_qr = forms.ImageField(required=False, widget=forms.FileInput())
codigo_seguridad = forms.IntegerField(required=False)
cuil = forms.CharField(required=False... | .all(), widget=forms.Select())
pendiente_revision = forms.BooleanField(required=False, initial=False, widget=forms.CheckboxInput())
causa_revision = forms.CharField(required=False, widget=forms.Textarea())
embarazada = forms.BooleanField(required=False, initial=False, widget=forms.CheckboxInput())
meses... |
bjornaa/ladim | examples/obstacle/animate.py | Python | mit | 1,379 | 0 | import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from postladim import ParticleFile
from gridforce_analytic impo | rt Grid
# Particle file
particle_file = "obstacle.nc"
# Get the grid information
grid = Grid(None)
imax, jmax = grid.imax, grid.jmax
# L = grid.L
R = grid.R
X0 = grid.X0
# particle_file
pf = ParticleFile(particle_file)
num_times = pf.num_times
# Set up the plot area
fig = plt.figure(figsize=(12, 8))
ax = plt.axes(... |
X, Y = pf.position(0)
particle_dist, = ax.plot(X, Y, ".", color="red", markeredgewidth=0.5, lw=0.5)
# title = ax.set_title(pf.time(0))
time0 = pf.time(0) # Save start-time
timestr = "00:00"
timestamp = ax.text(0.02, 0.93, timestr, fontsize=16, transform=ax.transAxes)
# Update function
def animate(t):
X, Y = pf.... |
jss-emr/openerp-7-src | openerp/addons/account_budget/wizard/account_budget_crossovered_summary_report.py | Python | agpl-3.0 | 2,217 | 0.002255 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>) | .
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# | published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This 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. Se... |
angr/angr | angr/storage/memory_mixins/paged_memory/page_backer_mixins.py | Python | bsd-2-clause | 8,238 | 0.005705 | from mmap import mmap
from typing import Union, List, Generator, Tuple
import logging
import claripy
import cle
from .paged_memory_mixin import PagedMemoryMixin
l = logging.getLogger(__name__)
BackerType = Union[bytes,bytearray,List[int]]
BackerIterType = Generator[Tuple[int,BackerType],None,None]
# since memoryv... | _addr <= addr < page_addr + self.page_size:
if new_page is None:
kwargs['allow_default'] = True
new_page = PagedMemoryMixin._initialize_default_page(self, pageno, **kwargs)
new_page.store(addr % self.page_size,
clarip... | ew_page is None:
return super()._i |
cedadev/AuthKit | authkit/authenticate/form.py | Python | mit | 10,231 | 0.004692 | # -*- coding: utf-8 -*-
"""Form and cookie based authentication middleware
As with all the other AuthKit middleware, this middleware is described in
detail in the AuthKit manual and should be used via the
``authkit.authenticate.middleware`` function.
The option form.status can be set to "200 OK" if the Pylons error ... | cate_function, strip_base, RequireEnvironKey, \
AuthKitAuthHandler
from authkit.authenticate.multi import MultiHandler, status_checker
import inspect
import logging
import urllib
log = logging.getLogger('authkit.authenticate.form')
def user_data(state):
return 'User data string'
def template(method=False):
... | >
<dl>
<dt>Username:</dt>
<dd><input type="text" name="username"></dd>
<dt>Password:</dt>
<dd><input type="password" name="password"></dd>
</dl>
<input type="submit" name="authform" value="Sign In" />
</form>
</body>
</html>
"""
if method is not False:
... |
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/astroid/tests/unittest_helpers.py | Python | apache-2.0 | 9,201 | 0.000109 | # Copyright (c) 2015-2016 Cara Vinson <[email protected]>
# Copyright (c) 2015-2016 Claudiu Popa <[email protected]>
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
import unittest
import six
from ... | x.PY2 else 'method'),
(ast_nodes[6], 'instancemethod' if six.PY2 else 'method'),
(ast_nodes[7], 'function'),
(ast_nodes[8], 'function'),
(ast_nodes[9], 'generator'),
]
for node, expected in expected_method_types:
node_type = helpers.object_type... | ode)
expected_type = self._build_custom_builtin(expected)
self.assert_classes_equal(node_type, expected_type)
@test_utils.require_version(minver='3.0')
def test_object_type_metaclasses(self):
module = builder.parse('''
import abc
class Meta(metaclass=abc.ABCMeta)... |
jtpaasch/artifact | artifact/stats/console.py | Python | mit | 13,192 | 0 | # -*- coding: utf-8 -*-
"""A module for displaying stats in the console."""
import sys
import time
import curses
from curses import wrapper
from artifact.stats import autoscalinggroups
from artifact.stats import ec2
from artifact.stats import elasticloadbalancers
from artifact.stats import launchconfigurations
from... | med>"
if datum.get("Tags"):
tags = datum.get("Tags")
for tag in tags:
if tag.get("Key") == "Name":
instance_name = tag.get("Value")
security_groups = []
if datum.get("SecurityGroups"):
sgs = datum.get("SecurityGroups")
... | security_groups.append(group_name + " " + group_id)
fieldset.append(instance_name)
fieldset.append(instance_id)
fieldset.append(instance_type)
fieldset.append(status)
if private_dnsname:
fieldset.append(private_dnsname)
if private_ip:
fieldset.app... |
scwuaptx/CTF | 2018-writeup/codegate/marimo.py | Python | gpl-2.0 | 1,472 | 0.011549 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pwn import *
import time
host = "10.211.55.6"
port = 8888
host = "ch41l3ng3s.codegate.kr"
port = 3333
r = remote(host,port)
def sell(idx):
r.recvuntil(">>")
r.sendline("S")
r.recvuntil(">>")
r.sendline(str(idx))
r.recvuntil("?")
r.sendline("... |
r.sendline("V")
r.recvuntil(">>")
r.sendline(str(idx))
data = r.recvuntil(">>")
if profile :
r.sendline("M")
r.recvuntil(">>")
r.sendline(profile)
return data
else :
r.sendline("B")
return data
puts_got = 0x603018
r.recvuntil(">>")
r.sendline("s... | anogg","fuck")
buy(1,"orange","fuck")
time.sleep(3)
data = view(0)
ctime = int(data.split("current time :")[1].split("\n")[0].strip())
view(0,"a"*0x30 + p32(ctime) + p32(1) + p64(puts_got) + p64(puts_got))
r.recvuntil(">>")
r.sendline("B")
data = view(1)
libc = u64(data.split("name :")[1].split("\n")[0].strip().ljust(8... |
dtulyakov/py | intuit/test2.py | Python | gpl-2.0 | 255 | 0.038835 | #!/usr/bin/env python2
# -* | - coding: utf-8 -*-
import os, sys
try:
s = "qwertyu"
while s != "":
print s
s = s[1:-1]
# print "Просто муйня"
except:
print "При выполнении прогр | аммы возникла проблема!"
|
xueyumusic/pynacl | tests/test_box.py | Python | apache-2.0 | 7,660 | 0 | # Copyright 2013 Donald Stufft and individual contributors
#
# 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... | ametrize(
(
"privalice", "pubalice", "privbob", | "pubbob", "nonce", "plaintext",
"ciphertext",
),
VECTORS,
)
def test_box_encryption(
privalice, pubalice, privbob, pubbob, nonce, plaintext, ciphertext):
pubalice = PublicKey(pubalice, encoder=HexEncoder)
privbob = PrivateKey(privbob, encoder=HexEncoder)
box = Box(privbob, pubalice... |
pulsar-chem/Pulsar-Core | lib/systems/l-glutamic_acid.py | Python | bsd-3-clause | 1,099 | 0.00091 | i | mport pulsar as psr
def load_ref_system():
""" Returns l-glutamic_acid as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
N 0.1209 -2.2995 -0.2021
C 0.4083 -0.9510 -0.7668
C -0.... | 0.5152 1.0936 -0.0551
C -1.5226 0.3991 0.1502
H -1.8462 0.6291 -0.8851
H -2.0847 -0.5077 0.4535
C -1.8924 1.5597 1.0413
O -1.8774 2.7496 0.7858
O -2.3012 1.2232 2.2867
... |
msfrank/Higgins | higgins/upnp/logger.py | Python | lgpl-2.1 | 296 | 0.006757 | # Higgins - A multi-media server
# Copyright (c) 2007-2009 Michael Frank <[email protected]>
#
# This program is free software; for license information see
# the COPYING file.
from higgins.logger im | port Loggable
class UPnPLogger(Logg | able):
log_domain = "upnp"
logger = UPnPLogger()
|
uwkejia/Clean-Energy-Outlook | examples/Extra/Codes/SVR_nuclear.py | Python | mit | 1,586 | 0.019546 | def read_data(file_name):
return pd.read_csv(file_name)
def preprocess(data):
# Data Preprocessing
data['GDP_scaled']=preprocessing.scale(data['GDP'])
data['CLPRB_scaled']=preprocessing.scale(data['CLPRB'])
data['EMFDB_scaled']=preprocessing.scale(data['EMFDB'])
data['ENPRP_scaled']=preproces... | MPB'])
data['PAPRB_scaled']=preprocessing.scale(data['PAPRB'])
data['PCP_scaled']=preprocessing.scale(data['PCP'])
data['ZNDX_scaled']=preprocessing.scale(data['ZNDX'])
data[' | OP_scaled']=preprocessing.scale(data['Nominal Price'])
data['OP2_scaled']=preprocessing.scale(data['Inflation Adjusted Price'])
return data
def split_data(data):
# Split data for train and test
all_x = data[['GDP_scaled','CLPRB_scaled','EMFDB_scaled','ENPRP_scaled','NGMPB_scaled','PAPRB_scaled','PCP_... |
cpennington/edx-platform | openedx/core/djangoapps/user_api/accounts/tests/test_api.py | Python | agpl-3.0 | 25,510 | 0.003652 | # -*- coding: utf-8 -*-
"""
Unit tests for behavior that is specific to the api methods (vs. the view methods).
Most of the functionality is covered in test_views.py.
"""
import itertools
import unicodedata
import ddt
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.... | elf.user.username)
def test_update_non_existent_user(self):
with self.assertRaises(UserNotAuthorized):
| update_account_settings(self.user, {}, username="does_not_exist")
self.user.username = "does_not_exist"
with self.assertRaises(UserNotFound):
update_account_settings(self.user, {})
def test_get_empty_social_links(self):
account_settings = get_account_settings(self.default... |
orlade/microsimmer | host/server/transformer.py | Python | mit | 2,039 | 0.000981 | FILE_PREFIX = '__file__'
class Form | Transformer(object):
"""
Deserializes requests constructed by HTML forms, and serializes results to
JSON.
"""
def parse(self, request, service_params):
"""
Parses the parameter values in the request to a list with the order of
the given service_params.
"""
# ... | = FILE_PREFIX + param
if file_param in request.files.keys():
value = self.parse_value(
request.files.get(file_param).file.read())
args.append(value)
elif param in request.params:
value = self.parse_value(request.params[param])
... |
shaftoe/home-assistant | homeassistant/components/calendar/demo.py | Python | apache-2.0 | 2,739 | 0 | """
Demo platform that has two fake binary sensors.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
import homeassistant.util.dt as dt_util
from homeassistant.components.calendar import CalendarEventDevice
from homeassistant.components.goog... | """Set the event data."""
middle_of_event = dt_util.now() \
- dt_util.dt.timedelta(minutes=30)
self.event = {
'start': {
'dateTime': middle_of_event.isoformat()
},
'end': {
'dateTime': (middle_of_event + dt_util.d... |
timedelta(minutes=60)).isoformat()
},
'summary': 'Current Event',
}
class DemoGoogleCalendar(CalendarEventDevice):
"""Representation of a Demo Calendar element."""
def __init__(self, hass, calendar_data, data):
"""Initialize Goo... |
anhstudios/swganh | data/scripts/templates/object/tangible/furniture/plain/shared_plain_coffee_table_s01.py | Python | mit | 463 | 0.047516 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MOD | IFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/furniture/plain/shared_plain_coffee_table_s01.iff"
result.attribute_template_id = 6
result.stfName("frn_n","frn_co... |
return result |
tinloaf/home-assistant | tests/components/test_rest_command.py | Python | apache-2.0 | 10,394 | 0 | """The tests for the rest command platform."""
import asyncio
import aiohttp
import homeassistant.components.rest_command as rc
from homeassistant.setup import setup_component
from tests.common import (
get_test_home_assistant, assert_setup_component)
class TestRestCommandSetup:
"""Test the rest command co... | with post."""
data = {
'payload': 'data',
}
self.config[rc.DOMAIN]['post_test'].update(data)
with assert_setup_component(4):
setup_component(self.has | s, rc.DOMAIN, self.config)
aioclient_mock.post(self.url, content=b'success')
self.hass.services.call(rc.DOMAIN, 'post_test', {})
self.hass.block_till_done()
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == b'data'
def test_rest_command_... |
gunan/tensorflow | tensorflow/python/data/kernel_tests/shuffle_test.py | Python | apache-2.0 | 13,444 | 0.006174 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ses(errors.OutOfRangeError):
self.evaluate(get_next())
@combinations.generate(combinations.combine(tf_api_version=1, mode="graph"))
def testSeedZero(self):
"""Test for same behavior when the seed is a Python or Tensor zero | ."""
iterator = dataset_ops.make_one_shot_iterator(
dataset_ops.Dataset.range(10).shuffle(10, seed=0))
get_next = iterator.get_next()
elems = []
with self.cached_session() as sess:
for _ in range(10):
elems.append(sess.run(get_next))
with self.assertRaises(errors.OutOfRangeE... |
mastizada/kuma | kuma/attachments/tests/test_templates.py | Python | mpl-2.0 | 2,137 | 0.001404 | from nose.plugins.attrib import attr
from nose.tools import eq_, ok_
from pyquery import PyQuery as pq
import constance.config
from django.conf import settings
from kuma.users.tests import UserTestCase
from kuma.wiki.tests import revision, WikiTestCase
from kuma.core.urlresolvers import reverse
from ..models import ... | e(self):
title = '"><img src=x onerror=prompt(navigator.userAgent);>'
# use view to create new attachment
file_for_uplo | ad = make_test_file()
post_data = {
'title': title,
'description': 'xss',
'comment': 'xss',
'file': file_for_upload,
}
self.client.login(username='admin', password='testpass')
resp = self.client.post(reverse('attachments.new_attachment'),
... |
eske/seq2seq | translate/utils.py | Python | apache-2.0 | 20,579 | 0.002478 | import os
import sys
import re
import numpy as np
import logging
import struct
import random
import math
import wave
import shutil
import collections
import functools
import operator
import heapq
from collections import namedtuple
from contextlib import contextmanager
# special vocabulary symbols
_BOS = '<S>'
_EOS =... | d(file_)
yield files
finally:
for file_ in files:
file_.close()
class AttrDict(dict):
"""
Dictionary whose keys can be accessed as attributes.
Example:
>>> d = AttrDict(x=1, y=2)
>>> d.x
1
>>> d.y = 3
"""
def __init__(self, *args, **kwargs):
... | _dict__.get(item)
def reverse_edits(source, edits, fix=True, strict=False):
if len(edits) == 1: # transform list of edits as a list of (op, word) tuples
edits = edits[0]
for i, edit in enumerate(edits):
if edit in (_KEEP, _DEL, _INS, _SUB):
edit = (edit, edit)
... |
collective/collective.z3cform.bootstrap | collective/z3cform/bootstrap/utils.py | Python | gpl-3.0 | 407 | 0 | from zope.interface import alsoProvides
from collective.z3cform.bootstrap.interfaces import IBootstrapLayer
def set_bootstrap_layer(request):
"""Set the IBootstrapLayer on the request. Useful if you don't want to
enable the bootstrap layer for your w | hole site. | """
alsoProvides(request, IBootstrapLayer)
def before_traversal_event_handler(obj, event):
set_bootstrap_layer(event.request)
|
samuelcolvin/pydantic | docs/examples/settings_add_custom_source.py | Python | mit | 978 | 0 | import json
from pathlib import Path
from typing import Dict, Any
from pydantic import BaseSettings
def json_config_settings_source(settings: BaseSettings) -> Dict[str, Any]:
"""
A simple settings source that loads variables from a JSON file
at the project's root.
Here we happen to choose to use the... | ttings(BaseSettings):
foobar: str
class Config:
env_file_encoding = 'utf-8'
@classmethod
def customise_sources(
cls,
init_settings,
env_settings,
file_secret_settings,
):
return (
init_settings,
... | son_config_settings_source,
env_settings,
file_secret_settings,
)
print(Settings())
|
masia02/chainer | chainer/functions/clipped_relu.py | Python | mit | 1,841 | 0.002173 | from chainer import cuda
from chainer import function
from chainer import utils
from chainer.utils import type_check
import numpy
class ClippedReLU(function.Function):
"""Clipped Rectifier Unit function.
Clipped ReLU is written as :math:`ClippedReLU(x, z) = \min(\max(0, x), z)`,
where :math:`z(>0)` is a... | _type, = in_types
type_check.expect(x_type.dtype == numpy.float32)
def forward_cpu(self, x):
return utils.force_array(numpy.minimum(
numpy.maximum(0, x[0]), self.cap)).astype(numpy.float32),
def backward_cpu(self, x, gy):
return utils.force_array(
gy[0] * (0 < x... | y.float32),
def forward_gpu(self, x):
return cuda.elementwise(
'T x, T cap', 'T y', 'y = min(max(x, (T)0), cap)',
'clipped_relu_fwd')(x[0], self.cap),
def backward_gpu(self, x, gy):
gx = cuda.elementwise(
'T x, T gy, T z', 'T gx',
'gx = ((x > 0) ... |
Fireblend/scikit-learn | sklearn/linear_model/base.py | Python | bsd-3-clause | 16,019 | 0.000499 | """
Generalized Linear models.
"""
# Author: Alexandre Gramfort <[email protected]>
# Fabian Pedregosa <[email protected]>
# Olivier Grisel <[email protected]>
# Vincent Michel <[email protected]>
# Peter Prettenhofer <[email protected]>
# ... | Returns predicted values.
"""
return self._decision_function(X)
def _decision_function(self, X):
check_is_fitted(self, "coef_")
X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
return safe_sparse_dot(X, self.coef_.T,
dense_output=True) ... | x}, shape = (n_samples, n_features)
Samples.
Returns
-------
C : array, shape = (n_samples,)
Returns predicted values.
"""
return self._decision_function(X)
_center_data = staticmethod(center_data)
def _set_intercept(self, X_mean, y_mean, X_std)... |
Demeterr/iam_acctmgr | iam_acctmgr.py | Python | apache-2.0 | 13,615 | 0.00022 | # Copyright 2015 Bebop Technologies
#
# 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 wr... | spwall
if user[0] in username_index)
uid_index = dict((int(user.pw_uid), user) for user in pwall)
next_uid = MIN_USER_UID
passwd, shadow, sudo = [], [], []
# Users that | have been removed from IAM will keep their UIDs around in the
# event that user IDs have. In practice, I don't anticipate this behavior
# to be problematic since there is an abundance of UIDs available in the
# default configuration UID range for all but the largest admin user pools.
for old_username ... |
IIIIIIIIll/sdy_notes_liaoxf | LiaoXueFeng/as_IO/async_await.py | Python | gpl-3.0 | 325 | 0.006154 | import threading
import asyncio
async def hello():
print('Hello world! (%s)' % threading.currentThread())
await asyncio.sleep(1)
pri | nt('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close() | |
selenized/clausius | clausius/eos/basicmixing.py | Python | unlicense | 877 | 0.003421 | import numpy as np
__all__ = ['vanDerWaalsMixing']
def vanDerWaalsMixing(kij=0):
"""Simple van der Waals mixing rules, returns a mixingrule function.
kij is an numpy array of binary interaction parameters"""
def vdw_mixing(molefraction, theta, TdthetadT, B, delta=None, epsilon=None, eta=None):
"... | _m, T*dtheta/dT_m, dtheta/dn, B_b, dB/dn"""
theta_ij = (1 - kij) * np.sqrt(np.outer(theta, theta))
dtheta_m = np.dot(molefraction, theta_ij)
B_m = np.dot(molefraction, B)
TdthetadT_ij = 0.5 * (1 - kij) * np.outer(theta, theta)**-0.5 * (np.outer(TdthetadT, theta) + np.outer(theta, Tdtheta... | 2 * dtheta_m, B_m, B
return vdw_mixing
|
hazelcast-incubator/pyhzclient | hzclient/codec/transactionalmultimapcodec.py | Python | apache-2.0 | 1,449 | 0.024845 | __author__ = 'Jonathan Brodie'
import ctypes
from hzclient.clientmessage import ClientMessage
from util import util
'''
PUT
'''
de | f putEncode():
msg=ClientMessage()
msg.optype=0x1101
util.rais | eNotDefined()
def putDecode(bytesobject):
servermsg=ClientMessage.decodeMessage(bytesobject)
util.raiseNotDefined()
'''
GET
'''
def getEncode():
msg=ClientMessage()
msg.optype=0x1102
util.raiseNotDefined()
def getDecode(bytesobject):
servermsg=ClientMessage.decodeMessage(bytesobject)
util.r... |
vladan-m/ggrc-core | src/ggrc/models/section_objective.py | Python | apache-2.0 | 1,173 | 0.01364 | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from ggrc import db
from .mixins import | Mapping
class SectionObjective(Mapping, db.Model):
__tablename__ = 'section_objectives'
@staticmethod
def _extra_table_args(cls):
return (
db.UniqueConstraint('section_id', 'objective_id'),
db.Index('ix_section_id', 'section_id'),
db.Index('ix_objective_id', 'objective_id'),
... | ttrs = [
'section',
'objective',
]
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(SectionObjective, cls).eager_query()
return query.options(
orm.subqueryload('section'),
orm.subqueryload('objective'))
def _display_name(self):
return... |
ministryofjustice/cla_backend | cla_backend/apps/reports/urls.py | Python | mit | 2,339 | 0.005558 | from django.conf.urls import patterns, url
from . import views
from . import api
urlpatterns = patterns(
"",
url(r"^api/exports/$", api.ExportListView.as_view(), name="exports"),
url(r"^api/exports/scheduled/$", api.ExportListView.as_view(scheduled=True), name="scheduled"),
url(r"^api/exports/(?P<pk>... |
),
url(
r"^mi-complaint-view-audit-log-extract/$",
views.mi_complaint_view_audit_log_extract,
name="mi_complaint_view_audit_log_extract",
),
url(r"^mi-feedback-e | xtract/$", views.mi_feedback_extract, name="mi_feedback_extract"),
url(r"^mi-duplicate-case-extract/$", views.mi_duplicate_case_extract, name="mi_duplicate_case_extract"),
url(r"^mi-contacts-per-case-extract/$", views.mi_contacts_extract, name="mi_contacts_extract"),
url(r"^mi-alternative-help-extract/$", v... |
slice/dogbot | dog/ext/quoting/cog.py | Python | mit | 7,284 | 0.000412 | import datetime
import time
from random import choice
import discord
import lifesaver
from discord.ext import commands
from lifesaver.bot.storage import AsyncJSONStorage
from lifesaver.utils import (
ListPaginator,
clean_mentions,
human_delta,
pluralize,
truncate,
)
from .converters import Message... | otes(self, guild: discord.Guild):
return self.storage.get(str(guild.id), {})
@lifesaver.command(aliases=["rq"])
@commands.guild_only()
async def random_quote(self, ctx):
"""Shows a random quote."""
| quotes = self.quotes(ctx.guild)
if not quotes:
await ctx.send(
"There are no quotes in this server. Create some with "
f"`{ctx.prefix}quote new`. For more information, see `{ctx.prefix}"
"help quote`."
)
return
... |
SequencingDOTcom/App-Market-API-integration | python/external/sequencing/utils/connect.py | Python | mit | 1,174 | 0.005963 | import base64
import urllib
import hashlib
import json
from Crypto.Cipher import AES
from external.sequencing.config import SequencingEndpoints
class AESCipher:
def __init__(self, key, iv):
self.key = key[:32]
self.iv = iv[:16]
__pad = lambda self,s: s + (AES.block_size - len(s) % AES.block_... | e) * chr(AES.block_size - len(s) % AES.block_size)
__unpad = lambda self,s: s[0:-ord(s[-1])]
def encrypt(self, raw):
raw = self.__pad(raw)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
return base64.b64encode | (cipher.encrypt(raw))
def decrypt(self, enc):
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
return self.__unpad(cipher.decrypt(enc).decode("utf-8"))
def get_connect_to_link(data , url=SequencingEndpoints.connect_to):
password = data['client_id'];
ci... |
shreevatsa/sanskrit | transliteration/transliterate.py | Python | gpl-2.0 | 8,647 | 0.008235 | # -*- coding: utf-8 -*-
"""Transliteration data."""
from __future__ import absolute_import, division, print_function, unicode_literals
try: unicode
except NameError: unicode = str
import slp1
from transliteration.detect import TRANSLITERATION_SCHEME
from transliteration import devanagari
from transliteration.transli... | teMachine()
_SLP1_TO_IAST_STATE_MACHINE = transliterator.MakeStateMachine(
_SLP1To | Alphabet(_IAST_ALPHABET_LOWER))
_ITRANS_ALPHABET = (['a', 'aa', 'i', 'ii', 'u', 'uu', 'RRi', 'RRI',
'LLi', 'LLI', 'e', 'ai', 'o', 'au', 'M', 'H',
'k', 'kh', 'g', 'gh', '~N',
'ch', 'Ch', 'j', 'jh', '~n',
'T', 'Th', 'D', 'Dh', 'N',
... |
Coderhypo/namiya | nayami/route/post.py | Python | apache-2.0 | 3,039 | 0.000329 | from flask import render_template, request, abort, redirect, url_for
from datetime import datetime
from nayami.common.app import app
from nayami.common.auth import user_auth
from nayami.model.post import Post
@app.route('/', methods=['GET'])
def index_page():
return render_template('index.html')
@app.route('/p... |
return render_template('backdoor/reply_post.html', post=post)
posts = Post.get_all_unanswered_post()
return render_template('backdoor/list.html', posts=posts)
if request.method == 'POST':
| post_id = request.form.get("post_id")
content = request.form.get("content")
sender_email = request.form.get("sender_email")
post = Post.get_post_by_id(post_id)
if post:
post.reply(sender_email, content)
return redirect(url_for("back_door_page"))
@app.route('/<pa... |
zomux/deepy | deepy/layers/softmax3d.py | Python | mit | 409 | 0.00489 | # | !/usr/bin/env python
# -*- coding: utf-8 -*-
from layer import NeuralLayer
import theano
import theano.tensor as T
class Softmax3D(NeuralLayer):
def __init__(self):
super(Softmax3D, self).__init__("softmax")
def compute_tensor(self, x):
shape = x.shape
x = x.reshape((-1, shape[-1]))
... | r.reshape(shape) |
MD-Studio/MDStudio | mdstudio/mdstudio/api/schema.py | Python | apache-2.0 | 9,728 | 0.002673 | import json
import jsonschema
import os
import re
import six
from jsonschema import FormatChecker, Draft4Validator
from mdstudio.api.exception import RegisterException
from mdstudio.api.singleton import Singleton
from mdstudio.deferred.chainable import chainable
from mdstudio.deferred.return_value import return_value... | _claims_fi | le)
def to_schema(self):
return self.schema
@staticmethod
def flatten(session):
return True
class ResourceSchema(ISchema):
def __init__(self, uri, versions=None):
super(ResourceSchema, self).__init__()
uri_decomposition = re.match(r'([\w\-_]+)/([\w\-_]+)/([\w/\-_]+?)(... |
OCA/l10n-brazil | l10n_br_fiscal/tests/test_certificate.py | Python | agpl-3.0 | 4,074 | 0 | # Copyright 2019 Akretion - Renato Lima <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import timedelta
from odoo import fields
from odoo.exceptions import ValidationError
from odoo.tests import common
from odoo.tools.misc import format_date
from ..tools ... | ert_date_exp.year)
self.assertEqual(cert.date_expiration.month, self.cert_date_exp.month)
self.assertEqual(cert.date_expiration.day, self.cert_date_exp.day)
self.assertEqual(cert.name, self.cert_name)
self.assertEqual(cert.is_valid, True)
def test_certificate_wrong_password(self):
... | g password"""
with self.assertRaises(ValidationError):
self.certificate_model.create(
{
"type": "nf-e",
"subtype": "a1",
"password": "INVALID",
"file": self.certificate_valid,
}
... |
goofwear/Emby.Kodi | resources/lib/ReadEmbyDB.py | Python | gpl-2.0 | 15,756 | 0.008314 | # -*- coding: utf-8 -*-
#################################################################################################
# ReadEmbyDB
#################################################################################################
from DownloadUtils import DownloadUtils
class ReadEmbyDB():
doUtils = Download... | except: pass
else: # If list was longer than 49 items, we pulled the entire list so we need to sort
if not lenlist:
result = self.filterbyId(r | esult, itemList)
return result
def getMusicSongsTotal(self):
result = []
url = "{server}/mediabrowser/Users/{UserId}/Items?Index=1&Limit=1&Fields=Etag,Path,Genres,SortName,Studios,Writer,ProductionYear,Taglines,CommunityRating,OfficialRating,CumulativeRunTimeTicks,Metascore,AirTime,DateC... |
evernym/plenum | plenum/test/msgs.py | Python | apache-2.0 | 572 | 0 | from plenum.common.messages.fields import NonEmptyStringField
from plenum.common.messages.message_base import MessageBase
from plenum.common.messages.node_message_factory import node_message_factory
from pl | enum.common.util import randomString
def randomMsg():
return TestMsg('subject ' + randomString(),
'content ' + randomString())
class TestMsg(MessageBase):
typename = "TESTMSG"
schema = (
("subject", NonEmptyStringField()),
("cont | ent", NonEmptyStringField()),
)
node_message_factory.set_message_class(TestMsg)
|
nwokeo/supysonic | venv/lib/python2.7/site-packages/storm/zope/metaconfigure.py | Python | agpl-3.0 | 1,225 | 0.000816 | #
# Copyright (c) 2006, 2007 Canonical
#
# Written by Gustavo Niemeyer <[email protected]>
#
# This file is part of | Storm Object Relational Mapper.
#
# Storm is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published | by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# Storm 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 Lesser General... |
AlessandroZ/LaZagne | Windows/lazagne/softwares/memory/libkeepass/hbio.py | Python | lgpl-3.0 | 4,214 | 0.002373 | # -*- coding: utf-8 -*-
import hashlib
import io
import struct
# default from KeePass2 source
BLOCK_LENGTH = 1024 * 1024
try:
file_types = (file, io.IOBase)
except NameError:
file_types = (io.IOBase,)
# HEADER_LENGTH = 4+32+4
def read_int(stream, length):
try:
return struct.unpack('<I', stream.r... |
Read the next block and verify the data.
Raises an IOError if the hash does not match.
"""
index = read_int(block_stream, 4)
bhash = block_stream.read(32)
length = read_int(block_stream, 4)
if length > 0:
data = block_stream.read(length)
... | raise IOError('Block hash mismatch error.')
return bytes()
def write_block_stream(self, stream, block_length=BLOCK_LENGTH):
"""
Write all data in this buffer, starting at stream position 0, formatted
in hashed blocks to the given `stream`.
For example, writing da... |
OneDrive/onedrive-sdk-python | src/python2/request/item_request.py | Python | mit | 3,549 | 0.003663 | # -*- coding: utf-8 -*-
'''
# Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
#
# This file was generated and any changes will be overwritten.
'''
from ..request_base import RequestBase
from ..model.item import Ite... | [email protected]" in value._prop_dict:
next_page_link = value._prop_dict["[email protected]"]
value.children._next_page_link = next_page_link
if value.tags:
if "[email protected]" in value._prop_dict:
next_page_link =... | Link"]
value.tags._next_page_link = next_page_link
if value.thumbnails:
if "[email protected]" in value._prop_dict:
next_page_link = value._prop_dict["[email protected]"]
value.thumbnails._next_page_link = next_page_... |
mogria/rtsh | srv/model/unitfactory.py | Python | gpl-2.0 | 546 | 0.005495 | from mod | el.commonfactory import CommonFactory
from model.slaveunit import SlaveUnit
from model.squireunit import SquireUnit
from model.swordfighterunit import SwordfighterUnit
from model.archerunit import ArcherUnit
from model.cavalryunit import CavalryUnit
UNIT_TYPES = {
'slave': SlaveUnit,
'squire': SquireUnit,
... | CommonFactory("unit", unit_type, UNIT_TYPES, *args, **kwargs)
|
tsmrachel/remo | remo/profiles/migrations/0003_auto_20160921_1608.py | Python | bsd-3-clause | 610 | 0 | # -*- coding: utf-8 -*-
from __future__ im | port unicod | e_literals
from django.db import migrations, models
def forwards(apps, schema_editor):
"""Create Peers group."""
Group = apps.get_model('auth', 'Group')
Group.objects.create(name='Peers')
def backwards(apps, schema_editor):
"""Delete Peers group."""
Group = apps.get_model('auth', 'Group')
G... |
skarphed/skarphed | admin/installer/debian7_nginx/__init__.py | Python | agpl-3.0 | 6,232 | 0.011555 | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# © 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Skarphed.
#
# Skarphed is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as ... | bdomain':nginx_subdomain,
'domainlineterm':domainlineterm}
nginxconfresult = open(os.path.join(self.BUILDPATH,"nginx.conf"),"w")
nginxconfresult.write(nginxconf)
nginxconfresult.close()
self.status = 10
| gobject.idle_add(self.updated)
scv_config = {}
for key,val in self.data.items():
if key.startswith("core.") or key.startswith("db."):
if key == "db.name":
scv_config[key] = val+".fdb"
continue
scv_config[key] = v... |
JeffAbrahamson/UNA_compta | ha_transfer.py | Python | gpl-3.0 | 2,996 | 0.002004 | #!/usr/bin/python3
"""Sum helloasso CSV file for certain accounts.
Used for computing balance transfers to next fiscal year.t
"""
import argparse
import dateutil.parser as dp
import pandas as pd
import sys
from tabulate import tabulate
# We have several get_data() functions, as the format changes slightly
# from ca... | """
with open(config_filename, 'r') as config_fp:
config = eval(config_fp.read())
return config
def find_account(config, descr, sub_descr):
if descr not in config:
return 'ignore'
descr_account = config[descr]
if 'subdescr' in descr_account and sub_descr in d | escr_account['subdescr']:
return descr_account['subdescr'][sub_descr]
if 'default' in descr_account:
return descr_account['default']
return 'ignore'
def make_find_account(config):
def this_find_account(row):
ret = find_account(config, row['description'], row['sub_description']),
... |
aaalgo/owl | annotate/management/commands/import.py | Python | bsd-2-clause | 1,100 | 0.009091 | import sys
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError, transaction
from django.contrib.auth.models import User
from annotate.models import *
class Command(Ba | seCommand):
d | ef add_arguments(self, parser):
parser.add_argument('--run', action='store_true', default=False, help='')
pass
@transaction.atomic
def handle(self, *args, **options):
#hours = options['hours'] + 24 * options['days']
#check_and_import(hours, not options['run'], options['check'])
... |
plotly/dash | components/dash-core-components/tests/integration/input/test_input_and_state.py | Python | mit | 1,787 | 0 | import time
from multiprocessing import Value
from dash import Dash, Input, Output, State, dcc, html
import dash.testing.wait as wait
def test_state_and_inputs(dash_dcc):
app = Dash(__name__)
app.layout = html.Div(
[
dcc.Input(value="Initial Input", id="input"),
dcc.Input(valu... | l input
wait.until(lambda: call_count.value == 1, timeout=1)
assert dash_dcc.wait_for_text_to_equal(
"#output", 'input="Initial Input", state="Initial State"'
)
input_.send_keys("x")
wait.until(lambda: call_count.value == 2, timeout=1)
assert dash_dcc.wait_for_text_to_equal(
"#... | h_dcc.wait_for_text_to_equal(
"#output", 'input="Initial Inputx", state="Initial State"'
), "state value sshould not trigger callback"
input_.send_keys("y")
wait.until(lambda: call_count.value == 3, timeout=1)
assert dash_dcc.wait_for_text_to_equal(
"#output", 'input="Initial Inputxy",... |
Williams224/davinci-scripts | kstaretappipig/JobSubmit.py | Python | mit | 1,942 | 0.031411 | #!/usr/bin/env ganga
import getpass
from distutils.util import strtobool
polarity='MagDown'
datatype='MC'
substitution='None'
channel='11164031'
b=Job()
b.application=DaVinci(version="v36r5")
if datatype=='MC':
b.application.optsfile='NTupleMaker_{0}.py'.format(polarity)
if datatype=='Data':
if substitution... | b.splitter = SplitByFiles(filesPerJob=10)
if datatype=='MC':
b.splitter = SplitByFiles(filesPerJob=2)
#b.OutputSandbox=["stderr","stdout"]
b.backend=Dirac()
#b.submit()
queues.add(b.submit)
polarity='MagUp'
b2=Job()
b2.application=DaVinci(version="v36r5")
if datatype=='MC':
b2.application.optsfile='NTupl... | DNTupleMaker.py'
if substitution=='PimforKm':
b2.application.optsfile='DNTupleMaker_PimforKm.py'
b2.outputfiles=[DiracFile('Output.root')]
b2.inputdata = b2.application.readInputData('{0}_12_{1}_{2}.py'.format(datatype,channel,polarity))
if substitution=='None':
b2.comment='{0}_12_{1}_{2}'.format(dataty... |
athenajc/XideSDCC | ide/sim/sim_test_app.py | Python | gpl-2.0 | 5,140 | 0.018093 | import wx
import random
from sim_scope import ScopePanelList
#----------------------------------------------------------------------------------
class TestSim():
def __init__(self):
self.time_stamp = 0
self.pin_logs = {}
self.pins = ['RA0','RA1','RA2','RA3','RA4','RA5','RA6','RA7',
... | self.pin_logs
for i in range(8):
s = 'RB' + str(i)
p[s] = []
self.pin_out.append(s)
#p['RB0'] = [1,2,4,8,0x10,0x20,0x40,0x80,0xff, 0x11, 0x61]
#p['RB1'] = [0x11, 0x22, 0x33, 0x44, 0x55]
#p['RB2'] = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
... | -----------------------------------------------------------
def get_pin_log(self, pin):
log = self.pin_logs.get(pin, [])
return log
#---------------------------------------------------------------
def step(self):
time = self.time_stamp
for i in range(8):
bit ... |
saltstack/salt | tests/unit/utils/test_schema.py | Python | apache-2.0 | 94,904 | 0.001475 | # pylint: disable=function-redefined
import copy
import salt.utils.json
import salt.utils.schema as schema
import salt.utils.stringutils
import salt.utils.yaml
from salt.utils.versions import LooseVersion as _LooseVersion
from tests.support.unit import TestCase, skipIf
try:
import jsonschema
import jsonschema... | title="Personal Access Token",
description=(
"This is the API access token which can be generated "
"under the API/Application on your account"
),
required=True,
)
ssh_key_file = sch | ema.StringItem(
title="SSH Private Key",
description=(
"The path to an SSH private key which will be used "
"to authenticate on the deployed VMs"
),
)
ssh_key_names = schema.StringItem(
title... |
tmthydvnprt/quilt | quilt/Quilter.py | Python | mit | 18,778 | 0.004047 | """
quilt.Quilter
Object to stitch a page based on quilt
{: .lead}
1. use [quilt file](#quiltfile) to create quilt
2. replace all [patch files](#patchfile) by matching `patch#id` tags in quilt with a `patch/id.html` file
3. parses [page file](#pagefile) using the following format:
1. `key: value` page variable *h... | ),
"source" : page_file,
"output" : page_file.replace(self.config["pages"], self.config["output"]).replace('.md', '.html'),
"markdownlink" : os.path.basename(page_file),
"directory" : os.path.basename(os.path.dirname(page_file))
})
if self.confi... | tpath"], 'http://'+self.pagevars["domain"])
# update pagevars
if overrides:
self.pagevars.update(overrides)
self.pagevars["keywords"] = ','.join(self.pagevars["keywords"])
self.__do_debug = self.pagevars["output"] == DEBUG_FILE
# parse html and build soup
s... |
M4sse/chromium.src | native_client_sdk/src/build_tools/test_projects.py | Python | bsd-3-clause | 12,150 | 0.011193 | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import subprocess
import sys
import time
import build_projects
import build_version
import buildbot_comm... | ateToolchains(toolchains):
invalid_toolchains = set(toolchains) - set(ALL_TOOLCHAINS)
if invalid_toolchains:
buildbot_common.ErrorExit('Inval | id toolchain(s): %s' % (
', '.join(invalid_toolchains)))
def GetServingDirForProject(desc):
dest = desc['DEST']
path = os.path.join(pepperdir, *dest.split('/'))
return os.path.join(path, desc['NAME'])
def GetRepoServingDirForProject(desc):
# This differs from GetServingDirForProject, because it retu... |
akritichadda/K-AND | daniel/vis3DConnect.py | Python | mit | 4,715 | 0.018028 | import pandas as pd
import scipy.ndimage as ndi
import numpy as np
import time
import pyqtgraph as pg
import pyqtgraph.opengl as pgl
pg.mkQApp()
def vis3D(brain_array,inj_array,pad = 30,ds_factor=6):
# set up time variables
now = time.time()
now_start = now
view = vis3D_glassBrain(brain_arra... | ns(view,inj_array,ds_factor)
print "build injection volume %0.2f" % (time.time() - now); now = time.time()
view.show()
print "rendering %0.2f" % (time.time() - now); now = time.time()
print "total run time: %0.2f" % (time.time() - now_start)
return view
de | f vis3D_glassBrain(brain_array,pad,ds_factor):
# initialize the window
view = pgl.GLViewWidget()
# downsample the brain image using the ds_factor
img = brain_array[::ds_factor,::ds_factor,::ds_factor]
# do padding of the brain to avoid holes during rendering
pad_img = np.zeros(... |
valexandersaulys/airbnb_kaggle_contest | venv/lib/python3.4/site-packages/Theano-0.7.0-py3.4.egg/theano/d3viz/d3viz.py | Python | gpl-2.0 | 3,909 | 0.000256 | """Dynamic visualization of Theano graphs.
Author: Christof Angermueller <[email protected]>
"""
import os
import shutil
import re
from six import iteritems
from theano.d3viz.formatting import PyDotFormatter
__path__ = os.path.dirname(os.path.realpath(__file__))
def replace_patterns(x, replace):
"""Repl... | viz'
for d in ['js', 'css']:
dep = os.path.join(outdir, dst_deps, d)
if not os.path.exists(dep):
shutil.copytree(os.path.join(src_deps, d), dep)
else:
dst_deps = src_deps
# Replace patterns in template
replace = {
'%% JS_DIR %%': os.path.join(... | %': os.path.join(dst_deps, 'css'),
'%% DOT_GRAPH %%': dot_graph,
}
html = replace_patterns(template, replace)
# Write HTML file
with open(outfile, 'w') as f:
f.write(html)
def d3write(fct, path, *args, **kwargs):
"""Convert Theano graph to pydot graph and write to dot file.
P... |
fintech-circle/edx-platform | openedx/core/djangoapps/waffle_utils/tests/test_init.py | Python | agpl-3.0 | 2,228 | 0.004039 | """
Tests for waffle utils features.
"""
import ddt
from django.test import TestCase
from mock import patch
from opaque_keys.edx.keys import CourseKey
from waffle.testutils import override_flag
from request_cache. | middleware import RequestCache
from .. import CourseWaffleFlag, WaffleFlagNamespace
from ..models import WaffleFlagCourseOverrideModel
@ddt.ddt
class TestCourseWaffleFlag(TestCase):
"""
Tests the CourseWaffleFlag.
"""
NAMESPACE_NAME = "test_namespace"
FLAG_NAME = "test_flag"
NAMESPACED_FLAG_... | = CourseKey.from_string("edX/DemoX/Demo_Course")
TEST_NAMESPACE = WaffleFlagNamespace(NAMESPACE_NAME)
TEST_COURSE_FLAG = CourseWaffleFlag(TEST_NAMESPACE, FLAG_NAME)
@ddt.data(
{'course_override': WaffleFlagCourseOverrideModel.ALL_CHOICES.on, 'waffle_enabled': False, 'result': True},
{'cour... |
Assassinss/daily-artwork | src/worker.py | Python | gpl-3.0 | 229 | 0 | from src import cron
from src.api import | Api
api = Api()
def fetch_photo():
api.fetch_photo()
@cron.route('/worker', methods=['GET'])
def scheduler_worker():
fe | tch_photo()
return 'fetch photo...'
|
brainwane/zulip | zerver/data_import/hipchat_user.py | Python | apache-2.0 | 2,581 | 0 | from typing import Any, Dict, List
from django.utils.timezone import now as timezone_now
from zerver.data_import.import_util import build_user_profile
from zerver.models import UserProfile
class UserHandler:
'''
Our UserHandler class is a glorified wrapper
around the data that eventually goes into
z... | e map ids
to names for mentions.
We also sometimes need to build mirror
users on the fly.
'''
def __init__(self) -> None:
self.id_to_user_map: Dict[int, Dict[str, Any]] = dict()
self.name_to_mirror_user_map: Dict[str, Dict[str, Any]] = dict()
self.mirror_user_id = 1
de... | > None:
user_id = user['id']
self.id_to_user_map[user_id] = user
def get_user(self, user_id: int) -> Dict[str, Any]:
user = self.id_to_user_map[user_id]
return user
def get_mirror_user(self,
realm_id: int,
name: str) -> Dict[str, ... |
kursitet/edx-ora2 | openassessment/assessment/api/self.py | Python | agpl-3.0 | 12,139 | 0.001812 | """
Public interface for self-assessment.
"""
import logging
from django.db import DatabaseError, transaction
from dogapi import dog_stats_api
from submissions.api import get_submission_and_student, SubmissionNotFoundError
from openassessment.assessment.serializers import (
InvalidRubric, full_assessment_dict, rub... | t(
submission_uuid,
user_id,
options_selected,
criterion_feedback,
overall_feedback,
rubric_dict,
scored_at
)
_log_assessment(assessment, submission)
except InvalidRubric as ex:
msg = "Invalid rubric definiti... | logger.warning(msg, exc_info=True)
raise SelfAssessmentRequestError(msg)
except InvalidRubricSelection as ex:
msg = "Selected options do not match the rubric: " + str(ex)
logger.warning(msg, exc_info=True)
raise SelfAssessmentRequestError(msg)
except DatabaseError:
err... |
loandy/billy | billy/reports/bills.py | Python | bsd-3-clause | 8,433 | 0.000119 | import datetime
import logging
from collections import defaultdict
from billy.core import db
from billy.core import settings
from billy.utils import term_for_session
from billy.reports.utils import (update_common, get_quality_exceptions,
combine_reports)
logger = logging.getLogger('bi... | : 0,
'_sponsors_with_i | d_count': 0,
'sponsors_per_type': defaultdict(int),
'_subjects_count': 0,
'bills_per_subject': defaultdict(int),
'versionless_count': 0,
'version_count': 0,
'unmatched_sponsors': set(),
'progress_meter_gaps': set(),
}
def ... |
WayneKeenan/picraftzero | picraftzero/thirdparty/pimoroni/pantilthat/__init__.py | Python | mit | 1,293 | 0.003094 | from sys import exit, version_info
import logging
logger = logging.getLogger(__name__)
try:
from smbus import SMBus
except ImportError:
if version_info[0] < 3:
logger.warning("Falling back to mock SMBus. This library requires python-smbus. Install with: sudo apt-get install python-smbus")
elif ver... | ight_type
servo_one = pantilthat.servo_one
servo_pulse_max = pantilthat.servo_pulse_max
servo_pulse_min = pantilthat.servo_pulse_min
servo_two = pantilthat.servo_two
servo_enable = pantilthat.servo_enable
set_all = pantilthat.set_all
set_pixel = pantilthat.set_pixel
set_pixel_rgbw = pantilthat.set_pixel_rgbw
s... | ne
tilt = pantilthat.servo_two
|
moshthepitt/answers | template/settings.py | Python | mit | 6,081 | 0.000164 | """
Django settings for template project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... | uction secret!
SECRET_KEY = 'mgu70)6s2vl#66ymf-iz=i8z05q==adv@6^*6^$8@p$bp8v04c'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'suit',
# django
'django.contrib.admin',
'django.contrib.auth',
'django.c... | 'django.contrib.humanize',
# custom
'core',
'users',
'questions',
'answers',
'reviews',
'reports',
'saas',
# third party
'allauth',
'allauth.account',
# 'allauth.socialaccount',
# 'allauth.socialaccount.providers.facebook',
# 'allauth.socialaccount.providers.twi... |
sekikn/ambari | ambari-common/src/main/python/ambari_commons/repo_manager/apt_manager.py | Python | apache-2.0 | 13,082 | 0.010472 | """
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 this ... | ckages in the system except packages in REPO_URL_EXCLUDE
:type pkg_names list|set
:type repo_filter str|None
:return formatted list of packages
"""
packages = []
available_packages = self._available_packages_dict(pkg_names, repo_filter)
with shell.process_executor(self.properties.installe... | allback=self._executor_error_handler,
strategy=shell.ReaderStrategy.BufferedChunks) as output:
for package, version in AptParser.packages_installed_reader(output):
if package in available_packages:
packages.append(available_packages[package])
if package n... |
Gitweijie/first_project | networking_cisco/apps/saf/agent/topo_disc/topo_disc_constants.py | Python | apache-2.0 | 890 | 0 | # Copyright 2017 Cisco Systems, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | specific language governing permissions and limitations
# under the License.
#
# Topology Discovery constants:
# Query LLDP Daemo | n every 15 seconds.
PERIODIC_TASK_INTERVAL = 15
# This means a topology update message will be sent after every minute (15*4),
# even if there's no change in the parameters.
TOPO_DISC_SEND_THRESHOLD = 4
|
ANR-COMPASS/shesha | tests/pytest/rtc/test_rtcUFU.py | Python | gpl-3.0 | 12,177 | 0.003449 | ## @package shesha.tests
## @brief Tests the RTC module
## @author COMPASS Team <https://github.com/ANR-COMPASS>
## @version 5.2.1
## @date 2022/01/24
## @copyright GNU Lesser General Public License
#
# This file is part of COMPASS <https://anr-compass.github.io/compass/>
#
# Copyright (C) 2011-2022 C... | GPU acceleration
# The COMPASS platform was designed to meet the need of high-performance for the simulation of AO systems.
#
# The final product includes a software package for simulating all the critical subcomponents of AO,
# particularly in the context of the ELT and a real-time core based on several control app... | hitecture of the GPU, the COMPASS tool allows to achieve adequate execution speeds to
# conduct large simulation campaigns called to the ELT.
#
# The COMPASS platform can be used to carry a wide variety of simulations to both testspecific components
# of AO of the E-ELT (such as wavefront analysis device with a pyra... |
vince8290/dana | ui_files/samples.py | Python | gpl-3.0 | 11,728 | 0.004093 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'events.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
from collections import *
from functools import *
import os, glob
import pandas a... | self.edits[k][row_index].setObjectName(_fromUtf8("_".join(["edit", k, str(row_index)])))
self.edits[k][row_index].setText(str(r[k]))
self.edits[k][row_index].setFont(self.font_edits)
if k in ['time', 'date']:
self.edit... | ixedWidth(80)
self.gridLayout.addWidget(self.edits[k][row_index], ypos+1, xpos, 1, 1)
elif k in combo_list:
self.combobox[k][row_index] = QtGui.QComboBox(Dialog)
self.combobox[k][row_index].setObjectName(_fromUtf8("_".join(["combo", k, ... |
1orwell/proghelp | proghelp/events/admin.py | Python | mit | 94 | 0.010638 | from django.contrib import admin
from events.mode | ls import Event
a | dmin.site.register(Event)
|
fajoy/nova | nova/virt/baremetal/ipmi.py | Python | apache-2.0 | 8,800 | 0.000568 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# coding=utf-8
# Copyright 2012 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 NTT DOCOMO, INC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.... | ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Baremetal IPMI power manager.
"""
import os
import stat
import tempfile
from nova.exception import Inval | idParameterValue
from nova.openstack.common import cfg
from nova.openstack.common import log as logging
from nova import paths
from nova import utils
from nova.virt.baremetal import baremetal_states
from nova.virt.baremetal import base
from nova.virt.baremetal import utils as bm_utils
opts = [
cfg.StrOpt('terminal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.