content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from serial import Serial
import time
print("Starting.")
port = "/dev/cu.usbmodem14201" #port for Arduino.
ser = Serial(port, 9600)
time.sleep(2) #wait for Arduino.
sendedBytes = ser.write("90,90,90".encode())
print(sendedBytes)
print(ser.readline()) #wait and read string from... | python |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
## Grayscale
def BGR2GRAY(img):
gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0]
gray = gray.astype(np.uint8)
return gray
# Sobel filter
def sobel_filter(img, K_size=3):
H, W = img.shape
... | python |
from audioop import add
from typing import Text
from linebot.models import TemplateSendMessage, ButtonsTemplate, LocationAction
from models.message_request import MessageRequest
from skills import add_skill
@add_skill('{action_location}')
def get(message_request: MessageRequest):
location = TemplateSen... | python |
"""
Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com
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, m... | python |
import tempfile
import time
from pybloom.pybloom import BloomFilter
NS = 10**9
for _p in xrange(1, 3):
p = 10 ** _p
for e in xrange(9):
X = int(1000 * 10 ** (e / 2.0))
print X, p,
bloomfilter = BloomFilter(X + 1, 1.0/p)
t = time.time()
for x in xrange(X):
b... | python |
# Copyright (C) 2021 DB Systel GmbH.
#
# 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... | python |
test_cases = int(input().strip())
for t in range(1, test_cases + 1):
N = int(input().strip())
nums = ''
while len(nums) != N:
nums += ''.join(input().strip().split())
num = 0
while True:
if str(num) not in nums:
break
num += 1
print('#{} {}'.format(t, num)... | python |
import FWCore.ParameterSet.Config as cms
from RecoJets.JetProducers.ak4TrackJets_cfi import ak4TrackJets
from CommonTools.RecoAlgos.TrackWithVertexRefSelector_cfi import *
from RecoJets.JetProducers.TracksForJets_cff import *
recoTrackJetsTask =cms.Task(trackWithVertexRefSelector,
trac... | python |
# encoding: utf-8
from __future__ import absolute_import
import csv
import datetime
import json
import six
from auth.constants import ROLES
from auth.models import Role, Network, Gateway, Voucher, Country, Currency, Product, db, users
from auth.services import manager
from flask import current_app
from flask_script ... | python |
from Layer.MulLayer import MullLayer
from Layer.AddLayer import AddLayer
# Buy Apple Pattern
apple = 100
applefigure = 2
appleLayer = MullLayer()
taxLayer = MullLayer()
tax = 1.1
# forward
print("\n---forward---")
applePrice = appleLayer.forward(apple, applefigure)
print("applePrice:" + str(applePrice))
allprice = ... | python |
#
# 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... | python |
from logging import getLogger
from django.conf import settings as django_settings
from django.core.mail import EmailMessage
from django.core.mail.backends.smtp import EmailBackend
from django.template.loader import render_to_string
from django.utils import translation, timezone
from core.version import __version__
fro... | python |
import argparse
import os
import torch
import numpy as np
from utils.config import create_config
from utils.common_config import get_model, get_train_dataset,\
get_val_dataset, get_val_dataloader, get_val_transformations
from utils.memory import MemoryBank
from utils.utils import fill_m... | python |
import sys
from pathlib import Path
file_dir = Path(__file__).parent
sys.path.append(str(file_dir.parent))
| python |
# _*_coding:utf-8_*_
# Author: xiaoran
# Time: 2018-12-13
import numpy as np
def zero_one_loss(y_true, y_pred):
'''
param:
y_true: narray or list
y_pred: narray or list
return: double
'''
y_true = np.array(y_true)
y_pred = np.array(y_pred)
return 1.0 * (len(y_true)... | python |
import numpy as np
name = input("Config file name: ")
configs = np.load("data/"+name+".npy")
print(len(configs))
dataset = input("Dataset: ")
n = int(input("Number of parts: "))
size = int(len(configs)/n)+1
for i in range(n):
np.save("data/"+dataset+"_conf"+str(i), configs[ size*i : size*(i+1) ]) | python |
# Copyright (c) 2018, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
'''
Fields to move from item group to item defaults child table
[ default_cost_center, default_expense_account, default_income_account ]
''... | python |
#
# @lc app=leetcode id=987 lang=python3
#
# [987] Vertical Order Traversal of a Binary Tree
#
# https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/description/
#
# algorithms
# Medium (37.69%)
# Likes: 1345
# Dislikes: 2343
# Total Accepted: 131.6K
# Total Submissions: 338.5K
# Testcase Exam... | python |
from tree import BinarySearchTree, BinaryTree
import pytest
def test_class():
assert BinarySearchTree
def test_traverse():
tree = BinarySearchTree()
tree.add('bananas')
tree.add('apples')
tree.add('cucumbers')
items = list(tree.traverse_in_order())
assert items == ['apples','bananas','c... | python |
from tg import expose, TGController, AppConfig
from controllers import RootController
from controllers import ArtistFileService
service = ArtistFileService.ArtistFileService('controllers/artists.json')
controller = RootController.RootController(service)
config = AppConfig(minimal=True, root_controller=controller)
ap... | python |
#!/usr/bin/python
def do_sum(n):
sum = 0
for i in xrange(n):
sum += i
print(sum)
if __name__ == '__main__':
import sys
n = int(sys.argv[1])
do_sum(n)
| python |
from bauh.api.abstract.model import SuggestionPriority
ALL = {
'com.spotify.Client': SuggestionPriority.TOP,
'com.skype.Client': SuggestionPriority.HIGH,
'com.dropbox.Client': SuggestionPriority.MEDIUM,
'us.zoom.Zoom': SuggestionPriority.MEDIUM,
'org.telegram.desktop': SuggestionPriority.MEDIUM,
... | python |
TARGET_FILE_FIELD='targetFile'
TARGET_METHOD_FIELD='targetMethod'
TARGET_METHOD_ARGS_FIELD='targetMethodArgs'
TARGET_METHOD_RETURN_FIELD='targetMethodReturn'
TARGET_METHOD_RETURN_VALUE='targetMethodReturnValue'
CHALLENGE_YAML='challenge.yaml'
API_ADRESS='127.0.0.1'
API_PORT=6070
MISSION_USER_SCORE_ENDPOINT='/deadlock/... | python |
from scipy import spatial
from .validator import validate_keys
import numpy as np
import time
from .utils import paral_query, print_histo, parallel_query
_VALID_KWARGS = {"k1": None,
"k5": None,
"k10": None,
"min_dist_vec": None,
"n": None,
"MRR": None,
"mean": None}
class Indicators(o... | python |
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy import optimize
from PIL import Image
import PIL
import cv2
# pip install opencv-python pip install pillow
# Variables outside Loop
period, periodUncertainty = [],[]
graphDirectory = "Lab/Ter... | python |
import numpy
numpy.random.seed(0)
import CDAE
import movie_lens
import metrics
# data
train_users, train_x, test_users, test_x = movie_lens.load_data()
train_x_users = numpy.array(train_users, dtype=numpy.int32).reshape(len(train_users), 1)
test_x_users = numpy.array(test_users, dtype=numpy.int32).reshape(len(test_us... | python |
"""Bunny worker solutions
"""
import timeit
def solution(x, y, mode=1):
# This is essentially a Fibonacci sequence problem
if mode == 1:
# Calculate starting number
c_0 = 1
for i in range(1, y+1):
c_0 += i - 1
# Calculate ID
bunny_id = c_0
for i ... | python |
import torch
from torch import nn
from torch.nn import *
__all__ = ["Squeeze"]
class
| python |
import numpy as np
from spyne.models import NeuralNetwork
from spyne.layers import FullyConnectedLayer
# generate some data
x = np.random.normal(0, 1, (50000, 5))
y = 3.14 * x[:, 0] + 1.41 * np.square(x[:, 1]) - 2.72 * np.power(x[:, 1], 4) - 1.62 * x[:, 4]
train_x = x[:40000]
train_y = y[:40000]
test_x = x[40000:]... | python |
import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing
process = cms.Process("DISPLAY")
options = VarParsing.VarParsing ()
options.register ('file',
"xxx", # default value
VarParsing.VarParsing.multiplicity.singleton,
VarPars... | python |
"""
File: abstractstack.py
Author: Ken Lambert
"""
from abstractcollection import AbstractCollection
class AbstractStack(AbstractCollection):
"""An abstract stack implementation."""
def __init__(self, sourceCollection = None):
"""Sets the initial state of self, which includes the
contents of ... | python |
#!/usr/bin/env python
import imp
"""
service example
"""
resources_dir = 'RESOURCES_PATH'
mypydoc=imp.load_source('mypydoc',resources_dir+'/mypydoc.py')
mypydoc.cli()
| python |
from setuptools import setup
setup(
name='fgdb2postgis',
version=__import__('fgdb2postgis').get_current_version(),
description="""ESRI file geodatabase to PostGIS converter""",
long_description=open('README.rst').read(),
author='George Ioannou',
author_email='gmioannou@cartologic.com',
url=... | python |
"""
Generate results presented in selective indexing paper.
Three figures are generated, as well as a text file containing
precision and recall scores for ensemble, cnn, and combined models
at a series of thresholds.
"""
import json
import numpy as np
import sys
import pandas as pd
import matplotlib.pyplot as plt
fr... | python |
import os, tempfile, random, cStringIO
os.environ['MPLCONfigureDIR'] = tempfile.mkdtemp()
try:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.patches import Ellipse
except ImportError:
raise HTTP(200, "requires mathplotlib... | python |
user='simple_user'
pw='simple_user'
url='db:5432'
db='commentcloud'
| python |
# Copyright 2017-2020 Fitbit, Inc
# SPDX-License-Identifier: Apache-2.0
"""JLink related tasks"""
import re
import socket
from functools import reduce # pylint: disable=W0622
from invoke import task
from ..deps import version_check, build_instructions
@task
def check_version(ctx, abort=True):
'''Check if JLin... | python |
# 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... | python |
###############################################################################
#
# searcher.py - File search utility
#
###############################################################################
import fnmatch
import os.path
import re
import sys
import subprocess
import threading
import time
import... | python |
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (c) 2019 HERE Europe B.V.
#
# SPDX-License-Identifier: MIT
# License-Filename: LICENSE
#
###############################################################################
from ..common.error import make... | python |
from mmseg.ops import DepthwiseSeparableConvModule
from ..builder import HEADS
from .fcn_head import FCNHead
@HEADS.register_module()
class DepthwiseSeparableFCNHead(FCNHead):
"""Depthwise-Separable Fully Convolutional Network for Semantic
Segmentation.
This head is implemented according to Fast-SCNN pap... | python |
#Constroi o arquivo e path de backup e retorna
from datetime import datetime, date
class Datahora:
date = datetime.now()
print ( date.hour, ':', date.minute, ' ', date.day, '-',
date.month, '-', date.year )
class Backup:
@staticmethod
def gerabackup( backup ):
# date = (time.strftim... | python |
import time
import serial
import queue
from threading import Thread
from tkinter import *
PASSWORD = 'pms'
LOGIN_NUM = 3
def login_handler(pass_entry, info, q):
# Check if the entered password is correct.
text = pass_entry.get()
if text == PASSWORD:
# Inform other threads that user tried to lo... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import rospy
from actionlib import ActionClient, ActionServer
from actionlib_msgs.msg import GoalStatus
from rpn_recipe_planner_msgs.msg import RPNRecipePlannerAction
from rpn_recipe_planner_msgs.srv import RPQuery, RPQueryResponse
from rpn_recipe_planner_msgs.srv import RPUpda... | python |
__version__ = '0.3.0'
__description__ = 'The Keb Docker wrapper'
| python |
# Copyright 2021 The Pigweed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | python |
#!/usr/bin/env python3.9
"""
Sever driver, this should be run first
"""
from SockMonkey.Domain.Client.cli import main as cli_main
from SockMonkey.Domain.Server.server import main as server_main
# cli_main()
server_main([])
| python |
# -*- coding: utf-8 -*-
# PyAlgoTrade
# @ rebuild by chinese xuefu@pyalgteam.sdu,please call me leiFeng.<sdu.xuefu@gmail.com>
# 实现tushare的livefeed读写,与tushare格式兼容,同时允许自定义在开始livefeed前加载前面n天或者小时等的历史数据,请教我雷锋
# 饿肚子饿到下午
# Copyright 2011-2015 Gabriel Martin Becedillas Ruiz
# Licensed under the Apache License, Version 2.0 (the... | python |
import abc
from typing import Optional
import logging
logger = logging.getLogger(__name__)
use_keyring = True
"""
``use_keyring`` is a :class:`bool` which denotes whether it is possible to use
:class:`KeyringSecretStore`.
"""
try:
import keyring
logger.info('Using keyring')
except ModuleNotFoundError:
... | python |
import sys
XOR_KEY = 0xFF
CHUNK_SIZE = 2048
def main():
file_name = 'gta3.img'
with open(file_name, 'rb') as infile, \
open(file_name + '-xor', 'wb') as outfile:
for chunk in iter(lambda: infile.read(CHUNK_SIZE), b''):
xored = bytearray(chunk)
for i, _ in enumerate(xore... | python |
from django.conf.urls import url
from .views import ReleaseList, Artifact, GroupsRelaseList
app_name = 'mystery'
urlpatterns = [
url(r'^release/list$', ReleaseList.as_view(), name='release_list'),
url(r'release/(?P<release>[0-9]*)$', Artifact.as_view(),
name='artifact_view'),
url(r'release/group/(?... | python |
import os
from datetime import datetime as dt
from datetime import timedelta as td
from typing import Any, List, Set, Tuple
import shutil
import pandas as pd
from formsite_util.core import FormsiteCredentials, FormsiteInterface, FormsiteParams
from formsite_util.downloader import _FormsiteDownloader
def init... | python |
"""Contains code for training model"""
import pickle
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms
from torch.nn.utils.rnn import pack_padded_sequence
from .models import EncoderCNN, DecoderRNN
from .dataset import get_loader
BATCH_SIZE = 32
EMBEDDING_DIM = 300
HID... | python |
"""Add requires_validator_role in project table
Revision ID: 5581aa8a3cd
Revises: 11695ee852ff
Create Date: 2017-01-10 11:18:46.081801
"""
# revision identifiers, used by Alembic.
revision = '5581aa8a3cd'
down_revision = '11695ee852ff'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_colum... | python |
from itertools import cycle
from typing import List
import numpy as np
from pyNastran.utils.numpy_utils import integer_types
from pyNastran.op2.tables.oes_stressStrain.real.oes_objects import (
StressObject, StrainObject, OES_Object)
from pyNastran.f06.f06_formatting import write_floats_13e, write_floats_8p1e
c... | python |
import themata
project = 'Exotic Libraries'
copyright = '2021, Exotic Libraries - MIT License'
author = 'Exotic Libraries Contributors'
html_theme_path = [themata.get_html_theme_path()]
html_theme = 'water'
master_doc = 'index'
html_favicon = 'assets/images/libcester/exoticlibs.png'
html_static_path = ['_st... | python |
def max_sequence(listeners, price):
"""
Compute the maximum earnings for a sequence of length 'length'.
An instance of the maximum subarray problem.
:param listeners: list of listeners for each break slot
:param price: price per break
:return: maximum profit
"""
best = 0
cur_... | python |
"""Module containing tests for two-repo mode of the Chlorine algorithm."""
from . import test_repo1_dir, test_repo2_dir
from engine.preprocessing.module_parser import get_modules_from_dir
from engine.algorithms.chlorine.chlorine import chlorine_two_repos
def test_chlorine_two_not_none():
"""Check if two-repo mod... | python |
# Copyright 2017-present Michael Hall
#
# 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... | python |
import json
from http.server import BaseHTTPRequestHandler
from flair.models import SequenceTagger
from REL.mention_detection import MentionDetection
from REL.utils import process_results
API_DOC = "API_DOC"
"""
Class/function combination that is used to setup an API that can be used for e.g. GERBIL evaluation.
"""... | python |
# MIT License
#
# Copyright (c) 2020 Archis Joglekar
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | python |
# coding: utf-8
"""
SCORM Cloud Rest API
REST API used for SCORM Cloud integrations.
OpenAPI spec version: 2.0
Contact: systems@rusticisoftware.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# pyth... | python |
import depthai #core packages
import logging # Logger
import cv2 # computer vision package
import json #json lib
from time import time, sleep, monotonic
from pathlib import Path #Path lib
from config import model, calib
# Object Tracker
from tracker import Tracker
from collision_avoidance import CrashAvoidance... | python |
from cranlock import main, lock
| python |
from django.urls import path
from . import views
urlpatterns = [
path('', views.bundle_list, name='bundles'),
path('<int:bundle_id>/', views.bundle_view, name='bundle'),
path('search/', views.bundle_search, name='search_bundles'),
]
| python |
class Encapsulada:
atributo_visible = 'soy visible'
_atributo_protegido = 'soy protegido'
__atributo_privado = 'soy un atributo privado'
def get_atributo_privado(self):
return self.__atributo_privado
def set_atributo_privado(self, cambio):
self.__atributo_privado = cambio
| python |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import os
import subprocess
import yaml
from git.git_repository import GitRepository
from manifests.bundle_manifest import Bu... | python |
from __future__ import print_function, division
#
import sys,os
os.environ['KMP_DUPLICATE_LIB_OK']='True' # uncomment this line if omp error occurs on OSX for python 3
os.environ['OMP_NUM_THREADS']='1' # set number of OpenMP threads to run in parallel
os.environ['MKL_NUM_THREADS']='1' # set number of MKL threads to run... | python |
from django.forms import SelectMultiple, HiddenInput
from django_filters import MultipleChoiceFilter
from service_catalog.models import Instance, Service
from service_catalog.models.instance import InstanceState
from Squest.utils.squest_filter import SquestFilter
class InstanceFilter(SquestFilter):
class Meta:
... | python |
#Import basic modules
import os, re
#Import local .py modules
from . import Utils
echo = Utils.echo
#Class to build a conditional tree to compare notes
class Node:
def __init__(self, string, depth = 0, removeBrackets = True):
self.children = []
if removeBrackets:
self.setString(strin... | python |
arquivo = open("dados.txt", "rt") #para ler oarquivo
arquivo = open("dados.txt", "wt+") #para escrver o aquivo, caso ele n exista criar
frase = []
frase.append('Olá \n')
frase.append('eu quero \n')
frase.append('cagarrr \n')
arquivo.writelines(frase)
print(arquivo.readline())
| python |
# This code sample uses the 'requests' library:
# http://docs.python-requests.org
import requests
import os
url = "https://api.trello.com/1/lists"
board_pos = int(os.environ.get("DAYS_OUT")) + 2
query = {
'key': os.environ.get("TRELLO_KEY"),
'token': os.environ.get("TRELLO_TOKEN"),
'name': os.environ.get("FO... | python |
"""Unit tests for cira_satellite_io.py."""
import unittest
from ml4tc.io import cira_satellite_io
TOLERANCE = 1e-6
TOP_DIRECTORY_NAME = 'foo'
CYCLONE_ID_STRING = '1998AL05'
VALID_TIME_UNIX_SEC = 907411500
SATELLITE_FILE_NAME = 'foo/1998/1998AL05/AL0598_19982761045M.nc'
class CiraSatelliteIoTests(unittest.TestCase)... | python |
'''
Submitted by: Ansh Gupta(@ansh422)
Date: 18/10/2021
'''
def isSafe(x,y,val,grid):
for i in range(9):
if grid[x][i] == val or grid[i][y] == val:
return False
for i in range(3):
for j in range(3):
if grid[i+(x-x%3)][j+(y-y%3)] == val:
return Fa... | python |
class Solution(object):
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
i=j=0
while i<len(s) and j<len(t):
if s[i]==t[j]:
i+=1
j+=1
else:
j+=1
return True if i==len(s) else False | python |
# Copyright 2020-2021 Exactpro (Exactpro Systems 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... | python |
import numpy as np
from scipy.stats import dirichlet
from scipy.special import psi, polygamma, gammaln
eps = 1e-100
max_iter = 10
converge_criteria = 0.001
def parameter_estimation(theta, old_alpha):
"""Estimating a dirichlet parameter given a set of multinomial parameters.
Parameters
----------
... | python |
# 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 b... | python |
from google.appengine.ext import ndb
# Keep the details of articles
class Article(ndb.Model):
# The parent of an Entry is Account
dateCreated = ndb.DateProperty()
lastEdited = ndb.DateProperty(indexed = True) # indexed = True is only useful for changing previous indexed = False
content = ndb.TextProperty()
titl... | python |
# module binary
import sys
sys.path.append('..')
from astropy import units as u
from astropy import constants as const
import astropy
import numpy
import numpy as np
import math
import timeit
import zams
import argparse
import System
from scipy.integrate import trapz
def parse_commandline():
parser = argparse.A... | python |
import pandas as pd
import numpy as np
#Returns number of cells in dataframe that are missing in percent
def calc_missing_values(df: pd.Series) -> float:
missing_per_column: pd.Series = df.isnull().sum()
total_missing: int = missing_per_column.sum()
total_number_cells = np.product(df.shape)
return total_missin... | python |
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
i=0
j=1
while i<=len(nums)-2:
if nums[i]==nums[j]:
return nums[j]
i+=1
j+=1
| python |
"""Cascade Mask RCNN with ResNet50-FPN, 3x schedule."""
_base_ = [
"../_base_/models/cascade_mask_rcnn_r50_fpn.py",
"../_base_/datasets/bdd100k.py",
"../_base_/schedules/schedule_3x.py",
"../_base_/default_runtime.py",
]
load_from = "https://dl.cv.ethz.ch/bdd100k/ins_seg/models/cascade_mask_rcnn_r50_fp... | python |
from gym.envs.registration import register
register(
id='HybridHammerEnv-v1',
entry_point='environments.metaworld.constructors:HybridHammerEnvV1',
max_episode_steps=200,
kwargs={'mode': 'train'}
)
register(
id='HybridDcEnv-v1',
entry_point='environments.metaworld.constructors:HybridDrawerClose... | python |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
from datetime import datetime, timedelta
from .common.base import BaseResource
from ..libs.respository import create_repo
from ..models.models import PipelineRPS
from ..schemas.pipeline_rps import (
PipelineRPSPostSchema,
PipelineRPSGetSchema,
PipelineRPSSchema
)
from flask import request, jsonify
from fl... | python |
'''
SAT Solver based on Davis–Putnam–Logemann–Loveland (DPLL) algorithm
Uses Jersolow-Wang 2-sided method (consider only positive literals)
Returns -
* SATISFIABLE followed by the model if the formula is satisfiable
* UNSATISFIABLE if the formula is unsatisfiable
'''
# Import necessary libraries
import argp... | python |
# coding=utf-8
from django.contrib import admin
from django.utils.html import format_html_join, format_html
from .models import NewsItem
@admin.register(NewsItem)
class NewsItemAdmin(admin.ModelAdmin):
readonly_fields = ('formatted_text',)
list_display = ('publish_date', 'get_title', 'source')
list_displ... | python |
from __future__ import absolute_import
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django_rq import queues
from redis import RedisError
from rq import Worker
from ..constants import OK, WARNING, ERROR
from ..decorators import timed
from . import Resource
class Djang... | python |
from .odeConstructs import *
from .EditorPanel import *
from direct.directtools.DirectCameraControl import *
from direct.tkpanels import Placer
from .PinballElements import *
import shutil
class PinballEditor:
__module__ = __name__
def __init__(self, bw, dfn):
self.defaultFilename = dfn
self.b... | python |
#==========================================================================
#===============================
a = int(input("Enter first number: "))
b= int(input("Enter second number: "))
c= int(input("Enter third number: "))
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest =b
... | python |
# Copyright (C) 2011 Victor Semionov
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and t... | python |
import os
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'project_demo'
USERNAME = 'root'
PASSWORD = 'zxcvBnm123'
DB_URI = 'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8' % (USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG = True
SECRET_KEY = o... | python |
#!/usr/bin/env python3
import argparse
import os
import serial
import struct
import sys
import time
from esp8266 import ESP8266, CLOSED
def expect(a, b):
if a == b:
return
print(f'Mismatch: {a} versus {b}', file=sys.stderr)
assert(0)
def sanity_check(ser):
'''Check sanity of current rate'''
... | python |
class CalculadorImposto:
def calcula(self, orcamento, imposto):
return imposto.calcula(orcamento)
| python |
#!/usr/bin/python
#
#./transformer.py input.csv transformations.csv > output.csv
##
#
# A Python program to read a csv file extract from a cell the content and replace
# elements with the tranformations rules.
# Program name - transformer.py
# Written by - Catalin Stanciu (catacsdev@gmail.com)
#
# Example:
# transfo... | python |
import time
EXIT_WIN_DELAY = 5 # [EXIT_WIN_DELAY] = s
class TicTacToe(object):
def __init__(self):
self.fields = []
self.reset()
def reset(self):
self.fields = [['' for _ in range(3)] for _ in range(3)]
def set_field(self, x, y, player):
self.fields[y][x] = player
... | python |
import datetime
import os
try:
from .ignore2 import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
except:
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID", "AKIAV2BJVZP6UY2H44NZ")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY", "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")
AWS_GROUP_NAME = ... | python |
from setuptools import setup
from pypaystack import version
setup(name='pypaystack',
version=version.__version__,
description='Python wrapper for Paystack API',
url='https://github.com/edwardpopoola/pypaystack',
author=version.__author__,
author_email='edwardpopoola@gmail.com',
license=version.... | python |
import FWCore.ParameterSet.Config as cms
from SimFastTiming.FastTimingCommon.fastTimeDigitizer_cfi import *
from SimFastTiming.FastTimingCommon.mtdDigitizer_cfi import *
from SimFastTiming.FastTimingCommon.mtdDigitizer_cfi import _barrel_bar_MTDDigitizer
from Configuration.Eras.Modifier_phase2_timing_layer_bar_cff i... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.