text stringlengths 2 999k |
|---|
"""
34. Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
""... |
from sys import (
platform,
)
from llvmlite import (
ir,
)
from imugi.compiler.types import (
char_pointer,
i64,
objc_ivar_list,
)
class ObjectiveCUtil(object):
@staticmethod
def get_objc_runtime_path() -> str:
if platform == 'darwin':
return '/usr/lib/libobjc.A.dylib... |
"""
https://leetcode.com/problems/word-break/
"""
from functools import lru_cache
def solve(s: str, word_list: list[str]):
n = len(s)
words = set(word_list)
chars = set("".join(words))
for c in s:
if c not in chars:
return False
@lru_cache(maxsize=None)
def dp(i, j):
... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... |
from imagepy.core.engine import dataio
from sciapp import Source
def read(path):
with open(path) as f: return f.read()
Source.manager('reader').add('md', read, 'md')
class Plugin(dataio.Reader):
title = 'MarkDown Open'
tag = 'md'
filt = ['MD'] |
"""
Train SNGAN
"""
import torch
from torchvision.utils import save_image
import numpy as np
import os
import timeit
from metrics.Inception_Score import inception_score
from torch.utils.tensorboard import SummaryWriter
import gc
from utils import IMGs_dataset
NC=3
IMG_SIZE=64
NFAKE_IS_TRAIN = 10000
BATCH_SIZE_IS_TR... |
from datetime import datetime, date, timedelta
from django.conf import settings
from django.db.models import Count, F
import cronjobs
from kitsune.customercare.models import Reply
from kitsune.dashboards import LAST_90_DAYS
from kitsune.dashboards.models import WikiDocumentVisits
from kitsune.kpi.models import (
... |
import logging
import abc
import time
import copy
import numpy as np
import pandas as pd
from multiprocessing.pool import ThreadPool
from scipy.optimize import fmin_slsqp
import matplotlib.pyplot as plt
from mshoot.optimize import optimize
class SimModel(abc.ABC):
"""
MShoot statefull model interface.
"... |
import os
import torch
from torch import nn
from torch.nn.functional import interpolate, softmax
from torch.cuda.amp import autocast
from .base import BaseNet
norm_layer = nn.BatchNorm2d
class DFF(BaseNet):
"""
Reference:
- Hu, Yuan, et.al "Dynamic Feature Fusion for Semantic Edge Detection... |
from invoke import task
import re
PKG = "blocked-matrix-utils"
PYVERSIONS = "3.6 3.7 3.8 3.9".split()
@task
def skeleton(c):
c.run(f'conda skeleton pypi {PKG}')
@task
def build(c):
for pyversion in PYVERSIONS:
c.run(f"conda build --py {pyversion} {PKG} -c conda-forge")
@task
def convert(c):
f... |
import numpy as np
import cv2
import torch
import torchvision
from torch.utils import data
from copy import deepcopy
from tqdm import tqdm
def resize_dataset(dataset, dim):
new_dataset = deepcopy(dataset)
N = len(dataset.data)
if len(dataset.data.size()) == 3:
new_data = torch.zeros(N, *dim)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: Ampel-interface/ampel/content/T3Document.py
# License: BSD-3-Clause
# Author: valery brinnel <firstname.lastname@gmail.com>
# Date: 23.02.2021
# Last Modified Date: 13.12.2021
# Last Modified By: valery brin... |
from django.db import models
class Usuario(models.Model):
nombre = models.CharField(max_length=255, blank=False, null=False)
correo = models.EmailField(max_length=255, blank=False, unique=True)
contrasena = models.CharField(max_length=255, blank=False, unique=True)
esAdmin = models.BooleanField(defaul... |
'''
This module repurposes the dbd linter from pyPDB (*) to parse EPICS database
definition files and give information about records.
(*) Available on conda-forge as epics-pypdb
'''
import ast
import copy
import pathlib
import caproto
import pytest
pyPDB = pytest.importorskip('pyPDB')
TEST_ROOT = pathlib.Path(__fil... |
class Solution:
def strStr(self, haystack, needle):
if needle in haystack:
return haystack.index(needle)
return -1
|
import logging
from datetime import datetime, timedelta
from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable
FORMAT = '%(asctime)-15s %(threadName)s %(message)s'
logging.basicConfig(filename='rx.log', format=FORM... |
# Copyright (c) 2020 PaddlePaddle 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 appli... |
# -*- coding: utf-8 -*-
###################################################################
# Author: Mu yanru
# Date : 2019.3
# Email : muyanru345@163.com
###################################################################
# Import future modules
from __future__ import absolute_import
from __future__ import division... |
from copy import deepcopy
from indy_node.test import waits
from stp_core.loop.eventually import eventually
from plenum.common.constants import VERSION
from indy_common.constants import FORCE
from indy_node.test.upgrade.helper import bumpedVersion, checkUpgradeScheduled, \
check_no_loop, sdk_ensure_upgrade_sent, c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-01-16 10:37
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stein', '0048_auto_20171230_1145'),
]
operations = [
migrations.AlterModelOptions(
... |
import numpy as np
import pandas
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
def obtain_sample(path):
X_val = []
Y_val = []
Z_val = []
# with open() as csv_file:
with open(File) as csv_file:
csv_reader = pd.read_csv(csv_file, delimiter=',')
pri... |
# Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of the Monodepth2 licence
# which allows for non-commercial use only, the full terms of which are made
# available in the LICENSE file.
from __future__ import absolute_import, division, print_function
from col... |
#!/usr/bin/env python
# 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.
import cStringIO
import logging
import os
import sys
import tempfile
import unittest
ROOT_DIR = os.path.dirname(os.path.dirname(os... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE
from __future__ import absolute_import
import operator
import numba
import numba.core.typing
import numba.core.typing.ctypes_utils
import awkward1.operations.convert
import awkward1._util
import awkward1._connect._numba.layout... |
""" Module containing a CLI for concatenating output files (hdf5 files)
"""
import argparse
from aizynthfinder.utils.files import cat_hdf_files
def main() -> None:
"""Entry-point for the cat_aizynth_output CLI"""
parser = argparse.ArgumentParser("cat_aizynthcli_output")
parser.add_argument(
"--fi... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
# This file is part of the Indico plugins.
# Copyright (C) 2002 - 2021 CERN
#
# The Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License;
# see the LICENSE file for more details.
from flask import flash, redirect, request
from flask_pluginengine import cur... |
import asyncio
import pytest
from tad.protocols.protocol_message_types import ProtocolMessageTypes
from tad.server.outbound_message import make_msg
from tad.server.rate_limits import RateLimiter, NON_TX_FREQ
from tests.setup_nodes import test_constants
@pytest.fixture(scope="module")
def event_loop():
loop = as... |
# populates fields for >>>help(imagezmq) and setup.py
__title__ = 'imzmqx'
__description__ = 'Transporting OpenCV images via ZMQ - enhanced.'
__url__ = 'https://github.com/minlaxz/imzmqx'
__version__ = '1.2.0'
__author__ = 'Jeff Bass, Min Latt'
__author_email__ = 'jeff@yin-yang-ranch.com, minminlaxz@gmail.com'
__licens... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict, SupportsInt, Tuple, cast
from unittest import TestCase
from torch.distributed impo... |
import logging
import logging.handlers
import time
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s')
logging.getLogger().addHandler(logging.handlers.DatagramHandler('127.0.0.1', 51010))
while True:
logging.debug("This shouldn't show up")
logging.info("This should show ... |
import os
import json
import glob
import shutil
import numpy as np
from tqdm import tqdm
import argparse
import matplotlib.pyplot as plt
def json_load(json_file):
with open(json_file, "r") as f:
data = json.load(f)
return data
def json_dump(data, json_out):
json.dump(data, open(json_out, "w"), i... |
from compas.utilities import color_to_colordict
import compas_rhino
__all__ = ['VertexArtist']
class VertexArtist(object):
__module__ = "compas_rhino.artists.mixins"
def clear_vertices(self, keys=None):
"""Clear all vertices previously drawn by the ``VertexArtist``.
Parameters
--... |
def whatever():
global a # 9521
if True:
a = 2
else:
a = 3 |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU', 'C3pro'])
Monomer('SmacM', ['BaxA'])
Monomer('BaxM', ['BidM', '... |
# dummy mcInterface to adapt dudecon's interface to MCEdit's
class MCLevelAdapter(object):
def __init__(self, level, box):
self.level = level
self.box = box
def check_box_2d(self, x, z):
box = self.box
if x < box.minx or x >= box.maxx:
return False
if z < b... |
from typing import List
from injector import inject
from pdip.connection.models.enums import ConnectionTypes
from pdip.data import RepositoryProvider
from pdip.dependency import IScoped
from pdip.exceptions import OperationalException
from pdi.application.connection.services.ConnectionService import ConnectionService... |
"""This is a test"""
from __future__ import nested_scopes; import string
def f(x):
def g(y):
return x + y
return g
result = f(2)(4)
|
import math
from typing import Any
from dictdiffer import diff
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from stade.core.models import Submission
de... |
"""GeoKey settings."""
from geokey.core.settings.dev import *
DEFAULT_FROM_EMAIL = 'no-reply@travis-ci.org'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'geokey',
'... |
#import useful libraries
import numpy as np
import matplotlib.pyplot as plot
if __name__ == '__main__':
# load PCA and NMF accuracy data for GDA
a_gpca = 100*np.load('../data/gpca.npy')
a_gnmf = 100*np.load('../data/gnmf.npy')
# load PCA and NMF accuracy data for Random For... |
#
# Copyright (c) 2019-2020 LG Electronics, Inc.
#
# This software contains code licensed as described in LICENSE.
#
from .geometry import Transform
from .utils import accepts
from collections import namedtuple
GpsData = namedtuple("GpsData", "latitude longitude northing easting altitude orientation")
... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import frappe.website.render
from frappe.website.doctype.website_slideshow.website_slideshow import get_slideshow
no_cache = 1
no_sitema... |
from fipy.docker import DockerCompose
from fipy.ngsi.orion import OrionClient
from fipy.ngsi.quantumleap import QuantumLeapClient
import pytest
from tests.util.fiware import orion_client, quantumleap_client, \
wait_on_orion, wait_on_quantumleap
docker = DockerCompose(__file__)
@pytest.fixture(scope='session', ... |
import sys, os, argparse, time
import pandas as pd
import numpy as np
from datetime import datetime
import ML_functions as ML
start_total_time = time.time()
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
def main():
########################
### Parse Input Args ###
######################... |
import torch
def _sqnorm(x, dim=None, keepdim=False):
x = torch.abs(x)
if dim is None:
assert not keepdim
return torch.sum(x * x)
else:
return torch.sum(x * x, dim=dim, keepdim=keepdim)
def _mse(estimate, target, dim=None):
error = torch.abs(estimate - target)
if dim is N... |
from data import *
from utils.augmentations import SSDAugmentation, BaseTransform
from utils.functions import MovingAverage, SavePath
from utils.logger import Log
from utils import timer
from layers.modules import MultiBoxLoss
from yolact import Yolact
import os
import sys
import time
import math, random
fro... |
#!/usr/bin/env python
""" Vpp VCL tests """
import unittest
import os
import subprocess
import signal
from framework import VppTestCase, VppTestRunner, running_extended_tests, \
Worker
from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath, DpoProto
class VCLAppWorker(Worker):
""" VCL Test Application... |
#!/usr/bin/env python
#
# Copyright (c) 2016-2017 Nest Labs, Inc.
# 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/lice... |
dists = [0]
[dists.append(int(dist)) for dist in input().split(' ')] # [0, city1, city2, etc]
for i in range(len(dists)): # each line
result = ''
dist1 = sum(dists[:i+1]) # the distance from city 1
for j in range(len(dists)): # For each of the cities
result += str(abs(dist1 - sum(dists[:j+1]))) + ... |
def main() -> None:
N = int(input())
assert 1 <= N <= (10**15) + 1
if __name__ == '__main__':
main()
|
class DataPoint:
dp_id = 0
def __init__(self,
tweet: str,
freq: dict,
time_stamp,
created_at,
index_in_df):
"""
the object that keeps the details of the dp
:param tweet: tweet's full text
... |
"""
Biblioteca que tem como funcionalidade armazenas funções. Retirando assim a criação de funções de outros locais
"""
import uuid
import sys
import os
from flask_login import current_user
import bcrypt
PY2 = sys.version_info[0] == 2
class RoleMixin(object):
"""
"solução" para adicionar role ao flask login... |
# First the basic types
from .npy import NumpyDataset
from .kaldi import KaldiDataset
from .imagefolder import ImageFolderDataset
from .text import TextDataset
from .numpy_sequence import NumpySequenceDataset
from .label import LabelDataset
from .shelve import ShelveDataset
# Second the selector function
def get_datas... |
# vim: set ts=4 sws=4 sw=4:
from builtins import str
from builtins import object
import sys # stderr
import functools
_templates = {}
_templates['initializer'] = \
'''\
typedef typename value_type<%s, ! std::is_pointer<%s>::value>::type
vector_type;
std::vector<vector_type> %s =
{ value_iterator<%s>(%s),... |
__version__ = '3.15.2' |
# 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 (the
# "License"); you may not u... |
import os
import subprocess
import yaml
from integration.replicasets.utils import get_list_from_log_lines
from project import patch_cartridge_proc_titile
from utils import (get_log_lines, get_replicasets, is_vshard_bootstrapped,
run_command_and_get_output, write_conf)
def assert_setup_logs(output,... |
import src.RPFramework
def test_to_unicode_ascii_string():
assert src.RPFramework.RPFrameworkUtils.to_unicode('test') == u'test'
def test_to_unicode_unicode_string():
assert src.RPFramework.RPFrameworkUtils.to_unicode(u'test') == u'test'
def test_to_unicode_int():
assert src.RPFramework.RPFrameworkUtils.... |
from collections import OrderedDict
from datetime import timedelta
from unittest import TestCase
from unittest.mock import patch
import pytest
from allauth.account.models import EmailAddress
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.contrib.admin import site
from dja... |
import argparse
import calendar
import configparser
import datetime
import logging
import os
import sys
import time
import ee
def arg_valid_file(file_path):
"""Argparse specific function for testing if file exists
Convert relative paths to absolute paths
"""
if os.path.isfile(os.path.abspath(os.path... |
# Copyright 2016-present MongoDB, 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 wri... |
#!/usr/bin/env python
import sys
import rospy
import std_msgs
import yaml
from std_msgs.msg import String
import math
import numpy as np
from tf.transformations import quaternion_from_euler, euler_from_quaternion
class SendMove(object):
def __init__(self):
rospy.init_node("Manipulation")
self.pub = ros... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
q = int(input())
s = input().strip()
vector... |
# imports - module imports
from ccapi.model.resource import Resource
from ccapi.core.mixins import JupyterHTMLViewMixin
from ccapi.template import render_template
class User(Resource, JupyterHTMLViewMixin):
"""
A User resource object.
Usage::
>>> import ccapi
>>> client = ccap... |
import torch
from .base import BaseModule
class Prenet(BaseModule):
"""
Prenet module from Tacotron 2.
"""
def __init__(self, config):
super(Prenet, self).__init__()
out_sizes = config['decoder_prenet_sizes']
in_sizes = [config['decoder_rnn_dim']] + out_sizes[:-1]
self... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Qtech.QSW2500.get_inventory
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------... |
import os
import json
import argparse
import telegram
BASE_LINK = 'https://github.com/totaki/rock-band-tour/releases/download/%s/rockbandtour-%s-debug.apk'
API_KEY = os.environ.get('RBT_TOKEN', '')
def get_subscribers():
s = os.environ.get('RBT_SUBSCRIBERS', None)
if s is None:
return []
else:
... |
""" Closuers
Free variables and closures
Remember: Functions defined inside another function can access the outer (nonLocal) variables
"""
def outer():
x = 'python'
/ this x refers to the one in outer's scope', this nonlocal variable x is called a free varia... |
from .base_options import BaseOptions
class TestOptions(BaseOptions):
def initialize(self, parser):
parser = BaseOptions.initialize(self, parser)
parser.add_argument('--task', required=True, help='the task you are testing, this effects visualization and evaluation.')
parser.add_argument('-... |
from django.contrib.admin.apps import AdminConfig
class CustomAdminConfig(AdminConfig):
default_site = 'apps.core.admin.site.CustomAdminSite'
|
__author__ = 'mnowotka'
from django.http import HttpResponse
from chembl_assay_network.matrix import fetchMatrix
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from chembl_core_model.models import Docs
import json
from django.views.decorators.cache import cache_page
#--------------... |
import sys
wiki = sys.argv[1]
if wiki == 'sr':
from serbian import srSplitDigraphs,srCyrillicToLatin
import unicodedata
import os
import classla
import re
url_re = re.compile('url="(.+?)"')
title_re = re.compile('title="(.+?)"')
id_re = re.compile('id="(.+?)"')
space_re = re.compile('\s+',re.UNICODE)
def cleanup(text... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 20:26:11 2020
@author: abcdk
"""
inputMin = 789
hours = int(inputMin/60)
minutes = inputMin%60
print ("Hours")
print(hours)
print("Minutes")
print(minutes)
|
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 2.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
# Build path... |
""" implement the TimedeltaIndex """
from pandas._libs import index as libindex, lib
from pandas._libs.tslibs import Timedelta, to_offset
from pandas._typing import DtypeObj, Optional
from pandas.errors import InvalidIndexError
from pandas.core.dtypes.common import TD64NS_DTYPE, is_scalar, is_timedelta64_dtype
from ... |
"""
this decorator replaces func with a function that returns func
this is useful for functions needed in templates, because they
are always evaluated, even when passing them to tags
hence the name: it's a decorator for functions passed to {% call %}
"""
from functools import partial
def for_call(func):
def fu... |
# Copyright (c) 2012 NetApp, Inc. All rights reserved.
# Copyright (c) 2014 Ben Swartzlander. All rights reserved.
# Copyright (c) 2014 Navneet Singh. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Bob Callaw... |
from saltunittest import TestCase
from salt.modules import config
config.__opts__ = {
"test.option.all": "value of test.option.all in __opts__"
}
config.__pillar__ = {
"test.option.all": "value of test.option.all in __pillar__",
"master": {
"test.option.all": "value of test.option.all in maste"
... |
# 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 time
def get_cell_brightness(field_history, column, row, maximal_level):
for index in range(maximal_level):
reversed_index = -(index + 1)
if reversed_index < -len(field_history):
continue
cell = field_history[reversed_index].get_cell(column, row)
if cell:
... |
from econ_watcher_reader.settings import TOP_MENU_PAGE, WatcherType
import pandas as pd
import datetime
from econ_watcher_reader import scraper, parser
from logging import getLogger
logger = getLogger(__name__)
class EconomyWatcherReader(object):
"""
Data reader for Economy Watcher provided from Cabinet Offic... |
# coding=utf-8
import json
import django.forms as django_forms
from django.contrib.contenttypes.models import ContentType
from django.forms import Media
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.functional import cached_property
from xadmin.plugins.utils impor... |
fruit_to_colour = {
'banana' : 'yellow',
'cherry' : 'red',
'orange' : 'orange',
'pear' : 'green',
'peach' : 'orange',
'plum' : 'purple',
'pomegranate' : 'red',
'strawberry' : 'red'}
# Invert fruit_to_colour.
colour_to_fruit = {}
for fruit in fruit_to_colour:
colour = fruit_to_c... |
import socket
from struct import pack
from unittest.mock import ANY, MagicMock, Mock, patch
import pytest
from vine import promise
from amqp import spec
from amqp.basic_message import Message
from amqp.channel import Channel
from amqp.exceptions import (ConsumerCancelled, MessageNacked, NotFound,
... |
# coding: utf-8
"""
Portainer API
Portainer API is an HTTP API served by Portainer. It is used by the Portainer UI and everything you can do with the UI can be done using the HTTP API. Examples are available at https://gist.github.com/deviantony/77026d402366b4b43fa5918d41bc42f8 You can find out more about Por... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
DOCUMENTATION = '''
'''
EXAMPLES = '''
'''
import socket
try:
import json
import requests
except ImportError:
requests_found = False
else:
requests_found = True
class BigIpCommon(object):
def __init__(self, module):
self._username = module.params.... |
import torch
from abstract_rl.src.data_structures.abstract_conf.model_configuration import ModelConfiguration
from abstract_rl.src.operator.trajectory_operator import TrajectoryOperator
class ResampleOperator(TrajectoryOperator):
"""
Samples for each state additional actionsa and equips
"""
def __re... |
# Copyright 2015-2020 Josh Pieper, jjp@pobox.com.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
#!/usr/bin/env python
import os
import web
from web import form
urls = (
'/', 'index'
)
PLOTS_PATH = "plots/"
items = set()
for path, dirs, files in os.walk(PLOTS_PATH):
path = path[len(PLOTS_PATH):]
path = path.split("/")
if len(path) < 2:
continue
path = os.path.join(*path[1:])
file... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 30 23:08:06 2020
@author: Srikar Balusu
"""
import json
import pandas as pd
import numpy as np
import re
import random
import sqlite3
import datetime
import calendar
from dateutil.relativedelta import *
with open('lookup1.json') as json_file:
data = json.load(jso... |
mapped_codepoints = {
"square_arrow_up": (0xf4ca, 0xf220),
"square_arrow_up_fill": (0xf4cb),
"book": (0xf3e7),
"book_fill": (0xf3e8),
"bookmark": (0xf3e9),
"bookmark_fill": (0xf3ea),
"info_circle": (0xf44c),
"arrowshape_turn_up_left": (0xf4c6),
"chat_bubble": (0xf3fb),
"person_crop_circle": (0xf419)... |
import re
from math import sqrt
lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam cursus convallis magna, et hendrerit arcu ornare et."
sentences = len(re.findall(r'\w+', lipsum))
print("Wordcount: {}\n".format(sentences))
print("sqrt(100) = {}\nsqrt(2) = {}\n".format(sqrt(100), sq... |
import aiosqlite
from typing import Optional, List, Dict, Tuple, Any
from beer.types.blockchain_format.sized_bytes import bytes32
from beer.types.blockchain_format.coin import Coin
from beer.types.blockchain_format.program import Program, SerializedProgram
from beer.util.ints import uint64, uint32
from beer.util.hash... |
#!/usr/bin/env python
import os, sys
sys.path.append(os.path.abspath('.'))
import pqaut.server as pqaut
import sip
import PyQt5.Qt as Qt
class Root(Qt.QWidget):
def __init__(self):
def button_click():
label.setText('Button was clicked')
sip.delete(button)
super(Qt.QWidge... |
class Node:
# konstruktor
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
# node-un data field-ini mənimsətmək üçün metod
def set_data(self, data):
self.data = data
# node-un data field-ini almaq üçün metod
def get_data(self):... |
import re
from collections import deque, defaultdict
puzzleInput = open('input.txt', 'r').read()
playersNum, score = map(lambda x: int(x), re.match(r'(\d+)[^\d]*(\d+)', puzzleInput).groups())
players = defaultdict(int)
circle = deque([0])
for marble in range(1, score+1):
if marble % 23 == 0:
circle.rotate(7)
... |
from engine import train_one_epoch, evaluate
import utils
import torch
from dataset import NBINewDataset
from torchvision import transforms
from model import rcnn_model
from torch.utils.data import DataLoader, Subset
from visualize import visualize
import os
def get_transform(train):
all_transforms = []
# if ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch import nn
class FastRCNNPredictor(nn.Module):
def __init__(self, config, pretrained=None):
super(FastRCNNPredictor, self).__init__()
stage_index = 4
stage2_relative_factor = 2 ** (stage_index - 1)
r... |
"""
Copyright 2020 Nvidia Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.