text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
"""
Visualization
"""
# import project config.py
import semseg_vaihingen.config as cfg
|
from setuptools import setup, find_packages
setup(
name='django-ckeditor-fc',
version='1.1',
description='Django admin CKEditor integration.',
long_description=open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst',
... |
def examples_queue(data_sources, data_fields_to_features, training,
data_items_to_decoders=None, data_items_to_decode=None):
"""Contruct a queue of training or evaluation examples.
This function will create a reader from files given by data_sources,
then enqueue the tf.Examples from these file... |
"""
Register Hypothesis strategies for Pydantic custom types.
This enables fully-automatic generation of test data for most Pydantic classes.
Note that this module has *no* runtime impact on Pydantic itself; instead it
is registered as a setuptools entry point and Hypothesis will import it if
Pydantic is installed. ... |
import numpy as np
import sys
import os
num1 = 0
num0 = 0
def Timeout(data, threshold):
return_value = []
global num0
global num1
for x in data:
if x <= threshold:
return_value.append(1)
num1 += 1
else:
num0 += 1
return_value.append(0)
... |
from setuptools import setup, find_packages
from clickfig import version
try:
with open("requirements.txt") as f:
requirements = [x.strip() for x in f if x.strip()]
except IOError as e:
requirements = []
print("requirements = {}".format(requirements))
setup(
name='clickfig',
version=version.__v... |
import tensorflow as tf
import tensorflow.keras.layers as layers
from .transformer import VALID_CHARS
class InputLayer(layers.Layer):
def __init__(self, num_class, **kwargs):
super(InputLayer, self).__init__(**kwargs)
self.num_class = num_class
self.reshape_layer = layers.Reshape((-1... |
import scipy.ndimage as ndimg
import numpy as np
from numba import jit
from imagepy.core.engine import Filter
from imagepy.ipyalg import find_maximum, ridge, stair, isoline, watershed
from imagepy.core.roi import PointRoi
#from skimage.morphology import watershed, disk
from skimage.filters import rank
from skimage.filt... |
import torch.nn as nn
from Decoder import Decoder
from Encoder import Encoder
class Generator(nn.Module):
def __init__(self, model_dict=None):
super(Generator, self).__init__()
self.encoder = Encoder(model_dict)
self.decoder = Decoder()
def forward(self, xb):
xb = self.encode... |
# -*- coding: utf8 -*-
########################################################################################
# This file is part of exhale. Copyright (c) 2017-2021, Stephen McDowell. #
# Full BSD 3-Clause license available here: #
# ... |
import environ
ROOT_DIR = (
environ.Path(__file__) - 3
) # (django_security_headers_example/config/settings/base.py - 3 =
# django_security_headers_example/)
APPS_DIR = ROOT_DIR.path("django_security_headers_example")
# Load operating system environment variables and then prepare to use them
env = environ.Env()
... |
#!/usr/bin/env python3
"""
Data Cleaning and Utility functions for CICIDS 2017 data
"""
# Load the top modules that are used in multiple places
import numpy as np
import pandas as pd
# Some global variables to drive the script
# The indir should match the location of the data
# The outdir should be the desired locat... |
import komand
from .schema import ExpandAllInput, ExpandAllOutput
# Custom imports below
import re
from komand_url_expander.util import util
class ExpandAll(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='expand_all',
description='Expand all... |
"""
This is called to populate stats about this database, for demo purposes.
Stats are self-contained in the "opsdb.stats" table, which holds the name
of the statistic, the value and also the SQL statement for generting the
statistic value.
These can actually be any value generated by a SQL command, and assigned
into... |
from django.db import models
from datetime import datetime
# Create your models here.
class Action(models.Model):
name = models.CharField(max_length=20)
create_date = models.DateTimeField(default= datetime.now())
CHOICES = [
("C", "Completed")
,("N", "Not Completed"),
("I", "In Pro... |
# 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 u... |
#!/usr/bin/env python
## @ BuildUtility.py
# Build bootloader main script
#
# Copyright (c) 2016 - 2021, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
##
# Import Modules
#
import os
import sys
import re
import glob
import struct
import shutil
import ... |
"""Image ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from common.ops import shape_ops
def center_crop(image, landmark, size):
"""Crop labeled image."""
image_size = image.shape[-2].value
if imag... |
from rest_framework.test import APITestCase
from django.core.management import call_command
from django.core.management.base import CommandError
class BaseTestCase(APITestCase):
def init_data(self):
self.url = '/api/post/'
self.good_url = '/api/post/1'
self.good_data = {"title": "Test", ... |
import json
from mqfactory.message import Message
def serialize(msg):
msg.payload = json.dumps({
"tags" : msg.tags,
"payload": msg.payload
}, sort_keys=True)
def unserialize(msg):
raw = json.loads(msg.payload)
msg.tags = raw["tags"] if "tags" in raw else {}
msg.payload = raw["payload"] if "... |
#!/usr/bin/env python
# Copyright (c) 2011-2020, wradlib developers.
# Distributed under the MIT License. See LICENSE.txt for more info.
"""
Gage adjustment
^^^^^^^^^^^^^^^
Concept
-------
The objective of this module is the adjustment of radar-based rainfall
estimates by rain gage observations. However, this module ... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from codecs import open # To use a consistent encoding
from os import path
from setuptools import setup
HERE = path.dirname(path.abspath(__file__))
# Get version info
ABOUT = {}
with open(path.join(HE... |
"""
Loads the SSD model from https://github.com/qfgaohao/pytorch-ssd.
"""
from ssd_pytorch.vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd, create_mobilenetv1_ssd_predictor
from ssd_pytorch.vision.ssd.mobilenet_v2_ssd_lite import create_mobilenetv2_ssd_lite, create_mobilenetv2_ssd_lite_predictor
from ssd_p... |
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
from hypothesis import given, settings
import numpy as np
class TestIntegralImageOps(serial.SerializedTestCase):
@given(batch_s... |
# coding: utf-8
import json
import fancyimpute
import numpy as np
import pandas as pd
X = []
Y = []
Z = []
for ctx in open('json/json'):
z = json.loads(ctx)['label']
ctx = json.loads(ctx)['forward']
x = np.asarray(ctx['values'])
y = np.asarray(ctx['evals'])
x_mask = np.asarray(ctx['masks']).asty... |
import boto3
import certifi
import json
import os
from aws_requests_auth.aws_auth import AWSRequestsAuth
from elasticsearch import Elasticsearch, RequestsHttpConnection
import logging
# Log level
logging.basicConfig()
logger = logging.getLogger()
# Parameters
REGION = os.getenv('AWS_REGION')
esendpoint = os.environ['... |
import os.path
import subprocess
import sys
def run_except_on_windows(commandline, env=None):
if os.name != "nt" and sys.platform != "cygwin":
# Strange failures on windows/cygin/mingw
subprocess.check_call(commandline, env=env, shell=True)
print(" Finished running: " + commandline)
testn... |
#!/usr/bin/env python3
import sys
import os
import shutil
def _copy_artifacts_to_results():
os.makedirs(paths.relative_path("result"), exist_ok = True)
gen.copy_root_ca_certificate_and_key_pair()
gen.copy_leaf_certificate_and_key_pair("server")
gen.copy_leaf_certificate_and_key_pair("client")
def gen... |
import os
from collections import Counter
from pathlib import Path
from typing import List, Optional, Tuple
import numpy as np
from tqdm import tqdm
from .filter import get_agents_slice_from_frames, get_frames_slice_from_scenes, get_tl_faces_slice_from_frames
from .zarr_dataset import ChunkedDataset
GIGABYTE = 1 * 1... |
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2018 AT&T Intellectual Property
#
# 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 2019 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
from __future__ import annotations
_shared_docs: dict[str, str] = {}
_shared_docs[
"aggregate"
] = """
Aggregate using one or more operations over the specified axis.
Parameters
----------
func : function, str, list or dict
Function to use for aggregating the data. If a function, must either
work when pa... |
#
# 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 writing, software
# distributed under ... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'plecothoughts_33879.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
... |
#!/usr/bin/env python
def main():
c = Cat("CoolCat")
d = Dog("Tank")
animals = []
animals.append(c)
animals.append(d)
for animal in animals:
animal.speak()
class Animal(object):
sound = "...silence"
name = "Animal?"
def speak(self):
print(self.sound)
class Dog... |
'''
A few checks to make sure the environment is sane
'''
# Original Author: Jeff Schroeder <jeffschroeder@computer.org>
# Import python libs
import os
import re
import sys
import stat
import socket
import getpass
import logging
# Import third party libs
if sys.platform.startswith('win'):
import win32file
else:
... |
from drf_yasg import openapi
from drf_yasg.inspectors import FieldInspector, NotHandled, PaginatorInspector, FilterInspector, SwaggerAutoSchema
from drf_yasg.utils import get_serializer_ref_name
from rest_framework.fields import ChoiceField
from rest_framework.relations import ManyRelatedField
from taggit_serializer.se... |
import os, sys
import numpy as np
import pandas as pd
import pyddem.tdem_tools as tt
from glob import glob
from collections import OrderedDict
fn_o1 = '/home/atom/ongoing/work_worldwide/vol/final/subreg_multann_O1_err.csv'
out_csv = '/home/atom/ongoing/work_worldwide/tables/final/ED_Table_3.csv'
df_in = pd.read_csv(... |
import unittest
from unittest import mock
import dbt.adapters
import dbt.flags as flags
import dbt.utils
from dbt.adapters.redshift import RedshiftAdapter
from dbt.exceptions import FailedToConnectException
from dbt.logger import GLOBAL_LOGGER as logger # noqa
from .utils import config_from_parts_or_dicts, mock_con... |
from .clinic_base import ClinicBase
from app.core.singleton import Singleton
class Dentistry(Singleton, ClinicBase):
id_clinic = 2
queue = []
def __init__(self) -> None:
super().__init__()
|
from django.contrib import admin
from django.urls import path
from hospital import views
from django.contrib.auth.views import LoginView, LogoutView
# -------------FOR ADMIN RELATED URLS
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.home_view, name=""),
path("aboutus", views.aboutus_view... |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2020 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... |
"""
sentry.tasks.cleanup
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from celery.task import task
@task(ignore_result=True)
def cleanup(days=30, logger=None, site=None, server=None, level=None,
project=... |
"""
GhostNet for ImageNet-1K, implemented in TensorFlow.
Original paper: 'GhostNet: More Features from Cheap Operations,' https://arxiv.org/abs/1911.11907.
"""
__all__ = ['GhostNet', 'ghostnet']
import os
import math
import tensorflow as tf
import tensorflow.keras.layers as nn
from .common import round_channe... |
import numpy as np
from napari.components import ViewerModel
base_colormaps = ['cyan', 'yellow', 'magenta', 'red', 'green', 'blue']
def test_multichannel():
"""Test adding multichannel image."""
viewer = ViewerModel()
np.random.seed(0)
data = np.random.random((15, 10, 5))
viewer.add_multichannel(... |
"""
$url watchstadium.com
$type live, vod
"""
import logging
import re
from streamlink.plugin import Plugin, PluginError, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.hls import HLSStream
from streamlink.utils.url import update_qsd
log = logging.getLogger(__name__)
@pluginmatcher... |
# 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 u... |
class Choices:
@classmethod
def choices(cls):
d = cls.__dict__
return [d[item] for item in d.keys() if not item.startswith("__")]
class ContestType:
PUBLIC_CONTEST = "Public"
PASSWORD_PROTECTED_CONTEST = "Password Protected"
EXCLUSIVE_CONTEST = 'Exclusive'
class ContestStatus:
... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
In addition to the remote_call mechanism implemented in CommBase:
- Implements _wait_reply, so blocking calls can be made.
"""
import os
import time
import threa... |
def hitung_gaji():
nama=(input("Masukan Nama Anda:"))
gol=(input("masukan golongan:"))
if gol == "1":
gaji=1000000
tunjangan=250000
total=gaji+tunjangan
print(f"Total gaji yang anda terima {total}")
elif gol == "2":
gaji=2000000
tunjangan=500000
... |
#!/usr/bin/env python
# encoding: utf-8
"""
:author: lixing
:file: config.py.py
:time: 2020/5/17 20:46
:file_desc:
"""
import os
SECRET_KEY = b'Kg\x93(p\xc8\x84\xdbk\xc9\x8e\x8f\x04\xf3(\xf3'
# AVATAR_PATH = './static/images/upload/avatars'
ALLOWED_IMAGE_EXTENSIONS = {'jpg', 'png', 'jpeg'}
AVATAR_PATH = os.path.jo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from scrapy.item import Item, Field
class Artist(Item):
name = Field()
class Tab(Item):
name = Field() |
import bs4
import csv
import piexif
import math
import pathlib
import glob
import pandas as pd
from datetime import datetime
from fractions import Fraction
from dateutil import tz
# sets UTC
JST = tz.gettz('Asia/Tokyo')
UTC = tz.gettz("UTC")
# sets type alias
NumSexagesimal = tuple[int, int, float, str]
LocSexagesima... |
import pyrealsense2 as rs
import numpy as np
import cv2
import time
class realSenseStream():
def __init__(self, path = './', w = 1920, h = 1080):
super().__init__()
self.config = rs.config() # Assign to realsense configuration
self.pipeline = rs.pipeline() # Assign to realsense pipeline
... |
##############################################################################
#The MIT License (MIT)
#
#Copyright (c) 2018 IBM Corporation, Carnegie Mellon University and others
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "So... |
"""
The rust_toolchain rule definition and implementation.
"""
def _rust_toolchain_impl(ctx):
compilation_mode_opts = {}
for k, v in ctx.attr.opt_level.items():
if not k in ctx.attr.debug_info:
fail("Compilation mode {} is not defined in debug_info but is defined opt_level".format(k))
... |
import json
import os
from typing import List
from piepline.utils.fsm import FileStructManager
class FoldedTrainer:
def __init__(self, folds: List[str]):
self._folds = folds
def run(self, init_trainer: callable, model_name: str, out_dir: str):
for fold_num in range(len(self._folds)):
... |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 8
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class NfsSettingsGlobalSettings(... |
# ball class
# TODO: crate ball and make it move
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.shape("circle")
self.penup()
self.x_move = 10
self.y_move = 10
self.move_speed = 0.1
def mov... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'LinkResult.content_type'
db.add_column(u'pecker_linkresul... |
import tweepy
import time
auth = tweepy.OAuthHandler('GZWVNKLCJ6PBzt8rql1kqWGdY', 'd7E1ab0nibe8nS35M4bHien7R2NhkEeaBX0QtRdwlItmqrZ0yz')
auth.set_access_token('632288942-YPTl36mulk5XRyGcriPFeGlz0fAihxmSFoudTPaQ',
'KXE87VPj1278zBmVuh04ELDoX5S3DrwkQYo0GpUTNnGOD')
api = tweepy.API(auth)
user = api.m... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys, getopt, datetime, codecs
if sys.version_info[0] < 3:
import got
else:
import got3 as got
def main(argv):
#print (argv)
if len(argv) == 0:
print('You must pass some parameters. Use \"-h\" to help.')
return
if len(argv) == 1 an... |
v1 = float(input('altura: '))
v2 = float(input('largura: '))
r = v1 * v2
t = r / 2
print(f' A área é: {r:>11}m²\n Litro de tinta: {t:>5}l')
|
#from coffea.nanoaod import NanoEvents
import awkward
#import awkward1
import uproot_methods
import pandas as pd
import numpy as np
#from coffea.btag_tools import BTagScaleFactor
def nanoObject(tree, prefix, branches, from_cartesian = False):
#branches = set(k.decode('ascii') for k in tree.keys() if k.decode('asc... |
import click
from mvs import run_mvs_reconstruction
from tqdm.auto import tqdm
from sfm_utils import is_correct_scan_id
@click.command()
@click.argument("scan_id_start", type=int, required=True)
@click.argument("scan_id_end", type=int, required=True)
@click.option(
"-u",
"--ultra",
"ultra",
type=bool... |
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors.
#
# 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/LI... |
"""
The class which stores blocks in a linkedlist fashion.
This class is meant to be used staticly.
"""
import time
from typing import List
from blockchain.Block import Block
class Blockchain:
# The difficulty of the proof-of-work algorithm.
difficulty = 2
unconfirmed_transactions: List
chain: List... |
import unittest
from bdebld.meta import buildflagsparser
class TestBuildFlagsParser(unittest.TestCase):
def setUp(self):
self.parser = buildflagsparser.BuildFlagsParser('-Wl,-Bdynamic',
'-Wl,-Bstatic',
... |
import os
import sys
import random
import pdb
import string
import struct
import logging
import threading
import time
import copy
import numpy as np
from sklearn import preprocessing
from milvus import Milvus, DataType
port = 19530
epsilon = 0.000001
namespace = "milvus"
default_flush_interval = 1
big_flush_interval ... |
# Copyright (c) 2021 Hieu Le and the UCI Networking Group
# <https://athinagroup.eng.uci.edu>.
#
# 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/LICE... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Movie)
admin.site.register(Review) |
"""personal URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
# -*- coding: utf-8 -*-
import asyncio
import threading
import time
from qqbot.core.util import logging
logger = logging.getLogger()
class SessionPool:
"""
SessionPool主要支持session的重连,可以根据session的状态动态设置是否需要进行重连操作
这里通过设置session_id=""空则任务session需要重连
"""
def __init__(self, max_async, session_manager... |
import sys
sys.path.append("../src")
sys.path.append("src/")
import unittest
import numpy as np
from tools import *
from gdft import *
from correlations import *
from sequencefinder import *
GDFT_MAT = np.array([[1, -1], [-1, -1]], dtype=np.complex128)
class TestSequenceFinder(unittest.TestCase):
def setUp(self)... |
# Copyright 2018 Jet.com
#
# 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 writing, sof... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "yslam_1"
PROJECT_SPACE_DIR = "/usr/lo... |
import json
import configparser
import json
import requests
def flatten(data):
flattened = {}
for key, value in data.items():
if isinstance(value, dict):
temp = flatten(value)
for k, v in temp.items():
flattened[key + '.' + k] = v
else:
flatt... |
# 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.
"""
Base classes for various fairseq models.
"""
import logging
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn a... |
"""Bootstrap themed components for use in Plotly Dash"""
import os
import sys
from dash_bootstrap_components import themes # noqa
from dash_bootstrap_components import _components
from dash_bootstrap_components._components import * # noqa
from dash_bootstrap_components._table import _generate_table_from_df
from dash... |
from django.test import TestCase
from datacash import models
XML_RESPONSE = """<?xml version="1.0"?>
<RealTimeResponse xmlns="T3MCallback">
<aggregator_identifier/>
<merchant_identifier>5567</merchant_identifier>
<merchant_order_ref>12345</merchant_order_ref>
<t3m_id>333333333</t3m_id>
<score>%(sc... |
from rest_framework.permissions import BasePermission
from environments.models import Environment
from projects.models import Project
ACTION_PERMISSIONS_MAP = {
"retrieve": "VIEW_PROJECT",
"destroy": "DELETE_FEATURE",
"list": "VIEW_PROJECT",
"create": "CREATE_FEATURE",
}
class FeaturePermissions(Bas... |
"""
Functions and data to use for formatting Pathoscope and NuVs analysis document. Formatted documents are destined for
API responses or CSV/Excel formatted file downloads.
"""
import asyncio
import csv
import io
import json
import statistics
from collections import defaultdict
import aiofiles
import openpyxl.styles... |
import pygame
from panels import *
class Ui_button:
def __init__(self, x, y, w, h, col_theme, text):
self.rect = pygame.Rect(x, y, w, h)
self.text = text
self.col = col_theme
def update(self):
pass
class Split:
def __init__(self, editor, panel1, panel2):
self.p... |
import mysql.connector
# cnx = mysql.connector.connect('root','xx74281','192.168.0.50','gestor')
|
# -*- coding: utf-8 -*-
from datetime import date
from unittest import TestCase
from mock import patch
import six
from .helpers import example_file
from popolo_data.importer import Popolo
EXAMPLE_EVENT_JSON = b'''
{
"events": [
{
"classification": "legislative period",
"end_dat... |
from wikiwho_wrapper import WikiWhoAPI, WikiWhoPickleAPI, WikiWho
# def test_wikiwhopickle_all_content_by_id():
# """Tests an API call to get a all content of a page by id"""
# api = WikiWhoAPI()
# df = api.all_content(2161298)
# ww_pickle_api = WikiWhoPickleAPI(pickle_path='pickles', lng='en')
# ... |
# Copyright (C) 2018 Google 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 in writing, ... |
import os
from shutil import rmtree, copy
from tempfile import gettempdir
from pathlib import Path
import pytest
from pew._utils import invoke_pew as invoke
@pytest.yield_fixture(scope='session')
def workon_home():
tmpdir = os.environ.get('TMPDIR', gettempdir())
os.environ['WORKON_HOME'] = str(Path(tmpdir) ... |
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
first_name = forms.CharField(max_length=32)
last_name = forms.CharField(max_length=32)
email = forms.EmailField(max_length=64)
class Meta:
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime, timedelta
from unittest import TestCase, skipIf
try:
import pytz
except ImportError:
pytz = None
from django import forms
from django.conf import settings
from django.contrib import admin
from django.contrib.admin ... |
from robolearn.torch.core import PyTorchModule
from robolearn.models.policies import ExplorationPolicy
class MultiPolicySelector(PyTorchModule, ExplorationPolicy):
def __init__(self, multipolicy, idx):
self.save_init_params(locals())
super(MultiPolicySelector, self).__init__()
ExplorationP... |
#!/usr/bin/env python3
# Copyright (c) 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Create a blockchain cache.
Creating a cache of the blockchain speeds up test execution when running
mu... |
from sklearn.base import BaseEstimator, clone
from active_learning.problem import ActiveLearningProblem
from active_learning.query_strats.base import IndividualScoreQueryStrategy, ModelBasedQueryStrategy
from typing import List
import numpy as np
def _lookahead(points: np.ndarray, model: BaseEstimator,
... |
import os
from datetime import timedelta
import asyncio
import platform
import functools
import time
import cProfile
import io
import pstats
import shelve
import threading
import datetime
import dateutil.parser
import yaml
import copy
import json
import inspect
from functools import wraps
from appdaemon.version import ... |
from setuptools import setup, find_packages
setup(name="CS5173-ManifoldLearning", version="1.0", packages=find_packages())
|
"""
Classes from the 'SymptomDiagnosticReporter' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
SDRDiagnosticReporter = _Class("SDRDiagnos... |
"""
Desafio 010
Crie um programa que leia quanto dinheiro uma pessoa tem na carteira
e mostre quantos Dólares ela pode comprar.
Considere
US$1.00 = 3.27
"""
carteira = float(input("Quantos tem na carteira? R$"))
dolar = carteira / 3.27
print(f'Com R${carteira:.2f} você pode comprar US${dolar:.2f}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.