content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import numpy as np
import time
import torch
from torch.autograd import Variable
def get_proc_memory_info():
try:
import os, psutil, subprocess
process = psutil.Process(os.getpid())
percentage = process.memory_percent()
memory = process.memory_info()[0] / float(2 ** 30)
retu... | python |
#! /usr/bin/env python
import rospy, sys, math, time
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
# CONSTANTS
NODE_NAME = "turntoN"
VEL_TOPIC = "turtle1/cmd_vel"
POSE_TOPIC = "turtle1/pose"
DTRF = math.pi / 180 # Degrees to Radians Conversion Factor
# GLOBALS
vel_pub = None
pose_sub = None
cpo... | python |
import streamlit as st
import pandas as pd
@st.cache
def get_data():
return(pd.read_csv('https://raw.githubusercontent.com/SaskOpenData/covid19-sask/master/data/cases-sk.csv'))
st.header('Covid in Saskatchewan')
st.write(get_data())
| python |
# -*- coding: utf-8 -*-
# @Date : Sun Mar 18 20:24:37 2018
# @Author: Shaoze LUO
# @Notes : Affinity Propagation
import numpy as np
def ap(s, iters=100):
a = np.zeros_like(s)
r = np.zeros_like(s)
rows = s.shape[0]
for _ in range(iters):
tmp_as = a + s
max_tmp_as = np.tile(tmp_as.max(1... | python |
import datetime
def string_to_datetime(st):
return datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S")
def datetime_to_datestr(st):
return st.strftime("%Y-%m-%d")
def datetime_to_string(st):
return st.strftime("%Y-%m-%d %H:%M:%S")
def transfer2time(it):
return datetime.time().replace(hour=it[0],... | python |
import metronome_loop
def five_sec_prin():
print("five_sec")
one_sec = metronome_loop.metronome(1000, lambda: print("one_sec"))
five_sec = metronome_loop.metronome(5000, five_sec_prin)
ten_sec = metronome_loop.metronome(10000)
while True:
one_sec.loop()
five_sec.loop()
if ten_sec.loop():
... | python |
# coding: utf-8
import sys
import logging
# {{ cookiecutter.project_name }} Modules
from {{cookiecutter.project_slug}}._{{cookiecutter.project_slug}} import MyPublicClass
log = logging.getLogger(__name__)
def main() -> int:
return MyPublicClass().run()
if __name__ == '__main__':
sys.exit(main())
| python |
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from __future__ import print_function
import os, sys, re
from os.path import join as jp
here = os.path.abspath(os.path.dirname(__file__))
sys.path.extend([jp(here, '../../..'), jp(... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: i2cy(i2cy@outlook.com)
# Filename: i2cydbclient
# Created on: 2021/5/29
import json
from i2cylib.database.I2DB.i2cydbserver import ModLogger
from i2cylib.utils.logger import *
from i2cylib.utils.stdout import *
from i2cylib.network.I2TCP_protocol.I2TCP_client import... | python |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2020 Stefano Gottardo (original implementation module)
Navigation for search menu
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from copy import deepcopy
import xbmcgu... | python |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django.urls import reverse_lazy
from django.views import generic
from parts.app.arrival.models import PartsArrival
from parts.app.mixins.common_mixins import PartsArrivalMixins
from parts.core.forms import PartsArrivalForm
... | python |
from collections import defaultdict
from exact_counter import ExactCounter
from space_saving_counter import SpaceSavingCounter
import time
from math import sqrt
from tabulate import tabulate
from utils import *
import matplotlib.pyplot as plt
class Test():
def __init__(self, fname="datasets/en_bible.txt", stop_wo... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
# URL pattern for the GoSetupView
url(
regex=r'^$',
view=views.GoSetupView.as_view(),
name='list'
),
# URL pattern for the GoV... | python |
from output.models.nist_data.list_pkg.ncname.schema_instance.nistschema_sv_iv_list_ncname_enumeration_2_xsd.nistschema_sv_iv_list_ncname_enumeration_2 import (
NistschemaSvIvListNcnameEnumeration2,
NistschemaSvIvListNcnameEnumeration2Type,
)
__all__ = [
"NistschemaSvIvListNcnameEnumeration2",
"Nistsche... | python |
#!/usr/bin/env python
import rospy
from biotac_sensors.msg import SignedBioTacHand
from std_msgs.msg import Float64, Bool, String
from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_output as outputMsg
from robotiq_2f_gripper_control.msg import _Robotiq2FGripper_robot_input as inputMsg
# reset and ac... | python |
"""Convert Aeon Timeline project data to odt.
Version 0.6.2
Requires Python 3.6+
Copyright (c) 2022 Peter Triesberger
For further information see https://github.com/peter88213/aeon3odt
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
import uno
from com.sun.star.awt.Messa... | python |
"""
Audio, voice, and telephony related modules.
"""
| python |
# -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from availability_app import views as avl_views
admin.autodiscover()
urlpatterns = [
## primary app urls...
url( r'^v1/(?P<id_type>.*)/(?P<id_value>.*)/$', avl_vi... | python |
import responses
from urllib.parse import urlencode
from tests.util import random_str
from tests.util import mock_http_response
from binance.spot import Spot as Client
mock_item = {"key_1": "value_1", "key_2": "value_2"}
key = random_str()
secret = random_str()
params = {
"asset": "BNB",
"type": 1,
"st... | python |
# -*- coding: utf-8 -*-
# @Author: Bao
# @Date: 2021-08-20 09:21:34
# @Last Modified time: 2022-01-19 09:03:35
import json
import subprocess as sp
from app import app
import argparse
def get_parser():
parser = argparse.ArgumentParser('PTZ-controller')
parser.add_argument('--encode-app',
'-ea',
... | python |
import setuptools
with open("README.md", "r") as f:
long_description = f.read()
setuptools.setup(
name="pathway-finder",
version="0.0.1",
author="Paul Wambo",
author_email="adjon081@uottawa.ca",
description="Genomic Pathway Miner Tool",
long_description=long_description,
long_descripti... | python |
import torch
from torch import nn
from .utils import add_remaining_self_loops, sum_over_neighbourhood
class GATLayer(nn.Module):
"""
Inspired by both Aleksa Gordic's https://github.com/gordicaleksa/pytorch-GAT and PyTorch Geometric's GATConv layer,
which we use as reference to test this implementation.
... | python |
import unittest
import datetime
import json
from app import create_app
class TestUser(unittest.TestCase):
def setUp(self):
""" Initializes app"""
self.app = create_app('testing')[0]
self.client = self.app.test_client()
self.user_item = {
"first_name" : "David",
... | python |
import cv2
videoCapture = cv2.VideoCapture('MyInputVid.avi')
fps = videoCapture.get(cv2.cv.CV_CAP_PROP_FPS)
size = (int(videoCapture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),
int(videoCapture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
videoWriter = cv2.VideoWriter(
'MyOutputVid.avi', cv2.cv.CV_FOURCC('I','4','2','... | python |
"""
`version` command test module
"""
from tests.utils import GefUnitTestGeneric, gdb_run_cmd
class VersionCommand(GefUnitTestGeneric):
"""`version` command test module"""
cmd = "version"
def test_cmd_version(self):
res = gdb_run_cmd(self.cmd)
self.assertNoException(res)
| python |
import home
from graphite_feeder.handler.event.appliance.thermostat.setpoint import (
Handler as Parent,
)
class Handler(Parent):
KLASS = home.appliance.thermostat.presence.event.keep.setpoint.Event
TITLE = "Setpoint maintenance(°C)"
| python |
from flask import request, make_response
from tests import app
@app.route("/cookie_file")
def cookie_file():
assert request.cookies['cookie1'] == 'valueA'
return ''
| python |
#!/usr/bin/env python3
# App: DVWA
# Security setting: high
# Attack: Linear search boolean-based blind SQL injection (VERY SLOW)
import requests
import string
import sys
import urllib
urlencode = urllib.parse.quote
def loop_inject(original_inject):
letters = ''.join(string.ascii_letters + string.digits + strin... | python |
# -*- coding: utf-8 -*-
#! \file ~/doit_doc_template/__init__.py
#! \author Jiří Kučera, <sanczes AT gmail.com>
#! \stamp 2018-08-07 12:20:44 +0200
#! \project DoIt! Doc: Sphinx Extension for DoIt! Documentation
#! \license MIT
#! \version See doit_doc_templ... | python |
"""
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees m... | python |
__author__='lhq'
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Variable
from torchvision import models
class logistic_regression(nn.Module):
def __init__(self):
super(logistic_regression, self).__init__()
self.logistic=nn.Linear(4096,2)
def... | python |
# Author: Kevin Köck
# Copyright Kevin Köck 2018-2020 Released under the MIT license
# Created on 2018-07-16
"""
example config:
{
package: .machine.adc
component: ADC
constructor_args: {
pin: 0 # ADC pin number or ADC object (even Amux pin object)
# calibration_v_max: 3.3 # ... | python |
import pytest
from flask import url_for
from mock import patch
from pydojo.core.tests.test_utils import count_words
from pydojo.core.forms import CodeEditorForm
@pytest.mark.usefixtures('client_class')
class TestCoreIndexView:
def test_get_status_code(self):
response = self.client.get(url_for('core.inde... | python |
# -*- coding: utf-8 -*-
"""
created by huash06 at 2015-04-29 16:49
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
"""
__author__ = 'huash06'
import sys
import os
import datetime
import functools
import itertools
import c... | python |
import networkx as nx
import networkx.readwrite.edgelist
import os
def generate(graph_type='', V=None, E=None, WS_probablity=0.1):
""" Generate a graph
Depending on the graph type, the number of vertices (V) or edges (E) can
be specified
:param graph_type: any of 'complete'
"""
if graph_type... | python |
from collections import Counter
class Vocab(object):
def __init__(self, path):
self.word2idx = {}
self.idx2word = []
with open(path) as f:
for line in f:
w = line.split()[0]
self.word2idx[w] = len(self.word2idx)
self.idx2word.appe... | python |
# -*- coding: utf-8 -*-
# @Time : 2020/8/19
# @Author : Lart Pang
# @GitHub : https://github.com/lartpang
import json
import os
import cv2
import mmcv
import numpy as np
from prefetch_generator import BackgroundGenerator
from torch.utils.data import DataLoader
class DataLoaderX(DataLoader):
def __iter__(se... | python |
#!/usr/bin/env python3
# quirks:
# doesn't redefine the 'import base64' of https://docs.python.org/3/library/base64.html
import sys
sys.stderr.write("base64.py: error: not implemented\n")
sys.exit(2) # exit 2 from rejecting usage
# copied from: git clone https://github.com/pelavarre/pybashish.git
| python |
# Data Parallel Control (dpctl)
#
# Copyright 2020-2021 Intel Corporation
#
# 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.... | python |
import foo.bar
foo.bar.baz()
#<ref>
| python |
import glob
import imp
import os
import pkgutil
import re
import sys
import tarfile
import pytest
from . import reset_setup_helpers, reset_distutils_log, fix_hide_setuptools # noqa
from . import run_cmd, run_setup, cleanup_import
PY3 = sys.version_info[0] == 3
if PY3:
_text_type = str
else:
_text_type = u... | python |
# ----------------------------------------------------------------------------
# Copyright (c) 2020 Ryan Volz
# All rights reserved.
#
# Distributed under the terms of the BSD 3-clause license.
#
# The full license is in the LICENSE file, distributed with this software.
#
# SPDX-License-Identifier: BSD-3-Clause
# -----... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 12:17:13 2020
@author: kenne
"""
from wtforms import (Form, validators,SubmitField,DecimalField)
import numpy as np
from flask import Flask
from flask import request
from flask import render_template
class ReusableForm(Form):
#Grad... | python |
import json
import os
import importlib
class Config(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __init__(self, **kwargs):
super(Config, self).__init__()
self.update(kwargs)
... | python |
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from django.urls import reverse
from django.db.models import Q, Min, F, When
from datetime import datetime, date, time, timedelta
from .models import *
from .utils import get_rating, get_game
from .forms import... | python |
# -*- coding: utf-8 -*-
from libs.pila import Pila
from libs.nodo import Nodo
import re
class ArbolPosFijo:
diccionario={}
def evaluar(self, arbol):
if arbol.valor=='+':
return self.evaluar(arbol.izquierda)+self.evaluar(arbol.derecha)
if arbol.valor=='-':
return self.ev... | python |
# Copyright (c) 2021, NVIDIA CORPORATION. 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
#
# Unless required by appli... | python |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | python |
import pytest
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler
from copy import deepcopy
from doctr import datasets
from doctr.transforms import Resize
def test_visiondataset():
url = 'https://data.deepai.org/mnist.zip'
with pytest.raises(ValueError):
datasets.da... | python |
import numpy as np
import pandas as pd
from typing import Union
from tpot import TPOTClassifier, TPOTRegressor
def _fit_tpot(
tpot: Union[TPOTClassifier, TPOTRegressor],
fit_X_train: Union[pd.DataFrame, np.array],
fit_y_train: Union[pd.DataFrame, np.array],
fit_X_val: Union[pd.DataFrame, np.array],
... | python |
import ast
import inspect
import sys
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from _pytest._code.code import Code
from _pytest._code.source import Source
LESS_PY38 = sys.version_info <= (3, 8)
def get_functions_in_function(
func: Callable,
) -> Dict[st... | python |
import dataclasses
import json
import logging
import time
from os.path import dirname
from pathlib import Path
from typing import Any, Dict, Optional, Union
from uuid import uuid4
from aioredis import Redis
from .defaults import (
DEFAULT_QUEUE_NAME,
DEFAULT_QUEUE_NAMESPACE,
DEFAULT_TASK_EXPIRATION,
D... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 18 17:00:19 2021
example: Parkfield repeaters::
@author: theresasawi
"""
import h5py
import numpy as np
import glob
import sys
import obspy
import os
import pandas as pd
sys.path.append('functions/')
from setParams import setParams
from generator... | python |
with open ('20.in','r') as f:
numbers = [map(int, l.split('-')) for l in f.read().split('\n')]
m,c = 0, 0
for r in sorted(numbers):
if m < r[0]: c += r[0] - m
m = max(m, r[1] + 1)
print c + 2**32 - m
| python |
#-*- coding: utf-8 -*-
import settings
settings.init()
import routers
import curses
import sys
from pages.mainMenu import MainMenu
# start curses
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
curses.curs_set(0)
stdscr.keypad(True)
def main(stdscr):
# Clear screen
stdscr.clear()
try:
... | python |
# Copyright (c) 2012 NTT DOCOMO, INC.
# Copyright 2011 OpenStack Foundation
# Copyright 2011 Ilya Alekseyev
#
# 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:... | python |
# Copyright (c) 2020 PaddlePaddle Authors. 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
#
# Unless required by appli... | python |
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data as data
from torch.autograd import Variable
from torch.nn.modules.module import _addindent
import h5py
from tqdm import tqdm
import time
import argparse
# Import all models
import model_inversion
import vae
import model_synthesis
class dee... | python |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | python |
import os
os.environ["TEST_VALUE"] = 'test'
| python |
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from SecAuthAPI.Core.models import Policy
class PolicySerializer(serializers.ModelSerializer):
class Meta:
model = Policy
fields = ('name', 'description', 'content')
| python |
from typing import Tuple
import os
import requests
import requests.adapters
class LocalFileAdapter(requests.adapters.BaseAdapter):
"""
Protocol Adapter to allow Requests to GET file:/// URLs
Example: file:///C:\\path\\to\\open_api_definition.json
"""
@staticmethod
def _check_path(path: str)... | python |
import logging
from channels.consumer import SyncConsumer
logger = logging.getLogger(__name__)
class UserConsumer(SyncConsumer):
def user_message(self, message):
pass
| python |
import os
from glob import glob
data_dirs = ["Training_Batch_Files","Prediction_Batch_files"]
for dir in data_dirs:
files = glob(dir+r"/*.csv")
for filePath in files:
print({filePath})
os.system(f"dvc add {filePath}")
print("\n#### All files added to dvc ####") | python |
_base_ = ['./bc.py']
agent = dict(
policy_cfg=dict(
type='ContinuousPolicy',
policy_head_cfg=dict(
type='DeterministicHead',
noise_std=1e-5,
),
nn_cfg=dict(
type='LinearMLP',
norm_cfg=None,
mlp_spec=['obs_shape', 256, 256, ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import urllib
import requests
from datetime import datetime, timedelta
import time
import logging
from lxml import html
from io import StringIO, BytesIO
import json
"""
Author: Anders G. Eriksen
"""
logger = logging.getLogger(__name__)... | python |
from discord.ext import commands
class SmashError(commands.CommandError):
def __init__(self, message=None, *args):
if message is not None:
super().__init__(str(message), *args)
else:
super().__init__(message, *args)
| python |
# -*- coding: utf-8 -*-
import logging
import nltk
import hashlib
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
class MEDLINESents:
def __init__(self, medline_abstracts, output_fname, lowercase=False):
self.medline_abstra... | python |
from django.urls import path
from . import views
app_name = 'shows'
urlpatterns = [
path('', views.IndexView.as_view(), name='home'),
path('<slug:slug>/', views.EpisodeView.as_view(), name='episodes')
] | python |
from typing import Sequence
from mathutils import Quaternion, Vector
from xml.etree import ElementTree as et
from ..maps.positions import PositionMap
from ..maps.rotations import RotationMap
class XFrame:
def __init__(self, f_time: float, bone_name: str, rotation: Sequence[float],
translation: Se... | python |
import numpy as np
import sklearn.svm
def dataset3Params(X, y, Xval, yval):
"""returns your choice of C and sigma. You should complete
this function to return the optimal C and sigma based on a
cross-validation set.
"""
# You need to return the following variables correctly.
C = 1
sigma = 0.3... | python |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class DynamicUpsamplingFilter(nn.Module):
"""Dynamic upsampling filter used in DUF.
Ref: https://github.com/yhjo09/VSR-DUF.
It only supports input with 3 channels. And it ... | python |
"""
Jax integration.
Importing this module registers the Jax backend with `phi.math`.
Without this, Jax tensors cannot be handled by `phi.math` functions.
To make Jax the default backend, import `phi.jax.flow`.
"""
from phi import math as _math
try:
from ._jax_backend import JaxBackend as _JaxBackend
JAX = ... | python |
from .vgg16 import get_vgg
from .vgg16_deconv import get_vgg_deconv
from .utils import get_image, store_feature, visualize_layer | python |
from unittest import TestCase, main
from unittest.mock import *
from src.sample.friendShips import FriendShips
from src.sample.friendShipsStorage import FriendStorage
class testFriendShipsStorage(TestCase):
def test_are_friend(self):
objectFriend = FriendShips()
objectFriend.dict = {"Przemek": ["... | python |
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
# pylint: disable=unused-variable
from pathlib import Path
import yaml
from pydantic import BaseModel
from service_integration.compose_spec_model import BuildItem, Service
from service_integration.osparc_config import MetaConfig, RuntimeConfig
f... | python |
#BEGIN_HEADER
from biokbase.workspace.client import Workspace as workspaceService
#END_HEADER
class nlh_test_psd_count_contigs:
'''
Module Name:
nlh_test_psd_count_contigs
Module Description:
A KBase module: nlh_test_psd_count_contigs
This sample module contains one small method - count_contigs.
... | python |
#!/usr/bin/env python
"""
ONS Address Index - Optimise the Probabilistic Parser
=====================================================
A simple script to run random search over CRF parameters to find an optimised model.
Uses a smaller training data set to speed up the process. Three-fold cross-validation
is being used ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def from_ghbdtn(text):
# SOURCE: https://ru.stackoverflow.com/a/812203/201445
layout = dict(zip(map(ord, '''qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~'''),
'''йцукенгшщзхъфывапролдж... | python |
#!env python3
# Heavily based on https://github.com/ehn-dcc-development/ehn-sign-verify-python-trivial
# under https://github.com/ehn-dcc-development/ehn-sign-verify-python-trivial/blob/main/LICENSE.txt
# It looks like public keys are at
DEFAULT_TRUST_URL = 'https://verifier-api.coronacheck.nl/v4/verifier/public_keys'... | python |
import numpy as np
import os
import matplotlib.pyplot as plt
class waveform:
"""A class to generate an arbitrary waveform
"""
def __init__(self, **kwargs):
# frequency with which setpoints will be given out
self.freq = kwargs.get('Bscan_RepRate', 33.333)
self.delta_t = 1/self.freq... | python |
# print("You have imported lc") | python |
"""Change User id type to string
Revision ID: 58c319e84d94
Revises: a15b1085162f
Create Date: 2021-05-04 01:10:37.401748
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '58c319e84d94'
down_revision = 'a15b1085162f'
branch_labels = None
depends_on = None
def u... | python |
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
print ("Hola Mundo del proceso ", rank)
| python |
#coding:utf-8
#
# id: bugs.core_1055
# title: Wrong parameter matching for self-referenced procedures
# decription:
# tracker_id: CORE-1055
# min_versions: []
# versions: 2.0.1
# qmid: bugs.core_1055
import pytest
from firebird.qa import db_factory, isql_act, Action
# version: 2.0.1
... | python |
# Definitions to be used in this HCM_Project folder
import os
# Main directory in which everything is stored
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = '/mnt/host/c/Users/Changxin/Documents/datasets/HCM_DATA_Organized'
DATA_DIR_WIN = 'c:/Users/Changxin/Documents/datasets/HCM_DATA_Organized'
# Di... | python |
# Python modules
from abc import ABC, abstractmethod
class Chain(ABC):
"""
An abstract base class for Chain objects. It can't be instantiated, but all
chains inherit from it and must have the abstract methods shown below.
Each Block object has a chain object reference, the set of Chain objects
pe... | python |
from BridgePython import Bridge
bridge = Bridge(api_key='myapikey')
class AuthHandler(object):
def join(self, channel_name, obj, callback):
# Passing false means the client cannot write to the channel
bridge.join_channel(channel_name, obj, False, callback)
def join_writeable(self, channel_name, secret_wo... | python |
"""DYNAPSE Demo.
Author: Yuhuang Hu
Email : duguyue100@gmail.com
"""
from __future__ import print_function
import threading
import numpy as np
from glumpy import app
from glumpy.graphics.collections import PointCollection
from pyaer.dynapse import DYNAPSE
# define dynapse
device = DYNAPSE()
print ("Device ID:", ... | python |
import subprocess
import logging
import os
import sys
import shlex
import glob
import yaml
from git import Repo, exc
logging.basicConfig()
logger = logging.getLogger('onyo')
def run_cmd(cmd, comment=""):
if comment != "":
run_process = subprocess.Popen(shlex.split(cmd) + [comment],
... | python |
# The MIT License (MIT)
#
# Copyright (c) 2019 Limor Fried for Adafruit Industries
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the righ... | python |
# Copyright 2020 The Bazel Authors. 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
#
# Unless required by applicable la... | python |
# -*- coding: utf-8 -*-
""" conda_content_trust.signing
This module contains functions that sign data using ed25519 keys, via the
pyca/cryptography library. Functions that perform OpenPGP-compliant (e.g. GPG)
signing are provided instead in root_signing.
Function Manifest for this Module:
serialize_and_sign
... | python |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | python |
"""
Photon installer
"""
#
# Author: Mahmoud Bassiouny <mbassiouny@vmware.com>
import subprocess
import os
import re
import shutil
import signal
import sys
import glob
import modules.commons
import random
import curses
import stat
import tempfile
from logger import Logger
from commandutils import CommandUtils
from ... | python |
"""Runs commands to produce convolved predicted counts map in current directory.
"""
import matplotlib.pyplot as plt
from astropy.io import fits
from npred_general import prepare_images
from aplpy import FITSFigure
model, gtmodel, ratio, counts, header = prepare_images()
# Plotting
fig = plt.figure()
hdu1 = fits.Ima... | python |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
from cgi import FieldStorage
from json import dumps
from base64 import b64decode
import subprocess
import sqlite3
import zlib
import struct
import os
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678901234567890123456789012345678901234567890123456789"... | python |
from typing import List, Tuple, Union
import torch
from torch import Tensor
from ..neko_module import NekoModule
from ..util import F
class Stack(NekoModule):
"""
The module version of torch.stack function family.
Args:
mode (``str``, optional): The mode of the pytorch stack type. Default origi... | python |
import os
from dotenv import load_dotenv
load_dotenv()
# basedir = os.path.abspath(os.path.dirname(__file__))
# DB_USERNAME = os.environ.get('DB_USERNAME')
# DB_PASSWORD = os.environ.get('DB_PASSWORD')
# DB_ENGINE = os.environ.get('DB_ENGINE')
# DB_NAME = os.environ.get('DB_NAME')
# DB_HOST = os.environ.get('DB_HOST'... | python |
path_inputs = "../data/stance_emb_sample.npy"
# path_inputs = "../data/stance_emb.npy"
path_stance = "../data/stance.npz"
from collections import defaultdict, Counter
from functools import partial
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score
from util import... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.