code stringlengths 1 199k |
|---|
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import validate_slug
from django.db import models
from django.utils import simplejson as json
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from philo.forms.fields imp... |
import hashlib
import json
import logging
import os
import subprocess
import sys
import time
from collections import defaultdict
from shutil import copy
from shutil import copyfile
from shutil import copystat
from shutil import copytree
from tempfile import mkdtemp
import boto3
import botocore
import yaml
import sys
fr... |
'''Contains the EpubBuilder class to build epub2.0.1 files with the getebook
module.'''
import html
import re
import datetime
import getebook
import os.path
import re
import zipfile
__all__ = ['EpubBuilder', 'EpubTOC', 'Author']
def _normalize(name):
'''Transform "Firstname [Middlenames] Lastname" into
"Lastnam... |
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from scipy.spatial import distance
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import StandardScaler
from sk... |
import time
def retries(times=3, timeout=1):
"""对未捕获异常进行重试"""
def decorator(func):
def _wrapper(*args, **kw):
att, retry = 0, 0
while retry < times:
retry += 1
try:
return func(*args, **kw)
except:
... |
"""
********************************************************************
Test file for implementation check of CR3BP library.
********************************************************************
Last update: 21/01/2022
Description
-----------
Contains a few sample orbit propagations to test the CR3BP library.
The... |
FAILEDOPERATION = 'FailedOperation'
FAILEDOPERATION_APIGATEWAY = 'FailedOperation.ApiGateway'
FAILEDOPERATION_APIGW = 'FailedOperation.Apigw'
FAILEDOPERATION_APMCONFIGINSTANCEID = 'FailedOperation.ApmConfigInstanceId'
FAILEDOPERATION_ASYNCEVENTSTATUS = 'FailedOperation.AsyncEventStatus'
FAILEDOPERATION_COPYFAILED = 'Fa... |
from runner.koan import *
class AboutIteration(Koan):
def test_iterators_are_a_type(self):
it = iter(range(1,6))
total = 0
for num in it:
total += num
self.assertEqual(15 , total)
def test_iterating_with_next(self):
stages = iter(['alpha','beta','gamma'])
... |
from api_request import Api
from util import Util
from twocheckout import Twocheckout
class Sale(Twocheckout):
def __init__(self, dict_):
super(self.__class__, self).__init__(dict_)
@classmethod
def find(cls, params=None):
if params is None:
params = dict()
response = cls... |
import json
import os
from flask import request, g, render_template, make_response, jsonify, Response
from helpers.raw_endpoint import get_id, store_json_to_file
from helpers.groups import get_groups
from json_controller import JSONController
from main import app
from pymongo import MongoClient, errors
HERE = os.path.d... |
from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic inf... |
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'commu... |
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
from FIFAscrape.items import PlayerItem
from urlparse import urlparse, urljoin
from scrapy.http.request import Request
from scrapy.conf import settings
import random
import time
class fifaSpider(Spider):
name... |
print("hello!!!!") |
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClie... |
from flask import Blueprint, request, render_template
from ..load import processing_results
from ..abbr import get_abbr_map
abbr_map = get_abbr_map()
liner_mod = Blueprint('liner', __name__, template_folder='templates', static_folder='static')
@liner_mod.route('/liner', methods=['GET', 'POST'])
def liner():
if requ... |
from msrest.serialization import Model
class Dimension(Model):
"""Dimension of a resource metric. For e.g. instance specific HTTP requests
for a web app,
where instance name is dimension of the metric HTTP request.
:param name:
:type name: str
:param display_name:
:type display_name: str
... |
import asyncio
import discord
import datetime
import pytz
from discord.ext import commands
from Cogs import FuzzySearch
from Cogs import Settings
from Cogs import DisplayName
from Cogs import Message
from Cogs import Nullify
class Time:
# Init with the bot reference, and a reference to the settings var
de... |
import unittest
from katas.beta.what_color_is_your_name import string_color
class StringColorTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(string_color('Jack'), '79CAE5')
def test_equal_2(self):
self.assertEqual(string_color('Joshua'), '6A10D6')
def test_equal_3(self)... |
from sqlalchemy.testing import eq_, assert_raises, assert_raises_message, \
config, is_
import re
from sqlalchemy.testing.util import picklers
from sqlalchemy.interfaces import ConnectionProxy
from sqlalchemy import MetaData, Integer, String, INT, VARCHAR, func, \
bindparam, select, event, TypeDecorator, create... |
"""
``editquality generate_make -h``
::
Code-generate Makefile from template and configuration
:Usage:
generate_make -h | --help
generate_make
[--config=<path>]
[--main=<filename>]
[--output=<path>]
[--templates=... |
from msrest.serialization import Model
class Product(Model):
_required = []
_attribute_map = {
'integer': {'key': 'integer', 'type': 'int'},
'string': {'key': 'string', 'type': 'str'},
}
def __init__(self, *args, **kwargs):
"""Product
:param int integer
:param str... |
"""
Parser for todo format string.
from todo.parser import parser
parser.parse(string) # return an Todo instance
"""
from models import Task
from models import Todo
from ply import lex
from ply import yacc
class TodoLexer(object):
"""
Lexer for Todo format string.
Tokens
ID e.g. '1.'
... |
import time
import pymemcache.client
import pytest
from limits import RateLimitItemPerMinute, RateLimitItemPerSecond
from limits.storage import MemcachedStorage, storage_from_string
from limits.strategies import (
FixedWindowElasticExpiryRateLimiter,
FixedWindowRateLimiter,
)
from tests.utils import fixed_start... |
import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab... |
"""
Gauged
https://github.com/chriso/gauged (MIT Licensed)
Copyright 2014 (c) Chris O'Hara <cohara87@gmail.com>
"""
from urlparse import urlparse, parse_qsl
from urllib import unquote
from .mysql import MySQLDriver
from .sqlite import SQLiteDriver
from .postgresql import PostgreSQLDriver
def parse_dsn(dsn_string):
... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ibtokin.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is real... |
import boto
import mock
import moto
import tempfile
import unittest
from click.testing import CliRunner
from rubberjackcli.click import rubberjack
class CLITests(unittest.TestCase):
@moto.mock_s3_deprecated
@mock.patch('boto.beanstalk.layer1.Layer1.create_application_version')
@mock.patch('boto.beanstalk.la... |
from __future__ import absolute_import, division, print_function
from __future__ import with_statement
import pickle
import os
import sys
from io import UnsupportedOperation
import _pytest._code
import py
import pytest
import contextlib
from _pytest import capture
from _pytest.capture import CaptureManager
from _pytest... |
import zmq
import datetime
import pytz
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from registrations.models import Registration
from registrations import handlers
from registrations import tasks
class Command(BaseCommand):
def log(self, message):
f = o... |
from noisemapper.mapper import *
def main():
mapper = NoiseMapper()
mapper.run()
if __name__ == "__main__":
main() |
import numpy as np
from numpy import cumsum, sum, searchsorted
from numpy.random import rand
import math
import utils
import core.sentence as sentence
import core.markovchain as mc
import logging
logger = logging.getLogger(__name__)
class dialogue_maker(object):
"""Class to handle creating dialogue based on a list ... |
from django.contrib.admin import TabularInline
from .models import GalleryPhoto
class PhotoInline(TabularInline):
"""
Tabular inline that will be displayed in the gallery form during frontend
editing or in the admin site.
"""
model = GalleryPhoto
fk_name = "gallery" |
from __future__ import annotations
from collections import defaultdict
from collections.abc import Generator, Iterable, Mapping, MutableMapping
from contextlib import contextmanager
import logging
import re
import textwrap
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, NamedTuple
from markdow... |
import teca.utils as tecautils
import teca.ConfigHandler as tecaconf
import unittest
class TestFileFilter(unittest.TestCase):
def setUp(self):
self.conf = tecaconf.ConfigHandler(
"tests/test_data/configuration.json",
{"starting_path": "tests/test_data/images"}
)
self.... |
from hdf5handler import HDF5Handler
handler = HDF5Handler('mydata.hdf5')
handler.open()
for i in range(100):
handler.put(i, 'numbers')
handler.close() |
"""
[2015-07-13] Challenge #223 [Easy] Garland words
https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/
A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the
same N letters in the same order, for some N greate... |
from decimal import Decimal
from django import forms
from django.template.loader import render_to_string
from django.template.defaultfilters import slugify
class BaseWidget(forms.TextInput):
"""
Base widget. Do not use this directly.
"""
template = None
instance = None
def get_parent_id(self, na... |
import sys
import os
from treestore import Treestore
try: taxonomy = sys.argv[1]
except: taxonomy = None
t = Treestore()
treebase_uri = 'http://purl.org/phylo/treebase/phylows/tree/%s'
tree_files = [x for x in os.listdir('trees') if x.endswith('.nex')]
base_uri = 'http://www.phylocommons.org/trees/%s'
tree_list = set(t... |
from .stats_view_base import StatsViewSwagger, StatsViewSwaggerKeyRequired
from .stats_util_dataverses import StatsMakerDataverses
class DataverseCountByMonthView(StatsViewSwaggerKeyRequired):
"""API View - Dataverse counts by Month."""
# Define the swagger attributes
# Note: api_path must match the path in... |
import uuid
from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import BaseUserManager
from django.utils import timezone
from accelerator_abstract.models import BaseUserRole
from accelerator_abstract.models.base_base_profile i... |
from setuptools import setup, find_packages
from codecs import open
import os
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='transposer',
version='0.0.3',
description='Transposes columns ... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('phone_numbers', '0001_initial'),
('sims', '0001_initial'),
]
operations = [
migrations.AddFie... |
def calc():
h, l = input().split(' ')
mapa = []
for i_row in range(int(h)):
mapa.append(input().split(' '))
maior_num = 0
for row in mapa:
for col in row:
n = int(col)
if (n > maior_num):
maior_num = n
qtd = [0 for i in range(maior_num + 1)]
for row in mapa:
for col in row:
n = int(col)
qtd... |
"""
Manage and display experimental results.
"""
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>'
__author__ = 'Lucas Theis <lucas@theis.io>'
__docformat__ = 'epytext'
__version__ = '0.4.3'
import sys
import os
import numpy
import random
import scipy
import socket
sys.path.append('./code... |
import traceback
class EnsureExceptionHandledGuard:
"""Helper for ensuring that Future's exceptions were handled.
This solves a nasty problem with Futures and Tasks that have an
exception set: if nobody asks for the exception, the exception is
never logged. This violates the Zen of Python: 'Errors shou... |
__package__ = 'archivebox.core' |
import logging.handlers
import os
_pabotlog = logging.getLogger('PABot')
_pabotlog.setLevel(logging.DEBUG)
_logPath = os.path.abspath("./logging/pabot.log")
_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
_consoleStreamHandler = logging.StreamHandler()
_consoleStreamHandler.setLev... |
import ast
import heisenberg.library.heisenberg_dynamics_context
import heisenberg.library.orbit_plot
import heisenberg.option_parser
import heisenberg.plot
import heisenberg.util
import matplotlib
import numpy as np
import sys
matplotlib.rcParams['agg.path.chunksize'] = 10000
dynamics_context = heisenberg.library.heis... |
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org/messages",
auth=("api", "key-679dc79b890e700f11f001a6bf86f4a1"),
data={"from": "Mailgun Sandbox <postmaster@sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org>",
... |
def load_keys(filepath):
"""
Loads the Twitter API keys into a dict.
:param filepath: file path to config file with Twitter API keys.
:return: keys_dict
:raise: IOError
"""
try:
keys_file = open(filepath, 'rb')
keys = {}
for line in keys_file:
key, value =... |
"""Main entry points for scripts."""
from __future__ import print_function, division
from argparse import ArgumentParser
from collections import OrderedDict
from copy import copy
from datetime import datetime
import glob
import json
import logging
import math
import os
import scipy.stats
import numpy as np
from .versio... |
def calc_note(count, value):
qnt = 0
if count >= value:
qnt = int(count) / value
print '%d nota(s) de R$ %d.00' % (qnt, value)
return count - qnt * value
n = float(raw_input())
print 'NOTAS:'
n = calc_note(n, 100)
n = calc_note(n, 50)
n = calc_note(n, 20)
n = calc_note(n, 10)
n = calc_note(n, 5)... |
import datetime
import time
import boto
import redis
import requests
import random
import zlib
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.db import IntegrityE... |
__author__ = "Guillaume"
__license__ = "MIT"
__copyright__ = "2015, ESRF"
import numpy
from freesas.model import SASModel
class Grid:
"""
This class is used to create a grid which include all the input models
"""
def __init__(self, inputfiles):
"""
:param inputfiles: list of pdb files ne... |
"""
Project-wide application configuration.
DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE.
They will be exposed to users. Use environment variables instead.
See get_secrets() below for a fast way to access them.
"""
import os
"""
NAMES
"""
PROJECT_NAME = 'quotable'
PROJECT_SLUG = 'quotable'
REPOSITORY_NAME = 'quot... |
import os
import logging
from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.template.loader import get_template
from workshops.models import Badge, Person, Role
logger = logging.getLogger()
class Command(BaseCommand):
help = 'Report instructors activity.'
def ... |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import Pipe... |
"""
Created on Fri Jun 25 16:20:12 2015
@author: Balázs Hidasi
@lastmodified: Loreto Parisi (loretoparisi at gmail dot com)
"""
import sys
import os
import numpy as np
import pandas as pd
import datetime as dt
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
... |
from attributes import *
from constants import *
class UnitManager (Attributes) :
"""
UnitManager class -- manages a pool
"""
# --------------------------------------------------------------------------
#
def __init__ (self, url=None, scheduler='default', session=None) :
Attributes.__in... |
import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from .models import Action
def create_action(user, verb, target=None):
now = timezone.now()
last_minute = now - datetime.timedelta(seconds=60)
similar_actions = Action.objects.filter(user_id=user.id,... |
import os
import sys
from os import path
ROOTDIR = path.abspath(os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, ROOTDIR)
import redpipe # noqa
extensions = [
'alabaster',
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
]
templates_path = ... |
from src.tools.dictionaries import PostLoadedDict
class ServerImplementationDict(PostLoadedDict):
def __missing__(self, key):
try:
return super().__missing__(key)
except KeyError:
return NotImplemented
class Server():
def __init__(self, shortname, loader):
# Not p... |
"""Python library for serializing any arbitrary object graph into JSON.
jsonpickle can take almost any Python object and turn the object into JSON.
Additionally, it can reconstitute the object back into Python.
The object must be accessible globally via a module and must
inherit from object (AKA new-style classes).
Cre... |
"""
Created on Wed Sep 09 13:04:53 2015
* If TimerTool.exe is running, kill the process.
* If input parameter is given, start TimerTool and set clock resolution
Starts TimerTool.exe and sets the clock resolution to argv[0] ms
Ex: python set_clock_resolution 0.5
@author: marcus
"""
import time, datetime
from socket impo... |
blocklevel = ["blockquote", "div", "form", "p", "table", "video", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "details", "article", "header", "main"]
def normalizeEnter(src):
#Deletes all user defined for readability reason existing line breaks that are issues for the HTML output
for elem in blocklevel:
while src.fin... |
import cairo
from gi.repository import Gtk
from gi.repository import Gdk
from pylsner import plugin
class Window(Gtk.Window):
def __init__(self):
super(Window, self).__init__(skip_pager_hint=True,
skip_taskbar_hint=True,
)
self... |
list = []
for i in range(11):
list.append(i)
print(list) |
"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="P... |
"""
http://community.topcoder.com/stat?c=problem_statement&pm=1667
Single Round Match 147 Round 1 - Division II, Level One
"""
class CCipher:
def decode(self, cipherText, shift):
a = ord('A')
decoder = [a + (c - shift if c >= shift else c - shift + 26) for c in range(26)]
plain = [chr(decode... |
from hwt.synthesizer.rtlLevel.extract_part_drivers import extract_part_drivers
from hwt.synthesizer.rtlLevel.remove_unconnected_signals import removeUnconnectedSignals
from hwt.synthesizer.rtlLevel.mark_visibility_of_signals_and_check_drivers import markVisibilityOfSignalsAndCheckDrivers
class DummyPlatform():
"""
... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
RJUST = 12
def format_fans(fans):
return format_line(prefix='fans'.rjust(RJUST), values=fans)
def format_rpms(rpms):
return format_line(prefix='rpms'.rjust(RJUST), values=rpms)
def format_pwms(pwms):
... |
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 'Package'
db.create_table(u'api_package', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key... |
from __future__ import absolute_import
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from plotly.tests.utils import compare_dict
from plotly.tests.test_optional.optional_utils import run_fig
from plotly.tests.test_optional.test_matplotlylib.data.annotations import *
def test_annotations():
... |
from distutils.core import setup
setup(
# Application name:
name="streaker",
# Version number (initial):
version="0.0.1",
# Application author details:
author="Aldi Alimucaj",
author_email="aldi.alimucaj@gmail.com",
# Packages
packages=["streaker"],
scripts=['bin/streaker'],
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import random
import socket
import time
from contextlib import contextmanager
log = logging.getLogger(__name__)
class StatsD(object):
def __init__(self, host='localhost', port=8125, enabled=True, prefix=''):
se... |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='fcit',
# Versions should comply with PEP440. For a discussion on sing... |
import pandas as pd
import os
import time
from datetime import datetime
import re
from time import mktime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
style.use("dark_background")
path = "intraQuarter"
def Key_Stats(gather="Total Debt/Equity (mrq)"):
statspath = path+'/_KeyStats'
s... |
from __future__ import absolute_import
from .base import WhiteNoise
__version__ = '2.0.3'
__all__ = ['WhiteNoise'] |
import struct
''' Refer to docs for all the exact formats. There are many so check them out before converting things yourself '''
''' If there's a specific offset you want to do things from, use pack_into and unack_into from the docs '''
i1= 1234
print "Int to string as 8 byte little endian", repr(struct.pack("<Q",i1))... |
"""
TODO...
"""
__all__ = ['GreedyPlayer']
import random
from jdhp.tictactoe.player.abstract import Player
class GreedyPlayer(Player):
"""
TODO...
"""
def play(self, game, state):
"""
TODO...
"""
action_list = game.getSetOfValidActions(state)
choosen_action = None... |
__author__ = 'besta'
class BestaPlayer:
def __init__(self, fichier, player):
self.fichier = fichier
self.grille = self.getFirstGrid()
self.best_hit = 0
self.players = player
def getFirstGrid(self):
"""
Implements function to get the first grid.
:return: th... |
import logging
class User(object):
"""
Wrapper object around an entry in users.json. Behaves like a read-only dictionary if
asked, but adds some useful logic to decouple the front end from the JSON structure.
"""
_NAME_KEYS = ["display_name", "real_name"]
_DEFAULT_IMAGE_KEY = "image_512"
def... |
"""
Looks for a specific sample
"""
import re
import sys
import os
import os.path
sample = sys.argv[1]
family,sample_only = sample.split("_")
match = re.match('\d*',family)
if match:
prefix=str(int(match.group(0))/100)
report_path = prefix+'x/'+family
report=0
bam=0
errors = []
if os.path.isfile... |
"""
Date: 2/2/2017
Team: Satoshi Nakamoto
@Authors: Alex Levering and Hector Muro
Non-standard dependencies:
* Twython
* NLTK
* Folium
* Geocoder
* psycopg2
TO DO BEFOREHAND:
The following steps are non-automatable and have to be performed manually.
* Have the NLTK vader lexicon locally (nltk.download("vader_lexicon"))... |
from __future__ import unicode_literals
import os
import unittest
import xlrd
import msp.schedule_parser as schedule_parser
__author__ = "Andrey Konovalov"
__copyright__ = "Copyright (C) 2014 Andrey Konovalov"
__license__ = "MIT"
__version__ = "0.1"
this_dir, this_filename = os.path.split(__file__)
SCHEDULE_PATH = os.p... |
import gzip
import glob
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from scipy.stats import spearmanr
def get_num_lines_gz(filename):
num_lines = 0
with gzip.open(filename, "r") as fp:
for line in fp:
num_lines += 1
return num_lines
def main():
"""get stat... |
student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'}
def Handler() :
while (1) :
choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n"))
print(choice)
if (choice == 1) :
if (student_phoneNumber_name) :
phone_number = input("Enter student's pho... |
""" Tests for Dynamo3 """
import sys
import unittest
from decimal import Decimal
from pickle import dumps, loads
from urllib.parse import urlparse
from botocore.exceptions import ClientError
from mock import ANY, MagicMock, patch
from dynamo3 import (
Binary,
Dynamizer,
DynamoDBConnection,
DynamoDBError... |
Alchemy sentiment analysis: fb12d2c55fff36e1e268584e261b6b010b37279f
Africa Is Talking: 676dbd926bbb04fa69ce90ee81d3f5ffee2692aaf80eb5793bd70fe93e77dc2e |
"""
Categorize and analyze user sessions.
Read in ecfs_obfuscated_filtered.gz file, output some fancy results.
"""
from collections import defaultdict
from collections import Counter
import sys
import time
import os
import resource
import json
import fnmatch
from pipes import Pipes
import operator
from operatio... |
"""
@author Stephan Reith
@date 31.08.2016
This is a simple example to demonstrate how the ROS Spinnaker Interface can be used.
You will also need a ROS Listener and a ROS Talker to send and receive data.
Make sure they communicate over the same ROS topics and std_msgs.Int64 ROS Messages used in here.
"""
import spynn... |
""" Resource Import Tools
@copyright: 2011-12 (c) Sahana Software Foundation
@license: MIT
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... |
from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlpars... |
from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
impo... |
from scrapy.spider import Spider
from scrapy.selector import Selector
from my_settings import name_file, test_mode, difference_days
from datetime import datetime, timedelta
print "Run spider NewenglandFilm"
file_output = open(name_file, 'a')
email_current_session = []
email_in_file = open(name_file, 'r').readlines()
if... |
import base64
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
from django import http, template
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django... |
import sys
from PySide import QtGui, QtCore, QtWebKit
Signal = QtCore.Signal |
from models.portfolio import Portfolio
from models.company import Company
from models.position import Position
import tenjin
from tenjin.helpers import *
import wikipedia
import matplotlib.pyplot as plt
from data_helpers import *
from stock_data import *
import BeautifulSoup as bs
import urllib2
import re
from datetime... |
from typing import List, Optional
"""
16. 3Sum Closest
https://leetcode.com/problems/3sum-closest/
"""
def bsearch(nums, left, right, res, i, j, target):
while left <= right:
middle = (left + right) // 2
candidate = nums[i] + nums[j] + nums[middle]
if res is None or abs(candidate - target) <... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.