content
stringlengths
5
1.05M
from django.conf.urls import url, include # from rest_framework import routers from nlp_tools import views # router = routers.DefaultRouter() # router.register(r'tokenize', views.tokenize) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ #...
""" Source: https://github.com/lemariva/uPySensors/blob/19c5e2a21d61dbb50bf3b1c9032789e816291720/hcsr04.py """ from machine import Pin, time_pulse_us from micropython import const from uasyncio import sleep import utime from constants import THOUSAND from utils.conversions import micro_to_base _DEFAULT_TIMEOUT = con...
#!/bin/python3 import math import os import random import re import sys # Complete the isValid function below. def isValid(s): frequency = [s.count(letter) for letter in set(s) ] if(max(frequency)-min(frequency) == 0): return('YES') elif(frequency.count(max(frequency)) == 1 and max(frequency)-min(...
from csv import DictReader from io import StringIO from objectify.encoding import _DEFAULT_ENCODING # data = DictReader(open(file, encoding='utf-8')) # for row in data: # rowmap = dict(row) # # print(dumps(rowmap, indent=2)) # cidr = rowmap['a_cidr'] # print(cidr) def objectify_csv(path_buf_stream, ...
#!/usr/bin/env python """ GUI Frame for XRD display """ import sys import os import time import copy from functools import partial from threading import Thread import socket from functools import partial import wx import wx.lib.mixins.inspection import wx.lib.scrolledpanel as scrolled try: from wx._core import P...
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf tf.get_logger().setLevel('ERROR') from tensorflow.keras.mixed_precision import experimental as mixed_precision import numpy as np import cv2 import shutil from lr_schedules import WarmupCosineDecay, WarmupPiecewise import os.path as osp from uti...
from pydantic import BaseModel try: from bme280 import BME280 as BME280Sensor from ltr559 import LTR559 as LTR559Sensor except ImportError: from mocks import BME280 as BME280Sensor, LTR559 as LTR559Sensor from models.bme280 import BME280 from models.ltr559 import LTR559 class Enviro(BaseModel): bme2...
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? """ from math import trunc def largestPrimeFactor(num): primeFactor = 1 x = 2 while x < num/x + 1: if num % x == 0: primeFactor = x num /= x else: ...
import rice_calc.modules as modules import os import numpy as np import datetime def cacl_rice_dos(list_str_day, day_input, file_list,result_path): output_img = 'ard_store' day_in_date = datetime.datetime(int(day_input[0:4]), int(day_input[4:6]), int(day_input[6:8])) start_day = day_in_date - datetime.time...
import requests import os from flask_rebar import errors from app.app import registry from app.app import rebar from app.schemas.chat import ChatSchema @registry.handles(rule="/chat", method="POST", request_body_schema=ChatSchema()) def post_chat(): # TODO: Do not use dockers internal host. chat = rebar.val...
# coding: utf-8 # # Copyright 2019 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://aws.amazon.com/apache2.0/ # # or in the "lice...
#!/usr/bin/python import StringIO import subprocess import os import time #import datetime from datetime import datetime from PIL import Image # Original code written by brainflakes and modified to exit # image scanning for loop as soon as the sensitivity value is exceeded. # this can speed taking of larger photo if m...
from tkinter import ttk, StringVar, colorchooser import json from .canvas import SimpleGraph class SelectorMeta(SimpleGraph): '''A selection icon that sets the shape and color of the graphic. Example: ====================== from tkinter import Tk root = Tk() select = SelectorMeta(root) s...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 from collections import OrderedDict import pytest import torch import funsor.ops as ops import funsor.torch.distributions as dist from funsor.cnf import Contraction from funsor.domains import Bint, Reals from funsor.gaussian import G...
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') a, b = _sm.symbols('a b', real=True) e = a*(b*x+y)**2 m = _sm.Matrix([e,e]).reshape(2, 1) e = e.expand() m = _sm.Matrix([i.expand() for i in m]).reshape((m).shape[0], (m).shape[1]) e = _sm.fa...
#!/usr/bin/env python3 import sys if sys.version_info.minor < 6: raise Exception("Execute this script with at least python 3.6 to ensure all dicts are ordered!") XRL_FUNCTIONS = { 'AtomicWeight': {'Z': int}, 'ElementDensity': {'Z': int}, 'CS_Total': {'Z': int, 'E': float}, 'CS_Photo': {'Z': int, 'E': float},...
import os, hashlib import requests from tqdm import tqdm URL_MAP = { "cifar10": "https://heibox.uni-heidelberg.de/f/869980b53bf5416c8a28/?dl=1", "ema_cifar10": "https://heibox.uni-heidelberg.de/f/2e4f01e2d9ee49bab1d5/?dl=1", "lsun_bedroom": "https://heibox.uni-heidelberg.de/f/f179d4f21ebc4d43bbfe/?dl=1", ...
import arrow from flask import request, session, url_for def init_utils(application): @application.before_request def before_request(): if request.args.get('css') in ['enable', 'disable']: session['css_disabled'] = request.args.get('css') == 'disable' @application.context_processor ...
import torch import numpy as np import readability from more_itertools import sort_together from tqdm import tqdm import pdb STRIDE = 200 def super_linear_uid_compute(input, k_power): uid = torch.zeros(1) for surprisal in input: uid = uid + torch.pow(surprisal, k_power) return uid/len(input) def ...
import hashlib from django.utils.crypto import get_random_string from django.template import Context, Template, TemplateSyntaxError def get_random_hash(length=32): return hashlib.sha1(get_random_string().encode("utf8")).hexdigest()[:length] def string_template_replace(text, context_dict): try: t = ...
# -*- coding:utf-8 -*- # author: hpf # create time: 2020/7/14 22:37 # file: select_sort.py # IDE: PyCharm # 思路: # 把一个无序序列看做两部分,前一部分为有序,后一部分为无序 # [ [], 34, 2, 13, 76, 54, 22, 90, 46, 13] # 从后一部分找出最小值,与第一个元素互换 # 找出次小值,与第二个元素互换,以此类推 def select_sort(alist): n = len(alist) # 需要进行n-1次选择操作 for j in range(n-1): ...
from .minimizer import GeneralizeToRepresentative from ._version import __version__ __all__ = ['GeneralizeToRepresentative', '__version__']
import discord from discord import message from discord.ext import commands from discord.ext.commands.core import command from discord.utils import get from discord.ext import tasks import ast import io import os import sys import traceback import textwrap import platform import psutil import config from pymongo impor...
import pandas as pd import pickledb db = pickledb.load('cornell_lines_out.db', False) import json df = pd.read_csv('./movie_lines.txt', sep = '\+\+\+\$\+\+\+', engine = 'python', index_col = False) df.head() df.drop(df.columns[1:4], axis=1, inplace=True) for value in df.values.tolist(): db.set(str(va...
import tornado.web import tornado.ioloop from apiApplicationModel import userData from cleanArray import Label_Correction import json import asyncio import aiohttp colName=['age', 'resting_blood_pressure', 'cholesterol', 'max_heart_rate_achieved', 'st_depression', 'num_major_vessels', 'st_slope_downsloping', '...
from .bool_type import BoolType from .int_type import IntType from .str_type import StrType from .float_type import FloatType
# -*- coding: utf-8 -*- import requests from lxml.html.clean import clean_html from django.db import transaction from django.core.management.base import BaseCommand, CommandError from budget.models import Reply, Keyword from lxml import etree from datetime import * from dateutil.parser import * from lxml.html.clean imp...
import json class Word: def __init__(self, word, translation=None, phrase=None, synonyms=[], sound_record_path=None, study_status=0, last_repeat_date=None, *args, **keywords): self.word = word.strip() self.word_lower = self.word.lower() self.translation = ...
import multiprocessing import os from time import sleep import boto3 from cloudlift.config import get_account_id, get_cluster_name, \ ServiceConfiguration, get_region_for_environment from cloudlift.config.logging import log_bold, log_intent, log_warning from cloudlift.deployment import deployer, ServiceInformatio...
#!/usr/bin/python import csv import sys import os.path from . import data_prep_utils from collections import OrderedDict def consoleLabel(raw_strings, labels, module): print('\nStart console labeling!\n') valid_input_tags = OrderedDict([(str(i), label) for i, label in enumerate(labels)]) printHelp(valid_...
# adapted from https://github.com/facebookresearch/pytorch_GAN_zoo import torch import torch.nn as nn import torch.nn.functional as F from model.layers import flatten, upscale2d, EqualizedLinear, EqualizedConv2d, NormalizationLayer from model.network_utils import mini_batch_std_dev class BasicBlock(nn.Module): d...
import FWCore.ParameterSet.Config as cms from Configuration.EventContent.EventContent_cff import AODSIMEventContent EXODisappTrkSkimContent = AODSIMEventContent.clone() EXODisappTrkSkimContent.outputCommands.append('drop *') EXODisappTrkSkimContent.outputCommands.append('keep *_reducedHcalRecHits_*_*') EXODisappTrkSki...
from utils import SYM2ID, ROOT_DIR, IMG_DIR, NULL, IMG_TRANSFORM from copy import deepcopy import random import json import numpy as np from PIL import Image import torch from torch.utils.data import Dataset, DataLoader from torch.utils.data.dataloader import default_collate class HINT(Dataset): def __init__(self,...
import sys sys.path.append('..') from robot.components import MotorComponent #from basestation.xbox import Controller import time motor = MotorComponent('leftMotor', 'l_stick_vertical', 11, 12) controllerValue = 0 while True: controllerValue += 5 print(controllerValue) time.sleep(.05) motor.doUpdate(co...
from turtle import Turtle WIDTH = 5 HEIGHT = 1 class Paddle(Turtle): def __init__(self, position): super().__init__() self.position = position self.shape("square") self.shapesize(WIDTH, HEIGHT) self.penup() self.color("white") self.goto(position) def up...
"""Smoke test.""" from . import u def test_render_no_commands(): t = """aa bb cc dd""" s = u.render(t, {}) assert s == t def test_empty(): t = "" s = u.render(t, {}) assert s == t def test_strip(): t = '{2+2} xxx {3+3} yyy {4+4}' s = u.render(t) assert s == '4 xxx 6 yyy 8' ...
# -*- test-case-name: twistedcaldav.test.test_upgrade -*- ## # Copyright (c) 2008-2015 Apple Inc. 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.or...
def corr_gamma(a1,a2,mu1,mu2,rho,N): """ Use: X1,X2 = corr_gamma(a1,a2,b1,b2,rho,N) This function follows an algorithm obtained at http://web.ics.purdue.edu/~hwan/IE680/Lectures/Chap08Slides.pdf It generates the two gamma distributed random variables X1 ~ Gamma(a1,mu1) X2 ~ Gamma(a2,mu2) ...
# coding: utf-8 """ Task Execution Service No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import...
import logging import os import sys from pynetdicom.presentation import StoragePresentationContexts from libs import Database, handle_open, handle_c_store, handle_c_find, handle_close, handle_c_echo, handle_c_get from pynetdicom import AE, build_context, evt def main(): """Main""" db = Database("config.ini"...
import warnings import hashlib import os from functools import total_ordering from lxml import etree from six import add_metaclass, string_types as basestring try: import urlparse except ImportError: from urllib import parse as urlparse try: from collections.abc import Iterable, Mapping except ImportErr...
#!/usr/bin/env python3 # 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. import os.path as osp import attr import numba import numpy as np from habitat_sim.bindings import cuda_enabled from h...
#!/usr/bin/env python # encoding: utf-8 # This file is part of the quickscons project. This project is used to build # other software that MAY or MAY NOT be licensed under the same terms as this # project. This project is licensed under the below: # # The MIT License (MIT) # # Copyright © 2015 Stephen M Buben <smbuben...
import os import re import sys import time import urllib2 sys.path.append("../frame/") from loggingex import LOG_INFO from loggingex import LOG_ERROR from loggingex import LOG_WARNING from singleton import singleton from mysql_manager import mysql_manager @singleton class stock_conn_manager(): def __init__(self)...
from cdmanager import cd import os from pathlib import Path import pandas as pd import shutil import subprocess from utilpipeline import ( checkMD5isCorrect, checkFastaQLenght, performTrimGaloreFourFiles, qualityCheckTrimGaloreFourFiles, performBismark ) ids_file = '../data/commonDa...
#!/usr/bin/python # -*- coding: utf-8 -*- """ (c) 2017 David Barroso <dbarrosop@dravetech.com> This file is part of Ansible Ansible 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 Licens...
from datetime import datetime, timedelta import makerbase from makerbase.models import * """ user: { 'id': 'name': 'avatar_url': 'html_url': <link to person?> } maker: { 'name': 'avatar_url': 'html_url': } project: { 'name': 'description': 'avatar_url': 'html_url': }...
import glob import json import os import torch class Saver(object): @staticmethod def meta_path(dir_): return os.path.join(dir_, 'meta.json') @staticmethod def model_path(dir_, num_step=None, model_name=None): model_name = model_name or 'model-*.ckpt' if num_step is not None:...
from .l2norm import L2Norm from .multibox_loss import MultiBoxLoss from .focal_loss import FocalLoss __all__ = ['L2Norm', 'MultiBoxLoss',"FocalLoss"]
import torch from torch import nn import torch.nn.functional as F from models import audio_convnet from models import image_convnet from models import base_models def normalize_img(value, vmax=None, vmin=None): value1 = value.view(value.size(0), -1) value1 -= value1.min(1, keepdim=True)[0] value1 /= value1...
""" The ledgerlink module ===================== This module defines the models allowing to manipulate information regarding links stored in the NEO blockchain. """ def init_app(app, **kwargs): # Register blueprints. from . import views app.register_blueprint(views.ledgerlink_blueprint)
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Ricardo Ribeiro" __credits__ = ["Ricardo Ribeiro"] __license__ = "MIT" __version__ = "0.0" __maintainer__ = "Ricardo Ribeiro" __email__ = "ricardojvr@gmail.com" __status__ = "Development" from pyforms.gui.Controls.ControlBase import...
from sklearn.svm import SVC from global_constants import TRAIN, TEST, DEV def train_and_predict(data, labels, kernel='linear', probability=True): # print "Probability", probability svc = SVC(kernel=kernel, probability=probability, verbose=False, max_iter=100000) svc.fit(data[TRAIN], labels[TRAIN]) pre...
"""Datasets required by pytorch dataloaders for competition data.""" import numpy as np from torch.utils.data import Dataset from constants import Mappings, FilePaths TGT2ERR_COL = {"reactivity": "reactivity_error", "deg_Mg_50C": "deg_error_Mg_50C", "deg_Mg_pH10": "deg_error_Mg_pH10"} class RNAData(Dataset): d...
import os import os.path import tempfile import numpy as np from magenta.models.rl_tuner import rl_tuner_ops from magenta.models.rl_tuner import note_rnn_loader from magenta.models.rl_tuner import rl_tuner import matplotlib import matplotlib.pyplot as plt # pylint: disable=unused-import import tensorflow.compat.v1 as...
from github import Github, InputGitTreeElement import re import datetime from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("-r", "--release", action="store_true", help="Release only mode") parser.add_argument("-c", "--commit", action="store_true", help="Commit only mode") parser.add_ar...
# -*- coding: utf-8 -*- import os import requests import json import time import pathlib import itertools import numpy as np from tqdm import tqdm from preprocessing import ( read_ts_dataset, normalize_dataset, moving_windows_preprocessing, denormalize, ) NUM_CORES = 7 def notify_slack(msg, webhook=N...
#!/usr/bin/env python # -*- coding:UTF-8 -*- # # follow.py # # 无限数据流 # Follow a file like tail -f. import time def follow(thefile): thefile.seek(0,2) try: while True: line = thefile.readline() if not line: time.sleep(0.1) continue yi...
from .nms import SingleLabelNMS, MultiLabelNMS POSTPROCESSES = { 'SingleLabelNMS': SingleLabelNMS, 'MultiLabelNMS': MultiLabelNMS } def build_postprocess(postprocess: dict): return POSTPROCESSES[postprocess.pop('type')](**postprocess)
def calculateNetIncome(gross, state): state_tax = {'NY': 10, 'LA': 12, 'CA': 2, 'SF': 0, 'HI': 15} net = gross - (gross * 0.10) if state in state_tax: net = net - (gross * state_tax[state]/100) print("The calculated Net income after deduction is: " + str(net)) return net else: ...
##Write code to rearrange the strings in the list winners so that they are in alphabetical order from A to Z. winners = ['Kazuo Ishiguro', 'Rainer Weiss', 'Youyou Tu', 'Malala Yousafzai', 'Alice Munro', 'Alvin E. Roth'] winners.sort()
from .test_utils import TempDirectoryTestCase from pulsar.managers.base import JobDirectory import os TEST_JOB_ID = "1234" class JobDirectoryTestCase(TempDirectoryTestCase): def setUp(self): super().setUp() self.job_directory = JobDirectory(self.temp_directory, TEST_JOB_ID) def test_setup(s...
import json from config import db # Insert into 'catalogs' with open('./assets/seller_catalogs_extra_fake_data_cambo.json') as json_file: fake_catalogs = json.load(json_file) batch = db.batch() for catalog in fake_catalogs: docRef = db.document(f'sellers/{catalog["seller_id"]}/catalogs/{catalog["i...
#from django.http import HttpResponse, JsonResponse import requests from requests.auth import HTTPBasicAuth import json #from . mpesa_credentials import MpesaAccessToken, LipanaMpesaPpassword #from django.views.decorators.csrf import csrf_exempt #from .models import MpesaPayment from keys import MpesaAccessToken,Lipana...
# flake8: noqa from codewars.meeting import meeting # pylint: disable=line-too-long def test_meeting() -> None: cases = [ ( "Alexis:Wahl;John:Bell;Victoria:Schwarz;Abba:Dorny;Grace:Meta;Ann:Arno;Madison:STAN;Alex:Cornwell;Lewis:Kern;Megan:Stan;Alex:Korn", "(ARNO, ANN)(BELL, JOHN)(...
import sys from typing import Dict import numpy as np from pso.strategy import OptimizationStrategy, MultiParticle from pso.swarm import Swarm, SwarmConfig class MultiSwarm: def __init__(self, outer_swarm_config: SwarmConfig, strategy: OptimizationStrategy): self.__strategy = strategy self.__num...
import pygame pygame.init() pantalla=pygame.display.set_mode((480,300)) salir=False reloj1= pygame.time.Clock() imagen1=pygame.image.load("alienr.png").convert_alpha() (x,y)= (100,100) vx=0 r1=pygame.Rect(250,70,25,500) sprite1= pygame.sprite.Sprite() sprite1.image=imagen1 sprite1.rect=imagen1.get_rect() sprite1.rect....
import os import py import pytest import time from lektor.builder import Builder from lektor.db import Database from lektor.project import Project from lektor.environment import Environment from lektor_npm_support import NPMSupportPlugin @pytest.fixture(scope='function') def project(): return Project.from_path(o...
from django.urls import path, register_converter from orders import views from .converters import ShiftConverter, OrderVenueConverter, OrderConverter register_converter(ShiftConverter, "shift") register_converter(OrderVenueConverter, "order_venue") register_converter(OrderConverter, "order") urlpatterns = [ path...
#!/usr/bin/env python import mock import pytest import requests import requests_mock from yaml import load, SafeLoader import cachet_url_monitor.exceptions import cachet_url_monitor.status from cachet_url_monitor.webhook import Webhook from cachet_url_monitor.configuration import Configuration import os @pytest.fix...
# Author: hys import math import torch from torch import nn import torch.nn.functional as F class Conv1dStaticSamePadding(nn.Module): """ modified by hys """ def __init__(self, in_channels, out_channels, kernel_size, stride=1, bias=False, groups=1, dilation=1, **kwargs): super().__init__() ...
'''https://practice.geeksforgeeks.org/problems/largest-number-in-k-swaps-1587115620/1 Largest number in K swaps Medium Accuracy: 46.92% Submissions: 26080 Points: 4 Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of st...
from subprocess import PIPE, run as s_run from time import sleep from panel.models import Messages, GeneralSettings from datetime import datetime from re import search as search_regex from django.contrib import messages from os import remove from paramiko import RSAKey from io import StringIO from django.conf import se...
import unittest from logger import Logger, SeverityType from test import TestPolicy class TestLoggerMethods(unittest.TestCase): def test_logger_init(self): print("TEST_LOGGER_INIT Unit Test") print("\tAssert Logger.__init__ functions.") try: logger = Logger(TestPolicy()) ...
import ctypes import os.path as osp import numpy as np import tensorrt as trt from .globals import dir_path ctypes.CDLL(osp.join(dir_path, 'libamirstan_plugin.so')) def create_batchednms_plugin(layer_name, scoreThreshold, iouThreshold, ...
from typing import List class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: if not triangle: return 0 dp = [0 for _ in triangle[-1]] dp[0] = triangle[0][0] print(dp) for level in triangle[1:]: dp[len(level) - 1] = dp[len(level)...
import os def insert_ones(y, segment_end_ms, Ty=1375): """ Update the label vector y. The labels of the 50 output steps strictly after the end of the segment should be set to 1. By strictly we mean that the label of segment_end_y should be 0 while, the 50 followinf labels should be ones. Argumen...
from ..remote import RemoteModel class DeviceViewerBridgeDomainsGridRemote(RemoteModel): """ | ``id:`` none | ``attribute type:`` string | ``tenant_name:`` none | ``attribute type:`` string | ``tenant_dn:`` none | ``attribute type:`` string | ``bridge_domain:`` none | ...
import socket import select import errno class SerialTCPConnection: """ A TCP socket API to match the pyserial API """ def __init__(self, address, port, timeout=None): self._recvBuffer = [] self._port = port self._recvTimeout = timeout self._in_waiting = 0 self...
# Copyright (c) 2016-2017 Enproduktion GmbH & Laber's Lab e.U. (FN 394440i, Austria) # 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 rig...
# -*- coding: utf-8 -*- """Generating Keywords for Google Ads.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/github/Suraj-Patro/ads_keywords_generator/blob/main/Generating_Keywords_for_Google_Ads.ipynb ## 1. The brief <p>Imagine working for a digital ...
# Copyright 2015 Hewlett-Packard Corporation # 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 # # Unle...
# Copyright (c) 2019 Tradeshift # Copyright (c) 2020 Fellow Consulting AG # # 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 u...
from pydantic import BaseModel from typing import Optional from ..helpers import ModificationContext from .pose import Pose from .velocity import Velocity class RobotShape(BaseModel): outline: list[tuple[float, float]] = [(-0.5, -0.5), (0.5, -0.5), (0.75, 0), (0.5, 0.5), (-0.5, 0.5)] height: float = 0.5 cla...
import sys import time from scapy.all import * sendp(Ether(dst='08:00:27:00:44:72')/IP(dst='192.168.33.10')/TCP(dport=8888), iface='eth1') def receive(packet): p = packet[0][1] if p.src == '192.168.33.10' and p.load == 'expired': sys.exit(1) sniff(filter='tcp', prn=receive, timeout=12, iface='eth1') ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0098_userpreferences_default_tab'), ] operations = [ migrations.AddField( ...
# encoding: utf-8 """Polynomial networks for regression and classification.""" # Author: Vlad Niculae <vlad@vene.ro> # License: Simplified BSD import warnings from abc import ABCMeta, abstractmethod import numpy as np from sklearn.preprocessing import add_dummy_feature from sklearn.utils import check_random_state f...
from sklearn.metrics import roc_auc_score, roc_curve, confusion_matrix, average_precision_score, auc, accuracy_score import numpy as np import torch import pandas as pd from datetime import datetime import matplotlib.pyplot as plt import seaborn as sn import os.path as path def l1_regularizer(model, lambda_l1=0.01): ...
import dearpygui.dearpygui as dpg import os from Waypoints import Waypoints from modules import * from modules.CaveBot import CaveBot from modules.Healing import Healing from modules.Utils import Utils import asyncio from modules.AttackSpells import AttackSpells # Create Objects healing = Healing() utils = Utils() cav...
import re import serial import glob from warnings import warn from panoptes.pocs.focuser.serial import AbstractSerialFocuser from panoptes.utils import error # Birger adaptor serial numbers should be 5 digits serial_number_pattern = re.compile(r'^\d{5}$') # Error codes should be 'ERR' followed by 1-2 digits error_pa...
"""Presets for end-to-end model training for special tasks.""" __all__ = [ "common_metric_gpu", "utils_gpu" ]
from __future__ import absolute_import import os from zope import interface from twisted.python import usage, reflect, threadpool, filepath from twisted import plugin from twisted.application import service, strports, internet from twisted.web import wsgi, server, static, resource from twisted.internet import reacto...
import autoarray.plot as aplt import numpy as np aplt.line( y=np.array([1.0, 2.0, 3.0]), x=np.array([0.5, 1.0, 1.5]), vertical_lines=[1.0, 2.0] ) aplt.line( y=np.array([1.0, 2.0, 3.0]), x=np.array([0.5, 1.0, 1.5]), vertical_lines=[1.0, 2.0], vertical_line_labels=["line1", "line2"], ) aplt.line( ...
import io from . import chunked_data_stream as chunky from splunklib.searchcommands import StreamingCommand, Configuration def test_simple_streaming_command(): @Configuration() class TestStreamingCommand(StreamingCommand): def stream(self, records): for record in records: ...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="pyconquest", # This is the name of the package version="0.0.7", # The release version author="René Monshouwer", # Full name of the a...
#Copyright ReportLab Europe Ltd. 2000-2004 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfbase/cidfonts.py #$Header $ __version__=''' $Id: cidfonts.py 3710 2010-05-14 16:00:58Z rgbecker $ ''' __doc__="""CID (Asian multi-byte) font su...
# -*- coding: utf-8 -*- import logging import numpy as np import math from sklearn.neighbors import KernelDensity from sklearn.metrics import roc_auc_score from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from dku_data_drift.preprocessing import Preprocessor from dku_data_drift.model_drift_con...
#!/usr/bin/python # -*- coding:utf-8 -*- import telnetlib def do_telnet(Host, username, password, finish, commands): tn = telnetlib.Telnet(Host, port=23, timeout=10) tn.set_debuglevel(2) tn.read_until('login:') tn.write(username + '\n') tn.read_until('password:') tn.write(password + '\n') ...
print("фыввфыфыв") #здесь был я (Nikikita62344) #здесь был алмазик
import argparse import os import random import sys import time from datetime import timedelta import numpy as np import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms from model import PipelineParallelResNet50 from schedule import (initialize_global_args, is_pipel...