content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python
# -*- coding:utf8 -*-
from library.cloudflare import CloudFlare
from library.dnspod import Dnspod
from helpers.logger import log_error
support = ['dnspod', 'cloudflare']
allowed_types = ['A', 'CNAME', 'AAAA', 'NS']
class dns:
def help(self, req, resp):
h = '''
... | python |
#!/usr/bin/env python2
# Copyright (c) 2016-2017, Daimler AG. All rights reserved.
import argparse
# Find the best implementation available
import logging
import os
from generic_tf_tools.tf_records import TFCreator
from generic_tf_tools.data2example import SwedenImagesv2
logging.basicConfig(level=logging.INFO)
logg... | python |
"""
Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard
objects or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowe... | python |
def readFile(file):
f = open(file)
data = f.read()
f.close()
return data
def readFileLines(file):
data = readFile(file)
return data.strip().split("\n")
def readFileNumberList(file):
lines = readFileLines(file)
return list(map(int, lines))
def differencesBetweenNumbers(numbers):
# ... | python |
import re
from src.vcd import VCD
from src.module import Module
from src.interval_list import IntervalList
from src.wire import Wire
class VCDFactory():
"""
Factory class
"""
seperator = "$enddefinitions $end"
@staticmethod
def read_raw(filename):
with open(filename, 'r') as f:
... | python |
import pytest
from sovtokenfees.constants import FEES
from plenum.common.exceptions import InvalidClientRequest
def test_set_fees_handler_static_validation(set_fees_handler, set_fees_request):
set_fees_handler.static_validation(set_fees_request)
def test_set_fees_handler_static_validation_no_fees(set_fees_hand... | python |
from app import controller #yeah...kinda stupid
import json
class controller():
def __init__(s,gen_new,nam=None,SECRET_KEY=b'12'):
s.q={}
s.gen_new=gen_new
s.max_id=0
if nam is None:nam=__name__
s.app=Flask(nam)
s.app.config["SECRET_KEY"]=SECRET_KEY
s.addroute()
def addroute(s):
... | python |
from flask import Flask,request
from PIL import Image
from tempfile import TemporaryFile
import json,base64
import captcha as capt
import model
app = Flask(__name__)
@app.route('/')
def hello():
return "hello,world"
@app.route('/captcha',methods=['GET','POST'])
def captcha():
if request.method == 'GET... | python |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | python |
# dir_utils.py is derived from [3DMPPE_POSENET_RELEASE](https://github.com/mks0601/3DMPPE_POSENET_RELEASE.git)
# distributed under MIT License (c) 2019 Gyeongsik Moon.
import os
import sys
def make_folder(folder_name):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
def add_pypath(path):
... | python |
import numpy as np
import theano as th
import theano.tensor as tt
import src.kinematics as kn
def test_unzero6dof():
# Make sure that our unzeroing actually doesn't change anything.
q = tt.dmatrix('q')
q_ = np.random.rand(50, 6)
th.config.compute_test_value = 'warn'
q.tag.test_value = q_
u =... | python |
from conans import ConanFile
class OSSCoreTestsConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake_find_package"
def requirements(self):
self.requires("catch2/2.13.3")
self.requires("nlohmann_json/3.9.1")
| python |
# Import packages to extend Python (just like we extend Sublime, Atom, or VSCode)
from random import randint
# re-import our game variables
from gameComponents import gameVars, winLose
# [] => this is an array
# name = [value1, value2, value3]
# an array is a special type of container that can hold mutiple items.
# a... | python |
class File(object):
def __init__(self,name, current_type):
self.name = name
self.block = 0
self.critical = 0
self.major = 0
# current modification type like 'modify' 'add' 'delete'
self.current_type = current_type
self.authors = list()
@staticmethod
... | python |
# Software Name: its-client
# SPDX-FileCopyrightText: Copyright (c) 2016-2022 Orange
# SPDX-License-Identifier: MIT License
#
# This software is distributed under the MIT license, see LICENSE.txt file for more details.
#
# Author: Frédéric GARDES <frederic.gardes@orange.com> et al.
# Software description: This Intellig... | python |
from pathlib import Path as _Path
from sys import platform as _platform
__all__ = [
"hmmfetch",
"hmmpress",
"hmmscan",
"hmmsearch",
"hmmemit",
"phmmer",
"binary_version",
]
binary_version = "3.3.2"
if _platform not in ["linux", "darwin"]:
raise RuntimeError(f"Unsupported platform: {_p... | python |
import time
import matplotlib.pyplot as plt
import numpy as np
class Timer(object):
def __init__(self, name=None):
self.name = name
def __enter__(self):
self.tstart = time.time()
def __exit__(self, type, value, traceback):
if self.name:
print('[%s]' % self.name, end=... | python |
from datetime import datetime
import logging
from telegram import (
InlineKeyboardButton
)
from iot.devices.base import BaseDevice, BaseBroadlinkDevice
from iot.rooms import d_factory, bl_d_factory
from iot.utils.keyboard.base import (
CLOSE_INLINE_KEYBOARD_COMMAND,
InlineKeyboardMixin,
KeyboardCallBa... | python |
# -*- coding: utf-8 -*-
__author__ = """Larissa Triess"""
__email__ = "larissa@triess.eu"
from .compute import (
get_points_over_angles_and_label_statistics as get_angle_label_stats,
)
from .compute import (
get_points_over_distance_and_label_statistics as get_distance_label_stats,
)
__all__ = [
"get_dis... | python |
#Given an array of integers nums.
#A pair (i,j) is called good if nums[i] == nums[j] and i < j.
#Return the number of good pairs.
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
hash = {}
count = 0
for i in range(0,len(nums)):
for j in range(1,l... | python |
from django.http import HttpResponse
from django.utils import simplejson
from django.template.defaultfilters import slugify
from django.utils.encoding import force_unicode
from django.core.exceptions import ValidationError
import models
from scipy_central.submission.models import TagCreation
import datetime
from coll... | python |
from qupulse.hardware.setup import HardwareSetup, PlaybackChannel, MarkerChannel
from qupulse.pulses import PointPT, RepetitionPT, TablePT
#%%
""" Connect and setup to your AWG. Change awg_address to the address of your awg and awg_name to the name of
your AWGs manufacturer (Zürich Instruments: ZI, TaborElectronics:... | python |
from unittest import TestCase
from mandrill import InvalidKeyError
from mock import patch
from welcome_mailer import settings
from welcome_mailer.backends import email
from welcome_mailer.testing_utils import create_user, fake_user_ping
class TestBaseBackend(TestCase):
""" Test cases for the base email backend... | python |
from __future__ import print_function
from __future__ import division
import os
import sys
sys.path.append(os.getcwd())
import argparse
import json
import random
import warnings
import time
from collections import defaultdict, OrderedDict
from types import SimpleNamespace
import glog as log
import os.path as osp
from... | python |
#!/usr/bin/env python3
# Copyright (c) 2015, Göran Gustafsson. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# thi... | python |
from DeepJetCore.DataCollection import DataCollection
from pprint import pprint
dc = DataCollection()
dc.readFromFile('dc/dataCollection.dc')#/storage/9/dseith/DeepJet/deepCSV/results/../../Ntuples/Thu_135917_batch/dataCollections/deepCSV/train/dataCollection.dc')
#dc.readFromFile('/storage/9/dseith/DeepJet/deepCSV/re... | python |
from django.apps import AppConfig
class SessionConfig(AppConfig):
name = "ticketflix.session"
verbose_name = "Session"
| python |
try:
x = 3
print(x[1,2:3,4])
except:
print('it was supposed to fail')
| python |
"""
By Dr Jie Zheng -Q, NAOC
v1 2019-04-27
"""
import numpy as np
from..util import *
def date_conv():
pass
#function date_conv,date,type, BAD_DATE = bad_date
#;+
#; NAME:
#; DATE_CONV
#; PURPOSE:
#; Procedure to perform conversion of dates to one of three possible formats.
#;
#; EXPLA... | python |
from commandlib import Command, CommandError
from path import Path
import patoolib
import shutil
import os
def log(message):
print(message)
def extract_archive(filename, directory):
patoolib.extract_archive(filename, outdir=directory)
class DownloadError(Exception):
pass
def download_file(downloaded... | python |
from dataclasses import dataclass, field
from typing import Optional, List
@dataclass
class MessageEvent(object):
username: str
channel_name: str
text: Optional[str]
command: str = ""
args: List[str] = field(default_factory=list)
@dataclass
class ReactionEvent(object):
emoji: str
usernam... | python |
"""
To get the mdp parameters from sepsis simulator
@author: kingsleychang
"""
import numpy as np
import pandas as pd
import torch
from .sepsisSimDiabetes.DataGenerator import DataGenerator
from .sepsisSimDiabetes.MDP import MDP_DICT
from .sepsisSimDiabetes.State import State
from sklearn.model_selection import train... | python |
SAMPLE_MAP = load_samples('examples/sample_list.xlsx')
print(f'SAMPLE_MAP:\n{SAMPLE_MAP}')
| python |
#!/usr/bin/python3
"""
Given a word, you need to judge whether the usage of capitals in it is right or
not.
We define the usage of capitals in a word to be right when one of the following
cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only t... | python |
#!/usr/bin/env python2
# coding: utf-8
# MedSal Database
# Connection & Data query
#
# University of Applied Sciences of Lübeck
#
# Anna Androvitsanea
# anna.androvitsanea@th-luebeck.de
# This scripts includes the code for connecting and querying the data that have been uploaded to the MedSal's project [database](h... | python |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Filters module tests."""
from __future__ import absolute_import, print_function
... | python |
# Copyright (c) 2021 Emanuele Bellocchia
#
# 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,... | python |
from unittest.mock import patch
from django.test import TestCase
from store.models import product_image_file_path
class ModelTests(TestCase):
@patch('uuid.uuid4')
def test_product_file_name_uuid(self, mock_uuid):
"""Test that image is saved in the correct location"""
uuid = 'test-uuid'
... | python |
"""Tests in the tutorial."""
from fractions import Fraction
from dice_stats import Dice
def test_basic_dice_operations_ga():
"""Test basic dice operations."""
d12 = Dice.from_dice(12)
assert d12 + 3 == Dice.from_full(
{
4: Fraction(1, 12),
5: Fraction(1, 12),
... | python |
import propar
import time
import random
dut = propar.instrument('com1')
print()
print("Testing using propar @", propar.__file__)
print()
n = 10
all_parameters = dut.db.get_all_parameters()
bt = time.perf_counter()
for i in range(n):
for p in all_parameters:
dut.read_parameters([p])
et = time.perf_counter()... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pytest
from exoscale.api.compute import *
class TestComputeSSHKey:
def test_delete(self, exo, sshkey):
ssh_key = SSHKey._from_cs(exo.compute, sshkey(teardown=False))
ssh_key_name = ssh_key.name
ssh_key.delete()
assert ssh_key.... | python |
from jobmine.jobmine import JobMine # yes, I do find this quite funny
| python |
import requests
bad = []
good = []
proxy_file = open("proxies.txt", "r")
proxies = proxy_file.read()
proxies = proxies.splitlines()
for proxy in proxies:
try:
print("Checking: " + proxy)
resp = (requests.get("http://discord.com", proxies={"http":proxy, "https":proxy}, timeout=2))
good.append(pr... | python |
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dacodesjobs',
... | python |
import numpy as np
import plotly
import plotly.graph_objs as go
from HypeNet.Networks.FCNN_SoftmaxCE import FCNN_SoftmaxCE
from HypeNet.Core.loadData import loadFashionMnist
from HypeNet.Core.Trainer import Trainer
from HypeNet.Core.utils import *
import os
DIR = os.path.dirname(os.path.abspath(__file__)) + '/SavedNet... | python |
'''
Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol,
na ordem de colocação. Depois mostre:
a) Os 5 primeiros times.
b) Os últimos 4 colocados.
c) Times em ordem alfabética.
d) Em que posição está o time do Bragantino.
obs.: Usarei a tabela... | python |
import os
import sys
import json
import numpy as np
import torch
import pdb
from torch.autograd import Variable
from PIL import Image
import time
from opts import parse_opts
from model import generate_model
from mean import get_mean
def main(video_root,output_root):
start_time = time.time()
for class_name in o... | python |
from multipledispatch import dispatch
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from .colour import PAL, gen_PAL
sns.set()
# Remove stheno from this temporarily cus too many dependencies and not maintained, it depends on lab and wbml which is not easy to install.
a = ... | python |
class Pessoa:
def __init__(self, nome,idade):
self.nome = nome
self.idade = idade
p = Pessoa.__new__(Pessoa)
dados = {'nome':'Fábio','idade':25}
for k,y in dados.items():
setattr(p,k,y)
print(p.nome, p.idade)
| python |
"""
TransformDF2Numpy is a simple tool for quick transformation from pandas.DataFrame to numpy.array dataset,
containing some utilities such as re-transformation of new data,
minimal pre-processing, and access to variable information.
##################
### Overview ###
##################
+ Transform a trainin... | python |
import numpy as np
def gtd_bias(z, growth, alpha, b0, c):
b = c + (b0 - c) / growth**alpha
return b
def q_bias(k, Q, A):
return (1 + Q * k**2) / (1 + A * k)
def make_grids(k, z):
K = np.tile(k[:, None], z.size)
Z = np.tile(z[:, None], k.size).T
return K, Z
def q_model(k, z, Q, A):
# ... | python |
import os.path
from datetime import datetime
import click
from spoty import settings
from typing import List
import dateutil.parser
import numpy as np
from multiprocessing import Process, Lock, Queue, Value, Array
import sys
import time
from time import strftime
from time import gmtime
import string
THREADS_COUNT = 12... | python |
from atexit import register
from datetime import datetime
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
# from .models import Patient
from django.conf import settings
from django.contrib.auth.models import User
from django.urls import reverse
from patie... | python |
#!/home/miranda9/miniconda3/envs/automl-meta-learning/bin/python
from argparse import Namespace
import torch
import torch.nn as nn
import torch.optim as optim
# from transformers import Adafactor
# from transformers.optimization import AdafactorSchedule
import uutils
from uutils.torch_uu import get_layer_names_to_do... | python |
from typing import List
import logging
import orjson
from instauto.api.actions.structs.feed import FeedGet
from instauto.api.client import ApiClient
logging.basicConfig()
logger = logging.getLogger(__name__)
def get_feed(client: ApiClient, limit: int) -> List[dict]:
ret = []
obj = FeedGet()
while len(ret) <... | python |
from django.urls import path
from boards.views import home, board_topics, new_topic, topic_posts, reply_topic
app_name = "boards"
urlpatterns = [
path("", home, name="home"),
path("boards/<int:pk>/", board_topics, name="board_topics"),
path("boards/<int:pk>/new/", new_topic, name="new_topics"),
path... | python |
"""Used for tidying up any changes made during testing"""
import shutil
def test_tidy_up(): # pragma: no cover
"""Delete all files and folders created during testing"""
try:
shutil.rmtree('config')
except (FileNotFoundError, PermissionError):
pass
assert True
| python |
import cherrypy
def serve(app, port=5000, config={}) -> None:
"""
Serve Flask app with production settings
:param app: Flask application object
:param port: on which port to run
:param config: additional config dictionary
:return:
"""
cherrypy.tree.graft(app, '/')
# Set the config... | python |
import pytest
from cowdict import CowDict
base_dict = {
"foo1": "bar1",
"foo2": "bar2",
"foo3": "bar3",
"foo4": "bar4",
"foo5": "bar5",
}
base_dict_items = tuple(base_dict.items())
keys = ("foo1", "foo2", "foo3", "foo4", "foo5")
def test_same_unchanged():
cd = CowDict(base_dict)
for ke... | python |
"""Pythonic toolkit for web development."""
| python |
from ElevatorComponent import ElevatorComponent
from Messages import *
from time import sleep
class STATE(Enum):
"""
States used exclusively by Car Door
"""
OPENED = "opened"
OPENING = "opening"
CLOSED = "closed"
CLOSING = "closing"
class CarDoor(ElevatorComponent):
def __init__(... | python |
from flask import Flask
from flask import flash
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import InputRequir... | python |
"""*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... | python |
"""
Created on 30/9/2015
@author: victor
"""
import sys
from trajectory_comparison.T_Disp_super_batch_analysis import get_folders_for_analysis
import os
import glob
import numpy
def get_num_models(merged_pdb):
models = 0
handler = open(merged_pdb,"r")
for line in handler:
if "MODEL" == line[0:5]:
... | python |
# Generated by Django 3.2 on 2021-04-28 04:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('team', '0001_initial'),
('lead', '0001_initial'),
]
operations = [
migrations.AddField(
m... | python |
"""606 · Kth Largest Element II"""
class Solution:
"""
@param nums: an integer unsorted array
@param k: an integer from 1 to n
@return: the kth largest element
"""
def kthLargestElement2(self, nums, k):
# write your code here
import heapq
heap = []
for num in num... | python |
#!/usr/bin/env python3
import os
import re
import sys
print('please set min_sentence_len: ')
min_sentence_len = int(input())
outfile='namu_extracted_deleted.txt'
max_sentence_len = 9999
if len(sys.argv) >1:
max_sentence_len=int(sys.argv[2])
outfile = outfile.rsplit('.')[0] + '_' + str(min_sentence_len) + '.txt... | python |
""" Test brainspace.utils.parcellation """
import pytest
import numpy as np
from brainspace.utils import parcellation as parc
parametrize = pytest.mark.parametrize
testdata_consecutive = [
# default start_from = 0 and dtype
(np.array([1, 3, 3, 2, 2, 2], dtype=np.int),
{},
np.array([0, 2, 2, 1,... | python |
from dataset import RailData
import torch
from torch import optim
import torch.nn as nn
from torch.utils.data import DataLoader, random_split
from multiprocessing import cpu_count
import pathlib
from tqdm import tqdm
from wcid import NetSeq
import sys
from validation.metrics import calculate_metrics
import os
import co... | python |
import sys, os, traceback, itertools, tempfile
from os import walk
import json
import subprocess32 as subprocess
from pyparsing import *
from common import *
import problems
class InconsistentPredicateException(Exception):
pass
"""
check_solution receives json of that form
{
"task_id" : 8xyz_uuid,
"problem... | python |
# Time: O(n * 2^n)
# Space: O(n), longest possible path in tree, which is if all numbers are increasing.
# Given an integer array, your task is
# to find all the different possible increasing
# subsequences of the given array,
# and the length of an increasing subsequence should be at least 2 .
#
# Example:
# Input: ... | python |
from dataclasses import dataclass
from typing import List
from csw.Parameter import Parameter
@dataclass
class CommandResponse:
"""
Type of a response to a command (submit, oneway or validate).
Note that oneway and validate responses are limited to Accepted, Invalid or Locked.
"""
runId: str
... | python |
import datetime
import json
import os
import time
import requests
STIX_TAXII_URL = 'http://54.244.134.70/api'
DOMAINS_URL = STIX_TAXII_URL + '/domains'
IPS_URL = STIX_TAXII_URL + '/ips'
class api():
def getInfo(self, firstrun=True):
"""
Get a list of bad domains and IPs.
@param firstru... | python |
from srcs.parser.tokens.abstract_token import AbstractToken
class OpenBracketToken(AbstractToken):
pass
| python |
# coding=utf-8
from django import forms
class QueueSearchForm(forms.Form):
key = forms.CharField(label=u'KEY', required=False)
sender = forms.CharField(label=u'发件人', required=False)
recipients = forms.CharField(label=u'收件人', required=False)
senderip = forms.CharField(label=u'发件IP', required=False)
| python |
from .colors import Colors
import contextlib
import functools
import subprocess
TERMINAL_ENVIRONMENT_VAR = '_NC_TERMINAL_COLOR_COUNT'
SIZES = 256, 16, 8
def context(fg=None, bg=None, print=print, count=None):
return Context(count)(fg, bg, print)
@functools.lru_cache()
def color_count():
cmd = 'tput', 'colo... | python |
#!/usr/bin/env python3
import ctypes
import gc
import logging
import multiprocessing
import os
import queue
import threading
import time
import unittest
import ringbuffer
class SlotArrayTest(unittest.TestCase):
def setUp(self):
self.array = ringbuffer.SlotArray(slot_bytes=20, slot_count=10)
def te... | python |
#################################################
# (c) Copyright 2014 Hyojoon Kim
# All Rights Reserved
#
# email: deepwater82@gmail.com
#################################################
import os
from optparse import OptionParser
import python_api
import plot_lib
import sys
import pickle
def plot_the_data(the_map... | python |
'''
Application 1
factorial problem
n!=n*(n-1)!
'''
def factorial(n):
if n == 0:
return 1
elif n >=1:
return n *factorial(n-1) # here we apply the function itself recursion
#print(factorial(5))
'''
Application 2
Draw English Ruler
'''
def draw_line(tick_length,tick_label=''): # tick_leng... | python |
"""
Utils module.
This module contains simple utility classes and functions.
"""
import signal
import textwrap
from datetime import timedelta
from pathlib import Path
from typing import Any, Dict, List
import pkg_resources
import toml
from appdirs import user_config_dir
from loguru import logger
from aria2p.types i... | python |
# -*- coding: utf-8 -*-
"""
modules for universal fetcher that gives historical daily data and realtime data
for almost everything in the market
"""
import requests
import time
import datetime as dt
import pandas as pd
from bs4 import BeautifulSoup
from functools import wraps
from xalpha.info import fundinfo, mfundin... | python |
#!/usr/bin/env python3
def convert_to_int(rom_num, num = 0):
if len(rom_num) == 0:
return num
else:
if rom_num[0] == 'M':
return convert_to_int(rom_num[1:], num + 1000)
elif rom_num[:2] == 'CM':
return convert_to_int(rom_num[2:], num + 900)
elif rom_num[0]... | python |
INPUTS_ROOT_PATH = "./dragons_test_inputs/geminidr/gmos/longslit/" | python |
from BasicTypeAttr import BasicTypeAttr
class DecimalAttr(BasicTypeAttr):
# @@ 2003-01-14 ce: it would make more sense if the Float type spewed a
# SQL decimal type in response to having "precision" and "scale" attributes.
pass
| python |
# -*- coding: utf-8 -*-
from PIL import Image
from io import BytesIO
import numpy as np
import matplotlib.pyplot as plt
import os
import gmaps
import requests
import google_streetview.api
from src import settings
class GoogleImages(object):
"""Save pictures from google using the lat lon."""
def __init__(se... | python |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from src.customer import forms
from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
f... | python |
"""
owtf.settings
~~~~~~~~~~~~~
It contains all the owtf global configs.
"""
import os
import re
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
import yaml
HOME_DIR = os.path.expanduser("~")
OWTF_CONF = os.path.join(HOME_DIR, ".owtf")
ROOT_DIR = os.path.dirname(os.path.realpath(__file_... | python |
_base_ = [
'../_base_/models/fcn_hr18.py', '../_base_/datasets/vaihingen.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
]
evaluation = dict(interval=288, metric='mIoU', pre_eval=True, save_best='mIoU')
model = dict(decode_head=dict(num_classes=6))
| python |
# Generated by Django 3.0 on 2019-12-09 16:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0005_auto_20191208_2110'),
]
operations = [
migrations.RenameField(
model_name='game',
old_name='name',
new... | python |
from xml.dom.ext.reader.Sax import FromXmlFile
from xml.dom.NodeFilter import NodeFilter
from place import Place
class PlaceXml:
def __init__(self, filename, places):
root = FromXmlFile(filename)
walker = root.createTreeWalker(root.documentElement,
NodeFilte... | python |
def marks(code):
if '.' in code:
another(code[:code.index(',') - 1] + '!')
else:
another(code + '.')
def another(code2):
call(numbers(code2 + 'haha'))
marks('start1 ')
marks('start2 ')
def alphabet(code4):
if 1:
if 2:
return code4 + 'a'
else:
... | python |
#!/usr/bin/env python
import functools
import logging
from errno import ENOENT, EINVAL
from stat import S_IFDIR, S_IFLNK, S_IFREG
import _thread
from fuse import FUSE, FuseOSError, Operations
from zfs import datasets
from zfs import posix
from zfs.posix.attributes import PosixType
logger = logging.getLogger(__name... | python |
#
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this s... | python |
import os
from deepinterpolation.generic import JsonSaver, ClassLoader
import datetime
now = datetime.datetime.now()
run_uid = now.strftime("%Y_%m_%d_%H_%M")
generator_param = {}
inferrence_param = {}
steps_per_epoch = 10
generator_param["type"] = "generator"
generator_param["name"] = "FmriGenerator"
generator_param... | python |
# An Iterative DFS solution.
class Graph:
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def add_edge(self, v, w):
self.adj[v].append(w)
def DFS_util(self, s, visited):
stack = []
stack.append(s)
while (len(stack) != 0):
... | python |
import enum
import types as _types
import typing
from importlib import import_module
from .. import exc
_DEFAULT_BACKEND = None
class Backends(enum.Enum):
"""The backends of PyFLocker."""
CRYPTOGRAPHY = "cryptography"
CRYPTODOME = "cryptodome"
def load_algorithm(
name: str, backend: typing.Option... | python |
# generated by update to not change manually
from bungieapi.base import BaseClient, clean_query_value
from bungieapi.forge import forge
from bungieapi.generated.components.responses import booleanClientResponse
from bungieapi.generated.components.responses.social.friends import (
BungieFriendListClientResponse,
... | python |
#!/usr/bin/env python
from setuptools import setup, find_packages
from NwalaTextUtils import __version__
desc = """Collection of functions for processing text"""
setup(
name='NwalaTextUtils',
version=__version__,
description=desc,
long_description='See: https://github.com/oduwsdl/NwalaTextUtils/',
... | python |
#!/usr/bin/env python3
'''Bananagrams solver.'''
import argparse
import logging
import random
from collections import Counter
from itertools import chain
from string import ascii_lowercase
DOWN, ACROSS = 'down', 'across'
BLANK_CHAR = '.'
class WordGrid:
'''Represents a grid of letters and blanks.'''
def ... | python |
from cloupy.scraping import imgw
import pytest
import urllib.request
import urllib.error
def check_if_NOT_connected_to_the_internet(host='http://google.com'):
try:
urllib.request.urlopen(host)
return False
except urllib.error.URLError:
return True
@pytest.mark.filterwarnings("ignore:... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.