content stringlengths 5 1.05M |
|---|
# the kafka consumer, used primarily for sentiment analysis.
# this script reads the kafka stream, produced by our various producers.
# the stream is read continuously, and each entry is assigned to a time window.
# the idea is to have 60second (1 minute) windows which to which data is assigned.
# this allows us to c... |
r"""Use TLV decoder and encoder to disassemble and assemble tag-length-value EMV data.
By default TLV data is broken down into bytes:
>>> import pyemv
>>> tlv_data = bytes.fromhex("9C0101E0055F2A0202089F0200")
>>> pyemv.tlv.decode(tlv_data)
{'9C': b'\x01', 'E0': {'5F2A': b'\x02\x08'}, '9F02': b''}
... |
from django.views.generic.base import TemplateView
from regulations.generator.api_reader import ApiReader
class SearchView(TemplateView):
template_name = 'regulations/search.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
results = get_data(self.requ... |
import os
from django.conf import settings
from django.core import management
from ievv_opensource.ievvtasks_common.base_command import BaseIevvTasksCommand
from ievv_opensource.ievvtasks_development.management.commands.ievvtasks_dump_db_as_sql import \
get_dumpdata_filepath
class Command(BaseIevvTasksCommand):... |
Print Nth term in A.P
The first two terms (a1, a2) of a strictly increasing arithmetic progression (A.P) are passed as input. The program must print the Nth term (aN) in the arithmetic progression.
Input Format:
- The first line will contain the value of the first term a1
- The second line will contain the value of th... |
#!/usr/bin/env python3
"""
Functions for predicting time-integrated ionospheric Faraday rotation effects.
Uses RMextract package to get time-dependent ionospheric RMs for a given
observation, then performs the time-integration to work out the effective
change in polarization angle, and the effective depolarization (t... |
import unittest
import numpy as np
import gzip
import struct
class OpenNI2Test( unittest.TestCase ):
def test16bitArray( self ):
arr = np.array([1,2,3], dtype=np.uint16)
f = gzip.open("tmp.bin.gz", "wb")
f.write( "".join([struct.pack("H", x) for x in arr]) )
f.close()
f = ... |
from telebot import TeleBot as Bot
from helpers.conversation import ConversationsStorage, Conversation
from helpers.messaging import parse_manifest, send_until_question
from api import UsersAPI, OrdersAPI, RequisitesAPI, BillsAPI
from constants import BOT_TOKEN
bot = Bot(BOT_TOKEN)
welcome, manifest = parse_manifest()... |
"""greensManager URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... |
from django.urls import path
from .views import LoginProfile, UserProfiles
urlpatterns = [
path('login/', LoginProfile.as_view(), name="loginuser"),
path('logout/<str:token>/', LoginProfile.as_view(), name="logoutuser"),
path('create/', UserProfiles.as_view(), name="createuser"),
]
|
import string
word_usage = dict()
d = open('words.txt') # open a text file of dictionary words
word_list = dict()
for i in d:
word_list[i.strip()] = None
word_list['i'] = None
word_list['a'] = None
def process_line(line):
"""Processes lines of text from Project Gutenberg, stripping punctuation,
conver... |
import json
import os
import sys
import mxnet as mx
import matplotlib.pyplot as plt
from mxnet import gluon, nd
from mxnet.gluon.model_zoo import vision
import numpy as np
import cv2
ctx = mx.cpu()
densenet121 = vision.densenet121(pretrained=True, ctx=ctx)
mobileNet = vision.mobilenet0_5(pretrained=True, ctx=ctx)
res... |
import pytest
from bs4 import BeautifulSoup
from django.contrib.auth import get_user_model
from django.forms import fields
from django.forms.models import ModelChoiceField, ModelMultipleChoiceField
from entangled.forms import EntangledModelForm
from .models import Product, Category
class ProductForm(EntangledModelF... |
from __future__ import absolute_import, division, print_function
from cctbx import translation_search
from cctbx import crystal
from cctbx import miller
from cctbx import xray
from cctbx import maptbx
from cctbx.development import random_structure
from cctbx.development import debug_utils
from cctbx.array_family import... |
###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2013-2014, NYU-Poly.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary for... |
import sys
import heapq
def sol():
# sys.stdin = open("./1261/input.txt")
input = sys.stdin.readline
M, N = map(int, input().split())
rooms = [list(map(int, list(input())[:-1])) for _ in range(N)]
print(dijkstra(rooms, N, M))
def dijkstra(rooms, N, M):
max_int = sys.maxsize
dist = [max_i... |
#
# PySNMP MIB module JUNIPER-MOBILE-GATEWAY-SGW-GTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-MOBILE-GATEWAY-SGW-GTP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:00:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using... |
"""
Geospatial queries.
"""
from collections import defaultdict
from shapely.geometry import mapping
__all__ = [
'tweets_in_region',
'hashtag_counts_in',
'user_counts_in',
]
seattle = [
[[-122.4596959,47.4810022],
[-122.4596959,47.7341388],
[-122.2244329,47.7341388],
[-122.2244329,47.4... |
"""
---OK---
"""
from collections import OrderedDict
import copy
import numpy as np
from crystalpy.examples.Values import Interval
class PlotData1D(object):
"""
Represents a 1D plot. The graph data together with related information.
"""
def __init__(self, title, title_x_axis, title_y_axis):
... |
import sys
sys.path.append("/vagrant/ctf-infrastructure/api")
import api
from datetime import datetime, timedelta
settings = api.config.get_settings()
settings["start_time"] = datetime.now()
settings["end_time"] = settings["start_time"] + timedelta(weeks=1)
api.config.change_settings(settings)
print("Started the ... |
import gzip
import io
import os
from datetime import datetime
from azure.storage.blob import BlockBlobService
class BlobHelper:
def __init__(self, blob=None):
account_name = os.environ["AzureStorageAccountName"]
account_key = os.environ["AzureStorageAccountKey"]
self.blob_service = BlockB... |
primeiro = int(input('Digite o primeiro Termo: '))
razao = int(input('Digite a razão: '))
c = 0
termos = 10
while c < termos:
print(primeiro)
primeiro += razao
c += 1
if c == termos:
termos = int(input('Quantos tempos deseja mostrar Mais: '))
c = 0
print('PROGRAMA ENCERRADO')
|
from markdown import markdown
import os
def render_markdown(file_name, dir_path = 'app/templates'):
"""Takes the specified file path and
returns it as HTML
"""
html = ""
#os.path.join creates an OS-valid path
path = os.path.join(dir_path, file_name)
with open(path) as html_file:
htm... |
import os
import time
import datetime
import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from collections import namedtuple
from more_itertools import windowed
import dill as pickle
import json
from tqdm import tqdm
import torch
import torch.nn.functional as F
from utils.parameter... |
from transformer import cli
if __name__ == '__main__':
cli.main_group()
|
# Copyright 2014 hm authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from hm import config
_managers = {}
_expected_methods = ['create_load_balancer', 'destroy_load_balancer', 'attach_real', 'detach_real']
def register(name, cls):
... |
from .db import db
class User_Group(db.Model):
__tablename__ = 'users_groups'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
groups_id = db.Column(db.Integer, db.ForeignKey(
"groups.id"), nullable=False)
def to_dict... |
print(input("Enter string to be reversed: ")[::-1])
|
import unittest
from monocliche.src.Board import Board
from monocliche.src.Game import Game
from monocliche.src.enum.GameStatus import GameStatus
class GameTest(unittest.TestCase):
def test_add_player(self):
game = Game()
player = game.add_player("Name")
self.assertEqual("Name", player... |
"""
Dask.DataFrame IO.
"""
from typing import Any, Callable, Dict, Iterable, Optional, Union
import dask
import dask.bag as db
import dask.dataframe as dd
import simplekv
from dask.delayed import Delayed
from kartothek.api.discover import discover_datasets_unchecked
from kartothek.core.cube.cube import Cube
from kart... |
import spacy
from benepar.spacy_plugin import BeneparComponent
nlp = spacy.load('en')
nlp.add_pipe(BeneparComponent("benepar_en2"))
doc = nlp(u"The time for action is now. It's never too late to do something.")
sent = list(doc.sents)[0]
print(sent._.parse_string)
print(list(sent._.children)[0])
|
# Generated by Django 2.2.4 on 2019-10-11 14:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("iaso", "0008_auto_20191010_1147")]
operations = [
migrations.CreateModel(
name="Group",
fields=[... |
#!/usr/bin/python3.6
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
from debug import dprint
df = pd.read_csv('../input/train.csv')
cls_counts = Counter(cls for classes in df['attribute_ids'].str.split() for cls in classes)
labels = pd.read_csv('../input/labels.csv')
labels = la... |
import json
import os
from os.path import dirname
class SubdivisionParser:
def __init__(self):
json = self._get_json()
temp_multi_words_dict = {
"united states": "US",
"us of america": "USA",
"u s a": "USA",
"u . s . a": "USA",
... |
#------------------------------------------------------------------------------
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from .wx_test_assistant import WXTestAssistant, skip_nonwindows
from .. import html
@skip_nonwi... |
import json
import re
import uuid
from typing import Optional
from django.apps import apps
from django.contrib.sites.shortcuts import get_current_site
from django.db import models, transaction
from django.db.models import Count, QuerySet
from django.template import Context, Template
from django.urls import reverse
fro... |
from time import ctime
from SocketServer import (TCPServer as TCP, StreamRequestHandler as SRH)
host = ""
port = 4134
addrs = (host, port)
class MyRequestHandler(SRH):
def handle(self):
print "connected from "+str(self.client_address)
self.wfile.write("["+ctime()+"] "+str(self.rfile.readline()))
... |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='To gather historical and ongoing rainfall data to use in the prediction of Australian wheat crop production.',
author='Rodney J Baker',
license='MIT',
)
|
"""Test creation of tensor datasets.
Test target:
- :py:meth:`lmp.util.dset.FastTensorDset`.
- :py:meth:`lmp.util.dset.SlowTensorDset`.
"""
import torch
import lmp.util.dset
from lmp.dset import WikiText2Dset
from lmp.tknzr import WsTknzr
def test_fast_tensor_dset(max_seq_len: int) -> None:
"""Load dataset in me... |
#!/usr/bin/python
"""Generate some amusing data."""
# It is your choice for the type of data you would like to send. It could
# be bitcoin prices at a given time, it could be the CPU utilization on the
# server at a given time, it could be temperature in your city at a given
# time. Keep in mind that this data will n... |
""" Bivariate operators"""
from .base import *
from .activation import BoundSqrt, BoundReciprocal
class BoundMul(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
... |
# Copyright 2001 by Tarjei Mikkelsen. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""
This module provides code to convert Bio.Pathway.System objects into
a text file that ca... |
#
# PySNMP MIB module MBG-SNMP-XPT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MBG-SNMP-XPT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:10:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
import itertools
import csv
import os
import requests
import click
from importers import CSVImportCommand
from utils import transform_polygons_to_multipolygon
import hmrc_addressbase
class CambridgeLandsImportCommand(CSVImportCommand):
def __init__(
self, file_names, api_url, token,
lr_ap... |
import motor.motor_asyncio
from fastapi import FastAPI
from fastapi_users import FastAPIUsers, models
from fastapi_users.authentication import JWTAuthentication
from fastapi_users.db import MongoDBUserDatabase
from httpx_oauth.clients.google import GoogleOAuth2
from starlette.requests import Request
DATABASE_URL = "mo... |
from __future__ import absolute_import
import sys
import unittest
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import clear_url_caches
from six.moves import reload_module
def reload_urls():
clear_url_caches()
reload_module(sys.modules[settings.ROOT_URLCONF... |
#!/usr/bin/env python
# coding: utf-8
# # Homework 3
# ## Download the Module 3 homework here: [Homework3](https://sites.psu.edu/math452/files/2022/02/HWWeek3.pdf)
# In[ ]:
|
from .JsonScraper import JSONScraper
from ._utils import get_minutes, normalize_string, dateCleaner
class PinchOfYum(JSONScraper):
@classmethod
def host(self):
return 'pinchofyum.com'
def title(self):
return self.data["name"]
'''{
"@context": "https:\/\/schema.org\/",
"@type":... |
from __future__ import print_function
import numpy as np
from . import checkers
from . import preference as pref
from . import common
class BipartiteGraphAnnealerBase :
def __init__(self, cext, dtype, b0, b1, W, optimize, prefdict) :
self._cext = cext
self.dtype = dtype
if not W is No... |
import discord
from discord.ext import commands, menus
from extra.menu import ConfirmSkill
import os
from typing import Dict, Any, List
from mysqldb import the_database
mod_role_id = int(os.getenv('MOD_ROLE_ID'))
admin_role_id = int(os.getenv('ADMIN_ROLE_ID'))
owner_role_id = int(os.getenv('OWNER_ROLE_ID'))
event_mana... |
# -*- coding: utf-8 -*-
"""
rio.blueprints.event.controllers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import json
import logging
from uuid import uuid4
from rio.core import cache
from rio.core import graph
from rio.models import get_data_by_slug_or_404
from rio.tasks import exec_event
logger = logging.getLogger('rio.eve... |
# Uma variavel é algo que salvamos na memoria no computador. Ela armazena uma
# inofrmação que pode ser chamada depois. Podendo ser algo simples como um texto
# ou até mesmo algo mais complicado como uma função
# Para criar um variavel apenas delcare seu nome, coloque igual e em seguida o
# que você deseja colocar d... |
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
__all__ = ['make_df_for_ml',
'make_simple_poly',
'get_linear_regression',
'get_cost_curve_coefs']
def mak... |
#!/usr/bin/env python3
import sys
import Pyro4
import publisher
def main():
sys.excepthook = Pyro4.util.excepthook
p1 = publisher.Publisher('P1', 'X')
p2 = publisher.Publisher('P2', 'Y')
with Pyro4.locateNS() as ns:
i1 = Pyro4.Proxy('PYRONAME:intermediary1')
i2 = Pyro4.Proxy('PYRONAME:i... |
# -*- coding: utf-8 -*-
"""Copyright Header Details
Copyright
---------
Copyright (C) Guya , PLC - All Rights Reserved (As Of Pending...)
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
LICENSE
-------
This file is subject to the terms and conditi... |
#
# Chip8
#
import pygame
import random, math
import time
import code
windowScale = 5
windowH = 32 * windowScale
windowW = 64 * windowScale
pixQt = windowH*windowW
chip8_fontset = (
0xF0, 0x90, 0x90, 0x90, 0xF0, # 0
0x20, 0x60, 0x20, 0x20, 0x70, # 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, # 2
0xF0, 0x10, 0xF0, ... |
malphabet = {".-": 'a', "-...": 'b', "-.-.": 'c', "-..": 'd', '.': 'e', "..-.": 'f', "--.": 'g', "....": 'h', "..": 'i',
".---": 'j', "-.-": 'k', ".-..": 'l', "--": 'm', "-.": 'n', "---": 'o', ".--.": 'p', "--.-": 'q',
".-.": 'r', "...": 's', '-': 't', "..-": 'u', "...-": 'v', ".--": 'w', "-..-"... |
import requests
import json
import os
import time
import sys,argparse
from datetime import datetime
parser=argparse.ArgumentParser()
parser.add_argument('--apikey', help='IBM Cloud API Key',required=True)
parser.add_argument('--rgid', help='Resource group ID',required=True)
parser.add_argument('--region', help='Regi... |
from .ParameterSearch import ParameterSearch
import concurrent.futures
class ThreadedParameterSearch(ParameterSearch):
"""Threaded version of :py:class:`alpenglow.utils.ParameterSearch`.
"""
def __init__(self, model, Score, threads=4, use_process_pool=True):
ParameterSearch.__init__(self, model, S... |
import discord
from discord.ext import commands
import asyncio
class Mod(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def format_mod_embed(self, ctx, user, success, method, duration = None, location=None):
'''Helper func to format an embed to prevent extra code'''
em... |
def ackermann(m,n):
#opening the file to check for values
file = open('ack_vals.txt','r')
values = file.read()
for line in values.split('\n'):
#each line has the parameters and their corresponding result
line_arr = line.split(' ')
#converted into array of numbers
if line... |
import numpy as np
import pandas as pd
import neurokit2 as nk
# =============================================================================
# Events
# =============================================================================
def test_events_find():
signal = np.cos(np.linspace(start=0, stop=20, num=1000))... |
"""A simple entrypoint-free plugin system for python"""
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import inspect
import warnings
from importlib import import_module
from collections import namedtuple
from enum import Enum
from diot import OrderedDiot
try: # pragma: no cover
import im... |
import logging
logger = logging.getLogger(__name__)
START_REWARD = 200
class LandType:
CONSTRUCTABLE = 0
INFRASTRUCTURE = 1
START = 2
PARKING = 3
JAIL = 4
CHANCE = 5
@staticmethod
def description(val):
ret = ["Constructable",
"Infrastructure",
"... |
"""
Deprecated stuff. This is expected to be removed partially or
completely at some point, so don't pollute main logic with it.
"""
import os
import distutils.dir_util
from logging import getLogger
from .iotprovision_main import STATUS_SUCCESS, STATUS_FAILURE
from .config import Config
def deprecated(args):
""... |
from .cameras import Camera
from .scene import Scene, split_scene
# add to __all__ as per pep8
__all__ = [Camera, Scene, split_scene]
|
#!/usr/bin/env python3
from collections import OrderedDict
try:
from lxml import etree
except:
from xml.etree import ElementTree as etree
class Node(object):
def __init__(self, name=None, depth=0):
self.name = name
self.depth = depth
self.sources = set()
self.children = Ord... |
# Keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Flatten, LSTM, Conv1D, MaxPooling1D, Dropout, Activation
from keras.layers.embeddings import Embedding
## Plot
import plotly.offline as py
im... |
import os
import re
import sys, time
import numpy as np
final=''#global vars to save results of op
fresult=''#global vars to save results of for
fcall=''#global vars to save results of call
def check(newcontext):
nc=newcontext
#TODO:cannot deal with multiple problems,need help
lk=nc.count('(')
rk=nc.count(')')
l... |
import math
from numba import cuda
SQRT_TWOPI = 2.506628274631
@cuda.jit
def get_mhat(mag, err, sed, sed_err, output):
pos, col = cuda.grid(2)
if col >= len(sed) or pos >= len(mag):
return
part1 = 0
part2 = 0
for i in range(sed.shape[1]):
if not math.isnan(mag[pos, i]) and not mat... |
# Copyright (c) 2017. Zuercher Hochschule fuer Angewandte Wissenschaften
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License'); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#... |
# Uses python3
import sys
import numpy as np
def get_fibonacci_huge_naive(n, m):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current % m
def get_fibonacci_mod(n, m):
fib_arr = []
mod_arr = []
... |
from django.apps import AppConfig
class MedicoConfig(AppConfig):
name = 'medico'
|
import pytest
from django.contrib.auth.models import Permission
from django.test import override_settings
from django.urls import reverse
from django_otp import login as otp_login
from django_otp.plugins.otp_totp.models import TOTPDevice
from wagtail_2fa.middleware import VerifyUserMiddleware, VerifyUserPermissionsMid... |
from dataclasses import replace
from typing import Any, Iterator
from unittest.mock import patch
import pytest
import black
from tests.util import (
DEFAULT_MODE,
PY36_VERSIONS,
THIS_DIR,
assert_format,
dump_to_stderr,
read_data,
)
SIMPLE_CASES = [
"beginning_backslash",
"bracketmatch... |
import sys
def solution(R):
return sum(R[i] < R[i+3] for i in range(len(R)-3))
print(solution([*map(int, sys.stdin.readlines())]))
|
tup2 = (1, 2, 3, 4, 5, 6, 7); #tuplas (son inmutables: sus valores no cambian)
print "tup2[1:4]: ", tup2[1:4];
print "-"*70
print len((1,2,"a",3)) # cantidad de valores
tup3= ("a","b","c","perro","e","f","g", "i","loro");
tup4 = tup2 + tup3
print tup4
print "-"*70
tup5 = tup4[0];
tup6 = tup4[1];
suma = tup5 + tup6
ca... |
from tempfile import TemporaryDirectory
import os
from forest.common import proc_utils
cmake_command = 'cmake'
default_args = list()
def _construct(self, srcdir, builddir):
self.srcdir = srcdir
self.builddir = builddir
def _is_configured(self):
return os.path.exists(os.path.join(self.builddir, 'Makefi... |
import json
import os
class Sample:
"""A helper class for managing static sample JSON returns from MBTA API V3.
"""
def __init__(self, json_path):
self.raw_json = json.loads(open(json_path, 'rt').read())
def __repr__(self):
return self.raw_json['data']
def __str__(self):
... |
from ..factory import Method
class viewTrendingStickerSets(Method):
sticker_set_ids = None # type: "vector<int64>"
|
#!/usr/bin/env python3
"""Prepares a simple TVM library for testing."""
from os import path as osp
import sys
import tvm
def main():
n = tvm.var('n')
A = tvm.placeholder((n,), name='A')
B = tvm.placeholder((n,), name='B')
C = tvm.compute(A.shape, lambda *i: A(*i) + B(*i), name='C')
s = tvm.creat... |
#
# Build various blueprints
#
from javascript import require
from botlib import *
Vec3 = require('vec3').Vec3
from blueprint import *
from workarea import *
import blueprint_data
#
# Main class that has the build, analyze and helper functions
#
class BuildBot:
def __init__(self):
self.blueprintL... |
"""
Test of integrating torch Conv2d and LSTM modules
"""
from numbers import Number
import numpy as np
import torch
import torch.nn as nn
if __name__ == "__main__":
MAX_LENGTH = 100
MIN_LENGTH = 10
NUM_SAMPLES = 45
CHANNELS = 3
WIDTH = 128
HEIGHT = 128
HIDDEN_SIZE = 32
HIDDEN_LAYERS =... |
"""
A title to keep sphinx-gallery happy
====================================
"""
from matplotlib import pyplot as plt
plt.plot()
plt.show()
|
import subprocess
# open Terminal and call run-mbed-cli.sh
subprocess.call(
["/usr/bin/open", "-W", "-n", "--fresh","-a", "/Applications/Utilities/Terminal.app", "run-mbed-cli.sh"]
)
# # call shell script that calls terminal
# subprocess.call(
# ["/bin/sh","/Users/ausbla01/mbed/mbed-cli-osx-installer/run-... |
from __future__ import annotations
from typing import List, Tuple, Dict
import docker
from docker.models.containers import Container
from docker.models.images import Image
from docker.client import DockerClient
from docker.errors import APIError
import re
import io
import tarfile
import os
from datetime import datetime... |
# __version__.py
__title__ = 'DirtyWordOfFilter'
__date__ = '2019-03-30'
__description__ = 'Filter out all dirty words.'
__version__ = '0.0.1'
__author__ = 'Residual Mark'
__author_email__ = '1285679912@qq.com'
|
from .redis import Redis
|
import ossaudiodev as sd
import scipy
from scipy.optimize import leastsq
import numpy as np
from IPython.display import Audio
from recipes.misc import is_interactive
from obstools.psf.model import Model
from .spectral import Spectral, normaliser
def rescale(data, interval=(-1, 1)):
"""Linearly rescale data t... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-20 19:44
from __future__ import unicode_literals
import c3nav.mapdata.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mapdata', '0064_access_permission_unique_key'),
]
opera... |
# Question 4
# Vowel checker
letter = input("Enter a letter: ")
if letter in ["a", "e", "ı", "i", "o", "ö", "u", "ü", "A", "E", "I", "İ", "O", "Ö", "U", "Ü"]:
print("Passed letter is vowel")
else:
print("Passed letter is not vowel")
|
""" Tracklet XML file parsing
This code was taken as is from the kitti website link
(http://cvlibs.net/datasets/kitti/downloads/parseTrackletXML.py ).
Minor Pythonic naming changes made and TRUNC_UNSET enum addition.
Original header and author comments follow below.
---
parse XML files containing tracklet info for kit... |
#!/usr/bin/env python3
"""
set_membership_annotation.py
Python 3 code for annotating a junction list with presence in annotation,
gene boundaries, antisense transcripts, and presence in various adult, stem
cell, and developmental samples.
"""
import argparse
from datetime import datetime
import glob
import json
imp... |
'''
Manage Azure Resource Manager deployments.
'''
from ... pyaz_utils import _call_az
from . import operation
def create(resource_group, aux_subs=None, aux_tenants=None, handle_extended_json_format=None, mode=None, name=None, no_prompt=None, no_wait=None, parameters=None, rollback_on_error=None, template_file=None, ... |
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["python"]
mycol = mydb["python_test"]
mydict = { "host": "devserver", "ip": "192.168.0.50" }
x = mycol.insert_one(mydict)
|
from rest_framework.common.entity import FileDTO
from rest_framework.common.services import Reader, Printer
import pandas as pd
import numpy as np
from sklearn import preprocessing
'''
살인 발생,살인 검거,강도 발생,강도 검거,강간 발생,강간 검거,절도 발생,절도 검거,폭력 발생,폭력 검거
'''
class Service(Reader):
def __init__(self):
self.f = FileDT... |
# -*-coding:utf-8-*-
from apps.core.flask.login_manager import osr_login_required
from apps.core.blueprint import api
from apps.core.flask.permission import permission_required, permissions
from apps.core.flask.response import response_format
from apps.modules.user.process.email import email_update
__author__ = "Allen... |
import numpy as np
import sys
M = int(sys.argv[1])
K = int(sys.argv[2])
N = int(sys.argv[3])
int8 = True if int(sys.argv[4]) == 1 else False
if int8:
#scale = np.random.normal(size=(M)).astype(np.float32)
scale = np.ones((M)).astype(np.float32)
else:
scale = 1
bias = np.random.normal(size=(M))
#bias = np.... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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 3 of the License, or
(at your option) any later version.
CVXPY is distributed i... |
import torch
from torch.optim import Optimizer
from meta_learning.backend.pytorch.optimizer.memory_static import MemoryStatic
class MetaSGD(Optimizer):
"""Implements SGD with meta learning algorithm.
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.