text
string
size
int64
token_count
int64
# imports - compatibility imports from bootstrap_scoped._compat import StringIO, input # imports - standard imports import sys from contextlib import contextmanager # imports - module imports from bootstrap_scoped.util import get_if_empty __STDIN__ = sys.stdin @contextmanager def mock_input(args): # https://s...
838
257
from .get_shufflenet import get_shufflenet
43
17
import unittest import join_button import start_party_button import queue import privacy_button import music_queue import contact_button loader = unittest.TestLoader() suite = unittest.TestSuite() runner = unittest.TextTestRunner(verbosity=3) suite.addTests(loader.loadTestsFromModule(join_button)) suite.addTests(loa...
608
185
#py proc.sendline('show arp') proc.expect('Type Interface') result = [] while True: index = proc.expect(['--More--', '#']) lines = proc.before.strip().replace('\x08', '').splitlines() for line in lines: cols = line.strip().split() length = len(cols) if length == 6 or length == 5: ...
853
271
from pyquil import Program from pyquil.parameters import Parameter, quil_sin, quil_cos from pyquil.quilbase import DefGate from pyquil.gates import * import numpy as np thetaParameter = Parameter('theta') controlledRx = np.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, quil_cos(thetaParameter / 2), -1j * quil...
682
260
#!/usr/bin/env python # coding: utf-8 # # Lexical normalization pipeline # # author - AR Dirkson # date - 15-7-2019 # # Python 3 script # # This pipeline takes raw text data and performs: # - Removes URLs, email addresses # - Tokenization with NLTK # - Removes non_English posts (conservatively) usin...
24,200
7,942
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.4.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% import os import matplotlib.pyplot as plt # %mat...
4,392
1,755
# coding=utf-8 with open('Alunos.txt') as arquivo: for linha in arquivo: lista = linha.split(";") media = float(lista[1]) + float(lista[2]) with open('saida.txt', 'w') as arquivo2: varLinha = str("{};{}".format(linha,media)) arquivo2.write(varLinha)
314
119
#!/usr/bin/env python import sys sys.path.insert(0, '/mummy/python') sys.path.insert(0, '/datahog/') sys.path.insert(0, '/src') def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook ...
6,844
2,453
from typing import NamedTuple class KeywordArgument(NamedTuple): """Use to explicitly search for a function keyword argument node when getting objects from a graph. This is useful in cases where named function names and keyword argument names clash. See Also -------- fungraph.Name """ ...
334
86
""" Language: Python Written by: Mostofa Adib Shakib Optimization Techniques: 1) Union by Rank: We always attach the smaller tree to the root of the larger tree. Since it is the depth of the tree that affects the running time, the tree with the smaller depth gets added under the root of the deeper tree. The depth of ...
2,382
775
# -*- coding: utf-8 -*- from __future__ import print_function import abc import clu.abstract import copy import os import pytest abstract = abc.abstractmethod @pytest.fixture(scope='module') def strings(): yield ('yo', 'dogg', 'iheard', 'youlike') @pytest.fixture(scope='module') def capstrings(): yield ('Y...
19,761
5,838
import sys import os import time from sklearn import metrics from text_model import * from loader import * def evaluate(sess,dev_data): '''批量的形式计算验证集或测试集上数据的平均loss,平均accuracy''' data_len = 0 total_loss = 0.0 total_acc = 0.0 for batch_ids,batch_mask,batch_segment,batch_label in batch_ite...
8,395
2,876
import collections import pytest from configmanager import Config, PlainConfig @pytest.fixture def simple_config(): return Config([ ('uploads', collections.OrderedDict([ ('enabled', False), ('threads', 1), ('db', collections.OrderedDict([ ('user', 'root...
722
191
""" Endpoint to launch an experiment on AzureML. """ import os from os.path import dirname from typing import Optional from azureml.train.estimator import Estimator from azureml.core import Workspace, Datastore, Experiment, Run from src.utils import pip_packages from src.azure_utils import load_azure_conf def run_...
2,633
826
################################################################## # # # twitch mod activity tracker # # # # Copyright (C) 2022 X Gamer Guide ...
2,386
602
from setuptools import setup def parse_requirements(requirements_path): requirements = [] try: for line in open(requirements_path): if '#' not in line: requirements.append(line) except IOError: print("Could not open requirements file {}".format(requirements_path...
644
193
"""RDT addons testing module."""
33
11
"""update lib_raid_errors table Revision ID: 93ff199763ac Revises: b1063869f198 Create Date: 2017-07-27 00:13:29.765073+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.schema import Sequence, CreateSequence # revision identifiers, used by Alembic. revision = '93ff199763ac' down_revision = '...
1,114
439
import sys, os import numpy as np def frac_dimension(z, threshold=0.9): def pointcount(z,k): s=np.add.reduceat(np.add.reduceat( z, np.arange(0, z.shape[0], k), axis=0 ), np.arange(0, z.shape[1], k), axis=1) return len(np.where( ( s>0 ) & (s<k*k) )[0]) z=(z<t...
1,864
743
import pytest import fiddy import numpy as np @pytest.fixture def line(): def function(x): return (3 * x + 2)[0] def derivative(x): return 3 return { "function": function, "derivative": derivative, "point": np.array([3]), "dimension": np.array([0]), ...
705
238
#!/usr/bin/python import errno import grp import os import pwd from stat import * # simple module that creates many directories for users # initially created for dbscripts to create staging directories in the user homes def main(): module = AnsibleModule( argument_spec = dict( permiss...
2,388
666
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ setup.py ~~~~~~~~ Usage: python3 setup.py build_ext --inplace :author: Wannes Meert :copyright: Copyright 2017-2019 KU Leuven and Regents of the University of California. :license: Apache License, Version 2.0, see LICENSE for details. """ from setuptools import setup...
8,264
2,848
import boto3 # pip3 install boto3 def boto_init(aws_id, aws_secret): """ :param aws_id: aws key id :param aws_secret: aws secret id :return: bot3 session object """ session = boto3.Session( aws_access_key_id=aws_id, aws_secret_access_key=aws_secret ) return session ...
780
257
""" This module demonstrates finding the top K,median K and least K terms in the inverted index based on their document frequency """ import numpy as np from part1 import createindexes def get_topk(invertedindex): """ This function outputs the top k terms with highest document frequency. It takes the invert...
2,995
989
# Generated by Django 3.1.7 on 2021-11-11 02:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0004_auto_20211012_1517'), ] operations = [ migrations.AddField( model_name='product', name='stock', ...
425
148
import os import json import argparse import numpy as np import matplotlib.pyplot as plt from scipy.stats import pearsonr from d3pe.metric.score import RC_score, TopK_score, get_policy_mean BenchmarkFolder = 'benchmarks' if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-...
2,578
995
''' Script to demonstrate how to retrieve a web page using the requests library ''' # Import the contents of the requests library import requests # URL to make the request to url = 'http://whatu.info' # Make the request, don't check for HTTPS certificate issues and store response in 'response' response = requests.ge...
374
101
#Seperate File - Filename - asset.py class Asset(): def __init__(self,service_tag,name,user,dept): def GetAssetInformation(service_tag): from suds.client import Client import uuid client = Client("http://xserv.dell.com/services/assetservice.asmx?WSDL") r...
1,185
407
from app.database.base_class import Base from app.models.place import Place from app.models.user import User
108
29
import datetime import os import yaml import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output # Répertoire du fichier des données PROCESSED_DIR = '../data/processed/' # Table principale ALL_DATA_FILE= 'all_data.csv' ENV_...
3,366
1,040
# Copyright 2019 VMware, Inc. # SPDX-License-Indentifier: Apache-2.0 from ..exception import TemplateEngineException from .tag_base import TagBase class ForEachTag(TagBase): """ Apply a list of binding data to a template repeatedly and return the resolved templates in a list. """ name = "for-each...
2,629
739
import smart_imports smart_imports.all() class GiveStabilityMixin(helpers.CardsTestMixin): CARD = None def setUp(self): super(GiveStabilityMixin, self).setUp() places_tt_services.effects.cmd_debug_clear_service() self.place_1, self.place_2, self.place_3 = game_logic.create_test_ma...
2,882
970
from django.shortcuts import render, redirect from django.contrib import messages from django.shortcuts import render from django.utils import timezone from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse, reverse_lazy from django.contrib.auth import login, logout, authenticate fr...
944
284
from mgt.datamanagers.midi_wrapper import MidiWrapper class Dictionary(object): def __init__(self, word_to_data, data_to_word): self.wtd = word_to_data self.dtw = data_to_word def word_to_data(self, word): return self.wtd[word] def data_to_word(self, data): return self.d...
673
227
# # @lc app=leetcode id=16 lang=python3 # # [16] 3Sum Closest # class Solution: def __init__(self, *, debug=False): super().__init__() self.debug = debug def binarySearchClosest(self, nums: List[int], target: int) -> int: if len(nums) == 0: return None if target <= n...
1,831
589
import torch from mmcv.cnn.bricks.registry import TRANSFORMER_LAYER_SEQUENCE from mmcv.cnn.bricks.transformer import TransformerLayerSequence def inverse_sigmoid(x, eps=1e-5): """Inverse function of sigmoid. Args: x (Tensor): The tensor to do the inverse. eps (float): EPS avoid num...
4,262
1,166
# -*- coding: utf-8 -*- from django.contrib.auth.models import Group from django.contrib.auth import authenticate from django.db.models import Q from django.shortcuts import get_object_or_404 from django.template.loader import render_to_string # HTML / TXT from django.utils import timezone from django.utils.translatio...
1,594
442
#!/usr/bin/python3 ''' def executar(funcao): = Criando a funcao executar if callable(funcao): = Validando se o objeto é tipo de uma funcao funcao() = Executando a funcoa recebida ''' def executar(funcao): if callable(funcao): # server para ingorar o parametro (1) funcao() def bom_dia(): print('Bom ...
703
281
from sims.template_affordance_provider.tunable_affordance_template_discipline import TunableAffordanceTemplateDiscipline from sims4.tuning.tunable import TunableTuple, TunableSimMinute, TunableList, TunableVariant, OptionalTunable class TunableProvidedTemplateAffordance(TunableTuple): def __init__(self, descripti...
1,708
413
from datetime import datetime, timedelta from random import randint from django.contrib.auth.mixins import UserPassesTestMixin from django.core.exceptions import ValidationError from accounts.models import Customer, ServiceProvider def phone_number_validator(value): if not value.startswith('98') or len(value) !...
1,616
522
# 4. Office Chairs # So you've found a meeting room - phew! ' \ # 'You arrive there ready to present, and find that someone has taken one or more of the chairs!! ' \ # 'You need to find some quick.... check all the other meeting rooms to see if all of the chairs are in use. # You will be given a number n re...
2,135
730
from __future__ import division from __future__ import print_function import random import numpy as np import cv2 import Config as config def preprocess(img): "scale image into the desired imgSize, transpose it for TF and normalize gray-values" # increase dataset size by applying random stretche...
1,378
518
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import argparse from functools import partial import numpy as np import tensorflow.compat.v1 as tf from tensorflow.keras.datasets import mnist from tensorflow.keras import layers from tensorflow.python import ipu from outfeed_optimizer import OutfeedOptimizer,...
11,249
3,570
# from apiclient.discovery import build # from apiclient.errors import HttpError from googleapiclient.discovery import build from googleapiclient.errors import HttpError from oauth2client.tools import argparser DEVELOPER_KEY = "AIzaSyCsrKjMf7_mHYrT6rIJ-oaA6KL5IYg389A" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_V...
1,161
413
# pylint: disable=unused-argument """ Run tests for the policy endpoints in the RBAC blueprint. Note that any test which will cause a call to ``fence.blueprints.rbac.lookup_policies`` must add the test policies to the database, otherwise fence will raise an error from not finding a policy. Use something like this: ...
5,837
1,832
from datetime import date import pandas as pd import requests from phildb.database import PhilDB from phildb.exceptions import DuplicateError MEASURANDS = ['last_day', 'last_week', 'last_month'] db = PhilDB('pypi_downloads') def get_pypi_info(package_name): r = requests.get('https://pypi.python.org/pypi/{0}/jso...
901
311
import torch from models.mobilenetv2 import MobileNetV2 import sklearn.metrics from tqdm import tqdm import argparse import logging from utils.dataset import LoadImagesAndLabels, preprocess from utils.torch_utils import select_device import yaml import pandas as pd import os import numpy as np LOGGER = logging.getL...
4,773
1,607
import imp import Default.exec from . import build_tools from . import logging imp.reload(build_tools) imp.reload(logging) # ***************************************************************************** # # ***************************************************************************** logger = logging.get_logger(__...
1,070
267
from django.contrib import admin from .models import Profile, Comments, Votes, Podcasts # Register your models here. admin.site.register(Podcasts) admin.site.register(Profile) admin.site.register(Comments) admin.site.register(Votes)
233
71
from NanoTCAD_ViDES import * #a=array([5.4,0,0,10,6]) #rank = MPI.COMM_WORLD.Get_rank() rank=0; a=array([5.43,0,1,3.85,10.5]) [x,y,z]=atoms_coordinates_nanowire(a); save_format_xyz("Z2.xyz",x/10.0,y/10.0,z/10.0,"Si"); [HH,n,Nc]=create_H_from_xyz(x,y,z,10,thop_Si,3,4); ind=argsort(HH[:,1]); savetxt("H",(real(HH[:,0:10])...
700
424
# We're linking against '../build/bin/libhumon-d.a' which is built by `../build.py`. from setuptools import setup, Extension with open ('README.md', 'r') as f: long_desc = f.read() setup(name="humon", version='0.0.3', description='A Python wrapper over humon\'s C API, for reading Humon token stream...
2,127
612
#!C:\Anaconda3\python.exe """ Copyright (c) 2012, ETH Zurich, Insitute of Molecular Systems Biology, George Rosenberger 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 co...
21,785
9,415
"""\ @file metrics.py @author Phoenix @date 2007-11-27 @brief simple interface for logging metrics $LicenseInfo:firstyear=2007&license=mit$ Copyright (c) 2007-2009, Linden Research, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (...
3,755
1,138
# https://www.codechef.com/viewsolution/44674409 from itertools import accumulate def binSearch(arr: tuple, r: int, lens: int, k: int, siz: int) -> int: s, l, siz2, total = 1, lens, siz ** 2, lens + 1 while (s <= l): m = int((s + l) / 2) avg = (arr[r][m] - arr[r][m - siz] - arr[r - siz][m] + ...
955
403
"""Professor game solver.""" from deck import Deck import tiles from display import Display from board import Board import argparse class Solver: """Solver for the professor game.""" def __init__(self): """Create the deck and start the solver.""" self.deck = Deck(tiles.DECK) self.disp...
3,074
1,021
import time import asyncio from examples.test_bili_danmu import test_tcp_v2_danmu_client as bi_danmu from examples.test_huya_danmu import test_ws_danmu_client as hy_danmu from examples.test_douyu_danmu import test_ws_danmu_client as dy_danmu # loop.run_until_complete(test_tcp_v2_danmu_client()) print('请选择直播平台 1.B站...
720
333
_CALCULATIONS_GRAPHVIZSHAPE = "ellipse"
40
23
print('\033[31m-=\033[m'*20) print('Analisador de Triângulos') print('\033[31m-=\033[m'*20) PS = float(input('Primeiro segmento:')) SS = float(input('Segundo segmento:')) TS = float(input('Terceiro segmento')) if PS < (SS + TS) and SS < (PS + TS) and TS < (PS + SS): print('Os segmentos acima PODEM FORMAR um triângu...
394
174
"""This module contains custom renderer classes.""" from rest_framework.renderers import BrowsableAPIRenderer class DynamicBrowsableAPIRenderer(BrowsableAPIRenderer): """Renderer class that adds directory support to the Browsable API.""" template = 'dynamic_rest/api.html' def get_context(self, data, med...
653
166
"""SQLStrainer filters SQLAlchemy Query objects based any column or hybrid property of a related model. .. code:: from sqlstrainer import strainer strainer = sqlstrainer(mydb) query.filter(strainer.strain(request.args)) mapper ------ .. automodule:: sqlstrainer.mapper strainer -------- .. automodule...
521
178
from pylayers.gis.layout import * from pylayers.simul.link import * L = Layout('TA-Office.ini',force=True) ##L.build() #plt.ion() ##L.showG('st',aw=True,labels=True,nodelist=L.ldiffout) #f,lax= plt.subplots(2,2) #L.showG('s',aw=True,labels=True,fig=f,ax=lax[0][0]) #lax[0][0].set_title('Gs',fontsize=18) #L.showG('st',a...
745
385
import pytest from matplotlib import pyplot as plt from pdffitx.modeling import F, multi_phase, optimize, fit_calib, MyParser @pytest.mark.parametrize( "data_key,kwargs,free_params,use_cf,expected", [ ( "Ni_stru", { 'values': {'scale_G0': 0.1, 'a_G0': 3.42, 'Bi...
4,839
2,004
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import logging import argparse import multiprocessing from pathlib import Path from pyFolderLock import MultiFolderEncryptor, InvalidPasswordError, InvalidArgumentError # ================================================================ # # Program specific part...
4,608
1,188
from segpy.reader import create_reader from segpy.writer import write_segy import numpy as np """ Docs: Segpy https://segpy.readthedocs.io/en/latest/ NumPy https://docs.scipy.org/doc/numpy-1.13.0/reference/index.html """ if __name__ == '__main__': with open('data/CUTE.sgy', 'rb') as segy_in_file:...
1,032
370
""" 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 __future__ import annotations import random import re from collections import Counter from typing imp...
5,405
1,755
#!/usr/bin/env python __doc__ = '''Assign new working names to glyphs based on csv input file - csv format oldname,newname''' __url__ = 'http://github.com/silnrsi/pysilfont' __copyright__ = 'Copyright (c) 2017 SIL International (http://www.sil.org)' __license__ = 'Released under the MIT License (http://opensource.org/l...
28,928
8,273
import getpass import os import sys import time from selenium import webdriver from selenium.common.exceptions import NoSuchWindowException from selenium.webdriver.firefox.options import Options as FirefoxOptions import savePlace def main(): print("Requested information about the Google Account where you want t...
2,963
891
from xminds.api.client import CrossingMindsApiClient from .config import ENVS_HOST class ApiClientInternal(CrossingMindsApiClient): ENVS_HOST = ENVS_HOST def __init__(self, **kwargs): host = self.ENVS_HOST super().__init__(host=host, **kwargs)
272
90
from .docker_training_runtime import DockerTrainingRuntime from .docker_training_runtime_config import DockerTrainingRuntimeConfig from .docker_training_task import DockerTrainingTask
184
43
import json import os import pickle from typing import Dict import bibtexparser import typer from functional import pseq from rich.console import Console from rebiber.bib2json import normalize_title console = Console() app = typer.Typer() def construct_paper_db(bib_list_file, start_dir=""): with open(bib_list...
4,763
1,458
# -*- coding: utf-8 -*- # # __code_header example # put your license header here # it will be added to all the generated files # from .fetchers import GAListsFetcher from .fetchers import GAUsersFetcher from bambou import NURESTRootObject class GARoot(NURESTRootObject): """ Represents a Root in the TDL ...
1,315
388
#! /usr/bin/env python ''' Description : FilePath : /qxtoolkit/qxtoolkit/__init__.py Author : qxsoftware@163.com Date : 2020-12-14 16:04:47 LastEditTime: 2021-07-14 10:27:10 Refer to : https://github.com/QixuanAI/qxtoolkit ''' from .imgetter import * from .gen_samples import * from .graffiti import ...
389
172
class exception(Exception): pass def num_there(s): return any(i.isdigit() for i in s) while True: user_input=input("introduceti un sir de caractere: ") try: if num_there(user_input): raise exception break except exception: print("introduceti un doar caractere") pr...
335
105
from typing import Any, Dict import pytest from statham.schema.elements import Element, String from statham.schema.parser import parse_element @pytest.mark.parametrize( "schema,expected", [ pytest.param({"type": "string"}, String(), id="with-no-keywords"), pytest.param( { ...
927
256
# Definition for singly-linked list. # 从尾到头建立链表 class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ x1...
789
283
#!/usr/bin/python3 from threading import Thread, Event import argparse import xrdinfo import queue import sys # By default return listMethods DEFAULT_METHOD = 'listMethods' # Default timeout for HTTP requests DEFAULT_TIMEOUT = 5.0 # Do not use threading by default DEFAULT_THREAD_COUNT = 1 def print_error(content)...
5,461
1,560
import os import sys import time import random import string import json import hashlib import socket import urllib import urllib2 from pprint import pprint import tornado.web import handlers_base BaseHandler = handlers_base.BaseHandler import twilio.twiml from HomelessHelper.config import Config from HomelessHelpe...
3,013
895
import falcon class WebResource: def on_get(self, req, resp): """Handles GET requests""" resp.status = falcon.HTTP_200 # This is the default status resp.body = ('Test OK!') # falcon.API instances are callable WSGI apps app = falcon.API() # Resources are represented by long-lived class in...
587
192
from collections import Counter import re from os.path import join from config import ASSET_PATH class WikipediaCorrection(object): def __init__(self): self.Vocab = [] # Vocab list self.vocab_n = None # Vocab length self.probs = {} # Probabilities dict self.init_vocab() ...
8,803
2,962
from pathlib import Path import finesse from finorch.sessions.abstract_wrapper import AbstractWrapper class CITWrapper(AbstractWrapper): def run(self): katscript = open('script.k', 'r').read() kat = finesse.Model() kat.parse(katscript) out = kat.run() finesse.save(out, P...
347
111
from flask import jsonify, g, session from app import db from app.api import bp from app.api.auth import basic_auth, token_auth #? Not GET ? @bp.route('/tokens', methods=['POST']) @basic_auth.login_required def get_token(): #print(1111) token = g.current_user.get_token() #print(2222, token) db.sessio...
1,048
381
# Dumb25519: a stupid implementation of ed25519 # # Use this code only for prototyping # -- putting this code into production would be dumb # -- assuming this code is secure would also be dumb import random import hashlib # curve parameters b = 256 q = 2**255 - 19 l = 2**252 + 27742317777372353535851937790883648493 ...
4,869
1,909
#! /usr/env python3 import gzip import io from typing import List, Tuple, Union import numpy as np class OpenMatrix: """ Simple class to simple class to iterate through bsbolt matrix file ------------------------------------------------------------------------------------ input: path to matrix file r...
1,608
443
class Solution: def reformatNumber(self, number: str) -> str: number = number.replace('-', '') number = number.replace(' ', '') string = '' while len(number) > 4: string += number[:3] + '-' number = number[3:] if len(number) == 4: string +=...
1,036
302
import cv2 import time import simpy import random import threading import numpy as np from math import sin, cos from devro.visualization import display class DynObstacle(): def __init__(self, radius, velocity, pixelSpan, direction): self.velocity = velocity self.position = {"x":random.randint(0,pi...
10,989
3,604
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """Unit tests for //compiler_gym/bin:random_walk.""" import gym from absl.flags import FLAGS from random_walk import run_random_walk def test...
537
194
#/usr/bin/python3 import os def print_image(filename, print_image = False): if print_image: os.system('lp ' + filename) return
145
50
""" This file defines the L-Op and R-Op, based on https://j-towns.github.io/2017/06/12/A-new-trick.html """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf def Lop(nodes, x, v): lop_out = tf.gradients(nodes, x, grad_ys=v) re...
567
222
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by Lucas Sinclair. MIT Licensed. Contact at www.sinclair.bio """ # Built-in modules # import warnings, multiprocessing # Internal modules # from seqsearch.databases.pfam import pfam from seqsearch.databases.tigrfam import tigrfam # First party modules # ...
4,177
1,233
from typing import Dict import pytest from numpy.testing import assert_almost_equal import numpy as np from dp._types import Policy from dp import FiniteMDP from dp.solve import ( backup_optimal_values, policy_evaluation, policy_evaluation_affine_operator, ) from .conftest import SimpleMDP, TState, TAction ...
2,290
864
from flask import Blueprint health_check = Blueprint('health_check', __name__) from . import health # noqa
109
35
# Copyright (c) 2022 PaddlePaddle Authors. 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 app...
8,192
2,900
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^team_overview.png$', views.team_overview), url(r'^rnd_overview.png$', views.rnd_overview), url(r'^ranking/$', views.ranking, name='ranking'), url(r'^ranking/overview.png$', views.rank...
719
316
import paddle import paddle.nn as nn import math def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2D(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Layer): expansion = 1 def __init__(self, ...
6,608
2,464
import requests class JasperServer(object): def __init__(self, endpoint, username, password): self.endpoint = endpoint self.username = username self.password = password def run_report(self, location, params): auth = (self.username, self.password) url = '{endpoint}{lo...
497
133
import bpy import bmesh import operator import mathutils import addon_utils from . import platform class Platform(platform.Platform): extension = 'obj' def __init__(self): super().__init__() def is_valid(self): return True, "" def file_export(self, path): bpy.ops.export_scene.obj( filepath =pat...
531
233
from beaker._compat import u_ import unittest from beaker.converters import asbool, aslist class AsBool(unittest.TestCase): def test_truth_str(self): for v in ('true', 'yes', 'on', 'y', 't', '1'): self.assertTrue(asbool(v), "%s should be considered True" % (v,)) v = v.upper() ...
1,684
586
# Copyright 2015,2016 NICTA # # 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...
8,774
2,719
# !/usr/bin/env python2.7 import threading import numpy as np # TODO: recommend most uncertain article in case of 2 very similar articles # TODO: use timestamp to lower ucb score over time class SimpleInputOutputThread(threading.Thread): def __init__(self, linucb, article): threading.Thread.__init__(sel...
4,166
1,289