content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from azur... | python |
import myhdl
from myhdl import intbv
from rhea import Constants
from rhea.system import Bit, Byte
from rhea.system import ControlStatusBase
from ..misc import assign
class ControlStatus(ControlStatusBase):
def __init__(self):
""" The control-status object for the SPI controller
Attributes:
... | python |
from django.forms.widgets import Widget, Media
from django.utils.safestring import mark_safe
import django.utils.copycompat as copy
class MultiWidgetLayout(Widget):
"""
Django's built-in MultiWidget is a widget that is composed of multiple widgets.
MutliWidtetLayout implements the same concept but the ren... | python |
#!/usr/bin/env python2
# coding: utf-8
# Parses decompiled Java source and re-generates a Thrift interface file.
import re
import sys
import os
from os import path
thrift_type_names = [
None,
"void",
"bool",
"byte",
"double",
None,
"i16",
None,
"i32",
None,
"i64",
"str... | python |
from collections import namedtuple
class FilePath(
namedtuple('FilePath', [
'subject', 'filetype', 'load_path', 'save_path', 'bad_channel_path'
])):
__slots__ = ()
def __new__(cls,
subject,
filetype,
load_path,
save_p... | python |
"""
"A Simple Domain Shifting Network for Generating Low Quality Images" implementation
Step 2: Training simple convolutional regressor to mimic Cozmo camera.
"""
import torch
from torchvision import datasets
import numpy as np
import torchvision.transforms as transforms
from PIL import Image
import os
from torch.ut... | python |
def digitize(num: int) -> list:
if num == 0:
return [0]
my_digitize = []
while num != 0:
l = num % 10
my_digitize.append(l)
num = (num - l) // 10
return list(reversed(my_digitize))
| python |
#================================Params.py=====================================#
# Created by Ciaran O'Hare 2019
# Description:
# This file just sets up some of the parameters that are used throughout the
# project. and some classes that link things together.
#=========================================================... | python |
num1 = 111
num2 = 222
num3 = 3333
num4 = 444444444444
num4 = 44444
num5 = 5555
| python |
"""empty message
Revision ID: 5c63a89ee7b7
Revises: 9afbd55082a0
Create Date: 2021-09-29 10:24:20.413807
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5c63a89ee7b7'
down_revision = '9afbd55082a0'
branch_labels = None
depends_on = None
def upgrade():
# ... | python |
import unittest
from model.shsamodel import *
class SHSAModelTestCase(unittest.TestCase):
"""Tests SHSA model."""
def setUp(self):
self.__graph_dict = {
'a': ['d'],
'b': ['c'],
'c': ['b', 'c', 'd'],
'd': ['a', 'c'],
# unconnected nodes are n... | python |
# Copyright 2017 Starbot Discord Project
#
# 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... | python |
from minesweeper.logic import FLAG, OPEN, Square, MINE
def test_not_open():
value = FLAG | 1
s = Square.from_triple(0, 0, value)
assert not s.open
assert not s.value
def test_flag():
value = OPEN | 1
s = Square.from_triple(0, 0, value)
assert s.open
assert s.value == 1
def test_ope... | python |
# model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='Central_Model',
pretrained='checkpoints/up-g/mnb4-cls-bn.pth',
backbone_name='MTB4',
task_names=('gv_patch', 'gv_global'),
main_task_name='gv_global',
trans_type='crossconvhrnetlayer',
... | python |
from pathlib import Path
import argparse
import pandas as pd
import os
HERE = os.path.abspath(os.path.dirname(__file__))
DEFAULT_CONFIG_FILE = os.path.join(HERE, "config_templates",
"default_configs.txt")
DATASET_STATS = os.path.join(HERE, "dataset_stats", "dataset_stats.tsv")
def ... | python |
from abc import ABCMeta,abstractclassmethod
class PocInterface(metaclass=ABCMeta):
'''
POC 实现接口
'''
@abstractclassmethod
def validate(self,*args,**kwargs):
'''
漏洞验证接口方法
:param args: 自定义参数
:param kwargs: 自定义参数
:return: 自定义,建议存在返回True,否则返回False
'''
... | python |
from collections import OrderedDict
import requests
from civis import APIClient
from civis.base import EmptyResultError
def file_to_civis(buf, name, api_key=None, **kwargs):
"""Upload a file to Civis.
Parameters
----------
buf : file-like object
The file or other buffer that you wish to upl... | python |
# imports
import datetime as dt
import psycopg2
# db global variables
HOST = 'localhost'
USER = 'postgres'
PASSWORD = 'Master/99'
DATABASE = 'job_apps'
print('Initiating database connections.')
# db connection
conn = psycopg2.connect(host=HOST, database=DATABASE,
user=USER, password=PASSWORD... | python |
from . import blockcipher
from . import pkc
from . import keyexchange
from . import signature | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from datastruct.list.node import SNode
def reverse_order_output(head, res=None):
if head is None:
return []
if res is None:
res = []
res = reverse_order_output(head.next, res)
res.append(head.value)
return res
def find_intersectio... | python |
from core import analyzer, element
from ui import run
element_type = {
"Resistance": element.Resistance,
"CurrentSource": element.CurrentSource,
"VoltageSource": element.VoltageSource,
"CCCS": element.CCCS,
"VCCS": element.VCCS,
"CCVS": element.CCVS,
"VCVS": element.VCVS
}
def solve(data... | python |
__all__ = [
"ConjugateGradient",
"NelderMead",
"ParticleSwarm",
"SteepestDescent",
"TrustRegions",
]
from .conjugate_gradient import ConjugateGradient
from .nelder_mead import NelderMead
from .particle_swarm import ParticleSwarm
from .steepest_descent import SteepestDescent
from .trust_regions impo... | python |
# Generated by Django 3.0.1 on 2019-12-21 20:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('tacos', '0004_auto_20191... | python |
import ipaddress
import logging
import time
import uuid
import redis
from haipproxy.settings import (
REDIS_HOST,
REDIS_PORT,
REDIS_DB,
REDIS_PIPE_BATCH_SIZE,
LOCKER_PREFIX,
)
logger = logging.getLogger(__name__)
REDIS_POOL = None
#### redis ####
def get_redis_conn():
global REDIS_POOL
... | python |
f = open("latency", "w")
for x in range(0,100):
for y in range(0,100):
if(x == y):
f.write("0")
else:
f.write("100")
if(y != 99):
f.write(" ")
f.write('\n')
f.close()
| python |
from config.config import IMDB_BASE_URL
class MovieResponse:
# TODO: refactor this - use named parameters
def __init__(self, *vargs):
self.movie_id = vargs[0]
self.imdb_url = IMDB_BASE_URL + self.movie_id + "/"
self.title = vargs[1]
self.directors = vargs[2]
self.actors... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 10:11:05 2019
@author: alheritier
"""
from pykds import KDSForest
import numpy as np
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
dim = data.data.shape[1]
alpha_label= len(np.unique(data.target))
m = KDSForest(ntrees=1,se... | python |
import luigi
import json
import time
import re
import datetime
import subprocess
import base64
from urllib import urlopen
import uuid
from uuid import uuid4
from uuid import uuid5
from elasticsearch import Elasticsearch
#for hack to get around non self signed certificates
import ssl
import sys
# TODO
# * I think we wa... | python |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated 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 ... | python |
import weakref
import numpy as np
import qmhub.helpmelib as pme
from .dobject import cache_update
class DependPME(pme.PMEInstanceD):
def __init__(self, cell_basis, alpha, order, nfft):
super().__init__()
self._name = "PME"
self._kwargs = {"alpha": alpha, "order": order, "nfft": nfft}
... | python |
import torch
import torch.nn as nn
class NeuralColumn(nn.Module):
def __init__(self, channels: int, output_dim: int) -> None:
""" channels is the number of output convolution channels for
each convolution layer of the network, except the last one.
"""
super(NeuralColumn, self).... | python |
"""D-Bus interface objects."""
from .systemd import Systemd
from .hostname import Hostname
from .rauc import Rauc
from ..coresys import CoreSysAttributes
class DBusManager(CoreSysAttributes):
"""A DBus Interface handler."""
def __init__(self, coresys):
"""Initialize D-Bus interface."""
self.... | python |
from enforce_typing import enforce_types
from engine import AgentBase
from agents.PublisherAgent import PublisherAgent
from agents.SpeculatorAgent import StakerspeculatorAgent
from agents.DataconsumerAgent import DataconsumerAgent
@enforce_types
class DataecosystemAgent(AgentBase.AgentBaseNoEvm):
"""Will operate... | python |
from django.core.management.commands.test import Command as TestCommand
from jsdir.core import JSDir
class Command(TestCommand):
def __init__(self):
JSDir.set_use_finders(True) # sets the value only for this thread
super(Command, self).__init__()
| python |
import matplotlib as mil
import tensorflow as tf
from matplotlib import pyplot
fig = pyplot.gcf()
fig.set_size_inches(4, 4)
sess = tf.InteractiveSession()
image_filename = "/home/ubuntu/Downloads/n02107142_16917.jpg"
filename_queue = tf.train.string_input_producer([image_filename]) # list of files to read
reader... | python |
#
# Copyright (C) 2014-2015 UAVCAN Development Team <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
# Author: Ben Dyer <ben_dyer@mac.com>
# Pavel Kirienko <pavel.kirienko@zubax.com>
#
from __future__ import division, absolute_import, print_function, unicode_literals
import... | python |
from .binarytree import BinaryTree
class LinkedBinaryTree(BinaryTree):
""" Linked reperesentation of a binary tree structure. """
class _Node: # Ligtweight non-public class for storing a node
__slots__ = '_element', '_parent', '_left', '_right'
def __init__(self, element, parent=None, lef... | python |
import logging
from helper import is_welsh
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class CoursesBySubject:
def __init__(self, mapper, language):
self.mapper = mapper
self.language = language
def group(self, courses, limit, of... | python |
import copy
import numpy
def convert_to_binary(list_of_digits):
list_of_str_digits = [str(digit) for digit in list_of_digits]
return int("".join(list_of_str_digits), 2)
with open("data/day3.txt") as f:
# The entire input forms a matrix of integers, parse it as such.
matrix = [[int(num) for num in l... | python |
# Copyright 2018 The ops Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | python |
# -*- coding: utf-8 -*-
"""
KJ-65X9500G の輝度制限と階調特性の関係調査
=========================================
Description.
"""
# import standard libraries
import os
# import third-party libraries
import numpy as np
from colour import write_image
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
# impor... | python |
import pytest
from openpecha.utils import download_pecha
@pytest.mark.skip("Downloading github repo")
def test_download_pecha():
pecha_path = download_pecha("collections")
| python |
# Generated by Django 2.2 on 2020-08-11 11:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Iniciativa',
fields=[
('id', models.AutoField... | python |
from dsame.trees.BinaryTreeNode import BinaryTreeNode
def inOrder(root: BinaryTreeNode):
if root:
inOrder(root.left)
print(root.data)
inOrder(root.right)
a = BinaryTreeNode(2)
b = BinaryTreeNode(3)
c = BinaryTreeNode(1, a, b)
print(inOrder(c))
| python |
import os
from ast import literal_eval
from pathlib import Path
import numpy as np
def read_info(filename: os.PathLike) -> dict:
"""Read volume metadata.
Parameters
----------
filename : PathLike
Path to the file.
Returns
-------
dct : dict
Dictionary with the metadata.
... | python |
import time
from options.train_options import TrainOptions
opt = TrainOptions().parse() # set CUDA_VISIBLE_DEVICES before import torch
import pickle
from data.custom_transforms import ToLabelTensor
# with open("opt.obj",'wb') as f:
# pickle.dump(opt,f)
from data.segmentation import SegmentationDataset
from models... | python |
from ...attribute import models as attribute_models
from ...discount import models as discount_models
from ...product import models as product_models
from ...shipping import models as shipping_models
def resolve_translation(instance, _info, language_code):
"""Get translation object from instance based on language... | python |
# Generated by Django 3.0.13 on 2021-04-01 08:17
from django.db import migrations, models
import ensembl.production.djcore.models
class Migration(migrations.Migration):
dependencies = [
('ensembl_dbcopy', '0005_targethostgroup'),
]
operations = [
migrations.AlterField(
model... | python |
from __future__ import absolute_import
import logging
# App must be initialized before models or ADDONS_AVAILABLE are available
from website.app import init_app
init_app()
from osf.models import OSFUser, AbstractNode
from framework.database import paginated
from scripts.analytics.base import SnapshotAnalytics
from w... | python |
#!/usr/bin/env python3
#class dedicated to archival functions for dnmt data
import re
import sys
import subprocess,platform,os,time,datetime,zipfile
import difflib
import pickle
import collections
# import pysvn
# import git
#3rd party imports
#local subroutine import
from DNMT.procedure.subroutines import SubRou... | python |
# Django
from django.db import models
class UserAbstractModel(models.Model):
""" Modelo basico abstracto.
UserAbstractModel es una clase abstracta de la que heredan
todos los modelos de User de la API. Esta clase provee
los siguientes atributos:
+ created (DateTime): Almacena la fecha de creacio... | python |
from time import perf_counter
def timer(func):
def wrapper(*args, **kwargs):
start_t = perf_counter()
r_val = func(*args, **kwargs)
end_t = perf_counter()
elapsed = end_t - start_t
print(f"{func.__name__} took time: {elapsed} seconds, {elapsed/60} minutes")
return r... | python |
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import MetodPage
def metod(request):
metods = MetodPage.objects.all().order_by('title')
paginator = Paginator(metods, 10)
page = request.GET.get('page')
try:
... | python |
import itertools
def subpaths_for_path_range(path_range, hardening_chars="'pH"):
"""
Return an iterator of paths
# examples:
# 0/1H/0-4 => ['0/1H/0', '0/1H/1', '0/1H/2', '0/1H/3', '0/1H/4']
# 0/2,5,9-11 => ['0/2', '0/5', '0/9', '0/10', '0/11']
# 3H/2/5/15-20p => ['3H/2/5... | python |
#!/usr/bin/env python3
"""
Play Nerdle (https://nerdlegame.com)
"""
import json
import logging
from itertools import product
from os import mkdir
from os.path import dirname, join, realpath
from typing import Any, Iterator, List, Optional, Tuple
from .exceptions import CorrectAnswer, OutOfEquations, OutOfGuesses
cla... | python |
from dbt.contracts.graph.manifest import Manifest
import os
from test.integration.base import DBTIntegrationTest, use_profile
def get_manifest():
path = './target/partial_parse.msgpack'
if os.path.exists(path):
with open(path, 'rb') as fp:
manifest_mp = fp.read()
manifest: Manifest... | python |
import time
from base.common.skeleton_base import SkeletonBase
from base.constants import DEFAULT_BEFORE_EXPIRES
from base.exceptions import ChannelTemplateNotFound
from base.helpers import validate_channel
from base.utils import format_response
from typing import Dict
from .router import *
from .webhook import *
fro... | python |
from django.forms.widgets import CheckboxSelectMultiple, RadioSelect
class RadioSelectBootstrap(RadioSelect):
template_name = "leprikon/widgets/multiple_input.html"
option_template_name = "leprikon/widgets/input_option.html"
class CheckboxSelectMultipleBootstrap(CheckboxSelectMultiple):
template_name = ... | python |
import pandas as pd
class LeakageInspector:
def __init__(self, df1, df2, patient_col):
"""
Args:
df1 (dataframe): dataframe describing first dataset
df2 (dataframe): dataframe describing second dataset
patient_col (str): string name of column with patient IDs
"""
self.df1 = df1
self.df2 = df... | python |
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name="Pairtree",
version="0.7.5",
description="Pairtree FS implementation.",
long_description="""\
From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html : Pairtree, a filesystem hierarc... | python |
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from pages.createprojectpage.questionnaire_creation_options_page import QuestionnaireCreationOptionsPage
from pages.dashboardpage.dashboard_locator import *
from pages.page import Page
class DashboardPage(Page):
def __init__(self, driver):
Page.__init__(self, dr... | python |
'''Use this for development'''
from .base import *
ALLOWED_HOSTS += ['127.0.0.1']
DEBUG = True
WSGI_APPLICATION = 'home.wsgi.dev.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'sarytask',
'USER': 'postgres',
'PASSWORD': 'S3d6622... | python |
import re
from jinja2.filters import contextfilter
@contextfilter
def to_dockbarx_items(context, pin_to_launcher_favorites):
'''
returns the DockbarX launcher items
'''
pin_to_launcher_favorites = list(pin_to_launcher_favorites)
omit = context.resolve('omit')
launcher_items = []
for f... | python |
import collections
import itertools
import typing
from checkmerge import analysis, report
class AnalysisResultMaxSeverityMetric(report.Metric):
"""
Metric for the maximum analysis result severity within a type.
"""
name = 'Max. severity'
low = .5
high = 1.5
def __init__(self, items: typi... | python |
"""
parser.py
products.json의 반찬 상세 페이지 url에 요청을 보내 크롤링하는 메소드 정의
메소들을 crawl.py 파일에서 사용함
"""
import requests
from bs4 import BeautifulSoup
import re
def get_soup(url):
webpage = requests.get(url).text
soup = BeautifulSoup(webpage, 'lxml')
return soup
def parse_name(name):
# content에 중량이 포함되어 있는지 체크
... | python |
import pandas as pd
import os
import sys
import subprocess
import numpy as np
import streamlit as st
import time
import random
from random import randint
from streamlit_player import st_player
from streamlit_autorefresh import st_autorefresh
import altair as alt
import back as fl
import usessss as fh
... | python |
GREY = (0.78, 0.78, 0.78) # uninfected
RED = (0.96, 0.15, 0.15) # infected
GREEN = (0, 0.86, 0.03) # recovered
BLACK = (0, 0, 0) # dead
COVID19_PARAMS = {
"r0": 2.28,
"incubation": 5,
"percent_mild": 0.8,
"mild_recovery": (7, 14),
"percent_severe": 0.2,
"severe_recovery": (21, 42... | python |
from troposphere import FindInMap, GetAtt, Join, Output, Parameter, Ref, Template
from troposphere.awslambda import MINIMUM_MEMORY, MAXIMUM_MEMORY, Code, Function
from troposphere.cloudformation import CustomResource
from troposphere.constants import NUMBER
from troposphere.ec2 import Instance, SecurityGroup
from tropo... | python |
from flask import Flask, render_template, redirect
app = Flask(__name__)
#--- routes start ---
from user import routes
@app.route("/")
def home():
return render_template('home.html')
@app.route("/login/")
def login_page():
return render_template('login.html')
@app.route("/about/")
def about():
return ... | python |
# qmpy/materials/element
"""
Django models representing elements and species.
"""
from django.db import models
from qmpy.db.custom import DictField
from qmpy.utils import *
class Element(models.Model):
"""
Core model for an element.
Relationships:
| :mod:`~qmpy.Atom` via atom_set
| :mod:`~... | python |
# # coding=utf-8
import unittest
import uuid
from google.appengine.ext import testbed
from application import create_app
from application.routes import create_routes
class FlaskClient(unittest.TestCase):
def setUp(self):
self.tb = testbed.Testbed()
self.tb.activate()
self.tb.init_memcache_... | python |
# -*- coding: utf-8 -*-
from django.db import models
from django.template.defaultfilters import date
from django.core.validators import MinValueValidator
from django.urls import reverse_lazy
from decimal import Decimal
from djangosige.apps.vendas.models import TIPOS_DESCONTO_ESCOLHAS, MOD_FRETE_ESCOLHAS, ST... | python |
class Stack(object):
"""This class implements all the need functions for a stack"""
def __init__(self):
self.items = []
def is_empty(self):
"""Returns true if stack is empty, returns false if stack has an
item"""
return self.items == []
def push(self, item):
""... | python |
# Implementacion generica de Arboles de Decisiones.
from math import log, inf
class Node:
def __init__(self, parent, X, Y, atr_types, default):
self.parent = parent
# Ejemplos del entrenamiento que pertenecen a este nodo.
self.X = X
# Etiquetas de los ejemplos.
self.Y = Y
# Tipos de atribut... | python |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class ISCSIDataIn(Base):
__slots__ = ()
_SDM_NAME = 'iSCSI_Data_In'
_SDM_ATT_MAP = {
'HeaderOpcode': 'iSCSI_Data_In.header.Opcode-1',
'HeaderFlags': 'iSCSI_Data_In.header.Flags-2',
'HeaderTotalAHSLength... | python |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This is more akin to a .pyl/JSON file, so it's expected to be long.
# pylint: disable=too-many-lines
from gpu_tests import common_browser_args as cba
from... | python |
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#transform to [[x,y,z]...] [[x...],[y...],[z...]]
#plot
def plot_sample_list(sample_list,lim_val=10):
sample_mat = np.array(sample_list... | python |
### ---------------------------------------------------------------------------
from .core.startup import initialize
from .sublime import commands, events
__version_tuple = (1, 0, 0)
__version__ = ".".join([str(num) for num in __version_tuple])
### ------------------------------------------------------------------... | python |
# coding:utf-8
import redis
SCRIPT_PUSH = '''
local q = KEYS[1]
local q_set = KEYS[1] .. "_set"
local v = redis.call("SADD", q_set, ARGV[1])
if v == 1
then
return redis.call("RPUSH", q, ARGV[1]) and 1
else
return 0
end
'''
SCRIPT_POP = '''
local q = KEYS[1]
local q_set = KEYS[1] .. "_set"
local v = redis.call("LP... | python |
import os
import datetime
os.system("powercfg /batteryreport")
d = datetime.datetime.now()
try:
os.rename('battery-report.html', f'battery-health/reports/battery-report-{d.month}-{d.day}-{d.year}.html')
os.startfile(f'battery-health\\reports\\battery-report-{d.month}-{d.day}-{d.year}.html')
except WindowsError... | python |
import aspose.words as aw
from docs_examples_base import DocsExamplesBase, MY_DIR, ARTIFACTS_DIR
class WorkingWithPclSaveOptions(DocsExamplesBase):
def test_rasterize_transformed_elements(self):
#ExStart:RasterizeTransformedElements
doc = aw.Document(MY_DIR + "Rendering.docx")
... | python |
# MINLP written by GAMS Convert at 04/21/18 13:54:00
#
# Equation counts
# Total E G L N X C B
# 750 619 34 97 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... | python |
import sqlite3
import os
from pomodoro import Pomodoro
os.chdir("..") # Go up one directory from working directory
# Create database if it does not exist
database_path = "data\pomodoros.db"
if not os.path.exists(database_path):
print("Creating database ...")
os.system("database.py")
conn = sqlite3.connect(... | python |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
w,h,k=map(int,input().split());r=0
for _ in [0]*k:
r+=(w+h<<1)-4;w-=4;h-=4
print(r) | python |
# -*- coding: utf-8 -*-
# À partir de l’export csv de https://opendata.paris.fr/explore/dataset/les-titres-les-plus-pretes/
# vous compterez le nombre d’ouvrages par ‘type de document’ et vous afficherez les types par ordre décroissant
from collections import Counter
sep = ';'
cnt = Counter()
with open('les-titres... | python |
#!/usr/bin/env python
#pythonlib
import os
import sys
import math
import re
import time
import glob
import numpy
#appion
from pyami import imagefun
from appionlib import appionLoop2
from appionlib import apImage
from appionlib import apDisplay
from appionlib import apDatabase
from appionlib.apCtf import ctfdb
from app... | python |
import torch
import torch.nn as nn
from models.pytorch_revgrad import RevGrad
from efficientnet_pytorch import EfficientNet as effnet
class EfficientNet(effnet):
def __init__(self, blocks_args=None, global_params=None):
super(EfficientNet, self).__init__(blocks_args=blocks_args, global_params=global_par... | python |
from idm.objects import dp, MySignalEvent, SignalEvent, __version__
from idm.utils import ment_user
from datetime import datetime
import time
@dp.signal_event_register('инфо', 'инфа', 'info')
def sinfo(event: SignalEvent) -> str:
if event.msg['from_id'] not in event.db.trusted_users:
message_id = event.sen... | python |
"""
Title: Video Vision Transformer
Author: [Aritra Roy Gosthipaty](https://twitter.com/ariG23498), [Ayush Thakur](https://twitter.com/ayushthakur0) (equal contribution)
Date created: 2022/01/12
Last modified: 2022/01/12
Description: A Transformer-based architecture for video classification.
"""
"""
## Introduction
V... | python |
import logging.config
import unittest
#import testing.mysqld
import sqlalchemy
from src.utils.Settings import Settings
# Modules to Test
from src.utils.Connector import Connector
class TestConnector(unittest.TestCase):
@classmethod
def tag(cls, *tags):
'''
Decorator to add tags to a test class... | python |
from rsTools.ui.menus import menu
from ... import shelf, shelfButton
from rsTools.glob import *
import os
import rsTools.utils.osUtils.enviroments as env
import maya.cmds as cmds
from rsTools.core.skeleton import skeletonAsset
class skeletonShelfButton(shelfButton.ShelfButton):
_color = (255, 157, 0)
_title =... | python |
# must be first, as it does event loop patching and other "first" things
from common.page_tokens import PageTokenManager
from oozer.entities.collect_entities_iterators import (
iter_collect_entities_per_page,
iter_collect_entities_per_page_graph,
)
from tests.base.testcase import TestCase, mock
from common.enu... | python |
"""
Model
"""
from . import attention
from . import evaluator
from . import GAN_model
from . import GAN_trainer
from . import generator
from . import trainer
| python |
import json
from typing import Dict, Optional
from azure.durable_functions.models.FunctionContext import FunctionContext
class DurableOrchestrationBindings:
"""Binding information.
Provides information relevant to the creation and management of
durable functions.
"""
# parameter names are as de... | python |
# Copyright 2014-2020 Free Software Foundation, Inc.
# 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 3 of the License, or
# (at your option) any later version.
#
# This program i... | python |
"""
Unit Testing
"""
def unittest(tests=None):
"""
A Unit Test wrapper that will return the return code and an error message ( if any )
- Return
Syntax:
{
0 : [return_code_1, error_message_1],
1 : [return-code_2, error_message_2],
}
Type: Dictionary
:: Syntax
tests
Description: The function ... | python |
n = int(input())
m = n
line = input().split()
t = 0
for i in range(0, n):
if int(line[i]) >= 0:
t += int(line[i])
else:
m -= 1
a = t / m
print(a) | python |
import pandas as pd
from pathlib import Path
import sys
import re
from collections import OrderedDict
import pyqtgraph as pg
from pyqtgraph.parametertree import Parameter, ParameterTree
from ephys.ephysanalysis import acq4read
from ephys.mapanalysistools import analyzeMapData as AMD
import pylibrary.tools.fileselector... | python |
first="Akash"
last="Singh"
fname=first+" "+last
print(fname) | python |
# Generated by Django 3.1.5 on 2021-01-13 18:09
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.