content stringlengths 5 1.05M |
|---|
"""
Calculate sentiment score, word count, gets parsed sentence
and words array from news
"""
from datetime import datetime
from misc.analysis import *
from models import Word
def news_with_one_company():
positive_words = Word.select().where(Word.is_positive == True)
negative_words = Word.s... |
"""Define class for Department argument."""
from args import _ArgType, _InputValue
from args.meta_arg import MetaArg
from args.arg import Arg
class Department(Arg, metaclass=MetaArg, argtype=_ArgType._DEPARTMENT):
"""Department argument."""
# This is necessary since Department is a dependency for other
#... |
import sys
def IsSortedArray(l):
c=0
i=1
length=l[0]
while i<length:
if l[i]>l[i+1] and c==0:
pass
elif l[i]<l[i+1]:
c=1
pass
else:
print("false")
return
i=i+1
print("true")
strm=''
num=sys.stdin.readlines()
for item in num:
strm+=item
lst=[int(x) for x in strm.splitlines()]
IsSortedArray... |
def f():
s: str
s = "01234"
print(s[1.2])
f()
|
"""
Script to scrape artists urls from all charts page on SoundCloud.
Cycle through all combinations of country and genre, for top50 and new.
The data pulled is going to be a catalogue of artists we are going to find
urls for and pull streaming data for.
This will include data for artist, track url and name. Keeping o... |
import pokepy
import random
search = pokepy.V2Client()
def get_pokemon_info(name):
try:
pokemon = search.get_pokemon(name)
except Exception:
return
species = search.get_pokemon_species(pokemon.id)
stats = {
(pokemon.stats[i].stat.name).upper(): pokemon.stats[i].base_stat
... |
# Generated by Django 3.1.6 on 2021-03-01 15:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('news', '0002_news_text')... |
import tkinter as tk
from tkinter import ttk
from app import tkinter_logic
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from app import card_fetcher
from app import Graph_functions
# GLOBALS
LARGE_FONT = ("Verdana", 12)
def draw_ca... |
import re
from typing import Pattern, Callable
from atcodertools.codegen.code_generators import cpp, java, rust, python
from atcodertools.codegen.models.code_gen_args import CodeGenArgs
from atcodertools.tools.templates import get_default_template_path
class LanguageNotFoundError(Exception):
pass
class Languag... |
# coding=utf-8
from datetime import datetime
from lxml import etree
from app.utils.parse_url import parse_url
from app.database import MongodbClient
class CrawlXs147(object):
"""
147xs crawler
source: http://www.147xs.com/
"""
def __init__(self):
self._base_url = 'http://www.147xs.com'
... |
from pacman import exceptions
import numpy
class BaseKeyAndMask(object):
""" A Key and Mask to be used for routing
"""
def __init__(self, base_key, mask):
"""
:param base_key: The routing key
:type base_key: int
:param mask: The routing mask
:type mask: int
... |
# Time: O(n), search for s in 2*s
# Space: O(n)
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
# return s in (2*s)[1:-1]
return s in (s[1:]+s[:-1])
|
from typing import Any, Dict
class AST:
def type_name(self) -> str:
raise NotImplementedError
def __eq__(self, rhs: Any) -> bool:
if isinstance(rhs, AST):
return self.type_name() == rhs.type_name() and \
self.state_dict() == rhs.state_dict()
return False
... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.FilteredInstanceTableView.as_view(), name='instances'),
path('instances', views.FilteredInstanceTableView.as_view(), name='instances'),
path('update', views.update, name='update'),
path('update/status', views.update_status,... |
#!/usr/bin/env python3
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*... |
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
import json
import base64
from PIL import Image
import io
from model_handler import ModelHandler
def init_context(context):
context.logger.info("Init context... 0%")
model = ModelHandler()
context.user_data.model = model
contex... |
from setuptools import setup
setup(
name="sync_location",
version="1.1.3",
author="Jelmer van Arnhem",
description="Read, parse and expose syncthing folder locations by name",
license="MIT",
py_modules=["sync_location"],
include_package_data=True,
python_requires=">= 3.*",
setup_req... |
X = 11
def g1():
print(X)
def g2():
global X
X = 22
def h1():
X = 33
def nested():
print(X)
nested()
def h2():
X = 33
def nested():
nonlocal X
X = 44
nested()
print(X)
if __name__ == '__main__':
g1()
g2()
g1()
h1()
h2()
|
import os
import pytest
from _pytest.fixtures import SubRequest
@pytest.fixture(scope='module', autouse=True)
def setup_dir(request: SubRequest) -> None:
os.mkdir('test-dir', mode=0o777)
def teardown_dir() -> None:
os.rmdir('test-dir-1')
request.addfinalizer(teardown_dir)
@pytest.mark.dir
def ... |
#!/usr/bin/python
# Gimp-Python - allows the writing of Gimp plugins in Python.
# Copyright (C) 2006 Manish Singh <yosh@gimp.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; ei... |
# Convert knowledge graph in NTRIPLES format to tsv file
import pandas as pd
df = pd.read_csv('kgraph_geodata.nt',
sep=r'\s+',
header=None,
names=None,
dtype=str,
usecols=[0, 1, 2])
df = df.astype(str)
df[[0, 1, 2]] = df[[0, 1, 2]]... |
import torch
import railrl.misc.hyperparameter as hyp
from experiments.murtaza.multiworld.reset_free.pointmass.generate_state_based_vae_dataset import generate_vae_dataset
from multiworld.envs.pygame.point2d import Point2DWallEnv
from railrl.launchers.launcher_util import run_experiment
from railrl.misc.ml_util import... |
# SPDX-FileCopyrightText: 2020 The Magma Authors.
# SPDX-FileCopyrightText: 2022 Open Networking Foundation <support@opennetworking.org>
#
# SPDX-License-Identifier: BSD-3-Clause
import os
def is_dev_mode() -> bool:
"""
Returns whether the environment is set for dev mode
"""
return os.environ.get('MA... |
import json
import logging
import requests
import time
from piperci.gman.exceptions import TaskError
log = logging.getLogger(__name__)
def request_new_task_id(
run_id=None, gman_url=None, project=None, caller=None, status=None, thread_id=None
):
"""
Request a new TaskID from GMan, associated with a give... |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2020 supr3me
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, ... |
from .hj_dict_api import HJDictApi, NotfoundException, MultiWordsException
from .tool import format_hjdict |
#!/usr/bin/python3
"""
Rename a PDF with information taken from its metadata.
Depends on PyPDF2: https://github.com/py-pdf/PyPDF2
Depends on pathvalidate: https://github.com/thombashi/pathvalidate
"""
import argparse
import os
from pathvalidate import sanitize_filename
from PyPDF2 import PdfFileReader
if __name__ ==... |
import pytest
from terraformpy import TFObject
@pytest.fixture(autouse=True, scope="function")
def reset_tfobject():
TFObject.reset()
|
import tensorflow as tf
class Net(object):
def __init__(self,param_scope):
def _sanitize_var_name(var):
base_scope_name = param_scope.name.split('/')[-1]
return ('/'.join(var.name.split(base_scope_name)[1:])).split(':')[0]
save_vars = {_sanitize_var_name(var) : var for var ... |
"""Generate the cweno extension module."""
import pathlib
import jinja2
import pyweno
jinja2.filters.FILTERS['pm'] = lambda x: "{:+d}".format(x)
jinja2.filters.FILTERS['pmr'] = lambda x: "{:+d}".format(x).replace('-','m').replace('+','p')
gendir = pathlib.Path(__file__).parent
srcdir = gendir.parent / 'src'
with ... |
import oneflow as flow
import argparse
import numpy as np
import time
from model.build_model import build_model
from utils.imagenet1000_clsidx_to_labels import clsidx_2_labels
from utils.numpy_data_utils import load_image
def _parse_args():
parser = argparse.ArgumentParser("flags for test ViT")
parser.add_a... |
print("1")
print("2",end="")
print(3)
print("4",end="")
print("5",end="")
print("6")
print("7",end="")
print("8",end="")
print("9",end="")
print("10")
|
import depthai as dai
import time
import cv2
from pathlib import Path
# Draw ROI and class label of each detected thing if confidence>50%
def frame_process(frame, tensor):
color = (255,0,0)
keeped_roi = []
for i in range(100): # There is 100 detections, not all of them are relevant
if (tensor[i*7... |
# Created by: Aaron Baker&Elliot Kjerstad
import pyshark
import sys
import os
import time
import multiprocessing
from pathlib import Path
from optparse import OptionParser
import colorama
from colorama import Fore, Back, Style
from classes.Collector import Collector
from classes.Print import Print
from classes.Totals... |
import os
def get_path(datafile):
thisfile = os.path.abspath(os.path.expanduser(__file__))
return os.path.join(os.path.dirname(thisfile), datafile) |
# coding: utf-8
import sys
import unittest
sys.path.append('../yurlungur')
import yurlungur as yr
from yurlungur.core.env import _Substance
@unittest.skipUnless(_Substance(), "Substance is not found")
class TestSubstance(unittest.TestCase):
@unittest.skip("only runtime")
def test_cmds(self):
with y... |
import pytest
from users.models import User
pytestmark = [pytest.mark.django_db]
def get_user():
return User.objects.last()
@pytest.fixture
def lead_data():
return {
'name': 'Monty Python',
'email': 'monty@python.org',
'recaptcha': '__TESTING__',
}
def test_creating(api, lead... |
class Solution:
def lengthOfLongestSubstring(self, s):
i = j = m = 0
t, l = set(), len(s)
while j < l:
if s[j] not in t:
t.add(s[j])
j += 1
m = max(m, len(t))
else:
t.remove(s[i])
i += 1
... |
# -*- coding: utf-8 -*-
"""
.. module:: openbread
:platform: Unix, Windows
:synopsis: OPENFPM based brownian reaction dynamics
.. moduleauthor:: openbread team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Lice... |
from flask import Flask
from flask import request
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, Float
from flask_marshmallow import Marshmallow
from flask_jwt_extended import JWTManager,jwt_required,create_access_token
from flask_mail import Mail, Mes... |
import datetime
import socket
import socketserver
import struct
from json import dumps
from time import time
import pymongo
from contentmanager import BoardManager, MailManager, PostManager
from user import User
from utils import *
class Server(socketserver.StreamRequestHandler):
def __init__(self, *args):
... |
import os
from parallelHillClimber import PARALLEL_HILL_CLIMBER
phc = PARALLEL_HILL_CLIMBER()
phc.Evolve()
phc.Show_Best()
|
"""
make_train_val_test_splits.py
Load a csv file into a dataframe containing Leavesdb metadata, split it into train, val, and test subsets, then write to new location as csv files.
Created on: Wednesday April 6th, 2022
Created by: Jacob A Rose
python "/media/data_cifs/projects/prj_fossils/users/jacob/github/imag... |
"""Tests for the object inspection functionality.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010 The IPython Development Team.
#
# Distributed under the terms of the BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
... |
import sys
import random
ans = True
while ans:
pergunta = input("Pergunte algo para Magic8Ball: (Pressione enter para sair) ")
resposta = random.randint(1,8)
if pergunta == '':
sys.exit()
elif resposta == 1:
print ('Com Certeza')
elif resposta == 2:
print('Perspectiva Bo... |
# Copyright 2020 The Nadi Data 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 readtextfile
import readjsonfile
import readparquetfile
import writeavrofile
import writetextfile
import writeparquetfile
import ray
from timeit impo... |
# pylint: disable=W0212
# W0212: It is fine to access protected members for test purposes.
#
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#Redistribution and use in source and binary forms, with o... |
from datetime import datetime, timedelta
import numpy as np
NA = float(np.nan)
FILTERS = {
"chart_type": ["regional", "viral"],
"period": ["daily", "weekly"],
"region": [
"global",
"us",
"gb",
"ar",
"at",
"au",
"be",
"bg",
"bo",
... |
from office365.runtime.paths.resource_path import ResourcePath
from office365.sharepoint.base_entity import BaseEntity
from office365.sharepoint.sharing.picker_settings import PickerSettings
class SharingInformation(BaseEntity):
"""Represents a response for Microsoft.SharePoint.Client.Sharing.SecurableObjectExten... |
# Copyright 2018 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.
"""This module is to process the code coverage metadata."""
import collections
import json
import logging
import re
import urlparse
import zlib
import cloud... |
"""VaeRnn implementation."""
from argparse import ArgumentParser
from typing import Any, Dict, Tuple
import torch
from torch import nn
from ....arg_parser.utils import str2bool
from ....tokenizer import Tokenizer
from ..base_model import GranularEncoderDecoderModel
from ..loss import LOSS_FACTORY
from ..module impor... |
'''Implementation for routing addremove triggers'''
# import genie.libs
from genie.libs.sdk.triggers.addremove.addremove import TriggerAddRemove
class TriggerAddRemoveIpv4StaticRoutes(TriggerAddRemove):
pass
class TriggerAddRemoveIpv6StaticRoutes(TriggerAddRemoveIpv4StaticRoutes):
pass |
import numpy as np
from PIL import Image
import os, cv2, pickle
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
recognizer = cv2.face.LBPHFaceRecognizer_create()
mainDir = os.path.dirname(os.path.abspath(__file__))
imageDir = os.path.join(mainDir,"img")
current_id =0
label_dec = {}
y_label... |
from formencode import ForEach, Schema, NestedVariables, validators
from pyramid.testing import DummySession
# This always stays the same.
dummy_csrf_token = DummySession().get_csrf_token()
class DummySchema(Schema):
allow_extra_fields = False
foo = validators.String(not_empty=True)
class LooseDummySchema... |
#!/usr/bin/env python
import sys
import os
import simplejson as json
f = open("bootconf.json", "r")
vals_dict = json.load(f)
f.close()
os.putenv('DEBIAN_FRONTEND', 'noninteractive')
os.putenv('TERM', 'dumb')
password=vals_dict['dbpassword']
dbname=vals_dict['dbname']
commands = []
commands.append('sudo -E apt-get ... |
"""
"""
from vyapp.plugins import ENV
from vyapp.areavi import AreaVi
ENV['cpsel'] = lambda sep='\n': AreaVi.ACTIVE.cpsel(sep)
ENV['ctsel'] = lambda sep='\n': AreaVi.ACTIVE.ctsel(sep)
ENV['chmode'] = lambda id: AreaVi.ACTIVE.chmode(id)
|
from pprint import pprint
from finnews.client import News
# Create a new instance of the News Client.
news_client = News()
# Grab the CNN Finance News Client.
cnn_finance_client = news_client.cnn_finance
# Grab the All Stories Feed.
content = cnn_finance_client.all_stories()
pprint(content)
# Grab the Top Stories ... |
"""
Copyright (c) 2015-2022 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 atomic_reactor.constants import IMAGE_TYPE_DOCKER_ARCHIVE
from atomic_reactor.dirs import BuildDir
from atomic_reactor.plugin import... |
import numpy as np
from tensorflow.keras.utils import Sequence
from ulaw import lin2ulaw
def lpc2rc(lpc):
#print("shape is = ", lpc.shape)
order = lpc.shape[-1]
rc = 0*lpc
for i in range(order, 0, -1):
rc[:,:,i-1] = lpc[:,:,-1]
ki = rc[:,:,i-1:i].repeat(i-1, axis=2)
lpc = (lpc[:... |
import os
import numpy as np
from scipy import stats
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.interpolate import UnivariateSpline
from sklearn.isotonic import IsotonicRegression
from statsmodels.base.model import GenericLikelihoodModel
def... |
import setuptools
if __name__ == '__main__':
setuptools.setup(
name='Latex to Wolfram',
packages=setuptools.find_packages(),
entry_points={
'console_scripts': [
'latex2wolfram = latex2wolfram.main:main',
],
},
setup_requires=['pytest-runner', 'ply'],
tests_require=['pytest'],
) |
import sys
from pymemcache.client.base import Client
TIMEOUT_SEC = 15
ITERATION_NUM = 100
ip, port = (sys.argv[1], sys.argv[2]) if len(sys.argv) == 3 else ("localhost", "11211")
## Connect
print(f"connecting to {ip}:{port}")
try:
client = Client((ip, port), connect_timeout=TIMEOUT_SEC, timeout=TIMEOUT_SEC)
... |
import sys
import numpy as np
# sum of deliciousness が border以上の組み合わせが K個以上あればTrue
def is_ok(a, b, c, X, Y, Z, K, border):
cnt = 0
for i in range(X):
for j in range(Y):
for k in range(Z):
if a[i] + b[j] + c[k] < border:
break
... |
#!/usr/bin/python3
##########################################################################
# Copyright 2022 Xu Ruijun
#
# 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.apa... |
"""
Copyright (c) 2021 Dell Inc, or its subsidiaries.
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... |
# -*- coding: utf-8 -*-
# author: @RShirohara
import re
from . import markdown
_RUBY = re.compile(r"{(?P<text>.*?)\|(?P<ruby>.*?)}")
_TCY = re.compile(r"\^(?P<text>.*?)\^")
_NEWPAGE = re.compile(r"^={3,}$")
def build_inlineparser():
parser = InlineParser()
parser.reg.add(parser.code_inline, "code_inline", ... |
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404, HttpResponse, HttpResponseForbidden, Http... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 3 14:49:57 2019
Title: MP4-Medical Image Processing
@author: MP4 Team
"""
# Main Program to Start
# Importing required PyQt5 class
import sys
import os
from PyQt5.QtGui import QIcon, QColor
from PyQt5.QtWidgets import (QApplication, QMainWindow, QAction, ... |
# GPL # "author": Paulo_Gomes
import bpy
from mathutils import Quaternion, Vector
from math import cos, sin, pi
from bpy.props import (
FloatProperty,
IntProperty,
BoolProperty,
)
# Create a new mesh (object) from verts/edges/faces
# verts/edges/faces ... List of vertices/edges/faces ... |
from myspiders.ruia import JsonField, Item, Spider, Bs4HtmlField, Bs4TextField
from urllib.parse import urlencode, urlparse, urljoin, quote
from config import Job
'''
companyName: null
deptOrgName: "广发总行"
education: "本科"
endDate: "2020-06-10"
hiddenSiteApply: 1
importPost: 0
lastEditDate: null
orgId: 102501
orgName: "... |
from qgis.PyQt.QtWidgets import *
from .diverseity_results_dialog_ui import Ui_dlgResults
class DlgResults(QDialog, Ui_dlgResults):
def __init__(self):
super(DlgResults, self).__init__()
self.setupUi(self)
self.setLayout(self.lytMain)
self.trwResults.setColumnWidth... |
import itertools
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.exceptions import FieldError
from autoslug import AutoSlugField
from otcore.lex.lex_utils import lex_slugify
from otcore.topic.models import Tokengroup
from otcore.relation.mode... |
from tools.bot import AdminBot
bot = AdminBot()
bot.run()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2017-2019, Erin Morelli.
Title : EM Downpour Downloader
Author : Erin Morelli
Email : erin@erinmorelli.com
License : MIT
Version : 0.2
"""
# Future
from __future__ import print_function
# Built-ins
import os
import re
import sys... |
import numpy as np
import networkx as nx
from sklearn import metrics
import hypercomparison.utils
logger = hypercomparison.utils.get_logger(__name__)
class LinkPredictionTask(object):
"""
Link prediction object
Given a test edges and negative edges and embedding, calculate ROC_AUC values.
"""
def... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Rene Liebscher
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-25 17:54
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('estoque', '0002_initial_data'),
('estoque', '0002_auto_20170625_1450'),
]
operation... |
import csv
import random
import time
import argparse
import os
import cv2
import flow_vis
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from network import *
from utils import *
from metrics import PSNR, SSIM, MSE
torch.backends.cudnn.dete... |
# Copyright (c) 2017 Blemundsbury AI Limited
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publ... |
import os
import pytest
import shutil
from muri.muda import Scale, Noise, NoiseScale, Transform
from muri.kantan import Scaler, Ichi, Ni, San, Both
def default_settings_model():
'''Returns default settings for scaling function (cpu)'''
scaler = Scale()
settings = scaler.config()
return settings.model... |
# Exercício Python 082:
# Crie um programa que vai ler vários números e colocar em uma lista.
# Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente.
# Ao final, mostre o conteúdo das três listas geradas.
lista_valores = list()
lista_par = list()
... |
from os import path
import numpy as np
import pandas as pd
import impyute as impy
from matplotlib import pyplot as plt
plt.close("all")
data_path = 'data'
# read geographic information for capitals
municipios = pd.read_csv(path.join(data_path, 'population_capitals.csv'))
# population density
municipios['density'] = m... |
#!/usr/bin/env python
#
# Copyright (c) 2017, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
#
# All rights reserved.
#
# The Astrobee platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in ... |
"""LBANN Python frontend."""
import sys
import os.path
import configparser
# Check for Python 3
if sys.version_info[0] != 3:
raise ImportError('Python 3 is required')
# Try getting build-specific paths from config file
_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
... |
def getSNP(SNPLine):
# Gets the SNP from a line with SNP information
if SNPLine == "":
return [("", 0), True]
SNPLineElements = SNPLine.strip().split("\t")
SNPPosition = (SNPLineElements[0], int(SNPLineElements[1]))
return [SNPPosition, False]
def findENCODEPeakOverlap(ENCODEFileName, SNPFileName, ... |
import argparse
import subprocess
import glob
import re
import os
parser = argparse.ArgumentParser(description='Installing ThirdParty')
parser.add_argument('--all', help='install all dependencies', default=True)
parser.add_argument('--reinstall_all',
help='re-install all dependencies', default=Fal... |
import numpy as np
import pandas as pd
import xgboost as xgb
from lifelines import WeibullAFTFitter
from sklearn.neighbors import BallTree
# lib utils
from xgbse._base import XGBSEBaseEstimator
from xgbse.converters import convert_data_to_xgb_format, convert_y
# at which percentiles will the KM predict
from xgbse.non... |
""" Print the third angle of a triangle given two angles"""
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
a, b = [int(i) for i in input().split()]
print(180-(a+b)) |
# Copyright 2018 Platform9 Systems, 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 wr... |
import argparse
from otoole.results.convert import convert_cplex_file
def main():
parser = argparse.ArgumentParser(description="Otoole: Python toolkit of OSeMOSYS users")
parser.add_argument("cplex_file",
help="The filepath of the OSeMOSYS cplex output file")
parser.add_argument("... |
import logging
import discord
from discord.commands import Option, context, permissions, slash_command
from discord.ext import commands
from chiya import config
from chiya.utils import embeds
log = logging.getLogger(__name__)
class PurgeCommands(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
... |
"""Main app/routing for Twitter"""
from flask import Flask, render_template
from models import DB, User, Tweet
from twitter import *
# function to intialize the flask instance
# create the application
def create_app():
"""Create and configuring an instance of the Flask application"""
# location of the Fla... |
from collections import namedtuple
import kornia.color as kc
import torch
import torch.nn as nn
import torch.nn.functional as f
import torchvision.models.vgg as vgg
class GANLoss(nn.Module):
"""PyTorch module for GAN loss.
This code is inspired by
https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix... |
import graphene
from django.utils.text import slugify
from .types import Ushop
from ..core.types import SeoInput, Upload
from ..core.types.common import SeoInput
from ..core.utils import clean_seo_fields, validate_image_file
from ..core.mutations import ( # ClearMetaBaseMutation,; UpdateMetaBaseMutation,
BaseMut... |
from __future__ import annotations
from dataclasses import dataclass
import re
@dataclass(frozen=True)
class CubeGeometry:
x1: int
x2: int
y1: int
y2: int
z1: int
z2: int
@staticmethod
def from_line(line: str) -> CubeGeometry:
return CubeGeometry(*map(int, re.findall(r"-?[0-9]... |
"""MIT License
Copyright (c) 2021 Buco
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribut... |
'''
Created on Aug 6, 2018
@author: fan
Design page subplot
'''
def subplot_design(plot_count=10, base_multiple=4, base_multiple_high_frac = 0.60):
"""subplot grid and size given total plot count
figsize = (width height)
Examples
--------
import Support.graph.subplot as sup_graph_subp... |
#!/usr/bin/env python
# coding: utf-8
# In[20]:
import numpy as np
import math
# In[48]:
class NodeL2():
inputArr=np.zeros((3,1))
def __init__(self,arr):
self.inputArr=np.copy(arr)
def output(self):
return np.sum(np.square(self.inputArr))
def localGradient(self):
return np... |
from . import base
from . import settings
|
import copy
import efficientnet.model as eff
from classification_models.models_factory import ModelsFactory
class BackbonesFactory(ModelsFactory):
_default_feature_layers = {
# List of layers to take features from backbone in the following order:
# (x16, x8, x4, x2, x1) - `x4` mean that features ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.