content stringlengths 5 1.05M |
|---|
import torch
import torchvision
import os.path
if (not os.path.isfile("./models/maskrcnn_resnet50_fpn.pt")) :
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
model.eval()
script_model = torch.jit.script(model)
script_model.save("./models/maskrcnn_resnet50_fpn.pt")
if (not ... |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import csv
import cv2
import itertools
import json
import numpy as np
import pickle
import time
__all__ = ['House']
###############... |
import torch
from Transfromer import Transformer
from config import ngpu, device, save_dir, num_layers, d_model, num_heads, dff, dropout_rate, MAX_LENGTH, BATCH_SIZE
from utils import create_mask, mask_accuracy_func, mask_loss_func
from sklearn.model_selection import train_test_split
import torchtext
from dataset impor... |
# -*- coding: utf-8 -*-
"""
@author: MAQ
"""
def seq_search_unord(l, el):
itr = 0
for i in l:
itr = itr+1
if i == el:
return itr
return False
def seq_search_ord(l, el):
itr = 0
for i in l:
itr = itr+1
if i > el:
return False
elif i =... |
# 144. Binary Tree Preorder Traversal
# Runtime: 28 ms, faster than 85.09% of Python3 online submissions for Binary Tree Preorder Traversal.
# Memory Usage: 14.3 MB, less than 12.95% of Python3 online submissions for Binary Tree Preorder Traversal.
# Definition for a binary tree node.
# class TreeNode:
# def __... |
import pytest
from app import app as flask_app
@pytest.fixture
def set_up_client():
flask_app.testing = True
client = flask_app.test_client()
yield client
@pytest.fixture()
def set_up_url():
url = 'http://0.0.0.0:5000/test'
yield url
def test_get_request(set_up_client, set_up_url):
get_res... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import argparse
import os
from typing import Any, Dict
import yaml
from normalization.destination_type import DestinationType
from normalization.transform_catalog.catalog_processor import CatalogProcessor
class TransformCatalog:
"""
To run this trans... |
# Status codes
OK = 200
ACCEPTED = 202
NO_CONTENT = 204
FORBIDDEN = 403
NOT_FOUND = 404
INTERNAL_SERVER_ERROR = 500
|
import json
import numpy as np
from opentrons import robot, instruments
from opentrons import deck_calibration as dc
from opentrons.deck_calibration import endpoints
from opentrons.config import robot_configs
from opentrons import types
# Note that several tests in this file have target/expected values that do not
... |
from tkinter import *
#create a new GUI window
window = Tk()
window.title("A Window")
#a label
lbl = Label(window,text="A Label")
lbl.pack()
#an 'entry' textbox
txt = Entry(window)
txt.pack()
#a button
btn = Button(window,text="A Button")
btn.pack()
window.mainloop()
|
import comet_ml
def log_extra(config, f1_score):
current_experiment = comet_ml.get_global_experiment()
afterlog_experiment = comet_ml.ExistingExperiment(previous_experiment=current_experiment.get_key())
exp_name = f"{config['dataset_name']}:{config['kmer_len']}:{config['stride']}:freeze={config['freeze']}:L... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 agree... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum, auto
from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union
from typing_extensions import final
... |
#!/usr/bin/env python3
import pandas as pd # Read CSV
import requests # Make web requests
import os
from tqdm.auto import tqdm # Progress bar
import glob # Matching filenames
files = glob.glob("*.csv")
for file in files:
df = pd.read_csv(file)
for i,row in tqdm(df.iterrows(), total=df.shape[0]):
url ... |
from cStringIO import StringIO
SEPARATOR = None
def print_table(fields, rows):
widths = {}
for field in fields:
widths[field] = len(field)
for row in rows:
if row is SEPARATOR:
continue
try:
widths[field] = max(widths[field],
... |
import pprint
data = {'created_at': '2021-12-15T01:14:28Z',
'description': 'Measured temperature by the Si7021 sensor connected to '
'Adafruit Feather Huzzah32.',
'enabled': True,
'feed_status_changes': [],
'feed_webhook_receivers': [],
'group': {'id': 55706,
'key': 'feather-iot',
... |
import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.uptime
def build_module():
config = core.config.Config([])
return modules.contrib.uptime.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class UptimeTest(TestC... |
from __future__ import print_function
import roslib
roslib.load_manifest('mct_camera_tools')
import rospy
import sys
from mct_camera_tools import camera_master
camera_master.set_camera_launch_param('calibration', False)
print(camera_master.get_camera_launch_param())
#camera_master.set_camera_launch_param('tracking', ... |
'''
Hello! Thank you for downloading a CORGIS library. However, you do not
need to open this file. Instead you should make your own Python file and
add the following line:
import police_shootings
Then just place the files you downloaded alongside it.
'''
import os as _os
import pickle as _pickle
__all__ = ['get_sho... |
from __future__ import print_function
"""
read_dsv.py
Author: Vasudev Ram
Web site: https://vasudevram.github.io
Blog: https://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
Purpose: Shows how to read DSV data, i.e.
https://en.wikipedia.org/wiki/Delimiter-separated_values
from either files or st... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_window.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWi... |
#!/usr/bin/env python3
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import sys
from readmemaker import ReadmeMaker
PROJECT_NAME = "typepy"
OUTPUT_DIR = ".."
def write_examples(maker):
maker.set_indent_level(0)
maker.write_chapter("Usage")
maker.write_introduction_file("usag... |
"""
authenticators: the server instance accepts an authenticator object,
which is basically any callable (i.e., a function) that takes the newly
connected socket and "authenticates" it.
the authenticator should return a socket-like object with its associated
credentials (a tuple), or raise AuthenticationError if it ... |
# coding: utf8
from __future__ import unicode_literals
from ...symbols import ORTH, LEMMA, NORM, PRON_LEMMA
_exc = {}
for exc_data in [
{ORTH: "ት/ቤት", LEMMA: "ትምህርት ቤት"},
{ORTH: "ወ/ሮ", LEMMA: PRON_LEMMA, NORM: "ወይዘሮ"},
]:
_exc[exc_data[ORTH]] = [exc_data]
for orth in [
"ዓ.ም.",
"ኪ.ሜ.",
]:... |
"""
Common meta-analytic workflows
"""
from .ale import ale_sleuth_workflow
from .conperm import conperm_workflow
from .macm import macm_workflow
from .peaks2maps import peaks2maps_workflow
__all__ = ['ale_sleuth_workflow', 'conperm_workflow', 'macm_workflow',
'peaks2maps_workflow']
|
import os
from typing import Literal
CWD = os.getcwd()
MODEL_NAME = "lstm"
DATA_PATH = f"/data/kindle_reviews.csv"
GLOVE_PATH = f"/data/glove.6B.50d.txt"
MODEL_PATH = f"/data/'MODEL_NAME'.h5"
SEED: int = 42
TRAIN_SIZE: float = 0.8
MAX_NB_WORDS: Literal[100000] = 100000
MAX_SEQUENCE_LENGTH: Literal[30] = 30
EMBEDD... |
print('Calculo do aumento do salario de funcionario em 15%')
n=int(input('Qual o salario atual do funcionario?'))
p=n*0.15
a=n+p
print('O salario do funcionario com aumento é {:.2f}!'.format(a))
|
def zmozi_sez(sez):
stevilo = 1
for x in sez:
stevilo *= x
return stevilo
def najmajši_zmonzek(n=20):
stevila = [2]
for x in range(3,n+1):
stevilo = x
trenuta_stevila = stevila
for y in trenuta_stevila:
if stevilo % y == 0:
... |
from scipy import misc
f = misc.face()
misc.imsave('face.jpg', f) # uses the Image module (PIL)
import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
|
import factory
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.utils import timezone
from ..models import Tag, TaggedItem
from .models import TagTestArticle0, TagTestArticle1
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = settings.AUT... |
#!/usr/bin/env python
# encoding: utf-8
# John O'Meara, 2006
# Thomas Nagy 2009
"Bison processing"
from waflib import Task, TaskGen
import os
bison = '${BISON} ${BISONFLAGS} ${SRC[0].abspath()} -o ${TGT[0].name}'
cls = Task.task_factory(
'bison', bison, color='CYAN', ext_in=['.yc', '.y', '.yy'], ext_out='.cxx .h... |
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/text-wrap/problem
# Difficulty: Easy
# Max Score: 10
# Language: Python
# ========================
# Solution
# ========================
import textwrap # Solution made without using... |
import argparse
import json
import sys
parser = argparse.ArgumentParser(description="Python script updates the channels_EP.json file")
parser._action_groups.pop() # removing optional argument title because I want to show required args before optional
#setting up required arguments
requiredArgs = parser.add_argument_g... |
import threading
import logging
import time
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s [%(threadName)s] %(message)s')
def worker(lock):
with lock:
logging.debug("ha ha ha ")
if __name__ == '__main__':
lock = threading.Lock()
t1 = threading.Thread(target=worker, na... |
# Copyright (c) 2019-2022, NVIDIA CORPORATION.
import glob
import math
import os
import numpy as np
import pandas as pd
import pytest
from packaging.version import parse as parse_version
import dask
from dask import dataframe as dd
from dask.utils import natural_sort_key
import cudf
import dask_cudf
# Check if cr... |
# Generated by Django 2.2.7 on 2019-11-27 16:01
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Hotel',
fields=[
('id', models.AutoField(au... |
from vyper.exceptions import InvalidLiteralException
def test_function_with_units(get_contract_with_gas_estimation):
code = """
units: {
N: "Newton",
m: "Meter",
s: "Second",
}
@public
def foo(f: uint256(N), d: uint256(m), t: uint256(s)) -> uint256(N*m/s**2):
return f * d / (t * t)
@public
def ba... |
from .nexe import Nexe
from .pkg import Pkg
|
#!/usr/bin/env python
from unittest import TestCase
from boutiques import bosh
from boutiques import __file__ as bfile
from jsonschema.exceptions import ValidationError
import json
import os
import os.path as op
from os.path import join as opj
import pytest
from boutiques.importer import ImportError
import boutiques
i... |
import torch
from .base import Flow
# Flow layers to reshape the latent features
class Split(Flow):
"""
Split features into two sets
"""
def __init__(self, mode='channel'):
"""
Constructor
:param mode: Splitting mode, can be
channel: Splits first feature dimensio... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
from flask import (Flask, render_template, jsonify)
from .markov import Markov
with open(sys.argv[1], "rb") as f:
drjc_facts = map(str, f)
app = Flask(__name__)
drjc = Markov(drjc_facts)
@app.route("/")
def index():
return render_template("index.html", fact... |
import json
from flask import Flask
app = Flask(__name__)
@app.route("/")
def patientpage():
with open("patient.json") as patientfile:
data = json.load(patientfile)
return data
if __name__=="__main__":
app.run(debug=True, use_reloader=True)
|
from stg.api import PulseFile, STG4000
# we initialize the STG and print information about it
stg = STG4000()
print(stg, stg.version)
# create a pulsefile with default parameters
p = PulseFile()
# compile the pulsefile and expand the tuple to positional arguments
# and download it into channel 1
# As you can see, ind... |
from __future__ import print_function
from builtins import str
from builtins import object
from collections import defaultdict
class GapMasker(object):
def __init__(self, template):
self.template = template
self.gap_positions = self.get_gap_positions()
def get_gap_positions(self):
gap... |
from finbot.core.environment import get_snapwsrv_endpoint
from finbot.clients import SnapClient
import pytest
@pytest.fixture
def api() -> SnapClient:
return SnapClient(get_snapwsrv_endpoint())
def test_healthy(api: SnapClient):
assert api.healthy
|
import json
from django.http import response
from django.shortcuts import render
import base64
from django.http.response import HttpResponse, JsonResponse
from rest_framework import status, decorators
from rest_framework.decorators import api_view, parser_classes
from myapi.models import RegdevData, RegtseData, Request... |
n = input("Digite seu nome: ")
print('Olá, {}! É um prazer te conhecer.'.format(n))
|
#!/usr/bin/python3
# MIT License
#
# Copyright (c) 2017 Marcel de Vries
#
# 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 us... |
#!/usr/bin/env python
import sys
import os
import getopt
import time
if sys.version_info < (3,0):
import ConfigParser
else:
import configparser as ConfigParser
import aliyun
import logging
import logging.handlers
# Set the global configuration
CONFIG_FILENAME = 'config.ini'
configFilepath = os.path.split(os.p... |
import cv2
from cv_object_detector import CVTFObjectDetector
IMAGE = "/home/nj/Desktop/CV/Dataset/DS/images/CV19_image_106.png"
FROZEN_GRAPH = "/home/nj/Desktop/CV/Trained_Models/FRCNN_Tray.pb"
PBTEXT = "/home/nj/Desktop/CV/Dataset/Trained/FRCNN_TRAY/opencv_frcnn_tray.pbtxt"
LABELS = {0: "Walnut",
1: "Pe... |
# pylint: disable=missing-module-docstring
# pylint: disable=missing-function-docstring
from unittest import mock
import pytest
from sql_judge.parse_configuration import build_configuration
# ConfigurationBuilder.is_valid
def test_empty_builder_is_invalid():
assert build_configuration.default().is_valid() is Fa... |
from zion.gateways.docker.protocol import Protocol
from zion.gateways.docker.function import Function
from zion.gateways.docker.worker import Worker
import time
class DockerGateway():
def __init__(self, be):
self.be = be
self.req = be.req
self.conf = be.conf
self.logger = be.logge... |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
import sys
import unittest
import numpy as np
import torch
import torch.nn.functional as F
import lava.lib.dl.slayer as slayer
verbose = True if (('-v' in sys.argv) or ('--verbose' in sys.argv)) else False
seed = np.random.randint(1000)... |
import os
import random
import numpy as np
import json
import doctest
from decitala import fragment
from decitala.fragment import (
Decitala,
DecitalaException,
GreekFoot,
Breve,
Macron,
ProsodicMeter,
GeneralFragment,
FragmentEncoder,
FragmentDecoder,
get_all_prosodic_meters,
prosodic_meter_query
)
from de... |
// Fizzzzz.......Buzzzzzzzzzz
//Author: @BreathlessVictor on GitHub
//email: sombit0503@gmail.com
for i in range (101):
if i % 3 == 0:
print ("Fizz")
elif i % 5 == 0:
print ("Buzz")
elif i % 3 == 0 and i % 5 == 0:
print ("FizzBuzz")
else:
print(i)
|
# -*- coding: utf-8 -*-
# type: ignore
"""Store simple data between multiple executions of a script.
A simple class to store small amounts data between
multiple executions of a script (for one-off scripts).
Copyright: Manuel Barkhau 2020 Dedicated to the public domain.
CC0: https://creativecommons.org/publicdomain/ze... |
# ignore alignability for the moment, we'll assume everything within 100bp of a read is alignable
import numpy
import argparse
import pysam
from string import maketrans
SAMPLE_MARGIN = 25 # on either side
CHROMS = None
COMPL = maketrans("ACGT", "TGCA")
def readWig(wig_file):
fin = open(wig_file, 'r')
masks = {}
... |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import math
import torch
from torch import nn
from torch.autograd import Function
from torch.nn.modules.utils import _pair
from torch.autograd.function import once_differentiable
import L... |
import os
import csv
import tensorflow as tf
BUFFER_SIZE=10000
def load_dataset(datapath, vocab, dimesion=0, splits=["split_1", "split_2", "split_4", "split_8", "split_16"]):
dataset = []
data = csv.DictReader(open(datapath, "r"))
midi_paths = []
for row in data:
filepath, valence, arousal =... |
from sqlalchemy import Table, Column, MetaData, select, testing
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import JSONB, JSON
from sqlalchemy.orm import sessionmaker
from sqlalchemy.testing import fixtures
from sqlalchemy.types import Integer
from sqlalchemy import JSON... |
# -*- coding: utf-8 -*-
class UmaClasse(object):
def metodo_1(self):
pass
def metodo_2(self, param, param2=None):
pass
def funcao_1():
if True:
pass
a = 1
b = 2
return a * b
|
from django.urls import path
from . import views
app_name = 'servers'
urlpatterns = [
path('', views.index, name='index'),
path('add/', views.add, name='add'),
path('edit/<int:id>', views.edit, name='edit'),
path('delete/<int:id>', views.delete, name='delete'),
path('reset/', views.reset, name='re... |
from django.test import TestCase
from django.core.management import call_command
from ..models import Report, Cluster
class CustomCommandTest(TestCase):
def setUp(self):
# Building dataset for test
keys = ('latitude', 'longitude', 'category')
data = (
(-22.0003, -43.0002, 'F')... |
import sqlite3
from contextlib import closing
dados = [
["São Paulo", 43663672], ["Minas Gerais", 21292666], ["Rio de Janeiro", 17366189],["Bahia", 14930634],
["Paraná", 11516840], ["Rio Grande do Sul", 11422973], ["Pernambuco", 9616621], ["Ceará", 9187103],
["Pará", 8690745], ["Santa Catarina", 7252502],... |
#!/usr/bin/env python
import getopt
import json
import os
import shutil
import subprocess
import sys
import urllib2
# colors for pretty printing
COLOR_FAIL = '\033[91m'
COLOR_ENDC = '\033[0m'
# Platform build paths
BUILD_PATH_IOS = "build-ios"
BUILD_PATH_MAC = "build-mac"
BUILD_PATH_LINUX = "build-linux"
BUILD_PATH_... |
from Adafruit_LED_Backpack import AlphaNum4
class DisplayManager(object):
def __init__(self, **displays):
self.displays = {}
for name, addr in displays.items():
self.register_display(name, addr)
def register_display(self, name, address=0x70, **kwargs):
for check_name, check... |
from __future__ import division
import collections
import itertools
from typing import (List, Dict, Callable, Tuple, Iterable, Set, Counter, Union,
Optional)
NGramsType = Counter[Tuple[str]]
ScoreType = Dict[str, float]
RougeType = Dict[str, Dict[str, float]]
try:
from math import isclose
exc... |
from rest_framework import viewsets
from rest_framework.viewsets import ModelViewSet
from .models import Supermarket, Product, ProductType, GroceryList
from .serializers import SupermarketSerializer, SupermarketProductSerializer, \
SupermarketProductTypeSerializer, SupermarketGroceryListSerializer
class ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 21 12:33:00 2022
Author: Gianluca Bianco
"""
#################################################
# Libraries
#################################################
import doctest
from termcolor import colored
import numpy as np
import matplotlib.pyplot... |
from yaetos.etl_utils import ETL_Base, Commandliner
from pyspark.sql.types import StructType
class Job(ETL_Base):
def transform(self):
return self.sc_sql.createDataFrame([], StructType([]))
if __name__ == "__main__":
args = {'job_param_file': 'conf/jobs_metadata.yml'}
Commandliner(Job, **args)
|
import os
import environ
from pathlib import Path
from django.utils.translation import gettext_lazy as _
BASE_DIR = Path(__file__).resolve().parent.parent
ENV_PATH = os.path.join(BASE_DIR, '.env')
env = environ.Env()
if os.path.isfile(ENV_PATH):
environ.Env.read_env(env_file=ENV_PATH)
SECRET_KEY = env('DJ_SECRE... |
import dataclasses
import typing
import pytest
from dataclasses_avroschema import AvroModel, types
@pytest.fixture
def user_dataclass():
@dataclasses.dataclass(repr=False)
class User(AvroModel):
name: str
age: int
has_pets: bool
money: float
encoded: bytes
cl... |
import torch
D_TYPE = torch.float32
DEVICE = torch.device(f"cuda:{torch.cuda.device_count() - 1}" if torch.cuda.is_available() else "cpu")
|
import numpy as np
import torch
def np_softmax(x):
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=-1)
def get_network_weights(network, exclude_norm=False):
"""
Args:
network: torch.nn.Module, neural network, e.g. actor or critic
exclude_norm: True if layers corresponding to no... |
from mind_mapper.models import Model
class Annotation(Model):
def __init__(self, **kwargs):
if kwargs:
self.text = kwargs["text"]
else:
self.text = ""
def __str__(self):
return "<annotation>\n" +\
self.serialize_text(self.text) +\
"\n</... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.fsl.preprocess import FAST
def test_FAST_inputs():
input_map = dict(args=dict(argstr='%s',
),
bias_iters=dict(argstr='-I %d',
),
bias_lowpass=dict(argstr='-l %d',
units='mm',
... |
import numpy as np
import logging
from timeit import default_timer as timer
from scipy.optimize import fmin_l_bfgs_b, basinhopping
import torch
import torch.nn.functional as F
from v1_metrics import compute_eer
import data_reader.adv_kaldi_io as ako
"""
validation without stochastic search for threshold
important: EE... |
from litepcie.core.endpoint import LitePCIeEndpoint
from litepcie.core.msi import LitePCIeMSI
|
from enum import Enum
from singleton import Singleton
class ActiveLayerIdentifier(Enum):
A = 0
B = 1
class ActiveLayer(metaclass=Singleton):
def __init__(self):
self._active_layer = ActiveLayerIdentifier.A
self._layer_change_events = []
self._activity_events = []
@property
... |
#!/usr/bin/env python
# BinBashCord, Discord quote bot based on an IRC quote bot.
# BinBashCord is Copyright 2017-2018 Dylan Morrison based on code
# Copyright 2010 Dylan Morrison
# See LICENSE file for licensing.
# Users: Edit these
TOKEN="" # Discord authentication token for the bot.
CHANNELIDS=[] ... |
from keras.optimizers import Optimizer
from keras.legacy import interfaces
from keras import backend as K
class QHAdam(Optimizer):
def __init__(self, lr=0.001, beta_1=0.999, beta_2=0.999, v1=0.7, v2=1., epsilon=1e-3, **kwargs):
super(QHAdam, self).__init__(**kwargs)
with K.name_scope(self.__class_... |
# Generated by Django 3.2.2 on 2021-06-03 09:17
import django.db.models.deletion
import i18nfield.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('pretixbase', '0191_event_last_modified'),
]
operations = [
migr... |
"""
Define a Pet class with their attributes
"""
class Pet(object):
def __init__(self, name, speaks):
self.name = name
self.speaks = speaks
def full_name(self):
return f"{self.name}"
def speaks(self):
print({self.name} + ' speaks')
if __name__ ==... |
a = [10, 45, 67, 89, 34, 91, 15, 18, 34]
n = len(a)
print(a)
max = a[0]
for i in range(1, n):
if (max < a[i]): max = a[i]
print('Max = ', max) |
from collections import Counter
from itertools import count
from .common import dict_coords_as_str
from .day12 import cmp
from .day8 import iter_chunks
from .day9 import Interpreter
from .intcode import load_program_from_file
from .plane import Coord
EMPTY = 0
WALL = 1
BLOCK = 2
PADDLE = 3
BALL = 4
debug_colors = {... |
"""The hint for this problem directs us to the page source, which contains
a very large comment with a note saying "find rare characters". Send a get
request to the page and construct a BeautifulSoup parser to find the second
comment (the one with mess of characters) then use a dictionary to keep count
of all the chara... |
coordinates_E0E1E1 = ((123, 112),
(123, 114), (123, 115), (123, 116), (123, 117), (123, 118), (123, 119), (123, 120), (123, 121), (123, 122), (123, 123), (123, 124), (123, 126), (124, 112), (124, 127), (125, 112), (125, 114), (125, 115), (125, 116), (125, 117), (125, 118), (125, 119), (125, 120), (125, 121), (125, 12... |
# coding: utf-8
from fabric.api import task, env, require
from fabric.operations import sudo
from jetpack.helpers import RunAsAdmin
@task(task_class=RunAsAdmin, user=env.local_user, default=True)
def logs(lines=50):
require('PROJECT')
sudo('tail --lines=%s /var/log/%s.log' % (lines, env.PROJECT.appname))
|
import os.path
from visual_mpc.policy.cem_controllers import NCECostController
from visual_mpc.agent.benchmarking_agent import BenchmarkAgent
from visual_mpc.envs.mujoco_env.cartgripper_env.cartgripper_xz_grasp import CartgripperXZGrasp
BASE_DIR = '/'.join(str.split(__file__, '/')[:-1])
current_dir = os.path.dirname(o... |
# Generated by Django 3.1 on 2021-11-15 21:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orders', '0002_auto_20211018_2216'),
]
operations = [
migrations.AlterModelOptions(
name='orders',
options={'ordering': ('-cre... |
import pickle
import numpy as np
import cmfg
from Parser import Parser
from math import pi
from astropy import units as u
import itertools
from sklearn.neighbors import NearestNeighbors
from matplotlib import pyplot as plt
from random import random
from matplotlib import colors, ticker, rc
class MidpointNormalize(c... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
# In[2]:
txd = pd.read_csv("luceneDocVector.csv", header=None, sep='\t')
print(txd)
# In[3]:
txd.to_numpy()
# In[4]:
U, S, V = np.linalg.svd(txd)
S = np.diag(S)
k=50
Uk = U[:, :k]
Sk = S[:k, :k]
Vk = V[:k, :]
Ak = Uk.... |
import toml
import importlib
pytom = toml.load("pyproject.toml")
package_name = pytom["project"]["name"]
author_name = " - ".join(pytom["project"]["authors"])
doc_dir_name = "docs"
doctest_notebooks_glob = "notebooks/doc-*.ipynb"
mymodule = importlib.import_module(package_name)
boilerplate_branch = "django-app"
|
from rest_framework.response import Response
from rest_framework.views import APIView
from Harvest.utils import CORSBrowserExtensionView
from plugins.redacted_uploader.create_project import create_transcode_project
from upload_studio.serializers import ProjectDeepSerializer
class TranscodeTorrent(CORSBrowserExtensio... |
from distance_sensor_118x import DistanceSensor
sensor = DistanceSensor('/dev/USB_Distance')
sensor.open()
sensor.printSettings()
sensor.close()
|
from django.contrib import admin
# this code does not work i don't know why
# from customer.models import customer
from . import models as customer_model
# for using permalink only...
from django.urls import reverse
from django.utils.html import format_html
# for formfield_overrides only...
from django.forms import Tex... |
import unittest
from math import sqrt, ceil
def count_steps_to_center_from(x):
if x == 1:
return 0
# Get ring info
ring = int(ceil((sqrt(x) - 1) / 2)) # 0-based ring around the center.
side_length = 2*ring + 1 # Length of each of the 4 sides of the ring.
perimeter = ring * 8 ... |
from solana.publickey import PublicKey
VOTE_PROGRAM_ID = PublicKey("Vote111111111111111111111111111111111111111")
"""Program id for the native vote program."""
VOTE_STATE_LEN: int = 3731
"""Size of vote account."""
|
#!/usr/bin/env python
"""
Collect BigBOSS throughput pieces from bbspecsim into
Specter throughput format.
TODO: Factor our parameters at the top into a configuration file.
Stephen Bailey, LBL
January 2013
"""
import sys
import os
import numpy as N
import fitsio
from scipy.interpolate import InterpolatedUnivariate... |
"""
Using monotonic decreasing stack.
Time complexity: O(N)
Space complexity: O(1) not considering result.
"""
from typing import List
class Solution:
def findBuildings(self, heights: List[int]) -> List[int]:
mono_stack = []
for i in range(len(heights)):
while mono_stack and heights[i] ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.