content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from __future__ import unicode_literals
import logging
from inspect import ismethod
from django.core.urlresolvers import (reverse, resolve, NoReverseMatch,
Resolver404)
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.encoding i... | python |
from sklearn.model_selection import GridSearchCV
from luciferml.supervised import classification as cls
def hyperTune(classifier, parameters, X_train, y_train, cv_folds, tune_mode, isReg):
"""
Takes classifier, tune-parameters, Training Data and no. of folds as input and Performs GridSearch Crossvalidation.
... | python |
import os.path
import logging
from utils import make_id, get_resource
from os.path import join
logger = logging.getLogger(__name__)
def apps_dir():
return os.path.dirname(os.path.abspath(__file__))
def load_app(app_def_file, app_id=None, parent_group="/"):
"""Loads an app definition from a json file and s... | python |
from abc import ABCMeta
import numpy as np
from torch.utils.data import ConcatDataset, Dataset, WeightedRandomSampler
from mmpose.datasets.builder import DATASETS
from .mesh_base_dataset import MeshBaseDataset
@DATASETS.register_module()
class MeshMixDataset(Dataset, metaclass=ABCMeta):
"""Mix Dataset for 3D hu... | python |
# coding: utf-8
# pylint: disable=missing-docstring
# pylint: disable=invalid-name
import os
import glob
import subprocess
from setuptools import setup, find_packages
about = {}
HERE = os.path.abspath(os.path.dirname(__file__))
with open(file=os.path.join(HERE, 'src','dima', '__version__.py'), mode='r', encoding='u... | python |
import logging
from os.path import expanduser
from git import InvalidGitRepositoryError
from pythoncommons.file_utils import FileUtils
from pythoncommons.git_wrapper import GitWrapper
LOG = logging.getLogger(__name__)
class FormatPatchSaver:
"""
A class used to export git-format-patch files from a git repo... | python |
"""Test the Cloudflare config flow."""
from pycfdns.exceptions import (
CloudflareAuthenticationException,
CloudflareConnectionException,
CloudflareZoneException,
)
from homeassistant.components.cloudflare.const import CONF_RECORDS, DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, SOURCE_USER... | python |
#!/usr/bin/env python
# Requires metasploit, snmpwalk, snmpstat and John the Ripper
# _____ _ ____ _______ ____ __
# / ___// | / / |/ / __ \ / __ )_______ __/ /____
# \__ \/ |/ / /|_/ / /_/ / / __ / ___/ / / / __/ _ \
# ___/ / /| / / / / ____/ / /_/ / / / /_/ / /_/ __/
#/____/_/ |_/_... | python |
nasc = int(input('Ano de nascimento: '))
idade = 2018 - nasc
if idade <= 9:
print('Categoria: Mirim')
elif idade <= 14:
print('Categoria: Infantil')
elif idade <= 19:
print('Categoria: Júnior')
elif idade <= 20:
print('Categoria: Sênior')
elif idade >= 21:
print('Categoria: Master') | python |
#!/usr/bin/env python
# coding:utf-8
"""
Test functionality of Service elements.
"""
# -- standard library ---------------------------------------------------------
from cgi import parse_header, FieldStorage
from threading import Thread
import unittest
import tempfile
import zipfile
import socket
import json
import s... | python |
import unittest
from PySide2.QtWidgets import *
from qtimgren.main_window import MainWindow
from unittest.mock import Mock, patch
import qtimgren.main_window
import qtimgren.about
import qtimgren.profile
import qtimgren.profiles
class TestMainWindow(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None... | python |
from airflow.plugins_manager import AirflowPlugin
from freshdesk_plugin.operators.freshdesk_to_s3_operator import FreshdeskToS3Operator
class freshdesk_plugin(AirflowPlugin):
name = "freskdesk_plugin"
operators = [FreshdeskToS3Operator]
hooks = []
# Leave in for explicitness
executors = []
mac... | python |
import numpy as np
import random
import matplotlib.pyplot as plt
from collections import deque
class UniformNoise(object):
def __init__(self, action_space, initial_exploration = 0.99, final_exploration = 0.05, decay_rate = 0.999):
self.action_dim = action_space.shape[0] # Requires Space with... | python |
# These dictionaries are applied to the generated attributes dictionary at build time
# Any changes to the API should be made here. attributes.py is code generated
# We are not code genning attributes that have been marked as obsolete prior to the initial
# Python API bindings release
attributes_codegen_method = {
... | python |
from Components.Sources.Source import Source
from Components.Network import iNetwork
from Tools.Directories import fileExists
from twisted import version
from socket import has_ipv6, AF_INET6, inet_ntop, inet_pton
def normalize_ipv6(orig):
net = []
if '/' in orig:
net = orig.split('/')
if net[1] == "128":
d... | python |
from services.lib.config import Config
from services.lib.db import DB
from localization.base import BaseLocalization
from localization.eng import EnglishLocalization
from localization.rus import RussianLocalization
from services.lib.utils import Singleton
class LocalizationManager(metaclass=Singleton):
def __init... | python |
import cv2
import numpy as np
img = cv2.imread("Resources/lena.png")
kernel = np.ones((5,5),np.uint8)
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(7,7),0)
imgCanny = cv2.Canny(img,150,200)
imgDialation = cv2.dilate(imgCanny,kernel,iterations=1)
imgEroded = cv2.erode(img... | python |
from __future__ import annotations
from collections import defaultdict
from typing import Any, Dict, Optional, Tuple
from .fields import Field, ModelField
from .validation import Validation
class ModelBase:
__slots__ = ()
def __init__(self):
pass
@classmethod
def get_xmltag(cls) -> str:
... | python |
"""Extension for using climatecontrol with dataclasses."""
from dataclasses import is_dataclass
from typing import Generic, Mapping, Type, TypeVar
import dacite
from climatecontrol.core import Climate as BaseClimate
from climatecontrol.core import SettingsItem as BaseSettingsItem
from climatecontrol.fragment import ... | python |
from flask import Blueprint, request, Response, json
from main.models import database
import csv
mypage_page = Blueprint('mypage', __name__)
def read_csv(user_id):
file = csv.reader(open('../main/recommendation/recommend_list/{}.csv'.format(user_id), 'r',encoding='utf-8'))
lists = []
for row in file:
... | python |
# Imports
import numpy as np
import matplotlib.pyplot as plt
import os
# Results directory
directory = os.path.join("results", "cbis", "history")
figs_directory = os.path.join("results", "cbis", "figures")
# Models
MODELS = ["densenet121", "resnet50", "vgg16"]
# Training Formats
TRAINING_MODE = ["baseline", "basel... | python |
import scapy.all as scapy
import time
import termcolor
class ConnectToTarget:
def spoof(self,router_ip,target_ip,router_mac,target_mac ):
packet1=scapy.ARP(op=2, hwdst=router_mac,pdst=router_ip, psrc=target_ip)
packet2=scapy.ARP(op=2, hwdst=target_mac,pdst=target_ip, psrc=router_ip)
scapy.send(packet1)
scap... | python |
"""Test stack
"""
import ARgorithmToolkit
algo = ARgorithmToolkit.StateSet()
stack = ARgorithmToolkit.Stack("st",algo)
def test_declare():
"""Test stack creation
"""
last_state = algo.states[-1]
assert last_state.content["state_type"] == "stack_declare"
def test_operations():
"""Test stack operat... | python |
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2017, Johannes Köster"
__email__ = "johannes.koester@tu-dortmund.de"
__license__ = "MIT"
import os
import re
import shutil
import subprocess as sp
from datetime import datetime
import time
from snakemake.remote import AbstractRemoteObject, AbstractRemoteProvid... | python |
import os
import os.path
import json
import numpy as np
import sys
import itertools
import random
import argparse
import csv
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UTILS_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'utils'))
sys.path.append(UTILS_DIR)
sys.path.append(BASE_DIR)
# sys.path.insert(1... | python |
import unittest
from Calculator import Calculator
from CsvReader.CSVReader import CsvReader
class MyTestCase(unittest.TestCase):
def test_instantiate_calculator(self):
calculator = Calculator()
self.assertIsInstance(calculator, Calculator)
def test_addition_method(self):
calculator =... | python |
import numpy as np
import pandas as pd
import xarray as xr
import cubepy
from pyplan_engine.classes.evaluators.BaseEvaluator import BaseEvaluator
from pyplan_engine.classes.evaluators.CubepyEvaluator import CubepyEvaluator
from pyplan_engine.classes.evaluators.IPythonEvaluator import IPythonEvaluator
from pyplan_engine... | python |
#! /usr/bin/env python
# $Id: test_class.py 5174 2007-05-31 00:01:52Z wiemann $
# Author: Lea Wiemann <LeWiemann@gmail.com>
# Copyright: This module has been placed in the public domain.
"""
Tests for the 'class' directive.
"""
from __init__ import DocutilsTestSupport
def suite():
s = DocutilsTestSupport.Parser... | python |
# coding:utf-8
# 将图片以小分片的形式裁剪下来
import tkFileDialog
import cv2
from configurationInjection import configInjection
import os
config = configInjection()
config.loadConfiguration()
rois = config.rois[0]
flag = True
videopath = tkFileDialog.askopenfilename(initialdir="/home/zb/myfile/cutSave")
count = 0
cap = cv2.VideoC... | python |
# -*- coding: utf-8 -*-
"""form base classes for aloha-editor integration"""
import floppyforms as forms
from djaloha.widgets import AlohaInput
from django.utils.encoding import smart_unicode
class DjalohaForm(forms.Form):
"""Base class for form with aloha editor"""
def __init__(self, model_class, lookup, ... | python |
"""Replays
RocketLeagueReplays API module
"""
import requests
BASE_URL = 'https://www.rocketleaguereplays.com/api/replays/?page='
def get_replays(page_num):
"""
Requests a page of replay data from the RocketLeagueReplaysAPI
:param page_num: Page number to request
:return: list of matches returned
... | python |
# -*- coding: utf-8 -*-
import urwid
PALETTE = [
('red', 'dark red', ''),
('selectedred', 'dark red', 'yellow'),
('selected', '', 'yellow'),
]
# Modify these as needed
SIZES = {'small': (4, 3), 'medium': (6, 4), 'large': (8, 6)}
card_size = 'large'
class BaseCardWidget(urwid.WidgetWrap):
def __init... | python |
# coding: utf-8
"""
ELEMENTS API
The version of the OpenAPI document: 2
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from elements_sdk.configuration import Configuration
class TapeFile(object):
"""NOTE: This class is auto generated by OpenAPI ... | python |
from unittest import mock
from django import forms
from django.test import SimpleTestCase
from django.utils.functional import lazy
from phonenumber_field.formfields import PhoneNumberField
ALGERIAN_PHONE_NUMBER = "+213799136332"
class PhoneNumberFormFieldTest(SimpleTestCase):
def test_error_message(self):
... | python |
from pkg.command.azcli_cmd import AzCliCommand
from pkg.entity._az_cli import AzCli
from pkg.executor._executor import Executor
from pkg.executor.azcli.command._azcli_cmd_executor import AzCliCommandExecutor
class AzCliExecutor(Executor):
def __init__(self):
pass
def run_az_cli(self, cmd: AzCli):
... | python |
from logging import captureWarnings
from operator import inv
from typing import Container, Iterable, Union
import uuid
import time
import math
from datetime import datetime, timedelta, timezone
from unittest import TestCase
from unittest.mock import patch, MagicMock, ANY, call
from botocore.exceptions import ClientErr... | python |
import datetime
import dateutil.parser
import pytz
from django.conf import settings
from django.db.models import F, Q
from django.http import (
Http404, HttpResponseBadRequest, HttpResponseRedirect, JsonResponse,
)
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils imp... | python |
from invoke import task
from os.path import join, exists
from os import makedirs
from shutil import copy, rmtree
from subprocess import run
from tasks.util.env import (
BIN_DIR,
GLOBAL_BIN_DIR,
KUBECTL_BIN,
AZURE_RESOURCE_GROUP,
AZURE_VM_SIZE,
AKS_CLUSTER_NODE_COUNT,
AKS_CLUSTER_NAME,
)
fro... | python |
import sys
class ModelSearchCriteria:
def __init__(self, datatable_names: [str], column_names: [str], search_text: str ):
self.datatable_names = datatable_names
self.column_names = column_names
self.search_text = search_text
| python |
#!/usr/bin/python
# -*- coding: utf_8 -*-
"""Access and query Twitter's API with the simplistic twitter package (`pip install twitter`).
"""
from __future__ import print_function
from __future__ import unicode_literals
import csv
import os
import time
from twitter import OAuth
from twitter import Twitter
def setup... | python |
import jieba
import jieba.analyse
from gensim.test.utils import get_tmpfile
import gensim.models.word2vec as word2vec
from path import Path
import argparse
from utils import readlines,SeqSubSeq,toarry
#文件位置需要改为自己的存放路径
#将文本分词
parser = argparse.ArgumentParser(description="precess tree file to a doc")
parser.add_argume... | python |
"""functions for working with tensorboard"""
from pathlib import Path
import pandas as pd
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
def logdir2df(logdir):
"""convert tensorboard events files in a logs directory into a pandas DataFrame
events files are created by Sum... | python |
import json
import logging
import os
from datetime import datetime
def coco_evaluation(dataset, predictions, output_dir, iteration=None):
coco_results = []
for i, prediction in enumerate(predictions):
img_info = dataset.get_img_info(i)
prediction = prediction.resize((img_info['width'], img_inf... | python |
from snovault import upgrade_step
@upgrade_step('suspension', '1', '2')
def suspension_1_2(value, system):
if 'biosample_ontology' in value:
del value['biosample_ontology']
@upgrade_step('suspension', '2', '3')
def suspension_2_3(value, system):
if 'url' in value:
value['urls'] = [value['url']]
del value['ur... | python |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase, override_settings
from django.views.generic import CreateView, UpdateView, DeleteView, DetailView
class CreateUserView(CreateView):
... | python |
"""
This set of functions is for analyzing all the articles in the PLOS corpus. A Jupyter Notebook is provided with
examples of analysis. It can:
* compare the articles indexed in Solr, PMC, and article pages
* spot-check individual JATS fields for irregularities
* create summaries of articles by type, publ... | python |
import json
import jk_json
import jk_typing
import jk_prettyprintobj
from thaniya_common.cfg import CfgKeyValueDefinition
from thaniya_common.cfg import AbstractCfgComponent
from .BackupVolumeID import BackupVolumeID
class _Magic(AbstractCfgComponent):
MAGIC = "thaniya-volume-cfg"
__VALID_KEYS = [
Cf... | python |
import os
from threading import Thread
from sh import tail
from pymouse import PyMouse
from datetime import datetime, timedelta
import subprocess
WAS_MOVED_SCATTER = 0
# in seconds
SHORT_PRESS = .15
MEDIUM_PRESS = .4
LONG_PRESS = .6
VERY_LONG_PRESS = 1
SCROLL_SENSITIVITY = 10
MOVE_SENSITIVITY = .8
MOVE_SCALING = 1.... | python |
#Write a Python program to add leading zeroes to a string.
string = '5699'
print()
print(string.ljust(7, '0')) | python |
from django.apps import AppConfig
class DbSearchConfig(AppConfig):
name = 'db_search'
| python |
import os
import shutil
import unittest
import pandas as pd
from python_tools.workflow_tools.qc.fingerprinting import (
read_csv,
plot_genotyping_matrix
)
class FingerprintingTestCase(unittest.TestCase):
def setUp(self):
"""
Set some constants used for testing
:return:
"... | python |
#!/usr/bin/python3
# SPDX-License-Identifier: Apache-2.0
# Copyright © 2020 VMware, Inc.
import os
import sys
import subprocess
import time
import shutil
import configparser
import pytest
import collections
import unittest
networkd_unit_file_path = '/etc/systemd/network'
network_config_manager_ci_path = '/run/networ... | python |
from project.appliances.appliance import Appliance
class TV(Appliance):
def __init__(self):
self.cost = 1.5
super().__init__(self.cost)
| python |
# Copyright 2020 The TensorFlow Quantum 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 req... | python |
from importlib import import_module
from importlib import resources
PLUGINS = dict()
def register_plugin(func):
"""Decorator to register plug-ins"""
name = func.__name__
PLUGINS[name] = func
return func
def __getattr__(name):
"""Return a named plugin"""
try:
return PLUGINS[name]
e... | python |
# import os
# os.environ["KIVY_WINDOW"] = "sdl2"
# uncomment the above lines to run on raspberrypi like it runs on windows.
import kivy
kivy.require('1.9.1')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from time import sleep, time
from random import randint
from functo... | python |
import torch
import unseal.transformers_util as tutil
from unseal.hooks import HookedModel
def test_load_model():
model, tokenizer, config = tutil.load_from_pretrained('gpt2')
assert model is not None
assert tokenizer is not None
assert config is not None
def test_load_model_with_dir():
model, tok... | python |
import cv2
from image_manipulation import binarize_image, grayscale_image
class Camera(object):
"""
Class to take pictures.
:param width_size: camera's image width
:type width_size: int
:param height_size: camera's image height
:type height_size: int
:param input_cam_device: p... | python |
#Passing a List
def greet(names):
for name in names:
msg=f"Hello, {name.title()}"
print(msg)
username=['alice','beerus','cyrus']
greet(username) | python |
# coding:utf-8
# log utils
"""
切记: 不要重复创造日志对象,否则会重复打印
"""
# import os
from logging import (
handlers,
getLogger,)
from logging import Formatter as LoggingFormatter
from logging import StreamHandler as LoggingStreamHandler
from logging import FileHandler as LoggingFileHandler
from logging import ERROR as LOGG... | python |
# Adapted from https://github.com/openai/triton/blob/master/python/triton/ops/blocksparse/softmax.py
import triton.language as tl
import triton
import torch
from src.models.attention.blocksparse_utils import sparsify_broadcast_tensor
def next_power_of_2(n):
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
... | python |
import time
import rich
from hurry.filesize import size
from tabulate import tabulate
class Format:
def __init__(self):
pass
@staticmethod
def cli(**kwargs):
"""
Handle in coming CLI Output Style
"""
if "standard" in kwargs["style"]:
return Format._defa... | python |
#!/usr/bin/env python2.7
import os
import sys
sys.path.insert(0, os.path.realpath(os.path.join(__file__, '../../../lib')))
import exatest
from exatest.utils import chdir
from exatest import (
useData,
)
class TestParameterized(exatest.TestCase):
@useData((x,) for x in range(10))
def test_pa... | python |
import sys, getopt
import run
def main(argv):
path_database = ''
path_cnn_trained = ''
path_folder_retrieval = ''
feature_extraction_method = ''
distance = ''
searching_method = ''
number_of_images = 0
list_of_parameters = []
try:
opts, args = getopt.getopt(argv,"h... | python |
import sys
import torch
sys.path.insert(0, "../")
from linformer_pytorch import Linformer, Visualizer
model = Linformer(
input_size=512,
channels=16,
dim_k=128,
dim_ff=32,
nhead=4,
depth=3,
activation="relu",
checkpoint_level="C0",
parameter_shar... | python |
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l<=r:
m = (l+r)//2
if nums[m]==target:
return m
elif nums[m]>target:
r=m-1
... | python |
import heapq
import math
import numpy as np
import nltk.probability
from nltk.classify import SklearnClassifier
from sklearn.svm import SVC
import re
import sys
sys.path.insert(0, '..')
from definitions import *
sys.path.insert(0, '../Wrapper/')
from helper import *
def get_svm_classifier(parameters):
print "Loa... | python |
# 1-TASK. Matnlardan iborat ro'yxat qabul qilib, ro'yxatdagi har bir matnning birinchi
# harfini katta harfga o'zgatiruvchi funksiya yozing.
def katta_harf(ismlar):
names = []
for i in range(len(ismlar)):
ismlar[i] = ismlar[i].title()
ismlar = ['ali', 'vali', 'hasan', 'husan']
katta_harf(ismlar)
print(... | python |
import NNRequestHandler.Base
import NNRequestHandler.User
NN_REQUEST_CMD_USER_LOGIN = 1
class DispatchCenter(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(DispatchCenter, cls).__new__(
cls, *args... | python |
import unittest
from streamlink.plugins.canlitv import Canlitv, _m3u8_re
class TestPluginCanlitv(unittest.TestCase):
def test_m3u8_re(self):
def test_re(text):
m = _m3u8_re.search(text)
self.assertTrue(m and len(m.group("url")) > 0)
test_re('file: "test" ')
test_r... | python |
"""
Open Orchestrator Cloud Radio Access Network
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... | python |
from greent.rosetta import Rosetta
import json
from collections import defaultdict
def setup():
rosetta = Rosetta()
neodriver = rosetta.type_graph.driver;
return neodriver
def dumpem(dtype = 'gene'):
driver = setup()
cypher = f'MATCH (a:{dtype})-[r]-(b) return a,r,b'
with driver.session() as s... | python |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
GeometryWrapper
A QGIS plugin
Converts geometry longitude from [-180,180] to [0,360]
-------------------
begin : 2017-03-16
... | python |
# Generated by Django 3.0.5 on 2020-04-06 15:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shortner', '0002_auto_20200331_0717'),
]
operations = [
migrations.AlterModelOptions(
name='entry',
options={'verbose_name_p... | python |
from numpy import diff
def check_sorted(nu___):
di_ = diff(nu___.ravel())
return (di_ <= 0).all() or (0 <= di_).all()
| python |
'''VGG for CIFAR10. FC layers are removed.
(c) YANG, Wei
'''
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import math
import torch
__all__ = ['vgg19_bn_para']
class VGG(nn.Module):
def __init__(self, features, gpu_num = 2, num_classes=1000, split_size=64):
super(VGG, self).__init__()... | python |
# variants, kā importēt garākus nosaukumus
import mape.helper as helper
# importē konkrētu funkciju, tā it kā tā būtu lokāli definēta
#from helper import ievadiSkaitli
def main():
sk1 = helper.ievadiSkaitli()
sk2 = helper.ievadiSkaitli()
print("Ievadīto skaitļu summa ir", sk1 + sk2)
helper.pievienotF... | python |
import six
import time
from collections import defaultdict
import ujson as json
import pandas as pd
from oct.results.models import db, Result, Turret
class ReportResults(object):
"""Represent a report containing all tests results
:param int run_time: the run_time of the script
:param int interval: the ... | python |
# Code generated by `typeddictgen`. DO NOT EDIT.
"""V1SubjectRulesReviewStatusDict generated type."""
from typing import TypedDict, List
from kubernetes_typed.client import V1NonResourceRuleDict, V1ResourceRuleDict
V1SubjectRulesReviewStatusDict = TypedDict(
"V1SubjectRulesReviewStatusDict",
{
"evalua... | python |
# Copyright 2021 Xilinx 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 in writing,... | python |
import os
from abc import abstractmethod
from collections import defaultdict
import PIL
import cv2
import math
import numpy as np
import sldc
import torch
from PIL import Image
from cytomine.models import Annotation
from rasterio.features import rasterize
from shapely import wkt
from shapely.affinity import translate,... | python |
#
# Copyright (c) 2019 UCT Prague.
#
# ec5cbec43ec8_initial_layout.py is part of Invenio Explicit ACLs
# (see https://github.com/oarepo/invenio-explicit-acls).
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... | python |
from language_learner_env import secret_settings
import learner
app = learner.App(secret_settings)
app.listen()
| python |
from maya import cmds as mc
from maya.api import OpenMaya as om
from dcc.maya.libs import transformutils
from . import transformmixin
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
class ConstraintMixin(transformmixin.TransformMixin):
"""
Overload of Transf... | python |
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys
sys.path.append('../')
# End of fix
import numpy as np
from NiaPy.task import StoppingTask, OptimizationType
from NiaPy.algorithms import BasicStatistics
from NiaPy.algorithms.b... | python |
# Copyright (c) 2014-2017, iocage
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... | python |
"""Anvil is a tool for automating the rigging process in a given DCC."""
from six import itervalues
import config
import utils
import colors
import meta_data
import log
import version
import interfaces
import runtime
import objects
import grouping
import node_types
import sub_rig_templates
import rig_templates
class ... | python |
import numpy as np
import pandas as pd
import os
from transformers import AutoModel
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.pandas_parameter_type import PandasParameterType
from inference_schema.parameter_types.numpy_parameter_type import NumpyP... | python |
#!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... | python |
####################################################################################################
# ------------------------------------------------------------------------------------------------ #
# Functions for handling pool presence table analysis
# -------------------------------------------------------------... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import os
def join_images(images):
rows = len(images[0])
cols = len(images[0][0])
final_image = np.zeros((rows, cols, 1), np.uint8)
print(len(images))
for img in images:
for row in range(0, len(final_image)):
... | python |
_mod_txt = """
NEURON {
POINT_PROCESS ExpSynMorphforge
RANGE tau, e, i
NONSPECIFIC_CURRENT i
RANGE peak_conductance
}
UNITS {
(nA) = (nanoamp)
(mV) = (millivolt)
(uS) = (microsiemens)
}
PARAMETER {
tau = 0.1 (ms) <1e-9,1e9>
e = 0 (mV)
peak_conductance = -100000 ()
}
ASSIGNED {
v (mV)
i (nA)
... | python |
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | python |
# Copyright 2018 Braxton Mckee
#
# 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 t... | python |
#!/usr/bin/env python
"""
read ntuple produced by Truth_JETMET...
make some validation plots
"""
import ROOT
ROOT.gROOT.SetBatch()
from optparse import OptionParser
def make_plots(file_name, post_fix):
import AtlasStyle
f1 = ROOT.TFile.Open(file_name)
tree = f1.Get("physics")
h_m4l = ROOT.TH1F("h_m4l... | python |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
cd=os.path.join('LinearRegression','Kidem_ve_Maas_VeriSeti.csv')
dataset = pd.read_csv(cd)
print(dataset.describe())
x=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1].values
from sklearn.cross_validation import train_test_split
x_train,... | python |
#__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance ... | python |
__author__ = 'Jeremy'
| python |
#!/bin/false python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import os
import shutil
from BaseRunner import ... | python |
class Solution:
def intToRoman(self, num):
def get_representation(num):
symbol_table={
1:"I",
5:"V",
10:"X",
50:"L",
100:"C",
500:"D",
1000 :"M",
}
if num ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.