text
string
size
int64
token_count
int64
from copy import copy from itertools import groupby import unittest from datetime import datetime, timedelta from typing import List from activitywatch.base import Watcher, Activity, Logger from activitywatch.settings import Settings from activitywatch.utils import floor_datetime, ceil_datetime from activitywatch.filt...
4,253
1,474
voc_it = [ ['a', 'noun', 'c'], ['a', 'preposition', 'a'], ['abbagliante', 'pres_part', 'c'], ['abbagliante', 'adjective', 'c'], ['abbagliante', 'noun', 'c'], ['abbaiare', 'verb', 'c'], ['abbandonare', 'verb', 'a'], ['abbandonato', 'past_part', 'b'], ['abbandonato', 'adjective', 'b'], ['abbandono', 'noun', 'b'], ['abbas...
254,077
114,529
from __future__ import absolute_import, division, print_function, unicode_literals import os # this arbitrary-looking assortment of functionality is provided here # to have a central place for overrideable behavior. The motivating # use is the FB build environment, where this source file is replaced # by an equivalen...
940
312
import json from collections import OrderedDict from typing import Union, List import clip import torch import torch.nn as nn import torch.nn.functional as F from libs.definitions import ROOT label_file = ROOT / 'imagenet_class_index.json' with open(label_file, 'r') as f: labels = json.load(f) _DEFAULT_CLASSNAM...
9,099
3,063
#!/usr/bin/env python from __future__ import print_function from optparse import OptionParser import os import random import subprocess import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt import pysam from scipy.stats import binom from scipy.stats.mstats import mquantiles import...
11,463
4,091
#!/usr/bin/env python3 import codecs import re def trans_addr(addr): """Traduit une position de fichier en une adresse du programme""" if addr < 0x1000: return 0 if 0x0000000000001000 <= addr < 0x0000000000001000 + 0x00001ef000000000: return 0x00002b0000000000 + addr - 0x0000000000001000 ...
1,657
717
import pygame_gui import pygame class colors: black = "#000000" dimgrey = "#696969" # lmao darkslategray = "#2F4F4F" TITLE = "TUNAPRO1234" BACKGROUND = colors.darkslategray WIDTH, HEIGHT = 1920, 1080 """ Hızlıca bir plan yapacağım Neural ağları kontrol edebileceğimiz küçük bir framework Ağların geli...
4,826
1,753
import time import pytest from flask import g from flask import session import paho.mqtt.client as paho from SmartSleep.db import get_db from flask import json import runpy msg_nr = 0 messages = [""] broker = 'broker.emqx.io' port = 1883 def update_contor(): global msg_nr msg_nr += 1 def on_message(client...
2,814
913
import theano.tensor as tt def explin(x): return tt.where(x >= 0, 1 + x, tt.exp(x)) def log_exp1p(x): return tt.log1p(tt.exp(x))
136
73
from pyEtherCAT import MasterEtherCAT #ライブラリの読出し nic = "eth0" # ネットワークカードのアドレスを記載 cat = MasterEtherCAT.MasterEtherCAT(nic) ADP = 0x0000 #1台目 ADDR = 0x0E00 #コアレジスタのアドレス cat.APRD(IDX=0x00, ADP=ADP, ADO=ADDR, DATA=[0,0,0,0,0,0,0,0]) #DATAは0を8個(64bit分)の枠を指示 (DATA, WKC) = cat.socket_read() #結果を読出し print("[0x{:04X}]= 0x{:...
470
319
#!/usr/bin/env python # -*- coding: UTF-8 -*- import pprint from base import BaseObject from base import FileIO class PythonLOCParser(BaseObject): """ Parse T/LOC from a Python File """ def __init__(self, file_path: str, is_debug: bool = False): """ C...
1,353
431
import pandas as pd import time df = pd.read_csv("data/sample.csv") for num in range(1000): argx = str(df["x"][num:num+1].get_values()) argy = str(df["y"][num:num+1].get_values()) print("x:{0} / y:{1}".format(argx,argy)) time.sleep(0.1)
255
113
from django.urls import path from . import views app_name = "graphs" urlpatterns = [ path("graphs/", views.GraphListView.as_view(), name="graph.list"), path("graphs/create/", views.GraphCreateView.as_view(), name="graph.create"), path( "graphs/<str:pk>/", views.GraphDetailView.as_view(), ...
601
202
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick - extended by Lukas Tuggener # -------------------------------------------------------- """Blob helper functions.""" from __future...
2,823
1,081
# coding=utf-8 """ Gathers the media folders """ import elib from ._context import Context def get_media_folders(ctx: Context): """ Gathers the media folders """ ctx.info('gathering media folders') media_folders = [] this_folder = ctx.source_folder while True: ctx.debug(f'trave...
1,022
333
from inspect import signature import twister2.tset.TSet as ts from twister2.utils import function_wrapper class TLink: def __init__(self, java_ref, env): self.__java_ref = java_ref self.__env = env def map(self, lam): map_wrapper = function_wrapper(lam) map_func_java_ref = s...
1,924
619
from e2cnn.gspaces import * from e2cnn.nn import FieldType from e2cnn.nn import GeometricTensor from e2cnn.group import Representation from e2cnn.group.representation import build_from_discrete_group_representation from ..equivariant_module import EquivariantModule import torch from typing import List, Tuple, Any i...
9,373
2,467
import requests import re import socket from common.colors import bad,que, info, good,run,W,end from common.uriParser import parsing_url as hostd class GatherHost(): def __init__(self,url,headers=None): self.url = url self.headers = headers def match_info(self,regex,data): match ...
2,551
811
from key import Key from query import Cursor class Datastore(object): '''A Datastore represents storage for any key-value pair. Datastores are general enough to be backed by all kinds of different storage: in-memory caches, databases, a remote datastore, flat files on disk, etc. The general idea is to wrap ...
34,379
10,916
from django.contrib import admin from django.contrib.admin import widgets from .models import Person, Publication, Position, Talk, Project, Poster, Keyword, News, Banner, Video, Project_header, Photo, Project_umbrella, Project_Role, Sponsor from website.admin_list_filters import PositionRoleListFilter, PositionTitleLis...
15,988
4,873
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 26 21:39:04 2019 @author: fmk """ import argparse,subprocess,string,random import pandas as pd ''' positional and optional argument parser''' parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, ...
6,191
2,008
import os import angr test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') def test_vtable_extraction_x86_64(): p = angr.Project(os.path.join(test_location, "x86_64", "cpp_classes"), auto_load_libs=False) vtables_sizes = {0x403cb0: 24, 0x403cd8: 1...
708
336
from zeep import Client def test(): client = Client('http://www.dneonline.com/calculator.asmx?wsdl') result = client.service.Add(100,220) print(result) def test2(): client = Client('http://172.16.237.11:8080/SendNotify_Interface_Gmail/services/Notify?wsdl') result = client.service.sendEmail("loitd...
465
198
'''The HTTP agent - provides observation using http push to remote agent and expects action in the reply''' import json import time import os import threading import requests from . import BaseAgent from .. import utility from .. import characters class HttpAgent(BaseAgent): """The HTTP Agent that connects to...
2,760
726
# -*- coding: utf-8 -*- from rest_framework import serializers from django_countries.serializer_fields import CountryField from .models import Event, CountryEvent class CountryEventSerializer(serializers.ModelSerializer): code = serializers.ReadOnlyField(source='country.code') name = serializers.SerializerM...
737
202
#!/usr/bin/env python """ Prints a map of the entire world. """ import os, sys import math from struct import pack # local module try: import nbt except ImportError: # nbt not in search path. Let's see if it can be found in the parent folder extrasearchpath = os.path.realpath(os.path.join(__file__,os.pardi...
13,998
5,844
from flaskcbv.url import Url, make_urls from .views import mainView namespases = make_urls( Url('', mainView(), name="main"), )
136
50
# Rest framework from rest_framework import permissions class IsAuthorOrReadOnly(permissions.BasePermission): """ Object level permission. Check if the requesting user is the author or not. If he/she the author then we will give him/her a read and write permission otherwise ready only """ def has_obje...
536
137
""" femagtools.vtu ~~~~~~~~~~~~~~ Read FEMAG vtu files """ import vtk import pathlib import numpy as np class Reader(object): '''Class to read vtu-files''' def __init__(self, pathname): '''Read the vtu-files Parameters ---------- pathname : str Directo...
8,595
2,494
#!/usr/bin/python #-------------------------------IMPORT--------------------------------# from lib import * #-------------------------------EXPORT--------------------------------# __all__ = ['<#PREFIX#>_app','<#PREFIX#>_index']
232
62
from collections import Counter import numpy as np def keep_word(word): return word.is_alpha def unique_words(problems): return set([word.lemma_ for problem in problems for word in problem.tokens() if keep_word(word)]) def create_word2idx(vocab): return {word: idx for idx, word in enumerate(vocab)} ...
916
288
#!/usr/bin/python ''' Tests for MPS and MPO ''' from numpy import * import matplotlib.pyplot as plt from numpy.testing import dec, assert_, assert_raises, assert_almost_equal, assert_allclose import pdb from ..sweep import * def test_iterator(): start = (1, '->', 2) stop = (3, '<-', 1) print('Testing ite...
1,507
636
from threading import Lock from time import time from ui import Menu from ui.utils import clamp, check_value_lock, to_be_foreground class NumberedMenu(Menu): """ This Menu allows the user to jump to entries using the numpad. If the menu is 10 entries or less the navigation is instant. Otherwise, it lets ...
4,471
1,353
# coding=utf-8 """Russian Peasant Multiplication algorithm Python implementation.""" def russ_peasant(a, b): res = 0 while b > 0: if b & 1: res += a a <<= 1 b >>= 1 return res if __name__ == '__main__': for x in range(10): for y in range(10): p...
358
135
from urllib.parse import urlparse, parse_qs from io import BytesIO import json class MockRequest: def getmethod(self, path): apiend = "v2/" start = path.find(apiend) + len(apiend) return path[start:] def urlopen(self, url): output = BytesIO() parsed = urlparse(url) ...
36,420
23,109
import math import torch from bisect import bisect_right class _LRScheduler: def __init__(self, optimizer, last_epoch=-1): self.optimizer = optimizer self.base_lr = optimizer.lr self.last_epoch = last_epoch def step(self): self.last_epoch += 1 self.optimizer.lr = self....
1,589
567
# -*- coding: utf-8 -*- from .._globals import IDENTITY from ..connection import ConnectionPool from .base import BaseAdapter class TeradataAdapter(BaseAdapter): drivers = ('pyodbc',) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'VARCHAR(2000)', 'j...
2,972
1,051
import os import platform import unittest import nose from conans import tools from conans.errors import ConanException from conans.model.version import Version from conans import __version__ as client_version from conans.model import settings from conans.test.utils.tools import TestClient from conans.test.assets.vis...
8,367
2,492
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import argparse import json import os from pinliner import __version__ import sys TEMPLATE_FILE = 'importer.template' TEMPLATE_PATTERN = '${CONTENTS}' def output(cfg, what, newline=True): # We need indentation for PEP8 cfg...
7,797
2,352
from dotenv import load_dotenv load_dotenv() import os import boto3 #s3 = boto3.resource('s3') s3 = boto3.resource('s3', aws_access_key_id=os.environ.get("AWS_KEY_ID"), aws_secret_access_key=os.environ.get("AWS_SECRET_KEY")) for bucket in s3.buckets.all(): print(bucket.name)
305
121
import os from sonar.testbench import Testbench, Module, TestVector, Thread from sonar.interfaces import AXIS from sonar_strToInt import strToInt hold_buffer = Testbench.default('hold_buffer') filepath = os.path.join(os.path.dirname(__file__), 'build/hold_buffer/') dut = Module.default("DUT") dut.add_clock_port('ap...
2,570
995
#!/usr/bin/env python # filename: pair.py # # Copyright (c) 2015 Bryan Briney # License: The MIT license (http://opensource.org/licenses/MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal in the Software...
16,957
5,065
import tensorflow as tf from t3f.tensor_train import TensorTrain from t3f.tensor_train_batch import TensorTrainBatch from t3f import shapes from t3f import decompositions def project_sum(what, where, weights=None): """Project sum of `what` TTs on the tangent space of `where` TT. project_sum(what, x) = P_x(what)...
38,104
14,392
from django.contrib import admin from . import models @admin.register(models.Username) class UsernameAdmin(admin.ModelAdmin): list_display = ('user', 'name', 'is_mod') readonly_fields = ('normalized_name',) search_fields = ('user__email', 'name')
262
81
import logging from iptv_proxy.providers.beast.constants import BeastConstants from iptv_proxy.providers.iptv_provider.json_api import ProviderConfigurationJSONAPI logger = logging.getLogger(__name__) class BeastConfigurationJSONAPI(ProviderConfigurationJSONAPI): __slots__ = [] _provider_name = BeastConsta...
346
105
#!/usr/bin/env python # Copyright 2015 Wieger Wesselink. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) import os import os.path import random import re import sys import traceback sys.path += [os.path.abspath(os.path.join...
30,912
9,017
""" Main program to launch proc/hdfs.py """ import argparse import logging from pars import addargs import sys import logging logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) from proc.hdfs import DIRHDFS def gettestargs(parser) : i = "/home/sbartkowski/work/webhdfsdirectory/testdata/...
969
350
"""JSON (de)serialization framework. The framework presented here is somewhat based on `Go's "json" package`_ (especially the ``omitempty`` functionality). .. _`Go's "json" package`: http://golang.org/pkg/encoding/json/ """ import abc import binascii import logging import OpenSSL import six from josepy import b64,...
15,748
4,722
from norm.models.norm import Status, Lambda from norm.executable import NormExecutable from typing import Union, List import logging logger = logging.getLogger(__name__) class VariableName(NormExecutable): def __init__(self, scope, name): """ The variable and its scope :param scope: the ...
6,463
1,782
from __future__ import print_function import os import sys import json import tika from tqdm import tqdm from utils import LogUtil from parser import Parser from ioutils import read_lines from tika import parser as tk_parser class TikaParser(Parser): """ The TikaParser class is wrapper of the Apache TIKA parse "...
3,318
1,063
from checkov.cloudformation.checks.resource.base_resource_check import BaseResourceCheck from checkov.common.parsers.node import DictNode from checkov.common.models.enums import CheckResult, CheckCategories class DocDBAuditLogs(BaseResourceCheck): def __init__(self) -> None: name = "Ensure DocDB has audit...
869
263
# # Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending # import jpy _JCallbackAdapter = jpy.get_type('io.deephaven.server.plugin.python.CallbackAdapter') def initialize_all_and_register_into(callback: _JCallbackAdapter): try: from . import register except ModuleNotFoundError as e: ...
584
183
"""Tests for parse tree pretty printing that preserves formatting Test case descriptions are in file test/data/output.test. """ import os.path import re from typing import Undefined, Any from mypy import build from mypy.myunit import Suite, run_test from mypy.test.helpers import assert_string_arrays_equal from mypy...
3,133
877
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import un...
2,395
638
import logging import os import tempfile import PIL.Image import numpy import tensorflow import microscopeimagequality.constants import microscopeimagequality.data_provider import microscopeimagequality.evaluation import microscopeimagequality.prediction class Inference(tensorflow.test.TestCase): def setUp(self...
7,005
2,181
""" QuickBot wiring config. Specifies which pins are used for motor control, IR sensors and wheel encoders. """ # Motor pins: (dir1_pin, dir2_pin, pwd_pin) RIGHT_MOTOR_PINS = 'P8_12', 'P8_10', 'P9_14' LEFT_MOTOR_PINS = 'P8_14', 'P8_16', 'P9_16' # IR sensors (clock-wise, starting with the rear left sensor): # rear-l...
498
246
#!/usr/bin/env python # Copyright (c) 2013 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. # Self-test for skimage. import filecmp import os import subprocess import sys import tempfile class BinaryNotFoundException(Exce...
8,912
2,489
from collections import namedtuple Condition = namedtuple( 'Condition', ['current_state', 'input_character'], )
121
33
"""Asset definitions for the simple_lakehouse example.""" import pandas as pd from lakehouse import Column, computed_table, source_table from pyarrow import date32, float64, string sfo_q2_weather_sample_table = source_table( path="data", columns=[Column("tmpf", float64()), Column("valid_date", string())], ) @com...
788
271
#!/usr/bin/env python # -*- coding: utf-8 -*- # #@created: 07.01.2018 #@author: Aleksey Komissarov #@contact: ad3002@gmail.com from aindex import * settings = { "index_prefix": "tests/kmers.23", "aindex_prefix": "tests/kmers.23", "reads_file": "tests/reads.reads", } index = load_aindex(settings) k = 23 seque...
4,386
2,039
"""Implements test for pytest-resource-path Fixtures with pytest.ini.""" from pathlib import Path import pytest def test_resource_path_ini(resource_path, request): """Fixture resource_path should be following absolute path.""" assert resource_path == Path(str(request.fspath)).parents[1] / Path( "data...
1,013
321
# Illustrates combining exception / error handling # with file access print('Start') try: with open('myfile2.txt', 'r') as f: lines = f.readlines() for line in lines: print(line, end='') except FileNotFoundError as err: print('oops') print(err) print('Done')
301
93
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 11 13:30:53 2017 @author: laoj """ import numpy as np import pymc3 as pm import theano.tensor as tt from pymc3.distributions.distribution import Discrete, draw_values, generate_samples, infer_shape from pymc3.distributions.dist_math import bound, lo...
8,455
3,796
from useful import * from os import system def remove_implication(formula): while ">" in formula: operator = formula.find(">") print(formula, operator) subform_left = get_subform_left(formula, operator) subform_right = get_subform_right(formula, operator) formula = get_remo...
8,054
2,831
# Copyright 2018 Oliver Berger # # 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,...
2,896
837
from trainer.utils.losses import * from trainer.utils import custom_ssim
73
23
############################################################################## # # Copyright (c) 2005 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS I...
1,693
496
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
3,132
950
#!/usr/bin/env python import sys HATOMS = ["HG", "HD", "HE", "HH"] lines = open(sys.argv[1]).readlines() for line in lines: if line[:6] == "ATOM " or line[:6] == "HETATM": if line[17:20] == "WAT": continue if line[13] == "H": continue if line[12:14] in HATOMS: ...
369
142
import Pmw import os import re from FastIndex import FastIndex, timer from PrologFrame import PrologFrame from TerminalFrame import TerminalFrame class OutputBook(Pmw.NoteBook): def __init__(self, master=None): self.app = master Pmw.NoteBook.__init__(self, self.app.bottom,createcommand=self.create...
7,693
2,453
import sqlite3 with sqlite3.connect('storage.db') as conn: cursor = conn.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS Produtos ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, price REAL, compra_id INTEGER, ...
5,468
1,583
disable_gtk_binaries = True def gtk_dependent_cc_library(**kwargs): if not disable_gtk_binaries: native.cc_library(**kwargs) def gtk_dependent_cc_binary(**kwargs): if not disable_gtk_binaries: native.cc_binary(**kwargs)
246
87
import sys from gensim import models from gensim.models.doc2vec import LabeledSentence import pickle def corpus_to_sentences(corpus): sentences = [] for idx, (name, doc) in enumerate(corpus.items()): sys.stdout.write('\r前処理中 {}/{}'.format(idx, len(corpus))) sentence = LabeledSentence(words=doc...
743
277
# -*- encoding: utf-8 -*- from collections import UserDict from itertools import count import shutil import winreg import uuid PATH = "Software\\Microsoft\\Windows\\CurrentVersion\\Lxss" KEY = winreg.HKEY_CURRENT_USER class RegistryDescriptor(object): def __init__(self, name): self.name ...
6,206
1,982
# changelog.py -- Python module for Debian changelogs # Copyright (C) 2006-7 James Westby <jw+debian@jameswestby.net> # Copyright (C) 2008 Canonical Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fo...
25,235
7,301
# Define a procedure, median, that takes three # numbers as its inputs, and returns the median # of the three numbers. # Make sure your procedure has a return statement. def bigger(a,b): if a > b: return a else: return b def biggest(a,b,c): return bigger(a,bigger(b,c)) def...
667
275
import requests import os import subprocess import gidgethub from gidgethub import sansio AUTOMERGE_LABEL = ":robot: automerge" def comment_on_pr(issue_number, message): """ Leave a comment on a PR/Issue """ request_headers = sansio.create_headers( "miss-islington", oauth_token=os.getenv("...
5,089
1,696
import aiosqlite import sqlite3 import asyncio import nonebot from nonebot.log import logger driver: nonebot.Driver = nonebot.get_driver() config: nonebot.config.Config = driver.config @driver.on_startup async def init_db(): config.db = await aiosqlite.connect("src/static/Kiba.db") logger.info("Kiba Kernel -...
1,918
569
from typing import Callable, Optional, Sequence, Tuple, Union import numpy from dexp.processing.utils.nd_slice import nd_split_slices, remove_margin_slice from dexp.processing.utils.normalise import Normalise from dexp.utils import xpArray from dexp.utils.backends import Backend def scatter_gather_i2i( function...
5,492
1,708
from .backend import Backend from .thread import HttpPool
58
15
#!/usr/local/bin/python3 def main(): # Test suite return if __name__ == '__main__': main()
107
42
import fnmatch import glob import os import sys import setuptools.command.build_ext APPLE = sys.platform == 'darwin' BASE_DIR = os.path.dirname(__file__) ABOUT = {} def _read_about(): with open(os.path.join(BASE_DIR, 'omnibus', '__about__.py'), 'rb') as f: src = f.read() if sys.version_info[0...
3,759
1,250
from day1 import * import unittest def test_get_fuel_requirements_for_mass(): assert get_fuel_requirements_for_mass(12) == 2 assert get_fuel_requirements_for_mass(14) == 2 assert get_fuel_requirements_for_mass(1969) == 654 assert get_fuel_requirements_for_mass(100756) == 33583 def test_sum_fuel_requirements_f...
689
302
import AppKit from PyObjCTools.TestSupport import TestCase, min_os_level class TestNSPDFInfo(TestCase): @min_os_level("10.9") def testMethods(self): self.assertResultIsBOOL(AppKit.NSPDFInfo.isFileExtensionHidden) self.assertArgIsBOOL(AppKit.NSPDFInfo.setFileExtensionHidden_, 0)
305
102
from collections import OrderedDict, defaultdict import numpy as np ''' generate a id to length dic ''' def gen_sid_len(sentences): sid2len = OrderedDict() for i, sent in enumerate(sentences): sid2len[i] = len(sent) return sid2len def batch_slice(data, batch_size): # data is a list of senten...
1,636
522
from ._schema import DefaultSchema from ._utils import get_minutes, get_yields, normalize_string class TheHappyFoodie(DefaultSchema): @classmethod def host(cls): return "thehappyfoodie.co.uk" def title(self): return self.soup.find("h1", {"class": "main-title"}).get_text() def total_t...
1,793
535
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright [2017] Tatarnikov Viktor [viktor@tatarnikov.org] # # 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/licen...
2,866
861
# -*- coding: utf-8 -*- # !/usr/bin/python __author__ = 'ma_keling' # Version : 1.0.0 # Start Time : 2018-11-29 # Update Time : # Change Log : ## 1. ## 2. ## 3. import time import arcpy import math def express_arcpy_error(): severity = arcpy.GetMaxSeverity() if severity =...
8,372
2,758
# -*- coding: utf-8 -*- """ Created on Sat Feb 8 07:38:05 2020 @author: Ham Self Challenge: Count Cluster of Non-0s Given a 1-dimension array of integers, determine how many 'clusters' of non-0 in the array. A 'cluster' is a group of consecutive non-0 values. Scoring: a solution needs to be a 1-liner; ...
3,894
2,364
"""Tests for node configuration.""" import json import logging import time from pathlib import Path import allure import pytest from _pytest.tmpdir import TempdirFactory from cardano_clusterlib import clusterlib from cardano_node_tests.utils import cluster_management from cardano_node_tests.utils import cluster_nodes...
5,133
1,702
#!/usr/bin/env python from __future__ import print_function import matplotlib matplotlib.use('Agg') import os import heapq import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.colors as colors import matplotlib.cm as cm from numpy import * from random import samp...
241,016
81,302
from multiprocessing import Queue, Value from time import sleep from access_face_vision.source.camera import Camera from access_face_vision.utils import create_parser from access_face_vision import access_logger LOG_LEVEL = 'debug' logger, log_que, que_listener = access_logger.set_main_process_logger(LOG_LEVEL) def...
661
215
from utils.deserializer.protobuf_deserializer import ProtoLoader from pathlib import Path import pandas as pd import pytest PROTOFILES_DIR_PATH = Path(__file__).parent.joinpath("protofilesdir").absolute().__str__() INVALID_PATH = "some/wrong/path" @pytest.mark.parametrize('filepath', ["test_file.pb", "test_file_1.tx...
1,537
531
#!/usr/bin/env python # encoding: utf-8 """ turbine.py Created by Andrew Ning and Katherine Dykes on 2014-01-13. Copyright (c) NREL. All rights reserved. """ from openmdao.main.api import Assembly, Component from openmdao.main.datatypes.api import Float, Array, Enum, Bool, Int from openmdao.lib.drivers.api import Fix...
18,966
6,798
"""add run_type Revision ID: 5dd2ba8222b1 Revises: 079a74c15e8b Create Date: 2021-07-22 23:53:04.043651 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '5dd2ba8222b1' down_revision = '079a74c15e8b' branch_labels = None ...
2,880
990
from .config import add_panopticfcn_config from .panoptic_seg import PanopticFCN from .build_solver import build_lr_scheduler
126
43
from http.client import HTTPResponse from django.shortcuts import render from django.http import HttpResponse # Create your views here. # def index(request): # return HttpResponse("Hello World!") def index(request): return render(request, "hello/index.html") def brian(request): return HttpResponse("Hello...
592
177
## # Copyright (c) 2010-2017 Apple Inc. 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 l...
19,426
5,590
from netapp.netapp_object import NetAppObject class AliasesInfo(NetAppObject): """ A list of WWPNs and their aliases generated according to the input - alias, WWPN or nothing. """ _vserver = None @property def vserver(self): """ Vserver containing the alias """ ...
1,770
547
import numpy as np import code from imagernn.utils import merge_init_structs, initw, accumNpDicts from imagernn.lstm_generator import LSTMGenerator from imagernn.rnn_generator import RNNGenerator def decodeGenerator(generator): if generator == 'lstm': return LSTMGenerator if generator == 'rnn': return RNNG...
5,745
1,878