text
string
size
int64
token_count
int64
""" https://leetcode.com/problems/degree-of-an-array/ https://leetcode.com/submissions/detail/130966108/ """ class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ d = dict() for index, num in enumerate(nums): if...
1,364
439
def shellSort(alist): gap = len(alist) // 2 while gap > 0: for i in range(gap, len(alist)): val = alist[i] j = i while j >= gap and alist[j - gap] > val: alist[j] = alist[j - gap] j -= gap alist[j] = val gap //= 2
318
111
import pytest import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression, RidgeClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.dummy import DummyClassifier @pytest.mark.parametrize( ("tes...
13,245
4,580
import os import shutil import subprocess from possum.exc import PipenvPathNotFound class PipenvWrapper: def __init__(self): self.pipenv_path = shutil.which('pipenv') if not self.pipenv_path: raise PipenvPathNotFound # Force pipenv to ignore any currently active pipenv envir...
2,249
650
import pytest import envpy import os folder = os.path.dirname(__file__) folder_env_file = f'{folder}/resources' file_dot_env = 'test.env' def test__init__(): karg = {'filepath':folder_env_file, 'filename':file_dot_env} envpy.get_variables(**karg) envpy.printenv(envpy.get_variables(**karg)) if __name_...
360
139
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: fnels """ import random def random_actions(): action_list = [random.randint(0, 3)] return action_list
195
71
#!/usr/bin/env python import argparse import os import pkt_kg as pkt import psutil import re from rdflib import Graph from rdflib.namespace import OWL, RDF, RDFS from tqdm import tqdm import glob import logging.config import time from datetime import timedelta from lxml import etree from urllib.request import urlopen ...
18,320
6,472
import os import sys import argparse import onnx import time import subprocess import numpy as np import tempfile from onnx import numpy_helper from collections import OrderedDict # Command arguments. parser = argparse.ArgumentParser() parser.add_argument('model_path', type=str, help="Path to the ONNX model.") parser...
11,513
3,414
class O(object): pass class A(O): pass class B(O): pass class C(O): pass class D(O): pass class E(O): pass class K1(A,B,C): pass class K2(D,B,E): pass class K3(D,A): pass class Z(K1,K2,K3): pass print K1.__mro__ print K2.__mro__ print K3.__mro__ print Z.__mro__
262
122
import requests from json import loads from bs4 import BeautifulSoup from os import environ l = ['atom','moon','star','space','astro','cluster','galaxy','sky','planet','solar','science','physic','scientist','cosmos'] def clean(text): while '[' in text: text = text.replace(text[text.find('['):text.find(']',...
3,154
894
############################################################################# # # # Module of BFA that manages server statistics in realtime # # ############################################################################# """ This module implements the real-time logging of in-game statistics specifically for one curre...
1,012
269
from django.shortcuts import render from django.http import JsonResponse from django.views import View from core.handlers.dispatcher import process_telegram_event from app_my_places.settings import TELEGRAM_TOKEN import json # Create your views here. def index(request): return JsonResponse({"error": "forbidden"})...
615
185
#!/usr/bin/env python3 def foo(): a = 10 # infer that b is an int b = a assert b == 10 print(b) if __name__ == "__main__": foo()
157
68
# Copyright (c) 2020, TU Wien, Department of Geodesy and Geoinformation # 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 notice,...
4,852
1,509
import pytest import tempfile @pytest.fixture def post(user): from posts.models import Post image = tempfile.NamedTemporaryFile(suffix=".jpg").name return Post.objects.create(text='Тестовый пост 1', author=user, image=image) @pytest.fixture def group(): from posts.models import Group return Grou...
1,592
496
from django.shortcuts import render # Create your views here. def index(): pass
85
25
#!/usr/bin/env python # The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/li...
17,584
5,837
from django.conf import settings from django.contrib.postgres.fields import JSONField from django.db import models from django.db.models import Q from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ TARGET_FKEY_ATTRS = dict( null=True, blank=True, on_...
5,551
1,624
import logging import threading import unittest from pykka import ActorRegistry, ThreadingActor from tests import TestLogHandler from tests.actor_test import ( EarlyFailingActor, FailingOnFailureActor, LateFailingActor) class LoggingNullHandlerTest(unittest.TestCase): def test_null_handler_is_added_to_avoi...
7,202
2,255
from nevow.inevow import ILanguages from nevow.i18n import I18NConfig from nevow import i18n _ = i18n.Translator(domain='ldaptor-webui') def render(): return i18n.render(translator=_)
190
78
import math from scipy.spatial.ckdtree import cKDTree from core.camera import Camera from core.intersection import Intersection from core.ray import Ray from core.renderer import Renderer from core.sample import Sample from core.sampler import Sampler from core.scene import Scene from core.spectrum import Spec...
2,026
692
from ...abc import Expression, evaluate from ..value.eventexpr import EVENT from ..value.eventexpr import KWARGS from ..value.eventexpr import ARG from ..value.valueexpr import VALUE from ..utility.context import CONTEXT class ITEM(Expression): """ Get the item from a dictionary. There are two forms: 1) Mapping f...
1,831
718
""" Faça um programa que pergunte a hora aousuário e, baseando-se na hora descrita, exiba a saudação apropriada. """ x=1 while x!=0: #Entra no try caso seja digitado um numero inteiro try: horas=int(input('Que horas são? ')) if horas>=0 and horas<=11: print('Bom dia!') x...
821
275
import aiohttp_jinja2 import jinja2 import secrets import random from aiohttp import web from aiohttp.client import MultiDict from source import fit_model, vectorize, model_predict routes = web.RouteTableDef() PORT = 8080 base_url = f"http://localhost:{PORT}" IMGS, X, Y = 3, 5, 7 THRESH = 0.1 networks = {} @rout...
4,137
1,514
x="There are %d types of people."%10 binary="binary" do_not="don't" y="Those who know %s and those who %s."%(binary,do_not) print(x) print(y) print("I said: '%s'."%y) hilarious=False joke_evaluation="Isn't that joke so funny?! %r" print (joke_evaluation % hilarious) w="This is the left side of ..." e="a string with a r...
343
146
# -*- coding: utf-8 -*- import sys from pathlib import Path import yaml class Config: """ Extracts the data from the configuration file given """ def __init__(self, path): with open(path, 'r') as f: contents = f.read() self.options = yaml.safe_load(contents) path_to_c...
627
198
from mezzanine.pages.admin import PageAdmin from django.contrib import admin from hs_modflow_modelinstance.models import MODFLOWModelInstanceResource admin.site.register(MODFLOWModelInstanceResource, PageAdmin)
217
62
#!/usr/bin/python import shellcode import optparse import httplib import logging import random import socket import sys import re from struct import pack, unpack from time import sleep ######################## # Global configuration # ######################## DEFAULT_ETAG_FILE = "ELBO.config" VERSION = "%prog v1.0.0....
24,526
7,666
from flask import Blueprint, render_template, url_for, session, flash, redirect, request from edu_visitor import db from edu_visitor.visitor_logs.forms import StudentSignInForm, StudentSignOutForm, VisitorSignInForm, VisitorSignOutForm, StudentUpdateForm, VisitorUpdateForm from edu_visitor.models import StudentLog, Vi...
8,716
2,678
import sys import abc import tensorflow as tf import numpy as np import optimizer class AbstractModel(abc.ABC): '''Abstract base class for knowledge graph embedding models. You won't usually want to derive directly from this class. In most cases, you'll want to derive from either `AbstractMainModel` or...
1,657
423
"""Tools for creating and manipulating event schedules and traffic matrices""" from fnss.traffic.eventscheduling import * from fnss.traffic.trafficmatrices import *
165
45
import os import sys from argparse import ArgumentParser from sphinxviewer.sphinx import build_html from sphinxviewer.server import serve_server def main(): parser = ArgumentParser(description="Live editing sphinx doc server") # parser.add_argument("-p", "--port", default=8888, help="Port to run server on")...
687
210
import mimetypes from django.contrib.staticfiles.storage import staticfiles_storage from django.core import signing from django.forms import widgets from django.forms.utils import flatatt from django.utils.safestring import mark_safe from django.utils.html import format_html from django.utils.translation import ugette...
4,338
1,280
from wok.task import task @task.main() def main(): values, count_port, sum_port = task.ports("x", "count", "sum") count = 0 sum = 0 for v in values: task.logger.info("value = {0}".format(v)) count += 1 sum += v task.logger.info("Sum of {0} numbers = {1}".format(count, sum)) count_port.send(count) sum_...
347
150
from flask import jsonify, render_template import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as dt from climateapp import app engine = create_engine('sqlite:///../Resources/hawaii.sqlite') Base = automap_base...
2,961
1,119
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import json import io import sys import traceback import webbrowser from contextlib import redirect_stdout from datetime import datetime from PyQt5.Qt import ( QApplication, QMessageBox, QThread, pyqtSignal, QMainWindow, QPushButton, QCheck...
9,443
3,099
"""fasterRCNN对象创建""" import numpy as np import colorsys import os from keras import backend as K from keras.applications.imagenet_utils import preprocess_input from PIL import Image, ImageFont, ImageDraw import copy import math from net import fasterrcnn as frcnn from net import netconfig as netconfig from net import ...
10,326
4,269
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. # Copyright 2021 RangiLyu. # # 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 # # Unle...
3,239
1,061
import click from os import path, listdir, rename, remove from datetime import datetime from sys import exit from multiprocessing import Pool from signal import signal, SIGINT from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from threading import Condition from .dropbox import...
5,910
1,763
# coding: utf-8 import os import shutil import sys import unittest from os import path as op from tempfile import gettempdir from send2trash import send2trash as s2t # import the two versions as well as the "automatic" version from send2trash.plat_win_modern import send2trash as s2t_modern from send2trash.plat_win_le...
4,703
1,697
import numpy as np import theano.tensor as T from numpy import linalg as la, random as rnd import pymanopt from pymanopt.manifolds import Oblique from pymanopt.solvers import ConjugateGradient def closest_unit_norm_column_approximation(A): """ Returns the matrix with unit-norm columns that is closests to A w...
1,133
423
# SPDX-FileCopyrightText: Copyright (c) 2021 Dylan Herrada for Adafruit Industries # # SPDX-License-Identifier: MIT """ `adafruit_dash_display` ================================================================================ CircuitPython library for creating Adafruit IO dashboards. * Author(s): Dylan Herrada Implem...
9,821
2,977
"""Unit tests for fygen module.""" import unittest import six import fygen import fygen_help from wavedef import SUPPORTED_DEVICES # pylint: disable=too-many-public-methods # pylint: disable=invalid-name # pylint: disable=too-many-lines class FakeSerial(object): """Fake serial object for when more i...
34,936
15,247
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='POC model for publication', author='Thomas Haine', license='MIT', )
212
67
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ class StatsApphook(CMSApp): name = _("Stats Apphook") def get_urls(self, page=None, language=None, **kwargs): return ["danceschool.stats.urls"] # replace th...
413
141
import logging import archinstall __version__ = 0.1 class Plugin: VARIANTS_DICT_KEY = "variants" VARIANT_KEY = "variant" def __init__(self): if self.has_variants() and self.variants_is_dict(): variant_key = self.get_selected_variant_key() variant = archinstall.arguments[...
2,577
735
from django.urls import path from declaracion.views import (BusquedaDeclarantesFormView, InfoDeclarantesFormView, InfoDeclaracionFormView, BusquedaDeclaracionesFormView, BusquedaUsuariosFormView, NuevoUsuariosFormView, EliminarUsuarioFormView,InfoUsuarioFor...
1,316
438
#! /usr/bin/env python3 import argparse import logging import scipy.io import pbio.misc.logging_utils as logging_utils import pbio.misc.math_utils as math_utils logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, ...
1,501
456
from litesockets import SocketExecuter, TcpServer import time #This starts a SocketExecuter with default of 5 threads SE = SocketExecuter() #creates a tcpServer listening on localhost port 11882 (socket is not open yet) server = TcpServer("localhost", 11882) #This is ran once the far side is connected def newConnect...
959
281
# Standard Library import pickle from typing import * from pathlib import Path # Third-party Party import numpy as np import PIL.Image as Image from colorama import Fore, init # Torch Library import torch import torch.utils.data as data import torchvision.transforms as T # My Library from helper import visualize_np...
6,679
2,203
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Contributors # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- ANSI_COLORS ...
11,221
4,822
# Copyright 2022 Huawei Technologies Co., Ltd # # 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...
20,209
6,375
import discord, youtube_dl, asyncio, json, random, os from youtube_search import YoutubeSearch from core import checks, embeds, files, database from discord.ext import tasks from difflib import SequenceMatcher commands = discord.ext.commands ytdl_format_options = { 'format': 'bestaudio/best', 'outtmpl': '...
4,863
1,510
def printVal(state, name): val = state[name] print("%s:" % state.fuzzy_names[name], val) def print_all(state): printVal(state, "var_default") printVal(state, "var_default_override") printVal(state, "var_default_override_twice") printVal(state, "var_default_override_twice_and_cli") def regis...
573
211
import itertools stevke = ['1', '3', '7', '9'] def je_prastevilo(n): if n < 2 or n % 2 == 0: return n == 2 i = 3 while i * i <= n: if n % i == 0 or n % 2 == 0: return False i += 2 return True def zasukej(nabor): stevilo = list(nabor) seznam = [] while l...
867
346
""" ~/utils/update_ontario_stocking.py Created: 23 Jan 2019 15:29:22 DESCRIPTION: This script updates the ontario data in the lake wide cwt database. Updates include tag type, and sequence number for sequential cwts, cwt manufacturer (where it should have been Micro Mark (MM)) Updates are preformed on both stocking...
6,650
2,250
from PIL import Image import numpy as np from matplotlib.path import Path import matplotlib.pyplot as plt import matplotlib.patches as patches image = Image.open('samp3.png', 'r') #read image image = image.convert('L') #convert image to greyscale data = np.asarray(image) #convert image t...
2,001
628
#!/usr/bin/env python3 import requests import json #Enter DO token DOTOKEN = "" HEADERS = {"Authorization": "Bearer " + DOTOKEN, "Content-Type": "application/json"} ################################################################################## # Droplets # ###########################...
2,425
769
import os from math import radians, sin, cos, asin, degrees, pi, sqrt, pow, fabs, atan2 from django import forms from django.db import models from django.conf import settings from modelcluster.fields import ParentalKey from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailadmin.edit_handlers impo...
24,784
8,308
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from botbuilder.core import MessageFactory, TurnContext, ActivityHandler class ActivitiyUpdateAndDeleteBot(ActivityHandler): def __init__(self, activity_ids): self.activity_ids = activity_ids async def on_m...
1,308
348
from deliravision.models.gans.deep_convolutional.dc_gan import \ DeepConvolutionalGAN
90
31
import random import sys from nobos_commons.data_structures.bounding_box import BoundingBox from nobos_commons.data_structures.bounding_box_3D import BoundingBox3D from nobos_commons.data_structures.dimension import Coord2D, Coord3D from nobos_commons.data_structures.skeletons.joint_2d import Joint2D from nobos_common...
3,526
1,472
"""Support for UK Met Office weather service.""" from homeassistant.components.weather import WeatherEntity from homeassistant.const import LENGTH_KILOMETERS, TEMP_CELSIUS from homeassistant.core import callback from homeassistant.helpers.typing import ConfigType, HomeAssistantType from .const import ( ATTRIBUTION...
4,556
1,354
# -*- coding: utf-8 -* """ some rule """ class MaxTruncation(object): """MaxTruncation:超长截断规则 """ KEEP_HEAD = 0 # 从头开始到最大长度截断 KEEP_TAIL = 1 # 从头开始到max_len-1的位置截断,末尾补上最后一个id(词或字) KEEP_BOTH_HEAD_TAIL = 2 # 保留头和尾两个位置,然后按keep_head方式截断 class EmbeddingType(object): """EmbeddingType:文本数据需要转换的emb...
5,816
3,070
import sys,argparse from cmdprogress.bar import ProgBar def parse_years(arg): years = set() for a in arg.split(','): if '-' in a: y0,y1 = map(int,a.split('-')) years |= set(range(y0,y1+1)) else: years |= {int(a)} years = list(years) years.sort() r...
8,511
2,832
#!/usr/bin/env python import os os.environ['POMAGMA_LOG_LEVEL'] = '3' from pomagma.compiler.util import temp_memoize # isort:skip from pomagma.reducer import bohm # isort:skip print('Example 1.') with temp_memoize(): bohm.sexpr_simplify('(ABS (ABS (1 0 (1 0))) (ABS (ABS (1 (0 0)))))') print('Example 2.') w...
409
191
"""Utilities for debugging memory usage, blocking calls, etc.""" import os import sys import traceback from contextlib import contextmanager from functools import partial from pprint import pprint from celery.platforms import signals from celery.utils.text import WhateverIO try: from psutil import Process except ...
4,709
1,566
#!/usr/bin/env python from browsers import browsers from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.support.wait import WebDriverWait from selenium.common.exceptions import TimeoutExc...
5,038
1,585
# Copyright (c) 2017, 2020, DCSO GmbH import json import sys import os # we change the path so that this app can run within the Splunk environment sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib")) from dcsotie.errors import TIEError from dcsotiesplunk.logger import get_logger logger = get_log...
1,845
597
#! /usr/bin/python3 import sys sys.path.append('../../') import numpy as np import numpy.fft as npfft import matplotlib.pyplot as plt from matplotlib import animation import time from netCDF4 import MFDataset from nephelae_simulation.mesonh_interface import MesoNHVariable from nephelae_base.types import Position fr...
7,388
3,121
# coding: utf-8 # Originally from # https://github.com/PPartisan/THE_LONG_DARK # Simply adapted to LINUX by Bernardo Alves Furtado import threading import time import psutil from pylab import rcParams from pynput.keyboard import Key, Controller import mapping rcParams['figure.figsize'] = 12, 9.5 def is_tld_runn...
1,432
468
import logging import os import signal import sys from pmonitor import PMonitor logging.getLogger().setLevel(logging.INFO) class MultiplyMonitor(PMonitor): def __init__(self, parameters, types): PMonitor.__init__(self, ['none', parameters['data_root']], ...
7,205
1,994
import random import cv2 padding = 20 MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746) genderList = ['Male', 'Female'] class GenderDetection(): def __init__(self): faceProto = 'data/opencv_face_detector.pbtxt' faceModel = 'data/opencv_face_detector_uint8.pb' genderProto ...
2,888
957
# import random # # deck = list() # for suit in ["♦", "♥", "♠", "♣"]: # for value in ["A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"]: # deck.append((value, suit)) # r_sample = random.sample(deck, 7) # print(r_sample) from enum import Enum, auto, unique class Suit(Enum): ...
2,223
896
# -*- coding: utf-8 -*- from networkapi import celery_app from networkapi.queue_tools.rabbitmq import QueueManager from networkapi.usuario.models import Usuario class BaseTask(celery_app.Task): def after_return(self, status, retval, task_id, args, kwargs, einfo): user = Usuario.get_by_pk(args[1]) ...
1,118
333
import datetime import unittest class KalmanFilterTest(unittest.TestCase): def test_kalman_filter_with_prior_predict(self): t0 = datetime.datetime(2014, 2, 12, 16, 18, 25, 204000) print(t0) self.assertEqual(1., 1.) def test_kalman_filter_without_prior_predict(self...
539
198
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from fclib.models.dilated_cnn import create_dcnn_model def test_create_dcnn_model(): mod0 = create_dcnn_model(seq_len=1) # default args assert mod0 is not None mod1 = create_dcnn_model( seq_len=1, n_dyn_fea=1, n_outputs=2,...
615
264
# threadpool example import sys from threading import Thread import queue import time class Worker(Thread): def __init__(self,queue): super(Worker, self).__init__() self._q = queue self.daemon = True self.start() def run(self): while True: f,args,kwargs = self._q.get() ...
1,579
532
#!/usr/bin/python import rospy from gazebo_msgs.msg import ContactsState from enhanced_sim.msg import CollisionState """ Spec: Look at all /panda/bumper* topics, get which are colliding and publish a boolean variable (per link) saying whether in collision """ class CollidingNode(object): def __init__(self, collisio...
2,102
809
""" This file is part of flatlib - (C) FlatAngle Author: João Ventura (flatangleweb@gmail.com) This module implements the Behavior Traditional Protocol. """ from flatlib import const from flatlib import aspects from flatlib.dignities import essential def _merge(listA, listB): """ Merg...
2,061
742
__version__ = "0.1.6" from .fetch_embed import fetch_embed from .embed_text import embed_text __all__ = ( "fetch_embed", "embed_text", )
147
57
#!/usr/bin/env python3 import numpy as np import numpy.random as npr import pytest A1 = npr.rand( 1, 1) B1 = npr.rand( 1, 1) C1 = npr.rand( 1, 1) A3 = npr.rand( 3, 3) B3 = npr.rand( 3, 3) C3 = npr.rand( 3, 3) A10 = npr.rand( 10, 10) B10 = npr.rand( 10, 10) C10...
4,570
2,270
import copy import numpy as np import matplotlib as mpl # mpl.use('agg') import matplotlib.pyplot as plt import matplotlib.patches as mpl_patches import matplotlib.colors as mpl_colors import matplotlib.cm as mpl_cm import matplotlib.animation as animation import matplotlib.patheffects as path_effects from mpl_toolkit...
51,242
19,231
import importlib import inspect import pprint from django.apps import apps from django.core.management import BaseCommand, call_command class Command(BaseCommand): help = 'Create initial data by using factories.' def add_arguments(self, parser): parser.add_argument( '--app-label', ...
4,174
1,113
# Copyright 2015 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 writing...
3,290
963
import numpy as np from bs4 import BeautifulSoup from tqdm import tqdm import json def read_file(filename): with open(filename, 'r', encoding='utf-8') as f: contents = f.read() soup = BeautifulSoup(contents, "html.parser") return soup if __name__ == '__main__': with open('name2idx.js...
725
240
import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from context import braingraphgeo as bgg def test_geomsurr(sample_W_1, sample_D): W = sample_W_1.values d = sample_D.values Wgeo = bgg.surrogates.geomsurr(W, d, rs=2021) result = np.array([[0., 0.00072248, 0.00...
2,658
1,661
# -*- coding: utf-8 -*- import dataiku import pandas as pd, numpy as np from dataiku import pandasutils as pdu import requests #import time from dataiku.customrecipe import * import sys import re import geocoder_utils import common import os logging.info('1/6 Creating base folder...' ) path_datadir_tmp = dataiku.get...
7,477
2,351
#!/usr/bin/python # 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, software # di...
15,008
4,502
from pytest import approx, warns, raises from pystrafe import basic def test_collide(): v = [-1000, 123, 456] basic.collide(v, [1, 0, 0]) assert v == [0, 123, 456] def test_collide_out_of_plane(): v = [100, 100, 100] with warns(RuntimeWarning): basic.collide(v, [1, 0, 0]) assert v ...
1,421
749
from firedrake import * import numpy as np from firedrake.petsc import PETSc from firedrake import COMM_WORLD try: import matplotlib.pyplot as plt plt.rcParams["contour.corner_mask"] = False plt.close("all") except: warning("Matplotlib not imported") nx, ny = 4, 4 Lx, Ly = 1.0, 1.0 quadrilateral = Fa...
6,108
2,645
"""Definition and configuration of data sets""" import functools from data_sets import data_set @functools.lru_cache(maxsize=None) def data_sets() -> ['data_set.DataSet']: """All available data sets""" return [] def charts_color() -> str: """The color (rgb hex code) to be used in charts""" return ...
329
111
class AbstractException(Exception): """Abstract exception for project""" def __init__(self, code, message): """ Constructor :param int code: error code :param str message: error message """ self._code = code self._message = message @property def...
578
153
from kafka import KafkaConsumer consumer = KafkaConsumer('test-topic', bootstrap_servers='localhost:9092') print("listening") for msg in consumer: print(msg)
163
54
import random import numpy as np import tensorflow as tf from recognition.utils import train_utils, googlenet_load try: from tensorflow.models.rnn import rnn_cell except ImportError: rnn_cell = tf.nn.rnn_cell from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops random.seed...
9,354
3,265
# AUTOGENERATED! DO NOT EDIT! File to edit: linear.ipynb (unless otherwise specified). __all__ = ['vv', 'denoising_MRF'] # Cell import numpy as np import gtsam from gtsam import noiseModel from .display import show from typing import Dict # Cell def vv(keys_vectors: Dict[int, np.ndarray]): """Create a VectorVal...
1,627
590
def solve(n, m, A, B): ans = 0 ones, twos = [], [] for i in xrange(n): if B[i] == 1: ones += A[i], else: twos += A[i], ones.sort() twos.sort() i, j = len(ones)-1, len(twos)-1 while m > 0 and (i >= 0 or j >= 0): if i >= 0 and ones[i] >= m: m -= ones[i] ...
899
354
#! /usr/bin/env python import mdscatter import numpy as np import h5py import time import os from loader import list_lammps_txt_files, load_lammps_txt from detector import Lambda750k if __name__ == '__main__': wavelen = 0.1127 energy = 1.23984 / wavelen sdd = 4. scale = 28 center = (0, 768)...
1,319
553
import os from shutil import copyfile from sphinxcontrib.collections.drivers import Driver class CopyFileDriver(Driver): def run(self): self.info('Copy file...') if not os.path.exists(self.config['source']): self.error('Source {} does not exist'.format(self.config['source'])) ...
895
245
# -*- coding: utf-8 -*- # Copyright 2020 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import ast import re from ansible.plugins.action import ActionBase from ansible.module...
6,598
1,755