content stringlengths 5 1.05M |
|---|
# coding: utf-8
import numpy as np
import pysptk
from os.path import join, dirname
from nose.tools import raises
DATA_DIR = join(dirname(__file__), "..", "data")
def test_cdist_invalid():
c1 = np.random.rand(10, 26)
c2 = np.random.rand(10, 26)
@raises(ValueError)
def __test_invalid(otype):
... |
import argparse
import glob
import json
import logging
import os
import shutil
import time
from typing import Tuple
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
from flask import Flask, jsonify, make_response, request, send_from_directory
from flask_cors import CORS, cross_origin
from werkzeug.utils import secure_filena... |
#!/usr/bin/python
# read_file3.py
with open('works.txt', 'r') as f:
contents = f.readlines()
for i in contents:
print(i.strip())
|
# 05.06.2007, c
# last revision: 05.06.2007
input_name = '../examples/navier_stokes/stokes.py'
output_name = 'test_stokes.vtk'
from testsBasic import TestInput
class Test( TestInput ):
pass
|
import threading
import subprocess
import uuid
from flask import Flask
from flask import render_template, url_for, abort, jsonify, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
#when the html page send the GET IP@/send, if will be capture by this one
@app.route('/... |
def transform_column_values(target_replacement_dictionary, target_column_headers_list, dataset):
"""
Replaces values in columns by using a dictionary of conversions (e.g., in order to quantify likert scales).
:param target_replacement_dictionary: (dict) A dictionary in which *keys* are old (target) values ... |
import telebot
from main import bot
def handler(event, _): # Функция для переадресаци запросов в func Yandex Cloud
message = telebot.types.Update.de_json(event['body'])
bot.process_new_updates([message])
return {
'statusCode': 200,
'body': '!',
}
|
# coding:utf:8
from django.http.response import JsonResponse
import requests
from requests.adapters import HTTPAdapter
requests.packages.urllib3.disable_warnings()
requests_retry = requests.Session()
requests_retry.mount('http://', HTTPAdapter(max_retries=3))
requests_retry.mount('https://', HTTPAdapter(max_retries=3... |
"""Functionality for common test setups.
See https://docs.pytest.org/en/stable/fixture.html#conftest-py-sharing-fixture-functions
In general, pass fixtures as arguments to a pytest test function in order to base the
test function on those fixtures. No additional import in the test module is required if
the fixture is ... |
# -*- coding: utf-8 -*-
"""
Created on Sun March 20 2020
@author: ron
MyPTV init file
"""
|
import pandas as pd
from pathlib import Path
from sklearn.utils import shuffle
def parse_table(df, shadow_size=100):
all_pos = df.loc[df[2] == "positive"]
all_pos = shuffle(all_pos)
all_neg = df.loc[df[2] == "negative"]
all_neg = shuffle(all_neg)
res = {}
all_pos_shadow = all_pos[:shadow_size... |
from math import log
def squared_digits_series(n):
power=log(n, 2)
up=10
down=1
total=up+down
for i in range(0, int(power)):
down*=2
up*=4
total+=up+down
return total-(2**int(power)-(n-down)-1)*(down*10+1) |
# hgf.py
#"""The HGF time series model."""
import numpy as np
import warnings
# Turn warnings into exceptions
#warnings.simplefilter('error')
# Generic HGF model
class Model(object):
"""Generic HGF model"""
def __init__(self):
self._nodes = []
@property
def nodes(self):
return self... |
#coding=utf-8
'''
Created on 2014-5-15
@author: ETHAN
'''
class TaskQueueCommandTypeEnum(object):
'''
all task status enum value for test task
'''
TaskQueueCommandType_Start=1
TaskQueueCommandType_Stop=2
TaskQueueCommandType_SendResultEmail=4
TaskQueueCommandType_RerunCase=5
|
import os
import shutil
def copy_file(source,destination,n=1):
print()
print("copying....")
if os.path.exists(source) and os.path.exists(destination):
print("path_exists")
try:
for i in range(n):
temp_destination = os.path.join(destination,"ball"+str(i)... |
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
opc = 0
while opc != 5:
print(''' [1] Somar
[2] Multiplicar
[3] Maior
[4] Novos números
[5] Sair do programa
''')
opc = int(input('Digite sua opção: '))
if opc == 1:
print('A soma entre ... |
"""IO methods for raw wind data, which may come from 4 different sources:
- HFMETARs (high-frequency [1- and 5-minute] meteorological aerodrome reports)
- MADIS (Meteorological Assimilation Data Ingest System)
- Oklahoma Mesonet stations
- Storm Events (dataset with local storm reports)
"""
import copy
import os.path... |
import pyqtgraph as pg
import numpy as np
from PyQt5 import QtGui
from pylsl import StreamInlet, StreamOutlet, StreamInfo, resolve_byprop
import threading
def fft_backend(input_stream, output_stream, window_length=256, pow2=True, window_type=np.hamming):
#################################
## Stream Inlet a... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: pnp_device
short_description: Manage PnpDevice objects of DeviceOnboardingPnp
description:
- >
Returns list of... |
import os
import requests
import httplib2
import json
import time
from oauth2client.service_account import ServiceAccountCredentials
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from email.mime.text import MIMEText
from email.mime.image import MIMEI... |
###############################################################################
# (c) 2022 Michael MacFadden
#
# CSC-841 Cyber Operations II
# Lab 08 and 09
###############################################################################
import time
from dataclasses import dataclass
from typing import Optional
from .ip... |
"""
Yatao (An) Bian <yatao.bian@gmail.com>
yataobian.com
May 13, 2019.
"""
# Fold ids
all_folds = [1,2,3,4,5,6,7,8,9,10]
amazon_categories = ('furniture', #0
'media', #1
'diaper', #2
'feeding', #3
'gear', #4
... |
/home/runner/.cache/pip/pool/c1/f2/71/d86f12780a6222d6bcd31376873a2dfb0bd74b0f9317c4d75c8619c321 |
# Time: O(n^3)
# Space: O(1)
import collections
# Two pointer solution. (1356ms)
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
result = []
for i in xrang... |
import os
import random
base=0
import copy
import os
#shutil.move("P23_GY/good","CellCycle")
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
#data = os.listdir(path[0])
import scipy.misc
import shutil
import random
import os
#shutil.move("P23_GY/good","CellCycle")
import matplot... |
# Author: Quentin Bertrand <quentin.bertrand@inria.fr>
# Mathurin Massias <mathurin.massias@gmail.com>
# License: BSD 3 clause
import numpy as np
import numbers
from sklearn.utils.validation import check_X_y
from sklearn.utils.multiclass import check_classification_targets
from sklearn.linear_model import La... |
import math as mt
import random as rm
import matplotlib.pyplot as plt
y=4.9
g=-0.0478
r=0.14
dt=0.005
x1=0
y1=0
xl=[]
yl=[]
xll=[]
def csn(x,y,r) :
xr=round(x)
yr=round(y)
if mt.sqrt((x-xr)**2+(y-yr)**2)<=2*r :
if (xr%2==0 and yr%2==0) or (xr%2==1 and yr%2==1) :
o=1
else :
... |
from Anagrams.searcher import Searcher
from Anagrams.indexer import Indexer
from word_list import WordList
def index_anagrams():
# Run this once to create the index file from the given word list
indexer = Indexer()
indexer.index_anagrams()
# Example how to create smaller anagram index files
indexe... |
import time
from common.db import open_database_session
from common.log import logger
from flight.models.airport import Airport
from flight.models.bounding_box import (bounding_box_related_to_airports,
BRAZILIAN_AIRSPACE_BBOX)
from flight.models.flight import Flight
from flight... |
import torch
import numpy as np
from torch import nn, optim
from torch.utils.data import DataLoader
from model import Pitch_lstm
from dataset import Dataset
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-e","--max-epochs", type=int, default=10)
parser.add_argument("-b","--batch-size", type=i... |
import torch
import pytest
from onnx2pytorch.operations.scatterelements import ScatterElements
def test_scatter_elements_with_axis():
op = ScatterElements(dim=1)
data = torch.tensor([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=torch.float32)
indices = torch.tensor([[1, 3]], dtype=torch.int64)
updates = torch.t... |
__author__ = 'bespider'
|
#!/usr/bin/env python
def load_compressed_features(fname_features):
try:
import gzip
import numpy
except ImportError:
print 'Error importing gzip and/or numpy modules. Please, verify their installation.'
import sys
sys.exit(0)
# load features from a gz compressed file
file_features = gzip.GzipFile(fname... |
#!/usr/bin/env python3
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
"""Create widgets' interactive nature.
This module contains the `Controller` class to bring life to the GUI defined
in the `GUI` class by connecting widgets up to control sequences that bring
about change.
"""
from configuration import load_config, save_config, save_pos_config
from epics import ca, caput, PV
from gu... |
r"""
.. testsetup::
import io
import struct
from pprint import pprint
from nbtlib import *
All the tag classes have a :meth:`Base.parse` classmethod that reads
nbt data from a file-like object and returns a tag instance. Tag
instances can then write their binary representation back to file-l... |
import random
import py
from rpython.jit.backend.arm.registers import *
from rpython.jit.backend.arm.locations import *
from rpython.jit.backend.arm.regalloc import ARMFrameManager
from rpython.jit.backend.arm.jump import remap_frame_layout, remap_frame_layout_mixed
from rpython.jit.metainterp.history import INT
fm = ... |
#!/usr/bin/env python3
import io
import logging
from argparse import ArgumentParser
from sys import argv
from typing import Any, List
import avro
from avro.datafile import DataFileReader
from confluent_kafka import Consumer
logging.basicConfig(level=logging.INFO)
def from_avro_bytes(b: bytes) -> Any:
bytes_read... |
import jesse.helpers as jh
from jesse.config import config
from jesse.exceptions import InvalidRoutes
from jesse.routes import router
from .state_app import AppState
from .state_candles import CandlesState
from .state_completed_trades import CompletedTrades
from .state_exchanges import ExchangesState
from .state_logs i... |
import json
from django.contrib.auth import get_user_model
from graphene_django.utils.testing import GraphQLTestCase
from graphql_jwt.shortcuts import get_token
from aww.models import Individual, Group
class IndividualMutationTest(GraphQLTestCase):
def setUp(self):
super().setUp()
get_user_model... |
import glob
import json
import os
import os.path as osp
import pickle
import numpy as np
import torch
from extract_patch_feature import extract_ft
from torch.utils.data import Dataset, DataLoader
from SuperMoon.utils.data import split_id
from SuperMoon.utils.data.pathology import sample_patch_coors, draw_patches_on_s... |
#! wirefish-venv/bin/python
import argparse
from scapy.all import get_if_list, conf
import actions
conf.use_pcap = True
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(
help="Shows the help of the actions",
dest="command_action",
required=True
)
# Parser for the show-interfaces a... |
# Copyright DataStax, 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 by applicable law or agreed to in writing, softwa... |
scores = {
"Rick Sanchez" : 70,
"Morty Smith" : 35,
"Summer Smith" : 82,
"Jerry Smith" : 23,
"Beth Smith" : 98
}
passed = [name for name, score in scores.items() if score >= 65]
print(passed)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# pip install psutil
import psutil
net_connections = psutil.net_connections()
print('Net connections ({}):'.format(len(net_connections)))
# Sort by pid
net_connections.sort(key=lambda x: x.pid)
# for connect in net_connections:
# print(con... |
#################################################################################
# Original source from NLM UMLS API examples
# Modified by: Denis Griffis
#
# see https://documentation.uts.nlm.nih.gov/rest/search/index.html for full docs
# on the /search endpoint
#
# version - example 2015AA
# string - example "diabet... |
#!/usr/bin/env python
#coding:utf-8
from os import name
if name == 'nt':
'''windows color table'''
#global BLACK,BLUE,GREEN,CYAN,RED,PURPLE,YELLOW,WHITE,GREY
BLACK = 0x0
BLUE = 0x01
GREEN = 0x02
CYAN = 0x03
RED = 0x04
PURPLE= 0x05
YELLOW= 0x06
WHITE = 0x07
... |
"""Create Sha1 for all entities."""
from mixer.gtfs.versioner.model import Model
class Controller(object):
"""For a dict of df, gen the id of the entities."""
def __init__(self, dict_df_mapped):
"""Constructor."""
self.dict_df_mapped = dict_df_mapped
def main(self):
"... |
from pwn import *
from Crypto.Cipher import AES
def subproblem1():
print 'Subproblem 1:'
m = 'QQ Homework is too hard, how2decrypt QQ'
c = '296e12d608ad04bd3a10b71b9eef4bb6ae1d697d1495595a5f5b98e409d7a7c437f24e69feb250b347db0877a40085a9'.decode('hex')
[m1, m2, m3] = [m[16*i:16*(i+1)] for i in range(3)]... |
import tensorflow as tf
import tensorflow.contrib.layers as tcl
import tensorflow.contrib.framework as tcf
import numpy as np
import os
import time
import random
from functools import partial
import pprint
from DCGAN import DCGAN, SampleImageHook
from input_utils import get_image_paths, get_input_batch_tensor
# Newer... |
# generated from catkin/cmake/template/cfg-extras.context.py.in
DEVELSPACE = 'FALSE' == 'TRUE'
INSTALLSPACE = 'TRUE' == 'TRUE'
CATKIN_DEVEL_PREFIX = '/root/ros_catkin_ws/devel_isolated/roslaunch'
CATKIN_GLOBAL_BIN_DESTINATION = 'bin'
CATKIN_GLOBAL_ETC_DESTINATION = 'etc'
CATKIN_GLOBAL_INCLUDE_DESTINATION = 'include'
... |
from pygame import mixer
mixer.init(buffer=1024)
class Sounds(object):
def play(self, filename, loop = 1):
mixer.music.load(filename)
mixer.music.play(loop)
def pause(self):
mixer.music.pause()
def unpause(self):
mixer.music.unpause()
|
import os
import sys
import time
from datetime import datetime, timezone
from suntime import Sun
from config import config
def try_to_mkdir(path):
if os.path.exists(path) == False:
os.makedirs(path)
def prepare_dir(base):
path = "pictures"
try_to_mkdir(base + "/" +path)
return path
def make_... |
"""
Settings that are to be used in a development environment.
"""
from .base import *
DEBUG = True
DATABASE_URI = "postgresql://localhost:5432/starter_dev"
SERVER_URL = "https://example.com/dev"
APPLICATION_ROOT="/dev"
## Keys for GitHub IU OAuth App
GITHUB_CLIENT_ID = ""
GITHUB_CLIENT_SECRET = ""
... |
from .hamiltonian import (
is_comeasureable,
group_comeasureable_terms_greedy,
compute_group_variances,
get_expectation_values_from_rdms,
get_expectation_values_from_rdms_for_qubitoperator_list,
estimate_nmeas_for_operator,
estimate_nmeas_for_frames,
reorder_fermionic_modes,
)
from .meas... |
n = int(input('Digite um número inteiro: '))
print(f'''{n} x 1 = {n *1}
{n} x 2 = {n *2}
{n} x 3 = {n*3}
{n} x 4 = {n *4}
{n} x 5 = {n *5}
{n} x 6 = {n *6}
{n} x 7 = {n *7}
{n} x 8 = {n *8}
{n} x 9 = {n *9}
{n} x 10 = {n *10}
''') |
import os
import sys
import numpy as np
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(__file__, "../.."))) # isort:skip
from pytorch_forecasting import TimeSeriesDataSet # isort:skip
from pytorch_forecasting.data.examples import get_stallion_data # isort:skip
# for vscode debugging: https://sta... |
# -*- coding: utf-8 -*-
import os
import requests
from bs4 import BeautifulSoup
import yaml
from selenium import webdriver
import time
import pandas as pd
from selenium.webdriver.support.ui import WebDriverWait
"""Main module."""
def parser(config):
df = pd.DataFrame(columns=['Rank', 'Company_Name', 'Company_We... |
#!/usr/bin/env python
# vim:set ts=4 sw=4 et:
#
# Copyright 2015 UAVenture AG.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later ... |
import sys
class colorize(str):
"""
Pretty simple to use::
colorize.make('foo').bold
colorize.make('foo').green
colorize.make('foo').yellow
colorize.make('foo').red
colorize.make('foo').blue
Otherwise you could go the long way (for example if you are
testing t... |
import unittest
from pbxproj.pbxsections.PBXContainerItemProxy import *
class PBXContainerItemProxyTest(unittest.TestCase):
def testGetComment(self):
obj = PBXContainerItemProxy()
self.assertEqual(obj._get_comment(), u'PBXContainerItemProxy')
|
"""
* Copyright 2019 EPAM Systems
*
* 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 in writing,... |
import torch
import pytorch_lightning as pl
from albumentations.pytorch import ToTensorV2
from torch.utils.data import DataLoader
import tqdm
from data_loader import PlantDataset
from model import LitPlants
import albumentations as alb
import pandas as pd
import time
import numpy as np
from config import DefaultConfig ... |
print('hello pythoneers, I have come with you') |
import pickle
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--mode', choices=['master', 'daim213', 'gc'], default='gc')
parser.add_argument('--rep', type=int, default=10)
parser.add_argument('--dataset', type=str, default='pc4')
parser.add_argument('--start_runid', type=int... |
import array
from kbhit import check_key
from getch import getch
_MEMORY_SIZE = 2 ** 16
_main_memory = array.array('H', [0 for i in range(_MEMORY_SIZE)])
class MMR:
"""Memory-mapped registers """
KBSR = 0xFE00 # keyboard status
KBDR = 0xFE02 # keyboard data
def load_image(*names):
global _main_me... |
# add the following 2 lines to solve OpenGL 2.0 bug
from kivy import Config
Config.set('graphics', 'multisamples', '0')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Te... |
import json
import os
functionInsight = "{\n"
functionInsight += " presetScene({\n"
functionInsight += " setup({ renderer, scene, camera }) {\n"
functionInsight += " },\n"
functionInsight += " animate({ renderer, scene, camera }) {\n"
functionInsight += " },\n"
functionInsight += " })\n"
functionInsight... |
# -*- coding: utf-8 -*-
"""
Display song/video and control MPRIS compatible players.
There are two ways to control the media player. Either by clicking with a mouse
button in the text information or by using buttons. For former you have
to define the button parameters in your config.
Configuration parameters:
but... |
"""_summary_
Models which represent data used in pieces of demo production
"""
from isu.models.audio import Audio, SoundBite
from isu.models.demo_tags import DEMO_RES, DIR_KEYS, DEBUG, DIRS
from isu.models.demo import Demo, DemoSectionIterator, DemoStepIterator
from isu.models.script import Script, TextBox
from isu.mo... |
from ..authorization.authorization_api import AuthorizationApi
from ..common.common_funcs import CommonFuncs
import requests
import json
import logging
class HierarchiesApi():
def __init__(
self,
application_name: str,
environment_id: str,
authorization_api: AuthorizationApi,
... |
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
# Enco... |
import numpy as np
import skimage.segmentation as segm
import skimage.filters as filters
from skimage.exposure import histogram
from src.utils import to_inst_map, cv2_opening
def naive_thresh_prob(
prob_map: np.ndarray,
threshold: float=0.5,
**kwargs
) -> np.ndarray:
"""
Threshold... |
from argparse import ArgumentParser
def parse_option():
'''
Get optional variables from command line arguments
--
References
https://qiita.com/taashi/items/400871fb13df476f42d2
https://qiita.com/kzkadc/items/e4fc7bc9c003de1eb6d0
'''
argparser = ArgumentParser()
argparser.add_argum... |
# Third-party
from astropy.constants import G
import astropy.units as u
import numpy as np
import pytest
# gala
from gala.dynamics import get_staeckel_fudge_delta, PhaseSpacePosition
import gala.potential as gp
from gala.units import galactic
from gala.tests.optional_deps import HAS_GALPY
@pytest.mark.skipif(not HAS... |
# Copyright (c) 2021 zfit
import pytest
import zfit
from zfit.util.exception import NormRangeUnderdefinedError
limits1 = (-4, 3)
limits2 = (-2, 5)
limits3 = (-1, 7)
obs1 = 'obs1'
obs2 = 'obs2'
space1 = zfit.Space(obs=obs1, limits=limits1)
space2 = zfit.Space(obs=obs1, limits=limits2)
space3 = zfit.Space(obs=obs1, l... |
#!/usr/bin/python
# Rot13 package for the the codex project
# created by : C0SM0 | Fyzz
# imports
import os
# help menu for cipheringing process
help_menu = """
+-------------------------------------------------------+
| [+] ARGUMENTS Rotation13-Cipher |
| [+] ARG 1. Ciphering Process ... |
# Generated by Django 3.2.11 on 2022-02-05 08:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0005_alter_product_category'),
]
operations = [
migrations.AddField(
model_name='productcategory',
name=... |
import bs4
import requests
def makeCode(folder):
x = requests.get(folder)
x.raise_for_status()
gitSoup = bs4.BeautifulSoup(x.text)
files = gitSoup.select('.js-directory-link') #get tag with URL for each file
urls = [f.get('href') for f in files if 'README.md' not in f.get('href')] #put urls in... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
#################################################### Load packages
import matplotlib.pyplot as plt #plotting
import os #platform independent paths
import pandas as pd
plt.style.use('~/lbFCS/styles/paper.mplstyle')
############################################################## Parameters
savepath='/fs/pool/pool-schwi... |
import argparse
import logging
from typing import Callable
from typing import Collection
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
import numpy as np
import torch
from typeguard import check_argument_types
from typeguard import check_return_type
from espnet2.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Test QiSrc Reset """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ imp... |
import os # loads built in python module
import pygame # loads downloaded module
video_mode = False # If true, frames are saved
current_frame = 1 # Show what the current is
path_checked = False # checks if file exist in python
def save_screen(screen):
"""
If test_mode is True, an image of `screen` is s... |
from spektral.layers.ops import sp_matrix_to_sp_tensor
class AdjToSpTensor(object):
"""
Converts the adjacency matrix to a SparseTensor.
"""
def __call__(self, graph):
if graph.a is not None:
graph.a = sp_matrix_to_sp_tensor(graph.a)
return graph
|
#!_PYTHONLOC
#
# (C) COPYRIGHT 2008-2016 Al von Ruff and Ahasuerus
# ALL RIGHTS RESERVED
#
# The copyright notice above does not evidence any actual or
# intended publication of such source code.
#
# Version: $Revision$
# Date: $Date$
import cgi
import sys
import MySQLdb
from isfdb impor... |
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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.... |
# -*- coding: utf-8 -*-
import tensorflow as tf
def main():
tf.debugging.set_log_device_placement(True)
# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
if __name__ == '__main... |
import pytest
from django.core import serializers
from ..utils import sample_data_equals
pytestmark = pytest.mark.django_db
def test_basic_serialization(english_german_base):
page, german_language = english_german_base
serialized_page = serializers.serialize(
"xliff", [page], target_language=german... |
"""Classes for face forgery datasets (FaceForensics++, FaceShifter, DeeperForensics, Celeb-DF-v2, DFDC)"""
import bisect
import os
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset
class ForensicsClips(Dataset):
"""Dataset class for FaceForensics++, FaceShift... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
def edge_weight_percolation(network : nx.Graph, weight_name : str, connecting = 'strong') -> np.ndarray:
'''Percolation with given weight on given network.
Parameters
---------------
network : `nx.Graph` (or `nx.DiGraph`)
... |
import json
from pywps import Process, LiteralInput, ComplexOutput
from pywps import FORMATS
import logging
LOGGER = logging.getLogger("PYWPS")
class ShowDefaults(Process):
"""
Process with examples of default value usage in WPS.
"""
def __init__(self):
inputs = [
LiteralInput(
... |
from dataclasses import dataclass
from dateutil.parser import parse
@dataclass
class Member:
# Attrs
def __init__(self, json, token) -> None:
self.__token: str = token
from .User import User
for key in json:
if key == "user":
setattr(self, key, User(json[... |
import json
import logging
import math
import os
import sys
from pathlib import Path
from typing import Dict, List, Tuple
import PIL.Image
import click
import cv2
import pandas as pd
from pytorch_lightning import seed_everything
from skimage import exposure
from sklearn.model_selection import train_test_split
from tq... |
import time
from typing import Tuple, List, Optional
import numpy as np
from pathlib import Path
from PIL import Image
from copy import deepcopy
from path.rrt_base import RRTBase
class RRT(RRTBase):
def __init__(self, grid_map: np.ndarray,
xy_init: Tuple[int, int],
xy_goal: Tup... |
# Copyright 2016 Quora, 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 by applicable law or agreed to in writing, so... |
#!/bin/env python
# Copyright (C) 2017 Eric Mely
#
# This file is part of tplink-hs1xx
#
# tplink-hs1xx is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... |
import os
import os.path
import sublime
import sublime_plugin
PLUGIN_NAME = 'PyenvEnv'
SETTINGS_PREFIX = PLUGIN_NAME + '.'
SETTINGS_FILE = PLUGIN_NAME + '.sublime-settings'
DEBUG = 0
def get_setting(name, default=None, view=None):
if view is None:
view = sublime.active_window().active_view()
vie... |
"""
=================================================================
Plot probabilities with different base classifiers
=================================================================
Plot the classification probability for ensemble models with different base classifiers.
We use a 3-class imbalanced dataset, and ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 15:45:49 2020
@author: peter
"""
import numpy as np
from pathlib import Path
import pandas as pd
from joblib import Parallel, delayed
import scipy.ndimage as ndimage
from vsd_cancer.functions import cancer_functions as canf
def make_all_tc(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.