text stringlengths 1 927k |
|---|
import requests
from bs4 import BeautifulSoup
import pandas as pd
class SearchWizard:
config = {
"base": "https://www.google.com/search?q=",
"query": None,
"format": "json"
}
search_results = []
def __init__(self, query: str = None):
if not query == None:
... |
from setuptools import find_packages, setup
from codecs import open
from os import path
version = '0.1.5'
install_requires = ['aiohttp', 'irc3', 'osuapi']
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='... |
from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.utils.crypto import constant_time_compare
from django.utils.translation import ugettext_lazy as _
from sentry.models import AuditLogEntryEvent, Authenticator, Or... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-03-17 03:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0538_auto_20210305_1140'),
]
operations = [
migratio... |
# Copyright 2020 Masao Someki
# MIT License (https://opensource.org/licenses/MIT)
import os
import glob
import h5py
import logging
import librosa
import numpy as np
from scipy.io import wavfile
from speech import Synthesizer
IRLEN = 1024
INTERVALS = 10
SEED = 1
LP_CUTOFF = 20
class Decoder(object):
def __init... |
# GRPC GYP build file
# This file has been automatically generated from a template file.
# Please look at the templates directory instead.
# This file can be regenerated from the template by running
# tools/buildgen/generate_projects.sh
# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import copy
import json
import os
import pickle
import unittest
import uuid
from django.core.exceptions import SuspiciousOperation
from django.core.serializers.json import DjangoJSONEncoder
from django.core.signals import request_finished
from django.d... |
# -*- coding: utf-8 -*-
# import state generators
from .state_generator import * |
from setuptools import find_packages
from setuptools import setup
version = '0.0.0'
setup(
name='chainer_dense_fusion',
version=version,
packages=find_packages(),
install_requires=open('requirements.txt').readlines(),
description='',
long_description=open('README.md').read(),
author='Shi... |
from __future__ import print_function
import unittest
class TestMarbleGame(unittest.TestCase):
def test_starts_empty(self):
game = MarbleGame(0, 0)
self.assertListEqual([], game.scores)
self.assertListEqual([0], game._circle)
def test_play_examples(self):
def high_score(player... |
import unittest
import obdlib.obd.modes as modes
class TestModes(unittest.TestCase):
def test_init(self):
m = modes.Modes(1)
self.assertIsInstance(m.modes, dict)
suite = unittest.TestLoader().loadTestsFromTestCase(TestModes)
unittest.TextTestRunner(verbosity=2).run(suite) |
#!/usr/bin/env python3
# encoding: utf-8
from lxml import html
import requests
import os
import random
import time
from fake_agent import fakeagent
class Gbrarscrapy(object):
def __init__(self, url_li, proxy_single):
self.title_xpa = '//a[@onmouseover]/text()'
self.score_list_xpa = '//span[@style... |
import pymongo
EXPERIMENT_NAME = 'EXP_3'
CORPUS_PATH = 'data/pride_and_prejudice_cleaned.txt'
TRAINING_WINDOW = 3
CONTEXT_DIMENSION = 64
CONTEXT_DECAY = 0.5
CONTRASTIVE_WEIGHT = 0.001
LEANING_RATE = 1
DROPOUT = 0.1
myclient = pymongo.MongoClient('mongodb://localhost:27017')
mydb ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 26 10:47:41 2018
@author: yonghong
"""
from __future__ import print_function
import sys
sys.path.append("..")
import argparse
import os
import tensorflow as tf
from Physionet2019ImputedSepsisData import readImputed
import gru_delta_forGAN
if __name... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Archerx
# @time: 2019/4/16 上午 11:35
from .models import TeamProfile
import xadmin
class TeamDispaly(object):
list_display = ('id','team_name','team_captain','team_member1','team_member2','team_member3','competition','team_token')
xadmin.site.register(TeamP... |
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory
# 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/LICEN... |
import torch
import logging
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
from torchtext.experimental.datasets.raw import language_modeling as raw
from torchtext.experimental.datasets.raw.common import check_default_set
from torchtext.experimental.datasets.raw.comm... |
from django.urls import path, re_path
from . import views
urlpatterns = [
path('', views.index, name='challenge.index'),
path('create', views.challenge_create, name='challenge.challenge_create'),
path('<str:unique_id>/edit/', views.challenge_edit, name='challenge.my_challenge_edit'),
re_path(r'^my-lis... |
import abc
from abc import abstractmethod
from typing import Union
from osiris.base.generalutils import instantiate
class SecretVault(abc.ABC):
@abstractmethod
def get_secret(self, key: str, attr: str = None, **kwargs) -> Union[dict, str]:
pass
class NoopSecretVault(SecretVault):
def get_secr... |
import logging
import asyncio
import argparse
import i2plib.sam
import i2plib.aiosam
import i2plib.utils
from i2plib.log import logger
BUFFER_SIZE = 65536
async def proxy_data(reader, writer):
"""Proxy data from reader to writer"""
try:
while True:
data = await reader.read(BUFFER_SIZE)
... |
# ~~~
# This file is part of the dune-gdt project:
# https://github.com/dune-community/dune-gdt
# Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
# License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
# or GPL-2.0+ (http://opensource.org/lic... |
import joblib
tempo = 500000
ppq = 480
numerator = 4
denominator = 4
clocks_per_click = 24
notated_32nd_notes_per_beat = 8
cc_kept = [64, 67]
cc_threshold = 64
cc_lower = 0
cc_upper = 127
vel_value = 64
n_notes = 128
n_cc = 2 * len(cc_kept)
n_sounds = 2 * n_notes + n_cc + 1
n_deltas = 66 + 1
pad_idx = 0
n_jobs... |
from django.contrib import admin
from . import models
# Register your models here.
@admin.register(models.Project)
class ProjectAdmin(admin.ModelAdmin):
list_display_links = (
'title',
)
search_fields = (
'title',
)
list_filter = (
'title',
'creator',
)
... |
#!/usr/bin/env python
import os
import csv
import rospy
# TODO: 1. Import waypoint messages
from sdc_package.msg import BaseWaypoint, Path
class MissionPlanner(object):
def __init__(self):
self.start_time = None
# TODO: 2. Init mission planner node
rospy.init_node('mission_planner')
... |
import os
import sys
import time
import numpy as np
import pandas as pd
import argparse
import math
import config as cfg
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
parser = argparse.ArgumentParser(
description='The Normarlized Error Mertric Calculation For FashionAI Keypoint Detection Scr... |
"""
===============================================================
Computing a simple NLTE 8542 line profile in a FAL C atmosphere
===============================================================
"""
#%%
# First, we import everything we need. Lightweaver is typically imported as
# `lw`, but things like the library of m... |
from __future__ import absolute_import
import os
import numpy as np
import gzip
import struct
from .preprocessing import one_hotify
def load(data_dir, valid_ratio=0.0, one_hot=True, shuffle=False, dtype='float32'):
train_set, valid_set, test_set = {}, {}, {}
# Get data from binary files
for img_set, file_name... |
""" PRE-PROCESSING FOR MODEL RUNS USING OGGM """
# Built-in libraries
import argparse
import collections
import inspect
import multiprocessing
import os
import time
# External libraries
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
# Local libraries
import cl... |
# -*- coding: utf-8 -*-
# @Time : 2019-11-10 16:50
# @Author : yingyuankai
# @Email : yingyuankai@aliyun.com
# @File : __init__.py
from .bert_tokenizer import BertTokenizer
from .tokenizer_base import BaseTokenizer
from .xlnet_tokenizer import XlnetTokenizer
from .gpt_tokenizer import CPMTokenizer |
import json
from pathlib import Path
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import Flow
# set of permissions for particular API
SCOPES = 'https://www.googleapis.com/auth/calendar'
CONFIG_PATH = Path.home() / '.gcalcli'
CREDENTIALS_PATH = CONFIG_PATH / 'credentials.json'
TOKEN... |
from abc import ABC
from django.contrib.auth.models import User
from django.db.models.functions import Length
from django.db.models.query_utils import Q
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
fro... |
def mensagem():
print('Criando no python')
def tabuada():
n = int(input('Digite um número que deseja ver a tabuada: '))
for x in range (1,11):
print('{} X {:2} = {:2}'.format(n, x, n*x))
mensagem()
tabuada() |
from enum import unique, Enum
class DFA:
def __init__(self, source_data):
if type(source_data) != dict:
raise TypeError('第 1 个参数期望 {arg_type_expect} 类型,却接收到类型 {arg_type} '.format(
arg_type_expect='dict', arg_type=str(type(source_data))
))
if type(source_da... |
# Generated by Django 2.1.2 on 2019-02-12 07:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0049_merge_20190212_0544'),
('core', '0049_article_head'),
]
operations = [
] |
#!/usr/bin/env python3
'''
Epydoc API Runner
------------------
Using pkg_resources, we attempt to see if epydoc is installed,
if so, we use its cli program to compile the documents
'''
try:
import sys, os, shutil
import pkg_resources
pkg_resources.require("epydoc")
from epydoc.cli import cli
sys.... |
#!/usr/bin/python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import ntpath
import posixpath
import os
import re
import subprocess
import sys
import gyp.MSVSNew as MSVSNew
import gyp.MSVSProject as MSVSPro... |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
p = min([int(readline()) for _ in range(3)])
g = min([int(readline()) for _ in range(2)])
print(p + g - 50) |
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
df = pd.read_csv("Airbnb-cleaned.csv")
df.columns
del df["Unnamed: 0"]
df1 = df[['neighbourhood',... |
from .rulings_object import RulingsObject
class Arena(RulingsObject):
"""
cards/mtgo/:id/rulings
Gets the ruling of a card by the Arena Id.
Args:
id (string): The arena id of the card you want rulings for.
format (string, optional): Returns data in the specified method. Defaults to JS... |
import logging
import os.path as op
import numpy as np
import pycuda.driver as cuda
import pycuda.gpuarray as gpuarray
import pycuda.autoinit
from pycuda.compiler import SourceModule
from ..improc_types import int3
from ..utils import gpuregion, cpuregion
from ..cuda import asgpuarray, grid_kernel_config
from ._cc... |
"""
Fyle Platform SDK Class
"""
from .apis import v1beta
from .globals.config import config
from .internals.auth import Auth
class Platform(Auth):
"""The main class which creates a connection with
Fyle APIs using OAuth2 authentication (refresh token grant type).
Parameters:
client_id (str): ... |
##
## Weirdo Tree Graph that powers jobChomper
## --
##
## Assertions:
## * DAG is made up of named edges
## * Each edge is a triple (A, B, NEEDSPREVIOUSTOPASS)
## A, B are the named nodes
## B will execute after A has evaluated
## NEEDSPREVIOUSTOPASS is True or False; if it is True then A _must_ eval... |
# Copyright (c) 2019 Workonline Communications (Pty) Ltd. All rights reserved.
#
# The contents of this file are licensed under the MIT License
# (the "License"); you may not use this file except in compliance with the
# License.
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... |
"""Handle August connection setup and authentication."""
import asyncio
import logging
import os
from aiohttp import ClientError, ClientResponseError
from august.api_async import ApiAsync
from august.authenticator_async import AuthenticationState, AuthenticatorAsync
from homeassistant.const import (
CONF_PASSWOR... |
# Imports
import sys
import torch
import os
import time
import numpy as np
from torch.distributions.multivariate_normal import MultivariateNormal
# Initial set up
lunarc = int(sys.argv[1])
dim = int(sys.argv[2])
seed = int(sys.argv[3])
seed_data = int(sys.argv[4])
hp_tuning = int(sys.argv[5]) # if hp_tuning = 0, no h... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayUserCertDocIDCard(object):
def __init__(self):
self._encoded_img_emblem = None
self._encoded_img_identity = None
self._expire_date = None
self.... |
# Generated by Django 2.2.3 on 2019-07-23 14:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inception', '0005_auto_20190723_0810'),
]
operations = [
migrations.AlterField(
model_name='busstation',
name='cost'... |
from problems.problem import Problem
def generate_pythagorean_triples(ub: int) -> []:
# https://en.wikipedia.org/wiki/Pythagorean_triple
result = []
for a in range(1, ub):
aa = a * a
b = a + 1
c = b + 1
while c <= ub:
cc = aa + b * b
while c * c < cc:
c += 1
if c * c == ... |
import argparse
import os
import maskgen.scenario_model
from maskgen.tool_set import *
from maskgen import video_tools
import tempfile
from maskgen.scenario_model import ImageProjectModel
from maskgen.image_graph import extract_archive
from maskgen.graph_rules import processProjectProperties
from maskgen.batch import B... |
import sys
import os
import argparse
this_dir = os.path.abspath(os.path.dirname(__file__))
modules_dir = os.path.join(this_dir, '..', 'modules')
sys.path.append(modules_dir)
from Const import *
from Util import *
from CondaUtils import *
from CDATSetupUtils import *
valid_py_vers = PYTHON_VERSIONS
parser = argparse... |
# coding: utf-8
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import numpy as np
DEFAULT_N_BINS = 10
def compute_summaries(clf, X, W, n_bins=DEFAULT_N_BINS):
proba = clf.predict_proba(X)
count, _ = np.histo... |
def metade(valor=0, formato=False):
res = valor/2
return res if formato is False else moeda(res)
def dobro(valor=0, formato=False):
res = valor*2
return res if formato is False else moeda(res)
def aumentar(valor=0, porcentagem=0, formato=False):
res = valor+(valor * porcentagem/100)
return r... |
# !/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Validate ORT kernel registrations.
"""
import argparse
import os
import sys
import typing
import op_registration_utils
from logger import get_logger
log = get_logger("op_registration_validator")
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
# coding=utf-8
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth.views import password_reset_confirm
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
fr... |
"Test pyparse, coverage 96%."
from idlelib import pyparse
import unittest
from collections import namedtuple
class ParseMapTest(unittest.TestCase):
def test_parsemap(self):
keepwhite = {ord(c): ord(c) for c in ' \t\n\r'}
mapping = pyparse.ParseMap(keepwhite)
self.assertEqual(mapping[ord(... |
from keras.saving.save import load_model
from board import GameState, Player
from encoder import Encoder
from agent import Agent
import scoring
from board import Move, Point
from tiaocan import bot_name
class My():
def select_move(self, game_state):
print("请输入点坐标和方向(或弃权):")
x, y, d = input().split(... |
# analy.py
# A python program to analyze the SUS weighting function in order to reach the following goals:
# 1. plot the weight function
# 2. generate the normalized distribution for Z=1
# 3. extrapolate the N distribution for different Zs given by the user.
# Author: Yuding Ai
# Date: 2015 Oct 23
import math
import n... |
import os
import json
import time
import urllib.parse
import urllib.request
def handler(event, context):
"""
alarm to slack
"""
print(json.dumps(event))
slack_webhook_url = os.environ['SLACK_WEBHOOK_URL']
channel = os.environ['CHANNEL']
username = os.environ['USERNAME']
icon_emoji = ... |
"""
ASGI config for codestorm_e_learning project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault(... |
"""
Code for managing the TESS eclipsing binary metadata.
"""
import pandas as pd
from pathlib import Path
from peewee import IntegerField, SchemaManager
from ramjet.data_interface.metadatabase import MetadatabaseModel, metadatabase
brian_powell_eclipsing_binary_csv_path = Path('data/tess_eclipsing_binaries/TESS_EB_... |
from configparser import RawConfigParser
from django.conf import settings
env = RawConfigParser()
env.read(settings.BASE_DIR + '/env.ini')
INSTAGRAM_ACCOUNT = env['instagram']['account']
INSTAGRAM_AUTH_URL = env['instagram']['auth_url']
INSTAGRAM_ACCESS_TOKEN_URL = env['instagram']['access_token_url']
INSTAGRAM_APP_... |
#! /usr/bin/env python2
import os
import sys
import subprocess
import select
from optparse import OptionParser
# Setup of the command-line arguments parser
text = "Usage: %prog [options] <root-folder>\n\nConvert (in-place) all the BLP files in <root-folder> and its subdirectories"
parser = OptionParser(text, version... |
## A recursive implementation of merge sort.
## Author: AJ
## test case 1 45 849 904 79 48942 7
class sorting:
def __init__(self):
self.arr = []
def get_data(self):
self.arr = list(map(int, input().split()))
return self.arr
def merge_sort(self, array):
if len(array) == 1:
... |
import os
from textx.metamodel import metamodel_from_file
from textx.model import children_of_type
from pynmodl.nmodl import NModlCompiler
mm = metamodel_from_file(
os.path.join(os.path.dirname(__file__), '../../grammar/nmodl.tx'))
mm.register_obj_processors({'VarRef': NModlCompiler().handle_varref})
def refs_in... |
"""Command line interface for chalice.
Contains commands for deploying chalice.
"""
import logging
import os
import platform
import sys
import tempfile
import shutil
import traceback
import functools
import json
import botocore.exceptions
import click
from typing import Dict, Any, Optional, cast # noqa
from chalic... |
from nanobox_libcloud import celery
from nanobox_libcloud import adapters
from time import sleep
import logging
@celery.task
def azure_destroy_arm(creds, name):
logger = logging.getLogger(__name__)
self = adapters.azure_arm.AzureARM()
driver = self._get_user_driver(**creds)
logger.info('Destroying se... |
#
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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, pu... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class LicenseInfoDTO(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the v... |
"""
Modified from https://github.com/Oneflow-Inc/models/blob/main/Vision/style_transform/fast_neural_style/neural_style/transformer_net.py
"""
from typing import Any
import oneflow as flow
from ..registry import ModelCreator
from ..utils import load_state_dict_from_url
__all__ = ["FastNeuralStyle", "fast_neural_sty... |
#!/usr/bin/env python3
# coding=utf-8
# Copyright 2020 The HuggingFace Team. 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/LICENS... |
#!/usr/bin/env python3
import argparse
import boto3
from botocore.exceptions import ClientError
parser = argparse.ArgumentParser(description='Check all S3 buckets in the AWS account and enables default encryption with AES256')
parser.add_argument('aws_account_name', type=str, help='Named AWS user account')
args = pa... |
# ==================================================================================
# Copyright (c) 2019 Nokia
# Copyright (c) 2018-2019 AT&T Intellectual Property.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... |
from .environment import *
from .merchant import *
from .sale import *
from .customer import *
from .creditCard import *
from .debitCard import *
from .payment import *
from .recurrentPayment import *
from .cieloEcommerce import * |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v3/proto/services/asset_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import... |
import dpkt
from parsers.utils import *
name = 'ip_parser'
def parseFunc(ts, eth):
if getMACString(eth.dst) == 'FF:FF:FF:FF:FF:FF':
return None
if isinstance(eth.data, dpkt.ip.IP):
return parseIPPacket(ts, eth)
def parseIPPacket(ts, eth):
ip = eth.data
tpa = getIPString(ip.dst)
t... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def base():
index = pd.date_range('20181023', periods=9) # 生成9个行索引
column = ['a', 'b', 'c', 'd'] # 生成4个列索引
a = np.random.randn(9, 4) # 随便生成的9行4列的数据
df = pd.DataFrame(a, index=index, columns=column)
print(df)
print(pd.Dat... |
import numpy as np
import os
from easydict import EasyDict as edict
config = edict()
config.bn_mom = 0.9
config.workspace = 256
config.emb_size = 512
config.ckpt_embedding = True
config.net_se = 0
config.net_act = 'prelu'
config.net_unit = 3
config.net_input = 1
config.net_blocks = [1, 4, 6, 2]
config.net_output = 'E... |
from django.db import migrations
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "wonderworks-33344.botics.co"
site_params = {
"name": "Wonderworks",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_... |
# coding: utf-8
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcore.http.http_config import HttpConfig
"""
# 导入指定云服务的库 huaweicloudsdk{service}
"""
from huaweicloudsdkvpc.v2 import *
from huaweicloudsdkvpc.v2.region.vpc_region imp... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import json
from typing import List
import numpy
from ..Spectrum import Spectrum
def save_as_json(spectrums: List[Spectrum], filename: str):
"""Save spectrum(s) as json file.
:py:attr:`~matchms.Spectrum.losses` of spectrum will not be saved.
Example:
.. code-block:: python
import numpy
... |
# Generated by Django 2.1.3 on 2019-01-23 10:05
import cvat.apps.git.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('git', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='gitdata',
nam... |
"""instagram URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from .guiconfig import collectView
class MenuBar(QtWidgets.QMenuBar):
viewID = "MenuBar"
@collectView
def __init__(self, parent):
super(MenuBar, self).__init__()
self.p... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Smartmontools(AutotoolsPackage):
"""S.M.A.R.T. utility toolset."""
homepage =... |
# Copyright 2009 Google 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 applicable law or ... |
"""BaseHTTPServer that implements the Python WSGI protocol (PEP 3333)
This is both an example of how WSGI can be implemented, and a basis for running
simple web applications on a local machine, such as might be done when testing
or debugging an application. It has not been reviewed for security issues,
however, and w... |
import random
n1 = str(input('nome 1='))
n2 = str(input('nome 2='))
n3 = str(input('nome 3='))
n4 = str(input('nome 4='))
lista = [n1, n2, n3, n4]
random.shuffle(lista)
print('nova ordem{}'.format(lista)) |
from django.views.generic.base import TemplateView
class AppView(TemplateView):
template_name = 'app.html' |
import unittest
from test import test_support
import UserDict, random, string
class DictTest(unittest.TestCase):
def test_constructor(self):
# calling built-in types without argument must return empty
self.assertEqual(dict(), {})
self.assert_(dict() is not {})
def test_literal_constr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import glob
import os
import codecs
import re
#from bs4 import BeautifulSoup
with codecs.open(sys.argv[2],'w',encoding='utf-8') as fout:
xmlpaths = glob.glob(os.path.join(sys.argv[1],'*.xml'))
for file in xmlpaths:
file_base = os.path.split... |
import json
from django.http import HttpResponse, Http404, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.urls import reverse
from .models import Article
get_articles = 10
# Create your views here.
def index(request):
# print(dir(request))
return HttpResponseRedirect(revers... |
# -*- coding: utf-8 -*-
# Copyright 2020-2021 CERN
#
# 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... |
# -*- coding: utf-8 -*-
"""
@author: eilxaix
"""
param = {
'data_path': '../dataset/ieee_xai.csv',
'terms_path': '../dataset/domain_terms.txt',
'conceptnet_emb': './embed_data/numberbatch-en-19.08.txt',
'elmo_options':'./embed_data/elmo_2x4096_512_2048cnn_2xhighway_5.5B_options.json',
'elmo_weight... |
"""
Copyright (c) 2019 NAVER Corp.
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, distribute, su... |
"""
This is a script that can be used to retrain the YOLOv2 model for your own dataset.
"""
import argparse
import os
from PIL import ImageOps
import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.m... |
Clock.bpm=100; Scale.default="minor"
p1 >> pulse([0,-1,-2,-3], dur=8, lpf=600, lpr=0.2, crush=8) + (0,2,4,const(6))
p3 >> blip(p1.pitch, dur=8, sus=4, room=1, oct=6) + [0,0,0,P*(2,4,3,-1)]
p2 >> saw(P[:5][:9][:16], dur=1/4, oct=var([3,4],[12,4])).penta()
d1 >> play("(x )( x)o{ vx[xx]}", crush=16, rate=.8).every([24,5,3... |
import scrapy
class StarAcmSpiderItem(scrapy.Item):
username = scrapy.Field()
source = scrapy.Field()
run_id = scrapy.Field()
data = scrapy.Field() |
import copy
import sys
#if '../PyCommon/modules' not in sys.path:
# sys.path.append('../PyCommon/modules')
if './modules' not in sys.path:
sys.path.append('./modules')
import Resource.ysMotionLoader as yf
import Simulator.ysPhysConfig as ypc
import Math.mmMath as mm
import Motion.ysHierarchyEdit as yme
import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.