text stringlengths 3.07k 12.6k |
|---|
###L09-01
def rainRightJust():
rainfile = open("rainfall.txt","r")
outfile = open("rainfallRightJust.txt","w")
for aLine in rainfile:
values = aLine.split()
cityNames=values[0]
numbers=values[1]
outfile.write("%+25s %+5s \n" % (cityNames,numbers))
rainfile.close()
o... |
import re
from datetime import datetime, timedelta
from threading import Thread
import jwt
import sendgrid
from decouple import config
from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from rest_framework import serializers, status
from rest_fra... |
"""chainsolve transmutation tests."""
import os
import nose
import warnings
from nose.tools import (
assert_equal,
assert_not_equal,
assert_raises,
raises,
assert_almost_equal,
assert_true,
assert_false,
assert_is,
with_setup,
assert_less,
)
from numpy.testing import dec, asser... |
from pathlib import Path
import numpy as np
import scipy.io as io
from utils.matching import optimum
import scipy.io as io
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
data_type = {"train": [1, 2, 5, 6, 9, 10, 13, 14], "test": [3, 7, 11, 15]}
Group = {
"Control": list(range(1, 5)),
... |
# Copyright 2021 DengBoCong. 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 a... |
import logging
import pickle
from typing import List
import torch
from transformers import RobertaTokenizer, RobertaModel
from src.dataobjs.mention_data import MentionData
logger = logging.getLogger(__name__)
class EmbedTransformersGenerics(object):
def __init__(self, max_surrounding_contx,
fi... |
import sys
import glob
import re
from pylab import *
from scipy.ndimage.measurements import center_of_mass
from collections import defaultdict
def find_next_while_pixel(image):
"""
Coordinates of the first white pixel in a binary image
Returns i,j image coordinates
"""
coords = nonzero(image)
i... |
from django.contrib.auth import authenticate, get_user_model
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.authtoken.serializers import AuthTokenSerializer
from .models import (Category, Question, Comment, Request, Expen... |
# Copyright (c) 2016. Mount Sinai School of Medicine
#
# 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 o... |
"""Encoding tools for a largely compatible encryption system based on the interpolation of character and ordinal values.
decode() - decode Ordinary into standard text.
encode() - encode a string into Ordinary.
dump() - convert and write ordinary/text to a file-like object (.write()).
load() - load ordinary/text from ... |
from pprint import pprint
import order_flower_intent
from pylexo import LexInputEvent, LexOutputResponse, CloseLexOutputResponse, ElicitIntentOutputResponse, \
ConfirmIntentOutputResponse, ElicitSlotOutputResponse, runtime_response
import json
orderFlowerJson = """
{
"messageVersion": "1.0",
... |
import itertools
# import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import (CosineAnnealingLR,
CosineAnnealingWarmRestarts,
ExponentialLR, LambdaLR,
ReduceLR... |
"""Perform on-device percentile calculation of 2D arrays."""
# see scripts/percentiletest.py for an example
from typing import Tuple, Mapping, Callable, Optional, Any, cast
from typing_extensions import TypedDict
import numpy as np
from . import accel
from . import tune
from .abc import AbstractContext, AbstractComm... |
import cv2
import random
import numpy as np
import albumentations as A
from pathlib import Path
from typing import List, Tuple
from .copy_paste import CopyPaste, CopyPasteAugmentation
# ------------------GENERAL CONFIG----------------------
# foreground objects
object_folder = Path(r'C:\Users\RN767KA\Projects\Document... |
"""
Copyright 2019 Conductor, 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, softwar... |
"""Solution for exercise 2.6/2.7
"""
# TODO: use ndarray of numpy replace original python list implementation(next PR)
from copy import deepcopy
def min_edit_distance(
source: str,
target: str,
del_cost=1,
ins_cost=1,
sub_cost=2,
):
"""Minimum-Edit-Distance(DP)
Args:
`source`: sou... |
#!/usr/bin/env python3
#
# Copyright (c) 2021 Red Hat, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modi... |
import tensorflow as tf
from tensorflow.python.keras.layers import Flatten, Dense, Conv2D, Dropout, BatchNormalization
from abc import ABC, abstractmethod
import numpy as np
import warnings
def dqn_mask_loss(batch_data, y_pred):
# The target is defined only for the action that was taken during the replay, hence t... |
import random
import linecache
import vk_api
import requests
from bs4 import BeautifulSoup
import time
from vk_api import VkUpload
import configparser
import logging
import os
from datetime import datetime
def get_files(path):
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path,... |
"""
Functions that will ensure that the ARN is returned if a string is passed.
If it is an object in troposphere, it will return GetAtt(obj, 'Arn') or Ref() depending on
what the object supports for return.
If it is a string, it must either comply to the last part of a ARN or be a full ARN
and match the ARN pattern
"... |
# Copyright (c) 2021, ifitwala and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from six import string_types
import frappe.share
from frappe import _
from frappe.utils import cstr, now_datetime, cint, flt, get_time, get_datetime, get_link_to_for... |
"""
Implements geometrical objects used for physics based mechanical simulations
Classes:
GeometryComponent(abstract)
Circle
Rectangle
GeneralPolygon
"""
import numpy as np
from abc import ABC, abstractmethod
import matplotlib.pyplot as plt
import shapely.geometry
from shapely.geometry.point import Point
from shapely... |
from unittest import mock
import pytest
from tulius.core.ckeditor import html_converter
from djfw.wysibb import models
from djfw.wysibb.templatetags import bbcodes
@pytest.mark.parametrize('data,value', [
[ # Check structure support
'aaa<b>d<some_tag>f</some_tag>f<s>fd</s>ff</b>bb',
'aaa[b]dff... |
import unittest
import libyang
import asyncio
import logging
import time
import itertools
from multiprocessing import Process, Queue
from goldstone.lib.connector.sysrepo import Connector
from goldstone.lib.server_connector import create_server_connector
from goldstone.lib.errors import *
from goldstone.lib.util import... |
"""
Database module (sqlalchemy with aiosqlite)
"""
from typing import Iterable, List, Optional
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import dec... |
# Copyright (c) 2017 Intel Corporation. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import os
import re
import errno
import socket
import json
from chroma_agent.lib.shell import AgentShell
from toolz.functoolz import pipe
from toolz.itertoo... |
# -*- coding: utf-8 -*-
import requests
import json
from ckan.plugins import toolkit as tk
from ckan import model as ckan_model
from ckan.logic import NotFound
from ckan.lib.mailer import mail_recipient
from .. import model
import logging
_ = tk._
check_access = tk.check_access
side_effect_free = tk.side_effect_free... |
"""
Code to change times in any format to times in any other format
Inputs can be: JD_UTC_f*, MJD_UTC_f*, HJD_UTC_f*, BJD_TDB_f*
where f* denotes the exposure timestamp location (see below)
Timestamp types can be: START, MID, END
Outputs can be: JD_UTC_MID, MJD_UTC_MID, HJD_UTC_MID, BJD_TDB_MID
"""
import sys
import... |
"""Provider implementation based on boto library for AWS-compatible clouds."""
import logging as log
import boto3
try:
# These are installed only for the case of a dev instance
from moto import mock_ec2
from moto import mock_s3
import responses
except ImportError:
log.debug("Development library m... |
# Copyright (c) 2016 IBM.
# 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 appl... |
from flask import Flask, jsonify, redirect, render_template, session, url_for, request
from flaskext.mysql import MySQL
app = Flask(__name__, static_url_path = "")
from myprojectprototype.script import dataAnalytic
import functools
from sqlalchemy import create_engine
import pandas as pd
import simplejson as json
def ... |
#!/usr/bin/env python
# coding: utf-8
"""Script to compare VCF files to each other and to truth data.
Outputs the resulting data as JavaScript on stdout.
"""
import argparse
import collections
import functools as ft
import json
import os
import sys
import vcf
import dream_evaluator
# In PyVCF, a [] for FILTER mean... |
from functools import partial
import asyncio
from abc import ABCMeta
from typing import Type
from .app import Component
from .error import PrepareError
from aiotg import Bot, Chat
import aiozipkin.span as azs
import aiozipkin.aiohttp_helpers as azah
from .misc import json_encode
class TelegramHandler(object):
__m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from pypinyin import (pinyin, slug, lazy_pinyin, load_single_dict,
load_phrases_dict, NORMAL, TONE, TONE2, INITIALS,
FIRST_LETTER, FINALS, FINALS_TONE, FINALS_TONE2)
def t... |
#!/usr/bin/env python3
# ================== i18n.py =====================
# It localizes website elements.
# Hook type: pre_build (modifies config file)
# Configuration:
# Create a i18n.yaml file in your project root. Look at i18n.yaml and i18n.example.yaml
# to get a feel for the structure.
# Add the correct id to... |
#!/usr/bin/env python
import os
import pprint
import subprocess
import sys
from optparse import make_option
from urllib import quote_plus
from urlparse import urljoin
import dateutil.parser
import requests
from django.conf import settings
from django.core.management import BaseCommand, CommandError
from six import pyt... |
#!/usr/bin/env python3
"""
Extracts images from the data stored with generate_data.py or optimal_trajectory_gen.py. Applies several transformation
to all images, if wished.
"""
import pathlib
import random
import argparse
import json
import shutil
from typing import List, Callable
import yaml
import numpy as np
impo... |
import os
import numpy as np
from collections import OrderedDict
import SimpleITK as sitk
import shutil
from batchgenerators.utilities.file_and_folder_operations import *
from nnunet.paths import nnUNet_raw_data
def get_identifier(img_path):
group_id = os.path.split(os.path.split(img_path)[0])[1]
id = os.path... |
# --------------------------------------------------------------------- #
# This file is a part of ShapeMapper, and is licensed under the terms #
# of the MIT license. Copyright 2018 <NAME>. #
# --------------------------------------------------------------------- #
import sys, os
from copy impo... |
"""Defines a Matchop class representing a pymongo matching operator."""
import re
import warnings
from math import inf
from comath.segment import LineSegment
__LOGICAL_OPS = set(('$or', '$and', '$not', '$nor'))
__COMPAR_OPS = set(('$eq', '$gt', '$gte', '$lt', '$lte', '$ne', '$in', '$nin'))
def _contains_logical_o... |
"""Functions that take an image and return a transformed image"""
from typing import Callable, Optional, Tuple
import cv2 as cv
import numpy as np
def resize(
image: np.array,
shape: Optional[Tuple[int, int]] = None,
min_dim: Optional[int] = None,
**kwargs,
) -> np.array:
"""
Resize input ima... |
#
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
#
# 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
#... |
#!/usr/bin/env python
# rhevmgr
# Accesses the API to manage the state of VMs on the cluster.
#
# Author: <NAME> <<EMAIL>>
# Created: Wed Mar 29 20:53:47 2017 -0400
#
# Copyright (C) 2016 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: rhevmgr.py [] <EMAIL> $
"""
Accesses the API to manage the state... |
def add_filter(bot, update):
from chats_data import chats_data
from filter_dict import filter_dict
chat_id = update.message.chat_id
msg = update.message.text
user = bot.get_chat_member(chat_id, update.message.from_user.id)['status']
if update.message.chat_id in chats_data.keys():
if chats_data[chat_id]['fil... |
'''
Copyright (c) 2011, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the fo... |
import os
import PySimpleGUIQt as sg
from multiprocessing import Process
from toolbox_creator.globe_icon import globe_icon
from toolbox_creator.function_window import create_function_window
from toolbox_creator.function_validation import validate_tool_list
from toolbox_creator.utils import get_list_of_keys
global wind... |
"""
HKDR
See: <NAME>, <NAME>, <NAME>, Ma RC, Ko GT, Ho CS et al.
Development and validation of a total
coronary heart disease risk score in type 2 diabetes mellitus.
Am J Cardiol. 2008;101:596-601.
"""
import numpy as np
from cvdm.score import cox_surv, BaseRisk
from cvdm.score import clean_age, clean_diab_dur, clea... |
"""Executes a script to retrieve pdf from given url in
an aid on aides-territoires.beta.gouv.fr API
"""
import json
import re
from io import BytesIO
from tabnanny import verbose
from urllib.parse import urlparse
import pandas as pd
import PyPDF2
from datasource.io import get_data_from_url
from datasource.utils import... |
from sample_players import DataPlayer
import math, random
class CustomPlayer_AB(DataPlayer):
def minimax(self, state, depth):
'''
Min-max algorithm
:param state: Game state
:param depth: Depth of tree
:return: the state with highest score
'''
def min_value(... |
#coding:utf-8
#
# PROGRAM/MODULE: saturnin
# FILE: saturnin/component/bundle.py
# DESCRIPTION: Service budle controller
# CREATED: 5.12.2020
#
# The contents of this file are subject to the MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softwar... |
import torch
import torch.nn as nn
import numpy as np
from . import lateral_net as lateral_net
from lib.utils.net_tools import get_func
from lib.models.WCEL_loss import WCEL_Loss
from lib.models.VNL_loss import VNL_Loss
from lib.models.image_transfer import bins_to_depth, kitti_merge_imgs
from lib.core.config import cf... |
# -*- coding: utf-8 -*-
import re
import time
import urllib
import random
import urlparse
from collections import namedtuple
from zitkino import log
from zitkino import http
from zitkino import parsers
from zitkino.models import Film
from . import BaseFilmID, BaseFilmService
class CsfdFilmID(BaseFilmID):
url_... |
#!/usr/bin/env python3
def array_part_loops_pruning(loops, config):
"""Apply pruning on array partitioning candidate loops.
At present, we apply the following heuristics:
- The product of all array_part loops should be greater than the total PE number
- TODO: Prune based on off-chip traffic
Para... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Testing :mod:`astropy.cosmology.flrw.wpwazpcdm`."""
##############################################################################
# IMPORTS
# STDLIB
# THIRD PARTY
import pytest
# LOCAL
import astropy.cosmology.units as cu
import astropy.units as u... |
# pylint: disable=too-many-instance-attributes,too-many-locals,unused-argument,no-self-use,wrong-import-order
import logging
from typing import Optional, List
import click
from sample_metadata.models import AnalysisType, AnalysisStatus, AnalysisModel
from sample_metadata.parser.generic_metadata_parser import (
Ge... |
import requests
import os
from pandas.io.json import json_normalize
import datetime
import base64
## import API use key, API user and base URL from Jenkins variables
try:
api_key = os.environ['AUTH_API_KEY']
except KeyError:
print("API-key is missing")
try:
api_user = os.environ['AUTH_API_USER']
except ... |
#!/usr/bin/env python
# coding=utf-8
# Stan 2012-03-10
from __future__ import (division, absolute_import,
print_function, unicode_literals)
import logging
from sqlalchemy import MetaData
from ...reg import reg_object1
from ...reg.result import *
from .stuff.backwardcompat import *
from .stuf... |
#!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import sys
import tempfile
REPOSITORY_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__), ... |
import logging
import os
import pathlib
import pickle
import numpy as np
import pandas as pd
from datasketch import MinHashLSHForest, MinHash, MinHashLSH, LeanMinHash
import src.QueryDatabase as queryDatabase
NUM_PERM = 128
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(m... |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from skimage.io import imread
import keras
from keras import Sequential
from tensorflow.keras.applications.mobilenet import MobileNet
from keras.layers import Dense
from keras.preprocessing import image
impo... |
import math
from datetime import timedelta
from datetime import datetime
MAX_GEE_PIXELS_DOWNLOAD = 1048576
GEE_ERROR_PLACEHOLDER = "ImageCollection.getRegion: Too many values: "
__all__ = ('tile_coordinates', 'retrieve_max_pixel_count_from_pattern',
'cmp_coords', 'get_date_interval_array', 'make_polygon')
... |
# Copyright (c) 2021 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... |
"""
Date and time tools.
"""
#-------------------------------------------------------------------------------
from __future__ import absolute_import
import datetime
import re
import pytz
from pytz import UTC
from .util import if_none
#-------------------------------------------------------------------------... |
import argparse
import string
class TestGroup:
def __init__(self, name, parent = None):
self.parent = parent
self.name = name
self.testGroups = {}
self.testCases = {}
if parent:
assert not name in parent.testGroups
parent.testGroups[name] = self
def getName (self):
return self.name
def getPath ... |
'''
* $Id
* File name : template_script.py
*
* Purpose : Allows for easy experimentation by running Models and archiving the results
*
* Author : <NAME>
*
* Created : 29-Aug-2020
*
* Bugs: --
*
* Change Log: Added an argument for Blur pooling -bl
*
*
'''
#Imports
######################################... |
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Iterative flags elimination.
Part of the Chrome build flags optimization.
This module implements the flag iterative elimination algorithm (IE) ado... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
import tensorflow as tf
tf.enable_eager_execution()
def get_type_id(tgt_len, tgt_idx, type_val):
tgt_idx_left_shift = tgt_idx[:-1]
type_val_right_shift = type_val[1:]
new_type_id_sh... |
import sample_utils, config, parse_midas_data, sfs_utils, diversity_utils, gene_diversity_utils, core_gene_utils
import os, os.path, sys, gzip
import numpy
temporal_change_directory = '%s/temporal_changes/' % (config.data_directory)
intermediate_filename_template = '%s/%s.txt.gz'
min_coverage = config.min_medi... |
"""DAVIS Demo based on RoShamBo.
Author: <NAME>
Email : <EMAIL>
"""
from __future__ import print_function
import argparse
import pickle
import threading
import numpy as np
import cv2
from glumpy import app, gloo, gl
from pyaer.davis import DAVIS
# parse model
parser = argparse.ArgumentParser()
parser.add_argument... |
#!/usr/bin/env python
import argparse
import numpy as np
import mdtraj as md
import matplotlib.pyplot as plt
from LLC_Membranes.llclib import physical
import pickle
def initialize():
parser = argparse.ArgumentParser(description='Figure out the weight percent of water in the pores and tails')
# trajectory c... |
# Copyright 2021 Google LLC
#
# 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 applicable law or agreed to in writing, ... |
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
from einops import rearrange, repeat
from kornia import filters
def compute_errors(depths, preds, masks):
errors = 0
cnt = 0
for depth, est, mask in zip(depths, preds, masks):
gt = depth[mask]
pred... |
from typing import Tuple
import torch
from cubework.distributed import ParallelManager as pm
from cubework.distributed import all_gather, all_reduce, broadcast, reduce, reduce_scatter
from cubework.distributed.utils import ParallelMode
from cubework.global_vars import env
from torch import Tensor
from torch.cuda.amp i... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
from time import time, sleep
import re
import requests
import os
impo... |
from keras import Input, Model, Sequential
from keras.layers import Flatten, Conv2D, Concatenate, Dense, Activation, concatenate
from keras.optimizers import Adam, SGD
from rl.agents import CEMAgent
from rl.memory import SequentialMemory, EpisodeParameterMemory
from hexagon_agent import *
from random import shuffle
fr... |
# encoding: utf-8
""" Main menu """
import sys
import os
import datetime
import asyncio
import curses
import npyscreen
from error_handler import error_handler
from main_menu_list import MainMenuList
from widgets.net_interfaces_widget import NetInterfacesWidget
APP_NAME = "{} ASR".format(os.environ.get("APP_NAME", "Sp... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import MFRC522
import signal
import time
import picamera
import base64
import requests
import json
import RPi.GPIO as GPIO
from subprocess import call
continue_reading = True
def end_read(signal, frame):
global continue_reading
print('Ctrl+C captured, ending read... |
import pandas as pd
import matplotlib.pyplot as plt
# Read data from csv into pandas dataframe
data = pd.read_csv('data.csv')[
['userid', 'From', 'To']]
# Display the first 10 rows of dataframe
print(data.head(10))
# Checking if there are NAN values
print("Presence of NAN values : \n", data.isnull().any())
# Fu... |
import csv
import matplotlib.pyplot as plt
import numpy as np
def analysePeltier(modelResults, result):
model = "Model 1"
# with open("tempTest.csv",'r') as f:
with open("PowerUsage/varPower", 'r') as f:
next(f)
for line in f:
res = line.strip().split(",")
if((fl... |
"""Utils for getting basic entity data.
For example, the
following information can be access about Colombo District.
.. code-block:: python
>> from gig import ents
>> ents.get_entity('district', 'LK-11')
{'district_id': 'LK-11', 'name': 'Colombo', 'province_id': 'LK-1',
'ed_id': 'EC-01', 'hasc': 'LK.... |
"""
PeerColab
Base python file for PeerColab Flask App
Copyright <NAME>, 2021.
"""
import sys
import os
# import datetime
from flask import (Flask, render_template, redirect, url_for, session, request,
flash, current_app)
from markupsafe import Markup
from util import db, helpers
import config
... |
"""Console script for ssl_certinfo."""
import argparse
import ipaddress
import logging
import os
import re
import sys
from typing import Tuple
from ssl_certinfo import __author__, __email__, __version__, ssl_certinfo, validation
from ssl_certinfo.ssl_certinfo import OutputFormat
VERSION = rf"""
ssl_certinfo {__versio... |
"""
* Project Name: NAD-Logging-Service
* File Name: logger.py
* Programmer: <NAME>
* Date: Sun, Nov 15, 2020
* Description: This file contains the logging app.
"""
import json as _json
import logging
import os
import time
from logging.config import dictConfig
from attr import attrib, attrs, validators
from dat... |
import hashlib
import struct
from collections import OrderedDict
from typing import IO, Any, Optional, Iterable, Mapping, Dict, \
NamedTuple, ClassVar, TypeVar, Type
from pymap.mailbox import MailboxSnapshot
from .io import FileWriteable
__all__ = ['Record', 'UidList']
_UDT = TypeVar('_UDT', bound='UidList')
... |
import luigi
from hyperopt import fmin, hp, tpe, rand
import json
import numpy as np
import mlflow
import os
import pickle
import yaml
from src.models.get_model_task_by_name import get_model_task_by_name
from src.utils.metrics import should_minimize
from src.utils.mlflow_task import MLFlowTask
from src.utils.seed_rand... |
#coding: utf-8
import json
import GlobalTools
def getRivalsScores(hash):
with GlobalTools.dbLock:
GlobalTools.cur.execute('''
SELECT rr.name AS name, rr.id AS id, ss.clear AS clear, ss.notes AS notes,
ss.pg*2+ss.gr AS score, ss.minbp AS minbp, rr.active AS active
FROM rivals AS rr INNER JOIN scores AS s... |
#!/usr/bin/python3
import os
import argparse
from pwd import getpwuid
from grp import getgrgid
import datetime
from stat import filemode, S_ISDIR, S_ISREG, S_IEXEC
from termcolor import colored, cprint
import stat
def remove_dot_files(list_files):
non_dot_list = []
for file in list_files:
if not file.... |
#打开邮件样本
with open('E:\lessons\ML wu.n.g\coursera-ml-py-master\coursera-ml-py-master\machine-learning-ex6\ex6\emailSample1.txt'
, 'r'
) as f:
email = f.read()
print(email)
#处理邮件的方法,常将url,email address , dollars 等标准化,忽略其内容
'''
1. Lower-casing: 把整封邮件转化为小写。
2. Stripping HTML: 移除所有HTML标签,只保留内... |
import time
import requests
import json
import sys
import getopt
mytimeinterval = 30
runcount = 1
def get_key_auth_token(ip,ver,uname,pword):
# The url for the post ticket API request
post_url = "https://partners.dnaspaces.io/client/v1/partner/activateOnPremiseApp"
print(post_url)
urllib3.disable_war... |
import random
import numpy as np
import pandas as pd
import math
from random import choice
import math
import os.path
from time import process_time
import threading
#number of verties
N=2000
#timer
total_time = 0
time_construct = 0
#creative a random spin array
spin_list = []
for i in range(N):
... |
#!/usr/bin/env python3
import argparse
import shutil
from functools import partial
from pathlib import Path
import numpy as np
from python_tools.generic import namespace_as_string
from python_tools.ml import metrics
from python_tools.ml.default.neural_models import EnsembleModel, MLPModel
from python_tools.ml.default.... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ..algorithm import imtool
class IntersectDialog(QDialog):
"""A dialog for action of intersection."""
def __init__(self, model, parent=No... |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import pdb
import os
import sys
sys.path.insert(0, os.path.abspath(".."))
from logger impo... |
import os.path
from typing import List, Optional, Tuple
import tensorflow as tf
from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel # type: ignore
from mlagents_envs.side_channel.environment_parameters_channel import EnvironmentParametersChannel # type: ignore
from tensorfl... |
from flask import Blueprint, flash, jsonify, request, redirect, render_template, session, url_for
from flask_login import login_required, current_user
from ims.common.ComboBoxUtil import getComCategoryList
from ims.common.Messages import Messages
from ims.common.RoleUtil import admin_required
from ims.contents.comCont... |
import numpy as np
from modules import functions as f
flat = lambda x: [a for b in x for a in b]
class Vertex(object):
def __init__(self, number, coord):
self.number = number
self.coord = coord
def find_edges(self,main_edges):
self.edges = [[x[0], x[1]] for x in main_edges ... |
import os
import numpy as np
import pickle
#import torch
#import torchvision.utils
import jittor as jt
from .gan_model import GANModel
class GANTrainer():
"""
Trainer creates the model and optimizers, and uses them to
updates the weights of the network while reporting losses
and the latest visuals to ... |
from datetime import timedelta
from django.db import models
from django.utils.translation import gettext_lazy
from mahjong_portal.models import BaseModel
from player.models import Player
from utils.tenhou.yakuman_list import YAKUMAN_CONST
class TenhouNickname(BaseModel):
RANKS = [
[0, u'新人'],
[1... |
from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
# -*- utf-8 -*-
from datetime import datetime
from django.db import models
# Create your models here.
class Target(models.Model):
uid = models.CharField(max_length=20, verbose_name=u"爬取用户")
cookie... |
# Copyright 2019 École Polytechnique Fédér<NAME>. 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 b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.