content
stringlengths
5
1.05M
# Copyright 2020, 37.78 Tecnologia Ltda. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# !/usr/bin/env python # -*- coding: utf-8 -*- from nltk.corpus import stopwords # stopwords to detect language from nltk import wordpunct_tokenize # function to split up our words from sys import stdin # how else should we get our input :) def get_language_likelihood(input_text): """Return a dic...
# Bus communication SJ_DefaultBaud = 115200 SJ_DefaultPortIn = 5000 # General SJ_Timeout = 100 #in ms SJ_CommandStart = "#" SJ_CommandEnd = "\r" #actions SJ_ActionLED = "LED" SJ_BlinkLED = "BLK" SJ_BlinkLEDSTOP = "NBLK" SJ_FetchTemperature = "ATMP" #response SJ_Temperature = "RTMP" # LED colors NAVIO_LED_Blac...
#! /usr/bin/python # -*- coding: UTF-8 -*- # Copyright 2012-2019 Luiko Czub, TestLink-API-Python-client developers # # 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.ap...
import pytest import time import pathlib from src.test_1.safe_call_decorator import safe_call @pytest.fixture def temp_file_path(tmp_path) -> pathlib.Path: filename = f"{time.time()}.txt" temp_dir = tmp_path / "test_bush_imitating_functions" temp_dir.mkdir() temp_file_path = temp_dir / filename r...
# -*- coding: utf-8 -*- # Copyright 2017 Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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...
def strategy(history, memory): """ Tit for Tat, but it only defects once in a row unless its opponent defected twice in a row. """ choice = 1 num_rounds = history.shape[1] opponents_last_move = history[1, -1] if num_rounds >= 1 else 1 opponents_second_last_move = history[1, -2] if num_ro...
from mindsdb.libs.data_types.persistent_object import PersistentObject class PersistentModelMetadata(PersistentObject): _entity_name = 'model_metadata' _pkey = ['model_name'] def setup(self): self.model_name = None self.train_metadata = None self.predict_columns = None s...
"""Routines for talking to a kake-server daemon, spawning one if necessary. Routines in this module are meant to be used from dev-appserver. This module defines these routines: start_server(): spawn a kake server as a daemon, if needed server_port(): returns port the current kake server is running on get(): giv...
from random import choice import string # Standard Caesar Cipher: Maps commonly used characters to Chinese counterparts. charset1 = [i for i in string.ascii_uppercase] + [i for i in string.ascii_lowercase] + list(map(str, range(10))) + "` ~ ! @ # $ % ^ & * ( ) - = _ + [ ] \\ { } | ; ' \" , . / < > ?".split() # Set of...
# Leetcode # 145. Binary Tree Postorder Traversal # TODO Iterative Solution # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def postorderTraversal(self, root: Op...
import os import dotenv from syspath import git_root dotenv.load_dotenv(os.path.join(git_root.path, '.env')) from app.serve import * # noqa
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() cv2.imshow('image', frame) key = cv2.waitKey(1) if key != -1: break cap.release() cv2.destroyAllWindows()
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import os import sys import stat import time import pickle import traceback import redis_lock import contextlib import abc from pathlib import Path import numpy as np import ...
''' According to my expectations, the three functions in this code below should all produce the same result. I've been stunned to discover that this is not the case. ''' def test1(): for i in range(5): def call(): return i yield call def test2(): all = [] for i in range(5): def call(): retu...
# # author: L. Pezzini # e-mail : luca.pezzini@edu.unito.it # created: 19.01.2021 # copyright: 2020 KU Leuven (c) # MIT license # # # Maxwell Solver 2D-3V (Transverse Electric mode) # • Collocated grid # • General coordinates # • Energy conserving # • Mimetic operator...
from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns( '', url(r'^csw$','catalog.views.csw'), )
from pymongo import MongoClient import ConfigParser import sys # read settings file config = ConfigParser.RawConfigParser() config.read('settings.cfg') mongo_uri = config.get('create-game-catalog', 'mongo_uri') db_name = config.get('create-game-catalog', 'db_name') base_collection_name = config.get('create-game-catalo...
from django.shortcuts import render import os import requests from .models import Image from .forms import ImageForm from django.views.generic import CreateView from django.urls import reverse_lazy import geocoder g = geocoder.ip('me') def maps_view(request): """This is the function defining the map view. ""...
from twocode import utils import builtins # a custom execution, written however so it works - nests etc # an alternative to the eval cascade # one implemented as a list going on, a pointer travelling the code structure, carrying its memory? # what is there to carry - just scopes # but! whatever loop it ...
import requests from tqdm import tqdm from time import sleep import os class DataLoader(): """ This class is used to download a pre-trained neural network model from url. It stores model name and the link to a model. """ def __init__(self): # url where model is stored self.mod...
# -*- coding: utf-8 -*- import re ''' This is a library of functions and variables that are helpful to have handy when manipulating Japanese text in python. Copyright (c) 2014, Mads Sørensen Ølsgaard All rights reserved. Released under BSD3 License, see http://opensource.org/licenses/BSD-3-Clause or license.txt ...
# Parse arguments and call main function import os import json import argparse import shutil from pprint import pprint from .model import train_and_evaluate if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--data_path', help='GCS or local path to training da...
# -*- coding: utf-8 -*- ''' Created on 2017. 10. 25. @author: HyechurnJang ''' import pygics import requests from page import W3 from bootpage import BootPage from bootpage.theme import cisco bp = BootPage('/', 'BootPage', theme=cisco.Theme()) overflow = bp.category(u'오버플로우', cisco.MenuIcon('newstatu...
from model import DCGAN import tensorflow as tf from utils import * from ops import * import numpy as np from utils_extended import * import os class Sketch2Image: def __init__(self, dcgan, FLAGS): self.dcgan = dcgan self.FLAGS = FLAGS self.output_height = FLAGS.output_height self.output_width = FLAG...
from datagenerationpipeline import dataGenerationPipeline imageDirectory = "\\\\192.168.1.37\\Multimedia\\datasets\\test\\watches_categories\\1" fileType=".jpg" pipeline=dataGenerationPipeline(imageDirectory, fileType) print("[INFO]: There should be 200 images in directory 1") pipeline.rotate() #assert there are 10...
from win10toast import ToastNotifier def notify(title, description): notifier = ToastNotifier() try: notifier.show_toast(title, description) except: pass
import hashlib from collections import defaultdict passcode = 'pgflpeqp' m = hashlib.md5() m.update(passcode) loc_hash = defaultdict(list) class Node(): def __init__(self, path='', n=None, pos=None): self.next = n if n else [] self.path = path self.pos = pos def __str__(self): return str((self.path, self....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 20 17:20:19 2018 @author: dimitricoukos """ import unittest #import json from DataTreatment import Enzyme, MetaboliteCandidate class CorrectConstruction(unittest.TestCase): '''Class contains methods to verify correct construction of class...
#!/usr/bin/env python """ populate_variable_request.py Populates the PRIMAVERA-DMT VariableRequest table with details from the PRIMAVERA data request spreadsheet. Uses the Google Sheets API: https://developers.google.com/sheets/quickstart/python To load the spreadsheet at: https://docs.google.com/spreadsheets/d/1ewKk...
import json from fastapi import FastAPI from starlette.config import Config from fastapi.requests import Request from fastapi.responses import HTMLResponse, RedirectResponse from starlette.middleware.sessions import SessionMiddleware from authlib.integrations.starlette_client import OAuth, OAuthError from fastapi.stati...
""" LeetCode Problem: 345. Reverse Vowels of a String Link: https://leetcode.com/problems/reverse-vowels-of-a-string/ Language: Python Written by: Mostofa Adib Shakib Time complexity: O(n) Space Complexity: O(n) """ class Solution: def reverseVowels(self, s: str) -> str: length = len(s) # Calculate...
import numpy as np import tensorflow as tf from random import shuffle from collections import namedtuple from module import * from ops import * from utils import * from glob import glob # os.environ["CUDA_VISIBLE_DEVICES"] = os.environ['SGE_GPU'] class Classifer(object): def __init__(self, sess, args): se...
# import os import io import csv # import json import requests from datetime import datetime from bs4 import BeautifulSoup from collections import OrderedDict class SunScraper(object): """ Base class for all the scrapers """ date_format = '%m/%d/%Y' def request(self, url, payload): header = { ...
"""Methods that are used by the other packages""" from . import transform from . import util
from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from instaclone.models import Item from .models import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, item_id): cart = Cart(request) # create a new cart object pa...
"""_lazy_table.py""" from tabulate import tabulate from .artists import Console def stream(table, artist=None, n_rows=None, **kwargs): """Streams a table. kwargs are forwarded to tabulate. Examples -------- >>> import time >>> import lazy_table as lt >>> >>> def fib_table(n): ....
#!/usr/bin/env python """ Setup script for sen1_ard_gamma. Use like this for Unix: $ python setup.py install """ # Copyright 2019 Pete Bunting # # 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 a...
"""empty message Revision ID: 9b41e55422d5 Revises: e676343c29b7 Create Date: 2018-11-06 22:52:36.938834 """ # revision identifiers, used by Alembic. revision = '9b41e55422d5' down_revision = 'e676343c29b7' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): ...
from aws_cdk import ( core, aws_iam as iam, aws_lambda as _lambda, aws_sns_subscriptions as sns_subscriptions, aws_sns as sns ) class SquidLambdaConstruct(core.Construct): def __init__(self, scope: core.Construct, id: str) -> None: super().__init__(scope, id) # Create ...
# -*- coding: utf-8 -*- """ Created on Thu May 7 17:30:50 2020 @author: sopmathieu This file contains several functions to calibrate a CUSUM chart for a panel of time series subject to missing values. It includes functions to compute the control limit, in-control and out-of-control average run lengths of the char...
from typing import List class Solution: def evalRPN(self, tokens: List[str]) -> int: operators = ['+', '-', '*', '/'] self.current_pos = len(tokens) -1 def posorder(tokens): if tokens[self.current_pos] not in operators: return int(tokens[self.current_pos]) ...
from functools import reduce import operator arabic_to_roman = { 1: "I", 5: "V", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M"} roman_to_arabic = {roman: arabic for (arabic, roman) in arabic_to_roman.items()} MAX = 4999 def unfold(f, initial_state): next_item, state = f(initial_st...
""" Define actions urls that should be appeared in apps list page.This urls will be added beside explorer buttons. There are three predefined groups of users to assign them actions{ admin, logged_in, anonymous}, groups names are self explanatory. urls dict must be as follows urls_dict = { 'admin':{'<url_name>':'<la...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Author : Yee_172 @Date : 2018/05/28 """ __author__ = 'Yee_172' class Matrix(): mod = 0x3b9aca07 def __init__(self, n): self.n = n self.a = [[0] * n for _ in range(n)] def __mul__(self, b): res = Matrix(self.n) for...
import click from click_didyoumean import DYMGroup import click_repl from prompt_toolkit.history import FileHistory from cogctl.cli.config import CogctlConfig import os from cogctl.cli.bootstrap import bootstrap from cogctl.cli.bundle.main import bundle from cogctl.cli.chat_handle import chat_handle from cogctl.cli.g...
# coding: utf-8 """ """ import json import os import pytest from sampledb.logic import actions, instruments import sampledb.__main__ as scripts from ..test_utils import app_context @pytest.fixture def instrument(): return instruments.create_instrument('Example Instrument', 'Example Instrument Description') @p...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-24 06:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Fish', ...
from django.core.exceptions import ValidationError from os import path as fs_path from time import strftime from django.utils.text import slugify from django.utils import six from django.utils.translation import ugettext as _ from django.core.cache import cache from django.conf import settings from django.db import mod...
# SPDX-Package: FAVD # SPDX-PackageHomePage: https://github.com/secureIT-project/FAVD # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: 2021-2022 David Binkley, Leon Moonen, Sibren Isaacman # common methods # include reading a file, dumping the sorted list, and making the prediction # (see also KerasCode.py, wh...
import functools import warnings class CradminDeprecated(object): """ Mark functions, classes, methods or modules as deprecated. Examples:: Function:: @CradminDeprecated() def myfunc(): pass Function with message:: @CradminDeprecated...
import numpy as np import cv2 cap = cv2.VideoCapture("/dev/video0") cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240) while(True): # Capture frame-by-frame ret, frame = cap.read() # Display the resulting frame # cv2.imshow('preview',frame) ...
def my_function(parameter): print (parameter) my_function(1) print() def luas_segitiga (alas, tinggi): luas = (alas * tinggi) / 2 print ("Luas segitiga:", luas) #Pemanggilan fungsi dan mengisi parameter / variabel luas_segitiga (4, 6)
""" Testing local lambda runner """ import os from unittest import TestCase from mock import Mock, patch from parameterized import parameterized, param from samcli.commands.local.lib.local_lambda import LocalLambdaRunner from samcli.commands.local.lib.provider import Function from samcli.local.lambdafn.exceptions imp...
from osim.env import ProstheticsEnv import numpy as np import unittest class SimulationTest(unittest.TestCase): def test1(self): env = ProstheticsEnv(visualize=True) observation = env.reset() simbody_state = env.osim_model.get_state() print(simbody_state.getNumSubsystems()...
import numpy as np import skimage.graph.mcp as mcp from skimage._shared.testing import assert_array_equal a = np.ones((8, 8), dtype=np.float32) horizontal_ramp = np.array([[ 0., 1., 2., 3., 4., 5., 6., 7.,], [ 0., 1., 2., 3., 4., 5., 6., 7.,], ...
# -*- coding: utf-8 -*- """Python e GTK 4: PyGObject Gtk.EntryCompletion().""" import gi gi.require_version(namespace='Gtk', version='4.0') from gi.repository import Gio, GObject, Gtk class MainWindow(Gtk.ApplicationWindow): brazilian_states = [ (1, 'Acre'), (2, 'Alagoas'), (3, 'Amapá'), (4, 'Amazonas'...
import requests __all__ = ['VideoValidation'] class VideoValidation: def __init__(self, titulo, descricao, url): # self.id = id self.titulo = self._is_valid_titulo(titulo) self.descricao = self._is_valid_descricao(descricao) self.url = self._is_valid_url(url) def _is_valid_...
import calendar from datetime import datetime def preprocess_data(dataframe): dataframe['date'] = dataframe['datetime'].apply(lambda x: x.split()[0]) dataframe['hour'] = dataframe['datetime'].apply(lambda x: x.split()[1].split(':')[0]) dataframe['weekday'] = dataframe['date'].apply( lambda date_st...
from armulator.armv6.opcodes.abstract_opcodes.ldc_literal import LdcLiteral from armulator.armv6.opcodes.opcode import Opcode from armulator.armv6.bits_ops import zero_extend from armulator.armv6.arm_exceptions import UndefinedInstructionException class LdcLiteralT1(LdcLiteral, Opcode): def __init__(self, instruc...
import argparse, multiprocessing, logging, signal, os, datetime, subprocess, time from boat import Boat logging.basicConfig( format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt='%y-%m-%d:%H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) class BoatCluster...
"""NSQ protocol parser. :see: https://nsq.io/clients/tcp_protocol_spec.html """ import abc import struct from typing import Any, Optional, Tuple, Union from ansq.tcp import consts from ansq.tcp.exceptions import ProtocolError from ansq.tcp.types import ( FrameType, NSQErrorSchema, NSQMessageSchema, NS...
from src import Neuron import numpy as np from typing import * class FlattenLayer: def __init__(self, num_inputs: int): """ Initializes a flatten layer. :param num_inputs: Number of inputs to each neuron """ self.name = "FlattenLayer" self.num_inputs = num_inputs ...
from flatland.envs.agent_utils import RailAgentStatus from flatland.evaluators.client import FlatlandRemoteClient import numpy as np import time import yaml import ray import gym from ray.rllib.utils import merge_dicts from ray.rllib.agents.dqn import ApexTrainer from ray.rllib.agents import dqn from envs.flatland.obse...
import logRegres dataArr, labelMat = logRegres.loadDataSet() print(logRegres.gradAscent(dataArr, labelMat))
from runAIML import runAIML inpt = '你好' test = runAIML(inpt) if test == '': print('QQ') else: print('QQQ') print(test)
from flask import Flask from flask import request from flask import render_template from flask import jsonify import config from datetime import datetime app = Flask(__name__) heading = dict() @app.route("/") def main(): print("config details") print(config.LOCAL_DNS_PORT) return str(config.LOCAL_DNS_PORT) @a...
""" Read the temperature and humidity from sensors and upload them to the mongodb. This script is executed every 5 minutes as a cronjob. """ import json import time from pathlib import Path from pymongo import MongoClient from inkbirdsensor import InkbirdSensor config_path = Path('/home/hendrik/.config/burchen_db.js...
# Make sure the translation functions work. # Start simple - unambiguous DNA to unambiguous protein from __future__ import print_function from Bio import Seq from Bio import Alphabet from Bio.Alphabet import IUPAC # First, test the transcription functions s = "ATA" dna = Seq.Seq(s, IUPAC.unambiguous_dna) rna = dna....
class InvalidFilterSpecError(ValueError): pass class SourceImageIOError(IOError): pass
import commands import config cfg = config.load_config() bot = commands.Bot(command_prefix=cfg.get('command_prefix'), help_command=commands.CustomHelpCommand()) bot.config = cfg for ext in cfg.get('active_extensions', []): bot.load_extension(ext) bot.run(cfg.get('discord_token'))
# encoding: utf-8 # VDM lexerを試すサンプルだが、日本語が交じるとダメ # ただし、日本語がダメなのは、lexerの問題ではなく、呼び出す時の問題だと思う from pygments import highlight from pygments_plugin.lexers.vdm import VDMLexer from pygments.formatters import HtmlFormatter if __name__ == '__main__': code = '' for line in file('FizzBuzz.vpp', 'r').readli...
''' Created on Jun 13, 2016 @author: Wajih-PC ''' import numpy as np from NN import nnpredict def nntest(nn,x,y): labels = nnpredict.nnpredict(nn,x) expected = y.argmax(axis=1) bad = np.where(labels != expected) er = np.size(bad)/np.size(x,0) return er,bad
from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path from chat.consumers import ChatConsumer from public_chat.consumers import PublicChatConsumer from notificati...
from wagtail.admin.edit_handlers import RichTextFieldPanel from wagtail.core.fields import RichTextField from wagtail.core.models import Page from wagtail_tag_manager.decorators import register_variable from wagtail_tag_manager.options import CustomVariable class HomePage(Page): content = RichTextField() co...
""" ACELib (AMPS Client Environment Library) A library to allow any process to supply data to an official AMPS Server """ import socket import json import base64 import hashlib import threading import keyExchange import encryption import packet as Packet import dataOverString as DataString import ACEEx...
#!/usr/bin/env python2 from PIL import Image, ImageDraw import requests import re #URL = "http://localhost:19505/exam" URL = "http://archive.sunshinectf.org:19005/exam" # Need requests session because you need cookies to keep track of your progress s = requests.Session() # get first exam r = s.get(URL) # Complete 1...
""" This file makes the following benchmarking datasets: - elasticity_K_VRH - elasticity_log10(K_VRH) - elasticity_G_VRH - elasticity_log10(G_VRH) From matminer's dataset library. """ from matminer.datasets.dataset_retrieval import load_dataset from matminer.data_retrieval.retrieve_MP import MPDataRet...
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: 'zfb' # time: 2020-12-04 18:17 from tencentcloud.common import credential # 导入可选配置类 from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile from tencentcloud.common.exception.tencent_cl...
""" An example of how to extract timeseries data from point locations using WRF data stored in AWS. Assumes that the `wrf-ak-ar5` S3 bucket is mounted at `~/wrf-ak-ar5` Authors: Michael Lindgren (malindgren@alaska.edu), SNAP """ import netCDF4 # prevent occasional obscure HDF5 issue with file locking on CentOS # Set...
from tools import trimmed, str_to_tuple from constants import COLORS class Color: def __init__(self, red:int, green:int, blue:int, alpha:int=255): self.set_red(red) self.set_green(green) self.set_blue(blue) self.set_alpha(alpha) def red(self): return self._red def ...
""" Home-Monitor: AI system for the detection of anomalous and possibly harmful events for people. Written by Gabriel Rojas - 2019 Copyright (c) 2019 G0 S.A.S. See LICENSE file for details Class information: Class to send notifications. """ import sys from os.path import dirname, normpath # Inc...
from __future__ import print_function, division from corner import corner import pandas as pd import numpy as np class Catalog(pd.DataFrame): _required_columns = () def __init__(self, *args, **kwargs): super(Catalog, self).__init__(*args, **kwargs) # ensure all required columns are present ...
# Copyright 2018 The TensorFlow 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 applica...
import json import os from typing import Dict, List, Optional, Union import requests from ape.utils import USER_AGENT from ape_etherscan.exceptions import get_request_error from ape_etherscan.utils import API_KEY_ENV_VAR_NAME def get_etherscan_uri(network_name: str): return ( f"https://{network_name}.et...
import unittest import matplotlib.pyplot as plt def harmonic_number(n): if n == 1: return 1 return 1 / n + harmonic_number(n - 1) class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(1, harmonic_number(1)) self.assertEqual(1.5, harmonic_number(2)) ...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Laboratory.created' db.add_column(u'core_laboratory', 'cr...
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM # https://arxiv.org/abs/1710.11063 class GradCAMPlusPlus(BaseCAM): def __init__(self, model, target_layers, use_cuda=False, reshape_transform=None): super(GradCAMPlusPlus, self).__init__(model, target_layers, use_c...
import bisect import fnmatch import os from os.path import isdir, isfile, join, basename, splitext from django.conf import settings # Use the built-in version of scandir/walk if possible, otherwise # use the scandir module version try: from os import scandir, walk except ImportError: from scandir import scandi...
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//div[@class='box_sp2']/div[@class='box_detailsp']/div[@class='slide_show']/h1", 'price' : "//div[@class='detail_sp']/div[@class='box_...
from PIL import Image, ImageDraw, ImageFont import json class DrawBoard(): def __init__(self, rows, columns, image_path=None): self._rows = rows self._columns = columns self._image_path = image_path # colors for different type of holds self._color_map = { 'start...
import sys, json, codecs, gzip from datetime import datetime from argparse import ArgumentParser from app.prepare.read_json import JsonLineReader from .comp_hets import FamilyDataMiner, CompHetsBatch #===================================== class PostAttonationProcess: def __init__(self, mine_lines = 1000, line_peri...
#!/usr/bin/env python3 # Convert Project Gutenberg transcriptions of Catalog of Copyright # Entries renewals to tab delimited files. # # See https://onlinebooks.library.upenn.edu/cce/ # # This will read a plain text transcription of CCE renewals and # "unnest" the entries. That is it will take text blocks with # heira...
def composite_value(value): if ';' in value: items = [] first = True for tmp in value.split(';'): if not first and tmp.startswith(' '): tmp = tmp[1:] items.append(tmp) first = False else: items = [value] return items
import pathlib import stat DIRECTORY = 0 EXECUTABLE = 1 FILE = 2 LINK = 3 def write_node(path, node): path = pathlib.Path(path) typ, content = node if typ == LINK: write_link(path, content) elif typ == DIRECTORY: write_directory(path, content) elif typ == EXECUTABLE: write...
''' Plot the difference image between two epochs of NGC 1404. ''' from astropy.io import fits # package for loading FITS files from matplotlib import pyplot as plt # plotting from matplotlib import cm # color maps import numpy as np # math, stats, etc f1 = fits.open('SN2011iv...
import mimetypes import smtplib import email.mime.base import email.mime.multipart import email.mime.text import email.encoders class Message: """ Represents an email message. """ def __init__(self, fromAddr, toAddr, subject, message): self.fromAddr = fromAddr self.toAddr = toAddr sel...
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved. from speakeasy.struct import EmuStruct, Ptr NTE_BAD_ALGID = 0x80090008 class SERVICE_TABLE_ENTRY(EmuStruct): def __init__(self, ptr_size): super().__init__(ptr_size) self.lpServiceName = Ptr self.lpServiceProc = Ptr
import nevergrad as ng import numpy as np import torch from pix2latent.utils.image import binarize class _BaseNevergradOptimizer(): """ Base template for NeverGrad optimization. Should be used jointly with BaseOptimizer. For full list of available optimizers > https://github.com...
import sys from collections import namedtuple from typing import Tuple import moderngl import demosys from demosys import project from demosys.conf import settings from demosys.view import screenshot GLVersion = namedtuple('GLVersion', ['major', 'minor', 'code']) class BaseKeys: """ Namespace for generic ke...