text
string
size
int64
token_count
int64
from . import utils from . import display from . import save from . import FFTW from . import stackregistration __version__="0.2.1"
132
42
# Copyright The PyTorch Lightning team. # # 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 i...
5,359
1,581
import numpy as np import unittest from pydlm.modeler.trends import trend from pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder import builder from pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 = kalmanFilter(disc...
5,458
2,127
from arcapix.fs.gpfs.policy import PlacementPolicy from arcapix.fs.gpfs.rule import MigrateRule # load placement policy for mmfs1 policy = PlacementPolicy('mmfs1') # create a new migrate rule for 'sata1' r = MigrateRule(source='sata1', threshold=(90, 50)) # add rule to start of the policy policy.rules.insert(r, 0) ...
349
128
#!/usr/bin/env python3 import sys depths = list(map(int, sys.stdin)) increased = [a > b for (a, b) in zip(depths[1:], depths[:-1])] print(sum(increased))
158
72
from flask import Blueprint, request, render_template, \ flash, g, session, redirect, url_for, jsonify from app import db, requires_auth from flask_cors import CORS from .models import Paste import uuid from datetime import datetime from app.user.models import User from pygments import highlight from pygments.lexers i...
13,961
5,324
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script run neural network model on a camera live stream """ import argparse import cv2 import numpy as np import os import time import sys COMMANDS = {0: "move_forward", 1: "go_down", 2: "rot_10_deg", 3: "go_up", 4: "take_off", 5: "land", 6: "idle"}...
8,333
2,708
""" Classification of pixels in images using color and other features. General pipeline usage: 1. Load and segment images (img_utils.py) 2. Prepare training data (label_image.py) 3. Train classifier or cluster data (sklearn KMeans, MeanShift, SVC, etc.) 4. Predict labels on new image or directory (classify_directory(...
5,431
1,709
from allennlp.common import JsonDict from allennlp.data import DatasetReader, Instance from allennlp.models import Model from allennlp.predictors import Predictor from overrides import overrides @Predictor.register("sentence_classifier") class SentenceClassifierPredictor(Predictor): def predict(self, sentence: st...
579
171
# Created on Sep 7, 2020 # author: Hosein Hadipour # contact: hsn.hadipour@gmail.com import os output_dir = os.path.curdir def skinnytk2(R=1): """ This function generates the relations of Skinny-n-n for R rounds. tk ================================================> TWEAKEY_P(t...
3,357
1,520
import pytest from bmipy import Bmi class EmptyBmi(Bmi): def __init__(self): pass def initialize(self, config_file): pass def update(self): pass def update_until(self, then): pass def finalize(self): pass def get_var_type(self, var_name): p...
2,447
867
from scrapy_compose.utils.context import realize from .field import FuncField as BaseField class StringField( BaseField ): process_timing = [ "post_pack" ] def __init__( self, key = None, value = None, selector = None, **kwargs ): #unify value format if isinstance( value, str ): value = { "_type": "string"...
592
192
import urllib.request import json from .models import News # Getting api key api_key = None # Getting the movie base url base_url = None def configure_request(app): global api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] def get_news_source(country,category)...
2,449
720
import numpy as np from hypernet.src.general import const from hypernet.src.general import utils from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic class MultiComponent(Basic): # Initialization ########################################################################### def __init...
3,590
1,225
from django.db import models from django.urls import reverse from datetime import date from django.contrib.auth.models import User #! 1 - Import user models MEALS = ( ('B', 'Breakfast'), ('L', 'Lunch'), ('D', 'Dinner') ) class Toy(models.Model): name = models.CharField(max_length=5...
1,760
613
""" Kedro plugin for running a project with Airflow """ __version__ = "0.5.0"
79
28
import play import behavior import main import robocup import constants import time import math ## This isn't a real play, but it's pretty useful # Turn it on and we'll draw the window evaluator stuff on-screen from the ball to our goal class DebugWindowEvaluator(play.Play): def __init__(self): super().__...
713
203
from ...imports import * def stringify_metallicity(Z): """ Convert a metallicity into a PHOENIX-style string. Parameters ---------- Z : float [Fe/H]-style metallicity (= 0.0 for solar) """ if Z <= 0: return "-{:03.1f}".format(np.abs(Z)) else: return "+{:03.1f}"...
331
127
# -*- coding: utf-8 -*- class Transaction(object): def __init__(self, **kwargs): self._completed_at = kwargs.get('completed_at') self._type = kwargs.get('type') self._symbol = kwargs.get('symbol') self._price = kwargs.get('price') self._amount = kwargs.get('amount') de...
1,506
463
# Copyright 2018 The TensorFlow Probability 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 law o...
14,779
6,026
import dash from flask import Flask from flask.helpers import get_root_path from flask_login import login_required from flask_wtf.csrf import CSRFProtect from flask_admin import Admin, BaseView, expose from flask_admin.contrib.sqla import ModelView from datetime import datetime from dateutil import parser import pytz f...
3,383
1,067
from __future__ import print_function from scipy.linalg import block_diag from scipy.stats import norm as ndist from scipy.interpolate import interp1d import collections import numpy as np from numpy import log from numpy.linalg import norm, qr, inv, eig import pandas as pd import regreg.api as rr from .randomization...
33,707
10,235
from __future__ import division import numpy as np na = np.newaxis import collections, itertools import abc from pyhsmm.util.stats import sample_discrete, sample_discrete_from_log, combinedata from pyhsmm.util.general import rle as rle # NOTE: assumes censoring. can make no censoring by adding to score of last # segm...
18,606
6,232
import six import json import gzip from exporters.default_retries import retry_long from exporters.writers.base_writer import BaseWriter class ODOWriter(BaseWriter): """ Writes items to a odo destination. https://odo.readthedocs.org/en/latest/ Needed parameters: - schema (object) sc...
1,406
442
""" Simple file to validate that maketests is working. Call maketests via: >>> from x7.shell import *; maketests('x7.sample.needs_tests') """ def needs_a_test(a, b): return a+b
184
70
''' Written by: Balazs Valer Fekete fbv81bp@outlook.hu fbv81bp@gmail.com Last updated: 29.01.2021 ''' # the concept is to generate a side channel resistant initialisation of the hashing function based on # one secret key and several openly known initialisation vectors (IV) in a manner that the same input # is n...
3,960
1,355
""" graphstar.utils ~~~~~~~~~~~~~~~ Cristian Cornea A simple bedirectional graph with A* and breadth-first pathfinding. Utils are either used by the search algorithm, or when needed :) Pretty self explainatory (I hope) For more information see the examples and tests folder """ def smooth_path(p): # If the ...
1,573
562
class Event: def __init__(self): self.handlers = set() def subscribe(self, func): self.handlers.add(func) def unsubscribe(self, func): self.handlers.remove(func) def emit(self, *args): for func in self.handlers: func(*args)
287
93
import os def check_env(env_var_name): """ Check and return the type of an environment variable. supported types: None Integer String @param env_var_name: environment variable name @return: string of the type name. """ try: val = os.getenv(env_var_name) ...
527
154
from .models import Sound , Album from rest_framework import serializers class SoundSerializer(serializers.ModelSerializer): class Meta: model = Sound fields = ["name" , "song_image" , "pk" , "like" , "played" , "tag" , "singer" , "upload_date"] class SoundDetailSerializer(seriali...
759
215
from datetime import datetime from django.conf import settings import pytz def check_tracker(obj, simple=True): if simple: if obj.status > 0: return True return False # we have a gatekeeper now = datetime.now(pytz.utc) if obj.tracker_publish_status < 0: ...
2,000
635
import datetime from fastapi import APIRouter router = APIRouter() @router.get("", tags=["health"]) async def get_health(): return { "results": [], "status": "success", "timestamp": datetime.datetime.now().timestamp() }
256
76
import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from distutils.version import StrictVersion from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image import json import time im...
3,220
1,195
from __future__ import unicode_literals import frappe, json from frappe.model.utils.user_settings import update_user_settings, sync_user_settings def execute(): users = frappe.db.sql("select distinct(user) from `__UserSettings`", as_dict=True) for user in users: user_settings = frappe.db.sql(''' select * f...
1,326
546
import BoltzmannMachine as bm import QHO as qho import numpy as np import datetime # Visualization imports from IPython.display import clear_output from PIL import Image import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['figure.dpi']=300 def sigmoid(x): return .5 * (1 + np.tanh(x / 2.)) # Set t...
3,993
1,496
import time import os import sys import shutil import json import argparse from zipfile import ZipFile from contextlib import contextmanager from datetime import datetime from Tests.private_build.upload_packs_private import download_and_extract_index, update_index_with_priced_packs, \ extract_packs_artifacts from T...
11,237
3,378
from django.apps import AppConfig class ArexperiencesConfig(AppConfig): name = 'Apps.ARExperiences'
106
37
dataset_type = 'FlyingChairs' data_root = 'data/FlyingChairs_release' img_norm_cfg = dict(mean=[0., 0., 0.], std=[255., 255., 255.], to_rgb=False) global_transform = dict( translates=(0.05, 0.05), zoom=(1.0, 1.5), shear=(0.86, 1.16), rotate=(-10., 10.)) relative_transform = dict( translates=(0.00...
2,843
1,060
# Copyright 2019 Intel Corporation. import logging from collections import namedtuple import numpy as np import six from plaidml2 import DType from plaidml2.core import TensorShape, Buffer from plaidml2.ffi import ForeignObject, ffi, ffi_call, lib logger = logging.getLogger(__name__) def __init(): """Docstrin...
23,370
8,253
""" Copyright (c) 2018 Intel 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 writin...
2,265
741
""" Class description goes here. """ import json import logging class JSONFormatter(logging.Formatter): """Simple JSON formatter for the logging facility.""" def format(self, obj): """Note that obj is a LogRecord instance.""" # Copy the dictionary ret = dict(obj.__dict__) # ...
807
220
# Orthogonal linear system solver tests from math import sqrt import numpy as np from orthogonal import orthogonal ################################################################################ # 2x2 orthogonal matrix A = np.matrix('1 1;' '1 -1', float) A = A*1.0/sqrt(2.0) # Known terms vector b = ...
845
274
import os import shutil from dataclasses import dataclass from datetime import datetime from typing import Dict, List, Optional from huggingface_hub import Repository from loguru import logger from prettytable import PrettyTable from .splits import TEST_SPLIT, TRAIN_SPLIT, VALID_SPLIT from .tasks import TASKS from .u...
11,056
3,597
# -*- coding: utf-8 -*- # Copyright 2012 Viewfinder Inc. All Rights Reserved. """Apple Push Notification service utilities. Original copyright for this code: https://github.com/jayridge/apnstornado TokenToBinary(): converts a hex-encoded token into a binary value CreateMessage(): formats a binary APNs message fr...
5,353
1,734
r"""Training and evaluating quantum kernels =========================================== .. meta:: :property="og:description": Kernels and alignment training with Pennylane. :property="og:image": https://pennylane.ai/qml/_images/QEK_thumbnail.png .. related:: tutorial_kernel_based_training Kernel-based tr...
25,485
7,515
#!/usr/bin/python3 import pygame import random import time ##VARIABLES TO CHANGE width = 500 height = 500 stats_height = 150 board_size = 5 window_name = "PyLoopover "+str(board_size)+"x"+str(board_size) scramble_turns = 50 t_round = 3 FPS = 30 ##DONT CHANGE THESE BOIS WHITE = (255,255,255) BLACK = (0,0,0) GREEN = (3...
5,465
2,520
# for문에서 continue 사용하기, continue = skip개념!!! for i in range(1,11): if i == 6: continue; print(i); print(i); print(i); print(i); print(i);
179
78
# ============================================================================= # # Copyright (c) 2016, Cisco Systems # 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 ...
12,044
5,006
# -*- coding: utf-8 -*- # Copyright to Alexander Liu. # Any distrubites of this copy should inform its author. If for commercial, please inform the author for authentication. Apr 2014 import sys reload(sys) sys.setdefaultencoding('utf-8') from lxml import etree import time import json import urllib import urllib2 # Fo...
41,579
12,395
from .color_converter import ColorConverter from .scale_converter import ScaleConverter
89
23
from plasTeX import Command, Environment def ProcessOptions(options, document): colors = {} document.userdata.setPath('packages/color/colors', colors) colors['red'] = latex2htmlcolor('1,0,0') colors['green'] = latex2htmlcolor('0,1,0') colors['blue'] = latex2htmlcolor('0,0,1') colors['cyan'] = ...
4,374
1,495
print('\033[0;33;44mTeste\033[m') print('\033[4;33;44mTeste\033[m') print('\033[1;35;43mTeste\033[m') print('\033[7;32;40mTeste\033[m') print('\033[7;30mTeste\033[m') print(" - - - Testando os 40 - - -") print("\033[0;37;40mPreto\033[m") print("\033[0;30;41mVermelho\033[m") print("\033[0;30;42mVerde\033[m") print("\03...
1,242
834
"""TurboGears project related information""" version = "2.4.3" description = "Next generation TurboGears" long_description=""" TurboGears brings together a best of breed python tools to create a flexible, full featured, and easy to use web framework. TurboGears 2 provides an integrated and well tested set of tools for...
1,296
364
## PRODUCE MEAN CALCULATIONS AND EXPORT AS .NPY from __future__ import print_function path = '/home/mkloewer/python/swm/' import os; os.chdir(path) # change working directory import numpy as np from scipy import sparse import time as tictoc from netCDF4 import Dataset # OPTIONS runfolder = 15 print('Calculating subgri...
816
321
""" Module to generate solutions for Boggle grids. Andrew Gillis 22 Dec. 2009 """ from __future__ import print_function import os import sys import collections import trie if sys.version < '3': range = xrange class BoggleSolver(object): """ This class uses an external words file as a dictionary of acce...
8,111
2,271
import logging import pytest from ocs_ci.framework.testlib import ( managed_service_required, skipif_ms_consumer, tier4, tier4a, ) from ocs_ci.ocs import constants from ocs_ci.utility import pagerduty log = logging.getLogger(__name__) @tier4 @tier4a @managed_service_required @skipif_ms_consumer @py...
1,151
385
# -*- coding: utf-8 -*- import numpy as np, pandas as pd, arviz as az, prince, matplotlib.pyplot as plt, seaborn as sns from cmdstanpy import CmdStanModel #%% load data data = pd.read_csv("data/overfitting.csv", index_col = 'case_id') data.columns data.info() feature_names = data.columns.str.startswith("...
3,442
1,320
# -*- coding: utf-8 -*- import json import threading import os import time import mats import sys import requests import traceback import re from util import debug, error class MatsLoader(threading.Thread): """ Fire and forget loader for materials - will queue a 'mats' event or an 'error' event if the lo...
4,206
1,246
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import os from scrapy import Request from scrapy.pipelines.images import ImagesPipeline from luoxia import settings class L...
1,706
592
# Copyright 2020 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 "license" file acc...
6,949
2,531
#! /usr/bin/env python3 # Copyright 2020 Tier IV, 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 la...
6,002
1,915
import asyncio import unittest from .helpers import async_test class AsyncTestCase(unittest.TestCase): ''' AsyncTestCase allows to test asynchoronus function. The usage is the same as :code:`unittest.TestCase`. It works with other test frameworks and runners (eg. `pytest`, `nose`) as well. AsyncTes...
2,578
714
import turtle as t def rectangle(horizontal, vertical, color): t.pendown() t.pensize(1) t.color(color) t.begin_fill() for counter in range(2): t.forward(horizontal) t.right(90) t.forward(vertical) t.right(90) t.end_fill() t.penup() def star(le...
1,551
668
# Given a linked list, remove consecutive nodes that sums up to zero # https://www.careercup.com/question?id=5717797377146880 from util import * def remove_zero_sum(head): start = head new = None root = None while start: end = start.next total = start.value zero = False ...
1,107
408
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
2,383
663
import sys import os from tempfile import TemporaryDirectory import numpy as np import tensorflow.compat.v1 as tf tf.get_logger().setLevel('ERROR') # only show error messages from recommenders.utils.timer import Timer from recommenders.utils.constants import SEED from recommenders.models.deeprec.deeprec_utils import ...
5,558
2,142
#!/usr/bin/env python """ ctypesgen.ctypedescs contains classes to represent a C type. All of them classes are subclasses of CtypesType. Unlike in previous versions of ctypesgen, CtypesType and its subclasses are completely independent of the parser module. The most important method of CtypesType and its subclasses ...
11,222
3,767
from random import randint import pyxel from constants import Screen import cursors class Text: def __init__(self, text): self._text = text self._symbol_len = 3 self._padding_len = 1 def _count_text_len(self): return ( self._symbol_len + self._padding_len ...
2,026
717
from pulzarutils.utils import Utils from pulzarutils.utils import Constants from pulzarutils.messenger import Messenger from pulzarcore.core_db import DB class AdminProcess: """Handle admin operations from manage """ def __init__(self, logger): self.TAG = self.__class__.__name__ self.logg...
1,769
525
#!/usr/bin/env python2 from __future__ import print_function import atexit import logging import sys import ssg_test_suite.oscap import ssg_test_suite.virt from ssg_test_suite.rule import get_viable_profiles from ssg_test_suite.virt import SnapshotStack logging.getLogger(__name__).addHandler(logging.NullHandler()) ...
2,767
695
import decimal import operator import warnings from wtforms import fields, widgets class ReferencePropertyField(fields.SelectFieldBase): """ A field for ``db.ReferenceProperty``. The list items are rendered in a select. :param reference_class: A db.Model class which will be used to generate t...
4,218
1,174
import mtrain import numpy as np import pandas as pd import random def simulate_games(num_players=4, domino_size=12, num_games=250, collect_data=True, debug=False, players=["Random", "Greedy", "Probability", "Neural"], file_name="PlayData/data4_12_250"): """ Runs the m...
3,947
1,161
__all__ = ("DottedMarkupLanguageException", "DecodeError") class DottedMarkupLanguageException(Exception): """Base class for all exceptions in this module.""" pass class DecodeError(DottedMarkupLanguageException): """Raised when there is an error decoding a string.""" pass
294
83
############################################################################## # # Below code is inspired on # https://github.com/facebookresearch/detectron2/blob/master/detectron2/data/datasets/pascal_voc.py # -------------------------------------------------------- # Detectron2 # Licensed under the Apache 2.0 license...
3,336
1,051
import glob import time import random filelist = glob.glob('/mnt/lustre/chenyuntao1/datasets/imagenet/train/*/*') random.shuffle(filelist) begin = time.time() for i, f in enumerate(filelist): if i == 10000: break with open(f, "rb") as fin: result = fin.read() end = time.time() print("%.1f im...
354
139
# Copyright (C) 2015-2019 Tormod Landet # SPDX-License-Identifier: Apache-2.0 import dolfin from . import register_boundary_condition, BoundaryConditionCreator from ocellaris.utils import ( CodedExpression, OcellarisCppExpression, OcellarisError, verify_field_variable_definition, ) class OcellarisDir...
12,864
3,818
import unittest from count_split_inversions import count_inversions class TestCountSplitInversions(unittest.TestCase): def test_count_inversions(self): input = [1, 3, 5, 2, 4, 6] result = count_inversions(input) self.assertEqual(result, 3) if __name__ == '__main__': unittest.main()
319
111
# # Copyright 2016 The BigDL 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 law or agreed to in ...
3,906
1,272
import time import krpc conn = krpc.connect(name='Sub-orbital flight') vessel = conn.space_center.active_vessel vessel.auto_pilot.target_pitch_and_heading(90, 90) vessel.auto_pilot.engage() vessel.control.throttle = 1 time.sleep(1) print('Launch!') vessel.control.activate_next_stage() fuel_amount = conn.get_call(ve...
1,922
730
#!/usr/bin/env python3 import numpy as np def get_rows(a): return list(a) def get_columns(a): return list(a.T) def main(): np.random.seed(0) a=np.random.randint(0,10, (4,4)) print("a:", a) print("Rows:", get_rows(a)) print("Columns:", get_columns(a)) if __name__ == "__main__": main()...
321
136
from distutils.version import LooseVersion from itertools import product import numpy as np import pandas as pd from ..model.event import Event from ..model.event import EventTeam from ..model.submission import Submission from ..model.team import Team from .team import get_event_team_by_name from .submission import...
18,031
5,288
#Automate the Boring Stuff with Python import time, sys indent = 0 # How many spaces to indent indent_Increasing = True # Whether the indentation is increasing or not try: while True: # The main program loop print(' ' * indent, end='') print('********') time.sleep(0.1) # Pause for 1/10th o...
623
178
import getpass import sys import json from reflowrestclient.utils import * host = raw_input('Host: ') username = raw_input('Username: ') password = getpass.getpass('Password: ') token = get_token(host, username, password) if token: print "Authentication successful" print '=' * 40 else: print "No token fo...
3,820
1,160
from django.conf import settings from django.conf.urls import url, static from . import views from . import jobs urlpatterns = [ url(r'^choose_company/(?P<company_id>.*)/$', views.choose_company, name='choose_company'), url(r'^cleanlogs/$', jobs.cleanlogs, name='cleanlogs'), url(r'^primecache/$', job...
412
141
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="i3-workspace-swap", description='A python utility swap the content of two workplaces in i3wm', long_description=long_description, long_description_content_type="text/markdown", version="1...
838
288
# coding: utf-8 """ Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environmen...
5,975
1,736
# # Copyright 2004-2016, by the California Institute of Technology. # ALL RIGHTS RESERVED. United States Government Sponsorship # acknowledged. Any commercial use must be negotiated with the Office # of Technology Transfer at the California Institute of Technology. # # This software may be subject to U.S. exp...
2,158
695
import pytest from nbformat.v4.nbbase import new_notebook, new_markdown_cell, new_code_cell, new_raw_cell from jupytext.compare import compare_notebooks, NotebookDifference, test_round_trip_conversion as round_trip_conversion def test_raise_on_different_metadata(): ref = new_notebook(metadata={'kernelspec': {'lan...
6,681
2,282
import asyncio import discord import random import datetime from discord.ext import commands from Cogs import DisplayName from Cogs import Nullify def setup(bot): # Add the bot bot.add_cog(Actions(bot)) class Actions(commands.Cog): ## class that handles storing and computing action messages class actionable...
14,026
5,215
########## # Additional dependencies are needed: # Follow the LOLA installation described in the tune_class_api/lola_pg_official.py file ########## import os import ray from ray import tune import marltoolbox.algos.lola.envs as lola_envs import marltoolbox.algos.lola_dice.envs as lola_dice_envs from marltoolbox.algos...
7,830
2,580
import string import random import json from calendar import month_name from django.conf import settings SHORTLINK_MIN = getattr(settings, "SHORTLINK_MIN", 6) def code_generator(size=SHORTLINK_MIN): chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for _ in range(size)) def c...
1,154
353
#!/usr/bin/python import argparse import ConfigParser import os import sys new_path = [ os.path.join( os.getcwd(), "lib" ) ] new_path.extend( sys.path[1:] ) sys.path = new_path from galaxy import eggs eggs.require( "SQLAlchemy >= 0.4" ) import galaxy.webapps.tool_shed.model.mapping as tool_shed_model from sqlalchemy....
4,745
1,491
from __future__ import unicode_literals from moto.core.responses import BaseResponse from .models import dynamodbstreams_backends from six import string_types class DynamoDBStreamsHandler(BaseResponse): @property def backend(self): return dynamodbstreams_backends[self.region] def describe_strea...
1,327
393
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np from openvino.tools.mo.front.extractor import FrontExtractorOp from openvino.tools.mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from openvino.tools.mo.ops.const import Const class ZerosFrontExtractor...
962
317
from JumpScale import j class builder(): # @property # def buildDir(self): # return j.sal.fs.joinPaths(j.dirs.tmpDir, "jsbuilder") @property def cuisine(self): return j.tools.cuisine.local # ALL NOT NEEDED ANY LONGER USE bower # def angular(self): # version = "1.5...
4,359
1,665
import sys import warnings import matplotlib.pyplot as plt from parsets import IMACC, IMG, PROGC, REGFLPC, ExecE, plot warnings.filterwarnings("ignore") MEM = IMACC(sys.stdin.read()) # Load memory from stdin PC = PROGC(0) # Start from the first instruction RF = REGFLPC() # initialize register and flags EE = ExecE...
882
341
import discord import re import emoji import contextlib import typing import datetime from discord.ext import commands from discord.http import Route class BetterMemberConverter(commands.Converter): async def convert(self, ctx, argument): try: user = await commands.MemberConverter().convert(ct...
5,884
1,734
""" kissim.cli.encode Encode structures (generate fingerprints) from CLI arguments. """ import numpy as np from kissim.api import encode from kissim.cli.utils import configure_logger def encode_from_cli(args): """ Encode structures. Parameters ---------- args : argsparse.Namespace CLI ...
1,172
376
import numpy as np from util import * def naiveDistanceProfile(tsA, idx, m, tsB = None): """Return the distance profile of query against ts. Use the naive all pairs comparison algorithm. >>> np.round(naiveDistanceProfile(np.array([0.0, 1.0, -1.0, 0.0]), 0, 4, np.array([-1, 1, 0, 0, -1, 1])), 3) array([[ 2...
1,690
668
import pyplot as plt import numpy as np from sklearn import linear_model
73
20