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 |
|---|---|---|---|---|---|
#!/bin/python3
import sys
fact = lambda n: 1 if n <= 1 else n * fact(n - 1)
n = int(input().strip())
fct = fact(n)
print(fct)
| lilsweetcaligula/Online-Judges | hackerrank/algorithms/implementation/medium/extra_long_factorials/py/solution.py | Python | mit | 134 |
class _DataTuner(object):
_skeys = ["sid", "fid", "area_ratio",
"time", "dlen", "olen",
"mean_dist", "qart_dist",
"top10", "top20", "top30", "top40", "top50",
"rtop10", "rdist", "inv_rdist"
]
def __init__(self):
"""
Output in... | speed-of-light/pyslider | lib/exp/pairing/data_tuner.py | Python | agpl-3.0 | 3,037 |
#
# Copyright 2015 BMC Software, 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 ... | boundary/pulse-api-cli | boundary/alarm_delete.py | Python | apache-2.0 | 2,519 |
# -*- 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):
# Changing field 'Participant.user'
db.alter_column(u'experiments_partic... | uhuramedia/django-lean | django_lean/experiments/migrations/0010_auto__chg_field_participant_user.py | Python | bsd-3-clause | 9,043 |
# vim: fileencoding=utf-8 et ts=4 sts=4 sw=4 tw=0 fdm=marker fmr=#{,#}
"""
Tornado versions of RPC service and client
Authors:
* Brian Granger
* Alexander Glyzov
Example
-------
To create a simple service::
from netcall.tornado import TornadoRPCService
echo = TornadoRPCService()
@echo.task
def e... | srault95/netcall | netcall/tornado/__init__.py | Python | bsd-3-clause | 1,409 |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import unittest
from django.utils import six
from django.utils.encoding import (
escape_uri_path, filepath_to_uri, force_bytes, force_text, iri_to_uri,
smart_text, uri_to_iri,
)
from django.utils.functional import SimpleLazyObje... | filias/django | tests/utils_tests/test_encoding.py | Python | bsd-3-clause | 5,759 |
from operator import add, div, mul, neg
from _ppeg import Pattern as P
def pattprint(pattern):
print pattern.env()
pattern.display()
mt = P(1)
ANY = P(1)
predef = {
'nl': P('\n'),
}
def getdef(name, defs):
c = defs and defs[name]
return c
def patt_error(s, i):
msg = (len(s) < i + 20) and s... | moreati/ppeg | pe.py | Python | mit | 3,807 |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import os.path
import types
from app.libs.utils import load_module_attrs
def _filter(module):
if hasattr(module, 'urls') and isinstance(module.urls, types.ListType):
return getattr(module, 'urls')
path = os.path.... | Damnever/2L | app/services/__init__.py | Python | bsd-3-clause | 421 |
''' -- imports from installed packages -- '''
from django.shortcuts import render_to_response
from django.template import RequestContext
# from django.core.urlresolvers import reverse
from mongokit import paginator
try:
from bson import ObjectId
except ImportError: # old pymongo
from pymongo.objectid import Objec... | Dhiru/gstudio | gnowsys-ndf/gnowsys_ndf/ndf/views/e-book.py | Python | agpl-3.0 | 2,256 |
# -*- coding: iso-8859-1 -*-
"""A lexical analyzer class for simple shell-like syntaxes."""
# Module and documentation by Eric S. Raymond, 21 Dec 1998
# Input stacking and error message cleanup added by ESR, March 2000
# push_source() and pop_source() made explicit by ESR, January 2001.
# Posix compliance, split(), st... | pculture/mirocommunity | localtv/search/shlex.py | Python | agpl-3.0 | 9,212 |
import csv
import logging
import re
import requests
from account.models import EmailAddress
from django.contrib.auth import get_user_model
from django.core.management.base import NoArgsCommand
from constance import config
from pycon.models import PyConTutorialProposal, PyConSponsorTutorialProposal
logger = logging... | PyCon/pycon | pycon/management/commands/update_tutorial_registrants.py | Python | bsd-3-clause | 5,738 |
import tensorflow as tf
"""tf.ceil(x,name=None)
功能:计算x各元素比x大的最小整数。
输入:x为张量,可以为`half`,`float32`, `float64`类型。"""
x = tf.constant([[0.2, 0.8, -0.7]], tf.float64)
z = tf.ceil(x)
sess = tf.Session()
print(sess.run(z))
sess.close()
# z==>[[1. 1. -0.]]
| Asurada2015/TFAPI_translation | math_ops_basicoperation/tf_ceil.py | Python | apache-2.0 | 308 |
from subprocess import call, os
from django.core.management.base import BaseCommand
from django.conf import settings
from boto.s3.connection import S3Connection
class Command(BaseCommand):
help = "Loads fixture images from S3 bucket"
def handle(self, *args, **options):
if len(args)>0:
A... | MadeInHaus/django-template | backend/apps/utils/management/commands/save_fixture_images.py | Python | mit | 1,139 |
import socket
from flask import Flask, jsonify
app = Flask(__name__)
PRICES = {
'BHP': {'Code': 'BHP', 'Price': 91.72},
'GOOG': {'Code': 'GOOG', 'Price': 34.21},
'ABC': {'Code': 'ABC', 'Price': 1.17}
}
@app.route('/ping', methods=["GET"])
def ping():
return socket.gethostname()
@app.route('/price... | morganjbruce/microservices-in-action | chapter-6/market-data/app.py | Python | mit | 672 |
from flask import request, session
from flask import Blueprint
import api
import json
import mimetypes
import os.path
import api.auth
import api.cache
import api.stats
import asyncio
import threading
from api.annotations import api_wrapper
from api.common import flat_multi
from api.exceptions import *
blueprint =... | EasyCTF/easyctf-2015 | api/api/routes/stats.py | Python | mit | 1,501 |
# -*- coding: utf-8 -*-
class Codes(object):
def __init__(self, **kws):
self._reverse_dict = {}
for k, v in kws.items():
self.__setattr__(k, v)
def str_value(self, value):
return self._reverse_dict[value]
def __setattr__(self, name, value):
super(Codes, self)._... | NSLS-II/channelarchiver | channelarchiver/structures.py | Python | mit | 735 |
import sc2reader
replay = sc2reader.load_replay('1.SC2Replay', load_level=4)
for i in range(0,3):
print("hello" + str(i))
| asveron/starcraftViz | starcraftViz1/learnPython.py | Python | mit | 130 |
import numpy as np
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) where x[i] is the ith input.
We multiply this against a weight matrix of shape (D, M) where
D = \prod_i d_i
Inputs:
x - Input data, of shape (N, ... | DeercoderCourse/cs231n | assignment3/cs231n/layers.py | Python | apache-2.0 | 6,236 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | jirikuncar/invenio-oaiserver | invenio_oaiserver/receivers.py | Python | gpl-2.0 | 2,841 |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import sys
from xml.dom import minidom
from swid_generator.command_manager import CommandManager as CM
from swid_generator.generators.utils import create_temp_folder
def sign_xml(data, signature_args):
fold... | pombredanne/swidGenerator | swid_generator/print_functions.py | Python | mit | 4,434 |
# -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | stormi/tsunami | src/secondaires/auberge/commandes/auberge/liste.py | Python | bsd-3-clause | 3,069 |
#!/usr/bin/env python
'''
Python bindings for libmagic
'''
import ctypes
from ctypes import *
from ctypes.util import find_library
def _init():
"""
Loads the shared library through ctypes and returns a library
L{ctypes.CDLL} instance
"""
return ctypes.cdll.LoadLibrary(find_library('magic'))
_li... | opf-attic/ref | tools/file/file-5.11/python/magic.py | Python | apache-2.0 | 6,558 |
from numpy import *
from struct import pack
def pack_coefs(c):
cw = list(zip(c[ :128][::-1],
c[128:256][::-1],
c[256:384][::-1],
c[384: ][::-1]))
m = max(sum(x) for x in cw)
return b''.join(pack('>4h', *(int(round(n / m * 32767)) for n in x)) for x ... | moncefmechri/dolphin | docs/DSP/free_dsp_rom/generate_coefs.py | Python | gpl-2.0 | 703 |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import unittest
from pants.engine.internals.addressable import (
MutationError,
NotSerializableError,
addressable,
addressable_dict,
addressable_sequence,
)
from pants... | tdyas/pants | src/python/pants/engine/internals/addressable_test.py | Python | apache-2.0 | 8,357 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Inventory/AppliedItem.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf im... | DenL/pogom-webhook | pogom/pgoapi/protos/POGOProtos/Inventory/AppliedItem_pb2.py | Python | mit | 3,946 |
import os
from seleniumbase import BaseCase
class FileUploadButtonTests(BaseCase):
""" The main purpose of this is to test the self.choose_file() method. """
def test_file_upload_button(self):
self.open("https://www.w3schools.com/jsref/tryit.asp"
"?filename=tryjsref_fileupload_get"... | mdmintz/SeleniumBase | examples/upload_file_test.py | Python | mit | 857 |
import urllib2
import socket
import re
import os
#MOCK addinfurl
class addinfoUrl():
"""class to add info() and getUrl(url=) methods to an open file."""
def __init__(self, url, code, msg):
self.headers = None
self.url = url
self.code = code
self.msg = msg
def info(self):
... | yvess/django-linkcheck | linkcheck/tests/__init__.py | Python | bsd-3-clause | 5,551 |
"""
description: open addressing Hash Table for CS 141 Lecture
file: hashtable.py
language: python3
author: sps@cs.rit.edu Sean Strout
author: scj@cs.rit.edu Scott Johnson
"""
from rit_lib import *
class HashTable(struct):
"""
The HashTable data structure contains a collection of values
where ea... | moiseslorap/RIT | Computer Science 1/Labs/lab9/hashtable.py | Python | mit | 4,321 |
#!/usr/bin/env python3
import argparse, time
import numpy as np
import django
from django.utils import timezone
import datetime, os
import sys
import db6 as db
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BasicBrowser.settings")
django.setup()
from tmv_app.models import *
def read_state(filename, terms):
... | mcallaghan/tmv | BasicBrowser/import_hlda.py | Python | gpl-3.0 | 5,188 |
#!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import shutil
import sys
from util import build_utils
_RESOURCE_CLASSES = [
"R.class",
"R##*.cla... | danakj/chromium | build/android/gyp/jar.py | Python | bsd-3-clause | 4,097 |
# -*- coding: utf-8 -*-
import pytest
from .utils import last_activity
@pytest.mark.usefixtures('versioning_manager', 'table_creator')
class TestActivityCreationWithColumnExclusion(object):
@pytest.fixture
def audit_trigger_creator(self, session, user_class):
session.execute(
'''SELECT au... | kvesteri/postgresql-audit | tests/test_sql_files.py | Python | bsd-2-clause | 1,919 |
"""
The Response class in REST framework is similar to HTTPResponse, except that
it is initialized with unrendered data, instead of a pre-rendered string.
The appropriate renderer is called during Django's template response rendering.
"""
from __future__ import unicode_literals
from django.core.handlers.wsgi import ST... | paulormart/gae-project-skeleton-100 | gae/lib/rest_framework/response.py | Python | mit | 3,150 |
import utils
import operation_registry
import operation_wrappers.base_wrappers as base_wrappers
import types
import exceptions
from protectron import protectron
@utils.doublewrap
def register_operation(func, operation_wrapper=base_wrappers.LocalOperation):
if isinstance(operation_wrapper, types.ClassType):
... | hkrist/ratatoskr | ratatoskr/__init__.py | Python | mit | 843 |
# z39.5er
# v.0.0
# June 1, 2017
# declarations and constants
normalizations = [['!',' '], ['"',' '], ['(',' '], [')',' '], ['-',' '], ['{',' '], ['}',' '], ['<',' '], ['>',' '], [';',' '], [':',' '], ['.',' '], ['?',' '], [',',' '],['[',''], [']',''], ["'",''], ['/',' ']]
stopwords = [ 'a', 'by', 'how', 'that',... | babrahamse/z395er | z395er.py | Python | mit | 4,347 |
from typing import List
class Solution:
def validSquare(
self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]
) -> bool:
def dist(p1: List[int], p2: List[int]):
return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1])
dist_set = set(
... | l33tdaima/l33tdaima | p593m/valid_square.py | Python | mit | 922 |
import glob
import os
import shutil
import copy
import simplejson
from contextlib import contextmanager
from PIL import Image
from PIL.ImageDraw import ImageDraw
from cStringIO import StringIO
from django.conf import settings
from django.test import TestCase
from dju_image import settings as dju_settings
from dju_image... | liminspace/dju-image | tests/tests/tools.py | Python | mit | 3,513 |
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
# in_file = open(from_file)
# indata = in_file.read()
indata = open(from_file).read()
print "The input file is %d bytes long" % len(in... | CodeCatz/litterbox | Pija/LearnPythontheHardWay/ex17.py | Python | mit | 570 |
# Author: Mr_Orange <mr_orange@hotmail.it>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | srluge/SickRage | sickbeard/providers/thepiratebay.py | Python | gpl-3.0 | 5,662 |
#!/usr/bin/env python
# Demonstration GET geo/reverse_geocode
# See https://dev.twitter.com/rest/reference/get/geo/reverse_geocode
from secret import twitter_instance
from json import dump
import sys
tw = twitter_instance()
# [1]
response = tw.geo.reverse_geocode(lat=35.696805, long=139.773828)
# [2]
dump(response... | showa-yojyo/notebook | source/_sample/ptt/geo-reverse_geocode.py | Python | mit | 380 |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from url_obfuscate.decorators import deobfuscate
from url_obfuscate.helpers import obfuscate
def home(request):
links = list()
for i in range(10):
links.append(obfuscate('Name %d' % (i+1)))
return render(request, 'index.html', { 'links': l... | lmanzurv/url_ofbuscate | tests/views.py | Python | apache-2.0 | 573 |
import os
from unittest import TestCase, main
from gruffy import Pie
TARGET_FILE = 'test.png'
class TestPie(TestCase):
def tearDown(self):
os.remove(TARGET_FILE)
def test_writable(self):
g = Pie()
g.data("test1", [1, 2, 3])
g.data("test2", [3, 2, 1])
g.write(TARGET_F... | hhatto/gruffy | test/test_pie.py | Python | mit | 364 |
from datetime import datetime, timedelta
import calendar
DAY_NAMES = [x.lower() for x in calendar.day_name[6:] + calendar.day_name[:6]]
DAY_ABBRS = [x.lower() for x in calendar.day_abbr[6:] + calendar.day_abbr[:6]]
# Choice tuples, mainly designed to use with Django
MINUTE_CHOICES = [(str(x), str(x)) for x in range(0,... | kipe/pycron | pycron/__init__.py | Python | mit | 4,831 |
#!/usr/bin/env python
#
# Copyright (c) 2010, ZX. All rights reserved.
# Copyright (c) 2016, Capitar. All rights reserved.
#
# Released under the MIT license. See LICENSE file for details.
#
import netaddr
import netifaces
import socket
import os
import os.path
import re
import sys
import subprocess
import time
__ve... | keesbos/fwmacro | fwmacro.py | Python | mit | 78,450 |
# Copyright 2008 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | htcondor/job_hooks | module/socketutil.py | Python | apache-2.0 | 2,064 |
from django.contrib import admin
from itxland.search.models import SearchTerm
class SearchTermAdmin(admin.ModelAdmin):
list_display = ('__unicode__','ip_address','search_date')
list_filter = ('ip_address', 'user', 'q')
exclude = ('user',)
admin.site.register(SearchTerm, SearchTermAdmin)
| davidhenry/ITX-Land | search/admin.py | Python | mit | 293 |
#!/usr/bin/env python
# *-* coding: UTF-8 *-*
"""Tuxy dorește să împlementeze un nou paint pentru consolă.
În timpul dezvoltării proiectului s-a izbit de o problemă
pe care nu o poate rezolva singur și a apelat la ajutorul tău.
El dorește să adauge o unealtă care să permită umplerea unei
forme închise.
Exemplu:
Por... | c-square/python-lab | python/solutii/daniel_toncu/paint/fill.py | Python | mit | 3,131 |
try:
from StringIO import StringIO
except ImportError:
from io import StringIO # nopyflakes
| SurfasJones/djcmsrc3 | venv/lib/python2.7/site-packages/cms/utils/compat/string_io.py | Python | mit | 101 |
# Created By: Virgil Dupras
# Created On: 2009-11-01
# 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/g... | fokusov/moneyguru | qt/controller/profit/sheet.py | Python | gpl-3.0 | 953 |
#!/usr/bin/env python
# Copyright 2013 YouView TV Ltd.
# License: LGPL v2.1 or (at your option) any later version (see
# https://github.com/drothlis/stb-tester/blob/master/LICENSE for details).
"""Generates reports from logs of stb-tester test runs created by 'run'."""
import collections
import glob
import itertools... | wmanley/stb-tester | stbt-batch.d/report.py | Python | lgpl-2.1 | 4,660 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
def get_notification_config():
return { "for_doctype":
{
"Issue": {"status": "Open"},
"Warranty Claim": {"status": "Open"},
"Task": {"statu... | shft117/SteckerApp | erpnext/startup/notifications.py | Python | agpl-3.0 | 1,380 |
import json
from django_api_tools.APIModel import APIModel, UserAuthCode
from django_api_tools.APIView import APIUrl, ReservedURL, StatusCode
from django_api_tools.tests.models import Foo, Bar, Baz, Qux, TestProfile
from django_api_tools.tests.views import TestAPIView
from django.test import TestCase
from django.test... | szpytfire/django-api-tools | django_api_tools/tests/tests.py | Python | mit | 24,690 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
from django.db.models import Q
def reconvert_social_work(apps, schema_editor):
pass
def convert_social_work(apps, schema_editor):
"""
Migrations 00... | fragaria/BorIS | boris/services/migrations/0015_socialwork.py | Python | mit | 3,466 |
"""
Cobbler settings - ``/etc/cobbler/settings`` file
=================================================
The Cobbler settings file is a **YAML** file and the standard Python ``yaml``
library is used to parse it.
Sample input::
kernel_options:
ksdevice: bootif
lang: ' '
text: ~
Examples:
... | wcmitchell/insights-core | insights/parsers/cobbler_settings.py | Python | apache-2.0 | 698 |
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 limitation the rights to us... | EmanueleCannizzaro/scons | test/Progress/spinner.py | Python | mit | 2,221 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Common types, and routines for manually loading types from file
via GCC.
"""
import glob
import os
import subprocess
import sys
import tempfile
import gdb
import pwndbg.events
import pwndbg.gcc
import pwndbg.memoize
module = sys.modules[__name__]
def is_pointer(va... | anthraxx/pwndbg | pwndbg/typeinfo.py | Python | mit | 5,640 |
##############################################################################
# Copyright (c) 2013-2017, 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... | TheTimmy/spack | var/spack/repos/builtin/packages/py-numpy/package.py | Python | lgpl-2.1 | 7,907 |
import sys
from time import time
import inspect
from importlib import import_module
from copy import deepcopy
from collections import defaultdict, OrderedDict
#import warnings
import numpy as np
import scipy as sp
import pymake.io as io
from pymake import logger
from sklearn.pipeline import make_pipeline
class Mod... | dtrckd/pymake | pymake/model.py | Python | gpl-3.0 | 17,406 |
""" Python Character Mapping Codec
For the Jape Konstanz encoding
Bernard Sufrin
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
... | RBornat/jape | dev/Unicode/jape_konstanz.py | Python | gpl-2.0 | 3,436 |
# usage: python setup.py pydexe
from pyd.support import setup, Extension, pydexe_sanity_check
import platform
pydexe_sanity_check()
projName = "datetime"
setup(
name=projName,
version='1.0',
ext_modules=[
Extension("datetime", ['datetime.d'],
build_deimos=True,
d_lump=True,
... | ariovistus/pyd | tests/deimos_unittests/datetime/setup.py | Python | mit | 368 |
#!/usr/bin/python2.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
# $Id$
#
# Copyright (C) 1999-2006 Keith Dart <keith@kdart.com>
#
# 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... | xiangke/pycopia | core/pycopia/inet/cgi_test.py | Python | lgpl-2.1 | 4,619 |
from couchpotato import get_session
from couchpotato.core.event import fireEvent, addEvent
from couchpotato.core.helpers.encoding import toUnicode, simplifyString, ss, sp
from couchpotato.core.helpers.variable import getExt, getImdb, tryInt, \
splitString
from couchpotato.core.logger import CPLog
from couchpotato.c... | lebabouin/CouchPotatoServer-develop | couchpotato/core/plugins/scanner/main.py | Python | gpl-3.0 | 32,904 |
def kab(n):
if n in (0, 1):
return [1]
for i in range(n):
b yield i * 2
| TakesxiSximada/TIL | python/python3.6/err2.py | Python | apache-2.0 | 95 |
"""
pyText2Pdf - Python script to convert plain text files into Adobe
Acrobat PDF files.
Version 1.2
Author: Anand B Pillai <abpillai at lycos dot com>
Keywords: python, tools, converter, pdf, text2pdf, adobe, acrobat,
processing.
Copyright (C) 2003-2004 Free Software Foundation, Inc.
This file is... | guptalab/dnacloud | source/pytxt2pdf.py | Python | mit | 20,500 |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(name="xlsxi18n",
py_modules=['xlsxi18n'],
version="0.0",
description="Simple command line utility to generate Android language files for your app from xlsx files.",
license="MIT",
author="Andrea Stagi",
author_... | astagi/xlsxi18n | setup.py | Python | mit | 641 |
"""
Miscellaneous utilities.
"""
import collections
import dis
import sys
import pyte
from pyte.exc import ValidationError
from . import tokens
PY36 = sys.version_info[0:2] >= (3, 6)
def ensure_instruction(instruction: int) -> bytes:
"""
Wraps an instruction to be Python 3.6+ compatible. This does nothing o... | SunDwarf/Pyte | pyte/util.py | Python | mit | 5,105 |
#!/usr/bin/env python
# coding: utf-8
# pylint: disable=global-statement
"""This module runs dev_appserver.py, creates virtualenv, performs requirements check,
creates necessary directories
"""
from distutils import spawn
import argparse
import os
import platform
import shutil
import sys
#############################... | madvas/gae-angular-material-starter | run.py | Python | mit | 8,998 |
from pylab import *
def gradient_scalar_wrt_scalar_non_const_dt(x,t):
x = x.astype(float64).squeeze()
t = t.astype(float64).squeeze()
x_grad = zeros_like(x)
x_grad[0] = (x[1] - x[0]) / (t[1] - t[0])
x_grad[-1] = (x[-1] - x[-2]) / (t[-1] - t[-2])
x_grad[1:... | stanford-gfx/Horus | Code/flashlight/gradientutils.py | Python | bsd-3-clause | 745 |
"""
Marginal Utility of Information, as defined here: http://arxiv.org/abs/1409.4708
"""
import warnings
from itertools import product
import numpy as np
from scipy.linalg import LinAlgWarning
from scipy.optimize import OptimizeWarning
from .base_profile import BaseProfile, profile_docstring
from .information_partit... | dit/dit | dit/profiles/marginal_utility_of_information.py | Python | bsd-3-clause | 5,164 |
# -*- coding: utf-8 -*-
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Manage SDK chroots.
This script is used for manipulating local chroot environments; creating,
deleting, downloading, etc. ... | endlessm/chromium-browser | third_party/chromite/scripts/cros_sdk.py | Python | bsd-3-clause | 44,269 |
"""Particle system example."""
from galry import *
import pylab as plt
import numpy as np
import numpy.random as rdn
import time
import timeit
import os
class ParticleVisual(Visual):
def get_position_update_code(self):
return """
// update position
position.x += velocities.x * tloc;
... | rossant/galry | examples/fountain.py | Python | bsd-3-clause | 3,841 |
with open("day-10.txt") as f:
nav_sys = f.read().rstrip().splitlines()
pairs = {
")": "(",
"]": "[",
"}": "{",
">": "<",
}
points = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
score = 0
for line in nav_sys:
brackets = []
for char in line:
if char in pairs:
... | scorphus/sparring | advent-of-code/2021/day-10-part-1.py | Python | mit | 540 |
#
# Epour - A bittorrent client using EFL and libtorrent
#
# Copyright 2012-2013 Kai Huuhko <kai.huuhko@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 Software Foundation; either version 2 of the ... | maikodaraine/EnlightenmentUbuntu | apps/epour/epour/gui/Preferences.py | Python | unlicense | 21,829 |
# coding=utf-8
# Reverse a linked list from position m to n. Do it in-place and in one-pass.
#
# For example:
# Given 1->2->3->4->5->NULL, m = 2 and n = 4,
#
# return 1->4->3->2->5->NULL.
#
# Note:
# Given m, n satisfy the following condition:
# 1 ≤ m ≤ n ≤ length of list.
# Definition for singly-linked list.
# class ... | jigarkb/CTCI | LeetCode/092-M-ReverseLinkedListII.py | Python | mit | 1,109 |
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
from mopy.mojo_python_tests_runner import MojoPythonTestRunner
def main():
test_dir_list = [
# Tests of... | jianglu/mojo | mojo/tools/run_mojo_python_tests.py | Python | bsd-3-clause | 799 |
def split_range_lower(rng):
parts = str(rng).split()
if len(parts) != 3:
return None
if parts[2].strip() == 'less':
return 0
return int(parts[0].replace(',',''))
def split_range_upper(rng):
parts = str(rng).split()
if len(parts) != 3:
... | CivicKnowledge/metatab-packages | census.gov/variance_replicates/census.gov-varrep_tables_support-2011e2015/lib/split.py | Python | mit | 524 |
from django.template import Template, Context
def test_get_setting_as_variable(settings):
settings.GREETING = "Hola"
template = Template(
r'{% load config %}{% get_setting "GREETING" as greeting %}{{ greeting }}'
)
c = Context({})
assert template.render(c) == "Hola"
| cmheisel/ebdocker-py | sample/hello/tests.py | Python | mit | 297 |
import argparse
__all__ = ['Args']
Args = None
def parse():
global Args
parser = argparse.ArgumentParser(description='Voctogui')
parser.add_argument('-v', '--verbose', action='count', default=0,
help="Set verbosity level by using -v, -vv or -vvv.")
parser.add_argument('-c',... | voc/voctomix | voctogui/lib/args.py | Python | mit | 1,875 |
__author__ = 'Lai Tash'
from .library import AND, NOT, XOR, OR
from .library import Button
from .library import PersistentSwitch
from .library import Informer
from .library import Switch
from .library import Timer
from .library import Latch | LaiTash/starschematic | stargate/library/__init__.py | Python | gpl-3.0 | 241 |
# -*- coding: utf-8 -*-
import requests
from framework.auth import Auth
from website import util
from website import settings
from osf.models import MailRecord
def record_message(message, nodes_created, users_created):
record = MailRecord.objects.create(
data=message.raw,
)
record.users_created.... | laurenrevere/osf.io | website/conferences/utils.py | Python | apache-2.0 | 1,976 |
from django import template
register = template.Library()
@register.filter
def rating_score(obj, user):
if not user.is_authenticated() or not hasattr(obj, '_ratings_field'):
return False
ratings_descriptor = getattr(obj, obj._ratings_field)
try:
rating = ratings_descriptor.get(user=user).s... | Tmr/django-simple-ratings | ratings/templatetags/ratings_tags.py | Python | mit | 415 |
# -*- twisted.conch.test.test_mixin -*-
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
import time
from twisted.internet import reactor, protocol
from twisted.trial import unittest
from twisted.test.proto_helpers import StringTransport
from twisted.conch import mixin
class TestB... | sorenh/cc | vendor/Twisted-10.0.0/twisted/conch/test/test_mixin.py | Python | apache-2.0 | 1,110 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\qad_dimstyle_diff.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DimStyle_Diff_Dialog(object):
def setupUi(se... | gam17/QAD | qad_dimstyle_diff_ui.py | Python | gpl-3.0 | 5,215 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | hryamzik/ansible | lib/ansible/modules/cloud/google/gcp_compute_image.py | Python | gpl-3.0 | 29,989 |
# coding=utf-8
"""
Programa que escanea todos los recursos de cada tipo y construye
el __init__ respectivo
Uso
$ __scan__.py -arg1 -arg2 -arg3
-folder
Game template
Autor: PABLO PIZARRO @ ppizarro ~
Fecha: ABRIL 2015
"""
# Importación de librerías de sistema
from datetime import date
import o... | ppizarror/Ned-For-Spod | resources/__scan__.py | Python | gpl-2.0 | 9,806 |
"""
Description:
This provides a VTK widget for pyGtk. This embeds a vtkRenderWindow
inside a GTK widget. This is based on GtkVTKRenderWindow.py.
The extensions here allow the use of gtkglext rather than gtkgl and
pygtk-2 rather than pygtk-0. It requires pygtk-2.0.0 or later.
There is a working example ... | b3c/VTK-5.8 | Wrapping/Python/vtk/gtk/GtkGLExtVTKRenderWindow.py | Python | bsd-3-clause | 17,778 |
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_appconfig import AppConfig
from flask_wtf import Form, RecaptchaField
from wtforms import TextField, HiddenField, ValidationError, RadioField,\
BooleanField, SubmitField
from wtforms.validators import Required
class ExampleF... | miguelgrinberg/flask-bootstrap | sample_application/sample_app.py | Python | apache-2.0 | 1,821 |
"""
Merge an arbitrary number of settings files ordered by priority.
This script will generate a new settings yaml file and write it to standard
output. The files are ordered on the command line from lowest priority to
highest priority, where higher priority settings override lower priority ones.
Usage:
pip ins... | edx/edx-load-tests | util/merge_settings.py | Python | apache-2.0 | 1,441 |
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2001-2006 Donald N. Allingham
# Copyright (C) 2008 Gary Burton
# Copyright (C) 2010 Nick Hall
# Copyright (C) 2011 Tim G L Lyons
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU G... | beernarrd/gramps | gramps/plugins/lib/libplaceview.py | Python | gpl-2.0 | 17,547 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from cx_Freeze import setup, Executable
from command import cmds
import glob
includes = []
excludes = []
packages = []
setup(
name='lit',
version='0.1.4',
install_requires=[
'wmi',
'pywin32'
],
cmdclass=cmds,
options={
'bu... | Answeror/lit | setup.py | Python | mit | 866 |
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('maps.urls')),
url(r'^venue/', include('venues.urls')),
u... | shaunokeefe/hoponit | hoponit/hoponit/urls.py | Python | mit | 734 |
# -*- coding: utf-8 -*-
import codecs
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx.util.nodes import set_source_info
class FileInputDirective(Directive):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = Tr... | tomka/CATMAID | sphinx-doc/source/exts/catmaid_fileinclude.py | Python | gpl-3.0 | 3,363 |
#
# grc.py -- Ginga Remote Control module
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import threading
import ginga.util.six as six
if six.PY2:
import xmlrpcli... | rajul/ginga | ginga/util/grc.py | Python | bsd-3-clause | 5,101 |
#!/usr/bin/env python
#
# Crypto.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi... | pdelsante/thug | thug/DOM/Crypto.py | Python | gpl-2.0 | 1,079 |
import _plotly_utils.basevalidators
class TickwidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="tickwidth", parent_name="layout.ternary.caxis", **kwargs
):
super(TickwidthValidator, self).__init__(
plotly_name=plotly_name,
pa... | plotly/plotly.py | packages/python/plotly/plotly/validators/layout/ternary/caxis/_tickwidth.py | Python | mit | 467 |
# Downloading dependancies
import nltk
nltk.download("stopwords")
nltk.download("punkt")
nltk.download("wordnet")
# Setup of ambiruptor package
from setuptools import setup
setup(name='ambiruptor',
version='0.1',
description='Disambiguation tool',
author='Ambiruptor',
license='GNU GENERAL PUBLI... | Ambiruptor/Ambiruptor | setup.py | Python | gpl-3.0 | 620 |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class FunctionVersionContentTes... | twilio/twilio-python | tests/integration/serverless/v1/service/function/function_version/test_function_version_content.py | Python | mit | 2,404 |
# Allows the creation of infix operators
# Thanks to Ferdinand Jamitzky
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
class Infix(object):
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x: self.function(other, x))
def __or__(s... | Kevin-Ray-Johnson/DM_Desk_Calc | Infix.py | Python | gpl-2.0 | 976 |
"""
Command to retrieve aggregated student forums data in a .csv
"""
import csv
import optparse
import os
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from instructor.utils import collect_studen... | jbassen/edx-platform | lms/djangoapps/instructor/management/commands/collect_student_forums_data.py | Python | agpl-3.0 | 1,826 |
{
'name': 'Control access to Apps',
'version': '1.0.0',
'author': 'IT-Projects LLC, Ivan Yelizariev',
'category': 'Tools',
'website': 'https://twitter.com/yelizariev',
'price': 10.00,
'currency': 'EUR',
'depends': [
'web_settings_dashboard',
'access_restricted'
],
... | berpweb/berp_custom | access_apps/__openerp__.py | Python | agpl-3.0 | 510 |
# -*- coding: utf-8 -*-
# Copyright (C) 2013 by
# Fred Morstatter <fred.morstatter@asu.edu>
# Jordi Torrents <jtorrents@milnou.net>
# All rights reserved.
# BSD license.
import random
from networkx.utils import not_implemented_for
from networkx.utils import py_random_state
__all__ = ['average_clustering']
__... | kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/networkx/algorithms/approximation/clustering_coefficient.py | Python | gpl-3.0 | 2,210 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.