content stringlengths 5 1.05M |
|---|
import sys
def isInteresting(line):
listOfInterestingThings=["models","all sites","training site 3 done","sensitivity","exp4UNF"]
for x in listOfInterestingThings:
if x in line:return True
return False or line[:2]=="9 "
def main(argv):
classes=["deciduous","healthyfir","sickfir"]
mode=in... |
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, value):
_node = Node(value)
_node.next = self.head
self.head = _node
def detect_and_remove_loop(s... |
class node(object):
def __init__(self, value = None):
self.value = value
self.next = None
class Stack(object):
def __init__(self, value = None):
self.top = node(value)
def push(self, value):
n1 = node(value)
if self.top == None:
self.top = n1
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: The Soloist
# @Time: 2021-06-02 08:20:59
# @File: /main.py
# @Description:
import sys
import configparser
from pathlib import Path
from notion2md.export_manager import export_cli
work_path = Path(__file__).parent
ini_path = work_path / "config.ini"
try:
... |
# Copyright (c) 2012-2015. The Regents of the University of California (Regents)
# and Richard Plevin. See the file COPYRIGHT.txt for details.
import os
import numpy as np
from pygcam.matplotlibFix import plt
import pandas as pd
import seaborn as sns
from six import iteritems
from six.moves import xrange
from pygcam.... |
import pandas as pd
import yfinance as yf
#from tqdm import tqdm
from datetime import datetime
stockList = pd.read_csv('Stock_List.csv')
stockListLen = len(stockList)
def getStockHistory():
'''
Runs through a csv file with stock abreviations
to download the daily history of every stock in the file.
... |
import sublime
import sublime_plugin
import re
import sys
from collections import defaultdict
class SortTodoCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in [sublime.Region(0, self.view.size())]:
# Determine the current line ending setting, so we can rejoin the
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
class Delta(object):
'''Brief Diff'''
def __init__(self, repo, diff, patch):
self.repo = repo
self.diff = diff
self._patch = patch
self.old_sha = patch['old_sha']
self.new_sha = patch['new_sha']
se... |
def schnet_network(tensors):
""" Network function for
SchNet: https://doi.org/10.1063/1.5019779
TODO: Implement this
Args:
tensors: input data (nested tensor from dataset).
gamma (float): "width" of the radial basis.
miu_max (float): minimal distance of the radial basis.
... |
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from constents import (
SHORT_CHAR_LENGTH,
USERNAME_MIN_LENGTH,
MEDIUM_CHAR_LENGTH,
VERIFY_CODE_LENGTH,
)
USER_MODEL = get_user_model()
class LoginFormSerializ... |
"""
Copyright (c) 2020 Intel Corporation
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 writin... |
import random
from collections import deque
import numpy as np
import tensorflow as tf
from agent.forward import Forward
from params import *
_EPSILON = 1e-6 # avoid nan
class Framework(object):
def __init__(self):
# placeholder
self.inputs = tf.placeholder(tf.float32, INPUT_SHAPE, 'input')
... |
import unittest
from unittest import mock
from unittest.mock import patch
import json
from requests import Session
from pvaw.wmi import decode_wmi, get_wmis, WMIInfo
class TestWMI(unittest.TestCase):
TEST_3_DIGIT_WMI_DECODE_URL = (
"https://vpic.nhtsa.dot.gov/api/vehicles/DecodeWMI/1FD?format=json"
)
... |
"""
Rewrite engine to get disjuntive normal form of the rules
"""
from collections import OrderedDict
from functools import singledispatch
from itertools import chain, product
from experta.conditionalelement import AND, OR, NOT
from experta.fieldconstraint import ORFC, NOTFC, ANDFC
from experta.rule import Rule
from e... |
vowels = set('AEIOU')
stuart = kevin = 0
word = input()
for i, c in enumerate(word):
if c in vowels:
kevin += len(word) - i
else:
stuart += len(word) - i
if stuart > kevin:
print('Stuart', stuart)
elif kevin > stuart:
print('Kevin', kevin)
else:
print('Draw') |
from dagster import build_assets_job
from hacker_news_assets.assets.comment_stories import comment_stories
from hacker_news_assets.assets.items import comments, stories
from hacker_news_assets.assets.recommender_model import component_top_stories, recommender_model
from hacker_news_assets.assets.user_story_matrix impor... |
# -*- coding: utf-8 -*-
"""
:mod:`papy.core`
================
This module provides classes and functions to construct and run a **PaPy**
pipeline.
"""
#
from types import FunctionType
from inspect import isbuiltin, getsource
from itertools import izip, imap, chain, repeat, tee
from threading import Thread, Event, L... |
# -*- coding: utf-8 -*-
import numpy as np
from keras.models import load_model
from Config import *
from DataProcessor import DataProcessor
class CNNPredictor:
def __init__(self, model_path=None):
self.config = DataConfig()
self.dp = DataProcessor(self.config)
self.num_channels = self.conf... |
#!/usr/bin/env python
import app_config
import calendar
import unittest
from app import utils
from fabfile import data
from models import models
from peewee import *
from time import time
from datetime import datetime
class ResultsLoadingTestCase(unittest.TestCase):
"""
Test bootstrapping postgres database
... |
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(12, 4))
# Sample from the latent variable prior
normal_data = np.random.normal(size=(x_train.shape[0], 2))
ax0.scatter(normal_data[:, 0], normal_data[:, 1], alpha=0.1)
ax0.set_title("Samples from the latent prior $p(z)$")
ax0.set_xlim(-4, 4)
ax0.set_ylim(-4, 4)
# ... |
import os
import numpy as np
import torch
import torchvision
import resnet as res
import time
from PIL import Image
from load import dataLoader, dataAugmentation
class modelEval():
def __init__(self, model, state_dict):
self.model = model
self.weight = state_dict
self.device = torch.device("... |
# vim: set fileencoding=utf-8 filetype=python :
"""
Loads all views in Python's default sort order.
"""
from django.core.management.base import BaseCommand
# noinspection PyProtectedMember
from pygipo.utils import runviews
class Command(BaseCommand):
help = 'Load views defined in <app_dir>/migrations/views/*.sq... |
import pytest
from pawapp import helpers
@pytest.mark.parametrize('data,from_fields,to_fields,expected', [
({'id': 1}, ['id'], ['to_id'], {'to_id': 1}),
({'id': 2}, ['ids'], ['to_ids'], {'id': 2}),
(
{'id': 1, 'field_1': 1, 'field_2': '2', 'field_3': [1, 2, 3]},
['id', 'field_1', 'field_3... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
class InputTransformNet(nn.Module):
def __init__(self):
super(InputTransformNet, self).__init__()
self.relu = nn.ReLU()
self.conv1 = nn.Conv1d(3, 64, 1)
self.bn1 = nn.BatchNorm1d(64)
... |
def split_string(string):
# Split the string based on space delimiter
list_string = string.split(' ')
return list_string
def join_string(list_string):
# Join the string based on '-' delimiter
string = '-'.join(list_string)
return string
# Driver Function
if __n... |
#!/usr/bin/python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import time
import unittest
from ui_perf_test_utils import UIPerfTestUtils
class TestUIPerfUtils(unittest.TestCase):
"""Test UIPe... |
"""Const for Tests."""
TEST_USER = "testuser"
TEST_PASS = "testpass"
TEST_HOST = "example.com"
TEST_PORT = 7728 |
from django.test import TestCase, RequestFactory
from django.contrib.auth.models import User
from django.conf import settings
from django.core.files.storage import default_storage
from rest_framework.authtoken.models import Token
from rest_framework.test import force_authenticate
from rest_framework.test import APIReq... |
import pytest
@pytest.fixture
def runner(app):
return app.test_cli_runner()
|
# Created by yingwen at 2019-03-10
import numpy as np
from copy import deepcopy
from collections import defaultdict
from functools import partial
from malib.agents.tabular.q_learning.base_q import QAgent
from malib.agents.tabular.utils import softmax
class RRQAgent(QAgent):
def __init__(self, id_, action_num, en... |
# -*- coding: utf-8 -*-
from datasetxy import DatasetXY as dd
from initialization import Initialization as ii
from activation import Activation as aa
from cost import Cost as cc
from regularization import Regularization as rr
from training import Training as tt
... |
# Copyright (c) 2016 Alex Parmentier, Andrew Hankinson
# 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, me... |
from flask import Flask, redirect, url_for, render_template, \
request, make_response, Response, Markup, Blueprint, current_app, g
blueprint_game = Blueprint("game", __name__,
template_folder="templates")
@blueprint_game.before_request
def before_request():
g.app = current_app._main
@blueprint_game.r... |
#Copyright (c) 2009, Walter Bender
#Copyright (c) 2009, Michele Pratusevich
#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,... |
# -*- coding: UTF-8 -*-
import json
import re
from TamTamBot.utils.utils import get_param_value, str_to_int, get_md5_hash_str
from openapi_client import Update, MessageCallbackUpdate, MessageLinkType, NewMessageLink, BotStartedUpdate, MessageCreatedUpdate, ChatType, User, Message, Recipient, Callback
class UpdateCmn... |
import smbus
import logging
import time
class Powerpi:
PORT = 1
ADDRESS = 0x6a #I2C address of the ups
#Refer to http://www.ti.com/lit/ds/symlink/bq25895.pdf for register maps
REG_WATCHDOG = 0x07
BYTE_WATCHDOG_STOP = 0b10001101 #Stop Watchdog timer
REG_SYSMIN = 0x03
BYTE_SYSMIN = 0b0... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import atexit
import time
import RPi.GPIO as GPIO
import spi
# assegurar que a função cleanup será chamada na saída do script
atexit.register(GPIO.cleanup)
# usar numeração lógica dos pinos
GPIO.setmode(GPIO.BCM)
DISPLAY = [17, 4, 9, 11, 7, 27, 22, 10]
SPI_CLK = 18
SPI... |
from .mixins import APIEndpointMixin
from django.urls import reverse
class BuildsEndpointTests(APIEndpointMixin):
def test_projects_builds_list(self):
self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token.key}')
response = self.client.get(
reverse(
'projects-b... |
from datetime import date, time, timedelta
from forty.views.status import StatusView
from forty.actions import WorkOptions
from forty.tools import ActionsBuilder as A
from forty.controllers import StatusController
from forty.managers.project_manager import Config
from ..controller_test_case import ControllerTestCase
... |
import datetime
import pytz
from django.core.paginator import Paginator
from django.db.models import Q, F, QuerySet
from bsmodels.models import Contest, ContestProblem, Problem, Registration
from utils.auxiliary import ret_response
from utils.decorators import require_nothing
@require_nothing
def contest_list(reque... |
# Copyright 2015 Red Hat, 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 o... |
"""
validataclass
Copyright (c) 2021, binary butterfly GmbH and contributors
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""
import pytest
from validataclass.exceptions import RequiredValueError, InvalidTypeError, StringInvalidLengthError, InvalidUrlError
from va... |
import sys
from loguru import logger
# sys.stdout.reconfigure(encoding="utf-8")
class Format:
time = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green>"
level = "<level>{level: <8}</level>"
module = "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>"
message = "<level>{message}</level>"
LEV... |
'''
@copyright: 2022 - Symas Corporation
'''
from .config import Config
from .validator import Validator
from .date import Date
from .day import Day
from .lockdate import LockDate
from .time import Time
from .timeout import TimeOut
from .current_date_time import CurrentDateTime
from .global_ids import ACTV_FAILED_DAY,... |
#!/usr/bin/env python
import os
import re
import sys
import time
import json
import cPickle as pickle
import pprint
import logging
import webapp2
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.ext.webapp import template
import datetime
# Set the current latest term... |
import enum
import itertools
import platform
import random
import datetime as dt
import statistics
import sys
from dataclasses import dataclass, asdict, field
from pathlib import Path
from typing import List, Optional
import pdfkit
from jinja2 import Template
if platform.system() == "Windows":
# ugh. Sorry. I ne... |
from .Integer import ZZ
from .QuotientRing import QuotientRing
from .polynomial_uni import UnivariatePolynomialRing
from .polynomial_multi import BivariatePolynomialRing
|
class Solution(object):
def oddEvenJumps(self, A):
N = len(A)
def make(B):
ans = [None] * N
stack = [] # invariant: stack is decreasing
for i in B:
while stack and i > stack[-1]:
ans[stack.pop()] = i
stack.appe... |
# Generated by Django 2.0.7 on 2018-08-14 22:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0008_company_owner'),
]
operations = [
migrations.AlterModelOptions(
name='client',
options={'verbose_name': ... |
from .users import UserViewSet |
import collections
import re
import numpy as np
TOKEN_RE = re.compile(r"[\w\d]+")
def tokenize_text_simple_regex(txt, min_token_size=4):
txt = txt.lower()
all_tokens = TOKEN_RE.findall(txt)
return [token for token in all_tokens if len(token) >= min_token_size]
def character_tokenize(txt):
return l... |
import numpy as np
from rlkit.torch import pytorch_util as ptu
from rorlkit.torch.data import MotionGraphDataset
from rorlkit.torch.data_management.rosbag_data import batch_features_to_pose_arrays, get_identity_feature
class MotionGCNEvaluator(object):
def __init__(
self,
model,
... |
#
# PySNMP MIB module CISCOSB-SpecialBpdu-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-SpecialBpdu-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
import sys
import extraction.ethereum as eth2
import time
import argparse
def main():
sys.path.append('/home/larte/projects/data_engineering_experiments_v1')
parser = argparse.ArgumentParser()
parser.add_argument("--bucket_name", help="define bucket name", type=str)
parser.add_argument("--object_f... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2019 Mobvoi 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... |
from math import pi
import numpy as np
from aleph.consts import *
from reamber.algorithms.generate.sv.generators.svOsuMeasureLineMD import svOsuMeasureLineMD, SvOsuMeasureLineEvent
from reamber.osu.OsuMap import OsuMap
SIN_CURVE = 0.2 # Curvature of sine < 0.5 for fast init, > 0.5 for fast out never negative
POW_CU... |
"""Support for Satel Integra devices."""
import logging
import voluptuous as vol
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.discovery import async_load_platform
from homeassistant... |
from iroha import IrohaCrypto
import sys
import json
import os
from copy import deepcopy
config_docker = {
"block_store_path" : "/tmp/block_store/",
"torii_port" : 50051,
"internal_port" : 10001,
"max_proposal_size" : 10,
"proposal_delay" : 10,
"vote_delay" : 1,
"mst_enable" : False,
"mst_expiration_ti... |
import cv2
import os
import json
from PIL import Image
def get_content_type(file):
return file.content_type.split("/")
def create_directories(directory_list):
for path in directory_list:
create_directory(path)
def create_directory(path):
if not os.path.exists(path):
os.makedirs(path)
... |
'''
Extraigo las preguntas en for de texto, ahora, como le quito los dos
patrones que trae?
<p><strong>
</strong> </p>
todos = soup.find_all('p')
print(type(todos))
# <class 'bs4.element.ResultSet'>
uno = soup.find('p')
print(type(uno))
# <class 'bs4.element.Tag'>
print(todos)
'''
... |
#
# 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 appl... |
import numpy as np
from django.db import models
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _, ugettext
from base.models import Stock, RunBase
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
... |
import sys
from collections import namedtuple
from random import randint
import os
from codecs import getdecoder
from codecs import getencoder
import asn1
from sympy import invert
from hashlib import sha256
Point = namedtuple("Point", "x y")
EllipticCurve = namedtuple("EllipticCurve", "a b")
Origin = None
... |
#!/usr/bin/env pybricks-micropython
from pybricks.messaging import BluetoothMailboxServer, TextMailbox
from pybricks.tools import wait
from monitor import SpikeMonitor
# Create monitor object and initialize mechanisms
spike = SpikeMonitor()
# Start server
server = BluetoothMailboxServer()
# Keep accepting connecti... |
"""
T: O(N)
S: O(N)
Do as the description says.
"""
class Solution:
def toHexspeak(self, num: str) -> str:
allowed_chars = {"A", "B", "C", "D", "E", "F", "I", "O"}
hex_representation = hex(int(num))[2:].upper()
result = hex_representation.replace('0', 'O').replace('1', 'I')
retur... |
def find_common_element(a, b, c):
i = j = k = 0
a_len = len(a) - 1
b_len = len(b) - 1
c_len = len(c) - 1
while i <= a_len and j <= b_len and k <= c_len:
max_element = max([a[i], b[j], c[k]])
while i < a_len and a[i] < max_element:
i += 1
while j < b_len and b[j] <... |
from enum import Enum
from flask import Flask, redirect, request
import urllib.parse as urlparse
from common.course_config import get_course
from common.db import connect_db
from common.html import error, html, make_row
from common.oauth_client import create_oauth_client, is_enrolled, is_staff, login
from common.rpc... |
# The array type can hold homogeneous data types and operate
# on them more efficiently while using less memory
from array import array
# TODO: Create an array of integer numbers
arr1 = array('i', [2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
# TODO: Add additional items to the array
# TODO: iterate over the array content... |
# -*- coding:utf-8 -*-
import weakref
class AbstractDescriptor(object):
def __init__(self):
self._resolve_cache = weakref.WeakKeyDictionary()
def _resolve_name(self, owner):
try:
return self._resolve_cache[owner]
except KeyError:
pass
for name in dir(... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-01 04:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('person', '0028_auto_20160229_2252'),
]
operations = [
migrations.AddField(
... |
import PyTCI.tci
import PyTCI.audio
|
import os
# Authenticated user
USERNAME = os.getenv('TWITTER_USERNAME').lower()
MENTION_EXPIRY_TIME_IN_SECONDS = 60
MENTION_CHECK_INTERVAL_IN_SECONDS = 15
LAST_MENTION_FILE = 'last_mention'
FONTS_DIR = 'fonts/'
QUOTES_DIR = 'quotes/'
IMAGES_DIR = 'images/'
IMAGE_STORE_FILE=f'{IMAGES_DIR}store.json'
IMAGE_EXT = '.jpg... |
from flask import render_template,request,redirect,url_for
from ..requests import getSources, get_articles
from ..models import Source
from . import main
@main.route('/')
def index():
news = getSources()
title = 'Highlights'
return render_template('index.html',title = title, news = news)
@main.rou... |
import validatish
import formish
import schemaish
import unittest
class TestFormData(unittest.TestCase):
"""Build a Simple Form and test that it doesn't raise exceptions on build and that the methods/properties are as expected"""
schema_nested = schemaish.Structure([
("one", schemaish.Structure([
... |
# flake8: noqa
"""
Copyright 2020 - Present Okta, Inc.
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 ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
from rest_framework import serializers
from .models import Warehouse, Product, Location, LocationQuantity
class WarehouseSerializer(serializers.HyperlinkedModelSerializer):
warehouse_locations = serializers.HyperlinkedRelatedField(
many=True, read_only=True, view_name="location-detail"
)
class Me... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: common.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf impo... |
# terrascript/resource/sacloud/sakuracloud.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:26:06 UTC)
import terrascript
class sakuracloud_archive(terrascript.Resource):
pass
class sakuracloud_archive_share(terrascript.Resource):
pass
class sakuracloud_auto_backup(terrascript.Resource):
... |
import argparse
import teuthology.worker
def main():
teuthology.worker.main(parse_args())
def parse_args():
parser = argparse.ArgumentParser(description="""
Grab jobs from a beanstalk queue and run the teuthology tests they
describe. One job is run at a time.
""")
parser.add_argument(
'-v', '--... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 7 09:02:56 2019
@author: helpthx
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy import ndimage
from pylab import imread,imshow,figure,show,subplot
from numpy import reshape,uint8,flipud
from sklearn.cluster import Min... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.errors import AnsibleFilterError
from ansible.module_utils.six import iteritems, string_types
from numbers import Number
def environment(parameters, exclude=[]):
if not isinstance(parameters, dict):
raise ... |
import io
import os
import sys
import copy
import json
import time
import logging
import datetime
import platform
from collections import OrderedDict
from bdbag import bdbag_api as bdb
from deriva.core import get_credential, format_credential, urlquote, format_exception, DEFAULT_SESSION_CONFIG, \
__version__ as VER... |
# -*- coding: utf-8 -*-
import mock
from django import http
from django import test
from django_cradmin import cradmin_testhelpers
from model_mommy import mommy
from devilry.apps.core import models as core_models
from devilry.devilry_dbcache import customsql
from devilry.devilry_deadlinemanagement.views import multi... |
#!/usr/bin/env python
"""
Prepares DB for loaddata command (must perform some cleanup first)
"""
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "openwisp2.settings")
django.setup()
from django.contrib.auth.models import ContentType
from django.contrib.auth.models import Permission
from openwis... |
# Importamos las librerías necesarias
import sys
import os
import time
import shutil
import pandas as pd
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
# Cargamos los archivos de entranamiento
training_data = 'data/train.csv'
include = ['Age', 'Sex', 'Embarked', 'Survived']
de... |
username = ""
password = ""
client_id = ""
client_secret = ""
user_agent = "Autoremoval Bot"
subreddit = ""
reply = "Upvote this comment if you feel this submission is characteristic of our subreddit. Downvote this if you feel that it is not. If this comment's score falls below a certain number, this submission will be... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Description
Christopher J.C. Burges, Robert Ragno, and Quoc Viet Le. 2006.
Learning to Rank with Nonsmooth Cost Functions. In Proceedings of NIPS conference. 193–200.
"""
import torch
import torch.nn.functional as F
from ptranking.base.ranker import NeuralRanker
from ... |
from django.db import models
from .helper import bulk_update
class BulkUpdateQuerySet(models.QuerySet):
def bulk_update(self, objs, update_fields=None,
exclude_fields=None, batch_size=None):
self._for_write = True
using = self.db
return bulk_update(
objs,... |
class Solution:
def maxKilledEnemies(self, grid: List[List[str]]) -> int:
n = len(grid)
m = len(grid[0])
count_grid = [[0]*m for _ in range(n)]
for i in range(n):
start = 0
count = 0
for j in range(m):
if grid[i][j] == "E":
... |
#!/usr/bin/env python3
# coding: utf8
class MyClass: pass
class MyClass1:
cls_attr = 1
|
# Add checker to close the program when MW2 closes after running.
import configparser
import os
import pymem
import pymem.process
import sys
import time
from win32gui import GetWindowText, GetForegroundWindow
# Memory addresses used in MW2 v1.2.211
FOV_ADDRESS = (0x0639322C) # float
FPS_ADDRESS = (0x638152C) # int... |
#!/usr/bin/env python
import codecs
from datetime import datetime
import gspread
import json
from oauth2client.client import GoogleCredentials
import os
from pymongo import MongoClient
import re
from dateutil import parser
projects_SHEET_KEY = '1mabXCaQwt8pxq45xsqosEAUqZ-F6csD3r771DxE9fJE'
MONGODB_URL = os.getenv('MO... |
"""nornir_scrapli.tasks.netconf"""
|
import torch
from .library_functions import AffineFeatureSelectionFunction
DEFAULT_BBALL_FEATURE_SUBSETS = {
"ball" : torch.LongTensor([0, 1]),
"offense" : torch.LongTensor(list(range(2,12))),
"defense" : torch.LongTensor(list(range(12,22))),
'offense_dist2ball': torch.LongTensor(list(range(2... |
from django.apps import AppConfig
from django.db.models.signals import post_migrate
from django.utils.translation import ugettext_lazy as _
from .management import create_default_site
class SitesConfig(AppConfig):
name = 'django.contrib.sites'
verbose_name = _("Sites")
def ready(self):
... |
import os
import signal
import tempfile
from argparse import ArgumentParser, RawTextHelpFormatter
from firexapp.plugins import load_plugin_modules, cdl2list
from firexapp.submit.console import setup_console_logging
from firexkit.permissions import DEFAULT_UMASK
logger = setup_console_logging(__name__)
def main():
... |
"""plotlib.py: Module is used to implement various plotting functions"""
__author__ = "Chakraborty, S."
__copyright__ = "Copyright 2021, Chakraborty"
__credits__ = []
__license__ = "MIT"
__version__ = "1.0."
__maintainer__ = "Chakraborty, S."
__email__ = "shibaji7@vt.edu"
__status__ = "Research"
import matplotlib as ... |
from __future__ import print_function, absolute_import, division
import KratosMultiphysics
import KratosMultiphysics.ConvectionDiffusionApplication as ConvectionDiffusionApplication
from KratosMultiphysics.ConvectionDiffusionApplication import convection_diffusion_analysis
import KratosMultiphysics.KratosUnittest as K... |
import networkx as nx
import eigenvector
from p9base import *
import math
EIGENVECTOR_CENTRALITY = 1
EIGENVECTOR_CENTRALITY_REV = 2
EDGE_CENTRALITY = 3
class Graph(object):
def __init__(self):
self.nodeorder = None
self.edgeorder = None
def Order(self):
return self.graph.order()
def Size(self):
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.