text stringlengths 3.07k 12.6k |
|---|
# Copyright 2016 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 agreed to in wri... |
# coding: utf-8
import mimetypes
import os
import time
import json
import requests
from acmd.jcr.path import join
from acmd import OK, UNCHANGED, SERVER_ERROR
from acmd import log, error
from acmd.util.strings import remove_prefix
from acmd.assets.utils import status_ok, AssetException
""" https://author-lbrands-asse... |
#!/usr/bin/env python3
"""
Copyright (C) 2019-2021 by
The Salk Institute for Biological Studies and
Pittsburgh Supercomputing Center, Carnegie Mellon University
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
"""
import os
i... |
import numpy as np
from tqdm import tqdm, trange
import os
import random
import torch
from torch.utils.data import (
DataLoader, RandomSampler, SequentialSampler, TensorDataset)
from torch.utils.data.distributed import DistributedSampler
from torch import nn
from transformers import glue_compute_metrics as compute... |
import argparse
import json
import os
from datetime import datetime
from itertools import product
import jsbeautifier
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from CausalDiscuveryToolboxClone.Models.NCC import NCC
from utils.data_loader import load_split_data
from ut... |
#------------------------------------------------------------------------------
#
# Copyright (C) 2018 Cisco Systems, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ve... |
#!/usr/bin/env python
"""
Demultiplex FASTQ files using UMI-tools-compliant barcodes present
within the FASTQ headers and a sample sheet file.
Usage::
python -m riboviz.tools.demultiplex_fastq [-h]
-s SAMPLE_SHEET_FILE -1 READ1_FILE
[-2 [READ2_FILE]] [-m MISMATCHES] [-o [OUT_DIR]]
[-d [DEL... |
# MIT License
#
# Copyright (c) 2016 <NAME>
#
# 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, pub... |
# -*- coding: utf-8 -*-
"""
Copyright 2018 NAVER Corp.
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, pu... |
# @copyright Copyright (c) 2017, <NAME> (<EMAIL>)
#
# @license zlib license
#
# This file is licensed under the terms of the zlib license.
# See the LICENSE.md file in the root of this repository
# for complete details.
"""Class defining the state of a satellite."""
import yaml
import os
from rospace_lib import KepO... |
import os, os.path, sys
from lxml import etree
import copy
def replace_all(s, defs):
for d in defs:
s = s.replace(d, defs[d])
return s
# def process_code(xml, dstxml, defs):
# etree.SubElement(dstxml, 'Code').text = replace_all(xml.find('Code').text, defs)
#
# def process_runsql(xml, dstxml, defs... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from datetimewidget.widgets import DateTimeWidget
from django import forms
from django.forms.widgets import SelectMultiple
from django_summernote.widgets import SummernoteInplaceWidget
from ontask import is_legal_name
from ontask.forms im... |
from snovault import upgrade_step
from . import _get_biofeat_for_target as getbf4t
@upgrade_step('experiment_repliseq', '1', '2')
def experiment_repliseq_1_2(value, system):
if value['experiment_type'] == 'repliseq':
value['experiment_type'] = 'Repli-seq'
@upgrade_step('experiment_repliseq', '2', '3')
d... |
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Lab 5A - LIDAR Safety Stop
"""
########################################################################################
# Imports
########################################################################################
import sys
import cv2 as cv
impo... |
import csv
import logging
import os
from datetime import datetime, timezone
import attr
from dateutil.parser import parse as to_datetime
import django.db.models as models
from django.core.management.base import BaseCommand
from corehq.apps.accounting.models import Subscription
from corehq.apps.es.domains import Doma... |
from django.urls import reverse_lazy
from django.forms.models import modelform_factory
from django.apps import apps
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView
from django.views.generic.base import TemplateResponseMixin, View, Templat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by <NAME>.
MIT Licensed.
Contact at www.sinclair.bio
"""
# Built-in modules #
import os, tempfile, re
# Internal modules #
import autopaths
# Constants #
if os.name == "posix": sep = "/"
if os.name == "nt": sep = "\\"
# Delimiters #
delimiters = ('_', '... |
import mysql.connector
from datetime import datetime
import pymongo
import pytz
'''
This module queries the MySQL replication status
Updates the MongoDB collection with any value differences between each iteration
'''
def slaveStatus(
CURSOR: mysql.connector,
env: dict
) -> dict:
'''
P... |
# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""Unit tests for h/atom.py."""
import mock
from h.feeds import atom
from h.test import factories
def test_feed_id():
feed = atom.feed_from_annotations([], 'atom_url', mock.Mock())
assert feed['id'] == 'atom_url'
def test_feed_title():
feed = ... |
import os
import time
import random
import colorama
def clearScreen():
if os.name == 'nt':
_ = os.system('cls')
else:
_ = os.system('clear')
def assembleBoard(xsize: int, ysize: int) -> tuple:
""" Create the play board """
xsize = xsize if xsize <= 80 else 80
ysiz... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
import numpy as np
import math
from transformers import Wav2Vec2Model
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
# class Encoder(nn.Module):
# def __init__(... |
import sys
from datetime import datetime
from abc import ABC, abstractmethod
from typing import Dict
from dataclasses import dataclass
from email.utils import parseaddr
from domain import PaymentProvider, Donation, DonationType, Money
import csv
def isEmail(s):
return '@' in parseaddr(s)[1]
class FilteredRow(Ex... |
# %%
import numpy as np
import pandas as pd
import scipy as sp
import scipy.optimize
from scipy.optimize import leastsq
import git
# Find home directory for repo
repo = git.Repo("./", search_parent_directories=True)
homedir = repo.working_dir
# Import plotting features
import matplotlib.pyplot as plt
import matplot... |
import roslibpy
from django.core.management.base import BaseCommand, CommandError
from silviacontrol.models import ResponseModel
from silviacontrol.utils import debug_log
from silviacontrol.tasks import async_save_response, ros_set_settings
from django.conf import settings as django_settings
from datetime import dateti... |
# 遍历所有文件夹 获取文件中的可下载文件链接 下载到当前目录 并替换
import sys
import os
import re
import requests
from bs4 import BeautifulSoup
def deal(path):
# ipp = 0
for root, dirs, files in os.walk(path):
for name in files:
# print(os.path.join(root, name))
# for name in dirs:
# print(os... |
print(__file__)
from itertools import product
import pandas as pd
from databroker.assets.handlers import HandlerBase, Xspress3HDF5Handler, XS3_XRF_DATA_KEY
fc = 7.62939453125e-05
adc2counts = lambda x: ((int(x, 16) >> 8) - 0x40000) * fc \
if (int(x, 16) >> 8) > 0x1FFFF else (int(x, 16) >> 8)*fc
enc2counts =... |
#!/usr/bin/env python
# github_img_to_cloudinary.py at https://github.com/wilsonmar/git-utilities/master/github_img_to_cloudinary.py
# Based on migrate_to_cloudinary.py at https://gist.github.com/akshay-ranganath/b5e2d9b0c29ddfe676bdf9cd3713cf12
import cloudinary
import cloudinary.uploader
import cloudinary.api
impor... |
'''
Meshes for hamitonian Generator
'''
from numpy import *
from multithreading import mpido
from scipy.linalg import eigh,eigvalsh
from matplotlib.pyplot import *
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from utils import H2G
import pdb,time
__all__=['Emesh','Hmesh','Gmesh']
class Emesh(obje... |
#!/usr/bin/python
# encoding: utf-8
import random
from PIL import Image
import numpy as np
####################################################
import shapely.geometry as geometry
import dota_process
####################################################
def distort_image(im, hue, sat, val):
im = im.convert('HSV')
... |
""" Full assembly of the parts to form the complete network """
from .unet_parts import *
from torch import nn
import torch
from .res_net import resnet34, resnet18, resnet50, resnet101, resnet152
import torch.nn.functional as F
from torch.autograd import Variable
class SaveFeatures():
features = None
def _... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Controls tests."""
# pylint: disable=redefined-outer-name
import copy
import pytest
from lib import base, browsers, factory, url
from lib.constants import element, objects
from lib.entities import entity... |
import datetime
from typing import Union
import os
from sheets import Spreadsheet
from date_validation import ensure_valid_date, date_validate_args, split_into_year_month
import api
import files
JsonFormat = dict[str, dict[str, list[int]]]
class ScoreCompare:
"""Main class responsible for preparing score compa... |
"""
:mod:`drain`
============
Drain class used by :class:`arq.worker.BaseWorker` and reusable elsewhere.
"""
import asyncio
import logging
from typing import Optional, Set # noqa
from aioredis import Redis
from async_timeout import timeout
from arq.utils import gen_random
from .jobs import ArqError
__all__ = ['Dr... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 17:49:18 2020
@author: <NAME>
@title: Chaining functions
"""
import pandas as pd
def chain(indices, double_link=False, base_periods=None):
"""
Chain the indices using direct (fixed-base) chaining.
By default, chains the indices using the direct (fixed-ba... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
import importlib
import logging
import os
import sys
import typing
from typing import T... |
"""Defines a command message that evaluates and updates recipes"""
from __future__ import unicode_literals
import logging
from django.db import transaction
from django.utils.timezone import now
from job.messages.blocked_jobs import create_blocked_jobs_messages
from job.messages.pending_jobs import create_pending_job... |
import threading
from stockpyle._base import BaseStore
from stockpyle.exceptions import NonUniqueKeyError
try:
import sqlalchemy
__HAS_SQLALCHEMY = True
except ImportError:
__HAS_SQLALCHEMY = False
if __HAS_SQLALCHEMY:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmak... |
"""
This module contains helper classes to statically type-check source files using mypy.
It is written and inspired by:
https://github.com/typilus/typilus/blob/e2aec24d94f10e58b3542c04be7fcf5640a1762b/exp/type_check/tcmanager.py
MIT License
"""
from abc import ABC, abstractmethod
from os.path import dirname, basename... |
import numpy as np
from loguru import logger
import matplotlib.pyplot as plt
from pathlib import Path
import torch
from myterial import light_green_dark, indigo_light
from pyrnn._plot import clean_axes
import torch.utils.data as data
import sys
from rich.progress import track
import pandas as pd
from sklearn.preprocess... |
# Copyright (c) 2017-2018 CRS4
#
# 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, distribut... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import csv
import re
import shutil
import sys
import time
import traceback
from collections import defaultdict
from itertools import count
from functools import partial
import gouda
import gouda.util
from gouda.engines.options import engine... |
# Copyright 2020 Google LLC
#
# 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, ... |
import numpy as np
from skimage.filters import threshold_adaptive, sobel, threshold_otsu
from skimage.measure import label, regionprops
from skimage.morphology import (reconstruction, disk, watershed, opening, selem, remove_small_objects,
binary_dilation, binary_erosion, dilation)
from s... |
# -*- Mode: Python -*-
import re
import coro
import coro.read_stream
from protocol import http_file, header_set, latch
W = coro.write_stderr
class HTTP_Protocol_Error (Exception):
pass
class Bad_Response (HTTP_Protocol_Error):
pass
# viewed at its core, HTTP is a two-way exchange of messages,
# some of w... |
'''
THIS CODE PROVIDES PARAMETER K SENSIBILITY ANALYSIS. TO DO THAT, N=3 WAS CHOSEN, AND BETA IS KEPT FIXED USING THE FOLLOWING ASSUMPTIONS
B_i,j = B_j,i
B = null for non neighbours
'''
# Importing important libraries
from fenics import *
import numpy as np
import matplotlib.pyplot as plt
import ufl
from guccionemateri... |
# -*- coding: utf-8 -*-
"""
Imap BodyStructure Entity
~~~~~~~~~~~~~~~~
Imap BodyStructure Entity
:copyright: (c) 2017 WTFPL.
:license: WTFPL, see LICENSE for more details.
"""
from typing import Iterable, List
from ..utils import build_content_part, list_to_dict, decode_parameter_value, \
is_i... |
from abc import *
from mommoo.http import HttpURLConnection
from mommoo.file import CSVFileRepository
from patent.property import BasicPatentProperty
from threading import Lock
from bs4 import BeautifulSoup
# this class help that crawling web-page-content of url and building parsing-object powered by `BeautifulSoup`
#... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2019 <NAME> <<EMAIL>>
#
# 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
# ... |
from src.utilities.model_response import CustomResponse
from src.utilities.model_response import Status
from src.utilities.utils import FileOperation
from src.kafka_module.producer import Producer
from src.kafka_module.consumer import Consumer
from src.resources.response_gen import Response
#from src.resources.response... |
import serial
from datetime import datetime
import json
import socket
with open('input.json') as doc:
data = json.load(doc)
U_ID = int(data['u_id'], 16)
ser = serial.Serial('/dev/tty.usbserial-A601D97W')
HOST = "192.168.1.147"
PORT = 40030
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST... |
from typing import List, Optional, Tuple
import chess
from chess import PIECE_TYPES, Board, popcount, square_rank, Color, Board, Square, Piece, square_distance
from chess import KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN
from chess.pgn import ChildNode
from chess.engine import Score
from typing import Type, TypeVar
A = T... |
# coding: utf-8
"""
Base classes and helper functions of various types that are used with different parsers.
"""
# region imports
from bs4 import BeautifulSoup
from bs4.element import ResultSet, Tag
from glob import glob
from kwhelp.decorator import DecFuncEnum, RequireArgs, RuleCheckAllKw
from kwhelp import rules
fro... |
import numpy as np
def find_corners(img):
"""Find corners of a polygon.
Note: This function finds the corner pixels. To find the
inter-pixel spaces, +1 must be added to each right and
lower coordinate (and additional corners may be necessary).
Arguments:
img -- 2d binary image of (filled)... |
#!/usr/bin/env python3
# Plots quality score boxplot by base position for FASTQ before and after trimming.
import argparse
import gzip
import logging
from Bio import SeqIO
from collections import namedtuple
import matplotlib
# Must run before pyplot import.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
impo... |
"""
Views to handle Dataverse initial requests
"""
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.conf import settings
from gc_apps.geo_utils.msg_util import msg, msgt
from gc_apps.geo_utils.time_util import get_l... |
# -*- coding: utf-8 -*-
#############################################################
# Copyright (c) 2020-2021 <NAME> #
# #
# This software is open-source and is distributed under the #
# BSD 3-Clause "New" or "Revised" License #... |
# Core imports
from panda3d.core import Geom, GeomVertexFormat, GeomVertexData, GeomVertexWriter, GeomTristrips
import math
# helper function to make a vertical cylinder given center, radius, and height
def makePlane(cx, cy, cz, width, height, facing="left", color=[0.25, 0.25, 0.25],
texHScaling=1.0, te... |
import os
import sys, time, json
from app.util import Util
import asyncoss
import oss2
from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
class Lib:
# ENV = app.config.name
@classmethod
async def Request(cls, headers={
"User-Agent": "Mozilla/5.0 (Macin... |
'''
Prepare the hr500k corpus of annotated sentences to be used by spaCy
'''
import spacy, sys
from spacy.tokens import Doc, DocBin
from pathlib import Path
hr500k_path = '/data/resources/cro.lang.resources/hr500k.conll/hr500k.conll'
hr500k_trunc_path = '/data/resources/cro.lang.resources/hr500k.conll/hr500k.trunc.co... |
from inspect import getmembers
from inspect import isfunction
from inspect import signature
from itertools import product
from copy import deepcopy as COPY
from pandas import read_csv
from pandas import DataFrame as df
from itertools import combinations as combos
import numpy as np
import os
import sys
import math
impo... |
# %%
import sys
sys.path.insert(0,'..')
import time
import timeit
import numpy as np
import torch
import matplotlib.pyplot as plt
import cpab
from tqdm import tqdm
# %%
from numpy.linalg import cond
from scipy.linalg import orth, norm, pinv
def plot_basis_velocity(T, B=None):
if B is not None:
T.params.... |
"""Build a mesh of a Bridge deck."""
import math
from typing import List, NewType, Tuple
import numpy as np
from bridge_sim.model import Bridge
from bridge_sim.sim.model import (
BuildContext,
DeckNodes,
DeckShellNodes,
DeckShells,
Node,
)
from bridge_sim.util import assert_sorted, flatten, print... |
from pathlib import Path
from typing import Union, Iterable, Generator
import zipfile
import hashlib
import shutil
from typing import List
import os
def pad_empty_file(file_path: Union[str, Path]) -> None:
"""Adds space to an otherwise empty file for compatibility purposes
:param file_path: path to a potenti... |
import json
import math
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
import matplotlib.image as img
import matplotlib.gridspec as gridspec
import matplotlib.patches as patches
def isFloat(str_val):
try:
... |
import contextlib
from django.conf import settings
from django.db import transaction
from projectroles.plugins import get_backend_api
from variants.helpers import get_engine
from variants.forms import PATHO_SCORES_MAPPING
from variants.models import prioritize_genes, VariantScoresFactory
from .queries import CasePre... |
#!/usr/bin/env python
"""
Some simple tests for the promise_keeper module.
"""
from promise_keeper import Promise, PromiseKeeper
from time import sleep
from random import random
from unittest import TestCase
def slow_add(x, y):
sleep(random() * 1)
return x + y
def slow_div(x, y):
sleep(random() * 1)
... |
"""
Copyright 2011-2018 <NAME>
Simplekml is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope tha... |
from lark.tools.standalone import main as _main
from lark_action.lark_action_raw import Lark, Transformer, Token, Tree, Lark_StandAlone
from textwrap import indent
from io import StringIO
from wisepy2 import wise
import os
import re
import sys
def keep_only_space(s: str):
return re.sub(r"\S", " ", s)
def dump(... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import correlation
from .hd3_ops import *
from .dla_up import DLAEncoder as dlaup_encoder
from .vgg import VGGEncoder as vgg_encoder
from . import decoder as PreDecoder
BatchNorm = nn.BatchNorm2d
class Context(nn.Module):
def __init__(sel... |
# TODO: Add an appropriate license to your skill before publishing. See
# the LICENSE file for more information.
# Below is the list of outside modules you'll be using in your skill.
# They might be built-in to Python, from mycroft-core or from external
# libraries. If you use an external library, be sure to include... |
""" Abstract base classes for inheritance. """
import abc
import warnings
from matching.exceptions import PlayerExcludedWarning, PreferencesChangedWarning
class BasePlayer:
"""An abstract base class to represent a player within a matching game.
Parameters
----------
name : object
An identifi... |
#!/usr/bin/python2
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Lic... |
from django.http import request, HttpResponse
from django.urls import reverse_lazy
from django.shortcuts import get_object_or_404, redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView
from django.contrib.sites.shortcuts import get_current_site
from django.co... |
"""
This allows membership control of a group without a graphical user interface.
WARNING: As these routines run in administrative mode, no access control is used.
Care must be taken to generate reasonable metadata, specifically, concerning
who owns what. Non-sensical options are possible to create.
This code is not a... |
import os
import numpy as np
import pandas as pd
import pickle
import time
import math
class once_LC_veh_selector():
def __init__(self, csv_data_path= '/home/xy/trajectories-0805am-0820am.csv',
t_h=30, t_f=50, d_s=2, enc_size = 64, grid_size = (13,3)):
print('\n working on {} \n'.format(... |
#! /usr/bin/env python
import os
import numpy as np
from astropy.io import fits
from astropy import units as u
import sys
from nrm_analysis.fringefitting.LG_Model import NRM_Model
from nrm_analysis.misctools import utils
from nrm_analysis.misctools.utils import mas2rad, amisim2mirage
from nrm_analysis import nrm_cor... |
import logging
import os
import random
import time
from typing import Dict, List, Optional, Tuple, Union, Any, Callable
import urllib
import torch
from torchvision.datasets import MNIST
from torchvision import transforms as transform_lib
from torch.utils.data import DataLoader, Dataset, random_split
from fulmo.core im... |
import pytest
from conway.grid import Cell
from conway.grid.toroidal import Grid, ToroidalArray
from . import GameRulesTestMixin
T = Cell.ALIVE
F = Cell.DEAD
class TestToroidalArray:
def test_init_recursive(self):
t = ToroidalArray([[0, 0, 0], [0, 1, 1], [0, 0, 0]], recursive=True)
assert isin... |
from ..utils import rest
from ..utils.checks import check_datetime, check_date
from ..utils.resource import Resource
class Transaction(Resource):
"""# Transaction object
A Transaction is a transfer of funds between workspaces inside Stark Bank.
Transactions created by the user are only for internal transa... |
# -*- coding: utf-8 -*-
# created: 2021-06-23
# creator: <EMAIL>
import logging
import traceback
from functools import wraps
import werkzeug
from quart import jsonify, Quart, json, Blueprint
from quart import has_request_context, request
from quart.logging import default_handler
from werkzeug.exceptions import NotFou... |
#!/home/hangyu5/anaconda2/envs/py3dl/bin/python
import argparse
import argh
from time import time
from contextlib import contextmanager
import os
import random
import re
import sys
from collections import namedtuple
import logging
import daiquiri
daiquiri.setup(level=logging.DEBUG)
logger = daiquiri.getLogger(__name_... |
#!/usr/bin/python3
import cv2
import os
import numpy as np
from pathlib import Path
from typing import List
from mseg.utils.dir_utils import create_leading_fpath_dirs
def cv2_write_rgb(save_fpath: str, img_rgb: np.ndarray):
"""
Args:
- save_fpath
Returns:
- None
"""
img_file_type = Path(save_fpath).suff... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import warnings
import typing as tp
import numpy as np
from nevergrad.common.typetools import ArrayLike
from .core import... |
#!/usr/bin/env python3.4
import requests
from bs4 import BeautifulSoup as BS
import datetime
import io
import nntplib
import time
import urllib.parse
import base64
import random
class Article:
"""
an nntp article
"""
timeFormat = '%a, %d %b %Y %H:%M:%S +0000'
def __init__(self, j, board, site)... |
from hashlib import md5
def _has_enabled_constraints(model_or_instance):
"""
Since we're no longer doing any extra write to enforce uniqueness there's
not much point in not enforcing it, so we always keep it enabled
"""
return True
def _has_unique_constraints(model_or_instance):
"""
Retu... |
import numpy as np
import Cost_Functions as cf
'''
@param x data example
@param c cluster center
@param s standard deviation
'''
def gaussian(x, c, s):
return np.exp((-1 / (2*(s**2))) * (cf.euc_dist(x,c)**2))
'''
@param c the set of centers
@brief return a set of standard deviations for each cent... |
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, ne... |
import argparse
import csv
import re
import os, os.path
import sys
import time
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def calculate_pkt_len(pkt_size, link_rate_gbps):
if not link_rate_gbps:
return 0
return int(round(float((pkt_size+24)*8) / float(link... |
import discord
blank = '<:black:588903518912380939>'
red = '<:red:588903539926106112>'
yellow = '<:yellow:588903561149153280>'
height = 6
width = 7
class c4game:
def __init__(self):
self.currentPiece = red
self.cols = [[blank]*height for i in range(width)]
def place(self, col):
... |
import vgamepad as vg
import time
import random
from controller_handler import Controller_handler, Controller_joystick
from pynput import keyboard
from arduino import setup, update_motors, reset_motors, turn_off_motors
test_mode = True;
gamepad = None
x = 0
y = 0
left_x = 0
right_y = 0
listener = None
... |
## Copyright 2017 Knossos authors, see NOTICE file
##
## 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... |
import logging
from abc import ABCMeta, abstractmethod
from typing import Generic, List, Literal, Type, TypeVar
from azure.servicebus import ServiceBusMessage, ServiceBusReceivedMessage
from azure.servicebus.aio import ServiceBusClient, ServiceBusReceiver
from azure.servicebus.exceptions import ServiceBusError
from ... |
from datetime import datetime
import time
import pandas as pd
import typer
import subprocess
import numpy as np
import random
import os.path
import noise_mechanism as nm
DEFAULT_DATA_DIRECTORY = "./tests/data"
DEFAULT_NOISE_DATA_DIRECTORY = "./data/mob-dp"
DEFAULT_FIPS = "36" # New York
DEFAULT_ITERATIONS = 1000
D... |
import os, mmap
from datetime import datetime, timezone
import argparse
# `pip install python-dotenv requests python-dateutil` in order to use this script
from dotenv import load_dotenv
import requests
import dateutil.parser as dt
BLOCKLIST='namelist.txt'
def update_namelist():
# uses namelist from https://githu... |
from aiohttp import web
import asyncio
import re
from bs4 import BeautifulSoup
import json
import traceback
from aiohttp_helpers import create_session
from request_helpers import RequestInfo
from disqus_objects import User
from worksheet import WorksheetManager
from constants import API_KEY, DISQUS_ID_RE
aioapp = w... |
# Classes to directly interact with the MK HAL layer.
import PathScripts.PathLog as PathLog
import itertools
import machinetalk.protobuf.object_pb2 as OBJECT
import machinetalk.protobuf.types_pb2 as TYPES
import threading
import uuid
import zmq
from MKCommand import *
from MKError import *
from MKService import *
... |
#!/usr/bin/env python
# _*_ coding: utf-8_*_
#
# Copyright 2016 <EMAIL>
# <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... |
import pdb, re
import numpy as np
import matplotlib.pyplot as plt
from . import NodeBrush, DynamicShow, QuantumCircuit, Pin
GATE = NodeBrush('qc.basic')
WIDE = NodeBrush('qc.wide')
C = NodeBrush('qc.C')
NC = NodeBrush('qc.NC')
NOT = NodeBrush('qc.NOT', size='small')
END = NodeBrush('qc.end')
MEASURE = NodeBrush('qc.m... |
import os
import importlib
import pandas as pd
import re
def read_data_file(path, filename, csv_separator, column_title):
# Function to read the input data files.
# Parameters:
# path = path where the csv file is located [string].
# filename = name of csv file [string].
file_path = os.path.join(... |
"""
Olivia immunization functions.
Immunization analyzes in which packages it is better to invest to protect the network as a whole.
"""
import random
import networkx as nx
from itertools import product
from olivia.lib.graphs import removed, strong_articulation_points
from olivia.model import OliviaNetwork
from ol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.