content stringlengths 5 1.05M |
|---|
"""
Takes the text and saves it as a dictionary and a corpus for gensim to use
"""
import os
import time
import traceback
from collections import defaultdict
from multiprocessing.pool import Pool
import psycopg2
from gensim import corpora
from src.features.text.article_tokenizer import tokenize
from src.visualization... |
# This script shows the netlist database for the VCO-ADC Database Using the new version of spectreIOlib
import sys
import numpy as np
import pandas as pd
import os
home_address = os.getcwd()
sys.path.insert(0,'/shares/MLLibs/GlobalLibrary')
from spectreIOlib import TestSpice, Netlists
import time
class DTC1_spice(... |
import MySQLdb
import sys
sys.path.append('C:/Users/900152/Documents/Dados/TrabalhoPython/JM_exerc')
from model.Back_model import BackEnd
class BackDb:
def select_all(self):
comand = 'SELECT * FROM topskills01.02_JM_BackEnd;'
selectcomand = self.cursor.execute(comand)
return selectcomand
... |
import sys
sys.path.append('..')
from Game import Game
from .Boese2Logic import Board
import numpy as np
class Boese2Game(Game):
def __init__(self, n):
self.n = n
self.Es = {}
def getInitBoard(self):
b = Board(self.n)
self.Es = {}
self.Es[self.stringRepresentation(... |
#~/usr/bin/env python
'''
Y_Classifier will classifiy each frame for the required classes
VideoReader will be used to read the video and to emit a certain frame based on the framerate that is chosen
VideoReader should run multithreaded with Y_Classifier as a shared resource, multiple video feeds can be simultaneously ... |
import unittest
from paddle.vision.models import mobilenet_v2
import numpy as np
import interpretdl as it
from tests.utils import assert_arrays_almost_equal
class TestLIME(unittest.TestCase):
def test_cv(self):
paddle_model = mobilenet_v2(pretrained=True)
img_path = 'imgs/catdog.jpg'
al... |
from flask import Flask
from .util import jinjasset
def create_app():
"""Construct the core application."""
app = Flask(__name__)
with app.app_context():
app.jinja_options['extensions'].append('jinja2.ext.debug')
app.jinja_options['extensions'].append('jinja2.ext.do')
app.jinja_en... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import subprocess
import oshelpers
import os
git = 'git'
empty_sha1 = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
# Returns the root dir for the Git repo
def get_root():
rev_parse = subprocess.Popen([git, 'rev-... |
import glob
import csv
# Python3.6 Standard Encodings
# (https://docs.python.org/3.6/library/codecs.html#standard-encodings)
# ascii big5 big5hkscs
# cp037 cp273 cp424 cp437 cp500 cp720 cp737 cp775cp850 cp852 cp855 cp856
# cp857 cp858 cp860 cp861 cp862 cp863cp864 cp865 cp866 cp869 cp874 cp875
# cp932 cp949 cp950 cp10... |
import random
import string
import os
import pwd
import random
BASE_DIR = 'uploads'
#USER = 'vagrant'
#USER_ID = pwd.getpwnam(USER).pw_uid
def gen_token(token_len):
#return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(token_len))
return str(random.randint(10000,99999))
de... |
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
with open('README.md', 'r') as fh:
long_description = fh.read()
setup(
name='y2j',
version='0.0.3',
author='Neal Ormsbee',
author_email='neal.ormsbee@g... |
# Generated by Django 3.1.2 on 2021-03-03 16:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('surveillance', '0005_aut... |
"""
Напишите программу, которая считывает с консоли числа (по одному в строке) до тех пор,
пока сумма введённых чисел не будет равна 0 и сразу после этого выводит сумму квадратов всех считанных чисел.
Гарантируется, что в какой-то момент сумма введённых чисел окажется равной 0,
после этого считывание продолжать не нуж... |
def areYouPlayingBanjo(name):
# Implement me!
if (name.startswith("R") |name.startswith("r") ):
return name + " "+"plays banjo"
else:
return name +" "+ "does not play banjo"
# return name
def areYouPlayingBanjo2(name):
return name + (' plays' if name[0].lower() == 'r' else ' does not... |
# Python 3.6.1
import re
import sys
from pdb import set_trace
"""
This version is significantly faster than p2_slow.py. I don't think you could
reasonably ever reach the answer for this using that one. Anyway, for this one,
I took an approach where I _calculate_ the 'position' of the scanner in the
current row. I th... |
from test.biota_models.coral.bio_process.bio_utils import (
coral_2x2,
matrix_1x1,
matrix_2x2,
valid_coral,
)
import pytest
from src.biota_models.coral.bio_process.temperature import Temperature
from src.biota_models.coral.model.coral_model import Coral
from src.core.common.space_time import DataResha... |
import os
import struct
from migen import *
from litex.soc.interconnect import wishbone
class MemoryMustHaveContents(Memory):
@staticmethod
def emit_verilog(memory, ns, add_data_file):
assert memory.init, "ROM contents not found! {}".format(memory.filename)
return Memory.emit_verilog(memory, ... |
import csv
import numpy as np
import os
import pandas as pd
import re
data_dir = 'data/'
missing = ['[removed]', '[deleted]']
## Remove 'edit:' or 'edit1:'
## strip jokes in the dataset class
# Weird unicode characters?
edits = ['edited to say', 'edit:', 'edit1:', 'credit:']
for name in ['train.tsv', 'dev.tsv', 't... |
from typing import List
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
import schemas, models, crud
from database import engine, SessionLocal
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
fina... |
"""
An implementation of the model described in [1].
[1] Eslami, SM Ali, et al. "Attend, infer, repeat: Fast scene
understanding with generative models." Advances in Neural Information
Processing Systems. 2016.
"""
from collections import namedtuple
import torch
import torch.nn as nn
import torch.nn.functional as F
... |
from core.symbols import Symbols
from core.errors import VersionError, CaculateError, PowerError, SymbolTypeError, SymbolNameError, EncryptError, CannotDecryptError, DecryptError
from sys import version_info
if version_info < (3, 6):
raise VersionError
del version_info
class Linear:
def __init__(... |
# Generated by Django 3.0.6 on 2020-05-22 00:29
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("teams", "0004_add_join_code")]
operations = [migrations.AlterUniqueTogether(n... |
array([[2.88738855, 0.72646774],
[3.16759122, 0.70478649],
[3.45517317, 0.69217863],
[3.75325158, 0.68581005],
[4.07281434, 0.68360819],
[4.50000223, 0.68376092],
[4.54999507, 0.68377879],
[5.11738115, 0.69080411],
[5.44798256, 0.7112322 ],
[5.71126558, 0.7... |
import numpy
import numba
print "IMPORTED NUMBA"
|
# -*- coding: utf-8 -*-
# File: rect.py
import numpy as np
from .develop import log_deprecated
__all__ = ['IntBox', 'FloatBox']
class BoxBase(object):
__slots__ = ['x1', 'y1', 'x2', 'y2']
def __init__(self, x1, y1, x2, y2):
log_deprecated("IntBox and FloatBox", "Please implement them by your own."... |
'''
- Leetcode problem: 5
- Difficulty: Medium
- Brief problem description:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"... |
from .exception import * # noqa: F401,F403
from .mixin import * # noqa: F401,F403
from .model import * # noqa: F401,F403
from .option import * # noqa: F401, F403
from .schema import * # noqa: F401,F403
__version__ = '0.1.0'
|
import os
name = 'swaglyrics'
__version__ = '1.1.2'
unsupported_txt = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'unsupported.txt')
backend_url = 'https://api.swaglyrics.dev'
class SameSongPlaying(Exception):
pass
|
import curses
from pmn.info_format import InfoFormat
from pmn.process_tree import ProcessTree
from pmn.size import Size, Method, Unit, Align
def colors():
curses.init_pair(1, 0, 231)
curses.init_pair(2, 231, 0)
curses.init_pair(3, 2, -1)
curses.init_pair(4, 2, 0)
def application_keymap(application)... |
"""An evaluator script for pre-trained policies."""
import os
import sys
import random
import numpy as np
import tensorflow as tf
from copy import deepcopy
from skvideo.io import FFmpegWriter
from hbaselines.algorithms import RLAlgorithm
from hbaselines.utils.eval import parse_options
from hbaselines.utils.eval import... |
# !/usr/bin/python3
varCondition = 0
if varCondition == 0:
pass
elif varCondition == 1:
pass
else:
pass
while varCondition < 3:
varCondition += 1
print("while loop condition=%d" % varCondition)
while varCondition < 5:
varCondition += 1
else:
print("while condition=%d" % varCondition)
for... |
from PyQt4 import QtCore
dPins = range(14)
aPins = range(18,24)
A0,A1,A2,A3,A4,A5 = aPins
HIGH,OUT = (1,1)
LOW,IN = (0,0)
class Driver():
def __init__(self,sim):
self.sim = sim
def pinMode(self,pin,mode):
self.sim.emit(QtCore.SIGNAL("sPinMode"),pin,mode)
def digitalRead(self,pin):
... |
import nltk
import logging
from pycorenlp import StanfordCoreNLP
import glob
import codecs
stopwords = ["all", "high", "left", "lower", "low", "right", "central", "severe", "mild", "large", "onset",
"bilateral", "multiple", "profound", "proximal", "distal", "foot", "long", "papules", "middle",
"position", "con... |
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import VTK_DOUBLE
from vtkmodules.vtkCommonDataModel import vt... |
# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtCore, QtWidgets, QtQuick
import custom_model
if __name__ == '__main__':
app = QtWidgets.QApplication( sys.argv )
view = QtQuick.QQuickView()#main_window.MainWindow()
my_model = custom_model.CustomModel()
view.rootContext().setContextProperty( '... |
import sys
import numpy as np
import matplotlib.pyplot as plt
from argparse import ArgumentParser
from conv_functions import hz2ct, ct2hz
def normalize(hz, fix):
if hz < -100:
return hz
v = np.power(np.e, hz)
v = hz2ct(v)
v = v + fix
v = ct2hz(v)
v = np.log(v)
return v
if __nam... |
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2011 by Tobias Heinzen
:license: BSD, see LICENSE for more details
"""
import os, os.path
from git import Repo, GitCommandError
from git.exc import BadObject
from pyggi.lib.repository import Repository, RepositoryError, EmptyRepositoryError
from pyggi.lib.config imp... |
from django.conf.urls import url
from django.urls import path
from .views import AdventCalendarView, AdventDoorView, QuizListView, QuizView, QuizResultView
from .views.quiz import quiz_reply, QuizScoreboardView, QuizResultDeleteView
from .views.user_test import test_result, TestView
from .views.advent import participat... |
import json
def parse_mfeprimer(jsoninfile):
with open(jsoninfile) as f:
mfepdata = json.load(f)
|
import logging
import logging.handlers
import argparse
import sys
import os
import time
import RPi.GPIO as gpio
from bluetooth.bluez import *
class LoggerHelper(object):
def __init__(self, logger, level):
self.logger = logger
self.level = level
def write(self, message):
if message.rst... |
"""
Prior Weights
=============
The priors on age, mass, and metallicty are computed as weights to use
in the posterior calculations.
"""
import numpy as np
from scipy.integrate import quad
from scipy.interpolate import interp1d
from beast.physicsmodel.grid_weights_stars import (
compute_bin_boundaries,
comput... |
from collections import defaultdict
from typing import List, Optional, Dict
import bpy
from ..source1.mdl.v49.mdl_file import Mdl as S1Mdl
from ..goldsrc.mdl_v10.mdl_file import Mdl as GMdl
from ..goldsrc.mdl_v4.mdl_file import Mdl as GMdlV4
from ..source2.resouce_types.valve_model import ValveCompiledModel
from ..sou... |
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
while 1 == 1:
list1 = []
file = open("Hours.txt", "a") # opens a file or if doesnt exists makes it.
file.write("--------------------------"+str(datetime.now())+"---------------------------------------------"+"... |
import numpy as np
import random
def vectorized_result(j):
e = np.zeros((2, 1))
e[j] = 1
return e
def load_data():
x = []
y = []
data = []
training_data = []
test_data = []
validation_data = []
with open('inp', 'r') as f:
data = []
for line in f:
arr = line.split()
if arr[1] == 'B':
... |
from inspect import isclass
from typing import Any
from tartiflette.schema.registry import SchemaRegistry
from tartiflette.types.exceptions.tartiflette import (
MissingImplementation,
UnknownScalarDefinition,
)
__all__ = ("Scalar",)
class Scalar:
"""
This decorator allows you to link a GraphQL Scala... |
"""Build decode graph
build decoder graph based on grammar WFST and
speller WFST using Compose algorithm
"""
import openfst_python as fst
from .grammar_builder import GrammarBuilder
from .lexicon_builder import LexiconBuilder
from .token_builder import TokenBuilder
from absl import logging
def remove_unk_arc(graph, ... |
import pytest
from datacatalog import githelpers
@pytest.mark.smoktest
def test_get_sha1():
githash = githelpers.get_sha1()
assert isinstance(githash, str)
assert len(githash) == 40
def test_get_sha1_short():
githash = githelpers.get_sha1_short()
assert isinstance(githash, str)
assert len(gith... |
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import json
class LoginException(Exception):
"""Could not login to twitter"""
pass
class Twitter:
def __init__(self, username, password):
self.username = username
self... |
# Copyright 2017 Prashant Singh, Fredrik Wrede and Andreas Hellander
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
"""
DRS Registration document resource package.
Copyright (c) 2018-2020 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
... |
# Source http://rischwa.net/coalitions/
# Input http://rischwa.net/api/coalitions/current
# Output meta."collation"
import sys
import requests
from _meta import *
from time import sleep
def main():
r = requests.get('http://rischwa.net/api/coalitions/current')
result = r.json()
result = result['... |
from src.model.StoriesModel import StoriesModel
class UserHighlightModel(StoriesModel):
def __init__(self, name):
self.stories = []
self.name = name
def getHighlightName(self):
return self.name
|
USER_AGENT = 'Mozilla/5.0 ()'
CONTENT_ENCODING = 'utf-8'
# {0} : tenant_code
# {1} : user_code
URL_TEMPLATES = {
'LoginPage': 'https://id.obc.jp/{0}',
'CheckAuthenticationMethod': 'https://id.obc.jp/{0}/login/CheckAuthenticationMethod',
'Authenticate': 'https://id.obc.jp/{0}/login/login/?Length=5',
'Pu... |
from sqlalchemy import create_engine
def initialize():
engine = create_engine('postgresql://postgres:postgres@db:5432/database')
return engine |
# Generated by Django 3.0.8 on 2020-07-18 16:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('network', '0002_blogpost'),
]
operations = [
migrations.RenameField(
model_name='blogpost',
old_name='blogposter',
... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: modify_library.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as... |
import numpy
def f(q, q_dot, xi):
l1, l2, l3 = q[0,0], q[1,0], q[2,0]
l1_dot, l2_dot, l3_dot = q_dot[0,0], q_dot[1,0], q_dot[2,0]
return 3.38058845865336e-11*l1**2 - 8.57996768441923e-11*l1*l2 + 1.77343591248946e-11*l1*l3 + 6.96600978936586e-14*l1 + 5.44544999423272e-11*l2**2 - 2.25334113136583e-11*l2*l3 -... |
"""
"""
def _helm(
command_ctx,
command,
args = [],
options = [],
inputs = []):
exec_file = command_ctx.actions.declare_file(command_ctx.label.name + "_helm_" + command)
# Generates the exec bash file with the provided substitutions
command_ctx.actions.write(
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys, timeit
import numpy as np
import matplotlib.pyplot as plt
from bmpProcessing.utils.Utils import get_int_from_bytes
class BmpProcessing:
'''
Implementation of an BMP format image
'''
def __init__(self, img, verbose):
'''
Initia... |
from __future__ import print_function
import fnmatch
import io
import os
import subprocess
import torch.distributed as dist
from tqdm import tqdm
def create_manifest(
data_path, output_path, min_duration=None, max_duration=None
):
file_paths = [
os.path.join(dirpath, f)
for dirpath, dirnames... |
import jax
import jax.nn
import jax.numpy as jnp
import numpy as np
from jax.lax import stop_gradient
import haiku as hk
from collections import deque
from typing import NamedTuple
import optax
import gym
from gym.wrappers import RecordEpisodeStatistics
import random
import os
from functools import partial
# tell JAX ... |
from collections import defaultdict
import rethinkdb as r
from flask import Flask, abort, g, jsonify, request
from .parse import build_engine, parse
from .respond import respond, respond_plastic
app = Flask(__name__)
@app.before_request
def before_request():
try:
g.rdb_conn = r.connect(host="localhost"... |
#!/usr/bin/env python3
import pathlib
from subprocess import Popen, PIPE
def main(model_data, model_output_dir):
for model_file in model_data:
mname = model_file.stem
output_file = str(model_output_dir / (mname + "_output.txt"))
error_file = str(model_output_dir / (mname + "_error.txt"))
... |
from decimal import Decimal
from typing import (
Any,
Dict,
Optional,
)
import asyncio
from hummingbot.core.event.events import (
OrderType,
TradeType
)
from hummingbot.connector.in_flight_order_base import InFlightOrderBase
s_decimal_0 = Decimal(0)
class GateIoInFlightOrder(InFlightOrderBase):
... |
# -*- coding: utf-8 -*-
"""
ZenMaxBuilder Copyright © 2021 darkmaster@grm34 https://github.com/grm34
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/l... |
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
from .a_div import ADiv
class AColumn(ADiv):
def __init__(self, size, *args, **kwargs):
self.attrs["class"] = "col s{}".format(size)
super().__init__(*args, **kwargs) |
import aiohttp
import time
import jwt
import pytest
import smarttub
ACCOUNT_ID = "account_id1"
pytestmark = pytest.mark.asyncio
@pytest.fixture(name="unauthenticated_api")
async def unauthenticated_api(aresponses):
async with aiohttp.ClientSession() as session:
yield smarttub.SmartTub(session)
@pyte... |
"""Product serializers."""
# Django REST Framework
from rest_framework import serializers
# Model
from vsbuy_backend.products.models.stores import Store
class StoreModelSerializer(serializers.ModelSerializer):
"""Store model serializer."""
class Meta:
"""Meta class."""
model = Store
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
import numpy as np
import random
def make_sample_her_experience(episode_batch, batch_size):
"""Creates a sample function that can be used for HER experience replay.
"""
def hash_memory(data):
achieved_hash = {}
desired_hash = {}
for idx in range(len(data)):
ac_x = data... |
import pytest
import sqlite3
import data_algebra
import data_algebra.SQLite
import data_algebra.test_util
from data_algebra.data_ops import *
from data_algebra.cdata import *
def test_extend_transform_1():
d = data_algebra.default_data_model.pd.DataFrame({"x": [1, 2]})
ops = describe_table(d, table_name="d"... |
# pylint: disable=E0401, E1101
"""
tests for the FlexCloud class
"""
import numpy as np
from nimrud.utils import point_clouds
SEED = 10
np.random.seed(SEED)
#---------------------------------------------------------------------------------------------------
def test_instantiation():
"""
test instantiation... |
import random
import time
SIMULATION_DELAY = 0.2
LATITUDE = 100
LONGITUDE = 100
MAX_VEL = 10
MAX_WAIT = 50
CANT_VEHICLES = 20
PLACE_PROB = 0.7
PLACES = ["Zoologico", "Shopping", "Plaza", "Museo", "Cine", "Teatro"]
OTHER_PLACE = "Otro"
CANT_PLACES = 50
class Vehicle:
def __init__(this, _id, ... |
class Calculator:
def __init__(self,num):
self.number = num
def Square(self):
print(f"The value of {self.number} square is {self.number ** 2}")
def Cube(self):
print(f"The value of {self.number} cube is {self.number**3}")
def SquareRoot(self):
print(f"... |
import sys
import os
import configparser
try:
configfile = os.path.join(os.path.dirname(__file__),"dmgui_au.conf")
configs = configparser.ConfigParser()
configs.read_file(open(configfile))
configs.read(configfile)
top_dir = configs['PathNames']['top_dir']
pkg_dir = configs['PathNames']['pkg_dir... |
# -*- coding: utf-8 -*-
"""
A unified logger for all the modules in the project
The Root logger is a singleton one, which is efficient and
won't instatiate the logger for each module conveniently
"""
import logging
from sys import stdout
logger = logging
# Define the logging configuration and different formats
# F... |
#program to find the first appearance of the substring 'not' and 'poor' from a given string, if 'bad'
# follows the 'poor', replace the whole 'not'...'poor' substring with 'good'.
# Return the resulting string.
def not_poor(str1):
snot = str1.find('not')
spoor = str1.find('poor')
if spoor > snot and snot>0 ... |
from app import App
import requests
import json
import polling2
from behave import step
from util import substitute_scenario_id
from string import Template
class GenericTestApp(App):
deployment_name_pattern = "{name}"
def __init__(self, name, namespace, app_image="ghcr.io/servicebindings/generic-test-app"):... |
from . import app
from . import routes
|
from django.shortcuts import render, redirect
from .models import User
import hashlib
import re
def login_required(func):
def inner(*args, **kwargs):
if 'user_id' in args[0].session:
return func(*args, **kwargs)
else:
return redirect('/login')
return inner
def index_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This code contains several versions of evaluation functions
"""
import numpy as np
from LSTM_models import LSTM_model_stance, LSTM_model_veracity
# from LSTM_models import build_LSTM_model_veracity
# from rmse import rmse
import os
from keras.preprocessing.sequence im... |
"""
Interactive kinetics app with sliders (with units).
Start by runing:
$ bokeh serve interactive.py
Add --show argument or navigate to:
http://localhost:5006/interactive
"""
from collections import defaultdict
import sys
from chempy.util.bkh import integration_with_sliders
from chempy.units import SI_base_re... |
from owlready2 import *
from ontology import *
s2022 = Season("2022")
s2021 = Season("2021")
s2020 = Season("2020")
s2019 = Season("2019")
s2018 = Season("2018")
s2017 = Season("2017")
s2016 = Season("2016")
s2015 = Season("2015")
s2014 = Season("2014")
s2013 = Season("2013")
s2012 = Season("2012")
s2011 = Season("201... |
from django.http import HttpResponse, HttpRequest
from axes.middleware import AxesMiddleware
from axes.tests.base import AxesTestCase
class MiddlewareTestCase(AxesTestCase):
STATUS_SUCCESS = 200
STATUS_LOCKOUT = 403
def setUp(self):
self.request = HttpRequest()
def test_success_response(sel... |
from Swift_serial.Swift_serial import Swift_serial
__all__ = [
'Swift_serial'
]
|
import sys
import tensorflow as tf
import numpy as np
from PIL import Image
from object_detection import ObjectDetection
MODEL_FILENAME = 'yoshi_top_secret/model.pb'
LABELS_FILENAME = 'yoshi_top_secret/labels.txt'
class TFObjectDetection(ObjectDetection):
"""Object Detection class for TensorFlow"""
... |
#!/usr/bin/env python
import sys
class Connect(object):
def __init__(self):
print("connect called.")
if __name__ == "__main__":
c = Connect()
|
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from __future__ import print_function
import base64
import json
import os
import re
from typing import Dict, List, Tuple
# ... |
from typing import List
from tensorflow import keras
from tfaip import DataGeneratorParams
from tfaip.data.pipeline.definitions import PipelineMode
from tfaip.data.pipeline.processor.dataprocessor import SequenceProcessorParams
from tfaip.data.pipeline.processor.params import SequentialProcessorPipelineParams
from tf... |
import sys
import codecs
from .exceptions import InvalidCommand
from .plugin import PluginDict
from .action import PythonAction
from .task import Stream
from .control import TaskControl
from .runner import Runner, MRunner, MThreadRunner
from .cmd_base import DoitCmdBase
from . import reporter
# verbosity
opt_verbosi... |
import types
from unittest.mock import Mock
import pytest
from bson import ObjectId
from mongonator import Paginate
from mongonator.paginator import PaginatedResponse
@pytest.fixture
def mongo_collection():
yield Mock()
def test_paginate_one_batch(mongo_collection):
mongo_collection.find.return_value.sort... |
from dbt.logger import GLOBAL_LOGGER as logger, log_cache_events, log_manager
import argparse
import os.path
import sys
import traceback
from contextlib import contextmanager
import dbt.version
from dbt.profiler import profiler
from dbt.adapters.factory import reset_adapters, cleanup_connections
import dbt.tracking
... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
from ipykernel.kernelbase import Kernel
import subprocess
import random
import os
import string
def randomword(length):
return ''.join(random.choice(string.ascii_lowercase) for i in range(length))
class KerneliX86(Kernel):
implementation = 'iX86'
implementation_version = '1.0'
language = 'no-op'
la... |
"""
Implements mi-SVM and MI-SVM
"""
from __future__ import print_function, division
import numpy as np
from random import uniform
from cvxopt import matrix as cvxmat, sparse
import inspect
from misvm.sil import SIL
from misvm.svm import SVM
from misvm.cccp import CCCP
from misvm.quadprog import IterativeQP, spzeros, s... |
from ...models import driver, user
from ...models.user import users
from ...models.driver import drivers
from werkzeug.security import check_password_hash
from flask import request, jsonify
import json
from utils import JSON_MIME_TYPE, json_response
def login():
""" Controlls user log in """
if not request.j... |
from connectors import apicem
import concurrent.futures
def main(parameters):
'''Gets the licenses for our network devices'''
text = 'Right now, I found these licenses:\n'
devices = apicem.get_network_device()
pool = concurrent.futures.ThreadPoolExecutor(max_workers=40)
futures = [pool.submit(ap... |
'''Uma empresa de cartão de crédito envia suas faturas por email com a seguinte mensagem:
Olá, Fulano de Tal
A sua fatura com vencimento em 9 de Janeiro no valor de R$ 350,00 está fechada.
Escreva um programa que receba (entrada de dados através do teclado) o nome do cliente, o dia de vencimento, o mês de vencimento e... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protobufs/services/post/containers.proto
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflectio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.