content stringlengths 5 1.05M |
|---|
"""Arnie Menu Maker Script
Jonathan Hanson
A quick-n-dirty way to place the menu into our postgres database.
Be careful! When you change the menu you may break the relations between
the menu and the orders tables!
"""
import psycopg2
import toml
import sys
SQL_CREATE_MENU_TABLE = """
CREATE TABLE IF NOT EXISTS menu ... |
from discord.ext import commands
import discord
from lyricsgenius import Genius
color = 0x00FF7F
genius = Genius("YOUR API KEY HERE")
@commands.command()
async def lyrics(ctx,*args):
songName = " ".join(args)
try:
result = genius.search_song(songName).lyrics
excep... |
# ------------------------------------------------------------------------------------------
# Copyright (c) Natsuneko. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root for license information.
# ------------------------------------------------------------------------------------... |
import pandas as pd
s_org = pd.Series(['aaa@xxx.com', 'bbb@yyy.com', 'ccc@zzz.com', 'ddd'], index=['A', 'B', 'C', 'D'])
print(s_org)
# A aaa@xxx.com
# B bbb@yyy.com
# C ccc@zzz.com
# D ddd
# dtype: object
df = s_org.str.extract('(.+)@(.+)\.(.+)', expand=True)
print(df)
# 0 1 2
# A aaa ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class GlobalContext(nn.Module):
"""
GlobalContext, inspired by 'SE' and 'GC'.
"""
def __init__(self, in_channels, channel_reduction=4, pooling_mode='attn', fusion_mode='add'):
super(GlobalContext, self).__init__()
... |
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def similarity_between_docs(doc1, doc2, is_1d=False):
if is_1d:
v1 = np.reshape(doc1, (1, -1))
v2 = np.reshape(doc2, (1, -1))
else:
d1 = np.mean(doc1... |
import cv2
import PIL
from PIL import Image
import numpy as np
img_list = []
cv_img_list = []
cv_img_merge_h_list = []
cv_img_merge_h_list_top = []
cv_img_merge_h_list_bottom = []
cv_img_panorama_list = []
cv_img_output_panorama = []
cv_y_zero_list = []
cv_y_two_list = []
panorama = "panorama_"
... |
import os, sys
import multiprocessing as mp
import subprocess
import numpy as np
import pandas as pd
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from lq_utils import write_fastq, open_seq_chunk, guess_format
from lq_exec import LqExec
from time import sleep
from logging import getLog... |
# -----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -----------------------------------------------------------------... |
#!/usr/bin/python3
import sys
def evaluate_postfix(postfix):
"""
Evaluates a postfix expression. Precondition: postfix is a valid postfix expression (no extra numbers, extra operators, etc.)
:param postfix: Postfix expression to be evaluated
:return: Result of the postfix expression, or error if unsup... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('login', '0002_auto_20160522_0301'),
]... |
from __future__ import division
import logging
import math
import numpy as np
import scipy.ndimage
from gunpowder import BatchFilter, Roi, ArrayKey, Coordinate
logger = logging.getLogger(__name__)
def _spatial_roi(roi, spatial_dims):
return Roi(
roi.get_begin()[-spatial_dims:],
roi.get_shape()... |
from setuptools import setup
# see https://stackoverflow.com/questions/14399534/reference-requirements-txt-for-the-install-requires-kwarg-in-setuptools-setup-py
setup(name='fuzzymatcher',
version='0.0.5',
description='Fuzzy match two pandas dataframes based on one or more common fields',
url='https:/... |
"""
"""
import sys
import argparse
import os
import gzip
import pandas
import gtfparse
import shellinford
from Bio import SeqIO
parser = argparse.ArgumentParser(usage=__doc__)
parser.add_argument(
"input_paths",
nargs="+",
help="Fasta files to process")
parser.add_argument(
"--out-csv",
required... |
import os
import json
import paramtools
import pandas as pd
from .outputs import credit_plot, rate_plot, liability_plot
from .constants import MetaParameters
from .helpers import arp_ref
from bokeh.models import ColumnDataSource
from taxcrunch.cruncher import Cruncher, CruncherParams
from taxcrunch.multi_cruncher impor... |
from django.utils.translation import ugettext as _
from .modelform import ModelFormMixin
class ObjectsFormMixin(ModelFormMixin):
pluralize = True
link_attributes = {
'data-listaction': 'urlupdate',
}
menus = ['list_action']
def get_invalid_pks(self):
return len(self.request.GET.g... |
#!/usr/bin/env python
#
# query.py - The FileTreeQuery class
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
# Author: Michiel Cottaar <michiel.cottaar@.ndcn.ox.ac.uk>
#
"""This module contains the :class:`FileTreeQuery` class, which can be used to
search for files in a directory described by a :class:`.FileTree`. ... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
"""Unit test package for data_quality_framework."""
|
import matplotlib.pyplot as plt
from velocity_transformations import *
# --------------------------------------------------------
# ---------------- Constants -----------------------------
# --------------------------------------------------------
QUIVER_SCALE = 200.
QUIVER_WIDTH = 0.001
def plot_theoretical_motion(... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 02:02:15 2020
@author: Sujay J
"""
import pandas as pd
messages = pd.read_csv("spam Classifier\SMSSpamCollection",sep = '\t',names = ["labels","message"])
import nltk
import re #regular Expressions
from nltk.corpus import stopwords
from nltk.stem.porter import PorterS... |
"""
This tests various types of arguments to make sure they are properly copied
by the namespace. This includes objects with circular references which need to
be carefully copied by NamespaceAPIFunctionWrapper._copy().
"""
import namespace
def foo(testarg):
return testarg
def noop(*args, **kwargs):
pass
foo_... |
class HtmlParser:
"""
@param: content: content source code
@return: a list of links
"""
def parseUrls(self, content):
import re
links = re.findall(r'href\s*=\s*("|\')+([^"\'>\s]*)', content, re.I)
return [link[1] for link in links if len(link[1]) and not link[1].startswith('#... |
import random
import json
import os
import re
import socket
import sqlite3
import uuid
from dataclasses import dataclass
from datetime import datetime
from urllib.request import urlopen
from pathlib import Path
from speedtest import Speedtest
CURDIR = Path(__file__).parent
@dataclass
class Vendor(object):
'''Co... |
from main import scale, scale1
a = "abcd\nefgh\nijkl\nmnop"
r = "aabbccdd\naabbccdd\naabbccdd\neeffgghh\neeffgghh\neeffgghh\niijjkkll\niijjkkll\niijjkkll\nmmnnoopp\nmmnnoopp\nmmnnoopp"
def test1(benchmark):
assert benchmark(scale, a, 2, 3) == r
def test(benchmark):
assert benchmark(scale1, a, 2, 3) == r
#... |
class ConnectionError(Exception):
def __init__(self, response, content=None, message=None):
self.response = response
self.content = content
self.message = message
def __str__(self):
message = "Failed."
if hasattr(self.response, 'status_code'):
message += " R... |
import unittest
from cgi import FieldStorage, MiniFieldStorage
from roundup.cgi.templating import *
from test_actions import MockNull, true
class MockDatabase(MockNull):
def getclass(self, name):
return self.classes[name]
class TemplatingTestCase(unittest.TestCase):
def setUp(self):
self.form... |
# -*- coding: utf-8 -*-
# This work is licensed under the GNU Public License (GPL).
# To view a copy of this license, visit http://www.gnu.org/copyleft/gpl.html
# Written by Abdullah Diab (mpcabd)
# Email: mpcabd@gmail.com
# Website: http://mpcabd.xyz
# Ported and tweaked from Java to Python, from Better Arabic Resh... |
from utils import sync
def firestore(event, context):
"""Triggered by a change to a Firestore document.
Args:
event (dict): Event payload.
context (google.cloud.functions.Context): Metadata for the event.
"""
resource_string = context.resource
# print out the resource string that ... |
import mailbox
mbox = mailbox.Maildir('Example')
for message in mbox:
print(message['subject'])
|
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# 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, me... |
import pytest
from .test_utils import *
@pytest.fixture
def noop_fixture():
pass
@pytest.fixture
def rootdir():
return get_current_dir()
@pytest.fixture
def sqlalchemy_conn():
engine = get_sqlalchemy_mysql_engine()
conn = engine.connect()
conn.execute("use %s" % test_config["MySQLTestSchema"]... |
# -*- coding: utf-8 -*-
from rest_framework import mixins, viewsets
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK
from super_notifications.mode... |
# Copyright 2017, 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
from .once_per_worker import once_per_worker
__all__ = ["once_per_worker"]
|
from __future__ import absolute_import
import numpy as np
from .abundance import FractionalAbundance
import pdb
class CollRadEquilibrium(object):
def __init__(self, atomic_data):
self.atomic_data = atomic_data
self.ionisation_coeff = atomic_data.coeffs['ionisation'] # RateCoefficient objects
... |
import asyncio
from logging.config import dictConfig
import pytest
from fastapi import FastAPI
from httpx import AsyncClient
from starlette.middleware import Middleware
from asgi_correlation_id import correlation_id_filter
from asgi_correlation_id.log_filters import celery_tracing_id_filter
from asgi_correlation_id.m... |
from crispy_forms.layout import Field
from django import forms
from .models import Stock_ID
class SearchStockForm(forms.ModelForm):
class Meta:
model = Stock_ID
fields = ['stock_ticker']
|
"""
Django settings for ananas project.
#
Generated by 'django-admin startproject' using Django 3.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
#... |
#!/usr/bin/python
import math
import re
import numpy as np
import inkscapeMadeEasy.inkscapeMadeEasy_Base as inkBase
import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw
import inkscapeMadeEasy.inkscapeMadeEasy_Plot as inkPlot
def findMinMaxStep(data, step):
''' returns the limits of the data, such that the ... |
class Solution:
def canTransform(self, start, end):
"""
:type start: str
:type end: str
:rtype: bool
"""
s = [(ch, idx) for idx, ch in enumerate(start) if ch in ('L', 'R')]
e = [(ch, idx) for idx, ch in enumerate(end) if ch in ('L', 'R')]
return len(s)... |
from plpred.preprocessing import compute_aa_composition
from Bio import SeqIO
import pandas as pd
import argparse
import pickle
def run_model(file_path:str, model_path:str) -> pd.DataFrame:
"""
Run a membrane protein prediction on a FASTA file.
Parameters
----------
file_path:str
path to p... |
# 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, ... |
'''
vars and printing
'''
# this stores an int
my_int = 10
# this stores a float
my_float = 4.2
# this stores a string
my_string = "lalala"
'''
this is a multiline comment
yay!
large comment
also prints stuff below
'''
print my_int
print my_float
print my_string |
import numpy as np
import itertools
import pathfinder
import utils
import app
import buffering
import os
class DataGenerator(object):
def __init__(self, dataset, batch_size, img_ids, p_transform, data_prep_fun, label_prep_fun, rng,
random, infinite, full_batch, override_patch_size=None, version=1... |
import os
import unittest
from tempfile import TemporaryDirectory
from thread_files.retriever import LinksRetriever, BatchDownloader
from tests.useful import *
from thread_files.utilities import IgnoreFilter
# todo: Speed up some of the tests...
class BatchDownloaderInstantiateTestCase(unittest.TestCase):
# d... |
'''
All functions take as arguments
i) a p by l np.array of floats. They are the
coefficients of the BP as returned by the
integrator function of .make_solution
ii) the timestep h>0
iii) the sampling_rate >0. This is the spacing
between the points where the solutions are sampled
in order to plot the functions and perfo... |
import numpy as np
from tensorpack.dataflow import *
class ILSVRC12Files(RNGDataFlow):
"""
Same as :class:`ILSVRC12`, but produces filenames of the images instead of nparrays.
This could be useful when ``cv2.imread`` is a bottleneck and you want to
decode it in smarter ways (e.g. in parallel).
"""... |
import discord
from discord.ext import commands
from discord.ext.commands import Cog, command
from discord import Embed, Member
from lib.notes import fwrite_note, db_read_note, flist_notes, fdel_note, updateable_check, fupdate_note, edit_note_check
# from lib.db.db import fwrite_note, db_read_note, flist_notes, fdel_no... |
import os
import re
import sys
from setuptools import Extension
from setuptools import setup
if sys.platform == 'win32':
versions = [
var for var in os.environ
if var.startswith('VS') and var.endswith('COMNTOOLS')
]
vs = sorted(versions, key=lambda s: int(re.search(r'\d+', s).group()))[-1]... |
"""
To run the experiment:
$ python examples/demo_experiment/run.py examples/demo_experiment/params_experiment.yaml
To see more options:
$ python examples/demo_experiment/run.py
"""
from rlberry.experiment import experiment_generator
from rlberry.stats.multiple_stats import MultipleStats
mstats = MultipleStats()
... |
# -*- coding: utf-8 -*-
"""
File Name: hasGroupsSizeX
Author : jing
Date: 2020/3/27
https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/
卡牌分组
"""
class Solution:
def hasGroupsSizeX(self, deck) -> bool:
if deck is None or len(deck) == 0:
return F... |
"""
Initialize the TCKDB backend module
"""
|
from flask import Flask, render_template
# app = Flask(__name__)
# app.config.from_object('config.default.Config')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/depgraph')
def depgraph():
return "Unimplemented"
@app.route('/conll')
def conll():
return "Unimplemented"
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Sniff every types of files you want on your network interface and save it.
#
# 2015/10/10
# by Oros
#
# Setup :
# $ sudo apt-get install python-scapy dvi2ps
# http://secdev.org/projects/scapy/doc/usage.html
#
# Help :
# $ files_sniffer.py -h
#
# Default usage :
# Sniff every... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
"""
Posterior sampling for 2D-Gaussian Mixture Model using Mean-Field VI
"""
import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt
K = 2
# Generate data
X1 = np.random.multivariate_normal([-5, -5], np.diag([2, 0.5]), size=20)
X2 = np.random.multivariate_normal([18, 18], np.diag([0.7, 1]), size=... |
import cv2
import numpy as np
from utils.generate_priors import generate_priors
def main(image_size=320):
anchors = generate_priors()
print(anchors)
for anchor in anchors:
ymin, xmin, ymax, xmax = anchor
left = int(max(xmin, 0) * image_size)
top = int(max(ymin, 0) * image_size)
... |
# Generated by Django 2.1.2 on 2019-05-06 19:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20190502_1658'),
]
operations = [
migrations.RenameField(
model_name='paciente',
old_name='p... |
import datetime as dt
from functools import cached_property
from itertools import product
from typing import Dict, List, Sequence, Union
import pandas as pd
from dateutil.relativedelta import relativedelta
from singleton_decorator import singleton
from . import date_utils
from .config import get_db_interface
from .da... |
import json
from enum import Enum
from itertools import chain
from pathlib import Path
from typing import Any, Union, Callable
import yaml
from openapi_core.schema.specs.models import Spec
from typing_extensions import Protocol
class SpecFileTypes(tuple, Enum):
JSON = ("json",)
YAML = ("yaml", "yml")
def g... |
import numpy as np
def _bootstrap_replicate_1d(data, reducer):
bs_sample = np.random.choice(data, len(data))
return reducer(bs_sample)
def _draw_bs_reps(data,
reducer,
n_reps):
perm_reps = np.empty(n_reps)
for i in range(n_reps):
... |
#!/usr/bin/python3
import subprocess
import sys
def cleanUpChroot(chrootPath):
returnVal, listmountpoints = findmountpoints(chrootPath)
if not returnVal:
return False
sortmountpoints(listmountpoints)
print(listmountpoints)
if not unmountmountpoints(listmountpoints):
return False... |
# encoding: utf-8
from datetime import datetime, timedelta
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.timezone import now
from dateutil.tz import tzlocal
from core.utils import slugify
class Setup(object):
def __init__(self):
self._ordering =... |
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import AsyncIterator, Awaitable, Callable, Generic, List, Optional, TypeVar
T = TypeVar('T')
U = TypeVar('U')
V = TypeVar('V')
class Middleware(Generic[T, U]): # pylint: disable=unsubscriptable-object
async def __call... |
from sp_api.api import Reports
from sp_api.base import Marketplaces, Schedules, SellingApiBadRequestException, SellingApiServerException
def test_create_report():
res = Reports().create_report(
reportType='GET_MERCHANT_LISTINGS_ALL_DATA',
dataStartTime='2019-12-10T20:11:24.000Z',
marketpla... |
# -*- coding: utf-8 -*-
import json
import warnings
from typing import List
from requests import Response
from TM1py.Exceptions.Exceptions import TM1pyException
from TM1py.Objects.Dimension import Dimension
from TM1py.Services.HierarchyService import HierarchyService
from TM1py.Services.ObjectService import ObjectSer... |
from rest_framework import routers
from shipping.api.v1.viewsets import ContinentViewSet, CountryViewSet, ShipperViewSet, PackageViewSet, \
OnlineShipmentViewSet, PackageShipmentViewSet
router = routers.DefaultRouter()
router.register(r'continents', ContinentViewSet)
router.register(r'countries', CountryViewSet)
... |
import json
import frappe
from frappe import _
from frappe.utils import now_datetime
from erpnext.selling.doctype.customer import customer
from erpnext.regional.india.utils import PAN_NUMBER_FORMAT
custom_make_address = customer.make_address
gst_category_map = {
"Regular": "Registered Regular",
"Input Service... |
# misc python stuff
import os
import re
import configparser
from slackclient import SlackClient # slack messaging when model is finished training
import pathlib # detecting if file exists in a path
import pickle # saving and loading keras tokenizer
# graphics libraries
imp... |
import uuid
from datetime import datetime, timedelta
from django.db import models
from django.forms import ValidationError
from utils.icao import ICAO
# from account.models import User
# Create your models here.
def generate_uuid():
"""
generate a unique id using uuid whenever a new aircraft is created
... |
#!/usr/bin/env python
#######################################################################
#######################################################################
## Skeleton copied on March 25, 2020 from nf-core/atacseq
#######################################################################
#######################... |
#!/usr/bin/env python3
#python
import time
from os import mkdir, listdir
from os.path import isdir, isfile
from itertools import chain
from pickle import load
from random import choice
#external
import numpy as np
from scipy.optimize import least_squares, minimize, approx_fprime
from scipy.signal import hilbert
from ... |
# python3 steven
import cv2
import argparse
import numpy as np
# ----------------------------------------------
# usgae: python yolo_opencv.py -i dog.jpg -c yolov3.cfg -w ./darknet-master/yolov3.weights -cl yolov3.txt
# usgae: python yolo_opencv.py -i dog.jpg -c yolov3.cfg -w ./darknet-master/yolov3.weights -... |
"""
Copyright (c) 2019 Imperial College London.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
import torch.nn as nn
import common.mytorch as mytorch
from common.mytorch.fft import fft2, ifft2
from common.mytorch.mri import (
... |
from concurrent.futures import ThreadPoolExecutor, as_completed, TimeoutError, ProcessPoolExecutor
import time
import pymtg
# Docs: https://docs.python.org/3/library/concurrent.futures.html
class WorkParallelizer(object):
"""
TODO: proper document that
wp = WorkParallelizer()
for i in range(30):
... |
from datetime import date, datetime, timedelta
from xm_s_common.raw_sql import exec_sql
from .frequent import fix_dimension
def fix_data():
start_date = date(2020, 10, 15)
while start_date < date(2021, 4, 21):
if start_date == date(2020, 10, 15):
sql_query_base = "SELECT msg_value FROM xm... |
"""
A toy example of playing against random bot on Mocsár
Using env "mocsar" and 'human_mode'. It implies using random agent.
"""
import rlcard3
# Make environment and enable human mode
env = rlcard3.make(env_id='mocsar', config={'human_mode': True})
# Reset environment
state = env.reset()
while not env.is_over():
... |
#Task https://adventofcode.com/2020/day/9
Input="""35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576"""
def parseInput(i):
return([int(n) for n in i.split("\n")])
somearray = parseInput(Input)
def preambule(arr,size):
for idx,n in enumerate(arr):
if(... |
# Copyright 2014 SolidBuilds.com. All rights reserved #
# Authors: Ling Thio <ling.thio@gmail.com>
from datetime import datetime
from flask import current_app, flash
from flask import Blueprint, redirect, render_template
from flask import request, url_for
from flask_user import current_user, login_required, roles_acc... |
#!/usr/bin/env python
# coding: utf-8
# # important libraries
# In[1]:
import numpy as np
import pandas as pd
import os
import re
from matplotlib import pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import seaborn as sns
import pickle
# Nltk for tekenize and stopwords
import nltk
from nltk.cor... |
from contact import Contact
import unittest #model that helps in running the test
import pyperclip
class TestContact(unittest.TestCase):
'''
test class that defines test case
'''
def setUp(self):
'''
setup method to run before each test
'''
self.new_contact = Contact("James","Muriuki","070... |
from moabb.datasets import BNCI2014001, Cho2017, PhysionetMI
from moabb.paradigms import MotorImagery
import numpy as np
from numpy.random import RandomState
import pickle
import time
import torch
import os
import pandas as pd
import mne
from NeurIPS_2.util.support import (
expand_data_dim,generate_common_chan_te... |
import tensorflow as tf
import torch
from .resnet import ResNet
# _url_format = 'https://s3.us-west-1.wasabisys.com/resnest/torch/{}-{}.pth'
_url_format = 'https://github.com/zhanghang1989/ResNeSt/releases/download/weights_step1/{}-{}.pth'
_model_sha256 = {name: checksum for checksum, name in [
('528c19ca', 'res... |
from netapp.netapp_object import NetAppObject
class WaflSyncHandle(NetAppObject):
"""
Handle representing a specific wafl-sync operation on a
volume.
"""
_volume = None
@property
def volume(self):
"""
Volume name on which wafl-sync operation being performed.
"""... |
from random import randint
def reverseList(List):
for x in range(0, (len(List) - 1)//2):
try:
endSpot = len(List) - 1 - x
temp = List[x]
List[x] = List[endSpot]
List[endSpot] = temp
except IndexError:
continue
return List
... |
#coding:utf-8
def checkBST(root):
stack = []
prev = None
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if prev == None:
prev = root.data
else:
if root.data <= prev:
... |
import numpy as np
import networkx as nx
import warnings
import os
from networkx.algorithms.shortest_paths.weighted import dijkstra_path
from utils import *
_sim_info = {}
def push_to_sim_info(key, value):
global _sim_info
if key in _sim_info.keys():
warnings.warn("Key already exists! Replacing its c... |
# Copyright(c) Max Kolosov 2009 maxkolosov@inbox.ru
# http://vosolok2008.narod.ru
# BSD license
__version__ = "0.2"
__versionTime__ = "2013-01-22"
__author__ = "Max Kolosov <maxkolosov@inbox.ru>"
__doc__ = """
pybass_ape.py - is ctypes python module for
BASS_APE - extension to the BASS audio library
that enables the p... |
'''
A tasker on top of a SQL database.
'''
import logging
from securitybot.tasker.tasker import Task, Tasker, STATUS_LEVELS, Escalation
from securitybot.sql import SQLEngine
from typing import List
# Note: this order is provided to match the SQLTask constructor
GET_ALERTS = '''
SELECT alerts.hash,
title,
... |
import runchecks
import setup
import socket
import settings
import request_handler
import threading
print('Identifying IP!')
HOST = socket.gethostbyname(socket.gethostname())
print('Your IPv4, is ' + str(HOST))
ADDR = (HOST, settings.PORT)
print('Starting Server on {}:{}'.format(HOST, settings.PORT))
# starting TCP ... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 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 Apach... |
# Copyright (c) 2019 UAVCAN Consortium
# This software is distributed under the terms of the MIT License.
# Author: Pavel Kirienko <pavel@uavcan.org>
import os
import sys
import time
import gzip
import typing
import pickle
import base64
import pathlib
import logging
import itertools
import dataclasses
import pydsdl
i... |
class ke2600(object):
def off(instr,ch=1):
if ch==1:
instr.write("smua.source.output=smua.OUTPUT_OFF")
if ch==2:
instr.write("smub.source.output=smub.OUTPUT_OFF")
def on(instr,ch=1):
if ch==1:
instr.write("smua.source.output=smua.OUTPUT_ON")
... |
# TODO: Create variables
import tensorflow as tf
import matplotlib.pyplot as plt
tf.reset_default_graph()
input_data = tf.placeholder(dtype=tf.float32, shape=None)
output_data = tf.placeholder(dtype=tf.float32, shape=None)
slope = tf.Variable(0.5, dtype=tf.float32)
intercept = tf.Variable(0.1, dtype=tf.flo... |
from aetherling.modules.term_any_type import DefineTermAnyType
from magma import *
import fault
from aetherling.helpers.fault_helpers import compile_and_run
def test_term_empty():
term = DefineTermAnyType(Array[0, Array[8, Bit]])
tester = fault.Tester(term)
tester.circuit.valid_up = 1
if False:
... |
# -*- coding: utf-8 -*-
from ReadData import *
# =====================각 학과 타입 데이터를 저장하는 리스트=========================
sw_list = read_data("Computer.txt")
# test code
print(sw_list)
print(type(sw_list)) # class 'list'
print(sw_list[0])
print(type(sw_list[0])) # class 'list'
print(sw_list[0][0])
print(type(sw_list[0][... |
import numpy as np
from math import ceil
from scipy import sparse
from scipy.sparse import csr_matrix, kron
from scipy.sparse.linalg import lsqr as sparse_lsqr
from scipy.sparse.linalg import inv as sparse_inv
from scipy.signal import fftconvolve, correlate
from scipy.integrate import quad
from ..spline import (
... |
import sys
import os
import subprocess
import avalon.api
from reveries.plugins import PackageLoader
"""
Deprecated
"""
def open(filepath):
"""Open file with system default executable"""
if sys.platform.startswith('darwin'):
subprocess.call(('open', filepath))
elif os.name == 'nt':
os.s... |
from src.ConfigReader import ConfigReader
from src.DocumentationBuilderTemplate import DocumentationBuilderTemplate
from sys import argv
from pathlib import Path
def main(generateDefault=False):
if(generateDefault):
print("Generating default configuration...")
else:
cr = ConfigReader(str(argv[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.