text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 23 08:58:37 2021
@author: michp-ai
"""
# This script is web automation for the Capstone project on ML rapid text labeling
# Before running this script in a different console start the web server by running main.py for the web app
# This is a simple demo script to illustr... |
"""Utilities for tracking and filtering spaces."""
import argparse
import attr
from collections import defaultdict
from itertools import product
from templateflow import api as _tfapi
NONSTANDARD_REFERENCES = [
'T1w',
'T2w',
'anat',
'fsnative',
'func',
'run',
'sbref',
'session',
]
"""Li... |
import string
class Solution:
def freqAlphabets(self, s: str) -> str:
di = dict(zip(range(1, 27), string.ascii_lowercase))
output=""
slist = s.split("#")
for numstr in slist[:-1]:
output+="".join([di[int(n)] for n in numstr[:-2]])
output+=di[int(numstr[-2:])]
... |
"""Regression tests for what was in Python 2's "urllib" module"""
import urllib.parse
import urllib.request
import urllib.error
import http.client
import email.message
import io
import unittest
from unittest.mock import patch
from test import support
import os
try:
import ssl
except ImportError:
ssl = None
imp... |
for i in range(0,100):
if(i%2!=0 and i%7!=0):
print(i) |
###############################################################################
# Name: haskell.py #
# Purpose: Define Haskell syntax for highlighting and other features #
# Author: Cody Precord <cprecord@editra.org> #
... |
import tkinter as tk
from random import choice
import cv2
import os
import pygame
import re
import sqlite3
import subprocess
import threading
import time
from PIL import Image
total = []
class mainw(object):
def win1(self):
self.i=1
self.root = tk.Tk()
self.root.title('carrito')
... |
# -*- coding: utf-8 -*-
"""
dicom2nifti
@author: abrys
"""
import os
import re
import traceback
import logging
import nibabel
import numpy
from pydicom.tag import Tag
import dicom2nifti.common as common
import dicom2nifti.convert_generic as convert_generic
from dicom2nifti.exceptions import ConversionValidationErro... |
#
# Copyright 2018 Analytics Zoo 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... |
#!/usr/bin/python3
#
# A script to generate functions (SPIR-mangled with SPIR AS) that will call
# target-specific kernel library functions (with OpenCL-mangled names and AS).
#
# e.g. _Z5frexpfPU3AS3i(float %x, i32 addrspace(1)* %y)
# would call
# _Z9_cl_frexpfPU7CLlocali(float %x, i32 * %1)
#
# output is LLVM IR text... |
from threading.TaskThread import TaskThread
class RMQCacheThread(TaskThread):
def __init__(self, queue, name, thread_pool, logger):
super().__init__(name, thread_pool, logger)
self.__queue = queue
|
# vvvvv MODIFY THIS IMPORT vvvvv
from executors.cexecutor import CExecutor
from codeserver import CodeServer
def main():
# Modify these variables for the specific language
host = ''
port = 4000
Executor = CExecutor
server = CodeServer(host,port,Executor)
server.handle_connection()
if __... |
"""
The :mod:`sklearnext.model_selection.search` includes utilities to search
the parameter and model space.
"""
# Author: Georgios Douzas <gdouzas@icloud.com>
# License: BSD 3 clause
from warnings import warn, filterwarnings
import re
from dask_searchcv.utils import copy_estimator
from sklearn.metrics import r2_scor... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
#! /usr/bin/python3
# Copyright 2018 Gaëtan Cassiers
#
# 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 ... |
# -*- coding: utf-8 -*-
"""
Hunt Colour Appearance Model
============================
Defines the *Hunt* colour appearance model objects:
- :class:`colour.appearance.InductionFactors_Hunt`
- :attr:`colour.VIEWING_CONDITIONS_HUNT`
- :class:`colour.CAM_Specification_Hunt`
- :func:`colour.XYZ_to_Hunt`
Reference... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from osbot_aws.Globals import Globals
from pbx_gs_python_utils.utils.Files import Files
from osbot_aws.apis.S3 import S3
#todo: refactor with better helper methods
class Temp_Folder_Code:
def __init__(self, file_name):
self.file_name = file_name
#self.s3 = S3()
self.folder ... |
class Point:
#GEOPANDAS
#teste
def indexa_pontos(pts):
pts_cp1 = pts.copy()
pts_cp2 = pts_cp1.copy()
for ponto in pts_cp1:
ponto.insert(3,-1)
x = pts_cp1[0][1]
y = pts_cp1[0][2]
pts_cp2.sort(key = lambda p: (p[1]-x)**2+(p[2]-y)**2)
p_i = pts_cp2[... |
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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... |
from django.db import models
from django.urls import reverse
from base.models import BaseModel
from project.models import Project
class Timeline(BaseModel):
"""
A timeline is a starting point for any Project.
One project can have many timelines, and all the smaller entities are part of the timeline.
... |
#! /usr/bin/python
#***********************************************************
#* Software License Agreement (BSD License)
#*
#* Copyright (c) 2009, Willow Garage, Inc.
#* All rights reserved.
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the ... |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'csgo.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you... |
"""Generate an HTML page"""
import dominate
from dominate import tags
doc = dominate.document(title="Dominate your HTML")
with doc.head:
tags.link(rel="stylesheet", href="style.css")
tags.script(type="text/javascript", src="script.js")
with doc:
with tags.div(id="header").add(tags.ol()):
for i i... |
from models.trade_model import TradeModel
from services.trade_record_file import FileDatabase
from datetime import datetime
class TradeService:
trading_details = {}
@classmethod
def trade_shares(cls, symbol, quantity, buy_or_sell, trade_price, timestamp=datetime.now()):
# read from file/db
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, VHRS and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class SubSectorTravel(Document):
pass
|
#!/usr/bin/env python
import os
import sys
import dotenv
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
dotenv.read_dotenv(os.path.join(BASE_DIR, 'settings/.env'))
if __name__ == "__main__":
ENVIRONMENT = os.getenv('ENVIRONMENT')
if ENVIRONMENT == 'STAGING':
settings = 'staging'
elif ENV... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Imports
########################################
import sys, os
# Update this to point to the directory where you copied the SciAnalysis base code
#SciAnalysis_PATH='/home/kyager/current/code/SciAnalysis/main/'
SciAnalysis_PATH='/home/yager/current/code/SciAnalysis/main/'
... |
import requests
import http.client
import sys
fake_headers = { 'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
}
def file_download(url):
try:
... |
from skimage.color import rgb2grey
from scipy import fftpack
import numpy as np
import numpy.ma as ma
def _dict_divide_(dividends, divisors):
ret = dict()
for key, dividend in dividends.items():
ret[key] = dividend / divisors.get(key, 1)
return ret
def _get_hashable_key_(key):
if key.squeeze... |
import tempfile
from equivalencecheckers.wmethod import WmethodEquivalenceChecker, RersWmethodEquivalenceChecker, \
SmartWmethodEquivalenceChecker
from learners.TTTmealylearner import TTTMealyLearner
from learners.mealylearner import MealyLearner
from suls.caches.rerstriecache import RersTrieCache
from suls.rersco... |
import abc
import numpy as np
import tensorflow as tf
from tensorflow.python.feature_column import feature_column_v2 as fc_lib
from elasticdl.python.common.constants import DistributionStrategy
from elasticdl.python.common.log_utils import default_logger as logger
from elasticdl.python.common.save_utils import Checkp... |
from django.apps import AppConfig
class RacesTableConfig(AppConfig):
name = 'races_table'
|
from random import randrange
from threading import currentThread
from time import sleep
from modulos.agencia import agencia
class cliente(object):
def __init__(self, Agencias: [agencia]):
self.agencias = Agencias
self.agenciaElegida = self.agencias[randrange(0,self.agencias.__len__())]
def ... |
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import random
import cv2
import IPython
import numpy as np
class Viz_Feat(object):
def __init__(self,val_data,train_data, class_labels,sess):
self.val_data = val_data
self.train_data = train_data
self.CLASS_LA... |
#!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... |
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Code related to managing kernels running in YARN clusters."""
import asyncio
import errno
import logging
import os
import signal
import socket
import time
from traitlets import default, Unicode, Bool
from typing im... |
import atexit
import logging
import os
import subprocess
import time
from concurrent import futures
import certifi
import click
from bentoml import config
from bentoml.configuration import get_debug_mode
from bentoml.exceptions import BentoMLException
from bentoml.yatai.utils import ensure_node_available_or_raise, pa... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="Optimized Kalman Filter",
version="0.0.2",
license='MIT',
author="Ido Greenberg",
description="Optimization of a Kalman Filter from data of states and their observations.",
long_descr... |
"""
Contains class that generates the 'locality.txt' file for any state.
locality.txt contains the following columns:
election_administration_id,
external_identifier_type,
external_identifier_othertype,
external_identifier_value,
name,
polling_location_ids,
state_id,
type,
other_type,
id
"""
impor... |
#!/usr/bin/env python3
from collections import namedtuple
from typing import Callable, Iterable, List, NamedTuple, Optional, Tuple, Union
import torch
from captum.attr import IntegratedGradients
from captum.attr._utils.batching import _batched_generator
from captum.attr._utils.common import _run_forward, safe_div
from... |
### init function for plotting results ###
from .control_plot_gp import plot_gaussian_process
from .single_visit_plots import plot_single_exposure, plot_eb_mode_single_visit
from .single_plot_results import plot_gpfit
from .plot_mean_function import plot_mean_ccd, plot_fov_mean, build_mean_in_tp
from .plot_output impo... |
from django.apps import AppConfig
class CoreConfig(AppConfig):
name = "templates_django.core"
verbose_name = "Core" # change this to anything and the django admin will reflect what is here.
|
# -*- coding : utf-8 -*-
# Copyright (C) 2018 by
# Cédric Santran <santrancedric@gmail.com>
# All rights reserved.
# BSD license.
#
# Authors:
# Cédric Santran <santrancedric@gmail.com>
import re
from warnings import warn
from pg2l.meta.grammar import MetaGrammar
class Lexer(object):
def __init__(... |
import torch
import torchvision
from torch import nn, Tensor
from torchvision.transforms import functional as F
from torchvision.transforms import transforms as T
from typing import List, Tuple, Dict, Optional
def _flip_coco_person_keypoints(kps, width):
flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 1... |
import enum
from dataclasses import dataclass
from decimal import Decimal
from typing import List
import py3dbp
class Axis(enum.Enum):
"""
Represents a single axis.
Width is on the x-axis, height is on the y-axis and depth is on the z-axis given a right handed coordinate system.
"""
width = 1
... |
"""Support for the Roku media player."""
import logging
import requests.exceptions
from homeassistant.components.media_player import MediaPlayerDevice
from homeassistant.components.media_player.const import (
MEDIA_TYPE_MOVIE,
SUPPORT_NEXT_TRACK,
SUPPORT_PLAY,
SUPPORT_PLAY_MEDIA,
SUPPORT_PREVIOUS_T... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from six import iteritems
from . import aci_metrics, exceptions, helpers
class Fabric:
"""
Collect fabric metrics from the APIC
"""
def __init__(self, check, api, instance):
self.check... |
from datetime import timedelta
from feast import Feature, FeatureView, ValueType
from feast.data_source import DataSource
def driver_feature_view(
data_source: DataSource, name="test_correctness"
) -> FeatureView:
return FeatureView(
name=name,
entities=["driver"],
features=[Feature("... |
import contextlib
import operator
import pickle
import sys
from functools import reduce
import numpy as np
import pytest
import scipy.sparse
import scipy.stats
import sparse
from sparse import COO
from sparse._settings import NEP18_ENABLED
from sparse._utils import assert_eq, random_value_array, html_table
@pytest.... |
from direct.showbase import ElementTree as ET
class HTMLTree(ET.ElementTree):
def __init__(self, title):
root = ET.Element('HTML')
ET.ElementTree.__init__(self, root)
head = ET.SubElement(root, 'HEAD')
titleTag = ET.SubElement(head, 'TITLE')
titleTag.text = title
b... |
# -*- coding: utf-8 -*-
r"""
malgan.discriminator
~~~~~~~~~~~~~~~~~
Discriminator (i.e., substitute detector) block for MalGAN.
Based on the paper: "Generating Adversarial Malware Examples for Black-Box Attacks Based on GAN"
By Weiwei Hu and Ying Tan.
:version: 0.1.0
:copyright: (c) 2019 ... |
#1. Numerical Rectangle/Ascending Number
"""
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5 """
n=int(input())
for i in range(0,n):
for j in range(0,5):
if j<4:
print(i+1,end=' ')
else:
print(i+1,end='')
if i<n-1:
print() |
from bookworm import bookworm
if __name__ == "__main__":
bookworm.main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayCommerceEducateAuthenticateCampuscardModifyModel import AlipayCommerceEducateAuthenticateCampuscardModifyModel
c... |
import random
from datetime import timedelta
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Union
from unittest import mock
import ujson
from django.conf import settings
from django.core.exceptions import ValidationError
from django.http import HttpRequest, HttpResponse
from django.utils.timezon... |
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This f... |
from django.apps import AppConfig
class CrowdsecViewsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "crowdsec_views"
|
"""Import and set up the imports_map."""
# The imports_map is special for some build systems, such as Bazel. Each entry
# consists of a short name and a full name; this allows handling build targets
# in a uniform way, with freedom to put the actual file in a different place
# (e.g., if the source tree is read-only ... |
from rest_framework import viewsets, permissions, status
from django.contrib.auth.models import User
from rest_framework.decorators import action
from rest_framework.response import Response
from .serializers import CommentSerializer, PostSerializer, UserSerializer
from content.models import Comment, Post, Upvote
fr... |
from .cli.run import main
if __name__ == '__main__':
import sys
from . import __name__ as module
# `python -m <module>` typically displays the command as __main__.py
if '__main__.py' in sys.argv[0]:
sys.argv[0] = '%s -m %s' % (sys.executable, module)
main() |
import logging
import time
from datetime import datetime
import requests
from oftester.constants import GROUP_ID
from oftester.openflow import basic_flows as flows
HTTP_HEADERS = {'Content-Type': 'application/json'}
class Switch:
def __init__(self, dpid, snake_start_port, snake_end_port, ingress_port,
... |
# -*- encoding: utf-8 -*-
#
# Copyright © 2014-2016 eNovance
#
# 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... |
# -*- coding: utf-8 -*-
# This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import os
import importlib
from viper.common.out import bold
from viper.common.abstracts import Module
from viper.core.session import __sessions__
from viper.common.constant... |
#
# Copyright (c) 2017, Massachusetts Institute of Technology 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 o... |
import gym
import numpy as np
import torch
import torch.optim as opt
from tqdm import tqdm
import gym_puzzle
from agent import Agent
# ハイパーパラメータ
HIDDEN_NUM = 128 # エージェントの隠れ層のニューロン数
EPISODE_NUM = 10000 # エピソードを何回行うか
MAX_STEPS = 1000 # 1エピソード内で最大何回行動するか
GAMMA = .99 # 時間割引率
env = gym.make('puzzle-v0')
agent = Age... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... |
"""
Tests tokenize_big_file function
"""
import unittest
import timeit
from memory_profiler import memory_usage
from lab_2.main import tokenize_big_file
class TokenizeBigFileTest(unittest.TestCase):
"""
Checks for tokenize_big_file function
"""
def test_tokenize_big_file_ideal_case(self):
""... |
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import List
from blspy import G1Element
from peas.types.blockchain_format.sized_bytes import bytes32
from peas.util.byte_types import hexstr_to_bytes
from peas.util.config import load_config, save_config
from peas.util.streamable im... |
# Copyright (c) 2020 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 app... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
## Copyright (c) 2021 Jeet Sukumaran.
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following... |
# -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# MIT License (https://opensource.org/licenses/MIT)
"""STFT-based Loss modules."""
import torch
import torch.nn.functional as F
from distutils.version import LooseVersion
is_pytorch_17plus = LooseVersion(torch.__version__) >= LooseVersion("1.7")
def stft(x... |
from pollbot.i18n import i18n
from pollbot.config import config
def poll_required(function):
"""Return if the poll does not exist in the context object."""
def wrapper(session, context):
if context.poll is None or context.poll.delete is not None:
return i18n.t("callback.poll_no_longer_exi... |
import abc
import copy
import sys
import weakref
import reframe.core.debug as debug
import reframe.core.environments as env
import reframe.core.logging as logging
import reframe.core.runtime as runtime
import reframe.frontend.dependency as dependency
from reframe.core.exceptions import (AbortTaskError, JobNotStartedEr... |
# Copyright (c) 2020 the original author or 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Opera browser history parsers."""
from __future__ import unicode_literals
import unittest
from plaso.parsers import opera
from tests.parsers import test_lib
class OperaTypedParserTest(test_lib.ParserTestCase):
"""Tests for the Opera Typed History p... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Generator of histology report
"""
import logging
logger = logging.getLogger(__name__)
import argparse
import sys
import numpy as np
# import traceback
import copy
import time
sys.path.insert(0, './py/computation')
sys.path.insert(0, '../../')
from fileio import readF... |
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='security-sensor',
v... |
# coding: utf-8
import os
# MONGO
MONGODB_DB = os.environ['OPENSHIFT_APP_NAME']
MONGODB_HOST = os.environ['OPENSHIFT_MONGODB_DB_HOST']
MONGODB_PORT = int(os.environ['OPENSHIFT_MONGODB_DB_PORT'])
MONGODB_USERNAME = os.environ['OPENSHIFT_MONGODB_DB_USERNAME']
MONGODB_PASSWORD = os.environ['OPENSHIFT_MONGODB_DB_PASSWORD'... |
#import tensorflow as tf
#import tensorflow as tf; print(tf.__version__); tf.test.is_gpu_available(cuda_only=False,min_cuda_compute_capability=None)
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import time
cpu_times = []
sizes = [1, 10, 100, 500, 1000, 2000, 3000, 4000, 5000, 8000, 10000]
for size in si... |
# Generated by Django 3.1.1 on 2020-10-25 19:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ramaelectric', '0007_auto_20201024_0030'),
]
operations = [
migrations.AlterField(
model_name='items',
name='arrival... |
import asyncio
import logging
import typing
from ib_async.bar import Bar, BarType
from ib_async.errors import UnsupportedFeature
from ib_async.instrument import Instrument
from ib_async.messages import Outgoing
from ib_async.protocol import RequestId, ProtocolInterface, OutgoingMessage, ProtocolVersion
from ib_async.u... |
# -*- coding: UTF-8 -*-
'''
hdmto scraper for Exodus forks.
Nov 9 2018 - Checked
Updated and refactored by someone.
Originally created by others.
'''
import re
import urllib
import urlparse
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources... |
#!/opt/anaconda3/bin/python
from bs4 import BeautifulSoup
import requests
import ftfy
import glob
import argparse
import os
import jsonlines
def main(args):
# Create the new file. Overwrite if it exits
f = open(args.output_file, "w+")
f.close()
# Get a list of documents in the folder
filelist = ... |
"""
Artoo is a class that interfaces with Slack as a bot user.
To drive Artoo, run 'artoo_driver.py'
Artoo is capable of running python 3 code posted on Slack
within the ```-demarked code tag or within Code Snippets.
On Slack, you can get a description of how to use Artoo
by posting '@artoo help'.
Copyright (c) 201... |
# -*- coding: utf-8 -*-
# @Time : 2020/8/10-17:13
# @Author : 贾志凯
# @File : train.py
# @Software: win10 python3.6 PyCharm
from pysoftNLP.kashgari.corpus import ChineseDailyNerCorpus
from pysoftNLP.kashgari.tasks.labeling import BiLSTM_CRF_Model,BiGRU_CRF_Model,BiGRU_Model,BiLSTM_Model,CNN_LSTM_Model
impo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 2 12:13:12 2022
@author: Thomas Sommerfeld
Class for dealing with Psi4 to Cfour SO mapping/transformation
"""
import numpy as np
class SymOrbs:
"""
SOs for one irrep
each SO is a column; each column has the length of all A... |
import unittest
import solve
class TestSelectSort(unittest.TestCase):
def test_sort_select1(self):
input_list = list()
input_list.append(5)
input_list.append(4)
input_list.append(3)
input_list.append(2)
input_list.append(1)
solve.sort_select(input_list)
... |
'''define the config file for ade20k and Swin-S'''
import os
from .base_cfg import *
# modify dataset config
DATASET_CFG = DATASET_CFG.copy()
DATASET_CFG.update({
'type': 'ade20k',
'rootdir': os.path.join(os.getcwd(), 'ADE20k'),
})
# modify dataloader config
DATALOADER_CFG = DATALOADER_CFG.copy()
# modify opt... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from contextlib import contextmanager
from common.Logger import Logger
class Db:
engine = None
user = None
password = None
port = None
host = None
dbname = None
S... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.io import fits
from regions import CircleSkyRegion
from gammapy.maps import HpxGeom, HpxMap, Hpx... |
# A gui bar chart using multiple liens
# IMPORTS
from graphics import GraphicsWindow
win = GraphicsWindow()
canvas = win.canvas()
canvas.setColor("red")
canvas.drawRect(0, 10, 200, 20)
canvas.setColor("green")
canvas.drawRect(0, 40, 300, 20)
canvas.setColor("blue")
canvas.drawRect(0, 70, 100, 20)
win.wait()
|
import logging
import math
import copy
import os
import pickle
import warnings
from collections.abc import Iterable
import numpy as np
from astropy.io import fits
from astropy.table import Table
from astropy.logger import AstropyUserWarning
import stingray.utils as utils
from .utils import assign_value_if_none, is_s... |
s = input()
l, u, o, e = [], [], [], []
for x in s:
if x.isalpha():
if x.islower():
l.append(x)
else:
u.append(x)
else:
if int(x) % 2 != 0:
o.append(x)
else:
e.append(x)
print(''.join(sorted(l) + sorted(u) + sorted(o) ... |
from __future__ import print_function
import sys
from pyspark import SparkContext
from operator import add
from lib.dwca import Dwca
if __name__ == "__main__":
# rs 00d9fcc1-c8e2-4ef6-be64-9994ca6a32c3, 129 MB .zip, 263 MB uncompressed
# 9.8 s to decompress
archive = Dwca("data/0072bf11-a354-4998-8730-c0... |
#! /usr/bin/env python
#
# Copyright 2018 California Institute of Technology
#
# 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
#
# Unles... |
"""
Example showing how to find all devices from NKT Photonics.
"""
from msl.equipment.resources import NKT
# When installing the SDK a NKTP_SDK_PATH environment variable is created
# and this variable specifies the path of the dll file. However, you
# can also explicitly specify the path of the dll file. For example,... |
from __future__ import absolute_import
from __future__ import print_function
import os
import os.path
from collections import defaultdict
from copy import deepcopy
import datetime
import re
import sys
from xml.sax.saxutils import escape
import yaml
from .constants import XCCDF_PLATFORM_TO_CPE
from .constants import ... |
# Copyright 2019 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 applicab... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from enum import Enum
class CertificatePolicyAction(str, Enum):
"""The supported action types for the lifetime of a certificate"""
email_contacts = "EmailCont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.