text string | size int64 | token_count int64 |
|---|---|---|
# You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are(i, 0) and (i, height[i]).
# Find two lines that together with the x-axis form a container, such that the container contains the most water.
# Return the maximum amount of water a conta... | 1,107 | 350 |
'''
Function:
define the Encoding Layer: a learnable residual encoder
Author:
Zhenchao Jin
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
'''Encoding Layer'''
class Encoding(nn.Module):
def __init__(self, channels, num_codes):
super(Encoding, self).__init__()
# init... | 2,304 | 787 |
import slog
slog.quiet("debbug")
slog.debbug("Hi!")
slog.warning("Debbug?")
slog.unquiet()
slog.debbug("Aaaaaaaaa")
with slog.quiet("debbug"):
slog.debbug("Hello!")
slog.info("Hi!")
slog.info("Debbug?")
slog.debbug("Hey.")
| 238 | 120 |
# coding=utf-8
"""Functions for calculation of features"""
from nltk import sentiment, tokenize
import numpy as np
import pandas as pd
from sklearn.feature_extraction import text as text_sk
from sklearn import preprocessing as preprocessing_sk
import preprocessing
def bag_of_words(tr_tweets, te_tweets, tr_targets=pd... | 7,325 | 2,398 |
from enum import Enum
class Size(Enum):
VerySmall = "Very Small"
Small = "Small"
Medium = "Medium"
Large = "Large"
Huge = "Huge"
feet_map = {
Size.VerySmall: 1,
Size.Small: 3,
Size.Medium: 5,
Size.Large: 10,
Size.Huge: 20,
}
def size_in_feet(size):
return feet_map.get(s... | 328 | 153 |
import setuptools
import os
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="supportr",
version="0.1",
author="Zijian Wang and David Jurgens",
author_email="jurgens@umich.edu",
description="Supportr",
long_description=long_description,
long_descri... | 629 | 218 |
import logging
import os
from zipfile import ZipFile
import yaml
from pathlib import Path
logging.basicConfig(
filename=os.path.join("Logs", "running.log"),
format="[%(asctime)s: %(module)s: %(levelname)s]: %(message)s",
level=logging.INFO,
filemode="a"
)
def read_yaml(config_path):
with open(conf... | 1,095 | 366 |
import os
import redis
import code
import urlparse
import json
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug.wsgi import SharedDataMiddleware
from werkzeug.utils import redirect
from jinja2 import Environment,... | 1,432 | 448 |
#!/usr/bin/env python
##### convert values to ranks, tie breaker as average #####
from __future__ import division
from sys import argv, stdin, stdout
from signal import signal, SIGPIPE, SIG_DFL
import argparse
signal(SIGPIPE, SIG_DFL)
# parse args
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--inVal... | 1,714 | 562 |
# Generated by Django 2.0.6 on 2019-05-29 14:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('SAcore', '0008_user_avator'),
]
operations = [
migrations.AlterField(
model_name='user',
name='avator',
... | 414 | 144 |
"""test_CLI_system_stats.py: tests expected behavior for CLI application"""
from os import path
import pytest
from plumbum import local
import pandas as pd
import navitron_crons.exceptions as exceptions
import navitron_crons._version as _version
import navitron_crons.navitron_system_stats as navitron_system_stats
im... | 2,121 | 657 |
import numpy as np
import WDRT.ESSC as ESSC
import copy
import matplotlib.pyplot as plt
# Create buoy object, in this case for Station #46022
buoy46022 = ESSC.Buoy('46022', 'NDBC')
# Read data from ndbc.noaa.gov
#buoy46022.fetchFromWeb()
#buoy46022.saveAsTxt(savePath = "./Data")
#buoy46022.saveAsH5('NDBC46022.h5')
#... | 6,414 | 2,901 |
'''
Functionality common to all parsers
Created on 1 Feb 2018
@author: Teodor G Nistor
@copyright: 2018 Teodor G Nistor
@license: MIT License
'''
from beamr.debug import warn
def p_nil(p): # An empty production
'nil :'
pass
def p_error(t): # Parsing error
try:
warn("Syntax error at toke... | 386 | 136 |
import pickle
import struct
from contextlib import ExitStack
from tempfile import NamedTemporaryFile
from .forking import fork, get_id
def skip(iterable, skip, shift):
for idx, item in enumerate(iterable):
if idx % skip != shift:
continue
yield item
_HEADER_FORMAT = '>Q'
_HEADER_SIZE... | 1,553 | 512 |
# 最小差值
# 给定n个数,请找出其中相差(差的绝对值)最小的两个数,输出它们的差值的绝对值。
def st171201():
n= int(input())
numbers = list(map(int, input().split()))
numbers.sort()
# print(numbers)
before=numbers[1]
temp = abs(before-numbers[0])
for i in numbers[2:]:
# print(temp,before,i,abs(i-before))
if abs(i-bef... | 438 | 213 |
from PyQt5 import QtCore
from PyQt5.QtWidgets import QProgressBar
class ProgressBar(QProgressBar):
def __init__(self):
super(ProgressBar, self).__init__()
self.setTextVisible(True)
self.setMaximum(100)
self.setAlignment(QtCore.Qt.AlignCenter) | 279 | 89 |
#!/usr/bin/env python
"""
move-virtualenv
~~~~~~~~~~~~~~~
A helper script that moves virtualenvs to a new location.
It only supports POSIX based virtualenvs and at the moment.
:copyright: (c) 2012 by Fireteam Ltd.
:license: BSD, see LICENSE for more details.
"""
from __future__ import print_f... | 11,655 | 3,965 |
from enum import Enum
class EventType(Enum):
MY_INFO = "myInfo"
PRESENCE = "presence"
BUDDY_LIST = "buddylist"
TYPING = "typing"
IM = "im"
DATA_IM = "dataIM"
CLIENT_ERROR = "clientError"
SESSION_ENDED = "sessionEnded"
OFFLINE_IM = "offlineIM"
SENT_IM = "sentIM"
SEND_DATA_IM... | 664 | 262 |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import boto3
import botocore
import logging
import os
import urllib.parse
from typing import Any
from gamekithelpers import ddb
# Custom Types:
S3Object = Any
# Magic Values:
ISO_8601_FORMAT = '%Y-%m-%dT%H:%M:%... | 4,730 | 1,487 |
from __future__ import print_function
#! /usr/bin/env cmsRun
import sys
import FWCore.ParameterSet.Config as cms
from SimTracker.TrackerMaterialAnalysis.trackingMaterialVarParsing import options
process = cms.Process("MaterialAnalyser")
if options.geometry == 'run2':
process.load('Configuration.Geometry.Geometr... | 1,533 | 497 |
# This unit test checks the python_server.py
# Run `pytest` in the root directory of the jRDF2vec project (where the pom.xml resides).
import threading
import python_server as server
import time
import requests
from pathlib import Path
uri_prefix = "http://localhost:1808/"
class ServerThread(threading.Thread):
... | 2,515 | 838 |
"""
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
Â
Example 1:
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --... | 1,041 | 401 |
from mock import MagicMock, patch
from nose.tools import eq_
from gease.contributors import EndPoint
from gease.exceptions import NoGeaseConfigFound
class TestPublish:
@patch("gease.contributors.get_token")
@patch("gease.contributors.Api.get_public_api")
def test_all_contributors(self, fake_api, get_toke... | 2,197 | 687 |
"""
Copyright 2015, Institute for Systems Biology
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 w... | 1,594 | 592 |
import tweepy
import re
import string
# Consumer keys and access tokens, used for OAuth
consumer_key = "P5wTozEUuNOAJCXMajGnRcDs2"
consumer_secret = "RB7p2JVEZxbodmRT3eaA32caonxpo5fS5DOKXcoTxEKJelTZys"
access_token = "997065391644917761-mSZZ6gkTdLEOdDSOAFfu7clvJO4vQPq"
access_token_secret = "MoAMNPZeAmYMwtjaopDrAs1njC... | 2,913 | 1,121 |
import json
import os
import cv2
import numpy as np
import dutils.imageutils as diu
import dutils.learnutils as dlu
import torch, torchvision
import dutils.simpleutils as dsu
from detectron2.utils.logger import setup_logger
from detectron2.utils import comm
from detectron2 import model_zoo
from detectron2.engine impor... | 8,529 | 2,924 |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def get_location(well_name, char2num):
"""
calculates for a well's name its row and column indices in an array that represents the plate.
Parameters
----------
well_name: str
the name of the well in the form "B - 02" ... | 5,166 | 1,638 |
#!/usr/bin/env python -B
# Copyright (c) 2014, Ericsson AB. 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 notice, this
# list... | 53,973 | 17,790 |
# server backend
server = 'cherrypy'
# debug error messages
debug = False
# auto-reload
reloader = False
# database url
db_url = 'postgresql://user:pass@localhost/dbname'
# echo database engine messages
db_echo = False
| 223 | 69 |
#!/usr/bin/env python3
import subprocess
import os
import sys
sys.path.append("../")
sys.path.append("../../system/lib/")
sys.path.append("../array/")
import json_parser
import pos
import pos_util
import cli
import api
import json
import time
import CREATE_ARRAY_BASIC
ARRAYNAME = CREATE_ARRAY_BASIC.ARRAYNAME
def exec... | 880 | 333 |
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
class BaseNewsQuerySet(QuerySet):
def published(self):
return self.filter(publish_date__lte=datetime.now()).order_by('publish_date')
class BaseNewsManager(models.Manager):
def get_... | 476 | 153 |
from oggm import cfg, utils
from oggm import workflow
from oggm import tasks
from oggm.cfg import SEC_IN_YEAR
from oggm.core.massbalance import MassBalanceModel
import numpy as np
import pandas as pd
import netCDF4
def single_flowline_glacier_directory(rgi_id, reset=False, prepro_border=80):
"""Prepare a GlacierD... | 5,885 | 1,893 |
import numpy as np
import matplotlib.pyplot as plt
# colors corresponding to initial flight, stance, second flight
colors = ['k', 'b', 'g']
### The attributes of sol are:
## sol.t : series of time-points at which the solution was calculated
## sol.y : simulation results, size 6 x times
## sol.t_events : list of t... | 6,601 | 3,056 |
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2 # noqa: E501
OpenAPI spec version: 2.0.0
Contact: support@ultracart.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and py... | 111,710 | 32,033 |
import os
import sys
import json
import shutil
import ipfsapi
import base64
import datetime
import maya
from twisted.logger import globalLogPublisher
from umbral.keys import UmbralPublicKey
### NuCypher ###
from nucypher.characters.lawful import Alice, Bob, Ursula
from nucypher.config.characters import ... | 7,753 | 2,518 |
#!/usr/bin/env python
# Copyright (c) 2004-2006 ActiveState Software Inc.
#
# Contributors:
# Trent Mick (TrentM@ActiveState.com)
"""
pythoncile - a Code Intelligence Language Engine for the Python language
Module Usage:
from pythoncile import scan
mtime = os.stat("foo.py")[stat.ST_MTIME]
... | 70,114 | 19,840 |
import numpy as np
class perceptron(object):
#eta learning rata
#n_iter times
def __init__(self,eta,n_iter):
self.eta=eta
self.n_iter=n_iter
def fit(self,x,y):
'''
x=ndarray(n_samples,n_features),training data
y=ndarray(n_samples),labels
returns
se... | 2,092 | 846 |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 2,552 | 757 |
import base64
import dataclasses
import gzip
import json
from collections import defaultdict
from typing import DefaultDict, Dict, Generator, List, Optional
from sentry_sdk.api import capture_exception, capture_message
from posthog.models import utils
Event = Dict
SnapshotData = Dict
@dataclasses.dataclass
class P... | 6,990 | 2,254 |
#!/usr/bin/env python3
"""
Generate the numeric limits for a given radix.
This is used for the fast-path algorithms, to calculate the
maximum number of digits or exponent bits that can be exactly
represented as a native value.
"""
import math
def is_pow2(value):
'''Calculate if a value is a power of 2.'''
... | 3,142 | 1,049 |
"""Django command for rebuilding cohort statistics after import."""
from django.core.management.base import BaseCommand
from django.db import transaction
from ...tasks import refresh_variants_smallvariantsummary
import variants.models as models
class Command(BaseCommand):
"""Implementation of rebuilding variant... | 1,077 | 278 |
# Incorrect Regex "https://www.hackerrank.com/challenges/incorrect-regex/problem"
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
for i in range(int(input())):
try:
re.compile(input())
print("True")
except ValueError:
print("False")
| 299 | 94 |
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
from api.views import category_list, category_detail, CategoryListAPIView, CategoryDetailAPIView, \
ProductListAPIView, ProductDetailAPIView
urlpatterns = [
# path('categories/', category_list),
# path('categories/<int:cat... | 634 | 196 |
"""
BEHAVIOR demo batch analysis script
"""
import argparse
import json
import logging
import os
from pathlib import Path
import pandas as pd
import igibson
from igibson.examples.learning.demo_replaying_example import replay_demo
def replay_demo_batch(
demo_dir,
demo_manifest,
out_dir,
get_callbacks... | 6,340 | 1,836 |
from Tkinter import *
from Tkinter import filedialog, simpledialog
from Tkinter import messagebox
from editor.settings import backgroundcolor as bc
from editor.settings import forgroundcolor as fc
from editor.settings import back as b
from editor.settings import fore as f
from editor.settings import size
from editor.se... | 428 | 111 |
# Basic UDP Multicasting server built in python
import socket
import struct
def UDPReceiveMultiCast(group, port):
# Create UDP Socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', port))
mreq = stru... | 712 | 271 |
# -*- encoding: utf-8 -*-
"""
These tests are only here to check that running the test scripts do
not actually fails.
Important: If a script contains While loop that are cancelled by user,
it should not be tested here.
"""
from antlr4.error.Errors import ParseCancellationException
from pathlib import Path
from wiz... | 1,232 | 365 |
from celery.task import task
from time import sleep
@task()
def add(x, y):
return x + y;
@task()
def status(delay):
status.update_state(state='PROGRESS', meta={'description': 'starting timer'})
sleep(delay)
status.update_state(state='PROGRESS', meta={'description': 'after first sleep'})
sleep(dela... | 341 | 113 |
import random
import MySQLdb
import requests
# ! -*- encoding:utf-8 -*-
import requests
# 要访问的目标页面
targetUrl = "https://blog.csdn.net/wang978252321/article/details/95489446"
# targetUrl = "http://proxy.abuyun.com/switch-ip"
# targetUrl = "http://proxy.abuyun.com/current-ip"
# 代理服务器
proxyHost = "http-dyn.abuyun.com... | 824 | 382 |
"""
面试题37:序列化二叉树
题目:请实现两个函数,分别用来序列化和反序列化二叉树
例:
树:
1
/ \
2 3
/ / \
4 5 6
序列化:
[1, 2, 4, $, $, $, 3, 5, $, $, 6, $, $]
"""
from datstru import TreeNode
from datstru import list_to_treenode
def serialize(root):
"""
:param root:tree root
:return:pre-order val list
""... | 1,093 | 430 |
from setuptools import setup
setup(name='tornpsql',
version='2.1.5',
description="PostgreSQL handler for Tornado Web",
long_description="",
classifiers=["Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: Apache Software License",
"Pr... | 803 | 245 |
'# Copyright ' + str(datetime.datetime.now().year) + ' Thomas Battenfeld, Alexander Thomas, Johannes Köster.'
'# Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)'
'# This file may not be copied, modified, or distributed'
'# except according to those terms.
'
'# Copyright 2021 Thomas Ba... | 7,392 | 2,141 |
from ..base import BuildStage
from pathlib import Path
TPL = """\"\"\"
WSGI config for {0} project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
\"\"\"
import os
from django.core.ws... | 638 | 229 |
from aioresponses import aioresponses
from asynctest import TestCase
from asyncworker.testing import HttpClientContext
from baas.api import app
class TransferAPITest(TestCase):
async def test_health(self):
async with HttpClientContext(app) as client:
resp = await client.get("/health")
... | 399 | 113 |
from maneuvers.kit import *
from maneuvers.driving.arrive import Arrive
class FastRecovery(Maneuver):
def __init__(self, car: Car):
super().__init__(car)
self.turn = AerialTurn(car, look_at(vec3(0, 0, -1)))
self.landing = False
def step(self, dt):
self.turn.step(d... | 1,288 | 456 |
import sys
import re
argvs = list(sys.argv)
result = ''
dataSourceName=argvs[1]
name=argvs[2]
if not dataSourceName or not name:
return
path="/mobile/app/upload/"+name+"/WEB-INF/classes/spring/applicationContext-ibatis.xml"
with open(path) as file:
result = file.read()
result = re.sub('<bean\\s+id\\s*=\\s*"da... | 1,046 | 406 |
from .base import Base
from .user import User
from .game import Game
from .role import Role
| 96 | 30 |
#!/usr/bin/env python
import logging
import sys
import argparse
import boto3
import botocore.exceptions
LOG_FORMAT = '%(asctime)s %(filename)s:%(lineno)s[%(process)d]: %(levelname)s: %(message)s'
class ArgsParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
kwargs.setdefault(
... | 3,382 | 1,052 |
import cv2
import time
#print(cv2.__version__)
cascade_src = 'cars.xml'
video_src = 'v3.avi'
start_time = time.time()
cap = cv2.VideoCapture(video_src)
#framerate = cap.get(5)
car_cascade = cv2.CascadeClassifier(cascade_src)
i=0
while True:
i=i+1
ret, img = cap.read()
if (type(img) == type(None)):
... | 778 | 343 |
"""
Capstone Project. Code to run on the EV3 robot (NOT on a laptop).
Author: Your professors (for the framework)
and Michael Johnson.
Winter term, 2018-2019.
"""
import rosebot
import mqtt_remote_method_calls as com
import time
import shared_gui_delegate_on_robot as dingding
def main():
"""
This... | 985 | 316 |
'''
Author: Methusael Murmu
Module implementing parallel Camera I/O feed
'''
import cv2
from threading import Thread
class CameraFeedException(Exception):
def __init__(self, src, msg = None):
if msg is None:
msg = 'Unable to open camera devive: %d' % src
super(CameraFeedExcepti... | 1,276 | 364 |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 19:44:44 2018
@author: LALIT ARORA
"""
from __future__ import unicode_literals
import youtube_dl
import urllib.parse
from bs4 import BeautifulSoup
def check_internet():
try:
urllib.request.urlopen('http://216.58.192.142', timeout=1)
... | 2,250 | 834 |
import numpy as np
from typing import Any, Tuple, Dict
import logging
class NotDescentDirection(Exception):
pass
class ZeroDescentProduct(Exception):
pass
class ZeroUpdate(Exception):
pass
class Newton:
def __init__(self,
obj_func : Any,
gradient_func : Any,
reg_inv_hessi... | 4,561 | 1,436 |
import discord
import random
def filtering(message):
manage = "소환사님 🎀✨예쁜 말✨🎀을 사용해😡주세요~!😎😘"
return manage
def command():
embed = discord.Embed(title=f"명령어 모음", description="꿀벌봇은 현재 아래 기능들을 지원하고 있습니다!", color=0xf3bb76)
embed.set_thumbnail(url="https://mblogthumb-phinf.pstatic.net/MjAxODA1MTdfMjEx/M... | 2,993 | 2,341 |
#!/usr/bin/env python
"""
This module provides File.MgrtList data access object.
"""
from dbs.dao.Oracle.File.MgrtList import MgrtList as OraFileMgrtList
class MgrtList(OraFileMgrtList):
pass
| 202 | 79 |
#!/usr/bin/env python3
# Copyright © 2021 Helmholtz Centre Potsdam GFZ German Research Centre for Geosciences, Potsdam, Germany
#
# 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.ap... | 3,478 | 1,119 |
import warnings
import os
from importlib import import_module
packages = ['sklearn', 'nibabel', 'numpy',
'matplotlib', 'skbold', 'niwidgets', 'scipy']
warnings.filterwarnings("ignore")
for package in packages:
try:
import_module(package)
print('%s was succesfully installed!' % package... | 512 | 151 |
#decorators
def decorator(myfunc):
def wrapper(*args):
return myfunc(*args)
return wrapper
@decorator
def display():
print('display function')
@decorator
def info(name, age):
print('name is {} and age is {}'.format(name,age))
info('john', 23)
#hi = decorator(display)
#hi()
display() | 296 | 110 |
import pytest
from sqlalchemy.orm.exc import NoResultFound
from content_store.api.api import create_app
from content_store.api.config import TestingConfig
from content_store.api.models import ArticlePart
from content_store.api.repositories import ArticlePartRepository
from content_store.api.database import DB
@pytest... | 1,886 | 605 |
def connected_tree(n, edge_list):
current_edges = len(edge_list)
edges_needed = (n-1) - current_edges
return edges_needed
def main():
with open('datasets/rosalind_tree.txt') as input_file:
input_data = input_file.read().strip().split('\n')
n = int(input_data.pop(0))
edge_l... | 630 | 228 |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | 13,135 | 3,581 |
from flask import Flask
app = Flask('savedots')
app.config['DATABASE_FILE'] = 'savedots_DB.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///savedots_DB.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = "CHANGE_ME"
if __name__ == '__main__':
print("Please run main.py to start... | 342 | 131 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('painindex_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PainProfile',
fields... | 1,019 | 331 |
# Transfer functions and derivatives
# Note _all_ transfer functions and derivatives _must_ accept keyword arguments
# and handle the output keyword argument out=z correctly.
# Gary Bhumbra
import numpy as np
import scipy.special
#-------------------------------------------------------------------------------
"""
de... | 1,765 | 600 |
import application
import tkinter
import gui.main
import gui.tdocs_table
import os
import os.path
import server
import traceback
import parsing.html as html_parser
import parsing.excel as excel_parser
import parsing.outlook
import parsing.word as word_parser
import threading
import pythoncom
import tdoc
import datetime... | 28,267 | 8,766 |
# Copyright (c) 2014 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... | 1,997 | 628 |
import urwid
from console.app import app
from console.widgets.help import HelpDialog
class Pane(urwid.WidgetPlaceholder):
"""
A widget which allows for easy display of dialogs.
"""
def __init__(self, widget=urwid.SolidFill(' ')):
urwid.WidgetPlaceholder.__init__(self, widget)
self.wi... | 1,432 | 399 |
import json
import os
import shutil
from jinja2 import Template
from zstacklib.utils import http
from zstacklib.utils import jsonobject
from zstacklib.utils import linux
from zstacklib.utils import linux_v2
from zstacklib.utils import iptables
from zstacklib.utils import lock
from zstacklib.utils import log
from zstac... | 47,000 | 15,445 |
__version__ = '0.9.4'
default_app_config = 'ajaximage.apps.AjaxImageConfig'
| 76 | 31 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# 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... | 45,760 | 11,588 |
from django import template
from django.contrib.sites.models import Site
from django.conf import settings
from ..utils import string_to_dict, roundrobin
register = template.Library()
@register.tag
def opengraph_meta(parser, token):
try:
tag_name, properties = token.split_contents()
except ValueError:... | 1,857 | 537 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-17 13:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... | 11,974 | 4,468 |
import random
import config
from faker import Factory
fake = Factory.create()
class User:
def __init__(self):
self.username = fake.user_name()
self.email = fake.company_email()
self.firstName = fake.first_name()
self.lastName = fake.last_name()
self.dateOfBirth = fake.iso8601()
self.password... | 2,281 | 824 |
#------testing the trained model and ensemble weights on the test data to get the final accuracy
#importing required libraries and modules
import os
import sys
import cv2
import numpy as np
from preprocess import Preprocess
from data_split import Load
from conv_net import CNN
from ensemble import Ensemble
... | 1,764 | 688 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... | 23,152 | 6,722 |
from dynaconf import FlaskDynaconf
from flask import Flask
def create_app(**config):
app = Flask(__name__)
FlaskDynaconf(app) # config managed by Dynaconf
app.config.load_extensions('EXTENSIONS') # Load extensions from settings.toml
app.config.update(config) # Override with passed config
return... | 539 | 174 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import torchvision.models as models
import torch.nn as nn
def get_model_from_name(model_name=None, image_size=None, num_classes=None, pretrained=True):
if model_name == 'resnet18':
model = models.resnet18(pretrained=pretrained)
in_features = model.fc.i... | 493 | 171 |
from collections import Counter
if __name__ == '__main__':
tc = int(input())
while tc > 0:
x = int(input())
balls = list(map(int, input().split()))
count = Counter(balls)
balls = list(filter((x).__ne__, balls))
if balls[0] == count[balls[0]]:
print("YES")
... | 371 | 124 |
from skimage import color
import numpy as np
colors = [
("base03", (10., +00., -05.)),
("base02", (15., +00., -05.)),
("base01", (45., -01., -05.)),
("base00", (50., -01., -05.)),
("base0", (60., -01., -02.)),
("base1", (65., -01., -02.)),
("base2", (92., -00., +02.)),
... | 1,502 | 661 |
import unittest
import numpy as np
import pandas as pd
import scipy.sparse
import smurff
verbose = 0
class TestPredictSession(unittest.TestCase):
# Python 2.7 @unittest.skip fix
__name__ = "TestPredictSession"
def run_train_session(self):
Ydense = np.random.normal(size = (10, 20)).reshape((10,20... | 2,890 | 1,085 |
"""Plots GridRad domains.
Specifically, plots number of convective days with GridRad data at each grid
point.
"""
import os.path
import argparse
import numpy
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot
from mpl_toolkits.basemap import Basemap
from gewittergefahr.gg_io import gridrad_io
from ... | 16,055 | 6,000 |
"""add task pending state
Revision ID: 30241b33d849
Revises: cd404ed93cc0
Create Date: 2021-01-07 14:39:43.251123
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '30241b33d849'
down_revision = 'cd404ed93cc0'
branch_labels = None
depends_on = None
def upgrade()... | 1,181 | 403 |
import random
import matplotlib.pyplot as plt
import gym
# from agents.actor_critic_agents.A2C import A2C
# from agents.actor_critic_agents.A3C import A3C
# from agents.actor_critic_agents.SAC import SAC
from agents.actor_critic_agents.SAC_Discrete import SAC_Discrete
# from agents.DQN_agents.DQN_HER import DQN_HER
#... | 4,932 | 1,852 |
import os, argparse, torch, math, time, random
from os.path import join, isfile
import torch.nn.functional as F
from torch.optim import SGD
from torch.distributions import Beta
from tensorboardX import SummaryWriter
import torchvision
import modified_vgg
from dataloader import dataloader1
import dataloader
from utils ... | 13,812 | 4,562 |
# coding=utf-8
import commands
import multiprocessing
import os
import re
import gensim
import numpy as np
import tensorflow as tf
import tflearn
from sklearn import metrics
from tflearn.data_utils import to_categorical
from tflearn.layers.conv import conv_1d, global_max_pool
from tflearn.layers.core import input_data... | 4,138 | 1,656 |
import pandas as pd
df = pd.read_csv('data.csv') # read the data
print(df)
def median(list_vales):
n_num = list_vales
n = len(n_num)
n_num.sort()
if n % 2 == 0:
median1 = n_num[n // 2]
median2 = n_num[n // 2 - 1]
median = (median1 + median2) / 2
else:
median = n_n... | 2,433 | 825 |
from skimage.draw import line as sk_line
from skimage.draw import circle_perimeter as sk_circle_perimeter
from RGBMatrixEmulator.graphics.color import Color
from RGBMatrixEmulator.graphics.font import Font
def DrawText(canvas, font, x, y, color, text):
# Early return for empty string prevents bugs in bdfparser l... | 2,408 | 773 |
#
# Copyright © 2021 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.
#
# SPDX-License-Identifier: NASA-1.3
#
"""Generate a grid of pointings on the sk... | 1,291 | 419 |
#!/usr/bin/env python
#---------------------------------#
#- Fibonacci Lookup Table -#
#---------------------------------#
fib_table = {0:0, 1:1, 2:1, 3:2}
#---------------------------------#
#- Compute Fibonacci Value -#
#---------------------------------#
def Fibonacci( F ):
# Check exit
... | 1,475 | 505 |
"""widget for pseudo inmport"""
import io
import os
import ipywidgets as ipw
import traitlets
from aiida import orm
from aiida.common import NotExistent
from aiida.engine import ProcessState, submit
from aiida.orm import Node, ProcessNode, load_code
from aiida.plugins import DataFactory, WorkflowFactory
from aiida_sss... | 42,365 | 12,066 |