content stringlengths 5 1.05M |
|---|
"""
The default bootpeg grammar
"""
from typing import Union
from functools import singledispatch
from ..apegs.boot import (
Value,
Range,
Any,
Empty,
Sequence,
Choice,
Repeat,
And,
Not,
Entail,
Capture,
Transform,
Reference,
Rule,
Clause,
Parser,
Gra... |
from ctypes import c_float
from math import ceil
from pathlib import Path
from pybgfx import bgfx
from pybgfx.utils import as_void_ptr
from pybgfx.utils.shaders_utils import ShaderType, load_shader
from natrix.core.common.constants import TemplateConstants
from natrix.core.fluid_simulator import FluidSimulator
from na... |
class Solution:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
one_bits_counts = [0]
for n in range(1, num + 1):
if n % 2 == 0:
extra = 0
else:
extra = 1
one_bits_counts.append(... |
"""
A very simple yet meaningful optimal control program consisting in a pendulum starting downward and ending upward
while requiring the minimum of generalized forces. The solver is only allowed to move the pendulum sideways.
This simple example is a good place to start investigating explicit and implicit dynamics. T... |
"""
Given a 2-D matrix representing an image, a location of a pixel in
the screen and a color C, replace the color of the given pixel and all adjacent same colored pixels with C.
For example, given the following matrix, and location pixel of (2, 2), and 'G' for green:
B B W
W W W
W W W
B B B
Becomes
B B G
G G G
G G ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
import funcoes as fun
def verifica_escola(texto):
result=""
contador=0
substring1 = "escola"
if substring1 in texto:
result+=substring1+" "
contador+=1
return result,contador
def encontra_esportes(texto):
result=""
c... |
"""
PF = Picture Frame
EW = Eye White
EC = Eye Color
BC = Body Color
OT = OutLine
BG = BackGround
BK = BeaK
CH = Christmas Hat
"""
import random
# color generator for common rarity
def common():
PF = [0, 0, 0]
EW = [255, 255, 255]
EC = [random.randint(0, 250), random.randint(0, 250), random.randint(0, 250... |
# The knows API is already defined for you.
# @param a, person a
# @param b, person b
# @return a boolean, whether a knows b
# def knows(a, b):
class Solution(object):
def findCelebrity(self, n):
"""
:type n: int
:rtype: int
"""
candidate=0
for i in xrange(n):
... |
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import dash_table
import numpy as np
# import functions from .py files
import app_graphing as app_gr
import app_wrangling as app_wr
# load board... |
from plum import dispatch
from plum import dispatch
from netket.utils import struct
from .algorithms import AbstractODEAlgorithm
from .controllers import PIController
##
def default_controller(alg, cache, qoldinit=None):
# if ispredictive(alg): PredictiveController
# if isstandard(alg): IController
bet... |
import config
"""
...
Usage
---------
mongo = mongo('prefix name e.g. myprojectname')
mongo.write_to_*()
"""
class Mongo:
"""
A class used to represent the mongo container
...
Attributes
----------
prefix : str
The prefix applied for all container names
container_name : str
... |
import os
import logging
from datetime import datetime
# This is for the console message printing.
ConsoleLogParm = {
"MsgLevel": logging.INFO,
"MsgFormat": '[%(asctime)s] %(name)s [%(levelname)s] %(message)s',
"DateFormate": '%m/%d %I:%M:%S'
}
# This log file will not be implemented by default.
File... |
b='Hong Pi Geng Nie Kong Zhi Xiao She Yu Jiang Voi Chong Qi Chen Sang Suo Qian Hui Shan E Ci Qiu Ke Ham Weng Zi Ji Mai Da Cuo Manh Chom Lou Kang Kuo Di Qie Mo Guo Hong Chao Hei Gei Gun Zaat Zoeng Cao Zhe Ke Keoi Gun Xu Peng Jue Gan Si Sui Que Wu Yan Peng ... |
from astropy.io import fits
# path_data = ''
import glob
imlist = sorted(glob.glob(f'{path_data}/Calib*NGC*0.fits'))
for inim in imlist:
with fits.open(inim) as hdul:
print(hdul.info()) |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class RACI(LoginRequiredMixin, TemplateView):
template_name = "RACI/RACI.html"
login_url = '/'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return... |
import atexit
import os
import random
import string
import subprocess
import sys
import pytest
class SubprocessIOC:
def __init__(self, ioc_py):
self.pv_prefix = "".join(
random.choice(string.ascii_uppercase) for _ in range(12)
)
sim_ioc = os.path.join(os.path.dirname(__file__),... |
#!/usr/bin/env python
import re
import os
import os.path
import struct
from numpy.fft import rfft
file_re = re.compile(r"([LR])(\-?\d+).*e(\d+)a.dat", re.IGNORECASE)
kemar = {}
for dirpath, _dn, files in os.walk("full"):
for fname in files:
#print dirpath, fname
m = file_re.match(fname)
if not m:
continue... |
from pygmy.model import *
from pygmy.config import config
from pygmy.database.sqlite import SqliteDatabase
from pygmy.database.postgresql import PostgreSQLDatabase
from pygmy.database.mysql import MySQLDatabase
from pygmy.database.base import Model
class DatabaseFactory:
@staticmethod
def create():
"... |
# RemovedInDjango50Warning.
from django.core.serializers.base import (
PickleSerializer as BasePickleSerializer,
)
from django.core.signing import JSONSerializer as BaseJSONSerializer
JSONSerializer = BaseJSONSerializer
PickleSerializer = BasePickleSerializer
|
"""
The solver for training
"""
import tensorflow as tf
import numpy as np
import logging
from time import time
from os import path, makedirs
from model import *
from train400_data import *
from ops import *
from utils import *
flags = tf.app.flags
conf = flags.FLAGS
class Solver(object):
def __init__(self):
... |
from telegram_bot_sdk.telegram_objects.sticker import Sticker
class StickerSet:
"""This class represents a sticker set
:param name: Sticker set name
:type name: str
:param title: Sticker set title
:type title: str
:param is_animated: True, if the sticker set contains animated stickers
:ty... |
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name
"""Tests for the ``PdosWorkChain.get_builder_from_protocol`` method."""
from aiida.engine import ProcessBuilder
from aiida.plugins import WorkflowFactory
import pytest
from aiida_quantumespresso.common.types import ElectronicType, SpinType
PdosWorkChain =... |
#97% Accuracy on 2 epoch
from keras.datasets import mnist
import tensorflow.keras as keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, BatchNormalization, Conv2D, MaxPooling2D
from keras.utils import normalize
from keras.callbacks import TensorBoard
import matplotlib.pyplot as... |
#!/usr/bin/python
"""
Build a simple network from scratch, using mininet primitives.
This is more complicated than using the higher-level classes,
but it exposes the configuration details and allows customization.
For most tasks, the higher-level API will be preferable.
"""
import csv
import sys
import time
from mini... |
import datetime
from tkinter import font
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mpl_dates
from mplfinance.original_flavor import candlestick_ohlc
import pandas as pd
def candlestick_plot(data):
data_clean = {"Date": [], "Open": [], "High": [], "Low": [], "Close": []}
... |
'''
Descripttion:
version:
Author: zpliu
Date: 2021-07-01 11:18:14
LastEditors: zpliu
LastEditTime: 2021-07-01 11:18:16
@param:
'''
|
from ascntr.cli import cli
def test_simple_call(cli_runner, oracle_dsn, target_dsn):
pass
|
import torch
import src
MAX_TRIES = 100
EPS = 1e-8
def lipschitz_max_grad(net, X_observe, X_target, Y_target, k=1):
'''
Description:
Penalizes the model if it does not have a K-Lipschitz
maximum gradient-norm for any interpolant between samples
from the target and observed distribut... |
from django.db import models
class Instances(models.Model):
channelId = models.UUIDField
channelName = models.TextField()
def __str__(self):
return "%s" % (self.channelId) |
import numpy as np
class NotInVocabularyError(Exception):
"""Auxillary class."""
pass
class GloVeDataIterator():
"""
Args:
get_text_iterator: Callable that returns an iterator that yields
text, as a list of words (strings).
window_size: Positive integer.
min_word_... |
"""
rasters.py includes code to work with raster datasets,
particularly to sample raster using a PrmsDiscretization
object and then use it as input data
"""
import numpy as np
class Rasters(object):
"""
Raster object which allows the user
to snap a raster to a grid.
Parameters
-----... |
expected_output = {
"services-accounting-information": {
"flow-aggregate-template-detail": {
"flow-aggregate-template-detail-ipv4": {
"detail-entry": [{
"byte-count": "184",
"input-snmp-interface-index": "1014",
"mpls-la... |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
import os
from django.conf import settings
from django.core.management import BaseCommand
from django_test_tools.generators.crud_generator import GenericTemplateWriter
from django_test_tools.generators.model_generator import FactoryBoyGenerator
from ...app_manager import DjangoAppManager
PRINT_IMPORTS = """
import s... |
import os
import numpy as np
#---#
# import cv2
# from scipy import ndimage
import imageio
#---#
import matplotlib.pyplot as plt
# data_path = '/opt/carnd_p3/data/' # On GPU-enabled workspace
data_path = '~/opt/carnd_p3/data/' # On local machine
# Expand the path
data_path = os.path.expanduser(data_path)
# The im... |
"""
Команда, которая показывает, что бот работает
"""
from time import time
import json
import platform
import psutil
from random import randint
from datetime import datetime
import sys
from vkbottle.bot import Blueprint, Message
from utils.edit_msg import edit_msg
from filters import ForEveryoneRule
... |
#!/usr/bin/python
print("Hello World")
print("Added line from src2")
print("Added line from src1")
import bar
import baz
|
# -*- coding: utf-8 -*-
# @Author: Muhammad Alfin N
# @Date: 2021-03-30 20:13:14
# @Last Modified by: Muhammad Alfin N
# @Last Modified time: 2021-04-07 18:38:41
import numpy as np
import imageio
import random
import torch
import PIL
import os
import cv2
import time
import pyrebase
from models import get_instru... |
from kangrouter import KangRouterClient
import time
import os
apiKey = os.environ["API_KEY"]
licenseId = os.environ["LICENSE_ID"]
problem = {
"nbResources": 3,
"jobs": [
{
"jobId": "Job01",
"origLat": "38.674921",
"origLon": "-9.175401",
"destLat": "38.716860",
"destLon": "-9.16... |
# -*- coding: utf-8 -*-
import urlparse
from nose.tools import * # flake8: noqa
from tests.base import ApiTestCase
from tests.factories import AuthUserFactory
from api.base.settings.defaults import API_BASE
class TestUsers(ApiTestCase):
def setUp(self):
super(TestUsers, self).setUp()
self.user... |
#!/bin/python3
import math
import os
import random
import re
import sys,array
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
k1=s-a
k2=b-t
c1=0
c2=0
m=apples.__len__()
n=oranges.__len__()
for i in range(m):
if(apples[i]>... |
import inspect
import io
import multiprocessing
import os
import socket
import sys
import tempfile
import time
import unittest
import requests
import uvicorn
from dijkstar.graph import Graph
from dijkstar.server import utils
from dijkstar.server.client import Client
from dijkstar.server.conf import settings
class T... |
from .base import BaseEmbedding
from .feature_embedding import FeatureEmbedding
from .tabtransformer_embedding import TabTransformerEmbedding
|
# TODO: wird alle 30 minuten vom Main angekickt
# imports
from database import session, Strings, strings, String1, string1, String2, string2, String3, string3, Panels, panels
import time
# import quick2wire.i2c as i2c
import serial_interface
import threading
class InputHandler(threading.Thread):
def __init__(sel... |
from .CountingGridModel import CountingGridModel
from .CountingGridModelWithGPU import CountingGridModelWithGPU
__all__ = ['CountingGridModel', 'CountingGridModelWithGPU']
|
import ijson
import pickle
import csv
import os
import sys
import gc
import time
from numpy import random
# Path to the 12gb arxiv dataset
path_dataset = "..\data\dblp.v12.json"
path_dataset_cities = "..\data\cities15000.txt"
# Path were we will store the dataset as a python dict
#path_pickled_dataset = "..\data\dbl... |
from torch.utils.tensorboard import SummaryWriter
class Logger:
def __init__(self, log_dir, logging_interval):
self.writer = SummaryWriter(log_dir)
self.logging_interval = logging_interval
self.counter = 0
@classmethod
def from_config(cls, config, name):
log_dir = config.l... |
"""
https://pythontutor.com/visualize.html#code=class%20Solution%3A%0A%20%20%20%20def%20duplicateZeros%28self,%20arr%29%20-%3E%20None%3A%0A%20%20%20%20%20%20%20%20%22%22%22%0A%20%20%20%20%20%20%20%20Do%20not%20return%20anything,%20modify%20arr%20in-place%20instead.%0A%20%20%20%20%20%20%20%20%22%22%22%0A%20%20%20%20%20%... |
"""
Unit tests for data_collections module
"""
import unittest
import pytest
from sentinelhub import DataCollection, TestSentinelHub, SHConfig
from sentinelhub.constants import ServiceUrl
from sentinelhub.data_collections import DataCollectionDefinition
from sentinelhub.exceptions import SHDeprecationWarning
class ... |
# 读写数据
import pickle
import os
from plugins import getNow
from plugins import logManage
key_allow: list = [
'#', '*',
',', ',',
'.', '。',
'!', '!',
'?', '?',
':', ':',
';', ';',
'+',
'-',
'/'
]
def save_obj(obj, name: str) -> None:
filePath = name + '.data'
with ope... |
#!/usr/bin/env python
import argparse
import gzip
import os
from collections import OrderedDict
import yaml
from Bio.SeqIO.QualityIO import FastqGeneralIterator
OUTPUT_DBKEY_DIR = 'output_dbkey'
OUTPUT_METRICS_DIR = 'output_metrics'
def get_sample_name(file_path):
base_file_name = os.path.basename(file_path)
... |
import os
import torch
from .base_synthesizer import BaseSynthesizer
class SwapSynthesizer(BaseSynthesizer):
@staticmethod
def add_commandline_args(parser):
return parser
def prepare_synthesis(self):
print("Preparing swapping visualization ...")
if self.folders i... |
"""Taskrunners"""
from .base import Taskrunner
from .coroutine import CoroutineTaskrunner
from .decorators import as_task
from .multi_dispatch import TaskDispatcher
from .multiprocess import MultiprocessTaskrunner
from .store_writer import StoreTaskWriter
from .store_reader import StoreTaskReader
from .thread import T... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import re
class LogcatSymbolicator(object... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
print 'os.name =',os.name
print 'os.uname=',os.uname()
print 'os.environ=',os.environ
print 'os.getenv(path)=',os.getenv('path')
#操作文件和目录的函数一部分在os中,一部分在os.path中
#查看当前目录的绝对路径
print '查看当前目录的绝对路径',os.path.abspath('.')
#在某个目录下面创建一个新目录
#首先先把要创建的新目录的完整路径写出来:
os.path.jo... |
from manimlib_cairo.imports import *
class Logo(VGroup):
CONFIG = {
'color_1': [WHITE, BLUE_B, BLUE_D],
'color_2': [WHITE, '#C59978', '#8D5630'],
# 'color_3': [average_color("#CCCCCC", BLUE_C), BLUE_C, BLUE_D],
# 'color_4': [average_color("#CCCCCC", "#C59978"), '#C59978', '#8D5630... |
path = "~/.calendars/*"
default_list = "Tasks"
date_format = "%d/%m/%Y"
time_format = "%H:%M"
default_due = 0
|
#!/usr/bin/python
import SocketServer, SimpleHTTPServer, argparse, json
parser = argparse.ArgumentParser()
parser.add_argument('--port', '-p', type=int, default=8008)
parser.add_argument('--log-request-body', action='store_true', default=False)
args = parser.parse_args()
class HTTPHandler(SimpleHTTPServer.SimpleHTTP... |
class circle():
def __init__(self,r):
self.radius = r
def circumference(self):
return self.radius*2*3.14
def area(self):
return self.radius**2*3.14
def volume(self):
return self.radius**3*(4/3)*3.14
x = circle(3)
print x.area()
print x.circumference()
print x.volume(... |
"""
This plugin does not perform ANY test: The aim is to visit all URLs grabbed so far and build
the transaction log to feed data to other plugins
NOTE: This is an active plugin because it may visit URLs retrieved by vulnerability scanner spiders
which may be considered sensitive or include vulnerability probing
"""
f... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 12 17:39:48 2022
@author: marco
"""
import pandas as pd
import numpy as np
import os
from scipy.linalg import pinv as pinv
from scipy.linalg import inv as inv
from sklearn.preprocessing import PolynomialFeatures
os.chdir('C://Users//marco//Desktop//Projects'... |
from django.db import models, transaction
from projects.models import Project
from organizations.models import Organization
class WorkstreamType(models.Model):
name = models.CharField(max_length=50)
organization = models.ForeignKey(Organization, null=True, on_delete=models.CASCADE)
def __str__(self):
... |
import os
import reprint
from fields.map import Map
from towers.tower import tower_dict, get_tower_info
from waves.monsters import PassedTheGateError
from waves.wave import EasyWave, HeavyWave
class Game:
def __init__(self):
self.gold = 100
self.lives = 30
self.points = 0
self.ma... |
from typing import Optional
from pydantic import BaseSettings, Field
class Config(BaseSettings):
ENVIRONMENT: str = Field(None, env="ENVIRONMENT")
JWT_SECRET: Optional[str]
DATA_HOST: Optional[str]
TPV: Optional[str]
TPV_USER: Optional[str]
TPV_CORE: Optional[str]
class Config:
e... |
#this function will return the price with a %10 discount
def discount(price):
result = 0.95*(price)
# print("price=%f, result=%f", price, result)
return result |
from __future__ import print_function
from collections import deque
class TrainEarlyStopOnLosses(object):
"""Estimate if early stop conditions on losses fullfiled
"""
def __init__(self, stop_conditions, max_mem, stop_on_all_conditions):
"""Initialize the TrainEarlyStopOnLosses( class
Param... |
#!/usr/bin/env python3
#
# huecon.py
#
# Interactive command line Hue console
#
import argparse
import os
import sys
import config
import hue
import cli
# Config file location
CONFIG_FILE = os.path.expanduser("~/.huecon")
CLI_HISTORY_FILE = os.path.expanduser("~/.huecon_history")
CLI_DEF = {
"show|:Show various ... |
"""Train dann."""
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from core.test import test
from core.test_weight import test_weight
from utils.utils import save_model
import torch.backends.cudnn as cudnn
import math
cudnn.benchmark = True
def weight(ten, a=10):
a = torch.tenso... |
# Copyright (c) 2017-present, Facebook, 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... |
import email
@then(u'my details should match')
def step_impl(context):
context.execute_steps(u'''
Then I should see "$first_name"
And I should see "$last_name"
And I should see "$contact_number"
And I should see "$email"
''')
@when(u'I confirm and submit my plea')
def step_im... |
#!/usr/bin/python
'''
'''
from ansible.module_utils.basic import AnsibleModule
from Crypto.Cipher import AES
#from Crypto.Util.Padding import pad, unpad
from Crypto import Random
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import base64, os, random, tarfile, struct
ANSIBLE_METADATA = {
... |
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
import unittest
from mock import Mock, patch
from django.contrib.auth.models import User
from datawinners.accountmanagement.models import NGOUserProfile
from datawinners.alldata import helper
from datawinners.alldata.helper import get_all_project_for_user
from datawinners.pro... |
from clld.web.maps import ParameterMap, Map
class NumeralParameterMap(ParameterMap):
def get_options(self):
return {
'base_layer': 'Esri.WorldPhysical',
'icon_size': 15,
'max_zoom': 9,
'hash': True,
}
class NumeralLanguagesMap(Map):
def get_opt... |
#!/usr/bin/env python3
#
# Copyright 2022 Graviti. Licensed under MIT License.
#
"""Parameter type releated classes."""
from typing import TYPE_CHECKING
from typing import Any as TypingAny
from typing import Dict, List, Sequence, Tuple, Type, Union
from graviti.portex.base import PortexType as ClassPortexType
from g... |
# Random utility functions.
import itertools
# Flatten a list of lists, e.g. [[1, 2], [3, 4]] => [1, 2, 3, 4].
def flatten(l):
return list(itertools.chain.from_iterable(l)
|
import time
import numpy as np
import pandas as pd
from research.gpq.icinco_demo import evaluate_performance
from ssmtoybox.mtran import UnscentedTransform
from ssmtoybox.ssinf import ExtendedKalman, ExtendedKalmanGPQD
from ssmtoybox.ssmod import UNGMTransition, UNGMMeasurement
from ssmtoybox.utils import GaussRV
st... |
from functools import partial
import numpy as np
from modAL.batch import uncertainty_batch_sampling
from modAL.models import ActiveLearner
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
# Set our RNG for reproducibility.
RANDOM_STATE_SEE... |
import numpy as np
from det3d.core.bbox import box_np_ops
from det3d.core.sampler import preprocess as prep
from det3d.builder import build_dbsampler
from det3d.core.input.voxel_generator import VoxelGenerator
from det3d.core.utils.center_utils import (
draw_umich_gaussian, gaussian_radius)
from ..registry import P... |
class Config(object):
from datetime import timedelta
SECRET_KEY = 'OVERRIDE THIS WITH A SECURE VALUE in instance/config.py!'
CELERY_BROKER_URL = 'redis://'
CELERY_RESULT_BACKEND = 'redis://'
CELERY_ACCEPT_CONTENT = ['pickle']
CELERYBEAT_SCHEDULE = {
'update-agencies-every-week': {
... |
# Copyright 2015 Geoscience Australia
#
# 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 la... |
import datetime
import dateutil.tz
import numpy as np
import numpy.testing
import pytest
import cara.data.weather as wx
def test_nearest_wx_station():
melbourne_lat, melbourne_lon = -37.81739, 144.96751
station_rec = wx.nearest_wx_station(longitude=melbourne_lon, latitude=melbourne_lat)
station_name = ... |
from decimal import Decimal
from django.db.models import Q
from .models import CustomerInfo
import re
import zenhan
def ExtractNumber(org_str, data_type):
"""
引数で渡された文字列を半角に変換し、数字のみを抽出して返す。
param: org_str。例:'(0120)123-456
param: data_type。例:1=電話番号用、2=郵便番号用、3=法人番号用
return: org_strから数字のみを抽出した文字列。例:... |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and rel... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
import socket
from scplib import *
from iplugin import Plugin
from icommand import *
from state import *
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8888
listen_sock_dict = {}
server_sock_dict = {}
client_sock_dict = {}
class Co... |
from unittest import TestCase
from piccolo.columns import Varchar
from piccolo.table import create_table_class
class TestCreateTableClass(TestCase):
def test_create_table_class(self):
"""
Make sure a basic `Table` can be created successfully.
"""
_Table = create_table_class(class_... |
import py_midicsv as pm
import numpy as np
import pandas as pd
import librosa
import matplotlib.pyplot as plt
from PIL import Image
import warnings
class Generated_Song:
def __init__(self, song_length=10000):
'''Break data into metadata, midi data, and end track data'''
self.meta_data = ['0, 0, He... |
from inspect import stack, getframeinfo,getsource
from colorama import Fore,init
from datetime import datetime
# Before reading code u should know
# -> getframeinfo(stack()[1][0]) function getting data about used code line and
# -> that why we can get debug of a code part from program
white=Fore.LIGHTWHITE_E... |
# sqlite3: SQLite 데이터베이스용 DB-API 2.0 인터페이스
# SQLite는 별도의 서버 프로세스가 필요 없고 SQL 질의 언어의 비표준 변형을 사용한다.
# 데이터베이스에 액세스할 수 있는 경량 디스크 기반 데이터베이스를 제공하는 C 라이브러리이다.
# 일부 응용 프로그램은 내부 데이터 저장을 위해 SQLite를 사용할 수 있다.
# 자세한 내용은 파이썬 공식 문서의 "sqlite3 — SQLite 데이터베이스용 DB-API 2.0 인터페이스"를 참고하면 된다.
# 파이썬 sqlite3 공식 문서 링크: https://docs.pyth... |
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QSlider, QWidget, QLabel, QPushButton
from src.common.QssHelper import QssHelper
class Style(object):
@staticmethod
def init_footer_style(slider_volume: QSlider, footer: QWidget, volume: int, btn_zoom: QPushButton... |
# -*- coding: utf-8 -*-
# Copyright 2009-2017 Yelp and Contributors
#
# 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... |
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description: 生成仿真评论
"""
import os
from textgen.unsup_generation.phrase import load_list, caculate_word_idf, text2review, find_word_phrase, get_seg_pos
from textgen.unsup_generation.util import text2seg_pos, get_aspect_express, get_candidate_aspect, \
mer... |
# -*- coding: utf-8 -*-
# Copyright 2019 The Blueoil 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
#
# Unles... |
import nltk
import pickle
import random
from nltk.classify import ClassifierI
from nltk.classify.scikitlearn import SklearnClassifier
from nltk.corpus import movie_reviews
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from sklearn.naive_bayes import GaussianNB
from ... |
"""Module allowing for ``python -m lexos ...``."""
from lexos import application
application.run()
|
"""Tools for getting spectra for lya fitting.
Includes choosing a data file for each star, reading the files, and
processing the spectral data (from either IUE, STIS, ...) into a format
that can be used directly for the fitting.
The variable target_use_which_spectrum indicates which data to use for
each star. It can ... |
# %% [markdown]
# # Models and Ensembling Methods
# %% [markdown]
# ## Import dependencies
import numpy
from gensim.models import word2vec
from gensim.models import KeyedVectors
import pandas
from nltk import WordPunctTokenizer
from sklearn.preprocessing import label_binarize
import sqlite3
from sklearn.multiclass imp... |
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from copy import deepcopy
from UI.app import app
from UI.pages import (
data_upload,
problem_formulation,
train_model,
optimize,
navigat... |
MESSAGE_TEXT='**Official Store:** https://shop.safemoon.net'
def store(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text=MESSAGE_TEXT , parse_mode='markdown', disable_web_page_preview='True')
|
import random as r
from termcolor import cprint
CHARSLIST = list("#@&\"'§!°-_*$`%=+/:;.,?^|<>{}[]()")
ACTIONS = {
'=':'Assign a value',
':':'Specify a type',
'<':'Start cast to a type',
'>':'End cast to a type',
'[':'Start a list',
']':'End a list',
'ö':'Start a dict',
'ë':'End a dict',
'°':'End a d... |
import time
start_time = time.time()
import json, yaml
import pandas as pd
import numpy as np
import redacted_logging as rlog
logger = rlog.get_logger(__name__)
#read input file
try:
with open(r'/inputVolume/security_input.yaml') as file:
inputYAML = yaml.load(file, Loader=yaml.FullLoader)
logger.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.