content stringlengths 5 1.05M |
|---|
import math
from typing import List, Union, Any
def _product(probs: Union[None, List[float]]) -> float:
if probs is None or len(probs) == 0:
return 0.
if 0 in probs:
return 0
prob = math.exp(sum([math.log(p) for p in probs]))
return prob
def _batchify(input: List[Any], batch_size: in... |
import os
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
from functionalities import traverser as tra
from functionalities import dataloader as dl
def plot(x, y, x_label, y_label, plot_label, title, filename, sub_dim=None, figsize=(15, 10), font_size=24, y_log_scale=False):
"""
... |
# occiput
# Stefano Pedemonte
# Aalto University, School of Science, Helsinki
# Oct 2013, Helsinki
# Martinos Center for Biomedical Imaging, Harvard University/MGH, Boston
# Dec. 2013, Boston
# Martinos Center for Biomedical Imaging, Harvard University/MGH, Boston
# Jan. 2015, Boston
# Feb. 2015, Helsinki
# Nov. 2015,... |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""OCP-on-All Tag Query Handling."""
from copy import deepcopy
from django.db.models import DecimalField
from django.db.models import F
from django.db.models import TextField
from django.db.models import Value
from api.models import Provider
from... |
from irc3.testing import BotTestCase, patch
from irc3.plugins.autocommand import AutoCommand, SleepCommand
class TestAutoCommand(BotTestCase):
config = dict(includes=['irc3.plugins.autocommand'])
@patch("irc3.asyncio.sleep")
def test_autocommand(self, sleep):
def new_async(coro, *args, **kw):
... |
# -*- coding: utf-8 -*-
# @Time : 2021/8/9 16:32
# @Author : zc
# @Desc : 获取租户token请求体实体
from chanjet_openapi_python_sdk.chanjet_content import ChanjetContent
# 获取租户token请求体实体
class GetTenantTokenContent(ChanjetContent):
def __init__(self, tenant_id, app_name, scope='auth_all'):
"""
获取租户to... |
import tensorflow as tf
import numpy as np
import joblib
from rl.acktr.utils import Scheduler, find_trainable_variables
from rl.acktr.utils import fc, mse
from rl.acktr import kfac
from irl.mack.tf_util import relu_layer, linear, tanh_layer
disc_types = ['decentralized', 'centralized', 'single', 'decentralized-all']
... |
#!/usr/bin/env python3
import os
import re
import shlex
import argparse
from subprocess import Popen, PIPE
from typing import List, Dict, Union
from threading import Thread, Lock, current_thread
import toml
from bs4 import BeautifulSoup
class Colors:
CYAN = '\033[96m'
GREEN = '\033[92m'
MAGENTA = '\033[... |
#!/usr/bin/python
from ntnx_api.client import PrismApi
from ntnx_api import prism
import random
import string
letters = string.digits
random_string = ''.join(random.choice(letters) for i in range(6))
network_cleanup = []
def _api():
return PrismApi(ip_address='192.168.1.44', username='admin', password='fUUif4l0C... |
# Copyright 2021 Huawei Technologies Co., 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 agreed to... |
# -*- coding: utf-8 -*-
"""
******************************************************************************
Rotinas para interpretar vários formatos de dados para utilização no 'plotMap'
Autor : Nelson Rossi Bittencourt
Versão : 0.111
Licença : MIT
Dependências: numpy, pygrib (que tem várias ... |
#!/usr/bin/env python
try:
from secrets import token_urlsafe
except:
from base64 import b64encode
from hashlib import sha256
from random import choice, getrandbits
def generate_hash_key():
try:
return token_urlsafe(32)
except:
return b64encode(
sha256(str(getrandbi... |
import builtins
from unittest import TestCase, skipIf
from mock import patch, mock_open, MagicMock
from pconf.store.file import File
from warnings import simplefilter
TEST_FILE_PATH = "test"
TEST_FILE_DICT = {"file": "result"}
TEST_FILE_RAW = '{"file": "result"}'
TEST_FILE_JSON = '{"file": "result"}'
TEST_FILE_JSON_N... |
__description__ = \
"""
Small library for generating GROMACS simulation inputs for proteins, small
molecules with custom forcefields, or both together.
"""
__author__ = "Michael J. Harms"
__date__ = "2021-04-16"
import re, glob, os, subprocess, shutil, random, string, sys
def _run_cmd(cmd_list,base=None,run_in_dir=N... |
#!/usr/bin/env python3
from collections import deque
deq = deque()
for _ in range(int(input())):
tok = input().split()
if tok[0] == 'append':
deq.append(int(tok[1]))
elif tok[0] == 'pop':
deq.pop()
elif tok[0] == 'appendleft':
deq.appendleft(int(tok[1]))
elif tok[0] == 'p... |
#!/usr/bin/env python3
'''
lib/util/hmac.py
Contains HMAC utility functions. The ycmd server expects an HMAC header with
all requests to verify the client's identity. The ycmd server also includes an
HMAC header in all responses to allow the client to verify the responses.
'''
import hashlib
import hmac
import loggin... |
from typing import Tuple
import numpy as np
from .operator import square_distance
def k_nearest_neighbors(coords1: np.ndarray, coords2: np.ndarray, k: int) -> Tuple[np.ndarray, np.ndarray]:
"""Compute k nearest neighbors between coords1 and coords2.
Args:
coords1: coordinates of centroid points (N, ... |
"""
Invoke based build automation.
isort:skip_file
"""
# TODO - Remove this patch once https://github.com/pyinvoke/invoke/issues/357 is fixed.
from tasks.patch_invoke import fix_annotations
fix_annotations()
# pylint: disable = wrong-import-position
from tasks.lint import lint
from tasks.test import unit_test
# pyli... |
import PyOK as ok
import time
import sys
def FormatBits(bitstr):
return int(bitstr, 0).to_bytes(4, byteorder='little')
# pretty print of a bytearray, ignores upstream nops
def PrintBytearrayAs32b(buf_out):
nop_count = 0
for idx in range(len(buf_out) // 4):
this_word_flipped = buf_out[4*idx:4*(idx+1)]
... |
# InsightIDR4Py.py
# Author: Micah Babinski
# Date: 10/1/2021
# Description: Contains useful functions for working with the Rapid7 InsightIDR REST API
# import required modules
import requests, json, time
from datetime import datetime
# define URLs to interact with the API
region = "us" # one of us/eu/ca/au... |
#!/usr/bin/env python3
import multiprocessing as mp
import domino_tiles_brute_force as dtbf
import yaml
import time
from random import randint
# Define an output queue
output = mp.Queue()
def print_grid(grid,num_rows):
for x in range(num_rows+2):
print(grid[x])
def find_snakes(num_tries,num_successes,output_... |
import logging
import re
from urllib.parse import urlparse
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import useragents, validate
from streamlink.stream import HDSStream, HLSStream, HTTPStream
from streamlink.utils import parse_json
log = logging.getLogger(__name__)
@pluginmatche... |
from . import Visualizer
import pyglet
from pyglet.window import key
from pyglet.gl import *
import numpy as np
import cv2
import sys
from ..sign_detection.ai import predict
class SignMedia:
def __init__(self, target):
if target == "cam":
self.media = cv2.VideoCapture(0)
if not s... |
from .tasks import *
from .examples_management import ExampleManagement
task_manager = ExampleManagement()
task_manager.register_tasks([
('news', NewsSegmentTask),
('news_cls', NewsClsTask),
('sentiment', SentimentTask)
])
if is_turbo_available():
task_manager.register_task('turbo-news', TurboNewsSeg... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
def bounding_rect_of_mask(img, mask):
where = np.argwhere(mask)
(y_start, x_start), (y_stop, x_stop) = where.min(0), where.max(0) + 1
return img[y_start:y_stop, x_start:x_stop]
|
import torch
from graph_updater_data import GraphUpdaterDataset, GraphUpdaterObsGenDataModule
from preprocessor import BOS, EOS
def test_graph_updater_dataset():
dataset = GraphUpdaterDataset("test-data/test-data.json")
assert len(dataset) == 3
for datapoint in dataset:
assert type(datapoint) == ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
class SmallSMILHandler(ContentHandler):
def __init__(self):
self.width = ""
self.height = ""
self.back = ""
self.idd = ""
self.top = ""
self.botto... |
import sys
import os
# Limitation: header and cpp needs to be in the same directory.
def TextFileToCpp(cppFName,hFName,varName,binFName):
strArray=[]
fp=open(binFName,"r")
for str in fp:
str=str.replace('\n','')
str=str.replace('\r','')
strArray.append(str)
fp.close()
TextToCpp(cppFName,hFName,varName,st... |
#!/usr/bin/env python3.4
import sys
import pprint as pp
import collections
def split_time(time_str):
'''Split up the time string to a list in the format of [hr, min]
in interger format
Args:
time_str: time in 24:00 format as a string
Returns:
split_time: list of time in [hr,min]
... |
from django.urls import include, path
from rest_framework import routers
from snakepy import views
from rest_framework import viewsets
v = [views.__dict__[k] for k in views.__dict__ if isinstance(
views.__dict__[k],
type
) and issubclass(
views.__dict__[k],
viewsets.ModelViewSet
)]
router = routers... |
from .inputRequired import InputRequired
from .exactMatch import ExactMatch
from .containsMatch import ContainsMatch |
from TestSuite import EMPTY_NAMESPACE
def get_exception_name(code):
import types
from xml import dom
for (name,value) in vars(dom).items():
if (type(value) == types.IntType
and value == code):
return name
def test(tester):
tester.startGroup('Element')
tester.startTest(... |
import logging
import os
import sys
import jsonlines
from tqdm import tqdm
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import json
from sklearn.metrics import mean_squared_error, f1_score
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
def... |
# Copyright 2013 Nebula Inc.
#
# 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 to... |
# ActivitySim
# See full license in LICENSE.txt.
import logging
import pandas as pd
from activitysim.core import simulate
from activitysim.core import tracing
from activitysim.core import config
from activitysim.core import inject
from activitysim.core import pipeline
from activitysim.core import timetable as tt
from... |
import sys
import numpy as np
import cv2
src = cv2.imread('love.jpeg')
if src is None:
print('no img')
sys.exit()
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')
eye_classifier = cv2.CascadeClassifier('haarcascade_eye.xml')
if face_classifier.empty() or eye_classifier.empty():
... |
#!/usr/bin/env python3
"""Some generic functions"""
import time
def cfind(haystack, needle, offset):
"""Return character index of needle found in haystack at offset"""
start = haystack.find(needle)
while start >= 0 and offset > 1:
start = haystack.find(needle, start+len(needle))
offset -= ... |
# Generated by Django 3.2.3 on 2021-12-21 13:51
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
import wagtail_photo_gallery.blocks
class Migration(migrations.Migration):
dependencies = [
('home', '0002_create_homepage'),
]
operations = [
migration... |
import pandas as pd
import numpy as np
from time import time
import sys
class StateBasedBucketer(object):
def __init__(self, encoder):
self.encoder = encoder
self.dt_states = None
self.n_states = 0
def fit(self, X, y=None):
dt_encoded = self.... |
#! /usr/bin/env python3
from setuptools import setup
setup(
name = "WiiProxy",
version = "2.0",
description = "Python 3 module for MultiWii firmware.",
url = "https://github.com/engineer-99b/WiiProxy",
author = "engineer-99b",
license = "MIT",
packages = ["Wi... |
from datalad.tests.utils import skip_if_no_module
skip_if_no_module('scrapy')
from datalad.tests.utils import skip_if_scrapy_without_selector
skip_if_scrapy_without_selector()
|
import tensortrade as td
from abc import abstractmethod
from tensortrade.base import Component
class DataMessageComponent(Component):
registered_name = "messages"
@abstractmethod
def __init__(self, data: dict):
self._data = data
@property
def data(self):
return self._data
... |
import RLAgents
import matplotlib.pyplot as plt
result_path = "./results/"
files = []
files.append("./models/ppo_baseline/result/result.log")
stats_baseline = RLAgents.RLStatsCompute(files)
files = []
files.append("./models/ppo_baseline_sparse/result/result.log")
stats_baseline_sparse = RLAgents.RLStatsCompute(file... |
import pytest
from io import StringIO
from unittest.mock import mock_open, patch, call
from exquisite_corpus.tokens import tokenize_file, tokenize_by_language
def run_tokenize(func, test_obj, kwargs):
input_file = [test_obj]
output_file = StringIO()
func(input_file, output_file, **kwargs)
output_file... |
from django.test import TestCase
from django.urls import resolve
from home.views import HomePage
class TestHomePageView(TestCase):
def test_root_url_resolves_to_home_page(self):
response = resolve('/')
self.assertEqual(response.func.__name__, HomePage.as_view().__name__)
def test_home_page_... |
'''
Functions to go in here (I think!?):
KC: 01/12/2018, ideas-
KC: 19/12/2018, added-
~NuSTAR class
'''
from . import data_handling
import sys
#from os.path import *
import os
from os.path import isfile
import astropy
from astropy.io import fits
import astropy.units as u
import matplotlib
import matplot... |
#!/usr/bin/env python
__author__ = "Kristian Rother"
__contributors__ = "Tomasz Puton"
__credits__ = ["Lukasz Kozlowski, Natalia Szostak, Joanna Kasprzak, Sandra Smit"]
__maintainer__ = "Kristian Rother"
__email__ = "krother@rubor.de"
__status__ = "Prototype"
from unittest import TestCase, main
from Bio.RNA.Secstruc... |
from torch.optim.lr_scheduler import _LRScheduler
# ----- Scheduler -----
class LowerBoundedExponentialLR(_LRScheduler):
def __init__(self, optimizer, gamma, lower_bound, last_epoch=-1):
self.gamma = gamma
self.lower_bound = lower_bound
super(LowerBoundedExponentialLR, self).__init__(opti... |
"""
undictify - tests
"""
import json
import pickle
import unittest
from datetime import datetime
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Union, Tuple
from typing import TypeVar
from ._unpack import type_checked_call, type_checked_constructor
TypeT = TypeVar('TypeT')
# pylint: disable=t... |
import json
import zipfile
import os
import hashlib
import shutil
def recursive_zip(zipf, directory, folder=""):
zipf.write(directory, folder)
for item in os.listdir(directory):
absolutePath = os.path.join(directory, item)
if os.path.isfile(absolutePath) and item != ".DS_Store":
zip... |
import h5py
import pandas as pd
import sys
with h5py.File(sys.argv[1],'r') as ipt:
gd = ipt['GroundTruth'][...]
gdt = pd.DataFrame({'EventID':gd['EventID'],'ChannelID':gd['ChannelID'],'PETime':gd['PETime'],'Weight':gd['Weight']})
import tables
# Define the database columns
class AnswerData(tables.IsDescription):
... |
from pile import Pile
class Hanoi:
def __init__(self, nb_disques=3):
self.__pile1 = Pile([i for i in range(nb_disques, 0, -1)])
self.__pile2 = Pile()
self.__pile3 = Pile()
self.__tours = [self.__pile1, self.__pile2, self.__pile3]
self.__nb_disques = nb_disques
... |
import functools
import os
import multiprocessing as mp
import multiprocessing.pool
import buzzard as buzz
import numpy as np
import skimage.io
import example_tools
from part1 import test_raster
ZOOMABLE_URLS = {
'andromeda': 'https://cdn.spacetelescope.org/archives/images/zoomable/heic1502a/',
'monocerotis... |
#
# Copyright (c) 2015 Intel Corporation
#
# Author: Alberto Murillo <alberto.murillo.silva@intel.com>
# Author: Julio Montes <julio.montes@intel.com>
#
# 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 Lic... |
from manimlib.imports import *
class Cover(Scene):
def construct(self):
t = TextMobject(*[c for c in 'requests'])
t.scale(3)
for idx, c in enumerate(t):
if idx % 2 == 0:
c.set_color(BLUE)
else:
c.set_color(GREEN)
t.shift(UP)
... |
from argparse import ArgumentParser
from pathlib import Path
from sys import exit
from constants import DATA_PATH
from experiments import run_vignettes_experiment
from inference import create_marginals_files
from results import produce_results
from utils import ensure_dir, load_from_json
def parse_args():
parser... |
class Solution:
def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
ans = [0] * len(s)
moves = {'L':(0, -1), 'R':(0, 1), 'U':(-1, 0), 'D':(1, 0)}
for i in range(len(s)):
curr_row, curr_col = startPos[0], startPos[1]
curr_step = 0
... |
import argparse
import os
import json
from mtl.datasets.definitions import SPLIT_VALID, SPLIT_TEST
def expandpath(path):
return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
... |
import numpy as np
import pandas as pd
from sklearn.utils import check_random_state
from skbio.stats.composition import ilr_inv
from skbio.stats.composition import clr_inv as softmax
def random_multimodal(num_microbes=20, num_metabolites=100, num_samples=100,
latent_dim=3, low=-1, high=1,
... |
import os
import argparse
import seq2edits_utils
from collections import defaultdict
import tokenization
import argparse
from utils import generator_based_read_file, do_pickle, pretty, custom_tokenize
from collections import Counter, defaultdict
from joblib import Parallel, delayed
from tqdm import tqdm
def add_argum... |
"""stash hosted zone id
Revision ID: b671b2b52afb
Revises: 6aeacb57a929
Create Date: 2020-06-18 21:55:54.220606
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
# revision identifiers, used by Alembic.
revision = "b671b2b52afb"
down_revision = "6aeacb57a929"
branch_labels = None
depends_on... |
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
import products
urlpatterns = [
# path('', include('products.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
from model_generator import ModelGenerator
from typing import List
from array_tools import ArrayTools
import itertools
class CastleModel(ModelGenerator):
castle_sizes: List[int] = []
castle_lifes: List[int] = []
castles_no: int = 0
def __init__(self, castle_sizes: List[int], castle_lifes: List[int]):... |
print("t3., This is %s" % __file__)
def f3():
print("t3.f3() called!") |
#MIT License
#Copyright (c) 2022 Michael Shekelyan, King's College London
#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 rights
#to use, ... |
'''
Author:Kiru Park (park@acin.tuwien.ac.at, kirumang@gmail.com)
'''
import os,sys
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import numpy as np
import yaml
import cv2
from matplotlib import pyplot as plt
#selection of detection pipelines
import keras
import tensorflow as tf_backend
ROOT_DIR = os.path.abspath(".")
sy... |
import jwt
import base64
from chatburo import settings
def encode(origin=None):
token_bytes = jwt.encode(
{"origin": origin}, settings.SERVER_SECRET, algorithm="HS256"
)
base64_bytes = base64.b64encode(token_bytes)
return base64_bytes.decode("ascii")
def decode(b64_token):
try:
... |
from urllib.request import urlopen
from pathlib import Path
inputs = Path("day1_input.txt").read_text()
module_weights = map(int, inputs.split())
def sum_with_fuel(weight: int) -> int:
weights = [weight]
while weights[-1] // 3 - 2 > 0:
weights.append( weights[-1] // 3 - 2 )
return ... |
# Generated by Django 2.1.7 on 2019-02-12 11:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='username',
field... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import versioneer
URL = 'https://github.com/kadrlica/cartosky'
with open('requirements.txt') as f:
install_requires = [req.strip() for req in f.readlines() if req[0] != '#']
setup(
name='cartosky',
version=vers... |
# -*- coding: utf-8 -*-
from .context import rdfpandas
import pandas as pd
import numpy as np
from rdflib import Graph, Literal, URIRef, BNode, Namespace
from rdflib.term import Identifier
from rdflib.namespace import NamespaceManager, SKOS, XSD
import rdflib.compare
import unittest
class ConversionTestCase(unitt... |
import mat73
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load four variables
h = mat73.loadmat('simulink_stuff/h.mat')
t = mat73.loadmat('simulink_stuff/timer.mat')
x = mat73.loadmat('simulink_stuff/x.mat')
tht = mat73.loadmat('simulink_stuff/theta.mat')
# Verify dict keys
# print(h.ke... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
from six import iteritems, string_types
"""build query for doclistview and return results"""
import frappe.defaults
from dateutil.parser._parser import ParserError
import opera... |
from reggae.reflect import get_dependencies
import os
import foo # noqa
def test_get_deps():
my_dir = os.path.dirname(os.path.realpath(__file__))
my_path = os.path.join(my_dir, __name__ + ".py")
assert get_dependencies(my_path) == [os.path.join(my_dir, "foo.py")]
|
import random
nomes = input('\033[35mDigite quatro nomes para sortea-los em uma sequência: ')
sorteio = nomes.split()
nm1 = (sorteio[0])
nm2 = (sorteio[1])
nm3 = (sorteio[2])
nm4 = (sorteio[3])
random.shuffle(sorteio)
print('A sequência de apresentação dos trabalhos é: ', sorteio)
|
from core.models import Ingredient
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from recipe.serializers import IngredientSerializer
from rest_framework import status
from rest_framework.test import APIClient
INGREDIENT_URL = reverse("recipe:ingredient-... |
#Copyright 2009 Humanitarian International Services Group
#
#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... |
__all__ = ["compare", "io", "preprocessing", "visualization"]
from .spectrum import Spectrum |
"""
Disctrict Cooling Network Calculations.
Use free cooling from Lake as long as possible ( HP Lake operation from slave)
If Lake exhausted, then use other supply technologies
"""
from __future__ import division
import time
import numpy as np
import pandas as pd
import cea.config
import cea.technologies.cooling_towe... |
from kvdroid.jclass.android import MediaPlayer, AudioManager
class Player(object):
mPlayer = MediaPlayer(instantiate=True)
content = None
def raw(self):
return self.mPlayer
def play(self, content: str):
self.content = content
try:
self.mPlayer.stop()
s... |
# -*- coding: utf-8 -*-
#
# ramstk.analyses.SimilarItem.py is part of the RAMSTK Project
#
# All rights reserved.
# Copyright 2019 Doyle Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Reliability Similar Item Assessment Module."""
# Standard Library Imports
from typing import Dict, List, Tuple
# Third Party ... |
import os
import sys
import logging
def test_print():
print('Printing to stdout')
print('Printing to stderr', file=sys.stderr)
logging.debug('Printing to debug')
logging.info('Printing to info')
logging.warning('Printing to warning')
logging.error('Printing to error')
# We don't want to di... |
# Client jwt
import os
import requests
import json
# login_url = 'http://localhost:4000/login'
# service_url = 'http://localhost:4001/users'
login_url = 'http://192.168.100.48/auth/login'
# service_url = 'http://192.168.100.48/api/users'
# service_url = 'http://localhost:5000/file/list'
service_url = 'http... |
from datetime import datetime
from .datapackage import ELECTION_TYPES
from .parser import DataPackageParser
from .slugger import slugify
parser = DataPackageParser(ELECTION_TYPES)
RULES = parser.build_rules()
CONTEST_TYPES = ("by", "by election", "by-election", "election")
def validate(identifier):
"""Validate ... |
class _FieldDescriptor(object):
def __init__(self, name):
self.name = name
class _Descriptor(object):
def __init__(self, name, fields):
self.name = name
self.fields = fields
_FOO = _Descriptor(
name='Foo',
fields=[_FieldDescriptor(name='valid_field')],
)
_BAR = _Descriptor(
... |
from struct import unpack
import warnings
from LnkParse3.target_factory import TargetFactory
"""
LINKTARGET_IDLIST:
An optional LinkTargetIDList structure (section 2.2), which specifies the
target of the link. The presence of this structure is specified by the
HasLinkTargetIDList bit (LinkFlags section 2.1.1) in the ... |
import enum
from multiprocessing.dummy import freeze_support
import os
import sys
from dotenv import load_dotenv
load_dotenv()
os.environ['WANDB_NOTEBOOK_NAME'] = 'pytorch_stats_own_data.ipynb'
os.environ['WANDB_API_KEY'] = os.getenv('WANDB_API_KEY')
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
... |
import chainer
from chainer import functions
from chainer import links
from chainer import reporter
from chainer_pointnet.models.linear_block import LinearBlock
from chainer_pointnet.models.pointnet2.set_abstraction_all_block import \
SetAbstractionGroupAllModule
from chainer_pointnet.models.pointnet2.set_abstract... |
from functools import reduce
from osgeo import ogr
import numpy as np
from .raster import Raster
def split_by_shp(raster, shp_path, by=None, overall=False):
"""Split rasters into several parties by polygons from shapefile.
Args:
raster (Raster or list of Raster): One or more rasters.
shp_pat... |
# Recitation Lab 2 Question 3: Program to display assignment score
# Author: Asmit De
# Date: 01/26/2017
assignment = input('Enter the assignment name: ')
totalpoints = input('Enter the total points: ')
score = input('Enter your score: ')
print('\nYou scored', score, 'out of', totalpoints, 'in', assignment)... |
'''Functions used to begin the planner or load the save data from the existing file containing the planner and its user's input. Function used to save and store the user input data to their planner.'''
import json
from pathlib import Path
def load_data():
filename = 'storedSchedule'
days_week = {}
path_t... |
#!/usr/bin/env python3
# Copyright (c) 2019 Arm Limited and Contributors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""List certificate argument handler."""
from mbl.cli.utils import cloudapi, store
def execute(args):
"""Entry point for the 'list-dev-cert' command."""
key = store.Store(... |
from sklearn.linear_model import LogisticRegression
import pandas
from detectors.tmd_base import TravelModeDetector
from sklearn.metrics import accuracy_score
class LogisticRegressionTMD(TravelModeDetector):
"""
Wrapper that uses LogisticRegression to train a travel mode detector through smartphone sensors
... |
#encoding: utf-8
import pathlib
import os
import getpass
import locale
def diretorio():
idioma = locale.getdefaultlocale()
print(idioma)
diretorio = pathlib.Path('/snap/gerenciadorcs/current/')
print(diretorio)
arquivos = ''
a = ''
if idioma == ('pt_BR', 'UTF-8'):
print('The Langu... |
# SPDX-License-Identifier: Apache-2.0
def set_ntp_config(
host,
username,
password,
ntp_servers,
protocol=None,
port=None,
host_names=None,
verify_ssl=True,
):
"""
Set NTP configuration for a given host of list of host_names.
host
The location of the host.
usern... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if (not head or not head.next):
return head
dummyNode = ListNode(0)
dummyNode.next = head
slow = dummyNode
fas... |
import tornado.web
import os, os.path
import time, datetime
import sys
sys.path.append('/root/sim-as-a-service/utils/')
from sim_constants import *
class JobApiHandler(tornado.web.RequestHandler):
def get(self):
history = { 'status': 200, 'jobs_his': []}
f = open('/root/sim-as-a-service/utils/hi... |
import tensorflow as tf
import numpy as np
def add_relu(input_layer):
return tf.nn.relu(input_layer)
def conv(input_layer, channel_num, kernel_size, stride, padding, biased=False, relu=False, name='conv', dilation=1):
if padding is None:
padding = 'SAME'
conv_layer = tf.layers.conv2d(
... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix)
Copyright (C) 2018 Caphm (original implementation module)
Kodi library integration: items library
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from __future__ import absolute_import... |
import gpUtils
from mklmm import MKLMM
import scipy.linalg as la
import cPickle
import time
import sys
import numpy as np
np.set_printoptions(precision=4, linewidth=200)
def findSignificantRegions(regionsFile, numSNPs, numRegions, regionPercentile=95, verbose=True):
#read regions file
chunksArr = np.loadtxt(re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.