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
import logging from telegram import ParseMode from telegram.ext import CommandHandler from . import rollem commands = ["roll"] logger = logging.getLogger(__package__) def register(dp): dp.add_handler(CommandHandler(commands, roll)) logger.info(f"Registered for commands {commands}") def roll(update, conte...
xurxodiz/iria
iria/modules/dice/dice.py
Python
mit
1,022
#! /usr/bin/python # -*- coding: utf-8 -*- # PythenMusicDeamon (pyMD) Server # # $Id: $ # # Copyright (c) 2017 Anna-Sophia Schroeck <annasophia.schroeck at outlook.de> # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # fr...
RoseLeBlood/pyMD
pyMD-Server.py
Python
mit
7,762
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import Provider, ProviderAccount class GitHubAccount(ProviderAccount): pass class GitHubProvider(Provider): id = 'github' name = 'GitHub' package = 'allauth.socialaccount.providers.github' account_class = GitHub...
uroslates/django-allauth
allauth/socialaccount/providers/github/models.py
Python
mit
373
# -*- coding: utf-8 -*- # # Copyright (c) 2012-2015, CRS4 # # 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, copy, modify...
crs4/clay
tests/test_mqtt.py
Python
mit
4,621
# -*- coding: utf-8 -*- import os import uuid import signal import docker import tarfile import checksumdir from contextlib import contextmanager from logzero import logger from config import DEFAULT_LIMITS, CPU_TO_REAL_TIME_FACTOR, DEFAULT_GENERATE_FILE_SIZE, TEMP_DIR, WORKING_DIR from exceptions import CrazyBoxErr...
USTB-LETTers/judger
utils.py
Python
mit
9,209
import os import random import numpy as np from scipy.misc import imresize, imread from scipy.ndimage import zoom from collections import defaultdict DATA_MEAN = np.array([[[123.68, 116.779, 103.939]]]) def preprocess_img(img, input_shape): img = imresize(img, input_shape) img = img - DATA_MEAN img = img[...
Vladkryvoruchko/PSPNet-Keras-tensorflow
utils/preprocessing.py
Python
mit
2,350
# -*- coding: utf-8 -*- """ Common templates tags for porticus """ from six import string_types from django.conf import settings from django import template from django.utils.safestring import mark_safe from django.shortcuts import get_object_or_404 from porticus.models import Gallery, Album register = template.Libr...
emencia/porticus
porticus/templatetags/porticus_tags.py
Python
mit
6,013
"""Authentication process""" import cherrypy import lib.db_users as db_users def check_auth(required=True, user_role=None): """Check authentication""" if required: user = db_users.user_by_session(cherrypy.session.id) if user == None: cherrypy.lib.sessions.expire() raise ...
JB26/Bibthek
lib/auth.py
Python
mit
1,040
# -*- coding: utf-8 -*- """ Utility methods for motif """ import csv from mir_eval import melody import numpy as np import os def validate_contours(index, times, freqs, salience): '''Check that contour input is well formed. Parameters ---------- index : np.array Array of contour numbers t...
rabitt/motif
motif/utils.py
Python
mit
4,174
#!/usr/bin/env python # This setup relies on setuptools since distutils is insufficient and # badly hacked code from setuptools import setup, find_packages version = '0.0.1' author = 'David-Leon Pohl' author_email = 'david-leon.pohl@rub.de' with open('requirements.txt') as f: required = f.read().splitlines() set...
DavidLP/hass_scripts
setup.py
Python
mit
1,045
#!/usr/bin/env python3 from setuptools import find_packages,setup VERSION = '0.1.0.dev1' install_requires = [ 'beautifulsoup4>=4.4.1', 'requests>=2.4.3', ] setup( name="Library API", version=VERSION, description="Privides access to various libraries (book borrowing places, not code libraries).", ...
BenjaminEHowe/library-api
setup.py
Python
mit
830
import cv2 import numpy as np HESSIAN_THRESHOLD = 400 FLANN_INDEX_KDTREE = 0 def test_surfmatch(ref_img, query_img, num_kp=None, min_match=10): ''' Tests the SURF matcher by finding an homography and counting the percentage of inliers in said homography. Parameters ---------- ref_img: ndarra...
sebasvega95/feature-matching
tests/surf_test.py
Python
mit
2,042
from movie.models import Movie import urllib as urllib import urllib2,json import os,glob from django.template import defaultfilters import unicodedata author_list = [] BASE='http://api.rottentomatoes.com/api/public/v1.0/' KEY='mz7z7f9zm79tc3hcaw3xb85w' movieURL=BASE+'movies.json' def main(): print('starting.')...
sameenjalal/mavenize-beta
mavenize/lib/db/DownloadAuthors.py
Python
mit
6,573
from dolfin import has_lu_solver_method lusolver = "superlu_dist" if has_lu_solver_method("superlu_dist") else "default" direct = dict( reuse = False, iterative = False, lusolver = lusolver, ) direct_reuse = dict( reuse = True, iterative = False, lusolver = lusolver, luparams = dict( ...
mitschabaude/nanopores
nanopores/tools/solvermethods.py
Python
mit
3,451
# Given two strings, write a method to decide if one is a permutation of the other def is_permutation(s, t): ''' time complexity: O(NlogN) ''' return sorted(s) == sorted(t) def is_permutation(s, t): ''' time complexity: O(N) ''' from collections import Counter return Counter(s) == Counter(t)
carlxshen/interview-questions
ctci/chapter-1/1-2.py
Python
mit
313
from __future__ import division import sys import os import pyglet from pyglet.gl import * from pyglet.window import key import mode import gui class MenuMode(mode.Mode): name = "menu_mode" def connect(self, controller): super(MenuMode, self).connect(controller) self.init_opengl() self...
vickenty/ookoobah
ookoobah/menu_mode.py
Python
mit
2,284
import os import sys def pytest_configure(config): os.environ['PYTHONPATH'] = ':'.join(sys.path)
xsteadfastx/ftp_rsync_backup
conftest.py
Python
mit
103
# -*- coding: utf-8 -*- # # Created on 2/7/16 by maersu from core.utils import IOS from django.utils.encoding import smart_str from interactions.handlers.base import BaseWriter import re from translations.models import TranslatedItem IOS_KEY_VALUE = re.compile(r'"(?P<key>.*?)"\s*?=\s*?"(?P<value>.*?)";', re.MULTILINE...
placeB/translation-service
server/interactions/handlers/ios.py
Python
mit
1,296
from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'image_uploader.settings') app = Celery('image_uploader') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS...
haridas/image_uploader_py
image_uploader/celery.py
Python
mit
416
import logging import os import time import subprocess def number_of_nodes(): _file = open(os.environ['HOME'] + "/machinefile", "r") n = len ([ l for l in _file.readlines() if l.strip(' \n') != '' ]) _file.close() return n return def log(msg): logging.debug("COMPUTATION: " + msg) return def co...
jmhal/elastichpc
beta/trials/static/Computation.py
Python
mit
1,718
""" Tests the methods within the flask-script file manage.py """ import os import unittest import testing.postgresql from biblib.app import create_app from biblib.manage import CreateDatabase, DestroyDatabase, DeleteStaleUsers from biblib.models import Base, User, Library, Permissions from sqlalchemy import create_eng...
adsabs/biblib-service
biblib/tests/unit_tests/test_manage.py
Python
mit
7,727
# This file is part of beets. # Copyright 2011, Adrian Sampson. # # 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, copy, ...
aspidites/beets
beets/autotag/match.py
Python
mit
18,831
""" Name: sdeconn.py Description: Utility functions for sde connections Author: blord-castillo (http://gis.stackexchange.com/users/3386/blord-castillo) Do on the fly connections in python using Sql Server direct connect only. Eliminates the problem of database connection files being inconsistent from machi...
DougFirErickson/arcplus
ArcToolbox/Scripts/sdeconn.py
Python
mit
4,782
import numpy from chainer.backends import cuda from chainer.functions.loss import black_out from chainer import link from chainer.utils import walker_alias from chainer import variable class BlackOut(link.Link): """BlackOut loss layer. .. seealso:: :func:`~chainer.functions.black_out` for more detail. ...
ronekko/chainer
chainer/links/loss/black_out.py
Python
mit
1,916
#!/usr/bin/env python """ -------------------------------------------------------------------------------- Created: Jackson Lee 1/28/14 This script reads in a fasta file and a tab delimited text file of annotations and replaces the header line with matched annotations Input fasta file format: any fasta file I...
leejz/misc-scripts
add_annotations_to_fasta.py
Python
mit
3,801
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import farms.models class Migration(migrations.Migration): dependencies = [ ('farms', '0001_initial'), ] operations = [ migrations.AlterField( model_name='cropseason', ...
warnes/irrigatorpro
irrigator_pro/farms/migrations/0002_auto_20150513_0054.py
Python
mit
1,045
import unittest from katas.kyu_7.ninja_vs_samurai_strike import Warrior class WarriorTestCase(unittest.TestCase): def setUp(self): self.ninja = Warrior('Ninja') self.samurai = Warrior('Samurai') def test_equals(self): self.samurai.strike(self.ninja, 3) self.assertEqual(self.n...
the-zebulan/CodeWars
tests/kyu_7_tests/test_ninja_vs_samurai_strike.py
Python
mit
337
# Copyright (c) 2016, Will Thames and contributors # Copyright (c) 2018, Ansible Project from ansiblelint import AnsibleLintRule class LineTooLongRule(AnsibleLintRule): id = '204' shortdesc = 'Lines should be no longer than 120 chars' description = ( 'Long lines make code harder to read and ' ...
MatrixCrawler/ansible-lint
lib/ansiblelint/rules/LineTooLongRule.py
Python
mit
506
import os import pytest import yaml from yml_config import Config @pytest.fixture() def data(): return { 'bool': False, 'number': 1, 'string': 'test_string', 'sequence': ['item1', 'item2', 'item3'], 'mapping': { 'key1': 'value1', 'key2': { ...
bvujicic/yml-to-env
tests/test_config.py
Python
mit
1,945
import re class FeaToolsParserSyntaxError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # used for removing all comments commentRE = re.compile("#.*") # used for finding all strings stringRE = re.compile( "\"" # " "([^...
jamesgk/feaTools
Lib/feaTools/parser.py
Python
mit
23,544
# -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __all__ = ["OneDSearch"] import os import h5py import numpy as np from .pipeline import Pipeline from ._compute import compute_hypotheses class OneDSearch(Pipeline): cache_ext = ".h5" query_parameters = dict( ...
dfm/ketu
ketu/one_d_search.py
Python
mit
3,255
import os from django.conf import settings from django.contrib import auth from django.contrib.auth.decorators import login_required, user_passes_test from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.db import connection from django.http ...
gwu-libraries/social-feed-manager
sfm/ui/views.py
Python
mit
6,575
from core.himesis import Himesis, HimesisPreConditionPatternLHS import cPickle as pickle from uuid import UUID class HNew1orMoreNamePart2_CompleteLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HNew1orMoreNamePart2_CompleteLHS. ...
levilucio/SyVOLT
UMLRT2Kiltera_MM/Properties/Multiplicity/Himesis/HNew1orMoreNamePart2_CompleteLHS.py
Python
mit
12,682
from PyQt4 import QtCore,QtGui import re # Initialize Qt resources from file resources.py from sessionClasses import * class DataSource(): """ gestisce le operazioni di lettura e scrittura sui settings di Qt per la gestione degli utenti """ def __init__(self,company,application): """ @param string: name-space...
arpho/mmasgis5
mmasgis/DataSource.py
Python
mit
2,673
import re from .default import DefaultParser class NoseParser(DefaultParser): name = "nose" def command_matches(self, command): return "nosetests" in command or "-m nose" in command def num_passed(self, result): return self.num_total(result) - self.num_failed(result) def num_total(...
skoczen/polytester
polytester/parsers/nose.py
Python
mit
1,085
""" Problem 2c. Write a while loop that sums the values 1 through end, inclusive. end is a variable that we define for you. So, for example, if we define end to be 6, your code should print out the result: 21 which is 1 + 2 + 3 + 4 + 5 + 6. """ i = 1 sm = 0 while (i <= end): sm += i i += 1 print sm
CptDemocracy/Python
MITx-6.00.1x-EDX-Introduction-to-Computer-Science/Week-2/Lecture-3/problem2c.py
Python
mit
318
""" Test utility functions """ from unittest.mock import Mock import csv import json import requests import pytest from mailchimp3 import MailChimp from mcwriter.utils import (serialize_dotted_path_dict, serialize_lists_input, serialize_members_input, ...
pocin/kbc-mailchimp-writer
tests/test_utils.py
Python
mit
15,874
from abc import abstractmethod from pgmpy.extern.six.moves import reduce class BaseFactor(object): """ Base class for Factors. Any Factor implementation should inherit this class. """ def __init__(self, *args, **kwargs): pass @abstractmethod def is_valid_cpd(self): pass def...
khalibartan/pgmpy
pgmpy/factors/base.py
Python
mit
3,183
import sys import PConstant class DummySchema(object): def __init__(self): self.request_body = {} def schema(): return self.request_body class TrialSchema(object): def __init__(self): self.request_body = { "settings": { "analysis": { ...
somilasthana/esearch
ESDatabaseMetaStore.py
Python
mit
4,873
# KidsCanCode - Game Development with Pygame video series # Shmup game - part 3 # Video link: https://www.youtube.com/watch?v=33g62PpFwsE # Collisions and bullets import pygame import random WIDTH = 480 HEIGHT = 600 FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, ...
kidscancode/gamedev
tutorials/shmup/shmup-3.py
Python
mit
3,817
class Response(dict): def __init__(self, *args, **kwargs): super(Response, self).__init__(*args, **kwargs) for (key, value) in self.items(): self[key] = self.convert_value(value) def __getattr__(self, name): return self.__getitem__(name) def __getitem__(self, item): ...
accepton/accepton-python
accepton/response.py
Python
mit
1,000
from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you dont want that, hit CTRL-C(^C)." print "If you do want that, hit RETURN." raw_input("?") print"Opening the file..." target = open(filename,'w') print "Truncating the file. Goodbye!" target.truncate() print "Now ...
AisakaTiger/Learn-Python-The-Hard-Way
ex16.py
Python
mit
662
import os import io import re import time import json import random import datetime import itertools import functools import sqlite3 import sphinxapi from contextlib import closing import flask from flask import (Flask, request, redirect, session, url_for, render_template, current_app, jsonify) fro...
langdev/log.langdev.org
logviewer/app.py
Python
mit
12,597
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding # from codecs import open from os import path here = path.abs...
cloudconsole/cloudconsole
setup.py
Python
mit
4,203
from django import template from ..models import get_related_documents register = template.Library() @register.filter(name='get_related_documents') def related_documents(model): return get_related_documents(model)
yourlabs/django-documents
documents/templatetags/documents_tags.py
Python
mit
222
import requests from django.conf import settings from django.db import models from django.urls import reverse_lazy from UserManagement.models import Attendent, ExpertProfile, Team # Import for Google Maps Plugin from django_google_maps import fields as map_fields from django.utils.text import slugify from datetime imp...
SkillSmart/ConferenceManagementSystem
SessionManagement/models.py
Python
mit
6,287
import unittest import tempfile import shutil import os from tempfile import TemporaryDirectory from threading import Thread from eubin import pop3 from mockserver import POP3Server class TestStatelog(unittest.TestCase): def setUp(self): self.tmpdir = TemporaryDirectory() self.logpath = os.path.joi...
fujimotos/Eubin
test/test_pop3.py
Python
mit
5,035
#!/usr/bin/env python # -*- coding: utf-8 -*- # Django settings for mysite project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', ...
mozillazg/django-simple-projects
projects/custom-context-processors/mysite/settings.py
Python
mit
5,731
from hcsr04sensor import sensor # Created by Al Audet # MIT License def main(): """Calculate the depth of a liquid in centimeters using a HCSR04 sensor and a Raspberry Pi""" trig_pin = 17 echo_pin = 27 # Default values # unit = 'metric' # temperature = 20 hole_depth = 80 # cent...
alaudet/hcsr04sensor
recipes/metric_depth.py
Python
mit
979
from pabiana import Area, repo from pabiana.utils import multiple from . import utils area = Area(repo['area-name'], repo['interfaces']) premise = utils.setup config = { 'clock-name': 'clock', 'clock-slots': multiple(1, 6), 'context-values': { 'temperature': 18, 'window-open': False } } @area.register def i...
kankiri/pabiana
demos/smarthome/smarthome/__init__.py
Python
mit
1,208
# -*- coding: utf-8 -*- """This module contains base class for dictionary entry""" class Entry(): """Store info of a word that is one part of speech. Store pronounciation,sound, part of speech, word explanation and example sentences about one word or expression. """ def __init__(self): ...
RihanWu/vocabtool
dict/base_class.py
Python
mit
1,940
""" Wave class Jacob Dein 2016 nacoustik Author: Jacob Dein License: MIT """ from sys import stderr from os import path from sox import file_info import numpy as np from scipy.io import wavfile class Wave: """Create wave object""" def __init__(self, wave): """ Parameters ---------- wave: file path...
jacobdein/nacoustik
nacoustik/wave.py
Python
mit
1,700
"""Read any number of files and write a single merged and ordered file""" import time import fastparquet import numpy as np import pandas as pd def generate_input_files(input_filenames, n, max_interval=0): for i_fn in input_filenames: df = _input_data_frame(n, max_interval=...
rheineke/log_merge
main.py
Python
mit
2,419
import unittest from yahtr.utils.attr import get_from_dict, copy_from_instance from yahtr.utils.color import Color class Dummy: pass class TestAttr(unittest.TestCase): def setUp(self): self.dummy = Dummy() self.args = ['p1', 'p2', 'p3'] self.d = {'p1': 'p1', 'p2': None, 'p4': {}} ...
fp12/yahtr
tests/tests_utils.py
Python
mit
1,541
# -*- coding: utf-8 -*- """Exception classes.""" class JSONAPIError(Exception): """Base class for all exceptions in this package.""" pass class IncorrectTypeError(JSONAPIError, ValueError): """Raised when client provides an invalid `type` in a request.""" pointer = '/data/type' default_message = '...
Tim-Erwin/marshmallow-jsonapi
marshmallow_jsonapi/exceptions.py
Python
mit
976
""" Second-Hand-Shop Project @author: Malte Gerth @copyright: Copyright (C) 2015 Malte Gerth @license: MIT @maintainer: Malte Gerth @email: mail@malte-gerth.de """ from django import template from events.models import get_active_event __author__ = "Malte Gerth <mail@malte-gerth.de>" __copyright__ = "Co...
JanMalte/secondhandshop_server
src/volunteers/templatetags/volunteer.py
Python
mit
613
#! /usr/bin/env python from hashlib import md5 from Crypto.Cipher import AES from Crypto import Random import struct class PaddingError(Exception): pass def derive_key_and_iv(password, salt, key_length, iv_length): d = d_i = '' while len(d) < key_length + iv_length: d_i = md5(d_i + password + sal...
mindeng/crypto-utils
padding-oracle-attack/poa_test.py
Python
mit
5,516
import math print("Usage:") print("City names can be as specific as needed, for example: San Fransico, CA, or Chicago, IL, USA") cityFirst = input("Enter the name of the first city: ") citySecond = input("Enter the name of the second city: ")
tanishq-dubey/personalprojects
Distance Between Cities/distCities.py
Python
mit
252
import re from markdown.preprocessors import Preprocessor from markdown import Extension __version__ = "0.1.1" class JournalPreprocessor(Preprocessor): pattern_time = re.compile(r'^(\d{4})$') pattern_date = re.compile(r'^(\d{4}-\d{2}-\d{2})$') def run(self, lines): return [self._t1(self._t2(line...
iandennismiller/mdx_journal
mdx_journal/__init__.py
Python
mit
992
import numpy as np import sympy from ..helpers import book, untangle, z from ._albrecht import albrecht_4 as stroud_s2_9_1 from ._albrecht import albrecht_5 as stroud_s2_11_2 from ._albrecht import albrecht_6 as stroud_s2_13_2 from ._albrecht import albrecht_7 as stroud_s2_15_2 from ._albrecht import albrecht_8 as str...
nschloe/quadpy
src/quadpy/s2/_stroud.py
Python
mit
2,646
# encoding: utf-8 """ Test suite for the docx.oxml.parts module. """ from __future__ import absolute_import, print_function, unicode_literals import pytest from .unitdata.document import a_body from ..unitdata.section import a_type from ..unitdata.text import a_p, a_pPr, a_sectPr class DescribeCT_Body(object): ...
guilhermebr/python-docx
tests/oxml/parts/test_document.py
Python
mit
2,154
class Flower: """A flower.""" def __init__(self, name, petals, price): """Create a new flower instance. name the name of the flower (e.g. 'Spanish Oyster') petals the number of petals exists (e.g. 50) price price of each flower (measured in euros) """ self...
GeorgeGkas/Data_Structures_and_Algorithms_in_Python
Chapter2/R-2/4.py
Python
mit
1,278
import numpy as np def sigmoid(x): """Calculate sigmoid""" return 1 / (1 + np.exp(-x)) x = np.array([0.5, 0.1, -0.2]) target = 0.6 learning_rate = 0.5 weights_input_hidden = np.array([[0.5, -0.6], [0.1, -0.2], [0.1, 0.7]]) weights_hidden_ou...
Kulbear/deep-learning-nano-foundation
lectures/backpropagation.py
Python
mit
1,296
# -*- coding: utf-8 -*- # # Mock module for the Unicorn Hat package # # Copyright (c) 2015 carlosperate http://carlosperate.github.io # # Licensed under The MIT License (MIT), a copy can be found in the LICENSE file # # This is a simple mock module that will print to screen the unicorn hat package # calls. It is used t...
carlosperate/LightUpPi-Alarm
LightUpHardware/unicornhatmock.py
Python
mit
1,231
import sys import os if len(sys.argv) < 2: print "Please include a template to knit." sys.exit(1) if sys.argv[1] == 'list': print "Available templates:\n" print "\n".join(os.listdir('./templates')) sys.exit(0) try: with open("./templates/%s" % sys.argv[1], 'r') as f: template = f.read...
staab/maria-code
knitter/main.py
Python
mit
493
from openpyxl import workbook, load_workbook xl = load_workbook(filename='./ipaddr.xlsx', data_only=True) xs = xl.active col_rang = xl['Sheet1'] cell_rang = xs['A1':'A2'] #print(col_rang['A'].value) print ('Getting Data From :', xl.get_sheet_names()) for row in xs.iter_rows(): for cell in row: ipaddr = cel...
phasedscum/python-as-a-waffle
Scratch Dir/Excel Testing/exceltest.py
Python
mit
397
# Write a program to check whether a given number is an ugly number. # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. # Note that 1 is typically treated as an ugly number. class Solution(object): ...
JiangKlijna/leetcode-learning
py/263 Ugly Number/UglyNumber.py
Python
mit
660
from .. import Provider as BaseProvider class Provider(BaseProvider): """ source: https://ja.wikipedia.org/wiki/%E8%81%B7%E6%A5%AD%E4%B8%80%E8%A6%A7 """ jobs = [ "アイドル", "アーティスト", "アートディレクター", "アナウンサー", "アニメーター", "医師", "イラストレーター", "医療事務員...
joke2k/faker
faker/providers/job/ja_JP/__init__.py
Python
mit
1,635
x, y = 999, 999 pals = [] def is_palindrome(num): strnum = str(num) for i in range(len(strnum)/2): if strnum[i]!=strnum[-1-i]: return False return True while x>0: while y>0: if is_palindrome(x*y): pals.append(x*y) y -= 1 x -= 1 y = 999 print 'palindrome is:', max(pals)
davidxmoody/kata
project-euler/completed/first-attempt/euler4.py
Python
mit
289
""" CLI program to continually send a morse string. Usage: test [-h] [-s c,w] <string> where -h means print this help and stop -s c,w means set char and word speeds and <string> is the morse string to repeatedly send The morse sound is created in a separate thread. """ import sys import os import...
rzzzwilson/morse_trainer
test.py
Python
mit
2,002
#!/usr/bin/env python """ Ask a manual question using human strings by referencing the name of a single sensor. Also supply a sensor filter that limits the column data that is shown to values that contain Windows (which is short hand for regex match against .*Windows.*). Also supply filter options that re-fetches any...
tanium/pytan
EXAMPLES/PYTAN_API/ask_manual_question_sensor_with_filter_and_3_options.py
Python
mit
5,155
from main import app, db from main.security import security, user_datastore from flask.ext.blogging import SQLAStorage, BloggingEngine # configure the bloggin storeage for the blog.db # using multiple database bound to sqlalchemy storage = SQLAStorage(db=db, bind="blog") # create all the tables db.create_all() # sta...
slippers/blogging_security
main/blogging/__init__.py
Python
mit
718
#!flask/bin/python from request_logger import app app.run(host='0.0.0.0')
i1caro/request_logger
run.py
Python
mit
75
# -*- coding: utf-8 -*- from django.shortcuts import render from django.views.generic import View, ListView, DetailView from .models import Living, LivingType from endless_pagination.views import AjaxListView class LivingList(AjaxListView): model = Living # queryset = Living.objects.filter(is_publish=True)#.o...
Guest007/vgid
apps/living/views.py
Python
mit
1,978
''' Lista 3b - Exercício 3 Verifique se um inteiro positivo n é primo. Felipe Nogueira de Souza Twitter: @_outrofelipe ''' n = int(input('Informe um número inteiro positivo: ')) i = 2 primo = True while i <= n - 1: if n % i == 0: primo = False break i += 1 if primo: print('O número %d é p...
outrofelipe/Python-para-zumbis
lista-3b/03_primo.py
Python
mit
386
from racks import __version__ import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup dependencies = ['docopt', 'termcolor'] def publish(): os.system("python setup.py sdist upload") if sys.argv[-1] == "publish": publish() sys.exit() setup( ...
myusuf3/racks
setup.py
Python
mit
1,126
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
Sorsly/subtle
google-cloud-sdk/lib/surface/runtime_config/configs/waiters/delete.py
Python
mit
2,419
""" Statusdb module""" __version__ = "1.0.0"
SciLifeLab/statusdb
statusdb/__init__.py
Python
mit
45
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.md')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.md')) as f: CHANGES = f.read() requires = [ 'arrow', 'celery', 'psycopg2>=2.7.0', # reg...
bradmwalker/wanmap
setup.py
Python
mit
1,279
""" Created on 2013-1-19 @author: Administrator """ import urllib.request import smtplib for line in urllib.request.urlopen('http://www.baidu.com'): line = line.decode('gb2312') print(line) server = smtplib.SMTP('localhost') server.sendmail('quchunguang@example.org', 'quchunguang@gmail.com', """To: quchungua...
quchunguang/test
testpy3/testinternet.py
Python
mit
408
#!python # encoding: utf-8 # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License # Version 1.1 (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....
herove/dotfiles
sublime/Packages/SublimeCodeIntel/libs/codeintel2/util.py
Python
mit
28,763
"""Main Fabric deployment file for CloudBioLinux distribution. This installs a standard set of useful biological applications on a remote server. It is designed for bootstrapping a machine from scratch, as with new Amazon EC2 instances. Usage: fab -H hostname -i private_key_file install_biolinux which will call...
chapmanb/cloudbiolinux
fabfile.py
Python
mit
19,514
from __future__ import unicode_literals __version__ = '0.8.0.1'
jstoxrocky/lifelines
lifelines/version.py
Python
mit
65
''' Window Pygame: windowing provider based on Pygame .. warning:: Pygame has been deprecated and will be removed in the release after Kivy 1.11.0. ''' __all__ = ('WindowPygame', ) # fail early if possible import pygame from kivy.compat import PY2 from kivy.core.window import WindowBase from kivy.core impo...
inclement/kivy
kivy/core/window/window_pygame.py
Python
mit
17,048
from os import getenv from django.conf import settings def _setting(key, default): return getenv(key, default) or getattr(settings, key, default) # API key from evnironment by default API_KEY = _setting("ONFIDO_API_KEY", None) # Webhook token - see https://documentation.onfido.com/#webhooks WEBHOOK_TOKEN = _s...
yunojuno/django-onfido
onfido/settings.py
Python
mit
1,275
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import base64 from typing import TYPE_CHECKING from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.p...
Azure/azure-sdk-for-python
sdk/identity/azure-identity/azure/identity/_internal/aadclient_certificate.py
Python
mit
1,944
import pytest from viper import compiler valid_list = [ """ x: public(num) """, """ x: public(num(wei / sec)) y: public(num(wei / sec ** 2)) z: public(num(1 / sec)) def foo() -> num(sec ** 2): return self.x / self.y / self.z """ ] @pytest.mark.parametrize('good_code', valid_list) def test_publ...
NedYork/viper
tests/parser/syntax/test_public.py
Python
mit
394
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import from builtins import zip from builtins import str from builtins import range from lxml import etree import sys import os.path from . import data_prep_utils import re import csv from argparse import Ar...
datamade/parserator
parserator/manual_labeling.py
Python
mit
7,110
#!/usr/bin/env python #--------------------------------------- # IMPORTS #--------------------------------------- import test from pymake2 import * #--------------------------------------- # FUNCTIONS #--------------------------------------- @target @depends_on('my_target_3') def my_target_1(conf): pass @targ...
philiparvidsson/pymake2
tests/make_depends_circular.py
Python
mit
610
from distutils.core import setup setup( name = 'Crollo', version = '1.0.1', packages = ['crollo',], license = 'MIT', long_description = open('README.md').read(), )
davidnjakai/bc-8-todo-console-application
setup.py
Python
mit
169
#!/usr/bin/python3 """ Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of t...
algorhythms/LeetCode
443 String Compression.py
Python
mit
1,906
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <rawcell> # #!/usr/bin/env python # <codecell> from __future__ import division from __future__ import with_statement import numpy as np from pylab import ion import matplotlib as mpl from matplotlib.path import Path from matplotlib import pyplot as plt from matp...
jllanfranchi/phys597_computational2
landau_ch19_problem19.3.2/p9x3x2_v2.py
Python
mit
7,841
import datetime from django.core import validators class Crontab: """ Simplified Crontab Support "minute hour weekday" components of a standard cron job. - "*/15 2,7,15 1-5" means "every fifteen minutes, on hours 2 7 15, Monday-Friday" - Minutes are from 0-59, hours from 0-23, and days from 0(Su...
aclowes/yawn
yawn/utilities/cron.py
Python
mit
4,118
#!/usr/bin/env python # encoding: utf-8 """ pascals-triangle-ii.py Created by Shuailong on 2016-02-20. https://leetcode.com/problems/pascals-triangle-ii/. """ class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ lastrow = [] ...
Shuailong/Leetcode
solutions/pascals-triangle-ii.py
Python
mit
754
import Levenshtein import json from string_util import cleanString ''' This script merges camp ids into the data from ./data/playaevents-camps-2013.json OR ./results/camp_data_and_locations.json using playaevents-events-2013 (The Playa Events API Events feed) ''' # Threshold under which to discard...
Burning-Man-Earth/iBurn-Data
scripts/2013/playa_data/merge_camp_id_from_events.py
Python
mit
2,285
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from base import GAETestCase from datetime import datetime, date from decimal import Decimal from question_app.question_model import Question from routes.questions.edit import index, save from mommygae import mommy from tekton.gae.middlewa...
raphaelrpl/portal
backend/test/question_tests/question_edit_tests.py
Python
mit
1,434
from django.conf.urls import patterns, url urlpatterns = patterns('parcels.views', url(r'^$', 'index', name='index'), url(r'^list/$', 'list_parcels', name='list_parcels'), url(r'^add_shipment/$', 'add_parcel'), url(r'^shipment/(?P<shipment_id>\d+)/$', 'shipment_info', name="single_shipment"), url(r...
festlv/latvijas-pasta-toolis
parcels/urls.py
Python
mit
467
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django from django.forms import Select from django.forms.models import modelform_factory from django.test import TestCase from django.utils import translation from django.utils.encoding import force_text try: from unittest import skipIf except: ...
velfimov/django-countries
django_countries/tests/test_fields.py
Python
mit
8,503
from utils import CanadianScraper, CanadianPerson as Person import json import re import requests COUNCIL_PAGE = 'http://winnipeg.ca/council/' class WinnipegPersonScraper(CanadianScraper): def scrape(self): # https://winnipeg.ca/council/wards/includes/wards.js # var COUNCIL_API = 'https://data.w...
opencivicdata/scrapers-ca
ca_mb_winnipeg/people.py
Python
mit
1,948
import tensorflow as tf STATE = tf.Variable(0, name='counter') #print STATE.name ONE = tf.constant(1) new_value = tf.add(STATE, ONE) update = tf.assign(STATE, new_value) init = tf.initialize_all_variables() # must have if define variable with tf.Session() as SESS: SESS.run(init) for _ in range(3): ...
zhaotai/tensorflow-practice
variable.py
Python
mit
366