content stringlengths 5 1.05M |
|---|
import pathlib
from importlib.machinery import SourceFileLoader
import setuptools
version = SourceFileLoader('version', 'darq/version.py').load_module()
def readfile(filename: str) -> str:
return pathlib.Path(filename).read_text('utf-8').strip()
long_description = '\n\n'.join((
readfile('README.rst'),
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : __init__.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 01/27/2018
#
# This file is part of Jacinle.
# Distributed under terms of the MIT license.
from .batchnorm import *
|
"""
GeoReport v2 Server
-------------------
Open311 GeoReport v2 Server implementation written in Flask.
:copyright: (c) Miami-Dade County 2011
:author: Julian Bonilla (@julianbonilla)
:license: Apache License v2.0, see LICENSE for more details.
"""
from data import service_types, service_defi... |
# Copyright 2014 Huawei Technologies Co. Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
#!/usr/bin/env python
"""
QCKTest.py
==================
::
QCerenkovIntegralTest
ipython -i tests/QCKTest.py
Hmm largest c2 for different BetaInverse always at 7.6eV
just to left of rindex peak.
Possibly there is a one bin shifted issue, that is showing up
the most in the region where rindex is changing... |
#!/usr/local/autopkg/python
#
# Copyright 2020 Drew Coobs
# WARNING: This is an independent project and is not supported by CrowdStrike.
#
# 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
#
# ... |
"""
Copyright 2020 Robert MacGregor
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, d... |
# coding: utf-8
'''
Determine whether an integer is a palindrome. Do this without extra space.
'''
### 判断一个整数是不是一个回文整数,注意,负数不是回文整数
import math
def isPalindrome(x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
n = 0
## n代表x的位数
for i in range(0, 100):
if x ... |
from keras import backend as K
from keras.models import load_model
from yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes
from yad2k.models.keras_yolo import yolo_head
from app_utils import yolo_eval
from os import listdir
from os.path import isfile, join
import os
# Create a ... |
# Modified by Lijie
# Email:glee1018@buaa.edu.cn
# Date Modified: 2019-03-20 21:54
################################################################################
# MIT License
#
# Copyright (c) 2018 Tom Runia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and ass... |
from typing import List
from math import ceil
from numpy import linspace
from scipy.interpolate import splrep, splev
import torch
class Spline(torch.nn.Module):
def __init__(self, upsample_rate : int) -> None:
super(Spline, self).__init__()
self.upsample_rate = upsample_rate
def forward(self... |
import torch
from torch.autograd import Function
from .utils import eye_like
from warnings import warn
def householder_matrix(unit_vector):
# If unit_vector has shape (batch,m) or (m,), turn it into matrix shape
# (batch,m,1) respectively (m,1).
if unit_vector.shape[-1] != 1:
# Handle edge case if ... |
#!/usr/bin/env python3
import os
import sys
import unittest
from pathlib import Path
from typing import Optional
from unittest import TestCase, mock
from unittest.mock import patch
import zulip_bots.run
from zulip_bots.lib import extract_query_without_mention
class TestDefaultArguments(TestCase):
our_dir = os.p... |
#!/usr/bin/env python
# Copyright (c) 2022 Oxford Robotics Institute (ORI), University of Oxford
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import time
import weakref
from edr.edr_sensor import EDRSensor
# =================================... |
# Generated by Django 2.0.10 on 2019-04-08 19:28
from django.db import migrations
def fill_reporter_slug(apps, schema_editor):
Reporter = apps.get_model("capdb", "Reporter")
for reporter in Reporter.objects.all():
reporter.save()
class Migration(migrations.Migration):
dependencies = [
('... |
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from .menu import NewsItemMenu
class NewsAppHook(CMSApp):
app_name = 'cmsplugin_newsplus'
name = _('News App')
def get_urls(self, page=None, language=None, **kwargs):
... |
"""
Meraki SSIDs API Resource
"""
from .meraki_api_resource import MerakiAPIResource
from .l3_firewall_rules import L3FirewallRules
class SSIDs(MerakiAPIResource):
""" Meraki API Organization Admins resource. """
resource = "ssids"
parameters = [
"name"
, "enabled"
, "authMode"
... |
import os
import random
import albumentations as A
import cv2
import imgaug as ia
import numpy as np
from PIL import Image, ImageFilter
from skimage.filters import (rank, threshold_niblack, threshold_sauvola)
from skimage.morphology import disk
import pyblur
from background_generator import BackgroundGenerator
from ... |
"""Create a factory pattern using classmethods."""
class User:
def __init__(self, first_name: str, last_name: str):
self._first_name = first_name
self._last_name = last_name
def __str__(self) -> str:
return " ".join([self._first_name, self._last_name])
@property
def f... |
"""Common configuration parameters for test cases"""
URL = "nats://127.0.0.1:4222"
CREDENTIALS = ""
CLUSTER_ID = "py-msgp-cluster"
CLIENT_ID = "test-client"
TEST_TOPIC = "test-topic-name"
TEST_PAYLOAD = b"test payload..."
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://stackoverflow.com/a/24352388/5909792
import win32gui
import win32ui
from ctypes import windll
from PIL import Image
hwnd = win32gui.FindWindow(None, 'Telegram')
# Change the line below depending on whether you want the whole... |
import numpy as np
class Aggregator:
def __init__(self):
self.union_set = np.array([])
self.aggregated_non_embeddings = {}
self.aggregated_i_embeddings = {}
self.aggregated_item_freq = {}
self.aggregated_n_records = 0
def receive_item_set(self, item_set):
# ... |
'''
Experiment to create a simple lookup cache
Author: Dave Cuthbert
Copyright: 2016
License: MIT
'''
def func_fact(x):
"""
>>> func_fact(0)
0
>>> func_fact(1)
1
>>> func_fact(4)
24
>>> func_fact(10)
3628800
>>> func_fact(20)
2432902008176640000L
... |
from typing import List
from ...excepcions import MeteocatLocalError
from ...helpers.utils import formateja_valors_data, neteja_diccionari, genera_info
class Pirineu:
def pirineu_pics_prediccio(self, slug_pic:str, any:int, mes:int, dia:int) -> List[dict]:
"""
Retorna la predicció pel pic i el dia i... |
from __future__ import absolute_import, unicode_literals
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY2:
import collections as collections_abc # noqa
import ConfigParser as configparser # noqa
import Queue as queue # noqa
import thread # noqa
def fake_python3... |
#abc, bac, cab,, acb,bca, cba,
# Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a a permutation.
def main(s,l,r):
if l == r:
print(''.join(s))
else:
for i in range(l,r+1):
s[i],s[l] = s[l],s[i]
main(s,l+1,r)
... |
'''
Created on Aug 2, 2018
@:
'''
import json
MAX_WEIGHT_HEADER = "max_weight"
SAVE_MODIFIED_ACTIONS_FILE_HEADER = "save_modified_actions_file"
MATCH_NUM_SAMPLES_HEADER = "match_num_samples"
SMOOTHING_ADDER_HEADER = "smoothing_adder"
NUM_EXPECTATION_SAMPLES_HEADER = "num_expectation_samples"
NUM_PERMUTATIONS_HEADER ... |
expected_output = {
"interface": {
"GigabitEthernet1": {
"group": {
100: {
"advertise_interval_secs": 1.0,
"auth_text": "hash",
"description": "DC-LAN Subnet",
"master_advertisement_interval_secs": 1.... |
"""
===========================================================
Getting Started with ``TrajectoryGroup`` and ``Trajectory``
===========================================================
The basic PySPLIT workflow consists of cycling through ``TrajectoryGroup``
containers of ``Trajectory`` objects and acting on each ``Tr... |
import matplotlib
matplotlib.use('Agg', warn=False)
from nose.tools import assert_equal, assert_almost_equal
import numpy as np
from probfit import (describe, rename, Convolve, Normalized,
Extended, AddPdf, AddPdfNorm, BlindFunc)
from probfit.pdf import gaussian, ugaussian
from probfit._libstat imp... |
from django.apps import AppConfig
class QuoteConfig(AppConfig):
"""Django App Config for the Quote app."""
name = 'datahub.omis.quote'
label = 'omis-quote' # namespaced app. Use this e.g. when migrating
|
#Given a list of numbers of size n, where n is greater than 3,
# find the maximum and minimum of the list using less than 2 * (n - 1) comparisons.
#Here's a start:
#Analysis
#Exploit the property of N>3
#for first 3 element, we can do 3-4 comparison to find the max and min numbers:
# A compare to B.... if A is large... |
from Jumpscale import j
from .healthcheck import HealthCheckRun
descr = """
Clean up ssh deamons and tcp services from migration
"""
class SSHCleanup(HealthCheckRun):
def __init__(self, node, service):
resource = "/nodes/{}".format(node.node_id)
super().__init__("ssh-cleanup", "SSH Cleanup", "S... |
"""
Logic condition tests
"""
import pytest
from marshmallow import ValidationError
from py_abac.context import EvaluationContext
from py_abac.policy.conditions.logic import AllOf
from py_abac.policy.conditions.logic import AnyOf
from py_abac.policy.conditions.logic import Not
from py_abac.policy.conditions.numer... |
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
import unittest
from graph_notebook.network.gremlin.GremlinNetwork import parse_pattern_list_str
from graph_notebook.network.gremlin.GremlinNetwork import PathPattern
class TestPatternListParser(unittest.T... |
# -*- coding: utf-8
"""
@File : t_normaldatabased.py
@Author : Zitong Lu
@Contact : zitonglu1996@gmail.com
@License : MIT License
"""
import numpy as np
import unittest
from pyctrsa.ctsimilarity.normaldatabased import ctsimilarities_cal
class test_normaldatabased(unittest.TestCase):
def ... |
import pandas as pd
import quandl
import pandas_datareader as pdr # Use to import data from the web
import datetime # use for start and end dates
import matplotlib.pyplot as plt
def importExcel(object_list):
for x in object_list:
raw_data = pd.read_excel(x)
return raw_data
def makeStock(ticker, start, end):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import sys
import re
import urllib.parse
import logging
import logging.handlers
import os
import time
import codecs
import string
from bs4 import BeautifulSoup
import tldextract
try:
from os import scandir, walk
except ImportError:
from scandir impor... |
from peepdis.core import peep, Peeper, CallablePeeper
import numpy as np
class AttrClass:
def __init__(self, foo):
self.foo = foo
class MethodAnnotationsClass:
def method_annotations(self, a: int, b: int) -> int:
return a + b
if __name__ == '__main__':
obj = np.array([1, 2, 3])
pee... |
from tap_ebay.streams.base import BaseStream
import singer
LOGGER = singer.get_logger() # noqa
class OrdersStream(BaseStream):
API_METHOD = 'GET'
TABLE = 'orders'
KEY_PROPERTIES = ['orderId']
@property
def path(self):
return '/sell/fulfillment/v1/order'
def get_stream_data(self, r... |
import unittest
from aviatrix_poller import *
class Aviatrix_Poller_Test(unittest.TestCase):
def test_find_subnets(self):
region_id='us-east-1'
vpc_id='vpc-afdee5d7'
ec2=boto3.client('ec2',region_name=region_id)
result=find_subnets(ec2,region_id,vpc_id)
self.assertIs(type(result), list)
for ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Write stage settings here, or override base settings
"""
from __future__ import absolute_import, unicode_literals
import sentry_sdk
from sentry_sdk import configure_scope
from sentry_sdk.integrations.django import DjangoIntegration
from pipit.settings.base import * ... |
import configparser
from caller.config.parser import parse_literal, parse_string, parse_list, parse_benchmarks, parse_bool
class ConfigMicro(object):
def __init__(self):
"""
Sets the default values for the micro benchmarks
"""
# run
self.values = 5
self.process... |
import config
import models
import numpy as np
import json
#Train TransR based on pretrained TransE results.
#++++++++++++++TransE++++++++++++++++++++
con = config.Config()
#Input training files from benchmarks/FB15K/ folder.
con.set_in_path("./benchmarks/FB15K/")
#True: Input test files from the same folder.
con.set_... |
"""
test_database.py - Tests for ovirt_engine_setup/engine_common/database.py
"""
import sys
import ovirt_engine_setup.engine_common as common
import mock
import pytest
# mock imports
common.constants = mock.Mock()
mock_ovirt_setup_lib = mock.Mock()
mock_ovirt_setup_lib.hostname = mock.Mock()
mock_ovirt_setup_lib.d... |
import os
import re
def get_erase_char():
if os.name == 'posix':
pttrn = re.compile(r'; erase = (\^.);')
settings = os.popen('stty -a').read()
return pttrn.findall(settings)[0]
def repair_console(erase_char = '^H'):
if os.name == 'posix':
os.system('stty sane')
os.sys... |
from winning.std_calibration import centered_std_density
from winning.lattice_calibration import dividend_implied_ability
from winning.lattice_conventions import STD_UNIT, STD_SCALE, STD_L, STD_A
import numpy as np
# Illustrates the basic calibration
# Exactly the same but here we modify the discretization parameters
... |
"""Main module."""
import functools
import json
from typing import Any, Dict, List, Optional
import jsonschema
import toml
from toml_resume.constants import _DEFAULT, RESUME_JSON_SCHEMA
from toml_resume.encoder import neat_encoder
def read_resume_json(filename: str) -> Dict[str, Any]:
d = json.load(open(filena... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Leopold Schabel
# All rights reserved.
#
import sys, os
import thread
import time
import logging
import threading
from utils import s7comm
class CheckerThread(threading.Thread):
def __init__(self, plc, password, delay=60):
threadin... |
import os
import sys
import numpy
numpy.random.seed(42)
with open(os.path.join(sys.argv[1], "dev-other.lst"), "r") as f:
data = [line.strip() for line in f]
for n, seed_val in enumerate([0, 2, 3, 4, 5]):
numpy.random.seed(42 + seed_val)
data = numpy.random.permutation(data)
with open("tts_shuffle... |
import scrapy
from scrapy.http import HtmlResponse
from jobparser.items import JobparserItem
class SjruSpider(scrapy.Spider):
name = 'sjru'
allowed_domains = ['superjob.ru']
start_urls = ['https://www.superjob.ru/vacancy/search/?keywords=Python&geo%5Bt%5D%5B0%5D=4']
def parse(self, response: HtmlResp... |
import unittest
from rdflib import Graph, ConjunctiveGraph, Namespace, URIRef, Literal, BNode
class KG_ask(unittest.TestCase):
kg = None
@classmethod
def setUpClass(cls) -> None:
super().setUpClass()
# from https://github.com/RDFLib/rdflib/issues/1003
rdf_triples_base = """
... |
from __future__ import annotations
from contextlib import contextmanager
from .logger import Logger
from ..typing import StyleOptions
class LoggedMixin:
"""
A mixin class that adds common log methods and accessors for the logger
object to which those log methods delegate.
"""
_logger: Logger
... |
# Eh! python!, We are going to include isolatin characters here
# -*- coding: latin-1 -*-
import unittest
import os
import tempfile
import numpy
from tables import *
from tables.flavor import flavor_to_flavor
from tables.tests import common
from tables.tests.common import (
typecode, allequal, numeric_imported, ... |
#!/usr/bin/env python
#############################################################################
## drug_scafs_2sql.py
##
## Input smiles file SMILES<space>NAME.
##
## Jeremy Yang
## 18 Jan 2017
#############################################################################
import sys,os,getopt,re
PROG=os.path.basen... |
import os
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from colander import (
Boolean,
Integer,
Length,
MappingSchema,
OneOf,
SchemaNode,
SequenceSchema,
String
)
from deform import (
Form,
ValidationFailure,
widget
)
here = os.pa... |
from .novel import Novel
from .novel_url import NovelUrl
from .volume import Volume
from .chapter import Chapter
from .asset import Asset
from .asset_type import AssetType
from .metadata import MetaData
|
""" Functions for testing what kind of Python or Python environment is in use.
"""
def is_py3():
""" Test whether we are running Python 3.
Returns
True if we are running Python 3, otherwise False
"""
import sys
return sys.version_info[0] == 3
|
from flask_wtf import FlaskForm
from wtforms import SubmitField, TextField
from wtforms.validators import DataRequired
class SomeForm(FlaskForm):
input1 = TextField("Input 1", validators=[DataRequired()])
input2 = TextField("Input 2", validators=[DataRequired()])
submit = SubmitField("Submit")
|
import subprocess
import os
import time
import StringIO
import unittest
import tempfile
import shutil
import uuid
import pkg_resources
from pynailgun import NailgunException, NailgunConnection
POSSIBLE_NAILGUN_CODES_ON_NG_STOP = [
NailgunException.CONNECT_FAILED,
NailgunException.CONNECTION_BROKEN,
Nail... |
string = input("Enter the string :")
print(string [len(string)::-1])
|
import numpy as np
from vispy.gloo import VertexBuffer
from vispy.visuals import Visual
from vispy.visuals.shaders import Function
from vispy.color import ColorArray
vert = """
#version 120
uniform float u_antialias;
uniform float u_px_scale;
uniform float u_scale;
attribute vec3 a_position;
attribute vec4 a_color;
a... |
""" some image manipulation functions like scaling, rotating, etc...
"""
from __future__ import print_function, unicode_literals, absolute_import, division
import numpy as np
from gputools import map_coordinates
from scipy import ndimage
import pytest
def create_shape(shape=(100, 110, 120)):
d = np.zeros(shape,... |
from pathlib import Path
import click
from .. import plot
from .._profiling import Profiling
__all__ = ["plot_acc_eeplot"]
@click.command()
@click.argument(
"experiment",
type=click.Path(
exists=True, dir_okay=True, file_okay=False, readable=True, resolve_path=True
),
)
@click.argument("accessi... |
import json
import os
from pathlib import Path
import time
from typing import List
import pandas as pd
import requests
from dotenv import load_dotenv
from rich import print
from rich.progress import track
from tqdm import tqdm
# from top_github_scraper.utils import ScrapeGithubUrl, UserProfileGetter, isnotebook
import... |
from __future__ import absolute_import
from .base import (
BaseValidator,
)
from .common import (
validate_uint256,
)
from .inbound import (
validate_account as validate_inbound_account,
validate_block_hash as validate_inbound_block_hash,
validate_block_number as validate_inbound_block_number,
... |
import pygame
def main():
pygame.init()
size = [700, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Background images")
done = False
clock = pygame.time.Clock()
background_image = pygame.image.load("saturn_family1.jpg").convert()
player_image = pygame.image.load("player.png").convert(... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 16:14:42 2013
@author: proto
"""
#!/usr/bin/env python
from collections import OrderedDict
import time
import libsbml
import writer.bnglWriter as writer
from optparse import OptionParser
import atomizer.moleculeCreation as mc
import sys
from os import listdir
import r... |
# -*- coding: utf-8 -*-
# @File Name: ikAPI.py
# @File Path: M:\MAS2\PRM_Robotic_Arm\Klampt_Robotic_Arm_Script\ikMount\ikAPI.py
# @Author: Ruige_Lee
# @Date: 2019-04-24 19:15:24
# @Last Modified by: Ruige_Lee
# @Last Modified time: 2019-05-31 16:15:56
# @Email: 295054118@whut.edu.cn
# @page: https://whutddk.github.... |
from __future__ import division, print_function, absolute_import
|
import sys
BASE = 16777216 # 2**24
def random_n(n, base=BASE):
if n <= 0:
return 1
else:
return (161 * random_n(n-1) + 2457) % base
def main():
m = 100
even = 0
for n in range(m):
if n % 2 == 1:
result = random_n(n)
if result % 2 == 0:
... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Func, IntegerField, Sum
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from django.views.generic import TemplateView
from rest_framework.r... |
from rest_framework import serializers
from department.models import Department
class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Department
fields = (
'id',
'name',
'location',
'latitude',
'longitude'
)... |
from .connection import RexProSyncSocket, RexProSyncConnectionPool, RexProSyncConnection
|
import logging
import time
from typing import TYPE_CHECKING
import psutil
from monalyza.monitoring import scheduler
if TYPE_CHECKING:
from monalyza.monitoring.buffer import Buffer
class SingleProcessMonitoring:
"""Monitor a single process without its children."""
def __init__(self,
pid... |
import numpy as np
import cv2
import logging
def get_keypoints_from_indices(keypoints1, index_list1, keypoints2, index_list2):
"""Filters a list of keypoints based on the indices given"""
points1 = np.array([kp.pt for kp in keypoints1])[index_list1]
points2 = np.array([kp.pt for kp in keypoints2])[index_... |
import cv2 as cv
class Text:
def addText(self, path, content, fontScale=5, x=0, y=0, color=(255, 255, 255), thickness=1):
img = cv.imread(path)
font = cv.FONT_HERSHEY_SIMPLEX
img = cv.putText(img, content, (x, y), font, fontScale, color, thickness, cv.LINE_AA)
cv.imwrite(... |
from pylexibank.providers.qlc import QLC
def test_QLC():
assert QLC
|
from .loopedit import LoopeditPSAfile
from .derive import DerivePSAfile
from .psa_plot_file import PlotPSAfile
from .seasave import SeasavePSAfile
|
from django.urls import path
from .views import MyView
urlpatterns = [
path('', MyView.as_view(template_name='index.html'), name='index'),
]
|
'''
Demos for designing, developing and demonstrating Azure CLI.
'''
from .. pyaz_utils import _call_az
def style(theme=None):
'''
A demo showing supported text styles.
Optional Parameters:
- theme -- The theme to format styled text. If unspecified, the default theme is used.
'''
return _call_... |
from .base import BaseModule
class Chat(BaseModule):
def get_message(self, **kwargs):
"""
To get messages history for a specific conversation, which can display the messages detail from sender and receiver.
:param kwargs
- offset
- page_size
- conve... |
from math import sin, asin, sqrt, pi
def in_tree_pixel(baf, img_width):
# baf is the Basal Area factor
# tree_width is the app measured tree pixel width
theta = 2 * asin(sqrt(baf) / 100) # radians
min_tree_width = theta / (2*pi) * img_width # also use rad(360) = 2 pi
return min_tree_width
de... |
"""
The OptimizationManager submodule contains all the required function for
optimizing via dolfin-adjoint. To use dolfin-adjoin set::
general:
dolfin_adjoint: True
in the param.yaml file.
Todo:
* Read through an update the docstrings for these functions.
* Create specific optimization classes.
... |
import tensorflow as tf
import numpy as np
import subprocess
import json
import pandas as pd
from collections import OrderedDict
def scale_panda(panda, factor, bias):
if isinstance(panda, pd.Series):
filter = panda.index
if isinstance(panda, pd.DataFrame):
filter = panda.columns
panda = fac... |
import cartography.intel.aws.ec2
import tests.data.aws.ec2.key_pairs
TEST_ACCOUNT_ID = '000000000000'
TEST_REGION = 'us-east-1'
TEST_UPDATE_TAG = 123456789
def test_load_ec2_key_pairs(neo4j_session, *args):
data = tests.data.aws.ec2.key_pairs.DESCRIBE_KEY_PAIRS
cartography.intel.aws.ec2.load_ec2_key_pairs(
... |
__all__ = ["acquisition", "config", "exploration", "ncut", "ntds_utils",
"preprocessing", "utils", "subpackage"] |
#!/usr/bin/env python3
import math
import numpy as np
import tinyarray as ta
from sph_core import SPH_APP, Point, domain, mid_domain, norm
dx = 1.0
density0 = dx**(-len(domain))
stiffness = 1.0e2
viscosity = 1.0e0
nudge = 0.0
k = 7
gravitiy = 1.0e2
ca = math.sqrt(stiffness*k/density0)
print(ca)
class LiquidPoint... |
#!/usr/bin/env python
import sys
import numpy as np
argument_list_length = len(sys.argv)
if argument_list_length != 2 and argument_list_length != 4:
print " "
print " Program returns average FWHM of the stellar profile"
print " Usage:"
print " ./fwhm.py <input_data_file> [flux_min] [flux_max]"
print " "
... |
# Copyright (c) 2017 Cisco Systems, Inc.
# 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 applic... |
from yacs.config import CfgNode
def get_cfg() -> CfgNode:
from .default import _C
return _C.clone()
def update_config(cfg, args):
cfg.defrost()
cfg.merge_from_file(args.cfg)
cfg.merge_from_list(args.opts)
cfg.freeze()
return cfg |
"""
Some utilities.
"""
from __future__ import unicode_literals
import array
import fcntl
import os
import termios
__all__ = (
'pty_make_controlling_tty',
'set_terminal_size',
'nonblocking',
)
def pty_make_controlling_tty(tty_fd):
"""
This makes the pseudo-terminal the controlling tty. This shoul... |
"""user_fuel_database.py
Create your own fuel database
"""
from pyrolib.fuelmap import FuelDatabase, FuelMap, BalbiFuel
# create fuel db
my_db = FuelDatabase()
# create fuel corresponding to your needs
short_grass_balbi = BalbiFuel(e=0.3)
tall_grass_balbi = BalbiFuel(e=0.3)
# add fuels to the database
## the key Ba... |
"""
Get a raw dataset with gps coordinates and push dump it into a dictionnary with format:
dict(
column_name -> dict(
code -> value
)
)
Each of these dictionnary must have a 'lat' and a 'lon' column (latitude, longitude).
So, if you want to check the coordinates of the city with postal code 75014, you... |
import os
import shutil
from platform import system
from urllib.request import urlretrieve
from zipfile import ZipFile
class OCSIUpdater:
def __init__(self):
self.data = []
self.local = []
self.zip = "https://github.com/KernelWanderers/OCSysInfo/archive/main.zip"
self.delim = "\\" ... |
def find_minimum_number_of_moves(rows, cols, start_row, start_col, end_row, end_col):
# row_low = start_row if start_row < end_row else end_row
# row_high = start_row if start_row > end_row else end_row
# col_low = start_col if start_col < end_col else end_col
# col_high = start_col if start_col > end_c... |
# Module: eapenum.py
# Description: Enumerates insecure Extensible Authentication Protocol (EAP) user identities.
# The Eapenum module will perform a deauthentication attack against a single access point/BSSID,
# while client probes attempt to reconnect Eapenum will sniff for insecure EAP user identities.
# Author(s): ... |
import pytest
import json
import os.path
from fixture.application import MyApplication
import clr
clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
from Microsoft.Office.Interop import Excel
fixture = None
target = None
def load_config(c_fil... |
def SoSoSplotchy(n):
if n==0:
return 1
elif n==1:
return 2
else:
return 2 * SoSoSplotchy(n-1) + SoSoSplotchy(n-2)
def main():
print (SoSoSplotchy(5))
main()
|
import splunklib.client as client
class ServerSettings(client.Entity):
def __init__(self, service, **kwargs):
client.Entity.__init__(self, service, 'server/settings', **kwargs)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.