text
stringlengths
957
885k
#import modules import json from binance.client import Client import pandas as pd import os from envs import env import time import statistics import numpy as np from scipy.stats import kurtosis, skew #import classes from ./ folder import postgresdbAccess class tradingAccess: def __init__(self): #read fib...
########################################################################## # If not stated otherwise in this file or this component's Licenses.txt # file the following copyright and licenses apply: # # Copyright 2020 RDK Management # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
import abc from ..utils import SQLite3StorageMixin, warn RACE_CONDITION = "WerkzeugCacheTempSubscriberStorage race condition." class SQLite3SubscriberStorageBase(SQLite3StorageMixin): def __init__(self, path): self.TABLE_SETUP_SQL = """ create table if not exists {}( callback_id text...
<gh_stars>0 # Copyright 2019 Grakn Labs Ltd # # 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 ...
<reponame>osukurikku/kuriso # KrykiZZ fix for some country id's countryCodes = { "IO": 104, "PS": 178, "LV": 132, "GI": 82, "MZ": 154, "BZ": 37, "TR": 217, "CV": 52, "BI": 26, "CM": 47, "JM": 109, "GU": 91, "CY": 54, "BW": 35, "KW": 120, "MY": 153, "SH...
<filename>mopidy_raspiradio/gui.py import time from luma.core import cmdline, error from luma.core.interface.serial import i2c, spi from luma.core.render import canvas from luma.oled.device import ssd1306, ssd1322, ssd1325, ssd1331, sh1106 from PIL import ImageFont import timers class ProgressBar(object): __progre...
#!/usr/bin/env python import sys from cafysis.file_io.ninfo import NinfoFile from cafysis.elements.ninfo import NinfoSet if len(sys.argv) != 3: print ("Usage: SCRIPT [input ninfo 1] [input ninfo 2]") sys.exit(2) nf = NinfoFile(sys.argv[1]) nf.open_to_read() ns1 = NinfoSet() nf.read_all(ns1) nf.close() nf...
#!/usr/bin/env python """Add an Intersight user by providing Cisco.com user ID and role via the Intersight API.""" import sys import json import argparse from intersight.intersight_api_client import IntersightApiClient from intersight.apis import iam_permission_api from intersight.apis import iam_idp_reference_api from...
""" General helper functions for Gabby Gums. Function abilities include: Functions for handling long text Sending Error Logs to the Global error log channel Getting Audit logs. Check permissions on a channel. Part of the Gabby Gums Discord Logger. """ import sys import string import asyncio import...
from __future__ import absolute_import, division, print_function from builtins import (bytes, str, open, super, range, zip, round, input, int, pow, object, map, zip) __author__ = "<NAME>" import numpy as np from astropy import units from .frame_converter import convert_nuFnu_to_nuLnu_src, conv...
<gh_stars>10-100 from attr import dataclass import pytest import numpy as np import ezomero import filecmp import os from omero.gateway import TagAnnotationWrapper def test_omero_connection(conn, omero_params): assert conn.getUser().getName() == omero_params[0] # Test posts ############ def test_post_dataset(co...
import numpy as np import pygame from highway_env.road.lane import LineType from highway_env.road.road import Road from highway_env.vehicle.graphics import VehicleGraphics class WorldSurface(pygame.Surface): _initial_scaling = 5.5 _initial_centering = [0.5, 0.5] _scaling_factor = 1.3 _moving_factor =...
import datetime import json import pytest from django.conf import settings from django.urls import reverse from freezegun import freeze_time from parkings.models import Parking from ..utils import ( ALL_METHODS, check_method_status_codes, check_required_fields, delete, patch, post, put) list_url = reverse('...
#!/usr/bin/python ##################################################################### # Cloud Routes Management Scripts: Get Stats # ------------------------------------------------------------------ # Description: # ------------------------------------------------------------------ # Pull newly created users from th...
from __future__ import absolute_import import re from lxml import etree from datetime import datetime from datetime import timedelta class TempestTestcaseList(object): _FULL_CLASSNAME = re.compile(r'^(\w|\.)*') _TEST_PARAMETERS = re.compile(r'\[(.*)\]') _TEMPEST_UUID_RGX = re.compile(r'(\b[0-9a-f]{8}\b-[...
#!/usr/bin/env python # This plan contains tests that demonstrate failures as well. """ This example shows how to display various data modelling techniques and their associated statistics in Testplan. The models used are: * linear regression * classification * clustering """ import os import sys from testplan import ...
<gh_stars>0 from typing import Dict, List, Any, Union import numpy as np import pytorch_lightning as pl import torch from omegaconf import DictConfig from utils.text_processing_utils import Embedder from utils.utils import load_obj class WSDLightning(pl.LightningModule): def __init__(self, hparams: Dict[str, fl...
<filename>-Telecom-Churn-Prediction-with-Boosting-/code.py # -------------- import pandas as pd from sklearn.model_selection import train_test_split #path - Path of file # Code starts here df = pd.read_csv(path) X = df.drop(columns=['customerID','Churn']) y = df['Churn'] X_train,X_test,y_train,y_test = train_test...
import numpy as np aes_sbox = np.array([ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x...
<reponame>pulumi/pulumi-alicloud # 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, Sequenc...
<gh_stars>1-10 ''' Writes result into the file Author: <NAME> ''' import os import logging import numpy as np import torchtext from torchtext import data from torchtext import vocab import torch import torch.nn as nn from tqdm import tqdm, tqdm_notebook, tnrange tqdm.pandas(desc='Progress') import utility....
from .constants import Utf8 from .attributes import Attribute # From: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html ########################################################################## # 4.6. Methods ########################################################################## # Each method, incl...
<gh_stars>10-100 import random from typing import Type, Union import habitat from habitat import Config, Env, RLEnv, VectorEnv, make_dataset from habitat_baselines.common.env_utils import make_env_fn from habitat.core.logging import logger from robo_vln_baselines.common.environments import VLNCEDaggerEnv class Simpl...
# Copyright 2021 ONDEWO GmbH # # 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 twitter from django.apps import AppConfig from django.db.models.signals import post_save def truncate_headline(headline, n_char): last = headline[-n_char - 3] headline = headline[:-n_char -3] i = len(headline) while last not in " ,.;:" and i: i -= 1 last = headline[i] if i ...
#!/usr/bin/python # -*- coding: utf-8 -*- import time, urllib, csv, re, time, sys from operator import itemgetter import MySQLdb as mdb import numpy as np import datetime as dt lib_path = os.path.abspath('/secure/conf') import ccoin_conf as cconf try: cconf.__sec_initialize(token="<PASSWORD>") con = mdb....
import panflute as pf import pandocfilters, json def test_all(): fns = [ ('./tests/1/api117/benchmark.json', './tests/1/api117/panflute.json'), ('./tests/1/api118/benchmark.json', './tests/1/api118/panflute.json'), ('./tests/2/api117/benchmark.json', './tests/2/api117/panflute.json'), ...
from django.db import models from django.urls import reverse from django.utils.timezone import now from markdown import markdown class Comic(models.Model): title = models.CharField(max_length=128) slug = models.CharField(max_length=128, unique=True) author = models.CharField(max_length=128, blank=True) ...
<reponame>vnep-approx/vnep-approx import pytest from alib import datamodel from vnep_approx.extendedcactusgraph import ExtendedCactusGraph, ExtendedCactusGraphError class TestExtendedCactusGraph: def setup(self): self.substrate = datamodel.Substrate("paper_example_substrate") self.substrate.add_n...
import numpy as np import torch import collections from base.baseagent import BaseAgent from core.console import Progbar import core.math as m_utils import core.utils as U from Option import OptionTRPO import core.console as C import gc class GateTRPO(BaseAgent): name = "GateTRPO" def __init__(self,env, gate...
<gh_stars>0 from discord.ext import commands from discord.ext import menus import discord import random import asyncio import aiohttp import json hid = 666317117154525185 async def req(a=0): async with aiohttp.ClientSession() as session: if a != 0 and a != 1 and a != 2 and a != 3: a = 0 if a == 0: url = "U...
<reponame>AIandSocialGoodLab/learningplan<gh_stars>1-10 import pandas as pd, copy, numpy as np, mdptoolbox, math settings = open("settings.txt", 'r') NUM_KC = int(settings.readline()) NUM_PLEVELS = int(settings.readline()) settings.close() def str2list(s): return [int(i) for i in s.strip('[]').split(', ')] def dict...
#!/usr/bin/env python # # volumeopts.py - Defines the VolumeOpts class. # # Author: <NAME> <<EMAIL>> # """This module defines the :class:`VolumeOpts` class.""" import copy import logging import numpy as np import fsl.data.image as fslimage import fsleyes_props as props import fsleyes.gl as fs...
from typing import Optional, Set, List, Dict from bionorm.common.SieveBased.models import SieveBasedEntity from bionorm.common.SieveBased.processing import Terminology from bionorm.common.SieveBased.processing.sieves.base_sieve import BaseSieve class PartialMatchNCBISieve(BaseSieve): """Partial Match sieve. ...
# -*- coding: utf-8 -*- """ This module defines the functions to configure and interact with Maestral from the command line. Some imports are deferred to the functions that required them in order to reduce the startup time of individual CLI commands. """ # system imports import sys import os import os.path as osp impo...
<filename>preprocessy/outliers/_handleoutlier.py<gh_stars>0 import warnings import pandas as pd from ..exceptions import ArgumentsError class HandleOutlier: """Class for handling outliers on its own or according to users needs. Private methods _ _ _ _ _ _ _ _ _ _ __return_quartiles() : returns t...
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.6. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib ...
<reponame>esikachev/sahara-backup<filename>sahara/tests/unit/utils/test_keymgr.py # Copyright (c) 2015 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.o...
<reponame>banboooo044/natural-language-sentiment-anaysis import os,sys sys.path.append('../') import numpy as np import pandas as pd from tqdm import tqdm import torch import torch.nn as nn import torch.nn.functional as F from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, f1_s...
<reponame>PawelMlyniec/Dail-a-ride import argparse import time import sys import os import json import csv import matplotlib.pyplot as plt import numpy as np import math import random import torch import torch.nn as nn import torchvision.transforms as transforms from torch.optim.lr_scheduler import MultiStepLR, Reduce...
from unittest import TestCase import responses from requests import Session from ...controllers import CommentController, CommentsController from ...models import Comment from ...utils.response import DoccanoAPIError from .mock_api_responses import bad from .mock_api_responses import comments as mocks class Comment...
<gh_stars>1-10 ![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/OralAndWritt...
<filename>api/generator.py<gh_stars>1-10 import datetime from datetime import date from sys import stderr from custom_errors import * """ #################################################################### used to generate the combinations of queries for the selected predicates #####################################...
import random from typing import Any, Callable, Generator, Generic, List from uuid import uuid4 from fipy.ngsi.entity import BoolAttr, Entity, FloatAttr, TextAttr def float_attr_close_to(base: float) -> FloatAttr: """Generate a `FloatAttr` having a random value close to `base`. More accurately, the generated...
<reponame>tomacorp/thermapythia #!/Users/toma/python278i/bin/python from PyTrilinos import Epetra, AztecOO def main(): # define the communicator (Serial or parallel, depending on your configure # line), then initialize a distributed matrix of size 4. The matrix is empty, # `0' means to allocate for 0 elements ...
<filename>viper/__init__.py<gh_stars>0 import http.server import sys import os import logging import urllib.parse import cgi import random import collections import json log = logging.getLogger(__name__) # TODO: # module design # more sophisticated UI segments # integration of Bootstrap # Dashboard as a subclass of ...
<filename>dtool_lookup_gui/main.py # # Copyright 2021-2022 <NAME> # 2021 <NAME> # # ### MIT license # # 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 ...
#!/usr/bin/env python3 import ast from typing import List, Dict from collections import OrderedDict from pathlib import Path from pprint import pprint import sys import argparse # From https://docs.python.org/3/library/functions.html # No idea how this changed over time BUILTINS: List[str] = [ "abs", "all", ...
import typing from typing import List import osi3.osi_lane_pb2 as osi_lane from sqlalchemy.sql.base import NO_ARG from . import osidb from .common import Identifier, Vector3d from geoalchemy2.shape import to_shape class BoundaryPoint: """ A single point of a lane boundary. """ position: Vector3d ...
<filename>src/Users.py import urllib, urllib2, socket, cookielib, requests from requests.auth import AuthBase import json import re class KongUser: USER_INFO_URL = 'http://www.kongregate.com/api/user_info.json?username=' ACCOUNT_URL = 'http://www.kongregate.com/accounts/' def __init__(self, username): self._use...
<filename>uf/modeling/uda.py # coding:=utf-8 # Copyright 2021 Tencent. 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 ...
import numpy as np import pandas as pd from fklearn.causal.effects import linear_effect from fklearn.causal.validation.curves import (effect_by_segment, cumulative_effect_curve, cumulative_gain_curve, relative_cumulative_gain_curve, effect_curves) def test_effect_by_segm...
<gh_stars>0 import numpy as np import copy from constant import * from functools import reduce def softmax(x): probs = np.exp(x - np.max(x)) probs /= np.sum(probs) return probs class TreeNode(object): """ """ def __init__(self, parent, prior_p, state, action): sel...
<filename>Polynomial Regression.py # House Pricing Prediction # Polynomial Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset training_set = pd.read_csv('Data/train.csv') X_train = training_set.iloc[:, :-1] y = training_set....
<gh_stars>1-10 import numpy as np import matplotlib.pyplot as plt raw=open('housing.dat','rb').read().split('\n') raw=[x.split('\t') for x in raw] raw=raw[1:-1] dataset = raw[42:] dataset = [[float(x[1]),float(x[3])] for x in dataset] dataset = np.array(dataset) states = [x[0] for x in raw] states = sorted(list(set(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- r""" Utilities for generating strings for use in homoglyph attacks. Single-character -------------------------- To get a list of homoglyphs for a character, invoke :func:list_alternates on the character. >>> list_alternates("a")[:4] ['U+120042', '...
<gh_stars>0 import statistics from boundary.BinaryBoundary import BinaryBoundary from boundary.BinaryBoundaryWithFeatures import BinaryBoundaryWithFeatures from boundary.HistogramBoundary import HistogramBoundary from boundary.KDEBoundary import KDEBoundary from database.session import Session def boundary_rating():...
from models.User import User from global_data import r_envoy import json class AnalyticsController: def analyze_hand_result(data): hand_result = data["hand_result"] session_id = data["session_id"] email = data["email"] positive_feedback_message = "" hand_raised = Fa...
from typing import Dict, List, Tuple import matplotlib.pyplot as plt import networkx as nx import numpy as np import cv2 from src.aexpansion import make_expansion, show_segmentation, construct_segmentation from src.base_segmentation import kmeans from src.graph import add_data_edges, build_base_graph, compute_energy ...
<gh_stars>10-100 import jittor as jt from jittor import nn from jittor import Module from jittor import init from jittor.contrib import concat class NormLayer(Module): def __init__(self, num_features): G = 1 if num_features >= 512: G = 32 elif num_features >= 256: G ...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import time import intelliflow.api_ext as flow from intelliflow.api_ext import * import logging from intelliflow.core.application.core_application import ApplicationState from intelliflow.utils.test.hook import Gene...
<reponame>DTUWindEnergy/TopFarm2<filename>topfarm/tests/deprecated_tests/test_topfarm_problems/test_nested_problems.py from topfarm import TurbineTypeOptimizationProblem,\ TurbineXYZOptimizationProblem, InitialXYZOptimizationProblem from openmdao.drivers.doe_generators import FullFactorialGenerator,\ ListGenera...
# Author: KTH dESA Last modified by <NAME> # Date: 26 November 2018 # Python version: 3.7 import os import logging import pandas as pd from math import ceil, pi, exp, log, sqrt, radians, cos, sin, asin from pyproj import Proj import numpy as np from collections import defaultdict logging.basicConfig(format='%(asctime...
#!/usr/bin/env python3 import sys; assert sys.version_info[0] >= 3, "Python 3 required." import os from binascii import unhexlify, hexlify from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend from .utils import bebs2ip, i2bebsp, beos2ip...
import tkinter as tk from tkinter import messagebox import stockclick as sc import time import os import pyperclip import subprocess import datetime import stockmodule as m import datetime import s0056 def check_pw(): global stop stop = False _, msg1, msg2 = s0056.send_info(2) listbox....
import math import numpy as np import numpy.matlib import time import uuid import os import sqlite3 import datetime import threading import multiprocessing import time import random import sys sys.path.append("../src/") import plantsKin as pk import baseToolbox as bt from math import pi threaded =...
<reponame>ninatu/anomaly_detection<gh_stars>10-100 """ Extract tumor patches from tumor slides """ import openslide import os from tqdm import tqdm import pandas as pd import numpy as np import skimage.io import skimage.transform import argparse import sys sys.path.append('./') from utils import get_tissue_mask, pre...
<reponame>pwqbot/eoj3 import logging import os import subprocess import traceback from django.conf import settings from django.shortcuts import redirect from django.urls import reverse from django.views import View from django.views.generic import ListView from django_q.tasks import async_task from contest.models imp...
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. import logging from cohesity_management_sdk.api_helper import APIHelper from cohesity_management_sdk.configuration import Configuration from cohesity_management_sdk.controllers.base_controller import BaseController from cohesity_management_sdk.http.auth.auth_manag...
<reponame>a-vishar/azure-cli # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ---------------------------------------...
<filename>generate_epitope_combinations.py from __future__ import division import pandas as pd import random import os import sys import csv try: from cStringIO import StringIO except ImportError: from io import StringIO import time import argparse from os import path from datetime import datetime import iter...
<filename>src/quantum/azext_quantum/vendored_sdks/azure_quantum/quantum_client.py # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license in...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Build a neural machine translation model with soft attention """ import copy import sys from collections import OrderedDict import ipdb import numpy import theano import theano.tensor as tensor from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams fro...
<gh_stars>0 """ Copyright MIT and Harvey Mudd College MIT License Summer 2020 Lab 1 - Driving in Shapes """ ######################################################################################## # Imports ######################################################################################## import sys sys.path....
# -*- coding: utf-8 -*- import optparse import os import sys import getpass import json import hashlib import smtplib import commands import subprocess import shutil import re from pbxproj import XcodeProject from pbxproj.pbxextensions.ProjectFiles import FileOptions #钥匙链相关 keychainPath="~/Library/Keychains/login.keyc...
<filename>contentcuration/contentcuration/views/admin.py import ast import base64 import cStringIO as StringIO import csv import json import locale import os import sys import time from itertools import chain import django_filters from django.conf import settings from django.contrib.auth.decorators import login_requir...
from collections.abc import Sequence import mmcv import numpy as np import torch from mmcv.parallel import DataContainer as DC class FormatShape: """Format final imgs shape to the given input_format. Required keys are "imgs", "num_clips" and "clip_len", added or modified keys are "imgs" and "input_shape"...
import logging from typing import TYPE_CHECKING, Callable, Dict, Optional, Tuple, Type, Union from django.contrib.auth import get_user_model from django.db import models from snitch.emails import TemplateEmailMessage from snitch.settings import ENABLED_SEND_NOTIFICATIONS if TYPE_CHECKING: from push_notifications...
<filename>cogs/moderation.py """ MIT License Copyright (c) 2021 - µYert Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, ...
import sys sys.path.append("../") sys.path.append("/home/ray__/ssd/BERT/") sys.path.append("/home/ray__/CS/org/etherlabs/ai-engine/pkg/") import text_preprocessing.preprocess as tp from extra_preprocess import preprocess_text from filter_groups import CandidateKPExtractor import nltk import networkx as nx from gpt_feat...
<filename>src/share.py # -*- coding: utf-8 -*- """ This is the share module of the game. @Author: yanyongyu """ __author__ = "yanyongyu" __all__ = ["copy", "save", "send_email"] import re import os import sys import time import logging import threading from tkinter import * from tkinter.ttk import * from tkinter impor...
<reponame>machow/pins-python<gh_stars>0 from pathlib import Path from .config import get_allow_pickle_read, PINS_ENV_INSECURE_READ from .meta import Meta from .errors import PinsInsecureReadError from typing import Sequence # TODO: move IFileSystem out of boards, to fix circular import # from .boards import IFileSys...
<filename>nn/augmentations.py from math import sqrt, pi import torch from torch import Tensor from torch.nn import Module, functional as F from nn.exponential_moving_average import ExponentialMovingAverage def t_2d(x: Tensor, y: Tensor) -> Tensor: assert x.ndim == y.ndim == 1 assert x.shape == y.shape ...
import asyncio import inspect import math import os import re import sys import traceback import uuid from base64 import b64decode from collections import OrderedDict, deque from contextlib import redirect_stdout from io import BytesIO, StringIO from itertools import chain import aiohttp from async_timeout import time...
<reponame>ankitkariryaa/MultiPlanarUNet<filename>mpunet/callbacks/callbacks.py import tensorflow as tf import psutil import numpy as np import os import matplotlib.pyplot as plt from tensorflow.keras.callbacks import Callback from datetime import datetime from mpunet.logging import ScreenLogger from mpunet.utils.plotti...
<reponame>arve0/leicacam<filename>test/test_cam.py """Tests for cam module.""" import socket from collections import OrderedDict from unittest.mock import MagicMock, patch import pytest from leicacam.cam import CAM, bytes_as_dict, tuples_as_bytes, tuples_as_dict # pylint: disable=redefined-outer-name, unnecessary-pa...
import test_util.proxy import test_util.runner import http.client import http.server import threading import test_util.thread_safe_counter import random import time if __name__ == "__main__": request_counter = test_util.thread_safe_counter.Counter() # This is HTTP 1.0 server that doesn't support persisent co...
<reponame>LSSTDESC/galsampler """ """ import numpy as np import pytest from ..utils import crossmatch from ..source_halo_selection import source_halo_index_selection, get_source_bin_from_target_bin from ..host_halo_binning import halo_bin_indices __all__ = ('test_source_halo_index_selection_no_missing_source_cells',...
#! /usr/bin/env python ####################################### # createPropSymbol.py # # A python class to create a nested proportional symbol showing three values. # # Used as part of the SoilSCAPE website to create symbols used in open layers to # display soil moisture. # See http://soilscape.usc.edu/drupal/?q=no...
<gh_stars>1-10 import os import torch import torch.utils.data as data import numpy as np from PIL import Image, ImageFile import random from torchvision.transforms import ToTensor from torchvision import transforms import cv2 import torch.nn.functional as F ImageFile.LOAD_TRUNCATED_IMAGES = True def collate_features...
"""A simple but complete HTML to Abstact Syntax Tree (AST) parser. The AST can also reproduce the HTML text. Example:: >> text = '<div class="note"><p>text</p></div>' >> ast = tokenize_html(text) >> list(ast.walk(include_self=True)) [Root(''), Tag('div', {'class': 'note'}), Tag('p'), Data('text')] ...
<filename>minesweeper.py #!/usr/bin/env python3 def dump(game): """ Prints a human-readable version of a game (provided as a dictionary) """ for key, val in sorted(game.items()): if isinstance(val, list) and val and isinstance(val[0], list): print(f'{key}:') for inner ...
<gh_stars>0 # 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 fr...
<reponame>osswangxining/iot-app-enabler-conversation<filename>conversationinsights-mynlu/mynlu/pipeline/__init__.py from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import import logging import os from collections import defau...
import argparse import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from PIL import Image from collections import OrderedDict import json impo...
# Copyright 2019 NREL # 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 distribu...
<reponame>bshishov/DeepForecasting<filename>models/lstm_conv.py import keras import matplotlib.pyplot as plt import numpy as np from keras import layers import metrics import processing import utils from layers.conv_deform_1d import ConvDeform1D, describe_deform_layer class CustomLSTM(keras.layers.LSTM): pass ...
<filename>cnn/models/resnet_imagenet.py # modified from https://github.com/fastai/imagenet-fast/blob/master/imagenet_nv/models/resnet.py import torch.nn as nn import math import torch.utils.model_zoo as model_zoo from .layers import Flatten from .butterfly_conv import ButterflyConv2d, ButterflyConv2dBBT def conv3x3(...
<gh_stars>1-10 from django.db import models from django import forms from django.utils.translation import gettext_lazy as _ from wagtail.admin.edit_handlers import TabbedInterface, ObjectList from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel from wagtail.images.edit_handlers import ImageChooserPanel ...
<gh_stars>1-10 import re from .common import Void, TokenizerError, SyntaxError from .location import Location, Source ################# ### TOKENIZER ### ################# class Token: def __init__(self, **args): self.location = None self.__dict__.update(args) def __str__(self): ret...