text stringlengths 1 927k |
|---|
"""
Consolidate Services
Description of all APIs # noqa: E501
The version of the OpenAPI document: version not set
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from argocd_python_client.model_utils import ( # noqa: F401
ApiTypeError,
Mo... |
import copy as cp
import numpy as np
from envs.lehnert_gridworld import LehnertGridworld
from model.LehnertGridworldModel import LehnertGridworldModel
from runners.runner import Runner
import config_constants as cc
import vis_utils
from model.cluster import Cluster
from utils.dataset import ArrayDataset
import constan... |
from graphics import *
from functionLibrary import *
WALL_THICKNESS = 5
BAT_Y = 10
BAT_THICKNESS = 2
BAT_WIDTH = 20 # works with 15, 10 for increased difficulty
BLOCK_HEIGHT = 2 # can easily be glitched through with a faster ball speed
BLOCK_ROWS = 2 # max 3 without reducing spacing in makeBlocks
BLOCKS_PER_ROW =... |
# 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, software
# distributed under t... |
import microdf as mdf
import pandas as pd
def test_top_pct():
x = list(range(1, 11)) # 1 to 10. Sum = 10 * 11 / 2 = 55.
df = pd.DataFrame({"x": x})
ms = mdf.MicroSeries(x)
RES = 10 / 55
assert mdf.top_10_pct_share(df, "x") == RES
assert ms.top_10_pct_share() == RES
x = list(range(1, 4))
... |
from .ctp_gateway import CtpGateway |
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... |
from unittest import TestCase
from oo.carro import Motor
class CarroTesteCase(TestCase):
def teste_velocidade_inicial(self):
motor=Motor()
self.assertEqual(0, motor.velocidade) |
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy import Column, String, Integer, DateTime
from sqlalchemy import ForeignKey, Enum, PrimaryKeyConstraint
from sqlalchemy.orm import relationship
import enum
import datetime
import kongUtils
from .inputConf import UserLimits, PermissionLimits, GroupLimits
from... |
# Copyright (C) 2013 eNovance SAS <licensing@enovance.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 applicabl... |
#!/usr/bin/env python3
from build import ninja_common
build = ninja_common.Build('shm_tools/shm-editor')
build.install('auv-shm-editor', f='shm_tools/shm-editor/auv-shm-editor.py')
build.install('auv-plot', f='shm_tools/shm-editor/shm_plotter.py') |
# Copyright 2017 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.
from collections import defaultdict
from collections import namedtuple
import logging
import math
import os
import re
from analysis import crash_util
from a... |
# coding: utf8
from botok import BoSyl
bs = BoSyl()
def test_bosyl():
# is_affixable() Vs. SylComponents.is_thame()
assert bs.is_thame("ཀུན") is False and bs.is_affixable("ཀུན") is False
assert bs.is_thame("དེའིའམ") is True and bs.is_affixable("དེའིའམ") is False
assert bs.is_thame("དེའི") is True and... |
# Marcelo Campos de Medeiros
# ADS UNIFIP 2020.1
# Patos-PB 17/03/2020
'''
Faça um Programa que pergunte quanto você ganha por hora
e o número de horas trabalhadas no mês.
Calcule e mostre o total do seu salário no referido mês.
'''
print('='*53)
print('PROGRAMA DO VALOR DO SÁLARIO PELAS HORAS DE TRABALHO')
print('='... |
#!/usr/bin/env python
import paramiko
import time
import os
host = "127.0.0.1"
port = 22
username = "admin" # CHANGE THIS
password = "admin" # CHANGE THIS
apname = "/system identity print" # Change this for a different command to be run
p = paramiko.SSHClient()
p.set_missing_host_key_policy(paramiko.AutoAddPolicy()... |
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
# See file LICENSE for terms.
import contextlib
import logging
@contextlib.contextmanager
def log_errors(reraise_exception=False):
try:
yield
except BaseException as e:
logging.exception(e)
if reraise_exception:
... |
#!/usr/bin/env python
# Copyright (c) 2018 Sony Pictures Imageworks 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 req... |
# Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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... |
"""
Views of API accessibility application.
"""
from rest_framework.exceptions import PermissionDenied
from rest_framework.generics import CreateAPIView
from wapyce.accessibility.models import IssueCode
from wapyce.accessibility.models import IssuePage
from .serializers import IssuePageSerializer
class NewIssueAPIVi... |
#!/usr/bin/env python3
import itertools
import curses
from enum import Enum
from collections import defaultdict
class Tiles(Enum):
EMPTY = 0
WALL = 1
BLOCK = 2
PADDLE = 3
BALL = 4
def getTexture(self):
textures = {
0: "",
1: "|",
2: "█",
... |
# Copyright 2020 The TensorFlow Probability 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 applicable law o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""diskover - Elasticsearch file system crawler
diskover is a file system crawler that index's
your file metadata into Elasticsearch.
See README.md or https://github.com/shirosaidev/diskover
for more information.
Copyright (C) Chris Park 2017
diskover is released under the... |
"""
ERIO tests restart with different PIO methods
This class inherits from SystemTestsCommon
"""
from CIME.XML.standard_module_setup import *
from CIME.SystemTests.system_tests_common import SystemTestsCommon
logger = logging.getLogger(__name__)
class ERIO(SystemTestsCommon):
def __init__(self, case):
"... |
# Generated by Django 3.2 on 2021-04-11 00:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0012_auto_20210411_0140'),
]
operations = [
migrations.RemoveField(
model_name='tweeprint',
name='tweet_author... |
# computes the gcd. taken from snappea
from functools import total_ordering
import re
def gcd(a, b):
a = abs(a)
b = abs(b)
if a == 0:
if b == 0: raise ValueError("gcd(0,0) undefined.")
else: return b
while 1:
b = b % a
if (b == 0): return a
a = a % b
... |
import os
import pathlib
from setuptools.config import read_configuration
def get_config():
repo_path = pathlib.Path(__file__).parent.parent.absolute()
config_setup = read_configuration(os.path.join(repo_path, "setup.cfg"))
config_requirements = config_setup["options"]["install_requires"]
return con... |
from bs4 import BeautifulSoup
with open("A-1.xml") as fp:
soup = BeautifulSoup(fp, 'xml')
print(soup.Statute) |
# Generated by Django 2.1.7 on 2019-06-14 04:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bestiary', '0013_auto_20190529_1253'),
]
operations = [
migrations.AddField(
model_name='monster',
name='awakening',... |
from collections import OrderedDict
import math
import numpy as np
import torch
import torch.optim as optim
from torch import nn as nn
import torch.nn.functional as F
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.torch.torch_rl_algorithm import TorchTrain... |
"""
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... |
import instaloader
import os
class InstaStories():
def __init__(self):
self.obj = instaloader.Instaloader(save_metadata=False,
filename_pattern="{owner_username}_{date_utc}", download_video_thumbnails='')
self.obj.load_session_from_file(os.getenv('SESSION_NAME'))
def upda... |
src =Split('''
src/CoAPDeserialize.c
src/CoAPExport.c
src/CoAPMessage.c
src/CoAPNetwork.c
src/CoAPObserve.c
src/CoAPPlatform.c
src/CoAPResource.c
src/CoAPSerialize.c
src/CoAPServer.c
''')
component =aos_component('link-coap', src)
global_includes =Split('''
./src
''')
for i in... |
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 3.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
... |
from __future__ import absolute_import
from abc import (
ABCMeta,
abstractmethod
)
import operator
from typing import ( # noqa: F401
Any,
Optional,
Callable,
cast,
Dict,
Generator,
Iterator,
Tuple,
Type,
TYPE_CHECKING,
Union,
)
import logging
from cytoolz import (... |
# Copyright 2018 The TensorFlow 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 applica... |
"""Set of functions to smooth model handling for templates that create
Python code
"""
import yacg.model.model as model
import yacg.util.stringUtils as stringUtils
def getDefaultPythonValue(propertyObj):
if propertyObj.isArray:
return '[]'
else:
if propertyObj.default is not None:
... |
# Copyright 2015, eBay 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 agre... |
# Autodetecting setup.py script for building the Python extensions
#
__version__ = "$Revision$"
import sys, os, imp, re, optparse
from glob import glob
from platform import machine as platform_machine
import sysconfig
from distutils import log
from distutils import text_file
from distutils.errors import *
from distu... |
#!/usr/bin/env python
import numpy as np
import random
from utils.gradcheck import gradcheck_naive
from utils.utils import normalizeRows, softmax
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
Arguments:
x -- A scalar or numpy array.
Return:
s -- sigmoid(x)
"""
... |
# histedit.py - interactive history editing for mercurial
#
# Copyright 2009 Augie Fackler <raf@durin42.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""interactive history editing
With this extension installed, Mercurial g... |
# -*- coding: utf-8 -*-
#
"""
Copyright (C) 2022 Jingl3s
This code is free software; you can redistribute it and/or modify it
under the terms of the DO WHAT THE FUCK YOU WANT TO. (see the file
COPYING.txt included with the distribution).
"""
from .device_dlink_dir822 import DeviceDlink822Factory, RouterDlinkDIR822
_... |
# Copyright 2015-2017 ARM Limited
#
# 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 w... |
### Copyright 2019-2020 MINES ParisTech (PSL University)
### This work is licensed under the terms of the MIT license, see the LICENSE file.
###
### Author: Grégoire Dupont de Dinechin, gregoire@dinechin.org
import sys, os
sys.path.append(sys.argv[sys.argv.index("--") + 1:][0])
import bpy
from Blender_Core import pri... |
#!/usr/bin/python
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013-2014 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from __future__ import pri... |
"""
Django settings for profiles_project project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
impor... |
"""multimodel statistics.
Functions for multi-model operations
supports a multitude of multimodel statistics
computations; the only requisite is the ingested
cubes have (TIME-LAT-LON) or (TIME-PLEV-LAT-LON)
dimensions; and obviously consistent units.
It operates on different (time) spans:
- full: computes stats on fu... |
"""Test configuration fragment replacement."""
import pytest
from dictator.validators.replace import (
FragmentReplace,
AutoFragmentReplace,
FragmentError,
)
from dictator.validators.lists import SubListValidator
from dictator.config import validate_config
def test_fragment_replace():
"""Test manual ... |
from . import moduleItem
from ....cfg import bbData
from .... import lib
from typing import List
from ..gameItem import spawnableItem
@spawnableItem
class GammaShieldModule(moduleItem.ModuleItem):
""""A module providing a ship with protection agains gamma radiation
:var effect: The reduction in gamma radiati... |
from pathlib import Path
from code2markdown import Code
def main():
output_dir = Path.cwd()
code = Code()
code.dump(output_dir=output_dir)
if __name__ == "__main__":
main() |
# Map Cobra languages to moment.js locales
LOCALE_MAPPING = {
'ar': 'ar',
'az': 'az',
'bg': 'bg',
'ca': 'ca',
'cs': 'cs',
'cy': 'cy',
'da': 'da',
'de': 'de',
'el': 'el',
'es': 'es',
'et': 'et',
'fa': 'fa',
'fi': 'fi',
'fr': 'fr',
'gl': 'gl',
'he': 'he',
... |
import logging
import os
import shutil
import subprocess
import psutil
from patroni.postgresql import Postgresql
logger = logging.getLogger(__name__)
class _PostgresqlUpgrade(Postgresql):
def adjust_shared_preload_libraries(self, version):
from spilo_commons import adjust_extensions
shared_pre... |
from tachikoma.emitters import BaseEmitter
class SlackEmitter(BaseEmitter):
def emit(self, channel, pipeline):
pass |
import calendar
from datetime import date, timedelta
# Tasks remaining:
# Create event implementation
"""
Hi future Stevie, it's Connor
I've just done some work for allowing you to access the calendar events. At the top you'll see a new import statement
that's pulling in the classes that will get them from the databa... |
import sys
import warnings
warnings.filterwarnings('ignore')
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QSlider
from PyQt5.QtCore import QSize, Qt, pyqtSlot, pyqtSignal
from PyQt5.uic import loadUi
class HelloWindow(QMainWindow):
pushButtonClicked = pyqtSignal()
val... |
"""Evaluation metrics."""
import numpy as np
import scipy.stats
from sklearn.metrics import matthews_corrcoef # noqa
from sklearn.metrics import recall_score # noqa
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import r2_score # noqa
from sklearn.metrics import mean_squared_error
from sklearn.m... |
from objects.modulebase import ModuleBase
from objects.permissions import PermissionManageRoles
import discord
from utils.funcs import find_role
class Module(ModuleBase):
usage_doc = '{prefix}{aliases} [add|remove] [role_name]'
short_doc = 'Assign or remove color role'
long_doc = (
'Subcommands... |
from .gaussian_arm import GaussianArm
class TestGaussianArm:
"""Test Gaussian arm"""
def test_probability_within_one_std(self):
mu, std = 0, 1
gaussian_arm = GaussianArm(mu, std)
rewards = gaussian_arm.pull(1000)
# Probability of rewards within [mu - std, mu + std]
prob_within_one_std = [
... |
# pylint: skip-file
import os
import importlib.util
got_cpu_lgb = False
got_gpu_lgb = False
from h2o4gpu.util.gpu import device_count
_, ngpus_vis_global = device_count()
enable_lightgbm_import = True
if enable_lightgbm_import:
lgb_loader = importlib.util.find_spec('lightgbm')
lgb_found = lgb_loader is not... |
import datetime
import logging
from collections import deque
import luigi
from exaslct_src.lib.build_config import build_config
from exaslct_src.lib.docker_config import docker_client_config, target_docker_repository_config
from exaslct_src.lib.flavor import flavor
from exaslct_src.lib.stoppable_task import Stoppable... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Simple class to interact with Polylogyx's Api.
:copyright: (c) 2019 by PolyLogyx.
:license: MIT, see LICENSE for more details.
The APIs are documented at:
https://github.com/polylogyx/polylogyx-api/
EXAMPLE USAGE:::
from api import PolylogyxApi
polylogyxApi = PolylogyxA... |
#!/usr/bin/env python3
"""This script provides a RESTful remote endpoint to the detection pipeline.
An image is sent to the server, which sends back the requested results.
"""
import inspect
import io
import json
from tempfile import NamedTemporaryFile
from urllib import parse
import cachetools
import msgpack
import ... |
import os
import pytest
import requests_mock
import CTRegisterMicroserviceFlask
from CTRegisterMicroserviceFlask.errors import NotFound
@pytest.fixture
def validate_env():
if not os.getenv('CT_URL'):
raise Exception('CT_URL needs to be set')
if not os.getenv('CT_TOKEN'):
raise Exception('CT_... |
import re
import json
from urllib.request import urlopen
url = 'https://ipinfo.io/json'
result = urlopen(url)
data = json.load(result)
hostname = data['hostname']
ip = data['ip']
org = data['org']
city = data['city']
country = data['country']
region = data['region']
print(f'IP:{ip}\nRegion:{region}\ncity:{city}') |
# This is a comment and it is the most common, and only one line.abs
'''
This is
the triple quote and will
not be reconized.abs
''' |
# Copyright 2020 CERN for the benefit of the ATLAS collaboration.
#
# 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... |
"""
Wiki Export Handler
Overview
===============================================================================
+----------+------------------------------------------------------------------+
| Path | PyPoE/cli/exporter/wiki/parser.py |
+----------+---------------------------------... |
# -*- coding: utf-8 -*-
"""
最大公约数
"""
def gcd(a, b):
"""
需a>=b
:param a:
:param b:
:return:
"""
if a == b or a % b == 0:
return b
else:
return gcd(b, a % b)
def gcd_2(a, b):
return b if a == b or a % b == 0 else gcd_2(b, a % b)
if __name__ == "__main__":
pr... |
"""
=================
Run RANSAC
=================
In this example we show how to run the RANSAC of ``pyprep``.
.. currentmodule:: pyprep
""" # noqa: D205 D400
# Authors: Yorguin Mantilla <yjmantilla@gmail.com>
#
# License: MIT
# Based On: use_noisy_module.py
######################################################... |
# Generated by Django 3.1.1 on 2020-11-06 13:43
from django.db import migrations
def populate_technologies(apps, schema_editor):
Technology = apps.get_model('OmniDB_app', 'Technology')
Technology(name='sqlite').save()
class Migration(migrations.Migration):
dependencies = [
('OmniDB_app', '0002... |
import os
import numpy as np
import keras.backend as K
from imageio import imread
from keras.utils import Sequence
class Generator(Sequence):
"""Keras Sequence object to train a model on larger-than-memory data.
Creates list of LR input and HR label files (images) locations.
Lists are filtered by extensio... |
# ----------------------------------------------------------------------------
# GS Nodegraph Copyright 2019-2021 by Noah Rahm and contributors
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/6/2 23:02
# @Author : Tom_tao
# @Site :
# @File : views.py
# @Software: PyCharm
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, "index.html")
def login(request):
next = request.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Demonstrates how colorise automatically reset colors when quit."""
__date__ = "2014-05-21" # YYYY-MM-DD
import colorise
ipsum = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna
aliquam erat ... |
import time
import random
global beastHealth
global attackOption
global runOption
global playerHealth
global monsterName
global monsterHealth
global monsterHealthxp
global xp
global playerHealthgain
global random_money
global money
global Sword
global BowAndArrow
global using_sword
global using_bow_and_arrow
global le... |
from locust import HttpUser, task, events
from locust_plugins import jmeter_listener
class DemoBlazeUser(HttpUser):
host = "https://www.demoblaze.com"
@task
def t(self):
self.client.get("/")
@events.init.add_listener
def on_locust_init(environment, **kwargs):
jmeter_listener.JmeterListener(... |
import socket
# import multiprocessing
# start keeping notes
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host, port))
# make listening a differnt thread
# when connection made from client quit listening
# when makeing connection quit to another server
# beco... |
import os
import tempfile
import time
import graphviz
from terra import files
EXTERNAL_INPUT_STYLE = dict(fillcolor="skyblue", shape="box", style="filled", fontcolor="black")
INTERNAL_INPUT_STYLE = dict(fillcolor="plum", style="filled", fontcolor="black")
INTERMEDIATE_FILE_STYLE = dict(fillcolor="lightgray", style="... |
# Generated by Django 2.2 on 2020-06-11 11:27
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
... |
import numpy as np
import sys
import math
from utils.plotting import EpisodeStats
from algorithms.discretization_functions import default_discretization
class QLearning:
def __init__(self,
env,
buckets=(1, ),
discount_factor=1.0,
min_alpha=0.1,... |
def sum(a, b):
"""Returns sum
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
sum -- Sum
"""
return a + b
def difference(a, b):
"""Returns difference
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
diff -- Differen... |
from django.contrib import admin
from .models import Choice, Question
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes':
['collapse']}),
]
inl... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class TaskOutputForDisplay:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The k... |
#!/usr/bin/env python
from pydy import *
from sympy import solve
# Declare a Newtonian Reference Frame
N = NewtonianReferenceFrame('N')
# Declare parameters, coordinates, and speeds
m1, m2, I1, I2, J1, J2, l, M = N.declare_parameters('m1 m2 I1 I2 J1 J2 l M')
(q1, q2, q3, q4, q5, q6, q7, q8), q_list, qdot_list = N.dec... |
from dearpygui.core import *
from db_manage import reset_db
def resetPad(pad_name):
# Erase all lines from the drawing pad
clear_drawing(pad_name)
set_item_color("Drawing Pad", style=mvGuiCol_WindowBg, color=[255, 255, 255])
reset_db() |
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
# Runtime: 16 ms
# Memory: 13.5 MB
try:
while True:
nums.remove(val)
except ValueError:
... |
class Solution(object):
def maxIncreaseKeepingSkyline(self, grid):
rm = [max(r) for r in grid]
cm = [max(c) for c in zip(*grid)]
#print rm, cm
ans = 0
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
ans += min(rm[i], cm[j]) - grid[i][j]
... |
from django.shortcuts import render
from django.http import HttpRequest
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import DetailView
from django.db.models import Count
from .models import Publication, PublicationMedia
def index(request):
publication_list = P... |
from django.db.models.signals import pre_save, post_save
from django.core.signals import request_finished
from django.dispatch import receiver
from .my_singal import action
def pre_save_model(sender, **kwargs):
print(sender)
print(kwargs)
def post_save_func(sender, **kwargs):
# 记个日志
print('发送者',sende... |
from inspect import currentframe, getframeinfo
import numpy as np
import matplotlib.pyplot as plt
import json
plt.style.use('seaborn-ticks')
# To disable debugging set it to False
# To print all debugging info set the second entry to 0
# To print a specific message set its id
DEBUG = [False, 0]
def print_debug_info(l... |
# coding: utf-8
import pytz
from datetime import datetime
from django.conf import settings
from django.http import Http404
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorator... |
from collections import defaultdict
class Solution:
# Dict (Accepted), O(n) time and space
def videoStitching(self, clips: List[List[int]], time: int) -> int:
d = defaultdict(int)
for start, end in clips:
if start < time:
d[start] = max(d[start], end)
prev, ... |
import numpy as np
class OrnsteinUhlenbeckNoiseProcess:
"""
Taken from https://github.com/openai/baselines/blob/master/baselines/ddpg/noise.py
"""
def __init__(self, mu, sigma, theta=.15, dt=1e-2, x0=None):
self.theta = theta
self.mu = mu
self.sigma = sigma
self.dt = dt... |
# Copyright 2019 Google LLC. 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 law or a... |
import time
import hashlib
import json
import requests
import base64
from flask import Flask, request
from multiprocessing import Process, Pipe
import ecdsa
from miner_config import MINER_ADDRESS, MINER_NODE_URL, PEER_NODES
node = Flask(__name__)
class Block:
def __init__(self, index, timestamp, data, previous_... |
import json
from decimal import Decimal
from django.db import models
from django.conf import settings
from channels import Group
class Location(models.Model):
name = models.CharField(max_length=255)
lat = models.DecimalField(max_digits=40, decimal_places=30, blank=True, null=True)
lng = models.DecimalFi... |
from multiprocessing import Process
from termcolor import colored
from .helper import set_logger
class EvalHTTPProxy(Process):
def __init__(self, args):
super().__init__()
self.args = args
def create_flask_app(self):
try:
from flask import Flask, request
from... |
from django.conf import settings
def my_settings(request):
return {
'settings': settings
} |
'''
Extracts features from the raw data extracted from polarity list.
'''
ofile = open('processed_polist.txt','w')
orig_scores = []
def import_scores():
ing1 = open('realresults.txt','r')
ing2 = ing1.read()
ing3 = ing2.split()
for j in range(len(ing3)):
orig_scores.append(int(ing3[j]))
print orig_scores[:10]
... |
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
from net.sync_batchnorm import SynchronizedBatchNorm2d
bn_mom = 0.0003
model_urls = {
'resnet18': 'http://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'http://download.pytorch.org/models/resnet34-333f7ec4.pth',
'... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os.path
import time
import sys
import tensorflow.compat.v1 as tf
import numpy as np
import importlib
import itertools
import argparse
import facenet
import lfw
from tensorf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.