content stringlengths 5 1.05M |
|---|
# Generated by Django 3.0.5 on 2020-04-30 14:54
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks
class Migration(migrations.Migration):
dependencies = [
('pages', '0004_remove_home_app'),
]
operations = [
migrations.Alte... |
import neovim
@neovim.plugin
class TestPlugin:
def __init__(self, nvim):
self.nvim = nvim
@neovim.function("TestFunction", sync=True)
def test_function(self, args):
return 3
@neovim.command("TestCommand", range='', nargs='*')
def test_command(self, args, rng):
self.nvim.cu... |
from math import exp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# data
def create_data():
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.t... |
import torch
import torch.nn as nn
from .rl_base_strategy import RLBaseStrategy, Timestep, TimestepUnit
from .buffers import Rollout
from torch.optim.optimizer import Optimizer
from typing import Union, Optional, Sequence, List
from avalanche_rl.training.plugins.strategy_plugin import RLStrategyPlugin
from torch.optim ... |
import logging
import time
import requests
from bs4 import BeautifulSoup
from ghost import Ghost
WAIT_TIMEOUT_SECONDS = 10
SSL_LABS_URL = "https://www.ssllabs.com/ssltest/analyze.html?hideResults=on&d="
SSL_LABS_API_URL = "https://api.ssllabs.com/api/v2/analyze"
CHROME_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) Apple... |
#!/usr/bin/env python
from abc import ABC
from contextlib import redirect_stdout, redirect_stderr
from unittest import TestCase, main
from unittest.mock import Mock
from cli_command_parser import Command, CommandConfig, Context
from cli_command_parser.core import get_config, get_parent, get_params
from cli_command_pa... |
# NAME : Batter Up
# URL : https://open.kattis.com/problems/batterup
# =============================================================================
# Use a list comprehension to map strings to integers then do simple math on
# the list.
# =============================================================================
... |
#
# Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "li... |
#!/usr/bin/env python
# encoding: utf-8
"""
delete-node-in-a-linked-list.py
Created by Shuailong on 2016-02-04.
https://leetcode.com/problems/delete-node-in-a-linked-list/.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
cl... |
import argparse
import json
import logging
from pathlib import Path, PurePath
from tqdm import tqdm
from utils.log import setup_logging
def main():
# Use first line of file docstring as description if it exists.
parser = argparse.ArgumentParser(
description=__doc__.split('\n')[0] if __doc__ else '',... |
import sys
import runner
if __name__ == '__main__':
args = sys.argv
if len(args) != 3:
print("""
Usage:
python main.py <output_file.csv> <config_file.json>
""")
exit()
runner.run(
args[2],
"data/skills.json",
"data/armour_sets.json",
... |
# -*- coding: utf-8 -*-
from model.person import Person
import pytest
import random
import string
def test_add_contact(app, json_contacts, check_ui,db):
contact = json_contacts
old_contacts = db.get_contact_list()
app.contact.add_contact_fill_form(contact)
assert len(old_contacts) + 1 == app.contact.c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tensorflow as tf
import os
import numpy as np
import shutil
import argparse
from DataHolder import DataHolder
from Config import Config
from Trainer import Trainer
from DFN import DFN
from CNN import CNN
from util import reconstruct_from_record, accuracy_per_categor... |
from typing import Deque, Any
from collections import deque
queue: Deque[Any] = deque()
queue.append('A')
queue.append('B')
queue.append('C')
print(queue)
print('Removido', queue.popleft())
print('Removido', queue.popleft())
print('Removido', queue.popleft())
|
import komand
from .schema import GetProjectInput, GetProjectOutput, Input, Output, Component
from ...util import project
class GetProject(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="get_project",
description=Component.DESCRIPTION,
in... |
# coding=utf-8
# Copyright 2021 The init2winit 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 la... |
from django.urls import path, re_path
from app import views, mobileViews
urlpatterns = [
re_path(r'^.*\.html', views.gentella_html, name='gentella'),
path('', views.index, name='index'),
# -------------------------------------------------------------------------------
# cordova
# mobile이지만 뺵업 느낌으로 ... |
"""Author model for Zinnia"""
from django.apps import apps
from django.conf import settings
from django.db import models
from django.urls import reverse
from zinnia.managers import EntryRelatedPublishedManager
from zinnia.managers import entries_published
def safe_get_user_model():
"""
Safe loading of the Us... |
import csv
import json
import copy
INPUT_CSV = '20210712.csv' # input: timetable csv
OUTPUT_JSON = '20210712.json' # output: timetable json
PERIOD = 'summer' # choices: 'semester', 'summer', 'winter'
def timeList(dic, week, fro, to):
left = dic[week][fro][to]
right = dic[week][to][fro]
time = []
... |
from __future__ import division, print_function
import numpy as np
from sqlalchemy import String, Integer, Float, Column
from sqlalchemy.schema import ForeignKey
from sqlalchemy.orm import relationship
from .connect import Base
from astropy.coordinates import SkyCoord
__all__ = ['Run', 'Tract', 'Patch', 'Source']
c... |
from core import Printer, Run
Printer.main()
while True:
args = input("=> ")
run = Run(args)
run.run()
if (run.exitStatus != 0):
print("\nGood bye :D\n")
break
|
#!/usr/bin/env false
"""TODO: Write
"""
# Internal packages (absolute references, distributed with Python)
# External packages (absolute references, NOT distributed with Python)
# Library modules (absolute references, NOT packaged, in project)
from src_gen.script.bash.complete import generate_activation as activation... |
"""
RTC typing class
his class includes support for using ESP32 RTC peripherals and memory
The content of the RTC memory is preserved during the deep sleep.
Up to 64 32-bit integers can be saved in RTC memory.
One string of up to 2048 characters can be saved in RTC memory.
The string can be, for example, json strin... |
'''
Speed: 77.11%
Memory: 82.57%
Time Complexity: O(n)
'''
class Solution:
def getRow(self, k: int) -> List[int]:
res = [1]*(k+1)
#res[0]=1
for i in range(1,k):
for j in range(i,0,-1):
res[j]+=res[j-1]
return res |
import re
import pytest
from vidispine.errors import InvalidInput, NotFound
from vidispine.utils import generate_metadata
def test_update_collection(
vidispine, cassette, create_metadata_field, collection
):
create_metadata_field('field_one')
create_metadata_field('field_two')
fields = {
't... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1066/A
def f(ll):
n,v,l,r = ll #1e9
lc = (l-1)//v
rc = r//v
tc = n//v
return lc + tc - rc
q = int(input()) #1e4
for _ in range(q):
l = list(map(int,input().split()))
print(f(l))
|
import os
import unittest
from unittest import mock
from src.common.markdown_parser import MarkdownParser
class TestMarkdownParser(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.md = MarkdownParser(init_md=False)
cls.md.namespace = "dnd"
def test_base_dir(self):
from ... |
import json
import pprint
import core.utility as util
def visualize_dict_results(title: str, results: dict, outfile: str):
"""
Print the results stored in the given dict and write them to the output file.
"""
print(title)
pprint.pprint(results)
with open(outfile, "w") as file:
file.wri... |
import numpy as np
def make_full_window(audio_data:np.ndarray, feature_window:int, feature_step:int):
"""
Takes in a 1d numpy array as input and add appends zeros
until it is divisible by the feature_step input
"""
assert audio_data.shape[0] == audio_data.size, "input data is not 1-d"
remainde... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-27 09:40
from __future__ import unicode_literals
import django.core.files.storage
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
m... |
#!/usr/bin/env python
import json
import logging
import subprocess
import sys
import textwrap
import xmlrpclib
USAGE = 'Usage: year_in_review.py [--json] <YEAR>'
# Note: Most of the bugzila api code comes from Scrumbugz.
cache = {}
log = logging.getLogger(__name__)
BZ_URL = 'http://bugzilla.mozilla.org/xmlrpc.cgi'... |
from flask import g, render_template, request, redirect, url_for, current_app
from datetime import date
from maintain_frontend.add_land_charge.validation.expiry_validator import ExpiryValidator
from maintain_frontend.decorators import requires_permission
from maintain_frontend.constants.permissions import Permissions
f... |
#!/usr/bin/env python
import multiprocessing
def worker():
print('new worker')
for i in range(8):
multiprocessing.Process(target = worker).start()
|
import numpy as np
import sounddevice as sd
from pynkTrombone.voc import Voc
import hashlib
sd.default.samplerate = 44100
#TODO: Add Lips, Add Tongue Shapes, Add Glottal Closing.
def remap(value, max_out, min_out, max_in=1.0, min_in=-1.0):
return (max_out - min_out) * (value + 1.0) / 2.0 + min_out
def main... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
from contextlib import contextmanager
from thenewboston_node.core.clients.node import NodeClient
@contextmanager
def force_node_client(node_client: NodeClient):
try:
NodeClient.set_instance_cache(node_client)
yield
finally:
NodeClient.clear_instance_cache()
|
# Copyright 2017 Bernhard Walter
#
# 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 writin... |
"""Video demo utils for showing live object detection from a camera
python3 video_demo.py --restore-weights=weights/<weights.h5>
"""
import ssd
import numpy as np
import cv2
import argparse
import datetime
import skimage
import label_utils
import config
from ssd import SSD
from boxes import show_boxes
from skimage.... |
# -*- coding: utf-8 -*-
from newspaper import Article
import nltk
""" COMUM """
def HASH_TEXTO(NOTICIA):
import hashlib
HASH512 = NOTICIA.encode('utf-8')
HASH512 = hashlib.sha512(HASH512).hexdigest()
return HASH512
def TIRAR_ESPACOS(TITULO):
"""----------- TIRAR ACENTOS E TROCAR ESPACOS POR UNDERSC... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-08-06 02:47
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.gis.db.models.fields
import django.contrib.postgres.fields.jsonb
import django.core.files.storage
from django.db import migrations, models
import djang... |
import numpy as np
from rpy2 import robjects as ro
import rpy2.rlike.container as rlc
def train(x_data, y_values, weights):
x_float_vector = [ro.FloatVector(x) for x in np.array(x_data).transpose()]
y_float_vector = ro.FloatVector(y_values)
weights_float_vector = ro.FloatVector(weights)
... |
import time
from config import cfg
from threading import Thread, Event
from queue import Queue
from typing import Dict, List
import os
import json
from multiprocessing import Queue as mpQueue
from src.base import EdgiseBase
VOLTAGE_ID_LIST: List = ['core', 'sdram_c', 'sdram_i', 'sdram_p']
class StateData:
tempe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayTradeOrderPayResponse(AlipayResponse):
def __init__(self):
super(AlipayTradeOrderPayResponse, self).__init__()
self._async_payment_mode = None
self._gmt... |
# Base component constants
NAME = "FXLuminaire Luxor"
DOMAIN = "luxor"
DOMAIN_DATA = f"{DOMAIN}_data"
VERSION = "0.0.1"
ISSUE_URL = "https://github.com/dcramer/hass-luxor/issues"
# Platforms
LIGHT = "light"
SCENE = "scene"
PLATFORMS = [LIGHT, SCENE]
# Configuration and options
CONF_HOST = "host"
# Defaults
DEFAULT_N... |
from lxml import html
import argparse
import requests
import re
import shutil
import os
class Manga:
def __init__(self,url,date,name,chapter,title):
self.url=url
self.name=name
self.chapter=chapter
self.title=title
self.date=date
def __str__(self):
return self.... |
from .cluster import Cluster, MultiSearchError
from .document import Document, DynamicDocument
from .expression import (
Params, Term, Terms, Exists, Missing, Match, MultiMatch, MatchAll, Range,
Bool, Query, DisMax, Filtered, Ids, Prefix, Limit,
And, Or, Not, Sort, Boosting, Common, ConstantScore, FunctionS... |
# -*- coding:utf-8 -*-
# &Author AnFany
import pandas as pd
import numpy as np
# 训练数据文件路径
train_path = 'C:/Users/GWT9\Desktop/Adult_Train.csv'
# 测试数据文件路径
test_path = 'C:/Users/GWT9\Desktop/Adult_Test.csv'
# 因为测试数据native-country中不存在Holand-Netherlands,不便于独热编码。
# 因此在测试文件中添加一个native-country为Holand-N... |
import os
import xml.etree.ElementTree as ET
CLASS_DICT = {}
HOME_DIR = os.path.expanduser('~/CourseWork/data/FlickrLogos_47/VOC2007')
ANNOTATIONS_PATH = os.path.join(HOME_DIR, 'Annotations')
#Remove xml files which were creater in previous trials
os.system('cd Annotations; rm *.xml')
with open(HOME_DIR + ... |
import wx
import os
import six
import sys
import math
import Utils
import Model
from GetResults import GetResults
from ReorderableGrid import ReorderableGrid
class Prizes( wx.Panel ):
rowsMax = 20
def __init__( self, parent, id=wx.ID_ANY, size=wx.DefaultSize ):
super(Prizes, self).__init__( parent, id, size=size... |
import numpy as np
from scipy.special import softmax
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as tdata
import pandas as pd
import time
from tqdm import tqdm
from utils import validate, get_logits_targets, sort_sum
import pdb
# Conformalize a model with a calibration set.
#... |
from django.shortcuts import get_object_or_404
from wsgiref.util import FileWrapper
from django.http import StreamingHttpResponse, BadHeaderError
from unidecode import unidecode
from wagtail.wagtaildocs.models import Document, document_served
def serve(request, document_id, document_filename):
doc = get_object_... |
from subprocess import call
frdr = file('values.txt','r') #Read Log File
fwtr = file('gnu.txt','w+') #Write Coords in Required format
while True:
line = frdr.readline()
if len(line) == 0:
break;
row = line.split(' ')
if row[0].isdigit() :
counter = 0
while counter <... |
import piexif
import sys
exif_dict = piexif.load(sys.argv[1])
#for ifd in ("0th", "Exif", "GPS", "1st"):
# for tag in exif_dict[ifd]:
# print(piexif.TAGS[ifd][tag]["name"], exif_dict[ifd][tag])
#print('Keys:', exif_dict.keys())
#print('Pre validate:', exif_dict['_types']['GPS'])
#print('Pre validate:', exif... |
"""
imutils/ml/data/datamodule.py
Created on: Wednesday March 16th, 2022
Created by: Jacob Alexander Rose
- Update (Wednesday March 24th, 2022)
- Refactored to make more modular BaseDataset and BaseDataModule, which Herbarium2022Dataset and Herbarium2022DataModule inherit, respectively.
- Update (Wednesday Apri... |
import unittest
import math
# from IPython import embed
from skopt import space as sp
import numpy as np
from buster import sampler, metrics
class TestAdaptiveSampler(unittest.TestCase):
def test_ask_one_dimension_numeric(self):
X = [[10], [20], [30], [40], [50], [60], [70], [80], [90], [100]]
y = [False,... |
from django.core.management.base import BaseCommand
from django.db.models import QuerySet
from django.contrib.auth import get_user_model
from urls.models import Url,RecycleUrl
class Command(BaseCommand):
help = "Custom Command to Perform a Database Operation"
def handle(self, *args, **kwargs):
User ... |
from diameter.AVP import AVP
from diameter.Error import InvalidAVPLengthError
import struct
class AVP_Unsigned64(AVP):
"A Diameter Unsigned64 AVP"
def __init__(self,code,value,vendor_id=0):
AVP.__init__(self,code,struct.pack("!Q",value),vendor_id)
def queryValue(self):
"""Returns the payl... |
r""" Static order of nodes in dask graph
Dask makes decisions on what tasks to prioritize both
* Dynamically at runtime
* Statically before runtime
Dynamically we prefer to run tasks that were just made available. However when
several tasks become available at the same time we have an opportunity to break
ties in... |
import sys
import datetime
from traceback import format_exception_only
import string
import random
import traceback
from sqlalchemy import or_, desc
from flask import (Blueprint, jsonify, request, current_app)
from sqlalchemy.exc import IntegrityError
from sqlalchemy import func
from mail import EmailTemplate, sendmail... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#import bibliotek
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.dummy import DummyClass... |
import time
import json
import argparse
import os
import sys
import logging
import shutil
from datetime import datetime
import glob
import random
from scipy.stats import mannwhitneyu
from scipy.stats import spearmanr
import numpy as np
from sklearn.metrics import roc_auc_score, precision_recall_curve, auc
import te... |
""" MLPNN for microbial samples from DIABIMMUNE subjects """
## v1.0
from __future__ import division, print_function, absolute_import
from collections import defaultdict, OrderedDict
import random
import os
import datetime
import timeit
import numpy as np
import pandas as pd
import tensorflow as tf
import sklearn.metr... |
try:
import io
except ImportError:
# probably linux
import StringIO
io = StringIO
import tokenize
import re
import sublime, sublime_plugin
def find(collection, f):
for i in collection:
if f(i):
return i
return None
def search_points_to_replace(command):
points_to_replace = set()
for region i... |
from __future__ import annotations
from prettyqt import gui, widgets
from prettyqt.qt import QtWidgets
QtWidgets.QGraphicsOpacityEffect.__bases__ = (widgets.GraphicsEffect,)
class GraphicsOpacityEffect(QtWidgets.QGraphicsOpacityEffect):
def serialize_fields(self):
return dict(opacity=self.opacity(), op... |
#!/usr/bin/env python
import pymongo
from flask import Blueprint
from flask import current_app as app
from flask import request
from flask_restx import Namespace, Resource, fields
import json
from libblapiserver.auth import require_user, require_admin
api = Namespace('mongodb', description='Binlex MongoDB API')
@api... |
import logging
from time import time
from decimal import ROUND_DOWN, Decimal
logger = logging.getLogger(__name__)
_missing = object()
def elapsed(t0=0.0):
"""
Get the elapsed time from the give time.
If the start time is not given, returns the unix-time.
Returns
-------
t : float
El... |
import requests
office_dict = {'PRS': 'President',
'USS': 'U.S. Senate',
'GOV': 'Governor',
'LTG': 'Lieutenant Governor',
'SOS': 'Secretary of State',
'CON': 'Controller',
'TRS': 'Treasurer',
'ATG': 'Attorney Gene... |
from keras.preprocessing import image
import os
import sys
import matplotlib.pyplot as plt
sys.path.insert(0, '../libraries')
from mrcnn.config import Config
import mrcnn.model as modellib
import cv2
from moviepy.editor import VideoFileClip
from mrcnn import visualize_drivable
# HOME_DIR is the path that the project y... |
'''
reference_pad_cds_alleles.py
Add reference seqeunces to the flanks of CDS
alleles from a single gene.
'''
import sys
import os
import subprocess
from Bio.Seq import Seq
from Bio import SeqIO
from utils import *
def parse_chromosome(filename, chrom_name):
sequence = ""
for record in SeqIO.parse(filenam... |
#!/usr/bin/env python
u"""
gmao_spire_gnss_sync.py
Written by Tyler Sutterley (10/2021)
Syncs Spire GNSS grazing angle altimetry data from the NASA
Global Modeling and Assimilation Office (GMAO)
CALLING SEQUENCE:
python gmao_spire_gnss_sync.py --user=<username>
where <username> is your NASA GMAO Extranet ... |
import numpy as np
from pathlib import Path
import json
from .. import DiscreteModel
class QLearning(DiscreteModel):
"""
Models the Q-Function over a StateActionSpace as an array of values updated with Q-Learning. This is the vanilla
Q-Learning.
"""
ARRAY_SAVE_NAME = 'q_values_map.npy'
SAVE_N... |
#!/usr/bin/env python3
##################################################################################
# Pyprojectx #
# https://github.com/houbie/pyprojectx #
# ... |
import requests
import json
class ChronicleEntry(object):
def __init__(self, data_dict, headers, cookies, api_url):
self.headers = headers
self.cookies = cookies
self.API_URL = api_url
self.episode = data_dict.get('episode', None)
self.anime_id = data_dict.get('id', None)
... |
import copy
from bntransformer.utils import entity_map
from transformers import (
AutoModelForQuestionAnswering,
AutoModelForTokenClassification,
AutoModelWithLMHead,
AutoTokenizer,
pipeline,
)
class BanglaQA:
def __init__(self, model_path=None):
if not model_path:
model_pa... |
#Write your code below this line 👇
from math import ceil
# Two ways of rounding up a number:
# import math
# print(int(math.ceil(4.2)))
# Second way:
# int(21 / 5) + (21 % 5 > 0)
# The first part becomes 4 and the second part evaluates to "True" if there is a remainder, which in addition True = 1; False = 0.
def pai... |
"""
BlobFactory.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on: Fri Dec 11 14:24:53 PST 2015
Description:
"""
import os
import re
import glob
import numpy as np
from inspect import ismethod
from types import FunctionType
from scipy.interpolate import RectBivariateSpline, inter... |
# Copyright (C) 2018 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# the License. Y... |
# 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.
"""Calculates confidence scores for all suspected CLs so far and save the scores
to data store.
"""
import argparse
from collections import defaultdict
i... |
class IncludeDependencyAnalyzer(object):
def listIncludes(self, source_file):
return []
|
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def talk():
pub = rospy.Publisher('message', String, queue_size=10)
rospy.init_node('talk')
rate = rospy.Rate(1)
while not rospy.is_shutdown():
freq = "8"
rospy.loginfo(freq)
pub.publish(freq)
rate.sleep... |
"""Provides utility programs.
Notes:
The astronomy-type utilities should probably be separated out into
another file.
--schriste
"""
from __future__ import absolute_import
from scipy.constants import constants as con
__all__ = ["toggle_pylab", "degrees_to_hours", "degrees_to_arc",
"kelv... |
"""Input objects for Queenbee jobs."""
from typing import Dict, List, Union
from pydantic import Field, constr
from ..artifact_source import HTTP, S3, ProjectFolder
from ...base.basemodel import BaseModel
from ...base.parser import parse_file
class JobArgument(BaseModel):
"""Job argument is an argument input fo... |
from math import sqrt
from problem import Problem
from utils import path
def load_words():
with path.load_file("p042_words.txt") as f:
return [w.strip('"') for w in f.read().split(",")]
class CodedTriangleNumbers(Problem, name="Coded triangle numbers", expected=162):
words = load_words()
@clas... |
#
# E M I T T E R A N D T R E A T M E N T
#
import time
import numpy as np
from abc import ABC, abstractmethod
# from Treatment import Treatment
# from typing import Callable
# import logging
# from time import sleep
# from datetime import datetime
import nidaqmx as ni
import threading, queue
# Pieces for how NI n... |
from app import db
from datetime import datetime
class Account(db.Model):
__tablename__ = 'account'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(255), nullable=False)
password = db.Column(db.String(500), nullable=False)
available = db.Column(db.... |
"""Basic Functionality for working with Microsoft Fluent Web components
See https://github.com/microsoft/fluentui/tree/master/packages/web-components
"""
class FluentComponent: # pylint: disable=too-few-public-methods
"""The FluentWidget and FluentLayout should inherit from this"""
__javascript_mo... |
"""
This module shows how to ITERATE (i.e. loop) through a SEQUENCE
in ways OTHER than just going thru the sequence from BEGINNING to END.
It also shows how to SELECT items in a sequence, e.g.:
-- the items that are strings
-- the items that are even integers (e.g. 2, 4, 6, ...)
Note that:
-- SELECTING items th... |
#!/bin/env python
"""
Parses sesame analysis
"""
import logging
import pandas as pd
import re
from functools import reduce
from matplotlib import pyplot as plt
from matplotlib.axes import Axes
from os import path, listdir
from srl_nlp.framenet.description import EXample
from srl_nlp.framenet.parse_xml import NetXMLPa... |
"""
Classes for computing nucleosome occupancy
@author: Alicia Schep, Greenleaf Lab, Stanford University
"""
from scipy import signal, optimize, stats
import numpy as np
import matplotlib.pyplot as plt
from pyatac.fragmentsizes import FragmentSizes
from pyatac.tracks import Track, CoverageTrack
from pyatac.chunk imp... |
messageTemplate = r'''
public class ITest__Min##__Invoke : IInterfacedMessage, IAsyncInvokable
{
public int a;
public int b;
public Type GetInterfaceType() { return typeof(ITest); }
public async Task<IValueGetable> Invoke(object target)
{
var __v = await ((I... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 1 22:34:19 2018
@author: chenxiaoxu
"""
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
import sklearn.metrics as metrics
from datetime import time
import matplotlib.pyplot a... |
from base64 import b64decode
import pytest
from tests.unit.conftest import CONFIG_PATH, FIXTURE_PATH, config_path, fixture_path
from whispers import core
from whispers.cli import parse_args
from whispers.secrets import WhisperSecrets
@pytest.mark.parametrize("configfile", ["exclude_keys.yml", "exclude_values.yml"])... |
# -*- coding: utf-8 -*-
# Copyright 2020- Datastax, Inc. 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 require... |
from analysis import data_gen_all
import os
basepath = os.environ['BASEPATH']
path = os.path.join(basepath, 'results/CRF_log/type78/CRF_path')
pathL = os.path.join(basepath, 'results/CRF_log/type78/CRF+LDA_pathL')
data_gen_all(path, path_L, 'multi-col', './output') |
import theano.tensor as tt
class Activation:
"""
Defines a bunch of activations as callable classes.
Useful for printing and specifying activations as strings.
(via activation_by_name)
"""
def __init__(self, fn, name):
self.fn = fn
self.name = name
def __call__(self, *args... |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
import cv2 as cv
import imutils
import time
import math
import numpy as np
"""
"""
def calculate_distance(x1, y1, x2, y2):
return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
def main():
image = cv.imread("G:\\Project\\opencv-ascs-resources\\... |
import os
from flask import Flask, render_template, send_from_directory, request, flash
from flask_wtf import Form
from wtforms import TextField, BooleanField, TextAreaField, SubmitField, validators, ValidationError
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
app.secret_key = 'development identi... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
from __future__ import annotations
from aws_cdk import (
core,
aws_iam as iam
)
import typing
from a... |
import argparse
import json
import logging
import os
from prometheus_client.core import GaugeMetricFamily, REGISTRY
from prometheus_client.twisted import MetricsResource
from twisted.internet import reactor
from twisted.web.resource import Resource
from twisted.web.server import Site
logger = logging.getLogger(__name... |
#!/usr/bin/env python
"""
WorkQueuManager test
"""
from __future__ import print_function, division
from builtins import next
import unittest
from WMCore_t.WorkQueue_t.WorkQueueTestCase import WorkQueueTestCase
from WMCore.WorkQueue.WorkQueue import globalQueue
def getFirstTask(wmspec):
"""Return the 1st top l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.