content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
import paramiko
import pandas as pd
import os
import datetime
import glob
import threading
import time
import boto3
from botocore.exceptions import ClientError
class sendtoserver(threading.Thread):
def __init__(self, dvr_num, dvr_ch, save_path):
threading... |
#!/usr/bin/env python
import sys
mode=0
n = int(sys.argv[1])
f = open("perftest.rail","w")
f.write("$ 'main'\n")
if mode==0:
for i in range(n):
f.write(" \\-")
f.write(n*"1o")
f.write("-\\\n")
f.write((4+n*2)*" "+ "|\n")
f.write(" /-"+n*("o1")+"-/\n")
f.write("|\n")... |
from blueprints import create_app
from config import config
app = create_app(config) |
"""
Helpers to pack and unpack a unicode character into raw bytes.
"""
import sys
UNICODE_SIZE = 4
BIGENDIAN = sys.byteorder == "big"
def pack_unichar(unich, buf, pos):
pack_codepoint(ord(unich), buf, pos)
def pack_codepoint(unich, buf, pos):
if UNICODE_SIZE == 2:
if BIGENDIAN:
buf.setit... |
import numpy as np
from itertools import combinations_with_replacement
import time
from random import choice
class CouldNotClassifyClusterError(Exception):
pass
class GaussianClusterTracker(object):
def __init__(self, atoms=None, threshold=0.001,
cluster_elements=[], num_clusters=1, init_cen... |
import rospy
class Node():
def __init__(self, name, topics={}):
rospy.init_node(name)
self.subscribers = []
self.timed_subscriber_memory = {}
self.pubs = {}
for topic, msg_type in topics.items():
self.pubs[topic] = rospy.Publisher(
topic, msg_type... |
log_path = 'logs/'
icon_server_path = './icon_server.ico'
icon_client_path = './icon_client.ico'
client_window_name = 'ChatClient'
server_window_name = 'ChatServer'
encoding = 'utf-8'
MAXSIZE = 2048
server_port = 3000
client_port = 4000
|
from __future__ import unicode_literals
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from .settings import * # NOQA
|
"""
LANGUAGE: PYTHON
AUTHOR: cdefga
GITHUB: https://github.com/cdefga
"""
import numpy as np
def n_dimensional_distance(a: np.ndarray, b: np.ndarray) -> float:
assert a.shape == b.shape, 'dimension of input must be equal'
dist = np.sqrt(np.sum((a - b)**2))
return dist
if __name__ == '__main__':
a =... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from .base_learner import BaseLearner
import model
import torch
import torch.nn as nn
import torch.optim as optim
class Tr... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Rtax(Package):
"""Rapid and accurate taxonomic classification of short paired-end
s... |
import sys
from collections import Counter
x = int(sys.stdin.readline())
xl = list(sys.stdin.readline().split())
y = int(sys.stdin.readline())
yl = list(sys.stdin.readline().split())
xl.sort()
count = Counter(xl)
for i in range(len(yl)):
if yl[i] in count:
print(count[yl[i]],end=" ")
else:
p... |
x = 6
x.meh = 5
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
#!/usr/bin/env python
import re
import json
config_text="""
-s, --separator TEXT Field separator in input .csv
-q, --quoting INTEGER Control field quoting behavior per csv.QUOTE_*
constants. Use one of QUOTE_MINIMAL (0),
QUOTE_ALL (1), QUOTE_NON... |
from .general import *
from .filtering import *
|
'''
说明:用yield from实现协程中断交出控制权
分析:
每一行程序都是按顺序一步一步执行的,如果有程序不是按顺序执行,表示曾经交出了控制权,以下的例子,本来应该应该顺序输出1,2,但是因为req1交出了控制权,所以,输出了2,1
'''
import time
from collections import deque
_delay = deque()
def sleep0():
yield
return None
def req1():
yield
b = yield from sleep0()
return 1
def req2():
yi... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from django.utils.translation import gettext as _
from core import models
class UserAdmin(BaseUserAdmin):
"""Admin panel configuration for User model"""
list_display ... |
# String variable statements with syntax errors.
string variable = 'This line should have a string variable.'
1string_variable_2 = "This line should have another string variable."
another_string_variable = 'This line has another string variable."
yet_another_string_variable = "This line has yet another string variable.... |
#!/usr/bin/env python
import rospy
import time
from std_msgs.msg import String, Int32
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
import json
# pose = Pose value
# location = string value
class Avoid():
def __init__(self):
# Publisher for object detected in front
# ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from Models.DataBase import DatabaseAccessor
class Receivable(object):
DB = DatabaseAccessor()
def __init__(self, ID):
self.__ID = ID
self.__receivable = self.DB.get_receivable_info_by_id(self.__ID)
self.__electricCharge = self.__receivable... |
"""Simple API to access Billboard charts."""
from requests import get
from bs4 import BeautifulSoup
import re
"""
__author__ = Deepjyoti Barman
__github__ = github.com/deepjyoti30
"""
class song():
"""Class to store song details."""
def __init__(self):
self.title = ""
self.artist = ""
... |
from django.test import TestCase
from lookout.report_schemas.base import ReportSchema
from lookout.report_schemas.generic import GenericReportSchema
class TestReportSchemaNotImplemented (TestCase):
""" Tests that schemas based on ``ReportSchema`` implement all of its abstract methods. """
def test_schema (self):... |
"""
Current user endpoint: /me/*
"""
from fastapi import APIRouter, Depends, HTTPException, status
from app.api.utils.security import get_current_active_user
from app.models.user import User as UserModel
from app.schemas.msg import Msg
from app.schemas.user import User, UserUpdate, UserUpdateFull
from app.utils import... |
import sys
import random
if len(sys.argv) != 3:
print >> sys.stderr, "USAGE: python generate_partitions.py <nodes_file> <partitions_per_node>"
sys.exit()
FORMAT_WIDTH = 10
nodes = 0
for line in open(sys.argv[1],'r'):
nodes+=1
partitions = int(sys.argv[2])
ids = range(nodes * partitions)
# use known seed ... |
import pandas as pd
import numpy as np
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import r2_score, mean_squared_error
from sklearn import linear_model
from sklearn.externals import joblib
import time
'''
Load data and declare parameters
Improvements
1. Load all kinds of data - csv, pickle, text ... |
# RPi Telecine - Perforation finding and detection
#
# Perforation location and frame extraction for Super 8 and
# Standard 8 film.
#
# This has been tested using Super8 amateur film with
# black film base, commercial 8mm film with a clear film base.
#
# Quite a few assumtions are made with regards to the position o... |
import torch.nn as nn
from modules.rnn import LSTM
from modules.dropout import *
from modules.crf import CRF
from torch.nn.utils.rnn import pad_sequence
import torch.nn.functional as F
from modules.BertModel import BertEmbedding
class BertSeqTagger(nn.Module):
def __init__(self, bert_embed_dim, hidden_size, num_r... |
# Copyright 2015, Pinterest, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
import collections
import dataclasses
import functools
import ipaddress
import socket
import xml.etree.ElementTree
import typing
import xmltodict
from palo_alto_firewall_analyzer.pan_config import PanConfig
# A registry is used to auto-register the policy validators and fixers.
policy_validator_registry = {}
def r... |
from loguru import logger
from app.arq.tasks.classes.abstract import AbstractSyncTask
from app.utils.minio import upload_screenshot
class UploadScrenshotTask(AbstractSyncTask):
def __init__(self, uuid: str, screenshot: bytes):
self.screenshot = screenshot
self.uuid = uuid
def _process(self) ... |
import pygame
import time
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red =(200,0,0)
light_red = (255,0,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
green = (34,177,76)
light_green = (0,255,0)
display_width = 800
display_height = 600
clock = pygame.time.Clock()
gameDisplay = pygame.d... |
import argparse
import os
import sys
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
# args
parser = argparse.ArgumentParser()
parser.add_argument("-g", action="store_true",... |
# Generated by Django 2.0 on 2017-12-10 17:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0005_auto_20171210_1927'),
]
operations = [
migrations.CreateModel(
name='RiderReview',
... |
"""
Platform support interface for fab_support
This will redirect various tasks to the correct platform to support them
"""
from fabric.api import env
#
import fab_support.heroku as heroku
from fab_support import FabricSupportException
def env_to_platform(stage):
"""
Given a stage will return the
:param... |
#!/usr/bin/env python
import time
from hexdump import hexdump
from panda import Panda
from bitstring import BitArray, BitStream
p = Panda()
# this is a test, no safety
p.set_safety_mode(Panda.SAFETY_ALLOUTPUT)
# get version
print(p.get_version())
# **** test K/L line loopback ****
send_bus = 3
receive_bus = 2
p.s... |
from pytest import mark
from cats.v2 import ByteCodec
class TestBytesCodec:
@mark.parametrize('inp, res', (
(b'Hello', b'Hello'),
(bytearray([10]), b'\x0A'),
(memoryview(b'Hello'), b'Hello')
))
@mark.asyncio
async def test_encode_success(self, inp, res):
as... |
#!/usr/bin/env python3
import os
import sys
import connexion
sys.path.append(os.path.join(os.path.dirname(__file__)))
from cerise.config import make_config
from cerise.front_end.encoder import JSONEncoder
app = connexion.App(__name__, specification_dir='front_end/swagger/')
app.app.json_encoder = JSONEncoder
app.a... |
from api import app
from api.views import login
from api.views import hits
from api.views import authentication
app.run(host='0.0.0.0', port=8080)
|
# Copyright (C) tkornuta, IBM Corporation 2019
#
# 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 agr... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Assets/Change_Account_PIN.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 i... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 18:47:50 2017
@author: adelpret
"""
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
from dynamic_graph.sot.torque_control.hrp2.control_manager_conf import IN_OUT_GAIN
from scipy import ndimage
from identification_utils import... |
A, B = map(int, input().split())
for a in range(1, B + 1):
x = (A + (a - 1)) // a * a
y = x + a
if y > B:
continue
result = a
print(result)
|
# -*- coding: utf-8 -*-
"""exercicio-02.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1qI-SbkB65f7XZPwYaeSAdg7h1t7s-ah8
"""
5 / 2
#2.5
7 * 4 + 2
#30
(7 * 4) + 2
#30
7 * (4 + 2)
#42
2 ** 3
#8
2 ** 3 ** 4
#2417851639229258349412352
2 ** -3 ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-10-01 21:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wells', '0024_auto_20180925_2022'),
]
operations ... |
import argparse
import json
from Bio import Phylo, SeqIO
from Bio.Align import MultipleSeqAlignment
from treetime import TreeAnc
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Add translations",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add... |
from sklearn.metrics import f1_score
import torch
from dataset import Dataset
from sklearn.preprocessing import label_binarize
import sklearn.metrics as metrics
import matplotlib.pyplot as plt
import os
from torchvision import transforms
import numpy as np
from PIL import Image, ImageFilter
from torch.autograd import V... |
import json
from discord.ext.commands import Cog, Bot, Context
from utils.utils import log_event, db, get_dict
class Extension(Cog):
def __init__(self, _bot: Bot):
self.bot = _bot
@Cog.listener()
async def on_ready(self):
log_event(f'{self.qualified_name} extension loaded')
class Databa... |
# Copyright (c) 2011-2020 Eric Froemling
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish,... |
#import libraries
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from datetime import datetime
import pandas as pd
#path for webdriver
driverpath = "PATH for your chromedriver"
#load data from csv file
df = pd.read_csv("si126_namelist.csv")
urllist = list(df[df.GSX == True].for... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
import math
def samples(n):
return int(n * (math.log(n) + 0.577216) + 1.0/2.0)
experiment_name = 'final-4-AdaMax-restarts-learned'
circuit_generator_script = 'random_circuit.py'
# parameters to be tested
number_of_qubits = [4]
n = 4
number_of_cycles = [5, 10, 15, 20]
number_of_circuits = 20 #number of random ci... |
from Jumpscale import j
import random, requests, uuid
import subprocess, uuid
skip = j.baseclasses.testtools._skip
@skip("https://github.com/threefoldtech/jumpscaleX_builders/issues/50")
def before_all():
pass
def random_string():
return str(uuid.uuid4())[:10]
def info(message):
j.tools.logger._log_i... |
import json
import os
import logging
import base64
import urllib
from json import JSONDecodeError
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from pajbot.managers.db import DBManager
from pajbot.managers.redis import RedisManager
from pajbot.models.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 22 15:37:02 2018
@author: patrickmcfarlane
test_playbyplay.py
This function contains the tests for
functions in the playbyplay.py file
"""
from .__init__ import HEADERS
from ..playbyplay import PlayByPlay
def test_playbyplay():
""" tests the... |
from django.conf.urls import patterns, include, url
from views import DashboardView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^/$', DashboardView.as_view(), name="dashboard"),
)
|
from weeby.media import Gif
from weeby.overlays import Overlay
from .json_response import JSON
from .effects import Image
from .overlays import Overlay
from .media import Gif
from .generators import Generator
class Weeby:
def __init__(self, token: str) -> None:
self.token = token
def get_json_response... |
# Copyright (c) OpenMMLab. All rights reserved.
from .eval_hooks import MyDistEvalHook, MyEvalHook
from .eval_metrics import (calculate_confusion_matrix, f1_score, precision,
precision_recall_f1, recall, support, class_accuracy,
CCC_score)
from .mean_ap import avera... |
#!/usr/bin/env python3
# coding=utf-8
"""Ubiquiti Networks Discovery Protocol Tool"""
import socket
from typing import List, Tuple
from platform import platform
from uuid import getnode as get_mac
from time import time
from struct import pack
from UbntTLV import UbntTLV
from UbntTuple import lookup_tlv_type, UbntTupl... |
# -*- coding: utf-8 -*-
{
'author': u'Blanco Martín & Asociados',
'category': 'Localization/Chile',
'depends': ['l10n_cl_invoice'],
"external_dependencies": {
'python': [
'xmltodict',
'base64'
]
},
'description': u'''\n\nDTE CAF File Data Model\n\n''',
... |
import click
import os
import json
from jinja2 import Environment, FileSystemLoader
from .phlexstructure import TreeStructure, PageData, split_path
from .phlexparsers import YAMLDownParser
import sys
PHLEX_VERSION = '1.0.0'
@click.command()
@click.option('--config', '-c', default=None, help='Path to configuration f... |
n = int(input('Digite o primeiro termo da PA: '))
razao = int(input('Digite a razão da PA: '))
ultimo = n + (10 - 1) * razao
print('Os 10 primeiros termos da PA são: ', end='')
for i in range(n, razao+ultimo, razao):
print('{} '.format(i), end=' - ')
|
import asyncio
import socket
clients = []
async def handle_client(client, address):
data = f"Please welcome our new chat member from {address}"
for _client in clients:
await loop.sock_sendall(_client, data.encode('utf8'))
while data != 'BYEBYE':
data = (await loop.sock_recv(client, 1024)... |
#!/usr/bin/env python
#
# Copyright 2009 Google 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 o... |
'''
https://en.wikipedia.org/wiki/Dutch_national_flag_problem
procedure three-way-partition(A : array of values, mid : value):
i ← 0
j ← 0
k ← size of A - 1
while j <= k:
if A[j] < mid:
swap A[i] and A[j]
i ← i + 1
j ← j + 1
else if A[j] > mid:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io
import zipfile
from attrdict import AttrDict
from pprint import pprint, pformat
from fnmatch import fnmatch
from authority.base import AuthorityBase
from utils.dictionary import merge
from app import app
from config import CFG
def not_200(call):
return c... |
import csv
import datetime
import os
from metricfarmer.exceptions import ExtensionException
def target_file_csv(metrics, **kwargs):
if 'path' not in kwargs:
raise ExtensionException('Path parameter must be specified for mf.file_csv')
path = kwargs['path']
override = kwargs.get('override', False)... |
from task.models import Task
from django.db import models
from django.forms import ModelForm
from .models import Task
from django import forms
class TaskCreateForm(forms.Form):
'''
user create his task by using this form
'''
name = forms.CharField(widget=forms.Textarea,
la... |
from .base import *
class CustomerGroups(ListableApiResource, CreateableApiResource, UpdateableApiResource, DeleteableApiResource):
resource_name = 'customer_groups'
|
from datetime import datetime
from decimal import Decimal
from uuid import uuid1
HOME_TEAM_NAME = "Drip Bayless"
def fantasy_comparison_response_transformer(comparison):
home_team_stats = comparison[HOME_TEAM_NAME]
away_team_name = list(comparison.keys())[-1]
away_team_stats = comparison[away_team_name]... |
""" Copyright start
Copyright (C) 2008 - 2021 Fortinet Inc.
All rights reserved.
FORTINET CONFIDENTIAL & FORTINET PROPRIETARY SOURCE CODE
Copyright end """
import time, os
import base64
from base64 import b64encode
from integrations.crudhub import make_request, make_file_upload_request
from connectors.cyops_uti... |
# Check whether matplotlib imports cleanly
import matplotlib
|
import logging
from okdata.sdk import SDK
log = logging.getLogger()
class Status(SDK):
def __init__(self, config=None, auth=None, env=None):
self.__name__ = "status"
super().__init__(config, auth, env)
def get_status(self, uuid, retries=0):
url = self.config.get("statusApiUrl")
... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
setup(
name='ensure',
version='1.0.2',
url='https://github.com/kislyuk/ensure',
license='Apache Software License',
author='Andrey Kislyuk',
author_email='kislyuk@gmail.com',
description='Literate BDD assertions in ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-15 18:57
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies =... |
import cv2
import os
os.chdir('C:\Python27\Lib\site-packages\pytesser')
from PIL import Image
from pytesseract import *
import re
import time
from Spellcheck import correction,is_english_word
image = cv2.imread("C:/Users/Muhammad/Downloads/Design/1 Vocable/Images/OCR2.jpg")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GR... |
''' Application configurables
+ user_info
+ commands
'''
#%% User info
''' Define user information in 'account_info'.
When the application needs user-unique information,
it'll refer to this object to get login information
to email server and Robinhood.
To get value for 'phone_address', sen... |
import dlib
from os import path
from dataflow import ports
import numpy as np
class FaceDetector:
def __init__(self, threshold=0.05):
self.detector = dlib.get_frontal_face_detector()
self.threshold = threshold
self.sink_image = ports.StateSink()
def out_bounds(self):
img = sel... |
"""Squirtle mini-library for SVG rendering in Pyglet.
Example usage:
import squirtle
my_svg = squirtle.SVG('filename.svg')
my_svg.draw(100, 200, angle=15)
"""
from pyglet import gl
try:
import xml.etree.ElementTree
from xml.etree.cElementTree import parse
except:
import elementtree.Eleme... |
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def permutations(nlen, nums, path):
if not nums:
res.append(path)
for i in range(nlen):
permutations(nlen - 1, nums[:i] + nums[i + 1:], path + [nums[i]])
res = []
n... |
# convert to a single pdf - using latex
import json
import os
import re
from utils import (load_scottish_psalter, load_sing_psalms, make_output_folder,
remove_folder, zip_folder)
def create_latex_body(psalms, toc_name, output_name):
body = u'''\\documentclass[11pt,a4paper]{report}
\\setlength{... |
import torch
from torch import nn
from interpret.attr import GuidedBackProp
def test_guidedbackprop():
inp = torch.randn(1,50, requires_grad=True)
l1 = nn.Linear(50, 1)
model = nn.Sequential(nn.ReLU(), l1)
attr = GuidedBackProp(model, inp, target_class=0)
relu_inp = torch.relu(inp).detach().clon... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------... |
"""
Copyright 2013 Rackspace
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
dist... |
def _v8_disable_pointer_compression(settings, attr):
return {
"//third_party/v8/HEAD:v8_enable_pointer_compression": "False",
}
v8_disable_pointer_compression = transition(
implementation = _v8_disable_pointer_compression,
inputs = [],
outputs = ["//third_party/v8/HEAD:v8_enable_pointer_com... |
from .family import Family
from .likelihood import Likelihood
from .prior import Prior
from .scaler_mle import PriorScalerMLE
from .scaler_default import PriorScaler
__all__ = ["Family", "Likelihood", "Prior", "PriorScaler", "PriorScalerMLE"]
|
"""
=======================================================
Reading an inverse operator and view source space in 3D
=======================================================
"""
# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
print(__doc__)
from mne.datasets import sample
from mn... |
import logging
from vcftoolbox import Genotype
from puzzle.models import Genotype as puzzle_genotype
logger = logging.getLogger(__name__)
class GenotypeExtras(object):
"""Class to store methods that deals with genotyping"""
def _add_genotype_calls(self, variant_obj, variant_line, case_obj):
"""Add ... |
from django.db.models import Count, Avg, Sum, IntegerField, Case, When, Q, Min, FloatField, F
from django.db.models.functions import TruncDate
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse, JsonResponse
from django.utils.translation import ugettext as _
fro... |
#!/usr/bin/env python
# coding=utf-8
import re
import time
import subprocess as sp
from concurrent import futures
def exec_cmd(cmd):
process = sp.Popen(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
try:
start_time = time.time()
time_out = 30
while True:
i... |
#!/usr/bin/env python
import numpy as np, os, sys, joblib
import joblib
import tensorflow as tf
from tensorflow import keras
from scipy.io import loadmat
def create_model():
# define two sets of inputs
inputA = keras.layers.Input(shape=(5000,12))
inputB = keras.layers.Input(shape=(2,))
conv1 = k... |
from math import sqrt
class Numbers:
''' Contains frequently used methods for numbers '''
def isPrime(self, num):
if num <= 1:
return False
for divisor in range(2, int(sqrt(num)+1)):
if num%divisor == 0:
return False
return True
def isArmst... |
from textwrap import dedent
import pytest
import env
from lightyear import LY
from lightyear.errors import UnsupportedCommaNesting
# SELECTORS
def test_simplest():
i = 'body\n width: 32px'
o = 'body{width:32px;}'
ly = LY()
ly.eval(i)
assert ly.css() == o
def test_type_sel():
i = dedent... |
from tkinter import *
from .widgetBase import *
class ButtonOBJ(widget):
def setOnClick(self, addr):
self.attributes["onClick"] = addr
def draw(self):
#try:
#print(getattr(self.window, self.attributes["onClick"]))
obj = Button(self.window, text=self.attributes["text"], co... |
# get input
lines = []
with open('input.txt') as file:
for line in file:
lines.append(line)
def getRow( rowString, rows ):
for rowHalf in rowString:
rows = halveRow( rowHalf, rows )
# print(rows)
return rows[0]
def halveRow( half, rows ):
if half == "F":
return rows[:int(len(rows)/2)]
else :... |
import os
import pathlib
import everett.manager
import everett.ext.yamlfile
default_config_yaml = './config.yaml'
if os.environ.get('MMBC_CONFIG_FILE') is not None:
config_yaml = os.environ.get('MMBC_CONFIG_FILE')
print(f'Using config file: {config_yaml}')
else:
config_yaml = default_config_yaml
# TODO ... |
from typing import List, Tuple
from pyrep.objects.proximity_sensor import ProximitySensor
from pyrep.objects.shape import Shape
from pyrep.objects.object import Object
from rlbench.backend.task import Task
from rlbench.backend.conditions import DetectedCondition
class EmptyDishwasher(Task):
def init_task(self) -... |
import unittest
import smithwilson as sw
import numpy as np
class TestSmithWilson(unittest.TestCase):
def test_ufr_discount_factor(self):
"""Test creation of UFR discount factor vector"""
# Input
ufr = 0.029
t = np.array([0.25, 1.0, 5.0, 49.5, 125.0])
# Expected Output
... |
from model.build_model import build_model
from utils.gpu import select_device
import torch
from torch.utils.data import DataLoader
import argparse
from utils.tools import *
from utils.model_info import get_model_info
from model.data_load.datasets import CocoDataset
from model.data_load import simple_collater, AspectRat... |
# https://codeforces.com/problemset/problem/405/A
n = int(input())
cubes = [int(x) for x in input().split()]
cubes.sort()
cubes = [str(x) for x in cubes]
print(' '.join(cubes))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.