text stringlengths 2 999k |
|---|
# GENERATED BY KOMAND SDK - DO NOT EDIT
from setuptools import setup, find_packages
setup(name='sqlmap-rapid7-plugin',
version='1.1.1',
description='The SQLMap plugin allows you to scan targets and analyze the results',
author='rapid7',
author_email='',
url='',
packages=find_packag... |
# CircuitPython NeoPixel Color Picker Example
import board
import neopixel
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_conne... |
'''resequencing class'''
from copy import copy
#sbaas lims
from SBaaS_LIMS.lims_biologicalMaterial_query import lims_biologicalMaterial_query
#SBaaS models
from SBaaS_models.models_COBRA_query import models_COBRA_query
from SBaaS_models.models_BioCyc_execute import models_BioCyc_execute
#sbaas
from .stage01_resequenci... |
#
# Base submodel class
#
import pybamm
class BaseSubModel(pybamm.BaseModel):
"""
The base class for all submodels. All submodels inherit from this class and must
only provide public methods which overwrite those in this base class. Any methods
added to a submodel that do not overwrite those in this b... |
class SameCardsInOneDeckError(Exception):
pass
|
from setuptools import setup
setup(
name='zipfpy',
version='0.1',
author='Greg Wilson',
packages=['zipfpy']
)
|
import sys
import time
File__ = None
FileSize__ = None
FileName__ = None
Secs__ = None
def InitFile(File, FileName = ""):
global Secs__, File__, FileSize__, FileName__
File__ = File
FileName__ = FileName
Secs__ = None
Pos = File.tell()
File.seek(0, 2)
FileSize__ = File.tell()
File.seek(Pos)
def FileDone(Ms... |
"""A framework for bulk data processing."""
|
# O(n) time | O(n) space
def branchSums(root):
sums = []
preorderTraversal(root, 0, sums)
return sums
# Recursive
def preorderTraversal(root, runningSum, sums):
if root:
if root.left or root.right:
preorderTraversal(root.left, runningSum + root.value, sums)
preorderTrave... |
import os
import shutil
from django.test import override_settings, TestCase
from drftest import doc_generator
@override_settings(DRF_TEST_DOCS_DIR='drftest/tests/test_docs')
class DocGeneratorTest(TestCase):
def setUp(self):
super().setUp()
doc_generator.store = [{
'method': 'post',
... |
import logging
import sys
try:
from enum import Enum
except ImportError:
from ..enum import Enum
from PySide2 import QtWidgets, QtCore, QtGui
from . import utils
# py 2.7
if sys.version_info[0] >= 3:
unicode = str
class AttributeTableView(QtWidgets.QTableView):
def __init__(self, parent=None):
... |
def reverso(n):
numeroInvertido = int(str(n)[::-1])
print(numeroInvertido)
n = int(input("Digite o número: "))
reverso(n) |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sonet.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
"""
Move Sprite With Keyboard
Simple program to show moving a sprite with the keyboard.
The sprite_move_keyboard_better.py example is slightly better
in how it works, but also slightly more complex.
Artwork from http://kenney.nl
If Python and Arcade are installed, this example can be run from the command line with:
... |
#!/usr/bin/env python
import andrena
def got_key(client):
# Setup callback for when diffie hellman key is negotiated
infile = open('README.md', 'r')
data = infile.read()
infile.close()
stream = andrena.FileTransfer(None, client)
stream.meta = "newreadme" # save file remotely as newreadme
... |
"""Implementation of :class:`Domain` class. """
from typing import Any, Optional, Type
from sympy.core import Basic, sympify
from sympy.core.sorting import default_sort_key, ordered
from sympy.external.gmpy import HAS_GMPY
from sympy.polys.domains.domainelement import DomainElement
from sympy.polys.orderings import ... |
from django.contrib import admin
from imagekit.admin import AdminThumbnail
import models
class PanelInline(admin.TabularInline):
prepopulated_fields = {"slug": ("title",)}
list_display = ['title', 'slug', 'visible']
model = models.Panel
extra = 3
class PageAdmin(admin.ModelAdmin):
prepopulated_... |
# Copyright 2022 The TensorFlow 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 applica... |
from sqlalchemy.orm import Session
from sqlalchemy import desc
from typing import List, Dict, Union, Any, Tuple
from datetime import datetime, timedelta
from fastapi import Form, Header
import uuid
import os
import enum
import jwt
from app.database import models, schemas
from app.database.base import get_db
from app ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import with_metaclass
from collections import OrderedDict
from django.db import models
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_lazy as _
from shop.models.fields import JSONField
from s... |
import numpy as np
from liquepy import functions
import eqsig
class ShearTest(object):
_stress = None
_strain = None
_pp = None
_esig_v0 = None
_i_liq = None
_i_liq_strain = None
_i_liq_pp = None
_n_points = 0
_n_cycles = None
_ru_limit = None
_da_strain = None
def __i... |
import pytest
import numpy as np
import torch
from doctr.models.preprocessor import PreProcessor
@pytest.mark.parametrize(
"batch_size, output_size, input_tensor, expected_batches, expected_value",
[
[2, (128, 128), np.full((3, 256, 128, 3), 255, dtype=np.uint8), 1, .5], # numpy uint8
[2, (1... |
#!/usr/bin/env python3
import serial
import subprocess
dev = serial.Serial("/dev/ttyUSB0", 115200)
results = []
for i in range(1, 250):
binary = f"benchmark-schoolbook_{i}.bin"
print(f">>> making {binary}")
subprocess.run(["make", binary])
print("done")
print(f">>> flashing {binary}")
subproc... |
# -*- coding: utf-8 -*-
# /*##########################################################################
#
# Copyright (c) 2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), t... |
import requests
from sys import argv
"""
quickly check api responses.
setup venv:
python3 -m venv merlinapi_venv
source merlinapi_venv/bin/activate
pip3 install -r requirements.txt
run:
python3 api_tests.py
"""
TFJS_URL = "http://127.0.0.1:3300/api/v1/classify/27758741/d0601ea6-8a3d-4899-9a24-473a7186f... |
from dataclasses import dataclass
from typing import List, Tuple
from tqdm import tqdm
from src.core.common.accents_dict import AccentsDict
from src.core.common.language import Language
from src.core.common.symbol_id_dict import SymbolIdDict
from src.core.common.symbols_dict import SymbolsDict
from src.core.common.te... |
from discord.ext import commands
import discord
import os
TOKEN = os.environ['DISCORD_BOT_TOKEN']
client = discord.Client()
@client.event
async def on_ready():
channel = client.get_channel(701731353783304225)
await channel.send('投稿削除サーバー起動')
return
@client.event
async def on_message(message):
channel = clien... |
import random
import re
import requests
from urllib3.exceptions import InsecureRequestWarning
from login.Utils import Utils
from login.casLogin import casLogin
from login.iapLogin import iapLogin
from login.RSALogin import RSALogin
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class TodayLoginS... |
# 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 required by applicable law or agreed to i... |
__title__ = 'cleanfreak'
__author__ = 'Dan Bradham'
__email__ = 'danielbradham@gmail.com'
__url__ = 'http://github.com/danbradham/cleanfreak'
__version__ = '0.1.8'
__license__ = 'MIT'
__description__ = 'Sanity checks and grades for CG production.'
import os
from functools import partial
# Package relative path joini... |
import numpy as np
def skew(x):
x=np.asarray(x).ravel()
""" Returns the skew symmetric matrix M, such that: cross(x,v) = M v """
return np.array([[0, -x[2], x[1]],[x[2],0,-x[0]],[-x[1],x[0],0]])
# !> Computes directional cosine matrix DirCos
# !! Transforms from element to global coordinates: xg = DC.xe... |
import os
import sys
testsPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, testsPath + '/../')
from suds.client import Client
import datetime
import pytest
import pytz
from nrewebservices.ldbws import NextDeparturesBoardWithDetails, Session
from helpers import mock_ldbws_response_from_file, ldb... |
from django.utils import timezone
from calendar import HTMLCalendar
import logging
logger = logging.getLogger(__name__)
class Calendar(HTMLCalendar):
def __init__(self, year=None, month=None, dark=False):
self.year = year
self.month = month
self.events = None
self.dark = dark
... |
from loguru import logger
def info(info_msg):
logger.info(info_msg)
def error(error_msg):
logger.error(error_msg)
def debug(debug_msg):
logger.debug(debug_msg)
def warning(warn_msg):
logger.warning(warn_msg)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to set the version number wherever it's needed before a release."""
from __future__ import unicode_literals, print_function
import io
import os
import re
import sys
import glob
import subprocess
import io
def sed_like_thing(pattern, repl, path):
"""Like re... |
# Copyright 2017 The TensorFlow 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 applica... |
from .graph_node import Node
from .graph import Graph
from .exceptions import GraphError
|
# Generated by Django 3.0.2 on 2020-01-20 12:15
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('api', '0012_auto_20200120_0659'),
]
operations = [
migrations.AddField(
model_name='vehiclechangehi... |
# coding: utf-8
"""
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
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 limit... |
#!/usr/bin/env python
"""Tests for grr.lib.flows.general.filetypes."""
import os
from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import flags
from grr.lib import test_lib
from grr.lib.aff4_objects import filetypes as aff4_filetypes
from grr.lib.flows.general import filetypes
from grr.lib.rdfva... |
"""
Functions to help with download and basic processing of GPS data
"""
from datetime import datetime, timedelta
import io
import json
import logging
import multiprocessing
import os
import re
from typing import cast, Dict, Iterable, Optional, Sequence, Tuple
import zipfile
import numpy
import requests
import georin... |
# SPDX-License-Identifier: BSD-3-Clause
"""
Utility to create a SoftFab results file from PyLint's JSON output.
For SoftFab, 'error' means the test results are incomplete, while 'warning'
means the results are complete but the content has problems. So if PyLint
ran successfully but finds errors in the code it examine... |
# -*- coding:utf-8 -*-
import pytest
cands = [
['>=1.2.3', '2.0.0-pre', False, False],
]
@pytest.mark.parametrize("range_, version, loose, expected", cands)
def test_it(range_, version, loose, expected):
from semver import make_semver, satisfies
# assert expected == make_semver(range_, loose=loose).test(... |
"""
Core functions used by unumpy and some of its submodules.
(c) 2010-2013 by Eric O. LEBIGOT (EOL).
"""
# The functions found in this module cannot be defined in unumpy or
# its submodule: this creates import loops, when unumpy explicitly
# imports one of the submodules in order to make it available to the
# user.
... |
import os
def get_cmap():
"""Gets the colormap (default: ``viridis``)
The colormap can be set by the environment variable ``TTSLEARN_CMAP``
for convenience.
Returns:
str: The name of the current colormap.
Examples:
.. ipython::
In [1]: from ttslearn.notebook import get_cm... |
# Sentinel-2 package
import ee
import math
import datetime
import os, sys
from utils import *
import sun_angles
import view_angles
import time
class env(object):
def __init__(self):
"""Initialize the environment."""
# Initialize the Earth Engine object, using the authentication credentials.
ee.Initialize()
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .vfe_template import VFETemplate
class PFNLayer(nn.Module):
def __init__(self,
in_channels,
out_channels,
use_norm=True,
last_layer=False):
super().__init__()
... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zerei.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... |
import os
import pytest
from ray.tests.conftest import * # noqa
@pytest.fixture
def enable_test_module():
os.environ["RAY_DASHBOARD_MODULE_TEST"] = "true"
yield
os.environ.pop("RAY_DASHBOARD_MODULE_TEST", None)
|
import MySQLdb
conn = MySQLdb.Connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = '123456',
db = 'softcup',
charset = 'utf8'
)
cursor = conn.cursor()
sql = "select title from douban_press01 where isbn13='9787010009292'"
cursor.execute(sql)
catalog = cursor.fetchall()
... |
"""
Harness to manage optimisation domains.
-- kandasamy@cs.cmu.edu,
kkorovin@cs.cmu.edu
"""
# pylint: disable=no-member
# pylint: disable=invalid-name
# pylint: disable=arguments-differ
# pylint: disable=abstract-class-not-used
import numpy as np
# Local
from explore.explorer import ga_opt_args, ga_op... |
from ..factory import Type
class messageVoiceNote(Type):
voice_note = None # type: "voiceNote"
caption = None # type: "formattedText"
is_listened = None # type: "Bool"
|
from django.test import tag
from unittest.mock import patch
from CMS.test.mocks.institution_mocks import InstitutionMocks
from CMS.test.utils import UniSimpleTestCase
from errors.models import ApiError
from institutions.models import Institution
@tag('azure')
class InstitutionsModelsTests(UniSimpleTestCase):
@p... |
"""Auto-generated file, do not edit by hand. AZ metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_AZ = PhoneMetadata(id='AZ', country_code=994, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='(?:(?:(?:[12457]\\d|60|88)\\d|365)\\d{3}... |
# -*- coding: utf-8 -*-
"""
@description:
@author:XuMing
"""
from __future__ import print_function # 兼容python3的print写法
from __future__ import unicode_literals # 兼容python3的编码处理
import base64
import binascii
import json
import logging
import re
import time
import requests
import rsa
import urllib
class WeiBoLogin(... |
"""
This is a sample on how to define custom components.
You can make a repo out of this file, having one custom component per file
"""
import os
import shutil
import pytest
import pp
from pp.add_padding import add_padding_to_grid
from pp.add_termination import add_gratings_and_loop_back
from pp.autoplacer.yaml_place... |
import sys
import sqlite3
import geoip2.database
db = sqlite3.connect(sys.argv[1])
geoip_reader = geoip2.database.Reader(sys.argv[2])
geoip_lookup = geoip_reader.city
with db as cur:
for row in db.execute('select ip from access'):
ip = row[0]
try:
r = geoip_lookup(ip)
except g... |
import sys
import re
import os
import argparse
from collections import deque
FLAG = None
def read_classify_list(filename):
classify_dic = {}
with open(filename,'r') as f:
for line in f:
l_sp = line.rstrip().split(' ')
ID = l_sp[0]
start_frame = l_sp[1]
c... |
import six
import warnings
from .. import errors
from ..utils.utils import (
convert_port_bindings, convert_tmpfs_mounts, convert_volume_binds,
format_environment, normalize_links, parse_bytes, parse_devices,
split_command, version_gte, version_lt,
)
from .base import DictType
from .healthcheck import Heal... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 5
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_1_0.models.ndmp_lo... |
# coding=utf-8
from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlWegdekvoegType(KeuzelijstField):
"""Vormen van wegdekvoeg."""
naam = 'KlWe... |
import torch
import torch.nn as nn
import torch.nn.init as init
from transformer.modules import Linear
from transformer.modules import ScaledDotProductAttention
from transformer.modules import LayerNormalization
class _MultiHeadAttention(nn.Module):
def __init__(self, d_k, d_v, d_model, n_heads, dropout):
... |
############################################################################
# Copyright 2015 Valerio Morsella #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may no... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import code
import warnings
import string
import argparse
from flask import _request_ctx_stack
from .cli import prompt, prompt_pass, prompt_bool, prompt_choices
class InvalidCommand(Exception):
pass
class Group(object):
"""
Sto... |
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
class AppServicePHPVersion(BaseResourceValueCheck):
def __init__(self):
name = "Ensure that 'PHP version' is the latest, if used to run the we... |
# python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
import argparse
import os
import pickle as pkl
import numpy as np
import torch
from statsmodels.tsa.arima_process import ArmaProcess
from attribution.mask_group import MaskGroup
from attribution.perturbation import GaussianBlur
from baselines.explainers import FO, FP, IG, SVS
from utils.losses import mse
explainers ... |
"""
Assorted utilities for working with neural networks in AllenNLP.
"""
# pylint: disable=too-many-lines
from collections import defaultdict
from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar
import logging
import copy
import math
import torch
from allennlp.common.checks import ConfigurationError... |
import os
import cv2
import numpy as np
import sys
import pickle
from optparse import OptionParser
import time
from keras_frcnn import config
import keras_frcnn.resnet as nn
from keras import backend as K
from keras.layers import Input
from keras.models import Model
from keras_frcnn import roi_helpers
from keras_frcnn ... |
from logger_base import logger
class SubClass:
def __init__(self, QID=None, label=None):
self.__QID = QID
self.__label = label
def __str__(self):
return (
f'QID: {self.__QID}, '
f'label: {self.__label}'
)
def getQID(self):
return self.__QID... |
import os
import time
import six
import uuid
import amostra.client.commands as acc
import conftrak.client.commands as ccc
from analysisstore.client.commands import AnalysisClient
import conftrak.exceptions
import logging
logger = logging.getLogger(__name__)
#12/19 - Skinner inherited this from Hugo, who inherited ... |
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
# ------------------------------------------------------... |
"""
A number of defitions get re-used frequently; this module attempts to centralize and deduplicate them (a little; some of this still duplicates from Doxygen's source).
Not in love with how this works...
"""
from collections import namedtuple
from . import exceptions
from . import loggle
constants = namedtuple("c... |
from simple_salesforce import Salesforce
from dotenv import load_dotenv
import os
import time
import random
BASE_DIR='./'
load_dotenv(os.path.join(BASE_DIR, '.env.iotxporg'))
USERNAME=os.getenv('USERNAME')
PASSWORD=os.getenv('PASSWORD')
SECURITY_TOKEN=os.getenv('SECURITY_TOKEN')
print("uname %s pw %s token %s" % (U... |
from typing import Union
import os
try:
import objc
import Foundation
# This import is required for NSImage
import AppKit # noqa: 5401
except ImportError:
raise Exception(
"""To use native notifications, you need to install the following dependencies:
- pyobjc-core
- pyobjc-framework-Noti... |
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
import numpy as np
import keras
from IPython.display import clear_output
import matplotlib as mpl
#plot function for sample images
def plot_tile(samples):
num_samples, x_d... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import torch
import numpy as np
f... |
import torch.utils.data
import os
from PIL import Image
import numpy as np
class SearchDataset(torch.utils.data.Dataset):
def __init__(
self,
root_dir=os.path.join(os.path.dirname(__file__), "data/train"),
transform=None,
):
self.transform = transform
# Implement additi... |
"""Latin scansion app."""
import functools
import unicodedata
import flask
import wtforms # type: ignore
import yaml
import latin_scansion
import pynini
CONFIG = "config.yaml"
## Startup.
# Creates app object.
app = flask.Flask(__name__)
# Loads configs.
with open(CONFIG, "r") as source:
app.config.upda... |
"""
Ory Kratos API
Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the admini... |
# -*- coding: 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 Apache License, Version 2.0 (the
#... |
"""
Support for ZigBee Home Automation devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zha/
"""
import collections
import enum
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant impo... |
# --------------------------------------------------------
# PyTorch WSDDN
# Copyright 2018. Seungkwan Lee
# Licensed under The MIT License [see LICENSE for details]
# Written by Seungkwan Lee
# Some parts of this implementation are based on code from Ross Girshick, Jiasen Lu, and Jianwei Yang
# -----------------------... |
from typing import List
from ..ex.relational import IRelationalRow
from . import xivrow, XivRow, IXivSheet
@xivrow
class GatheringPoint(XivRow):
@property
def base(self) -> "GatheringPointBase":
from .gathering_point_base import GatheringPointBase
return self.as_T(GatheringPointBase)
@pr... |
import datetime
from django import forms
from django.contrib import admin, messages
from django.contrib.admin.util import unquote
from django.contrib.admin.views.main import ChangeList
from django.contrib.auth.decorators import permission_required
from django.core.exceptions import ValidationError, PermissionDenied
fr... |
import os
import sys
import requests
import json
from datetime import datetime, timezone, timedelta
from django.core.management.base import BaseCommand
from api.models import AppealType, AppealStatus, Appeal, Region, Country, DisasterType, Event
from api.fixtures.dtype_map import DISASTER_TYPE_MAPPING
from api.logger i... |
# Copyright 2017 The TensorFlow 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 applica... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maximumProfit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
maximumProfit += (prices[i] - prices[i - 1])
return maximumProfit |
#!/usr/bin/env python
__all__ = ['miaopai_download']
from ..common import *
import urllib.error
def miaopai_download(url, output_dir = '.', merge = False, info_only = False, **kwargs):
'''Source: Android mobile'''
if re.match(r'http://video.weibo.com/show\?fid=(\d{4}:\w{32})\w*', url):
fake_headers_m... |
from ctypes import c_void_p
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
from django.utils import six
from django.utils.encoding import force_bytes, force_text
class Driver(GDALBas... |
import arcpy
from arcpy import env
env.overwriteOutput = True
env.workspace = "C:/Temp"
fcs = arcpy.ListFeatureClasses("","point")
if arcpy.Exists("roads.shp"):
for buff in fcs:
arcpy.Buffer_analysis (buff, "Results\Buffer" + buff, "0.25 MILES")
else:
print "the file does not exists"
|
# --------------------------------------------------------------------
###
# Supercell class:
# Methods
# get_data(): reads in rmc6f file from the set file path
# orthonormalise_cell(): converts atomic coordinates to an orthonormal basis
###
# --------------------------------------------------------------------
import... |
from rest_framework.serializers import ModelSerializer
from rest_framework.fields import SerializerMethodField
from .models import PlayerClanRule, PlayerClanRuleGoal
class PlayerClanRuleSerializer(ModelSerializer):
description = SerializerMethodField()
filtered_column_type = SerializerMethodField()
def ... |
#
# Copyright (c) 2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
"""Phased LSTM implementation based on the version in tensorflow contrib.
See: https://github.com/tensorflow/tensorflow/blob/r1.15/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1915-L2064
Due to restructurings in tensorflow some adaptions were required. This
implementation does not use global naming of variables and... |
# (c) 2019–2020, Ansible by Red Hat
#
# 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, dist... |
"""Google Photo API abstraction module"""
import json
import logging
import os.path
import time
from io import open
from datetime import date, datetime, timedelta
import requests
import six
logger = logging.getLogger(__name__)
AUTH_URL = "https://accounts.google.com/o/oauth2/auth"
CLIENT_ID = "834388343680-embh8gpu... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: job_tasks.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.