content
stringlengths
0
894k
type
stringclasses
2 values
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-10-28 13:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('ems', '0023_auto_20171028_0756'), ('registrations',...
python
VO = "https://www.vote.org" VA = "https://www.voteamerica.com" CODE = 'code' REG = 'reg' POLLS = 'polls' CITIES = 'cities' # XXX This should move to campaign.Campaign but it's disruptive ABS = 'abs' REGDL = 'regdl' ABROAD = 'abroad' class States: ALABAMA = 'Alabama' ALASKA = 'Alaska' ARIZONA = 'Arizona' ARKANSAS...
python
from azure.mgmt.keyvault import KeyVaultManagementClient from azure.keyvault import KeyVaultClient from common_util import CommonUtil from credentials.credentials_provider import ResourceCredentialsProvider import logging as log from azure.mgmt.keyvault.v2016_10_01.models import AccessPolicyUpdateKind, VaultAccessPolic...
python
import numpy as np from numpy.linalg import norm from MeshFEM import sparse_matrices def preamble(obj, xeval, perturb, etype, fixedVars = []): if (xeval is None): xeval = obj.getVars() if (perturb is None): perturb = np.random.uniform(low=-1,high=1, size=obj.numVars()) if (etype is None): etype = obj._...
python
from functools import partial from importlib import import_module from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.crypto import get_random_string generate_random_string = partial( get_random_string, length=50, allowed_chars='abcdefghijklmnopqrstu...
python
from setuptools import setup from os import path # Read the contents of the README file cwd = path.abspath(path.dirname(__file__)) with open(path.join(cwd, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name="pysvglib", version="0.3.2", description="SVG drawing library", ...
python
from argparse import ArgumentParser import numpy as np import py360convert import os import cv2 import os.path as osp from typing import Union from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot, ret_result from mmseg.core.evaluation import get_palette from PIL import Image import mmcv fro...
python
import json import requests import logging import hashlib import time from fake_useragent import UserAgent from uuid import uuid4 from .camera import EzvizCamera # from pyezviz.camera import EzvizCamera COOKIE_NAME = "sessionId" CAMERA_DEVICE_CATEGORY = "IPC" API_BASE_URI = "https://apiieu.ezvizlife.com" API_ENDPOINT...
python
# coding: utf-8 import os import sh import logging import shutil import tempfile from unittest import TestCase from nose.tools import nottest class UncanningTest(TestCase): """ Let's try to uncan a new project and run tests to see everything is ok Estimated running time 260s""" def setUp(self): ...
python
""" Solution to https://adventofcode.com/2018/day/4 """ from pathlib import Path # path from the root of the project INPUT_FILE = Path.cwd() / "2018" / "dec4.txt" def part1() -> int: sorted_lines = sorted(line for line in INPUT_FILE.read_text().split("\n") if line) if __name__ == "__main__": print(part1())...
python
# -*- coding: utf-8 -*- from numpy import cos, exp, sin from ....Classes.Arc1 import Arc1 from ....Classes.Segment import Segment from ....Classes.SurfLine import SurfLine def build_geometry(self, alpha=0, delta=0, is_simplified=False): """Compute the curve (Segment) needed to plot the Hole. The ending poin...
python
import pydantic import os import yaml import re import typing @pydantic.dataclasses.dataclass(frozen=True, order=True) class RegexTestCase: text: pydantic.constr() matches: typing.Optional[typing.List[str]] = None def run(self, regex): """ evaluate the test case against the pattern """ ac...
python
#!/usr/bin/env python3 __author__ = "Leon Wetzel" __copyright__ = "Copyright 2021, Leon Wetzel" __credits__ = ["Leon Wetzel"] __license__ = "MIT" __version__ = "1.0.1" __maintainer__ = "Leon Wetzel" __email__ = "post@leonwetzel.nl" __status__ = "Production" import praw from nltk import sent_tokenize def main(): ...
python
# coding: utf-8 # # Download TCGA Pan-Cancer Datasets from the UCSC Xena Browser # # This notebook downloads TCGA datasets for Project Cognoma. The file contents (text) remains unmodified, but files are given extensions and bzip2 compressed. # # [See here](https://genome-cancer.soe.ucsc.edu/proj/site/xena/datapages...
python
def palindromeRearranging(inputString): characters = {} error_count = 0 for character in inputString: if character not in characters: characters[character] = 1 else: characters[character] += 1 print(characters.values()) for value in characters.values(...
python
from .mock_plugin import MockPlugin __all__ = ['mock_plugin']
python
# encoding: utf-8 import os.path as osp from .bases import BaseImageDataset class target_test(BaseImageDataset): """ target_training: only constains camera ID, no class ID information Dataset statistics: """ dataset_dir = 'target_test' def __init__(self, root='./example/data/challenge_data...
python
#!/usr/bin/python from bs4 import BeautifulSoup import urllib2 import csv import codecs linksList = [] #f = csv.writer(open("worksURI.csv", "w")) #f.writerow(["Name", "Link"]) f = codecs.open("alllinkstrial.txt", encoding='utf-8', mode='w+') #'http://www.isfdb.org/cgi-bin/ea.cgi?12578 ', target_url=['ht...
python
# -*- coding: utf-8 -*- """ Created on Mon Dec 16 21:11:25 2019 @author: Jorge """ import tkinter as tk from tkinter import ttk import crearcapasconv from threading import Thread import sys from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from matplotlib.figure impor...
python
#!/usr/bin/env python import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt plt.style.use('classic') fig = plt.figure() population_age = [22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,111,115,80,75,65,54,44,43,42,48] bins = [0,10,20,30,40,50,60,70,80,90,100] plt.hist(population_age,...
python
# ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache #...
python
from django.shortcuts import render,redirect from django.contrib.auth.models import User from .models import Project,Profile from .forms import ProjectForm,ProfileForm,VoteForm from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from rest_framework.response im...
python
from torchvision import datasets, transforms def imagenet_transformer(): transform=transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.2...
python
import base64 import json import logging from io import BytesIO from urllib.parse import urljoin import feedparser from flask_babel import lazy_gettext as _ from PIL import Image from authentication_document import AuthenticationDocument from model import Hyperlink from opds import OPDSCatalog from problem_details im...
python
#!/usr/bin/env python # Copyright 2005-2009,2011 Joe Wreschnig # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. import glob import os import shutil import sys import subprocess from...
python
# -*- coding: utf-8 -*- # :Project: pglast -- DO NOT EDIT: automatically extracted from pg_trigger.h @ 13-2.0.6-0-ga248206 # :Author: Lele Gaifax <lele@metapensiero.it> # :License: GNU General Public License version 3 or later # :Copyright: © 2017-2021 Lele Gaifax # from enum import Enum, IntEnum, IntFlag, auto...
python
import ops import ops.cmd import ops.env import ops.cmd.safetychecks VALID_OPTIONS = ['all', 'permanent', 'cached'] class PasswordDumpCommand(ops.cmd.DszCommand, ): def __init__(self, plugin='passworddump', **optdict): ops.cmd.DszCommand.__init__(self, plugin, **optdict) def validateInput(self): ...
python
"""An App Template based on Bootstrap with a header, sidebar and main section""" import pathlib import awesome_panel.express as pnx import panel as pn from awesome_panel.express.assets import SCROLLBAR_PANEL_EXPRESS_CSS BOOTSTRAP_DASHBOARD_CSS = pathlib.Path(__file__).parent / "bootstrap_dashboard.css" BOOTST...
python
import codecs import json import matplotlib.pyplot as plt import numpy as np import os import itertools def plot_confusion_matrix(cm, target_names, title='Confusion matrix', prefix="", cmap=None, ...
python
class DataFilePath: def __init__(self): self.dataDir = '../data/citydata/season_1/' return def getOrderDir_Train(self): return self.dataDir + 'training_data/order_data/' def getOrderDir_Test1(self): return self.dataDir + 'test_set_1/order_data/' def getTest1Dir(self)...
python
from __future__ import print_function import argparse import logging import os import warnings import torch.nn as nn import torch.utils.data from torch.utils.data import SubsetRandomSampler from torch.utils.tensorboard import SummaryWriter from Colorization import utils from Multi_label_classification.dataset.datase...
python
from django.shortcuts import render from django.http import Http404 from django.views.generic.edit import UpdateView from django.views.generic import ListView, View from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.utils.decorators import method_decorator...
python
from src.traces.traces import main as traces_main import pandas as pd def main(): db_path = '/Users/mossad/personal_projects/AL-public/src/crawler/crawled_kaggle.db' traces_path = '/Users/mossad/personal_projects/AL-public/src/traces/extracted-traces.pkl' clean_traces_path = '/Users/mossad/personal_project...
python
# -*- coding: UTF-8 -*- # Copyright 2012-2017 Luc Saffre # # License: BSD (see file COPYING for details) """Defines the :class:`Page` model. """ from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.translation import pgettext_lazy from django.utils.translation import...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from annotator import annotation from annotator import document from h._compat import text_type class Annotation(annotation.Annotation): @property def uri(self): """Return this annotation's URI or an empty string. The uri is es...
python
import os import string from file2quiz import utils, reader def convert_quiz(input_dir, output_dir, file_format, save_files=False, *args, **kwargs): print(f'##############################################################') print(f'### QUIZ CONVERTER') print(f'##############################################...
python
# Copyright (c) 2021 by xfangfang. All Rights Reserved. # # Using potplayer as DLNA media renderer # # Macast Metadata # <macast.title>PotPlayer Renderer</macast.title> # <macast.renderer>PotplayerRenderer</macast.title> # <macast.platform>win32</macast.title> # <macast.version>0.4</macast.version> # <macast.host_versi...
python
import numpy as np from metod_alg import objective_functions as mt_obj from metod_alg import metod_algorithm_functions as mt_alg def test_1(): """ Test for mt_alg.forward_tracking() - check that when flag=True, track is updated. """ np.random.seed(90) f = mt_obj.several_quad_function g = ...
python
# -*- coding: utf-8 -*- # Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause from __future__ import absolute_import, division, print_function, unicode_literals from logging import getLogger import os import sys from .main import main as main_main from .. import CondaError from .._vendor.auxlib.i...
python
with open('input') as fp: grid = [line[:-1] for line in fp] grid_width = len(grid[-1]) x, y = (0, 0) n_trees = 0 while y < len(grid): if grid[y][x % grid_width] == '#': n_trees += 1 x += 3 y += 1 print(n_trees, "trees")
python
from __future__ import absolute_import import sys, os from subprocess import Popen, PIPE, check_output import socket from ..seqToolManager import seqToolManager, FeatureComputerException from .windowHHblits import WindowHHblits from utils import myMakeDir, tryToRemove #utils is at the root of the package class HHBlit...
python
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: # edge cases - if the element is present at start or last if not head: ...
python
# Export individual functions # Copy from .scopy import scopy from .dcopy import dcopy from .ccopy import ccopy from .zcopy import zcopy # Swap from .sswap import sswap from .dswap import dswap from .cswap import cswap from .zswap import zswap # Scaling from .sscal import sscal from .dscal import dscal from .cscal i...
python
import torch import trtorch precision = 'fp16' ssd_model = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_ssd', model_math=precision) input_shapes = [1, 3, 300, 300] model = ssd_model.eval().cuda() scripted_model = torch.jit.script(model) compile_settings = { "input_shapes": [input_shapes], "...
python
# Main file for the PwnedCheck distribution. # This file retrieves the password, calls the module check_pwd, # and check if the password has been breached by checking it with # the database in the following website # https://haveibeenpwned.com/Passwords import sys import logging from getpass import getpass from checkp...
python
""" ================================ Symbolic Aggregate approXimation ================================ Binning continuous data into intervals can be seen as an approximation that reduces noise and captures the trend of a time series. The Symbolic Aggregate approXimation (SAX) algorithm bins continuous time series into...
python
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-10 01:54 from __future__ import unicode_literals import django.core.files.storage from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cxp_v1', '0001_initial'), ] operations = [ m...
python
# -*- coding: utf-8 -*- import pytest from click.testing import CliRunner from jak.app import main as jak import jak.crypto_services as cs @pytest.fixture def runner(): return CliRunner() def test_empty(runner): result = runner.invoke(jak) assert result.exit_code == 0 assert not result.exception ...
python
try: import matplotlib.pyplot as plt import fuzzycorr.prepro as pp from pathlib import Path import numpy as np import gdal except: print('ModuleNotFoundError: Missing fundamental packages (required: pathlib, numpy, gdal).') cur_dir = Path.cwd() Path(cur_dir / "rasters").mkdir(exist_ok=True) ...
python
"""Support for Vallox ventilation units.""" from __future__ import annotations from dataclasses import dataclass, field import ipaddress import logging from typing import Any, NamedTuple from uuid import UUID from vallox_websocket_api import PROFILE as VALLOX_PROFILE, Vallox from vallox_websocket_api.exceptions impor...
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 may not u...
python
import numpy as np # type: ignore import pandas as pd # type: ignore # imported ML models from scikit-learn from sklearn.model_selection import (ShuffleSplit, StratifiedShuffleSplit, # type: ignore TimeSeriesSplit, cross_val_score) # type: ignore from sklearn.discriminant_anal...
python
#!/usr/bin/env python __author__ = 'Florian Hase' #======================================================================= from DatabaseHandler.PickleWriters.db_writer import DB_Writer
python
# # @lc app=leetcode id=383 lang=python # # [383] Ransom Note # # https://leetcode.com/problems/ransom-note/description/ # # algorithms # Easy (49.29%) # Total Accepted: 107.4K # Total Submissions: 216.8K # Testcase Example: '"a"\n"b"' # # # Given an arbitrary ransom note string and another string containing lette...
python
""" Guidelines from whitehouse.gov/openingamerica/ SYMPTOMS: - Downward Trajectory of Flu-like illnesses AND - Downward Trajectory of Covid symptoms 14 day period CASES: - Downward Trajectory of documented cases within 14 day period OR - Downward Trajectory of positive tests within 14 days ...
python
from pymodm import connect, MongoModel, fields from pymodm.base.fields import MongoBaseField import pymongo from datetime import datetime as dt db_server = "mongodb+srv://AtlasUser:8dNHh2kXNijBjNuQ@cluster0.a532e" db_server += ".mongodb.net/ECGServer?retryWrites=true&w=majority" mongodb_server = connect(db_server) ...
python
from django.urls import path from account.views import ( index, profile, LOGIN, LOGOUT, REGISTER, activate, change_password, update_profile, change_profile_pic ) from account.api import ( check_username_existing, get_users ) app_name = 'account' urlpatterns = [ # API URLs path('api/check_usern...
python
import msgpack_numpy import os import torch from collections import defaultdict from typing import List import lmdb import magnum as mn import numpy as np from torch.utils.data import Dataset from tqdm import tqdm import habitat from habitat import logger from habitat.datasets.utils import VocabDict from habitat.task...
python
from visualization import plot_binary_grid # used to show results from wrapper import multi_image # import segmenter for multiple images if __name__ == "__main__": # Apply segmenter to default test images. print("Classifying images...") masks = multi_image() # uses default test image print("Complete...
python
# from sqlalchemy package we can import Column, String, Integer, Date, Sequence from sqlalchemy import Column, String, Integer, Date, Sequence # imports Config class from config module from config import Config #exception handling using try except for FeatureRequestAppClass. try: # A class FeatureRequestApp will be...
python
from typing import List import config import datetime from email.mime.text import MIMEText from html.parser import HTMLParser import email.utils as utils import logging import queue import re import sys import threading from time import strftime import socket import feedparser import yaml from imap_wrapper import Im...
python
from flask.views import MethodView class APIView(MethodView): api_version = None path = None @classmethod def get_path(self): if self.path: return self.path elif self.__name__.endswith('View'): return self.__name__[:-4].lower() else: return ...
python
''' - Application Factory ''' from app import create_app from fastapi import FastAPI from fastapi.testclient import TestClient from pytest import fixture @fixture def client(): '''Cliente do FastAPI.''' app = create_app() return TestClient(app) def test_create_app(client): assert isinstance(create_a...
python
"""A module for evaluating policies.""" import os import json import pandas as pd import matplotlib.pyplot as plt from tf_agents.environments.tf_py_environment import TFPyEnvironment from lake_monster.environment.environment import LakeMonsterEnvironment from lake_monster.environment.variations import MultiMonsterEnvi...
python
import numpy as np from numpy import exp,dot,full,cos,sin,real,imag,power,pi,log,sqrt,roll,linspace,arange,transpose,pad,complex128 as c128, float32 as f32, float64 as f64 from numba import njit,jit,complex128 as nbc128, void import os os.environ['NUMEXPR_MAX_THREADS'] = '16' os.environ['NUMEXPR_NUM_THREADS'] = ...
python
#!/usr/bin/env python # Copyright (c) 2014 Spotify AB. # # 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 Ap...
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.backends.frame import FrameBase, FrameNode from .port import Port from .vessel import gen_vessel_definition from .matrix import gen_matrix def gen_ecr_frame(port_num: int, vessel_num: int, stop_nums: tuple, snapshots_num: int): """...
python
"""Provide functionality to handle package settings.""" import logging from enum import Enum from os import makedirs from os.path import isdir from urllib.error import URLError from urllib.parse import urlparse from urllib.request import Request, urlopen from dynaconf import Validator, settings LOGGER = logging.getLo...
python
# Copyright 2017 The Sonnet 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 applicable l...
python
#!/usr/bin/env python """ (C) 2007-2019 1024jp """ import pickle import cv2 import numpy as np import matplotlib.pyplot as plt _flags = (cv2.CALIB_ZERO_TANGENT_DIST | cv2.CALIB_FIX_K3 ) class Undistorter: def __init__(self, camera_matrix, dist_coeffs, rvecs, tvecs, image_size, ...
python
#!/usr/bin/env python names = ["Amy", "Bob", "Cathy", "David", "Eric"] for x in names: print("Hello " + x)
python
# coding: utf-8 from __future__ import unicode_literals import pytest from django.contrib.auth.models import AnonymousUser from mock import Mock from saleor.cart import decorators from saleor.cart.models import Cart from saleor.checkout.core import Checkout from saleor.discount.models import Voucher from saleor.produ...
python
#!/usr/bin/env python from re import sub from sys import argv,exit from os import path,getenv from glob import glob import argparse parser = argparse.ArgumentParser(description='make forest') parser.add_argument('--region',metavar='region',type=str,default=None) toProcess = parser.parse_args().region argv=[] import RO...
python
from tensorflow.keras import initializers from tensorflow.keras import layers from tensorflow.keras.models import Sequential def build_subnet(output_filters, bias_initializer='zeros', name=None): """构建功能子网络. Args: output_filters: int, 功能子网络输出层的神经元数量. bias_initializer: str or tf.ke...
python
from .seld import *
python
import numpy as np class UnionFind: def __init__(self, n): self.n = n self.parent = np.arange(n) self.rank = np.zeros(n, dtype=np.int32) self.csize = np.ones(n, dtype=np.int32) def find(self, u): v = u while u != self.parent[u]: u = self.parent[u] ...
python
import logging.config from .Camera import Camera import time from io import BytesIO from PIL import Image from dateutil import zoneinfo timezone = zoneinfo.get_zonefile_instance().get("Australia/Canberra") try: logging.config.fileConfig("/etc/eyepi/logging.ini") except: pass try: import picamera imp...
python
# 建立一个登录页面 from tkinter import * root = Tk() root.title("登陆页面") msg = "欢迎进入海绵宝宝系统" sseGif = PhotoImage(file="../img/hmbb1.gif") logo = Label(root,image=sseGif,text=msg, compound=BOTTOM) logo.grid(row=0,column=0,columnspan=2,padx=10,pady=10) accountL = Label(root,text="Account") accountL.grid(row=1) pwdL = Label(r...
python
from setuptools import setup setup( name='YinPortfolioManagement', author='Yiqiao Yin', version='1.0.0', description="This package uses Long Short-Term Memory (LSTM) to forecast a stock price that user enters.", packages=['YinCapital_forecast'] )
python
import analysis #Create historgram analysis.histogram() #Create scatterplot analysis.scatterplot("sepal_length","sepal_width") analysis.scatterplot("petal_length","petal_width") analysis.pair_plot() #Create summary.txt analysis.writeToAFile
python
import os from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('cron', hour=9) def scheduled_job(): os.system("python manage.py runbot") sched.start()
python
from django.db import models from i18nfield.fields import I18nCharField from pretalx.common.mixins import LogMixin from pretalx.common.urls import EventUrls class Track(LogMixin, models.Model): event = models.ForeignKey( to='event.Event', on_delete=models.PROTECT, related_name='tracks' ) name = I...
python
from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy import Column, Integer, String, Boolean, BigInteger, Text, ForeignKey, Float from sqlalchemy.orm import relationship #from sqlalchemy_views import CreateView, DropView # connection.execute("CREATE TABLE `jobs` (`clock` BIGINT(11),`j...
python
# -*- coding: UTF-8 -*- import os import sys import time import caffe import numpy as np from timer import Timer from db_helper import DBHelper import matplotlib.pyplot as plt from caffe.proto import caffe_pb2 from google.protobuf import text_format # Load LabelMap file. def get_labelmap(labelmap_path): labelmap...
python
#!/usr/bin/python # -*- coding: utf-8 -*- r""" Script to delete files that are also present on Wikimedia Commons. Do not run this script on Wikimedia Commons itself. It works based on a given array of templates defined below. Files are downloaded and compared. If the files match, it can be deleted on the source wiki...
python
#@+leo-ver=5-thin #@+node:ville.20110403115003.10348: * @file valuespace.py #@+<< docstring >> #@+node:ville.20110403115003.10349: ** << docstring >> '''Supports Leo scripting using per-Leo-outline namespaces. Commands ======== .. note:: The first four commands are a light weight option for python calculations ...
python
#Let's do some experiments to understand why to use numpy and what we can do with it. #import numpy with alias np import numpy as np import sys # one dimensional array a=np.array([1,2,3]) print(a) # two dimensional array a= np.array([(1,2,3),(4,5,6)]) print(a) #why numpy better than list.. #1)Less memory #2)faste2...
python
if '__file__' in globals(): import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import numpy as np from dezero import Variable import dezero.functions as F # im2col x1 = np.random.rand(1, 3, 7, 7) col1 = F.im2col(x1, kernel_size=5, stride=1, pad=0, to_matrix=True) print(col1.shape) ...
python
import sys import os from os.path import join as opj workspace = os.environ["WORKSPACE"] sys.path.append( opj(workspace, 'code/GeDML/src') ) import argparse import logging logging.getLogger().setLevel(logging.INFO) import torch.distributed as dist from gedml.launcher.runners.distributed_runner import Distributed...
python
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class Company(models.Model): _inherit = 'res.company' hr_presence_control_email_amount = fields.Integer(string="# emails to send") hr_presence_control_ip_list = fields.Char(...
python
#!/usr/bin/env python """ _ConfigureState_ Populate the states tables with all known states, and set the max retries for each state. Default to one retry. Create the CouchDB and associated views if needed. """ from WMCore.Database.CMSCouch import CouchServer from WMCore.DataStructs.WMObject import WMObject class ...
python
import numpy as np from numba import float32, jit from numba.np.ufunc import Vectorize from numba.core.errors import TypingError from ..support import TestCase import unittest dtype = np.float32 a = np.arange(80, dtype=dtype).reshape(8, 10) b = a.copy() c = a.copy(order='F') d = np.arange(16 * 20, dtype=dtype).resha...
python
import json import numpy as np def pack(request): data = request.get_json() furniture = data['furniture'] orientations = [] ''' Test TEST TTEESSTT ''' ################################################################## ####### Preliminary Functions ##############...
python
#!/usr/bin/env python3 # Dependencies: python3-pandas python3-plotly import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots import plotly.colors df = pd.read_csv(".perf-out/all.csv") fig = make_subplots( rows=2, cols=2, horizontal_spacing = 0.1, vertical_spacing ...
python
import json, re, pymongo, os from itemadapter import ItemAdapter from scrapy.exceptions import DropItem from unidecode import unidecode from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from datetime import date, datetime from scrapy import settings format="%d/%m/%Y" class NoticiasPipeline:...
python
from math import * from scipy.integrate import quad from scipy.integrate import dblquad from scipy import integrate from scipy import special from numpy import median from numpy import linspace from copy import deepcopy from scipy.stats import fisk "Defining the parameters for the tests" alpha = 0.05 delta = 0.002 k ...
python
from rest_framework import permissions class AnonymousPermission(permissions.BasePermission): """ Non Anonymous Users. """ message = "You are already registered. Please logout and try again." def has_permission(self, request, view): print(not request.user.is_authenticated) return n...
python
# -*- coding: UTF-8 -*- from operator import itemgetter from copy import deepcopy from pydruid.utils import aggregators from pydruid.utils import filters class TestAggregators: def test_aggregators(self): aggs = [('longsum', 'longSum'), ('doublesum', 'doubleSum'), ('min', 'min'), ('max'...
python
import os from django.templatetags.static import static from django.utils.html import format_html from django.utils.module_loading import import_string from wagtail.core import hooks from wagtail_icons.settings import BASE_PATH, SETS @hooks.register("insert_global_admin_css") def global_admin_css(): stylesheets...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Author: Ting''' import logging import traceback from argparse import ArgumentParser from datetime import date from pprint import pprint from subprocess import call import re from collections import defaultdict from os.path import join, abspath, dirname, isfile import csv...
python