code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
# !/usr/bin/python
# Written against python 2.7
# Matasano Problem 15
#
# Created by 404 on 15/11/26.
#
# Copyright (c) 2015 404. All rights reserved.
def pkcs7pad_remove(message):
last = message[-1]
length_message = len(message) - ord(last)
for i in xrange(length_message,len(message)):
assert(me... | Han0nly/crypto | solutions/15.py | Python | mit | 445 |
from django.shortcuts import render
from django.http import HttpResponse
import requests
def main(request):
return render(request, 'welcome.html')
def search(request):
return render(request, 'search.html')
def location(request):
return render(request, 'location.html')
| findapad/find_a_pad | find_a_pad_app/views.py | Python | mit | 291 |
#!/usr/bin/env python
#
# redirect data from a TCP/IP connection to a serial port and vice versa
# using RFC 2217
#
# (C) 2009-2015 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier: BSD-3-Clause
import logging
import socket
import sys
import time
import threading
import serial
import serial.rfc2217
cl... | raphaelbs/HomeR | NodeJS/node_modules/modbus-serial/examples/telnet.py | Python | mit | 6,313 |
from .types import Type, BlockType, AbstractWidget
from .connection import Connection
from .filedialog import FileDialog
from .notification import Notification
from .play_button import PlayButton
| AlvarBer/Persimmon | persimmon/view/util/__init__.py | Python | mit | 197 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009-2010 CloudSizzle Team
#
# 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 use,
#... | jpvanhal/cloudsizzle | cloudsizzle/scrapers/utils.py | Python | mit | 1,215 |
# TODO still necessary?
# from bootstrap import admin_actions_registry
from django.db import models
from django.utils.translation import ugettext as _, ugettext_lazy
# TODO still necessary?
# # admin action to be displayed in action row
# from django.core.urlresolvers import reverse
# admin_actions_registry['ip_asse... | dArignac/ip_assembler | ip_assembler/models.py | Python | mit | 4,699 |
from unittest import TestCase
import roxentools
import tempfile
import os
class TestInterfaceCall(TestCase):
def setUp(self):
# Create a temporary directory
self.test_dir = tempfile.mkdtemp()
self.conf_empty = os.path.join(self.test_dir, "empty.conf")
with open(self.conf_empty, '... | whojarr/roxentools | tests/interface/test_interface_call.py | Python | mit | 1,289 |
def do_monkeypatch():
def get_url(self):
return self._view.get_url('%s.%s' % (self._view.endpoint, self._view._default_view))
import flask_admin.menu
flask_admin.menu.MenuView.get_url = get_url | ActiDoo/gamification-engine | gengine/base/monkeypatch_flaskadmin.py | Python | mit | 214 |
"""
flyingsphinx
~~~~~~~~~~~~
:copyright: (c) 2012 by Pat Allan
:license: MIT, see LICENCE for more details.
"""
__title__ = 'flyingsphinx'
__version__ = '0.1.0'
__author__ = 'Pat Allan'
__license__ = 'MIT'
__copyright__ = 'Copyright 2012 Pat Allan'
from .api import API
from .cli impor... | flying-sphinx/flying-sphinx-py | flyingsphinx/__init__.py | Python | mit | 655 |
import os
import sys
import tempfile
import unittest
import mock
import numpy
import chainer
from chainer.backends import cuda
from chainer import link
from chainer import links
from chainer import optimizers
from chainer.serializers import hdf5
from chainer import testing
from chainer.testing import attr
if hdf5._... | aonotas/chainer | tests/chainer_tests/serializers_tests/test_hdf5.py | Python | mit | 14,628 |
import logging
import sys
import datetime
import os
import errno
import copy
from pythonjsonlogger import jsonlogger
from cloghandler import ConcurrentRotatingFileHandler
class LogFactory(object):
'''
Goal is to manage Simple LogObject instances
Like a Singleton
'''
_instance = None
@classme... | quixey/scrapy-cluster | utils/scutils/log_factory.py | Python | mit | 7,753 |
# -*- coding: utf-8 -*-
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including wit... | cryptapus/electrum | electrum/bitcoin.py | Python | mit | 25,370 |
"""
We train a simple Q-Learning algorithm for fraud detection.
"""
import state_space
import action_space
import numpy as np
class BanditAgent:
def __init__(self, do_reward_shaping=False):
self.frequency = np.zeros((state_space.SIZE, action_space.SIZE))
self.avg_reward = np.zeros((state_space.SI... | lmzintgraf/MultiMAuS | learning/agent_bandit.py | Python | mit | 1,093 |
from threading import local
__author__ = 'jhg | https://djangosnippets.org/snippets/3041/'
class SiteID(object):
"""
That class represents a local instance of SiteID. It is used as a local var to save SITE_ID in a thread-safe way.
"""
def __init__(self):
self._site_thread_info = local()
... | jisson/django-simple-domain | django_simple_domain/site_id_local.py | Python | mit | 652 |
import argparse
from datetime import datetime, timedelta
import logging
import os
import re
import stat
import sys
import pyexiv2
import photo_rename
from photo_rename import Filemap, FilemapList, FileMetadata, Harvester
from photo_rename.utils import CustomArgumentParser
logger = logging.getLogger(__name__)
def pr... | eigenholser/jpeg_rename | photo_rename/set_datetime.py | Python | mit | 3,637 |
from test_helper import TestHelper
from app import app, db
from app.models.plant_size import PlantSize
class TestPlantSize(TestHelper):
def test_create_plant_size(self):
ps1 = PlantSize(label='1 Gal')
assert ps1 != None
assert PlantSize.save_to_db(ps1) != False
def test_valid... | CHrycyna/LandscapeTracker | tests/test_plantsize.py | Python | mit | 744 |
"""
CraftyPluginOrganizer v0.8.0
Python 3
Requires modules from pip:
cfscrape
BeautifulSoup4
Linux only, `curl` and `nodejs` packages required.
(add more dependencies from github page for cfscrape)
Download from sites:
SpigotMC.org
GitHub
BukkitDev
Jenkins CI
EngineHub
TODO:
Add support for uncompressing .zip fil... | colebob9/CraftyPluginOrganizer | CPO-Organize.py | Python | mit | 12,328 |
def Endscript(text,*keys):
i = 0
Etext = ""
for Char in text:
Etext += chr((ord(Char)+keys[i])%256)
i += 1
if i >= len(keys):
i = 0
return Etext
NamePlainText = input("Please enter the file name of the plain text: ")
Key = int(input("Please enter encryption key: "))
NameCipherText = input("Please enter the... | Kasemsanm/Python | Security/Encryption/Encryption.py | Python | mit | 488 |
# -*- coding: utf-8 -*-
"""
aerende.configuration
------------------
This module contains the configuration logic for aerende. This includes the
logic for loading a config file, writing a config file none is present, and
the loading of default configuration options.
There are 3 seperate configuration categories, at ... | Autophagy/aerende | aerende/configuration.py | Python | mit | 5,140 |
import unittest
import datetime
from loggerglue.util.parse_timestamp import parse_timestamp
class TestParseTimestamp(unittest.TestCase):
pairs = {
'2003-10-11T12:14:15.003000Z': datetime.datetime(2003, 10, 11, 12, 14, 15, 3000),
'2003-10-11T12:14:15.003Z': datetime.datetime(2003, 10,... | AlekSi/loggerglue | loggerglue/tests/test_parse_timestamp.py | Python | mit | 1,797 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils.importlib import import_module
# Default settings
BOOTSTRAP3_DEFAULTS = {
'jquery_url': '//code.jquery.com/jquery.min.js',
'base_url': '//netdna.bootstrapcdn.com/bootstrap/3.2.0/',
'css_url'... | Titulacion-Sistemas/PythonTitulacion-EV | Lib/site-packages/bootstrap3/bootstrap.py | Python | mit | 2,732 |
"""This file includes a collection of utility functions that are useful for
implementing DQN."""
import gym
import tensorflow as tf
import numpy as np
import random
def huber_loss(x, delta=1.0):
# https://en.wikipedia.org/wiki/Huber_loss
return tf.where(
tf.abs(x) < delta,
tf.square(x) * 0.5,
... | berkeleydeeprlcourse/homework | hw3/dqn_utils.py | Python | mit | 14,060 |
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.login, name='shopify_app_login'),
path('authenticate/', views.authenticate, name='shopify_app_authenticate'),
path('finalize/', views.finalize, name='shopify_app_login_finalize'),
path('logout/', views.logout, name='... | Shopify/shopify_django_app | shopify_app/urls.py | Python | mit | 344 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-05-31 13:21
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('primus', '0036_assetplace'),
]
operations = [
migrations.RenameField(
mo... | sighill/shade_app | primus/migrations/0037_auto_20160531_1521.py | Python | mit | 423 |
# -*- 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 model 'InstagramAccount'
db.create_table('social_instagramaccount', (
('id', self.gf('d... | MadeInHaus/django-social | social/south_migrations/0006_auto__add_instagramaccount.py | Python | mit | 12,343 |
"""Calculate Lumi Show quiz scores."""
from operator import itemgetter
# Define correct answers.
correct = [3, 2, 1, 4, 1, 2, 4, 3, 4, 2, 1, 3]
# Read table details.
active_sheet('discussions')
tables = []
# Set data start row.
row = 5
# Loop through rows until empty row is found.
data_present = True
w... | justsostephen/datanitro-scripts | show-scores/scores.py | Python | mit | 2,311 |
# -*- coding: utf-8 -*-
#
# Sphinx markup documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 18 22:54:33 2009.
#
# 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.
#... | thomaspurchas/rst2pdf | rst2pdf/tests/input/sphinx-multidoc/conf.py | Python | mit | 7,320 |
import unittest
from pgallery.forms import PhotoForm
class PhotoFormTestCase(unittest.TestCase):
def test_form_invalid(self):
form = PhotoForm({})
self.assertFalse(form.is_valid())
| zsiciarz/django-pgallery | tests/test_forms.py | Python | mit | 204 |
import inspect
from django.core.exceptions import ValidationError
from rest_framework import serializers
from django.core.validators import validate_slug
class SerializerRelatedField(serializers.SlugRelatedField):
"""
SerializerRelatedField for DjangoRestFramework
for data add: Slug @from_native
fo... | pombredanne/snippit | snippit/apps/snippet/fields.py | Python | mit | 1,589 |
from conans import ConanFile, CMake
import urllib3
import tarfile
class FltkConan(ConanFile):
name = "FLTK"
version = "1.3.4"
license = "GNU LGPL with exceptions (http://www.fltk.org/COPYING.php)"
url = "https://github.com/trigger-happy/conan-packages"
description = "FLTK widget library for C++"
... | trigger-happy/conan-packages | fltk/conanfile.py | Python | mit | 2,459 |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from coll... | Azure/azure-sdk-for-python | sdk/digitaltwins/azure-digitaltwins-core/tests/_preparer.py | Python | mit | 5,928 |
#!/usr/bin/python3
# scrape HLTV results for CS:GO Matches
from requests import get
from bs4 import BeautifulSoup
import re
from csv import DictWriter
from time import gmtime, strftime
def formatMatch(hltvMatch):
'''
extract match information and format to list
'''
# team names
hltvMatchNames = ... | Schw4rz/csgo_glicko2 | scraper.py | Python | mit | 3,548 |
import base64
import hashlib
import warnings
from gevent.pywsgi import WSGIHandler
from .websocket import WebSocket, Stream
from .logging import create_logger
class Client(object):
def __init__(self, address, ws):
self.address = address
self.ws = ws
class WebSocketHandler(WSGIHandler):
"""
... | mcking49/apache-flask | Python/Lib/site-packages/geventwebsocket/handler.py | Python | mit | 9,388 |
import numpy as np
def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray:
"""
scipy.misc.bytescale had bugs
inputs:
------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
Michael H... | scivision/raspberrypi_raw_camera | pibayer/utils.py | Python | mit | 889 |
# 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 may ... | Azure/azure-sdk-for-python | sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets/_generated/v7_3_preview/models/_models.py | Python | mit | 19,685 |
from abc import ABCMeta, abstractmethod
from complexism.mcore import ModelAtom
from complexism.element import AbsTicker, Event
__author__ = 'TimeWz667'
__all__ = ['AbsActor', 'PassiveActor', 'ActiveActor']
class AbsActor(ModelAtom, metaclass=ABCMeta):
def __init__(self, name, pars=None):
ModelAtom.__init... | TimeWz667/Kamanian | complexism/multimodel/actor.py | Python | mit | 2,187 |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and Contributors
# See license.txt
import frappe
from frappe.integrations.doctype.social_login_key.social_login_key import BaseUrlNotSetError
import unittest
class TestSocialLoginKey(unittest.TestCase):
def test_adding_frappe_social_login_provider(self... | mhbu50/frappe | frappe/integrations/doctype/social_login_key/test_social_login_key.py | Python | mit | 1,273 |
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
"""
class Solution:
# @param prices, a list of integer
# @return ... | Ahmed--Mohsen/leetcode | best_time_to_buy_and_sell_stock.py | Python | mit | 527 |
"""Represent a descriptor of a resource."""
from __future__ import absolute_import
from inspect import isclass
import six
from future.builtins import object
from rotest.management.models import ResourceData
from rotest.management.common.errors import ResourceBuildError
from rotest.management.common.utils import (TYP... | gregoil/rotest | src/rotest/management/common/resource_descriptor.py | Python | mit | 2,988 |
# Kata link: https://www.codewars.com/kata/57fb142297e0860073000064
def product(s):
return s.count('!')*s.count('?')
| chyumin/Codewars | Python/7 kyu/Count the number of exclamation and question mark, return product.py | Python | mit | 122 |
#!C:\Users\saulo\Downloads\sauloal-cufflinksviewer-9364be0\sauloal-cufflinksviewer-9364be0\venvwin\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c11','console_scripts','easy_install'
__requires__ = 'setuptools==0.6c11'
import sys
from pkg_resources import load_entry_point
sys.exit(
load_ent... | sauloal/cufflinksviewer | venvwin/Scripts/easy_install-script.py | Python | mit | 392 |
from header_filter.matchers import Header
def test_and_matcher_supports_bitwise_not(rf):
h_name_1, h_value_1 = 'HTTP_X_A', 'val_x'
h_name_2, h_value_2 = 'HTTP_X_B', 'val_y'
matcher = ~(Header(h_name_1, h_value_1) & Header(h_name_2, h_value_2))
request = rf.get('/', **{h_name_1: h_value_1, h_name_2: h_... | sanjioh/django-header-filter | tests/test_matcher_and.py | Python | mit | 1,834 |
# 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 ... | fhoring/autorest | src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/operations/inheritance_operations.py | Python | mit | 4,687 |
# 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 may ... | Azure/azure-sdk-for-python | sdk/apimanagement/azure-mgmt-apimanagement/azure/mgmt/apimanagement/__init__.py | Python | mit | 841 |
#!/usr/bin/python
"""
Simple point imagery request for Earth Engine
"""
## MIT License
##
## Copyright (c) 2017, krishna bhogaonker
## 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... | krishnab-datakind/mining-data-acquisition | data_gather/EarthEngineSimplePointImageryProcessor.py | Python | mit | 3,293 |
from typing import Dict
from urllib.parse import (
urlencode,
urlunsplit,
)
class ISignEnvironment:
def __init__(self, name: str, netloc: str, scheme: str = "https") -> None:
self.name = name
self.netloc = netloc
self.scheme = scheme
def __repr__(self) -> str:
return f... | Paulius-Maruska/python-isign | src/isign/environment.py | Python | mit | 1,196 |
from rest_framework import serializers
from models import Resource
from votes.models import Vote
from comments.serializers import CommentSerializer
class ResourceSerializer(serializers.ModelSerializer):
"""Resource Serializer"""
comments = CommentSerializer(many=True, read_only=True)
author = serialize... | andela/codango | codango/resources/serializers.py | Python | mit | 1,724 |
# 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 may ... | Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/aio/operations/_local_network_gateways_operations.py | Python | mit | 27,485 |
"""
Functions:
convert_gene_ids
"""
# _convert_gene_ids_biomart
# _convert_gene_ids_local
# _convert_entrez_symbol_to_entrez # uses genefinder
# _find_entrez_gene
#
# _clean_genes_for_biomart
# _remove_dups
# _start_R
GLOBAL_R = None
def _start_R():
global GLOBAL_R
from genomicode import jmath
if GLO... | jefftc/changlab | genomicode/arrayannot.py | Python | mit | 8,944 |
#!/usr/bin/env python3
N = int(input())
memory = []
for each in range(N):
memory.append(input())
Q = int(input())
for each in range(Q):
query = input()
if query not in memory:
print(0)
else:
print(
memory.count(query)
)
| onyb/cpp | HackerRank/Domains/Data_Structures/Arrays/sparse-arrays.py | Python | mit | 275 |
# Generated by Django 3.2.6 on 2021-08-14 22:58
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_m... | pizzapanther/Neutron-Sync | nsync_server/account/migrations/0001_initial.py | Python | mit | 2,873 |
# The MIT License (MIT)
#
# Copyright (c) 2016 Fabian Wenzelmann <fabianwenzelmann@posteo.de>
#
# 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 limitati... | FabianWe/foodle | foodle/foodle_polls/models.py | Python | mit | 5,923 |
import datetime
from HistoryData import HistoryData
from Button import Button
from ButtonGenerator import ButtonGenerator
from typing import Tuple
class History:
def __init__(self):
self.hand_list = []
def add_information(self, center_of_hand, number_of_fingers: int) -> None:
time = datetime.... | BogyMitutoyoCTL/CalculatorCV | History.py | Python | mit | 3,677 |
# DO NOT EDIT THIS FILE!
#
# Python module CosNotifyChannelAdmin__POA generated by omniidl
import omniORB
omniORB.updateModule("CosNotifyChannelAdmin__POA")
# ** 1. Stub files contributing to this module
import CosNotifyChannelAdmin_idl
# ** 2. Sub-modules
# ** 3. End
| amonmoce/corba_examples | omniORBpy-4.2.1/build/python/COS/CosNotifyChannelAdmin__POA/__init__.py | Python | mit | 273 |
## Code to combine the output files per disease from individual differential expression analysis
## Written by Sumaiya Nazeen, nazeen@mit.edu
## Python version 2.7.6
## Platform: 3.13.0-35-gneric #62-Ubuntu (64-bit)
## The output file should preferrably have a .tab extension, so that it can be easily opened with MS Ex... | snz20/3TierMA | combineOutputOfDiffExp.py | Python | mit | 1,613 |
import os
import os.path
import getpass
import json
import time
default = object()
format_version = 1
def get_default_registry_path():
return os.path.join(os.path.expanduser('~'), '.checklists')
def get_default_project_path():
return os.path.join(os.getcwd(), '.checklist')
def json_dump_pretty(data):
... | storborg/checklist | checklist/model.py | Python | mit | 6,789 |
from django.utils import timezone
from waldur_core.structure import models as structure_models
from . import models
def update_daily_quotas(sender, instance, created=False, **kwargs):
if not isinstance(
instance.scope, (structure_models.Project, structure_models.Customer)
):
return
if n... | opennode/waldur-mastermind | src/waldur_mastermind/analytics/handlers.py | Python | mit | 585 |
import logging
from django.contrib.auth.signals import user_login_failed
from django.dispatch import receiver
logger = logging.getLogger(__name__)
@receiver(user_login_failed)
def log_failed_login(sender, **kwargs):
logger.info("login attempt for username '{}' failed".format(
kwargs['credentials']['usern... | zackmdavis/Finetooth | core/signals.py | Python | mit | 333 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-11 08:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tickets', '0016_auto_20161231_0937'),
]
operations = [
migrations.AlterFiel... | prontotools/zendesk-tickets-machine | zendesk_tickets_machine/tickets/migrations/0017_auto_20170111_0809.py | Python | mit | 468 |
FileIn = 'RegDati/Out/AllUnique.csv'
FileOut = FileIn.replace("AllUnique.csv","ExtractB.csv")
fIn = open(FileIn, 'r')
fOut = open(FileOut, 'w')
fOut.write('"Prov","Comu","Dist","CodScuola","Descrizione","ScAssiciataA","Indirizzo","ScPrincipaleCon"'+"\n")
cont = 0
for line in fIn:
cont+=1
if cont > 1:
... | scarimp/BB_UU_PYPA | ExtractFromUniqueB.py | Python | mit | 1,058 |
#!/usr/bin/env python
"""
Copyright (c) 2014-2022 Maltrail developers (https://github.com/stamparm/maltrail/)
See the file 'LICENSE' for copying permission
"""
import re
from core.common import retrieve_content
__url__ = "https://www.maxmind.com/en/high-risk-ip-sample-list"
__check__ = "Sample List of Higher Risk I... | stamparm/maltrail | trails/feeds/maxmind.py | Python | mit | 662 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import re
import cgi
__all__ = ['highlight']
class Highlighter(object):
"""
Do syntax highl... | SEA000/uw-empathica | empathica/gluon/highlight.py | Python | mit | 12,945 |
"""Engine for writing data to a JSON file"""
import os
import json
from retriever.lib.models import Engine, no_cleanup
from retriever import DATA_DIR
class DummyConnection:
def cursor(self):
pass
def commit(self):
pass
def rollback(self):
pass
def close(self):
pass
cla... | bendmorris/retriever | engines/jsonengine.py | Python | mit | 5,130 |
# Download the Python helper library from twilio.com/docs/python/install
import os
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
# To set up environmental variables, see http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_... | TwilioDevEd/api-snippets | messaging/services/service-create/service-create.7.x.py | Python | mit | 505 |
import os
from distutils.core import setup
# Utility function to read files. Used for the long_description.
def read(fname):
""" Reads the description of the package from the README.md file. """
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def get_version():
""" Extract the version o... | carze/cutlass | setup.py | Python | mit | 1,303 |
from django import forms
class StripeTokenForm(forms.Form):
stripe_token = forms.CharField()
| PDFGridder/PDFGridder | billing/forms.py | Python | mit | 99 |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="family", parent_name="volume.colorbar.title.font", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
paren... | plotly/plotly.py | packages/python/plotly/plotly/validators/volume/colorbar/title/font/_family.py | Python | mit | 524 |
class _fileobject(object):
"""Faux file object attached to a socket object."""
default_bufsize = 8192
name = "<socket>"
__slots__ = ["mode", "bufsize", "softspace",
# "closed" is a property, see below
"_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"]
def __ini... | longde123/MultiversePlatform | lib/IPCE/Lib/_fileobject.py | Python | mit | 6,599 |
from odict import *
| jmchilton/galaxy-central | modules/cookbook/__init__.py | Python | mit | 20 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def HostVirtualSwitchBeaconConfig(vim, *args, **kwargs):
'''This data object type describ... | xuru/pyvisdk | pyvisdk/do/host_virtual_switch_beacon_config.py | Python | mit | 1,557 |
from __future__ import print_function
#
# Made by duponc_j, modified by sourio_b while supervised by sbriss_a in case he fucked things up (and he did)
# Slightly modified by Arignir
# Version: 1.4.1
#
'''
An Epitech norme checker
Usage: python norme.py <dir to scan> [-nocheat] [-verbose] [-score] [-libc]
-verbose: ... | Arignir/Epitech-norm-linter | norminette/norm.py | Python | mit | 19,880 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# django-asana documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 21 11:12:30 2018.
#
# 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... | sbywater/django-asana | docs/conf.py | Python | mit | 5,037 |
"""
picture.py
Author: Daniel Wilson
Credit: none
Assignment:
Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape).
Use at least:
1. Three different Color objects.
2. Ten different Sprite objects.
3. One (or more) RectangleAsset objects.
4. One (or more) CircleAsset o... | danielwilson2017/Picture | picture.py | Python | mit | 2,001 |
import os
RASP_URL = "http://rasp.linta.de/GERMANY/"
suffix = "lst.d2.png"
today = "curr"
tomorrow = "curr+1"
parameters = {
"Cu Cloudbase where Cu Potential>0": "zsfclclmask",
"Thermal Updraft Velocity and B/S ratio": "wstar_bsratio",
}
here = os.path.abspath(os.path.dirname(__file__))
hours = ["07", "08", ... | tomislater/raspgif | raspgif/constants.py | Python | mit | 358 |
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import os
from direct.showbase import AppRunnerGlobal
from direct.directnotify import DirectNotifyGlobal
from pandac.PandaModules import *
class PetNameGenerator:
notify = DirectNotifyGlobal.directNotify.newCatego... | ToonTownInfiniteRepo/ToontownInfinite | toontown/pets/PetNameGenerator.py | Python | mit | 3,155 |
import itertools
import functools
import operator
def squared(x): return x**2
print("Itérateurs créés à partir d'une map")
iterator_of_powers_of_2_for_first_numbers = map(squared, range(1, 10))
print("La fonction map retourne un objet iterator :",
iterator_of_powers_of_2_for_first_numbers)
print("C'est bien u... | TGITS/programming-workouts | python/misc/learning_python/map_examples.py | Python | mit | 3,614 |
# output-json
from typing import Optional
from pydantic import BaseModel, Field
from pydantic.fields import ModelField
class RestrictedAlphabetStr(str):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, value, field: ModelField):
alphabet = f... | samuelcolvin/pydantic | docs/examples/schema_with_field.py | Python | mit | 865 |
# Specify version in Semantic style (with PEP 440 pre-release specification)
__version__ = "2.0.0a1"
| radiocosmology/alpenhorn | alpenhorn/__init__.py | Python | mit | 101 |
import random
from flask import Flask
from restea import errors
from restea.resource import Resource
from restea.adapters.flaskwrap import FlaskResourceWrapper
from restea import fields
app = Flask(__name__)
# Dummy data for the Resource
sites = [
{
'id': i,
'name': 'my__site_{}'.format(i),
... | bodbdigr/restea | example.py | Python | mit | 1,577 |
import falcon
from io import StringIO
from sqlalchemy import func, distinct, desc, text
from sqlalchemy.exc import SQLAlchemyError
from db import session
import model
import util
class UserExport(object):
def _stringify_users(self, users, sum_points):
"""
Pomocna metoda pro zapis uzivatelu do so... | fi-ksi/web-backend | endpoint/admin/userExport.py | Python | mit | 7,209 |
import requests
import gw2api
import gw2api.v2
from auth_test import AuthenticatedTestBase
class TestGuildAuthenticated(AuthenticatedTestBase):
guild_id = None
@classmethod
def setUpClass(cls):
super(TestGuildAuthenticated, cls).setUpClass()
if not cls.api_key:
return
... | hackedd/gw2api | test/guild_test.py | Python | mit | 3,196 |
# coding: utf8
{
' (leave empty to detach account)': ' (leave empty to detach account)',
' Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.': ' Module is the main communications ... | dotskapes/dotSkapes | languages/vi.py | Python | mit | 250,282 |
""" The file is responsable for cart in flask-webpage """
from flask import current_app as app
from flask_seguro.products import Products
class Cart(object):
""" The classe is responsable for cart in webpage """
def __init__(self, cart_dict=None):
""" Initializing class """
cart_dict = cart... | rochacbruno/python-pagseguro | examples/flask/flask_seguro/cart.py | Python | mit | 1,715 |
# coding=utf-8
class _Users:
def __init__(self, client=None):
self.client = client
def get_favorites_for_user(self, user_gid, params=None, **options):
"""Get a user's favorites
:param str user_gid: (required) A string identifying a user. This can either be the string \"me\", an email, ... | Asana/python-asana | asana/resources/gen/users.py | Python | mit | 8,331 |
from mk2.plugins import Plugin
from mk2.events import ServerOutput, StatPlayerCount, ServerStop, ServerEvent, Event
class Check(object):
alive = True
timeout = 0
time = 0
warn = 0
def __init__(self, parent, **kw):
self.dispatch = parent.dispatch
self.console = parent.console
... | SupaHam/mark2 | mk2/plugins/monitor.py | Python | mit | 7,104 |
# -*- coding: utf-8 -*-
"""
Configuration data for the system.
"""
import os
data_dir = None
FILES = {}
def get_config_paths(directory):
"""Sets the data directory containing the data for the models."""
assert os.path.isdir(directory), 'Invalid data directory'
return { key: os.path.join(directory, val... | papower1/nlpnet-for-korean | nlpnet/config.py | Python | mit | 5,209 |
import os
import random
import sqlalchemy
import sqlalchemy.orm
import sqlalchemy.ext
import sqlalchemy.ext.declarative
SqlAlchemyBase = sqlalchemy.ext.declarative.declarative_base()
class Measurement(SqlAlchemyBase):
__tablename__ = 'Measurement'
id = sqlalchemy.Column(sqlalchemy.Integer,
... | mikeckennedy/write-pythonic-code-demos | code/ch_04_collections/_03_slice_support.py | Python | mit | 1,180 |
from __future__ import print_function, unicode_literals
from django.core.management.base import BaseCommand
from django.apps import apps
from optparse import make_option
from resize.fields import ResizedImageField
from resize.utils import resize_image
class Command(BaseCommand):
help = 'Ensures that all Resize... | defrex/django-resize | resize/management/commands/resize_fields.py | Python | mit | 1,954 |
import time
from slackclient import SlackClient
from slackBot.recommender import recommend, query_item
# starterbot's ID as an environment variable
# BOT_ID = os.environ.get("BOT_ID")
BOT_ID = "ID"
# constants
AT_BOT = "<@" + BOT_ID + ">"
EXAMPLE_COMMAND = "!do"
CHECK = "!check"
LAKSHMI = "!lakshmi"
CODE = "!code"
... | kanishkamisra/something-like | slackBot/starterbot.py | Python | mit | 2,886 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Abstract class with common functions
#
# Copyright (c) 2012-2014 Alan Aguiar alanjas@hotmail.com
# Copyright (c) 2012-2014 Butiá Team butia@fing.edu.uy
# Butia is a free and open robotic platform
# www.fing.edu.uy/inco/proyectos/butia
# Facultad de Ingeniería - Univers... | nvazquez/Turtlebots | plugins/butia/pybot/functions.py | Python | mit | 10,197 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @date Dec 13 2015
# @brief
#
import sys
import threading
import logging
from logging.handlers import (
TimedRotatingFileHandler,
SocketHandler,
DatagramHandler,
SysLogHandler,
SMTPHandler,
HTTPHandler,
)
from logging import LoggerAdapter
t... | kaka19ace/kklogger | kklogger/logger.py | Python | mit | 7,452 |
# coding: utf-8
from __future__ import absolute_import
from google.appengine.ext import ndb
from api import fields
import model
class Artist(model.Base):
name = ndb.StringProperty()
artist_type = ndb.StringProperty()
gender = ndb.StringProperty(default='none', choices=['male', 'female', 'none'])
we... | ssxenon01/music-app | main/model/artist.py | Python | mit | 618 |
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import utils
import plotly.graph_objs as go
from plotly import tools
from scipy.stats import pearsonr
# main database
db = create_engine('sqlite:///data/processed.db')
def get_params(dataset):
tb = pd.read_sql_table(dataset, db, index_col... | lzlarryli/limelight | app/parameter_importance.py | Python | mit | 7,053 |
import cv2
import numpy as np
import sys
from collections import OrderedDict
import matplotlib.pyplot as plt
from gaussian_pyramid import *
from lucas_kanade import *
def backwarp(img, flow):
h, w = flow.shape[:2]
flow_map = -flow.copy()
flow_map[:,:,0] += np.arange(w)
flow_map[:,:,1] += np.arange(h)[... | rohithredd94/Computer-Vision-using-OpenCV | Warping-using-LK/flow_warping.py | Python | mit | 3,807 |
import mobula as M
import mobula.operators as O
import numpy as np
def test_exp():
N, C, H, W = 2,3,4,5
a = np.random.random((N, C, H, W))
l = O.Exp(a)
y = l.eval()
l.dY = np.random.random(l.Y.shape)
l.backward()
exp = np.exp(a)
assert np.allclose(y, exp)
assert np.allclose(l.dX, ex... | wkcn/mobula | tests/test_ops/test_exp_log.py | Python | mit | 895 |
# -*- coding: utf-8 -*-
from django.conf import settings
ARTICLE_PER_PAGE = getattr(settings, 'ARTICLE_PER_PAGE', 10)
| indexofire/gork | src/gork/application/article/settings.py | Python | mit | 120 |
#!/usr/bin/env python
#
# Electrum - lightweight Fujicoin client
# Copyright (C) 2012 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including with... | fujicoin/electrum-fjc | electrum/gui/qt/paytoedit.py | Python | mit | 8,129 |
# Problem:
# Write a program that reads from the console an integer n and prints the numbers from 1 to 2n.
n = int(input())
for i in range(0, n + 1, 1):
print(pow(2,i))
| YaniLozanov/Software-University | Python/PyCharm/07.Advanced Loops/03. Powers of Two.py | Python | mit | 176 |
# -*- coding: utf-8 *-*
from redis._compat import b, iteritems, iterkeys
class TestListCommands(object):
def test_binary_lists(self, r):
mapping = {
b('foo bar'): [b('1'), b('2'), b('3')],
b('foo\r\nbar\r\n'): [b('4'), b('5'), b('6')],
b('foo\tbar\x07'): [b('7'), b('8')... | katakumpo/niceredis | tests/commands/test_list.py | Python | mit | 5,629 |
from setuptools import setup, find_packages
setup(name='MODEL1110130000',
version=20140916,
description='MODEL1110130000 from BioModels',
url='http://www.ebi.ac.uk/biomodels-main/MODEL1110130000',
maintainer='Stanley Gu',
maintainer_url='stanleygu@gmail.com',
packages=find_packages(... | biomodels/MODEL1110130000 | setup.py | Python | cc0-1.0 | 377 |