content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import json
import os
import re
import time
import requests
import js2py
from diskcache import Cache
from SFIWikiBotLib import Config
from SFIWikiBotLib import GeneralUtils
dataCache = Cache(directory=os.path.join(Config.cacheDir, 'cache.gameData'))
# Fou... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''
Master Game Gen
1.0b
'''
import os
import sys
import json
from OS_Helper import CleanDirectory, BuildPage, BuildBack
#TSSSF Migration TODO:
#automagickally create vassal module :D
#individual artist naming
#.pon files have symbols like {ALICORN} and so on.
def load... |
from django.core.exceptions import ValidationError
from django.test import TestCase
from .models import Block, Transaction
class TestViewAddTransaction(TestCase):
def setUp(self) -> None:
pass
def test_add_transaction_true_1(self):
data = {
"sender":"012345678901234567890123456789... |
from typing import List
from django.urls.converters import (
IntConverter,
StringConverter,
)
def path_schema(params) -> List:
"""Generate path params schema"""
items = []
try:
for name, type_ in params[3].items():
if isinstance(type_, IntConverter):
type_str =... |
""" Testing cpuid module
"""
from sys import platform as PLATFORM, path
from os.path import dirname
path.append(dirname(__file__))
from itertools import product
from x86cpu import info, cpuid
from x86cpu.cpuinfo import _bit_mask, _has_bit
import pytest
from info_getters import (Missing, get_sysctl_cpu, get_proc_cp... |
#!/usr/bin/env python
#from https://thepoorengineer.com/en/arduino-python-plot/
from threading import Thread
import serial
import time
import collections
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import struct
import copy
import pandas as pd
import numpy as np
class se... |
"""
Typing.
"""
from typing import Dict, Callable, Tuple, Any, Optional, Set, Generic, TypeVar, Union, List, T
|
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
"""Function implementation"""
import logging
from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError
PACKAGE_NAME = "fn_sdk_test"
class FunctionComponent(ResilientComponent):
... |
class Solution:
# O(n) time | O(n) space - where n is the number of nodes of BST
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
def dfs(root):
if not root: return None
if low <= root.val <= high:
self.ans += root.val
if ro... |
from flask_restful import Resource, reqparse
from models import db, ApiKeys
from requests import get
import datetime
import secrets
import config
from decorators import restricted_api, admin_api
import errors
import logging
logger = logging.getLogger("api")
class ApiKey(Resource):
@restricted_api
def get(self):... |
import numpy as np
from sklearn.cluster import FeatureAgglomeration
from sklearn.preprocessing import (
MaxAbsScaler,
MinMaxScaler,
Normalizer,
PolynomialFeatures,
RobustScaler,
StandardScaler,
Binarizer,
)
from sklearn.kernel_approximation import Nystroem, RBFSampler
from sklearn.decomposi... |
from libnmap.process import NmapProcess
from libnmap.parser import NmapParser, NmapParserException
from time import sleep
class DinoNmap:
def __init__(self):
pass
def do_scan(self, targets, options):
parsed = None
nmproc = NmapProcess(targets, options)
rc = nmproc.run()
... |
import base64
from abc import ABCMeta
from enum import Enum
from typing import Union
class Bytes(bytes):
size = None
prefix = None
def __new__(cls, *args, **kwargs):
self = super().__new__(cls, *args, **kwargs)
if cls.size is not None and cls.size != len(self):
raise RuntimeEr... |
from .omdb import get_omdb_movie
from .tmdb import get_tmdb_movie, get_tmdb_genre, get_tmdb_details
def get_api(title, year, external_api="omdb"):
item = {
"title": None,
"genre": None,
"imdb": None,
"runtime": None,
"tomato": None,
"year": None,
"awards": N... |
"""
Displays overview financial data (cash flow)
"""
import curses
from app.const import NC_COLOR_TAB, NC_COLOR_TAB_SEL
from app.methods import format_currency, ellipsis, alignr
from app.page import Page
class PageOverview(Page):
""" Page class to display overview data """
def __init__(self, win, api, set_st... |
#!/usr/bin/env python3
from pathlib import Path
import re
class Probe:
x = y = 0
def __init__(self, u, v):
self.u = u
self.v = v
def step(self):
self.x += self.u
self.y += self.v
self.u = max(0, self.u - 1)
self.v -= 1
class Target:
def __init__(sel... |
import sys
sys.path.append('..')
from exnet_v3 import *
from sklearn.metrics import average_precision_score
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices):
# The experiment will only take necessary memory on the GPU.
tf.config.experimental.set_memory_growth(phys... |
import shutil
import utils
import sys
import os
import random
from typing import Tuple, List
NULL_STRING = " "
pattern_dict = {
# To use "test_patterns" as the mutation pattern set, set "patterns" attribute in
# configuration json to "test_patterns".
"test_patterns" : {
" < " : " == "
},
... |
# btrdb.utils.timez
# Conversion utilities for btrdb
#
# Author: PingThings
# Created: Wed Jan 02 17:00:49 2019 -0500
#
# Copyright (C) 2018 PingThings LLC
# For license information, see LICENSE.txt
#
# ID: timez.py [] [email protected] $
"""
Time related utilities
"""
###########################################... |
"""
Jinja support adds the following abilities:
1. Adds a ``YamlFrontMatterLoader``, which searchs the beginning of the file for
YAML between two lines of an equal number of three or more dashes.
These lines are stripped off before rendering.
2. Jinja has nice support for displaying errors, but the YAML front m... |
import click
verbose = click.option(
'--verbose', '-v', count=True, help="Increase verbosity.")
quiet = click.option(
'--quiet', '-q', count=True, help="Decrease verbosity.")
|
"""Handling of the input options
This module contains the useful quantities to deal with the preparation and
the usage of inputfiles for BigDFT code. The main object is the
:class:`Inputfile` class, which inherits from a python dictionary. Such
inheritance is made possible by the internal representation of the BigDFT
... |
#check palindrome practical 5
'''notes: if the input string is equal to the reverse string then it is a pallindrome '''
s = input("Enter a string: ")
r = s[::-1]
if s == r:
print("It's a palindrome!")
else:
print("It's not a palindrome") |
import tensorflow as tf
def main():
# simple test: assign a tensor to a slice of another tensor
# - then run some op depending on that assignment (control_dependency)
# the "buffer" to assign a slice to (matrix of 3x3)
buffer = tf.Variable(tf.zeros(shape=(2, 2)))
# the slice (one row of a 3x3 ma... |
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('fasta', type=argparse.FileType('r'))
args = parser.parse_args()
from Bio import SeqIO
lengthes = []
for record in SeqIO.parse(args.fasta, 'fasta'):
lengthes.append(len(record))
lengthes.sort()
from scipy import stats
im... |
import asyncio
import urllib
from functools import partial
import twisted.internet
import cloudscraper
from scrapy.http import HtmlResponse
from twisted.internet.asyncioreactor import AsyncioSelectorReactor
from twisted.internet.defer import Deferred
import sys
from .settings import *
if sys.platform == 'win32':
... |
import numpy as np
# Compute double element-wise square of vector
def vsquaresquare(V):
R = np.power(np.power(V, 2), 2)
|
import torch
import numpy as np
import mmcv
import cv2
def mask_rotate_target(pos_proposals_list, pos_assigned_gt_inds_list, gt_masks_list,
cfg):
cfg_list = [cfg for _ in range(len(pos_proposals_list))]
mask_rotate_targets = map(mask_rotate_target_single, pos_proposals_list,
... |
import sympy.physics.mechanics as me
import sympy as sm
import math as m
import numpy as np
q1, q2 = me.dynamicsymbols("q1 q2")
q1d, q2d = me.dynamicsymbols("q1 q2", 1)
q1d2, q2d2 = me.dynamicsymbols("q1 q2", 2)
l, m, g = sm.symbols("l m g", real=True)
frame_n = me.ReferenceFrame("n")
point_pn = me.Point("pn")
point_p... |
import pixellib
from pixellib.instance import custom_segmentation
segment_image = custom_segmentation()
segment_image.inferConfig(num_classes= 2, class_names= ["BG", "butterfly", "squirrel"])
segment_image.load_model("mask_rcnn_model.005-0.443756.h5")
segment_image.segmentImage("butterfly (1).jpg", show_bboxes=T... |
# Copyright (C) 2011 by Michele Silva ([email protected])
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
""" Bond length and angle constants.
These constants are primarily extracted from Engh, ... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Module',
fields=[
('id', models.AutoField(seria... |
# Generated by Django 4.0.3 on 2022-03-09 15:20
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_US... |
from .core import OcrPredictionHead, HeadOutputKeys
from .ctc import CtcPredictionHead
from .rnn_attention import RnnAttentionHead
from .factory import PredictionHeadsFactory
FACTORY = PredictionHeadsFactory()
FACTORY.register('ctc', CtcPredictionHead)
FACTORY.register('rnn_attn', RnnAttentionHead)
ATTENTION_HEAD_TYP... |
# -*- coding: iso-8859-1 -*-
import pywintypes
from . import utils
class ActiveDirectoryError (Exception):
u"""Base class for all AD Exceptions"""
pass
class MemberAlreadyInGroupError (ActiveDirectoryError):
pass
class MemberNotInGroupError (ActiveDirectoryError):
pass
class BadPathnameError... |
import setuptools
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='inkrement',
version='0.0.1',
author='Eric Boxer',
author_email='[email protected]',
description='Incremental data visualization in python',
long_description=long_description,
lo... |
# coding: utf-8
from abc import abstractmethod
from .tui import TUI
class TUIDisplay(TUI):
def __init__(self, inventory):
super(TUIDisplay, self).__init__()
self.term = TUI()
self.inventory = inventory
# adjust column width to fit the longest content
def format_columns(self, da... |
import pytest
from zipfile import ZipFile
from pyPreservica import *
def test_export_file_wait():
client = EntityAPI()
asset = client.asset("c365634e-9fcc-4ea1-b47f-077f55df9d64")
zip_file = client.export_opex_sync(asset)
assert os.path.exists(zip_file)
assert 1066650 < os.stat(zip_file).st_size
... |
from pprint import pprint
from flask import jsonify, request
from flask_marshmallow.sqla import ValidationError
from flask_restful import Resource, abort
from flask_auth.app.extensions.database.database_framework import db
from flask_auth.app.blueprints.users.models import UserModel
from flask_auth.app.blueprints.use... |
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
if len(nums) < 2:
raise Exception("Invalid Array")
pre_prod = [1] * len(nums)
post_prod = [1] * len(nums)
res = [None] * len(nums)
i = 1
while i <= len(nums) - 1:
pre_... |
'''
Node metadata.
Used when we encounter variable names in our AST.
Essentially, we're trying to deduce how variables are used. As a key part of
torc involves pulling data from all around the document in order to provide
document-wide data to the RNN as the RNN looks at set of lines, we use
NodeMetadata in order to ... |
import os
import json
import multiprocessing
import random
import math
from math import log2, floor
from functools import partial
from contextlib import contextmanager, ExitStack
from pathlib import Path
from shutil import rmtree
from collections import Counter
import matplotlib.pyplot as plt
import matplotlib.image as... |
"""
okex永续合约
https://www.okex.com/docs/zh/#swap-README
Author: Gary-Hertel
Date: 2020/10/27
email: [email protected]
"""
import time
from purequant.exchange.okex import swap_api as okexswap
from purequant.config import config
from purequant.exceptions import *
from purequant.logger import logger
class OKEXSWAP... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-12-01 22:15
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('vtn', '0052_auto_20171201_1346'),
]
operations = [
migrations.RemoveField(
... |
from django.db.models import (
CASCADE,
Model,
OneToOneField,
ForeignKey,
)
from gbe.models import StyleVersion
from django.contrib.auth.models import User
class UserStylePreview(Model):
version = ForeignKey(StyleVersion, on_delete=CASCADE)
previewer = OneToOneField(User, on_delete=CASCADE)
... |
# -*- coding: utf-8 -*-
'''
Created on 01.12.2014
@author: Simon Gwerder
'''
import json
import timeit
import requests
from ordered_set import OrderedSet
from utilities import utils
from utilities.retry import retry
class IDPreset:
name = None
terms = []
tags = []
def __init__(self):
self.... |
_base_ = [
'cascade_mask_rcnn_r50_fpn.py',
'coco_instance.py',
'schedule_1x.py', 'default_runtime.py'
]
|
import c4d
from ..Const import Const
from .ConfigManagerRedshift import ConfigManagerRedshift
const = Const()
class ConfigManager(c4d.gui.GeDialog, ConfigManagerRedshift):
def __init__(self):
self.jsonContent = self.loadJsonFile()
self.redshiftConfig = self.jsonContent["redshift"]
self.da... |
import pytest
# Set the path to import az
import context
from az.cli import az
AZ_SUCCESSFUL_COMMAND = "group list"
AZ_FAIL_COMMAND = "group show -n this-does-not-exist"
def test_az(az_login):
error_code, result_dict, log = az(AZ_SUCCESSFUL_COMMAND)
assert log == ""
assert error_code == 0
def tes... |
import datetime
import time
from typing import TYPE_CHECKING
import frappe
from kubernetes import client, config
from kubernetes.client.rest import ApiException
if TYPE_CHECKING:
from erpnext_feature_board.erpnext_feature_board.doctype.improvement.improvement import (
Improvement,
)
def get_container_registry()... |
n = 1
l = []
while n != 0:
l.append(int(input("Digite um número: ")))
n = l[-1]
print("\n\nVocê digitou 0 e encerrou o programa!")
print("\nOs números que você digitou foram:\n")
for elemento in l:
print(elemento)
if len(l) % 2 == 0:
print("\nVocê digitou uma quantidade PAR de números!")
else:
... |
import numpy as np
class Tri6:
"""Class for a six noded quadratic triangular element.
Provides methods for the calculation of section properties based on the finite element method.
:param int el_id: Unique element id
:param coords: A 2 x 6 array of the coordinates of the tri-6 nodes. The first three... |
class Hourly:
def __init__(self, temp, feels_like, pressure, humidity, wind_speed, date, city, weather):
self.temp=temp;
self.feels_like=feels_like;
self.pressure=pressure;
self.humidity=humidity;
self.wind_speed=wind_speed;
self.date=date;
self.city=city;
... |
import numpy as np
from fmmlib2d import hfmm2dparttarg
from fmmlib2d import lfmm2dparttarg
from fmmlib2d import rfmm2dparttarg
from fmmlib2d import zfmm2dparttarg
from fmmlib2d import cfmm2dparttarg
from fmmlib2d import h2dpartdirect
from fmmlib2d import l2dpartdirect
from fmmlib2d import r2dpartdirect
from fmmlib2d ... |
from __future__ import print_function, absolute_import, division
# Importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.KratosUnittest as KratosUnittest
import math
import os
def GetFilePath(fileName):
return os.path.join(os.path.dirname(os.path.realpath(__file__)), fileNam... |
from collections import OrderedDict
from datetime import datetime
import requests
from bs4 import BeautifulSoup
from dateutil import parser
from data_parser.base_parser import BaseParser
from validations.schemas.exams_schema import ExamsSchema
def get_course_info(month, year, course_code):
season = course_code[... |
from . import utils
from .asset import *
from .category import *
from .channel import *
from .client import *
from .embed import *
from .enums import *
from .errors import *
from .file import *
from .flags import *
from .invite import *
from .member import *
from .message import *
from .messageable import *
from .permi... |
from enum import Enum
from typing import Optional, Any
from System import InvalidOperationException # pylint: disable=import-error
from FlaUILibrary.flaui.exception import FlaUiError
from FlaUILibrary.flaui.interface import (ModuleInterface, ValueContainer)
from FlaUILibrary.flaui.util.converter import Converter
cla... |
import sys,os,re,socket,binascii,time,json,random,threading,Queue,pprint,urlparse,smtplib,telnetlib,os.path,hashlib,string,urllib2,glob,sqlite3,urllib,argparse,marshal,base64,colorama,requests
from colorama import *
from random import choice
from colorama import Fore,Back,init
from email.mime.multipart import MIMEMulti... |
import os, logging
# ----- LOGGING ----- #
DEBUG = True
LOG_FILE = 'logfile.log'
# 1 DEBUG - detailed info
# 2 INFO - confirmation that things according to plan
# 3 WARNING - something unexpected
# 4 ERROR - some function failed
# 5 CRITICAL - application failure
LOG_LEVEL = logging.DEBUG
logging.basi... |
from django.contrib.auth.models import User
from django.shortcuts import render
from .models import Message
from .forms import MessageForm
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import UpdateView, DeleteView
from django.utils import ... |
"""Define tests for the GeoNet NZ Quakes config flow."""
from datetime import timedelta
from asynctest import CoroutineMock, patch
import pytest
from homeassistant import data_entry_flow
from homeassistant.components.geonetnz_quakes import (
CONF_MINIMUM_MAGNITUDE,
CONF_MMI,
DOMAIN,
FEED,
async_se... |
def foo(a, b): a<caret>.
|
from setuptools import *
desc = """
Overview
=====
 [](https://webchat.freenode.net/) [](http://twitter.com/cofferproject)
A lightweigh... |
import os
import boto3
s3_client = boto3.client('s3')
s3_bucket = "aiworkflow"
training_dataset = "sim_data"
training_files = os.listdir(training_dataset+"/IMG/")
for file in training_files:
file_name = training_dataset+"/IMG/"+file
object_name = training_dataset+"_"+file
print(object_name)
s3_clien... |
##
# @filename : imagedata.py
# @brief : data file for epd demo
#
# Copyright (C) Waveshare August 16 2017
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation files (the "Software"), to deal
# in the Software ... |
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING, List, Optional
import pytest
from _pytest import nodes
from _pytest.config import Config
from _pytest.config.argparsing import Parser
from _pytest.main import Session
from _pytest.reports import TestReport
if TYPE_CHECKING:
from _pytest.cacheprovider impo... |
import re
import xml.etree.ElementTree as ET
import subprocess32 as subproces
import extraction.utils as utils
from extraction.core import ExtractionRunner
from extraction.runnables import Filter, Extractor, ExtractorResult
# Define extractors and filters
class HasNumbersFilter(Filter):
def filter(self, data, deps)... |
#!/usr/bin/env python2
"""
Our goal with version 2.0 of ExtraBacon is to support more ASA versions, as well
as simplify the Python and payload shellcode. This means stripping as much as
possible from the shellcode and Python to still be functional.
"""
import sys
import string
import subprocess
import binascii
import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 Lee McCuller <[email protected]>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline ... |
file = open("nomes.txt", "r")
lines = file.readlines()
title = lines[0]
names = title.strip().split(",")
print(names)
for i in lines[1:]:
aux = i.strip().split(",")
print('{}{:>5}{:>8}'.format(aux[0], aux[1], aux[2])) |
from http import HTTPStatus
from django.urls import reverse
from mock import patch
from core.tests import MarketAccessTestCase
class EditWTOStatusTestCase(MarketAccessTestCase):
@patch("utils.api.resources.APIResource.patch")
def test_empty_wto_has_been_notified_error(self, mock_patch):
response = s... |
# %%
from time import time
from bullet import Bullet
import pygame
from setting import Settings
from plane import Plane
import game_func as gf
from pygame.sprite import Group
from 敌机 import Eplane
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
import time
def run_game():... |
from flytekitplugins.spark import Spark
from mock import MagicMock
from flytekit import task
from flytekit.configuration import Config, SerializationSettings
from flytekit.remote.remote import FlyteRemote
def test_spark_template_with_remote():
@task(task_config=Spark(spark_conf={"spark": "1"}))
def my_spark(... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
from telemetry.page import shared_page_state
class FlingGestureSupportedSharedState(shared_page_state.SharedPageState):
def CanRunOnBrowse... |
from django.conf import settings
# max number of objects to return
DEFAULT_PAGE_SIZE = getattr(settings, "ZAPIER_TRIGGER_DEFAULT_PAGE_SIZE", 25)
|
# Copyright 2014-2016 Presslabs SRL
#
# 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... |
import cv2
import numpy as np
from rob9Utils.affordancetools import getPredictedAffordances
def convexHullFromContours(contours):
""" Input:
contours - list [cv2 contours]
Output:
hulls - list [N, cv2 hulls]
"""
hulls = []
for contour in contours:
hulls.append... |
from argparse import ArgumentParser
from logging import getLogger
from pathlib import Path
from tempfile import gettempdir
from pronunciation_dict_parser.app.common import \
add_default_output_formatting_arguments
from pronunciation_dict_parser.app.helper import save_dictionary_as_txt
from pronunciation_dict_parse... |
from django.contrib import admin
from .models import HomeBanner
# Register your models here.
@admin.register(HomeBanner)
class PromoCategoryAdmin(admin.ModelAdmin):
list_display = (
'id', 'describe', 'show_time', 'hide_time', 'banner_h5', 'script_h5', 'banner_pc', 'script_pc',
'sort')
search_... |
#!/usr/bin/python
# Copyright (c) 2017, 2020 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List, Mapping, Opt... |
def knapsack(max_weight, weights, values, n):
cache = [[0 for _ in range(max_weight+1)] for _ in range(n+1)]
# i iterates over values
for i in range(n + 1):
# j iterates over different max weight values
for j in range(max_weight + 1):
if i == 0 or j == 0:
c... |
# -*- coding: utf-8 -*-
import base64
import hashlib
import sys
import binascii
import ed25519
sys.path.insert(0, 'python-sha3')
from python_sha3 import *
from .helper import *
from config import config
import datetime
import struct
import binascii
import requests
import json
import time
def getTimeStamp(delta=0):
re... |
import os, sys
# import threading
# t_data = threading.local()
capture_stack = None
capture_manager = None
def configure():
_capture_stack = []
_capture_stack.append((sys.__stdout__, sys.__stderr__))
thismodule = sys.modules[__name__]
setattr(thismodule, 'capture_stack', _capture_stack)
_capture... |
from .Postgres import PostgresDataHandler |
"""Tools for working with design spaces."""
from typing import Any, List, Mapping, Type
from uuid import UUID
from citrine._rest.resource import Resource
from citrine._serialization import properties
from citrine._serialization.polymorphic_serializable import PolymorphicSerializable
from citrine._serialization.seriali... |
import flickr_api
from multiprocessing.pool import ThreadPool
import flickr_api.flickrerrors
import threading
import sys
import logging
class Photo:
_GPS_TAGS = ['gpslatitude','gps','gps latitude','gps position','gps altitude', 'latitude', 'position']
def __init__(self, photo):
self.data = photo
... |
import ops.cmd
import ops
import ops.env
import ops.cmd.safetychecks
from ops.cmd import getBoolOption, setBoolOption, getValueOption, setListOption
OpsCommandException = ops.cmd.OpsCommandException
VALID_OPTIONS = ['minimal', 'type']
class NetmapCommand(ops.cmd.DszCommand, ):
optgroups = {}
reqgroups = []
... |
#!/usr/bin/env python2
""" The layout class """
# upconvert.py - A universal hardware design file format converter using
# Format: upverter.com/resources/open-json-format/
# Development: github.com/upverter/schematic-file-converter
#
# Copyright 2011 Upverter, Inc.
#
# Licensed under the Apache License, Version... |
"""
This software is distributed under MIT/X11 license
Copyright (c) 2021 Mauro Marini - University of Cagliari
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 with... |
import argparse
import os
standard_path = 'no_dos'
parser = argparse.ArgumentParser(description='Cleans experiments folder.')
parser.add_argument('-e', default=standard_path, help='Path to experiments folder')
args = parser.parse_args()
# Iterate though experiment folders.
root = args.e
for top, dirs, files in os.wa... |
from draco.core.containers import GainData
from caput import mpiarray, mpiutil
import pytest
import glob
import numpy as np
import os
# Run these tests under MPI
pytestmark = pytest.mark.mpi
comm = mpiutil.world
rank, size = mpiutil.rank, mpiutil.size
len_axis = 8
dset1 = np.arange(len_axis * len_axis * len_axis)... |
from datetime import date
import sys
# Prereq issues can be signaled with ImportError, so no try needed
import sqlalchemy, sqlalchemy.orm
import Bcfg2.Server.Admin
import Bcfg2.Server.Snapshots
import Bcfg2.Server.Snapshots.model
from Bcfg2.Server.Snapshots.model import Snapshot, Client, Metadata, Base, \
File, G... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import update_reference_build as update_ref_build
# Disable for accessing private API of update_reference_build class.
# pylint: disable=pr... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Scheduling and job monitoring utilities.
"""
from contextlib import contextmanager, ExitStack
from dataclasses import da... |
#!/usr/bin/python3
import threading, ctypes, pathlib
import cryptography, os, requests, sys
from PIL import Image, ImageDraw, ImageFont
from win32api import GetSystemMetrics
from cryptography.fernet import Fernet
from tkinter import messagebox
from time import sleep
class D_E_ncrypt(object): # E... |
# let's import the flask
from flask import Flask, render_template, request, redirect, url_for
import os # importing operating system module
app = Flask(__name__)
# to stop caching static file
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
@app.route('/') # this decorator create the home route
def home ():
techs = ... |
#!/usr/bin/python3
import sys
import os
import binascii
import re
import subprocess
import signal
def handler(x, y):
sys.exit(-1)
signal.signal(signal.SIGALRM, handler)
signal.alarm(30)
def gen_filename():
return '/tmp/' + binascii.hexlify(os.urandom(16)).decode('utf-8')
EOF = 'zh3r0-CTF'
MAX_SIZE = 10000
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.