text
string
size
int64
token_count
int64
import csv vat_filenames = set() train_csv_filename = 'train_annotations.csv' val_csv_filename = 'val_annotations.csv' for csv_filename in [train_csv_filename, val_csv_filename]: for line in csv.reader(open(csv_filename)): vat_filename = line[0].split('/')[-1] vat_filenames.add(vat_filename) pr...
370
133
""" This file is part of LiberaForms. # SPDX-FileCopyrightText: 2020 LiberaForms.org # SPDX-License-Identifier: AGPL-3.0-or-later """ import os, json from flask import g, request, render_template, redirect from flask import session, flash, Blueprint from flask import send_file, after_this_request from flask_babel imp...
8,908
2,687
import os, copy import cv2 from functools import partial import numpy as np import torch import torchvision from torch.utils.data import Dataset from zephyr.data_util import to_np, vectorize, img2uint8 from zephyr.utils import torch_norm_fast from zephyr.utils.mask_edge import getRendEdgeScore from zephyr...
29,405
10,024
from Roteiro7.Roteiro7__funcoes import GrafoComPesos # .:: Arquivo de Testes do Algoritmo de Dijkstra ::. # # --------------------------------------------------------------------------- # grafo_aula = GrafoComPesos( ['E', 'A', 'B', 'C', 'D'], { 'E-A': 1, 'E-C': 10, 'A-B': 2, 'B...
814
372
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright © Tom Hören # Licensed under the terms of the MIT License # ---------------------------------------------------------------------------- """ Python QtScreenCaster Spyder API. """ class ScreenResolutions...
356
103
import os, os.path import subprocess from distutils.core import setup from py2exe.build_exe import py2exe PROGRAM_NAME = 'icom_app' PROGRAM_DESC = 'simple icom app' NSIS_SCRIPT_TEMPLATE = r""" !define py2exeOutputDirectory '{output_dir}\' !define exe '{program_name}.exe' ; Uses solid LZMA compression. Ca...
4,196
1,369
import torch from farm.data_handler.samples import Sample from farm.modeling.prediction_head import RegressionHead class FeaturesEmbeddingSample(Sample): def __init__(self, id, clear_text, tokenized=None, features=None, feat_embeds=None): super().__init__(id, clear_text, tokenized, features) self....
632
193
import pytest from rest_framework import status from rest_framework.test import APIClient class TestBase: __test__ = False path = None get_data = {} put_data = {} post_data = {} delete_data = {} requires_auth = True implements_retrieve = False implements_create = False implemen...
5,057
1,596
from collections import defaultdict import discord from redbot.core import Config, checks, commands from redbot.core.bot import Red from redbot.core.utils.chat_formatting import box, humanize_list, inline from abc import ABC # ABC Mixins from dashboard.abc.abc import MixinMeta from dashboard.abc.mixin impor...
2,259
762
""" https://leetcode.com/problems/find-peak-element/submissions/ """ from typing import List class Solution: def findPeakElement(self, nums: List[int]) -> int: l, r = 0, len(nums)-1 while l < r: lmid = (l + r) // 2 rmid = lmid + 1 if nums[lmid] < nums[rmid]: ...
410
147
from torchvision.datasets import ImageFolder from torchvision import transforms import random import os import torch from torch.utils.data.dataloader import DataLoader from utils import constants, get_default_device from image_folder_with_path import ImageFolderWithPaths def to_device(data, device): """Move tensor...
2,684
841
# import matplotlib # matplotlib.use('Qt5Agg') # Prevents `Invalid DISPLAY variable` errors import pytest import tempfile from calliope import Model from calliope.utils import AttrDict from calliope import analysis from . import common from .common import assert_almost_equal, solver, solver_io import matplotlib.p...
4,254
1,282
import os from mol.util import read_xyz dirname = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(dirname, 'look_and_say.dat') with open(filename, 'r') as handle: look_and_say = handle.read() def get_molecule(filename): return read_xyz(os.path.join(dirname, filename + ".xyz"))
302
111
# 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 # d...
13,198
4,821
""" This is algos.euler.transformer module. This module is responsible for transforming raw candle data into training samples usable to the Euler algorithm. """ import datetime import decimal from algos.euler.models import training_samples as ts from core.models import instruments from datasource.models import...
4,204
1,276
from diagrams import Node class _Outscale(Node): _provider = "outscale" _icon_dir = "resources/outscale" fontcolor = "#ffffff"
142
49
__doc__ = \ """ ======================================================================================= Main-driver :obj:`LogStream` variables (:mod:`mango.application.main_driver.logstream`) ======================================================================================= .. currentmodule:: mango.application.ma...
1,793
611
# -*- coding: utf-8-unix -*- import platform ###################################################################### # Platform specific headers ###################################################################### if platform.system() == 'Linux': src = """ typedef bool BOOL; """ #############################...
9,680
4,435
from overrides import overrides from ..masked_layer import MaskedLayer class OutputMask(MaskedLayer): """ This Layer is purely for debugging. You can wrap this on a layer's output to get the mask output by that layer as a model output, for easier visualization of what the model is actually doing. ...
565
162
""" energy.py function that computes the inter particle energy It uses truncated 12-6 Lennard Jones potential All the variables are in reduced units. """ def distance(atom1, atom2): """ Computes the square of inter particle distance Minimum image convention is applied for distance calculatio...
1,316
478
import numpy as np import math from scipy.optimize import curve_fit def calc_lorentzian(CestCurveS, x_calcentires, mask, config): (rows, colums, z_slices, entires) = CestCurveS.shape lorenzian = {key: np.zeros((rows, colums, z_slices), dtype=float) for key in config.lorenzian_keys} for k in range(z_slice...
2,628
973
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ############################################################# # File: network_models_LSTU.py # Created Date: Tuesday February 25th 2020 # Author: Chen Xuanhong # Email: chenxuanhongzju@outlook.com # Last Modified: Tuesday, 25th February 2020 9:57:06 pm # Modified By: Chen ...
7,572
2,830
from unittest import TestCase from expects import expect, equal, raise_error from slender import List class TestKeepIf(TestCase): def test_keep_if_if_func_is_none(self): e = List([1, 2, 3, 4, 5]) expect(e.keep_if(None).to_list()).to(equal([1, 2, 3, 4, 5])) def test_keep_if_if_func_is_valid...
760
324
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Cash Node developers # Author matricz # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test that inv messages are sent according to an exponential distribution with scale -...
6,809
2,001
import backend as F import numpy as np import scipy as sp import dgl from dgl import utils import unittest from numpy.testing import assert_array_equal np.random.seed(42) def generate_rand_graph(n): arr = (sp.sparse.random(n, n, density=0.1, format='coo') != 0).astype(np.int64) return dgl.DGLGraph(arr, readon...
33,871
11,389
# Copyright Amazon.com, Inc. or its affiliates. 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 # # Unl...
3,178
1,000
#! /usr/bin/env 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...
4,316
1,345
import sys f = open("/home/vader/Desktop/test.py", "r") #read all file python_script = f.read() print(python_script)
126
48
import smtplib import argparse from os.path import basename from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate import configparser import json def send_mail(send_from, send_to, subject, te...
2,001
621
import logging TRACE_LVL = int( (logging.DEBUG + logging.INFO) / 2 )
70
28
from dagster import repository from simple_lakehouse.pipelines import simple_lakehouse_pipeline @repository def simple_lakehouse(): return [simple_lakehouse_pipeline]
173
52
#Copyright ReportLab Europe Ltd. 2000-2017 #see license.txt for license details __version__='3.3.0' __doc__='' #REPORTLAB_TEST_SCRIPT import sys, copy, os from reportlab.platypus import * _NEW_PARA=os.environ.get('NEW_PARA','0')[0] in ('y','Y','1') _REDCAP=int(os.environ.get('REDCAP','0')) _CALLBACK=os.environ.get('CA...
7,649
2,861
""" econ/fred_view.py tests """ import unittest from unittest import mock from io import StringIO import pandas as pd # pylint: disable=unused-import from gamestonk_terminal.econ.fred_view import get_fred_data # noqa: F401 fred_data_mock = """ ,GDP 2019-01-01,21115.309 2019-04-01,21329.877 2019-07-01,21540.325 2019-...
764
393
# Copyright (c) 2009-2010 Denis Bilenko. See LICENSE for details. """Managing greenlets in a group. The :class:`Group` class in this module abstracts a group of running greenlets. When a greenlet dies, it's automatically removed from the group. The :class:`Pool` which a subclass of :class:`Group` provides a way to li...
10,938
3,157
import time import logging from typing import Dict, Any, Tuple import pickle import numpy as np import xgboost as xgb from .common import load_lw_dataset, encode_query, decode_label from ..postgres import Postgres from ..estimator import Estimator from ..utils import evaluate, run_test from ...dataset.dataset import ...
4,974
1,729
import os import configparser from warnings import warn def read_control_file(control_file): # Initialize ConfigParser object config = configparser.ConfigParser( strict=True, comment_prefixes=('/*', ';', '#'), inline_comment_prefixes=('/*', ';', '#') ) # Parse control file ...
2,525
804
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2017 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import numpy as np import pytest from pymor.core.pickle import dumps, loads from pymor.functions....
2,950
1,009
''' step 1 get the userID and their locations put them all into a database ''' from bs4 import BeautifulSoup import urllib import sqlite3 from selenium import webdriver import time import re from urllib import request import random import pickle import os import pytesseract url_dog = "http...
4,603
1,516
from .structure import Structure
33
8
import unittest import numpy as np from tbase.common.cmd_util import set_global_seeds from tbase.network.polices import RandomPolicy class TestPolices(unittest.TestCase): @classmethod def setUpClass(self): set_global_seeds(0) def test_random_policy(self): policy = RandomPolicy(2) ...
709
253
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
36,887
11,285
from .group import Group from .node import (Node, parse_xml_properties, ATTR_ID) from time import sleep from xml.dom import minidom class Nodes(object): """ This class handles the ISY nodes. This class can be used as a dictionary to navigate through the controller's structure to objects of type :cla...
17,327
4,694
# SPDX-FileCopyrightText: 2021 easyCore contributors <core@easyscience.software> # SPDX-License-Identifier: BSD-3-Clause # © 2021 Contributors to the easyCore project <https://github.com/easyScience/easyCore> __author__ = 'github.com/wardsimon' __version__ = '0.1.0' import logging class Logger: def __init__...
1,329
400
"""Module for IQ option billing resource.""" from iqoptionapi.http.resource import Resource class Billing(Resource): """Class for IQ option billing resource.""" # pylint: disable=too-few-public-methods url = "billing"
234
75
# -*- coding: utf-8 -*- def ordered_set(iter): """Creates an ordered set @param iter: list or tuple @return: list with unique values """ final = [] for i in iter: if i not in final: final.append(i) return final def class_slots(ob): """Get object attributes from...
3,416
993
import asyncio from collections import defaultdict from datetime import timedelta import pytest from yui.api import SlackAPI from yui.bot import Bot from yui.box import Box from yui.types.slack.response import APIResponse from yui.utils import json from .util import FakeImportLib def test_bot_init(event_loop, monk...
3,140
1,069
#!/usr/bin/env python import numpy as np import rospy import geometry_msgs.msg import tf2_ros from tf.transformations import quaternion_slerp def translation_to_numpy(t): return np.array([t.x, t.y, t.z]) def quaternion_to_numpy(q): return np.array([q.x, q.y, q.z, q.w]) if __name__ == '__main__': rosp...
2,901
911
import os import subprocess from pathlib import Path from torch.hub import load_state_dict_from_url import numpy as np model_urls = { # ResNet 'resnet18': 'https://download.pytorch.org/models/resnet18-f37072fd.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-b627a593.pth', 'resnet50':...
3,713
1,634
import requests from bs4 import BeautifulSoup def recursiveUrl(url, link, depth): if depth == 5: return url else: print(link['href']) page = requests.get(url + link['href']) soup = BeautifulSoup(page.text, 'html.parser') newlink = soup.find('a') if len(newlink) =...
702
226
"""Tests for SEIR model in this repo * Compares conserved quantities * Compares model against SEIR wo social policies in limit to SIR """ from pandas import Series from pandas.testing import assert_frame_equal, assert_series_equal from bayes_chime.normal.models import SEIRModel, SIRModel from pytest import fixture fro...
2,428
945
import numpy as np from scipy.interpolate import interp1d from pyTools import * ################################################################################ #~~~~~~~~~Log ops ################################################################################ def logPolyVal(p,x): ord = p.order() logs = [] ...
4,681
1,892
from setuptools import setup setup( name="ambient_api", version="1.5.6", packages=["ambient_api"], url="https://github.com/avryhof/ambient_api", license="MIT", author="Amos Vryhof", author_email="amos@vryhofresearch.com", description="A Python class for accessing the Ambient Weather API...
592
189
#!/usr/bin/env python import subprocess import os def setup_module(module): THIS_DIR = os.path.dirname(os.path.abspath(__file__)) os.chdir(THIS_DIR) def teardown_module(module): cmd = ["make clean"] cmdOutput = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) def test_1(): cmd...
585
206
class RegipyException(Exception): """ This is the parent exception for all regipy exceptions """ pass class RegipyGeneralException(RegipyException): """ General exception """ pass class RegistryValueNotFoundException(RegipyException): pass class NoRegistrySubkeysException(Regipy...
877
252
from collections import deque class Solution: """ @param n: a positive integer @return: the minimum number of replacements """ def integerReplacement(self, n): # Write your code here steps = 0 if n == 1: return steps queue = deque([n]) while q...
745
203
from flask import Blueprint, render_template from gateways.models import getWeatherData web = Blueprint("web", __name__, template_folder='templates') @web.route("/", methods=['GET']) def home(): items = getWeatherData.get_last_item() cityName = items["city"] return render_template("index.html", ...
947
255
from __future__ import absolute_import from changes.buildsteps.default import DefaultBuildStep class LXCBuildStep(DefaultBuildStep): """ Similar to the default build step, except that it runs the client using the LXC adapter. """ def can_snapshot(self): return True def get_label(self...
677
201
#!/usr/bin/env python3 """Star Wars API HTTP response parsing""" # requests is used to send HTTP requests (get it?) import requests URL= "https://swapi.dev/api/people/1" def main(): """sending GET request, checking response""" # SWAPI response is stored in "resp" object resp= requests.get(URL) # wh...
532
169
import json schema = { "Spartina": { "ColStart": "2000-04-01", "ColEnd": "2000-05-31", "random": 7, "mud_colonization": [0.0, 0.0], "fl_dr": 0.005, "Maximum age": 20, "Number LifeStages": 2, "initial root length": 0.05, "initial shoot length":...
4,132
1,814
def _replace_formatted(ctx, manifest, files): out = ctx.actions.declare_file(ctx.label.name) # this makes it easier to add variables file_lines = [ """#!/bin/bash -e WORKSPACE_ROOT="${1:-$BUILD_WORKSPACE_DIRECTORY}" """, """RUNPATH="${TEST_SRCDIR-$0.runfiles}"/""" + ctx.workspace_name, ...
2,316
740
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import AbstractUser, UserManager from django.db import models from django.utils import timezone # Create your models here. # Create our new user class class AccountUserManager(UserManager): def _create_user(self, usern...
1,376
374
""" If you find this code useful, please cite our paper: Mahmoud Afifi, Marcus A. Brubaker, and Michael S. Brown. "HistoGAN: Controlling Colors of GAN-Generated and Real Images via Color Histograms." In CVPR, 2021. @inproceedings{afifi2021histogan, title={Histo{GAN}: Controlling Colors of {GAN}-Generated and R...
11,973
4,161
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-05 18:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("careeropportunity", "0002_careeropportunity_job_type")] operations = [ migrations.AddFie...
501
174
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
14,482
5,945
#!/usr/bin/env python3 import json import argparse import re import datetime import paramiko import requests # cmd ['ssh', 'smart', # 'mkdir -p /home/levabd/smart-home-temp-humidity-monitor; # cat - > /home/levabd/smart-home-temp-humidity-monitor/lr.json'] from miio import chuangmi_plug from btlewrap import availabl...
11,038
4,125
import pickle from sklearn.neural_network import MLPClassifier train = pickle.load(open('train_pca_reservoir_output_200samples.pickle','rb')) test = pickle.load(open('test_pca_reservoir_output_50samples.pickle','rb')) train_num = 200 test_num = 50 mlp = MLPClassifier(hidden_layer_sizes=(2000,), max_iter=100, alpha=1...
642
263
import numpy as np import pandas as pd from skimage import io import skimage.measure as measure import os from lpg_pca_impl import denoise def getNoisedImage(originalImage, variance): # return random_noise(originalImage, mode='gaussian', var=variance) np.random.seed(42) noise = np.random.normal(size=origi...
4,099
1,570
import redis from rq import Queue, Connection from flask import Flask, render_template, Blueprint, jsonify, request import tasks import rq_dashboard from wingnut import Wingnut app = Flask( __name__, template_folder="./templates", static_folder="./static", ) app.config.from_object(rq_dashb...
3,178
1,067
from pytaboola.client import TaboolaClient
42
14
# -------------- # Importing header files import numpy as np import warnings warnings.filterwarnings('ignore') new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #New record #Reading file data = np.genfromtxt(path, delimiter=",", skip_header=1) data.shape cenus=np.concatenate((new_record,data),axis=0) cenus....
1,410
672
#! /usr/bin/env python # # Presents the results of an Autobahn TestSuite run in TAP format. # # Copyright 2015 Jacob Champion # # 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://ww...
3,887
1,184
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scls', '0003_other_repos'), ] operations = [ migrations.AlterField( model_name='otherrepo', name='ar...
1,143
337
import openpyxl wb = openpyxl.load_workbook('example.xlsx') sheet = wb.get_sheet_by_name('Sheet1') rows = sheet.get_highest_row() cols = sheet.get_highest_column() for i in range(1, rows + 1): for j in range(1, cols + 1): print('%s: %s' % (sheet.cell(row=i, column=j).coordinate, sheet.cell(row=i, column=j)....
389
154
# Generated by Django 3.1.13 on 2021-10-04 11:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("iaso", "0107_auto_20211001_1845"), ("polio", "0028_remove_campaign_budget_first_draft_submitted_at"), ] op...
787
255
#import external libraries used in code import requests, json import pycountry print('Currency Exchange') currencies = [] def findCurrency(): #Finds all avaliable currencies allCurrency = (list(pycountry.currencies)) for x in allCurrency: y = str(x) y = y[18:21] #Adds th...
6,257
1,889
r, c, m = map(int, input().split()) n = int(input()) op = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] board = [[0 for _ in range(c)] for _ in range(r)] for ra, rb, ca, cb in op: for j in range(ra, rb + 1): for k in range(ca, cb + 1): board[j][k] += 1 cnt = 0 for i in ra...
715
301
# Copyright (C) 2018 Alexandre Morlet, Henrique Pereira Coutada Miranda # All rights reserved. # # This file is part of yambopy # from __future__ import print_function from builtins import range from yambopy import * from qepy import * import json import matplotlib.pyplot as plt import numpy as np import sys import arg...
6,142
2,003
from module import XMPPModule import halutils import pyfatafl class Game(): self.players = [] self.xmpp = None self.b = None self.turn = "" self.mod = None def __init__(self, mod, p1, p2): self.players = [p1, p2] self.mod = mod self.xmpp = mod.xmpp self.xmpp.sendMsg(p2, "You have been challenged to play...
3,080
1,268
from typing import cast, Optional from datetime import datetime, tzinfo, timedelta from zonedbpy import zone_infos from zone_processor.zone_specifier import ZoneSpecifier from zone_processor.inline_zone_info import ZoneInfo __version__ = '1.1' class acetz(tzinfo): """An implementation of datetime.tzinfo using th...
2,218
742
from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 554539540 """ """ random actions, total chaos """ board = gamma_new(6, 8, 3, 17) assert board i...
8,510
4,675
# coding=utf-8 # Copyright 2019 The HuggingFace Inc. team. # Copyright (c) 2019 The HuggingFace 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.a...
25,928
8,178
from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils import LayerMapping from django.core.management.base import BaseCommand from envergo.geodata.models import Zone class Command(BaseCommand): help = "Importe des zones à partir de shapefiles." def add_arguments(self, parser): ...
676
208
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * # Anonymous Expansion {{{# class _AnonBase(_VimTest): args = '' def _extra_options_pre_init(self, vim_config): vim_config.append('inoremap <silent> %s <C-R>=UltiSnips#Anon(%s)<cr>' % (EA, se...
1,710
682
import discord from jshbot import utilities, data, configurations, plugins, logger from jshbot.exceptions import BotException, ConfiguredBotException from jshbot.commands import ( Command, SubCommand, Shortcut, ArgTypes, Attachment, Arg, Opt, MessageTypes, Response) __version__ = '0.1.0' CBException = ConfiguredB...
2,914
893
from tkinter import * from PIL import Image, ImageTk #python image library #imagetk supports jpg image a1 = Tk() a1.geometry("455x244") #for png image #photo = PhotoImage(file="filename.png") #a2 = Label(image = photo) #a2.pack() image = Image.open("PJXlVd.jpg") photo = ImageTk.PhotoImage(image) ...
374
162
import os import torch from PIL import Image from read_csv import csv_to_label_and_bbx import numpy as np from torch.utils.data import Subset, random_split, ConcatDataset class NBIDataset(object): def __init__(self, root, transforms, nob3=False): self.root = root self.transforms = transforms ...
8,113
2,862
# coding: utf-8 import functools def memoize(fn): known = dict() @functools.wraps(fn) def memoizer(*args): if args not in known: known[args] = fn(*args) return known[args] return memoizer @memoize def nsum(n): '''返回前n个数字的和''' assert(n >= 0), 'n must be >= 0' ...
1,056
408
from .transforms import *
27
10
# !\usr\bin\python import numpy as np from mpl_toolkits import mplot3d import matplotlib.pyplot as plt import scipy.optimize from matplotlib import animation from scipy.integrate import ode import pdb # Material parameters rho = 7800. E = 2.e11 nu = 0.3 mu = 0.5*E/(1.+nu) kappa = E/(3.*(1.-2.*nu)) lamb = kappa-2.*mu/3...
14,894
7,763
# _*_ coding: utf-8 _*_ #@Time : 2020/7/29 上午 09:49 #@Author : cherish_peng #@Email : 1058386071@qq.com #@File : connectionstate.py #@Software : PyCharm from enum import Enum class ConnectionState(Enum): ''' ConnectionState enum ''' DisConnected = 0 Connecting=1 Connected=2 ...
343
148
# -*- coding: utf-8 -*- import time from datetime import datetime import warnings from textwrap import dedent, fill import numpy as np import pandas as pd from numpy.linalg import norm, inv from scipy.linalg import solve as spsolve, LinAlgError from scipy.integrate import trapz from scipy import stats from lifelines....
84,787
26,079
""" Test configuration loading @author aevans """ import os from nlp_server.config import load_config def test_load_config(): """ Test loading a configuration """ current_dir = os.path.curdir test_path = os.path.sep.join([current_dir, 'data', 'test_config.json']) cfg = load_config.load_conf...
393
133
import os, json, inspect import mimetypes from html2text import html2text from RestrictedPython import compile_restricted, safe_globals import RestrictedPython.Guards import frappe import frappe.utils import frappe.utils.data from frappe.website.utils import (get_shade, get_toc, get_next_link) from frappe.modules impo...
4,469
1,753
"""Drop-in replacement for collections.OrderedDict by Raymond Hettinger http://code.activestate.com/recipes/576693/ """ try: all except NameError: def all(seq): for elem in seq: if not elem: return False return True class OrderedDict(dict, DictMixin): def __init__(self, *args, **kwds): if len(args) > 1:...
2,461
1,012
from HardBlock import * class Water(HardBlock): def __init__(self, pos=[0,0], blockSize = 25): image = "Block/Block Images/water.png" HardBlock.__init__(self, image, pos, blockSize) def update(*args): pass
286
90
import dill import haiku as hk import jax from jax.experimental import optix import jax.numpy as jnp from dataset import load_data MINERL_ENV = 'MineRLTreechopVectorObf-v0' PARAMS_FILENAME = 'bc_params_treechop.pkl' class PovStack(hk.Module): """ PovStack is a module for processing the point-of-view image data...
4,136
1,421
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
3,236
1,382
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of th...
10,418
4,574
import matplotlib.pyplot as plt, numpy as np, pandas as pd,os from ..model import recall_powerlaw_fits_to_full_models from .. import compute_power_rmse from .bluf import * from ..measure.powerlaw import * from .gener_q_vs_w_for_result_folder import * def q_vs_w_plotter_function_from_df(ax,df): # npartitions=os.cp...
6,939
2,874
import sys import math import numpy as np from datetime import datetime import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class DecAtt(nn.Module): def __init__(self, num_units, num_classes, embedding_size, dropout, device=0, training=True, p...
7,917
2,687