content stringlengths 5 1.05M |
|---|
from src.commands.Command import Command
from src.models.domain.User import User
from src.utilities.database import db_session
class AddStrandUserToTeamCommand(Command):
"""
1) Grab additional user info from Slack
2) Either create user with the team, or just attach existing user to the team
... |
import numpy as np
import scipy.signal
import matplotlib.pyplot as plt
from skimage import io, color
from skimage import exposure
img = io.imread('lena_gray.jpg') # Load the image
img = color.rgb2gray(img) # Convert the image to grayscale (1 channel)
# apply sharpen filter to the original image
# sharpen_kerne... |
import pandas as pd
from death.unified.uni import *
if __name__ == '__main__':
# test_all_for_AUROC_0(epoch=40, test_stat_dir="40epoch")
# test_all_for_AUROC_0(epoch=20, test_stat_dir="20epoch")
test_all_for_AUROC_0(epoch=4, test_stat_dir="4epoch")
# all_working_1()
# transformer200() |
import os
import genshinstats as gs
import pytest
import urllib3
# unless anyone knows how to inject certificates into a github workflow this is required
try:
gs.get_langs()
gs.search("a")
except urllib3.exceptions.SSLError:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
gs.genshi... |
from django.apps import AppConfig
class DatasetConfig(AppConfig):
name = 'volumes'
verbose_name = 'Scaleout Dataset'
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from gaiatest import GaiaTestCase
from gaiatest.apps.settings.app import Settings
class TestWallpaper(GaiaTestCase):
... |
#!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import argparse
import os
import re
from time import sleep
from subprocess import check_call
from io import BytesIO
import pexpect
def get_argparser(ArgumentParser=argparse.Argum... |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup, find_packages
APP = ['moonticker.py']
DATA_FILES = []
OPTIONS = {
'argv_emulation': True,
'plist': {
'LSUIElement': True,
},
'packages': ['rumps', 'requests', 'certifi']
}
setup(
... |
# helper file of droidbot
# it parses command arguments and send the options to droidbot
import argparse
import input_manager
import input_policy
import env_manager
from droidbot import DroidBot
from droidmaster import DroidMaster
def parse_args():
"""
parse command line input
generate options including h... |
# python-mqlight - high-level API by which you can interact with MQ Light
#
# Copyright 2015-2017 IBM Corp.
#
# 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/licens... |
import pymc3_ext as pm
import numpy as np
from numpy import random as nr
import numpy.testing as npt
import pytest
import theano.tensor as tt
import theano
from pymc3_ext.distributions.distribution import _draw_value, draw_values
from .helpers import SeededTest
def test_draw_value():
npt.assert_equal(_draw_value... |
"""
Drop-in replacement class for unittest.TestCase.
"""
from pedal.assertions.runtime import *
class PedalTestCase:
"""
Drop-in replacement for the existing unittest.TestCase class. Emulates
the original interface, but also supports all the Pedal features, allowing
an easier transition to our toolset... |
class Solution:
def subsets(self, nums):
if len(nums) == 0:
return []
if len(nums) == 1:
return [[], nums]
subs = [[], nums]
for i, el in enumerate(nums):
newSubs = self.subsets(nums[:i] + nums[i+1:])
for s in newSubs:
... |
#!/usr/bin/env python3
#
# Author:
# Tamas Jos (@skelsec)
#
import enum
# https://tools.ietf.org/html/rfc4513
# simple auth:
# - anonymous
# - user without password
# - username + password
#
# SASL:
# - plain
# - gssapi
# -SSPI
# - NTLM
# - KERBEROS
# Sicily:
# - NTLM
# Multiplexor
#
class LDAPAut... |
import numpy as np
from scipy.optimize import curve_fit
from scipy.special import *
import parsers
def load_slices(fname):
gout = parsers.parse_genesis_out(fname)
slices = gout['slice_data']
zsep = gout['input_parameters']['zsep']
xlamds = gout['input_parameters']['xlamds']
Nslice = len(slices)
... |
#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
"""Advanced calculator."""
import math
import operator
CONSTANTS = {
"pi": math.pi,
"e": math.e,
"t": math.tau,
}
BINARY_OPERATORS = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"^": ... |
import os
import click
from diana.apis import DcmDir
from diana.dixel import DixelView
from diana.plus.halibut import get_mobilenet
epilog = """
\b
$ diana-plus classify resources/models/view_classifier/view_classifier.h5 tests/resources/dcm IM2263
Classifying images
------------------
Predicted: negative (0.88)
"""
... |
import functools
import operator
import day03.data as data
def part1():
value = data.INPUT
mod = len(value[0])
tree_idx = 0
tree_count = 0
row_count = len(value)
for row_idx in range(row_count):
tree_idx = row_idx * 3
if value[row_idx][tree_idx % mod] == "#":
tr... |
"""
MIT License
Copyright (c) 2020 Collin Brooks
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 time
import asyncio
async def fn(delay,msg):
await asyncio.sleep(delay)
print(msg,'at',str(int(time.time())))
async def main():
print('Create tasks at',int(time.time()))
sec = (0x00)
t1 = asyncio.create_task(fn(sec+3,'Task 1'))
t2 = asyncio.create_task(fn(sec+2,'Task 2'))
t3 = asyncio.create_task(fn(s... |
"""
The strategy is inspired and derived from Turtle Trading System
Rules:
Entries:
Turtles entered positions when the price exceeded by a single tick the
high or low of the preceding 20 days. If the price exceeded the 20-day high, then the
Turtles would buy one Unit to initiate a long position in the cor... |
import os
import time
import numpy as np
from functions.model import Classifier
from functions.utils import Utilities
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets
import torchvision.models as models
class UnNormalize(object):
... |
# Generated by Django 3.0.5 on 2020-04-23 02:53
from decimal import Decimal
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... |
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
#SE CREA EL DIRECTORIO DE NUESTRO ARCHIVO PARA LA BASE DE DATOS
directory = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
#SE CONFIGURA LA BASE DE DATOS Y SE ESTABLECE PARA CREAR E... |
import snakerf as srf
import matplotlib.pyplot as plt
import numpy as np
from math import inf, pi, log2
from scipy import signal
# see https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.periodogram.html#scipy.signal.periodogram
m = 3
data = '{0:0{1:d}b}'.format(srf.gold_codes(m)[2], 2**m - 1)
print(dat... |
#!/usr/bin/env python3
import sys
import rospy
import actionlib
from control_msgs.msg import (FollowJointTrajectoryAction,
FollowJointTrajectoryGoal,
GripperCommandAction,
GripperCommandGoal)
from trajectory_msgs.msg import Join... |
from . import commands
from .task import BaseTask
from .utils import echo
from .worker import Worker
|
"""
This module contains the structs necessary to represent an automata.
"""
from __future__ import annotations
import logging
from typing import Any, Dict, Iterable, List, Set, Tuple, Union
from numlab.automata.state import State
from numlab.automata.transition import Transition
_ATMT_COUNT = 0
class Automata:
... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Tiago de Freitas Pereira <[email protected]>
# Tranformers based on tensorflow
import os
import pkg_resources
from bob.learn.tensorflow.utils.image import to_channels_last
from sklearn.base import TransformerMixin, BaseEstimator
from bob.extension.download... |
from .average_meter import AverageMeter
from .early_stopping import EarlyStopping
|
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems 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.o... |
import numpy as np
from src.data import Problem, Case, Matter
class TrimBackground:
"""pick first matter and trim background"""
def __init__(self):
pass
@classmethod
def array(cls, x_arr, background=0):
"""
:param x_arr: np.array(int), array to trim
:param background: ... |
from .sector import Sector
from github import Github
import re
import numpy as np
class Repository(Sector):
def __init__(self, currency, github_api, github_url, **kwargs):
super(Repository, self).__init__(currency, **kwargs)
self.type = 'repository'
self.github_url = self.sanitize_url(gith... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.core.management import call_command
fixture = 'licences'
def load_fixture(apps, schema_editor):
call_command('loaddata', fixture, app_label='editor')
def unload_fixture(apps, schema_editor):
Licenc... |
from datetime import datetime, timedelta
import rest_framework
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.exceptions import PermissionDenied
from rest_framework import status
from django.contrib.auth import get_user_mo... |
# -*- coding: utf-8 -*-
import click
from aiida.utils.cli import command
from aiida.utils.cli import options
from aiida_quantumespresso.utils.cli import options as options_qe
from aiida_quantumespresso.utils.cli import validate
@command()
@options.code(callback_kwargs={'entry_point': 'quantumespresso.pw'})
@options.s... |
import os
import time
import tkinter
import sqlite3
import json
import smtplib
import locale
import requests
import threading
import html2text as h2t
from tkinter import *
from tkinter.ttk import *
from tkinter import filedialog
from tkinter import messagebox
from email import encoders
from email.mime.text import MIMET... |
import argparse
import hashlib
import logging
logging.basicConfig(level=logging.INFO)
from urllib.parse import urlparse
import datetime
import os
import pandas as pd
logger = logging .getLogger(__name__)
def main(filename):
logger.info('starting cleaning process')
df = _read_data(filename)
df = _extract... |
#!/usr/bin/env python3
"""
File: test_aml
Element: AML
Title: Test Address Match List
"""
import unittest
from bind9_parser.isc_utils import assertParserResultDict, acl_name, \
key_id, key_id_list, key_id_list_series, \
key_id_keyword_and_name_pair, \
parse_me
from bind9_parser.isc_aml import aml_choices... |
from distutils.core import setup
setup(
name = 'SWMat',
packages = ['SWMat'],
version = '0.1.4',
license='Apache License 2.0',
description = 'A package for making stunning graphs/charts using matplotlib in just few lines of code!',
author = 'Puneet Grover',
author_email = '[email protected]',
... |
#/usr/bin/env python
#
# setup.py
#
# John Van Note
# 2017-03-05
#
# setup.py for the Markov Chain project
#
import os
from setuptools import setup
setup(
name='markov-tweetbot',
version='0.0.1',
author='John Van Note',
author_email='[email protected]',
description='Python implementation... |
template = """
module rom32x4 (
input [4:0] addr,
input clk,
output [4:0] data);
wire [7:0] rdata;
wire [15:0] RDATA;
wire RCLK;
wire [10:0] RADDR;
SB_RAM40_4KNR #( // negative edge readclock so we can apply and addres on the positive edge and guarantee data is available on the next posedge
.WRITE_MODE(... |
import numpy as np
from numba import prange
from ...geometry._algorithms.bounds import total_bounds_interleaved
from ...geometry._algorithms.orientation import triangle_orientation
from ...utils import ngjit, ngpjit
@ngjit
def segment_intersects_point(ax0, ay0, ax1, ay1, bx, by):
"""
Test whether a 2-dimensi... |
import numpy as np
def gamma(bilde, g=0.5):
"""
Gitt et HDR-bilde, returnerer resultatet av å gjennomføre enkel
rendring ved hjelp av en gamma-funksjon.
Parameters
----------
bilde : ndarray
Et bilde som kan ha ubegrenset antall dimensjoner/kanaler.
g : <0, 1> float
Gamma-... |
import networkx as nx
import graph_embeddings_library as gel
from Analysis.aggregate_data.data_aggregation_tools import create_graph_from_AS_relationships
graph = nx.Graph()
method = 'node2vec'
if method == 'example':
graph = nx.Graph()
graph.add_nodes_from(['a', 'b', 'c'])
method = 'example'
dict_arg... |
# -*- coding: utf-8 -*-
import sdata
from sdata.workbook import Workbook
import pandas as pd
import numpy as np
def test_blob():
wb = Workbook(name="workbook",
description="A excel like workbook",
)
print(wb)
assert wb.name == "workbook"
s0 = wb.create_sheet(1)
... |
import FWCore.ParameterSet.Config as cms
# Calorimetry Digis (Ecal + Hcal) - * unsuppressed *
# returns sequence "calDigi"
from SimCalorimetry.Configuration.ecalDigiSequence_cff import *
from SimGeneral.Configuration.SimGeneral_cff import *
doAllDigi = cms.Sequence(ecalDigiSequence)
pdigi = cms.Sequence(cms.SequenceP... |
import matplotlib.pyplot as plt
import numpy as np
from thermo import *
from fluids.numerics import logspace
ethanol_psat = VaporPressure(Tb=351.39, Tc=514.0, Pc=6137000.0, omega=0.635, CASRN='64-17-5')
ethanol_psat.plot_T_dependent_property(Tmin=400, Tmax=500, methods=['BOILING_CRITICAL', 'SANJARI', 'LEE_KESLER_PSAT'... |
from builtins import object
import glob
import os.path
from . import class_loader
class AlgorithmLoader(object):
@classmethod
def load_agent(cls, algorithm_path, algorithm_name):
return cls.load_algorithm_class(algorithm_path, algorithm_name, 'agent.Agent')
@classmethod
def load_parameter_... |
from experiments.gamut_games import *
from prettytable import PrettyTable
from algorithms.algorithms import global_sampling, psp
from structures.gamestructure import path_to_nfg_files
from experiments.noise import UniformNoise
from structures.bounds import HoeffdingBound
import pandas as pd
import ast
import time
def... |
# Generated by Django 2.2.8 on 2020-02-21 23:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('submissions', '0010_submissioncomment'),
]
operations = [
migrations.AddField(
model_name='submission',
name='status... |
import re
import collections
import logging
from dynamo.registry.registry import RegistryDatabase
from dynamo.dataformat import Configuration, Block, ObjectError, ConfigurationError
LOG = logging.getLogger(__name__)
class UnhandledCopyExists(object):
"""
Check for pending transfer requests made to Dealer.
... |
#
# ANIAnnc.py
#
# (c) 2020 by Andreas Kraft
# License: BSD 3-Clause License. See the LICENSE file for further details.
#
# ANI : Announceable variant
#
from .MgmtObjAnnc import *
from Types import ResourceTypes as T, JSON
from Validator import constructPolicy, addPolicy
# Attribute policies for this resource are con... |
#!/usr/bin/python
# Classification (U)
"""Program: masterrep_connect.py
Description: Unit testing of MasterRep.connect method in mysql_class.py.
Usage:
test/unit/mysql_class/masterrep_connect.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_... |
from criaenvio.cliente import APIClienteCriaEnvio
class EnvioCriaEnvioAPI(APIClienteCriaEnvio):
RECURSO = 'envios'
|
#############################################################################
#Copyright (c) 2010, Jo Bovy, David W. Hogg, Dustin Lang
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
# Redistrib... |
# Copyright 2019 Jake Magers
#
# 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, ... |
import os
import unittest
from unittest.mock import patch, Mock
os.environ["STAGE"] = "test"
os.environ["autotest"] = "True"
from sosw.worker_assistant import WorkerAssistant
from sosw.test.variables import TEST_WORKER_ASSISTANT_CONFIG
class WorkerAssistant_UnitTestCase(unittest.TestCase):
TEST_CONFIG = TEST_W... |
# *************************************************************************** #
# HyperNet #
# --------------------------------------------------------------------------- #
# Machine Learning-Based library for modeling #
... |
from Tkinter import *
from hummingbird import Hummingbird
import time
'''
Hummingbird Hardware Components
Connect TriColor LED to Port #1
Connect Servo Motor to port #1
Connect Gear Motor to port #1
Connect Temperature Sensor to sensor port #1
Connect Distance Sensor to sensor port #2
Connect Rotary Sensor to sensor... |
from django.apps import AppConfig
class AccomplishmentConfig(AppConfig):
name = 'accomplishment'
|
import math
from typing import Callable, Dict, Optional
from c2cwsgiutils import stats
from tilecloud import Tile
class Statistics:
def __init__(self, format: str = "%f"):
self.format = format
self.n = 0
self.sum = 0.0
self.sum_of_squares = 0.0
self.minimum: Optional[floa... |
import os
import six
import json
from requests_oauthlib import OAuth1Session
consumer_key = 'XJCbpn5nHHDNW48NBMx0eg'
consumer_secret = 'gcxv78Aq6kBulp663LFgug'
class Figshare(object):
def __init__(self, consumer_key, consumer_secret, access_token,
access_token_secret):
"""
Connec... |
def make_room(Room, title, description, floor):
return Room(
title = title,
description = description,
floor = floor,
items = None,
NPCs = None,
mobs = None,
north = None,
east = None,
south = None,
west = None
)
def make_floor(Roo... |
from __future__ import absolute_import
from .celeryapp import app as celery_app
|
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from experiments import default_reader
def load_and_process_data(path):
"""Loads breast cancer data from `path`"""
df = pd.read_csv(path, header=None)
#Remove the first column of t... |
from .lunch import Lunchbreak
|
#!/usr/bin/env python3
import build_file
import repository
import label
import argparse
import json
import os
import logging
from typing import List
class StoreKeyValuePair(argparse.Action):
"""
Parser action that populates a dictionary with '=' separated key-value
pairs.
"""
def __call__(self,... |
import time
from queue import Queue
import pytest
from polog.core.engine.real_engines.multithreaded.worker import Worker
from polog.core.stores.settings.settings_store import SettingsStore
from polog.core.log_item import LogItem
queue = Queue()
worker = Worker(queue, 1, SettingsStore())
def test_do(handler):
... |
import numpy as np
from tqdm import tqdm
class UserBased:
def __init__(self, M, N, neighbors=20, min_common_items=5, min_values=1.0, max_value=5.0):
self.M = M
self.N = N
self.neighbors = neighbors
self.min_common_items = min_common_items
self.min_value = min_values
... |
#!/usr/bin/env python2
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class I... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2019-20: Homework 5
"""
import torch
import torch.nn as nn
class CharDecoder(nn.Module):
def __init__(self, hidden_size, char_embedding_size=50, target_vocab=None):
""" Init Character Decoder.
@param hidden_size (int): Hidden size of the... |
import os
import re
from learning_objective.hidden_function import true_evaluate, get_settings
lim_domain = get_settings(lim_domain_only=True)
scribe = open("./data/regret_analysis/gp_hm.csv", 'w')
for f in os.listdir("./data/regret_analysis"):
if f.startswith("gp_hm"):
print f
f = "data/regret_a... |
import os
import platform
home_dir = os.path.expanduser("~")
os_name = platform.system()
def env(name: str):
return os.getenv(name)
def macos(name: str):
"""
docstring
"""
return os.path.join(home_dir, "Library", "Caches", name)
def windows(name: str):
appData = env("APPDATA") or os.path.... |
from transformers import BertForMaskedLM, BertModel, DistilBertForMaskedLM, DistilBertModel
def get_kobert_model():
""" Return BertModel for Kobert """
model = BertModel.from_pretrained("monologg/kobert")
return model
def get_kobert_lm():
""" Return BertForMaskedLM for Kobert """
model = BertFor... |
class StringBuff(object):
def __init__(self, init_string: str = ''):
self._string_buff = [init_string]
def __add__(self, other: str):
self._string_buff.append(other)
return self
def __str__(self):
return ''.join(self._string_buff)
__repr__ = __str__
def to_string(... |
from amaranth_boards.sk_xc6slx9 import *
from amaranth_boards.sk_xc6slx9 import __all__
import warnings
warnings.warn("instead of nmigen_boards.sk_xc6slx9, use amaranth_boards.sk_xc6slx9",
DeprecationWarning, stacklevel=2)
|
import figurefirst as fifi
layout = fifi.svg_to_axes.FigureLayout('example_negative_labels.svg')
layout.make_mplfigures()
layout.fig.set_facecolor('None')
ex = layout.axes['ex']
ex.plot([1, 2], [3, 4])
fifi.mpl_functions.adjust_spines(ex, spines='left', yticks=[-1, -2])
layout.insert_figures('panels', cleartarget=True... |
# pylint: disable=preferred-module # FIXME: remove once migrated per GH-725
import os
import unittest
from pathlib import Path
import pytest
from ansiblelint.testing import run_ansible_lint
from ansiblelint.text import strip_ansi_escape
class TestCliRolePaths(unittest.TestCase):
def setUp(self):
self.l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
from peyps.run_utils import str2date, makedate
class TestMakeDate(TestCase):
def test_makedate(self):
self.assertEqual(
date(2017... |
from __future__ import absolute_import
from hls4ml.report.vivado_report import read_vivado_report
from hls4ml.report.vivado_report import parse_vivado_report
from hls4ml.report.quartus_report import read_quartus_report
from hls4ml.report.quartus_report import parse_quartus_report |
import bs4 as bs
import requests
class Access_Tickers:
def __init__(self):
self.tickers = []
def save_sp500_tickers(self):
resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text, 'lxml')
table = soup.find('table', {'cla... |
# Hack Computer
from ._x__components import * |
import classad
import collections
import concurrent
import datetime
import htcondor
import logging
import os
import sys
import time
from configparser import NoSectionError, NoOptionError
from . import Executor
logger = logging.getLogger(__name__)
# context in strategy pattern
class HTCondor(Executor):
def __in... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import os.path
import sys
import itertools
import warnings
import functools
import posixpath
import ntpath
import errno
FS_ENCODING = sys.getfilesystemencoding()
PY_LEGACY = sys.version_info < (3, )
TRUE_VALUES = frozenset(('true', 'yes', '1', 'enable', 'enabl... |
#!/usr/bin/python
# Copyright (c) 2011 Tuenti Technologies
# See LICENSE for details
import base64
import os
import os.path
import socket
from keyring.backend import KeyringBackend
#TODO: Better exceptions
class HousekeeperClientException(Exception): pass
if os.environ.has_key('HOUSEKEEPER_SOCKET'):
default_soc... |
######## Useful Tools ########
#This is meant to be imported by modules_and_pip.py
import random
feet_in_mile = 5280
meters_in_kilometer = 1000
beatles = ["John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr"]
def get_file_ext(filename):
return filename[filename.index(".") + 1:]
def roll_dice(num):
... |
from rest_framework import serializers
from . import models
class UserSerilizer(serializers.Serializer):
"Serialize the name of user"
name=serializers.CharField(max_length=10)
class UserProfileSerilizer(serializers.ModelSerializer):
class Meta:
model=models.UserProfile
fields =('name','email... |
# Functions
def greet():
print('Hello')
print('Good morning')
greet()
def add(x,y):
c = x + y
print(c)
add(5,3)
def add_sub(x,y):
c = x + y
d = x - y
print(c,d)
add_sub(5,6)
def add_mult(x,y):
c = x + y
d = x * y
return c,d
addition,multiplication = add_mult(5,6)
print(ad... |
# BSD 3-Clause License
#
# Copyright (c) 2020, princeton-vl
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# li... |
# -*- coding: utf-8 -*-
from datetime import datetime
from billiard.exceptions import SoftTimeLimitExceeded
from rpc.client.result import ResultClient
from webs.api.models.db_proxy import crawl_task_model_proxy, result_model_proxy
from worker import celery_app
from worker.library.playwright import PlayWrightHandler
... |
import threading
import numpy as np
import os
import io
from flask import Flask, request, render_template, redirect, Response
from flask_classful import FlaskView, route
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.mlab import griddata
from matplotli... |
"""
This is a test applet deployed on a BDC to test fetching from HDFS from within
app-deploy.
"""
import re
import subprocess
import json
PRAXXIS_ROOT = "http://nmnode-0-svc:50070/webhdfs/v1/praxxis/"
def test(loc):
"""
collect the sequences for all users and all scenes.
should we record user/scene/time... |
import sys
from typing import Union
def prefsorted(seq: list,
preferred: Union[str, list, None] = None,
reverse: bool = False) -> list:
if isinstance(preferred, str):
preferred = preferred.split()
elif preferred is None:
preferred = []
taken = []
rest = ... |
""" Contains the cli interface for calculator """
import calculator.expression as expression
import calculator.expression_tree as expression_tree
ENTRY = "Welcome to Calculator!"
TAKE_INPUT = "Enter the expression:"
OUTPUT = "Answer is:"
def run():
print(ENTRY)
inp = input(TAKE_INPUT)
exp = expressi... |
# region imports
from fxpt.side_utils import pyperclip
from fxpt.qt.pyside import shiboken2, QtCore, QtGui, QtWidgets, isPySide2
import maya.OpenMayaUI as omui
import pymel.core as pm
from fxpt.fx_prefsaver import prefsaver, serializers
import searchers
from com import *
if isPySide2():
from fxpt.fx_search.ma... |
#!/usr/bin/env python3
import sys
if len(sys.argv) != 2:
print("Help: {} <filename>".format(sys.argv[0]))
sys.exit(0)
with open(sys.argv[1]) as file:
segments = file.readline().rstrip().split(", ")
target = ([int(x) for x in segments[0][15:].split("..")], [int(x) for x in segments[1][2:].sp... |
from __future__ import annotations
import logging
from abc import abstractmethod
from typing import Dict, Generic, Type, TypeVar, final
from dramatiq import Message
from common.runtimes import Runtime, RuntimeConfig
from deployments.deployment_actor import DeploymentActor, DeploymentDescription
from deployments.ent... |
description = 'Laser Safety Shutter'
prefix = '14IDB:B1Bi0'
target = 0.0
command_value = 1.0
auto_open = 0.0
EPICS_enabled = True |
import numpy as np
import matplotlib.pyplot as plt
import cv2
class GridWorld:
_direction_deltas = [
(-1,0),
(1,0),
(0,1),
(0,-1)
]
_num_actions = len(_direction_deltas)
def __init__(self, reward_grid, terminal_mask, obstacle_mask, action_probabilities, no_action_prob... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.