content stringlengths 5 1.05M |
|---|
# pylint: disable=C0103, R0902
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#
#modification, are permitted provided that the fol... |
# Python program to convert
# CSV to HTML Table
import pandas as pd
# to read csv file named "cities"
a = pd.read_csv("cities.csv")
# to save as html file
# named as "Table"
a.to_html("Table.html")
# assign it to a
# variable (string)
data_table = a.to_html()
|
from __future__ import absolute_import
import tensorflow as tf
import numpy as np
#
# Constant values
#
THETA = [0.0]
def _nan2inf(x):
return tf.where(tf.is_nan(x), tf.zeros_like(x)+np.inf, x)
class NB(object):
def __init__(self, theta=None, scope='nbinom_loss/', scale_factor=1.0,
debug=F... |
import pytest # type: ignore
from hopeit.app.config import AppConfig
from hopeit.server.engine import Server, AppEngine
from mock_app import mock_app_config # type: ignore # noqa: F401
from mock_plugin import mock_plugin_config # type: ignore # noqa: F401
from mock_engine import MockAppEngine
async def start_s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""Scikit learn interface for :class:`~gensim.models.doc2vec.Doc2Vec`.
Follows scikit-learn API conventions to facilitate using gensim ... |
#!python3
import os
import urllib
import webbrowser
import ui
from blackmamba.log import error
def script_exists(script_name, full_path=False):
if not full_path:
script_name = os.path.join(os.path.expanduser('~/Documents'), script_name)
return os.path.exists(script_name)
def run_script(script_name,... |
#-------------------------------------------------------------------------------
# Name: TicTacToe
# Purpose: A game of TicTacToe
# Version: 1.0
#
# Author: Bulut Ozturk < firstname dot lastname at gmail dot com >
#
# Created: 02/10/2014
#-------------------------------------------------... |
"""
Misc.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on: Sun Oct 19 19:50:31 MDT 2014
Description:
"""
import os
import subprocess
import numpy as np
from ..data import ARES
try:
# this runs with no issues in python 2 but raises error in python 3
basestring
except:
... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import functools
import itertools
import json
import logging
import os
import subprocess
import sys
import time
from pathlib import Path
from ty... |
from datetime import datetime
from django.conf import settings
from django.db import models
from autoslug import AutoSlugField
from puzzles.slugtools import puzzle_to_slug
from model_utils import FieldTracker
# **optional shortcut for optional fields
optional = {
'blank': True,
'null': True
}
# A mixin clas... |
from python_framework import HttpClient, HttpClientMethod
from config import AixSportsConfig, BrowserConfig
@HttpClient(
url = AixSportsConfig.BASE_URL
)
class AixSportsClient :
@HttpClientMethod(
url = AixSportsConfig.CHAMPIONSHIP_URL,
headers = {
'authority': AixSportsConfig.AUTH... |
from __future__ import division, print_function
import ntpath
import numpy.linalg as npl
import numpy as np
import sklearn
from scipy.sparse.csgraph import shortest_path
import sys
from scipy.stats import spearmanr, pearsonr
from sklearn.metrics import euclidean_distances
def contacts2distances(contacts):
""" I... |
import random,itertools,time,math
from random import randint
# The Driver function to this module
def pso(sequences,l,d) :
cp=list(sequences)
print "\t\t----PSO Initialising----"
numIteration=200
pop=30
gBest=[0 for i in range(len(cp)+1)]
# Randomly initialising the initial Population
initialPopulation=matrixGe... |
import json
import Database
from flask import Flask, request
from threading import Thread
app = Flask(__name__)
db = Database.Database('locked-assets')
@app.route('/get-locked-assets', methods=['GET'])
def get_locked_assets():
locked_assets = db.get_locked_assets()
ret = []
for asset in locked_assets:
... |
#!/usr/bin/env python3
from subprocess import run
from sys import argv, exit
PYVER = argv[1]
IMAGE = f"ruterstop:python{PYVER}"
print("Building", IMAGE)
run(
[
"docker",
"build",
"--network=host",
"--file=.deploy/Dockerfile",
f"--build-arg=PYTHON_VERSION={PYVER}",
f... |
import structlog
from raiden.messages import (
message_from_sendevent,
Lock,
)
from raiden.transfer.architecture import Event
from raiden.transfer.events import (
ContractSendSecretReveal,
ContractSendChannelClose,
ContractSendChannelSettle,
ContractSendChannelUpdateTransfer,
ContractSendCh... |
"""
File used to modelize GAN for phishing detection
-----------
Generative Adversarial Networks (GAN) research applied to the phishing detection.
University of Gloucestershire
Author : Pierrick ROBIC--BUTEZ
2019
Copyright (c) 2019 Khuzd
"""
# ---------------------
# Define different seeds to permit repeatability
# -... |
__author__ = "Fengming Liu"
__status__ = "prototype"
import emoji
import json
import nltk
import os
import re
import shutil
import string
import subprocess
import urllib3
def create_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
return dir
def nlp_process(text):
text = re.sub(pattern=re.compile(r'RT @(.... |
from vht import vht_core
from vht import vht_utils
import logging
import os
import sys
# Logging
verbosity = 'INFO'
level = { "DEBUG": 10, "INFO": 20, "WARNING" : 30, "ERROR" : 40 }
logging.basicConfig(format='[%(levelname)s]\t%(message)s', level = verbosity)
logging.debug("Verbosity level is set to " + verbosity)
# ... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: faro/proto/face_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
f... |
# setup file for building with distutils.
#
# Eli Bendersky [http://eli.thegreenplace.net]
# This code is in the public domain.
from distutils.core import setup, Extension
module1 = Extension('spam', sources = ['spammodule.c'])
setup (name = 'PackageName',
version = '1.0',
description = 'This is a dem... |
"""
Module containing helper functions that can be used in general
throughout tests
"""
import asyncio
import sys
PY_VERSION = sys.version_info
PY_VERSION_TO_CHECK = (3, 8)
def check_py_version(version_to_check):
"""
Tests environment's python version vs. a threshold version
"""
is_older = False
... |
from .conversion import *
from .load_database import *
__all__ = [
"join_with_emd",
"join_with_h3",
"join_with_table",
"shp_init",
"load_tables",
]
|
from .bundletypes import Coords, Tracks, Listfile, Rotfile, Bundle
from .sfminittypes import (read_rot_file, write_rot_file,
read_trans_soln_file, write_trans_soln_file,
read_edge_weight_file, write_edge_weight_file,
read_EGs_file, ... |
import socket
from flask import request
from flask import current_app
from flask_restful import Resource
from flask_restful_swagger import swagger
from cloudify.cluster_status import ServiceStatus, NodeServiceStatus
from cloudify._compat import httplib, xmlrpclib
from manager_rest import config
from manager_rest.res... |
"""
Implementation of textX language in Arpeggio.
The idea for this language is shamelessly stolen from the Xtext language but
there are some differences in both syntax and semantics. To make things clear I
have named this language textX ;)
"""
from __future__ import unicode_literals
import re
from arpeggio import St... |
__author__ = 'Pontus'
|
import unittest
import numpy
import numpy.linalg
from numpy.testing import assert_array_almost_equal
import theano
from theano import tensor, function
from theano.tensor.basic import _allclose
from theano.tests.test_rop import break_op
from theano.tests import unittest_tools as utt
from theano import config
# The on... |
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import plotly.graph_objects as go
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Contestant": ["Alex", "Alex", "Alex", "Jordan", "Jord... |
import ring
import pytest
from .test_func_sync import pythonmemcache_client
__all__ = ('pythonmemcache_client', )
class hybridmethod(object):
def __init__(self, func):
self.__func__ = func
def __get__(self, obj, type=None):
bound = obj if obj is not None else type
return self.__fun... |
# -*- coding: utf-8 -*-
_CAT_TREE_ID_ROUTE = "commerce/taxonomy/v1_beta/get_default_category_tree_id"
_CAT_TREE_ROUTE = "commerce/taxonomy/v1_beta/category_tree"
def get_macro_categories(credentials, marketplace):
"""
Retrieve top-level category names and IDs for the given eBay marketplace.
See: https://d... |
# Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)
#
# 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
#
# Unle... |
#!/usr/bin/env python3
#import ipdb
#ipdb.set_trace()
import configparser
import os, sys
import numpy as np
from matplotlib import pyplot as plt
import xarray as xr
thisDir = os.path.dirname(os.path.abspath(__file__))
parentDir = os.path.dirname(thisDir)
sys.path.insert(0,parentDir)
from pyCRTM import pyCRTM, profiles... |
for i in range(1000,10000): # i represent range between 1,000 and 10,000
if (i % 6 == 0) and not(i % 12 == 0): #if statments, with two conditions one is positive and the other is negative, which means that the number is divisible by first condition but not by the second one. Thats why I included "not" before rounde... |
from database.database import NichijouDatabase
NichijouDatabase()
|
from fastapi import FastAPI
from ginza.analyzer import Analyzer
# https://github.com/tiangolo/fastapi/issues/1663#issuecomment-906817935
# from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
import time
import threading
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
from setuptools import find_packages, setup
# Package meta-data.
NAME = 'cpython_assembly'
DESCRIPTION = 'An assembler for CPython bytecode into python functions'
URL = 'https://github.com/appelte1/cpython_assembly'
EMAIL = 'eric.appelt@gmail.com'
AUT... |
import numpy as np
from scipy import misc
from fibmeasure import measure
def print_result(result, ref):
"""A little function to neatly print measurement results"""
print("Estimated fibre centre: (%.3f, %.3f) wrt refPoint\n"\
" (%.3f, %.3f) absolute"
% (result[0], r... |
from django.db import models
from zendesk.models import Organisation
from products.models import Product
from timeline.models import Timeline
# Create your models here.
class AccountInformation(models.Model):
"""
Table: Account Information
Comment: The place to store all the Account Information
"""
... |
"""
The .csv preperation functions for WSJ0-Mix.
Author
* Cem Subakan 2020
"""
import os
import csv
def prepare_cs21(
train_path,
dev_simu_path,
dev_real_path,
eval_path,
savepath,
sources=["mix","noise","reverb","clean"],
skip_prep=False,
librimix_addnoise=False,
fs=16000,
):
... |
import psycopg2
import json
import random
# connects to use the psycopg2 module
conn = psycopg2.connect(
database='prepear',
user='gracewgao',
host='localhost',
port=26257
)
conn.set_session(autocommit=True)
cur = conn.cursor()
def setup_db():
cur.execute("CREATE TABLE IF NOT EXISTS users (id S... |
from .fid_evaluator import FIDEvaluator
from .fid_lerp_evaluator import FIDLerpEvaluator
from .knn_evaluator import KNNEvaluator
from .mean_fid_evaluator import MeanFIDEvaluator
from .reconstruction_evaluator import ReconstructionEvaluator
|
from ibmcloudant.cloudant_v1 import CloudantV1, Document
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
CLOUDANT_URL="https://apikey-v2-1mfs4kqo2nmnc2sdtgp9ji8myznbgm6mivk0o93pfopt:f70c9a73c52d287d3271ddc3dba6a30a@dc1a5ff5-996b-475c-8b7e-da87f4bf33a3-bluemix.cloudantnosqldb.appdomain.cloud"
CLOUDANT_AP... |
from __future__ import print_function
import scipy.io as sio
from shutil import copyfile
import os
import urllib
import tarfile
import numpy as np
from collections import defaultdict
from collections import namedtuple
from PIL import Image
import matplotlib.image as mpimg
import random
BoundingBox = namedtuple('Bound... |
import pygame
class _NoneSound(object):
def play(self):
pass
class Loader(object):
@staticmethod
def load_pixmap(filename):
try:
image = pygame.image.load(filename).convert()
except pygame.error as e:
raise SystemExit
return image
@staticmethod
def load_masked_pixmap(filename):
image = loa... |
class Parser:
def __init__(self, builtins):
self.builtins = builtins
def parse(self):
pass
def get_parser(self):
pass
|
"""
Auto-generate Fabric tasks for :term:`environments<environment>`.
The :func:`generate_tasks` function creates Fabric tasks to set the current
environment definition and is intended to be used as a setup step to other
standard Confab tasks (e.g. pull) to customize configuration data::
fab dev:web,queue push
"... |
"""
A word replacer to make a dumb sentence sound verysmart.
Leonardo Martinho
2017
"""
import API
import argparse
import re
from nltk import pos_tag
import sys
from pathlib2 import Path
def sanitize_for_url(word):
"""
Sanitizing of a word with a regex search string - everything that is not alphanumeric, a space or ... |
[
{
'date': '2017-01-01',
'description': 'Año Nuevo',
'locale': 'es-CO',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2017-01-09',
'description': 'Día de los Reyes Magos',
'locale': 'es-CO',
'notes': '',
'region... |
"""Weighted white kernel for scikit-learn Gaussian process.
"""
from setuptools import setup, find_packages
from os import path
import dtolpin.gaussian_process
# Get the long description from the README file
here = path.abspath(path.dirname(__file__))
with open(path.join(here, "README.md")) as f:
long_description... |
import logging
import os
import uuid
from pkg_resources import working_set
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
logger = logging.getLogger(_... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# redis_delete.py
#
# Jul/31/2017
#
import sys
#
import redis
#
# ------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
key_in = sys.argv[1]
print ("%s" % key_in)
#
rr = redis.Redis(host='localhost', port=6379, db=0)
#
str_key =... |
'''
markov_run.py
The Statistical language model, using markov chain
to generate new sentences based on data of quotes
@author: Yuting, PJ, and Minh
@date: 05/14/2021
'''
import random
import re
import sys
import statistics
class SLM:
"""
Class SLM represents an statistical language model
"""
... |
# -*- coding: utf-8 -*-
#
# escpos/impl/unknown.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
# Hybrid OBELISK model trained using pytorch v0.4.1 with TCIA data
# model contains two obelisk layers combined with traditional CNNs
# the layers have 512 and 128 trainable offsets and 230k trainable wei... |
import numpy as np
import matplotlib
matplotlib.rcParams['text.usetex'] = True
import matplotlib.pyplot as plt
fig = plt.figure()
#### BASIC ####
"""
x = 0
y = 0
z = 0
u = 0
v = 2
w = 5
"""
x = [0,0,0] # start x1 x2 x3
y = [0,0,0] # start y1 y2 y3
z = [0,0,0] # start z1 z2 z3
###### <0,2,3> <3,1,-2> <3,-2,1> ######
... |
import factory
from factory.declarations import SubFactory
from publication.models import Post, Topic
from .users import UserFactory
class TopicFactory(factory.django.DjangoModelFactory):
name = factory.Faker("name")
class Meta:
model = Topic
class PostFactory(factory.django.DjangoModelFactory):
... |
#!/usr/bin/env python3
import os
import psutil
from psutil._common import bytes2human
import iterm2
# Icons are base64-encoded PNGs. The first one is 32x34 and is used for Retina
# displays. The second is 16x32 and is used for non-Retina displays.
ICON1X = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA90lEQVQ4ja3R... |
from pyramid.security import (
Allow,
Authenticated,
ALL_PERMISSIONS,
Everyone,
Deny
)
from .init_db import Base, BaseExport, dbConfig, get_redis_con
from .base_model import *
from .base_view import *
from .base_resource import *
from .configuration_model import *
class SecurityRoot(Resource):
... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.front.common.partial_infer.utils import int64_array
from openvino.tools.mo.ops.gather import AttributedGather
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.front.onnx.extract... |
import FWCore.ParameterSet.Config as cms
horeco = cms.EDProducer("HcalSimpleReconstructor",
correctionPhaseNS = cms.double(13.0),
digiLabel = cms.InputTag("hcalDigis"),
Subdetector = cms.string('HO'),
correctForPhaseContainment = cms.bool(True),
correctForTimeslew = cms.bool(True),
dropZSmarked... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
from monorail_api import IssueTrackerAPI
from common import monitoring
from gae_libs import appengine_util
from gae_libs.handlers.base_handl... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import unittest
import serial
term = serial.Serial(os.environ.get("TTGOTERM", "/dev/ttyUSB0"), baudrate=int(os.environ.get("TTGOTERM_SPEED", 115200)), timeout=3.0)
def rd():
return term.read(1)
def wr(s):
term.write(s)
def strw(s, x, y, c):
... |
from github.scaffold import Scaffold
from github.types import Response
class IsUserBlocked(Scaffold):
"""
Check if a user is blocked by the authenticated user
"""
def is_user_blocked(
self,
*,
username: str,
) -> 'Response':
"""
Check if a user ... |
#!/usr/bin/env ipy
##############################################################################
# Written by: Calen Chen <cachen@novell.com>
# Date: 03/11/2008
# Description: This is a test application sample for winforms control:
# ToolStripDropDown
# ToolStripButton
##############... |
import os
import socket
import _bjoern
_default_instance = None
DEFAULT_LISTEN_BACKLOG = 1024
def bind_and_listen(host, port=None, reuse_port=False,
listen_backlog=DEFAULT_LISTEN_BACKLOG):
if host.startswith("unix:@"):
# Abstract UNIX socket: "unix:@foobar"
sock = socket.sock... |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
import pytorch3d.pathtracer as pt
from pytorch3d.pathtracer.bsdf import (
Diffuse, ComposeSpatialVarying, Phong, Plastic, NeuralBSDF, Conductor,
)
from pytorch3d.pathtracer.integrators impo... |
# -*- coding: utf-8 -*-
# This is a management command, rather than a migration script, for two primary reasons:
# 1. It makes no changes to database structure (e.g. AlterField), only database content.
# 2. It may need to be ran more than once, as it skips failed registrations.
from __future__ import unicode_liter... |
#!/usr/bin/env python3
import uuid
import pygsti
import pygsti.construction as pc
from pygsti.tools import timed_block
def main():
gates = ['Gi','Gx','Gy']
fiducials = pc.gatestring_list([ (), ('Gx',), ('Gy',), ('Gx','Gx'), ('Gx','Gx','Gx'), ('Gy','Gy','Gy') ]) # fiducials for 1Q MUB
germs = pc.gatestrin... |
from __future__ import absolute_import
from bokeh.models.annotations import Legend, BoxAnnotation
from bokeh.enums import (
NamedColor as Color, LineJoin, LineCap, FontStyle, TextAlign,
TextBaseline)
FILL = ["fill_color", "fill_alpha"]
BACKGROUND = ['background_fill_color', 'background_fill_alpha']
BORDER = ... |
import os
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from PIL import Image
def process(img):
# w = img.size[0]
# h = img.size[1]
# print(' From image file {}'.format(img))
img = np.asarray(img)
w = np.size(img, 1)
h = np.size(img, 0)
# print(img.... |
import argparse
import numpy as np
import sys
from collections import Counter
from scipy.sparse import csr_matrix, lil_matrix, vstack
from scipy.stats import gamma
# Read in vocabulary from file.
def get_vocab(vocab_fn, ignore_case):
vocab = []
vocab_index = {}
for i, line in enumerate(open(vocab_fn, mod... |
from bs4 import BeautifulSoup
import requests as req
from utils import (
exception, _response
)
from flask import jsonify
from api.entities.phim_response import PhimFetch
PHIMMOI_URL = "http://www.phimmoizz.net/"
PHIM_LE = 'phim-le/'
PAGE = 'page-'
# http://www.phimmoizz.net/phim-le/page-3.html
def fetch_phim... |
from toee import *
def OnBeginSpellCast(spell):
print "Storm of Elemental Fury OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
def OnSpellEffect(spell):
print "Storm of Elemental Fury OnSpellEffect"
targets... |
import requests
import json
import base64
import time
def register(user, password):
url = "http://127.0.0.1:5000/register"
aDict = {}
aDict["name"]= user
aDict["password"]= password
payload = json.dumps(aDict)
headers = {'content-type': "application/json"}
response = requests.request("POST"... |
import datetime
import logging
import torch
import torch.nn as nn
import torch.utils.data
class BertTrain:
"""
Trains on GPU / CPU
"""
def __init__(self, model_dir, scorers, use_loss_eval=False, device=None, epochs=10, early_stopping_patience=20,
checkpoint_frequency=1, checkpoint_d... |
#!/usr/bin/env python
class dbsListPrimaryDatasetTypes:
def __init__(self, typename, schemaowner):
if (typename.find("%")==-1 and typename.find("_")==-1): cond="="
else: cond="like"
self.sql = """
SELECT PT.PRIMARY_DS_TYPE_ID, PT.PRIMARY_DS_TYPE
FROM %sPRIMARY_DS_TYPES PT
WHERE PT.PRIMARY_DS_TYPE %s :primdst... |
# Copyright 2019 Nir Magnezi
#
# 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 agreed... |
from __future__ import annotations
from http import HTTPStatus
from typing import Mapping, Optional
from .responses import JSONResponse, Response
class SoieException(Exception):
"""Base Error"""
pass
class HTTPException(SoieException):
def __init__(
self,
status_code: int = 400,
... |
import sys, os, re
import pprint
sys.path.append("../src")
import pronlex
import phonecodes
from sentences import sents
"""This script should be run from the command line, in the test directory.
It will load some pronlexes from the 'fixtures' subdirectory,
test phone code conversion, and test both wor... |
# Generated by Django 3.1.6 on 2021-04-12 15:07
from django.db import migrations, models
def prepare_constraint_on_existing(apps, schema_editor):
FlexibleReport = apps.get_model('logs', 'FlexibleReport')
FlexibleReport.objects.filter(owner__isnull=False, owner_organization__isnull=False).update(
owne... |
"""
Signal Retriever
This is required to migrate from Monitor 1 to Monitor 2.
Scans Monitor-1 style signal raw file (one file a day) and generate a
ten-seconds .wav file.
BSD 2-Clause License
Copyright (c) 2017, Atsushi Yokoyama, Firmlogics (yokoyama@flogics.com)
All rights reserved.
Redistribution and use in sourc... |
import json
import yaml
import os.path
import aiofiles
class Dumper(yaml.Dumper):
def increase_indent(self, flow=False, indentless=False):
return super(Dumper, self).increase_indent(flow, False)
dumps = lambda x: yaml.dump(x, Dumper=Dumper, default_flow_style=False)
class Config:
def __init__(self, f... |
import functools
import numpy as np
import six
import multiworm
from multiworm.readers import blob as blob_reader
__author__ = 'peterwinter'
def find_nearest_index(seq, value):
return (np.abs(np.array(seq)-value)).argmin()
def frame_parser(blob_lines, frame):
"""
A lighter, probably quicker, parser to... |
from abc import ABC, abstractmethod
from typing import Tuple
class Corrector(ABC):
"""Abstract Corrector to be inherited by developer for any new corrector."""
@abstractmethod
def correction_step(self) -> Tuple:
pass
@abstractmethod
def _assign_states(self):
pass
|
# import mysql.connector
import re
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import euclidean_distances
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import pandas as pd
from pyemd import emd
import csv
import os
import gensim
from nltk... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_package(host):
p = host.package('frontier-squid')
assert p.is_installed
def test_hosts_service(host):
s = host.ser... |
import cv2
import os
import sys
from time import time, sleep
from datetime import datetime
import argparse
from imutils.video import FPS
import utils
from threading import Thread
from queue import Queue
from detector.ssd.ssd import SSDObjectDetector
from detector.yolo.yolo import YoloObjectDetector
def get_obj_detect... |
from base.base_net import BaseNet
from net_structures.FNN import AdaptiveFNN
from configs.net_config import MnistConfigBase
class MnistNet(MnistConfigBase, BaseNet):
def __init__(self):
super(MnistNet, self).__init__()
self.net_structure = AdaptiveFNN(num_in=self.n_in, num_out=self.n_out)
... |
'''
Module used to wrap various versions of the GDS API (previously GSE API).
These wrappers provide a common interface to the GDS API, buffering changes
and preventing upstream failures.
Created on Aug 28, 2018
@author: mstarch
'''
import copy
import fprime.gse.utils.gse_api
class GdsApiWrapper(object):
'''
... |
from __future__ import print_function
from costar_task_plan.abstract import AbstractOption
from .arm_policies import CostarArmMotionPolicy
class MotionOption(AbstractOption):
'''
This option calls out to the current segmenter and waits until termination.
'''
def __init__(self, world, goal, pose, pos... |
"""
Controller file for the web application.
The central file of the application.
"""
from flask import Flask
from flask import render_template
from flask import request
import sys
sys.path.insert(0, r'C:\Users\LSchw\Documents\benjamin\spiced_projects\final_project\EM_twitter_check')
import get_tweets_elon
from get... |
import datetime
import click
from socialcrawler.crawlers import UserCrawler, UserTweetCrawler
from socialcrawler.models import TwitterUser
from socialcrawler.queries import get_rows
from socialcrawler.utils import init_twitter_api, connect_db, get_accounts
@click.group()
def cli():
pass
@cli.command()
@click.... |
from aiortc import MediaStreamTrack, RTCPeerConnection, RTCSessionDescription
from av import VideoFrame
from .utils import logger
from . import transforms
import asyncio
import uuid
pcs = set()
class VideoTransformTrack(MediaStreamTrack):
"""
A video stream track that transforms frames from an another trac... |
class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
ans = 0
for i, ticket in enumerate(tickets):
if i <= k:
ans += min(ticket, tickets[k])
else:
ans += min(ticket, tickets[k] - 1)
return ans
|
#
# Copyright (c) 2022 TUM Department of Electrical and Computer Engineering.
#
# This file is part of MLonMCU.
# See https://github.com/tum-ei-eda/mlonmcu.git for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m... |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
DEMO_B64_SCRIPT = """
global:
environ:
PATH: /root:${PATH}
INPUT: 2 3
use_sys_env:
- PATH
tasks:
run_python:
sections:
- name: get_test_info
inputs:
- "copy:test_script.py:test_script.py"
outputs:
- "tag:wc_result.txt:wc"
- "tag:input_result.txt:... |
#!/usr/bin/env python
# @file
# @section COPYRIGHT
# Copyright (C) 2018 Consequential Robotics (CqR)
#
# @section AUTHOR
# Consequential Robotics http://consequentialrobotics.com
#
# @section LICENSE
# For a full copy of the license agreement, see LICENSE.MDK in
# the MDK root directory.
#
# Subject to the terms of ... |
import cffi
ffi = cffi.FFI()
ffi.embedding_api("""
int add(int, int);
""")
ffi.embedding_init_code("""
from _embedding_cffi import ffi
print("preparing") # printed once
@ffi.def_extern()
def add(x, y):
print("adding %d and %d" % (x, y))
return x + y
""")
ffi.set_source("_embed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.