content stringlengths 5 1.05M |
|---|
from __future__ import print_function
import re
from copy import deepcopy
from itertools import product
from builtins import map
from builtins import object
from builtins import range
from builtins import zip
class Cut(object):
def __init__(self, selection):
self.is_data = False
self.is_mc = Fal... |
'''
This tool will generate source insight 4 project file list
from build output file (*.dep),then we can import the
file list in the source insight 4 project.
'''
import os
import sys
import xml.etree.ElementTree as ET
from datetime import datetime
import re
# 1、Find .dep file
projectfilename = ''
sourcefile = ''
out... |
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
|
with_class = testing.expect.with_class
extract_text = testing.expect.extract_text
frontend.page(
"news",
expect={ "document_title": testing.expect.document_title(u"News"),
"content_title": testing.expect.paleyellow_title(0, u"News"),
"pageheader_links": testing.expect.pageheader_links... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-26 14:33
from __future__ import unicode_literals
from django.db import migrations, models
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('common', '0029_organizat... |
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2017 Jadson Bonfim Ribeiro <contato@jadsonbr.com.br>
#
import os
import subprocess
import re
import xml.etree.ElementTree as ET
FORMATS = (
'pdf',
'rtf',
'xls',
'xlsx',
'docx',
'odt',
'ods',
'pptx',
'csv',
'html'... |
#!/usr/bin/python3
import requests
import re
URL = "https://www.abuseipdb.com/sitemap?page="
ip_pattern = 'href="https://www.abuseipdb.com/check/(.+)"'
malicious = []
for ip in range(1,195):
r = requests.get(url=URL+str(ip)).text
if re.findall(pattern=ip_pattern, string=r):
malicious.append(re.... |
input_file = '../../../data/merged_base.data'
cf_train_f = '../../../data/cf_train.data'
with open(cf_train_f, 'w') as f:
pass
# User-Item dict
u_i_dict = {}
with open(input_file, 'r') as f_in:
for line in f_in:
ss = line.strip().split('\001')
# print(ss)
user_id, item_id, listen_len,... |
"""
Test szybkości dla rozdzielczości 600x600:
Odczyt, tworzenie i zapis zdjęć (z duplikatami czyli bez tego 'if is_new_data == True'):
Podczas 20 sekund udało się zapisać 455 zdjęć RGB albo 1200 zdjęć w grayscale 1 channel albo 546 zdjęć w grayscale
3 channels.
Tylko odczyt i tworzenie zdjęć, bez ich zapisywania:
Po... |
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from products_and_services_client.api.accounts_api import AccountsApi
from products_and_services_client.api.credit_cards_api import CreditCardsApi
from products_and_services_client.api.financings_api import FinancingsApi
from product... |
import sys
from mycroft import MycroftSkill, intent_file_handler
from Adafruit_IO import MQTTClient
ADAFRUIT_IO_KEY = 'aio_qKOt11nG7Bu0X9D1jEZLEg6VkEGE'
ADAFRUIT_IO_USERNAME = 'Kenzo16'
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
client.connect()
client.loop_background()
class Seconlambon(MycroftSkill... |
import os
import sys
from typing import Any, Callable, Dict, TextIO
from urllib.parse import urlparse
import click
import filelock
import structlog
from eth_utils import to_canonical_address, to_normalized_address
from web3 import HTTPProvider, Web3
from definitions import ROOT_DIR
import json
from eth_utils import en... |
"""
Functions to setup a real and sample database
"""
# General imports
from peewee import *
from datetime import datetime as DT
import logging
from passlib.handlers.pbkdf2 import pbkdf2_sha256
# Internal imports
from models import db
from models.models import *
# Function to generate the tables in database
def creat... |
"""
Comment Model
===========
Model for commenting on Practices and Lessons;
Always in a group under a user
"""
import logging
import os
import re
import config
import util
import mandrill
import searchable_properties as sndb
from .lesson import Lesson
from .model import Model
from .practice import Practice
from .t... |
from scipy.stats import uniform
import numpy as np
class mhmcmc:
def __init__(self,_func_prior_pdf, _func_prior_gen, _func_likelihood,_func_model_,
_func_kernel_gen, n_MC, dim,**kwargs):
self.n_MC = n_MC
self.dim = dim
self.x_MCMC = np.zeros (shape = (n_MC, dim))
... |
import unittest
from image_searcher.interfaces.image_loader import ImageLoader
class TestLoader(unittest.TestCase):
def setUp(self):
self.loader = ImageLoader(image_dir_path="./tests/test_data")
def test_loader(self):
images = self.loader.search_tree()
self.assertTrue(len(images) > 5... |
#!/usr/bin/env python
import sys
import os
import rospy
import time
import rospkg
import unittest
rospack = rospkg.RosPack()
mission_control_path = rospack.get_path('mission_control')
sys.path.append("%s/src" % mission_control_path)
import behaviour
from mission_control_utils_cache import Cache
from std_msgs.msg imp... |
"""Goal: Best set of guesses for the optimal attacker against a relaxed checker.
The best guesses are computed using greedy algorithm (and iterated greedy (TODO)
algoritm).
Returns: a file containing the list of guesses, and the guessing probability for
q=5,10,100,1000, q (user input)
"""
import json, os, sys, gc, r... |
# -*- coding: utf-8 -*-
import re
from shared_visualize import visualize_procedure,VISUALIZE
from collections import OrderedDict
from math import pi
MAKE_ANIM = True
included_re = re.compile("Included n([0-9]+) to route set ([0-9]+)")
rays_re = re.compile("Considering n([0-9]+) between rays (-?[0-9]+\.[0-9]+), (-?[... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Ryan L. Collins <rlcollins@g.harvard.edu>
# and the Talkowski Laboratory
# Distributed under terms of the MIT license.
"""
Count & weight CNVs overlapping genes
"""
import pybedtools as pbt
import numpy as np
import pandas as pd
from sklearn.linea... |
import syft
import torch
# interface
def test_sharing(workers):
bob, alice, james = (workers["bob"], workers["alice"], workers["james"])
plain_text = torch.tensor([3, 7, 11])
secret = plain_text.share(bob, alice, james, protocol="falcon")
assert isinstance(secret.child, syft.ReplicatedSharingTensor)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Counting Sheep
# https://code.google.com/codejam/contest/6254486/dashboard#s=p0
#===============================================================================
from __future__ import unicod... |
"""
Django settings for communicationsexample project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
... |
from collections import namedtuple
import os
from ergaleia.import_by_path import import_by_path
from ergaleia.load_from_path import load_lines_from_path
from ergaleia.to_args import to_args
from ergaleia.un_comment import un_comment
class _branch(dict):
def __lookup(self, name):
if name not in self:
... |
#!/usr/bin/python2
import os
import subprocess
import sys
import matplotlib as mpl
import numpy as np
try:
subprocess.check_output("env | grep DISPLAY", shell=True).decode('utf-8')
except:
mpl.use("Agg")
import matplotlib.pyplot as plt
#framealpha is only availabe for matplotlib version >= 1.2.0
oldversio... |
def write_new(first, last, id_num):
"""
Create a new entry in the storage text file.
:param first: the first name
:param last: the last name
:param id_num: id number
:return: None
"""
with open("database.txt", "a") as f:
f.write("{}, {}, {}\n".format(first, last, id_num))
def ... |
"""This module contains the general information for FirmwareConstraints ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class FirmwareConstraintsConsts:
pass
class FirmwareConstraints(ManagedObject):
"""This is Firmwa... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import HttpResponse, JsonResponse
from django.utils.translation import ugettext_lazy as _
import main.settings_environ as settings_environ
from main.settings_de... |
import os
import xml.etree.ElementTree as ET
from rogue_sky import darksky
DARKSKY_API_KEY = os.environ["DARKSKY_SECRET_KEY"]
def test_ping(backend_api_client):
response = backend_api_client.get("/api/health")
assert response.status_code == 200
assert response.get_json() == {"status": "ok"}
def test_g... |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .coons import *
from .tweening import *
__all__ = [name for name in dir() if not name.startswith('_')]
|
class Solution:
"""
@param A: A string
@param B: A string
@return: if string A contains all of the characters in B return true else return false
"""
def compareStrings(self, A, B):
A = list(A)
for b in B:
if b not in A:
return False
... |
import logging
from .particle import Particle
logger = logging.getLogger(__name__)
class ParticleSwarmOptimization(Particle):
def __init__(self):
super().__init__()
# augmented parameters
self.v = None
self.xl = None
# AIWPSO
self.pfit = 0.0 # fitness value of t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
# .---. .-----------
# / \ __ / ------
# / / \( )/ ----- (`-') _ _(`-') <-. (`-')_
# ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .->
# //// / // : : --- (,------... |
import configparser as cp
import os
config = cp.ConfigParser()
path = os.path.abspath(os.path.dirname(__file__)) + '/config.ini'
config.read(path) |
from starkware.crypto.signature.signature import pedersen_hash, private_to_stark_key, sign
from starkware.starknet.public.abi import get_selector_from_name
class Signer():
def __init__(self, private_key):
self.private_key = private_key
self.public_key = private_to_stark_key(private_key)
def s... |
"""
Main entrypoint for finetuning
It could be a function that wraps the huggingface Trainer and picks appropriate finetuning
parameters depending on the language
E.g.
from wav2vec_toolkit.finetune import finetune
finetune(base_model="facebook/wav2vec-xlsr", dataset="common_voice", language="fr", max_epochs=100)
""... |
from .df_utils import *
__version__ = "0.0.2"
author_name = "Anastasia Lysenko"
my_str = "This is my_str from __init__.py"
|
import logging
from greent.triplestore import TripleStore
from greent.util import LoggingUtil
import unittest
from pprint import pprint
logger = LoggingUtil.init_logging(__name__)
class MeSH(object):
def __init__(self, uri="http://id.nlm.nih.gov/mesh/sparql"):
self.triplestore = TripleStore (uri)
def ... |
from fabric.api import env
from fabric.api import run
from fabric.api import sudo
from flask import current_app
from multistack.log import LogStream
from multistack.constants import *
class Remote:
"""
A class to handle ssh communications with remote systems.
"""
def __init__(self, address, user, key... |
import os
from hashlib import md5
from time import time
import jwt
from flask import current_app as junior_app
from flask import flash, redirect, session, url_for
from flask_bcrypt import check_password_hash, generate_password_hash
from src.extensions import db
class User(db.Model): # noqa: WPS230
__tablename_... |
# This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
"""
Docker Compose Support
======================
Allows to spin up services configured via :code:`docker-compose.yml`.
"""
import requests
import subprocess
from testcontainers.core.waiting_utils import wait_container_is_ready
from testcontainers.core.exceptions import NoSuchPortExposed
class DockerCompose(object... |
#!/usr/bin/env python3
"""*.h5 を読んでONNXなどに変換するスクリプト。"""
import argparse
import os
import pathlib
import sys
import tensorflow as tf
try:
import pytoolkit as tk
except ImportError:
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent.parent))
import pytoolkit as tk
logger = tk.log.get(__n... |
import sys
sys.path.append("../../common")
import itertools
from env_indigo import *
def searchSim(bingo, q, minSim, maxSim, metric=None):
print(
"** searchSim({0}, {1}, {2}, {3}) **".format(
q.smiles(), minSim, maxSim, metric
)
)
result = bingo.searchSim(q, minSim, maxSim, m... |
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import utool as ut
import vtool as vt
import itertools as it
from six.moves import range, zip, map # NOQA
(print, rrr, profile) = ut.inject2(__name__)
# DEBUG_REQUERY = True
DEBUG_REQUERY = False
class FinalResult... |
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
from models import resnet18
from models import inception_v3
from models import vgg16_bn
import torch
def filter_state_dict(state_dict):
from collections import OrderedDict
if 'state_dict' in state_dict.keys():
... |
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... |
# Copyright (C) 2018-2021 Seoul National University
#
# 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... |
import pytest
import graphscope.nx as nx
@pytest.mark.usefixtures("graphscope_session")
class TestVoteRankCentrality:
@pytest.mark.skip(reason="not support list as attribute")
def test_voterank_centrality_1(self):
G = nx.Graph()
G.add_edges_from([(7, 8), (7, 5), (7, 9), (5, 0), (0, 1), (0, 2)... |
from enum import Enum
# This comes from crosswire.org "Standard OSIS Codes for Bible Editions"
# noinspection SpellCheckingInspection
from typing import Dict
class Version(Enum):
# Ancient Language Editions
STEPHANUS_GNT = "Steph"
LATIN_VULGATE = "Vul"
LATIN_ERASMUS = "Erasmus"
MASORETIC_TEXT = "... |
import cv2
import numpy as np
import random
image = cv2.imread('image.jpg')
image_rot = cv2.imread('image_rot.jpg')
gray= cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
gray_rot = cv2.cvtColor(image_rot,cv2.COLOR_BGR2GRAY)
surf = cv2.xfeatures2d.SURF_create()
kp, desc = surf.detectAndCompute(gray,None)
kp_rot, desc_rot = su... |
from errors import CustomListTypeException
from tests.customlist_tests.base.customlist_test_base import CustomListTestBase
class CustomListExtendTests(CustomListTestBase):
def test_customListExtend_whenNonEmptyAndExtendedNonEmpty_shouldExtendAndReturnList(self):
value = [5, 6, 7]
custom_list = se... |
"""
Legacy CASA uses a custom MS format while CNGI uses the standard
Zarr format. These functions allow conversion between
the two as well as directly from the telescope archival science data
model (ASDM) (future growth). Note that both the MS and Zarr formats
are directories, not single files.
This package has a de... |
import cv2
from pylot.perception.tracking.multi_object_tracker import MultiObjectTracker
class MultiObjectCV2Tracker(MultiObjectTracker):
def __init__(self, flags):
self._tracker = cv2.MultiTracker_create()
def reinitialize(self, frame, bboxes):
self._tracker = cv2.MultiTracker_create()
... |
# Copyright 2018 Google. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
from .widget import *
NSObject = ObjCClass('NSObject')
class TreeNode(object):
def __init__(self, *data):
self._impl = NSObject.alloc().init()
self._tree = None
self.data = data
self.children = []
class TreeDelegate_(object):
TreeDelegate = ObjCSubclass('NSOutlineView', 'Tree... |
# -*- coding: utf-8 -*-
import abc
class Fishing(object):
"""
钓鱼模板基类
"""
__metaclass__ = abc.ABCMeta
def finishing(self):
"""
钓鱼方法中,确定了要执行哪些操作才能钓鱼
"""
self.prepare_bait()
self.go_to_riverbank()
self.find_location()
print("start fishing")
... |
import os
import sys
import yaml
import json
from config import Config
from devita.sfo import sfo
class BackendClient:
def __init__(self, config):
self.config = config
# Returns an array of Title ID, Title pairs.
def get_games(self):
# May still be useful if more info on a game is needed... |
"""
"""
__all__ = [
'FlagField', 'BoolField'
]
import ctypes
from calpack.models.fields.Fields import Field
class FlagField(Field):
"""
A custom field for handling single bit 'flags'.
:param bool default_val: the default value of the field (default False)
"""
c_type = ctypes.c_uint8
de... |
from torchexpo import modules
from torchexpo import vision
from torchexpo import nlp
from torchexpo.version import __version__ |
/home/runner/.cache/pip/pool/ae/5b/5d/e981f613e78d042ef2f334c0f8f444f7d65d3d8ceb407effafc2e1c1a4 |
import os
from typing import Union, Any, Optional, Iterable, Dict, TYPE_CHECKING, Tuple, cast
if TYPE_CHECKING:
from pyfileconf.main import PipelineManager
from mixins.repr import ReprMixin
from pyfileconf.basemodels.config import ConfigBase
from pyfileconf.config.models.file import ActiveFunctionConfigFile
from... |
# Uso de paquete de las funcionalidades de Speech
import azure.cognitiveservices.speech as speechsdk
# Variables para tener acceso a la API
clave_suscripcion = "Aquí va la clave"
ubicacion = "Aquí la va región-ubicación"
# Acceso al recurso
speech_config = speechsdk.SpeechConfig(subscription=clave_suscripcion, region... |
import unittest
from interpreter import instructions
from interpreter.memory import Memory
from interpreter.registers import Registers
class TestLwl(unittest.TestCase):
# Lwl
# Test with different alignment
def test_lwl_0(self):
'''
Tests lwl instruction sets the left bits of the regis... |
from PIL import Image, ImageDraw, ImageFont
from PyQt5.QtWidgets import *
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap
import face_recognition
# Image for opening
nameImage = "C:\\Users\\Ni... |
# -*- coding: utf-8 -*-
import os, cv2
import numpy as np
import matplotlib.pyplot as plt
import pickle
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
tf.__version__
PATH = os.getcwd()
LOG_DIR = PATH + '/embedding-logs'
# metadata = os.path.join(LOG_DIR, 'metadata2.tsv')
# %%... |
############################################################################
#
# Copyright (c) 2001, 2002, 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
... |
import pika
import os
import asyncio
import concurrent.futures
import uuid
import time
from PikaBus import PikaBusSetup
from PikaBus import PikaErrorHandler
def GetDefaultConnectionParams():
credentials = pika.PlainCredentials('amqp', 'amqp')
host = 'localhost'
if os.getenv('RUNNING_IN_CONTAINER', 'false'... |
"""
Module for parsing exceptions
"""
import utils
# CLASSES =====================================================================
class CartographyParserException(Exception):
# Constructor -------------------------------------------------------------
def __init__(self, row: int, value: str, inv_type: str, p... |
"""This module contains the test cases for the middlewares of the ``scrapy_selenium`` package"""
from unittest.mock import patch
from contextlib import ExitStack
from scrapy import Request
from scrapy.crawler import Crawler
from scrapy_selenium.http import SeleniumRequest
from scrapy_selenium.middlewares import Sele... |
from __future__ import division
from pylab import *
import elution as el
import utils as ut
import orth
import collections
import scipy
def prot_counts(fs, min_count=2):
"""
Sum up all the spectral counts for all the proteins in a set of
fractionations.
Filtered s.t. any returned protein will have at... |
import csv
import numpy as np
from datetime import datetime
import matplotlib as mpl
import matplotlib.pyplot as plt
from numpy import genfromtxt
import csv
import numpy as np
from datetime import datetime
import matplotlib as mpl
from numpy import genfromtxt
times = []
accelerometer = []
aX = []
aY = []
aZ = []
... |
from django.shortcuts import render,redirect
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from .models import Project,Profile,Review,NewsLet... |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Restaurant20to50, obj[4]: Distance
# {"feature": "Education", "instances": 51, "metric_value": 0.9774, "depth": 1}
if obj[1]<=3:
# {"feature": "Occupation", "instances": 46, "metric_value": 0.9945, "depth": 2}
if obj[2]<=20:
... |
from setuptools import setup
setup(name="mstream",
version="0.2",
description="Instantly stream movies/ tv episodes you want to watch",
url="http://vaulstein.github.com",
author="Vaulstein Rodrigues",
author_email="vaulstein@gmail.com",
license='MIT',
packages=["mstream"],
scripts=["bin/mstrea... |
import datetime
from app import query_db
from app.ORM.Comment import get_all_comments_by_post
from app.ORM.User import get_user_by_id
class Post:
def __init__(self, user, content, image, creation_time=datetime.datetime.now(), id=0):
self.id = id # Never persisted
self.user = user
self.co... |
#!/usr/bin/env python
import libvirt
import socket
return_data = dict()
conn = libvirt.openReadOnly()
try:
domains = conn.listDomainsID()
return_data['kvm_vms'] = len(domains)
return_data['kvm_total_vcpus'] = conn.getCPUMap()[0]
return_data['kvm_scheduled_vcpus'] = 0
for domain in domains:
... |
from typing import Union, Tuple
from hwt.interfaces.agents.handshaked import HandshakedAgent
from hwt.interfaces.std import Handshaked, HandshakeSync, VectSignal
from hwt.synthesizer.param import Param
from hwtLib.handshaked.intfBiDirectional import HandshakedBiDirectionalAgent
from ipCorePackager.constants import DIR... |
#!/usr/bin/env python3
"""
Module to parse the vtr flow results.
"""
import sys
from pathlib import Path
import glob
from collections import OrderedDict, defaultdict
# pylint: disable=wrong-import-position
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import vtr
from vtr import paths
# pylint: enabl... |
from page_page import Page
from selenium.webdriver.common.by import By
class InternalPage(Page):
@property
def logout_button(self):
return self.driver.find_element_by_link_text("Log out")
@property
def is_this_page(self):
return self.is_element_visible((By.ID, "loginform"))
|
from rwp.environment import *
from rwp.sspade import *
from rwp.vis import *
from rwp.petool import *
logging.basicConfig(level=logging.DEBUG)
environment = Troposphere()
environment.ground_material = VeryDryGround()
environment.z_max = 300
max_range = 1000
#environment.knife_edges = [KnifeEdge(range=800, height=125)]... |
# -*- coding: utf-8 -*-
'''
Create an XDG function to get the config dir
'''
import os
def xdg_config_dir(config_dir=None):
'''
Check xdg locations for config files
'''
xdg_config = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
xdg_config_directory = os.path.join(xdg_config, 'salt'... |
# Copyright (C) 2020-2021 by Vd.
# This file is part of EnvReader, the modern environment variables processor.
# EnvReader is released under the MIT License (see LICENSE).
class EnvError(ValueError):
def __init__(self, field: str, msg: str):
self.__field = field
super().__init__(msg)
@propert... |
# Libraries
import numpy as np
import pickle
from skimage.color import rgb2gray
# Other python files
import constants as k
from evaluation_metrics import *
import experiments as exp
import dataset as ds
from NetworkTF import *
import GIST as cust_gist # You have to install FFTW and lear-gist first before you can impo... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 Amir Hadifar. 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 req... |
#!/usr/bin/env python3
# Author: Christopher Blöcker, Timotheus Kampik, Tobias Sundqvist, Marcus?
from __future__ import print_function
import logging
import numpy as np
import sys
import termios
from cflib import crazyflie, crtp
from controller import ControllerThread
from multiprocessing imp... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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... |
# Copyright (c) 2021 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... |
"""
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/7/trees/47/
题目:二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
@author Niefy
@date 2018-09-21
"""
# Definition for a bina... |
#!/usr/bin/env python3
#### PYTHON IMPORTS ################################################################################
#### PACKAGE IMPORTS ###############################################################################
from src.helpers import canonicalize
#### GLOBALS #######################################... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 11:25:29 2019
@author: aesher9o1
"""
import smtplib
import pandas as pd
database = pd.read_excel('test.xlsx')
for i, j in database.iterrows():
#email
TO = str(j[2])
SUBJECT = 'Welcome to IAESTE family'
TEXT = 'Dear '+ str(j["Name"])+'... |
# %% [markdown]
# # Notebook for converting the grocery upc spreadsheet into a database migration
# %%
import openpyxl
SPREADSHEET_FILEPATH = r'.\Grocery_UPC_Database.xlsx'
spreadsheet = openpyxl.load_workbook(SPREADSHEET_FILEPATH)
# %%
# %%
ws = spreadsheet.active
x = next(ws.iter_rows())
x
# %%
x[3].value
# %%
pickl... |
import pytest
import zproc
@pytest.fixture
def ctx():
return zproc.Context()
@pytest.fixture
def swarm(ctx):
return ctx.create_swarm()
def test_regular(swarm):
r1 = swarm.map(pow, range(10 ** 5), args=[10])
r2 = map(lambda x: pow(x, 10), range(10 ** 5))
assert r1 == list(r2)
def test_lazy(... |
# Простой класс модели для условной игры с главным циклом и событиями.
# Вещание на 8-Bit Tea Party.
import sys
import string
import random
class Event():
items = ["Small heal", "Small poison", "Medium heal", "Medium poison", "Large heal", "Large poison"]
chances = [45, 65, 35, 75, 20, 80]
points = [10, -8, 20, -2... |
import e2e_test_framework
class APIE2ETestUserGroup(e2e_test_framework.APIE2ETest):
uri = "/api/v1/user/group"
get_tests = [
{
"name": "Read groups"
}
]
post_tests = [
{
"name": "Check name requirement",
"status": 400,
"return": 5... |
"""The WebSocket Feed provides real-time market data updates for orders and
trades.
Find more here: `<https://docs.exchange.coinbase.com/#websocket-feed>`_
.. module:: websock
:synopsis: WebSocket Feed
.. moduleauthor:: Alexander Simeonov <agsimeon@buffalo.edu>
"""
from json import dumps, loads
from threadin... |
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
#
# (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved.
#
"""
DataPreparation
---------------
Machine learning relies on good dataset. DataPreparation prepare
the dataset before it is used for training a machine learning
... |
# Given n pairs of parentheses, write a function to generate
# all combinations of well-formed parentheses.
#
# For example, given n = 3, a solution set is:
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
class Solution:
def generateParenthesis(self, n):
res = []
de... |
from django.contrib import admin
from CryptoMessageApi.models import Message, Conversation, Device, User
# Register your models here.
admin.site.register(Device)
admin.site.register(Message)
admin.site.register(Conversation)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.