text stringlengths 1 927k |
|---|
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class EnhancedspiderSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
#... |
def helper(num):
return ''.join(sorted(str(num)))
def ans():
num = 100000
while True:
string = helper(num)
if all(helper(num * i) == string for i in range(2, 7)):
return num
num += 1
if __name__ == '__main__':
print(ans()) |
#!/usr/bin/env python
#encoding:UTF-8
import eyadisk
def main():
user = 'username'
pwd = 'password'
api = eyadisk.EYaDisk(user=user, pwd=pwd)
api.mkdir('eyadisk')
api.upload('README.MD', '/eyadisk/README.MD')
print api.publish('/eyadisk/README.MD')
if __name__ == '__main__':
main() |
import time
import matplotlib
import numpy as np
matplotlib.use('Agg')
import torch
import torch.nn as nn
class LossMultiTargets(nn.Module):
def __init__(self,loss_fnc=torch.nn.CrossEntropyLoss()):
super(LossMultiTargets, self).__init__()
self.loss = loss_fnc
def forward(self, inputs,target... |
""" Module containing classes that implement the CrawlerUrlData
class in different ways """
# Right now there is just one implementation - the caching URL data
# implementation using helper methods from urlhelper.
import crawlerbase
import hashlib
import zlib
import os
import re
import httplib
import time
from eiii_... |
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Hyper-parameters
sequence_length = 28
input_size = 28
hidden_size = 128
num_layers = 2
num_classes = 10
batch_size = 100
nu... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from object_detection.tf_utils import label_map_util
class LoadLabelMap():
def __init__(self):
return
def load_label_map(self, cfg):
"""
LOAD LABEL MAP
"""
print('Loading label map')
LABEL_PATH = cfg['la... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Krazy Lee'
__email__ = 'lixiangstar@gmail.com'
__version__ = '0.1.0'
from .piu import Piu |
#!/usr/bin/env python
""" generated source for module SymbolFactory """
# package: org.ggp.base.util.symbol.factory
import java.util.ArrayList
import java.util.LinkedList
import java.util.List
import org.ggp.base.util.symbol.factory.exceptions.SymbolFormatException
import org.ggp.base.util.symbol.grammar.Symbol
im... |
#
# @lc app=leetcode id=706 lang=python3
#
# [706] Design HashMap
#
# https://leetcode.com/problems/design-hashmap/description/
#
# algorithms
# Easy (57.83%)
# Likes: 600
# Dislikes: 84
# Total Accepted: 65.7K
# Total Submissions: 112.1K
# Testcase Example: '["MyHashMap","put","put","get","get","put","get", "re... |
# encoding: UTF-8
from sixtypical.ast import (
Program, Routine, Block, SingleOp, Reset, Call, GoTo, If, Repeat, For, WithInterruptsOff, Save, PointInto
)
from sixtypical.model import (
ConstantRef, LocationRef, IndexedRef, IndirectRef,
TYPE_BIT, TYPE_BYTE, TYPE_WORD,
TableType, PointerType, RoutineTyp... |
# -*- coding: utf-8 -*-
from pysignfe.xml_sped import *
from pysignfe.nfe.manual_300 import ESQUEMA_ATUAL
import os
DIRNAME = os.path.dirname(__file__)
class CabecMsg(XMLNFe):
def __init__(self):
super(CabecMsg, self).__init__()
self.versao = TagDecimal(nome=u'cabecMsg' , codigo=u'' , ... |
TAM_MAX_CH = 26
def recebeModo():
"""
Função que pergunta se o usuário quer criptografar ou
decriptografar e garante que uma entrada válida foi recebida
"""
while True:
modo = input("Você deseja criptografar ou decriptografar?\n").lower()
if modo in 'criptografar c decriptografar d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, JooWorld. You're at the j-polls index.") |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/misc/shared_mystical_orb.iff"
result.attribute_template_id = -... |
#python3
#This script will make csv so that graph_timeseries.py can create plots with them!
import pandas as p
MAX_EVAL = 512*512*1000
df = p.read_csv('../Data/Raw/min_programs__eval_262144000.csv')
treat = {}
TREATMENT = 'treatment'
FOUND = 'solution_found'
UPDATE = 'update_found'
EVAL = 'evaluation_found'
POS_UPDAT... |
import sys
from django.utils.timezone import now
try:
from django.db import models
except Exception:
print("There was an error loading django modules. Do you have django installed?")
sys.exit()
from django.conf import settings
import uuid
# Instructor model
class Instructor(models.Model):
user = mode... |
from django.db import models
# Create your models here.
"""
Genre model
This model is used to store information about the book category — for example whether it is fiction or non-fiction,
romance or military history, etc.
The model has a single CharField field (name), which is used to describe the genre (this is li... |
from enum import Enum
import gym
import numpy as np
from gym import spaces
from gym.utils import seeding
class Action(Enum):
decrease_attention = 0
increase_attention = 1
access_detector = 2
isolate_node = 3
forget_node = 4
class State(Enum):
healthy = 0
infected = 1
class MalwareEnv(... |
"""empty message
Revision ID: 7b0843b4944f
Revises: a83fe752a741
Create Date: 2016-08-08 23:12:27.138166
"""
# revision identifiers, used by Alembic.
revision = '7b0843b4944f'
down_revision = 'a83fe752a741'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
# Generated by Django 2.1.15 on 2021-06-30 17:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0003_ingredient'),
]
operations = [
migrations.CreateModel(
... |
from typing import Dict # isort:skip
from alchemy import Logger
from catalyst.dl import utils
from catalyst.dl.core import Experiment, Runner
from catalyst.dl.runner import SupervisedRunner
class AlchemyRunner(Runner):
"""
Runner wrapper with Alchemy integration hooks.
Read about Alchemy here https://a... |
"""Tests for functions that calculate plasma parameters."""
import numpy as np
import pytest
from astropy import units as u
from astropy.constants import m_e, m_p
from astropy.tests.helper import assert_quantity_allclose
from plasmapy.formulary.parameters import (
Alfven_speed,
betaH_,
Bohm_diffusion,
... |
import unittest
import unittest.mock
import xml.etree.ElementTree as ET
from programy.oob.callmom.email import EmailOutOfBandProcessor
from programytest.client import TestClient
class EmailOutOfBandProcessorTests(unittest.TestCase):
def setUp(self):
client = TestClient()
self._client_context = c... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_table('scrum_section', 'scrum_story')
def backwards(self, orm):
db.rename_table('scrum_story'... |
class Solution:
def maxDiv(self, a: int, b: int) -> int:
while a % b == 0:
a = a / b
return a
def isUgly2(self, n: int) -> bool:
n = self.maxDiv(n, 2)
n = self.maxDiv(n, 3)
n = self.maxDiv(n, 5)
return n == 1
def isUgly(self, n: int) -> bool:
... |
from copy import copy
import pytest
from stp_core.loop.eventually import eventually
from plenum.common.constants import OP_FIELD_NAME, BATCH
from plenum.common.messages.node_messages import Batch
from plenum.common.stacks import nodeStackClass
from plenum.common.types import f
from stp_core.network.auth_mode import A... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... |
import copy
import os
import pdb
import random
from typing import Dict, List, Text, TypeVar
import torch
import torch.nn as nn
import torch.nn.functional as F
from elvis.modeling.models import build_net
from elvis.modeling.models.layers import FC, MLP
from elvis.utils.vlp_objectives import optimal_transport_dist
from... |
import pytest
import pandas as pd
import numpy as np
import backlight
from backlight.portfolio.portfolio import create_portfolio as module
from backlight.portfolio.portfolio import _fusion_positions
import backlight.positions.positions
from backlight.trades.trades import make_trades
from backlight.asset.currency impor... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 applicab... |
import numpy as np
import math
import functools
import torch
import torch.nn as nn
from torch.nn import init
import torch.optim as optim
import torch.nn.functional as F
from torch.nn import Parameter as P
import layers
from sync_batchnorm import SynchronizedBatchNorm2d as SyncBatchNorm2d
# Architectures for G
# Att... |
import threading
import time
class Timer(object):
def __init__(self, interval, callback_func, oneshot=False, args=None, kwargs=None):
self._interval = interval
self._oneshot = oneshot
self._f = callback_func
self._args = args if args is not None else []
self._kwargs = kwar... |
# program.py
#
# Copyright (C) 2018 OSIsoft, LLC. All rights reserved.
#
# THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF
# OSIsoft, LLC. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT
# THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, LLC.
#
# RESTRICTED RIGHTS LEGEND
# Use, duplication,... |
#!/usr/bin/env python
import json
from sqlalchemy import Table, Column, String, MetaData
from catsnap import Client
from catsnap.table.tag import Tag
from catsnap.table.image import Image
from catsnap.table.image_tag import ImageTag
tags = []
images = []
image_tags = []
tag_table = Client().table('tag')
for item in ... |
"""
"""
import os
import unittest
from altdeutsch import PACKDIR
from altdeutsch.reader import read_export
__author__ = ["Clément Besnier <clemsciences@aol.com>", ]
class UnitTest(unittest.TestCase):
def test_hildebrandslied(self):
res = read_export(os.path.join(PACKDIR, "tests", "data", "hildebrands... |
"""
Common evaluation utilities.
"""
from collections import OrderedDict
from numbers import Number
import os
import json
import numpy as np
from rlkit.core.vistools import plot_returns_on_same_plot, save_plot
def get_generic_path_information(paths, stat_prefix=""):
"""
Get an OrderedDict with a bunch of s... |
# -*- coding: utf-8 -*-
# Author: XuMing <xuming624@qq.com>
# Brief:
import operator
import os
import tensorflow as tf
from keras.models import load_model
from model.nlp.keras_data_reader import load_dict
from model.nlp.keras_data_reader import pad_sequence
from model.nlp.keras_data_reader import vectorize_words
fro... |
# Owner(s): ["oncall: fx"]
import builtins
import contextlib
import copy
import functools
import inspect
import math
import numbers
import operator
import os
import pickle
import sys
import torch
import traceback
import typing
import types
import warnings
import unittest
from math import sqrt
from torch.multiprocessin... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
# coding=utf-8
"""
从词霸中获取每日一句,带英文。
"""
import requests
from everyday_wechat.utils.common import (
is_json
)
def get_acib_info():
"""
从词霸中获取每日一句,带英文。
:return:str ,返回每日一句(双语)
"""
print('获取格言信息(双语)...')
try:
resp = requests.get('http://open.iciba.com/dsapi')
if resp.status_co... |
"""
==========
Javascript
==========
Example of writing JSON format graph data and using the D3 Javascript library to produce an HTML/Javascript drawing.
"""
# Author: Aric Hagberg <aric.hagberg@gmail.com>
# Copyright (C) 2011-2018 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# ... |
"""
WSGI config for SMT project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` sett... |
from pyglet.sprite import Sprite
from swd_bot.editor.sprite_loader import SpriteLoader
class WonderSprite(Sprite):
def __init__(self, wonder_id: int):
super().__init__(SpriteLoader.wonder(wonder_id))
self.scale = 0.5
self.wonder_id = wonder_id |
from bs4 import BeautifulSoup
import requests
from splinter import Browser
import pandas as pd
import time
def init_browser():
# @NOTE: Replace the path with your actual path to the chromedriver
executable_path = {"executable_path": "./chromedriver"}
return Browser("chrome", **executable_path, headless=Fal... |
# ------------------------------------------------------------------------------
# Copyright (c) 2020 Zero A.E., LLC.
#
# 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.a... |
from django.contrib import admin
from .models import (
Customfield,
CustomfieldValue,
Queue,
TicketCustomfieldValue,
Ticket,
)
admin.site.register(Customfield)
admin.site.register(CustomfieldValue)
admin.site.register(Queue)
admin.site.register(TicketCustomfieldValue)
admin.site.register(Ticket) |
# Copyright Daniel Wallin 2006. Distributed under the
# Boost Software License, Version 1.0. (See accompanying file
# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
'''
>>> from python_test_ext import X
>>> x = X(y = 'baz')
>>> x.value
'foobaz'
>>> x.f(1,2)
3
>>> x.f(1,2,3)
6
>>> x.f(1,2, z = 3)
6
>>... |
#!/usr/bin/env python3
import pytest
from tools import Cell
class Sample:
def __init__(self, serial, x, y, target):
self.serial = serial
self.x = x
self.y = y
self.target = target
def __str__(self):
return f'Cell at {self.x}x{self.y}, ' \
f'grid seri... |
print(__doc__)
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import math
from decimal import *
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
import csv
from random... |
from django.apps import AppConfig
class ReleasenotesConfig(AppConfig):
name = 'releasenotes' |
# !/usr/bin/env python
# -*-coding:utf-8-*-
"""
@author: xhades
@Date: 2017/12/28
"""
# 随机森林分类器
import numpy as np
from numpy import *
from numpy import array, argmax
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import pickle
from sklearn.ensemble import Random... |
# coding: utf-8
"""
Jamf Pro API
## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and sh... |
from __future__ import annotations
from typing import NoReturn
from ...base import BaseEstimator
import numpy as np
from numpy.linalg import pinv
class LinearRegression(BaseEstimator):
"""
Linear Regression Estimator
Solving Ordinary Least Squares optimization problem
"""
def __init__(self, inclu... |
# -*- coding: utf-8 -*-
from datetime import date
from selenium import webdriver
from django.urls import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils.translation import activate
from django.utils import formats
class HomeNewVisitorTest(StaticLiveServerTestCase):
... |
import pytest
import os
from app import create_app
@pytest.fixture
def app(monkeypatch):
app = create_app()
monkeypatch.setenv('DATA_PATH', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sites.yml'))
app.config.update(
DATA_PATH=os.path.join(os.path.dirname(os.path.abspath(__file__)), '... |
import pickle
from build_pipeline import make_anomaly
def fit(
X, output_dir, class_order=None, row_weights=None, **kwargs,
):
"""
This hook must be implemented with your fitting code, for running drum in the fit mode.
This hook MUST ALWAYS be implemented for custom tasks.
For inference models, t... |
import sys
input = sys.stdin.readline
def main():
N, K = map(int, input().split())
A = tuple(map(int, input().split()))
ans = [0] * (N - K)
for i in range(N - K):
if A[i] < A[K + i]:
ans[i] = "Yes"
else:
ans[i] = "No"
print("\n".join(ans))
if __name__ =... |
import requests
import json
APIURL = "https://api.idpay.ir/v1.1/"
# You can get your Token from this url => https://idpay.ir/dashboard/web-services
TOKEN = "Your Token Here"
SANDBOX = str(1) # 1 or 0
Headers = {
"Content-Type": "application/json",
"X-SANDBOX":SANDBOX,
"X-API-KEY":TOKEN
}
def Payment(Ord... |
"""
db.py
"""
from pymongo import MongoClient
class Db: # pylint: disable=too-few-public-methods
"""
Database.
Singleton pattern, from Bruce Eckel
"""
class __Db: # pylint: disable=invalid-name
def __init__(self, dbname):
self.val = dbname
self.client = MongoClien... |
# Copyright (C) 2020 Adek Maulana.
# All rights reserved.
import json
import logging
import os
import re
import time
from os.path import exists
from subprocess import PIPE, Popen
from urllib.error import HTTPError
from pySmartDL import SmartDL
from uniborg.util import admin_cmd, humanbytes
logging.basicConfig(format... |
from . import base
from . import mixins
from datetime import date
class TransformedRecord(
mixins.GenericCompensationMixin,
mixins.GenericDepartmentMixin, mixins.GenericIdentifierMixin,
mixins.GenericJobTitleMixin, mixins.GenericPersonMixin,
mixins.MembershipMixin, mixins.Organization... |
import pytest
from plenum.common.messages.internal_messages import ViewChangeStarted, NewViewAccepted, NewViewCheckpointsApplied
from plenum.common.messages.node_messages import OldViewPrePrepareRequest, OldViewPrePrepareReply
from plenum.common.util import updateNamedTuple
from plenum.server.consensus.batch_id import... |
"""Defines the Ewa object which interfaces with Ewald"""
import os
import subprocess
import time
import sys
import fromage.io.edit_file as ef
import fromage.io.read_file as rf
from fromage.scripts.fro_assign_charges import assign_charges
class RunSeq(object):
"""
Class which sets up the order of operations f... |
PI = 3.14
def rectangle_funk():
a = float(input("Please, enter first side of rectangle: "))
b = float(input("Please, enter second side of rectangle: "))
return a * b
def triangle_funk():
a = float(input("Please, enter side of triangle: "))
h = float(input("Please, enter height of triangle: "))... |
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/gaogaotiantian/viztracer/blob/master/NOTICE.txt
from contextlib import redirect_stdout
import io
from .cmdline_tmpl import CmdlineTmpl
from viztracer import VizTracer
from viztracer.vizplugin import VizPl... |
import hashlib
import json
from pathlib import Path
from typing import TYPE_CHECKING, Dict, Optional
from pdm._types import CandidateInfo
from pdm.exceptions import CorruptedCacheError
from pdm.models import pip_shims
from pdm.utils import open_file
if TYPE_CHECKING:
from pip._vendor import requests
from pdm... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
# Generated by Django 2.1.15 on 2022-01-18 04:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_tag'),
]
operations = [
migrations.CreateModel(
... |
from __future__ import annotations
from abc import ABC
from enum import Enum
from typing import Any, List, Union
from awsstepfuncs.abstract_state import AbstractState
from awsstepfuncs.errors import AWSStepFuncsValueError
from awsstepfuncs.reference_path import ReferencePath
class DataTestExpressionType(Enum):
... |
from django.urls import path
from . import views
app_name = 'user'
urlpatterns = [
path('create/', views.CreateUserView.as_view(), name='create'),
path('token/', views.CreateTokenView.as_view(), name='token'),
path('me/', views.ManageUserView.as_view(), name='me'),
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2018 Miha Purg <miha.purg@gmail.com>
#
# 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, in... |
import inspect
class Warnings:
def __init__(self, config, user_data):
self._config = config
self._user_data = user_data
def _get_warnings(warnings_instance):
"""
returns a list of the returned value of
all private functions of warnings_instance
"""
# all functions of this cla... |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import warnings
from mmcv import is_tuple_of
from mmcv.utils import build_from_cfg
from mmdet3d.core import VoxelGenerator
from mmdet3d.core.bbox import (CameraInstance3DBoxes, DepthInstance3DBoxes,
LiDARInstance3DBoxes, ... |
"""UI class"""
import cv2 as cv
import numpy as np
class UI:
"""Handles UI drawing and managing"""
def __init__(self, frame):
height, width, channels = frame.shape
self.width = width
self.height = height
self.separators = {
"y": (0, height // 3, 2 * height // 3),
... |
###########################
# Implements Q and A functionality
###########################
from discord import NotFound
import db
# keep track of next question number
QUESTION_NUMBER = 1
# dictionary of questions with answers
QNA = {}
###########################
# Class: QuestionsAnswers
# Description: object with q... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
from numpy.testing import assert_allclose
from astropy.table import Table
import astropy.units as u
from ....utils.testing import requires_dependency
from ...population impo... |
def turn_right():
turn_left()
turn_left()
turn_left()
def jump():
turn_left()
while wall_on_right():
move()
turn_right()
move()
turn_right()
while front_is_clear():
move()
turn_left()
while not at_goal():
if wall_in_front():
jump()
else:
... |
from prismriver.plugin.common import Plugin
from prismriver.struct import Song
class LyrsterPlugin(Plugin):
ID = 'lyrster'
def __init__(self, config):
super(LyrsterPlugin, self).__init__('Lyrster', config)
def search_song(self, artist, title):
to_delete = ["'", '!', '(', ')', '[', ']']
... |
# Copyright 2015 Mirantis inc.
# 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... |
from unittest import TestCase
from mock import patch
from .. import constants
class mock_service_exeTestCase(TestCase):
def setUp(self):
super(mock_service_exeTestCase, self).setUp()
self.addCleanup(patch.stopall)
self.mock_os = patch.object(constants, 'os', autospec=True).start()
d... |
#!/usr/bin/env python
# encoding: utf-8
import numpy as np
#from scipy import integrate
gamma = 1.4
gamma1 = gamma - 1.
x0 = 0.5; y0 = 0.; z0 = 0.; r0 = 0.2
xshock = 0.2
pinf = 5.
def refinement_criterion_gradient(state):
import numpy
dimension_x = state.patch.dimensions[0]
dimension_y = state.patch.dimensions... |
from checksum import verifyFile
from components import requiredLibrariesFor
from configurations import getConfiguration
from download import downloadURL
from extract import TopLevelDirRenamer, extract
from libraries import allDependencies, librariesByName
from packages import getPackage
from patch import Diff, patch
f... |
__author__ = 'stowellc17'
from twisted.internet.error import AlreadyCalled
from twisted.internet.task import LoopingCall
from twisted.internet import reactor
from pygext.notifier import global_notify
TASK_DONE = 0
TASK_AGAIN = 1
class Task:
notify = global_notify.new_category('Task')
def __init__(self, ... |
import sqlite3
conn = sqlite3.connect("users.db")
# You can also supply the special name :memory: to create a temporary database in RAM
# conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("CREATE TABLE user (name text, age integer)")
c.execute("INSERT INTO user VALUES ('User A', 42)")
c.execute("INSER... |
import os as _os
_on_rtd = _os.environ.get('READTHEDOCS', None) == 'True'
if not _on_rtd:
import matplotlib.pyplot as _plt
import numpy as _np
from .setup_axes import setup_axes as _setup_axes
def plot(*args, ax=None, **kwargs):
"""
Plots but automatically resizes x axis.
.. versionadded:: 1.4
... |
# Copyright (c) 2010-2017 Bo Lin
# Copyright (c) 2010-2017 Yanhong Annie Liu
# Copyright (c) 2010-2017 Stony Brook University
# Copyright (c) 2010-2017 The Research Foundation of SUNY
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
#... |
# -*- coding: utf-8 -*-
"""
eve.io.base
~~~~~~~~~~~
Standard interface implemented by Eve data layers.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
import datetime
import simplejson as json
from copy import copy
from flask import request, abort
from eve... |
from typing import Dict, List, Union, Set
import logging
from overrides import overrides
import torch
from torch.autograd import Variable
from allennlp.common.checks import ConfigurationError
from allennlp.common.util import pad_sequence_to_length
from allennlp.data.fields.field import Field
from allennlp.data.fields... |
import pypsa
import numpy as np
import random
import matplotlib.pyplot as plt
random.seed(69)
network = pypsa.Network()
for i in range(30):
network.add("Bus","Bus {}".format(i))
for i in range(30):
network.buses.at[network.buses.index[i], 'x'] = random.randint(0,100)
network.buses.at[network.buses.index[i... |
from .bootstrap import main
main() |
# -*-coding:utf-8-*-
import pandas as pd
from numpy import *
dataset = pd.read_csv(
'test_data.csv', header=None)
dataset = round(dataset, 8)
List_data = mat(dataset)
Inverse = List_data.T
print(Inverse)
name = [
'cpu',
'cmui',
'amui',
'upcmui',
'tpcmui',
'mmui',
'mditi',
'mldsui',
... |
text = input()
save = []
pairs = {
"{": "}",
"[": "]",
"(": ")"}
valid = True
for el in text:
if el in "({[":
save.append(el)
elif el in ")}]":
if save:
current = save[-1]
if pairs[current] == el:
save.pop()
else:
... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
from __future__ import unicode_literals
from exceptions import ConnCanceledException
import dbus.service
class GenericAgent(dbus.service.Object):
"""
Generic agent service object class.
.. note:: GenericAgent can't be directly instantiated.
It should be sub-classed and provides a template for
... |
# coding: utf-8
# # Image Augmentation
# - Check images/sample-train
# - Check images/sample-confirm is empty
#
# In[15]:
import numpy as np
# In[16]:
from keras.preprocessing.image import ImageDataGenerator,array_to_img,img_to_array,load_img
from keras.applications.inception_v3 import preprocess_input
# **... |
"""Unit tests for the io module."""
# Tests of io are scattered over the test suite:
# * test_bufio - tests file buffering
# * test_memoryio - tests BytesIO and StringIO
# * test_fileio - tests FileIO
# * test_file - tests the file interface
# * test_io - tests everything else in the io module
# * test_univnewlines - ... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 6
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_1_1.models.statist... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.