content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python
from multi_circle_2 import Multi_circle_2
if __name__ == '__main__':
multi_circle_2 = Multi_circle_2(
[
#x , y, z, yaw, sleep
[0.0 , 0.0, 1.0, 0, 8],
[0.0 , 0.0 ,1.0, 0, 3],
[-0.3 , -1.4, 0.0, 0, 0],
]
)
multi_circle_2.run(... | python |
# Given a column title as appear in an Excel sheet, return its corresponding column number.
# For example:
# A -> 1
# B -> 2
# C -> 3
# ...
# Z -> 26
# AA -> 27
# AB -> 28
class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
d = {'... | python |
"""
Clustered/Convolutional/Variational autoencoder, including demonstration of
training such a network on MNIST, CelebNet and the film, "Sita Sings The Blues"
using an image pipeline.
Copyright Yida Wang, May 2017
"""
import matplotlib
import tensorflow as tf
import numpy as np
from scipy.misc import imsave
import o... | python |
"""
This provides wrappers for FMUs so they are easy to assemble in a short
script, as well as support writing data in HDF5 format using pytable, as
well as a library of FMUs ready to be assembled.
The structure of the file starts with the FMU utilities, goes on to define
modules and simulations, and ends with a list... | python |
import numpy as np
from jitcdde import input as system_input
from symengine import exp
from ..builder.base.constants import EXC, INH, LAMBDA_SPEED
from ..builder.base.network import SingleCouplingExcitatoryInhibitoryNode
from ..builder.base.neural_mass import NeuralMass
from .model_input import OrnsteinUhlenbeckProces... | python |
import os
import shutil
os_license = '{{ cookiecutter.license }}'
notebooks = '{{ cookiecutter['jupyter notebooks'] }}'
containers = '{{ cookiecutter.containers }}'
if os_license == "No license file":
os.remove("LICENSE")
if notebooks == "No":
shutil.rmtree("src/notebooks")
if containers == "one":
shuti... | python |
"""Basic functionality sanity tests"""
from urllib.parse import urljoin
import pytest
# Various sub-urls for the main page
PAGE_URL_LIST = ["", "about/", "docs/", "scls/"]
# Various sub-urls for a collection
SCL_URL_LIST = ["", "edit/", "coprs/", "repos/", "acl/", "review_req/"]
@pytest.mark.django_db
def test_scl_... | python |
from collections import OrderedDict
import jsonschema
from django.db.models import Q
from jsonschema import Draft4Validator
from rest_framework import serializers
from architecture_tool_django.modeling.models import Edgetype, Nodetype
from ..models import Edge, Node
class EdgeSerializer(serializers.ModelSerializer... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from patsy import dmatrix
from patsy import DesignMatrix, DesignInfo
from patsy import LookupFactor,ModelDesc,Term
X = [[1, 10], [1, 20], [1, -2]]
print(dmatrix(X))
design_info = DesignInfo(["Intercept!", "Not intercept!"])
X_dm = DesignMatrix(X, design_info)
print(dmatri... | python |
table_file_template = """
import argparse
from deriva.core import ErmrestCatalog, AttrDict, get_credential
import deriva.core.ermrest_model as em
from deriva.core import tag as chaise_tags
from deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args
{groups}
table_name = '{table_name}'
schema_na... | python |
from opentelemetry import trace
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleExportSpanProcessor
trace.set_tracer_provider(TracerProvider())
cloud_trace_exporter = CloudTraceSpanExporter()
trac... | python |
# Duas formas para se fazer a leitura de um número inteiro...#
def leiaint(msg):
valor = 0
while True:
n = str(input(msg))
if n.isnumeric():
valor = int(n)
break
else:
print('\033[31mERRO ! Digite um número inteiro válido.\033[m')
retur... | python |
from torch.nn import CrossEntropyLoss
class GPT2Loss(CrossEntropyLoss):
def __init__(self, pad_token_id):
super(GPT2Loss, self).__init__(ignore_index=pad_token_id)
def forward(self, output, labels):
"""
Loss function for gpt2
:param output:
:param labels:
:retu... | python |
from mccq.cli import cli
| python |
import sys
from bidi.algorithm import get_display
# variable length print, the string constants are adjusted for bidi.
# an unrelated editor is that vs code doesn't support bidi.
# the workaround is to put bidi text into separate string variables.
#not entirely sure, if we need to swap each element seperately...
def... | python |
import os
from pathlib import Path
from string import Template
template = Template("""
Package: zram-swap
Version: $version
Depends: python3, libpython3-stdlib
Section: custom
Priority: optional
Architecture: all
Essential: no
Installed-Size: $size
Maintainer: Dmitry Orlov <me@mosquito.su>
Description: Easy way to co... | python |
"""Test label"""
from napari.components.text_overlay import TextOverlay
def test_label():
"""Test creating label object"""
label = TextOverlay()
assert label is not None
| python |
import sys, clr
import ConfigParser
from os.path import expanduser
# Set system path
home = expanduser("~")
cfgfile = open(home + "\\STVTools.ini", 'r')
config = ConfigParser.ConfigParser()
config.read(home + "\\STVTools.ini")
# Master Path
syspath1 = config.get('SysDir','MasterPackage')
sys.path.append(syspath1)
# Bui... | python |
import json
from urllib.parse import urlencode
from flask import Response, request
def _create_link(path, limit, offset, order_by, order_how, args_dict):
# copy of the dict passed in so we don't modify the original
params = dict(args_dict)
params["limit"] = limit
params["offset"] = offset
params... | python |
from distutils.core import setup
setup(
name='http_request',
version='1.1',
packages=['http_request'],
url='https://github.com/dennisfischer/http_request',
license='MIT',
author='Dennis Fischer',
author_email='dennis.fischer@live.com',
description='A small python library to parse and bu... | python |
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2018. Authors: see NOTICE file.
# *
# * 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... | python |
import pandas as pd
from age.data.load.countries import base
from age.data.load import transformations
from age.data.load import utils
from age.data.load import ined
import logging
import datetime
from urllib.request import urlopen
_CASES_PATH = 'https://data.rivm.nl/covid-19/COVID-19_casus_landelijk.csv'
_INED_URL = ... | python |
"""
MIT License
Copyright (c) 2018 Elias Doehne
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import os.path
import xml.dom.minidom
import argparse
class Config():
def __add_server(self, parent_node, settings, server_name):
try:
os.environ["TRAVIS_SECURE_ENV_VARS"]
except KeyError:
print "no secur... | python |
#!/usr/bin/python
import gzip
import socket
#UDP_IP = "127.0.0.1"
UDP_IP = "0.0.0.0"
UDP_PORT = 6550
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
f = gzip.open('flight.dat.gz', 'wb')
print "Aura Logger"
print "listening for", UDP_IP,... | python |
"""REST API endpoints"""
from fastapi import APIRouter
from app.api.api_v1.endpoints import items, users
api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])
api_router.include_router(items.router, prefix="/items", tags=["items"])
| python |
import os
import sys
import time
import gc
import copy
import random
import numpy as np
import pandas as pd
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
from image_util import *
from data_util import *
from env import *
from sum_tree import *
im... | python |
from py_queryable import Model
from py_queryable import Column, PrimaryKey, ForeignKey
class StubModel(Model):
__table_name__ = u'test_table'
test_int_column = Column(int, 'int_column')
class StubModel2(Model):
__table_name__ = u'test_table'
test_int_column = Column(int)
class StubPrimary(Model):
... | python |
from mmcv.utils import Registry,build_from_cfg
TRANSFORMER = Registry('Transformer')
POSITIONAL_ENCODING = Registry('Position encoding')
def build_transformer(cfg,default_args=None):
"""Builder for Transfomer."""
return build_from_cfg(cfg,TRANSFORMER,default_args)
def build_positional_encoding(cfg,default_ar... | python |
from sports.nba.nba_team import NBA_Team
class HoustonRockets(NBA_Team):
"""
NBA Golden State Warriors Static Information
"""
full_name = "Houston Rockets"
name = "Rockets"
team_id = 1610612745
def __init__(self):
"""
"""
super().__init__()
| python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-02-17 09:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0043_backend_filteredlanguage'),
]
operations = [
migrations.AddFi... | python |
import sys
import secrets
from toolbox._common import PlaybookRun
class OCMAddon:
"""
Commands for managing OCM addons
"""
@staticmethod
def install(ocm_refresh_token, ocm_cluster_id, ocm_url, ocm_addon_id, wait_for_ready_state=False):
"""
Installs an OCM addon
Args:
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-31 08:21
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('first_app', '0005_inventory'),
]
operations = [
... | python |
import random
from shop import db
from shop.models import Menu, Computers
class Computer:
computers = 1
def __init__(self):
self.name = "Model: MacBook {}".format(self.computers)
self.price = random.randint(20000, 30000)
self.currency = '₽'
self.disk_size = "Disk size:{} Gb".f... | python |
import math
from collections import OrderedDict
from typing import Optional, Dict, List, Union
import numpy
import shapely.geometry
from OpenGL.GL import GL_RGB8
from pyrr import Vector3
from rasterio import features
from rasterio import transform
from rasterstats import zonal_stats
from shapely.geometry import Polygo... | python |
# Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
from gevent import monkey; monkey.patch_all()
from nose.tools import assert_raises
import mock
from . import scheduler as _
from config import config_value
from job import Job
from digits.utils import subclass, override
class TestScheduler():
... | python |
from pathlib import Path
from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, SubmitField
from wtforms.validators import DataRequired
path = Path(".")
forecast = sorted(path.glob("data/forecast_*.json"), reverse=True)
choices = [(p, p) for p in forecast]
class YearSelectForm(FlaskForm):
year ... | python |
"""
1. Clarification
2. Possible solutions
- Brute force
- HashMap
3. Coding
4. Tests
"""
# T=O(n^2), S=O(1)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
if len(nums) < 2: return [-1, -1]
for i in range(len(nums)):
for j in range(i + 1, len(nums)... | python |
import enum
from typing import Dict
class PropertyType(enum.Enum):
HOUSE = 0
FLAT = 1
BUNGALOW = 2
class BuiltForm(enum.Enum):
MID_TERRACE = 0
SEMI_DETACHED = 1
DETACHED = 2
END_TERRACE = 3
class OccupantType(enum.Enum):
OWNER_OCCUPIED = 0
RENTED_PRIVATE = 1
RENTED_SOCIAL =... | python |
import pdb
import logging
import numpy as np
import sys
sys.path.append('..')
import MRATools as mt
def determine_radius(k, h):
if k==0:
raise ValueError("Ensemble size must be stricly positive")
s = np.floor(np.sqrt(k))
if s % 2==0:
sf = s-1
else:
sf = s
if k==sf**2... | python |
# -*- coding: utf-8 -*-
"""Code for creating diagrams."""
| python |
from .confirmationwindow import ConfirmationWindow
from .menu import Menu
from .popupwindow import PopupWindow
from .scrollselector import ScrollSelector
from .filemenu import FileMenu
__all__ = ["PopupWindow","ScrollSelector",
"ConfirmationWindow","Menu",
"FileMenu"]
| python |
from typing import Optional
import torch
from anndata import AnnData
from scvi.model import SCVI
use_gpu = torch.cuda.is_available()
def unsupervised_training_one_epoch(
adata: AnnData,
run_setup_anndata: bool = True,
batch_key: Optional[str] = None,
labels_key: Optional[str] = None,
):
if run_... | python |
from jmanager.utils.print_utils import get_progress_text
PROGRESS_TEXT = "test |========================= | 50.0%"
class TestPrintUtils:
def test_get_progress_text(self):
assert get_progress_text(msg="test", iteration=1, total=2) == PROGRESS_TEXT
| python |
import numpy as np
def get_pieces_count(state):
count = 0
for s in state:
if s.isalpha():
count += 1
return count
def is_kill_move(state_prev, state_next):
return get_pieces_count(state_prev) - get_pieces_count(state_next)
def create_position_labels():
labels_array = []
l... | python |
import numpy as np
import theano
import theano.tensor as T
import util
def vanilla(params, gradients, opts):
return [(param, param - opts.learning_rate * gradient)
for param, gradient in zip(params, gradients)]
def momentum(params, gradients, opts):
assert opts.momentum >= 0.0 and opts.momentum <... | python |
distancia = float(input('Qual é a distancia da sua viagem?' ))
print('voce esta prestes a começa uma viagem de {}km.'.format(distancia))
preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45
print('É o preço da sua passagem sera de R${:2f}'.format(preço))
opcao4 = ''
while opcao4!= 'S' and opcao4 != 'N':
... | python |
# ### 1.5 function that post process the ccs results
import numpy as np
import pandas as pd
# define a function that could calculate the overall annual emission and lock emission
def bau_ccs_post (df):
coal_annual_existing_emission = df.loc[:,('coal_power_annual_emission_existing')].values
coal_annual_n... | python |
from bokeh.models import HoverTool, ColumnDataSource
from bokeh.plotting import figure, output_file, show
from bokeh.models.markers import marker_types
import bokeh.layouts
import datetime
import numpy as np
import DownloadData
age, year_week, data = DownloadData.incidence()
np_data = np.array(data)
np_data[np_data ... | python |
#!/usr/bin/env python
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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... | python |
#!/usr/bin/env python3
"""
Author : Ken Youens-Clark <kyclark@gmail.com>
Date : 2020-11-11
Purpose: Find patterns in files
"""
import argparse
import re
from typing import List, NamedTuple, TextIO
class Args(NamedTuple):
""" Command-line arguments """
pattern_file: TextIO
search_files: List[TextIO]
... | python |
#!/usr/bin/env python3
from __future__ import division, absolute_import, print_function, unicode_literals
import subprocess
import re
import time
import sys
import argparse
import yaml
from timeparse import timeparse
def call(args):
return '\n'.join(subprocess.check_output(args).decode().splitlines())
def get_a... | python |
from durabledict.base import DurableDict
from durabledict.encoding import NoOpEncoding
class MemoryDict(DurableDict):
'''
Does not actually persist any data to a persistant storage. Instead, keeps
everything in memory. This is really only useful for use in tests
'''
def __init__(self, autosync... | python |
# Copyright (c) The InferLO authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 - see LICENSE.
import random
from copy import copy
from functools import reduce
from typing import List, Optional
import numpy as np
from .factor import Factor, product_over_
from .graphical_model impo... | python |
import itertools
from collections import defaultdict, OrderedDict, Counter, namedtuple, deque
# defaultdict can define default_factory where
# accessing a key which does not exist, creates it with a default value
# and the default value is returned
# commonly used to append to lists in dictionaries
dd1 = defaultdict... | python |
#!/usr/bin/python3
from evdev import InputDevice, categorize, ecodes
import configparser, os
config = configparser.ConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__))+'/config.ini')
def sysrun(command):
os.system(command+ " &")
dev = InputDevice(config["DEVICE"]["path"])
dev.grab()
for event in d... | python |
from .colored import (
info,
error,
fatal
)
from .get_env_var import get_env_var
from .sync_to_async import sync_to_async
__ALL__ = (
'info',
'error',
'fatal',
'get_env_var',
'sync_to_async'
)
| python |
from .doc import AssemblyDocCommand
from .helpers import instruction_set
from .helpers import support_set
from .completion import completionListener
from .context import ContextManager
__all__ = ["AssemblyDocCommand", "instruction_set","support_set", "completionListener", "ContextManager"]
| python |
#!/usr/bin/python
# Filename: ex_for.py
for i in range(0, 5):
print("{0}: hello".format(i))
print('The for loop is over')
| python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# ============================================================================
# Erfr - One-time pad encryption tool
# Extractor script
# Copyright (C) 2018 by Ralf Kilian
# Distributed under the MIT License (https://opensource.org/licenses/MIT)
#
# Website: http://www.ur... | python |
import logging
g_logger = None
def get_logger():
return g_logger
def configure_logging(name: str, level: int = logging.DEBUG):
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=level)
global g_logger
g_logger = logging.getLogger(name=name)
g_logger.debug(... | python |
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from scipy import linalg
import torchvision
from torchvision import datasets, transforms
from Tools import FLAGS
def get_dataset(train, subset):
transf = transforms.Compose(
[transforms.ToTensor(), transforms.Normaliz... | python |
from collections.abc import Container
class MyContainer(Container):
def __init__(self, value):
self.data = value
def __contains__(self, value):
return value in self.data
| python |
# names, grades, attributes, sentences
names = ['Tom', 'Fred', 'Harry', 'Hermione', 'Ron', 'Sarah', 'Ele', 'Mike', 'Peter']
subjects = ['Maths','Science','English', 'Arts', 'Music', 'German', 'French', 'PE']
grade_adjective = {
1: ['terrible', 'horrible'],
2: ['below average', 'mediocre'],
3: ['Average', 'A... | python |
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.decorators import protected_resource
import json
from datetime import datetime
from django.utils import timezone
from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Dataset, User, Qu... | python |
# Copyright 2020 Google LLC. 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
#
# Unless required by applicable law or a... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import argv
import bottle
from bottle import default_app, request, route, response, get
from pymongo import MongoClient
import json
import api
bottle.debug(True)
def enable_cors(fn):
def _enable_cors(*args, **kwargs):
# set CORS headers
resp... | python |
class Pelicula:
# Constructor de clase
def __init__(self, titulo, duracion, lanzamiento):
self.titulo = titulo
self.duracion = duracion
self.lanzamiento = lanzamiento
print("Se ha creado la pelicula", self.titulo)
# Redefinimos el metodo String
def __str__(self):
... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randint
import time,sys
braille = ['⣽','⢿','⣻','⡿','⣾','⣟','⣯','⣷']
z = len(braille)
for x in range(10):
r = (randint(0,z-1))
sys.stdout.write("Working " + braille[r] + " " + str(x*10) + "% done" )
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("... | python |
# Generated by Django 3.0.4 on 2020-03-30 20:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0002_auto_20200330_1310'),
]
operations = [
migrations.RenameField(
model_name='product',
old_name='descrtiption',
... | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Title : 字符串工具类
@File : string_utils.py
@Author : vincent
@Time : 2020/9/15 11:14 上午
@Version : 1.0
'''
import os
def is_null(obj):
if obj is None:
return True
if len(obj) == 0:
return True
def list_2_str(str_list):
r_str = '... | python |
# Generated by Django 2.2.10 on 2020-02-27 14:37
from django.db import migrations, models
def nullify_courserun_expiration_dates(apps, schema_editor):
"""
Unset all of the expiration dates set automatically by the previous code.
We are moving to empty expiration dates by default and only explicitly setti... | python |
# Generated by Django 3.0.4 on 2020-03-11 21:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kegs', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='beer',
name='description',
fie... | python |
# Generated by Django 3.1.14 on 2022-03-24 11:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('feedback', '0030_auto_20220324_0947'),
]
operations = [
migrations.AddField(
model_name='report',
name='eid',
... | python |
from http import HTTPStatus
from django.urls import resolve, reverse
from mock import patch
from barriers.views.public_barriers import PublicBarrierDetail
from core.tests import MarketAccessTestCase
class PublicBarrierViewTestCase(MarketAccessTestCase):
def test_public_barrier_url_resolves_to_correct_view(self)... | python |
from __future__ import absolute_import
from __future__ import unicode_literals
import multiprocessing
import os
import sys
import mock
import pytest
import pre_commit.constants as C
from pre_commit.languages import helpers
from pre_commit.prefix import Prefix
from pre_commit.util import CalledProcessError
from testi... | python |
import requests
import os
import shutil
from constants import chromedriverPath
# Constants
chromedriverUrl = 'https://chromedriver.storage.googleapis.com/89.0.4389.23/chromedriver_win32.zip'
chromedriverFile = 'chromedriver.zip'
def downloadFile(url, name):
r = requests.get(url, allow_redirects=True)
... | python |
import turtle
###################################################
# range = antal gange
# rigth or left = grader til højre eller venstre
# forward or backward = længde på streg + retning fremad/tilbage
# kan man tegne flere samtidig? hvordan
###################################################
<<<<<<< HEAD
for n in ran... | python |
# __init__.py
from cogs.add import add
from cogs.add import add_all
from cogs.apply import apply
from cogs.clear import clear
from cogs.connect import connect
from cogs.delete import delete
from cogs.diff import diff
from cogs.fetch import fetch
from cogs.ignore import ignore
from cogs.init import init
from cogs.ls imp... | python |
class ActivationFrame():
def __init__(self, owner):
self.owner = owner
self.static_link = None
self.dynamic_link = None
self.params = []
self.local_vars = []
self.static_vars = []
self.external_vars = []
self.temp_vars = []
self.previous_PC = ... | python |
#4. Crie um código em Python que receba uma lista de nomes informados pelo usuário com tamanho indefinido (a lista deve ser encerrada quando o usuário digitar 0) e, na sequência, receba um nome para que seja verificado se este consta na lista ou não. Observação: ignorar diferenças entre maiúsculas e minúsculas.
nomes =... | python |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("BSC Indicator"),
"items": [
{
"type": "doctype",
"name": "BSC Initiative Log",
"description":_("BSC Initiative Log"),
"onboard": 1,
"dependencies": ["BSC Initiative"],
},
{
... | python |
# -*- coding: utf-8 -*-
"""
空白模板
"""
###### 欢迎使用脚本任务,首先让我们熟悉脚本任务的一些使用规则 ######
# 详细教程请在AI Studio文档(https://ai.baidu.com/ai-doc/AISTUDIO/Ik3e3g4lt)中进行查看.
# 脚本任务使用流程:
# 1.编写代码/上传本地代码文件
# 2.调整数据集路径以及输出文件路径
# 3.填写启动命令和备注
# 4.提交任务选择运行方式(单机单卡/单机四卡/双机四卡)
# 5.项目详情页查看任务进度及日志
# 注意事项:
# 1.输出结果的体积上限为20GB,超过上限可能导致下载输出失败.
# 2.脚本任务... | python |
# Generated by Django 2.1.7 on 2019-06-03 05:56
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('blog', '0015_auto_20190601_2202'),
]
operations = [
migrations.AlterField(
... | python |
from flask_babel import lazy_gettext as _
from .model import (
Session,
CirculationEvent,
ExternalIntegration,
get_one,
create
)
class LocalAnalyticsProvider(object):
NAME = _("Local Analytics")
DESCRIPTION = _("Store analytics events in the 'circulationevents' database table.")
# A g... | python |
import shutil, ssl, json
import requests, zipfile, gzip, io
import pandas as pd
from tbsdq import utilities as dqutils
from tbsdq import configuration as dqconfig
from topN import configuration as topnconfig
""" Non-Spatial dataset analysis on the open data registry """
def fetch_and_parse_catalogue(zip_url, expecte... | python |
from django.contrib.auth.models import Permission
class TestPermissionsMixin:
def _clean_permissions(self):
self.user.user_permissions.clear()
self._clean_perm_cache()
def _set_permissions(self, perms):
self.user.user_permissions.add(
*Permission.objects.filter(codename__... | python |
# -*- coding: utf-8 -*-
"""
github3.repos.commit
====================
This module contains the RepoCommit class alone
"""
from __future__ import unicode_literals
from . import status
from .. import git, models, users
from .comment import RepoComment
class RepoCommit(models.BaseCommit):
"""The :class:`RepoCommi... | python |
from pymusicterm.util.time import milliseconds_to_minutes, milliseconds_to_seconds
from py_cui.widgets import Widget
class LoadingBarWidget(Widget):
BAR_COMPLETED_CHAR=u'\u2588'
def __init__(self,id,title,grid,row,column,row_span,column_span,padx,pady,logger) -> None:
""" Initializer for Loading... | python |
import json
from typing import List, Dict, Union
import bleach
allowed_items = {
"section", "subsection", "link"
}
allowed_sub_items = {
"title",
"url",
"metadata",
"desc",
"commentary"
}
def clean_submission(upload_post: str) -> List[Union[str, Dict[str, str]]]:
output = []
for reso... | python |
import psycopg2 as pg
from psycopg2.extras import DictCursor
from getpass import getpass
##############
# Connecting #
##############
cx = pg.connect(
host='localhost', database='abq',
user=input('Username: '),
password=getpass('Password: '),
cursor_factory=DictCursor
)
cur = cx.cursor()
##################... | python |
def train(model, link_predictor, emb, edge_index, pos_train_edge, batch_size, optimizer):
"""
Runs offline training for model, link_predictor and node embeddings given the message
edges and supervision edges.
1. Updates node embeddings given the edge index (i.e. the message passing edges)
2. Compute... | python |
from .base import TemplateView
class Index(TemplateView):
template_name = 'feats/index.html'
| python |
from github import GitHub
username = "github_username"
db_path_account = "C:/GitHub.Accounts.sqlite3"
db_path_api = "C:/GitHub.Apis.sqlite3"
g = GitHub.GitHub(db_path_account, db_path_api, username)
g.repo.create('repository_name', description='this is repository description.', homepage='http://homepage.com')
| python |
#!/usr/bin/env python2.7
import argparse
import sys
import rospy
import tf
from gazebo_msgs.srv import GetLinkState, GetLinkStateRequest
parser = argparse.ArgumentParser()
parser.add_argument("object_name", help="Name of the object")
parser.add_argument("link_name", help="Link of the object")
parser.add_argument("wor... | python |
import json
from datetime import date
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
f... | python |
from flask import Flask, request, Response
import json
import numpy as np
import gpt_gen
import gpt_gen_thread
import sys
import time
import logging
import torch
from Config import config_predict
from datetime import datetime
ConfigPredict = config_predict()
batchGenerating=ConfigPredict.batchGenerating
path_configs = ... | python |
import pickle
class Carro:
def __init__(self, modelo, cor):
self.modelo = modelo
self.cor = cor
def __repr__(self):
return f'Carro(modelo="{self.modelo}", cor="{self.cor}")'
carro_1 = Carro('Celta', 'Prata')
data = {
'a': 'Eduardo',
'b': 'Banans',
'c': [1, 2, 3, 4],
... | python |
"""
1579. Remove Max Number of Edges to Keep Graph Fully Traversable
Hard
Alice and Bob have an undirected graph of n nodes and 3 types of edges:
Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can by traversed by both Alice and Bob.
Given an array edges where edges[i] = [typei, ... | python |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
requires = [
'cornice',
'gevent',
'pyramid_exclog',
'setuptools',
'couchdb',
'couchapp',
'pycrypto',
'openpro... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.