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/env python
# -*- coding: UTF-8 -*-
"""
from the data of edge formation/deletion, find the persisting edges and their monthly REL ST
"""
from collections import defaultdict
import codecs
import os
import json
import numpy as np
from igraph import *
IN_DIR = "../../../DATA/General/"
os.chdir(IN_DIR)
F_IN = ... | sanja7s/SR_Twitter | src_graph/edges_persisting_REL_ST.py | Python | mit | 6,379 |
# -*- coding: utf-8 -*-
"""
@file
@brief Module *pymmails*.
Functions to automatically grab and send mails.
"""
from .grabber.mail_exception import MailException
from .grabber.email_message import EmailMessage
from .grabber.mailboximap import MailBoxImap
from .grabber.mailbox_mock import MailBoxMock
from .render.email_... | sdpython/pymmails | src/pymmails/__init__.py | Python | mit | 1,048 |
import _plotly_utils.basevalidators
class LenmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="lenmode", parent_name="sunburst.marker.colorbar", **kwargs
):
super(LenmodeValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/plotly.py | packages/python/plotly/plotly/validators/sunburst/marker/colorbar/_lenmode.py | Python | mit | 501 |
from __future__ import division, unicode_literals
from django.core.exceptions import ValidationError
from rest_framework import serializers
from rest_framework.relations import HyperlinkedIdentityField
from apps.container.models import Container, Trip
from core.utils.funct_dates import convert_str_in_datetime
from cor... | jonaqp/heroku | apps/container/api/serializers.py | Python | mit | 7,585 |
import os.path
import sys
sys.path.insert(0, os.path.abspath('lib'))
| rcarmo/rss2imap-gae | appengine_config.py | Python | mit | 69 |
"""Test phial config."""
from phial import Phial
def test_uses_default_config_when_not_specified() -> None:
"""Test phial using default config."""
bot = Phial("test-token")
assert bot.config == Phial.default_config
def test_config_override() -> None:
"""Test config can be overriden."""
bot = Phi... | sedders123/phial | tests/bot/test_phial_config.py | Python | mit | 1,122 |
import concurrent.futures
import json
import time
import traceback
from copy import deepcopy
from typing import Callable, Dict, List, Optional
from urllib import parse
import requests
import urllib3
from requests.exceptions import HTTPError
import demistomock as demisto
from CommonServerPython import *
from CommonSer... | demisto/content | Packs/QRadar/Integrations/QRadar_v2/QRadar_v2.py | Python | mit | 86,392 |
"""Tests for the template tags of the ``outlets`` app."""
from django.test import TestCase
from . import factories
from ..templatetags import outlets_tags
class GetOutletCountriesTestCase(TestCase):
"""Tests for the ``get_outlet_countries`` template tag."""
longMessage = True
def setUp(self):
se... | bitmazk/django-outlets | outlets/tests/outlet_tags_tests.py | Python | mit | 540 |
from mpworker import ProcessMixin
import os
import asyncio
from time import sleep
from multiprocessing import Value
import unittest
from math import factorial
run = asyncio.get_event_loop().run_until_complete
class ExampleClass(ProcessMixin):
def __init__(self, *args, **kwargs):
self.args = args
s... | dustyrockpyle/mpworker | mpworker/tests.py | Python | mit | 5,228 |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
setup(
name='nnClassify',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py an... | PatrickgHayes/nnClassify | setup.py | Python | mit | 3,809 |
# -*- coding: utf-8 -*-
# Copyright (C) 2005 Joe Wreschnig
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""Read a... | achang97/YouTunes | lib/python2.7/site-packages/mutagen/flac.py | Python | mit | 31,346 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of tbucket daemon released under the MIT license.
# See the LICENSE file for more information.
import tornadis
from tbucket.config import Config
TORNADIS_POOL = None
def get_redis_pool():
global TORNADIS_POOL
if TORNADIS_POOL is None:
... | thefab/tbucket | tbucket/redis.py | Python | mit | 477 |
# 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/appplatform/azure-mgmt-appplatform/azure/mgmt/appplatform/v2020_11_01_preview/operations/_config_servers_operations.py | Python | mit | 28,398 |
class Solution:
def reverseString(s):
"""
:type s: str
:rtype: str
"""
if s is None or len(s) <= 1:
return s
i = 0
j = len(s) - 1
sa = list(s)
while (i < j):
tmp = sa[i]
sa[i] = sa[j]
sa[j] = tmp... | euccas/CodingPuzzles-Python | leet/source/twopointers/reverse_string.py | Python | mit | 509 |
import glob
import pandas as pd
import numpy as np
pd.set_option('display.max_columns', 50) # print all rows
import os
os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/correct_phylo_files")
normalB = glob.glob("binary_position_RRBS_normal_B_cell*")
mcell = glob.glob("binary_position_RRBS_NormalBCD19pCD27... | evanbiederstedt/RRBSfun | trees/chrom_scripts/normal_chr16.py | Python | mit | 25,844 |
#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# 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... | danodemano/monitoring-scripts | temp_readings.py | Python | mit | 2,768 |
from seabreeze.pyseabreeze.features._base import SeaBreezeFeature
# Definition
# ==========
#
# TODO: This feature needs to be implemented for pyseabreeze
#
class SeaBreezeOpticalBenchFeature(SeaBreezeFeature):
identifier = "optical_bench"
def get_fiber_diameter_microns(self) -> int:
raise NotImpleme... | ap--/python-seabreeze | src/seabreeze/pyseabreeze/features/opticalbench.py | Python | mit | 965 |
import os
import math
#import itertools
import numpy
#import xlwt
import csv
numpy.set_printoptions(threshold='nan')
from collections import OrderedDict
import subprocess
plate = ["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10","A11","A12","B1","B2","B3","B4","B5","B6","B7","B8","B9","B10","B11","B12",
"C1","C2","C3... | bargho/plateParser | plateParser.py | Python | mit | 6,126 |
# Import and setup this blueprint.
from sanic import Blueprint, response
from sanic_session import InMemorySessionInterface
bp_middleware = Blueprint("middleware")
session_interface = InMemorySessionInterface()
@bp_middleware.middleware
async def return_head(request):
if request.method == "HEAD":
retur... | catlinman/catlinman.com | blueprints/middleware.py | Python | mit | 612 |
from django.apps import AppConfig
class Config(AppConfig):
name = 'pangolinfog.users'
verbose_name = 'Users'
| skylifewww/pangolin-fog | pangolinfog/users/apps.py | Python | mit | 119 |
from ..osid import records as osid_records
class AssessmentPartRecord(osid_records.OsidRecord):
"""A record for an ``AssessmentPart``.
The methods specified by the record type are available through the
underlying object.
"""
class AssessmentPartQueryRecord(osid_records.OsidRecord):
"""A rec... | birdland/dlkit-doc | dlkit/assessment_authoring/records.py | Python | mit | 1,718 |
# Copyright (c) 2015-2016 Cisco Systems, Inc.
#
# 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, merge... | rgreinho/molecule | molecule/config.py | Python | mit | 7,590 |
# -*- coding: utf-8 -*-
from google.appengine.ext import db
from object_property import ObjectProperty
class Goal(db.Model):
# data
title = db.StringProperty(indexed=False)
objectives = ObjectProperty()
# a goal is 'completed' if it's finished or abandoned. This property is
# indexed so that we ... | jruiperezv/ALAS-KA | goals/models.py | Python | mit | 692 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
import numpy
import pandas
from data import *
def save_csv(pred, file_name):
idxs = []
ctys = []
for idx in xrange(len(ids)):
idxs += [ids[idx]] * 5
ctys += le.inverse_transform(numpy.argsort(... | wjfwzzc/Kaggle_Script | airbnb_recruiting_new_user_bookings/submissions/save_csv.py | Python | mit | 489 |
import contextlib
from sqlalchemy import Column
from sqlalchemy import event
from sqlalchemy import exc as sa_exc
from sqlalchemy import func
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import ... | sqlalchemy/sqlalchemy | test/orm/test_transaction.py | Python | mit | 71,891 |
import sys
from setuptools.command.test import test as TestCommand
from setuptools import setup
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno... | alex/coveralls-python | setup.py | Python | mit | 1,671 |
#!/usr/bin/python
"""
Stuff to import into bugzilla with
"""
def create_bug(BZ, ticket):
"""
Currently just a mock implementation...
Import a bug from sf.net to bugzilla
@param BZ: Bugzilla object that has already been logged in
@type BZ: bugzilla.Bugzilla
@param ticket: the sf.net ticket to... | pywikibot/sf-export | bz.py | Python | mit | 1,457 |
#!/usr/bin/env python
"""
Ask a question using an invalid filter.
"""
# import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback
# disable python from generating a .pyc file
sys.dont_write_bytecode = True
# change me to the path of pytan if this script is not runnin... | tanium/pytan | EXAMPLES/PYTAN_API/invalid_ask_manual_question_bad_filter.py | Python | mit | 3,090 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-10-09 09:59
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | davismathew/netbot-django | bootcamp/inventories/migrations/0001_initial.py | Python | mit | 1,824 |
from .abstract_crudconf import *
from .register import *
| tonimichel/django-modelcrud | modelcrud/__init__.py | Python | mit | 57 |
#########################################
## DennisX User-Managed MUD Server Kit ##
## helpers.py ##
## Helper Functions ##
## Copyright 2013 PariahSoft LLC ##
#########################################
## **********
## Permission is hereby granted, free of charge, to a... | pariahsoft/DennisX | inc/helpers.py | Python | mit | 1,709 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
from typing import Tuple, List, Union
import yaml
import psycopg2
from .exceptions import BranchingFound
def connect(url: str) -> Tuple[psycopg2.extensions.connection,
psycopg2.extensions.cursor]:
con = psycopg2.c... | ALFminecraft/migro | migro/utils.py | Python | mit | 1,942 |
# coding=utf-8
import psycopg2
from settings import DSN
# TODO 添加索引
create_table_sql_query = """
BEGIN;
CREATE TABLE "session" ("session_key" varchar(40) NOT NULL PRIMARY KEY,
"session_data" jsonb NOT NULL);
... | inuyasha2012/tornado-cat-example | example/create_table.py | Python | mit | 2,900 |
#%% @author: Zlatko
import sys; IMP_PATH = r'C:\\Users\\rslqulab\\Desktop\\zkm\\pyHFSS\\';
if ~(IMP_PATH in sys.path): sys.path.insert(0,IMP_PATH);
import pandas as pd, matplotlib.pyplot as plt, numpy as np;
import hfss, bbq, bbqNumericalDiagonalization
from hfss import CalcObject, ureg, load_HFSS_project
from bbq i... | alec-eickbusch/pyHFSS | Scripts/ZKM/DiTransmon/ebbq_vs_pass.py | Python | mit | 2,121 |
"""
Problem 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
"""
# Brute-force method
from Euler import nextPrime
num = 10001 # the nth prime
cPrime = 0
for k in range(1, num + 1): # from the 2nd prime to 10001st prime
cPri... | Tony-Tsoi/proj-euler-ans | problems/prob007.py | Python | mit | 368 |
#
# main.py
# Taco --- SPH Innovation Challenge
#
# Created by Mat, Kon and Len on 2017-03-11.
# Copyright 2016 Researchnix. All rights reserved.
#
import sys
import time
import FourWay
import Car
import Street
import Map
import Transmitter
import BookKeeper
import Timer
if __name__ == "__main__":
t = tim... | Researchnix/Taco | lennart.py | Python | mit | 905 |
#!/usr/bin/env python
from setuptools import setup
import sys
setup(
name='subtitli',
version='0.0.1',
description='Downloads the subtitle for a movie',
long_description=open('README.rst').read(),
author='Taranjeet Singh',
license='MIT',
classifiers=[
'Development Status :: 3 - Alp... | staranjeet/subtitli | setup.py | Python | mit | 1,395 |
"""
裸广搜
"""
class Solution:
f = None
d = ((0, -1), (0, 1), (-1, 0), (1, 0))
n = 0
m = 0
def bfs(self, grid, i, j):
queue = [(i, j)]
self.f[i][j] = True
ans = 1
while len(queue) != 0:
now = queue.pop(0)
for k in range(4):
x = ... | AtlantisFox/Green-Point-Challenge | leetcode/p695 Max Area of Island.py | Python | mit | 1,629 |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 2 14:48:24 2017
@author: thomas
"""
#from layers import Latent_Layer
import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
import tensorflow as tf
import tens... | tmoer/multimodal_varinf | networks/toy_vae.py | Python | mit | 5,171 |
#!/usr/bin/env python
"""
<Program Name>
setup.py
<Started>
May 4, 2009
<Author>
Michael Phan-Ba
<Purpose>
Runs a test server for
"""
import sys
from SimpleXMLRPCServer import SimpleXMLRPCServer
def echo(obj):
"""
<Purpose>
Serves as the test function for the XML-RPC client.
<Arguments>
ob... | sburnett/seattle | seattlelib/tests/testxmlrpc_client/testserver.py | Python | mit | 900 |
from flask.ext.admin import AdminIndexView, expose
from flask.ext import login
from flask import url_for, redirect
class CustomAdminIndexView(AdminIndexView):
@expose('/')
def index(self):
if not login.current_user.is_authenticated():
return redirect('/login')
return super(CustomAd... | piotrdubiel/scribeserver | app/admin.py | Python | mit | 1,643 |
print(all((lambda x:[x[1].count(s)<=x[2].count(s)for s in x[1]])(__import__('sys').argv)))
| m1cr0man/OneLineWonders | CA117/Lab_1/contains_cian_11.py | Python | mit | 91 |
#!/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/Fortran/F90COM.py | Python | mit | 4,691 |
import sqlite3
queries = {
'SELECT': 'SELECT %s FROM %s WHERE %s',
'SELECT_ALL': 'SELECT %s FROM %s',
'INSERT': 'INSERT INTO %s VALUES(%s)',
'UPDATE': 'UPDATE %s SET %s WHERE %s',
'DELETE': 'DELETE FROM %s where %s',
'DELETE_ALL': 'DELETE FROM %s',
'CREATE_TABLE': 'CREATE TABLE IF NOT EXIS... | emptyewer/DEEPN | functions/db.py | Python | mit | 8,961 |
from __future__ import absolute_import
import banana
from banana.utils.version import VersionInfo, get_version
def test_utils_version():
version = get_version(VersionInfo(1, 2, 3, 'alpha', 10))
assert version == '1.2.3a10'
banana.VERSION = VersionInfo(1, 0, 0, 'final', 0)
version = get_version()
... | banana-framework/banana-framework | tests/test_version.py | Python | mit | 346 |
import inspect
import itertools
import re
import discord
# This is all totally overkill, but if want markdown in our help text
# (rather than the giant code block discord.py uses by default) and
# still want pagination to work right this seems like the principled
# approach.
class Paginable:
def size(self):
... | inexactually/irisbot | formatter.py | Python | mit | 7,318 |
"""
WSGI config for jewzruxin_test project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jewzruxin_test.settings")
from... | weipin/jewzruxin | Jewzruxin/Test/jewzruxin_test/jewzruxin_test/wsgi.py | Python | mit | 403 |
#! /usr/bin/env python
import unittest
import gym
import sys
import os
import numpy as np
import tensorflow as tf
import itertools
import shutil
import threading
import multiprocessing
from inspect import getsourcefile
current_path = os.path.dirname(os.path.abspath(getsourcefile(lambda:0)))
import_path = os.path.absp... | rockingdingo/reinforcement-learning | PolicyGradient/a3c/train.py | Python | mit | 4,374 |
import pytz
import os
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.urls import reverse_lazy
from django.views.generic.detail import SingleObjectMixin
from djutils.views.generic import SortMixin
import core.fo... | telminov/ansible-manager | core/views/task.py | Python | mit | 6,010 |
"""
This module loads and pre-processes a bAbI dataset into TFRecords.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import re
import json
import tarfile
import numpy as np
import tensorflow as tf
from tqdm import tqdm
FLAGS = tf.app.flags.... | mikalyoung/recurrent-entity-networks | prep_datasets.py | Python | mit | 9,010 |
from modeltranslation.translator import translator, TranslationOptions
from airports.models import Airport
class AirportTranslationOptions(TranslationOptions):
fields = ['name', 'city', 'country']
translator.register(Airport, AirportTranslationOptions) | illing2005/django-airports-apis | airports/translation.py | Python | mit | 262 |
import numpy as np
import matplotlib.pyplot as plt
def forward(X, W1, b1, W2, b2):
Z = 1 / (1 + np.exp(-X.dot(W1) - b1))
A = Z.dot(W2) + b2
expA = np.exp(A)
Y = expA / expA.sum(axis=1, keepdims=True)
return Y, Z
def derivative_w2(Z, T, Y):
# N, K = T.shape
# M = Z.shape[1]
# ret1 = ... | adexin/Python-Machine-Learning-Samples | Feedforward_neural_network/backpropogation.py | Python | mit | 2,990 |
from django.db import models
class HistoryPitSummaryAPI(models.Model):
"""
Database schema for City of Portland's Point-In-Time Counts (HistoryPitSummary)
"""
Table = models.CharField(max_length=17, null=True, default='')
Population = models.CharField(max_length=40, null=True, default='')
Su... | rdubrock/hackOregonHomelessness | tallyapp/models.py | Python | mit | 2,155 |
#/usr/bin/env python
# -*- coding: utf-8 -*-
"""
zifeiyu.app
~~~~~~~~~~~~~~~~~~~~
manages the app creation and configuration process
:copyright: (c) 2016 by zifeiyu.
:license: MIT, see LICENSE for more details.
"""
from flask import Flask, url_for, redirect
from zifeiyu.extensions import csrf, db, ... | zifeiyusama/zifeiyu | zifeiyu/app.py | Python | mit | 3,231 |
# -*- coding: utf-8 -*-
import datetime
from django import forms
from pagedown.widgets import AdminPagedownWidget
class BlogForm(forms.ModelForm):
title = forms.CharField(label=u'标题', widget=forms.TextInput(attrs={'size': 118}))
content = forms.CharField(label=u'内容', widget=AdminPagedownWidget())
snippe... | lrqrun/lrqrun.org | src/apps/blog/forms.py | Python | mit | 790 |
#!/usr/bin/env python3
import os
import subprocess
import sys
neon = os.path.join("bin", "neon")
neonc = os.path.join("bin", "neonc")
i = 1
while i < len(sys.argv):
if sys.argv[i] == "--neon":
i += 1
neon = sys.argv[i]
elif sys.argv[i] == "--neonc":
i += 1
neonc = sys.argv[i]
... | ghewgill/neon-lang | scripts/run_c.py | Python | mit | 559 |
'''
Length Testing
'''
import numpy as np
from skimage.morphology import label
import scipy.ndimage as nd
from copy import copy
struct2a = np.eye(2)
struct2b = struct2a[::-1]
struct3a = np.eye(3)
struct3b = struct3a[::-1]
def lengths(skeleton, verbose=False):
'''
Length finding via morphology.
'''
... | e-koch/ewky_scripts | skel_length.py | Python | mit | 5,389 |
class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
if name in self.__dict__:
raise self.ConstError("Can't rebind const(%s)"%name)
self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()
# that's all -- now any client-code can
# import const... | ArcAwe/hazc | const.py | Python | mit | 492 |
#!/usr/bin/env python3
"""
OUTPUT:
Using the base name passed, several files will be created temporarily, but the final output
path will be:
OUTPUT_BASE.bam
ASSUMPTIONS:
This assumes very simple headers only as input like this:
@HD VN:1.0 SO:coordinate
@SQ SN:gi|551236890|ref|NZ_ATVB01000022.1... | jorvis/biocode | sam_bam/merge_bam_files.py | Python | mit | 2,659 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Find a quadratic formula that produces the maximum number of primes
for consecutive values of n.
f(n) = n2 + an + b, where |a| < 1000 and |b| < 1000
f(0) >= 2 => b >= 2
f(1) >= 2 => b >= 1 - a
"""
from primes import Primes
def pe27():
"""
>>> pe27()
(... | kittttttan/pe | py/pe/pe27.py | Python | mit | 852 |
class FlockMessage(object):
""" A FlockMessage identifies the data received from a device or a command to
send.
This class must be overloaded. Overloaded classes must implement a load
and a dump method to respectively load a message from a packet or
generate a packet from a message.
... | MainRo/python-flock | flock/message.py | Python | mit | 1,751 |
from flask import render_template, redirect, request, url_for, flash
from flask_login import login_user, logout_user, login_required, \
current_user
from . import auth
from .. import db
from ..common.models import User
from ..common.email import send_email
from .forms import LoginForm, RegistrationForm, ChangePassw... | cmacro/mogufsite | app/auth/views.py | Python | mit | 6,072 |
"""
Straight Ray with Volume Data Misfit Term
=========================================
Based on the SEG abstract Heagy, Cockett and Oldenburg, 2014.
Heagy, L. J., Cockett, A. R., & Oldenburg, D. W. (2014, August 5).
Parametrized Inversion Framework for Proppant Volume in a Hydraulically
Fractured Reservoir. SEG Tech... | simpeg/simpeg | examples/20-published/plot_tomo_joint_with_volume.py | Python | mit | 6,214 |
from integration_test.schemas.v2.definitions import uuid
get_inbound_sms_single_response = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "GET inbound sms schema response",
"type": "object",
"title": "GET response v2/inbound_sms",
"properties": {
"user_number": {"typ... | alphagov/notifications-python-client | integration_test/schemas/v2/inbound_sms_schemas.py | Python | mit | 1,696 |
"""SPADL schema for Wyscout data."""
import pandera as pa
from pandera.typing import DateTime, Object, Series
from socceraction.data.schema import (
CompetitionSchema,
EventSchema,
GameSchema,
PlayerSchema,
TeamSchema,
)
class WyscoutCompetitionSchema(CompetitionSchema):
"""Definition of a da... | ML-KULeuven/socceraction | socceraction/data/wyscout/schema.py | Python | mit | 1,246 |
"""Some common theano utilities."""
import numpy as np
import theano
from theano import tensor as T
from theano.ifelse import ifelse
def printed(var, name=''):
return theano.printing.Print(name)(var)
def logsumexp(mat, axis=0):
"""Apply a row-wise log-sum-exp, summing along axis."""
maxes = T.max(mat, axis=axis... | robinjia/nectar | nectar/theanoutil/util.py | Python | mit | 2,340 |
from ..utilities.retrieve_data_infos import RetrieveGeneralFileInfos, RetrieveGeneralDataInfos
from .. import DataType
class Step3GuiHandler:
def __init__(self, parent=None):
self.parent = parent
def load_normalized_changed(self, tab_index=0):
if tab_index == 0:
data_preview_box_... | ornlneutronimaging/iBeatles | src/iBeatles/step3/gui_handler.py | Python | mit | 1,968 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import collections
from abc import ABCMeta, abstractmethod, abstractproperty
from ios_code_generator._compat import implements_to_string
from ios_code_generator._internal import _DictAccessorProperty
from ios_code_generator.parser import ModelParserMixin... | banxi1988/iOSCodeGenerator | ios_code_generator/models/core.py | Python | mit | 5,323 |
class Solution(object):
# Write your code here
def __init__(self):
self.__stack = []
self.__queue = []
def pushCharacter(self, ch):
self.__stack.append(ch)
def enqueueCharacter(self, ch):
self.__queue.insert(0, ch)
def popCharacter(self):
return self.__stack.pop()
def dequeueCharacter(self):
retur... | ehouarn-perret/EhouarnPerret.Python.HackerRank | HackerRank/0 - Tutorials/30 Days of Code/Day 18 - Queues and Stacks.py | Python | mit | 977 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
The MIT License (MIT)
Copyright (c) 2016 Wei-Hung Weng
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 limita... | ckbjimmy/cdc | cdc/src/predict.py | Python | mit | 5,479 |
import tensorflow as tf
class Gcn():
propagators = None
updaters = None
def __init__(self, initializer, propagators, updaters):
self.initializer = initializer
self.propagators = propagators
self.updaters = updaters
self.variables = {}
def run(self, mode):
ca... | MichSchli/QuestionAnsweringGCN | models/tensorflow_components/gcn/gcns/gcn.py | Python | mit | 999 |
import numpy as np
from SimPEG import (
maps,
optimization,
inversion,
inverse_problem,
directives,
data_misfit,
regularization,
)
def run_inversion(
m0,
simulation,
data,
actind,
mesh,
maxIter=15,
beta0_ratio=1e0,
coolingFactor=5,
coolingRate=2,
up... | simpeg/simpeg | SimPEG/electromagnetics/static/resistivity/run.py | Python | mit | 1,983 |
#
# TRANSMITS COMMANDS TO THE ARDUINO OVER SERIAL
#
import os
import sys
import time
import serial
import struct
import global_data
import record_mode
TRANSMIT_DELAY = 0.08 # SECONDS
# SET TO FALSE FOR TESTING WITHOUT ARDUINO
TRANSMIT = True
# THIS WILL GET ASSIGNED DURING INITIALIZATION
CONNECTION = None
######... | DaveBuckingham/robosoft | mctransmitter.py | Python | mit | 3,109 |
from .web_sensor import WebSensor
| insolite/alarme | alarme/extras/sensor/web/__init__.py | Python | mit | 34 |
# coding:utf-8
from tasks.workers import app
from page_get import user as user_get
from db.seed_ids import get_seed_ids, get_seed_by_id, insert_seeds, set_seed_other_crawled
@app.task(ignore_result=True)
def crawl_follower_fans(uid):
seed = get_seed_by_id(uid)
if seed.other_crawled == 0:
rs = user_get... | KingOfBanana/SocialNetworkAI | tasks/user.py | Python | mit | 1,563 |
"""Auto-generated file, do not edit by hand. QA metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_QA = PhoneMetadata(id='QA', country_code=974, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[2-8]\\d{6,7}', possible_number_pattern=... | ayushgoel/FixGoogleContacts | phonenumbers/data/region_QA.py | Python | mit | 2,046 |
from __future__ import unicode_literals
from django.conf import settings
from django.core import mail
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import render_to_string
def send_email_from_template(to_email, from_email, subject,
markdown_templ... | InfoAgeTech/django-core | django_core/mail/sending.py | Python | mit | 4,664 |
import matplotlib
matplotlib.use("Agg")
from astropy.io import fits as pyfits
import numpy as np
import scipy
from scipy import signal,optimize
import copy
import glob
import os
import matplotlib.pyplot as plt
import sys
sys.path.append("../utils/GLOBALutils")
import GLOBALutils
from pylab import *
def get_hour(hour... | rabrahm/ceres | mike/mikeutils.py | Python | mit | 9,950 |
# -*- coding: utf-8 -*-
from lwp.utils import read_config_file
import ldap as ldap_m
class ldap:
def __init__(self):
config = read_config_file()
self.LDAP_HOST = config.get('ldap', 'host')
self.LDAP_PORT = int(config.get('ldap', 'port'))
self.LDAP_PROTO = 'ldaps' if config.getboo... | claudyus/LXC-Web-Panel | lwp/authenticators/ldap.py | Python | mit | 2,284 |
# -*- coding: utf-8 -*-
import wtforms as wtf
from wtforms import ValidationError, validators
from sqlalchemy.sql.expression import exists
from pyramid.i18n import TranslationStringFactory
from .utils import UserChoices, ListValidator
from intranet3.models import DBSession, Tracker, Client
_ = TranslationStringFactor... | stxnext/intranet-open | src/intranet3/intranet3/forms/client.py | Python | mit | 1,970 |
# Prompt for a number input
def number_input(message):
isValid = False
while not isValid:
userInput = input(message)
try:
val = int(userInput)
for i, ch in enumerate(userInput):
val = int(ch)
# print(ch, '(%d)' %i)
# for i in range(len(userInput)):
# print(userInput[i], '(%d)' %i)
isValid =... | hui-w/misc-fragment | python/bignum.py | Python | mit | 1,466 |
from flask import Flask
from flask_redis import FlaskRedis
from redis import StrictRedis
from config import BaseConfig
class DecodedRedis(StrictRedis):
@classmethod
def from_url(cls, url, db=None, **kwargs):
kwargs['decode_responses'] = True
return StrictRedis.from_url(url, db, **kwargs)
app... | tferreira/Flask-Redis | index.py | Python | mit | 431 |
import urllib2
import urllib
import json
from functools import partial
class food2fork():
'''
Usage:
import food2fork
f2f = food2fork("My Api Key")
recipes = f2f.search("chicken, rice")
moreRecipes = f2f.search("chicken, rice", 2)
'''
def __init__(self,apiKey, debug=False):
self.apiKey = apiKey
... | food2fork/python-api-client | food2fork.py | Python | mit | 2,313 |
from contextlib import closing
from django.core.cache import cache
from django.core.management.base import BaseCommand
from django.db import connection
from proso_models.models import ItemType
class Command(BaseCommand):
def handle(self, *args, **options):
with closing(connection.cursor()) as cursor:
... | adaptive-learning/proso-apps | proso_models/management/commands/fill_item_types.py | Python | mit | 857 |
"""
WSGI config for frontend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... | den1den/web-inf-ret-ml | frontend/base/wsgi.py | Python | mit | 399 |
import csv
import os
import tempfile
from office365.sharepoint.client_context import ClientContext
from tests import test_team_site_url, test_client_credentials
"Demonstrates how to export a List data as csv"
ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
# 1.retrieve list data
lis... | vgrem/Office365-REST-Python-Client | examples/sharepoint/listitems/export_list_items_csv.py | Python | mit | 856 |
# Import modules
import numpy as np
import pytest
@pytest.fixture()
def particles():
shape = (np.random.randint(10, 20), np.random.randint(2, 6))
particles_ = np.random.uniform(0, 10, shape)
print(particles_)
return particles_
| ljvmiranda921/pyswarms | tests/utils/decorators/conftest.py | Python | mit | 245 |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 17:55:02 2015
@author: Ferriss
Before and after heating comparison of FTIR spectra on the rims of cpx samples
"""
import cpx_spectra
import string
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.ticker import ... | EFerriss/HydrogenCpx | HydrogenCpx/Fig4_CpxResults.py | Python | mit | 7,442 |
# The MIT License (MIT)
#
# Copyright (c) 2017 James K Bowler, Data Centauri Ltd
#
# 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... | JamesKBowler/fxcmminer | fx_collect/utils/date_utils.py | Python | mit | 3,065 |
"Can be found in gpkit/docs/source/examples/external_sp2.py"
import numpy as np
from gpkit import Variable, Model
x = Variable("x")
def y_ext(self, x0):
"Returns constraints on y derived from x0"
if x not in x0:
return self >= x
return self >= x/x0[x] * np.sin(x0[x])
y = Variable("y", externalfn... | convexopt/gpkit | docs/source/examples/external_sp2.py | Python | mit | 414 |
from Nametag3d import *
class NametagFloat3d(Nametag3d):
WANT_DYNAMIC_SCALING = False
SCALING_FACTOR = 1.0
SHOULD_BILLBOARD = True
| ToonTownInfiniteRepo/ToontownInfinite | otp/nametag/NametagFloat3d.py | Python | mit | 144 |
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2016 Michal Stefanik <stefanik.m@mail.muni.cz>, Milan Cermak <cermak@ics.muni.cz>
# Institute of Computer Science, Masaryk University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentati... | CSIRT-MU/Stream4Flow | applications/detection/ddos/spark/detection_ddos.py | Python | mit | 10,022 |
# -*- coding: utf-8 -*-
#
# pyhdf documentation build configuration file, created by
# sphinx-quickstart2 on Sun Jul 27 02:07:57 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | fhs/python-hdf4 | doc/conf.py | Python | mit | 8,182 |
#!/usr/bin/env python3
import logging
import threading
import time
logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s.%(msecs)03d [%(levelname)s] (%(threadName)s) %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
def worker(n):
logging.debug("worker %d" % (n))
logging.debug("start")
for i in range(3):
th... | dubrayn/dubrayn.github.io | examples/threading/example7.py | Python | mit | 396 |
# coding: utf-8
import drawTools
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import os, re, sys
from numpy.ma import masked_array
# BIAŁY = WSZECHOBECNA ODCHŁAŃ 0
# ZÓŁTY = FORAMINIFERA 2
# ZIELONY = ALGA 1
# NIEBIESKI = SMRÓD ... | zytaw/foraminifera | src/drawing/drawAuto.py | Python | mit | 2,095 |
# devel.py
import os
import sys
import yaml
import pickle
import json
import time
import shutil
import h5py
import numpy as np
from scoop import futures as fu
from scoop import shared as sh
from sklearn import svm
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics.pairwise import rbf_kerne... | tttor/csipb-jamu-prj | predictor/connectivity/classifier/imbalance/devel.py | Python | mit | 12,508 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4 import QtGui
import Database
from StarsWidget import StarsWidget
class DioDetails( QtGui.QStackedWidget ):
def __init__( self, parent ):
QtGui.QStackedWidget.__init__( self, parent )
self.parent = parent
image_paths_label = QtGui.QLabel( 'Paths' )
... | daign/daign-image-organizer | src/DioDetails.py | Python | mit | 3,488 |
# coding=utf8
import scrapy
import scrapy.cmdline
spider_name = "biliSpider"
def main():
scrapy.cmdline.execute(argv=['scrapy', 'crawl', spider_name])
if __name__ == '__main__':
main()
| h12345jack/BilibiliSearchSystem | Spider/run_spider.py | Python | mit | 199 |
import nengo
import nengo_spinnaker
import numpy as np
model = nengo.Network("Node -> Node -> Ensemble -> Node")
with model:
def in_f(t):
val = np.sin(t)
return val
def out_f(t, val):
print("Output %.3f" % val[0])
a = nengo.Node(in_f, size_in=0, size_out=1, label="Input")
b =... | ctn-archive/nengo_spinnaker_2014 | examples/node_node_ensemble_node.py | Python | mit | 641 |
#!/usr/bin/env python
#
# Generate pnSeed[] from Pieter's DNS seeder
#
NSEEDS=600
import re
import sys
from subprocess import check_output
def main():
lines = sys.stdin.readlines()
ips = []
pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):28888")
for line in lines:
m = patt... | Besteri/bestericoin | contrib/seeds/makeseeds.py | Python | mit | 709 |