content stringlengths 5 1.05M |
|---|
from AccessControl import ClassSecurityInfo
from DateTime import DateTime
from Products.ATContentTypes.content import schemata
from Products.Archetypes import atapi
from Products.Archetypes.public import *
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import safe_unicode
from bika.lims i... |
# Copyright 2012, Intel, 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 agree... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from .choices import *
class User(AbstractUser):
email = models.EmailField(null=True, default=None)
USER_TYPE = (
('st', 'Студент'),
('com', 'Компания'),
('unv', 'Университет')
)
user_type = mod... |
tile_colors = {}
for _ in range(400):
path = input()
i = 0
pos_north = 0.0
pos_east = 0.0
while i < len(path):
if path[i] == 'e':
pos_east += 1.0
i += 1
elif path[i] == 'w':
pos_east -= 1.0
i += 1
elif path[i] == 'n' and path... |
#!/usr/bin/env python
__author__ = "Mageswaran Dhandapani"
__copyright__ = "Copyright 2020, The Spark Structured Playground Project"
__credits__ = []
__license__ = "Apache License"
__version__ = "2.0"
__maintainer__ = "Mageswaran Dhandapani"
__email__ = "[email protected]"
__status__ = "Education Purpose"
impo... |
from stack import *
class MinStack:
def __init__(self):
self.dataStk = ArrayStack()
self.minStk = ArrayStack()
def pop(self):
data = self.dataStk.pop()
if data == self.minStk.peek():
self.minStk.pop()
return data
def push(self, val):
if not sel... |
import pytest
import json
import bionic as bn
from bionic import interpret
from bionic.utils.urls import (
path_from_url,
is_file_url,
is_gcs_url,
)
class CacheTester:
"""
A helper class for testing changes to Bionic's cache.
Tracks the current and previous states of the Cache API, allow us... |
from math import log, sqrt
from numpy import exp, linspace, fft, array, arange, pi
import matplotlib.pyplot as plt
i = complex(0, 1)
# model parameters
T = 1
H_original = 90.0 # limit
K_original = 100.0 # strike
r_premia = 10 # annual interest rate
r = log(r_premia/100 + 1)
V0 = 0.316227766
sigma = V0
gamma = r - 0.5 *... |
"""Integration tests for the pyWriter project.
Test the conversion of the chapter descriptions.
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
from pywriter.html.html_chapterdesc import HtmlChapterDesc
fr... |
from os.path import join
from jpype import JClass, JString, getDefaultJVMPath, shutdownJVM, startJVM
def Normalize(query):
ZEMBEREK_PATH: str = join('Zemberek','bin', 'zemberek-full.jar')
startJVM(
getDefaultJVMPath(),
'-ea',
f'-Djava.class.path={ZEMBEREK_PATH}',
convertStrin... |
"""
Vertically partitioned SplitNN implementation
Worker 1 has two segments of the model and the Images
Worker 2 has a segment of the model and the Labels
"""
import torch
from torch import nn
import syft as sy
hook = sy.TorchHook(torch)
class SplitNN:
def __init__(self, models, optimizers):
self.mod... |
import sys
import json
import pprint
import os
from prism_building import Prism_Building
from present import Present
def main():
#box_perimeter_core("../cuboid-idf-test/box_perimeter_core_100_200_15.idf", 100, 200, 15, 5, True)
#L_shaped_perimeter_core("../cuboid-idf-test/L_perimeter_core_100_200_15.idf", 10... |
# Generated by Django 3.1.3 on 2021-01-01 18:33
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0036_auto_20201231_1205'),
]
operations = [
migrations.AlterField(
model_name='mentor',
... |
# Download the Python helper library from twilio.com/docs/libraries/python
from datetime import date
from twilio.rest import TwilioRestClient
# Your Account Sid and Auth Token from twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid... |
import pytest
from gaphor import UML
from gaphor.core.modeling import ElementFactory
from gaphor.plugins.xmiexport.exportmodel import XMIExport
@pytest.fixture
def element_factory():
ef = ElementFactory()
ef.create(UML.Package).name = "package"
c1 = ef.create(UML.Class)
c1.name = "class"
c2 = ef.... |
import logging
import re
import shutil
from pathlib import Path
import pdfplumber
import requests
from bs4 import BeautifulSoup
from openpyxl import load_workbook
from .. import utils
from ..cache import Cache
__authors__ = ["zstumgoren", "Dilcia19", "ydoc5212"]
__tags__ = ["html", "pdf", "excel"]
logger = logging.... |
#import nbformat
from nbparameterise import (extract_parameters, replace_definitions,parameter_values)
import notebooktoall.transform as trans
#with open("masso.ipynb") as f:
# nb = nbformat.read(f,as_version=4)
#orig_parameters = extract_parameters(nb)
#params = parameter_values(orig_parameters, filename = './da... |
# Generated by Django 3.2 on 2022-02-01 07:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0004_remove_goods_d... |
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
FIELDS = ['first_name', 'last_name', 'email', 'username', ]
class RegistrationForm(UserCreationForm):
"""
Customise the User Registration form from default Django UserCreationForm
"""
class Meta:
... |
import asyncio
from process_pixel import get_global_opacity, process_pixel, set_global_opacity
def off(strip):
for i in range(strip.numPixels()):
strip.setPixelColor(i, process_pixel(0))
strip.show()
async def off_animated(strip):
opacity = get_global_opacity()
for i in range(10, ... |
# Copyright 2016 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.
from recipe_engine import recipe_api
class PresubmitApi(recipe_api.RecipeApi):
@property
def presubmit_support_path(self):
return self.package_repo_... |
from __future__ import absolute_import, division, print_function
import sys
import h5py
import numpy as np
from scitbx import matrix
from scitbx.array_family import flex
from dxtbx.format.Format import Format
from dxtbx.format.FormatHDF5 import FormatHDF5
from dxtbx.format.FormatStill import FormatStill
class For... |
class Solution:
def winnerOfGame(self, colors: str) -> bool:
if len(colors) < 3:
return False
Alice = 0
Bob = 0
for i in range(1, len(colors)-1):
if colors[i-1] == colors[i] and colors[i] == colors[i+1]:
if colors[i] ... |
import json
from pathlib import Path
import pygame
from tkinter import filedialog
import objects as object_types
from settings import SCREEN_DIMS, WINDOW_CONST
class roomObject():
def __init__(self,
color = (0, 0, 255, 1),
rect = None, # or (x, y, w, h)
circle = ... |
import asyncio
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
from ....config.injection_context import InjectionContext
from ....utils.stats import Collector
from ...outbound.message import OutboundMessage
from ..http import HttpTransport
class TestHttpTransport(AioHTTPT... |
from analysis import makefigure
#from analysis import analysis
#from analysis import classdef
makefigure.makeSnap(datfile="TEST/snap000005.dat", pngfile="ae.png", bHeader=True)
|
import unittest
class TestJobExecutionOrder(unittest.TestCase):
# can actually execute in a number of different ways
# just need certain rules to hold with respect to the order
# A before F, G
# B, C before F
# F before H, I
# D before G before I
def order_checks(self, exec_order):
... |
from .handler import Handler
|
from z80 import util, io, gui, registers, instructions
import copy
from time import sleep, time
import sys
from PySide.QtCore import *
from PySide.QtGui import *
import threading
#logging.basicConfig(level=logging.INFO)
class Z80SBC(io.Interruptable):
def __init__(self):
self.registers = registers.Regi... |
# simple statistics module
import resource
def _systemtime ():
ru_self = resource.getrusage (resource.RUSAGE_SELF)
ru_ch = resource.getrusage (resource.RUSAGE_CHILDREN)
return ru_self.ru_utime + ru_ch.ru_utime
class Stopwatch:
""" A stop watch """
def __init__ (self):
self._started = 0
self._finish... |
# -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
from bs4 import BeautifulSoup
class PaginationController(Controller):
def get(self):
self.test_simple_1()
self.test_simple_2()
self.test_all()
self.test_first_page()
self.test_last_page()
... |
import util
def solve(input_path):
with open(input_path) as f:
line_points = tuple(util.completion_score(s.rstrip()) for s in f)
positive_points = tuple(filter(lambda s: s > 0, line_points))
return sorted(positive_points)[int(len(positive_points) / 2)]
if __name__ == '__main__':
print(solve('input... |
# 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, software
# distributed under t... |
# coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import re
from contextlib import contextmanager
from pants.base.revision import Revision... |
"Test for Range Query"
from progressivis.table.constant import Constant
from progressivis.table.table import Table
from progressivis import Print
from progressivis.stats import RandomTable, Min, Max
from progressivis.core.bitmap import bitmap
from progressivis.table.range_query import RangeQuery
from progressivis.util... |
import fw
class Magnifier(fw.Gen):
def gen(self, x, y):
wid = 2
xx, yy = x // wid, y // wid
v = (xx + yy) % 3
# print (xx, yy, v)
if v == 0:
return 0
elif v == 1:
return 128
else:
return self.maxval
if __name__ == "__mai... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
GeodesicDensifier
A QGIS plugin
Adds vertices to geometry along geodesic lines
-------------------
begin : 2018-02-21
g... |
# Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines.
import xlwt
'''workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
borders = xlwt.Borders... |
# 학습 데이터 불러오고 전처리하기
import pandas as pd
import itertools
# 1. 1차연도 어노테이터들이 적은 문장
music_by_numbers = pd.read_excel('./music_by_numbers.xlsx', engine='openpyxl')
dance_by_numbers = pd.read_excel('./dance_by_numbers.xlsx', engine='openpyxl')
visual_by_numbers = pd.read_excel('./visual_by_numbers.xlsx', engine='openpyxl')... |
from .models import Question, Option
from .serializers import QuestionSerializer, OptionSerializer, UserSerializer
from django.http import Http404
from django.contrib.auth.models import User
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.response import Response
from r... |
from __future__ import annotations
from collections import OrderedDict
import torch
from torch.utils.data import Dataset, DataLoader
from torch import Tensor
from functools import partial
from typing import Sequence, Union, Any, List, Iterable, Optional, TypeVar, Dict
from imagenet.definitions_and_structures import D... |
import numpy as np
from typing import Union, List, Dict, Iterable, Tuple, Callable
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import scipy.special as scsp
class Mesh:
def __init__(self, mesh_length=500, mesh_width=500, cellsize=2.e-6, mixed=False, label='None'):
... |
import asyncio
from aiohttp import web
import sys
import socketio
import pandas as pd
import ocakdeneme
import base64
sio = socketio.AsyncServer(async_mode='aiohttp',cors_allowed_origins="*")
app = web.Application()
sio.attach(app)
async def background_task():
"""Example of how to send server generated events ... |
'''
Generic Device class for HLTAPI-based devices.
'''
__all__ = (
'Device',
)
from enum import Enum
import contextlib
import functools
import itertools
import logging
import time
try:
from hltapi.exceptions import HltapiError
except Exception:
class HltapiError(Exception):
pass
from genie.de... |
from __future__ import absolute_import, division, print_function
import numpy as np
from cs231n.layers import *
from cs231n.layer_utils import *
class TwoLayerNet(object):
"""
A two-layer fully-connected neural network with ReLU nonlinearity
and softmax loss that uses a modular layer design. We assume a... |
from django.urls import path, re_path, include
from app1 import views
urlpatterns = [
path('video', views.VideoView.as_view())
]
|
import time
import datetime
def stringify(dt):
return time.strftime("%Y-%m-%d %H:%M:%S",dt.timetuple())
def parse(s):
return datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
|
from flask import render_template, request, redirect, url_for, abort
from . import main
from ..models import User,Pizza,Roles,Topping,Crust
from flask_login import login_required,current_user
@main.route('/user/<uname>')
def profile(uname):
user = User.query.filter_by(username = uname).first()
if user is Non... |
from env import Maze
from agent import QLearningTable
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
episode_count = 1000 # Number of episodes to run the experiment
episodes = range(episode_count)
movements = [] # Number of movements happened in each episode
rewards = [] # The gained reward ... |
import os
from pathlib import Path
from kombu import Queue
from celery.app.base import Celery
from dotenv import load_dotenv
PACKAGE_PARENT = '.'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
env_path = Path('./') / '.env'
load_dotenv(dotenv_path=env_path)
que... |
""" MIDI-like encoding method similar to ???
Music Transformer:
"""
from typing import List, Tuple, Dict, Optional
import numpy as np
from miditoolkit import Instrument, Note, TempoChange
from .midi_tokenizer_base import MIDITokenizer, Event, detect_chords
from .constants import *
class MIDILikeEncoding(MIDIToken... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, René Moser <[email protected]>
# 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',
... |
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
import matplotlib.pylab as plt
import sys
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from scipy import interpolate
from os import makedirs
from os.path import exists
from vampy import vamplot
from vampy import utils
... |
import os
import numpy as np
from six.moves import cPickle
from tensorflow import keras
import helper
from tfomics import utils, explain
#------------------------------------------------------------------------
num_trials = 10
model_names = ['cnn-dist', 'cnn-local']
activations = ['relu', 'exponential', 'sigmoid', 't... |
from .. import base # pylint: disable=unuse-import
class BaseAliyunApi:
""" Aliyun base class"""
def __init__(self, client=None):
self.client = client # type: base.BaseAliyunClient
|
import yaml
import os.path
from kubernetes import client, config, utils
#############################################################################################
# Following prints a list of all SAS models both active/running and inactive/ready_for_scoring
#
def list_knative_models(kubeconfig_path,k8s_namespace, k... |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-11-30 16:32:47
# @Last Modified by: 何睿
# @Last Modified time: 2019-11-30 16:44:05
from collections import defaultdict
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
window_count = defaultdict(int)
... |
import os
import subprocess
dir_path = os.path.dirname(os.path.realpath(__file__))
def run(redis_url=None):
env = os.environ.copy()
if redis_url is not None:
env['REDIS_URI'] = redis_url
return subprocess.Popen(['python', os.path.join(dir_path, 'extractor.py')], env=env)
|
import torch.nn as nn
class FeatureExtractor(nn.Module):
"""Extracts feature vectors from VGG-19"""
def __init__(self, model, i, j):
super().__init__()
maxpool = [4, 9, 18, 27, 36]
layer = maxpool[i-1]-2*j
self.features = nn.Sequential(*list(model.features.children())[:(layer+... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import socket
import datetime
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
f=open('udp','w')
try:
server_address = ('0.0.0.0', 10000)
sock.bind(server_address)
f.writelines('Watching %s:%s\n' % server_a... |
import torch
####################################################################################################################################################
# Context-aware loss function
############################################################################################################################... |
'''
An unnecessarily complex implementation of a heap data structure.
'''
from .binary_tree import BinaryNode, BinaryTree
from operator import le, ge
def _comparisonFactory(comparisonFunction):
def compareNodes(node1, node2):
if node1 is None:
return node2
if node2 is None:
... |
import pandas as pd
import numpy as np
import re
df = pd.read_csv('csv/location.csv')
df['lat_lon'] = df['location'].apply(lambda x : re.findall('(\d{2}.\d{10}),(\d{2}.\d{10})',x,re.DOTALL))
print(type(df['lat_lon'][0][0]))
df.drop(686, axis=0, inplace=True)
df['lat'] = [x[0][0] for x in df['lat_lon']]
df['lon'] ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
setup.py
A module that installs reporter as a module
"""
from glob import glob
from os.path import basename, splitext
from setuptools import find_packages, setup
setup(
name='reporter',
version='1.0.0',
license='MIT',
description='Reports AGOL usage ... |
from functools import partial
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from models.category_model import Category
from views.popup_view import PopupView
class ProductList:
''' Controlls the product list view, and the objects '''
def __init__(self, products, main_window):
self.LIMIT_ITEM... |
from authorization import authorization
from data_reading import read_data_from_api,read_token_file,read_from_local_data_file
from prettytable import PrettyTable
import datetime
table = PrettyTable()
def user_prompt():
"""
Description:
user_prompt is responsible for asking a user if they are
... |
import setuptools
with open("README.md") as fp:
long_description = fp.read()
setuptools.setup(
name="aws_cdk_python_dev_guide",
version="0.0.1",
description="A guide for AWS CDK development using Python",
long_description=long_description,
long_description_content_type="text/markdown",
... |
from identixone.api.sources.v1.sources import Sources
__all__ = [Sources]
|
import numpy as np
from numpy.fft import fft2, ifft2, ifftshift, fftshift
def shear_grid_mask(shape, acceleration_rate, sample_low_freq=False,
centred=False, sample_n=4, test=False):
'''
Creates undersampling mask which samples in sheer grid
Parameters
----------
shape: (nt, ... |
import numpy as np
class Statistics:
def __init__(self, keep_all=False):
self.keep_all = keep_all
self.data = []
self.n = 0
self.avg = 0.0
def add(self, x):
if self.keep_all:
self.data += x
else:
self.avg = self.avg * (self.n / float(se... |
"""
The implementation code for the command-send GDS CLI commands
"""
import difflib
from typing import Iterable, List
from fprime.common.models.serialize.type_exceptions import NotInitializedException
from fprime_gds.common.data_types.cmd_data import CommandArgumentsException
from fprime_gds.common.gds_cli.base_comm... |
from .siamrpn import SiamRPN
def get_tracker_class():
return SiamRPN
|
"""
Calculate the middle points, areas and best predictors of the polygons and the relative areas of the best predictors
"""
from shapely.geometry.polygon import Polygon
def get_predictor_cost(x, y, rho, sens, spec, cov):
"""
Calculate the predictor's cost on a point (x, y) based on the rho and its sensitivi... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 by Clemens Rabe <[email protected]>
# All rights reserved.
# This file is part of gitcache (https://github.com/seeraven/gitcache)
# and is released under the "BSD 3-Clause License". Please see the LICENSE file
# that is included as part of this package.
#
"""Unit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def predict_final(prefix=None,
assignment=None,
tutorial=None,
midterm=None,
takehome=None,
final=None):
""" Predictor for Final from model/59db76eb9b356c2c97004804
Predic... |
import numpy as np
np.random.seed(0)
def sigmoid(x):
out = 1 / (1+np.exp(-x))
return out
def relu(x):
out = x
out[out < -1] = -1
out[out > -1 and out < 0] = 0
return out
def tanh(x):
out = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))
return out
def softmax(x):
e_x = np.ex... |
routes = [
('Binance Futures', 'BTC-USDT', '1m', 'OttBands1min', 'hY?9')
]
extra_candles = []
|
# -*- coding:utf-8 -*-
__author__ = 'shshen'
import os
import random
import csv
import logging
import numpy as np
def logger_fn(name, input_file, level=logging.INFO):
tf_logger = logging.getLogger(name)
tf_logger.setLevel(level)
log_dir = os.path.dirname(input_file)
if not os.path.exists(log_dir):
... |
""" Copyright (c) 2019 Lumerical Inc. """
import sys
sys.path.append(".")
import os
from qatools import *
from lumopt.utilities.simulation import Simulation
from lumopt.utilities.base_script import BaseScript
class TestFDTDBaseScript(TestCase):
"""
Unit test for BaseScript class. It verifies that the o... |
from bs4 import BeautifulSoup
import requests
from summarize import getSummary
import datetime
def parseTime(time):
return time
headers = {
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"User-Agent" : "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100... |
import MicroRegEx
regex = MicroRegEx.compile("(a|b)cd*e?")
result = regex.match("abcde")
print(result)
result = regex.match("acde")
print(result)
|
import xlwt
from django.http import HttpResponse
from .models import Instansi
from .resources import InstansiResource
def export_instansi(request):
instansi = InstansiResource()
dataset = instansi.export()
response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Dispositi... |
# -*- coding:utf8 -*-
# File : __init__.py
# Author : Jiayuan Mao
# Email : [email protected]
# Date : 17/08/2017
#
# This file is part of TensorArtist.
from .adv import *
from .env import *
|
#!/usr/bin/env python
import colorsys
import math
import time
import unicornhathd
print("""Ubercorn rainbow 2x1
An example of how to use a 2-wide by 1-tall pair of Ubercorn matrices.
Press Ctrl+C to exit!
""")
unicornhathd.brightness(0.6)
# Enable addressing for Ubercorn matrices
unicornhathd.enable_addressing... |
# The MIT License (MIT)
#
# Copyright (c) 2017-2018 Niklas Rosenstein
#
# 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, ... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
## Opt transformations
# Test 2-opt
# Add a quality ratio to stop the 2-opt optimization
# 3-opt
# 4-opt
# k-opt
##
## 2-opt
def swap2opt(path, i, j):
new_path = path[i:j]
new_path.reverse()
return path[:i]+new_path+path[j:]
def optimization2opt(graph... |
# Copyright 2018 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 senteval
config = {
'classifier': 'log reg',
'nhid': 0,
'optim': 'adam',
'batch_size': 64,
'tenacity': 5,
'epoch_size': 4
}
def run_log_reg(params_senteval, batcher, prepare, probing_tasks):
classifier_config = {**params_sentev... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
serial = ['']
def recurse(node):
if node == None:
serial[0]+=("% ")
... |
import serial
import json
import time
import binascii
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class SerialChannels:
def __init__(self, CHANNELS):
self.channels = []
self.numChannels = CHANNELS - 1
self.frame_error = 0
self.failsafe = 0
class Seria... |
# Generated by Django 2.1.2 on 2018-11-09 21:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
from requests import get
from websocket import create_connection
from json import dumps, loads
from sys import argv
from os import listdir, path
from time import sleep
BASE_ADDRESS = "http://localhost:8080"
class Tab:
def __init__(self, res) -> None:
self.title = res["title"]
self.id = res["id"]
... |
"""Convert logincreate timestamps to TIMESTAMP(timzone=True)
Revision ID: 3accc3d526ba
Revises: 2e25bc9a0896
Create Date: 2020-02-27 16:06:48.018000
"""
# revision identifiers, used by Alembic.
revision = '3accc3d526ba'
down_revision = '2e25bc9a0896'
from alembic import op # lgtm[py/unused-import]
import sqlalche... |
# # # # # a = 215
# # # # a = int(input("Input a"))
# # # a = 9000
# # # a = 3
# # #
# if True: # after : is the code block, must be indented
# print("True")
# print("This always runs because if statement is True")
# print("Still working in if block")
# # # if block has ended
# print("This runs no matter w... |
import os
import sys
ret = []
for x in os.walk(sys.path[-1],'*.py'):
for y in x[2]:
ss = y.split('.')
if ss[-1] == 'py': ret.append(ss[0])
print(ret) |
# _*_ codig utf8 _*_
import numpy as np
import hmm_backward, hmm_forward
def hmm_kesai(alpha, beta, A, B, Q):
'''
计算观测序列中t时刻和t+1时刻状态分别为si 和sj的概率
:param alpha: 前向概率矩阵
:param beta: 后续概率矩阵
:param A: 状态转移矩阵
:param B:状态到观测值转移矩阵
:param Q:观测状态序列
:return: ξ矩阵
'''
N = alpha.shape[1]
... |
from typing import Type, Dict
class SsaContext():
"""
:ivar objCnt: the dictionary of object counts used for name generating
"""
def __init__(self):
self.objCnt = 0 # : Dict[Type, int] = {}
def genName(self, obj):
prefix = getattr(obj, "GEN_NAME_PREFIX", "o")
i = self.ob... |
import PyPDF2
from PyPDF2 import PdfFileReader
from pprint import pprint
from tkinter import filedialog
from tkinter import *
def fileName():
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("pdf files","*.pdf"),("all files","*.*")))
return str(r... |
import unittest
import numpy as np
from src.davil.lists import partition_train_test_validation
class TestPartitions(unittest.TestCase):
def test(self):
def check_sets(lists):
for ts in zip(*lists):
for t in ts:
t0 = ts[0].split('_')[0]
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 13 11:12:06 2021
@author: altair
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import LSTM, Dropout, Dense
from sklearn.preprocessing import MinMaxScaler
scaler = Mi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.