content stringlengths 5 1.05M |
|---|
from export import ShpResponder
from upload import upload |
"""
Get/Watch all information of a single key in the Configuration Database.
Usage:
ska-sdp (get|watch) [options] <key>
ska-sdp (get|watch) [options] pb <pb_id>
ska-sdp (get|watch) (-h|--help)
Arguments:
<key> Key within the Config DB.
To get the list of all keys:
... |
# -*- coding: utf-8 -*-
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}#, include_files": ['player.png']
setup( name = "CSCI-413-Project-Version-1.0",
version = "1.0"... |
from radical.entk.utils.init_transition import transition
import pika
from radical.entk import Task, Stage, Pipeline
import radical.utils as ru
import os
from threading import Thread
import json
from radical.entk import states
MLAB = 'mongodb://entk:entk123@ds143511.mlab.com:43511/entk_0_7_4_release'
def func(obj, ob... |
import uvicorn
from src.web.app.factory import create_app
main_app = create_app()
if __name__ in "__main__":
uvicorn.run(main_app, host="0.0.0.0", port=8080)
|
import argparse
import sys
import pycopier
def coerceArgsToArgparseCompatible(args):
'''
Turns /MT:<num> into /MT <num> ... without the user knowing.
This is to keep compatibility with robocopy
'''
args = list(args)
for idx, arg in enumerate(args):
if arg.startswith('/MT:') and arg... |
import psutil
import re
#User inputs name of process they want to try and use.
#checks that string against a list of processes running.
#If theres a match return it.
PROCESS_LIST = []
PPID_LIST = []
PROCESSES_REMAINING_STR = input("Enter how many processes you want to monitor? (1-4): ")
while int(PROCESSES_REMAINI... |
# Copyright 2019 the ProGraML authors.
#
# Contact Chris Cummins <chrisc.101@gmail.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
#
# ... |
from pathlib import Path
import pytest
from pipeline.recon import tool_paths, defaults, web_ports, top_tcp_ports, top_udp_ports
def test_tool_paths_absolute():
for path in tool_paths.values():
assert Path(path).is_absolute()
@pytest.mark.parametrize("test_input", ["database-dir", "tools-dir", "gobuste... |
"""Throttling serializers
Serializers convert data models to Python datatypes. However, Django REST Framework cannot handle relations between fields automatically.
'SlugRelatedField' objects are needed to serialize the relations.
The UWKGM project
:copyright: (c) 2020 Ichise Laboratory at NII & AIST
:author: Rungsima... |
# price-saving-block
# Out of stock
# class="product-sub-title-block product-out-of-stock"
# href="/ip/LEGO-Star-Wars-Imperial-Trooper-Battle-Pack-75165/55126217"
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
file_name = "scrapedata\legofromwalmart.csv"
f = open(file_name, "... |
"""
Unrolled Compressed Sensing (3D)
by Christopher M. Sandino (sandino@stanford.edu), 2020.
"""
import os, sys
import torch
from torch import nn
import sigpy.plot as pl
import utils.complex_utils as cplx
from utils.transforms import SenseModel
from utils.layers3D import ResNet
from unet.unet_model import UNet
from... |
import FWCore.ParameterSet.Config as cms
pfClustersFromL1EGClusters = cms.EDProducer("PFClusterProducerFromL1EGClusters",
src = cms.InputTag("L1EGammaClusterEmuProducer","L1EGXtalClusterEmulator"),
etMin = cms.double(0.5),
corrector = cms.string("L1Trigger/Phase2L1ParticleFlow/data/emcorr_barrel.root"),
... |
from ThesisAnalysis.plotting.setup import ThesisPlotter
from ThesisAnalysis import get_data, get_plot, ThesisHDF5Reader
import numpy as np
import os
class TFPlotter(ThesisPlotter):
def plot(self, x, y):
ymax = np.max(y, 0)
ymin = np.min(y, 0)
color = next(self.ax._get_lines.prop_cycler)[... |
from ...strategies.coordinator.scorer import TableScorer, PossibilityScorer, OpeningScorer, WinLoseScorer, NumberScorer, EdgeScorer, CornerScorer, BlankScorer, EdgeCornerScorer # noqa: E501
from ...strategies.coordinator.selector import Selector, Selector_W
from ...strategies.coordinator.orderer import Orderer, Ordere... |
#! python2.7
## -*- coding: utf-8 -*-
## kun for Apk View Tracking
## ViewTree.py
import copy
from TreeType import CRect,CTreeNode,CPoint
from ParseElement import ParseElement
from ViewState import ViewState
class ViewTree():
'''
View Tree
'''
def __init__(self, logger):
self.m_logger = ... |
from sumpy.annotators._annotator_base import _AnnotatorBase
from sumpy.annotators import SentenceTokenizerMixin, WordTokenizerMixin
from sumpy.document import Summary
from abc import ABCMeta, abstractmethod
import pandas as pd
import numpy as np
import networkx as nx
class _SystemBase(object):
"""Abstract base cla... |
import time
import sys
from typing import Iterable, Any, Mapping, Union, Iterator, Sequence
from elasticsearch import ElasticsearchException, NotFoundError
from elasticsearch.helpers import streaming_bulk, bulk
from . import connections
from .search import Search
class Exporter:
"""
Base class helper to exp... |
from ._venv import is_venv
from ._check import install_packages, check_module, require_module, check_fun, require_fun, check_attr, require_attr, check_class, require_class
|
n, q = map(int, input().split())
G = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = map(lambda x: int(x) - 1, input().split())
G[a].append(b)
G[b].append(a)
from collections import deque
P = [0] * n
dq = deque([0])
while dq:
v = dq.popleft()
for u in G[v]:
if P[u] > 0: continue
... |
import os
from warnings import warn
from flask import current_app
from .core import Config, lazy
from . import default_config
from flex.utils.local import LocalProxy
from flex.utils.lazy import LazyObject, empty
from flex.core.exc import ImproperlyConfigured
ENVIRONMENT_VARIABLE = 'FLEX_CONFIG_PATH'
ROOT_PATH_ENVAR ... |
import sys
import io
from twisted.logger import (
eventsFromJSONLogFile, textFileLogObserver
)
output = textFileLogObserver(sys.stdout)
for event in eventsFromJSONLogFile(io.open("log.json")):
output(event)
|
CELEBA_PATH = "/home/aixile/Workspace/dataset/celeba/"
GAME_FACE_PATH = "/home/aixile/Workspace/dataset/game_face_170701/"
|
#!/usr/bin/env python3
import unittest
from util import connect, load_data
LISTINGS_DATA = "YVR_Airbnb_listings_summary.csv"
REVIEWS_DATA = "YVR_Airbnb_reviews.csv"
CREATE_LISTINGS_TABLE = '''
CREATE TABLE listings (
id INTEGER,
-- ID of the listing
name TEXT,
-- Title of the list... |
import os
import logging
import pathlib
import random
import numbers
from tqdm import tqdm
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import torchvision.datasets as datasets
import torchvision.transforms.functional as TF
import torch.nn.functional... |
'''https://leetcode.com/problems/same-tree/'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def check(p, q):
... |
_C='ALTER TABLE '
_B='SELECT {} FROM {}'
_A=','
import mysql.connector
def table(x):global table;table=str(x)
def connect(*A):
if len(A)==3:B=mysql.connector.connect(host=A[0],user=A[1],password=A[2])
else:B=mysql.connector.connect(host=A[0],user=A[1],password=A[2],database=A[3])
return B
def query(x,y):A=x... |
import time
def isholiday(date):
singeday = ["01-01","01-02","01-03","01-04","01-05","01-06","01-07","01-08","01-11","01-12","01-13","01-14","01-15","01-16","01-17","06-18","07-08","07-09","07-10","07-11","07-12","08-01","08-02","08-03","08-04","08-05","08-06","08-07","08-08","08-09","08-10","10-03","10-04","10-05","... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
"""
Created on Fri Feb 17 12:38:44 2017
@author: ahefny, zmarinho
"""
from collections import defaultdict
import numpy as np
import theano
import theano.printing
import theano.tensor as T
import theano.tensor.slinalg
from theano.te... |
from __future__ import print_function, absolute_import, division
import KratosMultiphysics
import KratosMultiphysics.EmpireApplication
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.kratos_utilities as kratos_utils
from compare_two_files_check_process import CompareTwoFilesCheckP... |
# -*- coding: utf-8 -*-
#$HeadURL: https://rst2pdf.googlecode.com/svn/trunk/rst2pdf/tests/test_rst2pdf.py $
#$LastChangedDate: 2008-08-29 16:09:08 +0200 (Fri, 29 Aug 2008) $
#$LastChangedRevision: 160 $
from unittest import TestCase
from os.path import join, abspath, dirname, basename
PREFIX = abspath(dirname(__file__... |
import io
import os
import sys
from abc import ABC, abstractmethod
from typing import Optional
from demisto_sdk.commands.common.constants import (DIR_TO_PREFIX,
INTEGRATIONS_DIR,
SCRIPTS_DIR)
from demisto_sdk.commands... |
# Generated by Django 2.2.10 on 2020-03-08 18:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('team_fundraising', '0020_auto_20200308_1152'),
]
operations = [
migrations.AlterField(
model_name='campaign',
name=... |
# Imports
from flask import Blueprint
# SetUp
api = Blueprint('api', __name__)
# Routes
@api.route('/')
def index():
return 'urls index route'
|
import base64
import csv
import os
from zipfile import ZipFile
import openpyxl
from main import app
from core import action_hub, get_output_file_name, get_temp_file_name, get_temp_dir, send_email
from api_types import ActionDefinition, ActionList, ActionFormField, ActionRequest
slug = 'tabbed_spreadsheet'
icon_data... |
"""Classes for describing work and results.
"""
import enum
import json
import pathlib
class StrEnum(str, enum.Enum):
"An Enum subclass with str values."
class WorkerOutcome(StrEnum):
"""Possible outcomes for a worker.
"""
NORMAL = 'normal' # The worker exited normally, producing valid output
E... |
"""
_InsertCMSSWVersion_
Oracle implementation of InsertCMSSWVersion
"""
from WMCore.Database.DBFormatter import DBFormatter
class InsertCMSSWVersion(DBFormatter):
def execute(self, binds, conn = None, transaction = False):
sql = """DECLARE
cnt NUMBER(1);
BEGIN
... |
import datetime as dt
from dataclasses import dataclass, field
from typing import Any, ClassVar, Dict, List, Optional, cast
from ..types import VerificationDocument, VerificationDocumentStep
from .base import Resource
@dataclass
class Verification(Resource):
_endpoint: ClassVar[str] = '/v2/verifications'
id... |
# A mocked event controller to check whether our routines
# into the starting and restarting are touched correctly
from ev_core.config import Config
class EventControllerMock:
def __init__(self, config: Config):
self.started = True
self.restarted_cnt = 0
self.config = config
def st... |
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
# 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.... |
"""SCOPE:
1: Read the input given by the user
"""
print("Enter the number")
input_number=input()
print("The number is",input_number)
print(type(input_number))
input_number=int(input_number)
if(input_number>10):
print("It is greater than 10")
else:
print("It is less than 10")
|
from django.conf import settings
from disturbance import helpers
def disturbance_url(request):
template_group = 'disturbance'
TERMS = "/know/online-disturbance-apiary-terms-and-conditions"
is_officer = False
is_admin = False
is_customer = False
if request.user.is_authenticated:
is_a... |
from setuptools import setup, find_packages
import archapp
setup(
name='archapp',
version=archapp.__version__,
#packages=['archapp'],
packages=find_packages(),
description='Archiver Appliance Python Interface',
author='Zachary Lentz',
author_email='zlentz@slac.stanford.edu'
)
|
#!/home/bernard/acenv/bin/python3
import os, threading, sys, hashlib, uuid, pathlib
from indi_mr import mqtttoredis, mqtt_server, redis_server, tools
from indiredis import make_wsgi_app
from skipole import WSGIApplication, FailPage, GoTo, ValidateError, ServerError, use_submit_list, skis
from waitress import serve... |
#!/usr/bin/env python3
import os, sys
import multiprocessing
import subprocess as sp
import shutil
import shlex
import time
import csv
import json
sys.path.append('/home/jrchang/workspace/gym-OptClang/gym_OptClang/envs/')
import RemoteWorker as rwork
def getMultiAppsTargets(path):
"""
path: the root path for ... |
#!/usr/bin/env python3
#
# ===============LICENSE_START=======================================================
# Acumos
# ===================================================================================
# Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
# ==========================================... |
import paho.mqtt.client as mqtt
import os
import serial
import time
import random
from time import strftime
from datetime import datetime
import requests
import json
import schedule
import numpy as np
import tensorflow as tf
import random
import time
model2 = tf.keras.models.load_model('./my_model')
... |
import numpy as np
from Puzzle.Enums import directions, Directions, TypeEdge, TypePiece, rotate_direction
class PuzzlePiece():
"""
Wrapper used to store informations about pieces of the puzzle.
Contains the position of the piece in the puzzle graph, a list of edges,
the list of pixels comp... |
# -*- coding: utf-8 -*-
from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView, CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.decorators import ... |
PUPPETDB_HOST = 'localhost'
PUPPETDB_PORT = 8080
PUPPETDB_SSL_VERIFY = True
PUPPETDB_KEY = None
PUPPETDB_CERT = None
PUPPETDB_TIMEOUT = 20
DEV_LISTEN_HOST = '127.0.0.1'
DEV_LISTEN_PORT = 5000
UNRESPONSIVE_HOURS = 2
ENABLE_QUERY = True
LOCALISE_TIMESTAMP = True
LOGLEVEL = 'info'
REPORTS_COUNT = 10
OFFLINE_MODE = False
|
from collections import namedtuple
Position = namedtuple('Position', ['line', 'column'])
class JavaToken():
def __init__(self, value, position=None):
self.value, self.position = value, position
def __str__(self):
if not self.position:
return '%s "%s"' % (self.__class__._... |
"""Freeze metadata from Python index server to test locally.
Inspired by index_from_rubygems.rb from CocoaPods/Resolver-Integration-Specs.
This only reads metadata from wheels compatible with the given platform, and
does not cover sdists at all.
"""
from __future__ import annotations
import argparse
import collecti... |
from numpy.lib.npyio import load
import torch
import torch.nn.functional as F
from utility_functions import AvgPool3D
import h5py
import imageio
import numpy as np
import matplotlib.pyplot as plt
from utility_functions import AvgPool2D
import os
import h5py
from netCDF4 import Dataset
FlowSTSR_folder_path = os.path.di... |
'''
Unit tests for tree_util.py.
'''
import unittest
import tree_util
class TreeUtilTest(unittest.TestCase):
def setUp(self):
self.root = tree_util.Node({'id':0, 'form':'improve'}, [])
self.root.add_child(tree_util.Node({'id':1, 'form':'economy'}))
self.root.add_child(tree_util.Node({'id':2, 'form... |
"""
This project lets you practice NESTED LOOPS (i.e., loops within loops)
in the context of SEQUENCES OF SUB-SEQUENCES.
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Mark Hays, Amanda Stouder, Derek Whitley, their colleagues,
and PUT_YOUR_NAME_HERE.
""" # TODO: 1. PUT YOUR NAME... |
"""
Objects that represent -- and generate code for -- C/C++ Python extension modules.
Modules and Sub-modules
=======================
A L{Module} object takes care of generating the code for a Python
module. The way a Python module is organized is as follows. There is
one "root" L{Module} object. There can be any ... |
import sys
import click
import logging
import os
from datetime import datetime
from trimbot_modules import Configuration, Session, Recipe, V3Api, ResourceServiceFactory, CheckAction, NoCheckAction
def configure_logging(trace):
if trace:
logFormatter = logging.Formatter("%(asctime)s [%(levelname)s] %(messa... |
from django.db import models
class ProgrammingLanguage(models.Model):
name = models.CharField(max_length=200, null=False, unique=True)
def __str__(self):
return self.name
@property
def link(self):
return f'/?language={self.name}&rate=all#search-section-form'
@staticmethod
de... |
#This is code includes the logistic regression algorithm for the classification of the japanese credit dataset.
#goto http://ataspinar.com for a detailed explanation of the math behind logistic regression
#goto https://github.com/taspinar/siml for the full code
#It was used during hackathon4 of the Eindhoven Data Scien... |
#!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import numpy as np
import os.path
import random
import navpy
import simplekml
sys.path.append('../lib')
import Pose
import ProjectMgr
import SRTM
import ... |
from pynput.keyboard import Key, Controller, Listener
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6150
SOCK = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def sendjump(sock):
sock.sendto(("JUMP!").encode(), (UDP_IP_ADDRESS, UDP_PORT_NO) )
print("Jump Action Triggered!")
def on_press(key)... |
from shared_foundation.models.user import SharedUser
from shared_foundation.models.abstract_thing import AbstractSharedThing
from shared_foundation.models.abstract_contact_point import AbstractSharedContactPoint
from shared_foundation.models.abstract_postal_address import AbstractSharedPostalAddress
from shared_foundat... |
from __future__ import absolute_import
from __future__ import division
from multiprocessing import cpu_count, Pool
import time, signal
import numpy as np
from .decision_tree import DecisionTree
from .util import iterate_with_progress
#################################
# Multi-process funcs & klasses #
##############... |
from jet_bridge import fields
class SqlParamsSerializers(fields.CharField):
def to_internal_value_item(self, value):
value = super(SqlParamsSerializers, self).to_internal_value_item(value)
if value is None:
return []
# value = list(filter(lambda x: x != '', value.split(',')))
... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from django.db import models
from filebrowser.fields import FileBrowseField
from const.purpose import *
from crm import models as crmmodels
class XSLFile(models.Model):
title = models.CharField(verbose_name = _("Title"), max_length=100, ... |
from collections import namedtuple
import hashlib
import logging
import mimetypes
import os
import subprocess32 as subprocess
import time
from dropbox.client import DropboxClient
from dropbox.rest import ErrorResponse
from app import analytics
from app import celery
from app import db
from app import emailer
from app... |
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'testsecretkey'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'te... |
#!/bin/python3
"""
Parameters:
id: The Bugzilla bug ID to send the attachment to
image: The image to use (defaults to quay.io/kubevirt/must-gather)
api-key: Use a generated API key instead of a username and login
log-folder: Use a specific folder for storing the output of must-gather
Requirements... |
import doctest
import os
import sys
from glob import glob
from unittest import TestSuite, defaultTestLoader
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
def suite():
result = TestSuite()
result.addTest(doctest.DocTestSuite('django_any.xunit'))
result.addTest(doctest.DocTestSuite('django_any.f... |
import numpy as np
import tensorflow as tf
from absl.testing import absltest
import lm.examples
import lm.tf
class TestTF(absltest.TestCase):
def test_as_dataset(self):
def infeed(params):
def simplegen():
for i in range(batch_size):
yield lm.examples.Seq2S... |
import pytest
import six
from mock import Mock
from thefuck import conf
@pytest.fixture
def load_source(mocker):
return mocker.patch('thefuck.conf.load_source')
@pytest.fixture
def environ(monkeypatch):
data = {}
monkeypatch.setattr('thefuck.conf.os.environ', data)
return data
@pytest.mark.usefixt... |
from typing import Optional, List
import json
def load_json(file) -> Optional[any]:
json_obj = None
with open(file) as f:
json_obj = json.load(f)
return json_obj
def write_json(json_obj, file):
with open(file, 'w') as f:
json.dump(json_obj, f)
def create_json_of_types():
"""
... |
import matplotlib.pyplot as plt
from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
import matplotlib.image as mpimg
from scipy import misc
import math
import numpy as np
import sys as sys
from point import P2_Point
from point import R2_Point
import copy
def normalizeIm... |
# 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 u... |
from typing import ClassVar, List, Optional
from pycfmodel.model.base import CustomModel
from pycfmodel.model.resources.properties.policy_document import PolicyDocument
from pycfmodel.model.resources.resource import Resource
from pycfmodel.model.types import Resolvable, ResolvableStr, ResolvableStrOrList
from pycfmode... |
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# 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 th... |
from __future__ import annotations
import logging
from pathlib import Path
import bokeh
import bokeh.layouts
import bokeh.palettes
import pandas
from annofabcli.statistics.histogram import get_histogram_figure, get_sub_title_from_series
logger = logging.getLogger(__name__)
class Task:
"""'タスクlist.csv'に該当するデータ... |
from math import ceil
from typing import List, Tuple
# noinspection PyTypeChecker
# tag::calculator_class[]
class Calculator:
freq_items = [
(u"Año", 1, 10),
("Semestre", 2, 10),
("Cuatrimestre", 3, 12),
("Bimestre", 6, 12),
("Mes", 12, 12),
("Quincena"... |
import chess
import chess.pgn
import chess.engine
import sys, os
import random
import time
board = chess.Board()
print('legal_moves: ', list(board.legal_moves))
print(list(board.legal_moves)[0])
print(type(list(board.legal_moves)[0]))
m = list(board.legal_moves)[0]
print('m', m)
print('uci', m.uci())
print('san', bo... |
# -*- coding: utf-8 -*-
'''
© 2012-2013 eBay Software Foundation
Authored by: Tim Keefer
Licensed under CDDL 1.0
'''
import os
import sys
import gevent
from optparse import OptionParser
sys.path.insert(0, '%s/../' % os.path.dirname(__file__))
from common import dump
from ebaysdk.finding import Connection as finding... |
"""articles_column
Revision ID: 49f02f2c2ea
Revises: 171e70161dd
Create Date: 2016-03-19 22:38:51.402128
"""
# revision identifiers, used by Alembic.
revision = '49f02f2c2ea'
down_revision = '171e70161dd'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - pl... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-10 10:39
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... |
class DFDefault:
def __repr__(self):
return "DEFAULT_VAL"
def __str__(self):
return self.__repr__()
def __bool__(self):
return False
DEFAULT_VAL = DFDefault() # used for detecting when no parameter was passed without using 'None' or alternatives.
EMPTY_ARGS = dict(items=tuple()... |
'''
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2021-01-06 10:51:46
LastEditors: xiaoshuyui
LastEditTime: 2021-02-20 09:41:13
'''
import sys
sys.path.append("..")
import datetime
import importlib
import inspect
from devtool.devTool import DevTool
# import devtool.tests.utils.func1
from devt... |
import asyncio
from typing import Dict, List, Union
import dramatiq
from . import crud, models, settings, utils
MAX_RETRIES = 3
STATUS_MAPPING = {
0: "Pending",
3: "complete",
2: "invalid",
1: "expired",
4: "In progress",
5: "Failed",
"Paid": "complete",
"Pending": "Pending",
"Un... |
# The MIT License (MIT)
# Copyright (c) 2019 by the xcube development team and contributors
#
# 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... |
import tensorflow as tf
import numpy as np
from A3CAgent.helpers import *
from A3CAgent.AC_Network import AC_Network
from A3CAgent.Worker import Worker
import os
class A3CAgent:
def __init__(self):
self.first_init = True
self.roll_out_steps = 5
self.this_level = 0
self.worker_numbe... |
from __future__ import print_function
import httplib2
import os
import gspread
import praw
# https://github.com/burnash/gspread
from apiclient import discovery
from apiclient import errors
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse... |
#!/usr/bin/env python3
# -*- Coding: UTF-8 -*- #
# -*- System: Linux -*- #
# -*- Usage: *.py -*- #
# Owner: Jacob B. Sanders
# Source: code.cloud-technology.io
# License: BSD 2-Clause License
"""
...
"""
from . import *
import Database.SQL as SQL
import Database.Association
import Database.User.Models.Ba... |
"""
Blink LED - timer callback
On-board LED is connected to GPIO2.
"""
from machine import Pin, Timer
led = Pin(2, Pin.OUT)
my_timer = Timer(0) # using timer 0
# define callback function
def toggle_led(t):
led.value(not led.value()) # reverse led pin state
my_timer.init(period = 1000, callback = toggle_led) #... |
import click
from model.MyModel import MyModel
from model.utils.lr_schedule import LRSchedule
from model.utils.Config import Config
from model.pre.data import DataFrameDataset
from model.pre.transforms import trans_train, trans_valid
from model.pre.split_data import generate_split
from torch.utils.data import ... |
def numbers():
return [1, 2, 3]
def main():
print("Hello World!")
if __name__ == '__main__':
main() |
import sqlite3
from datetime import datetime #takes the date from the computer where the data is running
def handleWriting(next_pin_values):
# print(next_pin_values)
p0,p1,p2,p3,p4,sink=next_pin_values #sink is a throwaway value
date_value = str(datetime.now()) #gives python from the date and time a... |
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Intel Corporation. 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
#
# ... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import scriptcontext as sc
import compas_rhino
from compas_3gs.diagrams import FormNetwork
from compas.geometry import Translation
from compas_3gs.algorithms import volmesh_dual_network
from compas_3gs.rhi... |
from django.shortcuts import get_object_or_404
from rest_framework import mixins, views, viewsets
from ..models import Comment, ReplyComment
from .serializers import CommentSerializer, ReplyCommentSerializer
class CommentViewSet(
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,... |
import math
from typing import Dict, List, Tuple
def required_ore(
ingredients: Dict[str, Tuple[int, List[Tuple[int, str]]]], fuel: int
) -> int:
required = {"FUEL": fuel}
stock: Dict[str, int] = {}
while {k for k, v in required.items() if v > 0} != {"ORE"}:
next_required = next(k for k in req... |
# Nicholas Novak
# Introduction to Python course assignment
#Open the included file
dictionary_file = open("lab5_dictionary.txt","r")
dictionary_file.readlines()
# In this assignment, I created a function to find the longest word in a dictionary text file along with any ties for the longest word in that file.
# Not... |
import collections
import numpy as np
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.keras import activations
from tensorflow.python.keras import backend as K
from tensorflow.python.keras import constraints
from tensorflow.python.keras import initializer... |
import os
import random
from django.db import models
from contests.models import Submission, User, Contest
VERDICT = (
('RTE', 'Run Time Error'),
('MLE', 'Memory Limit Exceeded'),
('TLE', 'Time Limit Exceeded'),
('WA', 'Wrong Answer'),
('CE', 'Compilation Error'),
('IE', 'Internal Error'),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.