text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- import logging from pathlib import Path import torch from torch.utils.data import Dataset from torch.nn.utils.rnn import pad_sequence from ..utils.data import read_sentences logger = logging.getLogger('nmtpytorch') class TextDataset(Dataset): r"""A PyTorch dataset for sentences. A...
1,766
567
import argparse import sys from Choruslib import jellyfish import os from multiprocessing import Pool, Process from pyfasta import Fasta import pyBigWig import math def main(): args = check_options(get_options()) # jfgeneratorscount(jfpath, mer, output, generators,threads=1, size='100M'): # make genera...
9,194
3,009
import glob import nibabel as nib import pdb nii_files = glob.glob('./train3d/*.nii') for nii_file in nii_files: nii = nib.load(nii_file) nib.save(nii, nii_file[:-4] + '_0000.nii.gz') print(nii_file[:-4] + '.nii.gz')
224
115
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
5,259
1,612
# -*- coding: utf-8 -*- import os import sys lib_path = os.path.abspath('../') sys.path.append(lib_path) from API.APITextos import APITextos if __name__ == '__main__': """ users = APITextos.getUsersSimilar_user_all_topic("Taxigate", "ar", 100, 1) for user in users: print user.screen_name + "\t"+ use...
1,020
433
import os import matplotlib.image as mpimg import matplotlib.pyplot as plt import config def view_data(): nrows, ncols = 3, 3 pic_index = 0 fig = plt.gcf() fig.set_size_inches(nrows * 4, ncols * 4) pic_index = 2 next_rock = [os.path.join(config.TRAIN_DIR, 'rock', fname) for fname in os.listd...
1,333
533
import os import json from github3.pulls import PullFile from github3.repos.commit import RepoCommit def load_fixture(filename): path = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(path, 'fixtures', filename) fh = open(filename, 'r') return fh.read() def create_pull_files(data)...
454
165
# # One-liner implementation of cPickle # from pickle import * from pickle import __doc__, __version__, format_version, compatible_formats BadPickleGet = KeyError UnpickleableError = PicklingError # ____________________________________________________________ # XXX some temporary dark magic to produce pickled dumps ...
1,206
376
import os import sys from ..gameviewer import GameViewer class ConnectFourViewer(GameViewer): def __init__(self): super(ConnectFourViewer, self).__init__([6,7]) def showState(self, state): os.system("clear") sys.stdout.write("x\y|") for k in range(0, self.map_width): sys.stdout.write("%d "%(k)) sys.std...
847
370
"""Launchcontrol client The module exposes the Launchcontrol API as a Client object. Data: scripttypes -- list of a dictionaries containing supported script formats. """ import urllib2 scripttypes = [ { "name" : "funscript", "extensions": ["funscript"], "mediaType" ...
5,806
1,653
# Copyright (c) 2020 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 appli...
7,614
2,093
#! /mnt/software/unstowable/anaconda/bin/python import sys import os import argparse import subprocess def generating_mapping(kraken_report): kraken_dict = {} with open (kraken_report, "r") as fp: for line in fp: line = line.split("\t") if line[3] != 'S' and line[3] != '-': ...
2,858
887
# This code is adapted from the https://github.com/tensorflow/models/tree/master/official/r1/resnet. # ========================================================================================== # NAVER’s modifications are Copyright 2020 NAVER corp. All rights reserved. # ================================================...
19,394
6,504
import argparse import os import os.path import glob import re import sys import subprocess import shlex from pathlib import Path from functools import cmp_to_key from structlog import get_logger, wrap_logger from structlog.dev import ConsoleRenderer import yaml import semver import pkgconfig glog = wrap_logger(get_l...
16,442
6,039
import unittest from imputena import logistic_regression from test.example_data import * class TestLogisticRegression(unittest.TestCase): # Positive tests ---------------------------------------------------------- def test_logistic_regression_returning(self): """ Positive test dat...
5,103
1,542
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # 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 ...
3,349
964
import os import random import shutil import time import whisper from django.conf import settings from django.test import override_settings from mock import patch, Mock from .base import TestCase from graphite.finders.utils import BaseFinder from graphite.intervals import Interval, IntervalSet from graphite.node imp...
24,131
8,243
import sys from sfzgen import GetNote # Verify that GetNote gives us back the notes that we expect. midi_val = 24 # Starting midi value. for scale in range(1, 8): for note in 'cdefgab': for sharp in ('', 's', '#'): name = note + sharp + str(scale) if name[:2] in ('es', 'e#', 'bs', 'b#'): co...
804
286
from .base import PipBaseRecipe class PyRecipe(PipBaseRecipe): def __init__(self, *args, **kwargs): super(PyRecipe, self).__init__(*args, **kwargs) self.sha256 = '1f9a981438f2acc20470b301a07a4963' \ '75641f902320f70e31916fe3377385a9' self.name = 'py' self.ver...
338
163
import unittest from app.models import Article class ArticleTest(unittest.TestCase): ''' Test Class to test the behaviour of the Article class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_article = Article('NewsDaily', 'NewsDailyTr...
577
180
#!/usr/bin/env python3 import collections import datetime import subprocess import dateutil.parser import os from typing import Dict, Iterator, List, TypeVar, Tuple, Optional T = TypeVar('T') RawLog = collections.namedtuple('RawLog', ['commit', 'tree', 'date']) TreeInfo = collections.namedtuple('TreeInfo', ['mode', ...
4,979
1,630
#!/usr/bin/env python # Copyright (c) 2009, Willow Garage, Inc. # 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 # n...
8,651
3,143
from pathlib import Path from uuid import uuid4 from django.db import models from django_extensions.db.models import TimeStampedModel class Image(TimeStampedModel, models.Model): class Meta: indexes = [models.Index(fields=['scan', 'name'])] ordering = ['name'] id = models.UUIDField(primary_k...
737
238
from utils.libraries.Get_duration_execution_time import Get_duration_execution_time from utils.libraries.Bubble_sort import Bubble_sort from utils.libraries.Insertion_sort import Insertion_sort from utils.libraries.Merge_sort import Merge_sort from utils.libraries.Selection_sort import Selection_sort
302
90
#print ("Hello World") #counties=["Arapahoes","Denver","Jefferson"] #if counties[1]=='Denver': # print(counties[1]) #counties = ["Arapahoe","Denver","Jefferson"] #if "El Paso" in counties: # print("El Paso is in the list of counties.") #else: # print("El Paso is not the list of counties.") #if "Arapahoe" in ...
2,897
1,049
# # Copyright 2002.2.rc1710017 Barcelona Supercomputing Center (www.bsc.es) # # 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...
1,600
540
""" Plan add-on models """ # pylint: disable=too-few-public-methods from typing import Optional from beanie import Document from pydantic import BaseModel class AddonOut(BaseModel): """Addon fields returned to the user""" key: str name: str description: str class UserAddon(AddonOut): """Addo...
1,407
448
# Copyright (c) 2012 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. import optparse import os import sys def Init(): chromeapp_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'third_...
4,434
1,551
import json import requests import dash import dash_core_components as dcc import dash_html_components as html def server_setup(results): app = dash.Dash(__name__) app.layout = html.Div(children=[ html.H1(children='NHL 2018/2019 cumulative points stats'), html.Div(children=''' ...
3,247
1,031
############################################## # Author: Ruben Izquierdo Bevia # # VU University of Amsterdam # # Mail: ruben.izquierdobevia@vu.nl # # rubensanvi@gmail.com # # Webpage: http://rubenizquierdobevia.com # # Version: 1.0 ...
4,584
1,513
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. from __future__ import annotations class Snowflake(int): """Discord utilizes Twitter's snowflake format for uniquely identifiable descriptors (IDs). These IDs are guaranteed to be unique across all of Disco...
1,620
502
#Squeeze example import sys sys.path.insert(0,'..') import pycpdflib #DLL loading depends on your own platform. These are the author's settings. if sys.platform.startswith('darwin'): pycpdflib.loadDLL("/Users/john/repos/python-libcpdf/libpycpdf.so") elif sys.platform.startswith('linux'): pycpdflib.loadDLL("../...
784
296
import imaplib import email from create_orders_from_email import get_email_contents import time import sys with imaplib.IMAP4_SSL(host="imap.gmail.com", port=imaplib.IMAP4_SSL_PORT) as imap_ssl: resp_code, response = imap_ssl.login(sys.argv[1], sys.argv[2]) while True: resp_code, mail_count = imap_ssl....
858
302
import socket import struct class Patlite(object): auto_update = True OFF = 0 BLINK = 0x20 ON = 0x01 SHORT = 0x08 LONG = 0x10 STATUS_STRING = { OFF:"Off",BLINK:"Blink",ON:"On", SHORT:"Short",LONG:"Long" } RED = 0 ...
4,314
1,473
""" # type: ignore type ignore is to tell LSP-pyright to ignore the line because something it thinks that there are errors, but actually at runtime there are not """ from .validation import validate_password_check from .validation import validate_email from .validation import validate_password from .valida...
11,892
3,688
"""Fake server""" import asyncio import logging from typing import Callable, Dict, List, Optional, Tuple, Union from . import ( AmxDuetRequest, AmxDuetResponse, AnswerCodes, CommandNotRecognised, CommandPacket, ResponseException, ResponsePacket, read_command, write_packet ) _LOGGER...
4,075
1,100
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
13,810
3,816
from flask import Blueprint, abort, request, jsonify from prediction_utils import * prediction_page = Blueprint('prediction_page', __name__) @prediction_page.route('/map', methods=['GET']) def get_map_data(): offset = int(request.args['offset']) country = request.args['country'] if 'country' in request.args e...
581
179
from django.urls import path from . import views urlpatterns = [ path("draugiem/login/", views.login, name="draugiem_login"), path("draugiem/callback/", views.callback, name="draugiem_callback"), ]
209
70
"""Input transformer machinery to support IPython special syntax. This includes the machinery to recognise and transform ``%magic`` commands, ``!system`` commands, ``help?`` querying, prompt stripping, and so forth. Added: IPython 7.0. Replaces inputsplitter and inputtransformer which were deprecated in 7.0. """ # C...
26,174
7,796
from pathlib import Path import os import zipfile import json from addict import Dict from train_generator import get_data from loading import load_gen import numpy as np from collections import OrderedDict from tqdm import tqdm def get_univariate_results(model, num_tests=100, verbose=False, n=None): all_runs = l...
6,806
2,356
#first exercise #This code asks the user for hours and rate for hour, calculate total pay and print it. hrs = input("Enter Hours:") rate = input("Enter Rate:") pay = float(hrs) * float(rate) print("Pay:", pay) #second exercise #This code asks the user for hours and rate for hour, calculate total pay and print...
619
233
from typing import Optional from ctypes import * from vcx.common import do_call, create_cb from vcx.api.connection import Connection from vcx.api.vcx_stateful import VcxStateful import json class DisclosedProof(VcxStateful): def __init__(self, source_id: str): VcxStateful.__init__(self, source_id) ...
5,419
1,666
import sys import requests import json import argparse import time parser = argparse.ArgumentParser(description='Collects monitoring data from Pingdom.') parser.add_argument('-u', '--pingdom-user-name', help='The Pingdom User Name', required=True) parser.add_argument('-p', '--pingdom-password', help='The Pingdom Passw...
3,442
1,079
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy import stats from pandas.tools.plotting import scatter_matrix from scipy.optimize import curve_fit from matplotlib.colors import LogNorm df = pd.read_csv('/Users/tylern/Homework/PHYS723/project/LHC/CM...
10,224
4,919
from JumpScale import j # import sys # import time # import json # import os # import psutil from MonitorTools import * # from pssh import ParallelSSHClient from gevent import monkey monkey.patch_socket() class NodeBase(MonitorTools): def __init__(self,ipaddr,sshport=22,role=None,name=""): """ e...
4,187
1,440
import os import unittest import tempfile from abvdget import ABVDatabase, Record TESTDATA = os.path.join(os.path.dirname(__file__), 'nengone.json') EXPECTED = { 99: { "LID": 99, "Annotation": "arm and hand", "Cognacy": '1', "Item": "nin", "Loan": None, "Word": "ha...
2,467
937
#!/usr/bin/env python # ----------------------------------------------------- # Written by Zhu Lingfeng on 2021/3/28. # ----------------------------------------------------- import sys from pycocotools.coco_analyze import COCOAnalyze, my_plot annFile = sys.argv[1] coco = COCOAnalyze(annFile) # get all cats catNms =...
662
267
import logging from typing import Any, List, Optional from homeassistant.components.climate.const import ( HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_FAN_ONLY, ) from gehomesdk import ErdAcFanSetting from ..common import OptionsConverter _LOGGER = logging.getLogger(__name__) class AcFanModeOptionsConverte...
1,821
591
import django import os import pytest import shutil import sys import time import uuid # logging import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # init django settings file to retrieve settings os.environ['DJANGO_SETTINGS_MODULE'] = 'combine.settings' sys.path.append('/opt/combine'...
13,975
4,425
""" Decision Trees - Supervised learning: 1-Classification*, 2-Regression. D.T.s are a non-parametric supervised learning method used for classification and regression. The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred from the data features. Some adv...
5,188
1,328
import os import sys import re import numpy as np #from create_neglist import * import pandas as pd pd.set_option('display.max_rows', None) from create_tokenization import * from pycorenlp import StanfordCoreNLP from concept_extraction import * from syntactic_parsing import * from tree_rules import * from nltk.corpus i...
8,984
3,214
# 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 from ... import _utilities, _tables from...
61,939
16,937
__author__ = 'Junbo Wang' __version__ = '2.0' from flask import Flask from hackathon.functions import safe_get_config from flask_restful import Api from flask_cors import CORS # flask app = Flask(__name__) app.config['SECRET_KEY'] = '*K&ep_me^se(ret_!@#$' # flask restful api = Api(app) # CORS app.config['CORS_HEADE...
754
278
import os from .base import * # noqa import dj_database_url SECRET_KEY = "test mode" database_url = os.getenv("DATABASE_URL") if database_url: DATABASES = {"default": dj_database_url.parse(database_url)} else: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", ...
489
169
from models import Action, Block, Detect, Discovery, Edge, Node import renderer if __name__ == "__main__": root = Node(label="Reality") goal = Node(label="Attacker gets data from bucket") apiCache = Action( label="Search API Caches", chain="recon", cost=0, time=3, o...
1,213
379
import math from KratosMultiphysics import * from KratosMultiphysics.BRepApplication import * from KratosMultiphysics.IsogeometricApplication import * ### ### This module is a factory to generate typical geometries for isogeometric analysis, e.g. circle, l-shape, ... ### nurbs_fespace_library = BSplinesFESpaceLibrary...
14,853
5,751
#!/usr/bin/env python """ Analyze Imaging Mass Cytometry data =================================== This tutorial shows how to apply Squidpy to Imaging Mass Cytometry data. The data used here comes from a recent paper from :cite:`jackson2020single`. We provide a pre-processed subset of the data, in :class:`anndata.AnnD...
6,945
1,939
from pymongo import MongoClient client = MongoClient() db = client.music_space def print_collection(collection): print("/" * 75) for x in db[collection].find(): print(x) print("/" * 75) def save_sales_on_mongo(collection, data): for i in range(len(data['sales'])): data['sales'][i]['to...
604
211
from typing import Dict # The rest of the codebase uses mojos everywhere. # Only use these units for user facing interfaces. units: Dict[str, int] = { "cryptodoge": 10 ** 6, # 1 cryptodoge (XCD) is 1,000,000 mojo (1 million) "mojo:": 1, "colouredcoin": 10 ** 3, # 1 coloured coin is 1000 colouredcoin mojo...
324
134
# # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import argparse import logging import json import socket from datetime import datetime SOCKET_TIMEOUT = 6...
3,203
1,009
""" .. todo:: WRITEME """ import logging from theano import function, shared from pylearn2.optimization import linear_cg as cg from pylearn2.optimization.feature_sign import feature_sign_search import numpy as N import theano.tensor as T from pylearn2.utils.rng import make_np_rng logger = logging.getLogger(__nam...
4,167
1,472
#!/usr/bin/env python ''' Plots profiles for hydro-margin test case ''' from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import netCDF4 from optparse import OptionParser import matplotlib.pyplot as plt from matplotlib import cm secInYr = 3600.0 * 24.0 * 365.0 # N...
7,239
3,060
#!/usr/bin/python # -*- coding: utf-8 -*- from adsmutils import ADSFlask, get_date from views import bp from abovl.models import OAuthClient from flask.ext.session import Session def create_app(**config): """ Create the application and return it to the user :return: flask.Flask application """ ap...
3,301
1,001
ANGULAR_PACKAGES_CONFIG = [ ("@angular/animations", struct(entry_points = ["browser"])), ("@angular/common", struct(entry_points = ["http/testing", "http", "testing"])), ("@angular/compiler", struct(entry_points = ["testing"])), ("@angular/core", struct(entry_points = ["testing"])), ("@angular/forms...
853
269
#!/usr/bin/env python # # Author: Daniela Duricekova <daniela.duricekova@gmail.com> # import requests import threading import queue URLS = [ 'https://xkcd.com/138/', 'https://xkcd.com/149/', 'https://xkcd.com/285/', 'https://xkcd.com/303/', 'https://xkcd.com/327/', 'https://xkcd.com/387/', ...
792
326
# -*- coding: utf-8 -*- """ Factory and blueprints patterns """ import os from commons.logs import get_logger from commons.meta import Meta as m logger = get_logger(__name__) ################ config = { "default": "config.devel", "development": "config.devel", "production": "config.prod", # "testing...
593
202
import logging RPL_WELCOME = 1 RPL_WHOISUSER = 311 RPL_ENDOFWHO = 315 RPL_LISTSTART = 321 RPL_LIST = 322 RPL_LISTEND = 323 RPL_TOPIC = 332 RPL_WHOREPLY = 352 RPL_NAMREPLY = 353 RPL_ENDOFNAMES = 366 RPL_MOTD = 372 RPL_MOTDSTART = 375 RPL_ENDOFMOTD = 376 ERR_NOSUCHCHANNEL = 403 logger = logging.getLogger(__name__) ...
3,235
1,108
import re import cv2 import json import base64 import logging import requests import numpy as np from datetime import datetime import pytz import gridfs import pymongo from pymongo import MongoClient from pymongo.errors import ServerSelectionTimeoutError as MongoServerSelectionTimeoutError import image...
14,733
4,199
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import time import sys import functools import math import paddle import paddle.fluid as fluid import paddle.dataset.flowers as flowers import models import reader import argparse fr...
11,801
3,895
# Implement a class to hold room information. This should have name and # description attributes. class Room: def __init__(self, number, world, name, description, enemies, enemyHP, enemy_diff, companion=[], item=[] ,enemy_description=[] ): self.number = number self.name = name self.worl...
1,889
797
from __future__ import print_function import os import base64 import cStringIO import time import numpy from PIL import Image from flask import (Flask, request, render_template, url_for, flash, redirect, send_file) from SeamErasure import seam_erasure, obj_reader, util from SeamErasure.lib import weight_data ...
4,844
1,432
from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import parse_qs from IPython.display import display from summarizer import Summarizer bert_model = Summarizer() from transformers import pipeline bart_summarizer = pipeline("summarization") def bert_summarizing_model(input_txt, sent, ratio): ...
1,203
396
import matplotlib, numpy from . import plot import markdown import tabulate md_extensions = [ 'markdown.extensions.tables', 'markdown.extensions.extra' ] class HTMLElement(object): tag = None childtag = None def __init__(self, content=None, **kwargs): self.content = [] self.m...
3,481
1,086
#!/usr/bin/python # -*- coding: utf-8 -*- """Tools for setting up and using the data recorder of a PI device.""" from logging import debug, warning from time import sleep, time from pipython.pitools import FrozenClass # seconds SERVOTIMES = { 'C-413K011': 0.00003333333, 'C-663.11': 50E-6, 'C-702.00': 100...
20,472
7,312
from FoxDot import * from stemel.stemel import * def foxdotidy(pitches, durations, sustains): """ transform a stemel note matrix into a foxdot-compatible one. """ # clean up values that have rests but other notes too # replace mixed durations with the first non-rest counter = 0 for line in durations: ...
4,181
1,579
import io class container(dict): __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def pack(typ, obj): stream = io.BytesIO() typ.pack(stream, obj) data = stream.getvalue() stream.close() return data def unpack(typ, data): stream = io....
503
172
from skimage.segmentation import slic from skimage.io import imread, imsave from skimage.color import rgb2gray from skimage.measure import label, regionprops from skimage.filters import threshold_otsu, gaussian from skimage.color import label2rgb from skimage.morphology import binary_closing, binary_opening, square fro...
12,448
4,113
#!/usr/bin/env python # # Drain usage example, a simple HTTP log aggregation stats monitor. # # Monitor an ever-growing HTTP log in Common Log Format by tailing it (let's a # tail subprocess handle all the hassles like rename, re-creation during # log-rotation etc.) and aggregating some stats on a time-basis. # # LogSt...
5,271
1,632
from flask import Flask, jsonify from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, desc import pandas as pd import numpy as np import datetime as dt import sqlalchemy engine = create_engine("sqlite:///Resources/hawaii.sqlite") ...
3,854
1,567
import torch import torch.nn as nn from cogdl.utils import spmm class GINLayer(nn.Module): r"""Graph Isomorphism Network layer from paper `"How Powerful are Graph Neural Networks?" <https://arxiv.org/pdf/1810.00826.pdf>`__. .. math:: h_i^{(l+1)} = f_\Theta \left((1 + \epsilon) h_i^{l} + ...
1,189
397
from .atlas import *
20
7
from app.extensions import db, bcrypt __all__ = ['db', 'bcrypt']
67
26
""" Utility functions. """ def load_tf_names(path): """ :param path: the path of the transcription factor list file. :return: a list of transcription factor names read from the file. """ with open(path) as file: tfs_in_file = [line.strip() for line in file.readlines()] return tfs_in_...
325
106
import tweepy def autentica(): auth = tweepy.OAuthHandler(consumer_token, consumer_secret) auth.set_access_token(key, secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, retry_count=3, retry_delay=60, retry_errors=set([503])) return api
315
119
class User: """ Class that generates new instances of users. """ user_list = [] def __init__(self,tUsername,iUsername,email,sUsername): self.tUsername=tUsername self.iUsername=iUsername self.email=email self.sUsername=sUsername def save_user(self): Us...
678
203
# Copyright 2018 Oiki Tomoaki. 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 law or...
10,048
3,189
import json import falcon import time import uuid import requests from apps.database import init_db, db_session from apps.models import Account from apps.restaccount.logging import logging logger = logging.getLogger(__name__) from decouple import config ES_HOST = config('EVENTSTORE_HOST', default='eventstore') ES_PO...
2,776
815
# Copyright (c) OpenMMLab. All rights reserved. from typing import Sequence import torch from torchvision.transforms import Normalize from ..builder import ALGORITHMS, build_backbone, build_head, build_neck from .base import BaseModel @ALGORITHMS.register_module() class CAE(BaseModel): """CAE. Implementati...
4,123
1,254
''' PLNCPRO This file takes as input and it extracts dasta seq by label after reading prediction file Author : Urminder Singh email: urmind13_sit@jnu.ac.in UrMi 3/5/16 ''' import sys import getopt #import math #import re from Bio import SeqIO from Bio.Seq import Seq def main(args = sys.argv,home=None): #set defaults...
3,776
1,586
# -*- coding: utf-8 -*- # @Author : Skye # @Time : 2018/1/8 20:38 # @desc : python 3 , 答题闯关辅助,截屏 ,OCR 识别,百度搜索 import io import urllib.parse import webbrowser import requests import base64 import matplotlib.pyplot as plt import numpy as np from PIL import Image import os def pull_screenshot(): os.system('a...
1,609
740
import os import random import numpy as np import matplotlib.pyplot as plt from PIL import Image def main(): names = list(os.listdir('datasets/tianchi_xray/restricted/')) img1 = Image.open(os.path.join('datasets/tianchi_xray/restricted', names[random.randint(0, len(names))])) img2 = Image.open(os.path.joi...
1,084
458
from __future__ import print_function import os import re def openFile(f, m='r'): if (os.path.exists(f)): return open(f, m) else: return open('../' + f, m) demo_test = ' '.join(openFile('mockito_test/demo_test.py').readlines()) demo_test = demo_test.split('#DELIMINATOR')[1] readme_before = ''.join(...
650
245
from collections import namedtuple import hashlib import sys import time import traceback import pyperformance from . import _utils, _python, _pythoninfo from .venv import VenvForBenchmarks, REQUIREMENTS_FILE from . import _venv class BenchmarkException(Exception): pass class RunID(namedtuple('RunID', 'python ...
5,887
1,798
"""MotifPileupProcessors for QC filtering""" # TODO: combine PhredFilter and MapqFilter to avoid cost for double # iteration from mqc.visitors import Visitor from mqc.pileup.pileup import MotifPileup import mqc.flag_and_index_values as mfl qflag = mfl.qc_fail_flags mflag = mfl.methylation_status_flags from typing ...
2,147
671
#import mraa import smbus import time I2C_ADDR = 0x5C class AKI_I2C_LPS25H: def __init__(self): print "AKI_I2C_LPS25H" self.i2c = smbus.SMBus(1) def i2cReg(self,wr,addr=0x00,data=0x00): try: if(wr == "w"): return self.i2c.write_byte_data(I2C_ADDR,addr,data)...
1,110
494
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 27 09:58:57 2020 @author: gao """ import numpy as np import matplotlib.pyplot as plt from matplotlib import colors from mpl_toolkits.axes_grid1 import AxesGrid import matplotlib as mpl import os from matplotlib.colors import LinearSegmentedColormap...
7,326
2,949
import re class version_info(object): def __init__(self, verstr ): """verstr - version string""" m1 = re.match('(.*)([RBIXS])(.*)', verstr) self.type = m1.group(2) self.major = tuple(map(int,m1.group(1).split('.'))) # creates tuyple after_type = m1.group(3).split('.') self.minor = after_typ...
4,029
1,305
import numpy as np import tensorflow as tf from tensorflow.keras import Model, layers, Input from collections import namedtuple def abs_criterion(pred, target): return tf.reduce_mean(tf.abs(pred - target)) def mae_criterion(pred, target): return tf.reduce_mean((pred - target) ** 2) def sce_criterion(logit...
9,358
3,699
from flask import Flask from flask import render_template from flask import request,session, redirect, url_for, escape,send_from_directory import requests import json app = Flask(__name__, static_url_path='') def predictor(tavg, model, degree): if degree == 3: y = model['coef'][0][3]*(tavg**3) + \ ...
4,910
1,667