content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python """ .. module:: converters :synopsis: Converters for handling various types of content. """ import docutils import docutils.core import markdown import os content_types = ["markdown", "ReST"] # Content converters. def convertMDtoHTML(markdown_text): return markdown.markdown(markdown_text...
python
import logging def get_logger(): logger = logging.getLogger("ddns_server") logger.setLevel(logging.INFO) log_file = logging.FileHandler("log.log") log_file.setLevel(logging.INFO) log_stream = logging.StreamHandler() log_stream.setLevel(logging.INFO) formatter = logging.Formatter("[%(asc...
python
import imagehash import pandas as pd import os from PIL import Image from collections import defaultdict from square_crop import square_crop directory_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego_images/' data_path = '/Users/Ziyu/OneDrive - Clarivate Analytics/Desktop/lego/image_hashes_2.csv' data_...
python
#!/usr/bin/python # Import the CGI module import MySQLdb import cgi import cgitb cgitb.enable() # Test with: http://192.168.0.100:8000/cgi-bin/AddingDataXml.py?operanda=2&operandb=3&answer=5 # Required header that tells the browser how to render the HTML. def getHeader(): return """Content-Type: text/xml\n <?xml ...
python
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 import logging from myuw.dao.registration import get_schedule_by_term from myuw.dao.instructor_schedule import get_instructor_schedule_by_term from myuw.dao.term import get_current_quarter, get_current_summer_term from myuw.dao.buil...
python
#coding:utf-8 import scapy_http.http as HTTP from scapy.all import * from scapy.error import Scapy_Exception import time import re import os from xmlrpclib import ServerProxy count=0 pt = re.compile('(GET|POST).*(HTTP)') ag = re.compile('(User-Agent:).*') s = ServerProxy("http://localhost:8888") def getURL(data): u...
python
# coding=utf-8 import unittest from rozipparser.codeparser import CodeParser class TestSmallLocalityParsing(unittest.TestCase): def test_number_of_codes(self): parser = CodeParser("rozipparser/tests/inputs/small_locality_input.xlsx") codes = parser.get_codes() self.assertEqual(len(codes...
python
# 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 """ from pprint import pformat from six import iteritems import re class VideoCategory(object): """ NOTE: This class is au...
python
import cv2 import numpy as np img = cv2.imread('prof.jpeg', cv2.IMREAD_COLOR) img = cv2.resize(img, (500, 500)) # perfom a filter with a kernel # its like blurring it removes edges and averages blur1 = cv2.blur(img, (3,3)) # well in this case they are the same # Gaussian filter creation cv2.getGaussianKer...
python
from django import template from ..models import Category register = template.Library() @register.simple_tag def title(): return 'وبلاگ جنگویی' @register.simple_tag def brand_name(): return 'جنگو وب' @register.inclusion_tag('blog/partial/category_navbar.html') def category_navbar(): return { 'ca...
python
import random def generate_email(): prefix = 'ak' + str(''.join([random.choice(list('qwertyuio')) for x in range(5)])) return f"{prefix}@mail.ru" def generate_name(): prefix = 'Pug_' + str(''.join([random.choice(list('123456789')) for x in range(2)])) return prefix def test_login(app): admin_f...
python
# coding: utf-8 ################################################################################ # CS 224W (Fall 2017) - HW1 # Code for Problem 1 # Author: luis0@stanford.edu # Last Updated: Oct 8, 2017 ################################################################################ import snap import numpy as np impo...
python
import os def cpr(parentFile, pasteDir, names): parentFileContent = open(parentFile, "rb").read() extension = os.path.splitext(parentFile)[1] for name in names: name = str(name) currentDir = os.path.join(pasteDir, name)+extension currentFile = open(currentDir, "wb") currentFile.write(parentFileCont...
python
import time import bisect import dgl import torch import numpy as np from tqdm import tqdm # Count motif 1 def count_motif_1_1(g, threshold_time, eid): src, dst = g.find_edges(eid) if not g.has_edges_between(dst, src): return src_out_timestamp = g.edata['timestamp'][g.out_edges(src, form='eid')] src_out_...
python
# coding: utf8 from pycropml.transpiler.main import Main source = u"""def test(int a): cdef list g=[14,15,12,12] cdef int i a=12 for i in g: a=a+i return a """ output_cs=u"""using System; using System.Collections.Generic; public class Program { static in...
python
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you m...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-10-16 07:07 from __future__ import unicode_literals from django.db import migrations import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('cart', '0005_auto_20180111_0700'), ] operations = [ migrati...
python
from tkinter import * import sys # Medicine Menu def mclickedbtn1(): print("Hello") def mclickedbtn2(): print("Hello") def mclickedbtn3(): print("Hello") def mclickedbtn4(): print("Hello") def clickedbtn1(): medicine_menu_window = Tk() medicine_menu_window.geometry('350x200') medicine_menu_w...
python
# coding: utf-8 # # Explore offset vector # # We want to know what the offset vector is capturing. Theoretically it should be capturing the "essence of gene A" since it is defined by taking the samples with the highest expression of gene A and the lowest expression of gene A. # # We want to test if this offset vec...
python
import os import platform import click import kungfu.yijinjing.journal as kfj import pyyjj @click.group(invoke_without_command=True) @click.option('-H', '--home', type=str, help="kungfu home folder, defaults to APPDATA/kungfu/app, where APPDATA defaults to %APPDATA% on windows, " ...
python
#!/usr/bin/env python # coding: utf-8 # # Gaussian Mixture Model # # GMM runs on 5 features by default: beam, gate, time, velocity, and spectral # width. It performs well overall, even on clusters that are not well-separated # in space and time. However, it will often create clusters that are too high # varian...
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2017-12-05 07:47 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0055_merge_20171205_0847'), ] operatio...
python
from pathlib import Path from fhir.resources.codesystem import CodeSystem from oops_fhir.utils import CodeSystemConcept __all__ = ["AuditEventSourceType"] _resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json")) class AuditEventSourceType: """ Audit Event Source Type The type of proces...
python
from fastapi_tag.base import model __all__ = ["model"]
python
#!/usr/bin/env python """ plot energy usage by PM jobs """ __author__ = "Jan Balewski" __email__ = "janstar1122@gmail.com" import numpy as np import time from pprint import pprint from toolbox.Plotter_Backbone import Plotter_Backbone from toolbox.Util_IOfunc import read_one_csv from toolbox.Util_Misc import smooth...
python
# -*- coding: utf-8 -*- # ============================================================================= # MIT License # # Copyright (c) 2018 Charles Jekel # # 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...
python
# Script to get the system's info from __future__ import print_function import platform import multiprocessing as mp ''' Functions: ------------------------------------------------------ sysinfo(display = True, return_info = False) Gets the details about the system ----------------------------...
python
import LevelBuilder from sprites import * def render(name,bg): lb = LevelBuilder.LevelBuilder(name+".plist",background=bg) lb.addObject(Hero.HeroSprite(x=42, y=245,width=32,height=32)) lb.addObject(Beam.BeamSprite(x=42, y=287,width=17,height=14,angle='0',restitution=0.2,static='true',friction=0.5,density=20...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys class UnsupportedPythonError(Exception): pass __minimum_python_version__ = "3.6" if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): raise UnsupportedPythonError(f"pyvib does not support Python < {__minimum_pytho...
python
# Generated by Django 2.1.5 on 2019-02-07 23:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hyperion', '0003_userprofile_url'), ] operations = [ migrations.AddField( model_name='userprofile', name='github', ...
python
import random from evennia import TICKER_HANDLER from evennia import CmdSet, Command, DefaultRoom from evennia import utils, create_object, search_object from evennia import syscmdkeys, default_cmds from evennia.contrib.text_sims.objects import LightSource, TutorialObject # the system error-handling module is defined...
python
#coding=utf8 import itchat import re import sys from itchat.content import * global author global isDisturbOn global visit global username def messageProccess(msg): if not msg["FromUserName"] == author: if msg["Type"] == "Text": if re.search("#sinon", msg["Text"]) == None: if i...
python
import os from setuptools import setup from gitissius import gitissius setup( name = "Gitissius", version = gitissius.VERSION, author = "Giorgos Logiotatidis", author_email = "seadog@sealabs.net", description = "Distributed bug tracking for Git.", license = "Mixed", keywords = "bug, tracki...
python
""" Plot ENSO from 2015-2018 using daily oisstv2 Data : 18 March 2018 Author : Zachary M. Labe """ from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset import datetime import cmocean ### Directory and time directoryfigure = './Figures/' directorydat...
python
# -*- coding: utf-8 -*- """ Guney's network proposed in A Deep Neural Network for SSVEP-based Brain-Computer Interfaces. Modified from https://github.com/osmanberke/Deep-SSVEP-BCI.git """ from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F from .base import compute_...
python
import numpy as np import itertools import torch class TestAugmentor(object): """Test Augmentor. Args: mode (str): inference mode ('min', 'max', 'mean'). num_aug (int): number of data augmentations: 4-fold, 16-fold """ def __init__(self, mode='min', num_aug=4): self.mode = mode...
python
""" Cciss - Files ``/proc/driver/cciss/cciss*`` =========================================== Reads the ``/proc/driver/cciss/cciss*`` files and converts them into a dictionary in the *data* property. Example: >>> cciss = shared[Cciss] >>> cciss.data['Logical drives'] '1' >>> 'IRQ' in cciss.data True...
python
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import super from future import standard_library standard_library.install_aliases() import logging import os import errno from .BaseDispatch import BaseDisp...
python
from nintendo import account api = account.AccountAPI() pid = api.get_pid("Kinnay-WiiU") mii = api.get_mii(pid) print("NNID:", mii.nnid) print("PID:", pid) #Same as mii.pid print("Name:", mii.name) info = mii.data print("Mii:") print("\tBirthday: %i-%i" %(info.birth_day, info.birth_month)) print("\tCreator name:", i...
python
from unittest.mock import patch from pytest import fixture @fixture(autouse=True) def environ(): environ = { "slack_access_token": "slack-access-token", "slack_signing_secret": "slack-signing-secret", } with patch.dict("os.environ", environ, clear=True): yield environ @fixture d...
python
import cv2 import numpy as np from operator import floordiv vc = cv2.VideoCapture(0) cv2.namedWindow("top") cv2.namedWindow("bottom") if vc.isOpened(): rval, frame = vc.read() height = len(frame) width = len(frame[0]) else: rval = False lights = (16,9) history = 5 top = np.zeros((lights[0], 1,...
python
""" If you use this code, please cite one of the SynthSeg papers: https://github.com/BBillot/SynthSeg/blob/master/bibtex.bib Copyright 2020 Benjamin Billot 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 Lice...
python
"""Multiply SOIL13 and SOIL14 by 10 to change units from % to g/kg""" import pyiem.cscap_utils as util def main(): """Go Main Go""" config = util.get_config() spr_client = util.get_spreadsheet_client(config) drive = util.get_driveclient(config) # Fake last conditional to make it easy to reproces...
python
##!/usr/bin/python import numpy as np import pylab as plt import seaborn as sns sns.set_context('poster') plt.subplot(1,1,1) data = np.genfromtxt(fname='energy.dat') #data = np.loadtxt('traj.dat') #for x in range(1,data.shape[-1]): plt.plot(data[:,0],data[:,1],label='kinetic') plt.plot(data[:,0],data[:,2],label='p...
python
import nxutils import networkx as nx # TODO: Update this to remove dependency on static zipcode # if we ever need to use this code zipCode = '02138' prefix = 'neighborhood' n = nxutils.NXUtils(prefix, zipCode) n.buildNetwork() DG = n.getNetwork() fullCycles = nx.simple_cycles(DG) print('Number of cy...
python
# This file was auto generated; Do not modify, if you value your sanity! import ctypes try: # 2 from can_settings import can_settings from swcan_settings import swcan_settings except: from ics.structures.can_settings import can_settings from ics.structures.swcan_settings import swcan_settings # flags ...
python
"""Optimization methods."""
python
# -*- coding: utf-8 -*- """Build functions to wrap mlflow models. Existing implementation returns a synchronous/blocking function. This decision was taken because applying ML models is probably CPU-bound. Not having unnecessary asynchronous code also makes testing simpler. Current supports only the pyfunc flavour. C...
python
# Generated by Django 4.0.2 on 2022-02-04 17:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mainapp', '0001_initial'), ] operations = [ migrations.RenameField( model_name='products', old_name='product_type', ...
python
""" Copyright 2019 IBM Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software...
python
# Copyright (c) 2019 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...
python
import time from multiprocessing import Queue from queue import Full import numpy as np from .sampler import Sampler class FakeSampler(Sampler): def __init__(self, instance: np.ndarray, sample_queue: Queue, num_of_samples: int = 1000): super(FakeSample...
python
# Copyright (c) 2013 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditi...
python
import os.path as P def relative_path(this_file , rel_path): return P.join(P.dirname(this_file) , rel_path)
python
import pytest from qualipy.filters import * PATTERN = 'tests/images/pattern.jpg' NON_PATTERN = 'tests/images/lama.jpg' def test_recognizes_pattern(): assert Pattern().predict(PATTERN) def test_doesnt_recognize_normal_image(): assert not Pattern().predict(NON_PATTERN) def test_setting_threshold(): a...
python
from . import backup import logging from .config import DropboxOfflineBackupConfig def start(): logging.getLogger('').setLevel(logging.DEBUG) console = logging.StreamHandler() file_handler = logging.FileHandler(DropboxOfflineBackupConfig().config['DropboxBackup']['LogFile']) formatter = logging.Formatt...
python
#! /usr/bin/python3 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # import os import re import time import commonl.testing import tcfl.tc srcdir = os.path.dirname(__file__) ttbd = commonl.testing.test_ttbd( config_files = [ # strip to remove the compiled/optimized versi...
python
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/FamilyMemberHistory Release: R4 Version: 4.0.1 Build ID: 9346c8cc45 Last updated: 2019-11-01T09:29:23.356+11:00 """ import io import json import os import unittest import pytest from .. import familymemberhistory from ..fhirdate import FHIR...
python
# -*- coding: utf-8 -*- # Time : 2021/7/25 13:59 # Author : QIN2DIM # Github : https://github.com/QIN2DIM # Description: import json import os from datetime import datetime from bs4 import BeautifulSoup from selenium.common.exceptions import ( StaleElementReferenceException, WebDriverException, ...
python
import stweet as st def test_return_tweets_objects(): phrase = '#koronawirus' search_tweets_task = st.SearchTweetsTask( all_words=phrase, tweets_count=200 ) tweets_collector = st.CollectorTweetOutput() result = st.TweetSearchRunner( search_tweets_task=search_tweets_task, ...
python
import lmfit import numpy as np from uncertainties import ufloat from scipy.stats import sem from collections import OrderedDict from pycqed.analysis import fitting_models as fit_mods from pycqed.analysis import analysis_toolbox as a_tools import pycqed.analysis_v2.base_analysis as ba from pycqed.analysis.tools.plottin...
python
def zk_demo(cfg,V,F,ZMvtk) : #function max_abs_diff = demo( V,F,ZMvtk ) # num_vertices = 3 # num_vertices = 3; num_facets = cfg.size(F,0) #! ...
python
from django.urls import path from . import api_views, views urlpatterns = [ path('', views.firework_home, name='fireworks-home'), path('add/', views.add_firework, name='fireworks-add'), path('categories', views.category, name='fireworks-categories'), path('category/<slug:category_slug>/', views.catego...
python
from pydantic import BaseModel from starlette.requests import Request from fastapi.security.base import SecurityBase from fastapi.security.utils import get_authorization_scheme_param from typing import Optional from starlette.status import HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED from fastapi.exceptions import HTTPE...
python
print(1)<caret>
python
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY 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 version. CVXPY is distributed i...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import torch from torchknickknacks import metrics x1 = torch.rand(100,) x2 = torch.rand(100,) r = metrics.pearson_coeff(x1, x2) x = torch.rand(100, 30) r_pairs = metrics.pearson_coeff_pairs(x)
python
# Based off of https://github.com/getninjas/celery-executor/ # # Apache Software License 2.0 # # Copyright (c) 2018, Alan Justino da Silva # # 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 # # ...
python
import os import sys import json from pathlib import Path import shutil import argparse from wikiutils import split_wiki, sample_docs, cleanup_paths, save_stats parser = argparse.ArgumentParser() parser.add_argument("-l", "--lang", required=True, help="language of the wiki-dump to download / preprocess", type=str) ...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import uuidfield.fields class Migration(migrations.Migration): dependencies = [ ('schedule', '0001_initial'), migrations.swappable_dependency(settings.AUTH_US...
python
from .base import Dashboard
python
from django import forms from django.contrib import messages class InputForm(forms.Form): query = forms.CharField(max_length=200)
python
#!/usr/bin/python import base64 import binascii # CONSTANTS WORDLISTFILE = r'OSPD4.txt' SET1CH4INPUTFILE = r'4.txt' SET1CH6INPUTFILE = r'6.txt' # Functions def hextobase64(hexstring): bin = binascii.unhexlify(hexstring) return base64.b64encode(bin).decode() def xor(binary1, binary2): return ''.join(chr(ord(a) ^...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import unittest from mock import mock from conans.client.tools.oss import detected_architecture class DetectedArchitectureTest(unittest.TestCase): def test_various(self): # x86 with mock.patch...
python
import pytest import shutil from accident_prediction_montreal.weather import get_weather_station_id_df from accident_prediction_montreal.utils import init_spark @pytest.fixture(scope='session') def spark(): return init_spark() def test_get_weather_station_id_df(spark): acc_sample = spark.read.parquet('test...
python
# -*- coding: utf-8 -*- import sys import argparse from kits.parse_articles import parse_articles from config.conf import conf from config.conf import enviroment from kits.log import get_logger def initialize(): parser = argparse.ArgumentParser() parser.add_argument("-e", "--env", action="store", dest="env...
python
#!/usr/bin/env python # encoding: utf-8 # PYTHON_ARGCOMPLETE_OK # from __future__ imports must occur at the beginning of the file from __future__ import unicode_literals from __future__ import print_function from __future__ import division from .bypy import main if __name__ == "__main__": main() # vim: tabstop=4 n...
python
""" Define a new function using the @qgsfunction decorator. The function accept the following parameters :param [any]: Define any parameters you want to pass to your function before the following arguments. :param feature: The current feature :param parent: The QgsExpression object :param context: If th...
python
""" The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY """ from datetime import datetime class CommonRealDateUtils: ...
python
import logging from .utils import get_logging_level class Client(object): """ This object autheticates the account to the api """ def __init__(self, auth, **kwargs): """ Initializes Client object. Args: auth (tuple): Authentication object api (str): Api endpat...
python
from django.shortcuts import render from .models import Salas,Rentals from django.db.models import Q from django.shortcuts import get_object_or_404 from .forms import RentalForm def salas_home_view(request,*args,**kargs): hora_inicial = request.GET.get('inicio',None) hora_fim = request.GET.g...
python
from typing import MutableSequence class WrappingList(MutableSequence): def __init__(self, l=[]): if type(l) is not list: raise ValueError() self._inner_list = l def __len__(self): return len(self._inner_list) def __delitem__(self, index): index = self.__va...
python
import numpy as np from scipy.special import erf class GELU: def __call__(self, x: np.ndarray, approximate: bool = True) -> np.ndarray: if approximate: return x * 0.5 * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3)))) return x * 0.5 * (1.0 + erf(x / np.sqrt(2.0))) ...
python
import sys import os import pty import subprocess import shlex import selectors import multiprocessing as mp def run(cmd, input_lines=[]): """Run an interactive given command with input and capture all IO. Parameters ---------- cmd: str The command to run input_lines: list List ...
python
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jan 3 14:52:19 2017 @author: Falaize """ from __future__ import absolute_import import sys from PyQt5.QtWidgets import QApplication from widgets import PyphsGui import os path = os.path.join('pyphs_gui', 'tests', 'rlc.net') os.chdir('..') def runn...
python
# Copyright 2014 Baidu, 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...
python
#******************************************************************************* # # Filename : EDMNaming.py # Description : Getting the reduced name of a dataset and others # Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] # #*******************************************************************...
python
# Copyright 2019 Extreme 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 by applicable law or agreed to i...
python
# -*- coding: utf-8 -*- from rest_framework import viewsets, mixins from .models import Pet, Birth, Breed from .serializers import PetSerializer, BreedSerializer, BirthSerializer class PetViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset ...
python
""" Tests Input.__init__() and classes in input_classes.py Note that this is more of a regression test than a unit test. Compares with previously computed results.""" import os import numpy as np import pytest import astropy.units as u from astropy.time import Time from nexoclom.solarsystem import SSObject from nexoclo...
python
import argparse import os import numpy as np import torch from mmcv.runner import Sequential from tensorflow.python.training import py_checkpoint_reader from mmcls.models.backbones.efficientnet import EfficientNet def tf2pth(v): if v.ndim == 4: return np.ascontiguousarray(v.transpose(3, 2, 0, 1)) el...
python
import requests import re from bs4 import BeautifulSoup import pandas as pd import sys from PyQt4.QtGui import QApplication from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebPage import bs4 as bs import urllib.request import os import datetime path_of_brandwise = 'C:\\LavaWebScraper\\BrandWiseF...
python
#!/usr/bin/env python3 import argparse import sys import os import stat import httplib2 from oauth2client.service_account import ServiceAccountCredentials import apiclient SCOPE = 'https://www.googleapis.com/auth/androidpublisher' SCRIPT_VERSION = '2021-08-22' def print_info(): print('publisher.py: %s' % SCRIPT_V...
python
"""Base register module""" def pad_zeroes(addr, n_zeroes): """Padds the address with zeroes""" if len(addr) < n_zeroes: return pad_zeroes("0" + addr, n_zeroes) return addr def int_addr(addr): """Gets the integer representation of an address""" return int(addr[1:]) def next_addr(addr, i): ...
python
from . import views from django.urls import path urlpatterns = [ path('', views.BlogHome.as_view(), name='blog'), ]
python
# Time: O(n) # Space: O(1) # Two pointers solution class Solution(object): def numSubarraysWithSum(self, A, S): """ :type A: List[int] :type S: int :rtype: int """ result = 0 left, right, sum_left, sum_right = 0, 0, 0, 0 for i, a in enum...
python
from pytest import raises import pandas as pd from agape.mapping import dictify, gene2symbol class TestDictify(object): def setup_method(self): self.df = pd.DataFrame({"A": [0, 1], "B": ["x", "y"]}) self.key = "A" self.value = "B" def test_returns_dict(...
python
from . import api from . import core from .core import Stream, NameSpace, DataFeed
python
############################################################################## # Copyright by The HDF Group. # # All rights reserved. # # # # Th...
python
"""Test Refiners can be constructed with various configurations""" import os from copy import deepcopy import pytest from dxtbx.model.experiment_list import ExperimentListFactory from libtbx import phil from dials.algorithms.refinement import DialsRefineConfigError, RefinerFactory from dials.algorithms.refinement....
python