code stringlengths 3 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int64 3 1.05M |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django_markdown.models
class Migration(migrations.Migration):
dependencies = [
('mattborgman', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Tag'... | mgborgman/pcg2015_mgb | portfolio_site/mattborgman/migrations/0002_auto_20150405_1741.py | Python | mit | 1,023 |
import webapp2
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
class SampleIndex(webapp2.RequestHandler):
"""Stub request handler"""
def get(self):
"""Handles a get to /"""
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("hellowo... | rbanffy/testable_appengine | src/main.py | Python | apache-2.0 | 408 |
import _plotly_utils.basevalidators
class TickmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="tickmode", parent_name="layout.scene.zaxis", **kwargs
):
super(TickmodeValidator, self).__init__(
plotly_name=plotly_name,
par... | plotly/python-api | packages/python/plotly/plotly/validators/layout/scene/zaxis/_tickmode.py | Python | mit | 602 |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | EmreAtes/spack | var/spack/repos/builtin/packages/r-protgenerics/package.py | Python | lgpl-2.1 | 1,700 |
import numpy as np
def read_mult(f_in='mult.dat',D=8000):
fp = open(f_in)
lines = fp.readlines()
X = np.zeros((len(lines),D))
for i,line in enumerate(lines):
strs = line.strip().split(' ')[1:]
for strr in strs:
segs = strr.split(':')
X[i,int(segs[0])] = float(seg... | weleen/mxnet | example/notebooks/recommendation_systems/cdl/mult.py | Python | apache-2.0 | 395 |
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as spc
'''
To evaluate Change of Kinetic energy due to orthogonalization (Deltat E_kin ) which is Valence-Bond model for Pauli repulsion
see:
[1] eq.4 in http://aip.scitation.org/doi/10.1063/1.3272671
Jaramillo-Bo... | ProkopHapala/SimpleSimulationEngine | cpp/sketches_SDL/Molecular/python/eFF_KineticAndOverlap.py | Python | mit | 4,811 |
'''
Creating Our K Nearest Neighbors Algorithm - Practical Machine Learning with Python p.16 & 17
https://youtu.be/n3RqsMz3-0A?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
K nearest neighbours comparison requires _ALL_ points compared.
big O notation assessment is huge. ie: slow and does not scale well.
https://en.wikipe... | aspiringguru/sentexTuts | PracMachLrng/sentex_ML_demo15_K_nearest_Neighbours_compare_implementations.py | Python | mit | 4,374 |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | idaholab/raven | tests/framework/fail_xml/calc.py | Python | apache-2.0 | 899 |
import logging
class Summary(object):
"""Summary class to summarize cleanedup resources."""
num_of_instances = 0
num_of_networks = 0
num_of_subnets = 0
num_of_floating_ips = 0
num_of_routers = 0
num_of_ports = 0
num_of_stacks = 0
num_of_keypairs = 0
num_of_secgroups = 0
@... | yazug/shade_janitor | shade_janitor/summary.py | Python | gpl-3.0 | 1,390 |
import main
def shellLaunch():
''' Launch a pathGen command.
See doc strings of objects and the argParse object for details.
'''
launchArgs = vars(main.argParser()())
paths = main.createPathGenerator(launchArgs['regExPaths'])
for path in paths:
print path
if __name__=='__mai... | IRuk/pathGenerator | pathGenerator/pathGenCommand.py | Python | gpl-2.0 | 423 |
#! /usr/bin/env python
from __future__ import print_function
import argparse
import sys
import tsv
parser = argparse.ArgumentParser(description='Find and store media filenames.')
parser.add_argument('inputfile', metavar='PATH',nargs='?',help='CSV file to update artist from it.')
parser.add_argument('-c','--config-f... | pylover/chakameh | chakameh/tools/update_lyricists.py | Python | gpl-2.0 | 1,124 |
# -*- encoding: utf-8 -*-
import logging
from cliff.lister import Lister
class Encoding(Lister):
"""Show some unicode text
"""
log = logging.getLogger(__name__)
def take_action(self, parsed_args):
messages = [
'pi: π',
'GB18030:鼀丅㐀ٸཌྷᠧꌢ€',
]
return (
... | openstack/cliff | demoapp/cliffdemo/encoding.py | Python | apache-2.0 | 455 |
#! /usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Unfortunately, `flatc` doesn't output Rust 2018 conformant code which poses a
# problem when we want to embed it wit... | atxwebs/relay | compiler/crates/schema/src/flatbuffer/generate_flatbuffer.py | Python | mit | 2,656 |
#!/usr/bin/env python
# Hacked from Dale's dump_tsys.py
# Needs an sdf variable
import time, os
import numpy as np
from util import Time
from astropy.io import fits
def rd_miriad_tsys_file(filelist):
''' Read total power data (TSYS) directly from Miriad files
Major change to standardize output t... | dgary50/eovsa | test_svn/dump_tsys_ext_oops.py | Python | gpl-2.0 | 15,569 |
"""
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=... | SmartDeveloperHub/agora-client | agora/client/namespaces.py | Python | apache-2.0 | 1,193 |
# -*- coding: utf-8 -*-
# © 2017 Akretion (Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
from odoo.tools import float_compare
class TestDeliveryCost(common.TransactionCase):
def setUp(self):
... | kittiu/sale-workflow | sale_shipping_info_helper/tests/test_sale_shipping_info_helper.py | Python | agpl-3.0 | 3,889 |
#! /usr/bin/env python
import pathlib
from dataclasses import dataclass
from functools import partial
import click
out = partial(click.secho, bold=True, err=True)
err = partial(click.secho, fg="red", err=True)
def collect_notebooks(src):
p = pathlib.Path(src)
if p.is_dir():
return set([_p.absolute(... | landlab/landlab | notebooks/run_notebook_checks.py | Python | mit | 3,335 |
dict = {}
dict['1']='1'
dict['2']='2'
dict['3'] = '3'
for key in sorted(dict.keys()):
print "%s: %s" % (key, dict[key])
| ianfelzer1/ifelzer-advprog | ianfelzer/dict3.py | Python | gpl-3.0 | 125 |
from __future__ import absolute_import
from __future__ import print_function
from data_utils import load_dialog_task, vectorize_data, load_candidates, \
vectorize_seq2seq_fix, tokenize, vectorize_seq2seq, vectorize_candidates
import metrics
from memn2n import SeqN2NDialog
from itertools import chain
from six.moves... | Amber819/chatbot_AM | seq2seq_dialog.py | Python | mit | 12,121 |
"""Evaluates a simulation, based on the cloud, environment and the actually
performed schedule of actions.
"""
import math
import pandas as pd
import numpy as np
import philharmonic as ph
from philharmonic.logger import *
from philharmonic import conf
def print_history(cloud, environment, schedule):
"""Print t... | and2egg/philharmonic | philharmonic/scheduler/evaluator.py | Python | gpl-3.0 | 27,156 |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
class TestSpatialPyramidPooling2D(unittest.TestCase):
pyramid_height = 3
ou... | 1986ks/chainer | tests/chainer_tests/functions_tests/pooling_tests/test_spatial_pyramid_pooling_2d.py | Python | mit | 3,068 |
from __future__ import annotations
import enum
from typing import Union
import numpy
from . import ENUM_ARRAY_DTYPE, EnumArray
class Enum(enum.Enum):
"""
Enum based on `enum34 <https://pypi.python.org/pypi/enum34/>`_, whose items
have an index.
"""
# Tweak enums to add an index attribute to ea... | openfisca/openfisca-core | openfisca_core/indexed_enums/enum.py | Python | agpl-3.0 | 3,514 |
# -*- coding: utf8 -*-
from __future__ import unicode_literals
import time
import itertools
from optimizer import OptimizationSolution
from bruteForce import BruteForce
class Permutator(BruteForce):
"""
Basic optimizer by permutatons. Given that you have an infinite amount
of time to wait, this optimiz... | Hiestaa/ml-bench | src/solvers/permutator.py | Python | mit | 1,830 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-12 02:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('information', '0004_file_slug'),
]
operations = [
migrations.AddField(
... | VictorArnaud/sitepet | information/migrations/0005_auto_20170212_0217.py | Python | mpl-2.0 | 762 |
import random
import re
class FormRequest:
questions = {
0: {
'type': "Цвет",
'question': [
"Какого цвета вы хотите телефон?",
"Подскажите цвет, который вы хотите?",
"Какое предпочтение по цвету?"
]
},
1: {
'type': "Цена",
'question': [
"Какую максимальную цену вы готовы заплати... | Goodluckhf/chatbot | chatbot/formRequest.py | Python | apache-2.0 | 2,846 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Event.upload'
db.add_column(u'main_event', 'upload',
self.gf('django.d... | Nolski/airmozilla | airmozilla/main/migrations/0034_auto__add_field_event_upload.py | Python | bsd-3-clause | 22,020 |
# -*- coding: utf-8 -*-
"""Tests For SVN."""
from django.test import TestCase
from django_dynamic_fixture import get
from readthedocs.builds.models import Version
from readthedocs.projects.models import Project
from readthedocs.vcs_support.backends.svn import Backend as SvnBackend
class TestSvnBackend(TestCase):
... | rtfd/readthedocs.org | readthedocs/rtd_tests/tests/test_backend_svn.py | Python | mit | 913 |
import time, logging
class Cache():
def __init__(self, expires = 600):
logging.debug("Enabling memory cache, expires %s" % expires)
self.expires = expires
self.cache = {}
def keys(self):
return list(self.cache.keys())
def __len__(self):
return len(self.cache)
... | hay/chantek | memorycache.py | Python | mit | 1,118 |
# Licensed to the StackStorm, Inc ('StackStorm') 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 th... | dennybaa/st2 | st2common/tests/unit/test_state_publisher.py | Python | apache-2.0 | 3,137 |
import unittest
from collections import namedtuple
from tests.harness import instrumentGooey
from gooey import GooeyParser
from gooey.tests import *
Case = namedtuple('Case', 'inputs initialExpected')
class TestCommonProperties(unittest.TestCase):
"""
Test options and functionality
common across all wid... | chriskiehl/Gooey | gooey/tests/test_common.py | Python | mit | 1,822 |
# -*- coding: utf-8 -*-
# ===========================================================================
# Popular encoding:
# utf-8
# ISO-8859-1
# ascii
# encode: string -> string of bytes
# decode: string of bytes -> string
# ===========================================================================
from __future__ ... | imito/odin | odin/preprocessing/text.py | Python | mit | 24,225 |
import unicodedata
import re
import hashlib
import random
import logging
# Taken from Django
def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase.... | Owlz/StegoDone | stegoveritas/helpers.py | Python | gpl-2.0 | 990 |
from src.commons.dao.driver.mongo_driver import mongo_driver
import datetime
import pymongo
class agent_model(object):
def __init__(self, mongo_data, board_name, _agent_name):
self.mongo_client = mongo_driver(mongo_data)
self.db = self.mongo_client.db
self.collection = self.db[board_name]["agents"]
#self.coll... | EPSI-Hestia/Hestia | src/commons/dao/model/agent_model.py | Python | gpl-2.0 | 2,304 |
import _plotly_utils.basevalidators
class ArrayValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="array", parent_name="scatter.error_x", **kwargs):
super(ArrayValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/scatter/error_x/_array.py | Python | mit | 401 |
import requests
import datetime
import dateutil.parser as d
from bs4 import BeautifulSoup
from itertools import takewhile, dropwhile
from .jobcontainer import JobContainer
def parse_brainhunter_job_table(soup):
ret = []
job_table = soup.find("table", "job_list_table")
rows = job_table.find_all('tr')[1:]
... | rgscherf/gainful2 | parsing/parsinglib/utils_brainhunter.py | Python | mit | 2,551 |
#!/usr/bin/env python
#
# texttable - module for creating simple ASCII tables
# Copyright (C) 2003-2015 Gerome Fournier <jef(at)foutaise.org>
#
# 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 Foundat... | zverevalexei/trex-http-proxy | trex_client/external_libs/texttable-0.8.4/setup.py | Python | mit | 2,216 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# tocelsius.py
# Converts temperature from Fahrenheit to Celsius.
# Exercise 10.4: Python How to Program, 1st Ed. by Deitel, P. & Deitel, H.
#
# Author: Billy Wilson Arante
# Created: 2016/10/30 EDT
from __future__ import division
from Tkinter import *
import tkMessageBo... | arantebillywilson/python-snippets | py2/htp/ex10/tocelsius.py | Python | mit | 1,438 |
#!/usr/bin/python2.6
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | google/pymql | test/type_link_test.py | Python | apache-2.0 | 36,235 |
#!/usr/bin/env python3
"""
Rename and organize Horos QC exported data in <BIDS Root>/incoming and place in <BIDS Root>/sourcedata
AUTHOR
----
Mike Tyszka, Ph.D.
MIT License
Copyright (c) 2019 Mike Tyszka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated doc... | jmtyszka/CBICQA | bin/cbicqc_incoming.py | Python | mit | 4,170 |
# Firelet - Distributed firewall management.
# Copyright (C) 2010 Federico Ceratto
#
# 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 la... | FedericoCeratto/firelet | firelet/flssh.py | Python | gpl-3.0 | 21,960 |
# Copyright (c) 2009-2010 Reza Lotun http://reza.lotun.name/
# Copyright (c) 2011 Jann Kleen
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitat... | matthappens/taskqueue | taskqueue/venv_tq/lib/python2.7/site-packages/boto/ec2/autoscale/policy.py | Python | mit | 6,221 |
import unittest
from test_initializer import TestInitializer
from page_objects import TeachersPage, LoginPage, CourseName
class StaffPageTest(unittest.TestCase):
def setUp(self):
self.driver = TestInitializer().getDefaultDriver()
LoginPage(self.driver).loginAsAssistant()
@unittest.skip
de... | Aalto-LeTech/a-plus | selenium_test/test/staff_page_test.py | Python | gpl-3.0 | 824 |
from django.contrib import admin
from models.snippets import Contact
@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
pass
| kave/cfgov-refresh | cfgov/v1/admin.py | Python | cc0-1.0 | 143 |
# coding=utf-8
"""Tests for interpolation functionality done with QGIS API."""
import unittest
from qgis.core import QgsFeatureRequest, QgsVectorLayer
from safe.test.utilities import get_qgis_app, TESTDATA
from safe.gis.qgis_vector_tools import create_layer
from safe.engine.interpolation_qgis import interpolate_poly... | dynaryu/inasafe | safe/engine/test/test_interpolation_qgis.py | Python | gpl-3.0 | 5,184 |
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from PyQt4 import QtGui
import os
import unit... | mganeva/mantid | scripts/test/Muon/load_run_widget/loadrun_presenter_increment_decrement_test.py | Python | gpl-3.0 | 8,183 |
# -*- coding: utf-8 -*-
# @copyright (C) 2014-2015
#Developpeurs 'BARDOU AUGUSTIN - REZILLON ANTOINE - EUZEN DAVID - FRANCOIS SEBASTIEN - JOUNEAU NICOLAS - KIBEYA AISHA - LE CONG SEBASTIEN -
# MAGREZ VALENTIN - NGASSAM NOUMI PAOLA JOVANY - OUHAMMOUCH SALMA - RIAND MORGAN - TREIMOLEIRO ALEX - TRULLA AURELIE... | ehopsolidaires/ehop-solidaires.fr | ehop/ehopSolidaire_providers_register/templatetags/to_FR.py | Python | agpl-3.0 | 1,067 |
# -*- coding: utf-8 -*-
#
# This file is part of EUDAT B2Share.
# Copyright (C) 2017 University of Tuebingen, CERN, CSC, KTH.
#
# B2Share 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... | EUDAT-B2SHARE/b2share | tests/b2share_unit_tests/users/test_account_rest_permissions.py | Python | gpl-2.0 | 6,918 |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""
FILE: sample_translation_with_azure_blob.py
DESCRIPTION:
This sample demonstrates how to use Azure Blob Storage to set up the necessary resources to translate
... | Azure/azure-sdk-for-python | sdk/translation/azure-ai-translation-document/samples/sample_translation_with_azure_blob.py | Python | mit | 6,605 |
# -*- coding: utf-8 -*-
#
# Cloud Custodian documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 21 08:34:24 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated fil... | FireballDWF/cloud-custodian | docs/source/conf.py | Python | apache-2.0 | 9,848 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | rjschwei/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/models/application_gateway_backend_health.py | Python | mit | 1,082 |
__author__ = "Stacy Smith"
__credits__ = "Jeremy Schulman, Nitin Kumar"
import unittest
from nose.plugins.attrib import attr
from mock import patch, MagicMock
import os
from lxml import etree
from jnpr.junos import Device
from ncclient.manager import Manager, make_device_handler
from ncclient.transport import SSHSes... | pklimai/py-junos-eznc | tests/unit/facts/test_get_route_engine_information.py | Python | apache-2.0 | 11,946 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('contacts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='person',
name='indian_... | mayapurmedia/tovp | tovp/contacts/migrations/0002_auto_20150202_1432.py | Python | mit | 681 |
import os
import sys
from socketio import socketio_manage
from socketio.server import SocketIOServer
from socketio.namespace import BaseNamespace
from flask import request, session, json
from werkzeug.debug import DebuggedApplication
from werkzeug.serving import run_with_reloader
from werkzeug._internal import _log
f... | rlhatcher/Flask-SocketIO | flask_socketio/__init__.py | Python | mit | 10,875 |
# Author: Nic Wolfe <nic@wolfeden.ca>
# 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 Foundatio... | bbbenja/SickRage | sickbeard/common.py | Python | gpl-3.0 | 19,367 |
# -*- coding: utf-8 -*-
import os
# Author: Peter Prettenhofer <peter.prettenhofer@gmail.com>
#
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble
from sklearn import datasets
from sklearn.utils import shuffle
from sklearn.metrics import mean_squared_error
#####... | NicovincX2/Python-3.5 | Statistiques/Estimation (statistique)/Régression/Gradient boosting/gradient_boosting_regression.py | Python | gpl-3.0 | 2,287 |
#!/usr/bin/env python
# Copyright 2013 AlchemyAPI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | Riamse/ymmv | alchemyapi.py | Python | gpl-3.0 | 34,848 |
# Copyright 2017 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class BarcodeRule(models.Model):
_inherit = "barcode.rule"
generate_model = fields.Selection(
selection_add=[("stock.location", "Stock Location")],
)
| OCA/stock-logistics-barcode | barcodes_generator_location/models/barcode_rule.py | Python | agpl-3.0 | 304 |
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0: return 0
max_val = 0
count = 0
for i in range(len(nums)):
if nums[i] == 1:
count += 1
... | linjinjin123/leetcode | Python/485. Max Consecutive Ones.py | Python | mit | 510 |
from django.conf.urls import url
from . import views
from .views import Clients
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^api/?$', Clients.as_view()),
url(r'^api/(?P<client_id>[0-9]+)/?$', Clients.as_view()),
] | tabalinas/jsgrid-django | clients/urls.py | Python | mit | 243 |
# Copyright (C) 2007, One Laptop Per Child
#
# 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 distrib... | sugarlabs/sugar | src/jarabe/frame/clipboardmenu.py | Python | gpl-3.0 | 8,712 |
import click
from globus_cli.login_manager import LoginManager
from globus_cli.parsing import command
from globus_cli.termio import FORMAT_TEXT_RECORD, formatted_print, is_verbose
from ._common import resolve_id_or_name
@command(
"show",
adoc_output="""
When textual output is requested, the output varies de... | globus/globus-cli | src/globus_cli/commands/bookmark/show.py | Python | apache-2.0 | 1,863 |
import os
def user_friendly(path):
path = computer_friendly(path)
return path.replace(os.path.expanduser('~'), '~').replace(os.path.sep, '/')
def computer_friendly(path):
"""Also makes sure the path is valid"""
if '~' in path:
path = path[path.rfind("~"):]
if ':' in path:
path = p... | ameistad/FileManager | pathhelper.py | Python | mit | 2,089 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-16 05:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0001_initial'),
]
operations = [
migrations.AlterField(
... | unicef/un-partner-portal | backend/unpp_api/apps/project/migrations/0002_auto_20170816_0523.py | Python | apache-2.0 | 459 |
"""
Tests for second order centrality.
"""
import pytest
np = pytest.importorskip("numpy")
scipy = pytest.importorskip("scipy")
import networkx as nx
from networkx.testing import almost_equal
class TestSecondOrderCentrality:
def test_empty(self):
with pytest.raises(nx.NetworkXException):
G ... | SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/networkx/algorithms/centrality/tests/test_second_order_centrality.py | Python | gpl-3.0 | 1,967 |
#!/usr/bin/python
'''
We want to find coefficient of expantion of function which is linear combination of powers of R^2 since R^2 = x^2 + y^2 + z^2 (+w^2 ... ) is easy to compute
f(x) = Sum_i ai * x^(2*i)
We have 4 boundary conditions
f(x1)=y1, f'(x1)=dy1
f(x2)=y1, f'(x2)=dy2
for f(x) = a1 + a2*x**2 + a3*x**4 +... | ProkopHapala/SimpleSimulationEngine | cpp/apps/MolecularEditor/py/splineR2.py | Python | mit | 5,886 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('videos', '0012_auto_20160205_0603'),
]
operations = [
migrations.AlterField(
model_name='video',
nam... | projectjamjar/masonjar | jamjar/jamjar/videos/migrations/0013_auto_20160205_0737.py | Python | mit | 448 |
#
# Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
#
import requests, json
from requests.exceptions import ConnectionError
class AnalyticApiClient(object):
def __init__(self, cfg):
self.config = cfg
self.client = requests.Session()
self.init_client()
self.base = None... | sajuptpm/contrail-controller | src/analytics/contrail-topology/contrail_topology/analytic_client.py | Python | apache-2.0 | 3,095 |
# -----------------------------------------------------------------------------
# Karajlug.org
# Copyright (C) 2010 Karajlug community
#
# 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 Found... | Karajlug/karajlug | news/views.py | Python | gpl-2.0 | 2,076 |
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | jjinux/party-playlist-picker | third-party/atom/http_interface.py | Python | apache-2.0 | 5,182 |
# -*- coding: utf-8 -*-
"""
Standard baseclass form definitions & some widget definitions
:subtitle:`Class definitions:`
"""
import magic
import datetime
from django.conf import settings
from django import forms
from core.widgets import SelectDateWidget
from django.forms.widgets import Select, RadioSelect
from django.... | acesonl/remotecare | remotecare/core/forms.py | Python | gpl-3.0 | 18,511 |
from .utils import *
import models
import settings
class Commentable(models.Model):
base_url = "{prefix}/commentables".format(prefix=settings.PREFIX)
type = 'commentable'
| elimence/edx-platform | lms/lib/comment_client/commentable.py | Python | agpl-3.0 | 183 |
# -*- coding: utf-8 -*-
#
# SYMDIFF documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 5 20:56:38 2016.
#
# 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.
#
# A... | devsim/symdiff | sphinx/source/conf.py | Python | apache-2.0 | 12,212 |
# Created By: Virgil Dupras
# Created On: 2006/02/23
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl... | stuckj/dupeguru | core/tests/markable_test.py | Python | gpl-3.0 | 3,681 |
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
from settings import getSettings
settings = getSettings()
if 'CACHE_ROOT' in settings:
cache_root = settings['CACHE_ROOT']
else:
cache_root = '/tmp/screepsstats'
cache_opts = {
'cache.type': 'file',
'cache.data_d... | screepers/screeps-stats | screeps_etl/services/cache.py | Python | mit | 482 |
# -*- python-indent: 4; coding: iso-8859-1; mode: python -*-
# Copyright (C) 2008 Cedric Pinson, Jeremy Moles
#
# 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, o... | mp3butcher/osgexport | exporter/osg/osgobject.py | Python | gpl-2.0 | 53,972 |
from setuptools import setup
setup(name='pytest-truth',
version='0.0.2',
description='pytest plugin providing ability to easily parametrize tests with a truth table',
long_description=open('README.rst').read(),
author='Jackson J. Gilman',
author_email='jackson.j.gilman@gmail.com',
u... | rocketscienceproductions/pytest-truth | setup.py | Python | mit | 1,271 |
"""
Mock up a video feed pipeline
"""
import asyncio
import logging
import sys
import cv2
logging.basicConfig(format="[%(thread)-5d]%(asctime)s: %(message)s")
logger = logging.getLogger('async')
logger.setLevel(logging.INFO)
async def process_video(filename):
cap = cv2.VideoCapture(filename)
tasks = list()
... | dmeklund/asyncdemo | videofeed.py | Python | mit | 932 |
import logging
from typing import Any, Callable, Union
from .conditions import render
from .exceptions import (
InvalidModel,
InvalidStream,
InvalidTemplate,
MissingObjects,
)
from .models import BaseModel, Index, subclassof, unpack_from_dynamodb
from .search import Search
from .session import SessionW... | numberoverzero/bloop | bloop/engine.py | Python | mit | 17,321 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blogapp', '0007_auto_20151119_1315'),
]
operations = [
migrations.AlterModelOptions(
name='speakers',
... | jgsjv/treinamento_django | blog/blogapp/migrations/0008_auto_20151119_1353.py | Python | mit | 785 |
"""
This module contains the statusbar class
*Examples:* ::
Enter code examples here. (optional field)
*Todo:*
* Enter thing to do. (optional field)
*Author:*
* Mitri Van, mitri.van@volition-inc.com, 10/3/2013 11:14:40 AM
"""
import wx
class status_bar( wx.StatusBar ):
def __init__( self, par... | shaolinmike/dragonchess | menu_statusbar.py | Python | gpl-3.0 | 671 |
import unittest
from tests.utils import (
setup_test_env,
)
setup_test_env()
from softwarecenter.db.pkginfo import get_pkg_info
class TestSCAddons(unittest.TestCase):
""" tests the addons """
def setUp(self):
self.cache = get_pkg_info()
self.cache.open()
@unittest.skip("disabled un... | ceibal-tatu/software-center | tests/test_addons.py | Python | lgpl-3.0 | 2,335 |
# Copyright 2007 Jeff Epler <jepler@unpythonic.net>
#
# 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.
#
#... | EqAfrica/machinekit | lib/python/bitfile.py | Python | lgpl-2.1 | 4,050 |
'''
Config/Settings for ER Tweet Matching Service
'''
from datetime import date
# GLOBAL
# Maximum size a database can grow to (should be a multiple of 10MB)
MAX_DB_SIZE = 10485760 * 1000 * 100 # 10MB -> 10GB -> 1TB
## ER SERVICE
# Credentials
ER_USER = 'luis.rei@ijs.si'
ER_PASS = ''
# Log ER Requests?
ER_LOG =... | lrei/er_match | ermcfg.py | Python | mit | 2,864 |
# Copyright 2008-2009 WebDriver committers
# Copyright 2008-2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | mogotest/selenium | firefox/src/py/webdriver.py | Python | apache-2.0 | 3,538 |
from setuptools import setup, find_packages
NAME = 'mezzanine-blocks'
VERSION = '0.9.4'
DESCRIPTION = """
A fork of https://github.com/molokov/mezzanine-blocks.git to make it work with Django 1.9
A mezzanine flavored fork of django-flatblocks.
The goal of this project is to be able to easily create custom blocks of
... | renyi/mezzanine-blocks | setup.py | Python | bsd-2-clause | 1,214 |
#!/usr/bin/env python
#
# Copyright 2007 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | GoogleCloudPlatform/appengine-python-standard | src/google/appengine/api/apiproxy_stub.py | Python | apache-2.0 | 5,483 |
'''
TestProperties - Set properties that will be used by the unit tests
'''
REDIS_CONNECTION_PARAMS = { 'host' : '127.0.0.1', 'port' : 6379, 'db' : 0 }
# Use a function to keep namespace clean
def initProperties():
try:
from IndexedRedis import setDefaultRedisConnectionParams, getRedisPool
except... | kata198/indexedredis | tests/UnitTests/TestProperties.py | Python | lgpl-2.1 | 882 |
from __future__ import absolute_import, print_function
import os
import yaml
import requests
from os.path import join, exists, dirname, basename, relpath, splitext, isfile, isdir
from ..plugins.constants import __version__, job_id
from ..plugins.upload_to_s3 import S3_URL, upload_file_to_s3
from ..plugins.utils im... | Karel-van-de-Plassche/bokeh | tests/examples/collect_examples.py | Python | bsd-3-clause | 7,700 |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
# Credits#######################################... | 3dfxsoftware/cbss-addons | account_move_cancel/model/invoice.py | Python | gpl-2.0 | 2,046 |
'epub.py functions and classes'
from epub import Epub
'chapter.py functions and classes'
from chapter import Chapter
from chapter import ChapterFactory
from chapter import create_chapter_from_url
from chapter import create_chapter_from_file
from chapter import create_chapter_from_string
from chapter import save_image
... | wcember/pypub | pypub/__init__.py | Python | mit | 379 |
x = "module"
def f():
x = "temporary"
print x
print x
f()
print x
| gregpuzzles1/Sandbox | Example Programs/Ch_06_Student_Files/testscope.py | Python | gpl-3.0 | 76 |
import logging
import csv
import gzip
from contextlib import closing
from typing import Optional
import requests
from dipper.sources.Source import Source
from dipper.models.assoc.G2PAssoc import G2PAssoc
from dipper.models.Model import Model
from dipper.models.Genotype import Genotype
LOG = logging.getLogger(__name_... | TomConlin/dipper | dipper/sources/EBIGene2Phen.py | Python | bsd-3-clause | 10,806 |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 0, transform = "Logit", sigma = 0.0, exog_count = 100, ar_order = 0); | antoinecarme/pyaf | tests/artificial/transf_Logit/trend_MovingMedian/cycle_0/ar_/test_artificial_32_Logit_MovingMedian_0__100.py | Python | bsd-3-clause | 263 |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | octavioturra/aritial | google_appengine/google/appengine/tools/dev_appserver_channel.py | Python | apache-2.0 | 3,213 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... | Azure/azure-sdk-for-python | sdk/eventhub/azure-eventhub-checkpointstoreblob/azure/eventhub/extensions/checkpointstoreblob/_vendor/storage/blob/_deserialize.py | Python | mit | 7,616 |
#!/usr/bin/env python
# CreateInstanceFabric.py
#
# This class was intended to demonstrate an exercise using the Python AWS SDK
# (boto), however it will probably be extended to do much more over time,
# especially as I continue to test additional infrastructure.
#
# This class (CreateInstance) has some wrapper funct... | briantyr/auto-deploy | CreateInstanceFabric.py | Python | mit | 12,262 |
# -*- coding: utf-8 -*-
stopwords = """
| A German stop word list. Comments begin with vertical bar. Each stop
| word is at the start of a line.
| The number of forms in this list is reduced significantly by passing it
| through the German stemmer.
aber | but
alle | all
allem
allen
aller
... | michelp/xodb | xodb/snowball/german/__init__.py | Python | mit | 4,223 |
"""
Schema for ecommerce workflow
"""
from steps import *
from ..baseworkflow import BaseWorkflow
class EcommerceWorkflow(BaseWorkflow):
"""Class to manage the workflow for ecommerce
"""
def __init__(self):
self.flow = {
'PickOrderFromHub': PickOrderFromHub(['ScheduleDelivery'], []),
... | mohitranka/workflow_manager | workflow/ecommerce/schema.py | Python | gpl-3.0 | 1,037 |
# Copyright (c) 2015 SUSE Linux GmbH. All rights reserved.
#
# This file is part of kiwi.
#
# kiwi 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 la... | dirkmueller/kiwi | kiwi/solver/repository/deb.py | Python | gpl-3.0 | 1,449 |
import sqlite3
import string
def char_generator():
for c in string.ascii_lowercase:
yield (c,)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
cur.executemany("insert into characters(c) values (?)", char_generator())
cur.execute("select c from ... | Orav/kbengine | kbe/src/lib/python/Doc/includes/sqlite3/executemany_2.py | Python | lgpl-3.0 | 357 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.