text
string
size
int64
token_count
int64
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import torch import numpy as np import cv2 import pdb def sigmoid(x): return 1 / (1 + math.exp(-x)) def norm_angle(angle): norm_angle = sigmoid(10 * (abs(angle) / 0.7853975 - 1)) return norm_angle ...
8,738
3,175
"""Serves the single page app web ui.""" import json import tornado.gen from ndscheduler import settings from ndscheduler import utils from ndscheduler.server.handlers import base class Handler(base.BaseHandler): """Index page request handler.""" @tornado.gen.coroutine def get(self): """Serve u...
505
161
#!/usr/bin/env python # Created: Wed Jun 21 13:46:35 2000 # Last changed: Time-stamp: <00/12/02 14:18:23 thomas> # Thomas.Sicheritz@molbio.uu.se, http://evolution.bmc.uu.se/~thomas # File: xbb_io.py import os, sys # os.system, sys.argv sys.path.insert(0, '.') sys.path.insert(0, os.path.expanduser('~thomas/cbs/python/...
801
302
# Convert a Number to a String! # We need a function that can transform a number into a string. # What ways of achieving this do you know? def number_to_string(num: int) -> str: str_num = str(num) return str_num print(number_to_string(123)) print(type(number_to_string(123)))
288
100
import spacy from spacy.scorer import PRFScore import typer from pathlib import Path from wasabi import Printer, table import operator import benepar import clausecat_component import clausecat_model import clausecat_reader import clause_segmentation import clause_aggregation msg = Printer() def main(model_path: Pa...
2,693
825
import pathlib print(pathlib.Path(__file__).parent.resolve()) while True: next_cmd = input("> ") print(eval(next_cmd))
130
47
import logging import os import aiohttp.web from connexion import AioHttpApp from nlp_annotator_api.config.config import conf from nlp_annotator_api.config.logging import setup_logging from nlp_annotator_api.server.middleware.statsd_middleware import StatsdMiddleware from nlp_annotator_api.server.signals.statsd_clien...
934
336
import tensorflow as tf from tensorflow import keras from tensorflow.keras import backend as K from keras_cv_attention_models.aotnet import AotNet from keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.attention_layers import batchnorm_with_activation, conv2d_no_bias...
4,534
1,805
"""replace FileRequest with FileGeneration Revision ID: 8692ab1298e1 Revises: 4bbc47f2b48d Create Date: 2018-10-24 14:54:39.278159 """ # revision identifiers, used by Alembic. revision = '8692ab1298e1' down_revision = '4bbc47f2b48d' branch_labels = None depends_on = None from alembic import op import sqlalchemy as ...
3,518
1,278
import numpy as np import random import sys chainlength = int(sys.argv[1]) dfname = sys.argv[2] outfl = 'result.data' cluster_size = int(sys.argv[3]) def readsize(dfname): with open(dfname, 'r') as df: lines = df.readlines() for line in lines: content = line.split() if content and cont...
10,652
3,487
import numpy as np import quaternion sample_points = np.array([[-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,...
20,537
17,308
from django.test import TestCase from django.utils import timezone from accounts.models import CustomUser, CustomUserManager class UserCreateTestCase(TestCase): def test_create_user_correctly(self): "Creating users correctly" new_user = CustomUser.objects.create( email="participant@gm...
740
213
import os from typing import List import numpy as np from torchvision import datasets as torchdata from continuum.datasets import ImageFolderDataset from continuum import download from continuum.tasks import TaskType class DTD(ImageFolderDataset): """Describable Textures Dataset (DTD) Reference: * ...
2,284
748
from board import Direction # Tuples of input, action, expected output. moving_tests = [ ( [[0,0,0,0], [4,0,0,0], [0,0,0,0], [4,0,2,0]], Direction.UP, [[8,0,2,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]] ), ( [[0,0,0,0], ...
1,732
872
import pytest from pji.utils import ValueProxy @pytest.mark.unittest class TestUtilsValue: def test_value_proxy_init(self): value = ValueProxy() assert value.value is None value = ValueProxy(233) assert value.value == 233 def test_value_proxy_set(self): value = Value...
449
145
#Intro Page from tkinter import * from PIL import Image, ImageTk import cv2 #----------------------------Start Function--------------------------# def start(event): label1.destroy() import log win.destroy() log.main() #------------------------Main Window---------------------------------#li def main_...
1,727
518
""" This module provides helper functions to support exercises during AM1 with outliers, robust regression and template regression in the CORE data analytics workshop series, week 4. """ import numpy as np import pandas as pd import math from collections import namedtuple def recovery_sulphur_dataframe_wit...
16,740
5,280
from radixlib.actions import CreateTokenDefinition from typing import Dict, Any import unittest class TestMutableTokenAction(unittest.TestCase): """ Unit tests for the CreateTokenDefinition action of mutable tokens """ ActionDict: Dict[str, Any] = { "token_properties": { "name": "MutableTe...
2,671
773
floatVar = 1.0 listVar = [3, "hello"] dictVar = { "myField": "value" } aotVar = [dictVar, dictVar] intVar = 1
113
52
"""Recipes for xTB"""
22
11
# coding=utf-8 # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os from pants.backend.native.config.environment import Assembler, CCompiler, CppC...
6,869
2,245
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions a...
11,998
5,398
#!/usr/bin/env python from setuptools import setup, find_packages import os requires = [ ] setup( name='details', version=open(os.path.join('details', '_version')).read(), description='Tools for processing AWS detailed billing reports', long_description=open('README.md').read(), author='Mitch G...
1,127
337
''' Script to check the correctness of the analysis. The analysis is done on raw data and all results are compared to a recorded analysis. ''' import os import unittest import numpy as np from beam_telescope_analysis import track_analysis from beam_telescope_analysis.tools import test_tools class TestTrackAnalysis...
4,686
2,367
# Licensed under a 3-clause BSD style license - see LICENSE.rst import glob import os import sys import json from os.path import join, isfile import pytest from asv import util from . import tools def test_run_publish(capfd, basic_conf_2): tmpdir, local, conf, machine_file = basic_conf_2 tmpdir = util.lon...
3,723
1,190
# @author Metro # @time 2021/11/24 import os.path import gym from agents.pdqn import P_DQN from utilities.memory import ReplayBuffer from utilities.utilities import * from utilities.route_generator import generate_routefile class Train_and_Evaluate(object): def __init__(self, config): # Environment ...
5,750
1,759
import sys import pprint import json import datetime import uuid import urllib import types import traceback from django.core.urlresolvers import reverse, resolve from django.http import HttpResponseRedirect, Http404, HttpResponseServerError, HttpResponseNotFound from django.conf import settings from django.contrib.aut...
10,434
3,158
# -*- coding: utf-8 -*- import logging import utool as ut import six from . import draw_func2 as df2 from wbia.plottool import plot_helpers as ph from wbia.plottool import interact_helpers as ih from wbia.plottool.viz_featrow import draw_feat_row from wbia.plottool.viz_keypoints import show_keypoints from wbia.plottool...
8,301
2,878
from .database import StDatabase from .telegram import StTelegram from .tinydb import TinyDataBase, TinySelect from .utility import StDispatch
143
40
from algorithms.maths.gcd import gcd from typing import List def solve_chinese_remainder(num : List[int], rem : List[int]): """ Computes the smallest x that satisfies the chinese remainder theorem for a system of equations. The system of equations has the form: x % num[0] = rem[0] x % num[1] = ...
1,468
453
import spacy nlp = spacy.load("ja_core_news_sm") text = ( "チックフィレイはジョージア州カレッジパークに本社を置く、" "チキンサンドを専門とするアメリカのファストフードレストランチェーンです。" ) # トークナイズのみ行う doc = nlp(text) print([token.text for token in doc])
206
136
# -*- coding: utf-8 -*- """ ##图像相关函数 @author: lywen """ import sys import six import os import base64 import requests import numpy as np import cv2 from PIL import Image import traceback import uuid from glob import glob from bs4 import BeautifulSoup def sort_box_(box): x1,y1,x2,y2,x3,y3,x4,y4 = box[:8] pts =...
19,086
8,868
# -*- coding: UTF-8 -*- import sys, time class ShowProcess(): """ 显示处理进度的类 调用该类相关函数即可实现处理进度的显示 """ i = 0 # 当前的处理进度 max_steps = 0 # 总共需要处理的次数 max_arrow = 50 #进度条的长度 infoDone = 'done' # 初始化函数,需要知道总共的处理次数 def __init__(self, max_steps, infoDone = 'Done'): self.max_steps = ...
1,320
601
''' You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to bu...
1,748
517
import numpy as np from fixtrack.frontend.pickable_base import PickableBase from vispy import scene class PickableMarkers(PickableBase): """ Markers that can highlight on hover and be selected """ class State(PickableBase.State): def __init__(self, **kwargs): super(PickableMarker...
3,733
1,206
""" Example of subscribing to a D-Bus signal using blocking I/O. This subscribes to the signal for a desktop notification being closed. To try it, start this script, then trigger a desktop notification, and close it somehow to trigger the signal. Use Ctrl-C to stop the script. This example relies on the ``org.freedes...
2,242
654
from shholiday import holiday2020 as hd daytuple = (1,1) nowholiday = hd.holiday2020() print(nowholiday.is_holiday(daytuple))
126
55
from distutils.core import setup DISTNAME='pandas_composition' FULLVERSION='0.1' ...
740
103
# Generated by Django 2.1.7 on 2019-02-27 14:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0004_longer_password'), ] operations = [ migrations.AlterField( model_name='session', name='title', ...
404
139
from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='xiandb', version='0.2.0', description='A database model for Xian', long_d...
917
311
from functools import partial import tensorflow as tf _EPSILON = tf.keras.backend.epsilon() def register_keras_custom_object(cls): tf.keras.utils.get_custom_objects()[cls.__name__] = cls return cls def binary_focal_loss(y_true, y_pred, gamma, *, pos_weight=None, from_logits=False, label_smoothing=None): ...
4,993
1,600
import time from collections import OrderedDict from datetime import datetime, timedelta from django.db import models from django.conf import settings from django.utils.timezone import utc from .skills import Skill, SkillGroup from metrics.models import Corporation from tasks.models import EveApiCache, Task from evet...
13,808
3,804
# -*- coding: utf-8 -*- from {{cookiecutter.skill_name}}.root import app __all__ = ['app']
92
38
from django.urls import path from backend.api.v1.dialogs.views import ( DialogListCreateView, DialogRetrieveUpdateDestroyAPIView, DialogMembershipListCreateView, DialogMessageListCreateView, DialogMessageRetrieveUpdateDestroyAPIView, ) urlpatterns = [ path('', DialogListCreateView.as_view()), ...
602
187
# coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from bioblend import galaxy from biomaj2galaxy import config, pass_context from biomaj2galaxy.io import info, warn import click CONFIG_TEMPLATE = """## BioMAJ2Galaxy: Global Confi...
2,100
630
from ..datamart import * def test_create_dimension(): dimension = Dimension("test_dimension") assert dimension.is_degenerate == False def test_create_dimension_insert_2_identical_lines(): ''' with 2 identical lines, only one gets stored ''' dimension = Dimension("test_dimension") dimension.add...
848
255
# # msmarco doc: create the train.tsv triples # ------------------------------- import random random.seed(42) import argparse import os import sys from tqdm import tqdm sys.path.append(os.getcwd()) from matchmaker.evaluation.msmarco_eval import * from collections import defaultdict from matchmaker.dataloaders.blin...
4,700
1,548
from core.response import Response from communities.tests import TestCase class ReplyPermissionTest(TestCase): def setUp(self): self.create_user(is_staff=True) def test_permission_reply_all(self): self.create_forum() self.create_thread() thread_id = self.thread.id res...
13,748
4,166
# Author: Angela Chapman # Date: 8/6/2014 # # This file contains code to accompany the Kaggle tutorial # "Deep learning goes to the movies". The code in this file # is for Parts 2 and 3 of the tutorial, which cover how to # train a model using Word2Vec. # # *************************************** # # ****** Re...
6,711
2,027
from .core import FullTimePositions
36
10
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1,207
317
# Python3 program to print # given matrix in spiral form def spiralPrint(m, n, a): start_row_index = 0 start_col_index = 0 l = 0 ''' start_row_index - starting row index m - ending row index start_col_index - starting column index n - ending column index i - iterator ''' while (start...
1,332
493
""" Authorization Utilities """ from shared.models.user_entities import User from shared.service.jwt_auth_wrapper import JWTAuthManager manager = JWTAuthManager(oidc_vault_secret="oidc/rest", object_creator=lambda claims, assumed_role, user_roles: User( first_name=...
568
154
import matplotlib.pyplot as plt import numpy as np from photonpy.cpp.context import Context import photonpy.cpp.gaussian as gaussian from photonpy.smlm.util import imshow_hstack from photonpy.cpp.estimator import Estimator def CheckDeriv(psf:Estimator, theta): nderiv,ev=psf.NumDeriv(theta,eps=1e-6) deriv,ev=p...
1,365
548
# -*- coding: utf-8 """Module for testing helper functions. This file is part of project TESPy (github.com/oemof/tespy). It's copyrighted by the contributors recorded in the version control history of the file, available from its original location tests/tools_tests/helpers_tests.py SPDX-License-Identifier: MIT """ ...
2,018
666
import formencode import pylons from pylons import app_globals as g class OutputSchema(formencode.Schema): allow_extra_fields = False enabled = formencode.validators.Int() class ConfigForm(formencode.Schema): allow_extra_fields = True filter_extra_fields = True #pre_validators = [formencode.Nest...
4,110
1,188
""" Dynamo Utils ============ All utility functions for interactions with DynamoDB Functions - ensure_json - create_user_table - create_or_update_record - list_tables - list_records - get_record - delete_table - delete_record - check_active """ import boto3 from decimal import Deci...
8,960
2,432
from .branch import Branch
26
6
print('this is a test2 file')
30
11
""" ******************************************************************************** compas_blender.forms ******************************************************************************** .. currentmodule:: compas_blender.forms """ __all__ = []
247
47
#!/usr/bin/python3 import sys import git r = git.Repo( sys.argv[1] ) num = 0 for info in r.blame( 'HEAD', sys.argv[2] ): num += 1 commit = info[0] all_lines = info[1] print( '%s %6d:%s' % (commit, num, all_lines[0]) ) for line in all_lines[1:]: num += 1 print( '%*s %6d:%s' % (4...
340
152
# configs for the model training class model_training_configs: VALIDATION_ERRORS_DIRECTORY = 'results/validation_errors/' INFO_FREQ = 1 # configs for the model testing class model_testing_configs: RNN_FORECASTS_DIRECTORY = 'results/rnn_forecasts/' RNN_ERRORS_DIRECTORY = 'results/errors' PROCESSED_R...
544
203
# -*- coding: utf-8 -*- import unittest from uuid import uuid4 from copy import deepcopy from openprocurement.api.models import get_now from openprocurement.edge.tests.base import AuctionBaseWebTest, test_award, test_auction_data, test_document, ROUTE_PREFIX try: import openprocurement.auctions.core as auctions_co...
26,714
8,422
from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.remote.webelement import WebElement class Select(WebElement): """ Implements logic to work with Web List UI elements """ @property def is_multiple(self): value = self.get_attribute('multiple') re...
3,967
1,018
from PyQt5.QtWidgets import QDialog from PyQt5 import uic from PyQt5.Qt import Qt from PyQt5.Qt import QShortcut from PyQt5.Qt import QKeySequence from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QInputDialog from PyQt5.Qt import QDateTime from PyQt5.Qt import QStyle from PyQt5.Qt import QNetworkCook...
12,564
3,626
#!/usr/bin/env python3 import os import sys import logging import subprocess logging.basicConfig(level=logging.INFO) root_dir = 'submitted_data' submitted_file_split = set() for dir_, _, files in os.walk(root_dir): for file_name in files: rel_dir = os.path.relpath(dir_, root_dir) rel_file = os...
1,803
565
import enum class Status(enum.Enum): """Status enumeration.""" ACTIVE = 'ACTIVE' DISABLED = 'DISABLED' ARCHIVED = 'ARCHIVED' DELETED = 'DELETED' class ProgressStatus(enum.Enum): """Enumeration indicates the different stages of the progress made on an engagement, job or ...
469
198
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
5,880
2,024
import numpy as np img_dtype = np.float32 imgX, imgY, imgZ = (256, 256, 150) imgs_path_withfaces = '../dataset/withfaces' imgs_path_nofaces = '../dataset/nofaces' imgX_dwt1, imgY_dwt1, imgZ_dwt1 = (128, 128, 75) imgs_path_withfaces_dwt = './dataset/withfaces' imgs_path_nofaces_dwt = './dataset/nofaces' dwt_flag = (...
500
241
# 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...
10,288
3,221
# -*- coding: utf-8 -*- """ Created on Fri Jan 29 13:38:35 2021 GROUND INVASION! The Game @author: Ashton Hansen (ashhansen6@outlook.com) """ # Packages used: import numpy as np import pandas as pd import random as rng from termcolor import colored # Defining starting forces ## Defenders: def_force =...
14,267
4,851
from django.conf.urls import include, url from django.views.generic.base import RedirectView from pretalx.event.models.event import SLUG_CHARS from pretalx.orga.views import cards from .views import ( admin, auth, cfp, dashboard, event, mails, organiser, person, plugins, review...
24,609
6,084
''' This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de). PM4Py 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 Foundation, either version 3 of the License, or (at your option) any late...
1,925
577
from htmlman import HTMLMan from styleman import Template page=HTMLMan() page.make_responsive() page.add_title("Base Quiz") style=Template('antartica') page.add_body_class(style['page']) page.add_js("baseui.js") page.create_section('main',append=True) page['main'].add_style_class(style['main']) title=page.create_sec...
1,775
641
name = "cluster" num_cores = 1000 GENERAL_PARTITIONS = ["regular"] GPU_PARTITIONS = ["gpu"] PARTITIONS = GENERAL_PARTITIONS + GPU_PARTITIONS ACTIVE_JOB_STATES = ["RUNNING", "COMPLETING"] FINISHED_JOB_STATES = ["COMPLETED", "NODE_FAIL", "TIMEOUT", "FAILED", "CANCELLED"] JOB_STATES = ACTIVE_JOB_STATES + FINISHED_JOB_...
514
219
# This file is part of the CERN Indico plugins. # Copyright (C) 2014 - 2021 CERN # # The CERN Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; see # the LICENSE file for more details. import dateutil.parser import pytz from flask import flash, request...
7,146
1,834
from datamart.materializers.materializer_base import MaterializerBase import os import urllib.request import sys import csv import copy import json from typing import List from pprint import pprint import re import typing from pandas import DataFrame import traceback class WikidataSPOMaterializer(MaterializerBase): ...
6,808
1,876
from typing import Dict, List, Tuple import pkg_resources def load_file(filename: str, directory: str) -> List[List[str]]: """Loads a data file stored in the Axelrod library's data subdirectory, likely for parameters for a strategy.""" path = "/".join((directory, filename)) data_bytes = pkg_resources...
1,402
473
# -*- coding: utf-8 -*- from __future__ import unicode_literals # REST from rest_framework.viewsets import ViewSetMixin from rest_framework import routers, serializers, viewsets from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication from rest_framework.permissions imp...
5,248
1,477
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import atexit import logging import os import subprocess import sys from typing import List from .command import ClientException, ExitCode, State f...
2,484
687
from collections import deque, defaultdict import os import sys import logging import time import json import gym import torch.nn as nn import torch import numpy as np import matplotlib.pyplot as plt from model import RL_Policy, Semantic_Mapping from utils.storage import GlobalRolloutStorage from envs import make_vec_...
26,540
8,874
#!/usr/bin/env python # coding=utf-8 ''' Author: Shuangchi He / Yulv Email: yulvchi@qq.com Date: 2022-03-19 10:33:38 Motto: Entities should not be multiplied unnecessarily. LastEditors: Shuangchi He LastEditTime: 2022-03-23 00:52:55 FilePath: /Awesome-Ultrasound-Standard-Plane-Detection/src/ITN/srmg/core/RiemannianRigh...
6,889
2,599
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: v0449gRpc.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _message from go...
4,658
2,243
import datetime from django.core.management import call_command from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from resources_portal.management.commands.populate_dev_database import populate_dev_database from resources_portal.models import Material, Organ...
14,423
4,324
# Copyright 2019 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...
5,107
1,528
workdays = float(input()) daily_tips = float(input()) exchange_rate = float(input()) salary = workdays * daily_tips annual_income = salary * 12 + salary * 2.5 net_income = annual_income - annual_income * 25 / 100 result = net_income / 365 * exchange_rate print('%.2f' % result)
281
114
from transformer_rankers.trainers import transformer_trainer from transformer_rankers.datasets import dataset, preprocess_scisumm_ranked from transformer_rankers.eval import results_analyses_tools from transformers import BertTokenizer, BertForSequenceClassification from sacred.observers import FileStorageObserver fro...
7,483
2,200
#Q: Evaluate the sum of all the amicable numbers under 10000. #A: 31626 def divisor_sum(n): return sum([i for i in xrange (1, n//2+1) if not n%i]) def sum_amicable(start, end): sum = 0 for i in xrange(start, end): tmp = divisor_sum(i) if i == divisor_sum(tmp) and i != tmp: ...
424
174
import long_responses as long # Returns the probability of a message matching the responses that we have def messageProb(userMessage, recognizedWords, isSingleResponse=False, requiredWords=[]): messageCertainty = 0 hasRequiredWords = True # Counts how many words are present in each predefined message ...
4,033
1,243
from io import StringIO import numpy as np from h5py import File from keras.models import load_model as keras_load_model from PIL import Image, ImageOps def predict(image, model): # Create the array of the right shape to feed into the keras model # The 'length' or number of images you can put into the array ...
1,446
471
from setuptools import setup setup( name="workshop-client", install_requires=["flask==1.1.1", "requests==2.22.0"], python_requires=">=3.7", classifiers=[ "Development Status :: 1 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "P...
417
141
import json import unittest import pyfacebook.models as models class PhotoModelTest(unittest.TestCase): BASE_PATH = "testdata/facebook/models/photos/" with open(BASE_PATH + 'photo.json', 'rb') as f: PHOTO_INFO = json.loads(f.read().decode('utf-8')) def testPhoto(self): m = models.Photo....
561
225
# MIT License # # Copyright (c) 2020 Airbyte # # 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, publ...
5,837
1,521
from datetime import datetime from typing import Optional, Dict, List, Union from schema import Schema, Or from src.monitorables.nodes.node import Node from src.utils.exceptions import InvalidDictSchemaException class ChainlinkNode(Node): def __init__(self, node_name: str, node_id: str, parent_id: str) -> None:...
11,933
3,625
import pickle import numpy as np import os def _analyze_query_point_assignment( query_data_dict: dict, init_Rdata_dict: dict, init_Edata_dict: dict, num_R: int, query_point_assignment_array: np.ndarray, root: str, n_points_to_copy=50, ): """ Analyzes and visualizes qDCA results. ...
8,983
3,044
from .models import * from decorator import * from app_goods.views import getGoodsByID # 查询当前用户所有的购物车信息 def getCartByUser(user_id=None): if user_id == None: raise ParamException() return Cart.objects.filter(user_id=user_id) def getSelectedCart(user_id=None): if user_id == None: raise P...
2,905
1,069
#!/usr/bin/env python3 ############################################################################### # # Category Summaries # # ############################################################################### import datetime import io import json import logging import pprint import sys from typing import Dict, Any ...
7,704
2,426
from typing import ParamSpecArgs from flask_restful import Resource, reqparse from models.hotel import HotelModel from flask_jwt_extended import jwt_required from models.site import SiteModel from resources.filtros import * import sqlite3 path_params = reqparse.RequestParser() path_params.add_argument('cidade', type=s...
3,881
1,210
from __future__ import absolute_import, print_function, unicode_literals if __name__ == "__main__": from .cli import cli cli.wormhole() else: # raise ImportError('this module should not be imported') pass
221
66
import networkx as nx import utils.connectivity_metrics as connectivity_metric from platypus import NSGAII, EpsMOEA, NSGAIII, EpsNSGAII, Problem, Dominance, Subset, TournamentSelector, \ HypervolumeFitnessEvaluator, Archive import statistics import multiprocessing as mp G = nx.read_adjlist("input/Ventresca/Barabas...
2,413
861