text
string
size
int64
token_count
int64
import arcade import os SPRITE_SCALING = 0.5 SPRITE_NATIVE_SIZE = 128 SPRITE_SIZE = int(SPRITE_NATIVE_SIZE * SPRITE_SCALING) SCREEN_WIDTH = SPRITE_SIZE * 14 SCREEN_HEIGHT = SPRITE_SIZE * 10 MOVEMENT_SPEED = 5 COIN_SCALE = 0.7 class Room: """ This class holds all the information about the ...
18,598
6,794
# Copyright (c) 2018 gevent community # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, di...
4,869
1,519
''' marathon_example.py performs a simple matrix multiply using 3 compute nodes ''' def parseargs(): parser = argparse.ArgumentParser(description='Marathon for TensorFlow.') parser.add_argument('--n_tasks', default=1, help='an integer for the accumulator') parser.add_argument('--cpu', default=100.0, ...
1,628
521
''' Original code contributor: mentzera Article link: https://aws.amazon.com/blogs/big-data/building-a-near-real-time-discovery-platform-with-aws/ ''' import boto3 import json import twitter_to_es # from Examples.Demo.AWS_Related.TwitterStreamWithAWS.LambdaWithS3Trigger import \ # twitter_to_es from tweet_utils i...
2,922
837
from django.contrib.messages.constants import DEFAULT_LEVELS from user_messages.api import get_messages def messages(request): """ Return a lazy 'messages' context variable as well as 'DEFAULT_MESSAGE_LEVELS'. """ return { "messages": get_messages(request=request), "DEFAULT_MESSAG...
353
112
## Highest Score # ๐Ÿšจ Don't change the code below ๐Ÿ‘‡ student_scores = input("Input a list of student scores: ").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(student_scores) # ๐Ÿšจ Don't change the code above ๐Ÿ‘† # Write your code below this row ๐Ÿ‘‡ highest_score = 0...
502
186
import argparse from loader import MoleculeDataset from torch_geometric.data import DataLoader import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from tqdm import tqdm import numpy as np from model import GNN, GNN_graphpred from sklearn.metrics import roc_auc_score from ...
8,791
2,937
from jumpscale.core import exceptions class BaseError(exceptions.Base): """a generic base error for bcdb rest, with status code""" def __init__(self, status, *args, **kwargs): super().__init__(*args, *kwargs) self.status = status class VDCNotFound(BaseError): pass class MissingAuthori...
1,166
369
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import pandas as pd from ..events import events_plot from ..stats import standardize as nk_standardize def signal_plot( signal, sampling_rate=None, subplots=False, standardize=False, labels=None, **kwargs ): """Plot signal with events...
5,703
1,729
"""Only one validation per mission, user and actor Revision ID: 1a89721126f7 Revises: fa96dfc8237d Create Date: 2021-10-14 11:22:01.124488 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "1a89721126f7" down_revision = "fa96dfc8237d" branch_labels = None depends...
1,183
406
# Copyright 2020 Jan Feitsma (Falcons) # SPDX-License-Identifier: Apache-2.0 #!/usr/bin/python import os import sys import argparse from rtdb2 import RtDB2Store, RTDB2_DEFAULT_PATH import rtdb2tools from hexdump import hexdump # Main structure of the program if __name__ == "__main__": # Argument parsing. des...
1,979
878
from __future__ import print_function from __future__ import division import os import gym import numpy as np from skimage.transform import resize from skimage.color import rgb2gray class Atari(object): s_dim = [84, 84, 1] a_dim = 3 def __init__(self, args, record_video=False): self.env = gym.m...
2,219
733
#!/usr/bin/env python # coding: utf-8 # # Meta-Analytic Coactivation Modeling # In[1]: # First, import the necessary modules and functions import os from datetime import datetime import matplotlib.pyplot as plt from myst_nb import glue from repo2data.repo2data import Repo2Data import nimare start = datetime.now(...
5,935
2,068
""" CISCO_IPSLA_ECHO_MIB This MIB module defines the templates for IP SLA operations of ICMP echo, UDP echo and TCP connect. The ICMP echo operation measures end\-to\-end response time between a Cisco router and any IP enabled device by computing the time taken between sending an ICMP echo request message to the d...
50,863
16,535
# 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...
4,057
1,286
#!/usr/bin/env python3 import shlex from tkinter import * from tkinter import messagebox from psutil import Popen top = Tk() top.title("Franka Gripper Control") top.geometry("300x75") def open(): node_process = Popen(shlex.split('rosrun franka_interactive_controllers libfranka_gripper_run 1')) messagebox.showinfo...
762
297
for i in range(int(input())): number_of_candies = int(input()) candies_weights = list(map(int, input().split())) bob_pos = number_of_candies - 1 alice_pos = 0 bob_current_weight = 0 alice_current_weight = 0 last_equal_candies_total_number = 0 while alice_pos <= bob_pos: if al...
742
275
#!/usr/bin/env python """This tool builds or repacks the client binaries. This handles invocations for the build across the supported platforms including handling Visual Studio, pyinstaller and other packaging mechanisms. """ import logging import os import platform import time # pylint: disable=unused-import from ...
12,293
3,423
# -------------- # Code starts here # Create the lists class_1 = ['geoffrey hinton', 'andrew ng', 'sebastian raschka', 'yoshu bengio'] class_2 = ['hilary mason', 'carla gentry', 'corinna cortes'] # Concatenate both the strings new_class = class_1+class_2 print(new_class) # Append the list new_class.append('p...
1,549
587
# coding=utf-8 # Copyright 2022 The ML Fairness Gym Authors. # # 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 applicab...
1,830
597
import argparse import csv import os from moss_client.core import submit_and_dl, parse_moss_reports data_folder = 'data' def handle_input(user_id, base_folder, parse, only_parse, join_file, batch): global data_folder abs_path = os.path.abspath(os.path.dirname(__file__)) root_data_folder = os.path.join(ab...
3,034
908
#!/usr/bin/env python import rospy #from apriltags_ros.msg import AprilTagDetectionArray from duckietown_msgs.msg import AprilTagsWithInfos import tf2_ros from tf2_msgs.msg import TFMessage import tf.transformations as tr from geometry_msgs.msg import Transform, TransformStamped import numpy as np from localization imp...
6,495
2,262
#!/usr/bin/python # pylint: disable=W0223 """ Get a list of teams """ from html.parser import HTMLParser import requests class ChkTeams(HTMLParser): """ Extract team names from page """ def __init__(self): HTMLParser.__init__(self) self.retval = [] def handle_starttag(self, tag, a...
1,030
362
# # PySNMP MIB module Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB # Produced by pysmi-0.3.4 at Wed May 1 14:31:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5....
32,904
12,647
import codecs import tempfile from contextlib import closing from .cgi import CGIClient from .combine import CombineSVG from .mapserv import MapServer, InternalError from .tree import build_tree def _recursive_add_layer(nodes, params, svg, mapserver, translations): for node in nodes: group_name = format...
2,882
932
import frappe @frappe.whitelist() def filt_itemby_supplier(doctype, txt, searchfield, start, page_len, filters): return frappe.db.sql("""Select parent from `tabItem Supplier` where supplier= %s""",(filters.get("supplier"))); @frappe.whitelist() def filteritem(doctype, txt, searchfield, start, page_len, filters...
440
156
from common.bio.constants import SMILES_CHARACTER_TO_ID, ID_TO_SMILES_CHARACTER def from_smiles_to_id(data, column): """Converts sequences from smiles to ids Args: data: data that contains characters that need to be converted to ids column: a column of the dataframe that contains characters that ...
925
275
import os import sys import unittest # Set Python search path to the parent directory sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from lib.config import * class TestLibConfig(unittest.TestCase): def test_config_noconfigfile(self): config = BeaconConfigParser('not_exist.cfg') wit...
1,001
314
""" Test to make sure that libraries built with Nimporter can be installed via Pip. """ import sys, os, subprocess, shutil, pkg_resources, json, warnings from pathlib import Path import pytest import nimporter PYTHON = 'python' if sys.platform == 'win32' else 'python3' PIP = 'pip' if shutil.which('pip') else 'pip3' ...
7,188
1,985
samples = { "2_brother_plays": { "question_parts": [range(1, 13), range(13, 17)], "sp_parts": [range(20, 43), range(50, 60)] } }
153
73
# Generated by Django 3.1.7 on 2021-03-24 17:41 import django.db.models.deletion from django.conf import settings from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("blo...
695
228
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import ...
16,227
4,498
from kivy.uix.screenmanager import ScreenManager from kivy.uix.boxlayout import BoxLayout from kivy.lang.builder import Builder from kivy.animation import Animation from kivy.core.window import Window from kivymd.app import MDApp import kivymd import kivy print( ) def version(): kivy.require('2.0.0') print( )
319
116
import functools import itertools import numbers from ..backend_object import BackendObject from ..annotation import Annotation def normalize_types_two_args(f): @functools.wraps(f) def normalizer(self, region, o): """ Convert any object to an object that we can process. """ if ...
19,367
5,505
import logging from episodes import find_updates, db, count_all from logging import error as logi from flask import Flask, jsonify, request def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.config['JSON_AS_ASCII'] = False ...
2,663
746
from ..utils import Object class CanTransferOwnershipResultPasswordTooFresh(Object): """ The 2-step verification was enabled recently, user needs to wait Attributes: ID (:obj:`str`): ``CanTransferOwnershipResultPasswordTooFresh`` Args: retry_after (:obj:`int`): Time le...
868
273
# -*- coding: utf-8 -*- # catapult: runs python scripts in already running processes to eliminate the # python interpreter startup time. # # The lexicon for sparv.saldo.annotate and sparv.saldo.compound can be pre-loaded and # shared between processes. See the variable annotators in handle and start. # # Run scripts in...
12,199
3,711
from __future__ import unicode_literals import unittest from nose.tools import * # PEP8 asserts from nose.plugins.attrib import attr from textblob.sentiments import PatternAnalyzer, NaiveBayesAnalyzer, DISCRETE, CONTINUOUS class TestPatternSentiment(unittest.TestCase): def setUp(self): self.analyzer = ...
2,445
882
from django.apps import AppConfig class Config(AppConfig): name = 'unicef_security' verbose_name = "UNICEF Security"
127
41
import json import sys f=open(sys.argv[1]) y = json.loads(f.read()) print("Tests results: " + str(y["result"])) print("Tests duration: " + str(y["duration"])) print("Tests output:\n~~~~~~~~~~~~~~~~~~~~\n" + str(y["stdout"]))
229
85
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
14,533
4,861
""" Manage Linux kernel packages on APT-based systems """ import functools import logging import re try: from salt.utils.versions import LooseVersion as _LooseVersion from salt.exceptions import CommandExecutionError HAS_REQUIRED_LIBS = True except ImportError: HAS_REQUIRED_LIBS = False log = loggin...
7,079
2,115
import json import numpy as np from numba import jit from timeit import default_timer as timer # Constant, used in the formula. # Defined here to speed up the calculation, i.e. it's calculated only once # and then placed in the formula. SQRT_2PI = np.float32(np.sqrt(2 * np.pi)) # This function will run on the CPU. d...
1,818
620
#! /usr/bin/python import sys if sys.version_info[0] == 3: from .__main__ import * else: pass
103
43
import datetime def iso_extract_info(string): """ Will get all of the info and return it as an array :param string: ISO formatted string that will be used for extraction :return: array [year, month, day, military_time_hour, minutes, hours] :note: every item is an int except for minutes ...
5,605
1,953
from microbit import * import random, speech, radio eye_angles = [50, 140, 60, 90, 140] radio.off() sentences = [ "Hello my name is Mike", "What is your name", "I am looking at you", "Exterminate exterminate exterminate", "Number Five is alive", "I cant do that Dave", "daisee daisee give ...
1,424
578
import datetime import time def sleep(n_secs): time.sleep(n_secs) def get_timestamp(): dtime = datetime.datetime.now() un_time = time.mktime(dtime.timetuple()) return str(un_time) def print_docId(docId): print(docId) def print_phonepass(phone,password): print(phone + "---------" + password)...
322
119
from django.urls import path from issue_template.views import IssueTemplateView urlpatterns = [ path( '<str:owner>/<str:repo>/<str:token_auth>/', IssueTemplateView.as_view() ), ]
205
66
import os, tempfile, subprocess from hammer_vlsi import MMMCCorner, MMMCCornerType, HammerTool, HammerToolStep, HammerSRAMGeneratorTool, SRAMParameters from hammer_vlsi.units import VoltageValue, TemperatureValue from hammer_tech import Library, ExtraLibrary from typing import NamedTuple, Dict, Any, List from abc imp...
5,248
1,776
import collections import nltk import os from sklearn import ( datasets, model_selection, feature_extraction, linear_model, naive_bayes, ensemble ) def extract_features(corpus): '''Extract TF-IDF features from corpus''' sa_stop_words = nltk.corpus.stopwords.words("english") # words that might in...
2,837
1,011
# -*- coding: utf-8 -*- ''' File name: code\gcd_sequence\sol_443.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #443 :: GCD sequence # # For more information see: # https://projecteuler.net/problem=443 # Problem Statement ''' Let g(n) ...
649
331
# coding=utf-8 """ Collects data from RabbitMQ through the admin interface #### Notes * if two vhosts have the queues with the same name, the metrics will collide #### Dependencies * pyrabbit """ import diamond.collector try: from numbers import Number Number # workaround for pyflakes issue #13 im...
2,823
784
# Copyright (c) 2021, NVIDIA CORPORATION & 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 # # Unless requ...
27,170
8,257
from flask import Flask, request, jsonify from flask_cors import CORS from run import run_ansys from api.validate import spec_present, data_type_validate, spec_keys_validate, ansys_overload_check ansys_processing_count = 0 # debug # import ipdb; ipdb.set_trace() app = Flask(__name__) CORS(app) # local development co...
1,140
374
from .dataset import get_cifar100, get_cifar10, get_imagenet_lmdb, get_imagenet __all__ = ["get_cifar100", "get_cifar10", "get_imagenet_lmdb", "get_imagenet"]
160
79
from sklearn.model_selection import KFold def kfold_cross_validation(data, k=10): kfold = KFold(n_splits=k) for train, test in kfold.split(data): yield data[train], data[test]
196
71
from django.db import models class Category(models.Model): title = models.CharField(max_length=20) class Meta: db_table = 'category' verbose_name = ("Category") verbose_name_plural = ("Categories") def __str__(self): return self.title
310
110
# admin_tools/urls.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.conf.urls import re_path from . import views urlpatterns = [ re_path(r'^$', views.admin_home_view, name='admin_home',), re_path(r'^data_cleanup/$', views.data_cleanup_view, name='data_cleanup'), re_path(r'^dat...
1,488
531
""" A base node that provides several output tensors. """ from ....layers.algebra import Idx from .base import SingleNode, Node from .. import _debprint from ...indextypes import IdxType class IndexNode(SingleNode): _input_names = ("parent",) def __init__(self, name, parents, index, index_state=None): ...
3,414
974
from .zero import zero from main_module._unittester import UnitTester test = UnitTester(__name__) del UnitTester
113
35
import numpy as np import numpy.random as npr import scipy.optimize as spo import tomo_challenge.metrics as tcm # custom data type, could be replaced with/tie in to tree.py class # cut_vals is (nfeat, nbins - 1) numpy array, float # tree_ids is ((nbins,) * nfeat) numpy array, int TreePars = namedtuple('TreePars', ['cu...
4,151
1,433
import shelve regal = shelve.open('score.txt') def updateScore(neuerScore): if('score' in regal): score = regal['score'] if(neuerScore not in score): score.insert(0, neuerScore) score.sort() ranking = score.index(neuerScore) ranking = len(score)-ranking else: score = [neuerScore] ...
480
171
# -*- coding: utf-8 -*- import ldap BASE = ldap.SCOPE_BASE ONELEVEL = ldap.SCOPE_ONELEVEL SUBTREE = ldap.SCOPE_SUBTREE SCOPES = [BASE, ONELEVEL, SUBTREE] del ldap
165
91
import glob import numpy as np X = np.empty((0, 193)) y = np.empty((0, 10)) groups = np.empty((0, 1)) npz_files = glob.glob('./urban_sound_?.npz') for fn in npz_files: print(fn) data = np.load(fn) X = np.append(X, data['X'], axis=0) y = np.append(y, data['y'], axis=0) groups = np.append(groups, dat...
493
218
import dlib class CorrelationTracker(object): def init(self, image, bbox): self.tracker = dlib.correlation_tracker() x, y, x2, y2 = bbox x2 += x y2 += y self.tracker.start_track(image, dlib.rectangle(x, y, x2, y2)) return True def update(self, image): s...
485
169
# Copyright (c) 2021, NVIDIA CORPORATION. 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...
3,238
1,049
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class ApiKey...
6,007
1,666
# Copyright 2018 United States Government as represented by the Administrator of # the National Aeronautics and Space Administration. No copyright is claimed in # the United States under Title 17, U.S. Code. All Other Rights Reserved. # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed # un...
10,684
3,105
import os import errno import sys def mock_directory_tree(tree): tree = dict([(os.path.join(*key), value) \ for key, value in tree.iteritems()]) def listdir(path): try: names = tree[path] except KeyError: raise OSError(errno.ENOENT, os.strerror(err...
4,016
1,218
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PerlIpcRun(PerlPackage): """IPC::Run allows you to run and interact with child processes u...
864
353
import sys import unittest try: from unittest import mock except ImportError: import mock import argparse from tabcmd.parsers.create_site_users_parser import CreateSiteUsersParser from .common_setup import * commandname = 'createsiteusers' class CreateSiteUsersParserTest(unittest.TestCase): @classmethod...
1,369
422
#!/usr/bin/env python import argparse import json import os import boto3 parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='''\ Output following the defined format. Options are: dotenv - dotenv style [default] export - shell export style std...
1,078
342
""" Finds the number of distinct ways a player can checkout a score less than 100 Author: Juan Rios """ import math def checkout_solutions(checkout,sequence,idx_sq,d): ''' returns the number of solution for a given checkout value ''' counter = 0 for double in d: if double>checkout: ...
1,730
539
import jax.numpy as jnp from jax import lax import optax import chex def _onehot(labels: chex.Array, num_classes: int) -> chex.Array: x = labels[..., None] == jnp.arange(num_classes).reshape((1,) * labels.ndim + (-1,)) x = lax.select(x, jnp.ones(x.shape), jnp.zeros(x.shape)) return x.astype(jnp.float32) ...
804
338
import os from setuptools import setup, find_packages import versioneer if __name__ == "__main__": def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() meta = {} base_dir = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(base_dir, 'gammy', '_m...
1,758
505
import root if __name__ == '__main__': window = root.Root() window.mainloop()
88
32
from flask import Blueprint recommendation_blueprint = Blueprint('recommendations', __name__) from application.recommendations import routes
144
41
# python 3.7 """Predicts the scene category, attribute.""" import numpy as np from PIL import Image import torch import torch.nn.functional as F import torchvision.transforms as transforms from .base_predictor import BasePredictor from .scene_wideresnet import resnet18 __all__ = ['ScenePredictor'] N...
4,203
1,498
from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:mysql@127.0.0.1:3306/python_github" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True db = SQLAlchemy(app) class User(db.Model): id = db.Column(db...
1,845
705
from collections import deque def solution(N, bus_stop): answer = [[1300 for _ in range(N)] for _ in range(N)] bus_stop = [(x-1, y-1) for x,y in bus_stop] q = deque(bus_stop) for x,y in bus_stop: answer[x][y] = 0 while q: x, y = q.popleft() for nx, ny in ((x-1, y), (x+1, y)...
652
255
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] ...
1,218
398
# -*- coding: utf-8 -*- """File containing a Windows Registry plugin to parse the USBStor key.""" from __future__ import unicode_literals from plaso.containers import events from plaso.containers import time_events from plaso.lib import definitions from plaso.parsers import logger from plaso.parsers import winreg fro...
5,452
1,642
''' static analyzers are annoying so lets rename eval ''' evil = eval
71
20
import numpy as np import torch from torch.nn import functional as F from rltoolkit.acm.off_policy import AcMOffPolicy from rltoolkit.algorithms import DDPG from rltoolkit.algorithms.ddpg.models import Actor, Critic class DDPG_AcM(AcMOffPolicy, DDPG): def __init__( self, unbiased_update: bool = False, cu...
17,257
5,284
#!/usr/bin/python #---------------------------------------------------------------- # OSM POI handler for pyroute # #------------------------------------------------------ # Copyright 2007, Oliver White # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publ...
3,714
1,458
from __future__ import annotations import os import traceback as tb from collections import defaultdict from enum import IntEnum from functools import update_wrapper from itertools import chain from typing import Any, Callable, DefaultDict, Generator, Iterable, Optional from pelutils import get_timestamp, get_repo fro...
13,025
4,000
import mock import pytest import datetime as dt from django.utils import timezone from elasticsearch_metrics import metrics from elasticsearch_dsl import IndexTemplate from elasticsearch_metrics import signals from elasticsearch_metrics.exceptions import ( IndexTemplateNotFoundError, IndexTemplateOutOfSyncErro...
10,942
3,331
from functools import lru_cache @lru_cache def fib(n): return n if n<2 else fib(n-1)+fib(n-2) def sum_fibs(n): return sum(j for j in (fib(i) for i in range(n+1)) if j%2==0)
180
85
"""Tests for :mod:`esmvalcore.iris_helpers`.""" import datetime import iris import numpy as np import pytest from cf_units import Unit from esmvalcore.iris_helpers import date2num, var_name_constraint @pytest.fixture def cubes(): """Test cubes.""" cubes = iris.cube.CubeList([ iris.cube.Cube(0.0, var...
1,924
774
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Geo regions for map plot """ __author__ = "Saeed Moghimi" __copyright__ = "Copyright 2017, UCAR/NOAA" __license__ = "GPL" __version__ = "1.0" __email__ = "moghimis@gmail.com" import matplotlib.pyplot as plt from collections import defaultdict defs = defaultdict(dic...
11,429
5,185
import numpy import matplotlib.pyplot as plt fig_convergence = plt.figure(1,figsize=(12,6)) x = numpy.loadtxt('log_deepAI_paper_nonlin_action_long.txt') plt.subplot(122) plt.plot(x[:,0]) plt.xlim([0,500]) plt.ylim([-10,200]) plt.xlabel('Steps') plt.ylabel('Free Action') plt.axvline(x=230.0,linestyle=':') plt.axvline...
771
383
#! python3 # Help from: http://www.scotttorborg.com/python-packaging/minimal.html # https://docs.python.org/3/distutils/commandref.html#sdist-cmd # https://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # https://docs.python.org/3.4/tutorial/modules.html # Install it with python setup.py ins...
2,938
912
import io import sys from textnn.utils import ProgressIterator #inspired by https://stackoverflow.com/a/34738440 def capture_sysout(cmd): capturedOutput = io.StringIO() # Create StringIO object sys.stdout = capturedOutput # and redirect stdout. cmd() ...
1,838
583
import os import numpy as np import pandas as pd housing_df = pd.read_csv(filepath_or_buffer='~/C:\Users\nikhi\NIKH0610\class5-homework\toys-datasets\boston')
159
65
def insert_metatable(): """SQL query to insert records from table insert into a table on a DB """ return """ INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES ('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0...
379
119
# -*- coding: utf-8 -*- """Highlevel wrapper of the VISA Library. :copyright: 2014-2020 by PyVISA-py Authors, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ import random from collections import OrderedDict from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, cast fr...
24,973
6,391
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import cv2 import numpy as np import os import math from PIL import Image, ImageDraw, ImageFont from caffe2.python import workspace from detectron.core.config import cf...
13,219
4,840
# -*- coding: utf-8 -*- ''' Execute salt convenience routines ''' # Import python libs from __future__ import print_function from __future__ import absolute_import import collections import logging import time import sys import multiprocessing # Import salt libs import salt.exceptions import salt.loader import salt.m...
13,740
3,721
# For usage of lark with PyInstaller. See https://pyinstaller-sample-hook.readthedocs.io/en/latest/index.html import os def get_hook_dirs(): return [os.path.dirname(__file__)]
186
69
# Copyright (c) 2019 Sagar Gubbi. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import numpy as np import gym import tensorflow as tf from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Input,...
4,257
1,551