content
stringlengths
5
1.05M
from __future__ import print_function import BaseHTTPServer import json import os import tempfile import time import urllib import urllib2 from mysos.common.cluster import wait_for_master, wait_for_termination from sqlalchemy import create_engine from sqlalchemy.exc import OperationalError from twitter.common import...
from .wrapper import MySQLWrapper # initialize MySQLWrapper object mysqlwrapperpackage = MySQLWrapper.start()
import angr import IPython proj = angr.Project("crackme",load_options={'auto_load_libs':False}) state = proj.factory.entry_state() sim = proj.factory.simgr(state) sim.explore(find=0x00401250) print(sim.found[0].posix.stdin.concretize()) IPython.embed()
""" Simple graph implementation """ from typing import TypeVar, Generic, Set, Optional, List from utils import Stack, Queue T = TypeVar('T') PathType = List[T] class Graph(Generic[T]): """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {...
""" Some helper functions for ``lxml`` objects. """ from copy import deepcopy from typing import Iterator from lxml import etree from inxs import utils def extract_text(element: etree._Element, include_tail=False, reduce_whitespaces=True) -> str: """ Returns all text that is contained in the gi...
# Copyright 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of con...
import abc import logging import time import aprslib from aprslib.exceptions import LoginError from aprsd import trace from aprsd.clients import aprsis, kiss LOG = logging.getLogger("APRSD") TRANSPORT_APRSIS = "aprsis" TRANSPORT_TCPKISS = "tcpkiss" TRANSPORT_SERIALKISS = "serialkiss" # Main must create this from t...
import argparse from os.path import abspath from random import randint import pandas as pd from qcore.utils import load_yaml def generate_pertb_config(vm_params, perturbation_model: pd.DataFrame): max_depth = vm_params["nz"] * vm_params["hh"] bottom_depth = 0 i = 0 layers = [] while bottom_de...
from HOGFeatExtractor import HOGFeatExtractor import WindowExtractor __all__ = [HOGFeatExtractor, WindowExtractor]
import re import os import platform from zipfile import is_zipfile import pytest import requests from chromeguard import ChromeDriver def test_chromedriver_init(): driver = ChromeDriver() assert isinstance(driver, ChromeDriver) def test_parse_chromedriver_version(): driver = ChromeDriver() VERSION...
import os import subprocess from subprocess import check_output import tensorflow as tf #source = '/root/qualcomm/OpenImage2TFRecords/OID/Dataset/train' """ Usage: python oid_txt_xml.py --dataset_path Dataset/train --voc_script OIDv4_to_VOC/OIDv4_to_VOC.py """ flags = tf.app.flags flags.DEFINE_string("dataset_path"...
import os os.environ['CUDA_VISIBLE_DEVICES'] = '3,2,1,0' NUM_CUDA_DEVICES = len(os.environ['CUDA_VISIBLE_DEVICES'].split(',')) from common import * from net.rate import * from net.loss import * from utility.file import * from dataset.cdimage import * from dataset.sampler import * from dataset.transform import * # -...
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import spacy spacy.load('en_core_web_sm') # from spacy.lang.en import English from chatterbot.trainers import ChatterBotCorpusTrainer # Creating ChatBot Instance chatbot = ChatBot('<b>CRCE BOT</b>') # nlp = spacy.load("en_core_web_sm") chatbo...
from helpers import save_data, load_data, get_next_gameweek_id import numpy as np import json import os import variables import sys # global variables all_seasons = variables.ALL_SEASONS next_event = get_next_gameweek_id() positions = variables.positions() league_data = {} for season in all_seasons: league_data...
"""Foreground Farm Farm aproach: Move the mouse in the screen and watch if the enemy life's bar appears, then click in the mob to attack it. Doesn't work very well. """ # region Imports import time from pyfiglet import Figlet from pynput.mouse import Listener as MouseListener import keyboard import pyautog...
from django.shortcuts import render, redirect from django.db.models import Q from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.auth.decorators import login_required from .models import Book from .forms import BookForm @login_required def list_books(request): # Search ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This file contains the test for the MerklePrefixTree module. More information about the tests can be found in the docstrings within each test method below. """ import pytest from merkle_prefix_tree import MerklePrefixTree, AppendOnlyError class TestM...
""" aspen.wsgi ++++++++++ Provide a WSGI callable. It would be a little nicer if this was at aspen:wsgi instead of aspen.wsgi:website, but then Website would be instantiated even if we don't want it to be. Here, it's only instantiated when someone passes this to gunicorn, spawning, etc. """ from __future__ import ab...
from twilio.rest import Client account_sid = "ACd621bbcae9f2c8e4aab3378eb674506a" auth_token = 'd00a7dca49cdaac9a8cac9d56d351a29' def send_sms(): twilio_number = '+12087389649' target_number = '+917300807892' client = Client(account_sid, auth_token) message = client.messages.create(...
""" Contains the Django URLs for the 'results' app """ from django.urls import path from .views import ResultsView urlpatterns = [ path( "<str:job_id>/", ResultsView.as_view(), name="results", ), ]
from unittest import TestCase from .solution import min_window class TestMinWindow(TestCase): def test_repeated_character(self): S = "ADOBECODEBANC" T = "OBOC" self.assertEqual(min_window(S, T), "OBECO") def test_unique_character(self): S = "ADOBECODEBANC" T = "ABC" ...
import os import dj_database_url import django_heroku from decouple import config,Csv from django.contrib.messages import constants as message_constants from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.DEBUG: 'alert-info', messages.INFO: 'alert-info', messages.SUCCESS: 'a...
from datetime import datetime import pandas as pd from more_itertools import flatten from utils import format_generalization def gen_dict(anonymization, dom_values_enum): def f(x): for idx in range(len(anonymization) - 1): if anonymization[idx] <= x < anonymization[idx + 1]: ...
import numpy as np print("*** RTE ***") npzfile = np.load("export/RTE/RTE_state_dict.npz") print(npzfile["self_attn.k_proj.weight"]) print("***") print("*** SST-2 ***") npzfile = np.load("export/SST-2/SST-2_state_dict.npz") print(npzfile["self_attn.k_proj.weight"]) print("***") print("*** MNLI ***") npzfile = np.lo...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, print_function, absolute_import, unicode_literals) __all__ = ["plot_bpt"] import numpy as np import matplotlib.pyplot as plt import pkg_resources c = 2.9979e10 def plot_bpt(logq_val='all', z_val=1.0, kappa_val=20...
from tkinter import Tk, ttk, Frame, Menu from backend import Backend from frames import HomeFrame, FileSelectFrame from widgets import VendorEntryPopup, CategoryEntryPopup class App(Tk): def __init__(self, testing_mode, *args, **kwargs): Tk.__init__(self, *args, **kwargs) icon_filepath =...
import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from workspace_utils import active_session from PIL import Image import numpy as np import argparse import json from functions import args_paser_...
# # PySNMP MIB module ChrComPmEthETH-Current-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrComPmEthETH-Current-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:19:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
import os class Config: SECRET_KEY = os.environ.get('PROD_SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.environ.get('PROD_SQLALCHEMY_DATABASE_URI') MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USE_SSL = False MAIL_USERNAME = os.environ.get('EMAIL_USERNAME') ...
begin_unit comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#...
import numpy from dabax_util import get_dabax_file from silx.io.specfile import SpecFile from f0coeffs_fit import Crystal_get_f0coeffs from SymbolToFromAtomicNumber import SymbolToFromAtomicNumber from orangecontrib.xoppy.util.xoppy_xraylib_util import bragg_metrictensor def crystal_parser(filename='Crystals.dat', e...
# SPDX-License-Identifier: MIT """Login handler """ import falcon class Login: """Login """ def on_get(self, req, resp): """Handles GET requests""" session = req.context.session session["user"] = {"id": "123", "groups": ["user"]} resp.status = falcon.HTTP_200 resp...
"""Tests for PROPKA functionality.""" import logging from pathlib import Path import pytest import common _LOGGER = logging.getLogger(__name__) @pytest.mark.parametrize("input_pdb", ["1K1I", "1AFS", "1FAS", "5DV8", "5D8V"], ids=str) def test_propka_apo(input_pdb, tmp_path): """PROPKA non-regression tests on pro...
#!/usr/bin/env python # db_retrieve_backup.py -- retrieve database files from backup import restore import sys import time if __name__ == '__main__': intf = restore.Interface() dbHome, jouHome, bckHost, bckHome = restore.getHomes(intf) print " dbHome =", dbHome print "jouHome =", jouHome print "bckHost =", bc...
import sys import os import math from PIL import Image from PIL import ImageDraw from PIL import ImageFilter if __name__ == '__main__': args = sys.argv faces = ( "out0", "out1", "out2", "out3", "out4", "out5" ) out_width = 1024 start_x = 0 img = Image.new('RGBA', [out_width*6, out_width], (0x00,0x...
from extract_image_features import * from extract_svd_features import * from feature_engineering import * from data_cleaning import * from scoring import * from kaggle.api.kaggle_api_extended import KaggleApi from zipfile import ZipFile import os import re import json import numpy as np import pandas as pd import cv2 ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getMinimumDifference(self, root: TreeNode) -> int: ret = float('inf') pre = -1 stack = [[root, False]] ...
import sys from PySide.QtCore import * from PySide.QtGui import * # importo todas las funciones de pyside import layout_CiclosApp from JOULE_BRAYTON.Ciclo_JouleBrayton_App import JouleBraytonDialog from SABATHE.Ciclo_Sabathe_App import SabatheDialog __appName__ = 'Ciclos App' class CiclosAppDialog(QDialog, layou...
""" Constants required for bayes_sensor.py """ ATTR_OBSERVATIONS = 'observations' ATTR_PROBABILITY = 'probability' ATTR_PROBABILITY_THRESHOLD = 'probability_threshold' CONF_OBSERVATIONS = 'observations' CONF_PRIOR = 'prior' CONF_PROBABILITY_THRESHOLD = 'probability_threshold' CONF_P_GIVEN_F = 'prob_given_false' CONF_...
from .baseline import baseline from .checksum import checksum from .heuristic import duplicate_row, deviated_value, truncated_value from .regulation import forbidden_value, sequential_value, row_constraint
from django.contrib import admin from .models import Worker, Machine # Register your models here. admin.site.register(Worker) admin.site.register(Machine)
# -*- coding: utf-8 -*- # from .surface_base import SurfaceBase class CompoundSurface(SurfaceBase): """ Generates the Compound Surface Gmsh function. Creates a compound surface from several elementary surfaces. When meshed, a compound surface will be reparametrized as a single surface, whose mesh ...
""" regression tests """ import unittest from django.test import TestCase from src.clustering.models import ClusteringMethods from src.core.tests.common import split_double, add_default_config from src.encoding.encoding_container import EncodingContainer, ZERO_PADDING from src.encoding.models import ValueEncodings f...
#!/usr/bin/env python import os import re from logging518 import logger pem_file = "/usr/local/lib/python3.8/site-packages/grpc/_cython/_credentials/roots.pem" cert_label = 'Label: "DST Root CA X3"' issuer_label = "# Issuer:" end_cert_label = "-----END CERTIFICATE-----" if __name__ == "__main__": ignore_start = ...
# -*- coding: utf-8 -*- from telegram import ReplyKeyboardMarkup from helpers import * logger = logging.getLogger(__name__) def check_assign_permission(update): if update.message.from_user.username not in ADMIN_USERS: update.message.reply_text(YOU_HAVE_NO_POWER_OVER_ME) return False return T...
import logging logger = logging.getLogger('nodes.data_preparation') def run(client, params): pass
import time class FPS_counter: def __init__(self, limit=0): self._time = time.time() # seconds since epoch self._dt = 0 # seconds self._min_dt = 1 / limit if limit > 0 else 0 self._limited = False def _get_dt(self): return time.time() - self._time d...
"""This program reads a file and prints the letters in decreasing order of frequency. It doesn't count spaces, numerics and special characters!""" # file handling fname = input('Enter a file: ') try: if len(fname) < 1: fname = 'clown.txt' fhand = open(fname) except: print("File doesn't exist:", fname) ...
import logging.config import os import pickle import click from slughorn.processor import ExpressionExtractor, WordListGenerator, RuleGenerator from slughorn.scraper import FacebookScraper, TwitterScraper from slughorn.scraper import constants_factory from slughorn.scraper.constants_factory import load_constants, res...
import tkinter import datetime import threading import time import pytz from playsound import playsound import os sound_path = os.path.dirname(os.path.abspath(__file__)) + "/../sound.mp3" def main(): root = tkinter.Tk() root.title("Nuru Clock") root.resizable(False, False) width = root.winfo_screenwi...
import os, sys import bibtexparser def get_years(): return [mydir for mydir in sorted(os.listdir('./abstracts')) if os.path.isdir('./abstracts/'+mydir)] def get_bibtex_entries_by_year(year_dir): bibtex_entries = list() for page in os.listdir('./abstracts/'+year_dir): with open('./abstracts/'+year_...
from django.apps import AppConfig class DatasciConfig(AppConfig): name = 'datasci'
#!/usr/bin/env python3 ### Burak Less Data Experiment Utils ### GENERIC import copy import datetime import io import os from os import listdir from os.path import isfile, join, isdir import sys from functools import partial ### DATA PROCESS import pandas as pd import numpy as np import ast from sklearn.metrics impor...
#Façaum algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto. produto = float(input('O produto headset esta R$ ')) new = produto - (produto * (15.0/100)) new1 = produto - (produto * (10.0/100)) print('Pagando no pix você ganha 15% de desconto, ficando no valor de R$ {} \n no bol...
import cv2 class Debug: def __init__(self): pass def print_debug_info(self, image, state, callback): debug_image = image.copy() font = cv2.FONT_HERSHEY_SIMPLEX bottom_left_corner_of_text = (10, 35) font_scale = 1 font_color = (255, 255, 255) line_type ...
from django.conf import settings from django.test import TestCase, RequestFactory from django.urls import reverse from Main.views import error_500_handler from Users.models import User from tests.testing_base import BaseCase class UserSetupTest(BaseCase): @staticmethod def get_url(user): return reve...
""" This module is an interface for loading existing wave runup datasets. These datasets can be used to evaluate existing models or train new models. Datasets are returned as :obj:`pandas.DataFrame`. """ import io import pkgutil import random from datetime import datetime, timedelta import numpy as np import pandas a...
# pylint: disable=missing-docstring import unittest import numpy as np from reactions.units import Energy class EnergyTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.q = Energy.load(mev=3) def test_kev(self): np.testing.assert_approx_equal(3000.0, self.q.kev) def tes...
''' Use __new__ when you need to control the creation of a new instance. Use __init__ when you need to control initialization of a new instance. ''' class Shape: def __new__(cls, sides, *args, **kwargs): print("Creating Instance") if sides == 3: instance= Triangle(*args, **kwargs) ...
import re import os # color = (101, 0, 0) color = ['#fff', '#aaa', '#1f1f1f'] input_path = './src/content' output_path = None filter_name = 'tile.svg' # color = ['#666', '#fff'] # input_path = './assets/originals' # output_path = './assets/converted' # filter_name = None def convert_file(file_path, color, output_p...
import sys, os, pytest sys.path.append(os.getcwd()) from do_grader_lib import PartQuality from anyint import grader input_data = '' quality = PartQuality('test', 7, 10) greedy_submission = '7\n123\n' opt_submission = '10\n123\n' # Score Test def test_full_credit(): result = grader.grade(input_data, quality, o...
import os import platform import subprocess import sys import urllib.request from pathlib import Path import cv2 import depthai as dai from depthai_helpers.cli_utils import cli_print, PrintColors from depthai_helpers.managers import Previews def show_progress(curr, max): done = int(50 * curr / max) sys.stdo...
import os.path import tensorflow as tf import helper import warnings import ssl import project_tests as tests import scipy import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from distutils.version import LooseVersion from moviepy.editor import VideoFileClip # Check TensorFlow Version assert Loos...
# %% from dotenv import load_dotenv from os import getenv from datetime import datetime, date, tzinfo from gcalendar.gcalendar import GCalendar # %% load_dotenv() CALENDAR_ID = getenv("CALENDAR_ID") PICKLE_PATH = getenv("GTOKEN_PICKLE_PATH") TIMEZONE = getenv("GTIMEZONE") CREDENTIALS_PATH = getenv("GCREDENTIALS_PATH")...
""" Naive approaches: Using two loops: for each node in list: from start to curr each node: check curr node is its next node using modified Node structure using visited field in each node traverse list and mark each curr node as visited while traversing check if curr node is alre...
#! /usr/bin/env python import fileinput max_mem = 0.0 i = 0 mem_id = 6 for line in fileinput.input(): curr_id = 0 if i == 0: i += 1 else: row = line.rstrip().split(' ') for col in row: if len(col) > 0: if curr_id == mem_id: mem = floa...
import unittest2 from datafeeds.usfirst_matches_parser import UsfirstMatchesParser @unittest2.skip class TestUsfirstMatchesParser(unittest2.TestCase): def test_parse_2012ct(self): with open('test_data/usfirst_html/usfirst_event_matches_2012ct.html', 'r') as f: matches, _ = UsfirstMatchesParse...
name = raw_input("What's your name?") if name.endwith('Gumby'): print 'Hello, Mr. Gumby'
from EasyNN.utilities.download import download from EasyNN.utilities.data.load import load from . import file, url from os.path import exists if not exists(file): download(file, url) dataset = load(file)
from configparser import ConfigParser CONFIGURATION_FILE = 'config/config.ini' CONFIG = ConfigParser() CONFIG.read(CONFIGURATION_FILE) DEFAULTS = { 'server' : {'key_path' : 'place_in_config.pem', 'server_dns' : 'ec2-public-ipv4-address.compute-1.amazonaws.com'}, 'world' : {'world_name' : 'Ter...
from __future__ import absolute_import from .resnet import resnet18, resnet34, resnet50
DEFAULT_JSONLD_CONTEXT = { "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "hydra": "http://www.w3.org/ns/hydra/core#", }
from math import log import numpy as np import pytest from scipy import optimize from sklearn.multioutput import MultiOutputRegressor from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal from numpy.testing import assert_raises from skopt.acquisition import _gaussian_acquis...
import pytest from pathlib import Path from sklearn.ensemble import RandomForestClassifier from explainerdashboard import * from explainerdashboard.datasets import * from explainerdashboard.custom import * @pytest.fixture def generate_assets(): X_train, y_train, X_test, y_test = titanic_survive() model = Ran...
import json import math import os import tempfile import unittest from collections import Counter from pymatgen.analysis.bond_valence import BVAnalyzer from pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies import MultiWeightsChemenvStrategy from pymatgen.analysis.chemenv.coordination_env...
import os import cv2 import math import time import datetime import numpy as np from PIL import Image, ImageDraw import face_recognition.api as face_recognition #################################### # DEVELOPER : VIKRAM SINGH # # TECHNOLOGY STACK : PYTHON # #################################### # ======...
# -*- coding:utf-8 -*- from django.contrib import admin from .models import Project, ServerInfo # Register your models here. class ProjectModelAdmin(admin.ModelAdmin): """ Project Model Admin """ list_display = ('id', 'name_en', 'name', 'address', 'address_pro', 'need_test') ...
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['test_get_partition_sets_for_pipeline 1'] = { 'partitionSetsOrError': { '__typename': 'PartitionSets', 'results': [ ...
from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib.auth import views from . import view urlpatterns = [ url(r'^$', view.index, name='index'), url(r'^(?P<user_id>[0-9]+)/$', view.profile, name = 'profile'), url(r'^(?P<use...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from pkg_resources import require, DistributionNotFound import pages import os package_name = 'django-page-cms' def local_open(fname): return open(os.path.join(os.path.dirname(__file__), fname)) requirements = local_open('requirements/external_a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # */AIPND-revision/intropyproject-classify-pet-images/get_pet_labels.py # # PROGRAMMER: Pascal Kolleth # DATE CREATED: 13.11.2018 # REVISED DATE: # PURPOSE: Create the function get_pet_labels that creates the pet labels from # the image's filename. This function i...
# -*- coding: utf-8 -*- import torch import torch.nn as nn class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class DownSample(nn.Module): def __init__(self, n_in, n_out, relu='prelu', batchnorm=True, dropout_prob=0.0): super(DownSample, self).__init__(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import string import mapping import common import names SQLITE3_CREATE_SQL_0 = u'create table if not exists %s(%s) WITHOUT ROWID;' class PBClass(object): """docstring for PBClass""" def __init__(self, table): self.table = table self.comment = tabl...
# Copyright 2013-2015 ARM Limited # # 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...
""" test all files types with time limits """ import pytest from pathlib import Path from datetime import datetime import numpy as np import georinex as gr R = Path(__file__).parent / "data" @pytest.mark.parametrize( "fn, tlim, tref, tlen", [ ( R / "york0440.zip", ("2015-02-1...
from future.builtins import range import numpy as np import modred as mr num_vecs = 100 nx = 100 # np.n-uniform grid and corresponding inner product weights. x_grid = 1. - np.cos(np.linspace(0, np.pi, nx)) x_diff = np.diff(x_grid) weights = 0.5*np.append(np.append(x_diff[0], x_diff[:-1]+x_diff[1:]), x_diff[-1]) # Ar...
# Copyright 2017 Yahoo Inc. # Licensed under the terms of the Apache 2.0 license. # Please see LICENSE file in the project root for terms. from __future__ import absolute_import from __future__ import division from __future__ import nested_scopes from __future__ import print_function import logging import os import s...
from django.forms import ModelForm, Textarea, SelectMultiple, TextInput, NumberInput from newspaper.models import SubSection import hashlib class SubSectionForm(ModelForm): class Meta: model= SubSection fields = '__all__' class PartialSubSectionForm(ModelForm): class Meta: model= SubSection fields = '__a...
import sys import torch from torch import nn from torch.optim import Adam,lr_scheduler from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torchvision import transforms, datasets from AlexNet import AlexNet from PIL import Image sys.path.append("..") if __name__ == '__main_...
""" RHC NN training on my classification problem """ """ Do this before running the code in terminal / command line: git clone https://github.com/originell/jpype.git cd jpype python setup.py install' Additional reference doc: https://stackoverflow.com/questions/35736763/practical-use-of-java-class-jar-in...
import sys import json import logging import os from .log import fatal_error logger = logging.getLogger('session-bot') CONFIG = os.getenv('CONFIG') def init(): global config logger.info('Loading config...') try: if CONFIG[0] == '{': config = json.loads(CONFIG) else: ...
from silica.cfg.types import Block, BasicBlock, Yield, Branch from silica.cfg.control_flow_graph import ControlFlowGraph
import json import pandas as pd import os import ast from ..feature_extraction.passage_feature_extraction import PassageFeatureExtraction import math import gc class QueryLikelihood: def __init__( self, passage_data: dict, doc_term_freq: dict, col_term_freq: dict, smoothing...
import wbdata import pandas as pd # set up the indicator indicators = {'NY.GDP.PCAP.PP.KD': 'gdppc'} gdp = wbdata.get_dataframe(indicators, convert_date=False) gdp = gdp.reset_index() gdp = gdp.rename(columns={'date': 'year'}) gdp.to_csv('gdpPerCap.csv', index=None)
# -*- coding: utf-8 -*- from openerp import models,fields,api,tools,SUPERUSER_ID from openerp.tools.translate import _ from openerp.osv import osv import xmlrpclib class is_moyen_fabrication_autre(models.Model): _name='is.moyen.fabrication.autre' _sql_constraints = [('name_uniq','UNIQUE(name)', u'Ce code exi...
# -*- coding: utf-8 -*- """ Tests to validate all equations in the NRWAL directory can be parsed and evaluated. """ import os import pytest from NRWAL.utilities.utilities import NRWAL_ANALYSIS_DIR from NRWAL.handlers.equations import Equation from NRWAL.handlers.directories import EquationDirectory TEST_DIR = os.path...
#!/usr/local/bin/python -u import os import boto3 import requests import traceback from time import sleep import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s %(message)s') check_interval = int(os.environ.get('CHECK_INTERVAL')) class ...
import torch import torch.nn as nn from typing import List class FCNN(nn.Module): """Class that describe the architecture and behavior of the neural network""" neurons_per_layer: int = 0 # number of neurons per layer layers: List[nn.Module] # Ordered list of the network layers sequence: n...
# Copyright (c) 2021. Sergei Sazonov. All Rights Reserved subscribers = {} def subscribe(event_type: str, fn): if event_type not in subscribers: subscribers[event_type] = [] subscribers[event_type].append(fn) def post_event(event_type: str, data): if event_type not in subscribers: retu...
from decouple import config from flask import Flask, render_template, request from .models import DB, User #now we make a app factory def create_app(): app = Flask(__name__) #add out config app.config['SQLALCHEMY_DATABASE_URI'] = config('DATABASE_URL') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = F...