text stringlengths 1 927k |
|---|
import os
os.system("")
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m' |
import inspect
import logging
import os
import shlex
import subprocess
import time
import typeguard
from contextlib import contextmanager
from typing import List
import parsl
from parsl.version import VERSION
logger = logging.getLogger(__name__)
@typeguard.typechecked
def get_version() -> str:
version = parsl._... |
# -*- coding: utf-8 -*-
# Spearmint
#
# Academic and Non-Commercial Research Use Software License and Terms
# of Use
#
# Spearmint is a software package to perform Bayesian optimization
# according to specific algorithms (the “Software”). The Software is
# designed to automatically run experiments (thus the code name
... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Attempt to generate templates for module reference with Sphinx
XXX - we exclude extension modules
To include extension modules, first identify them as valid in the
``_uri2path``... |
# -*- coding: utf-8 -*-
"""
@description: Download file.
"""
import hashlib
import os
import shutil
import sys
import tarfile
import time
import typing
import zipfile
from pathlib import Path
import numpy as np
import six
from six.moves.urllib.error import HTTPError
from six.moves.urllib.error import URLError
from si... |
from .languages import ProgrammingLanguage
from .estimations import Estimation, SizeEstimation, TypePart
from .programs import Program, Report, Pip
from .parts_of_code import ReusedPart, BasePart, NewPart |
# input_converter.py
# author: Playinf
# email: playinf@stu.xmu.edu.cn
import os
import six
import json
import random
import argparse
import tensorflow as tf
def load_vocab(filename):
fd = open(filename, "r")
count = 0
vocab = {}
for line in fd:
word = line.strip()
vocab[word] = cou... |
import numpy as np
import pandas as pd
import re, argparse, datetime
from timeit import default_timer
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer
from sklearn.model_selection import train_test_split, cross_validate
from sklearn.metr... |
# -*- coding: utf-8 -*-
# Copyright 2018 Microsoft Corporation
#
# 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 applic... |
import ast
import functools
import inspect
import re
import sys
import textwrap
import numpy as np
import taichi.lang
from taichi._lib import core as _ti_core
from taichi.lang import impl, runtime_ops
from taichi.lang.ast import (ASTTransformerContext, KernelSimplicityASTChecker,
transform... |
# model settings
model = dict(
type='CascadeRCNN',
pretrained='pytorch_resnext101.pth',
backbone=dict(
type='ResNeXt',
depth=101,
groups=32,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', require... |
SHOW_MARQUEE = "SHOW_MARQUEE"
SHOW_WINDOW = "SHOW_WINDOW"
HIDE_WINDOW = "HIDE_WINDOW" |
# -*- coding: utf-8 -*-
"""
@author: Rafaela e Eric
"""
'''
Questão 4:
Faça um programa que leia um número inteiro positivo
e em seguida monte a figura abaixo. (Não utilize vetor)
Exemplo:
Se o número digitado for n=0. Deverá aparecer na tela:
*
Se o número digitado for n=1. Deverá aparecer na tela:
*
*
Se o n... |
for i in range(1, int(input())+1):
print(i) |
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y) |
# -------------------------------------------------------------
#
# 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 unde... |
"""
Map p elements from hypothesis annotation pointers to XML ids in the collation chunk XML
"""
import json
import re
import warnings
from glob import glob
from os import path
from lxml import etree, html
from itertools import groupby
class Annotation:
def __init__(self, js):
self.data = json.loads(js)
... |
from argparse import ArgumentParser
from typing import Any
from django.core.management.base import BaseCommand, CommandError
from zerver.lib.actions import do_delete_old_unclaimed_attachments
from zerver.models import get_old_unclaimed_attachments
class Command(BaseCommand):
help = """Remove unclaimed attachmen... |
from rest_framework import serializers
from orchestra.api import router
from orchestra.contrib.accounts.models import Account
from orchestra.contrib.accounts.serializers import AccountSerializerMixin
from .models import Bill, BillLine, BillContact
class BillLineSerializer(serializers.HyperlinkedModelSerializer):
... |
from django.shortcuts import render,redirect
from django.http import HttpResponse , HttpResponseRedirect
from django.contrib.auth.models import User , auth
from django.contrib.auth import authenticate , login , logout
from django.contrib import messages
def home(request):
return render(request,'home.html')
def ha... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Feb-09-21 22:23
# @Author : Kelly Hwong (dianhuangkan@gmail.com)
import numpy as np
import tensorflow as tf
class XOR_Dataset(tf.keras.utils.Sequence):
"""XOR_Dataset."""
def __init__(
self,
batch_size=1,
shuffle=False,
... |
# Copyright 2019 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, ... |
# -*- coding: utf-8 -*-
from ccxt.base.exchange import Exchange
from ccxt.base.errors import ExchangeError
class paymium (Exchange):
def describe(self):
return self.deep_extend(super(paymium, self).describe(), {
'id': 'paymium',
'name': 'Paymium',
'countries': ['FR', ... |
# -*- coding: utf-8 -*-
#
# DNNを学習します.
#
# Pytorchを用いた処理に必要なモジュールをインポート
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch import optim
# 作成したDatasetクラスをインポート
from my_dataset import SequenceDataset
# 数値演算用モジュール(numpy)をインポート
import numpy as np
# プロット用モジュール(matplotlib)をインポート
import... |
import unittest
from cert_issuer.models import validate_issuance_date
class UnitValidationV3 (unittest.TestCase):
def test_validate_issuance_date_invalid_RFC3339 (self):
candidate = '20200202'
try:
validate_issuance_date(candidate)
except:
assert True
re... |
# Static variables are class level variables
# Static variables are always referenced by class name
# Local variables are local to methods
class Student:
school = 'PQR' #Static variable
def __init__(self,name,roll,section):
super().__init__()
self.name = name #Instance variable
self.r... |
import requests
import urllib
from collections import namedtuple
from certbot.plugins import dns_common
try:
from urllib import quote # Python 2.X
except ImportError:
from urllib.parse import quote # Python 3+
_GandiConfig = namedtuple('_GandiConfig', ('api_key',))
_BaseDomain = namedtuple('_BaseDomain', ('... |
# Generated by Django 3.0.6 on 2020-05-24 19:49
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
f... |
#!/usr/bin/env python3.8
# Copyright 2017 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Build script for a Go app.
import argparse
import os
import subprocess
import sys
import string
import shutil
import errno
from g... |
from arclet.alconna.types import ObjectPattern, add_check, ArgPattern, PatternToken
from arclet.alconna import AlconnaFire
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.message.element import Plain, Image, At, MusicShare
from graia.ariadne.app import Ariadne, MiraiSession
bot = Ariadne(connec... |
from importlib import import_module
from pydcop.algorithms import AlgorithmDef, ComputationDef, load_algorithm_module
from pydcop.computations_graph.constraints_hypergraph import \
VariableComputationNode
from pydcop.dcop.objects import Variable |
__all__ = [
'fetch_fsaverage'
]
from .fetchers import fetch_fsaverage |
#!usr/bin/python
# -*- coding: utf-8 -*-
"""
Package installation setup
"""
import os
import subprocess
from setuptools import find_packages, setup
version = '0.1.2a0'
sha = 'Unknown'
package_name = 'torchcam'
cwd = os.path.dirname(os.path.abspath(__file__))
try:
sha = subprocess.check_output(['git', 'rev-par... |
"""
sphinx.writers.latex
~~~~~~~~~~~~~~~~~~~~
Custom docutils writer for LaTeX.
Much of this code is adapted from Dave Kuhlman's "docpy" writer from his
docutils sandbox.
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import r... |
import sys
from common import *
def main(muse_score_path, directory_path):
muse_score_export(muse_score_path, directory_path, OutputFormat.pdf)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2]) |
import dash_bootstrap_components as dbc
from dash import html
spinners = html.Div(
[
dbc.Spinner(color="primary"),
dbc.Spinner(color="secondary"),
dbc.Spinner(color="success"),
dbc.Spinner(color="warning"),
dbc.Spinner(color="danger"),
dbc.Spinner(color="info"),
... |
#!/usr/bin/env python
# coding: utf-8
'''
Read multiple skeletons txts and saved them into a single txt.
If an image doesn't have skeleton, discard it.
If an image label is not `CLASSES`, discard it.
Input:
`skeletons/00001.txt` ~ `skeletons/xxxxx.txt` from `SRC_DETECTED_SKELETONS_FOLDER`.
Output:
`skeletons_i... |
# -*- coding: utf-8 -*-
import time
from celery_app import app
@app.task
@app.task(queue='test_celey_queue_multiply')
def multiply(x, y):
# time.sleep(0.02)
return x * y |
#!/usr/bin/python3
class InstructionNotRecognized(Exception):
''' Exception to throw when an instruction does not have defined conversion code '''
pass
reg_labels = """ .section .tdata
REG_BANK:
.dword 0
.dword 0
.dword 0
.dword 0
.dword 0
.dword 0
... |
#!/usr/bin/env python
#
# Copyright (c) 2014-2018 Apple Inc. All rights reserved.
# Copyright (c) 2014 University of Washington. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistribution... |
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Commander
# Copyright 2022 Keeper Security Inc.
# Contact: commander@keepersecurity.com
#
# Example script to run a BreachWatch status report, parse the results,
# and send users an email r... |
from __future__ import unicode_literals
import datetime
import os
import subprocess
def get_version(version=None):
"Returns a PEP 440-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - ... |
from indicators.SingleValueIndicator import SingleValueIndicator
from math import sqrt
class StdDev(SingleValueIndicator):
def __init__(self, period, timeSeries = None):
super(StdDev, self).__init__()
self.period = period
self.initialize(timeSeries)
def _calculate(self):
if len(self.timeSeries) < self.per... |
# -*- test-case-name: twisted.test.test_compat -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Compatibility module to provide backwards compatibility for useful Python
features.
This is mainly for use of internal Twisted code. We encourage you to use
the latest version of Python di... |
from copy import copy
def saddle_points(matrix):
if not matrix:
return []
if len(set(map(len, matrix))) != 1:
raise ValueError('irregular matrix')
# Saddle point is a point where the element is the biggest in its row but the smallest in its column.
# First off, I guess I'd create colum... |
#!/usr/bin/env python2
# CVE-2018-15473 SSH User Enumeration by Leap Security (@LeapSecurity) https://leapsecurity.io
# Credits: Matthew Daley, Justin Gardner, Lee David Painter
import argparse, logging, paramiko, socket, sys, os
class InvalidUsername(Exception):
pass
# malicious function to malform packet
def ... |
import os
import threading
from platypush.context import get_bus
from platypush.plugins.media import PlayerState, MediaPlugin
from platypush.message.event.media import MediaPlayEvent, MediaPlayRequestEvent, \
MediaPauseEvent, MediaStopEvent, NewPlayingMediaEvent, MediaSeekEvent
from platypush.plugins import actio... |
"""Profile model and related models declaration."""
# Django
from django.db import models
# Models
from cride.utils.models import CRideModel
from cride.users.models import User
class Profile(CRideModel):
"""Profile Model Declaration
It's a proxy model to the user but its difference
is that this one is... |
_base_ = [
'../../_base_/meta_test/mini-imagenet_meta-test_5way-5shot.py',
'../../_base_/runtime/iter_based_runtime.py',
'../../_base_/schedules/adam_100k_iter.py'
]
img_size = 84
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(... |
"""
A library written in CUDA Python for generating reduction kernels
"""
from numba.np.numpy_support import from_dtype
_WARPSIZE = 32
_NUMWARPS = 4
def _gpu_reduce_factory(fn, nbtype):
from numba import cuda
reduce_op = cuda.jit(device=True)(fn)
inner_sm_size = _WARPSIZE + 1 # plus one to avoid SM ... |
from scipy.stats import nchypergeom_fisher
import numpy as np
def fisher_exact_nonunity(table, alternative="two-sided", null_odds=1):
"""Perform a Fisher exact test on a 2x2 contingency table.
Parameters
----------
table : array_like of ints
A 2x2 contingency table. Elements must be non-negat... |
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
DefaultDict,
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
from sanic_routing.route import Route # type: ignore
from sanic.models.http_types import Credentials
if TYPE_CHECKING: # no cov
from s... |
import sys
# Find jVMC package
#sys.path.append("/Users/akhter/githesis-/jvmc/vmc_jax")
sys.path.append("/Users/akhter/thesis/vmc_jax")
import jax
from jax.config import config
config.update("jax_enable_x64", True)
import jax.random as random
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_... |
##
# @file __init__.py
# @author Zhou Fei
# @date Oct 2020
# |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
remove_start,
sanitized_Request,
)
class EinthusanIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?einthusan\.com/movies/watch.php\?([^#]*?)id=(?P<id>[0... |
# -*- coding: utf-8 -*-
"""
==============================================================================
Nanotube bundle base class (:mod:`sknano.structures._nanotube_bundle`)
==============================================================================
.. currentmodule:: sknano.structures._nanotube_bundle
"""
fro... |
'''
Base test
'''
def test_index(client):
assert client.get('/').status_code == 302
def test_registration(client):
assert client.post('/registration',
json={"email": "test4@gmail.com", "password": "12345", "name": "PyTest"}).status_code == 200
assert client.post('/registratio... |
import robocup
import constants
import play
import enum
import behavior
import main
import skills.move
import plays.testing.line_up
import time
# Maintains the state of the ball's position by keeping track of which
# half the ball is on and prints on both entering a given state and
# continuously during the execution... |
"""
__author__: Abhishek Thakur
"""
import torch
import numpy as np
from PIL import Image
from PIL import ImageFile
try:
import torch_xla.core.xla_model as xm
_xla_available = True
except ImportError:
_xla_available = False
ImageFile.LOAD_TRUNCATED_IMAGES = True
class ClassificationDataset:
def ... |
import math
import gym
from gym import spaces, logger
from gym.utils import seeding
import numpy as np
from gym.envs.classic_control import rendering
class MazeEnv(gym.Env):
def __init__(self, task={}):
super(MazeEnv, self).__init__()
# 0-up 1-down 2-left 3-right
self.action_space = [0, 1... |
import os
import glob
import importlib
def _package_contents():
for path in glob.glob(os.path.join(os.path.dirname(__file__), "*.py")):
path = os.path.basename(path)
if not path.startswith("_"):
module_name = path.replace(".py", "")
yield module_name, importlib.import_modul... |
"""Higher-level abstractions for robot control."""
from lhrhost.robot.robot import Robot |
#!/usr/bin/env python2
# The Notices and Disclaimers for Ocean Worlds Autonomy Testbed for Exploration
# Research and Simulation can be found in README.md in the root directory of
# this repository.
## GLOBAL VARS ##
J_SCOOP_YAW = 5
J_HAND_YAW = 4
J_DIST_PITCH = 3
J_PROX_PITCH = 2
J_SHOU_PITCH = 1
J_SHOU_YAW = 0
J_GR... |
import pytest
import numpy as np
all_dtypes = pytest.mark.parametrize('dtype', ['f4', 'f8', 'c8', 'c16'])
class Base(object):
def rand(self, dtype, shape=()):
a = np.random.normal(size=shape).astype(dtype)
if np.issubdtype(dtype, np.complexfloating):
a += np.random.normal(size=a.sha... |
import os, sys
import json
import os.path
import numpy
class DemandProfile:
def __init__(self):
cwd = os.getcwd()
self.fname = cwd + '/demand-profile.json'
def get_data(self):
demand={}
with open(self.fname) as demand_info:
demand = json.load(demand_info)
... |
import numpy as np
from mpi4py import MPI
class Kmeans:
def __init__(self, k=3, num_iterations=100, seed=42):
self.k = k
self.num_iterations = num_iterations
self.centorids = None
self.dim = None
self.n = None
np.random.seed(seed)
def train(self, X, parallel=F... |
# -*- coding: utf-8 -*-
"""
module for realtime watch and notfication
"""
import datetime as dt
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import formataddr, parseaddr
from re import match
import pandas as pd
from xalpha.cons import today
from xalpha.info imp... |
#!/usr/bin/env python
# upload to AWS S3 and clean up
# author Roman Sereda
# sereda.roman@gmail.com
#
# install dependenses
#sudo pip install boto
import json
import os.path
import logging
import subprocess
from boto.s3.connection import S3Connection
from boto.s3.key import Key
config_file = 'config.json'
json... |
"""
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
... |
import xml.etree.ElementTree as ET
import os
from Element import Element
class GMXToPython(object):
def __init__(self, xmlFile):
self.gmxroot = ET.parse(xmlFile).getroot()
self.root = Element(self.gmxroot)
for child in self.gmxroot:
self.process(child, self.root)
def process(self, element, parent):
ele... |
# Modified by Microsoft Corporation.
# Licensed under the MIT license.
import logging
import torch
import torch.utils.data as data
from torch.autograd import Variable
from utils.config import *
from utils.until_temp import entityList
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString... |
# *****************************************************************************
# * Author: Miguel Magalhaes
# * Email: miguel@magalhaes.pro
# *****************************************************************************
# * Main
# *****************************************************************************
import sy... |
from django.contrib import admin
from .models import Artist, Song
admin.AdminSite.site_title = 'Chords administration'
admin.AdminSite.site_header = 'Chords Administration'
class ArtistAdmin(admin.ModelAdmin):
exclude = ['slug']
actions = ['delete_selected']
search_fields = ['name']
def delete_sele... |
import turtle
ninja = turtle.Turtle()
ninja.speed(10)
for i in range(180):
ninja.forward(100)
ninja.right(30)
ninja.forward(20)
ninja.left(60)
ninja.forward(50)
ninja.right(30)
ninja.penup()
ninja.setposition(0, 0)
ninja.pendown()
ninja.right(2)
turtle.done() |
import pytest
from starlette.testclient import TestClient
from policyguru.main import app
@pytest.fixture(scope="module")
def test_app():
client = TestClient(app)
yield client # testing happens here |
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim
from TextDataset import TextDataset
from Model.BasicModel.TextCLRModel import TextCLRModel
from Model.BasicModel.TextSLBModel import TextSLBModel
from Model.BasicModel.TextNMTModel impo... |
from __future__ import print_function
import hashlib
import sys
import time
import os
import shlex
from ..utils.common import get_current_user, user_input, PassiveTimer
from ..utils import parsing_opts, text_tables
from ..common.trex_api_annotators import client_api, console_api
from ..common.trex_client import TRexC... |
"""
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRa... |
import collections
import math
import os
import random
import subprocess
from socket import gethostname
from typing import Any, Dict, Set, Tuple, Union
import numpy as np
import torch
from loguru import logger
from torch import Tensor
from torch._six import string_classes
from torch.autograd import Function
from torch... |
"""
This file contains configuration variables used for the backfill alerting.
"""
from datetime import datetime, timedelta
class Config:
"""Static configuration variables."""
## dates
FIRST_DATA_DATE = datetime(2020, 1, 1)
# shift dates forward for labeling purposes
DAY_SHIFT = timedelta(days=1... |
import os
import boto3
import pystow
import logging
import botocore
from gilda import __version__
logger = logging.getLogger(__name__)
HERE = os.path.abspath(os.path.dirname(__file__))
MESH_MAPPINGS_PATH = os.path.join(HERE, 'mesh_mappings.tsv')
resource_dir = pystow.join('gilda', __version__)
GROUNDING_TERMS_BASE_... |
"""Zoom.us REST API Python Client -- Report component"""
from __future__ import absolute_import
from zoomus import util
from zoomus.components import base
class ReportComponent(base.BaseComponent):
"""Component dealing with all report related matters"""
def get_account_report(self, **kwargs):
util.... |
from django.contrib import admin
class CdCategoryAdmin(admin.ModelAdmin):
pass
class CdAdmin(admin.ModelAdmin):
pass
class UserCdAdmin(admin.ModelAdmin):
def get_queryset(self, request):
"""
Show only current user's objects.
"""
qs = super(UserCdAdmin, self).queryset(r... |
#!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any ... |
import numpy as np
from sklearn.linear_model import LogisticRegression
import kiwi
import kiwi.sklearn
if __name__ == "__main__":
X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)
y = np.array([0, 0, 1, 1, 1, 0])
lr = LogisticRegression()
lr.fit(X, y)
score = lr.score(X, y)
print("Score: %s" %... |
""" manage PyTables query interface via Expressions """
from __future__ import annotations
import ast
from functools import partial
from typing import Any
import numpy as np
from pandas._libs.tslibs import (
Timedelta,
Timestamp,
)
from pandas.compat.chainmap import DeepChainMap
from pandas.core.dtypes.comm... |
#coding:UTF-8
class B():
def __init__(self,Data):
pass |
class Solution(object):
def minimumAbsDifference(self, arr):
"""
:type arr: List[int]
:rtype: List[List[int]]
"""
if len(arr) < 2:
return []
sa = sorted(arr)
min_diff = sa[1] - sa[0]
res = [[sa[0], sa[1]]]
for i in range(1, len(sa) ... |
from pandas import DataFrame
from moonstone.parsers.counts.taxonomy.base import BaseTaxonomyCountsParser
class SunbeamKraken2Parser(BaseTaxonomyCountsParser):
"""
Parse output from `Kraken2 <https://ccb.jhu.edu/software/kraken2/>`_
merge table from `Sunbeam <https://github.com/sunbeam-labs/sunbeam/>`_ pi... |
import json
import logging
from collections import defaultdict
from datetime import datetime
from typing import Dict, AnyStr
import pandas as pd
from actor_libs.database.async_db import db
from actor_libs.tasks.backend import update_task
from actor_libs.tasks.exceptions import TaskException
from actor_libs.utils impo... |
import os
from importlib.util import find_spec
from importlib import import_module
import inspect
def get_engine_object(table, baseobj):
'''Return the appropriate class object to operate on the specified table'''
spec = find_spec('suzieq.engines.pandas')
for file in spec.loader.contents():
if (os.... |
import pandas as pd
import matplotlib.pyplot as plt
from frames import games, info, events
plays = games.query("type == 'play' & event != 'NP'")
plays.columns = ['type', 'inning', 'team', 'player', 'count', 'pitches', 'event', 'game_id', 'year']
pa = plays.loc[plays['player'].shift() != plays['player'], ['year', 'gam... |
#from extras.plugins import PluginMenuButton, PluginMenuItem
from nautobot.extras.plugins import PluginMenuButton, PluginMenuItem
#from utilities.choices import ButtonColorChoices
from nautobot.utilities.choices import ButtonColorChoices
menu_items = (
PluginMenuItem(
link="plugins:ciscodnacnautobot:statu... |
# Angr script written by other people
import angr
import claripy
FLAG_LEN = 29
STDIN_FD = 0
# base_addr = 0x100000 # To match addresses to Ghidra
base_addr = 0
proj = angr.Project("./attachments/hotel_key_puzzle", main_opts={'base_addr': base_addr})
flag_chars = [claripy.BVS('sun{%d}' % i, 8) for i in range(FLAG_L... |
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from app.airtable.response import AirtableResponse
class CreateAirtableSSJTypeformStartASchool(BaseModel):
first_name: str = Field(alias="First Name")
last_name: str = Field(alias="Last Name")
email: str = Fi... |
import json
import warnings
from collections import namedtuple
from datetime import datetime
from uuid import uuid4
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.translation import ugettext_lazy as _
from casexml.apps.case.xform import get_case_ids_from_form
from casexml.apps.case.xml i... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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 .eip import *
from .eipassociation import *
fr... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
# http://www.apache.org/licenses/LICENSE-2.0
# or in the "license" file... |
#!/usr/bin/env python
"""A module for lazy instantiation of the GRR's Python API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from grr_api_client import api
from grr_colab import flags
FLAGS = flags.FLAGS
_... |
from datasets.__local__ import implemented_datasets
from datasets.mnist import MNIST_DataLoader
from datasets.cifar10 import CIFAR_10_DataLoader
from datasets.GTSRB import GTSRB_DataLoader
from datasets.bdd100k import BDD100K_DataLoader
from datasets.dreyeve import DREYEVE_DataLoader
from datasets.prosivic import PROSI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.