content stringlengths 5 1.05M |
|---|
import fcntl
import time
import os
class Mutex(object):
NetmaxLockI2C_handle = None
def __init__(self, debug = False):
self.mutex_debug = debug
self.NetmaxLockI2C_handle_filename = '/run/lock/NetmaxLockI2C'
self.NetmaxOverallMutex_filename = '/run/lock/NetmaxOS_overall_mutex'
... |
class Solution:
def maxResult(self, nums: List[int], k: int) -> int:
N = len(nums)
h = [(-nums[0],0)]
for i in range(1,N):
while h[0][1] < i - k:
heappop(h)
max_so_far = h[0][0]
heappush(h, (max_so_far - nums[i], i))
if i == N... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) Camille Scott, 2019
# File : signatures.py
# License: MIT
# Author : Camille Scott <[email protected]>
# Date : 15.10.2019
import decimal
import hashlib
import json
import typing
from boltons.iterutils import windowed_iter
import ijson
import pandas as ... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
# ActivitySim
# See full license in LICENSE.txt.
import logging
# import multiprocessing
import pandas as pd
import numpy as np
from activitysim.core import tracing
from activitysim.core import config
from activitysim.core import pipeline
from activitysim.core import simulate
from activitysim.core import inject
from... |
import webbrowser
class Movie():
def __init__(self, movie_title, movie_poster, movie_storyline,
movie_trailer_url):
'''Created a structure in order to store the movie details.
self :- examples or instancces of this class
This structure takes 4 string type parameters
... |
# -*- coding:utf-8 -*-
###
# @Author: Chris
# Created Date: 2020-01-02 21:16:28
# -----
# Last Modified: 2020-02-23 15:38:39
# Modified By: Chris
# -----
# Copyright (c) 2020
###
import os
import copy
import json
import random
import pandas as pd
from tqdm import tqdm
from loguru import logger
from script.utility imp... |
from direct.directnotify import DirectNotifyGlobal
from otp.distributed.DistributedDirectoryAI import DistributedDirectoryAI
from otp.distributed.OtpDoGlobals import *
from toontown.distributed.ToontownInternalRepository import ToontownInternalRepository
# TODO: Remove Astron dependence.
class ToontownUDRepository(... |
import requests
import os
import sys
from datetime import datetime
import logging
from bsnl import data
logger = logging.getLogger(__name__)
headers = data.common_headers
payload = {
'location': 'NOID',
'actionName': 'manual',
'_search': 'false',
'nd': '1588301203519',
'rows': '4',
'page': '1',
'sidx': '... |
"""Tracking utilities."""
from textwrap import dedent
from typing import Any, Callable, Mapping, Optional, cast
__all__ = [
"init_tracker",
]
def init_tracker(
config: Mapping[str, Any],
use_wandb: bool,
information: Mapping[str, Any],
wandb_name: Optional[str] = None,
wandb_group: Optional[s... |
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describ... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from inception import Inception3
from PIL import Image
use_gpu = True
dtype = torch.float32
device = torch.device('cuda') if use_gpu and torch.cuda.is_available() else torch.device('cpu')
print('Using device: ', device)
def load_m... |
import os
import json
from datetime import datetime
from django.views import View
from django.middleware import csrf
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from dj... |
import numpy
from tensorflow import keras
from keras.constraints import maxnorm
seed = 21
from __bazaPodatkov import bazaPodatkov
# Nalaganje baze podatkov slik
(X_train, y_train), (X_test, y_test), class_num = bazaPodatkov()
# Sestavljanje modela
# POKUSI spremenite plasti nevronske mreže, tako da dodaš, odvzameš ... |
import numpy as np
import tensorly as tl
from gnss_func.gnss_function import frequecy_domain_CA, correlator_bank_Q
from gnss_func.array import array_lin
from gnss_func.utils import normalise_columns
import pandas as pd
from sklearn.decomposition import TruncatedSVD
import sys
sys.path.extend(['/Users/araujo/Documents/... |
from pprint import pformat
from typing import Optional
import typer
from .config import get_skill_config
from .helpers import create_nlp
app = typer.Typer(help='Commands for working with NLP models')
# take name to find app path, otherwise default to cwd
@app.command()
def build(
name: Optional[str] = typer.Ar... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <[email protected]>
# Copyright (C) 2014-2017 Jesús Espino <[email protected]>
# Copyright (C) 2014-2017 David Barragán <[email protected]>
# Copyright (C) 2014-2017 Alejandro Alonso <[email protected]>
# This program is free software: you can r... |
#!/usr/bin/env python2
"""
builtin_test.py: Tests for builtin.py
"""
from __future__ import print_function
import unittest
import sys
from core import pyutil
from osh import split
from osh import builtin # module under test
class BuiltinTest(unittest.TestCase):
def testAppendParts(self):
# allow_escape is T... |
import base64
import json
import zlib
from .primitives import E, Entity
from .util import UP, RIGHT, DOWN, LEFT, Point
FORMAT_VERSION = '0'
MAP_VERSION = 0x1000330000
# Size of non-1x1 entities. Needed as blueprints specify location by center point.
# Each entry is (width, height), as per their layout with orien... |
class DuplicateKeyError(LookupError):
pass
class udict(dict):
def __setitem__(self, key, value):
if key in self:
raise DuplicateKeyError(key)
super().__setitem__(key, value)
class lazy:
def __init__(self, f):
self.f = f
def __get__(self, obj, cls):
ret = ... |
# nlg.py
# -*- coding: utf-8 -*-
import random
import datetime as dt
class NLG(object):
"""
Used to generate natural language. Most of these sections are hard coded. However, some use simpleNLG which is
used to string together verbs and nouns.
"""
def __init__(self):
# make random more random by seeding with ti... |
import logging
from egtsdebugger.egts import *
import socket
class RnisConnector:
"""Provide functional for connecting to RNIS"""
def __init__(self, host, port, num, dispatcher, file, **kwargs):
self.host = host
self.port = port
self.num = 0
self.max = num
self.did = di... |
from typing import Any
from .exceptions import PipelineError
from .initialize import GLib, Gst
def bus_call(_: Any, message: Gst.Message, loop: GLib.MainLoop) -> None:
"""Handle bus messages."""
if message.type == Gst.MessageType.EOS:
loop.quit()
elif message.type == Gst.MessageType.ERROR:
... |
import os,sys
import random
import UserList
def __ascending__(a,b):
if (a < b):
return -1
elif (a > b):
return 1
return 0
def __descending__(a,b):
if (a < b):
return 1
elif (a > b):
return -1
return 0
class GroupedSort(UserList.UserList):
def sortOn(self,ke... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
import six
from pygments.lexer import RegexLexer
from pygments.lexer import include
from pygments.token import Comment
from pygments.to... |
from .base import BaseProvider
from .process import ProcessProvider
__all__ = ["BaseProvider", "ProcessProvider"]
|
# 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
# d... |
###############################################################################
# Exercise
# Use the corpus module to explore austen-persuasion.txt.
# How many word tokens does this book have?
# How many word types?
###############################################################################
# import the corpus con... |
"""
This module contains the different algorithms that were evaluated for discovering log file templates (format strings).
Add additional template processors to this file.
Functions in this module should accept an iterable of LogLines.
Functions should return an iterable of Templates.
(see named tuple definition in m... |
""" Module to test processing root requests """
from unittest.mock import Mock, call
import pytest
from pinakes.main.approval.tests.factories import (
WorkflowFactory,
RequestFactory,
)
from pinakes.main.approval.services.process_root_request import (
ProcessRootRequest,
)
from pinakes.main.approval.tasks i... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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, ... |
#!/usr/bin/env python
import sys
from unittest import TestCase
from mock import Mock, patch
# Mock out the collectd module
sys.modules['collectd'] = Mock()
from plugin.nginx_plus_collectd import MetricSink, MetricRecord
class MetricSinkTest(TestCase):
def setUp(self):
self.sink = MetricSink()
sel... |
import os
import sys
def usage():
print "%s script.b" % sys.argv[0]
sys.exit(127)
class Machine:
def __init__(self, filename):
self.filename = filename
self.code = []
self.codePos = 0
self.tape = []
self.tapePos = 0
try:
with open(filename, ... |
from threading import *
def mymsgprint():
print("Display function ")
mythreadobj = current_thread()
print("The main thread name is",mythreadobj.getName(), end = '')
if mythreadobj.daemon:
print(" and is a daemon thread.")
else:
print(" and is a non-daemon thread.")
mychildt1 = Thread(target = mym... |
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2018, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import os
from pga... |
from setuptools import setup
setup(
name="keycloak_cli",
version='0.1',
py_modules=['keycloak_cli'],
install_requires=[
'Click',
'requests==2.23.0',
'PyYAML==5.3.1'
],
entry_points='''
[console_scripts]
keycloak_cli=keycloak_cli:cli
''',
) |
import cronex
import dateutil.parser
from django.http import JsonResponse
from django.db.models import Q
from django.utils import timezone
from django.views.decorators.gzip import gzip_page
from django.views.decorators.http import require_GET
from .lookup import query_can_map_static
from .models import DynamicAuth, ... |
# 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,... |
import secrets
import time
import csv
from selenium import webdriver
from common_steps import *
import os.path
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by im... |
from pydantic import BaseModel
from typing import Optional
class UserModel(BaseModel):
username: Optional[str] = ""
passcode: Optional[str] = ""
def is_valid(self):
error = []
if len(self.username) == 0:
error.append("Username cannot be blank")
if len(self.passcode) =... |
from office365.mail.item import Item
class Contact(Item):
"""User's contact."""
@property
def id(self):
return self.properties.get("id", None)
|
from django.test import TestCase
from mirrors.tests import create_mirror_url
class MirrorUrlTest(TestCase):
def setUp(self):
self.mirror_url = create_mirror_url()
def testAddressFamilies(self):
self.assertIsNotNone(self.mirror_url.address_families())
def testHostname(self):
... |
"""Utilities for creating a new resource state
"""
from ..constructs.workspace import Workspace
def create_resource_state_cli(args) -> None:
workspace = Workspace.instance()
create_resource_state(workspace)
def create_resource_state(workspace: Workspace) -> None:
workspace.get_backend().create_resour... |
''' *********************** USER-PARAMETERS OF BASE ESTIMATOR *********************** '''
from base_estimator_conf import * # noqa
K = 6 * (1e7, )
|
# TODO: this is no longer woring due to recent Reddit API changes
import time
import datetime
import json
import argparse
import praw
class RedditRetriever(object):
def __init__(self, _subreddit, _outfile, _start_date, _end_date, step=3600):
self.r = praw.Reddit(site_name='graphbrain', user_agent='Graph... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 10 22:29:29 2016
@author: nam
"""
import mmRef;
import utilities;
def prepareEvacEventFile(evacEventFileName,plfName,refEventName):
newRow = [];
for i in range(len(mmRef.EvacEventCols)):
newRow.append('');
newRow[mmRef.EvacEventCo... |
import numpy as np
import skimage.draw as skdraw
def vis_bbox(bbox,img,color=(255,0,0),modify=False,alpha=0.2):
im_h,im_w = img.shape[0:2]
x1,y1,x2,y2 = bbox
x1 = max(0,min(x1,im_w-1))
x2 = max(x1,min(x2,im_w-1))
y1 = max(0,min(y1,im_h-1))
y2 = max(y1,min(y2,im_h-1))
r = [y1,y1,y2,y2]
c... |
'''
simple trigger test case
@author: Huiyugeng
'''
import time
from task import task
from task import task_container
from task.trigger import simple_trigger
from example.jobs import time_job
container = task_container.TaskContainer()
def get_now():
time_stamp = time.time()
time_now = time.strftime("%Y... |
import os
import os.path as op
import logging
lgr = logging.getLogger(__name__)
# start with SLURM but extend past that #TODO
def queue_conversion(progname, queue, outdir, heuristic, dicoms, sid,
anon_cmd, converter, session,with_prov, bids):
# Rework this...
convertcmd = ' '.jo... |
from datetime import datetime
from turnips.ttime import TimePeriod
def datetime_to_timeperiod(timestamp: datetime) -> TimePeriod:
weekday = timestamp.isoweekday() % 7
if timestamp.hour < 8:
raise ValueError(
"This is way too early to log a price. If you meant to log a price for another "
... |
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
import matplotlib
import seaborn
import logging
import warnings
import scipy.stats as st
import statsmodels as sm
import statistics
def remove_static(df, unocc_st = '01:00:00', unocc_et = '04:00:00', quartile='75%'):
... |
import tweepy
import random
import configparser
from twitter_auth import twitter_api as api
# Read config files - default config and auth config
config = configparser.ConfigParser()
config.read('config.ini')
cfg = config['DEFAULT']
# Store id of the last mentioned tweet so that you don't double-reply
def update_last... |
from manta import *
dim = 2
particle_number = 2
res = 32
gs = vec3(res, res, res)
narrowBandWidth = 3
combineBandWidth = narrowBandWidth - 1
if dim == 2:
gs.z = 1
particleNumber = 3
s = Solver(name='Josue', gridSize=gs, dim=dim)
s.timestep = 0.5
minParticles = pow(2, dim)
flags = s.create(FlagGrid)
phi... |
import argparse
import logging
from api_proxy import api_proxy
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser('release tools')
subparsers = parser.add_subparsers(title='actions', dest='action')
register_command = subparsers.add_parser('register')
register_com... |
from dataloaders.dataset1d import EcgDataset1D
from dataloaders.dataset2d import EcgDataset2D
from models import models1d, models2d
from trainers.base_trainer import BaseTrainer
class Trainer2D(BaseTrainer):
def __init__(self, config):
super().__init__(config)
def _init_net(self):
model = get... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------... |
#!$HOME/github/my_venv/bin/python
# Open virtual environment
# -*- encoding: utf-8 -*-
# Script file to finalize score
import os
import shutil
import abjad
# from muda_score.segments import segment_01
# Paths
srcdir = "muda_score/segments"
dstdir = "muda_score/score"
# Runs "segment_0X.py" files (generate segments... |
from hask.lang import Eq
|
# -*- coding: utf-8 -*-
import helpers.boobankCommands as boobank
import helpers.objectTypes as types
from helpers.pretty import pretty_print
from helpers.configure import configure_backends, erase_credentials
from helpers.serializer import serialize
import webbrowser
import os
filename = '/root/src/weboobToFile/fi... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE
from __future__ import absolute_import
import json
import ctypes
import numpy
import numba
import awkward1.layout
import awkward1._util
import awkward1._connect._numba.arrayview
@numba.extending.typeof_impl.register(awkward1... |
"""ParallelGeneralGraph for parallel directed graphs (DiGraph) module"""
import logging
import sys
import warnings
from multiprocessing import Queue
import multiprocessing as mp
from multiprocessing.sharedctypes import RawArray
import ctypes
import numpy as np
import networkx as nx
from .utils import chunk_it
from .g... |
import operator
from typing import Type, Union, Callable, Any
from pydantic.utils import GetterDict
def bind_orm_fields(**fields: Union[str, Callable]) -> Type[GetterDict]:
"""GetterDict that binds ORM attributes to a Pydantic model.
A field is a key-value mapping where the key is the name of the
field ... |
from django.apps import AppConfig
class WiredriveConfig(AppConfig):
name = 'wiredrive'
|
# Copyright (c) 2011 - 2016, Zhenyu Wu, NEC Labs America 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
# ... |
#coding=utf-8
# 计算图像文件 '正方形面积占比计算.JPG'中粉红色区域占总正方形面积的比例
# 思路:蒙特卡洛算方法:
# 假设正方形边长为1
# 以正方形的左下角定点为直角坐标系圆点,记圆点为A(0,0)
# 正方形右下角的点为B(1,0)
# 正方形左上角的点为C(0,1)
# 正方形上面的那条边的中点为D(0.5,1)
# 记AD与BC两线的交点,即为粉红色三角形的定点为P
# 直线AD的方程式为 y = 2*x
# 直线BC的方程为 y = 1-x
# 粉红的区域的可行域为满足 y < 2*x 且 y < 1-x 且 y >0,其中x的范围为 0~1
# 正方形区域的可行域为 0<x<1;0<y<1
... |
import json
import logging
import uuid
from datetime import datetime
from datetime import time as dt_time
from datetime import timedelta
from functools import partial
from typing import Callable, Dict, Optional, Sequence, Tuple, List
import flask
import werkzeug.exceptions
from dateutil.tz import tz
from flask import ... |
#
# 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... |
""" Sensor platform for Alarm.com """
from datetime import timedelta
import logging
import async_timeout
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import (... |
import os
import json
readme = open('README.md', 'r')
contents = readme.read()
header = contents[:contents.find('##')+14]
readme.close()
readme = open('README.md', 'w')
readme.write(header)
url_stem = 'https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Finteresting-pr... |
import sys
def main():
name = input("Enter your name: ")
age = input("Enter your age: ")
print(f"The user {name} of age {age} is learning Python programming")
return None
if __name__ == "__main__":
sys.exit(main())
|
""" Utility module for validating camera feeds. """
from __future__ import absolute_import, division, print_function
from .textformatter import TextFormatter
from .feed import CameraFeed
def view_valid_camera_feeds():
"""
Shows all valid feed views, one after another. The next feed shows when the current is ... |
import math
import torch
from torch import Tensor
from torch import nn
from .concepts import Conceptizator
class EntropyLinear(nn.Module):
"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
"""
def __init__(self, in_features: int, out_features: int, n_classes: int, temperatur... |
# python
import logging
# django
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
from django.core.management.base import BaseCommand
# pyes
from pyes.exceptions import IndexAlreadyExistsException, ElasticSearchException
# django_elasticsearch
from django_elasticsearch.mapping imp... |
"""
Gán nhãn
"""
|
import unittest
from models import sources
Source=sources.Sources
class SourcesTest(unittest.TestCase):
'''
Test class to test the behavior of our souce class
'''
def setUp(self):
'''
setUp method that is run before every test
'''
self.new_source=Source('1234','KBC','b... |
# -*- coding: utf-8 -*-
"""
plugin
~~~~
plugin demo for sampling
:entity: sampling()
:invoked: trend/ref/label rendering
:distinct: true
:copyright: (c) 2017-2018 by Baidu, Inc.
:license: Apache, see LICENSE for more details.
"""
import numpy as np
from v1 import utils
logger = utils... |
class TempraryImageMixin:
@staticmethod
def temporary_image():
"""
임시 이미지 파일
"""
import tempfile
from PIL import Image
image = Image.new('RGB', (1, 1))
tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
image.save(tmp_file, 'jpeg')
tmp... |
import io
import mimetypes
import os
import unittest
from pyramid import testing
class TestResponse(unittest.TestCase):
def _getTargetClass(self):
from pyramid.response import Response
return Response
def test_implements_IResponse(self):
from pyramid.interfaces import IResponse
... |
from topology import node, edge
|
import pandas as pd
read_file = pd.read_csv (r'Path where the Text file is stored\File name.txt')
read_file.to_csv (r'Path where the CSV will be saved\File name.csv', index=None) |
#
from .plugin import EdgeLBPlugin
__all__ = ["EdgeLBPlugin"]
|
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2019 Dr. Helder Marchetto
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... |
#!/usr/bin/env python
# Copyright (c) 2021 Samsung Electronics Co., Ltd. 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... |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
# i think a general way to approach this is kadanes algorithm
# sum values as we iterate over from 1 -> len(nums) - 1, if it isn't negative
for i in range(1, len(nums)):
if nums[i - 1] > 0:
... |
# coding=utf-8
# Copyright 2021 RLDSCreator 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/LICENSE-2.0
#
# Unless required by applicable law o... |
import splinter
import time
import random
import requests
import re
from bs4 import BeautifulSoup
from splinter import Browser
from selenium import webdriver
from pymongo import MongoClient
class DataNode(object):
"""docstring for DataNode"""
def __init__(self, arg):
super(DataNode, self).__init__()
self.arg = a... |
"""
This script plots the printout file that contains the convergence history
of the Jacobi-Davidson eigenvalue solver
"""
import enum
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
import matplotlib.pyplot as plt
import os
import argparse
import re
class JDHistoryPlotter:
def __init__(s... |
def success(request_type, properties={}):
return {
"success": True,
"type": request_type,
**properties
}
def fail(request_type, reason, properties={}):
return {
"success": False,
"reason": reason,
"type": request_type,
**properties
} |
from django.db import models
from django.contrib.auth.models import User
class Image(models.Model):
"""A model of a Image."""
caption = models.TextField()
media = models.ImageField(upload_to='uploads/%Y/%m/%d/')
user = models.ForeignKey(User, on_delete=models.CASCADE)
# if published_on is null, thi... |
from lxml import etree
elemento = etree.Element("Teste")
elemento.text = "Este é o texto da tag Teste"
print(elemento.tag)
print()
root = etree.Element("clientes")
sub = etree.SubElement(root,"cliente")
print(root.tag)
print(sub.tag)
print()
root = etree.Element("clientes")
sub = etree.Element("cli... |
from flask import Flask
from database import register_db
from flask_bootstrap import Bootstrap
from flask_debug import Debug
from nav import nav
from bundle import apply_assets
app = Flask(__name__)
app.config.from_object('config.DevConfig')
register_db(app)
nav.init_app(app)
Bootstrap(app)
apply_assets(app)
Debug(app... |
"""Preset views."""
|
from week_7.data.io import load_tweets
from utils.utils import get_data_path
import os.path
import pickle
tweets = load_tweets()
# Merge sentence lists.
for tweet in tweets:
text_concat = list()
if tweet.text_cleaned is not None:
for sentence in tweet.text_cleaned:
text_concat.extend(sente... |
import numpy as np
import matplotlib
matplotlib.use("QT5Agg")
import qcodes as qc
from qcodes.instrument.parameter import ArrayParameter, MultiParameter
from qcodes.tests.instrument_mocks import DummyInstrument
from qcodes.utils.wrappers import do1d, do2d, do1dDiagonal, init
from qcodes.plots.qcmatplotlib_viewer_widget... |
from keras import backend as K
from keras.models import load_model
from keras.optimizers import Adam
import numpy as np
from matplotlib import pyplot as plt
from models.keras_ssd300 import ssd_300
from keras_loss_function.keras_ssd_loss import SSDLoss
from keras_layers.keras_layer_AnchorBoxes import AnchorBoxes
from k... |
# from napari_clio_test import napari_experimental_provide_dock_widget
# add your tests here... |
#!/usr/bin/env python3
#
# Change json output to be human-readable
import argparse
import csv
import json
import re
import os
import sys
csv.field_size_limit(sys.maxsize)
def int_of_label(s):
total = 0
for c in s:
total += ord(c) - ord('a') + 1
return total
def label_of_int(i):
s = ""
max... |
n = int(input().strip())
c = [int(x) for x in input().strip().split(' ')]
count_ = []
socks = list(set(c))
for j in socks:
count_.append(c.count(j))
ans = 0
for k in count_:
ans += k//2
print(ans)
|
# -*- coding: utf-8 -*-
""" vsphere datastore expoter for prometheus init file """
from __future__ import absolute_import, unicode_literals, print_function
import os
import traceback
import logging
import logging.config
from flask import Flask
from vsphere_ds_exporter.views import metrics
from vsphere_ds_exporter.tes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.