content
stringlengths
5
1.05M
from numba.core.decorators import njit import numpy as np import numba as nb from .core import Signal, signal from .oscillators import Sin # NOQA @njit([ nb.types.Tuple((nb.float32, nb.float32))( nb.int64, nb.float32, nb.float32, nb.float32[:], nb.float32[:], nb.float32[:] ) ]) def first_order_low_p...
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #733. Flood Fill #An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). #Given a c...
from pytrek.gui.gamepieces.base.BaseMiss import BaseMiss class KlingonTorpedoMiss(BaseMiss): FILENAME: str = "KlingonTorpedoMiss.png" def __init__(self, placedTime: float): super().__init__(fileName=KlingonTorpedoMiss.FILENAME, placedTime=placedTime)
import numpy as np from scipy import linalg from hmmlearn.hmm import GaussianHMM from hmmlearn.base import ConvergenceMonitor from sklearn.utils import check_array from hmmlearn.utils import iter_from_X_lengths ################################################################################################### # Classe...
import cv2 import os, glob from os import listdir, makedirs from os.path import isfile, join path_p = input("Current path: ") dstpath_p = input("Destination path: ") path = r"{}".format(path_p) # Source Folder dstpath = r"{}".format(dstpath_p) # Destination Folder try: makedirs(dstpath) except Exception a...
import os import numpy as np import stempeg class Track(object): """ Generic audio Track that can be wav or stem file Attributes ---------- name : str Track name path : str Absolute path of mixture audio file stem_id : int stem/substream ID is_wav : boolean ...
import re from typing import List, Dict import argparse from pathlib import Path from pycparser import CParser, c_ast from autopxd import AutoPxd # List the includes to the stdlib we are expecting. This is needed to hack # around them given they are needed for pycparser, but should endup in the pxd # as `from libc.st...
from .core import * try: from .item import * from .keychain import * from .settings import * from .mail import * from alp.request.request import * except ImportError: pass try: from .notification import * except ImportError: pass
import math import os import hashlib from datetime import datetime from typing import List, Dict, Optional from bcoding import bencode, bdecode from dumper import dump class Torrent(): def __init__(self, torrent_file: str): self.torrent_file = torrent_file self.metainfo = self.decode_file() ...
from dataclasses import dataclass from typing import TypeVar, Optional, Dict, Any from dbt.adapters.base.column import Column Self = TypeVar('Self', bound='TiDBColumn') @dataclass class TiDBColumn(Column): table_database: Optional[str] = None table_schema: Optional[str] = None table_name: Optional[str] ...
import os import sys from pykit import fsutil fn = sys.argv[1] fsutil.makedirs(fn) stat = os.stat(fn) os.write(1, '{uid},{gid}'.format(uid=stat.st_uid, gid=stat.st_gid))
a = float(input()) if a % 10 == 5: print("YES")
from .processing import process_documents, process_results, batch_items from .elastic import elastic_to_search_results from .verification import check_duplicate_documents, check_document_types
from setuptools import setup setup( name='rextester_py', version='0.0.2', url='https://github.com/ProgrammingError/rextester_py', license='MIT', author='nitanmarcel', author_email='nitan.marcel@gmail.com', description='Simple Python interface for rextester.com, using aiohttp/requests', ...
import pandas as pd import requests from geopy.geocoders import Nominatim from geopy.extra.rate_limiter import RateLimiter from tqdm import tqdm import geopandas as gpd from shapely.geometry import Polygon, MultiPolygon import os geog_file = 'Assessor_Historical_Secured_Property_Tax_Rolls.csv' asr_file = 'assessor_200...
"""All the classes used as parameters for the decorators.""" from aws_lambda_decorators.decoders import decode from aws_lambda_decorators.utils import is_valid_variable_name PATH_DIVIDER = "/" ANNOTATIONS_START = "[" ANNOTATIONS_END = "]" class ExceptionHandler: """Class mapping a friendly error message to a giv...
import networkx as nx import numpy as np from sklearn.model_selection import KFold, StratifiedKFold import copy import random def write_edgelist(G, path, delimiter=',', write_extra=False, shuffle=True): lines = [] fp = path if type(path) == type('str'): fp = open(path, 'w') for (u, v, d) in G...
#!/usr/bin/python import os from setuptools import find_packages, setup setup(use_scm_version=True,)
# -*- coding: utf-8 -*- from aloe import step from aloe import world from ..stepslib import upper_half_frequency_axis from ..stepslib import complete_frequency_axis import numpy @step('TimeAxis is created from FrequencyAxis') def ta_from_fa(self): wa = world.wa world.ta = wa.get_TimeAxis() @step(...
# -*- coding: utf-8 -*- # All GPIO pins below are BCM PWM_TO_PIN = { # map between PCB labels and GPIO pins 1: 6, 2: 13, # hardware PWM1 available 3: 16, 4: 12, # hardware PWM0 available 5: 18, } # led and button GPIO pins PCB_LED_PIN = 23 PCB_BUTTON_PIN = 24 # hall sensor HALL_SENSOR_PIN ...
import api import m3u8 from user import User class VideoSegment: def __init__(self, segment, muted_segments): self.id = int(segment.uri.replace(".ts", "").replace("-unmuted", "")) self.uri_base = segment.base_uri self.uri_name = segment.uri if self.id in muted_segments: ...
import vficredit.equations as eq import numpy as np def test_MPL(): assert eq.MPL(1.,1.,1.,1.) == 0. assert eq.MPL(1.,1.,1.,0.) == 1. assert eq.MPL(0.,1.,1.,1.) == 0. assert eq.MPL(0.,1.,1.,0.) == 0. assert eq.MPL(0.5,1.,1.,0.5) == 0.25 assert eq.MPL(0.5,1.,1.,0) == 0.5 def test_MPK(): ...
import json from tqdm import tqdm import jsonlines import json from nltk.tokenize import sent_tokenize # from KILT.kilt.knowledge_source import KnowledgeSource from collections import defaultdict import random def chunks(l, n): n = max(1, n) return [l[i:i+n] for i in range(0, len(l), n)] def preproc(split): ...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.decorators import login_required from .models import Posts, Category, Comment from .forms import PostForm, CommentForm from django.urls import reverse # Create your views here. @login_required def h...
(InteractiveConsole) >>> from osoba.models import MilitaryRank, Platoon, ServiseID, Unit >>> image_path = 'D:\downloads\photo_2021-02-13_10-45-02.jpg' >>> with open(image_path,'rb') as image_file: ... image_string = image_file.read() ... sid = ServiseID.objects.create(image3x4=image_string, name='proba', sename =...
from copy import deepcopy from .cpx import cpx class Poly: # takes in dictionary of {power : coefficient} def __init__(self, d: dict = None): if d: self.d = d self.leading_c = max(d.keys()) else: self.d = {} self.leading_c = 0 # create Poly from leading term and list of roots # not sure if there i...
# USAGE # python demo.py --base-model $CAFFE_ROOT/models/bvlc_googlenet \ # --image initial_images/fear_and_loathing/fal_01.jpg \ # --output examples/simple_fal.jpg # import the necessary packages from batcountry import BatCountry from PIL import Image import numpy as np import argparse # construct the argument parse...
import pandas as pd import random #-------------------------read the dataset----------------------------- data = pd.read_csv('Salary_Data.csv') print("\nReading the dataset \n") print(data) #------------------------counting the rows and colums-------------------------- rows = len(data.axes[0]) cols = len(data.axes[1]...
# Generated by Django 3.1.7 on 2021-03-29 12:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('venues', '0004_auto_20210329_1038'), ] operations = [ migrations.AlterModelOptions( name='vmanager', options={'ordering': ['...
# -*- coding: utf-8 -*- """ Created on Wed Nov 11 16:47:03 2015 @brief: Create sample sheet from TCGA metadata.json for Genomon. @author: okada $Id: create_samplesheet.py 127 2016-01-22 02:17:18Z aokada $ $Rev: 127 $ @code create_samplesheet.py {TCGA metadata.json} {path to bam dir} {path to output_sample.csv} --ch...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Dict, List import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, cat, get_norm from detectron2.structu...
import pandas as pd from sklearn.model_selection import train_test_split TEST_SIZE = 0.05 MAX_LEN = 1000 train_de = open('./data/train.de', encoding='utf-8').read().split('\n') train_en = open('./data/train.en', encoding='utf-8').read().split('\n') dev_de = open('./data/dev.de', encoding='utf-8').read().split('\n')...
from flask import Flask app = Flask(__name__) @app.route('/routers/<hostname>') def router(hostname): return 'You are at %s' % hostname @app.route('/routers/<hostname>/interface/<int:interface_number>') def interface(hostname, interface_number): return 'You are at %s interface %d' % (hostname, interface_numbe...
#!/usr/bin/python ''' (C) Copyright 2019 Intel 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 ...
# Imports import cv2 import numpy as np import matplotlib.pyplot as plt # Step 1) Load image img = cv2.imread("./Data/test_img.jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Step 2) Gray Scale gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) gray_img = cv2.dilate(gray_img, kernel=np.ones((5, 5), np.uint8)) # Ste...
def {0}(*args): '''{1}''' if len(args) == 1: return _dispatcher.ic_function_objarg('{2}{0}', args[0]) return _dispatcher.ic_function_varargs('{2}{0}', args)
import iseg.types as T from ._intersect_and_union import _intersect_and_union def iou( segmap_list: T.List[T.Array], mask_list: T.List[T.Array], num_classes: int, ignore_index: int ) -> T.Dict[str, float]: """ Compute the IoU over all predictions and masks in validataion or test dataset. Args: ...
__author__ = 'yinjun' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head: the list # @param k: rotate to the right k places # @return: the list after rotation def rotateRight(self, head, k)...
import shutil def clean(): print("Performing clean...") print('Removing "doc" directory...') shutil.rmtree("./doc") print("Clean done.")
import socket from asyncio import (gather, get_event_loop, open_connection, start_server) from ipaddress import ip_address from struct import calcsize, pack, unpack from ._util import log # __all__ = ['Socks5'] # class Socks5: """ Socks5 proxy class """ NO_ADDR = '0.0.0.0' ATYP_IPv...
# -*- coding: utf-8 -*- # # Copyright 2020 Chris Myers # # 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 ...
''' .1111... | Title: ophcrack .10000000000011. .. | Author: Oliver Morton .00 000... | Email: grimhacker@grimhacker.com 1 01.. | Description: .. | runs ophcrack as a subprocess, parsing stdout. .. | does not return c...
""" Serialization tools =================== Contains multipurpose utilities for serializing objects. .. Copyright: Copyright 2019 Wirepas Ltd licensed under Apache License, Version 2.0 See file LICENSE for full license details. """ import json import datetime import binascii def ser...
# Given an array containing None values fill in the None values with most recent # non None value in the array from random import random def generate_sample(n): rand = 0.9 while n: yield int(rand * 10) if rand % 1 > 1 / 3 else None rand = random() n -= 1 def fill1(array): for i i...
from itertools import chain, count from collections import defaultdict from otf2.events import Enter, Leave, ThreadTaskCreate """ Contains assorted helper functions for __main__.py and trace.py """ def attr_getter(attr_lookup): """Make a function to lookup an attribute of some event by its name""" def event_...
# Name: Liu Eng Ann Joseph # Email: kelpabc123@gmail.com # Filename: course.py # File: Contains class definitions for a course object, contains the structure required # to be potentially extended to a database import csv # Course object stores the information associated with a course class MyCourse: #######...
""" Tests for openedx.core.djangolib.translation_utils """ import unittest import datetime import ddt from openedx.core.djangolib.translation_utils import translate_date @ddt.ddt class TranslateDateTest(unittest.TestCase): """Test that we can convert the date object into a string with translation.""" @dd...
from typing import List def pad_sequences( chunk_size: int, subfam_seqs: List[str], chrom_seqs: List[str], padding_char: str = ".", ) -> None: """ Right-pad sequences with `(chunk_size - 1) / 2` copies of ".". The first sequence is ignored since that is the skip state. The `padding_c...
from django.urls import path, include from rest_framework.routers import DefaultRouter from core.views.demo_schemas import ListDemos router = DefaultRouter() router.register('tags', ListDemos) app_name = 'core' urlpatterns = [ path('', include(router.urls)) ]
from datetime import datetime, timedelta, timezone from unittest.mock import patch import asf_search import pytest import process_new_granules def test_get_unprocessed_granules(tables): items = [ { 'job_id': 'job1', 'request_time': '2021-01-01T00:00:00+00:00', 'user_i...
# Copyright 2014 Confluent 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, s...
import torch.nn as nn import torch import math import torch.utils.model_zoo as model_zoo import torch.nn.functional as F from torch.nn.modules.conv import _ConvNd from torch.nn.modules.utils import _ntuple from collections import OrderedDict import operator from itertools import islice from modules.networks.dsbn impo...
from numpy.testing import assert_allclose import bokeh.driving as driving def _collector(results): def foo(val): results.append(val) return foo w = 0.3 A = 3 phi = 0.1 offset = 2 def test_sine_sequence_values(): results = [] func = driving.sine(w, A, phi, offset)(_collector(results)) for...
import pytest from bs4 import BeautifulSoup from django.urls import reverse from caseworker.advice.services import FCDO_CASES_TO_REVIEW_QUEUE, FCDO_TEAM from core import client @pytest.fixture(autouse=True) def setup(mock_queue, mock_denial_reasons, mock_case): yield @pytest.fixture def url(data_queue, data_s...
import configparser import os import unittest from TM1py.Objects import User from TM1py.Services import TM1Service from TM1py.Utils.Utils import CaseAndSpaceInsensitiveSet config = configparser.ConfigParser() config.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini')) PREFIX = "TM1py_Tests_" ...
import asyncio import logging from json import JSONEncoder from typing import List, Any from aiohttp import TCPConnector, ClientSession from .executor import AsyncioProgressbarQueueExecutor, AsyncioSimpleExecutor class InputData: def __init__(self, value: str): self.value = value def __str__(self):...
from tensorflow import keras from tensorflow.keras.datasets import mnist from tensorflow.keras.layers import BatchNormalization, Dense, Flatten,\ LeakyReLU, Reshape from tensorflow.keras.models import Model, Sequential from tensorflow.keras.optimizers import Adam import matplotlib.pyplot as plt import numpy as np ...
from dataclasses import dataclass from datetime import datetime from typing import Dict, List, Literal DIFFERENCE = "difference" @dataclass class RatingMetric: name: str against: str = None prediction: Literal["difference", "sum"] = "difference" @dataclass class Rating: entity_id: int team_id: ...
import numpy as np from numpy import array import pandas as pd from keras.preprocessing import text, sequence from keras.preprocessing.text import Tokenizer from keras.utils import to_categorical from keras.models import Model, Input from keras.layers import LSTM, Embedding, Dense, TimeDistributed, Bidirectional, GRU,...
import numpy as np #get get these working with numpy functions #https://stackoverflow.com/questions/43493256/python-how-to-implement-a-custom-class-compatible-with-numpy-functions class vec: def __init__(self): pass @property def _fields_(self): return [(__memeber_name__, self.__member_type__) for __member_t...
from typing import ( Callable, Any, Union, Dict, Tuple, Set, List, ) from dearpygui import dearpygui from dearpypixl.components import * ################################################## ####### NOTE: This file is auto-generated. ####### ################################################## ...
from time import sleep from math import fabs def contador(a, b, c): cont = list() cont.append(a) if c == 0: c = 1 if c < 0: c = int(fabs(c)) if a < b: while cont[-1] < b: # c Positivo item = cont[-1] + c if item <= b: cont.append(ite...
from rest_framework import serializers from .models import data class dataSerializer (serializers.ModelSerializer): class Meta: model = data fields = '__all__'
# Generated by Django 2.1.7 on 2019-05-29 12:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('custom_models', '0003_auto_20190528_1156'), ] operations = [ migrations.AlterField( model_name='itemtext', name='tex...
def get_access_key(): return "" def get_secret_key(): return "" def get_bucket_name(): return "NARAuatstorage"
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import editor.jsonfield class Migration(migrations.Migration): dependencies = [ ('editor', '0023_merge'), ] operations = [ migrations.AddField( model_name='customparttype...
# Copyright 2015 gRPC authors. # # 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...
""" Tests for configular """ import os import pytest from configular import Configular from configular import ParameterNotFoundException CONFIG_FILE = 'tests/resources/config_file.cfg' OVERRIDE_FILE = 'tests/resources/override_file.cfg' @pytest.fixture def config(): return Configular(CONFIG_FILE, override_fi...
""" Module to present a base neuroimaging scan, currently T1 mri, without any overlay. """ import argparse import subprocess import sys import textwrap import traceback import warnings from abc import ABC from os import makedirs from subprocess import check_output import matplotlib.image as mpimg import numpy as np...
""" sentry.plugins.base.structs ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function __all__ = ['ReleaseHook'] from django.utils import timezone from sentry.mod...
# -*- coding: utf-8 -*- # # Copyright (C) 2021 CERN. # Copyright (C) 2021 TU Wien. # # Invenio-Requests is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see LICENSE file for more # details. """Component for creating request numbers.""" from invenio_records_resources.ser...
import unittest2 from ..statement_header_parser import StatementHeaderParser from ..statement import Statement from ..utils import to_long_date # flake8: noqa statement_header = """ Raiffeisenbank a.s. Bank statement No. 8 For period 01.08.2016/31.08.2016 Name of account: Test McTestman Account number: 2000145399...
import boto3 from botocore.exceptions import ClientError from .. import compressor from .. import logging logger = logging.getFormattedLogger() s3 = boto3.resource('s3') s3_client = boto3.client('s3') def path_exists(bucket, object): """Check that s3 bucket and key exist""" try: obj = list(s3.Bucket...
# Copyright 2015 Google Inc. 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 law or ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2017-03-16 15:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ADFS', '0001_initial'), ] operations = [ migrations.AlterField( ...
import random random.seed() print(random.random()) print(random.uniform(0,10)) print(random.triangular(0,10,5)) print(random.betavariate(.1,.5)) print(random.expovariate(100)) print(random.gammavariate(1,2)) print(random.gauss(1,2)) print(random.lognormvariate(1,2)) print(random.vonmisesvariate(1,2)) print(random.paret...
# Copyright 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. """ Store Metadata relating to which spatial locations are active at each scale. Convolutions, submanifold convolutions and...
# ============================================================================== # Copyright 2018-2020 Intel 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://ww...
# -*- coding:utf-8 -*- """ @file name : lesson-02.py @author : Jianhua Ma @date : 2021-03-28 @brief : create tensor """ import torch import numpy as np # Sets the seed for generating random numbers. Returns a torch.Generator torch.manual_seed(1) cuda_available = torch.cuda.is_available() # Example 1...
# Generated by Django 3.1.2 on 2020-10-17 16:05 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Contacts', fields=[ ('id', ...
import click from create_github_project.utils import Accounts @click.command(help='Drop GitHub account under managements.') @click.argument('account_id', type=str) def drop(account_id: str) -> None: """ツール管理下にある GitHub アカウントを管理から外す。 Args: account_id (str): GitHub アカウント ID """ accounts = Acco...
import networkx as nx import matplotlib.pyplot as plt import time def filter_price_change(G, threshold): unsignificant_nodes = [] for name in G: if G.node[name]['type'] == 'Company' and G.node[name]['price_change'] >= threshold: G.node[name]['label'] += ' : ' + str(G.node[name]['price_chan...
cities = [ 'Warsaw', 'Lodz', 'Krakow', 'Wroclaw', 'Poznan', 'Gdansk', 'Szczecin', 'Bydgoszcz', 'Lublin', 'Katowice', 'Bialystok', 'Gdynia', 'Czestochowa', 'Sosnowiec', 'Radom', 'Mokotow', 'Torun', 'Kielce', 'Gliwice', 'Zabrze', 'Bytom',...
#!/usr/bin/python # coding=utf-8 """ 第 0020 题: 登陆中国联通网上营业厅 后选择「自助服务」 --> 「详单查询」,然后选择你要查询的时间段, 点击「查询」按钮,查询结果页面的最下方,点击「导出」,就会生成类似于 2014年10月01日~2014年10月31日 通话详单.xls 文件。写代码,对每月通话时间做个统计。 """ import xlrd def count_the_dail_time(filename): excel = xlrd.open_workbook(filename) sheet = excel.sheet_by_index(0) row...
#!/usr/bin/python import random def insertion_recursive(AA, n): # exit condition if (n == 0): return # divide insertion_recursive(AA, n-1) # merge key = AA[n] idx = n-1 while (idx >=0 and key < AA[idx]): AA[idx+1] = AA[idx] idx -= 1 AA[idx+1] = key RANGE=10 AA = [random.randint(1, ...
import os from PIL import Image import numpy as np import torchvision from datasets import base from datasets import tinyimagenet from platforms.platform import get_platform class Dataset(tinyimagenet.Dataset): @staticmethod def _augment_transforms(): return [ torchvision.transforms.Random...
from __future__ import unicode_literals from django.db import models from django.contrib.sites.models import Site from fontawesome.fields import IconField from photologue.models import Photo class Service(models.Model): slug = models.CharField(max_length=512, blank=True, null=True) title = models.CharField(m...
from floodsystem.station import * from floodsystem.stationdata import * from floodsystem.stationdata import build_station_list stations= build_station_list() def run(): """Requirements for Task 1F""" list_of_inconsistent_stations = inconsistent_typical_range_stations(stations) #sort the list alphabetical...
from pyVmomi import vim from pyVim.connect import SmartConnect, Disconnect import time def _get_obj(content, vimtype, name): """ Get the vsphere object associated with a given text name """ obj = None container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True) ...
# -*- coding: utf-8 -*- import os from ohmyrss.settings import CRAWL_FLAG_DIR import time import urllib import hashlib def mkdir(directory): return os.makedirs(directory, exist_ok=True) def get_hash_name(s): return hashlib.md5(s.encode('utf8')).hexdigest() def is_crawled_url(url): url_hash = get_hash...
from os import listdir from os.path import isfile, join import json onlyfiles = [f for f in listdir('../img/2017') if isfile(join('../img/2017', f))] img_list = [] for file in onlyfiles: temp = dict([('src', './img/2017/' + file), ('w', 1382), ('h', 1036)]) img_list.append(temp) # print(json.dumps(img_list)) # ...
import spacy from scispacy.linking import EntityLinker print("Installing ScispaCy ontologies. Please wait...") nlp = spacy.load("en_core_sci_sm") config = dict() config["linker_name"] = "umls" config["resolve_abbreviations"] = True nlp.add_pipe("scispacy_linker", config=config) linker = nlp.get_pipe("scispacy_linker...
import glob import os.path as osp dir_path="/home/huangju/dataset/dml_ped12" img_paths = glob.glob(osp.join(dir_path, '*/*/*.jpg')) #print(len(img_paths)) count=0 for img_path in img_paths: #print(img_path.split('/')[-1].split("_")[-1]) if img_path.split('/')[-1].split('.')[0].split("_")[-1]=="face": c...
import pickle as pickle import torch from collections import OrderedDict, defaultdict from multiprocessing import Process import random import json from netquery.data_utils import parallel_sample, load_queries_by_type, sample_clean_test from netquery.graph import Graph, Query, _reverse_edge def load_graph(data_dir, e...
from django.contrib import admin from . import models class UserAdmin(admin.ModelAdmin): list_display=('id', 'first_name', 'last_name', 'username', 'last_login',) class LyricsAdmin(admin.ModelAdmin): list_display=('id', 'artist', 'title') prepopulated_fields = {"title_slug": ("title",), "artist_slug": ("ar...
# -*- coding: utf-8 -*- """ DO NOT EDIT THIS FILE WITHOUT CONSULTING WITH ME @revision: 0 + inputs + Problem @author: etodorov @date: 14 Feb 16 @revision: 1 + Solver @author: etodorov @date: 14 Feb 16 @revision: 2 + TestProblem @author: etodorov @date: 15 Feb 16 """ from __future__ import division import os #inputs...
''' Utilties module ''' from .progressbar import MultiCKMeansProgressBars from .plotting import ( plot_ckmeans_result, plot_multickmeans_metrics, plot_wecr_result, plot_wecr_result_metrics, plot_cmatrix, )
# mypy: allow-any-expr # mypy: allow-any-explicit # mypy: allow-any-generics """ Simple json serialization and de-serialization tool. """ from typing import Any, Dict, Union, Sequence, List, Tuple, Iterable, Mapping import json import importlib from ...errors import ( PetroniaValueNotSerializable, PetroniaSe...
# -*- coding:utf-8 -*- """ rotation functions script """ import numpy as np from math import cos from math import sin class Rotation(object): def __init__(self): pass @staticmethod def euler2dcm(pitch, yaw, roll): """ calculate right hand dcm with euler angle by order xyz ...
""" Compute time to first fixation, dwell time, number of fixations and number of re-entering (each with respect to the ROI of the respective scene) for a subject """ import pandas as pd from argparse import ArgumentParser from config import fname, subjects, blocks, display_resolution, image_size from helpers import...