content stringlengths 5 1.05M |
|---|
#!/usr/bin/python
# This file is part of INDXParse.
#
# Copyright 2011 Will Ballenthin <william.ballenthin@mandiant.com>
# while at Mandiant <http://www.mandiant.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with th... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator 2.3.33.0
# ... |
import numpy as np
from kernel import Kernel
from svm import SVM
from tools.dataset_tools import ACTION_DECODER
def cross_validate(X_train, y_train, X_val, y_val, ker_type="rbf"):
"""
Cross Validation by predicting over validation_data
this function is thought for the RBf kernel for now.
T... |
""" RTSP Client
Wrapper around OpenCV-Python. """
import os as _os
from . import ffmpegstream
from .ffmpegstream import Client
del(ffmpegstream)
from pathlib import Path as _Path
with open(_Path(_os.path.abspath(_os.path.dirname(__file__))) / '__doc__','r') as _f:
__doc__ = _f.read()
|
__author__ = 'Kuba'
import itertools
def is_good(n):
numbers = [2, 3, 5, 7, 11, 13, 17]
for z, x in enumerate(range(1, 8)):
if not int(n[x:x+3]) % numbers[z] == 0:
return False
return True
def main():
suma = 0
pandigits = itertools.permutations([str(x) for x in range(10)])
... |
# Copyright 2015 Brocade Communications System, 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.org/licenses/LICENSE-2.0
#
# ... |
from flask_restful import Resource, reqparse, abort, fields, marshal_with, \
marshal
from http import HTTPStatus
from Services.GetUserService import GetUserService
from extensions import db
from models import User
from models import Story, Comment, Like
from sqlalchemy.exc import *
from sqlalchemy import func
from... |
from app import redis_store
from flask import current_app
def redis_check() -> str:
if not redis_store.active:
return 'Not Enabled'
redis_client = redis_store.redis_store
try:
redis_client.ping()
except Exception as ex:
current_app.logger.error(ex, exc_info=True)
return... |
import typing as tp
from threading import Thread, Event
from time import sleep
from pymeterreader.core.meter_reader_node import MeterReaderNode
class MeterReaderTask(Thread):
class Timer(Thread):
"""
Precise event timer
"""
def __init__(self, interval: tp.Union[int, float], event:... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-present, CloudZero, Inc. All rights reserved.
# Licensed under the BSD-style license. See LICENSE file in the project root for full license information.
import base64
from datetime import timedelta
import simplejson as json
from pairing.utils import ExtendedEncoder, get_e... |
#!/usr/bin/env python
#coding=utf8
import subprocess
import json
from collections import namedtuple
disk_ntuple = namedtuple('partition', 'device mountpoint fstype')
def disk_partitions(all=False):
"""Return all mountd partitions as a nameduple.
If all == False return phyisical partitions only.
"""
p... |
# -*- coding: utf-8 -*-
"""
=== DFT_dirac.py ==========================================================
Plots zum Kapitel "DFT": Betrags- und Phasengang des Diracstoßes mit unter-
schiedlichen Verzögerungen
(c) 2016 Christian Münker - Files zur Vorlesung "DSV auf FPGAs"
===================================... |
{
"targets": [
{
"target_name": "displays",
"sources": ["linux.cc", "osx.cc", "win.cc", "displays.cc"],
"include_dirs": [ "<!(node -e \"require('nan')\")" ]
}
],
"conditions": [
[ "OS=='mac'",
{
"xcode_settings": {
"GCC_ENABLE_CPP_EXCEPTIONS": "YES",
... |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# 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... |
from django.conf.urls import url,include
from . import views
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.welcome, name = 'welcome'),
url(r'^signup/$', views.signup, name='signup'),
url(r'^a... |
import glob
import os
from setuptools import find_packages, setup
from torch.utils import cpp_extension
def find_cuda():
# TODO: find cuda
return '/usr/local/cuda'
def have_cuda():
if os.getenv('QUIVER_ENABLE_CUDA') == 1: return True
import torch
return torch.cuda.is_available()
def create_ex... |
from django.db import models
import matplotlib.path as mplPath
import numpy as np
import json
# Create your models here.
class Specimen(models.Model):
class Meta:
db_table = 'specimen'
specimenid = models.AutoField(primary_key=True)
name = models.CharField(max_length=64, help_text=u'名字')
sex... |
"""The util module provides some common helper functions and wrappers,
to parse timestamps, read streams in chunks, etc.
"""
from io import BytesIO
from time import strptime, struct_time
import mwklient.errors as errors
def version_tuple_from_generator(string, prefix='MediaWiki '):
"""Return a version tuple from... |
import os, sys
try:
import genomics_gans
except:
exec(open('__init__.py').read())
import genomics_gans
print("complete")
class TestImports:
def test_root(self):
current_file = os.path.realpath(__file__)
current_file_parent_dir = os.path.dirname(current_file)
root_dir = os.... |
import ProcessHandler as Handler
import threading
from json import load
import telegram
from telegram.ext import Updater, MessageHandler, Filters, CommandHandler
import time
config = load(open(Handler.baseDir + 'config.json'))
session = Updater(token = config['token'], use_context = True)
tasks = []
for item in confi... |
# coding=utf-8
import os
import numpy as np
import torch
class Accuracy(object):
def __init__(self):
self.reset()
def reset(self):
self.val_loss = 0
self.num_inst = 0
self.num_correct = 0
def update(self, loss, outputs, labels):
self.num_inst += labels.size(0)
... |
import os
import sys
from .collection import Collection
from .exceptions import CollectionNotFound
from .task import Task
class Loader(object):
def __init__(self, root=None):
"""
Creates a loader object with search root directory of ``root``.
If not given, ``root`` defaults to ``os.getcw... |
from unittest import TestCase
from .cache import Cache
class CacheCase(TestCase):
def test_cache_prefixes(self):
c_test = Cache(prefix="test")
c_test1 = Cache(prefix="test1")
c_test.add("test", {"test": "test"})
c_test1.add("test", {"test1": "test1"})
self.assertDictEqua... |
from .blogger import app
|
# Maintain a persistent ssh connection to an individual router
#
# Copyright (c) 2018 Ensoft Ltd
import os, socket, sys, time
try:
import paramiko
import ncclient.manager as nc_mgr
from ncclient.operations import RaiseMode
from entrance.connection.base import ConnectionFactory, ConState
from entra... |
# -*- coding: utf-8 -*-
import scrapy
import codecs
import sys
#리눅스상에서 utf-8 로 파일에 내용을 기록하려면 시스템 기본 인코딩으 ㄹutf-8 로 설정해야함
reload(sys)
sys.setdefaultencoding('utf8')
# scrapy 에서 spider 는 crawling/scrapping을 담당하는 핵심부분
#crawling/scrapping 절차에 대한 정의를 하는 부분
class CurrSpider(scrapy.Spider):
name = 'currSpider'
start_... |
from src.lighting.LightInterface import LightInterface
class LightLoader(LightInterface):
""" Loads light source\'s settings and sets them.
Settings can be defined in the config file in the corresponding section or in the external file.
**Configuration**:
.. list-table::
:widths: 25 10... |
#!/usr/bin/python
# Assertions-based Coverage tool : find coverage and coverage percentage using assertions
# Tool version 1.0
# Code start from here
import os
from Tkinter import *
root = Tk()
root.title(" Assertions-based Coverage tool V 1.0")
# to take arguments from entry boxes
ass_path_in = StringVar()
transc... |
from typing import List
from django.db import transaction
import app.services.google.calendar
from event.enums import EventStatus
from event.models import Event, Session
@transaction.atomic
def create_or_update(event: Event):
session_updates = []
if event.status == EventStatus.PUBLISHED:
for session... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 22:31:03 2017
@author: Mihailo
"""
import cv2
import numpy as np
import math
def thresholdImage(img):
grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# retval, threshImg = cv2.threshold(grayImg,0,255,cv2.THRESH_OTSU)
threshImg = cv2.adaptiveThr... |
from app.main import main_blueprint
from flask import render_template, url_for, send_from_directory
from config import GeneralConfig
from app import mail
from app.utils.mail import Message
@main_blueprint.route('/')
def index_page():
return render_template('index.html')
@main_blueprint.route('/img/<string:filenam... |
from tkinter import *
from tkinter.font import BOLD
from tkinter import ttk
from tkinter import tix
import sqlite3
from turtle import bgcolor
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.pdfbase import pdfmetrics
from reportlab.platypus import SimpleDocTem... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Category, Picture
# Create your views here.
'''
view_photo route function
'''
def view_photo(request,pk):
picture = Picture.objects.get(id=pk)
return render(request,'picgallery/view_photo.html',{'picture':pictu... |
"""Interface to the HST catalog of the LMC field.
Author:
-------
Tony Sohn
"""
import os
import gzip
import shutil
from astropy.table import Table
from .utils import download_file
local_dir = os.path.dirname(os.path.abspath(__file__))
hst_catalog_name = 'lmc_calibration_field_hst_2017p38_jwstmags'
hst_catalog_... |
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
import wormnest.utils as utils
# import utils
engine = create_engine('sqlite:///url.db', e... |
from dataclasses import dataclass
from enum import Enum
class Backend(Enum):
POSTGRES = 1
MYSQL = 2
SQLITE = 3
class ParameterStyle(Enum):
NUMERIC = 1 # SELECT * FROM user WHERE id = :1
# DB-API2
DOLLAR_NUMERIC = 2 # SELECT * FROM user WHERE id = $1
... |
import scrapy
from scrapy import Request
from .spider import Spider
from splash_utils import splash_request
from entities.article import Article
from logger import Logger
from urllib.parse import urlencode
import re
class GeelbeSpider(Spider):
'''
Araña para escrapear la página de geelbe
'''
name = '... |
#Selahattin Ahmed Ataşoğlu -- 190401090
import sympy as sym
sym.init_printing() #Polinom denklemini de göstermek istediğim için,
x = sym.Symbol('x') #günlük hayattaki yazım şekliyle x'e sembol tanımlaması yapıyoruz.
... |
from .increment_register import IncrementRegisterInstruction
class Dey(IncrementRegisterInstruction):
register_name = 'y'
amount = -1
|
import shap
import numpy as np
def test(X):
return np.sum(X, 1)
def custom_masker(mask, x):
return (x * mask).reshape(1,len(x)) # just zero out the features we are masking
explainer = shap.Explainer(test, custom_masker)
shap_values = explainer(X[:100])
assert np.var(shap_values.values - shap_values.data) < ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# cython: language_level=3
import math
import os
import shutil
import tempfile
import uuid
import sympy as sym
import numpy as np
from scipy.special import binom
from pycompilation import compile_link_import_py_ext
_template_base = os.path.dirname(__file__) + "/external... |
#Funkciju iz prethodne zadaće učitati kao funkciju modula u novi program i pozvati je nakon traženja unosa
#od korisnika.
import zadaca6
zadaca6.obrnuto("kaktus")
|
# Given an integer n,
# count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
# Example:
# Input: 13
# Output: 6
# Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
# Hints:
# Beware of overflow.
class Solution(object):
def countDigitOne(self... |
# coding: utf-8
# 2021/2/15 @ tongshiwei
import mxnet.ndarray as nd
from longling.ML.MxnetHelper import fit_wrapper
@fit_wrapper
def fit_f(net, batch_data, loss_function, *args, **kwargs):
state, action, reward = batch_data
loss = []
pred = nd.pick(net(state), action)
for _, loss_f in loss_function.it... |
import tensorflow as tf
from tensorflow.keras import layers
def create_model(input_shape):
inputs = tf.keras.Input(shape=input_shape)
x = layers.Conv2D(96, 11, activation="relu")(inputs)
x = layers.MaxPooling2D()
x = layers.Conv2D(256, 5, activation="relu")(x)
x = layers.MaxPooling2D(3)(x)
x =... |
from opencog.atomspace import TruthValue, types
from opencog.type_constructors import *
from thought_engine import *
from global_space import *
initialize_global_space()
initialize_thought_pool()
introspective_search_engine = ThoughtEngine('introspective search', 1.0, 0.85, 0.375)
|
import json
import os
import threading
import unittest
from http.server import BaseHTTPRequestHandler, HTTPServer
from test.support import EnvironmentVarGuard
from urllib.parse import urlparse
from datetime import datetime, timedelta
import mock
from google.auth.exceptions import DefaultCredentialsError
from google.cl... |
from flask import Flask
from flask import Response
from flask import make_response
from flask import jsonify
import sqlite3
import json
app = Flask(__name__)
@app.route('/')
def default_route():
conn = sqlite3.connect('swp.db')
c = conn.cursor()
c.execute('SELECT temp,amount,status,timestamp FROM api ORDE... |
from .cli import CliEntrypoint
if __name__ == "__main__":
import fire
fire.Fire(CliEntrypoint)
|
from django.contrib import admin
from .models import Organization
# Register your models here.
admin.site.register(Organization) |
#!/usr/bin/env python3
import cv2
import numpy as np
import sys, time
import os
import io
import open3d as o3d
import argparse
from transforms3d.affines import compose
from transforms3d.euler import euler2mat
from cyclonedds.domain import DomainParticipant
from cyclonedds.pub import DataWriter
from cyclonedds.sub ... |
class Solution:
def XXX(self, num: int) -> int:
if 2**31-1>num>0:
s=str(num)
result=eval(s[-1::-1].strip('0'))
return result if 2**31-1>result>0 else 0
elif num==0:
return num
elif (-2**31)<=num<0:
num=abs(num)
s=str(num... |
# -*- coding: utf-8 -*-
import logging
from flask import request, g
from flasgger import swag_from
from http import HTTPStatus
from pathlib import Path
from vantage6.common import logger_name
from vantage6.server import db
from vantage6.server.permission import (
Scope as S,
Operation as P,
PermissionMana... |
import HtmlGen as hg
class MarkdownGenerator:
def __init__(self, prompt):
self.code = input(prompt)
def __read_code(self, c):
if c[0:2] == "**" and c[::-1][0:2] == "**":
try:
c = c[2:-2]
return "<b>" + c + "</b>"
except:
... |
"""new attributes for csv files
Revision ID: 9dccb02d8201
Revises: 70abcb00e23f
Create Date: 2017-06-30 15:30:33.159354
"""
from alembic import op
import sqlalchemy as sa
from limonero.migration_utils import is_sqlite
# revision identifiers, used by Alembic.
revision = '9dccb02d8201'
down_revision = '70abcb00e23f'
... |
#
# file: make_iris_tree.py
#
# A parsimonious decision tree for the iris dataset
# from the SNOBOL chapter. For the CLIPS example.
#
# RTK, 08-May-2021
# Last update: 08-May-2021
#
################################################################
import matplotlib.pylab as plt
import numpy as np
from sklearn.t... |
from .pointnet2_head import PointNet2Head
from .cylinder_head import Cylinder3DHead
__all__ = ['PointNet2Head', 'Cylinder3DHead']
|
#!/usr/bin/env python
# Copyright 2020 Red Hat, Inc.
#
# 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 ap... |
# -*- coding: utf-8 -*-
##############################################################################
# Copyright (c), Gianfranco Ulian and Giovanni Valdre'. #
# All rights reserved. #
# ... |
# accept two numbers and an operation, and then perform the operation on the two numbers
print("Simple calculator!")
first_number = input("First number? ")
opreator = input("Operation? ")
second_number = input("Second number? ")
opreator_list = ["+", "-", "*", "**", "%", "/"]
if first_number.isnumeric() == False or s... |
from __future__ import absolute_import
from __future__ import unicode_literals
from blazeutils.strings import StringIndenter, simplify_string, case_cw2us, case_mc2us, \
case_us2mc, case_us2cw, reindent, randchars, randnumerics, randhash
def test_string_indent_helper():
s = StringIndenter()
s.inc('1.0')
... |
from src.remote.Fetcher import Fetcher
from src.remote.DataKeeper import DataKeeper
from src.remote.Scheduler import Scheduler
from src.remote.Reducer import Reducer
from src.remote.HaltSignalActor import HaltSignalActor
|
PROJECT = '{project_name}'
LOCALE = 'en_US'
PROCESSES = 1
PORT = 8000
DEBUG = True
LOGGERS = {
'': {
'level': 'INFO',
'fmt': '%(color)s[%(fixed_levelname)s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s',
#'fmt': '[%(fixed_levelname)s %(asctime)s %(module)s:%(lineno)d] %(me... |
# Generated by Django 3.1.4 on 2021-04-15 16:48
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('civictechprojects', '0042_auto_20210303_0016'... |
#!/usr/bin/env python
import os, sys, argparse, errno, yaml, time, datetime
import cv2, numpy
import rospy, rospkg, threading
import torch, torchvision
import torch.optim as optim
import torch.nn.functional as function
import torchvision.datasets as datasets
import torchvision.models as models
import torchvision.tran... |
import sys
import enot
from setuptools import setup, find_packages
def get_requirements() -> list:
with open('requirements.txt', 'r') as f:
deps = f.readlines()
result = []
for dep in deps:
if dep == '': # drop empty deps
continue
dep = get_name(dep)
if dep ==... |
import pandas as pd
import matplotlib as mpl
import seaborn as sns
tips = sns.load_dataset("tips")
print(tips.iloc[0:5])
sns.set()
sns.lmplot(x='total_bill', y='tip',
hue='smoker', data=tips)
mpl.pyplot.show()
|
from ml_dl_models.models import MelodyGenerator
__title__ = 'ML DL Models'
__version__ = '1.0.1'
__author__ = 'Laxman Maharjan'
|
#!/usr/bin/env python
import rospy
from rospy_tutorials.srv import AddTwoInts
if __name__=='__main__':
rospy.init_node("add_two_ints_client",anonymous=True)
rospy.wait_for_service("/add_two_int")
try:
add_two_int = rospy.ServiceProxy("/add_two_int",AddTwoInts)
response= add_two... |
## Copyright 2015-2019 Ilgar Lunin, Pedro Cabrera
## 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... |
# Write a program to calculate the voltage for a given values of resistance and current
resistance = float(input("Enter the resistance: "))
current = float(input("Enter the current: "))
voltage = resistance * current
print(f"{voltage} V") |
import itertools
import warnings
from numbers import Number
import numpy as np
from ..abc import SparseArray
from ..utils import NDArrayReprMixin
from ..utils import is_broadcastable
from ..utils import ravel_sparse_multi_index
from ..utils import unravel_sparse_index
__all__ = ['CoordinateArray']
class Coordinat... |
import io
from PIL import ExifTags
from PIL import Image
from mitmproxy.types import multidict
from . import base
class ViewImage(base.View):
name = "Image"
prompt = ("image", "i")
content_types = [
"image/png",
"image/jpeg",
"image/gif",
"image/vnd.microsoft.icon",
... |
#!/usr/bin/env python3
import json
import os
from cryptography.fernet import Fernet
from validate_email import validate_email
import keyring
DATA_PATH = "/etc/.secure_filesystem_emails"
def generateFernetKey():
key = Fernet.generate_key()
keyring.set_password("safe_filesystem", "nothingtosee", key)
retur... |
import pytest
import dataservice
class TestSwagger:
"""
Tests the swagger spec
"""
@pytest.mark.parametrize('path', [
'definitions.Participant',
'definitions.Diagnosis',
'definitions.DiagnosisPaginated',
'definitions.DiagnosisResponse',
'definitions.Participan... |
###################################################
## ##
## This file is part of the KinBot code v2.0 ##
## ##
## The contents are covered by the terms of the ##
## BSD 3-clause license included in the LICENSE ##
## file,... |
"""Tests for the protocol engine's ActionDispatcher."""
from decoy import Decoy
from opentrons.protocol_engine.actions import (
ActionDispatcher,
ActionHandler,
PlayAction,
)
def test_sink(decoy: Decoy) -> None:
"""It should send all actions to the sink handler."""
action = PlayAction()
sink... |
# Copyright 2017 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Run3_cff import Run3
process = cms.Process('PROD',Run3)
process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi")
process.load("Configuration.Geometry.GeometryExtended2021Reco_cff")
process.load("Configuration.StandardSequences.MagneticField_cff")
pro... |
import random
from discord.ext.commands import Command
from bot import bot # pylint: disable=no-name-in-module
@bot.command('p')
async def pokerole(ctx, n):
n = int(n)
rolls = [random.randint(1, 6) for _ in range(n)]
result = \
f'''
Rolls: {' '.join(map(str, rolls))}
Successes: {len(list(fil... |
# -*- coding: utf-8 -*-
from prompt_toolkit.contrib.completers import WordCompleter
from prompt_toolkit.contrib.shortcuts import get_input
from prompt_toolkit.interface import Abort
import pyorient
from tabulate import tabulate
from pygments.style import Style
from pygments.token import Token
from pygments.styles impor... |
# Copyright 2015 Google 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import os
from pymongo import MongoClient
import pytest
from dcctools.anonlink import Results
def test_insert_results():
systems = ["a", "b", "c"]
project = "name-dob"
anonlink_results = {
"groups": [[[0, 1], [1, 2], [2, 3]], [[1, 5], [2, 6]], [[0, 8], [2, 9]]]
}
client = MongoClient(po... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.stats import special_ortho_group
import numpy as np
class AIO_SlowCouplingBlock(nn.Module):
''' This elegant coupling block was invented by Jakob Kruse '''
def __init__(self,
dims_in, dims_c=[],
subnet_constructor=N... |
from collections import OrderedDict
import gzip
import logging
from typing import List
import numpy
from overrides import overrides
import pyhocon
import spacy
import tqdm
from ...common.models import get_submodel
from ...common.params import replace_none, Params
from ...common import util
from ...data.instances.sent... |
'''
(c) University of Liverpool 2019
All rights reserved.
@author: neilswainston
'''
# pylint: disable=invalid-name
# pylint: disable=too-many-arguments
# pylint: disable=wrong-import-order
from sklearn.preprocessing import MinMaxScaler
from liv_ms.chem import encode_desc
import numpy as np
def get_data(filename, ... |
def metroCard(lastNumberOfDays):
if lastNumberOfDays == 28 or lastNumberOfDays == 30:
return [31]
elif lastNumberOfDays == 31:
return [28, 30, 31]
else:
return null
|
#!/usr/bin/env python
import os
field0 = ""
lastLine = ""
found_metadata = False
for l in os.sys.stdin:
m = l.split()
if len(m) > 0 and m[0] == "META_DATA":
found_metadata = True
print("")
if found_metadata:
print(l, end=' ')
else:
if len(m) == 11 and m[0][0] != "#":
if m[0] != field... |
import datetime
import time
import json
import pika # Python AMQP Library
RABBIT_HOST = "123.123.123.123"
RABBIT_USER = "guest"
# RABBIT_PWD_ENCRYPTED =
RABBIT_PWD_DECRYPTED = "guest"
credentials = pika.PlainCredentials(RABBIT_USER, RABBIT_PWD_DECRYPTED)
parameters = pika.ConnectionParameters(credentials=credential... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.jvm.resolve.jvm_tool import JvmToolBase
from pants.option.option_types import SkipOption
from pants.util.docutil import git_url
class KtlintSubsystem(JvmToolBase):
options... |
from .linear_ae import LINEAR_AE
from .lstm_ae import LSTM_AE
from .conv_lstm_ae import CONV_LSTM_AE
|
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... |
import os
class ExportPath:
""" An internal helper class to automatically build path names when generating images from annotations with variations """
def __init__(self, destination_directory: str, symbol_class: str, raw_file_name_without_extension: str,
extension: str = "png", stroke_thickn... |
"""
>>> avg = make_averager()
>>> avg(10)
10.0
>>> avg(11)
10.5
>>> avg(12)
11.0
>>> avg.__code__.co_varnames
('new_value', 'total')
>>> avg.__code__.co_freevars
('series',)
>>> avg.__closure__ # doctest: +ELLIPSIS
(<cell at 0x...: list object at 0x...>,)
>>> avg.__closure__[0].cell_contents
[10, 11, 12]
"""
def mak... |
"""
REST API Documentation for the NRS TFRS Credit Trading Application
The Transportation Fuels Reporting System is being designed to streamline
compliance reporting for transportation fuel suppliers in accordance with
the Renewable & Low Carbon Fuel Requirements Regulation.
OpenAPI spec version: ... |
__author__ = 'ritesh'
import json
import contextlib
from flask import Flask, redirect, url_for, request, make_response
import pandas as pd
import numpy as np
app = Flask(__name__)
def ema(values, period):
values = np.array(values)
return pd.ewma(values, span=period)[-1]
#values = [10127.75, 10118.25, 10044.... |
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.bind((host, port))
s.listen(5)
c = None
while True:
if c is None:
# Halts
print("[Esperando la coneccion]")
c, addr = s.accept()
print("Enviando coneccion a: ", addr)
else:
... |
# -----------------------------------------------------------------------------
def filter_list(values, excludes):
"""
Filter a list of values excluding all elements from excludes parameters and return the new list.
Arguments:
values : list
excludes : list
Returns:
list
""... |
"""
``semiclass`` provides classes implementing various domain adaptation methods.
All domain adaptation methods have to be subclass of BaseEstimator.
This implementation aims for clarity rather than efficiency (it is not fast enough) and scalability (it can't really deal with large dimension or large sample case).
For... |
from setuptools import setup
import os
VERSION = "0.1.1"
def get_long_description():
with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"),
encoding="utf8",
) as fp:
return fp.read()
setup(
name="asgi-auth-github",
description="ASGI middleware that... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.