text
string
size
int64
token_count
int64
''' @author: Josh Payne Description: For creating multiple overlaid charts ''' from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA import matplotlib.pyplot as plt import numpy as np ### Get values from performance.py, input here ### x = [4, 5, 8, 9, 16, 32, 64] lst = [(2.585895228...
1,600
902
"""Utilities to download and import datasets. * **Dataset loaders** can be used to load small datasets that come pre-packaged with the pulse2percept software. * **Dataset fetchers** can be used to download larger datasets from a given URL and directly import them into pulse2percept. .. autosummary:: :toct...
804
310
# # PySNMP MIB module TIMETRA-SAS-IEEE8021-PAE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-SAS-IEEE8021-PAE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:21:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
7,452
2,997
#!/usr/bin/env python """ mk_all_level1_fsf.py - make fsf files for all subjects USAGE: python mk_all_level1_fsf_bbr.py <name of dataset> <modelnum> <basedir - default is staged> <nonlinear - default=1> <smoothing - default=0> <tasknum - default to all> """ ## Copyright 2011, Russell Poldrack. All rights reserved. ...
7,093
2,491
import tweepy import csv class dealWithTwitter: def __init__(self): self.access_token = "" self.access_token_secret = "" self.consumer_key = "" self.consumer_secret = "" self.api = "" def loadTokens(self): tokens = [] with open('pwd.txt') as pwd_file: ...
2,492
791
import json import random import numpy as np import os import time import os.path import networkx as nx import users_endpoint.users import grn_endpoint.grn_info import move_endpoint.movement import reward_endpoint.rewards import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages # Global var...
22,175
7,656
# TODO: # - allow inheritance from GDScript class # - overload native method ? import pytest from godot.bindings import ResourceLoader, GDScript, PluginScript def test_native_method(node): original_name = node.get_name() try: node.set_name("foo") name = node.get_name() ass...
2,384
811
# 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...
1,880
695
"""The Worker class, which manages running policy evaluations.""" import datetime import grpc import gym import os from google.protobuf import empty_pb2 from proto.neuroevolution_pb2 import Evaluation, Individual from proto.neuroevolution_pb2_grpc import NeuroStub from worker.policy import Policy ENVIRONMENT = os.ge...
3,350
988
# -*- coding: utf-8 -*- """ Created on Sat Feb 16 17:05:36 2019 @author: Utente """ #Chapter 4 #docstring import turtle import math bob = turtle.Turtle() print(bob) def polyline(t, n, lenght, angle): #documentation string---> """Draws n line segments with the given lenght and angle...
836
300
x = 0 y = 0 aim = 0 with open('input') as f: for line in f: direction = line.split()[0] magnitude = int(line.split()[1]) if direction == 'forward': x += magnitude y += aim * magnitude elif direction == 'down': aim += magnitude elif directio...
378
112
from . import type_checker from .dtodescriptor import DTODescriptor class DTOMeta(type): def __init__(cls, name, bases, namespace, partial: bool = False): super().__init__(name, bases, namespace) def __new__(cls, name, bases, class_dict, partial: bool = False): descriptors = {k: v for k, v i...
2,329
633
#!/usr/bin/python3 import json import pprint import sys import os import numpy as np import traceback import random import argparse import json import tensorflow import keras from keras import optimizers from keras.models import Sequential from keras.models import load_model from keras.layers import Conv2D, MaxPooling...
10,158
3,681
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014 Thoughtworks. # # 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 # #...
43,498
12,497
from dataclasses import dataclass, field from typing import List from xml.etree.ElementTree import QName __NAMESPACE__ = "http://schemas.microsoft.com/2003/10/Serialization/" @dataclass class Array: class Meta: namespace = "http://schemas.microsoft.com/2003/10/Serialization/" item: List[object] = fi...
1,239
373
# # PySNMP MIB module PRIVATE-SW0657840-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PRIVATE-SW0657840-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:33:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
54,161
27,874
from __future__ import print_function try: import h5py WITH_H5PY = True except ImportError: WITH_H5PY = False try: import zarr WITH_ZARR = True from .io import IoZarr except ImportError: WITH_ZARR = False try: import z5py WITH_Z5PY = True from .io import IoN5 except ImportError: ...
14,005
4,713
class MinDiffList: # def __init__(self): # self.diff = sys.maxint def findMinDiff(self, arr): arr.sort() self.diff = arr[len(arr) - 1] for iter in range(len(arr)): adjacentDiff = abs(arr[iter + 1]) - abs(arr[iter]) if adjacentDiff < self.diff: ...
481
177
""" Add the taxonomy to the patric metadata file """ import os import sys import argparse from taxon import get_taxonomy_db, get_taxonomy c = get_taxonomy_db() if __name__ == '__main__': parser = argparse.ArgumentParser(description="Append taxonomy to the patric metadata file. This adds it at column 67") par...
2,075
648
from __future__ import division import numpy as np from rawADCPclass import rawADCP from datetime import datetime from datetime import timedelta import scipy.io as sio import scipy.interpolate as sip import matplotlib.pyplot as plt import seaborn def date2py(matlab_datenum): python_datetime = datetime.fromordinal(...
11,450
4,177
""" Author: CaptCorpMURICA Project: 100DaysPython File: module1_day06_lists.py Creation Date: 6/2/2019, 8:55 AM Description: Learn the basic of lists in python. """ list_1 = [] list_2 = list() print("List 1 Type: {}\nList 2 Type: {}".format(type(list_1), type(list_2))) ...
1,923
845
class MagicDice: def __init__(self, account, active_key): self.account = account self.active_key = active_key
131
40
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/repeated-string/problem # Difficulty: Easy # Max Score: 20 # Language: Python # ======================== # Solution # ======================== import os # Complete the repeatedStrin...
708
244
#!/usr/bin/python from fvregress import * import string # really? you have to do this? if len(sys.argv) > 1 : wantPause = True timeout=9999999 valgrindArgs= [] else: wantPause = False timeout=5 valgrindArgs= None # start up a flowvisor with 1 switch (default) and two guests #h= HyperTest(guests=[('localhost'...
6,056
3,860
""" Writing actual code might be hard to understand for new-learners. Pseudocode is a tool for writing algorithms without knowing how to code. This module contains classes and methods for parsing pseudocode to AST and then evaluating it. Example: If you installed this module with pip you can run pseudocode from fi...
1,325
404
from talon import ( Module, Context, ) mod = Module() mod.tag("deep_sleep", desc="Enable deep sleep") ctx = Context() @mod.action_class class Actions: def enable_deep_sleep(): """???""" ctx.tags = ["user.deep_sleep"] def disable_deep_sleep(): """???""" ctx.tags = []
320
111
"Module 'upip_utarfile' on firmware 'v1.10-247-g0fb15fc3f on 2019-03-29'" DIRTYPE = 'dir' class FileSection(): ... def read(): pass def readinto(): pass def skip(): pass REGTYPE = 'file' TAR_HEADER = None class TarFile(): ... def extractfile(): pass def next(): ...
396
151
from zeit.cms.i18n import MessageFactory as _ import zope.formlib.interfaces import zope.interface @zope.interface.implementer(zope.formlib.interfaces.IWidgetInputError) class DuplicateAuthorWarning(Exception): def doc(self): return _( u'An author with the given name already exists. ' ...
482
138
def countWord(word): count = 0 with open('test.txt') as file: for line in file: if word in line: count += line.count(word) return count word = input('Enter word: ') count = countWord(word) print(word, '- occurence: ', count)
237
89
import random import os import logging import pickle import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn # import faiss ################################################################################ # General-...
9,190
3,092
header = """/* Icebreaker and IceSugar RSMB5 project - RV32I for Lattice iCE40 With complete open-source toolchain flow using: -> yosys -> icarus verilog -> icestorm project Tests are written in several languages -> Systemverilog Pure Testbench (Vivado) -> UVM testbench (Vivado) -> PyUvm (Icarus) -> Formal ...
7,009
2,530
import feedparser def read_rss_feed(feed_url): feed = feedparser.parse(feed_url) return [trim_entry(entry) for entry in feed.entries] def trim_entry(entry): return { 'date': "{}/{}/{}".format(entry.published_parsed.tm_year, entry.published_parsed.tm_mon, entry.published_parsed.tm_mday), 't...
438
149
import asyncio import datetime import json import logging import os import sys import typing from pathlib import Path from typing import Any, Dict, Optional, Tuple import discord import toml from discord.ext.commands import BadArgument from pydantic import BaseModel from pydantic import BaseSettings as PydanticBaseSet...
9,229
2,767
# plot rotation period vs orbital period import os import numpy as np import matplotlib.pyplot as plt import pandas as pd import glob import re from gyro import gyro_age import teff_bv as tbv import scipy.stats as sps from calc_completeness import calc_comp # np.set_printoptions(threshold=np.nan, linewidth=9) plotpar...
5,851
2,496
# Copyright 2016, 2017 California Institute of Technology # Users must agree to abide by the restrictions listed in the # file "LegalStuff.txt" in the PROPER library directory. # # PROPER developed at Jet Propulsion Laboratory/California Inst. Technology # Original IDL version by John Krist # Python transla...
9,911
3,809
__author__ = 'cmantas' from tools import * # Kmeans mahout vs spark m_q = """select mahout_kmeans_text.documents/1000, mahout_kmeans_text.time/1000 from mahout_tfidf inner join mahout_kmeans_text ON mahout_tfidf.documents=mahout_kmeans_text.documents AND mahout_tfidf.dimensions=mahout_kmeans_text.dimensions where ...
1,571
683
# Copyright 2021 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...
1,818
594
# -*- coding: utf-8 -*- # Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved. # Please refer to our terms for more information: # # https://www.sqreen.io/terms.html # import logging import traceback from datetime import datetime from ..runtime_storage import runtime from ..utils import is_string LO...
3,338
995
# Copyright (c) 2021, Roona and Contributors # See license.txt # import frappe import unittest class TestRoonaAppSetting(unittest.TestCase): pass
149
54
# coding=utf-8 # noinspection PyUnresolvedReferences import maya.cmds as cmds from LxBasic import bscMtdCore, bscObjects, bscMethods # from LxPreset import prsConfigure, prsOutputs # from LxCore.config import appCfg # from LxCore.preset.prod import assetPr # from LxDatabase import dtbMtdCore # from LxDatabase.data imp...
37,505
10,428
import json class Service(object): id: int = None name: str = None type: int = None type_name: str = None repeat_period: int = 5 # repeat period by second metadata = {} def __init__(self, arr: list): self.id = arr[0] self.name = arr[1] self.type = arr[2] ...
441
148
import json import pickle import re from copy import copy, deepcopy from functools import lru_cache from json import JSONDecodeError from os import system, walk, sep from abc import ABC, abstractmethod from pathlib import Path import time from subprocess import check_output from tempfile import NamedTemporaryFile from ...
22,422
6,302
# encoding=utf8 from load_to_db import * save_list = [] import random import string def randomString(url, stringLength=20): """Generate a random string of fixed length """ Letters = string.ascii_lowercase + string.ascii_uppercase + string.digits url_split = url.split(".") format_ = url_split[-1] ...
801
258
num = int(input()) x = 0 if num == 0: print(1) exit() while num != 0: x +=1 num = num//10 print(x)
124
61
import math from stable_baselines_model_based_rl.wrapper.step_handler import StepRewardDoneHandler class ContinuousMountainCarStepHandler(StepRewardDoneHandler): goal_position = 0.45 goal_velocity = 0 def get_done(self, step: int) -> bool: s = self.observation.to_value_list() ...
786
268
from django.core.exceptions import FieldError from django.db import ProgrammingError from stats.models import Tour, Sortie from django.db.models import Max import config RETRO_COMPUTE_FOR_LAST_TOURS = config.get_conf()['stats'].getint('retro_compute_for_last_tours') if RETRO_COMPUTE_FOR_LAST_TOURS is None: RETRO_C...
3,305
908
## -*- coding: utf-8 -*- # # Copyright (c) 2016, Veritomyx, Inc. # # This file is part of the Python SDK for PeakInvestigator # (http://veritomyx.com) and is distributed under the terms # of the BSD 3-Clause license. from .base import BaseAction class RunAction(BaseAction): """This class is used to make a RUN cal...
2,016
577
#!/usr/bin/env python3 import os import sys import json from datetime import datetime from submitty_utils import dateutils def generatePossibleDatabases(): current = dateutils.get_current_semester() pre = 'submitty_' + current + '_' path = "/var/local/submitty/courses/" + current return [pre + name for name in ...
3,757
1,344
class SpecValidator: def __init__(self, type=None, default=None, choices=[], min=None, max=None): self.type = type self.default = default self.choices = choices self.min = min self.max = max
252
71
# # levelpy/async/__init__.py # import asyncio
48
22
# -*- coding: utf-8 # Models from ..models import Channel, ChannelUser, Message async def test_channel_model(channel_data): channel = Channel( owner_id=1, name='General') channel = await channel.create() assert repr(channel) == "<Channel: 'General'>" async def test_channel_user_model(c...
751
237
from ._base import BaseModel, BaseModelMeta, BaseTableModel from ._schema import BaseField, ModelSchema, ModelSchemaMeta, Pluck, fields from .attachment import AttachmentModel from .table import TableModel
206
53
"""FactoryAggregate provider prototype.""" class FactoryAggregate: """FactoryAggregate provider prototype.""" def __init__(self, **factories): """Initialize instance.""" self.factories = factories def __call__(self, factory_name, *args, **kwargs): """Create object.""" ret...
506
141
"""Test cnlunardate.""" import unittest import pickle from cnlunardate import cnlunardate from cnlunardate import MIN_YEAR, MAX_YEAR from datetime import timedelta pickle_loads = {pickle.loads, pickle._loads} pickle_choices = [(pickle, pickle, proto) for proto in range(pickle.HIGHEST_PROTOCOL + 1)...
27,385
10,009
# -*- coding: utf-8 -*- import time def time_now(): """returns current unix time as an integer""" return int(time.time()) def get_day_times(num_days=1, end_time=time_now()): """returns a list of tuples, where each tuple contains the start and end times (in unix time format, as integers) of the day(s...
756
257
# Copyright (c) 2017, IGLU consortium # 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, # this list of conditions and...
4,593
1,624
import logging import sqlite3 from logging import Logger from sqlite3 import Connection from typing import Optional from slack_sdk.oauth.installation_store.async_installation_store import ( AsyncInstallationStore, ) from slack_sdk.oauth.installation_store.installation_store import InstallationStore from slack_sdk....
9,244
2,213
from django.contrib import admin from parler.admin import TranslatableAdmin from .models import Address, Municipality, Street @admin.register(Municipality) class MunicipalityAdmin(TranslatableAdmin): pass @admin.register(Street) class StreetAdmin(TranslatableAdmin): pass @admin.register(Address) class Ad...
381
112
from collections import Iterable from h5py import RegionReference from .form.utils import docval, getargs, ExtenderMeta, call_docval_func, popargs from .form import Container, Data, DataRegion, get_region_slicer from . import CORE_NAMESPACE, register_class from six import with_metaclass def set_parents(container, p...
7,704
2,317
import os import pandas as pd from open_geo_engine.src.get_google_streetview import GetGoogleStreetView def test_get_google_streetview(): size = "600x300" heading = "151.78" pitch = "-0.76" key = os.environ.get("GOOGLE_DEV_API_KEY") image_folder = "tests/test_data" links_file = "tests/test_da...
2,246
978
#!/usr/bin/env python """ _selfupdate_ Util command for updating the cirrus install itself Supports getting a spefified branch or tag, or defaults to looking up the latest release and using that instead. """ import sys import argparse import arrow import os import requests import inspect import contextlib from cirru...
6,186
1,863
from base_bot import log def atoi(text): return int(text) if text.isdigit() else text def bool_to_emoticon(value): return value and "✅" or "❌" # https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries # merges b into a def merge(a, b, path=None): if path is None: path = [...
1,335
468
from jsgf import parse_grammar_string def main(args): # Parse input grammar file. with open(args.input_file_path, "r") as fp: text = fp.read() print("\ninput grammar: ") print(text) grammar = parse_grammar_string(text) # Print it. print("\noutput grammar: ") text = ...
877
295
# coding: utf-8 import os import logging.config from webspider import setting LOG_FILE_PATH = os.path.join(setting.BASE_DIR, 'log', 'spider_log.txt') LOGGING_CONFIG = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'default': { 'format': '%(asctime)s- %(module)s:%(l...
2,685
848
# Copyright (c) 2015 Hitachi Data Systems, 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 # # U...
53,851
19,080
#!/usr/bin/env python # -*- coding: utf-8 -*- """Generate dummy data for tests/examples """ import numpy as np def dummy_gauss_image(x=None, y=None, xhalfrng=1.5, yhalfrng=None, xcen=0.5, ycen=0.9, xnpts=1024, ynpts=None, xsigma=0.55, ysigma=0.25, nois...
2,978
1,118
from approximate_equilibrium.optimize.optimization import de_optimizer, objective_function, brute_force_optimizer, objective_function_iccn, gradient_optimizer
159
43
""" Copyright 2021 Dynatrace LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software ...
4,295
1,253
from .. import Check from .common import common_checks def check(db): for org in db.organizations.find({"classification": "legislature"}): for check in common_checks(org, 'organization', 'organizations'): yield check jid = org.get('jurisdiction_id') if jid is None: ...
2,984
821
from sdk.color_print import c_print from tqdm import tqdm #Migrate def compare_trusted_networks(source_networks, clone_networks): ''' Accepts the source trusted alert network list and a clone trusted alert network list. Compares the source tenants network list to a clone tenant networks list. ''' ...
5,165
1,680
# Copyright 2015 Google 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 law or ag...
4,004
1,068
from typing import Any, Dict, List, Tuple from unittest import TestCase from ..cterm import CTerm from ..kast import TRUE, KApply, KInner, KVariable from ..kcfg import KCFG from ..prelude import token def nid(i: int) -> str: return node(i).id # over 10 is variables def term(i: int) -> CTerm: inside: KInner...
7,047
2,732
from cortexpy.tesserae import Tesserae class TestTesserae: def test_mosaic_alignment_on_short_query_and_two_templates(self): # given query = "GTAGGCGAGATGACGCCAT" targets = ["GTAGGCGAGTCCCGTTTATA", "CCACAGAAGATGACGCCATT"] # when t = Tesserae() p = t.align(query, ta...
645
260
try: from ._version import version as __version__ except ImportError: __version__ = "unknown" from . import _key_bindings del _key_bindings
151
49
import numpy as np from numpy.random import RandomState from numpy.testing import assert_allclose from nnlib.l_layer.backward import linear_backward, linear_backward_activation, model_backward from nnlib.utils.derivative import sigmoid_backward, relu_backward from nnlib.utils.activation import sigmoid, relu def test...
8,544
4,825
"""Uploaded data to nuuuwan/news_lk:data branch.""" from news_lk import scrape if __name__ == '__main__': scrape.scrape_and_dump()
137
56
from schematics import Model from schematics.types import IntType, UUIDType, StringType, BooleanType from ingredients_db.models.region import RegionState, Region from ingredients_http.schematics.types import ArrowType, EnumType class RequestCreateRegion(Model): name = StringType(required=True, min_length=3) ...
1,814
556
#!/usr/bin/env python3 from src.cli import Cli from src.core import Orchestrator def main(): config, args = Cli.parse_and_validate() Orchestrator.launch_modules(config, args.modules, args.targets, args.audit) if __name__ == '__main__': main()
257
91
# -*- coding: utf-8 -*- # DO NOT EDIT THIS FILE! # This file has been autogenerated by dephell <3 # https://github.com/dephell/dephell try: from setuptools import setup except ImportError: from distutils.core import setup import os.path readme = '' here = os.path.abspath(os.path.dirname(__file__)) readme_...
1,696
654
#!/cm/shared/languages/python-3.3.2/bin/python # submit script for submission of mizuRoute simualtions # Peter Uhe Oct 29 2019 # # call this script from 'run_mizuRoute_templated_mswep050calib.py which creates a qsub job to submit to the HPC queue # This script is actually called from 'call_pythonscript.sh' (which is n...
1,505
542
from xml.etree.ElementTree import iterparse, ParseError from io import StringIO from os.path import isfile from re import findall class XmlParser: def __init__(self, source=""): self.source = source self.proces_file = False self.use_io = False self.encoding = 'UTF-8' self....
17,968
4,550
from flask import Flask, request from flask_restful import Resource from .models import Order, orders class OrderDetals(Resource): def get(self, id): order = Order().get_order_by_id(id) if not order: return {"message":"Order not found"}, 404 return {"order": ord...
1,404
408
from typing import Mapping, Any, Sequence import numpy as np import heapq import math from tqdm import tqdm import scipy.optimize import cvxpy as cvx def n_bias(x_count: np.ndarray, bias: float): # return np.sum(x_count[x_count >= bias]) clipped = np.clip(x_count - bias, a_min=0, a_max=None) return n...
5,198
2,148
import json, os ## base spawner config try: c.Spawner.cmd = \ json.loads(os.environ['SPAWNER_CMD']) except KeyError: c.Spawner.cmd = [ 'jupyterhub-singleuser', # OAuth wrapped jupyter instance server '--KernelManager.transport=ipc', # -- all kernel comms over UNIX sockets '--Ma...
874
310
__all__ = ['get_dataset'] def get_dataset(params): if params['name'] == 'multimodal_points': from datasets.multimodal_gaussian_2d import Dataset return Dataset(params) elif params['name'] == 'kicks': from datasets.kicks import Dataset return Dataset(params) assert False and...
339
103
# coding: utf-8 """ Memsource REST API Welcome to Memsource's API documentation. To view our legacy APIs please [visit our documentation](https://wiki.memsource.com/wiki/Memsource_API) and for more information about our new APIs, [visit our blog](https://www.memsource.com/blog/2017/10/24/introducing-rest-apis...
8,419
2,600
def f(x): #return 1*x**3 + 5*x**2 - 2*x - 24 #return 1*x**4 - 4*x**3 - 2*x**2 + 12*x - 3 return 82*x + 6*x**2 - 0.67*x**3 print(f(2)-f(1)) #print((f(3.5) - f(0.5)) / -3) #print(f(0.5))
188
133
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import itertools import threading import numpy as np from six.moves import zip # pylint: disable=redefined-builtin from google.protobuf import json_format from tensorflow....
19,194
4,850
import pytest @pytest.fixture def config_yaml(): return """ local_sender: cls: aioworkers.net.sender.proxy.Facade queue: queue1 queue1: cls: aioworkers.queue.base.Queue worker: cls: aioworkers.net.sender.proxy.Worker autorun: true input: queue1 ...
761
258
import torch import torchvision import numpy as np import lib.model from lib.model import MetadataModel, train_model import lib.dataset import lib.dirs as dirs import lib.utils as utils import lib.vis_utils as vutils import lib.defines as defs if __name__ == "__main__": data_path = dirs.data...
2,794
930
#!/usr/bin/env python # -*- coding: utf-8 -*- """Parse tree and find files matching owncloud forbidden characters. Rename in place or move into a specific folder """ import KmdCmd import KmdFiles import os, re import logging class KmdOwncloudRename(KmdCmd.KmdCommand): regexp = r'[\*:"?><|]+' def extendParser...
1,533
474
import random def get_random_bag(): """Returns a bag with unique pieces. (Bag randomizer)""" random_shapes = list(SHAPES) random.shuffle(random_shapes) return [Piece(0, 0, shape) for shape in random_shapes] class Shape: def __init__(self, code, blueprints): self.code = code self....
13,975
4,384
import sys input = sys.stdin.readline n = int(input()) if n < 2: print(n) exit(0) d = [0] * (n+1) d[1] = 1 d[2] = 3 for i in range(n+1): if i < 3: continue d[i] = (d[i-1] % 10007 + (d[i-2]*2) % 10007) % 10007 print(d[n])
249
146
import Light __author__ = 'adilettad' print("---------------") print("----Welcome----") print("------to-------") print("-----Saber-----") print("---------------") sab = Light.Saber() while True: command = raw_input('Your command:') if command == "blink": sab.demoLED() elif command == "dist" or...
1,074
346
# Copyright 2021 Nokia # Licensed under the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause import a10.structures.constants import a10.structures.identity import a10.structures.returncode import a10.asvr.db.core import a10.asvr.db.announce import a10.asvr.elements def getTypes(): """Gets a list of...
739
270
# Generated by Django 2.2.12 on 2021-04-16 10:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('packages', '0003_auto_20210416_1007'), ] operations = [ migrations.AlterField( model_name='address', name='street_n...
456
158
from django.shortcuts import render # Python functions - user is going to request an url # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("<h1> This is the music app homepage</h1>")
241
65
''' @author Tian Shi Please contact tshi@vt.edu ''' import math import torch class PositionalEmbedding(torch.nn.Module): ''' Implementation of Positional Embedding. ''' def __init__(self, hidden_size, device=torch.device("cpu")): super().__init__() self.hidden_size = hidden_size ...
1,073
410
from tor4 import tensor def test_tensor_sum(): a = tensor(data=[-1, 1, 2]) a_sum = a.sum() assert a_sum.tolist() == 2 assert not a_sum.requires_grad def test_tensor_sum_backward(): a = tensor(data=[-1, 1, 2.0], requires_grad=True) a_sum = a.sum() a_sum.backward() assert a_sum.tolis...
3,108
1,406
import numpy as np import matplotlib.pyplot as plt def aprbs(**parms): # Generate an Amplitude modulated Pseudo-Random Binary Sequence (APRBS) # # The Pseudo-Random Binary Sequence (PRBS) is extensively used as an # excitation signal for System Identification of linear systems. It is # cha...
3,150
1,063