content stringlengths 5 1.05M |
|---|
# SPDX-License-Identifier: BSD-3-Clause
from typing import ClassVar, Mapping, cast
import logging
from softfab.ControlPage import ControlPage
from softfab.Page import InvalidRequest, PageProcessor
from softfab.authentication import TokenAuthPage
from softfab.joblib import JobDB
from softfab.pageargs import DictArg, E... |
from django.conf.urls import url, include
from django.contrib.auth import views
from simplemooc.accounts.views import register
from simplemooc.accounts.views import dashboard
from simplemooc.accounts.views import edit, edit_password, password_reset, password_reset_confirm
#from django.contrib import aut
urlpatterns =... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("ICALIB")
process.MessageLogger = cms.Service(
"MessageLogger",
threshold = cms.untracked.string('INFO'),
#destinations = cms.untracked.vstring('cout'),
destinations = cms.untracked.vstring('SiStripDetVOffFakeBuilder.log')
)
process.source... |
"""The redis sessions plugin"""
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
import os
import binascii
import hashlib
from tornado import escape
from .middleware import *
from .options import *
def random_hex(length):
"""Generates a random hex string"""
... |
import produce_data.prop_database as db
import pandas as pd
import numpy as np
import datetime
def main(prop):
'''
produce data table based on query property
'''
subs = db.request_substance_pd()
subs.dropna(axis = 0, inplace = True)
subs.set_index('CAS', inplace = True)
# make li... |
class Position(object):
def __init__(self, startDate: str, ticker: str, investment: float, purchasePrice: float, goal: float, holdTime: int,
shares: int, posID):
self.startDate = startDate
self.ticker = ticker
self.initialInvestment = investment
self.purchasePrice = ... |
""" dict utils
:Author: Jonathan Karr <karr@mssm.edu>
:Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu>
:Date: 2016-08-25
:Copyright: 2016-2018, Karr Lab
:License: MIT
"""
class DictUtil(object):
""" Dictionary utility methods """
@staticmethod
def nested_in(dict, keys, key_delimiter='.'):
"""... |
from biicode.common.exception import (PublishException, UpToDatePublishException,
ForbiddenException, AuthenticationException)
from biicode.common.edition import changevalidator
from biicode.common.diffmerge.compare import compare
from biicode.common.model.symbolic.block_version im... |
import torch
import os
import shutil
def save_checkpoint(model, optimizer, curr_epoch, curr_step, args, curr_loss, curr_acc, filename):
"""
Saves a checkpoint and updates the best loss and best weighted accuracy
"""
is_best_loss = curr_loss < args.best_loss
is_best_acc = curr_acc > args.best_ac... |
# coding=utf-8
"""Object detection inferencing. single gpu only."""
import os
import argparse
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # so here won't have poll allocator info
# remove all the annoying warnings from tf v1.10 to v1.13
import logging
logging.getLogger('tensorflow').disabled = True
import numpy as np
i... |
import numpy as np
import scipy.signal
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
#plots euve lightcurves nicely for proposal
plt.figure('gd394_euve',figsize=(12,8))
plt.subplots_adjust(top=0.99, right=0.99, left=0.07, bottom=0.08, wspace=0.1, hspace=0.09)
gs = plt.GridSpec(2,2)
lcs = ... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from cms.extensions import PageExtensionAdmin
from .models import CatalogExtension
class CatalogExtensionAdmin(PageExtensionAdmin):
pass
admin.site.register(CatalogExtension, CatalogExtensionAdmin)
|
"""
Functions for TF analysis.
@author: mje
@email: mads [] cnru.dk
"""
import mne
from mne.time_frequency import (psd_multitaper, tfr_multitaper, tfr_morlet,
cwt_morlet)
from mne.viz import iter_topography
import matplotlib.pyplot as plt
import numpy as np
def calc_psd_epochs(epochs... |
"""
Task Module
"""
# Local Library
from app.modules.util.humanize import Humanize
from app.modules.entity.option_entity import OptionEntity
from app.modules.entity.notification_entity import NotificationEntity
class Notification():
PENDING = "pending"
FAILED = "failed"
PASSED = "passed"
ERROR = "er... |
print('-' * 20)
print(' LOJA SUPER BARATÃO')
print('-' * 20)
totpreço = prod1000 = menor = cont = 0
barato = ''
while True:
produto = str(input('Nome do produto: '))
preço = float(input('Preço: R$ '))
cont += 1
totpreço += preço
if preço > 1000:
prod1000 += 1
if cont == 1 or preço < meno... |
"""
**A unique identifier generator module**
Also provides the dfo revision number.
This module is imported automatically when dfo is imported.
"""
from os import getpid
from socket import gethostname
__all__ = ['locationID', 'revision']
revision_str = "$Rev: 773 $"
revision = int(revision_str.split(' ')[1])
# Un... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import unittest
import requests
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome() # buat panggil browser
self.driver.maximize_window()
self.driver.implicitly_wait(5)
self.driver... |
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from django.db import models
from meiduo_mall.utils.models import BaseModel
# Create your models here.
class GoodsCategory(BaseModel):
"""
商品类别
"""
name = models.CharField(max_length=10, verbose_nam... |
import functools
import operator
import scipy.sparse
import numpy as np
import akg
from akg import tvm
from akg import composite
from akg.utils import CUDA
from tests.common.base import get_rtol_atol
from tests.common.gen_random import random_gaussian
from tests.common.tensorio import compare_tensor
from akg.utils imp... |
import io
import os
import json
import time
import boto3
from datetime import datetime
from xml.etree import ElementTree
from textract_util import *
from boto3.dynamodb.conditions import Key, Attr
def lambda_handler(event, context):
s3 = boto3.resource('s3')
textract = boto3.client('textract')
dynamodb = b... |
import sys
import json
import numpy as np
import os
sys.path.append(
os.path.join(os.path.dirname(__file__), '../../../pythia/scripts/coco/')
)
import coco_caption_eval # NoQA
def print_metrics(res_metrics):
print(res_metrics)
keys = ['Bleu_1', 'Bleu_2', 'Bleu_3', 'Bleu_4', 'METEOR', 'ROUGE_L', 'SPICE',... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from binance.client import Client
import pandas as pd
import json
with open('C:/Users/USER/Desktop/binance_api.json', mode='r') as key_file:
data = json.load(key_file)
api_key = data['key']
api_secret = data['secret']
client = Client(api_key, api_secret)
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 7 01:30:34 2016
@author: cemgil
Bouncing Ball with x and y coordinates
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.ad... |
from math import floor
def extract_digits(n):
# Increase value to 4 digits
value = n
exponent = 0
while value < 999.5 and exponent < 3:
value *= 10
exponent += 1
value = floor(value + 0.5) / (10**exponent)
str_value = str(value)
dp_pos = str_value.find('.') - 1
digits ... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import (
print_function, unicode_literals, absolute_import, generators, division)
import sys
import os
script_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
root_dir = os.path.realpath("%s/../.." % script_dir)
version_path = "%s/VERSION" % root_dir
d... |
#!/usr/bin/env python
#
#
import os, shutil
import mcvine.run_script
import unittest
class TestCase(unittest.TestCase):
def test3(self):
outdir = 'out-method-run_mpi'
if os.path.exists(outdir):
shutil.rmtree(outdir)
mcvine.run_script.run_mpi('test_instrument_method.py', outdir,... |
class TierFulfillmentMessages(object):
RROR_PROCESSING_TIER_REQUEST = 'There has been an error processing the tier config request. Error description: {}'
class BasePurchaseMessages:
pass
class BaseChangeMessages:
pass
class BaseSuspendMessages:
NOTHING_TO_DO = 'Suspend method for request {} - Nothi... |
# This file is part of the Hotwire Shell user interface.
#
# Copyright (C) 2007,2008 Colin Walters <walters@verbum.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... |
# ¡-*- coding: utf-8 -*-
from django.test import TestCase, RequestFactory
from msn.views import (
main,
forms,
board,
config,
)
class MsnViewTest(TestCase):
def setUp(self):
self.factory = RequestFactory()
def tearDown(self):
pass
def test_main_view(self):
... |
# Generated by Django 3.1.12 on 2021-06-24 08:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bus', '0003_auto_20210624_0634'),
('trip', '0002_auto_20210624_0634'),
]
operations = [
migrations.AddField(
model_name... |
#!/bin/env python
import numpy as np
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.types as types
try:
from matplotlib import pyplot as plt
has_matplotlib = True
except ImportError:
has_matplotlib = False
BATCH_SIZE=4
COUNT=5
VIDEO_FILES=["prepared.mp4"]
ITE... |
import json
from google.cloud import datastore
import google.cloud.exceptions
client = datastore.Client("speech-similarity")
def user_get(request):
request_json = request.get_json(silent=True)
request_args = request.args
if request_json and "userId" in request_json:
user_id = request_json["userI... |
import logging
import boto3
def wait_for_instances(instances):
"""
Wait until the given boto3 instance objects are running
"""
logging.info("Waiting for instances: {}".format([i.id for i in instances]))
for i in instances:
logging.info("Waiting for instance {}".format(i.id))
i.wait_u... |
import pickle
from tqdm import tqdm
import numpy as np
class Dataset(object):
def __init__(self, file_name):
self.dataset = self._load_data(file_name)
def _load_data(self, file_name):
print("loading dataset from %s" % file_name)
with open(file_name, 'rb') as f:
... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from scipy.misc import factorial
import pandas as pd
from CHECLabPy.core.io import DL1Reader
from IPython import embed
def poisson(k, lamb):
"""poisson pdf, parameter lamb is the fit parameter"""
return (lamb**k/factorial(k... |
from .models import Note, Icon
from djangoseo.admin import register_seo_admin
from django.contrib import admin
from .seo import BasicMetadata
class NoteAdmin(admin.ModelAdmin):
readonly_fields = ('slug', 'content_html')
admin.site.register(Note, NoteAdmin)
admin.site.register(Icon)
register_seo_admin(admin.sit... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
2020
@author: jmmauricio
"""
import numpy as np
from pydae.tools import get_v,get_i,get_s
import json
from collections import namedtuple
import numba
class grid(object):
def __init__(self,syst):
#def bokeh_tools(data):
self.syst = syst
... |
'''
Manage schedule condition of the HDInsight cluster which enabled Schedule-based Autoscale.
'''
from .... pyaz_utils import _call_az
def create(cluster_name, days, resource_group, time, workernode_count, no_wait=None):
'''
Add a new schedule condition.
Required Parameters:
- cluster_name -- The nam... |
import unittest
import aiohttp
import requests
import os
import dhooks
from io import BytesIO
import asyncio
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
REAL_URL = os.getenv('TEST_WEBHOOK_URL', None)
if REAL_URL is None:
raise ValueError("TEST_WEBHOOK_URL environment variable not foun... |
from matplotlib.path import Path
from matplotlib.patches import BoxStyle
import matplotlib.pyplot as plt
# we may derive from matplotlib.patches.BoxStyle._Base class.
# You need to overide transmute method in this case.
class MyStyle(BoxStyle._Base):
"""
A simple box.
"""
def __init__(self, pad=0.3):... |
import logging
import time
from django.http import HttpRequest
class LoggingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.logger = logging.getLogger("LoggingMiddleware")
@staticmethod
def get_milliseconds_now():
return int(time.time() * 1000)... |
#!/usr/bin/env python
# coding: utf-8
# # Minimum Risk-Free Rate of Return
#
#
# Application of Farka's lemma and convex duality. - Ar
#
#
# ## Farka's lemma
#
# Farka's lemma, first published by the Hungarian mathematician and physicist Gyula Farkas in 1902, is one of foundations for the theory of linear program... |
# -*- coding: utf-8 -*-
"""
fuocore.provider
~~~~~~~~~~~~~~~~
"""
from abc import ABC, abstractmethod
from contextlib import contextmanager
from fuocore.models import (
SongModel,
ArtistModel,
AlbumModel,
PlaylistModel,
LyricModel,
UserModel,
ModelType,
)
_TYPE_NAME_MAP = {
Model... |
from bs4 import BeautifulSoup
import requests
import csv
import sys
from urllib.error import HTTPError
sys.path.append("..")
import mytemp
import time
from urllib.error import HTTPError
import urllib.request
cityCode='020000'
#若要使用代理,改为TRUE,补充get_proxies_abuyun函数中代理渠道验证信息
proxy=False
beginPage=1
urlro... |
#!/usr/bin/env python
from color import Color, HSV, RGB, hsv_to_rgb, rgb_to_hsv, is_rgb_tuple, is_hsv_tuple
from itertools import count
import opc, time
from random import randint
numLEDs = 20
client = opc.Client('localhost:7890')
black = [(0, 0, 0)] * numLEDs
white = [(255, 255, 255)] * numLEDs
c = count(100)
__al... |
from .exponential_coordinates_of_rotation import (SO3_to_vec, so3_to_vec,
vec_to_so3, vec_to_SO3)
|
import cv2
from cv2 import aruco
from bach import darknet
import bach.geometry
class Detector:
def __init__(self, configuration, meta, weights):
"""
Default constructor.
"""
self.configuration_file = configuration
self.meta_file = meta
self.weights_file = weights
... |
#!/usr/bin/env python
import os
from glob import glob
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from pathlib import Path
version_path = Path(__file__).parent / "karton/unpacker/__version__.py"
version_info = {}
exec(version_path.read_text(), version_info)
def get_... |
# django rest framework imports
from rest_framework import serializers
# app imports
from .models import Article
class ArticleSerializer(serializers.Serializer):
"""
docstring
"""
title = serializers.CharField(max_length=120)
description = serializers.CharField()
body = serializers.C... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
import pandas as pd
import re
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from bs4 import BeautifulSoup
import requests
def get_stop_words(stop_file_path):
with open(stop_file_path, 'r', encoding="utf-8") as f:
stopwords = f.read... |
import logging
import click
logger = logging.getLogger(__name__)
@click.group()
def user():
pass
@user.command(name='create')
@click.pass_context
# @my_global_options
def user_create(ctx, **kwargs):
logging.debug(ctx.obj)
logging.debug('users_create')
|
from django.db.models import Q
from django.forms import modelformset_factory
from django.http import JsonResponse
from django.shortcuts import render, redirect
from books.models import Book
from funds.calcs import sum_fund, parts_count
from funds.forms import FundList, NewIncomeDocument, IncomeDetail, \
NewOutcome... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doctype("Time Log")
for d in frappe.get_all("Time Log"):
time_log = frappe.get_doc("Time Log", d.name)
... |
from booster import app, db
class EventType(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
description = db.Column(db.String(256))
events = db.relationship('Event', backref='event_type', lazy='dynamic')
def __init__(self, name, description):
self.na... |
"""
test_populations_popIII.py
Author: Jordan Mirocha
Affiliation: McGill
Created on: Tue 7 Apr 2020 21:18:13 EDT
Description:
"""
import ares
import numpy as np
from ares.physics.Constants import rhodot_cgs
def test():
mags = np.arange(-25, -5, 0.1)
zarr = np.arange(6, 30, 0.1)
pars = ares.util.Pa... |
import os
import tempfile
import pytest
from litedb.errors import DatabaseNotFound
from litedb.utils.path import load_tables
def test_load_database_well_formed():
with tempfile.TemporaryDirectory() as tempdir:
table_dir = os.path.join(tempdir, "0x1234567890123456")
os.mkdir(table_dir)
in... |
from character import SwCharacter
from graphql import graphql_attr_field
from graphql import graphql_object
@graphql_object('Human', 'A humanoid creature in the Star Wars universe.')
@graphql_attr_field(
'home_planet', 'homePlanet', 'String',
'The home planet of the human, or null if unknown.')
class SwHuman(... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
__name__ = 'bobafett'
release_info = {}
infopath = os.path.abspath(os.path.join(os.path.dirname(__file__),
__name__, 'info.py'))
with open(infopath) as open_file:
exec(open_file.read(),... |
#
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,TextAreaField
from wtforms.validators import Required,Email,EqualTo
from wtforms import ValidationError
from ..models import Subscription
class blogForm(FlaskForm):
title = StringField('Title', validators=[Required()])
description = Text... |
"""
ReSpeaker Python Library
Copyright (c) 2016 Seeed Technology Limited.
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 a... |
# Pix2Pix : https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.autograd import Variable
from torch.optim import lr_scheduler
import numpy as np
##################################################... |
from ._real import AudioReal
__all__ = [
"AudioReal",
]
|
from datetime import datetime
try:
from urlparse import urljoin, urlparse, parse_qs
except ImportError:
from urllib.parse import urljoin, urlparse, parse_qs
def join_url(base, query):
"""Joins a query to a url.
"""
sep = '&' if '?'in base else '?'
return base + sep + query
def strip_query(u... |
def create_matrix(size):
matrix = [[0 for x in range(size)] for y in range(size)]
value = 1
turn_size = 1
w, h = int(size/2), int(size/2)
while(value < size ** 2):
if(turn_size == 1):
print(str(w) + " " + str(h))
matrix[w][h] = value
w += 1
val... |
# -*- coding: utf-8 -*-
from ...collection import Collection
from ..utils import (
allocatable_production,
choose_reference_product_exchange,
get_single_reference_product,
single_input,
)
from ..uncertainty import scale_exchange
from .economic import economic_allocation
from .validation import valid_rec... |
import networkx as nx
import matplotlib.pyplot as plt
G = nx.erdos_renyi_graph(7,0.5)
actors = {0:"Luca",1:"Edo",2:"Antonio",3:"Giacomo",
4:"Joni",5:"Valeria",6:"Ennio"}
nx.draw_kamada_kawai(G,labels=actors,with_labels=True)
plt.savefig("sample_social.png")
plt.show()
|
import os
import pyqtgraph as pg
import idephyx
import pyacq
from idephyx.controlpanel import ControlPanel
def test_ControlPanel():
conf = {}
configuration_file = 'test_idephyx_config.py'
exec(open(configuration_file).read(), None, conf)
print(conf)
app = pg.mkQApp()
win = Contro... |
from tkinter import *
import tkinter.messagebox as ss
savan = Tk()
savan.title("temperature unit converter")
savan.geometry("500x700")
savan.configure(background="lightgrey")
i = u'\N{DEGREE SIGN}'
l1= Label(text=f"Enter The Value of {i}C :")
l10= Label(text=f"Enter The Value of {i}F :")
abc = IntVar()
e1=E... |
#Code : Remove Min
"""
Implement the function RemoveMin for the min priority queue class.
For a minimum priority queue, write the function for removing the minimum element present.
Remove and return the minimum element.
Note : main function is given for your reference which we are using internally to test the code.
"""... |
"""
Task:
1. Convert all videos in to small clips in tensor with name:
videoName_frameId_actionName.pkl
2. Convert all labels to json with structure:
{
"label_fname + end_frame + label_i": {
"begin_frame": 2,
"end_frame": 10,
"duration": 8,
"vspec_id": "label_fname", # the name of... |
from flask.wrappers import Request
from . import app, db
from flask import jsonify, request
from ..models.users import User
from ..models.courses import Course
from flask_msearch import Search
from marshmallow import Schema, fields
from ..models.resultSchema import resultSchema
from flask_cors import CORS
search=Searc... |
# Copyright (c) 2021, kiran and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Property(Document):
# validate
def after_insert(self):
frappe.msgprint((f'Document {self.name} insert successfully... |
import logging as log
from common.config import MILVUS_TABLE, OUT_PATH, OUT_DATA
from indexer.index import milvus_client, search_vectors, get_vector_by_ids
from indexer.tools import connect_mysql, search_by_milvus_id
import numpy as np
import torch
import pickle
import dgl
import json
import random
def get_list_info(... |
class Solution(object):
def findSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.subsets(nums, 0, [], res)
return res
def subsets(self, nums, start, temp, res):
if len(temp) > 1:
res.append(... |
# -*- coding: utf-8 -*-
"""User views."""
from flask import Blueprint, render_template, request
from flask_login import login_required, current_user
from rssfeedcreator.feed.forms import FeedForm
blueprint = Blueprint('user', __name__, url_prefix='/users', static_folder='../static')
@blueprint.route('/')
@login_requ... |
import unittest
from unittest import TestResult
from integration import test_gameplay
from unit import test_janggi_game
from unit import test_obstacle_detection_strategy
from unit import test_path_generation_strategy
def run_tests(*args, **kwargs) -> TestResult:
"""
Run test suite for one or more test module... |
from tests.conftest import client
from flask import url_for
# def login(client, email, password):
# # function to send user data to sign in
# return client.post(url_for("auth.login"), data={"email":email, 'password': password}, follow_redirects=True)
# def logout():
# pass
def login(client, email, ... |
import urwid as u
class game:
count1 = 0
count2 = 0
def __init__(self,count1,count2):
self.count1 = count1
self.count2 = count2
def count_one(self, count1):
i = 0
for x in range(1,count1):
print(self.count1)
i = i + 1
def count_two(self, count2):
j = 0
for x in range... |
import asyncio
from nats.aio.client import Client as NATS
async def example():
# [begin connect_multiple]
nc = NATS()
await nc.connect(servers=[
"nats://127.0.0.1:1222",
"nats://127.0.0.1:1223",
"nats://127.0.0.1:1224"
])
# Do something with the connection
await nc.close()
... |
N = int(input())
print('GO' if N % 4 == 0 else 'SEN')
"""
import sys
sys.setrecursionlimit(10**5)
def dfs(s):
if s >= N:
return False
if memo[s] != -1:
return memo[s]
ret = False
for i in range(3):
if not dfs(s+i+1):
ret = True
memo[s] = ret
return memo[s]
... |
import httplib2
import base64
import json
class BsnRest(object):
def __init__(self, host, user, password, debug=False):
self.host = host
self.user = user
self.password = password
self.debug = debug
self.http = None
self.http_port = None
self.session_cookie =... |
from dataclasses import dataclass
from diamond_miner.queries.fragments import IPNetwork
from diamond_miner.queries.query import (
UNIVERSE_SUBSET,
LinksQuery,
ResultsQuery,
links_table,
results_table,
)
@dataclass(frozen=True)
class GetNodeDiscoveries(ResultsQuery):
def statement(
sel... |
# coding: utf-8
"""
Galaxy 3.2 API (wip)
Galaxy 3.2 API (wip) # noqa: E501
The version of the OpenAPI document: 1.2.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import openapi_client
from openapi_client.models.namespaces_page import Na... |
#
# PySNMP MIB module ITOUCH-SYSTEM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ITOUCH-SYSTEM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:47:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
import python_script as ps
assert(ps.c2f(0) == 32)
assert(ps.c2f(100) == 212)
assert(ps.k2c(273.15) == 0)
assert(ps.k2c(0) == -273.15)
assert(ps.k2f(273.15) == 32)
|
# -*- coding: utf-8 -*-
import os
import json
import base64
import datetime
from enum import Enum
from orator import DatabaseManager, Model
from ..util.config import config
from ..model.pet import Pet, Photo
from ..log import Logger
class StatusCodes(Enum):
SUCCESS = 0
INSERTION_ERROR = 1
PET_NOT_FOU... |
from django.urls import path
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
from django.contrib.auth.decorators import login_required, permission_required
from equipment.views import (
EquipmentView,
ModelView
)
app_name = "equi... |
import boto3
from ..services import util
client = boto3.client('ecr')
def describe_repositories():
response = client.describe_repositories()
return response.get('repositories')
def describe_repository(repository):
response = client.describe_repositories(repositoryNames=[repository])
return response.g... |
a, b, c = int(input()), int(input()), int(input())
d, e = int(input()), int(input())
if (a <= d or b <= d or c <= d) and (a <= e or b <= e or c <= e):
print('YES')
else:
print('NO')
|
import numpy as np
import matplotlib.pyplot as plt
def plot_voltages(data):
"""Plot the voltages."""
fig, ax = plt.subplots(figsize=(12, 8), dpi=100)
ax.matshow(data, cmap='magma')
ax.axis('off')
plt.savefig('output.png')
plt.close()
def plot_connectivity(weights, delays):
"""Plot weig... |
from dectate.app import App, directive
from dectate.config import commit, Action, Composite
from dectate.error import ConflictError, ConfigError
import pytest
def test_simple():
class MyDirective(Action):
config = {"my": list}
def __init__(self, message):
self.message = message
... |
from extension_native_helpers import *
Dtool_PreloadDLL('libpanda')
from libpanda import *
from extension_native_helpers import *
Dtool_PreloadDLL('libpanda')
from libpanda import *
def pPrintValues(self):
return '\n%s\n%s\n%s' % (self.getRow(0).pPrintValues(), self.getRow(1).pPrintValues(), self.getRow(2).pPrintV... |
# 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 2.3.3... |
import asyncio
from . import socket
iter_chunks = asyncio.coroutine(socket.iter_chunks)
read_until = asyncio.coroutine(socket.read_until)
|
# This file was auto-generated by support/scripts/gen-bootlin-toolchains
# Do not edit
from tests.toolchain.test_external import TestExternalToolchain
class TestExternalToolchainBootlinAarch64GlibcBleedingEdge(TestExternalToolchain):
config = """
BR2_aarch64=y
BR2_TOOLCHAIN_EXTERNAL=y
BR2_... |
#M SHAPE PATTERN
result_str="";
for row in range(0,7):
for column in range(0,7):
if (column == 1 or column == 5 or (row == 2 and (column == 2 or column == 4)) or (row == 3 and column == 3)):
result_str=result_str+"* "
else:
result_str=result_st... |
import argparse
from utee import misc, quant, selector
import torch
import torch.backends.cudnn as cudnn
cudnn.benchmark =True
from collections import OrderedDict
import pprint
import os
import torch.nn as nn
from torch.nn.parameter import Parameter
import copy
model_root = '~/pytorch-mobilenet-v2/mobilenetv2_718.p... |
def pipe(df_test):
df_test['dlk_cob_date'] = pd.to_datetime(df_test['dlk_cob_date'], yearfirst=True)
df_test.sort_values(['cif_id', 'dlk_cob_date'], inplace=True)
df_test = df_test[df_test['dlk_cob_date'] < '2018-07-01']
df = df_test.drop(['cu_education_level', 'cu_empl_area', 'cu_empl_level',
... |
"""
Main Control of C'thuen
Train the Neural Operator
Generat the Relation Graph
"""
import setup
import utils
import word_tokenize
import graph_constructor
import neural_operators
#from tokenize import TokenMarker
# Tensorflow settings etc
import tensorflow as tf
import tensorflow.keras as keras
impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.