code stringlengths 1 199k |
|---|
"""Softmax."""
scores = [3.0, 1.0, 0.2]
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
# Compute and return softmax(x)
return np.exp(x)/np.sum(np.exp(x), axis=0)
print(softmax(scores))
import matplotlib.pyplot as plt
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vs... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "python_clientcred.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weight?",
weight = raw_input()
print "So, you're %r old, %r tall, and %r heavy." % (
age, height, weight) |
from .shark import Shark
class Cookiecuttershark(Shark):
_required = []
def __init__(self, *args, **kwargs):
"""Cookiecuttershark
"""
super(Cookiecuttershark, self).__init__(*args, **kwargs)
self.fishtype = 'cookiecuttershark' |
from permission.decorators.permission_required import permission_required |
__author__ = 'bharathramh'
from Vertex import *
from Edges import *
from Graph import *
from MinHeap import *
import sys
class Dijkstra:
def __init__(self):
pass
def dijkstra(self):
self.initializeSingleSource()
S = [] #a set of vertices whose fi... |
import re
from basedownloader import BaseDownloader
class MangahereDownloader(BaseDownloader):
''' Downloader implementation that are targeted at mangahere.com '''
def get_page_count(self, soup):
''' Get the number of pages in the chapter '''
pages = soup.select('select.wid60')[0]
page_c... |
PINBOARD_API_TOKEN = ""
EVERNOTE_DEVELOPER_TOKEN = ""
DIFFBOT_TOKEN = ""
DATABASE_PATH = ""
EVERNOTE_NOTEBOOK = 'archiver_test' |
from djutils.response import JSONResponse
from django.shortcuts import redirect
from django.conf import settings
from rest_framework import status
from . import RestException
class RestExceptionMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, requ... |
from __future__ import annotations
import datetime as dt
from psycopg2.extensions import connection
from gargbot_3000 import config, quotes
from tests import conftest
def test_forum_random(conn: connection):
text, user, avatar_url, date, url, desc = quotes.forum(conn, args=None)
assert isinstance(date, dt.datet... |
from math import log10
count = 0
for i in range(1,10):
count = count + int(1/(1-log10(i))) ##realise that for x > 10, x^n > 10^n
print(count) |
from django.core.checks import ( # pylint: disable=redefined-builtin
Tags,
Warning,
register,
)
from django.utils.module_loading import import_string
from axes.backends import AxesBackend
from axes.conf import settings
class Messages:
CACHE_INVALID = (
"You are using the django-axes cache handl... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bubitest.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from flask import Flask
from imageserver import init_imageserver
import os
from providers import FileSystemProvider
app = Flask(__name__)
init_imageserver(app, provider=FileSystemProvider(os.getenv('MEDIA_ROOT')))
if __name__ == "__main__":
app.run(host='0.0.0.0') |
from django.conf.urls import url
from .views import FlagView, flag_action
urlpatterns = ['',
url('^flag/$', FlagView.as_view(), name='flaggit'),
url('^flag-action/(?P<flag_id>\d+)/(?P<action>[a-zA-Z0-9\-]+)/$', flag_action, name='flag_action'),
] |
import re
import alot
"""
async def pre_envelope_send(ui, dbm, __):
p = r'.*([Aa]ttach|附件|附图|已附|所附)'
e = ui.current_buffer.envelope
if re.match(p, e.body, re.DOTALL) and not e.attachments:
msg = 'No attachments. Send anyway?'
if not (await ui.choice(msg, select='yes')) == 'yes':
... |
import _plotly_utils.basevalidators
class TicklenValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="ticklen", parent_name="barpolar.marker.colorbar", **kwargs
):
super(TicklenValidator, self).__init__(
plotly_name=plotly_name,
parent... |
import hashlib
class User(ksc_db.Model):
first_name = ksc_db.Column(ksc_db.String(140))
last_name = ksc_db.Column(ksc_db.String(140))
username = ksc_db.Column(ksc_db.String(80), unique=True, primary_key=True)
email = ksc_db.Column(ksc_db.String(120), unique=True, primary_key=True)
password = ksc_db.... |
"""
Turbulenz framework for creating browser based games.
"""
__author__ = "Turbulenz Limited"
__copyright__ = "Copyright (c) 2009-2011,2013 Turbulenz Limited"
__version__ = '1.0.7' |
from distutils.core import setup
from setuptools import find_packages
import cabric
setup(
name='cabric',
version=cabric.version,
packages=['cabric'],
url='https://github.com/baixing/cabric',
download_url='https://github.com/baixing/cabric/tarball/master',
license='http://opensource.org/licenses... |
'''
'''
import unittest
class TestCases(unittest.TestCase):
def setUp(self):
pass
def test1(self):self.assertEqual(remove_smallest([1, 2, 3, 4, 5]), [2, 3, 4, 5], "Wrong result for [1, 2, 3, 4, 5]")
def test2(self):self.assertEqual(remove_smallest([5, 3, 2, 1, 4]), [5, 3, 2, 4], "Wrong result for [5... |
class Solution:
# @return a string
def convert(self, s, nRows):
n = len(s)
if n <= 1:
return s
step = 2*(nRows-1)
if step <= 0:
return s
zigzag = ''
for i in range(0, n, step):
zigzag += s[i]
for i in range(1, nRows-1):
... |
from .constant import Constant
__NR_exit = Constant('__NR_exit',1)
__NR_fork = Constant('__NR_fork',2)
__NR_read = Constant('__NR_read',3)
__NR_write = Constant('__NR_write',4)
__NR_open = Constant('__NR_open',5)
__NR_close = Constant('__NR_close',6)
__NR_waitpid = Constant('__NR_waitpid',7)
__NR_creat = Constant('__NR... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('order', '0002_auto_20150209_1943'),
]
operations = [
migrations.AddField(
model_name='customer',
name='customer_slug',
... |
import io
import sys
import numpy as np
import collections
import threading
__all__ = ['stprint', 'stformat', 'print_to_string']
__stprint_locks = collections.defaultdict(threading.Lock)
def _indent_print(msg, indent, prefix=None, end='\n', file=sys.stdout):
print(*[' '] * indent, end='', file=file)
if prefix ... |
from __future__ import division, print_function, unicode_literals
import pytest
import sacred.optional as opt
from sacred.config.config_scope import (ConfigScope, dedent_function_body,
dedent_line, get_function_body,
is_empty_or_comment)
fr... |
from .container_groups_operations import ContainerGroupsOperations
from .operations import Operations
from .container_group_usage_operations import ContainerGroupUsageOperations
from .container_logs_operations import ContainerLogsOperations
from .start_container_operations import StartContainerOperations
__all__ = [
... |
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
size = len(nums)
if size <= 1:
return size
l = 1
prev = 0
comm = nums[0]
for i in range(1, size):
if prev <= 0 an... |
from setuptools import find_packages, setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='agate-sql',
version='0.5.8',
description='agate-sql adds SQL read/write support to agate.',
long_description=long_description,
long_description_content_type='text/x-rst',
author... |
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ansl = -1
ansr = -1
posl = 0
posr = len(nums)
while posl < posr:
mid = (posl+posr)/2
if num... |
a = 2
b = "my string"
type(a) # >>> <class 'int'>
type(b) # >>> <class 'str'>
id(a) # >>> 4412808440
isinstance(a, int) # >>> True
isinstance(a, str) # >>> False
isinstance(b, str) # >>> True
issubclass(bool, int) # >>> True
a is a # >>> True
a is b # >>> False
c = a
a is c # >>> True |
from multiverse.mars import *
from multiverse.mars.core import *
from multiverse.mars.objects import *
from multiverse.mars.util import *
from multiverse.mars.plugins import *
from multiverse.mars.behaviors import *
from multiverse.server.math import *
from multiverse.server.plugins import *
from multiverse.server.even... |
import sys, time, serial
from serial.tools import list_ports
import dcload
import xln6024
from struct import pack, unpack
import smbus
import bq78350
import srec
usbid_bk8514 = '067B:2303'
usbid_bkXLN6024 = '10C4:EA60'
sn_xln6024_top = '276D14130'
sn_8514_top = '1687110009'
sn_xln6024_bottom = '276F12110'
sn_8514_botto... |
from __future__ import print_function
import os
import sys
import pid
import traceback
from axp209 import AXP209
from time import sleep
from threading import Thread
import json
if sys.version_info[0] < 3:
from ConfigParser import SafeConfigParser as ConfigParser
from ConfigParser import NoOptionError, NoSection... |
from __future__ import unicode_literals
from django.apps import AppConfig
class AliasesConfig(AppConfig):
name = 'aliases' |
""" Implementation of command line interace. """
import t05_Node
import t05_Acob
import t05_CFunction
import t05_Function
import t05_helpers
class CommandLineInterface:
def __init__(self):
self.state = None
self.inputFiles = []
def init(self, state, args):
self.state = state
self... |
"""Landing page URL Configuration
"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',
views.LandPageView.as_view(),
name='index'),
] |
import pdb
import os.path, httplib, json, time
from datetime import datetime, date
from scrapy.spiders import Spider
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item, Field
from xvfbwrapper import Xvfb
from pprint import pprint
from selenium import webdriver
from selenium.webdriver.common.by i... |
import unittest
from nativeconfig import StringOption
from test.options import OptionMixin, Option, make_option_type
class TestStringOption(unittest.TestCase, OptionMixin):
@classmethod
def setUpClass(cls):
cls.OPTIONS = [
Option(
option_type=StringOption,
val... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungroupe... |
import click
from .base import cluster_command
@cluster_command.command()
@click.pass_context
def destroy(ctx):
'''Destroy the connected Kubernetes cluster.'''
ctx.obj.controller.destroy_connected_cluster() |
from django import forms
from django.utils.translation import ugettext_lazy as _
class ProfileForm(forms.Form):
name = forms.CharField(
label=_('Name'),
widget=forms.TextInput(attrs={'class': 'uk-width-1-1'}),
max_length=100,
required=False
)
about = forms.CharField(
... |
from FlatCAMObj import FlatCAMGerber, FlatCAMGeometry
def test_isolate(self):
"""
Test isolate gerber
:param self:
:return:
"""
self.fc.exec_command_test('open_gerber %s/%s -outname %s'
% (self.gerber_files, self.copper_top_filename, self.gerber_top_name))
gerbe... |
"""API Discovery api.
The AXIS API Discovery service makes it possible to retrieve information about APIs supported on their products.
"""
import attr
from .api import APIItem, APIItems, Body
URL = "/axis-cgi/apidiscovery.cgi"
API_DISCOVERY_ID = "api-discovery"
API_VERSION = "1.0"
class ApiDiscovery(APIItems):
"""A... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from os import environ
from sys import stderr
DEBUG = environ.get('PGCTL_DEBUG', '')
def debug(msg, *args):
if DEBUG:
print('DEBUG:', msg % args, file=stderr) # pragma: no cover |
import re
import shortcodes.parsers
from django.core.cache import cache
def import_parser(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def parse(value):
ex = re.compile(r'\[(.*?)\]')
groups = ex.findall(value)
... |
import Utils.Util as utl
import Utils.Simulation as sim
import numpy as np
import CLEAR.Libs.Markov as mkv
import simuPOP.demography as dmg
import pandas as pd
import Utils.Plots as pplt
import pylab as plt
def getPopSize(model):
model.plot(utl.home+'aa.png')
return pd.Series([model.init_size[0]]+(model.pop_reg... |
import pkg_resources
import sys
import asyncio
import nest_asyncio
if sys.version_info < (3, 6):
raise EnvironmentError('Hail requires Python 3.6 or later, found {}.{}'.format(
sys.version_info.major, sys.version_info.minor))
if sys.version_info[:2] == (3, 6):
if asyncio._get_running_loop() is not None:... |
"""Code for importing and exporting database records to CSV and YAML sample sheets"""
from collections import OrderedDict
import datetime
import json
from django.shortcuts import get_object_or_404
from django.db import transaction
from django.core.exceptions import ValidationError
from .models import (
BarcodeSet, ... |
"""Pytest fixtures and plugins for the UI application."""
from __future__ import absolute_import, print_function
import pytest
from invenio_app.factory import create_ui
@pytest.fixture(scope='module')
def create_app():
"""Create test app."""
return create_ui |
"""empty message
Revision ID: dab9687afeeb
Revises: 37f460a1f4d2
Create Date: 2019-04-24 16:47:12.721137
"""
from alembic import op
import sqlalchemy as sa
revision = 'dab9687afeeb'
down_revision = '37f460a1f4d2'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please... |
from . import ExistingBookAction
class PublishAction(ExistingBookAction):
pass |
ROOT_POLLUTION_API_URL = 'openweathermap.org/pollution/v1'
CO_INDEX_URL = 'co'
OZONE_URL = 'o3'
NO2_INDEX_URL = 'no2'
SO2_INDEX_URL = 'so2'
NEW_ROOT_POLLUTION_API_URL = 'openweathermap.org/data/2.5'
AIR_POLLUTION_URL = 'air_pollution'
AIR_POLLUTION_FORECAST_URL = 'air_pollution/forecast'
AIR_POLLUTION_HISTORY_URL = 'ai... |
import unittest
from app.models import User,Role,AnonymousUser,Permission
import sys
import time
from app import create_app,db
class UserModelTestCase(unittest.TestCase):
def test_password_setter(self):
u = User(password= 'cat')
self.assertTrue(u.password_hash is not None)
def test_no_password_g... |
from random import random
import numpy
from sigmoidNode import SigmoidNode
class Network:
def __init__(self, rowSizes):
#Initialize the network's nodes
self.network = list()
for i in rowSizes:
self.network += [[SigmoidNode() for x in range(i)]]
def startFromScratch(self):
... |
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.decomposition import PCA
data=pd.read_csv('train.csv')
data1=data.values
X=data1[:,1:]
y=data1[:,:1]
y=np.ravel(y)
Xtrain,Xtest,ytrain,... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('foobar', '0022_merge_20170412_1029'),
]
operations = [
migrations.AlterModelOptions(
name='purchase',
options={'ordering': ['-date_create... |
import RPi.GPIO as GPIO
import threading
import time
from RecordingQuality import RecordingQuality
from enum import Enum
class RecordingLEDState(Enum):
off = 1
on = 2
blinking = 3
BOUNCE_TIME = 300
REC_BLINK_TIME = 0.4
BIG_LED_PIN = 38
MED_LED_PIN = 31
FAST_LED_PIN = 26
REC_LED_PIN = 15
BIG_BUTTON_PIN = 36
... |
def load_codes(filename):
with open(filename, 'r') as filehandle:
line = filehandle.readlines()[0].strip()
codes = map(int, line.split(','))
return codes
def xor_codes(txt_codes, pw_codes):
ret = []
for i, textcode in enumerate(txt_codes):
xored = textcode ^ pw_codes[i % len(... |
"""
[11/6/2012] Challenge #111 [Difficult] The Josephus Problem
https://www.reddit.com/r/dailyprogrammer/comments/12qicm/1162012_challenge_111_difficult_the_josephus/
Flavius Josephus was a roman historian of Jewish origin. During the Jewish-Roman wars of the first century AD, he was
in a cave with fellow soldiers, 41 ... |
import climate
import glob
import os
import pagoda
import pagoda.viewer
def full(name):
return os.path.join(os.path.dirname(__file__), name)
def main(root, subject, block='block00', trial='trial00'):
w = pagoda.cooper.World(dt=1. / 100)
w.erp = 0.3
w.cfm = 1e-6
w.load_skeleton(full('skeleton-{}.txt'... |
"""
Custom admin used for testing.
"""
from __future__ import unicode_literals
from django.conf.urls import url
try:
from django.core.urlresolvers import reverse
except ImportError:
from django.urls import reverse
from django.template.response import TemplateResponse
from django.utils.translation import ugettex... |
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
longdesc = """
PyBagIt Version 1.5.3
This module helps with creating an managing BagIt-compliant packages. It has
been created to conform ... |
def singleton(cls):
instance = cls()
instance.__call__ = lambda: instance
return instance |
"""Test cases for min cut."""
import math
from src.course1.week4.mincut import min_cut
def test_mincut():
graph = {
1: [2, 3, 4],
2: [1, 4, 5],
3: [1, 4],
4: [1, 2, 3, 5],
5: [2, 4]
}
n = len(graph)
trials = math.ceil(n * n * math.log(n))
result = n
while ... |
import unittest
from tests.harness import instrumentGooey
from gooey import GooeyParser
from gooey.tests import *
class TestTextarea(unittest.TestCase):
def makeParser(self, **kwargs):
parser = GooeyParser(description='description')
parser.add_argument('--widget', widget="Textarea", **kwargs)
... |
import os
import platform
import random
import sys
import tarfile
import tempfile
import time
from unittest import mock
import pytest
import wandb
if sys.version_info >= (3, 9):
pytest.importorskip("tensorflow")
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy
import plotly
import requests
from ... |
from requests import request
from huegely import (
exceptions,
groups,
utils,
)
from huegely.lights import LIGHT_TYPES
from huegely.sensors import SENSOR_TYPES
class Bridge(object):
def __init__(self, ip, username=None, transition_time=None):
self.ip = ip
self.username = username
... |
import panflute as pf
import string
EXAMPLE_TEMPLATE = '''
\\exdisplay
\\begingl[aboveglftskip=-2.25pt]
\\gla $target//
\\glc $gloss//
\\glft `$native'//
\\endgl
\\xe
'''
EXAMPLE_BLOCK_TEMPLATE = '''
\\begin{sentence}
$examples
\\end{sentence}
'''
RULE_TEMPLATE = '''
\\begin{definition}[$name]
~\\\\
\\textsc{$definitio... |
from unittest import TestCase
from nba_player_news.data.subscriber_event.outcomes import SubscriberEventOutcome
from nba_player_news.data.subscriber_event.processors import Subscriber
class MockSubscription:
def __init__(self, unsubscribed_at):
self.unsubscribed_at = unsubscribed_at
class MockSubscriptions:... |
BOT_NAME = 'gtrends_scraper'
SPIDER_MODULES = ['gtrends_scraper.spiders']
NEWSPIDER_MODULE = 'gtrends_scraper.spiders'
ROBOTSTXT_OBEY = False
ITEM_PIPELINES = {
'gtrends_scraper.pipelines.SQLiteItemPipeline': 300,
}
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 5
AUTOTHROTTLE_MAX_DELAY = 60
AUTOTHROTTLE_TA... |
class Solution:
# @param head, a ListNode
# @param val, an integer
# @return a ListNode
# Non-recursive way
def removeElements(self, head, val):
# Write your code here
i = head
while i is not None:
if i.val != val:
head = i
break
... |
from .a_component import AComponent
class AUnorderedList(AComponent):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def tagname(self):
return "ul" |
subreddit = 'python'
t_channel = '@pythonreddit'
def send_post(submission, r2t):
return r2t.send_simple(submission, min_upvotes_limit=100) |
r"""Tool to validate submission for adversarial competition.
Usage:
python validate_submission.py \
--submission_filename=FILENAME \
--submission_type=TYPE \
[--use_gpu]
Where:
FILENAME - filename of the submission
TYPE - type of the submission, one of the following without quotes:
"attack", "targ... |
import poplib
username = 'someuser'
password = 'S3Cr37'
mail_server = 'mail.somedomain.com'
p = poplib.POP3(mail_server)
p.user(username)
p.pass_(password)
for msg_id in p.list()[1]:
print msg_id
outf = open('%s.eml' % msg_id, 'w')
outf.write('\n'.join(p.retr(msg_id)[1]))
outf.close()
p.quit() |
import numbers
from swimlane.exceptions import ValidationError
from .base import Field
class NumberField(Field):
field_type = (
'Core.Models.Fields.NumericField, Core',
'Core.Models.Fields.Numeric.NumericField, Core'
)
supported_types = [numbers.Number]
def __init__(self, *args, **kwargs... |
import os
class Config(object):
STAND_COAL_COEFFICIENT = {
u'原煤': 0.7143,
u'洗精煤': 0.900,
u'其他洗煤': 0.2857,
u'型煤': 0.5000,
u'焦炭': 0.9714,
u'焦炉煤气': 5.714,
u'其他煤气': 5.571,
u'原油': 1.4286,
u'汽油': 1.4714,
u'煤油': 1.4714,
u'柴油': 1.4571,
... |
SERVER_NAME = '127.0.0.1:5000'
writings_schema = {
# Schema definition, based on Cerberus grammar. Check the Cerberus project
# (https://github.com/nicolaiarocci/cerberus) for details.
'title': {
'type': 'string',
},
'chapters': {
'type': 'list',
},
'heroes': {
'type'... |
__author__ = 'Joe'
def export(field_desc):
"""
:param field_desc:
:type field_desc: bitcoder.bitcoder.Encoded
:return:
"""
output = '// Automatically generated file, changes may be lost when file is regenerated\n'
output += '\n'
for name, field in field_desc.fields().iteritems():
... |
"""
DOCS for dataenc as a module
When run it should go through a few basic tests - see the function test()
This module provides low-level functions to interleave two bits of data into each other and separate them.
It will also encode this binary data to and from ascii - for inclusion in HTML, cookies or email transmiss... |
import unittest
from unittest.mock import patch
import inspect
from functools import wraps
import asyncio
import json
import warnings
import io
import sys
import aiohttp
from ..util import rag
from ..request import Request, SessionFactory
from .. import restspec
try:
trace_func = sys.gettrace()
except:
pass
els... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Collection.publication_status'
db.delete_column('portal_collection', 'publication_status')
# Adding field 'Re... |
import collections
import json
import logging
import os
from lib.cuckoo.common.abstracts import Processing, BehaviorHandler
from lib.cuckoo.common.config import Config
from .platform.windows import WindowsMonitor
from .platform.linux import LinuxSystemTap
log = logging.getLogger(__name__)
class Summary(BehaviorHandler)... |
"""
Module with some useful functions that will be used all around the rest of
the code for varied purposes.
@author: Luiz Felipe Machado Votto
"""
import json
import matplotlib.pyplot as plt
import pathlib
import pickle
import time
import numpy as np
import base64
import csv
from glmtscatt.constants import WAVE_NUMBER... |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline impo... |
import pyalps.cthyb as cthyb
import pyalps.mpi as mpi
import sys, re
def readParameters(str_parms):
comment_symbol = '(!|#|%|//)'
propFile= open(str_parms, "rU")
propDict= dict()
for propLine in propFile:
propDef= propLine.strip();
if re.match(comment_symbol, propDef) is not None \
... |
def common_words(first, second):
parse = lambda s:set(s.split(','))
out = parse(first).intersection(parse(second))
return ','.join(sorted((out)))
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert common_words("hello,world", "hello,ear... |
'''
A script to find 9 digit pandigital products
'''
def isPandigital(num):
if sorted(str(num)) == sorted('123456789'):
return True
else:
return False
def check_for_pan():
prods=[]
for i in range(1,10):
for j in range(1000,10000):
if isPandigital(str(i)+str(j)+str(i*j... |
import os
from twilio.rest import Client
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
document_permission = client.sync \
.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.documents("MyFirstDocument") \
.document_permis... |
TOKEN = 'token_here'
HOST = '0.0.0.0'
PORT = 80
PASSWORD = 'pw_no_blank'
RESOURCE_URL = 'http://example.com/songs' # Mustn't end with '/'
HOST_WEB = '0.0.0.0'
PORT_WEB = 8080 |
import vim
from indenty.scanner import Scanner, Indents
scanner = Scanner()
scanner.modelines = vim.vars['indenty_modelines']
scanner.tabstop_priority = vim.vars['indenty_tabstop_priority']
scanner.min_lines = vim.vars['indenty_min_lines']
scanner.max_lines = vim.vars['indenty_max_lines... |
from flask import Flask
from api.login_api import login_blueprint
from api.notes_api import note_blueprint
from api.register_api import register_blueprint
from log.log_util import register_logger
log = register_logger("demo")
app = Flask(__name__)
app.register_blueprint(login_blueprint, url_prefix="/login")
app.registe... |
from os import path
PROJECT_DIR = path.dirname(path.realpath(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATI... |
from getpass import getpass
from websocket import create_connection
import requests
import json
import time
import datetime
import threading
feed_port = "5555"
websockets_port = "2006"
feed_delay = 70
spec_on = 5
record = False
record_start = 5
record_stop = 5
spec_player = "player_name"
url = "http://live.fakkelbrigad... |
from .__version__ import __title__, __description__, __url__, __version__
from .__version__ import __build__, __author__, __author_email__, __license__
from .__version__ import __copyright__ |
class SeamheadsPipeline(object):
def process_item(self, item, spider):
return item |
import itertools
import os.path
import re
from rime.basic import codes as basic_codes
from rime.basic import consts
from rime.basic import test
from rime.basic.targets import problem
from rime.core import codes as core_codes
from rime.core import targets
from rime.core import taskgraph
from rime.util import files
class... |
from modserver import *
def run(s):
rwrite(s, "hello from Python") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.