content stringlengths 5 1.05M |
|---|
#! /usr/bin/python
import argparse
import re
import sys
import os
# < CONSTANTS >
__CMD_COMPILE__ = "compile"
__CMD_IMPORT__ = "import"
__CMD_OUTFILE__ = "outFile"
__CMD_REMOVE_COMF__ = "rmCompile"
__COMMAND_REGEX__ = r"((#)|(\/\/))\s*!(?P<cmd>\w*)\s\"?(?(1)((?P<file>.*)\"\s*)|... |
# Copyright 2020 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 "license" file acc... |
# -*- coding: utf-8 -*-
import lazygantt as lg
import os
PATH_MINIMAL_GANTT = os.path.join(os.path.curdir, 'files', 'minimal_gantt.csv')
PATH_GANTT = os.path.join(os.path.curdir, 'files', 'gantt.csv')
PATH_CONFIG = os.path.join(os.path.curdir, 'files', 'config.yaml')
def default_gantt():
"""Creates a g... |
"""
Copyright 2018-2019 Skyscanner Ltd
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... |
# -*- coding: utf-8 -*-
# $Id: wuiadminbuildsource.py $
"""
Test Manager WUI - Build Sources.
"""
__copyright__ = \
"""
Copyright (C) 2012-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute i... |
from nose.tools import assert_equal, assert_true
import pyrk.reactivity_insertion as ri
from pyrk import timer
from pyrk.utilities.ur import units
ti = timer.Timer(t0=0.0 * units.seconds,
tf=10.0 * units.seconds,
dt=0.01 * units.seconds)
def test_default_ri():
default = ri.Reac... |
"""
General file system methods.
.. moduleauthor:: Jaisen Mathai <jaisen@jmathai.com>
"""
from __future__ import print_function
from builtins import object
import os
import re
import shutil
import time
import sys
from elodie import geolocation
from elodie import log
from elodie.config import load_config
from elodie.... |
from pincer import Client
from pincer.commands import command, CommandArg, Description
from pincer.objects import Embed, MessageContext
class Bot(Client):
@command(description="Say something as the bot!")
async def say(
self,
ctx: MessageContext,
content: CommandArg[str, Description["T... |
import os.path as op
import numpy as np
from numpy.testing import assert_array_almost_equal
from nose.tools import assert_true, assert_equal
from mne import io, pick_types
from mne.time_frequency.ar import yule_walker, fit_iir_model_raw
from mne.utils import requires_statsmodels, requires_patsy
raw_fname = op.join(o... |
"""
Data structures implemented for demo use
ListDeque
NodeDeque
"""
class DequeBase(object):
def __init__(self):
pass
def __len__(self):
pass
def append(self, nd):
pass
def index(self, idx):
pass
def insert(self, nd, idx=-1):
pass
def empty(self):... |
import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk
from selenium import webdriver
import time
import pyautogui
height = pyautogui.size()[1]
width = pyautogui.size()[0]
print("resolution = " + str(width) + ", " + str(height))
window = tk.Tk()
window.title("YouTube Bot")
window.r... |
import turtle
turtle.tracer(10, 0) # Increase the first argument to speed up the drawing.
turtle.setworldcoordinates(0, 0, 700, 700)
turtle.hideturtle()
LINE_LENGTH = 5 # Try changing the line length by a litte.
ANGLE = 90 # Try changing the turning angle by a few degrees.
LEVELS = 6 # Try changing the recursive lev... |
#!/usr/bin/env python
"""Tests for client_utils_linux.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import platform
import tempfile
import unittest
from absl.testing import absltest
from builtins import range # pylint: disable=redefine... |
# Copyright 2017 The Bazel 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 la... |
import FWCore.ParameterSet.Config as cms
# This cfi contains everything needed to use the VolumeBased magnetic
# field engine version 160812.
#
# PLEASE DO NOT USE THIS DIRECTLY
# Always use the standard sequence Configuration.StandardSequences.MagneticField_cff
magfield = cms.ESSource("XMLIdealGeometryESSource",
... |
from pyb import I2C
class i2cDev():
def __init__(self, id):
self.i2c_slave_id = id
self.i2c_bus_id = 2
self.i2c_baudrate = 100000
self.mem_write = 0
self.mem_read = 0
self.write = 0
self.read = 0
self.i2c_bus = self._i2c_bus_init()
def _i2c_bus_... |
import sys
if sys.version_info <= (3,7):
sys.exit('Python >= 3.7 is required')
from setuptools import setup
def readme():
with open('Readme.md') as f:
return f.read()
setup(name='SoMeNLP',
version='0.1',
description='NLP procedures for scientific articles and software extraction.',
... |
from .plot_colors import plot_colors
from .plot_intensity import plot_intensity
from .plot_phase import plot_phase
from .plot_longitudinal_profile import plot_longitudinal_profile_colors, plot_longitudinal_profile_intensity |
import numpy as np
# import sys
import nltk
from nltk.tokenize import word_tokenize
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.layers import Dropout
from tensorflow.python.keras.layers import LSTM
from tensorflow.python.keras.call... |
# http://www.codewars.com/kata/56598d8076ee7a0759000087/
import math
def calculate_tip(amount, rating):
tip_percentage = {
"terrible": 0,
"poor": 0.05,
"good": 0.1,
"great": 0.15,
"excellent": 0.2
}
if rating.lower() in tip_percentage.keys():
return math.c... |
# ------------------------------------------------------------------------------
# Joyous events models
# ------------------------------------------------------------------------------
import datetime as dt
import calendar
from collections import namedtuple
from contextlib import suppress
from functools import partial
... |
from src import math_functions
integer_one = 1
integer_two = 2
integer_three = math_functions.complex_math(integer_one, integer_two)
print(integer_three)
integer_four = math_functions.less_complex_math(integer_one, integer_two)
print(integer_four)
integer_five = math_functions.calculate_complex_number(integer_one, ... |
#!/usr/bin/env python3
import argparse
import fnmatch
import hashlib
import json
import os
import re
import shutil
import sys
import time
from typing import Dict, List, Optional, Set, Tuple
FILE_CHUNK_SHA1_SIZE = 8192
REPORT_FILE_FORMAT_TEXT = "text"
REPORT_FILE_FORMAT_JSON = "JSON"
REPORT_FILE_FORMAT_JSON_SEPARATORS... |
from typing import List, Tuple, Dict, Any
import numpy as np
import pandas as pd
import networkx
class Graph(object):
def __init__(
self,
nodes: List[int],
edges: List[Tuple[int, int]] = None,
weighted_edges: List[Tuple[int, int, float]] = None,
):
if ... |
import lazy_import
lazy_import.lazy_module("tensorflow") |
import os
import unittest
from unittest import TestCase
from unittest.mock import patch
import requests
from explainaboard.explainaboard_main import main
from explainaboard.tests.utils import OPTIONAL_TEST_SUITES, top_path
class TestCLI(TestCase):
"""TODO: these tests only tests if they run. After the main scri... |
import model
def izpis_igre(igra):
return (
f"Igraš igro vislic:\n" +
f"Narobe ugibane črke so: {igra.nepravilni_ugibi()}\n" +
f"Trenutno stanje besede: {igra.pravilni_del_gesla()}\n"
)
def izpis_poraza(igra):
return(
f"Izgubil si, več sreče prihodnjič\n"
f"Narobe... |
from regression_tests import *
class TestDsm(Test):
settings=TestSettings(
input='test.exe'
)
def test_strings_in_code(self):
assert self.out_dsm.contains(r'0x407755:.*call 0x407458 <puts>')
assert self.out_dsm.contains(r'; function: _puts at 0x407458 -- 0x40745e')
assert s... |
import logging
from pkg_resources import get_distribution
from django.conf import settings
from keystoneclient.v2_0 import client as keystone_client
from openstack_auth.backend import KEYSTONE_CLIENT_ATTR
from horizon import exceptions
from hsm_dashboard.api import base
LOG = logging.getLogger(__name__)
def _g... |
"""
CLI for 4D image registration of .mat files using the FMRIB Software Library (FSL).
"""
import tempfile as tf
import os
import sys
import time
import click
import numpy as np
import nibabel as nib
import hdf5storage
@click.command()
@click.argument("path")
@click.option("-n", "--name", required=True, help="Image ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-20 01:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... |
# Functions for adding argparse arguments to different scripts
# (Several arguments are shared among the scripts.)
import argparse
from hyperparams import CLASSIFIER_CONFIGS, ADVERSARY_CONFIGS
def add_emnist_datasets(parser):
"""
Adds the required parser arguments representing the training and testing
EMN... |
'''
Python program to check the priority of the four operators (+, -, *, /)
'''
from collections import deque
import re
__priority__ = {
'-': 1,
'+': 2,
'*': 3,
'/': 4,
}
def test_higher_priority (operator1, operator2):
return __priority__[operator1] > __priority__[operator2]
print(test_higher_pr... |
import random
import math
import copy
random.seed(11)
def sigmoid(x):
try:
return (1.0 / (1.0 + math.exp(-x)))
except OverflowError:
return 0 if x < 0 else 1
class Options:
@staticmethod
def set_options(
num_inputs,
num_outputs,
population_size,
fitn... |
from irida_uploader_cl.core import logger
from irida_uploader_cl.core import cli_entry
from irida_uploader_cl.core import exit_return
from irida_uploader_cl.core.cli_entry import VERSION_NUMBER
|
import textwrap
import traceback
from disnake.ext import commands
from disnake.ext.commands import Cog
from loguru import logger as log
from bot import Context, Xythrion
from bot.utils import codeblock, markdown_link
BASE_URL = "https://api.duckduckgo.com/?q={}"
class Warnings(Cog, command_attrs=dict(hidden=True))... |
from utils import joystick, singleton
from constants import Constants
from wpilib.buttons.joystickbutton import JoystickButton
from commands import togglehatchlatch
class OI(metaclass=singleton.Singleton):
"""Deals with anything controller related,
be it gamepads, joysticks, or steering wheels."""
def __... |
import os
from rpm.system.ui import UI
from rpm.system.update import Update
from pyrevit.coreutils.ribbon import ICON_LARGE
from pyrevit import forms
__context__ = 'zero-doc'
def __selfinit__(script_cmp, ui_button_cmp, __rvt__):
if os.system('git --version') != 0:
return False
if Update.checkPyRevit() or Update.... |
from django.shortcuts import get_object_or_404, redirect
from .models import URL
def root(request, url_hash):
url = get_object_or_404(URL, url_hash = url_hash)
url.clicked()
return redirect(url.full_url)
|
import time
def test_client_can_get_subforums(client):
resp = client.get('/api/subforums')
assert resp.status_code == 200
def test_client_gets_correct_subforums_fields(client):
resp = client.get('/api/subforums')
assert 'offset' in resp.json
assert resp.json['offset'] is None
assert 'total' ... |
from functools import partial
from nose.tools import *
import unittest
import pandas as pd
import six
import py_entitymatching.feature.simfunctions as sim
@nottest
def test_null_cases(sim_measure, input1, input2):
val = sim_measure(input1, input2)
assert_equal(pd.isnull(val), True)
def test_invalid_input_c... |
#!/usr/bin/env python3
# -*- coding:utf-8-*-
from SQLiteHelper import DBHelper
if __name__ == '__main__':
db = DBHelper()
db.create_database()
tmp = db.insert_user('admin', 'admin') # 默认用户
tmp2 = db.insert_content_by_username('admin','flask-example', 'https://github.com/doudoudzj/flask-example.git', '... |
#coding:utf-8
from pyglet.gl import *
import numpy as np
import OpenGL.GL.shaders
import ctypes
import pyrr
import time
from math import sin
from pyrr import Vector3, matrix44, Matrix44
import time
import numpy
class ObjLoader:
def __init__(self):
self.vert_coords = []
self.text_coords = []
... |
from enum import IntEnum
import requests
from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth
class Commands(IntEnum):
OFF = 0
ON = 1
RESET = 3
AUTO_REBOOT_ON = 4
AUTO_REBOOT_OFF = 5
class WattBox(object):
def __init__(self, ip, port=80, user="wattbox", pass... |
from app import app
if __name__ == "__main__":
app.run(debug = True, port = 5002)
|
#!/usr/bin/python3
### Copyright (c) 2018 Silvio Mayolo
### See LICENSE.txt for licensing details
# Note: Depends on Alakazam (pip install alakazam)
import sys
import traceback
from contextlib import closing
from enum import Enum
from itertools import count
import alakazam as zz
from alakazam import _1, _2, _3, _4,... |
import requests
import json
import logging
import math
# Required datasets: adni_9rows, adni, data_pr1, desd-synthdata
endpointUrl = 'http://88.197.53.100:9090/mining/query/PEARSON_CORRELATION'
def test_PearsonCorrlation_MIP_AlgoTesting_1():
"""
Results from 2019_MIP_Algo_Testing/PearsonCorrelation
lef... |
from hk_scom import *
from numberGen import generate
class ScomData():
def createData(self):
hk_packet = bytearray(hk_scom_enabled([1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0]))
hk_packet.extend(hk_scom_errors([1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0]))
hk_packet.extend(hk_scom_s... |
import numpy as np
import pandas as pd
from scipy.stats import invgauss
from tqdm import tqdm
def simulate_subject(parameters, values, gaze, n_repeats=1, subject=0, boundary=1, error_weight=0.05, error_range=(0, 5000), drift='multiplicative'):
n_trials, n_items = values.shape
rts = np.zeros(n_trials * n_rep... |
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
elif request.method == 'POST':
first_value = float(request.form.get('firstNumber'))
... |
# -*- coding: utf-8 -*-
#
# File : echotorch/nn/EESN.py
# Description : An ESN with an embedding layer at the beginning.
# Date : 22 March, 2018
#
# This file is part of EchoTorch. EchoTorch is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by... |
from os import path as path
def find_target() -> str:
cd = path.abspath(".")
maybe = path.join(cd, "target")
while not path.exists(maybe):
cd = path.abspath(path.join(cd, ".."))
maybe = path.join(cd, "target")
return maybe |
import pyblish.api
import pype.maya.action
from avalon import io
import pype.api
class ValidateRenderLayerAOVs(pyblish.api.InstancePlugin):
"""Validate created AOVs / RenderElement is registered in the database
Each render element is registered as a subset which is formatted based on
the render layer an... |
"""Tests for the device package."""
|
"""Retrieves the tracker data generated from currently recorded video in .json format and converts it to the desired .csv format."""
#takes recording_ID as input.
import sys
import requests
import json
from pandas.io.json import json_normalize
from pathlib import Path
#tracker_dir is the directory where the tracking ... |
import json
def FuzzerRunOne(FuzzerInput):
try:
obj = json.loads(FuzzerInput.decode("utf-8", "replace"))
except json.decoder.JSONDecodeError:
return
except RecursionError:
return
except ValueError:
return
enc = json.dumps(obj)
obj2 = json.loads(enc)
|
#!/usr/bin/env python
import argparse
import smtplib
from email.mime.text import MIMEText
import time
import socket
timestamp = time.strftime("%Y%m%d-%H%M%S")
parser = argparse.ArgumentParser()
parser.description = ('Send a test email to a given SMTP server')
parser.add_argument('-a', '--address', default='local... |
from django.shortcuts import render
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile, File
from django.conf import settings
from django.core.mail import EmailMessage
from django.core.mail import send_mail
import os
import shutil
from django.http import HttpRes... |
#! /usr/bin/python3
# -*- coding:utf-8 -*-
import pickle
import pandas as pd
import numpy as np
import glob
import os
import math
import xml.etree.ElementTree as ET
import cv2
from pie_ras import PIERas
import matplotlib.pyplot as plt
import seaborn as sns
miss_data = []
false_data = []
data_path = "/home/kuriatsu... |
"""Botometer tests."""
from unittest import TestCase
from unittest.mock import MagicMock, patch
from sara.core.botometer_api import (check_users_botometer,
check_user_botometer)
class TestBotometer(TestCase):
"""Test Botometer methods."""
@patch('sara.core.botometer_api.... |
from simulator.reports.DtnAbstractReport import DtnAbstractReport, concat_dfs
class DtnInRadioBundlesReport(DtnAbstractReport):
_alias = 'in_radio'
def collect_data(self):
# Get the bundles stored in all the node's radios
df = concat_dfs({nid: concat_dfs({rid: r.stored for rid, r in node.radi... |
#!/usr/bin/env python
'''
'''
from .version import __version__
from .beam import Beam
from . import coordinates
from .airy import Airy
from .cassegrain import Cassegrain
from .gaussian import Gaussian
from .array import Array, DipoleArray
from .finite_cylindrical_parabola import FiniteCylindricalParabola
from .pha... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is my attempt at coding the last question of the last homework assignment
for my algorithms class at Portland State University.
"""
__author__ = 'Mike Lane (http://www.github.com/mikelane/'
__copyright__ = 'Copyright (c) 2015 Mike Lane'
__license__ = 'GPLv3'
imp... |
#This is the basic program to print Hello, World using Python
print("Hello, World!") |
import os
import random
import numpy as np
import cv2
from lxml import etree
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def object_random(objects):
"""
random choice the object
:param objects: ['object1','object2',...]
:return: 'object3'
"""
return random.choi... |
import logging
from datetime import datetime
from data._version import current_version
now = datetime.now()
date = now.strftime("%y%m%d")
logging.basicConfig(
filename=f"search.log",
filemode="w",
level=logging.DEBUG,
format="%(asctime)s - %(message)s",
datefmt="%d-%b-%y %H:%M:%S",
)
# log and pr... |
import datetime
import gc
import lmdb
import logging
import math
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
import pprint
import subprocess
import struct
import sys
import tletools
import scipy
import scipy.interpolate
import scipy.signal
from .defs import *
from .util... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import maya.cmds as cmds
import cmt.rig.transformstack as ts
from cmt.test import TestCase
class TransformStackTests(TestCase):
def setUp(self):
self.leaf = cmds.createNode("transform", name="leaf... |
from bitflyer.api import BitflyerApi
from zaif.api import ZaifApi, CURRENCY_PAIR_BTC_JPY
bitflyer_api = BitflyerApi()
result = bitflyer_api.request_private_api('/v1/me/getbalance', 'GET')
print(result)
zaif_api = ZaifApi()
result = zaif_api.request_currency_pairs()
print(result)
result = zaif_api.request_latest_trad... |
savedStates = []
def SaveState(actionState):
# Find all states matching the given state that are already in the database
matchingStates = list(state for state in savedStates if state.boardState == actionState.boardState)
bestScore = actionState.score
if matchingStates:
# For each matching state
... |
import sys
import numpy as np
import cv2.cv2 as cv2
# Read the query image as query_img
# and train image This query image
# is what you need to find in train image
# Save it in the same directory
# with the name image.jpg
img1 = cv2.imread('match_results_2022.png')
img2 = cv2.imread('2022/frame2040.png')
# img2 = c... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
print(f"Adding {data} to the top of the stack")
# If there is no data, we add the value in the top element and return
if self.top == None:
self.top... |
import numpy as np
import math
import random
from lattice_mc.global_vars import rate_prefactor
class Transitions:
"""
Transitions class
Contains methods that operate on sets of Jumps.
"""
def __init__( self, jumps ):
"""
Initialise a Transitions object.
Args:
... |
# Basic training configuration file
from pathlib import Path
from torch.utils.data import ConcatDataset
from torchvision.transforms import RandomVerticalFlip, RandomHorizontalFlip
from torchvision.transforms import RandomResizedCrop
from torchvision.transforms import ToTensor, Normalize
from common.dataset import File... |
#!/usr/bin/env python3
import re
from setuptools import setup
# Get the version number from __init__.py
version = re.search(
'^__version__\s*=\s*"(.*)"',
open("phadd/phadd.py").read(),
re.M,
).group(1)
# Import pypandoc to convert the readme
try:
import pypandoc
long_description = pypandoc.... |
from .run_fuzzing import run
|
import argparse
import re
import chainer
from chainer import Link
import chainer.links.caffe.caffe_function as caffe
"""
Please download a weight from here.
http://www.robots.ox.ac.uk/%7Evgg/software/very_deep/caffe/VGG_ILSVRC_16_layers.caffemodel
"""
def rename(name):
m = re.match(r'conv(\d+)_(\d+)$', name)
... |
#!/usr/bin/env python
"""
Pandoc filter that replaces content that is within a "SOLUTION" comment.
"""
from pandocfilters import toJSONFilter
import re
ignoreSolution = False
def exercises(key, value, format, meta):
global ignoreSolution
p_begin = re.compile("<!-- BEGIN SOLUTION -->")
p_end = re.compil... |
"""
File: testqueue.py
Author: Ken Lambert
A tester program for queue implementations.
"""
from arrayqueue import ArrayQueue
from linkedqueue import LinkedQueue
def test(queueType):
# Test any implementation with same code
q = queueType()
print("Length:", len(q))
print("Empty:", q.isEmpty())
prin... |
"""
Validate BioC data structure
"""
from typing import Callable, List
from bioc.bioc import BioCDocument, BioCCollection
# pylint: disable=unused-argument
def _default_error(msg, traceback):
"""Default error handler that accepts two parameters: error message and traceback."""
raise ValueError(msg... |
import json
import logging
import os
import random
from flask import Flask, Response, request
from flask_cors import CORS
from flask.ext.cache import Cache
import db
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
cors = CORS(app)
cache = Cache(app, config={
'CACHE_TYPE': 'filesystem',
'CACHE... |
# -*- coding: utf-8 -*-
"""
(C) 2014-2019 Roman Sirokov and contributors
Licensed under BSD license
http://github.com/r0x0r/pywebview/
"""
import os
import sys
import logging
from threading import Event
import ctypes
from ctypes import windll
from uuid import uuid4
from platform import machine
import time
from webvi... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from scipy import sparse
import sys
import umap
import warnings
import networkx as nx
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
import pandas as pd
from scipy.stats import norm, zscore, poisson
from sklearn.preprocessing import normalize
wa... |
#TODO: REmove github icomns when not needed from cards
#TODO: Remove projects pages and articles pages
#TODO: Add project and articles heading
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_trich_components as ... |
import numpy as np
def filter_overlapping_intervals(to_be_filtered, filter_intervals, filter_coverage=0.6):
"""
Removes any interval in *to_be_filtered* which overlaps an interval in *filter_intervals* by a ratio of at least *filter_coverate*
:param to_be_filtered: An ndarray fo shape (n, 2) with time-sor... |
from io import StringIO
import numpy as np
import pandas as pd
import pytest
from lxml.etree import XMLSyntaxError # nosec
from typeddfs.df_errors import NoValueError
from typeddfs.untyped_dfs import UntypedDf
from . import Ind1NonStrict as Ind1
from . import Ind2Col2NonStrict as Ind2Col2
from . import Ind2NonStric... |
"""Datasource interface to the CIFAR dataset.
"""
# FIXME[new]: this is not yet implemented. This file holds just
# some code snippets from
# https://github.com/MINGUKKANG/Adversarial-AutoEncoder.git
# file: data_utils.py
#
# The new implementation may be based on ./mnist.py
# standard imports
import logging
import t... |
import time
from os import getenv
from requests.exceptions import ConnectionError
from pygeocoder import Geocoder
import pandas as pd
from pygeolib import GeocoderError
from sodapy import Socrata
# Unauthenticated client only works with public data sets. Note 'None'
# in place of application token, and no username or... |
import json
import time
import paho.mqtt.client as MQTT
import RPi.GPIO as GPIO
class MyMQTT:
def __init__(self, broker, port, notifier):
self.broker = broker
self.port = port
self.notifier = notifier
self._paho_mqtt = MQTT.Client("Actuator_controller_main", True)
self._pa... |
#!/usr/bin/env python
# A program for aligning CDSs of a orthogroup using multiprocess.
# USAGE: ./macse4cdsOrthofiles_TA.py
# Author(s): Taruna Aggarwal and Brian Moore
# Affiliation: University of New Hampshire, Durham, NH, USA
# Date: 01/27/2016
# Purpose is
import sys
import os
import subprocess
import argparse
fr... |
#!/usr/bin/env python
"""
oocgcm.stats.timestats
Define functions to perform timeseries analysis
"""
import xarray as xr
import numba
import numpy as np
def detrend(x, t=None, typ='linear'):
"""
Fit a linear or quadratic trend and remove it.
Parameters
----------
x : ndarray
Input timeseries
typ : {'linear'... |
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.colors import LogNorm
import numpy as np
from astropy.visualization import SqrtStretch
from astropy.visualization.mpl_normalize import ImageNormalize
def init_plotting(x=14,y=9):
plt.rcParams['figure.figsize'] = (x,y)
plt.... |
class BColors:
HEADER = '\033[95m'
OK_BLUE = '\033[94m'
OK_GREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
END_COLOR = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class PrintHelper(object):
@staticmethod
def switch(color):
mapped_colors = {
... |
'''
Write a Python program that matches a string that has an 'a' followed by anything, ending in 'b'.
'''
import re
def text_match(str):
match = re.search(r'^(a|\w*a)\w*b$', str)
if match:
print "string is:", match.group()
return True
else:
print "Match is not found"
return... |
#!/usr/bin/env python
#-*- coding: windows-1251 -*-
###############################################################################
#
# This module implements MongoDB request packet serialization.
#
# Pythomnic3k project
# (c) 2005-2014, Dmitry Dvoinikov <dmitry@targeted.org>
# Distributed under BSD license
#
#########... |
# -*- coding: utf-8 -*-
"""Imports for the path specification resolver."""
from dfvfs.resolver_helpers import fake_resolver_helper
from dfvfs.resolver_helpers import os_resolver_helper
|
from collections import Callable
from typing import Any, List
from dataclasses import dataclass
from transformers import PreTrainedTokenizer
from gpv2.image_featurizer.image_featurizer import ImageCollater
from gpv2.model.gpv_example import GPVExample
import numpy as np
@dataclass
class CollateWithTokenizer(Callabl... |
import os
import json
from six import iteritems
from . import constants
class PackageJsonWorkspaceError(RuntimeError):
pass
class PackageJson(object):
DEP_KEY = "dependencies"
DEV_DEP_KEY = "devDependencies"
PEER_DEP_KEY = "peerDependencies"
OPT_DEP_KEY = "optionalDependencies"
DEP_KEYS = ... |
from api.system import system
from api.transform import transform
import traceback
class updater_class:
__slots__ = ('list', 'remove_list')
def __init__(self):
self.list = []
self.remove_list = []
def register(self, o):
self.list.append(o)
return
def unregister(self, o... |
import requests
url = 'https://httpbin.org/ip'
proxies = {
"http": 'http://209.90.63.108:80',
"https": 'http://209.90.63.108:80'
}
response = requests.get(url)
print(response.json())
import requests
import socks
import socket
#s = socks.socksocket() # Same API as socket.socket in the standard lib
socks.set_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.