text stringlengths 2 999k |
|---|
import functools
import json
import logging
import os
from collections import defaultdict
from discord.ext import commands
from tle import constants
from tle.util import cache_system2
from tle.util import codeforces_api as cf
from tle.util import db
from tle.util import discord_common
from tle.util import event_syste... |
#!/usr/bin/env python3
import boto3
import json
import os
import os
import pprint
from sys import version_info
import sys
AWS_REGION = "us-west-1"
EC2_CLIENT = boto3.client('ec2', region_name=AWS_REGION)
INSTANCE_ID = 'i-06a2ac220369ddb08'
# Stopping the instance using stop_instances.
instances = EC2_CLIENT.stop_i... |
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import struct
import ipaddress
from socks5.exception import ProtocolError
from socks5.connection import Connection
from socks5.events import (
Socks4Request, Socks4Response,
GreetingRequest, GreetingResponse,
... |
num1 = 10
num2 = 20
num3 = 30
num4 = 40
# 以下来自dev分支编写
num5 = 50
|
from shop.admin import notification
|
# -*- test-case-name: twisted.logger.test.test_stdlib -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Integration with Python standard library logging.
"""
import logging as stdlibLogging
from typing import Mapping, Tuple
from zope.interface import implementer
from constantly import ... |
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
class CivilscraperSpiderMiddlewar... |
# coding: utf-8
"""
Iot API
Collection of all public API endpoints. # noqa: E501
The version of the OpenAPI document: 2.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from... |
#!/usr/bin/env python
# -*- test-case-name: twisted.names.test.test_examples -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Print the Address records, Mail-Exchanger records and the Nameserver
records for the given domain name. eg
python testdns.py google.com
"""
import sys
from t... |
# first images year
L4_start = 1982
# max year for land cover
land_cover_max_year = 2020
sensor_max_year = 2021
land_cover_first_year = 1992
# name of the sensor, GEE asset
sensors = {
"Landsat 4": ["LANDSAT/LT04/C01/T1_SR", 30, "l4"],
"Landsat 5": ["LANDSAT/LT05/C01/T1_SR", 30, "l5"],
"Landsat 7": ["LAN... |
from fuzion.mixins import RetrieveNotSupportedMixin
from fuzion.subresource import SubResource
class AbstractContact(RetrieveNotSupportedMixin, SubResource):
path = "abstracts/{}/contacts"
object_id_attr_name = "fuzion_contact_id"
|
fruit_evaluation= [
['Яблоко', '5', '4', '5', '3', '4', '5'],
['Финоград', '4', '3', '4', '5', '5', '5'],
['Дыня', '5', '5', '4', '5', '3', '4'],
['Арбуз', '4', '4', '3', '5', '5', '4'],
['Киви', '4', '3', '5', '5', '4', '4'],
['Ананас', '4', '3', '4', '5', '4', '5']
]
def show_assessment(assess... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from CTFd.models import Challenges
from tests.helpers import create_ctfd, destroy_ctfd, login_as_user, register_user
def test_missing_challenge_type():
"""Test that missing challenge types don't cause total challenge rendering failure"""
app = create_ctf... |
from copy import copy
from typing import List
import numpy as np
import torch
import torch.optim as optim
import torchvision.transforms as T
import yaml
from matplotlib.pyplot import fill
import wandb
from attacks.initial_selection import find_initial_w
from utils.wandb import load_model
class AttackConfigParser:
... |
# -*- coding: utf-8 -*-
"""The user module."""
from flask import render_template,current_app
import random,string
try:
from StringIO import StringIO
except ImportError:
from io import BytesIO
from datetime import datetime
try:
from PIL import Image,ImageDraw,ImageFont,ImageFilter
except Exception as e:
impor... |
#!/usr/bin/env python
# A script to check for the presence of all the required modules
# Gain access to the spawn.find_executable(), which works a lot like `which`
from distutils import spawn
def check_modules(setup=False, fetch=False, predict=False):
"""Function to try to import required modules, and retur... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from improving_agent.models.base_model_ import Model
from improving_agent.models.log_entry import LogEntry
from improving_agent.models.message import Message
from impro... |
def exchange_rate_format(data):
"""Return a dict with the exchange rate data formatted for serialization"""
return {
'provider_1': {
'name': 'dof',
'rate': data.dof_rate,
'date': data.dof_date,
'last_updated': data.dof_last_updated,
},
'pro... |
import logging
import os
import traceback
from collections import OrderedDict
import great_expectations.exceptions as exceptions
from great_expectations.core.util import nested_update
from great_expectations.data_context.store.html_site_store import (
HtmlSiteStore,
SiteSectionIdentifier,
)
from great_expectat... |
# Obstacle Avoidance Program for the Micro:Maqueen robot based the micro:bit
# board
#
# This program starts driving the Maqueen robot 2s after pressing the A
# button straight until encountering an obstacle, then backs up to the right or
# left with warning beeping and then resumes going straight. It stops after
# th... |
#!/usr/bin/env python3
# Copyright (c) 2016 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 Hierarchical Deterministic wallet function."""
from test_framework.test_framework import BitcoinTestFr... |
#
# 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 us... |
# SPDX-Package: FAVD
# SPDX-PackageHomePage: https://github.com/secureIT-project/FAVD
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021-2022 David Binkley, Leon Moonen, Sibren Isaacman
import numpy as np
class CharacterTable(object):
"""Given a set of characters:
+ Encode them to a one hot intege... |
"""Operations for dannce."""
import tensorflow as tf
import numpy as np
from scipy.interpolate import RegularGridInterpolator
import tensorflow.keras.backend as K
import tensorflow.keras.initializers as initializers
import tensorflow.keras.constraints as constraints
import tensorflow.keras.regularizers as regularizers
... |
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pycon.settings.celery")
app = Celery("pycon")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks(["integrations"])
|
# --------------------------------------------------------------------------
# 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 may cause incor... |
# @Author: Manuel Rodriguez <valle>
# @Date: 01-Jan-2018
# @Email: valle.mrv@gmail.com
# @Last modified by: valle
# @Last modified time: 13-Jul-2018
# @License: Apache license vesion 2.0
"""
Django settings for service_web project.
Generated by 'django-admin startproject' using Django 1.10.7.
For more informat... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0022_auto_20151118_1642'),
]
operations = [
migrations.AddField(
model_name='role',
name='co... |
# coding: utf-8
"""
Engine api
Engine APIs # noqa: E501
The version of the OpenAPI document: 1.0.4
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import vtpl_api
from vtpl_api.models.extra import Extra # noqa: E501
from vtpl_api.rest impo... |
valor = float(input("qual o valor atual do produto o qual você deseja dar o desconto? "))
desconto = float(input("quanto de desconto você quer dar ao produto? em porcentagem "))
print("o produto custava {}, mas com desconto de {}% ele passa a custar {:.2f}R$".format(valor, desconto, (valor -(( desconto * 1/100)*valor))... |
from plenum.common.constants import TXN_TYPE, DATA
from plenum.test.helper import sdk_gen_request, sdk_sign_and_submit_req_obj, sdk_get_reply
from plenum.test.plugin.demo_plugin.constants import AUCTION_START
def send_auction_txn(looper,
sdk_pool_handle, sdk_wallet_steward):
op = {
TX... |
# Can 31 dominoes cover all but two opposite corners of a chess board?
def dominoes():
# Each dominoe must cover one black and one white square.
# But there are different numbers of black and white squares.
# Read up on such parity arguments here:
# http://ihxrelation.blogspot.com/2015/10/tiling-problems.html
... |
import numpy as np
import pandas as pd
csv_data = pd.read_csv("../data/double11_1020_1120.csv")
csv_data *= 100.0
# csv_data.fillna(0.0,inplace=True)
# print(csv_data.isnull().any())
csv_data_u = csv_data.round(5).drop_duplicates(subset=csv_data.columns[1:],keep='first')
# csv_data_u = csv_data
csv_data_u = csv_data... |
import unittest
from mysql.toolkit import MySQL
from tests import config
from looptools import Timer
def printer(title, data, sep='-' * 100):
print('\n{title}:\n{sep}\n{data}\n{sep}\n'.format(title=title.upper(), sep=sep, data=data))
class TestStructureDefinition(unittest.TestCase):
@classmethod
def set... |
import requests
from bs4 import BeautifulSoup
def GetPubSubdir():
response = requests.get(
"https://mirrors.edge.kernel.org/pub/linux/utils/util-linux/")
html = response.content.decode("utf-8")
parsedHtml = BeautifulSoup(html, "html.parser")
links = parsedHtml.find_all("a")
return ("https://... |
import pyfirmata
board = pyfirmata.Arduino('/dev/ttyACM0')
led_pin = board.get_pin('d:10:p')
while True:
duty_s = input("Enter Brightness (0 to 100):")
duty = int(duty_s)
led_pin.write(duty / 100.0)
|
import logging
import sys
from logging.handlers import RotatingFileHandler
import os
FORMATTER = logging.Formatter("%(asctime)s — %(threadName)s — %(name)s — %(levelname)s — %(funcName)s:%(lineno)d — %(message)s")
def get_console_handler():
console_handler = logging.StreamHandler(sys.stdout)
console_handler.... |
"""
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Game plan
1. Keep 4 pointers top, bottom, left, right
2. Start from the first row and iterate over the columns, top ... |
#This Project Works Well if Your camera(WEBCAM) is working ..if Not then Check my another project where the video is loaded manually (From directory)
#----------------------------------------#
#FACE DETECTION USING PYTHON3 AND OPENCV #
#--------AUTHOR- Ritesh Aggarwal---------#
#-----------Language->Python3----... |
# Copyright (c) 2021, NVIDIA CORPORATION.
import numpy as np
import pandas as pd
import pytest
from dask import dataframe as dd
import dask_cudf as dgd
import cudf
def _make_random_frame(nelem, npartitions=2):
df = pd.DataFrame(
{
"x": np.random.randint(0, 5, size=nelem),
"y": ... |
#!/usr/bin/python
#
# Copyright (c) 2020 by VMware, Inc. ("VMware")
# Used Copyright (c) 2018 by Network Device Education Foundation, Inc.
# ("NetDEF") in this file.
#
# Permission to use, copy, modify, and/or distribute this software
# for any purpose with or without fee is hereby granted, provided
# that the above c... |
# 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! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .backup_short_term_retention_policy impo... |
import sys
import logging as log
import time
import datetime
from . import gitlab
from .approvals import Approvals
GET, POST, PUT, DELETE = gitlab.GET, gitlab.POST, gitlab.PUT, gitlab.DELETE
class MergeRequest(gitlab.Resource):
@classmethod
def create(cls, api, project_id, params):
merge_request_i... |
from core import Window, alerts
import imgui
from utils import singleton
@singleton
class ExceptionAlert():
def __init__(self, exception, traceinfo):
self.exception = exception
self.traceinfo = traceinfo
def render(self):
expanded, visible = imgui.collapsing_header(self.exception)
... |
# K2000 KIT Python Module
# to be used in conjonction with the arduinoMicroShiftRegisterTest(s), to produce effect(s) such as K2000 KIT
import time
from collections import deque # used to cycle/rotate the leds deck pattern to be sent over serial to the uC/Ar
# == debug tests ==
'''
larger_list = [0,'A','B','C',1, 1,'F... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Andrey Skopenko <andrey@scopenco.net>
PLUGIN_NAME = 'CageFS'
import sys
sys.path.insert(0, '/usr/local/ispmgr/addon')
from cli import ExitOk, Log, xml_doc, xml_error
from libcagefs import CageFS
from os import chdir
from sys import exit, stderr
from cgi import ... |
# coding: utf-8
"""
Pure Storage FlashBlade REST 1.8.1 Python SDK
Pure Storage FlashBlade REST 1.8.1 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.8.1
Cont... |
# qubit number=3
# total number=15
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collectio... |
import pytest
from asynch.cursors import DictCursor
from asynch.proto import constants
@pytest.mark.asyncio
async def test_fetchone(conn):
async with conn.cursor() as cursor:
await cursor.execute("SELECT 1")
ret = cursor.fetchone()
assert ret == (1,)
await cursor.execute("SELECT ... |
from .env import init_dist, get_root_logger, set_random_seed
from .train import train_detector
from .inference import inference_detector, show_result
__all__ = [
'init_dist', 'get_root_logger', 'set_random_seed', 'train_detector',
'inference_detector', 'show_result'
]
|
# Copyright 2016-present, Facebook, Inc.
# 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. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import absol... |
import difflib
import functools
import math
import numbers
import os
import warnings
import numpy as np
from tlz import frequencies, concat
from .core import Array
from ..highlevelgraph import HighLevelGraph
from ..utils import has_keyword, ignoring, is_arraylike
try:
AxisError = np.AxisError
except AttributeErr... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.21
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
# 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 may ... |
# https://www.hackerrank.com/challenges/python-sort-sort/problem
import math
import os
import random
import re
import sys
if __name__ == "__main__":
N, M = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(N)]
K = int(input())
arr.sort(key=lambda x: x[K])
[print(*el... |
import androidhelper
droid = androidhelper.Android()
import math
#definiranje klase tocka
class Tocka (object):
def __init__(self,rbr,y,x,z):
self.rbr = str(rbr)
self.y = float(y)
self.x = float(x)
self.z = float(z)
def smjerni(self,other):
dy = (other.y)-(self.y)
dx = (other.x)-(self.x)
if... |
#! /usr/bin/python
#
# Copyright (c) 2012 Tresys Technology LLC, Columbia, Maryland, USA
#
# This software was developed by Tresys Technology LLC
# with U.S. Government sponsorship.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License a... |
import logging
import sys
# Log configurations
LOG_FORMAT = (
"%(asctime)s [%(levelname)s] %(name)s:%(lineno)d: %(message)s"
)
LOG_FORMATTER = logging.Formatter(
LOG_FORMAT,
datefmt="%Y-%m-%d %H:%M:%S"
)
LOG_FILE = "main.log"
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
file_handler = logg... |
from person_start import Person
bob = Person('Bob Smith', 42)
sue = Person('Sue Jones', 45, 40000)
people = [bob, sue]
for person in people:
print(person.name, person.pay)
x = [(person.name, person.pay) for person in people]
print(x)
x = [rec.name for rec in people if rec.age >= 45]
print(x)
x = [(rec.age ** ... |
# Author : github.com/slingthy
# Time : March 4, 2020
# ---------------------------------------------
# The purpose is to extract someone's record
# from wechat group and store it in a docx file.
# !!!JUST 'TEXT' message.
# ---------------------------------------------
# Before RUN:
# 1. COPY the WeC... |
# 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', '... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import copy
import unittest
from typing import Dict, List
from databuilder.models.table_metadata import ColumnMetadata, TableMetadata
from databuilder.models.type_metadata import ArrayTypeMetadata, TypeMetadata
from databuilder.se... |
#!/usr/bin/env python3
# Copyright (c) 2014-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.
"""
ZMQ example using python3's asyncio
EducaCoind should be started with the command line argum... |
""" FizzBuzzフレームワークの利用例 """
from typing import Any, List
import framework
def FizzBuzzFilter() -> framework.OperatorChain:
""" 入力値に対してFizzBuzz変換掛けるフィルタ
中身は単純に ModReplaceFilter を組み合わせただけ。
"""
return framework.OperatorChain(
framework.ModReplaceFilter(15, "fizzbuzz"),
framework.ModRe... |
import wxf_test as t
t.wxf('./test.jpg') |
# coding: utf-8
# View all groups
# Created by James Raphael Tiovalen (2021)
import slack
import ast
import settings
import config
from slackers.hooks import commands
conv_db = config.conv_handler
@commands.on("viewgroups")
def viewgroups(payload):
return
|
import math
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
return int(math.sqrt(x))
|
from abc import ABC
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
# User serializer
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
# Register seria... |
# -*- coding: utf-8 -*-
"""Top-level package for UK Boards."""
__author__ = """Griffith Rees"""
__email__ = "griff.rees@gmail.com"
# fmt: off
__version__ = '0.5.4'
# fmt: on
|
from Jumpscale import j
class Package(j.baseclasses.threebot_package):
def _init(self, **kwargs):
if "branch" in kwargs.keys():
self.branch = kwargs["branch"]
else:
self.branch = "*"
def prepare(self):
"""
is called at install time
:return:
... |
# Copyright 2013-2022 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 RGgsignif(RPackage):
"""Enrich your 'ggplots' with group-wise comparisons. This package pr... |
'''
Stanley Bak
Engine controller specification checking
'''
import numpy as np
from numpy import deg2rad
from RunF16Sim import RunF16Sim
from PassFailAutomaton import AirspeedPFA, FlightLimits
from CtrlLimits import CtrlLimits
from LowLevelController import LowLevelController
from Autopilot import FixedSpeedAutopil... |
"""
Heidi: Helpers related to visuals.
"""
import logging
__all__ = ['ColorizingStreamHandler', 'ReadableSqlFilter']
# Copyright (C) 2010-2012 Vinay Sajip. All rights reserved. Licensed under the new BSD license.
# https://gist.github.com/758430
class ColorizingStreamHandler(logging.StreamHandler):
# color names... |
import time
from abc import ABCMeta
from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException, \
WebDriverException, InvalidElementStateException
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.expected_conditions impo... |
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Secrets Manager
# Copyright 2021 Keeper Security Inc.
# Contact: ops@keepersecurity.com
import json
import mimetypes
import os
from datetime import datetime
from pathlib import Path
import... |
#!/usr/bin/env python3
import re
import sys
import datetime
import subprocess
from widgets.widget import Widget
from widgets.config import colors, icons
class button(Widget):
'''
'''
def __init__(self, value=''):
'''
Params:
bg: background color
fg: foreground col... |
import sys
from scrimmage.client import Client
from game.engine import Engine
from game.utils.generate_game import generate
import game.config
import argparse
import subprocess
import updater
if __name__ == '__main__':
plat = sys.platform
# Setup Primary Parser
par = argparse.ArgumentParser()
# Creat... |
from stellar_model.response.account_data_response import *
from stellar_model.response.account_response import *
from stellar_model.response.accounts_response import *
from stellar_model.response.assets_response import *
from stellar_model.response.claimable_balance_response import *
from stellar_model.response.claimab... |
# 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 may ... |
def test_del():
a: i32
b: i32
a = 4
b = 20
del a, b
|
import itertools
import os
import shutil
import tempfile
from contextlib import contextmanager
from dagster import check
from dagster.core.storage.file_manager import LocalFileHandle
def _unlink_swallow_errors(path):
check.str_param(path, "path")
try:
os.unlink(path)
except Exception:
pas... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import papermill as pm
import pytest
import scrapbook as sb
# Parameters
KERNEL_NAME = "python3"
OUTPUT_NOTEBOOK = "output.ipynb"
@pytest.mark.notebooks
@pytest.mark.linuxgpu
def test_01_notebook_run(similarity_notebooks):... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
import numbers
import contextlib
from unittest.mock import patch
import numpy as np
import nevergrad.common.ty... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Model exaplaination https://www.coursera.org/lecture/advanced-computer-vision-with-tensorflow/fcn-architecture-details-uwVDj
@author: anelmusic
"""
import tensorflow as tf
import config
vgg_weights_path = config.VGG_WEIGHTS_PATH
def block(x, n_convs, filters, kernel... |
import pandas as pd
import psycopg2 as pg2
import yaml
import io
import ohio.ext.pandas
from sqlalchemy import create_engine
def open_db_connection(secrets_file="secrets.yaml", verbose=True):
"""
Opens connection to psql db
:return:
connection object
"""
try:
with open(secrets_... |
import argparse
import torch
import pyro
import pyro.distributions as dist
from pyro.infer.mcmc.api import MCMC
from pyro.infer.mcmc import NUTS
"""
This simple example is intended to demonstrate how to use an LKJ prior with
a multivariate distribution.
It generates entirely random, uncorrelated data, and then attem... |
#!/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.
"""An example functional test
The module-level docstring should include a high-level description of
what the t... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# 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, inc... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: language_agent_v2/JVMMetric.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_d... |
from django.urls import path
from traffic import views
from django.conf.urls import url
urlpatterns = [
# path('', views.index, name='index'),
url(r'^traffic_all_long', views.traffic_all_long, name='traffic_all_long'),
url(r'^traffic_all_short', views.traffic_all_short, name='traffic_all_short'),
url(r... |
from insights.parsers import init_process_cgroup
from insights.tests import context_wrap
CGROUP_HOST = """
11:hugetlb:/
10:memory:/
9:devices:/
8:pids:/
7:perf_event:/
6:net_prio,net_cls:/
5:blkio:/
4:freezer:/
3:cpuacct,cpu:/
2:cpuset:/
1:name=systemd:/
""".strip()
CGROUP_CONTAINER = """
11:hugetlb:/system.slice/d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2021. Huawei Technologies Co., Ltd. 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.... |
from direct.showbase import PythonUtil
from pandac.PandaModules import VBase4
GameActions = PythonUtil.Enum(('EnterDoor',
'RevealDoor',
'OpenDoor',
'Countdown',
'TimeAlert'))
SecondsUntilTimeout = 4.0 * 60.0
SecondsUntilGameEnds = 60.0
SecondsForTimeAlert = 60.0
MaxPlayers = 4
IntroDurationSeconds = 24.0
FinishDura... |
import numpy as np
#import jax.numpy as np
from typing import Callable
import warnings
'''
optimization module
Provides matrix-valued prox-gradient method and its accelerated versions.
Modified from the code in https://github.com/harrispopgen/mushi/
'''
def hs_dot(A, B):
return (A*B).flatten().sum()
def prox_g... |
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as dt
import matplotlib.ticker as ticker
import datetime
import pickle
import copy
import snake_case
YAXPARAMS = {
'cases': {
'total': {
'ymax': 90,
'yinterval':10... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pytest
import pandas
import modin.pandas as pd
from modin.pandas.utils import (
to_pandas,
from_pandas
)
@pytest.fixture
def ray_df_equals_pandas(ray_df, pandas_df):
return to_pandas(ray_df... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 22:15:47 2020
@author: mofarrag
"""
from IPython import get_ipython
get_ipython().magic("reset -f")
# import os
# os.chdir("")
import geopandas as gpd
import numpy as np
import pandas as pd
import Hapi.inputs as IN
# BasinF = "F:/02Case studies/Coello/base_data/GIS/de... |
# -*- coding: utf-8 -*-
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserLocaleProfile'
db.create_table(u'common_userlocaleprofile', (
(u'id', self.gf('django.db.mod... |
import basis.robot_math as rm
import modeling._ode_cdhelper as mcd
class ModelCollection(object):
"""
a helper class to further hide pandanodes
list of collision and geom models can be added to this collection for visualization
author: weiwei
date: 201900825, 20201212
"""
def __init__(self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.