content stringlengths 5 1.05M |
|---|
"""
Abstract class for generic scraping actions
"""
from abc import ABC, abstractmethod
import logging
from logging import Logger
from pathlib import Path
from bs4 import BeautifulSoup
import requests
from requests.exceptions import ConnectTimeout, HTTPError, RequestException
import config as cfg
class Page(ABC):... |
import logging
import threading
import os
import sys
from collections import Counter
from itertools import islice
from multiprocessing import cpu_count
from typing import IO, List, Iterable, Optional, cast
import subprocess
LOGGER = logging.getLogger(__name__)
DEFAULT_STOP_EPSILON_VALUE = '0.00001'
DEFAULT_STOP_WI... |
import unittest
import os, sys, inspect, json
from src.solr_export import prep_url, exclude, match
dir_path = os.path.dirname(os.path.realpath(__file__))
resource_path = dir_path + os.sep + "resources"
class solr_export_test(unittest.TestCase):
def test_prep_url(self):
preped = prep_url("http://localhost... |
# -*- coding: utf-8 -*-
# Distributed under the terms of MIT License (MIT)
import pywikibot
import re
from pywikibot import pagegenerators
from pywikibot import config
import MySQLdb as mysqldb
def numbertopersian(a):
a = str(a)
a = a.replace(u'0', u'۰')
a = a.replace(u'1', u'۱')
a = a.replace(u'2', u'... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
from ax.core.observation import ObservationData
from ax.modelbridge.transforms.ivw import IVW, ivw_m... |
from setuptools import setup
setup(
name="ytdlmusic",
version="2.0.0",
description="ytdlmusic is a command-line program to search and download music files from YouTube without use browser.",
long_description="The complete description/installation/use/FAQ is available at : https://github.com/thib1984/y... |
# 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, software
# distributed under the Li... |
"""
The ``interface`` taxon is the most fundamental and generic applet taxon. It groups applets
implementing interfaces that are used for purposes that do not fit into any single other taxon.
Because the ``interface`` taxon is so important, the applet names in this taxon are not prefixed
with the taxon name.
Examples... |
from .gelu import gelu
from .transformer import *
__version__ = '0.39.0'
|
from twilio.rest import Client
account_sid = 'AC988415bd476b4abc248b4afaa8bc6717'
auth_token = '3b62cb9653d077b61f0d1f50bc06e718'
client = Client(account_sid, auth_token)
message = client.messages.create(
from_='+13343423628',
body='asdf',
... |
from marshmallow import fields
from marshmallow import Schema
class SmsRequestParameters(Schema):
national_number = fields.String(required=True, description='National Number')
country_code = fields.String(
required=True, description='Country Code, like 86 for China'
)
class ValidateSmsCodeParame... |
# -*- coding: utf-8 -*-
from flask import current_app
from .util import render_email_template, send_or_handle_error, escape_markdown
import rollbar
import pendulum
def send_brief_response_received_email(supplier, brief, brief_response, supplier_user=None, is_update=False):
to_address = brief_response.data['res... |
from downloader import download
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
def main(file, out):
in_file = open(file, "r")
out_file = open(out, "w")
for l in in_file.readlines():
l_split = l.split("\t")
# if it's a known IDS attack OR normal traffic
if (l_split[14] != "0" and l_split[17] == "-1"... |
from __future__ import unicode_literals
import youtube_dl
ydl = youtube_dl.YoutubeDL({'format': 'mp4'})
def download(url):
ydl.download([url])
|
import pkg_resources
from timeseries.timeseries import *
from timeseries.lazy import *
try:
__version__ = pkg_resources.get_distribution(__name__).version
except:
__version__ = 'unknown'
|
from time import time
import numpy as np
import cv2
import math
from pydarknet import Detector, Image
from constants import *
if CAPTURE_MODE == "ZED_SDK":
import pyzed.sl as sl
zed = sl.Camera()
init_params = sl.InitParameters()
init_params.camera_resolution = sl.RESOLUTION.HD720
init_params.depth_... |
import thingspeak
import schedule
from twitter_bot_module import Twitter_Bot
from gpiozero import CPUTemperature
from time import sleep, strftime
# Declare CPU, thingspeak and local variables
cpu = CPUTemperature()
channel_id = 1357661
write_key = '037QCFSLSVG4MFMZ'
# read_key = 'TZ9SADGMTGS7B3M0'
degre... |
class AccountPermissions(object):
MUTATE_DATA = 1
permissions = {
MUTATE_DATA: {
"name": "MUTATE_DATA",
"description": "Can edit any site data. TODO: make this work.",
},
}
|
# GlitchyGames
# palette: Manages the custom color palette file format used by the engine
import configparser
import os.path
import sys
from pygame import Color
VGA = 'vga'
SYSTEM = 'system'
NES = 'nes'
class ColorPalette:
_BUILTIN_PALETTE_LOCATION = os.path.join(os.path.dirname(__file__), 'resources')
_D... |
'''
datetime_utilities.py
========================
Basic functions to make dealing with Dates and Times easier
datetime_utilities - Module Contents
+++++++++++++++++++++++++++++++
'''
import pytz
class tzAlias(object):
'''
Enum like objec to organize pytz time zones. They are called based on s... |
from django.contrib import admin
from example_app.models import Secret
admin.site.register(Secret)
|
from setuptools import setup
with open('README.md', 'r') as fh:
long_description = fh.read()
setup(
name='ingreedypy',
py_modules=['ingreedypy'],
version='1.3.5',
description='ingreedy-py parses recipe ingredient lines into a object',
long_description=long_description,
long_description_co... |
# Autogenerated constants for Arcade Gamepad service
from enum import IntEnum
from jacdac.constants import *
from jacdac.system.constants import *
JD_SERVICE_CLASS_ARCADE_GAMEPAD = const(0x1deaa06e)
class ArcadeGamepadButton(IntEnum):
LEFT = const(0x1)
UP = const(0x2)
RIGHT = const(0x3)
DOWN = const(0... |
import os
import typing
import tornado.web
from tornado_swagger._builders import generate_doc_from_endpoints
from tornado_swagger._handlers import SwaggerSpecHandler, SwaggerUiHandler
STATIC_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "swagger_ui"))
def export_swagger(
routes: typing.List[to... |
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
dp = [0 for _ in range(len(cost))]
dp[0] = cost[0]
dp[1] = cost[1]
for k in range(2, len(cost)):
dp[k] = min(dp[k-1], dp[k-2]) + cost[k]
return min(dp[-1], dp[-2]) |
import json
import requests
import warnings
from .models import University
def _deprecated(msg):
warnings.simplefilter('always')
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
warnings.simplefilter('default')
class API(object):
"""API object for making requests to the university datab... |
"""
A federated learning training session using FEI.
"""
import logging
import fei_agent
import fei_client
import fei_server
import fei_trainer
def main():
""" A Plato federated learning training session using the FEI algorithm. """
logging.info("Starting RL Environment's process.")
trainer = fei_trainer... |
# Menu
# PROBABLY WONT COMPILE
from consolemenu import *
from consolemenu.items import *
from colorama import *
from termcolor import colored
from geo_scraper.site_scrapers import humdata_check_filter, humdata_scraper
print(colored(ascii-art.txt, 'green', 'on_red'))
menu = ConsoleMenu("chimera", "interface")
humd... |
import urllib.parse
import async_timeout
import aiohttp
import asyncio
import logging
import voluptuous as vol
import homeassistant.util as util
import voluptuous as vol
from datetime import timedelta
from homeassistant.helpers.aiohttp_client import async_get_clientsession
_LOGGER = logging.getLogger(__name__)
... |
# Copyright 2013 IBM Corp.
#
# 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 agree... |
from typing import Dict
class ConfigError(RuntimeError):
"""An error encountered during reading the config file
Args:
msg (str): The message displayed to the user on error
"""
def __init__(self, msg):
super(ConfigError, self).__init__("%s" % (msg,))
class MonzoInvalidStateError(Runt... |
import os
import torch
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
from functools import reduce
import abc
class imageDataset(Dataset):
def __init__(self, csv_file_path, cont_flag=True, standardize_dirty=False, dirty_csv_file_path=None):
self.df_dataset = pd... |
import copy
import datetime
import json
import unittest
from mock import MagicMock, patch
import config
from archiver.archiver import IngestArchiver, Manifest, ArchiveSubmission, Biomaterial
# TODO use mocks for integration tests
class TestIngestArchiver(unittest.TestCase):
def setUp(self):
self.ontolog... |
from pybamm import Parameter
def lico2_volume_change_Ai2020(sto):
"""
lico2 particle volume change as a function of stochiometry [1, 2].
References
----------
.. [1] Ai, W., Kraft, L., Sturm, J., Jossen, A., & Wu, B. (2020).
Electrochemical Thermal-Mechanical Modelling of Stress Inhomogenei... |
import sys
import os
__all__=['mc_wordcloud.py']
sys.path.append("..")
def Get(name):
return os.path.dirname(os.path.realpath(__file__)) + '\\' + name |
"""Loads configuration yaml and runs an experiment."""
from argparse import ArgumentParser
import os
import glob
from datetime import datetime
import shutil
import yaml
from tqdm import tqdm
import torch
import numpy as np
from collections import defaultdict
import data
import model
import probe
import regimen
import ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 5 01:30:10 2021
@author: kfp
"""
try:
import __devel__
_release_ = False
except:
_release_ = True
from functools import reduce
from pygnuplot import gnuplot
if not _release_:
from storage import STORAGE
else:
from numaplot.... |
from rdflib import Graph
from rdflib.resource import Resource
from rdflib.namespace import RDFS
def test_properties(rdfs_graph: Graph) -> None:
"""
The properties of a `rdflib.resource.Resource` work as expected.
"""
cres = Resource(rdfs_graph, RDFS.Container)
assert cres.graph is rdfs_graph
a... |
import pyglet
from pyglet.gl import *
from robocute.base import *
QUAD_SW = 0
QUAD_SE = 1
QUAD_NE = 2
QUAD_NW = 3
'''
Quad
'''
class Quad(Base):
def __init__(self, texture):
super().__init__()
self.texture = texture
self.width = texture.width
self.height = text... |
import py
from pypy.rpython.extfunc import BaseLazyRegistering, extdef, registering
from pypy.rlib import rarithmetic
from pypy.rpython.lltypesystem import lltype, rffi
from pypy.tool.autopath import pypydir
from pypy.rpython.ootypesystem import ootype
from pypy.rlib import rposix
from pypy.translator.tool.cbuild impo... |
import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
lock = threading.Lock()
acquired = lock.acquire()
print(acquired)
# acquired = lock.acquire() # this blocks the main thread
# p... |
#!/usr/bin/python3
# update_produce.py - Corrects costs in produce sales spreadsheet.
import openpyxl
wb = openpyxl.load_workbook('produceSales.xlsx')
sheet = wb.get_sheet_by_name('Sheet')
# Os tipos de produtos e seus processo atualizados
PRICE_UPDATES = {'Garlic': 99.07,
'Celery': 101.19... |
# Exercise_3_tests.py
from Tests import *
# format testów
# TESTS = [ {"arg":arg0, "hint": hint0}, {"arg":arg1, "hint": hint1}, ... ]
TESTS = [
# 0
{
"arg": [[[(1, 2), (2, 4)],
[(0, 2), (3, 11), (4, 3)],
[(0, 4), (3, 13)],
[(1, 11), (2, ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##----------------------------------------------------------
##file :get_maya_win.py
##author:xiyuhao
##email:695888835@qq.com
##----------------------------------------------------------
##date:2017.9.15
##-----------------------------------------------------------
import s... |
"""
Logging setup
By default: Log with lastResort logger, usually STDERR.
Logging can be overridden either programmatically in code using the library or by creating one or more of
- /etc/ocrd_logging.py
- $HOME/ocrd_logging.py
- $PWD/ocrd_logging.py
These files will be executed in the context of ocrd/ocrd_logging.p... |
import os
from pathlib import Path
from tempfile import NamedTemporaryFile
import numpy as np
from napari.utils import io
from napari.plugins.io import read_data_with_plugins
def test_builtin_reader_plugin(make_test_viewer):
"""Test the builtin reader plugin reads a temporary file."""
with NamedTemporaryFi... |
import unittest
from hamcrest import *
from src.students import Students
from src.exampleData import Data
class StudentsAssertPyTest(unittest.TestCase):
def setUp(self):
self.temp = Students(Data().example)
def test_delete_lack_student(self):
assert_that(calling(self.temp.deleteStudent)
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
from typing import List, Tuple, Union
if TYPE_CHECKING:
from .account import Account
from qlib.backtest.position import BasePosition, Pos... |
from urllib.parse import urlencode
import pytest
from django.core.exceptions import ImproperlyConfigured
from saleor.core.emails import get_email_context, prepare_url
def test_get_email_context(site_settings):
site = site_settings.site
expected_send_kwargs = {"from_email": site_settings.default_from_email}... |
from pokermon.poker.board import Board, mkflop
from pokermon.poker.cards import mkcard
from pokermon.poker.deal import FullDeal
from pokermon.poker.evaluation import EvaluationResult
from pokermon.poker.game_runner import GameRunner
from pokermon.poker.hands import HandType, mkhand
from pokermon.poker.result import Res... |
import requests
from jikanpy import Jikan
from animeoffline import *
from animeoffline import config
from animeoffline import utils
# if anime_offline/config.py is unedited, this assumes a local instance
# of jikan-rest is running on your system
# https://github.com/jikan-me/jikan-rest
jikan = Jikan(selected_base=co... |
#!/bin/usr/env python3
import argparse, sys
import time, os
from rclpy.qos import qos_profile_system_default
from rclpy.qos import QoSProfile
from rclpy.qos import QoSReliabilityPolicy
from rclpy.utilities import remove_ros_args
from rclpy.node import Node
import rclpy
import nudged
# from rmf_task_msgs.msg import Lo... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import dace
import dace.sdfg.nodes as nodes
from dace.fpga_testing import xilinx_test
import importlib.util
import numpy as np
from pathlib import Path
@xilinx_test()
def test_map_unroll_processing_elements():
# Grab the systolic GEMM im... |
class Component:
def __init__(self, start_node, end_node, val):
self.symbol = ''
self.type = 'generic'
self.start_node = start_node
self.end_node = end_node
self.val = val
self.id = -1
def is_node(self, node):
if (self.start_node == node) or (self.end_nod... |
# Generated by Django 3.0.6 on 2020-05-25 22:47
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('register', '0013_auto_20200525_2239'),
]
operations = [
migrations.AlterField(
model_name='patient... |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Thomas Amland
#
# 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... |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
# Write your code here
siblings = []
count = 0
if root:
siblings.append(root)
... |
from tests import TestCase
from unittest import skip
class TestMine(TestCase):
def test_my_account_as_anonymous(self):
self.assertLogin('/user')
def test_my_account_as_gateway(self):
self.login('main-gateway1@example.com', 'admin')
html = self.assertOk('/user')
response = self... |
from django.shortcuts import render, HttpResponseRedirect
from django.urls import reverse
def index(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('qa:index'))
else:
return render(request, 'web/index.html')
|
"""
Package for vectorized test particle simulation
Author : Tien Vo
Date : 12-29-2021
"""
from .plasma_parameters import *
from .hdf5_helpers import *
from .distribution import *
from .conversions import *
from .mpi_helpers import *
from .constants import *
from .whistler import *
from .pusher impor... |
# Problem Name: Tandem Bicycle
# Problem Description:
# A tandem bicycle is a bicycle that's operated by two people: person A and person B. Both peope pedal the bicycle, but the person that pedals faster dictates the speed of the bicycle. So if person A is pedals at a speed of 5, and person B pedals at a speed of 4, t... |
"""
Convenience functions and sample script for converting
Freesurfer annot files to a set of VTKs (and manifest file)
for use with the roygbiv web tool.
"""
import glob
import os
import json
import numpy as np
import nibabel as nib
HTML_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'web'))
DATA_DIR... |
#!/usr/bin/env python
import os
import scipy.stats as stats
import numpy as np
import pandas as pd
import ndjson
from pandas.io.json import json_normalize
import statsmodels.stats.multitest as mt
# The schema of the cpg genotype file is the following and the header is included
# snp_id
# chr
# asm_region_inf
# asm_r... |
import numpy as np
import torch
from pytorch3d.transforms import quaternion_multiply, quaternion_apply
class Skeleton:
def __init__(self, offsets, parents, device, joints_left=None, joints_right=None):
assert len(offsets) == len(parents)
self._offsets = torch.tensor(offsets, dtype=torch.float32, d... |
from collections import OrderedDict
import param
from ..io.resources import bundled_files
from ..reactive import ReactiveHTML
from ..util import classproperty
from .grid import GridSpec
class GridStack(ReactiveHTML, GridSpec):
"""
The GridStack layout builds on the GridSpec component and
gridstack.js to... |
#!/usr/bin/env python
#
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the OpenTimelineIO project
"""Test file for the track algorithms library."""
import unittest
import opentimelineio as otio
import opentimelineio.test_utils as otio_test_utils
class TimelineTrimmingTests(unittest.TestCase, oti... |
import logging
_LOGGER = logging.getLogger(__name__)
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.util import slugify
from homeassistant.components.device_tracker.config_entry import TrackerEntity
from homeassistant.helpers.dispatcher import async_dispatcher_connect
fro... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Alexey Pechnikov. All rights reserved.
# https://orcid.org/0000-0001-9626-8615 (ORCID)
# pechnikov@mobigroup.ru (email)
# License: http://opensource.org/licenses/MIT
# process [multi]geometry
def _NCubeGeometryToPolyData(geometry, dem=None):
#from shapely.geometry.base ... |
#!/usr/bin/env python3
from strips import *
from golog_program import *
from domains.elevator import *
up = lambda: Exec(ElevatorState.up())
down = lambda: Exec(ElevatorState.down())
turn_off = lambda: Exec(ElevatorState.turn_off())
def next_floor_to_serve(fl):
return Test(lambda s: s.light[fl])
def go_floor(fl... |
from pydantic import BaseModel, root_validator
from app.resources.utils import str_to_isoformat
class MeasurementRequest(BaseModel):
# API expects a json object like:
start_time: str # YYYY-MM-DDThh:mm:ss+00:00
stop_time: str # YYYY-MM-DDThh:mm:ss+00:00
@root_validator(pre=True)
def check_requ... |
"""
Django settings for sana_pchr project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databas... |
import json
import pickle
import zlib
# from sqlalchemy.orm.interfaces import SessionExtension
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.types import (
TypeDecorator,
VARCHAR,
PickleType
)
# py3 compatibility
try:
unicode
except NameError:
unicode = str
from six import iterit... |
from django import template
register = template.Library()
@register.inclusion_tag('project_components/tables/headers.html')
def header(*headers, expand_last_by=0):
context = {}
context.update({'headers': [header for header in headers]})
return context
|
import numpy as np
def identity():
return np.eye(3, dtype=np.float32)
def scale(s):
matrix = identity()
np.fill_diagonal(matrix[:2, :2], s)
return matrix
def translate(t):
matrix = identity()
matrix[:2, 2] = t
return matrix
def rotate(radian): # clockwise
cos = np.cos(radian)
... |
# Application condition
beep.id == max_used_id and not cur_node_is_processed
# Reaction
beep_code = "ecrobot_sound_tone(1000, 100, " + str(beep.Volume)+ ");\n"
code.append([beep_code])
id_to_pos_in_code[beep.id] = len(code) - 1
cur_node_is_processed = True
|
# Copyright 2021 Red Hat 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,... |
# Serializers define the API representation.
from django.contrib.auth import get_user_model
from rest_framework import serializers
User = get_user_model()
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
"id",
"email",
"... |
import pytest
from sympy.abc import a, b, c, d, e
from devito.tools import toposort
from devito import configuration
pytestmark = pytest.mark.skipif(configuration['backend'] == 'yask' or
configuration['backend'] == 'ops',
reason="testing is currently rest... |
from .WeiXinCrawler import WeiXinCrawler
|
import os, sys
from logs import logDecorator as lD
import json
from scipy.interpolate import interp1d
from scipy.integrate import odeint
import numpy as np
import tensorflow as tf
import time
from tensorflow.python.client import timeline
config = json.load(open('../config/config.json'))
logBase = config['logging'... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
### 创建带有偏差的 y = 3x^2 -2 的数据
x = np.random.rand(100, 1) # 制作100个0到1的随机数
x = x * 4 - 2 # 值的范围变更为-2~2
y = 3 * x**2 - 2 # y = 3x^2 - 2
y += np.random.randn(100, 1) # 加上标准正态分布(均值0、标准偏差1)的随机数
### 学习
from skl... |
from collections import defaultdict
class trienode():
def __init__(self, isleaf=False):
self.isLeaf = isleaf
self.mapping = defaultdict(trienode)
def get_mapping(self):
return self.mapping
def is_leaf(self):
return self.isLeaf
class trie:
def __init__(self, head=None... |
import sys
PATH = [
"src/comms/mqtt"
]
for lib in PATH:
sys.path.append(lib)
import mqtt_net as mqtt
# defining for test script
if __name__ == '__main__':
# Note: make sure you are reading values from a subscriber on the same board to see the result
# Start a client
mqtt_tx ... |
# coding: utf-8
# import the packages
import numpy as np
from scipy.misc import imread, imresize, imsave
import matplotlib.pyplot as plt
from numpy import matlib
import math
from scipy import stats
import imageio
from skimage.transform import resize
import skimage
import zlib, sys
import gzip
import matplotlib
impor... |
import numpy as np
import pytest
from numpy.testing import assert_almost_equal
from sequgen.dimension import Dimension
from sequgen.parameter_space import ParameterSpace
from sequgen.samplers.sample_uniform_random import sample_uniform_random
class TestParameterSpaceWithSinglePlainDimension:
@pytest.fixture
d... |
"""
Classes in this file are standalone because we don't want to impose a false hierarchy
between two classes. That is, inheritance may imply a hierarchy that isn't real.
"""
class Settings(object):
kExactTestBias = 1.0339757656912846e-25
kSmallEpsilon = 5.684341886080802e-14
kLargeEpsilon = 1e-07
SM... |
"""
Common methods and constants
"""
UUID_PATTERN = r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'
|
"""
File: 405.py
Title: Convert a Number to Hexadecimal
Difficulty: Easy
URL: https://leetcode.com/problems/convert-a-number-to-hexadecimal/
"""
import unittest
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return "0"
if num < 0:
num = 0xf... |
import numpy as np
import sys
import skimage.io as sio
import os
import sys
import shutil
from objloader import LoadTextureOBJ
libpath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(libpath + '/../lib')
import render
import objloader
input_obj = sys.argv[1]
V, F, VT, FT, VN, FN, face_mat, kdmap = objlo... |
"""
Module for working with modulemd YAML definitions with the least abstractions as
possible. Within this module, modulemd YAMLs are represented simply as a string,
and all transformation functions are `str` -> `str`.
"""
import os
import gi
import yaml
# python3-packaging in not available in RHEL 8.x
try:
from ... |
from unittest.mock import Mock
from prices import Money, TaxedMoney
from ....plugins.manager import PluginsManager
from ....product.models import ProductVariant
from ....product.utils.availability import get_variant_availability
from ...tests.utils import get_graphql_content
QUERY_GET_VARIANT_PRICING = """
query ($c... |
# -*- coding: utf-8 -*-
import pandas as pd
from windpyplus.utils.tradedate import tradedate
from windpyplus.stockSector.StockSector import allAstock, MSCIAStock
from windpyplus.fundamental.foreCastWind import foreCastWind
from windpyplus.utils.convertToWindCode import convertBQCode, convertCode
from windpyplus.utils... |
#!/usr/bin/env python
# Copyright 2017 Open Source Robotics Foundation
#
# 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 ... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: consensus_submit_message.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
fr... |
from tkinter import *
from videomaker.functions.startThread import startThread
def initButton(focus):
focus.startButton = Button(focus.master, text="Start!", width=42, height=5, command= lambda: startThread(focus))
# Cant make the text bigger or bolder without distorting the size of the button, even if the but... |
from Runner import Runner
from Scheduler import Scheduler
from model import Player, PlayerHadouken
def main():
runner = Runner(
players=(
Player(0),
),
state='ryu_vs_ken_highest_difficulty'
)
scheduler = Scheduler(runner.on_frame, fps=40)
scheduler.run()
if __name... |
'''OpenGL extension OES.fbo_render_mipmap
This module customises the behaviour of the
OpenGL.raw.GLES2.OES.fbo_render_mipmap to provide a more
Python-friendly API
Overview (from the spec)
OES_framebuffer_object allows rendering to the base level of a
texture only. This extension removes this limitati... |
from abc import ABC, abstractmethod
from ungenetico.gene import Gene
#from ungenetico.ga import GeneticAlgorithm
from ungenetico.population import Population
import random
from dataclasses import dataclass
from itertools import accumulate
import copy
import numpy as np
class Mutation(ABC):
"""Abstract class"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.