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 |
|---|---|---|---|---|---|---|---|---|
guineawheek/Dozer | dozer/cogs/teams.py | Python | gpl-3.0 | 6,850 | 0.00365 | """Commands for making and seeing robotics team associations."""
import collections
import discord
from discord.ext.commands import BadArgument, guild_only
from ._utils import *
from ..asyncdb.orm import orm
from ..asyncdb import psqlt
# alter table team_numbers alter column team_number type text
class Teams(Cog):
... | n = segments[0]
for i, seg in enumerate(segments[1:], 1):
e.add_field(name=("more " * i).capitalize() + "users", value=seg)
await ctx.send(embed=e)
onteam.example_usage = """
`{prefix}onteam type team_number` - Returns a list of users associated with a given team type an... | team.command()
@guild_only()
async def top(self, ctx):
"""Show the top 10 teams by number of members in this guild."""
# adapted from the FRC Dozer's equivalent.
query = f"""SELECT team_type, team_number, count(*)
FROM {TeamNumbers.table_name()}
WHERE use... |
BrysonMcI/Skitter | API-Gateway/python/wsgi.py | Python | mit | 105 | 0 | """ simple wsgi | script for the gateway """
from app import APP
if __name__ == "__main__":
APP.run() | |
eevee/cocos2d-mirror | cocos/particle.py | Python | bsd-3-clause | 17,917 | 0.01239 | # ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2011 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the... | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE... | NCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Particle system engine'''
__docformat__ = 'restructuredtext'
import random
import pyglet
from p... |
newvem/pytz | pytz/zoneinfo/Africa/Lubumbashi.py | Python | mit | 385 | 0.01039 | '''tzi | nfo timezone information for Africa/Lubumbashi.'''
from pytz.tzinfo import StaticTzInfo
from pytz.tzinfo import memorized_timedelta as timedelta
class Lubumbashi(StaticTzInfo):
'''Africa/Lubumbashi timezone definition. See datetime.tzinfo for details'''
zone = 'Africa/Lubumbashi'
_utcoffset = timedelta(sec... | bashi = Lubumbashi()
|
robehickman/simple-http-file-sync | shttpfs3/storage/versioned_storage.py | Python | mit | 21,979 | 0.011102 | import json, hashlib, os, os.path, shutil
from collections import defaultdict
from datetime import datetime
from typing import List, Dict, Any, cast
from typing_extensions import TypedDict
import shttpfs3.common as sfs
from shttpfs3.storage.server_db import get_server_db_instance_for_thread
import pprint
#++++++++... | -> None:
if self.have_active_commit(): raise Exception()
# Possable optimisations
# Don't store GC log in DB
# Don't flush GC log
# Don't store active files in DB, don't update active files dynamically, but do it in one go during commit
| active_files = {}
head = self.get_head()
if head != 'root':
commit = self.read_commit_index_object(head)
active_files = self.flatten_dir_tree(self.read_dir_tree(commit['tree_root']))
sdb = get_server_db_instance_for_thread(self.base_path)
sdb.begin_commit... |
0x90/libnl | libnl/linux_private/netlink.py | Python | lgpl-2.1 | 10,685 | 0.001029 | """netlink.h.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/linux/netlink.h
This library 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 version 2.1
of the License.
"""
from libnl.misc import ... | ted by NLMSG_DONE
NLM_F_ACK = 4 # Reply with ack, with zero or error code
NLM_F_ECHO = 8 # Echo this request
NLM_F_DUMP_INTR = 16 # Dump was inconsistent due to sequence change
# Modifiers to GET request.
NLM_F_ROOT = 0x100 # Specify tree root.
NLM_F_MATCH = 0x200 # Return all matching.
NLM_F_ATOMIC = 0x400 # At... | 0 # Override existing.
NLM_F_EXCL = 0x200 # Do not touch, if it exists.
NLM_F_CREATE = 0x400 # Create, if it does not exist.
NLM_F_APPEND = 0x800 # Add to end of list.
class sockaddr_nl(Struct):
"""Netlink sockaddr class (C struct equivalent).
https://github.com/thom311/libnl/blob/libnl3_2_25/include/lin... |
zookeepr/zookeepr | zkpylons/tests/functional/test_event_type.py | Python | gpl-2.0 | 274 | 0.010949 | from | .crud_helper import CrudHelper
class TestEventType(CrudHelper):
def test_permissions(self, app, db_session):
CrudHelper.test_permissions(self, app, db_session, dont_get_pages='view')
def test_view(self): |
pass # No view page, block crud helper
|
MicrosoftGenomics/FaST-LMM | fastlmm/util/standardizer/__init__.py | Python | apache-2.0 | 2,365 | 0.014799 | from .Beta import *
from .Unit import *
#import warnings
#warnings.warn("This __init__.py is deprecated. Pysnptools includes newer version", DeprecationWarning)
def factory(s):
s = s.capitalize()
if s == "Unit" or s=="Unit()":
return Unit()
if s=="Beta":
return Beta()
i... | ps)
snp_sum = np.nansum(snps,axis=0)
n_obs_sum = (~imissX).sum(0)
snp_mean = (snp_sum*1.0)/n_obs_sum
snps -= snp_mean
snp_std = np.sqrt(np.nansum(snps**2, axis=0)/n_obs_sum)
# avoid div by 0 when standardizing
if snp_std.__contains__(0.0):
logging.warn("A least one s... | deviation is zero")
snp_std[snp_std == 0.0] = 1.0
snps /= snp_std
snps[imissX] = 0
if returnStats:
return snps,snp_mean,snp_std
return snps
def standardize_beta_python(snps, betaA, betaB):
'''
standardize snps with Beta prior
'''
N = snps.shape[0]
... |
marcsans/cnn-physics-perception | phy/lib/python2.7/site-packages/theano/tensor/nnet/conv3d2d.py | Python | mit | 12,138 | 0.000494 | import theano
from theano.gradient import DisconnectedType
from theano.gof import Op, Apply, TopoOptimizer
from theano import tensor
import theano.sandbox.cuda as cuda
from theano.tensor.opt import copy_stack_trace
def get_diagonal_subtensor_view(x, i0, i1):
"""
Helper function for DiagonalSubtensor and IncDi... |
def connection_pattern(self, node):
rval = [[True], [False], [False]]
return rval
diagonal_subtensor = DiagonalSubtensor(False)
class IncDiagonalSubtensor(Op):
"""
The gradient of DiagonalSubtensor.
"""
__props__ = ("inplace",)
def __str__ | (self):
if self.inplace:
return "%s{inplace}" % self.__class__.__name__
return "%s" % self.__class__.__name__
def __init__(self, inplace=False):
self.inplace = inplace
if inplace:
self.destroy_map = {0: [0]}
def make_node(self, x, i0, i1, amt):
_... |
amwelch/a10sdk-python | a10sdk/core/slb/slb_template_tcp.py | Python | apache-2.0 | 3,902 | 0.005894 | from a10sdk.common.A10BaseClass import A10BaseClass
class Tcp(A10BaseClass):
"""Class Description::
L4 TCP switch config.
Class tcp supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param initial_window_size: {"descriptio... | e: {"default": 0, "optional": true, "type": "number", "description": "keep connection alive if active traffic", "format": "flag"}
:param qos: {"description": "QOS level (number)", "format": "number", "type": "number", "maximum": 63, "minimum": 1, "optional": true}
:param name: {"description": "Fast TCP Template... | "}
:param reset_fwd: {"default": 0, "optional": true, "type": "number", "description": "send reset to server if error happens", "format": "flag"}
:param half_open_idle_timeout: {"description": "TCP Half Open Idle Timeout (sec), default off (half open idle timeout in second, default off)", "format": "number", "t... |
thiagof/treeio | treeio/identities/south_migrations/0003_related_accessentity.py | Python | mit | 12,940 | 0.00711 | # encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Migrate Cont... | ptr
contact.save()
def backwards(self, orm):
raise RuntimeError("Cannot reverse this migration.")
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': (... | ls.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name... |
grahesh/Stock-Market-Event-Analysis | Examples/Event Analysis/Half-Yearly End/Half_Year_End_Analysis.py | Python | bsd-3-clause | 4,522 | 0.017249 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 03 10:16:39 2013
@author: Grahesh
"""
import pandas
from qstkutil import DataAccess as da
import numpy as np
import math
import copy
import qstkutil.qsdateutil as du
import datetime as dt
import qstkutil.DataAccess as da
import qstkutil.tsutil as tsu
imp... | ('NSEData')
if verbose:
print __name__ + " reading data"
# Reading the Data
close = dataobj.get_data(timestamps, symbols, closefield)
# Com | pleting the Data - Removing the NaN values from the Matrix
close = (close.fillna(method='ffill')).fillna(method='backfill')
# Calculating Daily Returns for the Market
tsu.returnize0(close.values)
# Calculating the Returns of the Stock Relative to the Market
... |
davebrent/consyn | consyn/cli/__init__.py | Python | gpl-3.0 | 2,350 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2014, David Poulter
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | models import Base
from ..settings import get_settings
__all__ = ["configurator", "main"]
settings = get_settings(__name__)
COMMANDS = [
"add",
"ls",
" | rm",
"cluster",
"mosaic",
"show",
"config"
]
class Config(object):
def __init__(self):
self.database = None
self.debug = False
self.verbose = False
self.session = None
configurator = click.make_pass_decorator(Config, ensure=True)
@click.group()
@click.option("-... |
tatools/demo-python | demo_python_at/commons/printer.py | Python | apache-2.0 | 527 | 0 | from abc import ABC, abstractmethod
from demo_python_at.commons.message import | Message
class Printer(ABC):
"""Base class for all printers."""
@abstractmethod
def print(self, message: Message):
"""Abstract method for printing."""
pass
class StdoutPrinter(Printer):
"""Class that prints a message to console."""
def print(self, message: Message):
"""
... | """
print(message.data())
|
fanwenl/kindle-image | encryption/sha.py | Python | apache-2.0 | 119 | 0.008403 | import hashlib
f = open('file_pa | th', 'rb')
sh = hashlib.sha256()
| sh.update(f.read())
print(sh.hexdigest())
f.close() |
philanthropy-u/edx-platform | lms/djangoapps/grades/api/v1/tests/mixins.py | Python | agpl-3.0 | 4,459 | 0.00157 | """
Mixins classes being used by all test classes within this folder
"""
from datetime import datetime
from pytz import UTC
from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory
from openedx.core.djangoapps.content.course_overviews.tests.factories import CourseOverviewFactory
from student.tests.fac... |
self.other_student = UserFactory(password=self.password, username='other_student')
self._create_user_enrollments(self.st | udent, self.other_student)
@classmethod
def _create_test_course_with_default_grading_policy(cls, display_name, run):
"""
Utility method to create a course with a default grading policy
"""
course = CourseFactory.create(display_name=display_name, run=run)
_ = CourseOvervi... |
runozo/leaflet-adv-demo | run.py | Python | mit | 89 | 0 | from demo im | port app
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
| |
chubbymaggie/simuvex | simuvex/s_pcap.py | Python | bsd-2-clause | 2,173 | 0.005983 | import dpkt
import socket
import logging
l = logging.getLogger("simuvex.s_pcap")
class PCAP(object):
def __init__(self,path, ip_port_tup, init=True):
self.path = path
self.packet_num = 0
self.pos = 0
self.in_streams = []
self.out_streams = []
#self.in_buf = ''
... | :length]
self.pos += temp
else:
if (self.pos + length) >= plength:
rest = plength-self.pos
length = rest
self.pack | et_num += 1
packet_data = pdata[self.pos:plength]
if self.packet_num is not initial_packet:
self.pos = 0
return packet_data, length
def copy(self):
new_pcap = PCAP(self.path, (self.ip, self.port), init=False)
new_pcap.packet_num = self.packet_num
ne... |
Charlotte-Morgan/inasafe | safe/impact_function/postprocessors.py | Python | gpl-3.0 | 13,430 | 0 | # coding=utf-8
"""Postprocessors."""
# noinspection PyUnresolvedReferences
from qgis.core import QgsFeatureRequest
from safe.definitions.minimum_needs import minimum_needs_parameter
from safe.gis.vector.tools import (
create_field_from_definition, SizeCalculator)
from safe.processors import (
field_input_ty... | if value['value'] == layer_crs_input_value:
default_parameters[key] = layer.crs()
if value['value'] == size_c | alculator_input_value:
exposure = layer.keywords.get('exposure')
if not exposure:
keywords = layer.keywords.get('exposure_keywords')
exposure = keywords.get('exposure')
default_parameters[key... |
backbohne/docx-xslt | docxxslt/package.py | Python | mit | 1,498 | 0.000668 | from zipfile import ZipFile
class Package(object):
"""ZipFile wrapper to append/update/remove files from zip"""
def __init__(self, filename=None):
self.filename = filename
self.content = {}
def read(self, filename=None):
filename = filename or self.filename
with ZipFile(fi... | ts" % filename)
else:
self.content[filena | me] = content
def remove(self, filename):
if self.has(filename):
del self.content[filename]
else:
raise IndexError("%s does not exists" % filename)
|
ppizarror/korektor | bin/easyprocess/about.py | Python | gpl-2.0 | 83 | 0 | #!/usr/bin/e | nv python
# -*- coding: utf-8 -*-
"""
About
"""
__version__ = '0.2 | .2'
|
eltoncarr/tubular | tubular/scripts/merge_branch.py | Python | agpl-3.0 | 3,106 | 0.003542 | #! /usr/bin/env python3
"""
Command-line script to merge a branch.
"""
from __future__ import absolute_import
import io
from os import path
import sys
import logging
import yaml
import click
import click_log
# Add top-level module path to sys.path before importing tubular code.
sys.path.append(path.dirname(path.dirn... | ired=True
)
@click.option(
u'--target_branch',
help=u'Target branch into which the source branch will be merged in the PR.',
required=True
)
@click.option(
u'--fast_forward_only',
help=u'Either perform a fast-forward merge -or- fail if not possible.',
default=False,
is_flag | =True
)
@click.option(
u'--output_file',
help=u'File in which to write the script\'s YAML output',
default=u'target/merge_branch_sha.yml'
)
@click.option(
u'--reference-repo',
help=u'Path to a reference repo to use to speed up cloning',
)
@click_log.simple_verbosity_option(default=u'INFO')
@click_lo... |
numenta/nupic.research | src/nupic/research/frameworks/vernon/interfaces/__init__.py | Python | agpl-3.0 | 1,076 | 0 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this s | oftware code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WIT... | anty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ------------------------------... |
robotology-dependencies/urdfdom | urdf_parser_py/src/urdf_parser_py/xml_reflection/core.py | Python | bsd-3-clause | 16,161 | 0.03756 | from urdf_parser_py.xml_reflection.basics import *
import sys
import copy
# @todo Get rid of "import *"
# @todo Make this work with decorators
# Is this reflection or serialization? I think it's serialization...
# Rename?
# Do parent operations after, to allow child to 'override' parameters?
# Need to make sure tha... | ring Gazebo's SDF api
@param xml_var: | Xml name
@todo If the value_type is an object with a tag defined in it's reflection, allow it to act as the default tag name?
@param var: Python class variable name. By default it's the same as the XML name
"""
def __init__(self, xml_var, value_type, required = True, default = None, var = None):
self.xml_var = x... |
Juniper/tempest | tempest/tests/lib/common/test_cred_client.py | Python | apache-2.0 | 3,309 | 0 | # Copyright 2016 Hewlett Packard Enterprise Development LP
# 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 ... | ='desc', domain_id='fake_domain_id')
def test_delete_project(self):
self.creds_client.delete_project('fake_id')
self.projects_client.delete_project.assert | _called_once_with(
'fake_id')
|
florentchandelier/zipline | zipline/finance/trading.py | Python | apache-2.0 | 9,694 | 0.000309 | #
# Copyright 2016 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | l_benchmark=local_benchmark, environ=self.environ)
self.benchmark_returns, self.treasury_curves = load(
self.trading_calendar.day,
self.trading_calendar.schedule.index,
self.bm_symbol,
)
def write_data(self, **kwargs):
"""Write data into the | asset_db.
Parameters
----------
**kwargs
Forwarded to AssetDBWriter.write
"""
AssetDBWriter(self.engine).write(**kwargs)
class SimulationParameters(object):
def __init__(self, start_session, end_session,
trading_calendar,
capit... |
amdowell/python-brasil-2016 | samples/falcon/run.py | Python | mit | 517 | 0 | # encoding: utf-8
import falcon
from tornado import (httpserver, ioloop, wsgi)
from resources.hello import Hello
PORT = 5000
def r | outes():
# V1
routes = falcon.API()
routes.add_route('/api/v1/hello', Hello())
return routes
def execute(routes):
# Servidor WSGI
container = wsgi.WSGIContainer(routes)
http_server = httpserver.HTTPServer(container)
http_server.listen(PORT)
ioloop.IOLoop.instance().start()
if __... | execute(routes())
|
PanDAWMS/panda-bigmon-core | core/iDDS/DAGvisualization.py | Python | apache-2.0 | 2,510 | 0.001195 | from core.views import initRequest
from django.shortcuts import render_to_response
from django.utils.cache import patch_response_headers
import urllib.request
from urllib.error import HTTPError, URLError
from core.settings.config import IDDS_HOST
import json
SELECTION_CRITERIA = '/monitor_request_relation'
def query... | {'group': 'nodes',
'data': {'id': str(node),
}
}
| )
for edge in edges:
edges_dag_vis.append({
'group': 'edges',
'data': {
'id': str(edge['start']) + '_to_' + str(edge['finish']),
'target': str(edge['finish']),
'source': str(edge['star... |
hailongqiu/new-deepin-media-player | src/widget/notebook.py | Python | gpl-3.0 | 8,517 | 0.004043 | #! /usr/bin/ python
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Deepin, Inc.
# 2013 Hailong Qiu
#
# Author: Hailong Qiu <356752238@qq.com>
# Maintainer: Hailong Qiu <356752238@qq.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | how_check:
layout2_x = -self.allocation.width
else:
layout2_x = 0
allocation.x = layout2_x
allocation.y = 0 + self.title_h #self.layout2.allocation.y
allocation.width = self.allocation.width
allocation.height = self.allocation.height - se | lf.title_h
self.layout2.size_allocate(allocation)
if not self.layout_show_check:
layout1_x = - self.allocation.width
else:
layout1_x = 0
allocation.x = layout1_x
allocation.y = 0 + self.title_h #self.layout1.allocation.y
self.layout1.size_allocate(... |
rohitranjan1991/home-assistant | homeassistant/components/sensor/device_trigger.py | Python | mit | 7,736 | 0.001163 | """Provides device triggers for sensors."""
import voluptuous as vol
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.device_automation.exceptions import (
InvalidDeviceAutomationConfig,
)
from homeassistant.components.homeassistant.triggers import (
... | ,
SensorDeviceClass.VOLTAGE: [{CONF_TYPE: CONF_VOLTAGE}],
DEVICE_CLASS_NONE: [{CONF_TYPE: CONF_VALUE}],
}
TRIGGER_SCHEMA = vol.All(
DEVICE_TRIGGER_BASE_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF | _TYPE): vol.In(
[
CONF_APPARENT_POWER,
CONF_BATTERY_LEVEL,
CONF_CO,
CONF_CO2,
CONF_CURRENT,
CONF_ENERGY,
CONF_FREQUENCY,
CONF_GAS,
... |
moment-of-peace/EventForecast | rnn_text.py | Python | lgpl-3.0 | 9,696 | 0.007735 | import os
import pickle
import sys
import getopt
import numpy as np
from keras.models import Sequential
from keras.layers import Flatten, Dropout, Dense, Bidirectional
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
from keras.layers.embeddings import Embeddi... | length)+1, int(dim)), dtype = np.float64) # {index: [vector], ...}
line = f.readline()
i = 1
while line != '':
index = line.find(' ')
word = lin | e[:index]
vector = []
for e in line[index+1:].split(' '):
try:
vector.append(float(e))
except Exception:
print('float' + e)
vocab[word] = i
vec[i] = np.array(vector, dtype=np.float64)
... |
andymckay/addons-server | src/olympia/users/management/commands/activate_user.py | Python | bsd-3-clause | 1,391 | 0 | from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from olympia.access.models import Group, GroupUser
from olympia.users.models import UserProfile
class Command(BaseCommand):
"""Activate a registered user, and optionally set it as admin."""
args = 'email'
... | date(confirmationcode='')
admin_msg = ""
if set_admin:
| admin_msg = "admin "
GroupUser.objects.create(user=profile,
group=Group.objects.get(name='Admins'))
self.stdout.write("Done, you can now login with your %suser" %
admin_msg)
|
mkhuthir/catkin_ws | src/chessbot/devel/lib/python2.7/dist-packages/nasa_r2_common_msgs/msg/_JointStatusArray.py | Python | gpl-3.0 | 10,820 | 0.014325 | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from nasa_r2_common_msgs/JointStatusArray.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import nasa_r2_common_msgs.msg
import std_msgs.msg
class JointStatusArray(genpy.... | xcept TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize(self, str):
"""
unpack s | erialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
if self.header is None:
self.header = std_msgs.msg.Header()
if self.status is None:
self.status = None
end = 0
_x = self
start = end
end += 1... |
henryhallam/peregrine | peregrine/analysis/acquisition.py | Python | gpl-3.0 | 8,541 | 0.011357 | #!/usr/bin/env python
# Copyright (C) 2012 Swift Navigation Inc.
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
# EITHER EXPRESSED ... | ,
linestyle='dashed', color='black')
ax.text(0.01, 0.97, 'threshold = %.1f' % threshold,
horizontalalignment='left',
verticalalignment='top',
transform = ax.transAxes)
yticks = ax.get_yticks()
dist = np.abs(yticks - threshold).min()
if dist >= 0.25*(yticks[1] - yticks[... | threshold))
ax.set_xbound(-0.5, len(acq_results)-0.5)
ax.set_xlabel('PRN')
return ax
def peak_plot(powers, freqs, samples_per_code, code_length=1023.0):
"""
Visualise the peak in a table of acquisition correlation powers.
Display, in various ways, the peak in a 2D array of acquisition correlation
powe... |
ibex-team/ibex-lib | doc/conf.py | Python | lgpl-3.0 | 7,943 | 0.008057 | # -*- coding: utf-8 -*-
#
# IBEX documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 21 11:59:19 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | mt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
primary_domain = 'cpp'
# The reST default role (used for this markup: `text`) to use for a... | dd_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of t... |
Tinuqin/dynamic-graph-metrics | binaryreader.py | Python | mit | 470 | 0.012766 | #!/usr/bin/e | nv python
# encoding: utf-8
# Written by Aapo Kyrola
# http://stackoverflow.com/questions/28349805/extracting-plain-text-output-from-binary-file
import struct
from array import array as binarray
import sys
inputfile = sys.argv[1]
data = open(inputfile).read()
a = binarray('c')
a.fromstring(data)
s = struct.Struct(... | from(a, i * 4)[0]
print ("%d %f" % (i, x))
|
Marwe/particlemap | sample.py | Python | mit | 20 | 0 | __autho | r__ = 'tibi' | |
LLNL/spack | var/spack/repos/builtin/packages/minigan/package.py | Python | lgpl-2.1 | 1,105 | 0.00362 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
fr | om spack impo | rt *
class Minigan(Package):
"""miniGAN is a generative adversarial network code developed as part of the
Exascale Computing Project's (ECP) ExaLearn project at
Sandia National Laboratories."""
homepage = "https://github.com/SandiaMLMiniApps/miniGAN"
url = "https://github.com/SandiaMLMiniApp... |
TheBoegl/letsencrypt | letsencrypt/plugins/common_test.py | Python | apache-2.0 | 7,982 | 0.000125 | """Tests for letsencrypt.plugins.common."""
import unittest
import mock
import OpenSSL
from acme import challenges
from acme import jose
from letsencrypt import achallenges
from letsencrypt.tests import acme_util
from letsencrypt.tests import test_util
class NamespaceFunctionsTest(unittest.TestCase):
"""Tests... | , account_key=auth_key),
achallenges.KeyAuthorizationAnnotatedCha | llenge(
challb=acme_util.chall_to_challb(
challenges.TLSSNI01(token=b'token2'), "pending"),
domain="letsencrypt.demo", account_key=auth_key),
]
def setUp(self):
from letsencrypt.plugins.common import TLSSNI01
self.sni = TLSSNI01(configurator=mock.MagicMoc... |
palashahuja/pgmpy | pgmpy/tests/test_inference/test_Mplp.py | Python | mit | 4,901 | 0.006937 | import unittest
import numpy as np
from pgmpy.models import MarkovModel
from pgmpy.inference.mplp import Mplp
from pgmpy.factors import Factor
from pgmpy.readwrite import UAIReader
class TestMplp(unittest.TestCase):
def setUp(self):
reader_file = UAIReader('pgmpy/tests/test_readwrite/testdata/grid4x4_wit... | esult['L'], query_result['var_11'], places=4)
self.assertAlmostEqual(expected_result['M'], query_result['var_12'], places=4)
self.assertAlmostEqual(expected_result['N'], query_result['var_13'], places=4)
self.assertAlmostEqual(expected_result['O'], query_result['var_14'], places=4)
self.... | elf.mplp.get_integrality_gap()
self.assertAlmostEqual(64.59, int_gap, places=1)
class TightenTripletOn(TestMplp):
# Query when tighten triplet is ON
def test_query_tighten_triplet_on(self):
query_result = self.mplp.map_query(tighten_triplet=True)
# Results from the Sontag code for a m... |
amaozhao/algorithms | algorithms/union-find/count_islands.py | Python | mit | 2,094 | 0.000478 | """
A 2d grid map of m rows and n columns is initially filled with water.
We may perform an addLand operation which turns the water at position
(row, col) into a land. Given a list of positions to operate,
count the number of islands after each addLand operation.
An island is surrounded by water and is formed by connec... | ber of islands = 1
0 0 0
Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.
1 1 0
0 0 0 Number of islands = 1
0 0 0
Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.
1 1 0
0 0 1 Number of islands = 2
0 0 0
Operation #4: addLand(2, 1) turns the water at grid[2][1] into a la... | Number of islands = 3
0 1 0
"""
class Solution(object):
def num_islands2(self, m, n, positions):
ans = []
islands = Union()
for p in map(tuple, positions):
islands.add(p)
for dp in (0, 1), (0, -1), (1, 0), (-1, 0):
q = (p[0] + dp[0], p[1] + dp[1])... |
bespike/litecoin | contrib/testgen/gen_key_io_test_vectors.py | Python | mit | 9,388 | 0.004261 | #!/usr/bin/env python3
# Copyright (c) 2012-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Generate valid and invalid base58 address and private key test vectors.
Usage:
PYTHONPATH=../../t... | random(template[2]))
if no_data:
rv = bech32_encode(hrp, [])
else:
data = [witver] + convertbits(witprog, 8, 5)
if template[3] and not no_data:
if template[2] % 5 in {2, 4}:
data[-1] |= 1
else:
data.append(0)
rv = bech32_en... | CHARSET.replace(rv[i], '')) + rv[i + 1:]
if |
gustavla/self-supervision | selfsup/caffe.py | Python | bsd-3-clause | 7,096 | 0.002959 | from .util import DummyDict
from .util import tprint
import deepdish as dd
import numpy as np
# CAFFE WEIGHTS: O x I x H x W
# TFLOW WEIGHTS: H x W x I x O
def to_caffe(tfW, name=None, shape=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()):
assert conv_fc_transitionals is None or name is not No... | return tfW
else:
return cfW.T
def load_caffemodel(path, session, prefix='', ignore=set(),
conv_fc_ | transitionals=None, renamed_layers=DummyDict(),
color_layer='', verbose=False, pre_adjust_batch_norm=False):
import tensorflow as tf
def find_weights(name, which='weights'):
for tw in tf.trainable_variables():
if tw.name.split(':')[0] == name + '/' + which:
... |
rtucker-mozilla/mozilla_inventory | mozdns/models.py | Python | bsd-3-clause | 8,260 | 0 | from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
import mozdns
from mozdns.domain.models import Domain
from mozdns.view.models import View
from mozdns.mixins import ObjectUrlMixin, DisplayMixin
from mozdns.validation import validate_first_label, validate_name
from moz... | ose
to the user when they are creating and updateing an Object. This
function should be implemented in inheriting models and overriden to
provide additional fields. Tastypie ignores any relational fields on
the model. See the ModelResou | rce definitions for view and domain
fields.
"""
return ['fqdn', 'ttl', 'description', 'views']
def clean(self):
# The Nameserver and subclasses of BaseAddressRecord do not call this
# function
self.set_fqdn()
self.check_TLD_condition()
self.check_no_n... |
tmm1/pygments.rb | vendor/pygments-main/pygments/lexers/matlab.py | Python | mit | 31,893 | 0.00138 | # -*- coding: utf-8 -*-
"""
pygments.lexers.matlab
~~~~~~~~~~~~~~~~~~~~~~
Lexers for Matlab and related languages.
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import Lexer, RegexLe | xer, bygroups, default, words, \
do_insertions
from pygments.tok | en import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation, Generic, Whitespace
from pygments.lexers import _scilab_builtins
__all__ = ['MatlabLexer', 'MatlabSessionLexer', 'OctaveLexer', 'ScilabLexer']
class MatlabLexer(RegexLexer):
"""
For Matlab source code.
.. versionadded:... |
mdrasmus/summon | examples/18_summon.py | Python | gpl-2.0 | 2,904 | 0.017218 | #!/usr/bin/env python-i
# draws SUMMON logo
#
import math
import summon
from summon.core import *
from summon import shapes, colors
def interleave(a, b):
c = []
for i in xrange(0, len(a), 2):
c.extend(a[i:i+2] + b[i:i+2])
return c
def curve(x, y, start, end, radius, width):
p = shapes.arc_pa... | th(x, y, start, end, radius-width, 30)
return triangle_strip(*interleave(p, p2))
def draw_u(top, bottom, w, t):
return g | roup(shapes.box(-w,top, -w+t, bottom+w),
shapes.box(w,top, w-t, bottom+w),
curve(0, bottom+w, -math.pi, 0.0, w, t))
def draw_m(top, bottom, w, t):
return group(
translate(0, -2*w+t,
rotate(180,
draw_u(top, bottom, w, t))),... |
jhumphry/gazetteer_etl | gazetteer/fields.py | Python | gpl-2.0 | 3,587 | 0 | # gazetteer.fields
# Copyright 2016, James Humphry
# 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 progr... | e = 'DOUBLE PRECISION'
class TextField(GazetteerField):
'''A gazetteer field corresponding to the SQL type TEXT.'''
sql_type_name = 'TEXT'
class FixedTextField(GazetteerField):
'''A gazetteer field corresponding to the SQL type CHARACTER VARYING()
with a defined width.'''
d | ef __init__(self, field_name, width, sql_name='', nullable=True):
super().__init__(field_name, sql_name, nullable)
self.width = width
def generate_sql(self):
if self.nullable:
return self.sql_name + ' CHARACTER VARYING({})'.format(self.width)
else:
return sel... |
gemrb/gemrb | gemrb/GUIScripts/GUISONGS.py | Python | gpl-2.0 | 2,309 | 0.026851 | # GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# This program is free software; you can redistribute it and/or
# modify | it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTAB... |
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
#instead of credits, you can listen the songs of the game :)
import GemRB
import GameCheck
MovieWind... |
IndiciumSRL/wirecurly | wirecurly/configuration/node.py | Python | mpl-2.0 | 363 | 0.055096 | import logging
log = logging.getLogger(__name__)
__all__ = ['Node']
class Node(object):
'''
Node oject for acls
'''
def __init__(self,perm,add):
sup | er(Node, self).__init__()
self.attrs = {'type' : perm , 'cidr' : add}
def todict(self):
'''
| Create a dict so it can be converted/serialized
'''
return {'tag': 'node', 'attrs': self.attrs }
|
anhstudios/swganh | data/scripts/templates/object/tangible/component/armor/shared_base_armor_segment_enhancement.py | Python | mit | 504 | 0.043651 | ### | # NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/component/armor/shared_base_armor_segment_enhancement.iff"
result.attr... | ####
return result |
memoria-exorior/memoria | memoria/wsgi.py | Python | apache-2.0 | 97 | 0 | from memoria.app import create | _app
app = create_app()
if __name__ == "__main__":
app.run() | |
svohara/svo_util | src/svo_util/data_io.py | Python | unlicense | 12,678 | 0.013409 | '''
Created on Dec 10, 2012
@author: Stephen O'Hara
Utility functions for interacting with certain types
of data files.
'''
import os
import numpy as np
import svo_util
from StringIO import StringIO
import tokenize
find = np.nonzero #this is the matlab command
which = np.nonzero #this is the R command
def smart_spl... | et of integers. For regression data sets where | the "labels"
are continuous-valued numbers, set label_cols = None, and all
the csv fields will be loaded into the data matrix.
'''
self.datadir = datadir
self.csvfile = csvfile
self.label_cols = label_cols
self.label_dict = {} # key is label_col #, value is a lis... |
Som-Energia/heman | heman/config.py | Python | gpl-3.0 | 2,611 | 0.000383 | from __future__ import absolute_import
import logging
import os
from flask import Flask
from flask_pymongo import PyMongo
from raven.contrib.flask import Sentry
from heman.api import HemanAPI
api = HemanAPI(prefix='/api')
"""API object
"""
sentry = Sentry(logging=True, level=logging.ERROR)
"""Sentry object
"""
mong... | '
configure_logging(app)
configure_sentry(app)
configure_api(app)
configure_mongodb(app)
configure_login(app)
return app
def configure_api(app):
"""Configure API Endpoints.
"""
from heman.api.cch import resources as cch_resources
from heman.api.infoenergia import | resources as infoenergia_resources
from heman.api import ApiCatchall
# Add CCHFact resources
for resource in cch_resources:
api.add_resource(*resource)
# Add InfoEnergia resources
for resource in infoenergia_resources:
api.add_resource(*resource)
api.add_resource(ApiCatchall,... |
rahulunair/nova | nova/conf/keystone.py | Python | apache-2.0 | 1,257 | 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
# ... | " BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneauth1 import loading as | ks_loading
from oslo_config import cfg
from nova.conf import utils as confutils
DEFAULT_SERVICE_TYPE = 'identity'
keystone_group = cfg.OptGroup(
'keystone',
title='Keystone Options',
help='Configuration options for the identity service')
def register_opts(conf):
conf.register_group(keystone_group)... |
uppsaladatavetare/foobar-api | src/wallet/migrations/0007_auto_20170218_2034.py | Python | mit | 880 | 0.002273 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-18 20:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('wallet', '0006_auto_20170130_1... | field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='wallet.WalletTransaction'),
),
migrations.AlterField(
model_name='wallettransaction',
name='date_created',
field=models.DateTimeField(blank=True, defaul | t=django.utils.timezone.now, editable=False, null=True, verbose_name='date created'),
),
]
|
seLain/mattermost_bot | tests/behavior_tests/run_bot.py | Python | mit | 701 | 0.00428 | #!/usr/bin/env python
from mattermost_bot.bot import Bot, PluginsManager
from mattermost_bot.mattermost import MattermostClient
from mattermost_bot.dispatcher import MessageDispatcher
import bot_settings
class LocalBot(Bot):
def __init__(self):
self._client = MattermostClient(
bot_settings.BOT... | self._dispatcher = MessageDispatcher(self._client, self._plugins)
def main():
bot = LocalBot()
bot.run()
| if __name__ == '__main__':
main()
|
speccy88/SSD1306_Edison | example1_image.py | Python | mit | 351 | 0.008547 | import SSD1306
import Image, ImageFilter
disp = SSD1306.SSD1306_128_64()
disp.begin()
disp | .clear()
disp.display()
image = Image.open('edison.png')
image = image.resize((128,64))
#image = image.filter(ImageFilter.SHARPEN)
image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)
image = image.convert('1')
disp.image(image)
disp.display()
disp.invert( | )
|
harshk360/yantra_shiksha | hw8/cifar/enhanced/cifar10_eval.py | Python | gpl-3.0 | 5,485 | 0.006746 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | .in_top_k(logits, labels, 1)
# Restore the moving average versi | on of the learned variables for eval.
variable_averages = tf.train.ExponentialMovingAverage(
cifar10.MOVING_AVERAGE_DECAY)
variables_to_restore = variable_averages.variables_to_restore()
saver = tf.train.Saver(variables_to_restore)
# Build the summary operation based on the TF collection of Sum... |
ElementsProject/elements | test/functional/rpc_txoutproof.py | Python | mit | 6,163 | 0.003894 | #!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test gettxoutproof and verifytxoutproof RPCs."""
from test_framework.messages import CMerkleBlock, Fro... | est_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
from test_framework.wallet import MiniWallet
class MerkleBlockTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_a... | odes[0])
# Add enough mature utxos to the wallet, so that all txs spend confirmed coins
miniwallet.generate(5)
self.nodes[0].generate(100)
self.sync_all()
chain_height = self.nodes[1].getblockcount()
assert_equal(chain_height, 105)
txid1 = miniwallet.send_self_t... |
kavigupta/61a-analysis | src/ocr.py | Python | gpl-3.0 | 1,475 | 0.002712 | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import ed | itdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_ | distance=1, min_nonclassify_distance=3):
"""
Runs an OCR classifier on a given image file, drawing from a dictionary
"""
read = image_to_string(Image.open(image)).lower()
result = None
for person in people_class:
dist = editdistance.eval(person, read)
if dist <= max_classify_dist... |
weechat/weechat.org | weechat/context_processors.py | Python | gpl-3.0 | 1,229 | 0 | #
# Copyright (C) 2003-2022 Sébastien Helleu <flashcode@flashtux.org>
#
# This file is part of WeeChat.org.
#
# WeeChat.org is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
#... | GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""Context processors."""
from django.conf import settings
def theme(request):
"""Add theme variables in context."""
user_theme = request.GET.get(
'theme',
request.COOKIES.get('theme', settin... | EMES:
user_theme = settings.THEMES[0]
other_themes = [name for name in settings.THEMES if name != user_theme]
return {
'theme': user_theme,
'other_themes': other_themes,
}
|
deryckh/dcuolfg | dcuolfg/missions/models.py | Python | lgpl-3.0 | 2,609 | 0 | # Copyright 2012 Deryck Hodge. This software is licensed under the
# GNU Lesser General Public License version 3 (see the file LICENSE).
"""
Models for missions in DCUO LFG.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from dcuolfg.missions.managers import MissionManager
... | OICES = (
(0, 'Normal'),
(1, 'T1'),
(2, 'T2'),
)
MISSION_NUM_PLAYER_CHOICES = (
(2, '2'),
(4, '4'),
| (5, '5'),
(8, '8'),
)
mission_type = models.IntegerField(
_('mission type'), choices=MISSION_TYPE_CHOICES, default=1)
mode = models.IntegerField(
_('mode'), blank=True, null=True, choices=MISSION_MODE_CHOICES)
name = models.CharField(_('name'), max_length=100)
slug =... |
PhonologicalCorpusTools/PolyglotDB | polyglotdb/acoustics/pitch/base.py | Python | mit | 10,009 | 0.003397 | import math
from datetime import datetime
from conch import analyze_segments
from conch.analysis.segments import SegmentMapping
from .helper import generate_pitch_function
from ..segments import generate_utterance_segments
from ...exceptions import SpeakerAttributeError
from ..classes import Track, TimePoint
from ..... | lence_threshold': 0.03,
# 'voicing_threshold': 0.45, 'octave_cost': 0.01, 'octave_jump_cost': 0.35,
# 'voiced_unvoiced_cost': 0.14}
elif source == 'reaper':
path = corpus_context.config.reaper_path
# kwargs = None
pitch_function = generate_pitch_function(source,... | ontext.hierarchy.acoustics:
corpus_context.hierarchy.add_acoustic_properties(corpus_context, 'pitch', [('F0', float)])
corpus_context.encode_hierarchy()
if algorithm == 'speaker_adjusted':
speaker_data = {}
if call_back is not None:
call_back('Getting original speaker mea... |
florentmercier/BtoVLE | src/main.py | Python | gpl-2.0 | 1,659 | 0.024714 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# sans titre.py
#
# Copyright 2013 Florent Mercier <contact@florentmercier.com>
#
# 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 ... | nalTransition import *
from ExternalTransition import *
from Observation import *
from Event import *
from strings import *
def main():
# MAN
if (len(sys.argv)<3):
print BTOVLE_MAN
sys.exit(0);
# Opening project:
cwd = os.path.split(sys.argv[0])[0]
projectName = os.path.basename(sys.argv[1])
path =... | ),path)
os.chdir(path)
Namespace(sys.argv[1], sys.argv[2]).write()
if __name__ == '__main__':
main()
|
a13m/ansible | v2/ansible/executor/task_executor.py | Python | gpl-3.0 | 16,471 | 0.004432 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | self._connection = self._get_connection(variables)
self._handler = self._get_action_handler(connection=self._connection)
# Evaluate the conditional (if any) for this task, which we do before running
# the final task post-validation. We do this before the post validation due to
... | variable not being present which would otherwise cause validation to fail
if not self._task.evaluate_conditional(variables):
debug("when evaulation failed, skipping this task")
return dict(changed=False, skipped=True, skip_reason='Conditional check failed')
# Now we do final val... |
kjemmett/TARGet | bindings/python/dionysus/viewer/diagram.py | Python | gpl-3.0 | 5,443 | 0.009186 | from PyQt4 import QtGui, QtCore
from math import fabs
class DiagramPoint(QtGui.QGraphicsEllipseItem):
def __init__(self,x,y, p, infty = False, color = 0):
super(QtGui.QGraphicsEllipseItem, self).__init__()
c = self.color(color)
self.setBrush(QtGui.QBrush(c[0]))
se... | item = DiagramPoint(x,y,p, infty = True, color = i)
else:
item = DiagramPoint(x,y,p, color = i)
self.scene.addItem(item)
# Flip y-axis
self.scale(1, -1)
# Set the correct view
rect = self.scene.itemsBoundingRect()
... | panStartX = event.x()
self._panStartY = event.y()
self.setCursor(QtCore.Qt.ClosedHandCursor)
event.accept()
else:
p = self.mapToScene(event.pos())
item = self.scene.itemAt(p)
if isinstance(item, DiagramPoint):
self.selection... |
unique-horn/ppap | ppap/layers/HyperNetwork_max.py | Python | gpl-3.0 | 4,797 | 0.003961 | """
This is an extension of the HyperNetwork, where the layer specific input z's
will be conditioned on the input. We first find the max of the input across
the feature channel, then we project this reduced input to the dimension of
z's, which is 4 here.
"""
import keras.backend as K
from keras.engine.topology import L... | self, input_shape):
rows = input_shape[2]
cols = input_shape[3]
rows = conv_output_length(rows, self.weight_shape[0],
self.border_mode, self.strides[0])
cols = conv_output_length(cols, self.weight_shape[1],
self.border_mode, self.strides[1])
... |
class HyperNetwork_gen(object):
"""
Simple feed forward generator
Doesn't take any explicit input
"""
def __init__(self,
input_channels,
rows, cols,
output_shape,
num_filters,
hidden_dim,
init="glorot_uniform"):
"... |
DPRL/CROHME_2014 | src/symbol_classifier.py | Python | gpl-3.0 | 3,883 | 0.011589 | ## DPRL CROHME 2014
## Copyright (c) 2013-2014 Lei Hu, Kenny Davila, Francisco Alvaro, Richard Zanibbi
##
## This file is part of DPRL CROHME 2014.
| ##
## DPRL CROHME 2014 is free software:
## you can redistribute it and/or modify it under the terms of the GNU
## General Public License as published by the Free Software Foundation,
## either version 3 of the License, or (at your option) any later version.
##
## DPRL CROHME | 2014 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
#... |
kartotherian/meddo | get-external-data.py | Python | mit | 9,549 | 0.010786 | #!/usr/bin/env python3
# This script is designed to load quasi-static data into a PostGIS database for
# rendering maps. It differs from the usual scripts to do this in that it is
# designed to take its configuration from a file rather than be a series of
# shell commands, and consideration has been given to doing the ... | ame, conn, config["settings"]["temp_schema"], config["settings"]["schema"], config["settings"]["metadata_table"])
this_table.clean_temp()
if not opts.force:
headers = {'If-Modified-Since': this_table.last_modified()}
else:
headers = {}
download = s.get(source["url"]... | Last-Modified" in download.headers:
new_last_modified = download.headers["Last-Modified"]
else:
new_last_modified = None
if "archive" in source and source["archive"]["format"] == "zip":
zip = zipfile.ZipFile(io.BytesIO(download.content))
for member in ... |
yuanbaowen521/tadbit | _pytadbit/utils/three_dim_stats.py | Python | gpl-3.0 | 19,120 | 0.002929 | """
30 Oct 2013
"""
from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper
from pytadbit.consistency import consistency_wrapper
from itertools import combinations
import numpy as np
from math import pi, sqrt, cos, sin, acos
def generate_sphere_points(n=100):
"""
Returns list of 3d coordinates of points on a sp... | tes accordin | g to the center of mass
:param x: list of x coordinates
:param y: list of y coordinates
:param z: list of z coordinates
"""
xm, ym, zm = get_center_of_mass(x, y, z, zeros)
for i in xrange(len(x)):
x[i] -= xm
y[i] -= ym
z[i] -= zm
# def generate_circle_points(x, y, ... |
tystr/mongodb-replication-status | mongodb_replication_status.py | Python | mit | 6,156 | 0.004224 | #!/usr/bin/env python
# mongodb_replicaset_status.py
# Author: Tyler Stroud <ststroud@gmail.com>
# Date: 2012-11-06
"""
This script monitors replication status of a replicaset
"""
from daemon import runner
import logging
from pymongo import Connection
from pymongo.errors import AutoReconnect
from time import sleep
im... | (message)s'))
self.logger.addHandler(self.logger_handler)
def set_notifier(self, notifier):
assert isinstance(notifier, Notifier), ('"notifier" must be an instance'
| 'of "Notifier"')
self.notifier = notifier
def get_members(self):
""" Connect to the primary member and refresh the replica set status """
if self.last_primary is not None:
connection = self.get_connection(self.last_primary)
if connec... |
kouroshparsa/iis_bridge | iis_bridge/config.py | Python | gpl-2.0 | 2,094 | 0.004298 | """
This module is used for common operations
as well as global variables
:copyright: (c) 2014 by Kourosh Parsa.
"""
import os
import subprocess
import platform
IIS_HOME = "%s\\Windows\\System32\\inetsrv" % os.getenv("SYSTEMDRIVE")
APP_CMD = "%s\\appcmd.exe" % IIS_HOME
DOCROOT = "%s\\inetpub\\wwwroot" % os... | returns the stdout as string
cmd: string - command to run
errMsg: string (default=None) - the error message to display
"""
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, err = proc.communicate()
if type(output) == bytes:
output = outpu | t.decode(encoding='UTF-8')
if "[Error]" in output or proc.returncode != 0:
if errMsg:
raise Exception(errMsg)
else:
raise Exception("%s\r\n%s" % (output, err))
return output
|
tasercake/Crypto_Algotrader | crizzle/patterns/__init__.py | Python | mit | 398 | 0.002513 | from crizzle.patterns.memoize import memoize
from crizzle.patterns.observer import Obse | rvable, Observer
from crizzle.patterns.singleton import Singleto | n
from crizzle.patterns.deprecated import deprecated
from crizzle.patterns.value_checking import assert_none, assert_not_none, assert_in, assert_type, assert_equal
from crizzle.patterns.graph import DiGraph
from crizzle.patterns import conversion
|
mmottahedi/neuralnilm_prototype | scripts/e470.py | Python | mit | 7,017 | 0.005558 | from __future__ import print_function, division
import matplotlib
import logging
from sys import stdout
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import (Net, RealApplianceSource,
BLSTMLayer, DimshuffleLayer,
Bidirectiona... | pe': DenseLayer,
'num_units': seq_length,
'nonlinearity': rectify
},
{
'label': 'dense2',
'type': DenseLayer | ,
'num_units': 128,
'nonlinearity': rectify
},
{
'label': 'dense3',
'type': DenseLayer,
'num_units': seq_length,
'nonlinearity': rectify
},
{
'type': DenseLayer,
'num_units': (seq_length - 3) ... |
flavoi/diventi | diventi/ebooks/migrations/0121_auto_20201005_2211.py | Python | apache-2.0 | 834 | 0.003597 | # Generated by Django 2.2.16 on 2020-10-05 20:11
import ckeditor.fie | lds
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ebooks', '0120_auto_20201005_1453'),
]
operations = [
mig | rations.AlterField(
model_name='book',
name='summary',
field=ckeditor.fields.RichTextField(blank=True, verbose_name='summary'),
),
migrations.AlterField(
model_name='book',
name='summary_en',
field=ckeditor.fields.RichTextField(blan... |
jdemel/gnuradio | gnuradio-runtime/python/gnuradio/gr/qa_uncaught_exception.py | Python | gpl-3.0 | 2,500 | 0 | #!/usr/bin/env python
#
# Copyright 2018 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr, gr_unittest, blocks
from multiprocessing import Process
import numpy
# This block just exists to pass data through and throw an excepti... | sink_2 = blocks.null_sink(gr.sizeof_gr_complex)
tb.connect(src, e_block_1)
tb.connect(src, e_bl | ock_2)
tb.connect(e_block_1, sink_1)
tb.connect(e_block_2, sink_2)
tb.run()
class test_uncaught_exception(gr_unittest.TestCase):
def test_exception_throw_uncaught(self):
# Test to ensure that throwing an exception causes the
# process running top_block to exit
p = Process(targ... |
googleads/googleads-shopping-samples | python/shopping/content/accounts/insert.py | Python | apache-2.0 | 1,326 | 0.008296 | #!/usr/bin/python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | erchantId']
common.check_mca(config, True)
name = 'account%s' % common.get_unique_id()
account = {'name': name, 'websiteUrl': 'https://%s.example.com/' % name}
# Add account.
request = service | .accounts().insert(merchantId=merchant_id, body=account)
result = request.execute()
print('Created sub-account ID %s for MCA %d.' % (result['id'], merchant_id))
if __name__ == '__main__':
main(sys.argv)
|
mjpbaywolf/plugin.video.wwen | resources/wwe.py | Python | gpl-3.0 | 18,159 | 0.002478 | import re
from urllib import unquote
import requests
from xml.dom.minidom import parseString
PRE_LOGIN_URL = "https://secure.net.wwe.com/enterworkflow.do?flowId=account.login"
LOGIN_URL = "https://secure.net.wwe.com/workflow.do"
LOGOUT_URL = "https://secure.net.wwe.com/enterworkflow.do?flowId=registration.logout"
VID... | live_media_state'] == 'MEDIA_ON':
live_stream.item_type = 'episode'
live_stream.show_name = i['show_name']
live_stream.name = 'LIVE: ' + i['title']
live_stream.title = i['title']
live_stream.media_id = i['media_playback_ids']['live']['conte... | umbnail_scenarios']['35']
live_stream.fan_art = i['thumbnail_scenarios']['67']
live_stream.banner = i['thumbnail_scenarios']['63']
live_stream.description = i['big_blurb']
live_stream.air_date = i['dates_and_times']['air_date_gmt']
live_str... |
LucidAi/nlcd | nlcd/wsgi.py | Python | mit | 221 | 0.004525 | # coding: utf-8
# Aut | hor: Vova Zaytsev <zaytsev@usc.edu>
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nlcd.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application( | )
|
frePPLe/frePPLe | freppledb/input/migrations/0020_buffer_owner.py | Python | agpl-3.0 | 1,109 | 0 | #
# Copyright (C) 2017 by frePPLe bv
#
# This library 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 library 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 Affero
# General Public License for more details.
#
# You should have received a cop... | GNU Affero General Public
# License along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("input", "0019_available")]
operations = [
migrations.RemoveField(model_name="buffer", name="lft"),
... |
waltherg/PLoSPy | setup.py | Python | bsd-3-clause | 555 | 0 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
|
kargs = {}
kargs['name'] = 'PLoSPy'
kargs['version'] = ''
kargs['author'] = 'Georg R Walther'
kargs['author_email'] = 'contact@georg.io'
kargs['packages'] = ['plospy']
kargs['package_dir'] = {'plospy': 'plospy'}
kargs['url'] = 'http://georg.io'
kargs['license'] = 'BSD'
kargs['description'] = 'A library for handling P... | up']
setup(**kargs)
|
CarlFK/wafer | wafer/schedule/south_migrations/0003_auto__add_day__add_field_slot_day__add_field_slot__order__chg_field_sl.py | Python | isc | 11,509 | 0.007386 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Day'
db.create_table(u'schedule_day', (
(u'id... | u'schedule.day': {
'Meta': {'ordering': "['date']", 'object_name': 'Day'},
'date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'schedule.scheduleitem':... | me': 'ScheduleItem'},
'details': ('wafer.snippets.markdown_field.MarkdownTextField', [], {'blank': 'True', 'allow_html': 'False'}),
'details_html': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'n... |
EdDev/vdsm | lib/vdsm/v2v.py | Python | gpl-2.0 | 48,122 | 0.000062 | # Copyright 2014-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... | cmdutils
from vdsm.common.define import errCode, doneCode
from vdsm.common import response
from vdsm.common import zombiereaper
from vdsm.common.compat import CPopen
from vdsm.common.logutils import traceback
from vdsm.common.time import monotonic_time
from vdsm.constants import P_VDSM_LOG, P_VDSM_RUN, EXT_KVM_2_OVIRT
... |
from vdsm import password
from vdsm.utils import terminating, NICENESS, IOCLASS
try:
import ovirt_imageio_common
except ImportError:
ovirt_imageio_common = None
_lock = threading.Lock()
_jobs = {}
_V2V_DIR = os.path.join(P_VDSM_RUN, 'v2v')
_LOG_DIR = os.path.join(P_VDSM_LOG, 'import')
_VIRT_V2V = cmdutils.... |
davidgutierrez/HeartRatePatterns | Python/NMF.py | Python | gpl-3.0 | 3,873 | 0.00672 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 19 00:50:49 2017
Utils for calculating the NMF
@author: David Gutierrez
"""
from sklearn.decomposition import NMF
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import sys
import os
sys.path.append(os.path.abspath("/home/scidb/Heart... | on)+1)
maxperson = max(pearson)
indxperson = pearson.index(maxperson)
plt.subplot(111)
plt.plot(leng, pearson, lw=2)
plt.annotate('maximo ('+str(maxperson)+","+str(indxperson+2)+")",
xy=(indxperson, maxperson),
xytext=(indxperson+5, maxperson-0.02),
... | t.xlabel('Valor de k en NMF')
plt.show()
def plot_error(title, pearson):
leng = range(2, len(pearson)+2)
plt.subplot(111)
plt.plot(leng, pearson, lw=2)
plt.title(title)
plt.xlabel('Valor de k en NMF')
plt.show()
def find_best_NMF(patients, survived):
fig_size = [16, 4]
plt.rcParams... |
jjgomera/pychemqt | lib/EoS/Cubic/PT.py | Python | gpl-3.0 | 7,861 | 0 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com>
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 Softwar... | N are compound specific parameters available for
several co | mpounds from [2]_. In compound with no parameters available use
the SRK original temperature dependence:
.. math::
\alpha^{0.5} = 1 + F\left(1-Tr^{0.5}\right)\\
Examples
--------
Example 4.3 from [4]_, Propane saturated at 300K
>>> from lib.mezcla import Mezcla
>>> mix = Mezcla(5,... |
mbrondani/django-agenda | agenda/templatetags/next_previous.py | Python | gpl-3.0 | 2,732 | 0.007687 | import logging
from django import template
register = template.Library()
@register.tag(name="previous")
def do_previous(parser, token):
# previous in <list> from <object> as < | previous_object>
bits = token.contents.split()
if len(bits) != 7:
raise template.TemplateSyntaxError, "%r takes six arguments" % | bits[0]
return PreviousNode(bits[2], bits[4], bits[6])
def get_previous(object_list, object_current):
logging.debug('Finding previous of %s in %s' % (object_current, object_list))
assert object_list.contains(object_current)
index = object_list.index(object_current)
if index == 0:
... |
tacaswell/pyOlog | setup.py | Python | mit | 640 | 0 | '''
Copyright (c) 2010 Brookhaven National Laboratory
All rights reserved. Use is subject to license terms and conditions.
Created on Jan 10, 2013
@author: shroffk
'''
from setuptools import setup
setup(name='pyOlog',
version='0.3.0',
description='Python Olog Client Lib',
author='Kunal Shroff',
... | 3 (>=1.7.1)'],
entry_points={'console_scripts': [
'olog | = pyOlog.cli:main'],
'gui_scripts': [
'ologgui = pyOlog.gui:main']}
)
|
kvas-it/cli-mock | tests/conftest.py | Python | mit | 1,537 | 0 | import os
import py
import pytest
@pytest.fixture()
def logfile(tmpdir):
return tmpdir.join('log.txt')
@pytest.fixture()
def testlog():
datadir = py.path.local(os.path.dirname(__file__)).join('data')
return datadir.join('log.txt')
@pytest.fixture()
def creplay(script_runner, tmpdir, testlog):
def... | ner.run('crecord', *crecord_args, **kw)
try:
print(logfile.read()) # For test debugging.
except IOError:
print('-- no logfile produced\n-- stderr:')
print(ret.stderr)
return ret
return crecord
@pytest.fixture | ()
def pyscript(tmpdir):
script = tmpdir.join('script.py')
script.write('')
script.chmod(0o777)
return script
|
xuru/pyvisdk | pyvisdk/do/virtual_serial_port_pipe_backing_info.py | Python | mit | 1,296 | 0.009259 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VirtualSerialPortPipeBackingInfo(vim, *args, **kwargs):
| '''The data object defines information for backing a with a named pipe. You can
use a pipe to connect a virtual serial port to a host application or | to another
virtual machine on the host computer. This is useful for capturing debugging
information sent through the virtual serial port.'''
obj = vim.client.factory.create('ns0:VirtualSerialPortPipeBackingInfo')
# do some validation checking...
if (len(args) + len(kwargs)) < 2:
raise... |
tykling/bulkvote | src/bulkvote/wsgi.py | Python | bsd-3-clause | 393 | 0 | """
WSGI config for bulkvote project.
It ex | poses the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_ws | gi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bulkvote.settings")
application = get_wsgi_application()
|
azumimuo/family-xbmc-addon | plugin.video.elysium/resources/lib/sources/disabled/mvzone_mv.py | Python | gpl-2.0 | 3,243 | 0.026827 | # -*- coding: utf-8 -*-
'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in... | u.org/licenses/>.
'''
import re,urllib,urlparse
from resources.lib.modules import control
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import directstream
class source:
def __init__(self):
self.domains = ['moviezone.ch']
self.base_... | elf.elysium_url = []
try:
self.elysium_url = []
title = cleantitle.getsearch(title)
cleanmovie = cleantitle.get(title)
query = self.search_link % (urllib.quote_plus(title),year)
query = urlparse.urljoin(self.base_link, query)
link = client.request(query)
r = client.parseDOM(link, 'div', attrs = ... |
piontec/docker-enforcer | rules/rules.py | Python | gpl-3.0 | 96 | 0 | rules = [
{
" | name": "always false",
"rule": lam | bda container: False
}
]
|
pratikmallya/heat | heat/tests/engine/service/test_stack_resources.py | Python | apache-2.0 | 21,657 | 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 unde... | self.assertIn('description', r)
self.assertIn('updated_time', r)
self.assertIn('stack_identity', r)
self.assertIsNotNone(r['stack | _identity'])
self.assertIn('stack_name', r)
self.assertEqual(self.stack.name, r['stack_name'])
self.assertIn('metadata', r)
self.assertIn('resource_status', r)
self.assertIn('resource_status_reason', r)
self.assertIn('resource_type', r)
self.assertIn('physical_res... |
tushortz/pygeminfo | pygeminfo/example/stats_example.py | Python | mit | 1,132 | 0.020318 | from pygeminfo.gems import *
#from pygeminfo.gems import Stats
#! Import pygeminfo
#--> sample = pygeminfo.gems.Stats("ruby")
#Using the gem's Stats class
#Enter Rubygem's name as argument
sample = Stats("ruby")
print ("Gem Name: {}".format(sample.name()))
print ("Overall Gem download: {}".format(sample.total()))
pri... | ))
print ("Secure Hash Algorithm: {}".format(sample.sha()))
print ("Gem's URL: {}".format(sample.gemURL | ()))
print ("Project URL: {}".format(sample.projectURL()))
print ("Gem's homepage: {}".format(sample.homepage()))
print ("Wiki webpage: {}".format(sample.wikiURL()))
print ("Documentation webpage: {}".format(sample.docURL()))
print ("Mailing list website: {}".format(sample.mailURL()))
print ("Source code URL: {}".forma... |
DGA-MI-SSI/YaCo | deps/swig-3.0.7/Examples/test-suite/python/smart_pointer_multi_typedef_runme.py | Python | gpl-3.0 | 188 | 0 | from smart_pointer_multi_typedef import *
f = Foo()
b = Bar(f)
s = Spam(b)
g = Grok(b) |
s.x = 3
if s.getx() != 3:
raise RuntimeError
g.x = 4
if g.getx() != 4:
raise Runt | imeError
|
Gatomlo/shareandplay | catalogue/migrations/0015_auto_20170415_1628.py | Python | gpl-3.0 | 495 | 0.00202 | # - | *- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-15 14:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalogue', '0014_auto_20170414_0845'),
]
operations = [
migrations.AlterField... | ),
]
|
tttro/projektityokurssi | backend/lbd_backend/middleware/cors.py | Python | mit | 837 | 0.004785 | # -*- coding: UTF-8 -*-
__author__ = 'Aki Mäkinen'
from django.http import HttpResponse
_cors_dict = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "false",
"Access-Control-Allow-Headers": "LBD_LOGIN_HEADER, LBD_OAUTH_ID, Authorization, Content-Type, Accept",
"Access-Control-... | OL_REQUEST_METHOD" in request.META:
return HttpResponse()
else:
return None
def process_response(self, request, response):
if isinstance(response, HttpResponse):
| for header, value in _cors_dict.iteritems():
response[header] = value
return response
|
wteiken/letsencrypt | certbot/plugins/disco_test.py | Python | apache-2.0 | 10,343 | 0.000097 | """Tests for certbot.plugins.disco."""
import unittest
import mock
import pkg_resources
import zope.interface
from certbot import errors
from certbot import interfaces
from certbot.plugins import standalone
from certbot.plugins import webroot
EP_SA = pkg_resources.EntryPoint(
"sa", "certbot.plugins.standalone",... | is config)
# try to give different config
self.assertTrue(self.plugin_ep.init(123) is plugin)
self.assertTrue(plugin.config is config)
self.assertFalse(self.plugin_ep.prepared)
self.assertFalse(self.plugin_ep.misconfigured)
self.assertFalse(self.plugin_ep.available)
... | iface3 = mock.MagicMock(__name__="iface3")
# pylint: disable=protected-access
self.plugin_ep._initialized = plugin = mock.MagicMock()
exceptions = zope.interface.exceptions
with mock.patch("certbot.plugins."
"disco.zope.interface") as mock_zope:
mo... |
allenlavoie/tensorflow | tensorflow/contrib/tpu/python/tpu/tpu_system_metadata.py | Python | apache-2.0 | 5,758 | 0.006947 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ('*** Num TPU Cores Per Worker: %d',
metadata.num_of_cores_per_host)
for device in metadata.devices:
logging.info('*** Ava | ilable Device: %s', device)
else:
logging.info('Failed to find TPU: %s', metadata)
return metadata
def _obtain_topology(master_address, run_config):
try:
logging.info('Initializing TPU system (master: %s) to fetch topology '
'for model parallelism. This might take a while.',
... |
ksteinfe/decodes | tests/test_voxel.py | Python | gpl-3.0 | 906 | 0.054084 | import unittest
import decodes.core as dc
from decodes.core import *
from decodes.extensions.voxel import *
class Tests(unittest.TestCase):
def test_constructor(self):
bounds = Bounds(center=Point(),dim_x=8,dim_y=8,dim_z=8)
vf = VoxelField(bounds,4,4,4)
vf.set(0,0,0,10.0)
vf.set(3... | ),0.0)
def test_bounds_and_cpt(self):
bounds = Bounds(center=Point(),dim_x=8,dim_y=8,dim_z=8)
vf = VoxelField(bounds,4,4,4)
self.ass | ertEqual(vf.dim_pixel,Vec(2,2,2))
self.assertEqual(vf.cpt_at(0,0,0),Point(-3,-3,-3))
vf.bounds = Bounds(center=Point(),dim_x=12,dim_y=12,dim_z=8)
self.assertEqual(vf.dim_pixel,Vec(3,3,2))
self.assertEqual(vf.cpt_at(0,0,0),Point(-4.5,-4.5,-3))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.