content stringlengths 5 1.05M |
|---|
class Command(object):
@classmethod
def execute(cls):
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import os
import time
from prometheus_client import Gauge
from prometheus_client import start_http_server
class D2():
""" Division2 class which get user information. """
def __init__(self, url):
self.url = url
def get_user_id(self, ... |
from common.utils import datetime_to_string
class Verification:
def __init__(self, id, type, entity_id, status, requestee, created_at, updated_at, reject_reason=None):
self.id = id
self.type = type
self.entity_id = entity_id
self.status = status
self.requestee = requestee
... |
from profanity_check import predict, predict_prob
from directoryLoader import directoryFileListBuilder
from fileAnalyzer import fileAnalyzer
'''
Dev: Alexander Edward Andrews
Email: alexander.e.andrews.ce@gmail.com
'''
def main():
fileNode = directoryFileListBuilder()
recursiveCaller(fileNode)
def recursiveCa... |
#!/usr/bin/env python3
import os
import canopus
import time
from sys import argv
from collections import defaultdict
from typing import List, Dict, Tuple, Union, DefaultDict, Any
def analyse_canopus(sirius_folder: str,
gnps_folder: str,
output_folder: str = './',
... |
# Importing essential libraries
from flask import Flask, render_template, request
from googletrans import Translator
translator=Translator()
app = Flask(__name__)
@app.route('/predict')
def predict():
message = request.args.get('message')
lang=request.args.get('languages')
lang=lang.lower()
... |
"""Top-level package for Deployer of AWS Lambdas."""
__author__ = """Sean Lynch"""
__email__ = 'seanl@literati.org'
__version__ = '0.2.1'
|
import math
from controller import Controller
from math_helpers import PolarCoordinate, RelativeObjects, normalise_angle
class TurretController(Controller):
def calc_inputs(self):
if not self.helpers.can_turret_fire():
return self.calc_rotation_velocity(), False
if (
se... |
from src.run import hello_world
def test_hello():
assert hello_world() == "Hello world!"
|
from setuptools import setup
from setuptools import find_packages
long_description = '''
Implementation of a sharable vector-like structure.
'''
setup(name='PyVector',
version='0.0.1',
description='',
long_description=long_description,
author='Frédéric Branchaud-Charron',
author_email='f... |
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from modem_api import views
urlpatterns = [
path('modems/', views.ModemList.as_view(), name='modem-list'),
path('modems/<int:pk>/', views.ModemDetail.as_view(), name='modem-detail'),
path('stations/', views.StationLi... |
import pandas as pd
import matplotlib.pyplot as plt
#reading data
stock_price = pd.read_csv('datasets/intel.csv', parse_dates=True, index_col='Date')
#reviewing the data
# print(stock_price)
stock_price.loc['2017-10-16':'2017-10-20', ['Open', 'Close']].plot(style='.-', title='Intel Stock Price', subplots=True)
plt.... |
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.editor, name='editor'),
path('<int:index>', views.editor, name='editor'),
path('rename_segment/<int:index>/<str:new_name>', views.rename_segment,
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... |
# Copyright Contributors to the OpenCue Project
#
# 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... |
import pytest
from aio_forms import ERROR_REQUIRED, LengthValidator, StringField
from tests.fields.utils import FIELD_KEY, do_common
pytestmark = pytest.mark.asyncio
async def test_common():
await do_common(
field_cls=StringField,
default=' Test default ',
default_new=' Test defa... |
from sklearn import metrics
import numpy as np
def get_fpr_tpr_ths(y_param, scores_param):
"""
Returns fpr, tpr, thresholds.
Positive label is +.
"""
y = np.array(y_param)
scores = np.array(scores_param)
fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label='+')
return fpr, t... |
# Copyright (c) 2010 Charles Cave
#
# 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, c... |
import multiprocessing # python's version of openMP
import math
from random import uniform
num_of_procs = 1 # can be used for testing number of processes
num_of_points = int(1000000/num_of_procs) # the original amount of points in 4.22 divided by number of processes
points_in_circle = 0
x_points = []
y_po... |
# import commands
import subprocess
import os
main = "./testmain"
if os.path.exists(main):
# rc, out = commands.getstatusoutput(main)
(rc, out) = subprocess.getstatusoutput(main)
print ('rc = %d, \nout = %s' % (rc, out))
print ('*'*10)
f = os.popen(main)
data = f.readlines()
f.clos... |
import dash_bootstrap_components as dbc
from dash import Input, Output, State, html
alert = html.Div(
[
dbc.Button(
"Toggle alert with fade",
id="alert-toggle-fade",
className="me-1",
n_clicks=0,
),
dbc.Button(
"Toggle alert withou... |
#!venv/bin/python
# -*- encoding: utf-8 -*-
import sys
import os.path
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db, models
def create():
... |
import binascii
import logging
import textwrap
import typing
from array import array
from typing import List, Union
import pytest
from numpy.testing import assert_array_almost_equal
pytest.importorskip('caproto.pva')
from caproto import pva
from caproto.pva._fields import FieldArrayType, FieldType
logger = logging.... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
""" A universal module with functions / classes without dependencies. """
import functools
import re
import os
_sep = os.path.sep
if os.path.altsep is not None:
_sep += os.path.altsep
_path_re = re.compile(r'(?:\.[^{0}]+|[{0}]__init__\.py)$'.format(re.escape(_sep)))
del _sep
def to_list(func):
def wrapper(*... |
from math import sqrt
n = int(input('Digite um número: '))
d = n * 2
t = n * 3
r = sqrt(n)
print('O dobro de {} é {}\nO triplo de {} é {}'.format(n, d, n, t))
print('A raiz quadrada de {} é {}.'.format(n, r))
|
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... |
import tkinter as tk
from tkinter import ttk
app = tk.Tk()
def rb_click():
print()
country = tk.IntVar()
rb1 = tk.Radiobutton(app, text='Russia', value=1, variable=country, padx=15, pady=10, command=rb_click)
rb1.grid(row=1, column=0, sticky=tk.W)
rb2 = tk.Radiobutton(app, text='USA', value=2, variable=country... |
from django.apps import AppConfig
class DevconnectorConfig(AppConfig):
name = 'devconnector'
|
from __future__ import print_function
from io import StringIO
from argparse import ArgumentParser
from os.path import join as osp_join
import sys
from catkin_tools.verbs.catkin_build import (
prepare_arguments as catkin_build_prepare_arguments,
main as catkin_build_main,
)
from catkin_tools.verbs.catkin_loca... |
# -*- coding: utf-8; -*-
# Copyright (c) 2017, Daniel Falci - danielfalci@gmail.com
# Laboratory for Advanced Information Systems - LAIS
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# *... |
from zerocon import IOException
from benchutils import getInterface, getSeries
from threading import Thread
import time, Queue
class Emitter(Thread):
def __init__(self, queue):
Thread.__init__(self)
self.queue = queue
def run(self):
while True:
time.sleep(1)
... |
# import numpy as np
# import torch
# from medpy import metric
# from scipy.ndimage import zoom
# import torch.nn as nn
# import cv2
# import SimpleITK as sitk
#
# import matplotlib.pyplot as plt
# import tensorflow as tf
# import matplotlib.pylab as pl
# from matplotlib.colors import ListedColormap
#
#
# device = torc... |
# coding: utf-8
"""
Neucore API
Client library of Neucore API # noqa: E501
The version of the OpenAPI document: 1.14.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from neucore_api.configuration import Configuration
class GroupApplication(ob... |
from django.apps import AppConfig
class RouterConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'my_router'
def ready(self):
import my_router.receivers # noqa
|
# -*- coding: utf-8 -*-
# Copyright 2004-2005 Joe Wreschnig, Michael Urman, Iñigo Serna
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
import os
from gi.repository import Gtk, GObj... |
import os
os.system("mkdir data")
os.system("wget https://www.dropbox.com/s/zcwlujrtz3izcw8/gender.tgz data/")
os.system("tar xvzf gender.tgz -C data/")
os.system("rm gender.tgz")
|
from setuptools import setup, find_packages
PROJECT_URL = 'https://github.com/pfalcon/sphinx_selective_exclude'
VERSION = '1.0.3'
setup(
name='sphinx_selective_exclude',
version=VERSION,
url=PROJECT_URL,
download_url=PROJECT_URL + '/tarball/' + VERSION,
license='MIT license',
author='Paul Soko... |
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar.
# considere US$1,00 = R$5,58
real = float(input('Quando dinheiro você tem na carteira? '))
dolar = real / 5.58
print('Com R${:.2f} você pode comprar US${:.2f}'.format(real, dolar))
|
import AppKit
from PyObjCTools.TestSupport import TestCase
class TestNSInterfaceStyle(TestCase):
def testConstants(self):
self.assertEqual(AppKit.NSNoInterfaceStyle, 0)
self.assertEqual(AppKit.NSNextStepInterfaceStyle, 1)
self.assertEqual(AppKit.NSWindows95InterfaceStyle, 2)
self.a... |
#f __name__ == "__main__":
def Pomodoro(time):
if time == 0:
return 25*60
elif time > 120:
return 25*60
return time*60
|
import numpy as np
from sklearn.base import clone
from sklearn.metrics import accuracy_score
from python_ml.Ensemble.Combination.VotingSchemes import majority_voting
class RandomSubspace(object):
def __init__(self, base_classifier, pool_size, percentage=0.5):
self.has_been_fit = False
self.pool_si... |
#!/usr/bin/env python
__description__ = 'Calculate the SSH fingerprint from a Cisco public key dumped with command "show crypto key mypubkey rsa"'
__author__ = 'Didier Stevens'
__version__ = '0.0.2'
__date__ = '2014/08/19'
"""
Source code put in public domain by Didier Stevens, no Copyright
https://DidierStevens.com... |
"""
10
Enunciado
Faça um programa que sorteie 10 números entre 0 e 100 e imprima:
a. o maior número sorteado;
b. o menor número sorteado;
c. a média dos números sorteados;
d. a soma dos números sorteados.
"""
import random
lista = []
for c in range(0, 10):
numeros = random.randint(0, 100)
lista.append(n... |
"""The noisemodels module contains all noisemodels available in Pastas.
Author: R.A. Collenteur, 2017
"""
from abc import ABC
from logging import getLogger
import numpy as np
import pandas as pd
from .decorators import set_parameter
logger = getLogger(__name__)
__all__ = ["NoiseModel", "NoiseModel2"]
class No... |
import functools
import logging
import warnings
from pathlib import Path
from typing import List, Optional
import monai.transforms.utils as monai_utils
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import skimage
from sklearn.pipeline import Pipeline
from autorad.config.type_definit... |
import cv2
import os
import sys
def facecrop(image):
cascPath = "C:\Python36\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml"
cascade = cv2.CascadeClassifier(cascPath)
img = cv2.imread(image)
minisize = (img.shape[1],img.shape[0])
miniframe = cv2.resize(img, minisize)
faces =... |
import sys
def num_nice(input):
return len([s for s in input.split('\n') if is_nice(s)])
def is_nice(s):
return has_non_overlapping_pairs(s) and has_repeat_with_gap(s)
def has_non_overlapping_pairs(s):
for i in xrange(0, len(s) - 3):
needle = s[i:i+2]
haystack = s[i+2:]
if needle in haystack:
return True... |
from typing import Iterator
import xmlschema
from xmlschema import XsdElement, XsdComponent
def test_validate(config_folder, fixtures_path):
schema = xmlschema.XMLSchema(config_folder / 'cin.xsd')
errors = list(schema.iter_errors(fixtures_path / 'sample.xml'))
for error in errors:
print(error)
... |
import os
import random
class Speaker():
def __init__(self, name="-v alex ", rate="-r 100 "):
self.name = str(name)
self.rate = str(rate)
def __repr__(self):
iamwhoiam = "I am who I am"
return repr(iamwhoiam)
def speak(self, words):
words = self.stripper(words)
... |
import os
import configparser
import pandas as pd
from finvizfinance.screener import (
technical,
overview,
valuation,
financial,
ownership,
performance,
)
presets_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "presets/")
# pylint: disable=C0302
def get_screener_data(
p... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
"""
import pytest
from common.testexecresults import TestExecResults
from common.testresult import TestResults, TestResult
def test__ctor__test_results_not_correct_type__raises_type_error():
with pytest.raises(TypeError):
test_exec_r... |
from numpy import cos, sin, sqrt, linspace as lsp, arange, reciprocal as rp
from matplotlib.pyplot import plot, polar, title, show
from math import pi as π
##Polar square... and byenary 100 all!
θ, ρ = lsp(0, π/0b100, 0b10), π/0o10 # ... or for octoplus!
r = rp(cos(θ))
for θ in (θ + n*π/0b10 for n in range(4)):
... |
"""PSS/E file parser"""
import re
from ..consts import deg2rad
from ..utils.math import to_number
import logging
logger = logging.getLogger(__name__)
def testlines(fid):
"""Check the raw file for frequency base"""
first = fid.readline()
first = first.strip().split('/')
first = first[0].split(',')
... |
from typing import Union
from pathlib import Path
from PIL import Image
def verifyTruncated(path: Union[str, Path]) -> bool:
try:
with Image.open(path) as image:
image.verify()
if image.format is None:
return False
return True
except (IOError, OSErr... |
import os
import flask
flask.cli.load_dotenv()
os.environ["DATABASE_URL"] = "sqlite:///:memory:"
import pytest
from offstream import db
from offstream.app import app
@pytest.fixture
def setup_db():
db.Base.metadata.create_all(db.engine)
yield
db.Base.metadata.drop_all(db.engine)
@pytest.fixture
def ... |
from .convert import Converter
from .register import register
__all__ = [
'Converter',
'register'
]
|
import json
import os
from kivy.app import App
from kivy.config import Config
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.button import Button
class planeFinder(App):
def build(self... |
from __future__ import print_function, absolute_import
class MiddlewareMixin(object):
def __init__(self, get_response=None):
super(MiddlewareMixin, self).__init__()
|
# -*- coding: utf-8 -*-
import os
import codecs
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
readme_path = os.path.join(here, 'README.txt')
with codecs.open(readme_path, 'r', encoding='utf-8') as file:
readme = file.read()
setup(
name='circus-env-modifier',
version='0.1... |
from keras.preprocessing.sequence import pad_sequences
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
import train
import predict
from config import Config
import preprocessing as prep
import numpy as np
... |
import csv
import json
import re
import sys
from collections import OrderedDict, defaultdict
import yaml
from abc import ABCMeta
from Bio import SeqIO
import itertools
from lib.proximal_variant import ProximalVariant
csv.field_size_limit(sys.maxsize)
class FastaGenerator(metaclass=ABCMeta):
def parse_proximal_var... |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
import numpy as np
from sacred import Experiment
from sacred import Ingredient
from time import perf_counter
from functools import lru_cache
from functools import partial
from gym.spaces import Box
from gym_socks.envs.integrator import NDIntegratorEnv
from gym_socks.sampling import random_sampler
from gym_socks.sa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 18:20:39 2019
@author: nico
"""
import sys
sys.path.append('/home/nico/Documentos/facultad/6to_nivel/pds/git/pdstestbench')
from spectrum import CORRELOGRAMPSD
import os
import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import... |
from .connection import GibsonConnection, create_connection
from .errors import (GibsonError, ProtocolError, ReplyError,
ExpectedANumber, MemoryLimitError, KeyLockedError)
from .pool import GibsonPool, create_pool, create_gibson
__version__ = '0.1.3'
# make pyflakes happy
(GibsonConnection, creat... |
from .metadata import Metadata
from . import errors
class Check(Metadata):
"""Check representation.
API | Usage
-------- | --------
Public | `from frictionless import Checks`
It's an interface for writing Frictionless checks.
Parameters:
descriptor? (str|dict): schema descrip... |
import tempfile
import pytest
from unittest import mock
from blaze.chrome.har import har_from_json
from blaze.command.manifest import view_manifest
from blaze.config.environment import EnvironmentConfig
from blaze.preprocess.har import har_entries_to_resources
from blaze.preprocess.resource import resource_list_to_pu... |
# -*- coding: utf-8 -*-
"""
data_stream
===========
Classes that define data streams (DataList) in Amira (R) files
There are two main types of data streams:
* `AmiraMeshDataStream` is for `AmiraMesh` files
* `AmiraHxSurfaceDataStream` is for `HxSurface` files
Both classes inherit from `AmiraDataStream` class, which... |
import traceback
import logging
from django.shortcuts import render
# Create your views here.
def error_404(request):
'''
It is 404 customize page.
Use this method with handler if we need to customize page from backend.
'''
data = {}
return render(request,'common/404.html', data)
def load_on_startup():
try:
... |
result=[]
base=[1,2,3]
for x in base:
for y in base:
result.append((x,y))
print(result)
|
from world_simulation import WorldEngine, EngineConfig
mp = WorldEngine(5, 5)
EngineConfig.ModelsConfig.HerbivoreConfig.number_min = 1
EngineConfig.ModelsConfig.HerbivoreConfig.number_max = 1
EngineConfig.ModelsConfig.HerbivoreConfig.health_min = 4
EngineConfig.ModelsConfig.HerbivoreConfig.health_max = 6
EngineConf... |
from pyfuzzy_toolbox import transformation as trans
from pyfuzzy_toolbox import preprocessing as pre
import pyfuzzy_toolbox.features.count as count_features
import pyfuzzy_toolbox.features.max as max_features
import pyfuzzy_toolbox.features.sum as sum_features
import test_preprocessing as tpre
import nose
print 'Load... |
"""
This is used for Versus game againts the computer with all characters.
"""
import os
import pygame
from battle import Battle
from colors import *
class Versus(object):
def __init__(self, game):
# Start loading
with game.load():
self.game = game
self.window = self.game.window
self.characters = []
... |
from Board import Board
from Board import Card
import numpy as np
from PIL import Image, ImageGrab
class ScreenParser:
"""
Screen Parser
"""
def __init__(self):
self.recognizer = CardRecognizer()
self.origin = None
def capture_screenshot(self, im_path='screenshot.png'):
im ... |
import torch
from torch import nn
import sys
from src import models
from src import ctc
from src.utils import *
import torch.optim as optim
import numpy as np
import time
from torch.optim.lr_scheduler import ReduceLROnPlateau
import os
import pickle
from sklearn.metrics import classification_report
from sklearn.metric... |
from django.conf.urls import *
from django.contrib.auth.decorators import permission_required
import signbank.video.views
urlpatterns = [
url(r'^video/(?P<videoid>\d+)$', signbank.video.views.video),
url(r'^upload/', signbank.video.views.addvideo),
url(r'^delete/(?P<videoid>\d+)$', signbank.video.views.de... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
#!/usr/bin/env python
# coding: utf-8
# # This will create plots for institutions of universities in THE WUR univs only and for the period of 2007-2017. The input dataset contains info of THE WUR univs only but for any period of time.
# #### The unpaywall dump used was from (April or June) 2018; hence analysis until ... |
def DataFrameRelatorio(listaUsuarios, listaMegaBytes, listaMegaBytesPorcentagem):
'''Função que converte dados em tabela'''
#usando o pandas vamos utilizar a função para converter em tabela
tabelaDados = pd.DataFrame({
"Usuário": listaUsuarios,
"Espaço Utilizado": listaMegaBytes,
"% de Uso": l... |
def reverse(k):
str = ""
for i in k:
str = i + str
return str
k = input('word:')
print ("awal : ",end="")
print (k)
print ("dibalik : ",end="")
print (reverse(k))
|
import os
from .gcloud import GoogleCloud
class GoogleCloudRepository:
def __init__(self, gc: GoogleCloud) -> None:
self.gc = gc
pass
def get_firebase_credential(self):
credentials = self.gc.get_secrets(filter="labels.domain:fitbit AND labels.type:firebase-config AND labels.id:credent... |
import abc
class Command(abc.ABC):
"""Base command class."""
name = 'base'
@abc.abstractmethod
def configure(self, parser):
"""Configures the argument parser for the command."""
pass
@abc.abstractmethod
def run(self, args):
"""Runs the command."""
pass
@... |
import time
import traceback
# .TwitterAPI is a local copy used for development purposes. If not present, import from the installed module (prod)
try:
from .TwitterAPI import TwitterAPI
except ImportError:
from TwitterAPI import TwitterAPI
def auto_retry(request):
def aux(*args, **kwargs):
# Try ... |
import smtplib
import json
from email.message import EmailMessage
import winsound
with open('./quant/config.json') as json_file:
data = json.load(json_file)
GMAIL_USER = data['gmail']['user']
GMAIL_PASSWORD = data['gmail']['password']
SUBSCRIBERS = data['subscribers']
def notification(source, ticker, ... |
'''
the primary output of the project
this script performs the actual image search
'''
from shared.configurationParser import retrieveConfiguration as rCon
from shared.histogramFeatureMethods import singleImageHisto
from shared.convnetFeatureMethods import singleImageConv
from shared.localBinaryPatternsMetho... |
import torch as tc
class LinearActionValueHead(tc.nn.Module):
def __init__(self, num_features, num_actions):
super().__init__()
self._num_features = num_features
self._num_actions = num_actions
self._linear = tc.nn.Linear(
in_features=self._num_features,
out... |
#
# Copyright (c) 2019 Intel 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 applicable law or ... |
import pandas as pd
import numpy as np
from sklearn import linear_model
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn import cross_validation
from sklearn.metrics import cohen_kappa_... |
from socket import *
import time
sock = socket(AF_INET, SOCK_STREAM)
sock.connect(('localhost', 25000))
while True:
start = time.time()
sock.send(b'30')
resp = sock.recv(100)
end = time.time()
print(end-start)
|
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. 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... |
#fastjson rce检测之python版rmi服务器搭建
'''
fastjson检测rce时候,常常使用rmi协议。
如果目标通外网,payload可以使用rmi://randomstr.test.yourdomain.com:9999/path,通过dnslog来检测。
但是目标是内网,我们在内网也可以部署rmi server,通过查看日志看是否有主机的请求来检测。
Java 写一个Java的rmi服务挺简单的,但是如果你正在python开发某个项目,而又不想用调用java软件,此文章获取能帮助你。
POST data
{
"a":{
"@type":"java.lang.Class",
"val":"com.... |
import sys
import json
sys.path.insert(0,'..')
def get_stats(team_id, team_name, cache_repository, http_repository):
stats = cache_repository.get_team_stats(team_id)
if not stats:
stats = http_repository.get_team_stats(team_id, team_name)
cache_repository.set_team_stats(team_id, json.dumps(stat... |
import pyspark.sql.functions as F
from pyspark.ml import Transformer
from pyspark import keyword_only
from pyspark.ml.param.shared import HasInputCol, HasInputCols, HasOutputCol, \
Params, Param, TypeConverters, HasLabelCol, HasPredictionCol, \
HasFeaturesCol, HasThreshold
from pyspark.ml.util import DefaultPar... |
from matplotlib import pyplot as plt
import math
import re
import statistics
f = open("/Users/rafiqkamal/Desktop/Data_Science/RNAProject210110/RNAL20StructuresGSSizes.txt")
contents = f.readlines()
# The original code worked for what is it was made for, but after talking with the lead researcher, I see that the code ... |
import pandas as pd
def dataframe_from_csv(path, header=0, index_col=0):
return pd.read_csv(path, header=header, index_col=index_col)
|
'''@package models
Contains the neural net models and their components
'''
from . import model, model_factory, run_multi_model, dblstm, \
linear, plain_variables, concat, leaky_dblstm, multi_averager,\
feedforward, leaky_dblstm_iznotrec, leaky_dblstm_notrec, dbrnn,\
capsnet, dbr_capsnet, dblstm_capsnet, dbgr... |
import torch
from torch import nn, Tensor
from torch.nn import functional as F
class BasicBlock(nn.Module):
"""2 Layer No Expansion Block
"""
expansion: int = 1
def __init__(self, c1, c2, s=1, downsample= None) -> None:
super().__init__()
self.conv1 = nn.Conv2d(c1, c2, 3, s, 1, bias=F... |
# MenuTitle: Replace Foreground with Background Paths
# -*- coding: utf-8 -*-
__doc__ = """
Replaces only the paths in the current active layer with those from the background.
"""
for l in Glyphs.font.selectedLayers[0].parent.layers:
for pi in reversed(range(len(l.paths))):
del l.paths[pi]
for p in l... |
class AbstractCallback:
"""
Interface that defines how callbacks must be specified.
"""
def __call__(self, epoch, step, performance_measures, context):
"""
Called after every batch by the ModelTrainer.
Parameters:
epoch (int): current epoch number
step... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.