content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import torch
import torch.nn as nn
import torch.nn.functional as F
class GraphAttentionLayer(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True, drop_enc=False):
super(GraphAttentionLayer, ... | python |
from FrameLibDocs.utils import read_json, write_json
from FrameLibDocs.variables import help_dir, current_version
def main():
template_dir = help_dir / "templates"
internal_dir = help_dir / "internal_tabs"
external_dir = current_version / "FrameLib" / "externals"
master_template = help_dir / "help_tem... | python |
# 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, ... | python |
from mini_gplus.models import Media
def get_media(object_name):
return Media.objects.get(id=object_name)
def create_media(object_name):
media = Media()
media.id = object_name
# have to force save for some reason...
# https://github.com/MongoEngine/mongoengine/issues/1246
media.save(force_ins... | python |
# -*- coding: utf-8 -*-
"""Particle system Constraints objects
MIT License
Copyright (c) 2020 Mauro Lopez
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 l... | python |
from django.db import models
from django.contrib.auth.models import User
"""Dzien pracy - od zeskanowania kodu do ponownego zeskanowania
"""
class WorkDay(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
started = models.DateTimeField(auto_now_add=True)
finished = models... | python |
import sys
import unittest
class SC2EnvTests(unittest.TestCase):
def test_sc2env_four_towers_hra(self):
sys.argv = ['',
'--task', 'abp.examples.sc2env.four_towers.hra',
'--folder', 'test/tasks/sc2env_four_towers_hra']
from abp.trainer.task_runner import main
... | python |
# Regression test based on detection of carbuncle phenomenon (Odd-Even decoupling)
# MHD Riemann solvers
#
# Modules
import logging
import scripts.utils.athena as athena
import sys
import os
from shutil import move
sys.path.insert(0, '../../vis/python')
import athena_read # noqa
athena_read... | python |
"""
******** INFO ********
Created by Konrad Wybraniec
konrad.wybraniec@gmail.com
**********************
"""
from mainwindow import MrRoot
if __name__ == '__main__':
root = MrRoot()
root.configure()
root.mainloop()
# this is testing comment.
| python |
#
# Copyright (C) 2021 Vaticle
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0... | python |
#!/usr/bin/env python
# coding: utf-8
#
# <a href="https://colab.research.google.com/github/aviadr1/learn-advanced-python/blob/master/content/14_pandas/edm_us_adult_census_income/questions.ipynb" target="_blank">
# <img src="https://colab.research.google.com/assets/colab-badge.svg"
# title="Open this file in Go... | python |
#!/usr/bin/env python
"""
_AcquireFiles_
MySQL implementation of Subscription.GetCompletedFiles
"""
__all__ = []
from WMCore.WMBS.MySQL.Subscriptions.GetAvailableFiles import GetAvailableFiles
class GetCompletedFiles(GetAvailableFiles):
sql = """SELECT wmsfc.fileid, wl.site_name FROM wmbs_sub_files_complete wm... | python |
# Generated by Django 4.0.2 on 2022-03-01 16:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Library', '0002_book_image'),
]
operations = [
migrations.AlterField(
model_name='book',
name='Image',
f... | python |
#!/usr/bin/python3
import copy
import itertools as it
import os
import unittest
import unittest.mock as mock
import plato_pylib.plato.parse_tbint_files as parseTbint
import plato_pylib.plato.private.tbint_test_data as tData
import plato_fit_integrals.core.coeffs_to_tables as tCode
class TestIntegralHolder(unittest.... | python |
from unittest import TestCase, mock
from flask import url_for
from app import app
class RootTests(TestCase):
def setUp(self):
self.app = app
self.app.testing = True
self.app_context = self.app.test_request_context()
self.app_context.push()
self.client = self.app.test_client... | python |
from django.apps import AppConfig
class DadfesConfig(AppConfig):
name = "dadfes"
| python |
##########################################################
### PYGAME – Graph ###
### 1st Project for Data Structure at NYU Shanghai ###
##########################################################
__author__ = "Jack B. Du (Jiadong Du)"
__copyright__ = "Copyright 2014, the DS 1st P... | python |
# -*- coding: utf-8 -*-
"""
DB操作层
只涉及DB操作,最好不涉及业务
"""
from typing import List
from app.exceptions import AuthenticationFailed, ObjNotFound
from app.utils import sha256
from users.models import User, UserPermissionRelation, Permission, Role, UserRoleRelation, RoleMenuRelation, Menu, \
Platform
def authenticate(p... | python |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2020 D. Craig Brinck, SE; tamalone1
"""
import unittest
# Run the tests in this module
# Use warnings flag to suppress the PendingDeprecationWarning
# from numpy.matrix
# unittest.main(warnings='ignore')
test_suite = unittest.TestLoader().discover("Testing", pat... | python |
import logging
import unittest
from morm.q import Q
LOGGER_NAME = 'morm-test-q-'
log = logging.getLogger(LOGGER_NAME)
class TestMethods(unittest.TestCase):
def test_Q(self):
self.assertEqual(Q('string'), '"string"')
if __name__ == "__main__":
unittest.main(verbosity=2)
| python |
"""
Copyright (c) 2016 Jet Propulsion Laboratory,
California Institute of Technology. All rights reserved
"""
import json
from webservice.NexusHandler import NexusHandler, nexus_handler, AVAILABLE_HANDLERS
from webservice.webmodel import NexusResults
@nexus_handler
class HeartbeatHandlerImpl(NexusHandler):
name... | python |
"""
263. Ugly Number
Easy
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return true if n is an ugly number.
Example 1:
Input: n = 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore ... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'EMG3.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, ... | python |
iterable = [1, 2, 3, 4]
for item in iterable:
print(item)
print('-')
i = 0
while i<len(iterable):
print(iterable[i])
i += 1
# tuple unpacking
print('-')
tupleList = [('a', 1), ('b', 2), ('c', 3)]
for letter, number in tupleList:
print("letter is ", letter)
# need terminating condition and updation in wh... | python |
# A List it's a collection of grouping of items
item1 = 'bananas'
item2 = 'lego set'
# we can do it shorter -->>
tasks = ['Install Python', 'Learn Python', 'Take a break']
length = len(tasks) # Shows the length of the List
print(length)
# Accessing specific element from List wi the square brackets and position numbe... | python |
import torch
from datasets import CubDataset
from models import FineGrainedModel, ResNet18
from torchvision import transforms
from torch.utils.data import DataLoader
train_transforms = transforms.Compose(
[
transforms.Resize((128, 128)),
transforms.ToTensor(),
transforms.Normalize((0.4819... | python |
from gurobipy import *
from prediction.predictor import predict_scores
from utils.progress import inhour
import time
import numpy as np
def sample_users(num_users, num_users_sampled):
return np.random.choice(num_users, num_users_sampled, replace=False)
def sample_items(candidate_items, num_items_sampled):
r... | python |
import json
from rest_framework.fields import MISSING_ERROR_MESSAGE
from rest_framework.relations import *
from django.utils.translation import ugettext_lazy as _
from rest_framework_json_api.exceptions import Conflict
from rest_framework_json_api.utils import Hyperlink, \
get_resource_type_from_queryset, get_res... | python |
import kube_vars as globalvars
import kube_factory as factory
import kube_secret
import kube_servicecheck
import kube_pvc
if __name__=="__main__":
# This is the unified interface to accept parameters
# Python model argparse be used to parse the input parameter
# Subparser has been defined in git_handler.py... | python |
import sys
from PIL import Image, ImageDraw
WRITABLES = [(0, 0, 7, 7), (24, 0, 39, 7), (56, 0, 63, 7)]
imagePath = "schoolgirlsweater_tanukirotate.png"
img = Image.open(imagePath)
draw = ImageDraw.Draw(img)
lengthPass = False
length = 0
while not lengthPass:
msg = input("Enter the messaage to encode ... | python |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
import time
import unittest
import common.mqtt_connection as mqtt_connection
import common.mqtt_messages as mqtt_messages
import server.MQTT_callbacks as MQTT_callbacks
import server.storage as server_storage
... | python |
import os,copy
import pandas as pd
from collections import OrderedDict
from pypospack.pyposmat.data import PyposmatDataAnalyzer
from pypospack.pyposmat.data import PyposmatDataFile
from pypospack.pyposmat.data import PyposmatConfigurationFile
_fn_config = os.path.join("resources","pyposmat.config.in")
_fn_results_in =... | python |
def slugify(text):
"""
Removes all char from string that can cause problems whe used as a file name.
:param text: text to be modified.
:return: modified text
"""
return "".join(x for x in text if x.isalnum())
| python |
# Generated by Django 3.2.4 on 2021-06-21 18:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pvs_suban', '0009_auto_20210621_1753'),
]
operations = [
migrations.AddField(
model_name='addre... | python |
from PyQt5.QtWidgets import QBoxLayout
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QDialogButtonBox
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QMenu
from PyQt5.QtWidgets import QPushButton
from PyQt5.Qt import pyqtSignal
from PyQt5.Qt import ... | python |
"""Merge constrained primitives as property constraints."""
import collections
from typing import Tuple, Optional, List, Mapping, MutableMapping, Sequence
from icontract import ensure
from aas_core_codegen import intermediate
from aas_core_codegen.common import Error
from aas_core_codegen.infer_for_schema import (
... | python |
from core.models import UrineDrugScreen
from rest_framework import serializers
class UrineDrugScreenSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = UrineDrugScreen
fields = ('id', 'participant_id', 'date_of_test', 'uds_temp', 'pregnancy_test', 'opiates', 'fentanyl', 'bup', '... | python |
from typing import Optional, List
from pydantic import BaseModel
from feeder.api.models import BasePaginatedList
class GenericResponse(BaseModel):
success: str = "ok"
class FrontButton(BaseModel):
enable: bool = True
class UTCOffset(BaseModel):
utc_offset: int = -7
class TriggerFeeding(BaseModel):
... | python |
from al_utils.vaal_util import train_vae, train_vae_disc
from al_utils import vae_sampling as vs
import sys
import pickle
import torch
import numpy as np
import os
from copy import deepcopy
from pycls.core.config import custom_dump_cfg
import pycls.datasets.loader as imagenet_loader
def save_numpy_arrays(arrays, nam... | python |
import sys
import os
import datetime
import psycopg2
import pandas
from subprocess import call, Popen
print "dropping temporary members from database..."
conn_string = "dbname='hamlethurricane' user=postgres port='5432' host='127.0.0.1' password='password'"
try:
conn = psycopg2.connect(conn_string)
exc... | python |
######################################################################
######################################################################
# Copyright Tsung-Hsien Wen, Cambridge Dialogue Systems Group, 2016 #
######################################################################
####################################... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2018-07-30 19:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data', '0053_merge_20180615_1859'),
]
operations = [
migrations.AddField(
... | python |
"""Allow _view property in graph file schema
Revision ID: 8f6d4eef042d
Revises: a2316139e9a3
Create Date: 2021-10-20 10:04:21.668552
"""
import hashlib
import json
from os import path
import fastjsonschema
import sqlalchemy as sa
from alembic import context
from alembic import op
from sqlalchemy import table, column... | python |
# -*- coding: utf-8 -*-
from abc import ABC, abstractmethod
from fuocore.models import (
SongModel,
ArtistModel,
AlbumModel,
PlaylistModel,
LyricModel,
UserModel,
)
class AbstractProvider(ABC):
"""abstract music resource provider
"""
# A well behaved provider should implement it... | python |
import warnings
from mmdet.models.builder import (BACKBONES, DETECTORS, HEADS, LOSSES, NECKS,
ROI_EXTRACTORS, SHARED_HEADS, build)
from .registry import FUSION_LAYERS, MIDDLE_ENCODERS, VOXEL_ENCODERS
from mmdet3d.datasets.pipelines import Compose
def build_backbone(cfg):
"""Buil... | python |
from flask import Flask
from . import api_credentials_provider
def create_app(test_config=None) -> Flask:
"""Main entry point of the service. The application factory is responsible for
creating and confguring the flask app. It also defines a http ping endpoint and registers blueprints.
Returns:
F... | python |
# encapsulation
def outer(num1):
print("outer")
def inner_increment(num1):
print("inner")
return num1 + 1
num2 = inner_increment(num1)
print(num1, num2)
outer(10) | python |
'''
Extract special sequences from fasta file. You can specify which sequences get extracted by using the a separator.
Usage: python extract <fasta_file> <output_file> <separator>
Author: Nicolas Schmelling
'''
from Bio import SeqIO
import sys
def extract(fasta_file, output_file, separator):
with o... | python |
"""Utilities for interacting with ProxyStore"""
import proxystore as ps
from typing import Any, Optional, Union
from colmena.models import SerializationMethod
class ColmenaSerializationFactory(ps.store.redis.RedisFactory):
"""Custom Factory for using Colmena serialization utilities"""
def __init__(self,
... | python |
from ... import error
from ..entity import Entity
from ..component import Component
__all__ = ["Parent"]
class Parent(Component):
def __init__(self, parent: Entity):
self._parent = parent
def parent(self, err=True) -> Entity:
if self._parent is None and err:
raise error.ecs.Paren... | python |
from microbit import *
import utime
class Rangefinder:
def __init__(self, pin):
'''Setup a rangefinder on the specified pin'''
self.pin = pin
def distance_cm(self):
'''Returns the distance from a rangefinder in cm'''
self.pin.write_digital(0)
utime.sleep_us(200)
... | 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 |
def test_requirements(supported_configuration):
pass
| python |
import os
import sys
import math
import scipy.signal
import schemasim.schemas.l0_schema_templates as st
class PhysicalCondition(st.RoleDefiningSchema):
def __init__(self):
super().__init__()
self._type = "PhysicalCondition"
self._meta_type.append("PhysicalCondition")
self._roles ... | python |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | python |
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2020 Intel Corporation
""" ETCD Data Write Tool """
import argparse
import logging
import os
import sys
import eis_integ
def parse_arguments(_cli_args):
""" Parse argument passed to function """
parser = argparse.ArgumentParser(descr... | python |
from app.validation.validation import validate, ARGS, KWARGS
import json
import os
__db_items__ = "db/items"
class Item:
def __init__(self):
pass
@validate(4, ARGS)
def save(self, id, name, price, qty):
with open(f"{__db_items__}/{name}.json", 'w') as f:
data = {
... | python |
import json
from setuptools import setup, find_packages
from pydoccano import __version__
def requirements():
requirements_list = []
with open('Pipfile.lock', "r") as requirements:
data = json.load(requirements)
data = data['default']
for i in data:
try:
req = i + data[i... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
import time
from multiprocessing import Process
import pytest
import six
import thriftpy2
from thriftpy2.http import make_server as make_http_server, \
make_client as make_http_client
from thriftpy2.protocol import TApacheJSONProtocolFact... | python |
#!/usr/bin/env python
""" """
# Script information for the file.
__author__ = "Philippe T. Pinard"
__email__ = "philippe.pinard@gmail.com"
__version__ = "0.1"
__copyright__ = "Copyright (c) 2015 Philippe T. Pinard"
__license__ = "GPL v3"
# Standard library modules.
import unittest
import logging
import os
import temp... | python |
import argparse
from multiprocessing import Pool
from grit.occlusion_detection.occlusion_detection_geometry import OcclusionDetector2D
from grit.core.base import create_folders
from igp2.data import ScenarioConfig
def prepare_episode_occlusion_dataset(params):
scenario_name, episode_idx, debug, debug_steps = par... | python |
# This is the base module that will be imported by Django.
# Try to import the custom settings.py file, which will in turn import one of the deployment targets.
# If it doesn't exist we assume this is a vanilla development environment and import .deployments.settings_dev.
try:
from .settings import * # noqa
excep... | python |
http://stackoverflow.com/questions/2339101/knights-shortest-path-chess-question
| python |
import numpy as np
import pandas as pd
import pickle
import os
import json
import glob
import scipy
from ngboost import NGBRegressor
from ngboost.distns import Normal
from ngboost.learners import default_tree_learner
from ngboost.scores import MLE, LogScore
from sklearn.model_selection import KFold
from sklearn.metrics... | python |
"""Runs the webserver."""
from absl import app
from absl import flags
from absl import logging
from icubam import config
from icubam.db import store
flags.DEFINE_string('config', 'resources/config.toml', 'Config file.')
flags.DEFINE_string('dotenv_path', None, 'Optionally specifies the .env path.')
flags.DEFINE_enum(... | python |
from time import sleep
def msg(string):
print('~' * (len(string) + 2))
print(f' {string} ')
print('~' * (len(string) + 2))
while True:
print('\33[30;42m', end='')
msg('Sistema de ajuda PyHELP')
user = str(input('\033[mFunção ou Biblioteca \033[32m>>>\033[m '))
if user.lower() == 'fim':
... | python |
import unittest
from streamlink.plugins.schoolism import Schoolism
class TestPluginSchoolism(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
'https://www.schoolism.com/watchLesson.php',
]
for url in should_match:
self.assertTrue(Schoolism.can_ha... | python |
""""Process the results of DrFact and DrKIT"""
import json
import sys
from tqdm import tqdm
prediction_file = sys.argv[1]
output_file = sys.argv[2]
outputs = []
with open(prediction_file) as f:
print("Reading", f.name)
lines = f.read().splitlines()
for line in tqdm(lines[1:], desc="Processing %s"%f.name):
... | python |
# -*- coding: utf8 -*-
from __future__ import unicode_literals
def main():
print('234'.isdecimal())
if __name__ == '__main__':
main()
| python |
def main():
x, y = c(input()), c(input())
if x * y == 0:
return 0
return "S" + ("(S" * ((x * y) - 1)) + "(0" + (")" * (x * y))
def c(x):
return x.count('S')
if __name__ == '__main__':
print(main())
| python |
# @copyright@
# Copyright (c) 2006 - 2018 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
#
# @rocks@
# Copyright (c) 2000 - 2010 The Regents of the University of California
# All rights reserved. Rocks(r) v5.4 www.rocksclusters.org
# ... | python |
#!/usr/bin/python3
"""
Master program """
import multiprocessing
import math
import queue
import time
import pickle
import numpy as np
import pygame
import zmq
class CommProcess(multiprocessing.Process):
"""Communicates with robot."""
def __init__(self, image_queue, command_queue):
super().__init__(d... | python |
# Generated by Django 3.0.8 on 2020-07-15 09:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Resources', '0008_resume'),
]
operations = [
migrations.CreateModel(
name='People',
... | python |
import os
import sys
import yaml
import subprocess
from cryptography.fernet import Fernet
secrets_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'secrets.yaml')
def decrypt_secrets(cfg):
with open(os.path.join(cfg['global']['fernet_tokens_path'],'fernet_tokens.txt'), 'r') as token_file:
... | python |
#Test metadata model
from src.models import metadata
from src import data
from src import utils
import torch
import os
from pytorch_lightning import Trainer
ROOT = os.path.dirname(os.path.dirname(data.__file__))
def test_metadata():
m = metadata.metadata(sites = 1, classes=10)
sites = torch.zeros(20)
... | python |
from PyQt5 import QtWebEngineWidgets, QtWidgets
from tootbox.core.framework import LayoutView
from tootbox.views.toot import Toot
class Timeline(LayoutView):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initialize_ui()
def initialize_ui(self):
self.but... | python |
from __future__ import unicode_literals
import csv
import io
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save, pre_save
from django.utils.text import slugify
from yourapp.signals import csv_uploaded
from yourapp.validators import csv_file_validator
def uploa... | python |
import cv2
import numpy as np
# Let's load a simple image with 3 black squares
image = cv2.imread('Hough.jpg')
cv2.waitKey(0)
# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Find Canny edges
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)
# Finding Contours
# Use a copy of the image e.g.... | python |
import numpy as np
import tensorrt as trt
import cv2
import os
import pycuda.autoinit
import pycuda.driver as cuda
try:
from . import TRT_exec_tools
except ImportError:
import TRT_exec_tools
class Semantic_Segmentation:
def __init__(self, trt_engine_path):
"""
Parameters:
---... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from quant_benchmark.data.base_data_source.default_data_source import DefaultDataSource
import jqdatasdk
#see https://github.com/JoinQuant/jqdatasdk/blob/master/tests/test_api.py
jqdatasdk.auth(username='13922819479', password='123456')
data_source = DefaultDataSource(... | python |
def f06(word1 = 'paraparaparadise', word2 = 'paragraph'):
ngram = lambda n: lambda tl: [''.join(tl[i:i + n]) for i in range(len(tl) - n + 1)]
X = set(ngram(2)(list(word1)))
Y = set(ngram(2)(list(word2)))
print(X.union(Y))
print(X.difference(Y))
print(X.intersection(Y))
| python |
import math
def get_digit(n, i):
return n // 10**i % 10
def int_len(n):
if n == 0:
return 1
return int(math.log10(n))+1
def get_new_recipes(n):
recipes = []
for i in range(int_len(n)):
recipes.append(get_digit(n, i))
return recipes[::-1]
def part1(count):
recipes = [3, 7... | python |
from ._Activate import *
from ._Deactivate import *
from ._Completed import *
from ._Startup import *
from ._Shutdown import *
from ._Recs import *
| python |
# %% codecell
import os
import numpy as np
from tqdm import tqdm
from shutil import copyfile
# %% codecell
class_indices_S2_rev = {
'Waterbuck': 1,
'Baboon': 2,
'Warthog': 3,
'Bushbuck': 4,
'Impala': 5,
'Oribi': 6,
'Elephant': 7,
'Genet': 8,
'Nyala': 9,
'Setup': 10,
'Bushpig... | python |
import csv
import os
import random
from .utils import write_into_file, train_val_test_split
def preprocess(in_csv_paths, out_dir_path, val_split, test_split):
dataset = []
for path in in_csv_paths:
with open(path, "r") as file:
reader = csv.DictReader(file)
for row in reader:
... | python |
"""Output timeseries in NetCDF format.
"""
import glob,os,sys
import pandas as pd
import datetime as dt
import copy
def defaultExtensions():
return ['.nc']
def NCfile(filename,datas):
datas=copy.deepcopy(datas)
fileout=copy.deepcopy(filename)
for i,df in enumerate(datas):
if len(datas)>1:
... | python |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CassandraCluster(object):
"""Implementation of the 'CassandraCluster' model.
Specifies an Object containing information about a Cassandra cluster.
Attributes:
primary_host (string): Primary host from this Cassandra cluster.
seeds (lis... | python |
"""
A Work-In-Progress agent using Tensorforce
"""
from . import BaseAgent
from .. import characters
class TensorForceAgent(BaseAgent):
"""The TensorForceAgent. Acts through the algorith, not here."""
def __init__(self, character=characters.Bomber, algorithm='ppo'):
super(TensorForceAgent, s... | python |
## 2. Frequency Distribution ##
fandango_distribution = reviews['Fandango_Ratingvalue'].value_counts().sort_index()
imdb_distribution = reviews['IMDB_norm'].value_counts().sort_index()
print(fandango_distribution)
print('--'*12)
print(imdb_distribution)
## 4. Histogram In Matplotlib ##
fig, ax = plt.subplots()
plt... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 03. 円周率
sentence = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
print([len(c.strip(",.")) for c in sentence.split()])
| python |
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models
from problem.models import Submit, ProblemStats, LogEvent
@receiver(post_save, sender=Submit)
def update_problem_status(sender, instance, **kwargs):
try:
stats: ProblemStats = ProblemStats.obje... | python |
km = float(input('Informe a distância em KM: '))
v = float(input('Informe a velocidade média: '))
t = km / v
t_h = t // 1
t_m = (t - t_h) * 60
print(f'O tempo da viagem será de {t_h:.0f} horas e {t_m:.0f} minutos.')
| python |
# from .runner import main
| python |
import re
from typing import List, Dict, Type
import pkgutil
import inspect
import importlib
import HABApp
from HABApp.core import Items
from HABApp.core.items.base_item import BaseItem
import zone_api.core.actions as actions
from zone_api import platform_encapsulator as pe
from zone_api import device_factory as df
f... | python |
from unittest import TestCase
from unittest.mock import patch, call
import os
import pytest
from osbot_utils.utils.Dev import pprint
from osbot_utils.utils.Json import json_load_file
from cdr_plugin_folder_to_folder.processing.Analysis_Elastic import Analysis_Elastic
from cdr_plugin_folder_to_folder.utils.testing.Se... | python |
from seleniumbase import BaseCase
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from parameterized import parameterized
import pytest
from test_thermal.test_CompanyAdmin.test_RoleManagement.RoleManageBase import RoleManageBase
from utilities import utilities
from utilities.... | python |
"""
Here we're going to code for the local rotations. We're doing an object oriented approach
Left and right are in reference to the origin
"""
__version__ = 1.0
__author__ = 'Katie Kruzan'
import string # just to get the alphabet easily iterable
import sys # This just helps us in our printing
from typing import Di... | python |
from controller.csi_general import csi_pb2
SUPPORTED_FS_TYPES = ["ext4", "xfs"]
access_mode = csi_pb2.VolumeCapability.AccessMode
SUPPORTED_ACCESS_MODE = [access_mode.SINGLE_NODE_WRITER]
# VolumeCapabilities fields which specify if it is volume with fs or raw block volume
VOLUME_CAPABILITIES_FIELD_ACCESS_TYPE_MOUNT ... | python |
import pybamm
import numpy as np
import sys
# set logging level
pybamm.set_logging_level("INFO")
# load (1+1D) SPMe model
options = {
"current collector": "potential pair",
"dimensionality": 1,
"thermal": "lumped",
}
model = pybamm.lithium_ion.SPM(options)
# create geometry
geometry = model.default_geome... | python |
#
# Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS,
# BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, RIXEN@TUM.DE.
#
# Distributed under 3-Clause BSD license. See LICENSE file for more information.
#
"""
Mapping Module
"""
# -- STANDARD MAPPI... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.