text
stringlengths
1
927k
#!/usr/bin/python3 # FILE: robot2.py # PURPOSE: Test reading distance sensor and ultrasonic sensor from easygopigo3 import EasyGoPiGo3 import time import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(funcName)s: %(message)s') DIODE_DROP = 0.7 ULTRASONIC_CORRECTION_AT_100mm = 17.0 # mm ToF_C...
import streamlit as st import pandas as pd import yaml import duolingo import seaborn as sns import matplotlib.pyplot as plt import matplotlib.font_manager from datetime import timezone, timedelta matplotlib.rcParams['font.family'] = ['Source Han Sans CN'] with open("duo_credentials.yaml", 'r') as stream: creds = ...
# -*- coding: utf-8 -*- """ Functions used to format and clean any intermediate results loaded in or returned by a bigfish method. """ import numpy as np from scipy import ndimage as ndi from .utils import check_array, check_parameter, get_offset_value from skimage.measure import regionprops, find_contours from ski...
from .waymo import WaymoDataset from .waymo_common import * __all__ = ["WaymoDataset"]
#!/usr/bin/env python import Bio from Bio.KEGG import REST from Bio.KEGG import Enzyme import re from Bio.KEGG import Compound import gzip import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns def create_enzyme_df(path_to_file): """ input:path_to...
import pygame import psutil import cpuinfo import socket import time import nmap from cpuinfo import get_cpu_info red = (200,0,0) white = (210,214,217) blue = (0,0,200) grey = (105,105,105) black = (0,0,0) largura_tela, altura_tela = 1024,760 pygame.init() pygame.font.init() font = pygame.font.Font(None, 32) uso = ps...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.item import Item, Field class CrawlerItem(scrapy.Item): url = Field() html_title = Field() html_h1 = Field() html_h2 = Field...
class Table: context = '' fields = () columns = () sortable = () types = () def context_dict(self): return {field: {'field': field, 'column': col, 'sortable': sort, 'type': type_} for field, col, sor...
from dataclasses import dataclass from moxom.compiler.lexer import OperatorToken, IdentifierToken, AtomTokens from typing import Union, Optional from .cstparser import CstNode, Expr import ast from moxom.compiler.operators import operator_dict, AssignOperator, AndOperator, ThenOperator @dataclass class AtomNode: ...
import numpy from sklearn.metrics import confusion_matrix def load_data(): train_labels = [] with open('digitdata/traininglabels', 'rb') as f: for i, line in enumerate(f): train_labels.append(int(line)) train_labels = numpy.array(train_labels, dtype=int) train_x = numpy.zeros((trai...
# Copyright 2014 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...
import json from pprint import pprint, pformat from dateutil.parser import parse as parsetimestamp SILENCE_STATUSES = [ "CREATE_COMPLETE", "CREATE_IN_PROGRESS", "DELETE_COMPLETE", "DELETE_IN_PROGRESS", "REVIEW_IN_PROGRESS", "ROLLBACK_COMPLETE", "ROLLBACK_IN_PRO...
# RUN: %PYTHON %s import absl.testing import numpy import test_util import urllib.request from PIL import Image model_path = "https://tfhub.dev/tensorflow/lite-model/mobilenet_v2_1.0_224_quantized/1/default/1?lite-format=tflite" class MobilenetQuantTest(test_util.TFLiteModelTest): def __init__(self, *args, **kwar...
#!/usr/bin/env python # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
from jsonrpc import ServiceProxy import sys import string import getpass # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:9634") e...
import numpy as np def relu(input): '''Define your relu activation function here''' # Calculate the value for the output of the relu function: output output = max(input, 0) # Return the value just calculated return(output) input_data = np.array([3,5]) # Calculate node 0 value: node_0_output ...
# Copyright (C) 2019 Intel Corporation. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # import scenario_cfg_lib import launch_cfg_lib import common import pt def is_nuc_whl_linux(names, vmid): uos_type = names['uos_types'][vmid] board_name = names['board_name'] if launch_cfg_lib.is_linu...
import math from typing import List, Union, Tuple import torch import torch.nn as nn from astro_dynamo.snap import SnapShot from .snaptools import align_bar def _symmetrize_matrix(x, dim): """Symmetrize a tensor along dimension dim""" return (x + x.flip(dims=[dim])) / 2 class DynamicalModel(nn.Module): ...
import torch from node2vec import Node2Vec as Node2Vec_ from .brain_data import BrainData from torch_geometric.data import Data from networkx.convert_matrix import from_numpy_matrix from .utils import binning, LDP import networkx as nx from .base_transform import BaseTransform from numpy import linalg as LA import nump...
# Copyright 2018 The TensorFlow Probability 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 applicable law o...
# -*- coding: utf-8 -*- ''' Copyright (c) 2019 Colin Curtain 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, mer...
from flask import Flask app = Flask(__name__) @app.route("/") def sample_program(): return "This is sample flask program"
# --------- # Imports # --------- import sys import os import stat import time import struct import re try: import grp import pwd except ImportError: grp = pwd = None # --------------------------------------------------------- # tar constants # --------------------------------------------------------- N...
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2016 Dean Jackson <deanishe@deanishe.net> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2016-03-13 # """searchio <command> [<options>] [<args>...] Alfred 3 workflow to provide search completion suggestions from various search engines i...
from django.urls import path from . import views urlpatterns = [ path('', views.Home, name="home"), path('portfolio', views.portfolio, name="portfolio"), path('news', views.news, name="new"), path('contacts', views.contacts, name="contacts"), path('about', views.about, name="about"), path('prod...
# -*- coding: utf-8 -*- from django import template register = template.Library() @register.filter(name='times') def times(value, arg): return value * int(arg)
import os from flask import Flask, jsonify from scraper import Scraper app = Flask(__name__) scraper = Scraper() @app.route("/") def store_playstation(): return jsonify(scraper.store_playstation("https://store.playstation.com/ja-jp/category/1b6c3e7d-4445-4cef-a046-efd94a1085b7/")) if __name__ == "__main__": ...
import yfinance import pandas as pd import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm def _simulate_returns(historical_returns,forecast_days): return historical_returns.sample(n = forecast_days, replace = True).reset_index(drop = True) def simulate_modifie...
def extractWriterupdatesCom(item): ''' Parser for 'writerupdates.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loit...
# -*- coding: utf-8 -*- from zvt.contract import IntervalLevel from zvt.factors.target_selector import TargetSelector from zvt.factors.ma.ma_factor import CrossMaFactor from zvt.factors import BullFactor from ..context import init_test_context init_test_context() class TechnicalSelector(TargetSelector): def init...
#!/usr/bin/python from capstone import * from unicorn import * import regress class MipsBranchDelay(regress.RegressTest): def runTest(self): md = Cs(CS_ARCH_MIPS, CS_MODE_MIPS32 + CS_MODE_LITTLE_ENDIAN) def disas(code, addr): for i in md.disasm(code, addr): print '0x%...
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import unicode_literals import docker import requests from dockerfile_parse import DockerfileParser from atomic_reactor.pl...
# !/usr/bin/env python # -*- coding:utf-8 -*- from bs4 import BeautifulSoup import urlparse import re class Parser(object): def _pre_test(self, url, soup): bad_links = {} if soup.title == "手机搜狐" and url != 'http://m.sohu.com': bad_links[url] = 404 # todo:坏链处理。。。 ...
from .inverted_residual import InvertedResidual, InvertedResidualV3 from .non_bottleneck_1d import non_bottleneck_1d from .dilated_bottleneck import DilatedBottleneck
from hashlib import sha256 from os import urandom from btcpy.structs.crypto import PublicKey, PrivateKey from btcpy.structs.transaction import MutableTransaction, TxOut from btcpy.structs.sig import P2pkhSolver from pypeerassets.networks import net_query class Kutil: def __init__(self, network: str, privkey: b...
# MIT License # # Copyright (c) 2022 Ferhat Geçdoğan All Rights Reserved. # Distributed under the terms of the MIT License. # # # evalie - a toy evaluator using # shunting-yard algorithm. # ------ # github.com/ferhatgec/evalie # import math class evalie: def __init__(self): self.precedence = { ...
import os import pickle from .Utils import purify, staticPath def cacheIn(dir, name, data): """ Store given `data` under ./cache/dir/name.pickle file. Note that `dir` and `name` are "purified" before used! -dir: string of sub-directory to be created. Cache-file will be stored in it. It should...
"""" Program name : Website cloner author : https://github.com/codeperfectplus How to use : Check README.md """ import os import sys import requests from bs4 import BeautifulSoup class CloneWebsite: def __init__(self, website_name): self.website_name = website_name def crawl_website(sel...
# Copyright 2020 Google LLC. 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 a...
""" Filename: plot_ohc_drift.py Author: Damien Irving, irving.damien@gmail.com Description: Create a bar chart showing drift in ocean heat content and its thermal and barystatic components """ # Import general Python modules import sys import os import re import pdb import argparse import...
import tkinter as tk import threading from tkinter import scrolledtext from tkinter import messagebox ENCODING = 'utf-8' class GUI(threading.Thread): def __init__(self, client): super().__init__(daemon=False, target=self.run) self.font = ('Helvetica', 13) self.client = client self...
from sqlalchemy.orm.exc import NoResultFound from whoahqa.models import ( ClinicFactory, User, ) from whoahqa.constants import groups from whoahqa.constants import permissions as perms def get_request_user(request): user_id = request.authenticated_userid try: return User.get(User.id == user_...
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-11 01:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Goal', ...
from math import ceil def karatsuba(a,b): if a < 10 and b < 10: return a*b n = max(len(str(a)), len(str(b))) m = int(ceil(float(n)/2)) a1 = int(a // 10**m) a2 = int(a % (10**m)) b1 = int(b // 10**m) b2 = int(b % (10**m)) ...
from .oauth import BaseOAuth1 class WithingsOAuth(BaseOAuth1): name = 'withings' AUTHORIZATION_URL = 'https://oauth.withings.com/account/authorize' REQUEST_TOKEN_URL = 'https://oauth.withings.com/account/request_token' ACCESS_TOKEN_URL = 'https://oauth.withings.com/account/access_token' ID_KEY = '...
# # 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 # ...
"""Example: Find all servers per group""" import os from configparser import ConfigParser from cbw_api_toolbox.cbw_api import CBWApi CONF = ConfigParser() CONF.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'api.conf')) CLIENT = CBWApi(CONF.get('cyberwatch', 'url'), CONF.get('cyberwatch', 'api_ke...
# -*- coding: utf-8 -*- # 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...
""" This file offers the methods to automatically retrieve the graph Azotobacter vinelandii. The graph is automatically retrieved from the STRING repository. Report --------------------- At the time of rendering these methods (please see datetime below), the graph had the following characteristics: Datetime: 2021...
from django.conf.urls import url from movies import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='movies-index'), url(r'^name/$', views.NameSearchView.as_view(), name='movies-name-search'), url(r'^id/$', views.IDSearchView.as_view(), name='movies-id-search'), ]
try: import time FirstTime = time.time() import os import io import sys import time import glob import socket import locale import hashlib import tempfile import datetime import subprocess from ctypes import windll from urllib.request import urlopen try...
import lxml.html musicUrl= "http://books.toscrape.com/catalogue/category/books/music_14/index.html" doc = lxml.html.parse(musicUrl) #base element articles = doc.xpath("//*[@id='default']/div/div/div/div/section/div[2]/ol/li[1]/article")[0] #individual element inside base title = articles.xpath("//h3/a/text()") pri...
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #----------------------------------------------------------------...
from .utils import * from .funcs import * def test_unit(): storage = Storage() @op(storage) def f(x:int) -> int: return x + 1 @superop(storage) def f_twice(x:int) -> int: return f(f(x)) with run(storage, autocommit=True): f_twice(42) cg = storage.cal...
import pytest from src.conanbuilder.remote import Remote @pytest.fixture def remote(): return Remote("myName", "myUrl") def test_default_values(remote): assert remote.name == "myName" assert remote.url == "myUrl" assert remote.verify_ssl is True assert remote.priority == 0 assert remote.forc...
from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() # settings value @register.simple_tag def settings_value(name): defaults = { 'SITE_HEADER': '<b>Map</b>Ground', 'SITE_TITLE': 'MapGround' } if name in d...
import superimport import numpy as np import matplotlib.pyplot as plt import pyprobml_utils as pml import tensorflow as tf import tensorflow_datasets as tfds np.random.seed(0) ds, info = tfds.load('emnist', split='test', shuffle_files=False, with_info=True) # horribly slow print(info) plt.figure(figsize=(10, 10))...
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//h1[@itemprop='name']", 'price' : "//div[@class='div-new-price']/span[@class='new-price']", 'category' : "//span[@class='item']/a...
import numpy as np from sympy import * def interpolate_cubic(p1, p2, k_traj, t): ''' Computes a smooth cubic polynomail between 2 N-dimensional points Input: p1: Nx1 numpy array the first point p2: Nx1 numpy array the second point ...
from model.Sender import Sender from model.SenderType import SenderType import logging import math import numpy as np class NoobSender(Sender): def __init__(self, id, deliveryRate, debug=True): super().__init__(id, SenderType.Noob, deliveryRate=deliveryRate, debug=debug) def getNumberOfPacketsToCreat...
''' ----------------------------------------------------------------------- Additional Documentation Made by Zachary A Brader, Kieran Coito, Pedro Goncalves Mokarzel while attending University of Washington Bothell Made in 03/09/2020 Based on instruction in CSS 458, taught by professor Johnny Li...
__author__ = 'Danyang' import logging import sys class LoggerFactory(object): def getConsoleLogger(self, cls_name, level=logging.DEBUG): lgr = logging.getLogger(cls_name) lgr.setLevel(level) if not lgr.handlers: ch = logging.StreamHandler(sys.stdout) ch.setLevel(leve...
from datetime import datetime import datetime def yesterday(today=datetime.datetime.now()): yesterday = today - datetime.timedelta(days=1) yesterday_timestamp = int(yesterday.timestamp()) * 1000 return yesterday_timestamp def extractDate(name, prefix, fileType): prefixLen = len(prefix) fileTypeL...
from datetime import datetime from ctyped.types import CRef from .base import _ApiResourceBase from .stats import CurrentApplicationAchievements from .user import User class Application(_ApiResourceBase): """Exposes methods to get application data. Aliased as ``steampak.SteamApplication``. .. code-bloc...
import mem_profile import random import time names = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas'] majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business'] print 'Memory (Before): {}Mb'.format(mem_profile.memory_usage_psutil()) def people_list(num_people): result = [] for i in xrange(num_people...
"""`jupytext` as a command line tool""" import argparse import glob import json import os import re import shlex import subprocess import sys import warnings from copy import copy from tempfile import NamedTemporaryFile from .combine import combine_inputs_with_outputs from .compare import NotebookDifference, compare,...
""" Django settings for spencer project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib...
from exercises.structures.src.treasure_map import TreasureMap tm = TreasureMap() tm.populate_map() def test_beach_key(): assert tm.map['beach'] == 'sandy shore'.casefold() def test_coast_key(): assert tm.map['coast'] == 'ocean reef'.casefold() def test_volcano_key(): assert tm.map['volcano'] == 'hot ...
# from flask import Flask, Blueprint # from flask_sqlalchemy import SQLAlchemy # from flask_login import LoginManager # import os from flask import Flask, jsonify, request, make_response, redirect, url_for import jwt import datetime import os from functools import wraps from flask_sqlalchemy import SQLAlchemy import u...
c = get_config() # If the master config file uses syntax that's invalid in Python 3, we'll skip # it and just use the factory defaults. try: load_subconfig('ipython_config.py', profile='default') except Exception: pass else: # We reset exec_lines in case they're not compatible with Python 3. c.Interact...
# Copyright 2019 The FastEstimator Authors. 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...
from django.contrib import admin from . import models admin.site.register(models.Bark)
"""Utilities for ImageNet data preprocessing & prediction decoding. """ import json import keras.utils.data_utils as data_utils CLASS_INDEX = None CLASS_INDEX_PATH = ('https://storage.googleapis.com/download.tensorflow.org/' 'data/imagenet_class_index.json') def decode_predictions(preds, top=5): ...
import copy from lto.accounts.ecdsa.account_factory_ecdsa import AccountFactoryECDSA import base58 import pytest from lto.transactions.anchor import Anchor class TestAccountECDSA(): factory = AccountFactoryECDSA('L') seed = 'divert manage prefer child kind maximum october hand manual connect fitness small sym...
import subprocess from consolemenu.items import ExternalItem class CommandItem(ExternalItem): """ A menu item to execute a console command """ def __init__(self, text, command, arguments=None, menu=None, should_exit=False): """ :ivar str command: The console command to be executed ...
from tests.base import BaseTestCase from binpacking.solver.data_structure.solution import Solution from binpacking.solver.statistics import Statistics, StatisticIteration, StatisticFitness class StatisticsTest(BaseTestCase): def test_statistics(self) -> None: iteration = StatisticIteration() fitn...
# 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, Mapping, Optional, Sequence, Union from .. import _utilitie...
import unittest from selenium import webdriver class Typos(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path = r'./chromedriver.exe') driver = self.driver driver.get('http://the-internet.herokuapp.com/') driver.find_element_by_link_text('Typos').cl...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'isValid' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def isValid(s): # Write your code here # Write your code here freq = {i : s.count(i) for i in...
# # Account information # # Copy this file to account.py and fill in the real values for the Minecraft account. # # # # account = { "user" : 'your@login.com', "password" : 'your_password', "master" : 'minecraft_name_who_the_bot_will_listen_to', "host" : 'exampleserver.wha...
from django.shortcuts import render,redirect from django.contrib import messages from django.template import Context from .models import Court, CourtManager, SelectedCourt from apps.users.models import User from datetime import datetime from decimal import Decimal from django.contrib.auth.decorators import login_requir...
import unittest import os import numpy as np import pandas as pd from scipy.signal import StateSpace import matplotlib.pyplot as plt import mshoot def cfun(xdf, ydf): """ :param ydf: DataFrame, model states :param ydf: DataFrame, model outputs :return: float """ qout = ydf['qout'].values ...
# -*- coding: utf-8 -*- """ The main user-facing module of ``edges-cal``. This module contains wrappers around lower-level functions in other modules, providing a one-stop interface for everything related to calibration. """ from __future__ import annotations import attr import h5py import numpy as np import tempfile...
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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...
""" # # Exercise 2: Service Health Check # Create one or multiple filip clients and check if the corresponding services # are up and running by accessing their version information. # The input sections are marked with 'ToDo' # #### Steps to complete: # 1. Set up the missing parameters in the parameter section # 2. C...
from .base import AsyncUrbanClient, UrbanClient, UrbanDefinition, UrbanDictionaryError
# Copyright (c) 2015 Walt Chen # # 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 class ParserException(Exception): pass ...
from pathlib import Path import copy import time import torch.optim as optim import numpy as np import torch from torch.autograd import Variable from model import * from data_utils import * import torch.nn as nn from loguru import logger feature_dim = 8 block_size = 16 pad=2 n_conv=3 thresh=0.5 debug = False def test...
# # * This file is distributed under the terms in the attached LICENSE file. # * If you do not find this file, copies can be found by writing to: # * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, # * Berkeley, CA, 94704. Attention: Intel License Inquiry. # * Or # * UC Berkeley EECS Computer Science Divis...
/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/fnmatch.py
# coding=utf-8 import nltk from classification_utils import get_lines_from_file, load_manually_labeled_tweets, aggregate_results from sklearn.svm import LinearSVC, NuSVC, NuSVR, OneClassSVM, SVC, SVR from nltk.classify.scikitlearn import SklearnClassifier __author__ = 'kiro' def get_list_of_possible_words_in_tweets(...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from typin...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django_countries import countries def populate_weights(apps, schema_editor): Weights = apps.get_model("reports", "Weights") db_alias = schema_editor.connection.alias for item in COUNTRY_WEIGHTS: ...
from flask import render_template, redirect, request, url_for, flash from flask_login import login_user, logout_user, login_required, current_user from . import auth from .. import db from ..models import User from .forms import LoginForm, RegistrationForm, ChangePasswordForm, ResetPassword, ResetPasswordRequest, \ ...
# Copyright (C) 2007 Google 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 writ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch.utils.data class FairseqDataset(torch.utils.data.Dataset): """A dataset that provides helpers for batchi...
import frappe from frappe.utils import flt def merge_bundled_items(self, method): bundles = {} item_meta = frappe.get_meta(self.doctype + " Item") count = 0 copy_fields = ['qty', 'stock_qty'] sum_fields = ['total_weight', 'amount', 'net_amount'] rate_fields = [('rate', 'amount'), ('net_rate', 'net_amount'), ('w...
from __future__ import absolute_import import six import string from django.utils.encoding import force_text from sentry.interfaces.base import Interface from sentry.utils.json import prune_empty_keys from sentry.utils.safe import get_path, trim __all__ = ("Contexts",) context_types = {} class _IndexFormatter(st...
# # @lc app=leetcode id=79 lang=python3 # # [79] Word Search # # @lc code=start class Solution: def exist(self, board, word): start = [None, None] h = len(board) l = len(board[0]) walked = [[0] * l for _ in range(h)] for i in range(h): for j in range(l): ...
""" ----------------------------------------------------------------------------- AUTHOR: Soumitra Samanta (soumitramath39@gmail.com) ----------------------------------------------------------------------------- """ import subprocess import os import numpy as np from datetime import datetime import pandas as pd from ...