text
string
size
int64
token_count
int64
import unittest import zipfile from StringIO import StringIO import tempfile import shutil import boto3 import dill import moto import mock import pip from easy_lambda.deployment import Lambda, DeploymentPackage @moto.mock_lambda class Test(unittest.TestCase): def setUp(self): super(Test, self).setUp() ...
1,951
632
import shlex import subprocess from .exceptions import CommandExecutionError, CommandParameterError class Command(object): process = None command = 'true' ignore_output = True fail_silently = False required_parameters = None stdout = subprocess.PIPE stderr = subprocess.PIPE def __ini...
2,397
633
import struct import pointbreak import pointbreak.types as types from pointbreak.types import TestAccessor as Accessor def test_type_get_simple_value(): accessor = Accessor(b"\x01\x00\x00\x00") ref = types.reference(types.int32, 0, accessor) assert ref.value == 1 def test_type_set_simple_value(): ...
2,926
1,231
""" Author: Edo Cohen-Karlik """ from __future__ import division # import os.path as osp import json # import sys import os import torch import torch.utils.data as data import cv2 import numpy as np #from augmentations import SSDAugmentation, SSDBoneCellAugmentation # ignore classes with label value -1. BONE_CELL_CL...
9,853
3,290
from .restrict import aibl_restriction, oasis_restriction
58
19
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from .config import RiveScriptTestCase class ObjectMacroTests(RiveScriptTestCase): """Test object macros.""" def test_python_objects(self): self.new(""" > object nolang ...
1,989
566
import functools import pandas as pd from ABONO.Regressor import Regressor from ABONO.Processer import Processer from ABONO.Session import Session TRAIN_PATH = 'data/train.csv' TEST_PATH = 'data/test.csv' def timed(session): def innertimed(f): import time @functools.wraps(f) def wrapped(*args): ...
2,556
791
# ---------------------------------------------------------------------------- # Copyright 2015 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...
29,946
9,697
#No pastrami: sandwich_orders = ['maxican','pastrami','aloo','pastrami','spicypoteto''pastrami','lulu'] finished_sandwich = [] while sandwich_orders: sandwich = sandwich_orders.pop() if sandwich == 'pastrami': print("We are out of pastrami.") continue print("I made your",sandwich,"sandwich...
439
155
C_KEY = "XXXXX" # replace with your own C_SECRET = "XXXXX" # replace with your own A_TOKEN = "xxxxx" # replace with your own A_TOKEN_SECRET = "XXXXX" # replace with your own
174
67
#! /usr/bin/env python3 import sys from os.path import expanduser import argparse import boto3 import botocore def printDebug(action, publicKeyName, publicKeyText, regionList, debug, dryRun, credProfile): return 0 def buildArgParser(argv): parser = argparse.ArgumentParser(description="Upload, delete, or lis...
6,811
1,788
from sympy import * #3次曲線と点の距離を陽に書き下すプログラム X = Symbol("X") Y = Symbol("Y") t = Symbol("t") l_x = Symbol("l_x") l_y = Symbol("l_y") a_x = Symbol("a_x") b_x = Symbol("b_x") c_x = Symbol("c_x") d_x = Symbol("d_x") a_y = Symbol("a_y") b_y = Symbol("b_y") c_y = Symbol("c_y") d_y = Symbol("d_y") print( expand( (X - (a...
1,072
718
# -*- coding: utf-8 -*- # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Calculate what workon packages have changed since the last build. A workon package is treated as changed if any of the bel...
8,868
2,745
import sys import random import os.path as osp import shutil import torch from torch.nn.functional import relu from torch_geometric.utils import erdos_renyi_graph from torch_geometric.data import Data, NeighborSampler from torch_geometric.datasets import Planetoid from torch_geometric.nn.conv import SAGEConv import t...
4,316
1,516
"""Tests for the object departures module.""" import responses # initialize package, and does not mix up names import test as _test import navitia_client import requests class DeparturesTest(_test.TestCase): def setUp(self): self.user = 'leo' self.core_url = "https://api.navitia.io/v1/" ...
529
178
from django.contrib import admin # Register your models here from . forms import StatusForm from .models import Status class StatusAdmin(admin.ModelAdmin): list_display = ['user', '__str__', 'image'] form = StatusForm admin.site.register(Status)
264
72
""" Author: RedFantom License: GNU GPLv3 Source: This repository """ try: import Tkinter as tk import ttk import tkFileDialog as fd except ImportError: import tkinter as tk from tkinter import ttk import tkinter.filedialog as fd import sys from ttkwidgets import AutoHideScrollbar class DebugWi...
3,222
1,001
"""add release_date_uk field and director_id to movie model Revision ID: e9596ed3a618 Revises: affd804a37d8 Create Date: 2020-08-05 17:34:58.197456 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e9596ed3a618' down_revision = 'affd804a37d8' branch_labels = Non...
967
369
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=wrong-import-position, too-many-locals """ Create time- and DOM-independent (TDI) whole-detector Cartesian-binned Retro table. The generated table is useful for computing the total charge expected to be deposited by a hypothesis across the entire detecto...
26,267
8,995
"""Create certificate_payload table Revision ID: e47e29a9537c Revises: 072fba4a2256 Create Date: 2017-05-19 19:51:20.672688 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e47e29a9537c' down_revision = '072fba4a2256' branch_labels = None depends_on = None de...
885
311
#!/usr/bin/env python3 """ exipicrename beta of python3 version. Reads exif data from pictures and rename them. Used exif tags are: * DateTimeOriginal * FNumber * ExposureTime * FocalLength * Model * ISOSpeedRatings """ # Copyright (c) 2019 Hella Breitkopf, https://www.unixwitch.de # MIT License -> see LICENSE fil...
28,929
9,261
""" # Name: cms/urls.py # Description: # Created by: Phuc Le-Sanh # Date Created: Nov 23, 2016 # Last Modified: Nov 23, 2016 # Modified by: Phuc Le-Sanh """ from django.conf.urls import url, include # from rest_framework import routers from rest_framework.authtoken import views as rest_views from re...
4,324
1,601
from SyntheticDataset2.ElementsCreator import * import unittest from PIL import Image class UpdatedSyntheticDatasetShapesTestCase(unittest.TestCase): def test_rectangle(self): width = 100 height = 50 color = (255,0,0) rotation = 45 midpoint = (250,250) test_backgrou...
8,396
3,538
# # @lc app=leetcode id=44 lang=python3 # # [44] Wildcard Matching # class Solution: def _consume_seq(self, s: str, p: str, s_i: int, p_i: int): while p_i < len(p) and p[p_i] != '*': if s_i >= len(s) or (p[p_i] != s[s_i] and p[p_i] != '?'): return -1, -1 s_i, p_i = s_...
1,243
523
import numpy as np from fractions import Fraction if __name__ == '__main__': #enter coordinates vectors Y = np.array([[-420,-330]]).T X = np.array([[300,0]]).T # y =mx +c O = np.ones(X.shape) A = np.append(X,O,axis=1) A_t = A.T A_t_dot_A = A_t.dot(A) A_t_dot_A_inv = np.linalg.inv(A_t_dot_A) ...
664
344
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # California Institute of Technology # (C) 2008 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
2,159
597
#!/usr/bin/env python3 # author : Alina Kutlushina # date : 01.05.2018 # license : BSD-3 #============================================================================== import sys import argparse import pandas as pd def main(in_fname, out_act_fname, out_inact_fname): """ split a d...
2,052
686
# import cv2 import os # import numpy as np list = os.listdir('./') names = open('sn.txt', 'a') for path in list: names.write('(\'mxnet\\\\' + path +'\' ,\'.\'),\n')
175
74
# -*- coding: utf-8 -*- import scrapy from ..items import ClItem from ..settings import META_URL from ..settings import SELECT from ..settings import TYPE from ..settings import DOWNLOAD_HISTORY class GrassSpider(scrapy.Spider): name = 'grass' # allowed_domains = [] start_urls = [META_URL + 'thread.php?fi...
2,084
640
FOREGROUND_THRESHOLD = .25 IMG_PATCH_SIZE = 16 NUM_CHANNELS = 3 NUM_LABELS = 2 PIXEL_DEPTH = 255
97
61
#!/usr/bin/env python # https://wiki.bash-hackers.org/scripting/terminalcodes import sys,termios, time ## Font attributes ## # off off = '\x1b[0m' # off default = '\x1b[39m' # default foreground DEFAULT = '\x1b[49m' # default background # bd = '\x1b[1m' # bold ft = '\x1b[2m' # faint st = '\x1b[3m' # standout ul = '\...
12,177
4,617
import os from flask import Flask, render_template, request from .models import db, User def create_app(): """Create and configure an instance of the Flask appication.""" app_dir = os.path.dirname(os.path.abspath(__file__)) database = "sqlite:///{}".format(os.path.join(app_dir, "twitoff.sqlite3")) ...
740
247
import scrapy from locations.items import GeojsonPointItem class CostaCoffeePLSpider(scrapy.Spider): name = "costacoffee_pl" item_attributes = {"brand": "Costa Coffee", "brand_wikidata": "Q608845"} allowed_domains = ["api.costacoffee.pl"] start_urls = ["https://api.costacoffee.pl/api/storelocator/lis...
1,664
416
import numpy as np """ basic implementation of Recurrent Neural Networks from scrach to train model to learn to add any number pair when given in binary arrayed format devloper-->sayaneree paria """ class RecurrentNeuralNetwork: def __init__(self,hidden_size=10): """hidden_size is number of...
7,530
2,412
# asyncio_ensure_future.py import asyncio async def wrapped(): print('now in function wrapped') return 'result' async def inner(task): print('now in function inner') print('inner: waiting for {!r}'.format(task)) ret = await task print('inner: task return: {}'.format(ret)) async def outer()...
572
188
from psycopg2 import pool import psycopg2 import psycopg2.extras import unittest class TestDB(unittest.TestCase): def setUp(self): self.connection_pool = pool.ThreadedConnectionPool(1, 2, database='test', user='postgresql', password='test123', hos...
1,737
582
""" Model Sales Channel Production Livestock """ from django.db import models class LivestockSalesChannel(models.Model): """ Modelo canal de ventas relacionado con la produccion """ production_livestock = models.OneToOneField( "producer.ProductionLivestock", related_name="livestock_sale...
747
226
import os import subprocess import pytest @pytest.mark.usefixtures("revert_discovery") class TestReportDiscovery: def test_report_daemon_not_running(self, host): "Test the output when the discovery daemon is not running" # Make sure discovery isn't running result = host.run("stack disable discovery") asser...
967
316
#*****MAGIC 8 BALL CODE***** import sys import random ans = True while ans: question = input("ask the magic 8 ball a question: (press enter to quit) ") answers = random.randint(1,8) if question == "": sys.exit() elif answers == 1: print ("Good:)") elif answ...
862
266
### File created by preshma import numpy as np import math def BackgroundFilter(x,y,t,pol,cam,xdim,ydim,dt): lastTimesMap=np.zeros((xdim,ydim)) index=np.zeros((len(t),1)) for i in range(len(t)): ts=t[i] xs=x[i]-1 #to compensate for matlab indexing starting from 1 ys=y[i]-1 d...
1,060
447
from stock_base import StockEventBase, dataLine def unit_test_NoneHeaderError(): try: raise NoneHeaderError('Test!') except NoneHeaderError as e: print(e) def unit_test_stockEventBase(): from dev_global.env import GLOBAL_HEADER import pandas as pd event = StockEventBase(GLOBAL_HE...
3,372
1,182
# # This script is licensed as public domain. # # http://docs.python.org/2/library/struct.html from xml.etree import ElementTree as ET from xml.dom import minidom import os import struct import array import logging log = logging.getLogger("ExportLogger") def enum(**enums): return type('Enum', (), enums) PathT...
7,592
2,381
""" Joe Tacheron difficulty: TBD runtime: instant answer: 2.223561019313554106173177 *** 751 Concatenation Coincidence Find the only value of theta for which the concatenated sequence equals theta. Give your answer rounded to 24 places after the decimal point. """ from math import floor from decimal import getco...
793
350
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2020-04-20 02:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0465_auto_20200415_1227'), ] operations = [ migration...
487
175
import json from datetime import datetime, timedelta from collections import defaultdict from django.shortcuts import redirect from rest_framework import generics from rest_framework import status from rest_framework.response import Response from rest_framework.renderers import TemplateHTMLRenderer from api.serialize...
2,991
877
#!/usr/bin/env python3 """ Pubtator REST API client https://www.ncbi.nlm.nih.gov/CBBresearch/Lu/Demo/tmTools/RESTfulAPIs.html Formats: JSON, PubTator, BioC. Nomenclatures: Gene : NCBI Gene e.g. https://www.ncbi.nlm.nih.gov/sites/entrez?db=gene&term=145226 Disease : MEDIC (CTD, CTD_diseases.csv) e.g. http://ctdbase...
2,651
1,020
from GalleryRunner import GalleryRunner from LarsoftRunner import LarsoftRunner class RunnerTypes(dict): def __init__(self, **kwargs): super(RunnerTypes, self).__init__(kwargs) self['larsoft'] = LarsoftRunner self['gallery'] = GalleryRunner
270
72
from entities import Tank, Missile, Base from particlesys import ParticleSystem import ai import pygame import sys import copy ''' General constants ''' WIDTH = 800 HEIGHT = 600 ''' ''' psys = ParticleSystem() ''' Key bindings for both players ''' KEY_BINDINGS_1 = {pygame.K_LEFT: "left", ...
6,258
2,238
#!python # -*- coding: UTF-8 -*- ''' ################################################################ # Utilities - Tools # @ Modern Deep Network Toolkits for pyTorch # Yuchen Jin @ cainmagi@gmail.com # Requirements: (Pay attention to version) # python 3.5+ # numpy 1.13+ # Useful tools for data analysis and recordi...
3,340
938
class Modifier: def __init__(self, lst): self.lst = lst def swap(self, index_1, index_2): self.lst[index_1], self.lst[index_2] = self.lst[index_2], self.lst[index_1] def multiply(self, index_1, index_2): self.lst[index_1] = int(self.lst[index_1]) * int(self.lst[index_2]) def d...
925
343
__author__ = 'jwely' import numpy import os from chunk import chunk # from dnppy import raster # please see chunk_bundle.read() for dnppy.raster import class chunk_bundle(): """ Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce me...
6,023
1,689
import dataclasses from chestrandomizer import get_event_items from character import get_character, get_characters from dialoguemanager import get_dialogue, set_dialogue from locationrandomizer import get_location, get_locations, NPCBlock from monsterrandomizer import change_enemy_name from utils import (WOB_TREASURE_...
58,965
25,651
""" 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 writing, softw...
3,742
1,008
from flask import Flask, jsonify, request import azimuth.model_comparison import numpy as np from azure_service import azure_service from azure_service.azure_service import Settings, AzureService app = Flask(__name__) @app.route("/") def home(): return "Welcome to use Azimuth Web Service API!" @app.route("/test...
4,078
1,359
import numpy as np import pandas as pd import matplotlib.pyplot as plt import os from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import confusion_matrix from sklearn.metrics import classificatio...
939
351
import mysqlTest print('yay')
30
11
from django.urls import path from users.views import ( login, register, logout, profile, unverified_email, verify_email, password_reset, new_password, settings ) app_name = 'users' urlpatterns = [ path('register/', register, name='register'), path('login/', login, name='log...
756
238
#!/bin/env python3 import sys import os project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_root) import argparse import h5py import itertools import numpy import pylru from multiprocessing import Process, Array, Queue import ctypes import arl.test_support from crocodil...
9,132
3,196
import threading from local_utils.scrapyutils import scrap_bookinfos class SpiderThread(threading.Thread): """""" def __init__(self, name, isbn): """Constructor""" threading.Thread.__init__(self) self.name = name self.isbn = isbn def run(self): scrap_bookinfos(sel...
328
108
#!/usr/bin/env python # coding: utf-8 import pytest import numpy as np import pandas as pd import xarray as xr from labelled_functions import label from labelled_functions.maps import * from example_functions import * def test_map_with_several_kind_of_inputs(): length = np.random.rand(5) radius = np.random...
2,953
1,163
from django.contrib.contenttypes.fields import GenericForeignKey, \ GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models as m from django.utils.translation import ugettext_lazy as _ class Post(m.Model): id = m.AutoField(primary_key=True) user = m.ForeignK...
2,740
872
import os from devo.api import Client, ClientConfig, TO_BYTES key = os.getenv('DEVO_API_KEY', None) secret = os.getenv('DEVO_API_SECRET', None) api = Client(auth={"key": key, "secret": secret}, address="https://apiv2-eu.devo.com/search/query", config=ClientConfig(response="csv", ...
719
235
# Copyright 2014 CloudFounders NV # # 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 writ...
2,246
645
#!/usr/bin/env python3 # load.py -*-python-*- import csv import io import os import re import time import urfiles.db # pylint: disable=unused-import from urfiles.log import DEBUG, INFO, ERROR, FATAL class Load(): def __init__(self, directories, config, source=None, debug=False, md5file='md5sum.t...
5,776
1,746
class Image: def __init__(self, json_object): self.type = json_object.get("type") self.fileId = json_object.get("fileId") self.mimeType = json_object.get("mimeType") self.name = json_object.get("name") self.size = json_object.get("size") self.width = json_object.get("...
375
120
# -*- coding: utf-8 -*- """vector3.py Representation of a vector in 3D. License: http://www.apache.org/licenses/LICENSE-2.0""" import math class Vector3(object): def __init__(self, x: float, y: float, z: float) -> None: self.__c = (x, y, z) def __add__(self, other: 'Vector3') -> 'Vector3': ...
2,656
1,028
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Event and exception handeling with logger """ import functools import logging def create_logger(logfile=r"/tmp/tomoproc.log"): """Default logger for exception tracking""" logger = logging.getLogger("tomoproc_logger") logger.setLevel(logging.INFO) # ...
2,109
684
#!python # caller_1.py # caller file for forms # Mikhail Kolodin, 2020 # ver. 2020-02-27 1.0 from forms_1 import * global_values = {'max': 5000, 'min': 100, 'name': 'Vasya'} def main(args): local_values = {'max': 3000, 'name': 'Kirill'} my_values = {**global_values, **local_values} temp = templates['ma...
674
262
class Point(): def __init__(self, input1, input2): self.x = input1 self.y = input2 p = Point(2, 8) print(p.x) print(p.y)
142
60
# Copyright (c) 2013 Mirantis 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 law or agreed to in writ...
3,614
1,088
"""set_districts_on_parkgin_places.py set the district from SP, on the parking place. """ import json import math from sp_districts import get_districts, get_district_from_point _VAGAS_FILE = 'data/vagas/ZonaAzuVagas_DF_ID_latlong.json' _OUTPUT_FILE_RAW = 'data/vagas/vagas_latlong.csv' _OUTPUT_FILE_SCORED = 'data/v...
3,308
1,105
from __future__ import absolute_import from __future__ import division from __future__ import print_function from builtins import object # leaflet object class Leaflet(object): """ Create a bilayer Leaflet representation. This class object is used to group lipids together according to their bilayer leaflet. ...
10,744
2,933
import torch from torch import optim import torch.nn.functional as F from dqn import DQN import run import gym import numpy as np from trajectory_dataset import TrajectoryDataset from torch.utils.tensorboard import SummaryWriter from run import collect_trajectories import os import datetime import qvalues import random...
11,797
3,988
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Licensed to Systerel under one or more contributor license # agreements. See the NOTICE file distributed with this work # for additional information regarding copyright ownership. # Systerel licenses this file to you under the Apache # License, Version 2.0 (the "License...
4,105
1,232
""" This module contains classes intended to parse and deal with data from Roblox promotion channel endpoints. """ from typing import Optional class UserPromotionChannels: """ Represents a user's promotion channels. Attributes: facebook: A link to the user's Facebook profile. twitter: ...
832
243
import tensorflow as tf tf.compat.v1.disable_v2_behavior() from src.datasets.toxic import Toxic from src.models.cnn1 import getCNN1 from src.models.predict import predict_mcdropout import tensorflow as tf def build(): # config RANDOM_STATE = 1 VOCAB_SIZE = 20000 MAX_SEQUENCE_LENGTH = 500 ...
1,256
525
def isPalindrome(r): rL = len(r) rHalf = rL // 2 for i in range(rHalf): if r[i] != r[rL - i - 1]: return False return True def longestPalindrome(s): sLen = len(s) if sLen < 2: return s if sLen == 2: if isPalindrome(s): return s else...
1,691
647
from collections import OrderedDict import torch from ignite.engine import Engine, Events from ignite.handlers import Timer class BasicTimeProfiler(object): def __init__(self): self._dataflow_timer = Timer() self._processing_timer = Timer() self._event_handlers_timer = Timer() def ...
8,437
2,769
#! /usr/bin/env python ########################################################################## # Hopla - Copyright (C) AGrigis, 2015 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.ht...
4,678
1,411
from dipdup.context import HandlerContext from dipdup.models import Transaction from tortoise.exceptions import IntegrityError from quartz_metadata.manager import ResolveMetadataTaskManager from quartz_metadata.models import ResolveToken from quartz_metadata.types.ubisoft_quartz_minter.parameter.mint import MintParame...
999
297
import os def getIndexPage(): return os.popen('cat /var/task/index.html').read()
87
32
import gws.lib.feature import gws.lib.shape import gws.lib.xml2 # geoserver # # <GetFeatureInfoResponse> # <Layer name="...."> # <Feature id="..."> # <Attribute name="..." value="..."/> # <Attribute name="geometry" value="wkt"/> def parse(text, first_el, crs=None, invert_axis=None, **kwar...
1,161
358
# Generated by Django 2.0.6 on 2018-07-02 10:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('parkingsystem', '0015_auto_20180629_1215'), ] operations = [ migrations.AlterField( model_name='parkinglot', name='l...
981
318
# Author: Martin McBride # Created: 2021-05-23 # Copyright (C) 2021, Martin McBride # License: MIT # Use the ranking filters. # Create a final image with all the filters. from PIL import Image, ImageFilter, ImageDraw, ImageFont image = Image.open('boat-small.jpg') min_image = image.filter(ImageFilter.MinFilter()) m...
1,287
553
""" Подготовка датасета для файнтюнинга ruT5 и ruGPT, чтобы модель могла подставлять NP в предложения. Используется неразмеченный текст и синтаксический парсер UDPipe для выделения именных групп. ATT: используются всякие локальные корпуса, которые я не выгружаю в общий доступ по разным соображениям. Тем не менее, не в...
4,974
1,649
import csv from app import db from app.models import Feature def process_row(row): key, value = row[0], row[1] if '/' in value: values = [val.strip() for val in value.split('/')] for v in values: f = Feature(key=key, value=v) db.session.add(f) db.session.commit(...
601
198
__all__ = ["AbstractDataset", "BasicDataset", "Dataset"] class Dataset(object): """A dataset is a collection of values arranged in a structured format. Most datasets are two dimensional -- they can be viewed as a table with rows and columns being the two dimensions. Values in a dataset are usuall...
2,918
852
# -*- coding: utf-8 -*- """ File Name: tf_utils Description : tensorflow工具类 Author : mick.yi date: 2019/3/13 """ import tensorflow as tf def pad_to_fixed_size(input_tensor, fixed_size): """padding到固定长度, 在第二维度末位增加一个padding_flag, no_pad:1, pad:0. Parameter: input_ten...
2,234
1,152
while True : try : text = input() arr = text.split(',') for i in range(len(arr)) : if i == 4 : continue if i == 6 : print("+", end = "") print(arr[4], end = "-") print(arr[6], end = "") else : print(arr[i], end = ",") print() except EOFError : break
291
143
# Copyright 2018 Google LLC # # 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, s...
15,621
5,009
from simtk.openmm.app import * from simtk.openmm import * from simtk.unit import * import numpy as np def membrane_term(oa, k=1*kilocalorie_per_mole, k_m=20, z_m=1.5, membrane_center=0*angstrom, forceGroup=24): # k_m in units of nm^-1, z_m in units of nm. # z_m is half of membrane thickness # membrane_cent...
9,922
4,034
import sys import os import inspect currentdir = os.path.dirname(os.path.abspath( inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) import matplotlib.pyplot as plt import matplotlib.dates as mdates import seaborn as sns import pandas as pd from datetim...
8,192
2,674
# Loss for AE, VAE, ML-AE, Inv-ML-AE
36
20
from .config import * from .funcs import norm, target_estimate from .helpers import ImageHelper from ...common import load_kernels_for_image, release_kernels from ....support import sci_2 def set_info( image: ImageWrapper, image_axis=None, analysis_axis=None, **config ): raw = imag...
5,443
1,655
import tvm import logging import numpy as np from collections.abc import Iterable from .namespace import MSIR_COLLECTION,MSIR_NAME,MSIR_TARGET def _get_logger(): if not MSIR_COLLECTION.get(MSIR_NAME.LOGGER): MSIR_COLLECTION.set(MSIR_NAME.LOGGER, logging.getLogger("MSIR")) return MSIR_COLLECTION.get(MS...
2,187
774
######################################################################### # Dicomifier - Copyright (C) Universite de Strasbourg # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for...
2,072
693
# -*- coding: utf-8 -*- """ *** Labelling is T O M B S It depends on the distance between the baseline and its above and below valid (S) cut Cuts are SIO Copyright Naver Labs Europe(C) 2018 JL Meunier Developed for the EU project READ. The READ project has received fun...
12,365
3,667
""" 111 / 111 test cases passed. Runtime: 440 ms Memory Usage: 14.9 MB """ class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: count = largest = 0 def dfs(idx, res): nonlocal count, largest if idx == len(nums): if res > largest: ...
574
180
#!/usr/bin/env python """ MIT License (modified) Copyright (c) 2020 The Trustees of the University of Pennsylvania Authors: Vasileios Vasilopoulos <vvasilo@seas.upenn.edu> Omur Arslan <omur@seas.upenn.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this **file** (the "Software"),...
111,008
42,538
from time import sleep from pysphere import VITask, FaultTypes from pysphere.vi_virtual_machine import VIVirtualMachine from pysphere.resources.vi_exception import VIException, VIApiException from pysphere.vi_mor import VIMor from pysphere.vi_task import VITask import ssl import pypacksrc import re, subprocess def ...
33,529
11,802