text stringlengths 2 999k |
|---|
import os
import json
import numpy as np
import torch
import torch.nn.functional as F
from torch.optim import Adam
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
import matplotlib
import matplotlib.pyplot as plt
import warnings
from mode_disent_no_ssm.utils.skill_policy_wrapper import DiaynSki... |
import pytest
from marshmallow import (
fields,
Schema,
ValidationError,
EXCLUDE,
INCLUDE,
RAISE,
missing,
)
from marshmallow.exceptions import StringNotCollectionError
from tests.base import ALL_FIELDS
@pytest.mark.parametrize(
("alias", "field"),
[
(fields.Int, fields.I... |
from abc import ABC, abstractmethod
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch import Tensor, autograd
from cn_dpm.ndpm.summaries import Summaries, VaeSummaries, ClassificationSummaries
from typing import Tuple, List
class Component(nn.Module, ABC):
def __init__(self, co... |
from knox import views as knox_views
from .views import UserAPIView, RegisterAPI, LoginAPI, EmployeeInfoAPI
from django.urls import path
urlpatterns = [
path('api/register/', RegisterAPI.as_view(), name='register'),
path('api/user/', UserAPIView.as_view()),
path('api/login/', LoginAPI.as_view(), name='logi... |
""" Problem Difficulty: [Medium]
Given a 2-D matrix representing an image, a location of a pixel in the screen and a color C,
replace the color of the given pixel and all adjacent same colored pixels with C.
For example, given the following matrix, and location pixel of (2, 2), and 'G' for green:
B B W
W W W
W W W
... |
#!/usr/bin/env python
"""
Datastructure for a node in a game tree. Useful in reinforcement learning
"""
from noughts_crosses import *
class Node:
def __init__(self, board):
'initialise a new node with a board'
# score is the reward given to board if this node is terminal
self.board = board... |
from AESfunctions import KeyExpansion, AES_Encrypt, AES_Decrypt
# Nb = 4 columns in state (in this standard)
Nb = 4 # columns
# AES can use 128, 192, or 256 bit cipher keys
# 16, 24, or 32 byte cipher keys
# Nk = 4, 6 or 8 [32-bit words] columns in cipher key
# Nr = max(Nb, Nk)... |
# coding: utf-8
"""
Looker API 3.0 Reference
### Authorization The Looker API uses Looker **API3** credentials for authorization and access control. Looker admins can create API3 credentials on Looker's **Admin/Users** page. Pass API3 credentials to the **/login** endpoint to obtain a temporary access_token.... |
# Copyright (c) 2021-2022, 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 ... |
# -*- coding: utf-8 -*-
"""
sphinx.builders.html
~~~~~~~~~~~~~~~~~~~~
Several HTML builders.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import sys
import zlib
import codecs
import posixpath
from os import path
from hashli... |
from rest_framework import serializers
from . import models
class HelloSerializer(serializers.Serializer):
"""Serializes a name field for testing our APIView"""
name = serializers.CharField(max_length=10)
class UserProfileSerializer(serializers.ModelSerializer):
"""Serializes a user profile objects"""
... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.16.14
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unitt... |
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import path,include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('',views.ind... |
import turtle
t = turtle.Turtle()
t.speed(10)
def sierpinski(length, n):
if n == 1:
draw_triangle(length)
else:
sierpinski(length, n-1)
t.rt(120)
t.fd(length * 2**(n-2))
sierpinski(length, n-1)
t.lt(120)
t.fd(length * 2**(n-2))
sierpinski(lengt... |
# Generated by Django 3.1.3 on 2020-11-07 18:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0006_auto_20201107_1742'),
]
operations = [
migrations.RenameModel(
old_name='MentorMe... |
#!/usr/bin/env python
# coding=utf-8
from sacred.host_info import (get_host_info, host_info_getter,
host_info_gatherers)
def test_get_host_info():
host_info = get_host_info()
assert isinstance(host_info['hostname'], str)
assert isinstance(host_info['cpu'], str)
assert is... |
from djmodels.db.models import CharField, Value as V
from djmodels.db.models.functions import Lower, StrIndex, Substr, Upper
from djmodels.test import TestCase
from ..models import Author
class SubstrTests(TestCase):
def test_basic(self):
Author.objects.create(name='John Smith', alias='smithj')
... |
#Award program
while True:
b_num = int(input("Enter number of B grades attained this year: "))
if b_num == 2:
print("You get a participation award.")
elif b_num == 3:
print("You get a credit award.")
elif b_num == 4:
print("You get a distinction award.")
elif b_num... |
#!/usr/bin/python3
#
# Antes de usar, execute o seguinte comando para evitar que o Linux feche
# as conexões TCP abertas por este programa:
#
# sudo iptables -I OUTPUT -p tcp --tcp-flags RST RST -j DROP
#
import asyncio
import socket
import os
import sys
import queue
import struct
import time
import signal
FLAGS_F... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import torch
from .base_grad_scaler import BaseGradScaler
__all__ = ['DynamicGradScaler']
class DynamicGradScaler(BaseGradScaler):
def __init__(self,
initial_scale: int = 2**16,
growth_factor: int = 2,
backoff_fa... |
import os
import sys
from multiprocessing.context import SpawnProcess
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from dirty_equals import IsStr
from watchfiles import arun_process, run_process
from watchfiles.main import Change
from watchfiles.run import detect_target_type, import_string,... |
import csv
import os
directory = "priced dir/"
files = os.listdir(directory)
full = []
for file in files:
csv_file = open(directory + file, encoding='utf-8')
csv_reader = csv.reader(csv_file)
for row in csv_reader:
if len(row) == 0:
continue
full.append(row)
csv_file.close(... |
"""
Support for the Swedish weather institute weather service.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/weather.smhi/
"""
import asyncio
from datetime import timedelta
import logging
from typing import Dict, List
import aiohttp
import async_timeout
... |
"""Create machine learning training data from satellite imagery and OpenStreetMap"""
import sys
import argparse
import logging
import json
from os import makedirs, path as op
from cerberus import Validator
from shapely.geometry import MultiPolygon, Polygon
from label_maker.version import __version__
from label_maker... |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2022 The HuggingFace Team 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-... |
from pprint import pformat, pprint
class Pattern(list):
def __init__(self, tracks=[], resolution=220, format=1):
self.format = format
self.resolution = resolution
super(Pattern, self).__init__(tracks)
def __repr__(self):
return "midi.Pattern(format=%s, resolution=%s, tracks=\\\... |
import os
from dotenv import load_dotenv
from logbook import Logger
from slack import WebClient
from textblob import TextBlob
from textblob.exceptions import TranslatorError
from telegram.ext import CommandHandler, ConversationHandler, MessageHandler, Filters
from pdf_bot.constants import TEXT_FILTER
from pdf_bot.uti... |
''' Modifying and extending Named Tuples
Named tuples are immutable
How we can change values inside the tuple
Just like with strings, we have to create a new tuple, with the modified values
Point2D = namedtuple('Point2D', 'x y'
''' |
"""
Django settings for project_crypto project.
Generated by 'django-admin startproject' using Django 3.1.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from ... |
import scipy as sp
import numpy as np
def compute_perm_amg(parents):
"""
Return a list of indices to reorder the adjacency and data matrices so
that the union of two neighbors from layer to layer forms a binary tree.
"""
# Order of last layer is random (chosen by the clustering algorithm).
ind... |
import docopt
import inspect
class NoDocExist(Exception):
pass
class ArgumentRequired(Exception):
pass
class NoExistCommand(Exception):
def __init__(self, command, supercommand):
super().__init__("No Exist Command: %s" % command)
self.command = command
self.su... |
# **********************************************************************************************************************
#
# brief: script to preprocess the data
#
# author: Lukas Reithmeier
# date: 09.07.2020
#
# *************************************************************************************************... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import os
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorCollection, AsyncIOMotorDatabase
from pymongo import ASCENDING, IndexModel
from quart.local import LocalProxy
__all__ = ["mongo_client", "db",
"anime_collection",
"url_pool_collection",
"source_index_collection"... |
import railrl.misc.hyperparameter as hyp
from multiworld.envs.mujoco.cameras import sawyer_xyz_reacher_camera_v0
from multiworld.envs.mujoco.sawyer_xyz.sawyer_reach import SawyerReachXYEnv
from railrl.launchers.launcher_util import run_experiment
from railrl.torch.grill.launcher import grill_her_td3_full_experiment
fro... |
from flask import Flask, jsonify, request
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity
)
app = Flask(__name__)
# Setup the Flask-JWT-Extended extension
app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this!
jwt = JWTManager(app)
# Provide a method t... |
"""Common code for converting proto to other formats, such as JSON."""
import base64
import collections
import json
from protorpc import messages
from protorpc import protojson
from apitools.base.py import exceptions
__all__ = [
'CopyProtoMessage',
'JsonToMessage',
'MessageToJson',
'DictToMessage',... |
#
# Copyright (c) 2019 UAVCAN Development Team
# This software is distributed under the terms of the MIT License.
# Author: Pavel Kirienko <pavel.kirienko@zubax.com>
#
r"""
Submodule import policy
+++++++++++++++++++++++
The following submodules are auto-imported when the root module ``pyuavcan`` is imported:
- :mod... |
from django.db import connection
from django.urls import reverse
from django.utils import timezone
from django_filters import rest_framework as filters
from rest_framework import generics, status
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import FormParser, JSONParser, MultiPartPa... |
'''Toto uses the following error codes internally:
* ``ERROR_SERVER = 1000``
* ``ERROR_MISSING_METHOD = 1002``
* ``ERROR_MISSING_PARAMS = 1003``
* ``ERROR_NOT_AUTHORIZED = 1004``
* ``ERROR_USER_NOT_FOUND = 1005``
* ``ERROR_USER_ID_EXISTS = 1006``
* ``ERROR_INVALID_SESSION_ID = 1007``
* ``ERROR_INVALID_... |
import multiprocessing
from RLToolbox.toolbox.common.utils import *
import gym
import time
from random import randint
import cv2
class Actor(multiprocessing.Process):
def __init__(self, args, task_q, result_q, actor_id, monitor, pms, net_class):
multiprocessing.Process.__init__(self)
self.actor_id... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Creates an elasticsearch index with denormalized article data coming from GraphDB
Usage:
> python -m hello-scigraph.loadElastic
"""
from __future__ import print_function
import json, sys, time
from rdflib.plugins.stores.sparqlstore import SPARQLStore
from rdflib impor... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
fro... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 31 14:08:54 2021
@author: robin grapin
"""
import numpy as np
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.core.problem import Problem, ElementwiseProblem
from pymoo.optimize import minimize
from pymoo.factory import get_performance_indicator
from smt.applic... |
import logging
from dask_sql.datacontainer import DataContainer
from dask_sql.java import org
from dask_sql.physical.rel.base import BaseRelPlugin
from dask_sql.utils import convert_sql_kwargs, import_class
logger = logging.getLogger(__name__)
class CreateModelPlugin(BaseRelPlugin):
"""
Create and train a m... |
"""
URL routing schema for {{ cookiecutter.application_name }}.
"""
from django.urls import path
from . import views
app_name = "{{ cookiecutter.application_slug }}"
urlpatterns = [
path('example', views.example, name='example'),
]
|
import pandas as pd
def LongitudinalSpec(index, date, outcome):
'The index, timestamp, and outcome column names of a longitudinal dataset.'
return {'index': index, 'date': date, 'outcome': outcome}
def AlignmentSpec(index, time, date, baseline):
'The date and baseline column names used to align longitud... |
#!/usr/bin/env python
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fi... |
import env
import pymongo
import time
import mysql.connector
from queries import nodes, subs, groups, calls, replication
'''
This is the main Tetra polling module
Each query is split in to separate modules that are imported as above
'''
def connectMongoDB() -> pymongo.MongoClient:
'''
Connects to MongoDB... |
# -*- coding: utf-8 -*-
"""The module of methods that calculate statistics related to model
performance.
Authors:
Fangzhou Li - fzli@ucdavis.edu
"""
from typing import Union
from scipy.spatial import distance_matrix
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from sklearn.metrics impo... |
# Generated by Django 2.2.10 on 2021-05-06 08:28
import ckeditor_uploader.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
"""
New(0721) try adding GPU agents
NOTE(0714) My attempt at making a simpler version of a multi-task trainer that
handles EnvRunner, ReplayBuffer, and the Agent Update with a slightly more
flattened logic.
Big credit to Stephen's MultiTaskQAttention for great reference
"""
import os
import time
import copy
import wa... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import time
import visa
rm=visa.ResourceManager()
li=rm.list_resources()
for index in range(len(li)):
print(str(index)+" - "+li[index])
choice = input("Which device?: ")
vi=rm.open_resource(li[int(choice)])
print(vi.query("*idn?"))
vi.write("outp on")
vi.write("inst first")
for lev in range(100):
cmd = "volt ... |
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
... |
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import keras
from keras.layers import *
from keras.models import *
from tensorflow.keras.optimizers import *
from keras.utils.vis_utils import *
from keras.preprocessing.image import *
from keras.preprocessing impor... |
import ray
from ray.rllib.agents.ppo import PPOTrainer
from ray.rllib.agents.dqn import DQNTrainer
from rlcard.rllib_utils.model import ParametricActionsModel
from ray.rllib.models import ModelCatalog
from rlcard.rllib_utils.rlcard_wrapper import RLCardWrapper
from ray.tune.registry import register_env
import time
... |
import pandas as pd
import numpy as np
import tkinter as tk
from tkinter import filedialog
import matplotlib.pyplot as plt
import os
"quick plot of IR spectra from the Bruker IR"
colnames = ['Wavenumber', 'Intensity']
export_me = False
# Select the rest
root = tk.Tk()
root.withdraw()
file_path1 = filedialog.askopenf... |
__author__ = 'patras'
from domain_searchAndRescue import *
from timer import DURATION
from state import state
def GetCostOfMove(r, l1, l2, dist):
return dist
DURATION.COUNTER = {
'giveSupportToPerson': 15,
'clearLocation': 5,
'inspectPerson': 20,
'moveEuclidean': GetCostOfMove,
'moveCurved': G... |
from django import template
from taxonomy.inline_templates import FlatTreeRenderer, StackTreeRenderer
from django.utils.safestring import mark_safe
register = template.Library()
# https://css-tricks.com/scale-svg/
class StackedTreeRendererNode(template.Node):
def __init__(self, tree_data, x_space, data_height):
... |
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2016-2018 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to dea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# {{ cookiecutter.project_slug }} documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values a... |
#! /usr/bin/env python3
# importing modules
import time
import datetime
import requests
import json
import pandas as pd
import praw
import re
# set datetime string pattern
# limit_date below will need to match this format
# CHANGE VALUE HERE
date_pattern = '%Y-%m-%d %H:%M:%S' # == YYYY-MM-DD HH:MM:SS
# date limit fo... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import unittest
from copy import deepcopy
import torch
from pytorchvideo.layers.accelerator.mobile_cpu.fully_connected import FullyConnected
from pytorchvideo.layers.accelerator.mobile_cpu.pool import (
AdaptiveAvgPool2d,
A... |
prefixes = ["[s]", "s.", "self."]
def Prefix(quote = None):
if not quote:
quote = '"'
pPrefix = ""
for prefix in prefixes:
pPrefix += ("{}".format(quote)+prefix+"{}".format(quote)+", ")
pPrefix = pPrefix[:-2]
return pPrefix |
# !user/bin/env python3
# -*- coding: utf-8 -*-
# Author: ChaoqiYin
class BaseField(object):
def __init__(self, index, datetime_format=None, col_name=None, converter=None):
'''
init
:param index: 解析列对应位置,从0开始
:param datetime_format: 字符串/datetime互相转换的模板,导入时不满足会计入错误
:param co... |
_base_ = [
'../_base_/models/swin_unet_v2_gtv12.py', '../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
model = dict(
backbone=dict(
embed_dim=96,
depths=[2, 2, 6, 2],
num_heads=[3, 6, 12, 24],
window_size=7,
ape=F... |
"""Rename product_id to product_ref_id.
Revision ID: 709452f38a5c
Revises: 7093ca478d35
Create Date: 2016-06-27 13:10:00
"""
# revision identifiers, used by Alembic.
revision = '709452f38a5c'
down_revision = '7093ca478d35'
MYSQL_CHARSET = 'utf8'
from alembic import op
import sqlalchemy as sa
def upgrade():
""... |
from PyQt5.QtMultimedia import QMediaPlayer, QMediaPlaylist, QMediaContent
from PyQt5 import QtCore
class AudioPlayer(QMediaPlayer):
def __init__(self, data_handler):
super().__init__(flags=QMediaPlayer.VideoSurface)
self.data_handler = data_handler
self.playlist = QMediaPlaylist()
... |
import pytest
from validate import check_query_f
# Mark that all tests in this module can be run as server upgrade tests
pytestmark = pytest.mark.allow_server_upgrade_test
usefixtures = pytest.mark.usefixtures
@pytest.mark.parametrize("transport", ['http', 'websocket'])
@usefixtures('per_class_tests_db_state')
class... |
import logging
from flask_restful import Resource, request
from .eli5c_qa_model import ELI5cQAModel
from .validate_json import validate_json
model_instance = ELI5cQAModel()
logging.info('ELI5C Model Resource Loaded.')
model_schema = {
'type': 'object',
'properties': {
'name': {'type': 'string'}
... |
import warnings
import torch
import numpy as np
from typing import Any, List, Optional, Tuple
try:
# Check replay buffer fits in memory, if possible
import psutil
except ImportError:
psutil = None
class ReplayBuffer:
def __init__(
self,
n_state: int,
n_action: int,
s... |
def primeCheck(number):
prime = True
for i in range(2, int(number**(0.5)+1), 2):
if i != 2:
i = i - 1
if number % i == 0:
prime = False
break
return prime
def main():
print(primeCheck(37))
print(primeCheck(100))
print(primeCheck(77))
if __nam... |
from prettytable import PrettyTable
# from models.pointnet.src.models.pointnet2_segmentation import Net
from models.pointnet.src.models.pointnet2_regression_v2 import Net
def count_parameters(model):
table = PrettyTable(["Modules", "Parameters"])
total_params = 0
for name, parameter in model.named_paramete... |
#!/usr/bin/env python3
# Copyright (c) 2017 The TMIcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""An example functional test
The module-level docstring should include a high-level description of
what the t... |
from mapentity import views as mapentity_views
from geotrek.authent.decorators import same_structure_required
from georiviere.studies.filters import StudyFilterSet
from georiviere.studies.forms import StudyForm
from georiviere.studies.models import Study
class StudyList(mapentity_views.MapEntityList):
model = St... |
# -*- coding: utf-8 -*-
'''
# Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
#
# This file was generated and any changes will be overwritten.
'''
from __future__ import unicode_literals
from ..one_drive_object_bas... |
from time import sleep
def maior(* vls):
mvalor = i = 0
print('-='*20)
print('Analisando os valores passados...')
for c in vls:
print(c, end=' ')
sleep(0.5)
i += 1
if i == 0:
mvalor = c
else:
if c > mvalor:
mvalor = c
pr... |
from emlp.nn import MLP,EMLP,MLPH,EMLPH
from emlp.groups import SO2eR3,O2eR3,DkeR3,Trivial
from emlp.reps import Scalar
from trainer.hamiltonian_dynamics import IntegratedDynamicsTrainer,DoubleSpringPendulum,hnn_trial
from torch.utils.data import DataLoader
from oil.utils.utils import cosLr,FixedNumpySeed,FixedPytorchS... |
# coding: utf-8
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import re # noqa: F401
import sys # noqa: F401
import nulltype # ... |
# coding=utf-8
__author__ = "Dimitrios Karkalousos"
import argparse
import gc
import pathlib
import sys
import time
from collections import defaultdict
from typing import Dict
import numpy as np
import torch
from torch.utils.data import DataLoader
from mridc import save_reconstructions, complex_mul, complex_conj, if... |
from gaphor.UML.usecases.actor import ActorItem
from gaphor.UML.usecases.extend import ExtendItem
from gaphor.UML.usecases.include import IncludeItem
from gaphor.UML.usecases.usecase import UseCaseItem
from gaphor.UML.usecases import usecaseconnect
__all__ = ["ActorItem", "ExtendItem", "IncludeItem", "UseCaseItem"]
|
from unittest import TestCase
import pandas as pd
from scattertext import whitespace_nlp, CorpusFromParsedDocuments
from scattertext.test.test_corpusFromPandas import get_docs_categories
class TestParsedCorpus(TestCase):
@classmethod
def setUp(cls):
cls.categories, cls.documents = get_docs_categories()
cls.pa... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2020 all rights reserved
def test():
"""
Exercise the simplest non-trivial use case
"""
# get the journal
import journal
# make a channel
channel = journal.debug(name="test.j... |
######################
# Description:
# Simple controller that invokes commands.
######################
from itertools import chain
from types import StringTypes
from wanderu.commander import modutils
class Controller(object):
def __init__(self, pkg):
"""
pkg: The name of the package under which ... |
import base64
# TODO: These tests should be merged with python/ql/test/experimental/dataflow/tainttracking/defaultAdditionalTaintStep-py3/test_string.py
base64.a85encode(bs) # $ encodeInput=bs encodeOutput=Attribute() encodeFormat=Ascii85
base64.b85encode(bs)# $ encodeInput=bs encodeOutput=Attribute() encodeFormat=Bas... |
import os
SECRETS_DIR = "/var/openfaas/secrets/"
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
dir_contents = os.listdir(SECRETS_DIR)
print(dir_contents)
with open(SECRETS_DIR+"my-new-secret") as fptr:
print(fptr.read())
return dir_co... |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import sys
# Constants for energy binning
a0 = -0.8400
a1 = 0.1200
# Cross section factor for formula strength = xsec*factor/Egamma
xsec_factor = 8.68e-8
strengthfile = open('strength.nrm', 'r')
strengthlines = strengthfile.readlin... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import mock
from pyramid import httpexceptions
import pytest
from h.admin.views import admins as views
@pytest.mark.usefixtures('routes')
class TestAdminsIndex(object):
def test_when_no_admins(self, pyramid_request):
result = views.admins_... |
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import scoped_session, sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///habilidades.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(autoc... |
from __future__ import absolute_import, division, print_function
class reader:
"""A class to read the CBF files used in DIALS"""
def read_file(self, filename):
"""Read the CBF file"""
import pycbf
self.cbf_handle = pycbf.cbf_handle_struct()
self.cbf_handle.read_file(filename,... |
from pathlib import Path
import re
import typing
def parse(filename: str, protocol: str) -> typing.Set[str]:
"""Parse the roles for the specified 'protocol' found in the
Scribble specification in the specified 'filename'."""
# TODO: get these by calling NuScr with --enum flag?? Same result but no regexp.... |
def filter_weblog_by_dates(weblog,start,end,timestamp_column):
return weblog[(weblog[timestamp_column]>start)&(weblog[timestamp_column]<end)];
|
# coding: utf-8
""" Wrapper around SciPy DOPRI853 integrator. """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Third-party
from scipy.integrate import ode
# Project
from ..core import Integrator
from ..timespec import parse_time_specification
__all__ = ["DOPRI853... |
#!/usr/bin/env python
import re
from keyword import kwlist
from google.protobuf.internal.enum_type_wrapper import EnumTypeWrapper
from csgo import common_enums
kwlist = set(kwlist + ['None'])
_proto_modules = ['gcsystemmsgs_pb2',
'gcsdk_gcmessages_pb2',
'cstrike15_gcmessages_pb2',... |
num = 10
if not type(num) is int:
raise Exception("Valor não permitido")
else:
print("NUM") |
"""users personality
Revision ID: 7cfd2c17be9f
Revises: b5a34b10d18c
Create Date: 2018-05-21 09:53:28.454538
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7cfd2c17be9f'
down_revision = 'b5a34b10d18c'
branch_labels = None
depends_on = None
def upgrade():
... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from fuji_server.models.base_model_ import Model
from fuji_server import util
class FAIRResultEvaluationCriterium(Model):
"""NOTE: This class is auto generated by... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import warnings
import torch
from botorch import fit_gpytorch_model
from botorch.exceptions.errors ... |
import diamond
def test_a():
assert diamond.Diamond('A').print_diamond() == "A"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.