content stringlengths 5 1.05M |
|---|
import unittest
import sys
sys.path.append('..')
import modes
import os
os.system("tshark -r xml/smtp.pcap -T pdml > tmp.pdml")
class TestModeAll(unittest.TestCase):
def test_expression_false(self):
result = modes.modeAll(['AVG(fake.attr) == 5'])
self.assertEqual(result, False)
def test_syn... |
import csv
import requests
import dateutil.parser
import re
from sys import argv
from bs4 import BeautifulSoup
import scrape_util
default_sale, base_url, prefix = scrape_util.get_market(argv)
report_path = '/category/market-information/'
strip_char = ':;,. \n\t'
def get_sale_head(line):
"""Return the total num... |
"""
Copyright (c) 2021, NVIDIA CORPORATION.
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 ... |
"""
RRT_2D
@author: huiming zhou
Modified by David Filliat
"""
class Env:
def __init__(self):
self.x_range = (0, 50)
self.y_range = (0, 30)
self.obs_boundary = self.obs_boundary()
self.obs_circle = self.obs_circle()
self.obs_rectangle = self.obs_rectangle()
@staticmet... |
"""
Performance tests for the stats api.
"""
import os
import random
import tempfile
import time
import yappi
from dogapi import DogStatsApi
class NullReporter(object):
"""
A DogAPI to nowhere.
"""
def flush(self, metrics):
print('flushing metrics')
class NullDogStatsApi(DogStatsApi):
... |
def get_book_by_osis_id(id):
"""
Retrieves book meta data
:param id: the osis book id
:return:
"""
sort = find_key(id, osis_ids)
return get_book_by_sort(sort)
def get_book_by_sort(sort):
"""
Retrieves book metadata
:param sort: the sort order of the book to look up
:return:
... |
#!/usr/bin/env python
'''
Align text-bound stand-off annotations to noun phrases.
Author: Pontus Stenetorp <pontus stenetorp se>
Version: 2011-11-02
'''
# XXX: This script is a mess, should be refactored:
# * Handle ALL annotations at once, currently we don't do interactions
# between annotations f... |
# Script to translate text into proper images
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from PIL import Image
import time
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# Function to show image to screen
def show_img(s,t):
img = mpimg.imread(s)
plt.imshow(img)
p... |
from django.contrib.auth.models import User
from django.db.models import Q
from tasktrack.models import Collaborators
def get_username_from_userid(user_id):
return User.objects.get(id=user_id).username
def get_user_notifications(user_id):
current_user = User.objects.get(id=user_id)
raw_notifications = Co... |
from pathlib import Path
import zipfile
import io
import numpy as np
import holoviews as hv
from holoviews import opts
from holoviews import streams
import panel as pn
from PIL import Image
import cv2
hv.extension('bokeh')
def get_image_from_in_memory_zipfile(image_file_path, zipped_file):
return cv2.imdecode(... |
import os
import sys
import shlex
import six
encoding = os.getenv("MOCKET_ENCODING", 'utf-8')
text_type = six.text_type
byte_type = six.binary_type
basestring = six.string_types
PY2 = sys.version_info[0] == 2
if PY2:
from BaseHTTPServer import BaseHTTPRequestHandler
from urlparse import urlsplit, parse_qs, ... |
# SPDX-FileCopyrightText: 2022 Dan Halbert for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# DOESN'T WORK
import time
import board
import digitalio
def blink(pin, interval, count):
with digitalio.DigitalInOut(pin) as led:
led.switch_to_output(value=False)
for _ in range(count):
... |
import numpy as np
import pandas as pd
import random as rnd
from dsbase.KFoldDSBase import KFoldDSBase
def evaluateParams(X, y, k_fold, model_class, model_prefix_name, params_list, num_tries):
tries = {}
for i in range(num_tries):
kf = KFoldDSBase(X, y, k_fold, model_class, model_prefix_name, params_list[i])
... |
from django.template import Context
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from html2text import html2text
from tardis.tardis_portal.models import ExperimentParameter, ExperimentParameterSet, ParameterName, Schema
from tardis.tardis_portal.Parame... |
def sol():
n = int(input())
print( int(n * (n + 1) / 2) )
if __name__ == "__main__":
sol()
|
from __future__ import annotations
import random
from typing import Dict, List, Tuple, Union, Iterator, Any, TYPE_CHECKING
import tcod
import numpy as np #type: ignore
import entity_factories as ef
from game_map import GameMap
import tile_types
if TYPE_CHECKING:
from engine import Engine
from entity import ... |
import sys
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import os
import numpy as np
import glob
sys.path.append("/home/smp16fm/forked_amrvac/amrvac/tools/python")
from amrvac_pytools.datfiles.reading import amrvac_reader
from amrvac_pytools.vtkfiles import read, amrplot
def subplot_animat... |
"""
ID: tony_hu1
PROG: pprime
LANG: PYTHON3
"""
import math
def generate_primes(smallest,largest):
outstring = ''
if smallest == 5:
outstring = '5\n'
odd = {0,2,4,5,6,8}
for i in range(smallest,largest+1):
if not i in odd:
if is_pal(i):
if is_prime(i):
... |
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/1387
#!/usr/bin/env python2.7
# encoding : utf-8
while True:
a,b = [int(i) for i in raw_input().split(" ")]
if a== 0 and b == 0:
break
else:
print a+b
|
# 1514. Path with Maximum Probability
# User Accepted:1828
# User Tried:3791
# Total Accepted:1908
# Total Submissions:9912
# Difficulty:Medium
# You are given an undirected weighted graph of n nodes (0-indexed),
# represented by an edge list where edges[i] = [a, b] is an undirected edge connecting
# the nodes a and ... |
#!/usr/bin/env python
#
# Jiao Lin
"""
compute multiple scattering
"""
def sqe(mpsqe, Ei):
"""given multiphonon SQE, compute multiple scattering sqe
"""
# multiple scattering (MS) is uniform along Q
# so we want to compute the average S from multi-phonon
# scattering and assign the value to MS r... |
# Copyright 2018
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
import sys
from ..converter import Converter, ConversionError, ValidationError
class Ginkgo(Converter):
"""Convert Transcriptic samples.json to sample-set schema"""
VERSION = '0.0.2'
FILENAME = 'ginkgo_samples'
def convert(self, input_fp, output_fp=None, verbose=True, config={}, enforce_validation=Tru... |
import csv
file_path = 'D:/Programming/web/Python/Python-Basic-02/141-Memperbarui File CSV/myfile2.csv'
tmp_file = []
fieldnames = ['no','nama','profesi']
# # Mengubah data pada kolom
# Membaca dan menyalin data pada file ke variable list
with open(file_path, mode='r', newline='\n') as my_file_csv:
file = csv.Di... |
import datetime
from services.db.database import DbSingleton, Round, RoundImport
from services.rounds import Rounds
def test_round_import_with_lead_investor():
db = DbSingleton.get_instance()
db.prep_test()
# create mock objects
RoundImport.create(
uuid='asdf',
name='Test Name',
... |
#!/usr/bin/python
# Copyright 2021 Northern.tech AS
#
# 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 ap... |
"""Message packet."""
import re
from collections import namedtuple
from .packet import Packet
class MessageComponent(namedtuple("Component", ("type", "data", "text"))):
""":obj:`MessagePacket` component.
Valid Types:
========= ===================================== ===================
Type ... |
from __future__ import print_function
import sys
import mxnet as mx
import numpy as np
import random
import datetime
import multiprocessing
import cv2
from mxnet.executor_manager import _split_input_slice
from rcnn.config import config
from rcnn.io.image import tensor_vstack
from rcnn.io.rpn import get_rpn_testbatch, ... |
# -*- coding: utf-8 -*-
# @Time : 2020-01-10 15:38
# @Author : yingyuankai
# @Email : yingyuankai@aliyun.com
# @File : tnew_transformer.py
import os
from tqdm import tqdm
import json
import logging
import numpy as np
# import hanlp
import pickle
from random import random, randrange
from pathlib import Path
f... |
# -*- coding: utf-8 -*-
"""
Create ORS programs for newly defined programs in Aasaan
"""
from datetime import date
import json
from collections import Counter
from django.core.management.base import BaseCommand
from schedulemaster.models import ProgramSchedule, ProgramScheduleCounts, \
ProgramCountMaste... |
import numpy as np
from model.constant_variables import Z_field, Z_lab
def set_up_model_geometry(geom="FieldScale0.5m"):
"""
Set-up model geometry
Arguments
------------------------------
geom Flag for geometry of choice
Results
---------------------------
n... |
import os
import operator
class grid_cell:
def __init__(self, distance = 0, coord = 0):
self.distance = distance
self.coord = coord
input = open('input.txt', 'r')
coords = []
for row in input:
coords.append((int(row[:row.find(',')]),int(row[row.find(' ')+1:-1])))
input.close()
#... |
'''Defines the `JavaCompilationInfo` provider.
'''
JavaCompilationInfo = provider(
doc = "Describes the inputs, outputs, and options of a Java compiler invocation for a particular Java target.",
fields = {
"srcs": "A depset of the Java source `File`s directly included in a Java target. (This does not i... |
"""A script which helps users create their nengo_spinnaker config file."""
import argparse
from nengo_spinnaker.utils.paths import nengo_spinnaker_rc
from rig import wizard
import os
CONFIG_TEMPLATE = """\
### SpiNNaker system configuration.
# File automatically generated by nengo_spinnaker_setup.
[spinnaker_mach... |
#Types.
from typing import Dict, List, Any
#Meros class.
from python_tests.Meros.Meros import Meros
#NodeError Exception.
from python_tests.Tests.Errors import NodeError
#JSON standard lib.
import json
#Socket standard lib.
import socket
#RPC class.
class RPC:
#Constructor.
def __init__(
self,
... |
import sys
f = open(sys.argv[1], "r")
class container:
def __init__(self, _type):
self._type = _type
self.open = False
self.burnt = False
prntStack = []
burnables = []
curCont = container(None)
usedTypes = []
lineNum = 0
pages = {}
for line in f.readlines():
parts = line.split()
... |
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(XA,yA)
yP = knn.predict(XB) |
"""
Unit tests for examples/*.
"""
import pytest
from pathlib import Path
# this is a workaround to print text, which is printed during import time, before tests are run
# to guarantee independence of test run order
from abcvoting.output import WARNING
from abcvoting.output import output
from test_abcrules import re... |
import argparse
DEFAULT_VOCAB_FILE = "glove-6b-zip/glove.vocab.txt"
DEFAULT_VECTOR_FILE = "glove-6b-zip/glove.6B.300d.txt"
parser = argparse.ArgumentParser()
parser.add_argument('--vocab_file', default=DEFAULT_VOCAB_FILE, type=str)
parser.add_argument('--vectors_file', default=DEFAULT_VECTOR_FILE, type=str)
|
import os
import py # NOQA
import pytest
import re
import shutil
import subprocess
import tempfile
from types import TracebackType # NOQA
from typing import Any # NOQA
from typing import IO # NOQA
from typing import List # NOQA
from typing import Optional # NOQA
from typing import Tuple # NOQA
from typing import... |
from pynput.keyboard import Key, Controller, Listener
import pynput
import keyboard
import time
class MyKeyboard:
controller = Controller()
geral = []
def on_press(self, key):
print('{0} pressed'.format(
key))
self.geral.append({"pressed": key})
def on_release(self, key):... |
# Copyright 2017 Alethea Katherine Flowers
#
# 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... |
"""
Definitions of the tier 6 food items: Melon, Mushroom, Pizza, and Steak.
"""
__all__ = ['Melon', 'Mushroom', 'Pizza', 'Steak']
# Local application imports
from gym_snape.game.food import Food
# Third party imports
import numpy as np
class Melon(Food):
def __init__(self):
super().__init__()
... |
from setuptools import setup
from buildconf import BuildUnrarCommand
from distutils.command.build import build
with open("README.md", "r") as fh:
long_description = fh.read()
class BuildUnrarBeforeBuild(build):
def run(self):
self.run_command('build_unrar')
build.run(self)
setup(
cmdclas... |
import os
import sys
print("--- SOME DIAGNOSTIC VALUES: ---")
print("\nsys.executable: ", sys.executable)
print("\ncwd (Current Working Directory): ", os.getcwd())
print("\nsys.path: ", sys.path)
print("\nsys.path again, this time on separate lines: ")
for p in sys.path:
print(" ", p)
|
#!/usr/bin/env python
from mil_msgs.msg import ObjectInImage
from std_msgs.msg import Header
import cv2
import numpy as np
from mil_msgs.msg import Point2D
class Overlay:
def __init__(self, header,object_in_image, color = (0,255,0), brush = 3, font = cv2.FONT_HERSHEY_SIMPLEX, font_scale=1, *args, **kwargs):
... |
#!/usr/bin/env python
import argparse
import logging
from dataclasses import dataclass, field
from typing import List
from rl_rpsr import bsr, pomdp, psr, rpsr
from rl_rpsr.policy import ModelPolicy, Policy, RandomPolicy
from rl_rpsr.serializer import IntentsSerializer, TestsSerializer, VF_Serializer
def make_policy... |
# coding: utf-8
# # The Basal Ganglia
#
# The basal ganglia
# according to [Stewart 2010](http://compneuro.uwaterloo.ca/files/publications/stewart.2010.pdf)
# is an action selector
# that chooses whatever action has the best "salience" or "goodness".
# Its really interesting behaviour manifests itself
# when it inte... |
import xmltodict
settings = dict()
def load_settings():
global settings
with open('Data/settings.xml') as f:
settings = xmltodict.parse(f.read())['settings']
return settings
def check_min_setup():
param_missing = False
if not get_app_token():
param_missing = True
print('ap... |
import pandas as pd
from datetime import datetime, date, timedelta
import numpy as np
import os
from pathlib import Path
from pandas.core.frame import DataFrame
from ETL import DataLoader
import logging, coloredlogs
import dicts_and_lists as dal
pd.options.mode.chained_assignment = None
# ------ Logger ------- #
logge... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
"""trojsten_judge_client - Client for Trojsten Judge System."""
__author__ = 'Michal Hozza <mhozza@gmail.com>'
__all__ = []
|
from django import forms
from newExam.expense_app.models import Expense
class ExpenseForm(forms.ModelForm):
class Meta:
model = Expense
fields = '__all__'
widgets = {'description': forms.Textarea(attrs={'rows': 10, 'columns': 40})}
class DeleteExpenseForm(ExpenseForm):
def __init__(... |
import sys
from pathlib import Path
DAVIS16_DIR = Path('/home/achald/research/misc/datasets/davis/davis-2016/')
DAVIS17_DIR = Path('/home/achald/research/misc/datasets/davis/davis-2017/')
if not DAVIS16_DIR.exists():
raise ValueError(
"Could not find DAVIS 2016 repo at %s. Please edit the path in %s.",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import sys
if sys.version_info[0] == 2:
raise Exception('python3 required.')
install_requirements = [
'sanic==18.12.0',
'Jinja2==2.10'
]
setup(
name='Sanic_Jinja',
version='0.0.1',
url='https://github.com/htwenning/sa... |
# stdlib
import socket
# 3p
from nose.plugins.attrib import attr
# project
from tests.checks.common import AgentCheckTest
@attr(requires='riak')
class RiakTestCase(AgentCheckTest):
CHECK_NAME = 'riak'
CHECK_GAUGES = [
'riak.node_gets',
'riak.node_gets_total',
'riak.node_puts',
... |
# RUN: %PYTHON %s
# TODO: Numpy compiler has bitrotted.
# XFAIL: *
from npcomp.compiler.numpy.backend import iree
from npcomp.compiler.numpy.frontend import *
from npcomp.compiler.numpy import test_config
from npcomp.compiler.numpy.target import *
from npcomp.compiler.utils import logging
# TODO: This should all exis... |
#!/usr/bin/env python
# Copyright (c) 2014 v3aqb
#
# 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,... |
# Generated by Django 3.2.5 on 2021-08-05 10:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('db', '0005_auto_20210728_0612'),
]
operations = [
migrations.AddField(
model_name='site_results',
name='count',
... |
import maya.cmds as cmds
import maya.OpenMaya as OpenMaya
import maya.OpenMayaUI as OpenMayaUI
import maya.OpenMayaRender as OpenMayaRender
from PySide import QtCore, QtGui
from shiboken import wrapInstance
import math
class KeyboardEvents(QtCore.QObject):
def __init__(self, view3D = OpenMayaUI.M3dView.active3d... |
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^login/$', auth_views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^register/$', views.user_create, name='user_create'),
url(r'^verify/$', views... |
import typing
from string import punctuation
def clear_punctuation(text: str) -> str:
"""Очищает полученный string от пунктационных знаков не учитывая пробелы"""
return ''.join([simbol for simbol in text if simbol not in punctuation])
def lower_and_split(text: str) -> typing.List:
"""
Переводим все ... |
from flask_wtf import FlaskForm
from wtforms.fields.html5 import IntegerField, DecimalField
from flask_security.forms import ConfirmRegisterForm
from wtforms.validators import (
InputRequired, DataRequired, EqualTo, URL, NumberRange,
Length,
)
from wtforms import (
BooleanField, StringField, PasswordField, ... |
import math
import torch
import numpy as np
import torch.nn.functional as F
from src.utils.utils import l2_normalize
class MoCo(object):
def __init__(self, outputs1, outputs2, queue, t=0.07):
super().__init__()
self.outputs1 = l2_normalize(outputs1, dim=1)
self.outputs2 = l2_normalize(ou... |
import tensorflow as tf
from .logger import (StepLoggerHook,
LossLoggerHook,
AccuracyLoggerHook,
TimeLoggerHook,
EolLoggerHook)
def hooks(display_step, last_step, batch_size, loss, accuracy):
return [
tf.train.StopAtStepH... |
import typing
from TorchTSA.simulate.ARMASim import ARMASim
class ARSim(ARMASim):
def __init__(
self,
_phi_arr: typing.Union[float, typing.Sequence[float]],
_mu: float = 0.0, _sigma: float = 1.0,
):
if isinstance(_phi_arr, float) or isinstance(_phi_arr, int):
... |
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from datetime import datetime
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
MEMBERSHIP_CHOICES = (
('Enterprise', 'ent'),
('Professional', 'pro'),
('Free', 'free')
)
# Create your models here.
... |
import unittest, time
from src.tic_toc import tic, toc, Timer
class TestTicToc(unittest.TestCase):
def test_tic_toc(self):
pause = 2
t = tic()
time.sleep(pause)
elapsed = toc(t)
self.assertAlmostEqual(elapsed, pause, places=1)
def test_helper_class(self):
paus... |
# -*- coding: utf-8 -*-
"""
Created on Mon July 9 22:20:12 2018
@author: Adam
"""
import os
import sqlite3
import numpy as np
import pandas as pd
from datetime import datetime
from emonitor.core import TABLE, DATA_DIRE
from emonitor.tools import db_path, db_init, db_check, db_describe, db_insert
from emonitor.data imp... |
from django.urls import path
from . import views
urlpatterns = [
# path('', views.list, name='blog'),
# path('<int:id>/', views.post, name='post'),
path('', views.PostListView.as_view(), name='blog'),
# path('<int:pk>/', views.PostDetailView.as_view(), name='post'),
path('<int:pk>/', views.post, na... |
from __future__ import unicode_literals
import argparse
import logging
from dvc.pkg import PkgManager
from dvc.exceptions import DvcException
from .base import CmdBase, CmdBaseNoRepo, fix_subparsers, append_doc_link
logger = logging.getLogger(__name__)
class CmdPkgInstall(CmdBase):
def run(self):
try:... |
#!/usr/bin/env python3
from enum import IntEnum
import time
import rospy
from threading import Thread
from dorna_enums import HumanResponse, DornaMovement
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from moveit_msgs.msg import RobotState, RobotTrajectory, DisplayTrajectory, CollisionObject
... |
#------------------
# Script to calculate EKE from ERA-interim files (currently 6-hourly)
# Taken from ipython notebook
#
# Written by Rachel White (rachel.white@cantab.net) on 15-Dec-2016
#-------------------
import os, errno
import netCDF4
import numpy as np
import datetime as dt
import pandas as pd
import xray as xr... |
from itertools import chain
import pygame
import sys
import time
import classes.lemmings
from functions.level_utilities import level_load_save, level_save, level_create
from global_variables import BLOCK_DEFAULT_SIZE, LEVEL_DEATH_FRAMES, LEVEL_FRAME_TIME,\
LEVEL_BACKGROUND_COLOR, LEVEL_TEXT_COLOR
def level_run(s... |
from django.db import models
from django_resized import ResizedImageField
# Create your models here.
def upload_directory(instance,filename):
ext = filename.split('.')[-1]
return f'user_{instance.id}/profile_picture.'+ext
class User(models.Model):
username = models.CharField(max_length=100,unique=True)
... |
# -*- coding: utf-8 -*-
from icemac.addressbook.i18n import _
import datetime
import icemac.addressbook.browser.base
import icemac.addressbook.interfaces
import icemac.truncatetext
import z3c.pagelet.browser
import z3c.table.batch
import z3c.table.column
import z3c.table.table
import zope.i18n
END_OF_DATE = datetime.... |
__author__ = "rolevin"
from typing import List, Optional
from synapse.ml.cyber.utils.spark_utils import DataFrameUtils, ExplainBuilder
from pyspark.ml import Transformer
from pyspark.ml.param.shared import Param, Params
from pyspark.sql import DataFrame, functions as f, types as t
import random
class ComplementAcc... |
import sys, os
import numpy as np
import statsmodels.stats.multitest
if (len(sys.argv) < 4):
print("python3 fdrPASTAAResult.py PASTAA_result, outputFile, pvalue")
else:
PASTAA_result = sys.argv[1]
output_ = sys.argv[2]
p = float(sys.argv[3])
TFs = []
pvalues = []
#read result
with op... |
# vim:set ts=4 sw=4 et:
'''
ImageName
---------
'''
import logging
import re
try:
from urllib.parse import parse_qs, urlsplit
except ImportError:
# python2
from urlparse import parse_qs, urlsplit
from ..action_mapper import Action
from ..exceptions import (ConfigurationException, InvalidRequestException,
... |
import numpy as np
import pria_lifechem
import os
from pria_lifechem.function import *
from pria_lifechem.models.CallBacks import *
from pria_lifechem.models.deep_classification import *
from pria_lifechem.models.deep_regression import *
task_list = ['cross_validation_Keck_Pria_AS_Retest', 'cross_validation_Keck_FP',... |
#!/usr/bin/python3
#‑∗‑ coding: utf‑8 ‑∗‑
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.utils.tensorboard as tensorboard
from random import choices
from collections import deque
class Agent:
""" Initialize agent.
Args:
nb_actions ... |
from django.contrib import admin
from .models import RuleSet, ProfilingRecord
class RuleSetAdmin(admin.ModelAdmin):
list_display = (
'enabled',
'uri_regex',
'user_filter_type',
'user_group_filter',
)
class ProfilingRecordAdmin(admin.ModelAdmin):
list_display = (
... |
import sys
import os
#sys.path.append(os.path.abspath(sys.path[0]+"/src/streamline/model_selection/models/"))
from ..AbstractRegressorPredictiveModel import AbstractRegressorPredictiveModel
from sklearn.linear_model import Lasso
class LassoRegressorPredictiveModel(AbstractRegressorPredictiveModel):
#properties
... |
from typing import Callable
import schedule
from . import constants as c
from .gpsd import GPSD
from .logging import get_logger
from .server import Server
logger = get_logger(__name__)
def schedule_job(job: Callable, seconds: int) -> None:
"""Clear a previously running job, if exists, and launch it again"""
... |
# -*- coding: utf-8 -*-
# Copyright (2017) Hewlett Packard Enterprise Development LP
#
# 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... |
# proxy module
from __future__ import absolute_import
from mayavi.sources.image_reader import *
|
from .StructureConsensuLossFunction import StructureConsensuLossFunction
|
#Import("env", "projenv")
import os
import shutil
import glob
import pathlib
def readall(path):
f = open(path, 'r')
data = f.read()
f.close()
return data
def create_name_from_filename(filename):
ret = filename
ret = ret.replace(".", "_")
ret = ret.replace(" ", "_")
return ret
EMBED... |
#!/usr/bin/python3
import argparse
import glob
import os
# This should be in the remote server in /root/messages_to_download.py
# This file is part of https://github.com/cpina/science-cruise-data-management
#
# This project was programmed in a hurry without any prior Django experience,
# while circumnavigating the A... |
"""
This scripts allows to play with the 4 parameters of the backlash model.
Based on matplotlib's interactive slider demo
.. seealso::
https://matplotlib.org/3.1.1/gallery/widgets/slider_demo.html
"""
from typing import Union
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matp... |
from typing import Tuple
__all__: Tuple[str, ...] = (
"AlexFlipnoteException",
"BadRequest",
"NotFound",
"InternalServerError",
"Forbidden",
"HTTPException",
)
class AlexFlipnoteException(Exception):
pass
class BadRequest(AlexFlipnoteException):
pass
class NotFound(AlexFlipnoteEx... |
import lgsvl
import time
from environs import Env
from ..scenario import Scenario
from .common import spawn_state, place_car_on_the_point
env = Env()
LGSVL__SIMULATOR_HOST = env.str("LGSVL__SIMULATOR_HOST", "127.0.0.1")
LGSVL__SIMULATOR_PORT = env.int("LGSVL__SIMULATOR_PORT", 8181)
LGSVL__AUTOPILOT_0_HOST = env.str("... |
'''
This sets the callback for reloading a user from the session. The function
you set should take a user ID (a unicode) and return a user object, or
None if the user does not exist.
'''
from google.appengine.ext import ndb
def user_callback(user_id):
# Because we are always provided an unicode here, we use the ... |
import json
import os
from os import path as osp
from random import choice
import re
import shutil
from subprocess import PIPE, Popen, check_call, check_output
import time
import threading
import urllib2
import sys
from behave import given, when, then # pylint: disable=E0611
from pyvs import helpers
from pyvs.helpers... |
"""
* MIT License
*
* Copyright (c) 2019 Arpit Aggarwal Shantam Bajpai
*
* 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 ... |
import socket
import threading
from django.core.handlers.wsgi import WSGIHandler
from django.core.servers import basehttp
from django.test.testcases import TransactionTestCase
from django.core.management import call_command
class StoppableWSGIServer(basehttp.WSGIServer):
"""WSGIServer with short timeout, so that ... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Tests for partition functions from equivalence.py"""
import unittest
from typing import Any, Iterable
from beanmachine.ppl.utils.equival... |
from torch import optim
from torch.nn import MSELoss
import torch.nn.functional as F
AGENT_CONFIG = {
# 'lr' indicates the learning rate of the "mainbody".
# Value-based RL: Q net; Policy-based RL: Policy net; Actor-critic RL: Actor
'lr':0.01,
'mom':None,
'reward_decay':0.9,
'memory_size': 1e6,... |
# Copyright 2015 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 page_sets.login_helpers import login_utils
from telemetry.core import util
from telemetry.page import action_runner as action_runner_module
def GetGai... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from typing import Optional
import mmap
from kgx.cli.cli_utils import transform # type: ignore
from kg_idg.transform_utils.transform import Transform
"""
Ingest KGX-format human protein-protein interactions from
STRING. Filter by interaction confidence
(combi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.