text stringlengths 1 927k |
|---|
# qubit number=4
# total number=15
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=1
pr... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"module_name": "Senstech",
"category": "Modules",
"label": _("Senstech"),
"color": "grey",
"icon": "icon cube-blue",
"type": "module"
},
{
"module_name": "Senstech Settin... |
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# Copyright (c) 2013, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ---------------------------... |
"""
The LLVM Compiler Infrastructure
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
Prepares language bindings for LLDB build process. Run with --help
to see a description of the supported command line arguments.
"""
# Python modules:... |
import shutil
from typing import Dict
from covid_shared import workflow
import covid_model_seiir_pipeline
from covid_model_seiir_pipeline.pipeline.parameter_fit.specification import FIT_JOBS, FitScenario
class BetaFitTaskTemplate(workflow.TaskTemplate):
tool = workflow.get_jobmon_tool(covid_model_seiir_pipeline... |
import discord
from dataclasses import dataclass
@dataclass
class FakeAvatar:
url: str
class FakeUser(discord.Object):
@property
def avatar(self):
return FakeAvatar("https://cdn.discordapp.com/embed/avatars/0.png")
@property
def mention(self):
return f"<@{self.id}>"
@prope... |
# Copyright 2014-2018 The PySCF Developers. 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 appl... |
#!/usr/bin/env python3
# Copyright (c) 2014-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the listtransactions API."""
from decimal import Decimal
import os
import shutil
from test_frame... |
from . import db
games_users = db.Table(
'games_users',
db.Column('game_id', db.Integer(), db.ForeignKey('game.id')),
db.Column('user_id', db.Integer(), db.ForeignKey('user.id'))
)
class Game(db.Model):
'''
status - text field
game status, values created|declined|started|withdrew|ended
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/5/15 16:01
# @Author : Yizheng Dai
# @Email : 387942239@qq.com
# @File : __init__.py.py |
#!/usr/bin/env python3
# Copyright (c) 2019-2020 The Vadercoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Tests NODE_COMPACT_FILTERS (BIP 157/158).
Tests that a node configured with -blockfilterindex and -p... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import defaultdict, OrderedDict
from logging import getLogger
from .enums import NoarchType
from .match_spec import Mat... |
__version__ = "1.1.0-SNAPSHOT" |
""".. Line to protect from pydocstyle D205, D400.
Externals
=========
A number of external software is needed for iCount to work.
.. automodule:: iCount.externals.cutadapt
:members:
.. automodule:: iCount.externals.star
:members:
"""
from . import cutadapt
from . import star
EXPECTED_CUTADAPT_VERSION = '1.... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import analysis_pb2 as analysis__pb2
class AnalysisStub(object):
"""The analysis service definition.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.RequireAnalysis... |
import re
from typing import Iterable, Dict, Tuple, Union, Optional
from .abstract import Fact
from ..connectors.abstract import Executor
RE_UPGRADEABLE = r'([^\/]+)\/([^\s]+)\s+([^\s]+)\s+(\w+)\s+' \
r'\[upgradable from:\s+([^\s]+)\]$'
def parse_upgradeable(lines: Iterable[str]) -> Iterable[Tuple[... |
import json
import falcon
class HealthResource(object):
def on_get(self, req, resp):
"""Handles GET requests"""
response = {"status": "good"}
as_string = json.dumps(response)
# Set attributes of the Response which is sent to requestor
resp.body = as_string
resp.stat... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
from flask_restplus import Api
from flask import Blueprint
# Import all endpoints for all models
from .views.product_endpoints import api as product_namespace
from .views.sales_endpoints import api as sales_namespace
from .views.auth_endpoints import ns2 as userLogin_namespace
from .views.auth_endpoints import api a... |
import pyexcel
from . import db
from .databases import SrsRecord, SrsTuple
def import_excel(filename, sheet_name):
for record in pyexcel.iget_records(file_name=filename, sheet_name=sheet_name):
if SrsRecord.query.filter_by(front=record['Front']).first() is None:
srs_record = SrsRecord(**SrsTu... |
from streamsx.topology.topology import *
from streamsx.topology.state import ConsistentRegionConfig
import unittest
from datetime import timedelta
# Test the ConsistentRegionConfig class.
class TestConsistentRegionConfig(unittest.TestCase):
_DEFAULT_DRAIN_TIMEOUT = 180.0
_DEFAULT_RESET_TIMEOUT = 180.0
_DE... |
"""
Impulse reponse-related code
"""
from __future__ import division
import numpy as np
import numpy.linalg as la
import scipy.linalg as L
from scipy import stats
from statsmodels.tools.decorators import cache_readonly
from statsmodels.tools.tools import chain_dot
#from statsmodels.tsa.api import VAR
import statsm... |
#!/usr/bin/env python
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# 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 withou... |
# Generated by Django 2.0.3 on 2018-04-04 01:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0002_auto_20180402_2041'),
]
operations = [
migrations.AlterField(
model_name='proj... |
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from django.db import models
from voting.managers import VoteManager
SCORES = (
(u'+1', +1),
(u'-1', -1),
)
class Vote(models.Model):
"""
A vote on an... |
# python3
import sys
class Bracket:
def __init__(self, bracket_type, position):
self.bracket_type = bracket_type
self.position = position
def Match(self, c):
if self.bracket_type == '[' and c == ']':
return True
if self.bracket_type == '{' and c == '}':
... |
from sqlalchemy import Column, ForeignKey, Integer, String, TIMESTAMP, LargeBinary
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy import create_engine, func
import other_info
Base = declarative_base()
clas... |
import subprocess
import datetime
dt_date = datetime.datetime.now()
revision = (
subprocess.check_output(["git", "describe", "--abbrev=7", "--dirty", "--always", "--tags"])
.strip()
.decode("utf-8")
)
print("-DGIT_HASH='\"Version: %s built: %s\"'" % (revision, dt_date.strftime("%d %b %Y %H:%M"))) |
import time
import datetime
import random
from selenium import webdriver
driver = webdriver.Edge('C:\Program Files\Python\MicrosoftWebDriver.exe')
driver.get('https://github.com/santarini/seleniumPushes/blob/master/pythonlog.md');
rand1 = random.uniform(3,10)
time.sleep(rand1)#arbitrary sleep time
page_body = driver.f... |
import FWCore.ParameterSet.Config as cms
XMLIdealGeometryESSource = cms.ESSource("XMLIdealGeometryESSource",
geomXMLFiles = cms.vstring('Geometry/CMSCommonData/data/materials.xml',
'Geometry/CMSCommonData/data/rotations.xml',
'Geometry/HcalCommonData/data/hcalrotations.xml',
'G... |
from OdrvWrapper.odrv_wrapper import Odrive_Arm
import random
print("Initialize")
arm = Odrive_Arm()
while True:
# Move to random point, this blocks the thread until the move is complete
arm.move_blocking( (random.random(),random.random(),random.random())) |
"""
"""
import os
import shutil
from SNDG import execute, mkdir
import Bio.SeqIO as bpio
import multiprocessing
class Assembly:
SPADES_DOCKER_IMAGE = 'ezequieljsosa/spades'
@staticmethod
def assemble_pe(r1: str, r2: str, out: str, name: str , ss: str = None, trusted_contigs: str = None,
... |
# ___________________________________________________________________________
#
# Prescient
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This software is ... |
import json
from django.urls import reverse
from netaddr import IPNetwork
from rest_framework import status
from nautobot.dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Site
from nautobot.extras.models import Status
from nautobot.ipam.choices import *
from nautobot.ipam.models import (
Aggregate... |
import unittest
from trulioo_sdk.model.address import Address
from trulioo_sdk.exceptions import ApiAttributeError, ApiTypeError
from trulioo_sdk.configuration import Configuration
class TestAddress(unittest.TestCase):
def test_address(self):
address = Address(
unit_number="123",
... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.5.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
#... |
import gym
from gym import spaces
from gym.utils import seeding
def cmp(a, b):
return int((a > b)) - int((a < b))
# 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def draw_card(np_random):
return np_random.choice(deck)
def draw_hand(np_random):
# ... |
# ######################################################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
# -*- coding: utf-8 -*-
{
"A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.": "یک موقعیت که منطقه جغرافیایی را برای این ساحه مشخص می کند. این یک موقعیت از سلسله موقعیت ها یا 'موقعیت ... |
import codecs
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
def convert_to_gsis_id(new_id):
"""
Convert new player id columns to old gsis id
"""
if type(new_id) == float:
return new_id
return codecs.decode(new_id[4:-8].replace('-', ''), ... |
import requests
import json
import re
import tqdm
import multiprocessing
from functools import partial
import argparse
def get_parallel_url(from_url, lang_from='th', lang_to='en'):
d = {f'{lang_from}_url':'',f'{lang_to}_url':''}
to_url = from_url.replace(f'/{lang_from}/',f'/{lang_to}/')
blank_url = from_ur... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
"""Userbot help command"""
from userbot import CMD_HELP
from userbot.events import register
@register(outgoing=True,... |
def test_names_to_values():
import pybk8500
cmd = pybk8500.CommandStatus(status=0x90)
assert cmd.status == 'Checksum incorrect'
assert cmd[3] == 0x90
cmd = pybk8500.CommandStatus(status='Parameter incorrect')
assert cmd.status == 'Parameter incorrect'
assert cmd[3] == 0xA0
cmd = pybk85... |
from operator import itemgetter
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
from toontown.toonbase import TTLocalizer
class DistributedTrophyMgrAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedTro... |
def handler(context, event):
context.logger.info('This is an unstructured log')
return 'Hello, from Nuclio :]' |
from __future__ import print_function, absolute_import, division
import operator
from functools import reduce
from llvmlite import ir
from llvmlite.llvmpy.core import Type
import llvmlite.llvmpy.core as lc
import llvmlite.binding as ll
from numba.core.imputils import Registry
from numba.core import cgutils, types
fr... |
# Generated by Django 2.2.3 on 2019-07-22 08:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('MECboard', '0004_merge_20190722_1200'),
('MECboard', '0005_auto_20190722_1610'),
]
operations = [
] |
"""A mixing that extends a HasDriver class with Galaxy-specific utilities.
Implementer must provide a self.build_url method to target Galaxy.
"""
import collections
import contextlib
import random
import string
import time
from abc import abstractmethod
from functools import (
partial,
wraps,
)
from typing im... |
name, age = "Jacob Ranjit", 19
username = "Jcupzz"
print ('Hello!')
print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username)) |
"""
..
Copyright: 2017 Twinleaf LLC
Author: kornack@twinleaf.com
OriginalDate: March 2017
"""
import struct
import yaml
import tio
from .tl_cmd_conf import *
class TwinleafDevFirmwareInfoController(object):
def __init__(self, dev):
self._dev = dev
def hash(self):
return self._dev._tio.rpc('de... |
from conans import ConanFile, CMake, tools
import functools
import os
required_conan_version = ">=1.33.0"
class HarfbuzzConan(ConanFile):
name = "harfbuzz"
description = "HarfBuzz is an OpenType text shaping engine."
topics = ("opentype", "text", "engine")
url = "https://github.com/conan-io/conan-cen... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/automl_v1beta1/proto/image.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 messa... |
import sys
from MI_Classes import ResidualsGenerate
# Default parameters
if len(sys.argv) != 4:
print('WRONG NUMBER OF INPUT PARAMETERS! RUNNING WITH DEFAULT SETTINGS!\n')
sys.argv = ['']
sys.argv.append('Age') # target
sys.argv.append('test') # fold
sys.argv.append('eids') # pred_type
# Option... |
# -*- coding: utf-8 -*-
# Author Frank Hu
# iDoulist Function 0 - output
'''
std test
output_list = ['http://book.douban.com/subject/1139336/',
'http://book.douban.com/subject/25724948/']
'''
def output_CLI(output_doulist):
print 'iDoulist: your input doulist link contains: '
for i in output_doulist... |
from mesa import Agent
class Gagent(Agent):
def __init__(self, pos, model, stepcount=0, score=0):
super().__init__(pos, model)
self.pos = pos
self.stepCount = stepcount
self.score = score
def some_function(self):
a = 2 + 2
return a
def step(self):
... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
"""
Userbot module to help you manage a group
"""
from asyncio import sleep
from os import remove
from telethon import ... |
import numpy as np
from .provider import BaseProvider
from pathlib import Path
from torch import is_tensor
class AudioProvider(BaseProvider):
"""Provides the data for the audio modality."""
def __init__(self, *args, **kwargs):
self.modality = 'audio'
super().__init__(*args, **kwargs)
... |
from linkml_runtime.tests.support.test_environment import TestEnvironment
env = TestEnvironment(__file__) |
# -*- coding: utf-8 -*-
#
# Test documentation build configuration file, created by
# sphinx-quickstart on Sat Feb 7 20:09:23 2015.
#
# This file is execfile() with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-01-29 03:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nlp_tools', '0002_auto_20180127_1231'),
]
operations = [
migrations.CreateM... |
from datetime import date, datetime, timedelta, time
from types import FunctionType
from collections import Iterable
from openpyxl.cell import WriteOnlyCell
from openpyxl.formatting import Rule
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.datavalidation import DataValidation
from openpyxl_temp... |
"""
Runtime: 6200 ms, faster than 5.01% of Python3 online submissions for Container With Most Water.
Memory Usage: 27.5 MB, less than 57.22% of Python3 online submissions for Container With Most Water.
"""
from typing import List
from typing import Optional
class Solution:
def maxArea(self, height: List[int]) -> i... |
import datetime
from unittest import mock
from astropy import time
from astropy import units as u
import gcn
import lxml.etree
import numpy as np
import pkg_resources
import pytest
from .. import models
from ..jinja import btoa
from ..flask import app
from ..gcn import handle, listen
from . import mock_download_file
... |
import matplotlib.pyplot as plt
class Chart:
"""
Chart class to create and format a basic pyplot figure
"""
def __init__(self, title=None, xlabel=None, ylabel=None, figsize=None):
self.title = title if title else "Unnamed Chart"
self.xlabel = xlabel if xlabel else "X-Axis"
sel... |
from __future__ import absolute_import
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import copy
# \ref page 4, layers=2, forward + backward, concat[forward_projection, backward_projection]
class LstmbiLm(nn.Module):
de... |
# 별 표현식
a, b = (1,2)
print(a,b)
#위와 달리 갯수가 맞지 않을 경우
a, b, *c = (0,1,2,3,4,5)
print(a)
print(b)
print(c) # 리스트로 반영
scores = [8.8,8.9,8.7,9.2,9.3,9.7,9.9,9.5,7.8,9.4]
*valid_score, a, b = scores
print(valid_score) # a = 7.8, b = 9.4 이외는 valid_scoreㄷ
# 체조 점수 구하기 : 최고/최저 제거
scores = [8.8,8.9,8.7,9.2,9.3,9.7,9.9,9.5,7.... |
import logging
import os
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict
from os.path import join
from typing import Iterable, List, Optional, Tuple, Union
import torch
from torch import nn
from .composition import AdapterCompositionBlock, Fuse, Stack, parse_composition
from .c... |
# Generated by Django 2.0.9 on 2019-04-07 12:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('events', '0008_auto_20190407_1227'),
migrations.swappable_depen... |
# coding: utf-8
"""
Deep Lynx
The construction of megaprojects has consistently demonstrated challenges for project managers in regard to meeting cost, schedule, and performance requirements. Megaproject construction challenges are common place within megaprojects with many active projects in the United State... |
import numpy as np
import pandas as pd
def AAFT(df, random=np.random.uniform, random_state=None):
"""Amplitude Adjusted Fourier Transform Baseline Generator."""
# set random seed
np.random.seed(random_state)
# Operate on numpy.ndarray
ts = df.values
# 2d time-series format
_ts = ts.reshape... |
from sklearn import metrics
import numpy as np
import logging
logger = logging.getLogger(__name__)
# TODO: add others
# TODO: add ability to include generic functions
def r2_score(true_target, prediction):
# R2 metric
return metrics.r2_score(y_true=true_target, y_pred=prediction)
def rms_score(true_target,... |
# -----------------------------------------------------------------------------
# Copyright (c) 2015-2021, NeXpy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING, distributed with this software.
# -------------------------------------------------... |
#!/usr/bin/python3
from troposphere import Ref, Join, GetAtt, Output, ImportValue, Export
from troposphere.apigateway import Deployment
from troposphere.apigateway import RestApi, Resource, MethodResponse, IntegrationResponse, Integration, Method
from troposphere.awslambda import Permission
class ApiGateway(object):... |
#===============================================================================
# Copyright 2014 Intel Corporation
#
# 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.o... |
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
# Python
from StringIO import StringIO
import json
import logging
import os
import re
import subprocess
import tempfile
from collections import OrderedDict
# Django
from django.conf import settings
from django.db import models, connection
from django.core.exce... |
#!/usr/bin/env python
# This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This file follows the
# PEP8 Python style guide and uses a max-width of 120 characters per line.
#
# Author(s):
# Cedric Nugteren <www.cedricnugteren.nl>
import sys
import os.path
import glob
import a... |
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic string exercises
# Fill in the code for the functions below. main() is already se... |
import os
import shutil
import numpy as np
import torch
from torch.autograd import Variable
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.sum += val * n
... |
from django.contrib import messages
from django.db import transaction
from django.db.models import Count, Exists, OuterRef, Q
from django.shortcuts import get_object_or_404, redirect
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from django.views.generic imp... |
import copy
import os
import pickle
import uuid
import nbformat
import papermill
import six
from papermill.engines import papermill_engines
from papermill.iorw import load_notebook_node, write_ipynb
from papermill.parameterize import _find_first_tagged_cell_index
from dagster import (
AssetMaterialization,
Ev... |
import numpy as np
from pylab import scatter, plot, show
import dislib as ds
from dislib.regression import LinearRegression
def main():
"""
Linear regression example with plot
"""
# Example data
x = np.array([1000, 4000, 5000, 4500, 3000, 4000, 9000, 11000, 15000,
12000, 7000, ... |
# -*- coding: utf-8 -*-
import logging
import os
import trawsate
logger = logging.getLogger(__name__)
logging.getLogger('boto3').setLevel(logging.INFO)
logging.getLogger('botocore').setLevel(logging.INFO)
logging.getLogger('urllib3').setLevel(logging.INFO)
logger.setLevel(logging.DEBUG)
_TRAVIS_ACCESS_TOKEN = os.en... |
#!/usr/bin/env python
#
# File containing standard definitions for various things
#
# File suffixes or extensions
ADDS_SUFFIX = "bin"
ASC_SUFFIX = "asc"
BUFR_SUFFIX = "bufr"
EPL_SUFFIX = "epl"
GINI_SUFFIX = "gini"
GRB_SUFFIX = "grb"
GRB2_SUFFIX = "grb2"
GZIP_SUFFIX = "gz"
HDF_SUFFIX = "h5"
NC_SUFFIX = "nc"
NETCDF_SUF... |
'''
/**
* real_time_insights.py
*
* Streams a real-time insights for the supplied pair
* An example of the real-time insights is available here:
* https://app.ae3platform.com/insights
*
* Disclaimer:
* APEX:E3 is a financial technology company based in the United Kingdom https://www.apexe3.com
*
* None of... |
import sys,json,time,os
sys.path.insert(0, "/Users/tom/Dropbox/msc-ml/project/src/")
sys.path.insert(0, "/cs/student/msc/ml/2017/thosking/dev/msc-project/src/")
import tensorflow as tf
import numpy as np
import discriminator.config
from discriminator.model import Model
from discriminator.prepro import convert_to_feat... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Tests for EditorSplitter class in editor.py
"""
# Standard library imports
try:
from unittest.mock import Mock
import pathlib
except ImportError:
from mock import Mock # Python 2
im... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Bituls Company Limited and Contributors
# See license.txt
from __future__ import unicode_literals
import unittest
# test_records = frappe.get_test_records('Owner Contract')
class TestOwnerContract(unittest.TestCase):
pass |
# Problem : https://www.hackerrank.com/challenges/py-introduction-to-sets/problem
# Score : 10 points(MAX)
def average(arr):
return (sum(set(arr))) / (len(set(arr))) # apenas divida a soma de um set pelo seu número de elementos
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split... |
# qubit number=4
# total number=46
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_... |
from Jumpscale import j
import git
import copy
JSBASE = j.application.jsbase_get_class()
class GitClient(JSBASE):
"""
Client of git services, has all git related operations like push, pull, ...
"""
def __init__(self, baseDir, check_path=True): # NOQA
if baseDir==None or baseDir.strip()=="":... |
from glue.config import link_function
@link_function(info="Celsius to Fahrenheit",
output_labels=['F'])
def celsius2farhenheit(c):
return c * 9. / 5. + 32
@link_function(info="Fahrenheit to Celsius",
output_labels=['C'])
def farhenheit2celsius(f):
return (f - 32) * 5. / 9. |
# encoding: utf-8
#
# Copyright 2009-2021 Greg Neagle.
#
# 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 l... |
# 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 u... |
# Exercise 5.35
# Author: Noah Waterfield Price
import numpy as np
import matplotlib.pyplot as plt
def f(x):
r = np.zeros(len(x))
r[x < 0] = -x[x < 0] - 5
r[x >= 0] = x[x >= 0] - 5
return abs(r)
x = np.linspace(-10, 10, 101)
plt.plot(x, f(x))
plt.show() |
#!/usr/bin/env python
from setuptools import setup, find_packages
packages = ['upconvert.' + p for p in find_packages('upconvert', exclude=['test', 'test*', '*.t'])]
packages.append('upconvert')
setup(
name='python-upconvert',
maintainer='Upverter Inc.',
maintainer_email='opensource@upverter.com',
ve... |
from abc import ABC, abstractmethod, abstractproperty
import numpy as np
import pandas as pd
import scipy
from bokeh.layouts import widgetbox, gridplot, column, row, layout
from bokeh.models import HoverTool, Band
from bokeh.models.widgets import DataTable, Div, TableColumn
from bokeh.models.annotations import Title
fr... |
"""Draws DAG in ASCII."""
import logging
import os
import pydoc
import sys
from rich.pager import Pager
from dvc.env import DVC_PAGER
from dvc.utils import format_link
logger = logging.getLogger(__name__)
DEFAULT_PAGER = "less"
DEFAULT_PAGER_FORMATTED = (
f"{DEFAULT_PAGER} --chop-long-lines --clear-screen --R... |
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
from typing import Any, List, Mapping, Tuple
from airbyte_cdk.logger import AirbyteLogger
from airbyte_cdk.sources import AbstractSource
from airbyte_cdk.sources.streams import Stream
from airbyte_cdk.sources.streams.http.auth import TokenAuthenticator
fro... |
import xml.etree.ElementTree as ET
from tkinter.filedialog import askopenfilename
import os
import csv
def readFile(filename):
if not os.path.exists(filename): return
tree = ET.parse(filename)
root = tree.getroot()
#############################################
dict_keys = []
dict_keys = [item for item in input... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.