text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
# Created by: <NAME>
# Descript: A simple program that takes a list of nucleotide genbank accession numbers and
# downloads the 16S ribosomal RNA contained within the sequences linked to those
# accessions. Its then stores these 16S genes within a multi-sequence fasta file. The
# script also cr... |
import logging
from astropy.convolution import convolve as ap_convolve
from astropy.convolution import Box1DKernel, Gaussian1DKernel
from astroML.time_series import lomb_scargle, lomb_scargle_BIC, lomb_scargle_bootstrap
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import argrelextrema
def acf... |
'''search_tools: collection of useful tools for demonstrating search algorithms.
See: https://aroberge.gitbooks.io/reeborg-s-world-advanced-world-creation/content/searching/search.html
'''
from browser import window
class Deque:
'''Double-ended queue implemented for teaching purpose - not for efficiency.
... |
#!/usr/bin/env python3
import os
import sys
import json
from io import StringIO
from lxml import html
# max parties possible to select per results page
MAX_SELECT_PARTY = 8
# directory to save files
PROCESSING_DIR = 'online'
PARTY_FILE_SUFFIX = '_party.html'
RESULT_FILE_SUFFIX = '_result.html'
wom_newformat = [
... |
#!/usr/bin/env python
###############################################################################
#
# netnodedeltaflow2svg.py - convert traffic model net, node and two sets
# of flow data to SVG show flow differences
#
# File: nodenetdeltaflow2svg.py
# Author: <NAME>
# Created: March 2... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import json
from hashlib import sha256
from datetime import datetime
from OpenSSL import crypto
import base64
import requests
from time import sleep
import os
import logging
from kmtii_util import set_logger, debug_htt... |
from typing import Any, Dict, Optional
import graphene
from django.utils.text import slugify
from wagtail.core import blocks
from wagtail.embeds.blocks import EmbedBlock
from wagtail.images.blocks import ImageChooserBlock
from grapple.helpers import register_streamfield_block
from grapple.models import (
GraphQLB... |
"""
Count the kmers in a file and report entropy and eveness.
This version should run anywhere (stand alone - does not require roblib)
"""
import os
import sys
import argparse
import gzip
from math import log2
BLUE = '\033[94m'
GREEN = '\033[92m'
ENDC = '\033[0m'
RED = '\033[91m'
def rc(dna):
"""
Reverse co... |
import pexpect
import re
import sys
import types
import logging
import time
class BashShell(object):
def __init__(self,buffer_size=1024):
# FIXME: figure out how to deal with WINCH
self.logger = logging.getLogger(__name__)
self.logger.write = self._write
self.logger.flush = self.... |
# ---------- ADVANCED FUNCTIONS ----------
# ---------- FUNCTIONS AS OBJECTS ----------
def mult_by_2(num):
return num * 2
# A function can be
# 1. Assigned to another name
times_two = mult_by_2
print("4 * 2 =", times_two(4))
# 2. Passed into other functions
def do_math(func, num):
return func(num)
pri... |
import os
import re
import sys
import argparse
import pandas as pd
from tqdm import tqdm
# add previous and current path
sys.path.append('./')
sys.path.append('../')
sys.path.append('../../')
sys.path.append('../../../')
from utils.generic_utils import compute_wer, compute_cer
# portuguese char vocab
vocab_string_... |
import pandas as pd
import tensorflow as tf
import numpy as np
class GenericDataset(object):
"""Wrapper class for datasets"""
def __init__(self):
"""Initialize instance"""
class MNISTDataset(object):
"""Container class for MNIST datasets imported from CSV"""
def __init__(
self,... |
#!/usr/bin/env python
import os
import logging
from collections import Counter
import gffutils
from gffutils.create import logger
logger.setLevel(logging.INFO)
usage = """
Converts a GFF file downloaded from FlyBase into a GTF file suitable for
use with Cufflinks. Support for ignoring chromosomes, featurety... |
#!/usr/bin/env python3
"""
Finish a release, after it has been pushed to robotpkg:
- find the last release tag
- check devel & stable status
- update stable with the tag, then devel with stable
- push the tag, devel & stable
- get the distfiles in /tmp
- show the url for creating a release on gi... |
"""
MIT License
Copyright (c) 2021 AkshuAgarwal
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, merge, publish, ... |
import logging
from pprint import pprint
from sirbot import SirBot
from slack import methods
from slack.actions import Action
from pybot.endpoints.slack.utils.action_messages import *
from pybot.endpoints.slack.utils import COMMUNITY_CHANNEL, TICKET_CHANNEL
logger = logging.getLogger(__name__)
def create_endpoints... |
#!/usr/bin/env python3
#===============================================================================
# chipseqpeaks.py
#===============================================================================
"""Easy management of ChIP-seq peak calling data
A mini-module for managing ChIP-seq peak calling data. The languag... |
# file to load the data, tokenize and update labels accordingly
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from transformers import AutoTokenizer, ElectraTokenizer
import pickle
import argparse
import random
import copy
# https://huggingface.co/transformers/v3.2.0/custom_datasets.html
# htt... |
"""
Implementation of the Istio Details Microservice
"""
from __future__ import print_function
from flask_bootstrap import Bootstrap
from flask import Flask, request, jsonify, make_response
from urllib.parse import urlparse
import simplejson as json
import requests
import sys
import logging
import os
import asyncio... |
import argparse
import cv2
import os
import numpy as np
import imutils
import math
from scipy.spatial import distance as dist
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--edge-detector", type=str, required=True)
ap.add_argument("-i", "--image", type=str, required=True)
args = vars(ap.parse_args())
class Cr... |
'''
MIT License
Copyright (c) 2017 Grok
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, merge, publish, distribu... |
from __future__ import absolute_import
import tempfile
import os
from io import BytesIO
import tarfile
import logging
from threading import Timer
import requests
import maxminddb
from dxlbootstrap.app import Application
from dxlclient.service import ServiceRegistrationInfo
from .requesthandlers import *
# Configure l... |
"""
Base class for managing example datasets.
"""
# Authors: <NAME>
# License: BSD 3 Clause
import io
import os
import webbrowser
from os import environ, makedirs
from os.path import exists, expanduser, join
import zipfile
import requests
import pandas
from bs4 import BeautifulSoup
from ..io import open as ps_open
... |
from dataset_walker import DatasetWalker
import sys
import json
import argparse
slot_keys = [
("restaurant", "book", "people"),
("restaurant", "book", "day"),
("restaurant", "book", "time"),
("restaurant", "semi", "food"),
("restaurant", "semi", "pricerange"),
("restaurant", "semi", "name"),
... |
import logging
import logging.config
import shutil
import sys
from pathlib import Path
import requests
from PIL import Image, ImageDraw, ImageFont
def download_image(survey_url, star_ra, star_dec, logger, base_image):
"""Downloads the HiPS image.
This research made use of hips2fits,
(https://alasky.u-st... |
""" A simple manager for a task queue.
The manager handles creating, submitting, and managing
running jobs, and can even resubmit jobs that have failed.
author: <NAME>
since: 2015-08-27
"""
from .reporting import BaseReportingMixin, HtmlReportingMixin, TextReportingMixin
from .job_template import JobTemplate
class B... |
import os
import time
import base64
import json
from socketserver import ThreadingMixIn
import http.client
from kervi.spine import Spine
from kervi.core.authentication import Authorization
import kervi.utility.encryption as encryption
from kervi.utility import nethelper
from kervi.plugin.webserver import WebServerPlu... |
import glob
import re
import os
from ..test_classes.generic_test_class import FileOpener
import logging
class Decisions:
@classmethod
def get_all_decisions(cls, test_runner, lowercase: bool = True, return_paths: bool = False) -> list:
"""Parse all files in common/decisions and return the list with all... |
import logging
import numcodecs
import xarray as xr
def get_chunksizes(da, for_cdo=False, time_dim="time", chunks=None):
"""Get chunksizes for :py:class:`xarray.DataArray` for ``to_netcdf(encoding)`` from original file.
If ``for_cdo=True``, ensure ``time_dim`` ``chunksize`` of 1 when compressed."""
asser... |
from __future__ import annotations
from ._QueryParameters.QueryParameters import _QueryParameters
from ._QueryParameters.ExtractionRangeType import ExtractionRangeType
from .RelativeInterval import RelativeInterval
from Artesian._ClientsExecutor.RequestExecutor import _RequestExecutor
from Artesian._ClientsExecutor.Cli... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import torch
import torch.nn
from neuralcompression.functional import count_flops
from neuralcompression.models import ScaleH... |
import itertools
from util import read_input
def parse_data(data):
splitted = data.splitlines()
return splitted[0], splitted[1]
def is_horizontal(line):
p1, p2 = line
return p1[1] == p2[1]
def is_vertical(line):
p1, p2 = line
return p1[0] == p2[0]
def line_cross(l1, l2):
p11, p12 ... |
'''Implementation of the reduction expression.
This supports generic reduce operations such as
``sum``, ``argmin``, ``argmax``, ``min`` and ``max``.
'''
import numpy as np
import collections
from ..array import extent, distarray
from ..expr.local import make_var, LocalExpr, LocalReduceExpr, LocalInput, LocalCtx
from... |
from typing import Optional
from fastapi import FastAPI
import hashlib
import base64
import random
from pydantic import HttpUrl, BaseModel
from fastapi import FastAPI, Depends, Body, HTTPException
from fastapi.encoders import jsonable_encoder
from fastapi.responses import RedirectResponse, HTMLResponse, JSONResponse
im... |
import streamlit as st
from helper import fetch_db
from sqlalchemy import create_engine
import pandas as pd
import plotly.express as px
import datetime
import plotly.graph_objs as go
import warnings
DEFAULT_PLOTS = [
"nena_px",
"photons_mean",
"frame_std",
"n_locs",
"locs_frame",
"bg_mean",
... |
# -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, 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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
__all__ = [
"test_constant", "test_white", "test_dot_prod",
"test_exp", "test_exp_squared", "test_rbf", "test_matern32",
"test_matern52", "test_rational_quadratic",
"test_cosine", "test_exp... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2019/12/5 20:23
# @author : Mo
# @function: data utils of ml, text_summarization
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
import macropodus
import re
__all__ = ["extract_chinese",... |
import argparse
import importlib
import json
import numpy as np
import os
import shutil
environment_variable_name = 'PYSTIMPATH'
def list_stimuli():
stimuli = [
'test',
'square',
'euler',
'dg',
'fi',
'fi_comp',
'fi_merge',
'fipwc',
'fipwfc... |
from typing import List
import sys
import os
import logging
from cmake import CMAKE_BIN_DIR
from mltk import MLTK_ROOT_DIR
from .shell_cmd import run_shell_cmd
from .path import clean_directory, create_tempdir
from .system import get_current_os
from .logger import DummyLogger, make_filelike
from .python import as_list... |
"""
Custom formats used to return data in different formats.
These are used from the query itself when calling the fetch_as_format()
method.
For example, returning a LogQuery as a table::
query = LogQuery(fetch_size=200)
for log in query.fetch_batch(): # Default is TableFormat
print(log)
As CS... |
import os
import cv2
from colorama import Fore
from plugin import plugin
IMAGE_FORMATS = ['.jpg', '.png', '.jpeg', '.svg']
def valid_path(path):
"""Checks if a given path leads to a valid directory
Returns true if the path leads to valid dir, false otherwise
Parameters
----------
path: a pat... |
#!/usr/bin/python3
import pandas as pd
import requests
# import concurrent.futures
import os
from feature_extraction import Extractor
import csv
from queue import Queue
from alive_progress import alive_bar
#debug lib
import logging
import gc
import psutil
#some mtfk suggest using this cause simultane... |
import sys
import time
import curses
from .youtube import *
from time import sleep
from loguru import logger
from tools.lyrics import *
from ffpyplayer.player import MediaPlayer
def rewind_callback(player, start=False):
if start:
player.seek(0, relative=False)
else:
player.seek(-10.0)
def fo... |
# -*- coding: utf-8 -*-
"""
Channel Creator
===============
This class creates the several channels of the SPARC4. The AIS is based on the
Factory Method to implement the correct star flux calculation as a function of
the optical path of each channel. This package has as abstract class that will
be provided to the Po... |
import cv2
import os
from os import listdir
import xml.etree.ElementTree as parser
import numpy as np
import pprint
from time import time as timer
########################
# DRAW FUNCTIONS #
########################
def draw_line(image, points):
for i in range(0, len(points) - 1):
point = poin... |
from transformers import BertTokenizer, RobertaTokenizer
from keras.preprocessing.sequence import pad_sequences
import json
import pdb
from collections import Counter
import queue
from tqdm import tqdm
debug = False
class DatasetReader():
def __init__(self, max_len, BERT_name):
self.max_len = max_len
... |
import os
# Import the `pprint` function to print nested data:
from pprint import pprint
from dotenv import load_dotenv
import bson
import pymongo
def print_title(title, underline_char="="):
"""
Utility function to print a title with an underline.
"""
print() # Print a bl... |
import argparse
import datetime
import json
import requests
import configparser
def get_coordinates(website, apikey, location):
"""
Pobiera współrzędne na podstawie lokalizacji
:param website: endpoint API do pobrania koordynatów na podstawie parametru location
:param apikey: klucz do autoryzacji w se... |
import abc
import json
import math
import sys
from itertools import product
from typing import Dict, List, NamedTuple
import numpy as np
import yaml
from ml_intuition.enums import Dataset, Sample
class Params(NamedTuple):
"""
Parameters of noise injection.
pa - Fraction of noisy pixels, the number of a... |
from django.db import models
# Create your models here.
from ckeditor_uploader.fields import RichTextUploadingField
from django.utils.translation import ugettext_lazy as _
import json
import ast
class ListField(models.TextField):
__metaclass__ = models.SubfieldBase
description = "Stores a python list"
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import argparse
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.utils.data.distributed
from option import Option
from dcp.pruning import ResModelPrune
from torch import nn
from dcp.trainer import Trainer
from dcp.aux_checkpoint import AuxCheckPoint
from dcp.dataloader import *
from... |
import re
from typing import Optional, List, Union
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator
from google.cloud.bigquery.external_config import HivePartitioningOptions
from debussy_concert.core.motif.motif_base import PMotif
class TableReference:
"""
NOTE: might ... |
import os
import sys
import random
import time
import json
import subprocess
import hadoop_filestatus_utils
__author__ = "<NAME>"
__copyright__ = ""
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Prototype"
def util_count_lines(filenam... |
import re, cPickle
from disco.util import err, data_err, msg
def netstr_reader(fd, content_len, fname):
if content_len == None:
err("Content-length must be defined for netstr_reader")
def read_netstr(idx, data, tot):
ldata = len(data)
i = 0
lenstr = ""
if ldata - idx < ... |
###
#
# Lenovo Redfish examples - Set BMC vlan id
#
# Copyright Notice:
#
# Copyright 2018 Lenovo 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/li... |
import time
import sys
print('Welcome To fastrack USSD Banking Project...')
time.sleep(8)
bank_list="""
1. Access Bank
2. Fidelity Bank
3. Guarantee Trust Bank
4. Heritage Bank
5. Polaris Bank
6. Stanbic IBTC
7. Unity Bank
8. Wema Bank
"""
gen_bvn = " "
def BVN_checker( ):
global gen_bvn
... |
#!/usr/bin/env python
# This file is for preprocessing gcode and the new G29 Autobedleveling from Marlin
# It will analyse the first 2 Layer and return the maximum size for this part
# After this it will replace with g29_keyword = ';MarlinG29Script' with the new G29 LRFB
# the new file will be created in the same fold... |
"""Bundles common gui functions and classes
When creating a standalone app, you can use :func:`jukeboxcore.gui.main.init_gui` to
make sure there is a running QApplication. Usually the launcher will do that for you.
Then use set_main_style to apply the main_stylesheet to your app.
That way all the plugins have a consis... |
import os
import sys
import time
import re
class BasePlugin():
def __init__(self, src):
self.source = src
def lookup(self, token):
return None
class ReadOnlyTokenFile(BasePlugin):
# source is a token file with lines like
# token: host:port
# or a directory of such files
def... |
from discord.ext import commands
from aiohttp import ClientSession, ClientConnectorError
from core.embeds import *
import re
import json
import random
GET_KEYS = ["-H"]
POST_KEYS = ["-H", "-D"]
class Requests(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.session = None # Initialize ... |
import socket # for creating a socket
import re # for pattern matching ip address
import logging
import logging.handlers
import os
import sys
sys.path.append("..")
from anhost import anhost
from anhost import inputs
FORMAT = "[%(filename)s:%(lineno)s - %(threadName)s %(funcName)20s] %(levelname)10s %(message)s"
loggi... |
from neuwon.database.time import TimeSeries
from neuwon.examples.HH import make_model_with_hh
import matplotlib.pyplot as plt
import numpy as np
class Model:
def __init__(self,
time_step = 1e-3,
stagger = True,
# These parameters approximately match Figure 4.9 & 4.10 o... |
# Copyright 2018 Espressif Systems (Shanghai) PTE 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 ... |
#!/usr/bin/env python
"""The X12.map.SQL module emits SQL table definitions from an :mod:`X12.parse` structure.
These table definitions are minimized by flattening Segments into their
parent Loop structures.
See :ref:`traversal` for notes on the **Visitor** design pattern.
.. autoclass:: SQLDetailsVisitor
:memb... |
import errno
import os
import uuid
import shade
import dib2cloud.config
from dib2cloud import process
from dib2cloud import util
def gen_uuid():
return uuid.uuid4().hex
class Upload(process.ProcessTracker):
process_properties = [
'build_uuid',
'build_name',
'image_format',
... |
# Copyright (c) 2014-present PlatformIO <<EMAIL>>
#
# 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 ag... |
## Copyright 2020 UT-Battelle, LLC. See LICENSE.txt for more information.
###
# @author <NAME>, <NAME>, <NAME>, <NAME>
# <EMAIL>
#
# Modification:
# Baseline code
# Date: Apr, 2020
# **************************************************************************
###
import os
from multi_thread_r... |
from remediation_modules.logger import get_logs, log
from botocore.exceptions import ClientError
import json
import copy
publicURIs = ['http://acs.amazonaws.com/groups/global/AllUsers', 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers']
acl_permissions = {
'READ': [],
'WRITE': ['WRITE', 'FULL_CONTRO... |
import logging
import re
from datetime import date, datetime, time, timedelta
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.core import validators
from django.db import models, transaction
from django.db.models import F, Max, Sum
from django.urls import r... |
from typing import Any
from ampel.base.LogicalUnit import LogicalUnit
from ampel.secret.NamedSecret import NamedSecret
from ampel.dev.DevAmpelContext import DevAmpelContext
import pytest
from pydantic import create_model, ValidationError
from ampel.model.StrictModel import StrictModel
from ampel.secret.Secret import ... |
"""
MIT License
Copyright (c) 2019 RookiePC
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, merge, publish, dist... |
##################################################
# Import Own Assets
##################################################
from hyperparameter_hunter.library_helpers.keras_helper import parameterize_compiled_keras_model
##################################################
# Import Miscellaneous Assets
###################... |
# Copyright 2018 The Wallaroo Authors.
#
# 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 ... |
# -*- encoding: utf-8 -*-
"""
@File : /detectron2/projects/FlowNet/flownet/data/dataset_mapper.py
@Time : 2020-11-24 23:58:33
@Author : Facebook, Inc. and its affiliates.
@Last Modified: 2020-11-25 22:19:55
@Modified By : Chen-Jianhu (<EMAIL>)
@License : Copyright(C), USTC
@Desc : No... |
import os
import shutil
import subprocess
import sys
# import tempfile
# import importlib
import random
import string
import json
from functools import partial
from multiprocessing import Pipe, Pool, Process
from pathlib import Path
from tqdm import tqdm
import numpy as np
def read_file(filename):
""" return ... |
# coding= utf-8
# Copyright (c) 2014 Rackspace, 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 o... |
# -*- coding: utf-8 -*-
"""
Convergence test on bands of a given pseudopotential
"""
from aiida.common import AttributeDict
from aiida.engine import workfunction
from aiida import orm
from aiida_sssp_workflow.utils import update_dict, NONMETAL_ELEMENTS
from aiida_sssp_workflow.workflows.bands import BandsWorkChain
fro... |
import argparse
import datetime
import json
import elasticsearch
from elasticsearch import helpers
import hail as hl
HAIL_TYPE_TO_ES_TYPE_MAPPING = {
hl.tint: "integer",
hl.tint32: "integer",
hl.tint64: "long",
hl.tfloat: "double",
hl.tfloat32: "float",
hl.tfloat64: "double",
hl.tstr: "ke... |
import time
import serial
from modules import comm
from modules.anglePlaqueToAngleMoteur_c import getAngles_cffi
from modules.anglePlaqueToAngleMoteur_c.getAngles import getAngles
from kivy.app import App
from kivy.clock import Clock
from kivy.config import Config
from kivy.core.window import Window
from kivy.lang im... |
#!/usr/bin/env python
# Third-party
# import cython
import numpy as np
# Local
from .libfronts import abs2d
from .libfronts import clustering
from .libfronts import equpot
from .libfronts import filt2d
from .libfronts import grad
from .libfronts import norm2d
from .libfronts import pottemp
from .libfronts import scal... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 15:34:55 2020
@author: BTHRO
"""
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import os
from pathlib import Path
from datetime import date
class Parameters():
def __init__(self):
self.colour = 'grey' #options are gre... |
import datetime
import json
from django.shortcuts import render
from django.views.decorators.http import require_POST
from django.http import Http404, JsonResponse
from django.contrib.auth.decorators import login_required
from django.forms.models import model_to_dict
from common.models import Product
from contacts.mode... |
import math
'''
solid name
facet normal n1 n2 n3
outer loop
vertex p1x p1y p1z
vertex p2x p2y p2z
vertex p3x p3y p3z
endloop
endfacet
endsolid name
'''
def normalize(vec):
abs_vec = math.sqrt(sum(map(lambda x: pow(x, 2), vec)))
return map(lambda x : x/abs_vec, vec)
def rotateX(v, a):
x, y, ... |
# 文件功能:实现 GMM 算法
import numpy as np
from numpy import *
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from scipy.stats import multivariate_normal
plt.style.use('seaborn')
class GMM(object):
def __init__(self, n_clusters, max_iter=50):
self.n_clusters = n_clusters # 聚类个数
... |
"""Create the GUI to handle script execution.
The module also defines the way scripts are converted before being run."""
from PyQt5 import QtCore, QtWidgets
from PyQt5.uic import loadUiType
import sys, traceback, time, os, logging
#from .ui.SlaveWindow import Ui_MainWindow
from matplotlib.pyplot import draw
from datet... |
import csv
import cv2
import matplotlib.pyplot as plt
import numpy as np
import sklearn
from keras.callbacks import EarlyStopping
from keras.layers import Flatten, Dense, Conv2D, Cropping2D, Lambda
from keras.models import Sequential
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle... |
import datetime
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from aao.spiders.spider import Spider
from aao.spiders import sports
class SpiderWilliamhill(Spider):
bookmaker = 'williamhill'
... |
import discord
from discord.ext import commands
import tweepy
import datetime
import aiocron
from utils import database
from utils import discord as Discord
from config import api_keys, discord_channels
# Constants:
HOT_TRENDS_LIMIT_PERCENTAGE = 20
# Main
DiscordAPI = commands.Bot(command_prefix='$')
# Twitter au... |
##Application de matrices de convolution sur des images
import numpy as np
import random as rand
from PIL import Image
import os
from usuelles import * #Importe les fonctions usuelles
from scipy import signal
IDENTITE = (np.array([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]),... |
import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import time
import os
import distributed as dist
from datasets.block import BlockDataset, LatentBlockDataset
import numpy as np
from torchvision import transforms
import custom_datase... |
import dateutil
from app_server.config import *
from app_server.models import *
from websocket import create_connection
import dateutil.parser
db = SqliteDatabase(DATABASE)
def wsSend(message):
try:
ws = create_connection(WEBSOCKETS_URI, timeout=2)
ws.send(message)
ws.close()
except:
... |
from copy import deepcopy
from pathlib import Path
from tempfile import TemporaryDirectory
from pytest import fixture
from resotocore import core_config
from resotocore.core_config import (
parse_config,
CoreConfig,
ApiConfig,
DatabaseConfig,
RuntimeConfig,
config_model,
EditableConfig,
... |
import pandas as pd
import numpy as np
from os import listdir, mkdir
from os.path import isfile, join, isdir, split, dirname
import matplotlib.pyplot as plt
#Rename the headers for all the files
def Rename_Spectra_Labels (spectra_dir, header_file):
print("Working...one moment please")
header = pd.read_csv(header_fil... |
# SPDX-FileCopyrightText: 2021 Carnegie Mellon University
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import time
import cv2
import numpy as np
import rospy
from busedge_utils.msg import FeatureMsg, PreprocessedMsg
from cv_bridge import CvBridge, CvBridgeError
from feature_extractor import FeatExtractor
f... |
# Copyright 2021 NREL
# 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, software
# distri... |
# Copyright (c) 2022 CNES
#
# All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
Test partitioning by sequence.
==============================
"""
from typing import Dict, Iterator
import pickle
import dask.array.core
import numpy
import pytest
... |
import board
import time
import simpleio
import usb_hid
import math
import digitalio
import analogio
from struct import pack_into, unpack
import Pedals
def f(x):
return int(32760*math.sin(float(x)/1000.0))
pedals = Pedals.Pedals(usb_hid.devices)
def pedal_sim():
t = 0;
while True:
print("t=", t)
... |
import tensorflow as tf
import numpy as np
import pandas as pd
from PIL import Image
from PIL import ImageDraw
from os.path import isdir, abspath, join, isfile, exists
import os
from os.path import join, abspath, isdir, exists
from object_detection.utils import label_map_util
# TODO: rework this to match n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.