content stringlengths 5 1.05M |
|---|
from .serializers import User |
"""
Other plotting routines outside of matplotlib
"""
import matplotlib.transforms as transforms
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.lines import Line2D
import matplotlib.dates as mdates
from matplotlib import collections
from matplotlib.ticker impo... |
import win32gui
from src.services.window_managers.base_window_manager import WindowTitleManager
class WindowsWindowManager(WindowTitleManager):
def fetch_window_title(self) -> str:
window_in_focus = win32gui.GetForegroundWindow()
return win32gui.GetWindowText(window_in_focus)
|
import requests
from bs4 import BeautifulSoup
LIMIT = 50
URL = f"https://www.indeed.com/jobs?q=python&limit={LIMIT}"
def _check_has_first_page_end() -> bool:
"""Check if the first page has a link to the last page"""
first_response = requests.get(URL)
soup = BeautifulSoup(first_response.text, "h... |
from django.contrib import admin
from django.urls import include, path
from accounts.author.api import (
ForgetPasswordView,
LoginAuthorAPIView,
RegisterAuthorView,
)
from accounts.editor.api import (
ForgetEditorPasswordView,
LoginEditorAPIView,
RegisterEditorView,
)
from accounts.reviewer.api... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Useful functions for Counter manipulation.
"""
from collections import Counter
def scale(cntr, factor):
cntr_ = Counter()
for key, value in cntr.items():
cntr_[key] = value * factor
return cntr_
def normalize(cntr):
return scale(cntr, 1./sum(... |
# Copyright 2017-2018 The Open SoC Debug Project
#
# 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 agr... |
from __future__ import absolute_import
import os.path
import sys
import threading
import typing
import attr
from ddtrace.internal import compat
from ddtrace.internal import nogevent
from ddtrace.internal.utils import attr as attr_utils
from ddtrace.internal.utils import formats
from ddtrace.profiling import collecto... |
"""
Added dag name column to executions
Revision ID: e937a5234ce4
Revises: a472b5ad50b7
Create Date: 2021-02-25 12:14:38.197522
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "e937a5234ce4"
down_revision = "a472b5ad50b7"
branch_labels = None
depends_on = None
... |
# Generated by Django 3.1 on 2020-08-05 10:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('website', '0010_auto_20200804_1433'),
]
operations = [
migrations.AlterModelOptions(
name='userplugin',
options={'ordering': (... |
from pathlib import Path
def findFullFilename(path, pattern):
filenameGenerator = Path(path).glob(pattern)
firstPath = next(filenameGenerator, None)
if firstPath is None:
return None
return firstPath.name
def findPywFilenameHere(pattern):
return findFullFilename(".", f"{pattern}*... |
from heuristicSearch.planners.astar import Astar
from heuristicSearch.envs.env import GridEnvironment
from heuristicSearch.graph.node import Node
from heuristicSearch.envs.occupancy_grid import OccupancyGrid
from heuristicSearch.utils.visualizer import ImageVisualizer
from heuristicSearch.utils.utils import *
import m... |
#! /usr/bin/env python
from pathlib import Path
import re
import uxn
import sys
token_prog = re.compile(r"\s*(\)|\S+)")
line_comment_prog = re.compile(r".*")
string_prog = re.compile(r".*?(?<!\\)\"")
fixed_prog = re.compile(r"(-|\+)?\d+\.\d+")
prefix_chars = '%:.;,@&|$#~\'"'
def eprint(s):
sys.stderr.write(f"{... |
# Python3 program for Painting Fence Algorithm
# optimised version
# Returns count of ways to color k posts
def countWays(n, k):
dp = [0] * (n + 1)
total = k
mod = 1000000007
dp[1] = k
dp[2] = k * k
for i in range(3,n+1):
dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])... |
"""
Manipulate Excel workbooks.
"""
from datetime import datetime
import os
from openpyxl import Workbook
from openpyxl.styles import NamedStyle, Font, Border, Side, PatternFill
from trellominer.api import trello
from trellominer.config import yaml
class Excel(object):
def __init__(self):
self.config =... |
# -*- coding: utf-8 -*-
"""
This is the Keras implementation for the GermEval-2014 dataset on NER
This model uses the idea from Collobert et al., Natural Language Processing almost from Scratch.
It implements the window approach with an isolated tag criterion.
For more details on the task see:
https://www.ukp.tu-dar... |
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
application = Cling(get_wsgi_application())
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: fabric_next.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 import reflection as _r... |
import torch as th
import numpy as np
from gym import Env
from gym.spaces import Discrete, MultiDiscrete
__all__ = [
"MatrixGameEnv"
]
class MatrixGameEnv(Env):
def __init__(self, matrices, reward_perturbation=0, rand: th.Generator = th.default_generator):
super().__init__()
matrices ... |
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
else:
unicode = str
import os
from matplotlib import rc
from matplotlib import rcParams
font_size=14
rcParams["backend"] = "PDF"
rcParams["figure.figsize"] = (4, 3)
rcParams["font.family"] = ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# 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 agreed to in... |
#!/usr/bin/env python3
import argparse
import sys
import logging
from pathlib import Path
from capanno_utils.validate import *
from capanno_utils.validate_inputs import validate_inputs_for_instance
from capanno_utils.helpers.validate_cwl import validate_cwl_tool
from capanno_utils.helpers.get_paths import get_types_fr... |
_base_ = [
'../../_base_/models/vision_transformer/vit_large_p16_sz224.py',
'../../_base_/datasets/imagenet/swin_sz384_8xbs64.py',
'../../_base_/default_runtime.py',
]
# model
model = dict(backbone=dict(img_size=384))
# data
data = dict(imgs_per_gpu=64, workers_per_gpu=6)
# additional hooks
update_interv... |
from rest_framework import serializers
from core.models import Link, Comment
class LinkSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Link
class CommentSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Comment
|
# Generated by Django 3.2.4 on 2021-06-23 21:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timewebapp', '0044_alter_settingsmodel_first_login'),
]
operations = [
migrations.AlterField(
model_name='settingsmodel',
... |
import pytest
import os
@pytest.mark.processor("gpu")
@pytest.mark.model("placeholder")
@pytest.mark.skip_cpu
@pytest.mark.skip_py2_containers
def test_placeholder():
pass
|
#!/usr/bin/env python
'''
Experimental viewer for DAVIS + OpenXC data
Author: J. Binas <jbinas@gmail.com>, 2017
This software is released under the
GNU LESSER GENERAL PUBLIC LICENSE Version 3.
Usage:
Play a file from the beginning:
$ ./view.py <recorded_file.hdf5>
Play a file, starting at X percent:
$ ./view.py... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from pages.top_bars.top_navigate_bar import TopNavigateBar
class TemplatesPage(TopNavigateBar):
""" Templates page - contains variety of templates to select """
_TEMPLATES_BLOCK = (By.CSS_SELECTOR, "#templ... |
#Hall bar geometry device. Measurements have r_xx and/or r_xy
import numpy as np
import matplotlib.pyplot as plt
import warnings
from scipy.signal import savgol_filter
from pylectric.analysis import mobility
from scipy import optimize as opt
class Meas_GatedResistance():
"""Class to handle a single sweep of raw da... |
import pyautogui
import time
while True:
initial_mouse = pyautogui.position()
time.sleep(0.5)
final_mouse = pyautogui.position()
print(initial_mouse)
print(final_mouse)
if initial_mouse != final_mouse:
pyautogui.hotkey("alt","tab")
else:
exit
|
'''
Crie um programa:
Leia o nome de um aluno
leia duas notas do aluno
guarde em uma lista composta
no final mostre:
Um boletim contendo:
A média de cada um
permita que o usuário possa mostrar as notas de cada aluno individualmente
'''
alunos = list()
while True:... |
"""
pyTRIS
------
pyTRIS - a simple API wrapper for Highways England's WebTRIS Traffic Flow API.
"""
from .api import API
from . import models
__all__ = ['API']
|
# -*- coding: utf-8 -*-
"""
created by huash06 at 2015-04-15 08:45
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
如果是求不连续的字串
方法1:
令f(i,j)表示s[i:j+1]的最长回文的长度
if s[i]==s[j]:
f(i,j) = f(i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 13:10:45 2018
@author: aloswain
"""
from datetime import datetime
import backtrader as bt
class SmaCross(bt.SignalStrategy):
def __init__(self):
sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
crossover = bt.ind.Cr... |
'''
Algoritmo de Prim
1. T ← vazio;
2. V' ← {u};
3. para-todo v E V – V' faça
4. L(v) ← peso ({u,v});
5. fim-para-todo
6. enquanto V' != V faça
7. ache um vértice w tal que L(w) = min {L(v) | v E V-V'};
8. u = o vértice de V', ligado a w, representando a aresta com o menor custo;
9. e = {u,w};
10... |
#! /usr/bin/python
from pylab import *
from sys import argv,exit,stdout
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
from scipy import interpolate
import numpy as np
from finite_differences_x import *
from interp import *
def read_EFIT(EFIT_file_name):
EFITdict = {}
f = open(... |
# from __future__ import absolute_import
from abstractions.recognition import DistanceEstimator
import numpy
from typing import List
class NumpyDistanceEstimator(DistanceEstimator):
def distance(self,
face_features_we_have : [bytes],
face_feature_to_compare
) -> List[float]:
if len(face... |
import json
import os
import random
import sqlite3
import urllib
import requests
from flask import Flask
app = Flask(__name__)
def get_cursor():
connection = sqlite3.connect("database.db")
c = connection.cursor()
return c
USER_ID = 1
def init_db():
c = get_cursor()
c.execute("""
CREATE T... |
#######################################################################
### Script for Calling Plotting Scripts and Merging the Plots ###
#######################################################################
import sys
current_path = sys.path[0]
ex_op_str = current_path[current_path.index('progs')+6: current_p... |
from heapq import heappush, heappop, heapify
import itertools
class Queue:
def __init__(self):
self.q = []
def enqueue(self, element):
self.q.append(element)
def dequeue(self):
return self.q.pop(0)
def is_empty(self):
return len(self.q) == 0
def front(self):
return self.q[0]
class DisjointSets:
d... |
# import pytest
# from ..accessor import session
# @pytest.mark.skip(reason="initial run on gh actions (please remove)")
# def test_session():
# """
# tests that a session can be created without error
# """
# with session() as db:
# assert db
|
"""
This file builds Tiled Squeeze-and-Excitation(TSE) from paper:
<STiled Squeeze-and-Excite: Channel Attention With Local Spatial Context> --> https://arxiv.org/abs/2107.02145
Created by Kunhong Yu
Date: 2021/07/06
"""
import torch as t
def weights_init(layer):
"""
weights initialization
Args :
--layer: one la... |
from typing import Iterable
from eth2spec.test.context import PHASE0
from eth2spec.test.phase0.genesis import test_initialization, test_validity
from gen_base import gen_runner, gen_typing
from gen_from_tests.gen import generate_from_tests
from eth2spec.phase0 import spec as spec
from importlib import reload
from eth... |
#!/usr/bin/env python
import os
import sys
import shutil
download_fail_times = 0
pvmp3_path = sys.path[0]
download_path = os.path.join(pvmp3_path, "source")
final_src_path = os.path.join(pvmp3_path, "src")
print('download pvmp3 source file')
if not os.path.exists(final_src_path):
while True:
if not os.p... |
import csv
from environs import Env
env = Env()
env.read_env()
fieldnames = ['id', 'nome_da_receita', 'descricao_da_receita']
def listar_receitas():
with open(env('RECEITAS_CSV')) as f:
reader = csv.DictReader(f)
return [receita for receita in reader]
def buscar_receitas(nome):
with open(... |
from datetime import datetime, timedelta
from pynput.keyboard import Listener as KeyboardListener
from pynput.mouse import Listener as MouseListener
from apis.mongo.mongo_client import log_event, log_processes
from apis.monitoring_details.win32_window_details import active_window_process, all_open_windows
# logging.... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# noc.core.snmp.ber tests
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ------------------------------------------------------... |
import logging
from itertools import cycle, islice
from typing import Callable, List, Optional
import torch
from hypergraph_nets.hypergraphs import (
EDGES,
GLOBALS,
N_EDGE,
N_NODE,
NODES,
RECEIVERS,
SENDERS,
ZERO_PADDING,
HypergraphsTuple,
)
from strips_hgn.hypergraph.hypergraph_v... |
# Generated by Django 2.2.7 on 2019-12-18 14:21
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),
('catalog', '0003_favourit... |
# always write to disk
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler'
]
STATIC_URL = '/static/'
STATIC_ROOT = '/app/public'
MEDIA_ROOT = '/data'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDire... |
import os
import keras
import random as rn
import numpy as np
import tensorflow as tf
from keras.layers import Dense, Activation, Embedding
from keras.layers import Input, Flatten, dot, concatenate, Dropout
from keras import backend as K
from keras.models import Model
from keras.engine.topology import Layer
from keras... |
from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
import unidecode as udc
import scipy
class CustomOneHotEncoder(BaseEstimator, TransformerMixin):
"""
Clase que convierte a dummies las variables categóricas de un dataFrame. Permite eliminar
las dummies creadas según su re... |
# -*- coding: utf-8 -*-
###########################################################
# #
# Copyright (c) 2018 Radek Augustýn, licensed under MIT. #
# #
#######################################################... |
"""
Check if 2 strings are anagrams of each other
"""
from collections import Counter
def check_anagrams(str1, str2):
ctr1 = Counter(str1)
ctr2 = Counter(str2)
return ctr1 == ctr2
def check_anagrams_version2(str1, str2):
hmap1 = [0] * 26
hmap2 = [0] * 26
for char in str1:
pos = ord... |
import sys
import os
#reference = sys.argv[1]
#os.system("cp "+reference+" "+sys.argv[4])
firstfile = sys.argv[1] #sys.argv[1]
secondfile = sys.argv[2]
thirdfile = sys.argv[3]
seq1 = set()
seq2 = set()
file3 = open(thirdfile, 'r')
for line in file3:
myline = line.strip()
seqnames = myline.split('\t')
seq... |
class TicTacToe():
'''
Game of Tic-Tac-Toe
rules reference: https://en.wikipedia.org/wiki/Tic-tac-toe
'''
# coordinates of the cells for each possible line
lines = [ [(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)],
[(0,0), (1,0), (2... |
import cv2
import numpy as np
# Read image
img = cv2.imread("imori.jpg")
# Dicrease color
out = img.copy()
out = out // 64 * 64 + 32
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import collections.abc
import json
import typing
from azure.functions import _sql as sql
from . import meta
class SqlConverter(meta.InConverter, meta.OutConverter,
binding='sql'):
@classmethod
... |
'''
This program parses a txt file containing proteins to analyse with IUPRED/BLAST/JALVIEW
'''
import warnings # allows program to be able to ignore benign warnings
#####
# IGNORE WARNINGS
#####
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufun... |
from typing import TYPE_CHECKING
from UE4Parse.BinaryReader import BinaryStream
from UE4Parse.Provider.Common import GameFile
if TYPE_CHECKING:
from UE4Parse.IO import FFileIoStoreReader
from UE4Parse.IO.IoObjects.FIoChunkId import FIoChunkId
from UE4Parse.IO.IoObjects.FIoOffsetAndLength import FIoOffsetA... |
# Copyright 2014 The Crashpad 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 applicabl... |
import unittest
import numpy as np
import tensorflow as tf
from pplp.core import box_4c_encoder
class Box4cEncoderTest(unittest.TestCase):
def test_np_box_3d_to_box_4c(self):
# Test non-vectorized numpy version on ortho boxes
# Sideways box
box_3d_1 = np.asarray([0, 0, 0, 2, 1, 5, 0])
... |
from .xml_style import XMLDataset
class VOCDataset(XMLDataset):
CLASSES = ['spike']
def __init__(self, **kwargs):
super(VOCDataset, self).__init__(**kwargs)
|
#!/usr/bin/env python
from .web_api_2 import SwaggerGiant |
import os, paramiko, time, schedule, smtplib, ssl
from datetime import datetime
from email.message import EmailMessage
host='localhost'
port='5432'
user='postgres'
password='admin'
database='testdb'
#chemin de sauvegarde locale
local_dir = 'C:\\Users\\Kamla\\projets\\auto-backup-sqldb\\backup\\'
#local_dir = 'Chemin ... |
from pathlib import Path
import pandas as pd
from collections import defaultdict
from typing import List, Union
from .types import Child
def create_csv(children: List[Child], output_dir: Union[Path,str]):
header_df = create_header(children)
episodes_df = create_episodes(children)
uasc_df = create_uasc(chi... |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--latitude", type=float, required=True, help="The latitude of your bounding box center")
parser.add_argument("--longitude", type=float, required=True, help="The longitude of your bounding box center")
args = parser.parse_args()
dlat = 0.005
dlon =... |
from modules.data.fileRead import readMat
from numpy import arange
from modules.modelar.leastSquares import calculate
# Alternativa para caso as constantes escolhidas não forem escolhidas pelo Usuário
SP = 50
OVERSHOOT = 0.10
TS = 70
# Pegando vetores de entrada e saída
ENTRADA, SAIDA, TEMPO = readMat()
# Calculando... |
import argparse
import os
import pandas as pd
import re
import spacy
import sys
from datetime import datetime
from geopy.extra.rate_limiter import RateLimiter
from geopy import Nominatim
from epitator.geoname_annotator import GeonameAnnotator
from epitator.date_annotator import DateAnnotator
from epita... |
from cmsisdsp.sdf.nodes.simu import *
import numpy as np
import cmsisdsp as dsp
class Processing(GenericNode):
def __init__(self,inputSize,outputSize,fifoin,fifoout):
GenericNode.__init__(self,inputSize,outputSize,fifoin,fifoout)
def run(self):
i=self.getReadBuffer()
o=self.getWrit... |
def say_hi():
print("hello world function")
def cube(num):
return num*num*num
say_hi()
print(cube(3))
# Statements
is_male = False
if is_male:
say_hi()
else:
print("Goodbay")
# Statements
is_female = True
if is_female or is_male:
print("Hi")
else:
print("Goodbay")
# Dictionary
mont... |
import os
from argh.dispatching import dispatch_command
import application
def start_app():
port = int(os.getenv('PORT'))
application.start(port=port)
if __name__ == '__main__':
dispatch_command(start_app)
|
import os
from git import Repo
from django.core.exceptions import PermissionDenied
from base.handlers.extra_handlers import ExtraHandler
from base.handlers.file_handler import FileHandler
from base.handlers.form_handler import FormHandler
from base.handlers.path_handlers import PathHandler
from base.handlers.github_... |
from radixlib.api_types.identifiers import AccountIdentifier
from radixlib.serializable import Serializable
from radixlib.api_types import TokenAmount
from typing import Dict, Any
import radixlib as radix
import json
class TransferTokens(Serializable):
""" Defines a TransferTokens action """
def __init__(
... |
# -*- coding: utf-8 -*-
from flask import render_template, redirect, request, url_for, flash, jsonify, abort
from flask_login import login_user, logout_user, login_required, current_user
from . import estate
from .. import db
from ..models import SzEstate
import urllib
import os
import time
import math
from datetime i... |
# Freetype library
freetype = StaticLibrary( 'freetype', sources = [ 'src/base/*', 'src/gzip/ftgzip.c', 'src/winfonts/winfnt.c', 'src/cid/type1cid.c' ], defines = [ 'FT2_BUILD_LIBRARY', 'FT_CONFIG_OPTION_SYSTEM_ZLIB' ] )
freetype.include( 'include' )
# Add Freetype modules sources
prefix = { 'gzip': 'ft', 'cid': ... |
"""
Created on Wednesday Septebmer 25 17:07 2019
tools to work with XRF data from the Geotek MSCL (Olympus head)
@author: SeanPaul La Selle
"""
import os
import sys
import glob
import tkinter
from tkinter import filedialog
import numpy as np
import csv
import pandas
import matplotlib as matplotlib
import matplotlib.... |
#!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'fútū'
CN=u'扶突'
NAME=u'futu41'
CHANNEL='largeintestine'
CHANNEL_FULLNAME='LargeIntestineChannelofHand-Yangming'
SEQ='LI18'
if __name__ == '__main__':
pass
|
class Bar():
pass
|
import os
import core.settings as st
from flask import Flask
from api.login import app as login_router
from api.create_account import app as account_router
from api.products import app as products_router
from api.producer import app as producer_router
from api.shop_car import app as shop_car_router
from api.order impor... |
# Copyright (c) 2017 Presslabs SRL
#
# 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... |
from .logic import *
from .notifications import *
from .preprocessors import *
from .vigil import *
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2021.03.22
Start operation.
@author: zoharslong
""" |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import sys
import os
import time as t
import numpy as np
import theano as th
import theano.tensor as T
import theano.ifelse
import theano.compile
import theano.compile.mode
import hand_io
############## Objective in theano ##################
... |
# Copyright 2018 Cisco and its affiliates
#
# 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... |
import logging,uuid
from exchangemanager import ExchangeManager
from result import Result
from order import Order
class BacktestManager(ExchangeManager):
def __init__(self, config = {} ):
ExchangeManager.__init__(self, "BTEST", config )
self.balance = None
self.log = logging.getLogger('cry... |
# Import libraries
import matplotlib.pyplot as plt
import numpy as np
# Draw
plt.title("Lines") # put title on plot
plt.plot([-4,2], [-2,-2], "b") # Plot the lines to draw a house
plt.plot([-4,-1], [2,3], "b")
plt.plot([-1,1], [3,5], "b")
plt.plot([2,4], [-2,0], "b")
plt.plot([1,4], [5,4], "b")
plt.plot([1,-2], [5,4... |
# -*- coding: utf-8 -*-
import sys
from optparse import OptionParser;
from xml.dom import minidom;
import re
import os
import csv
import hashlib
import shutil
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from HorizonBuildFileUtil import HorizonBuildFileUtil
import subprocess
class HorizonUE4Buil... |
"""Flategy - a basic playable strategy game & bot."""
import os
import io
import subprocess
import tempfile
import cairo
import IPython.display
import numpy as np
class State:
__slots__ = ['position', 'radius', 'world_shape']
def __init__(self, position, radius, world_shape):
self.position = positi... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from transformers import BertModel, RobertaModel
class EmbeddingGeneratorGLOVE(nn.Module):
def __init__(self, config, path):
super(EmbeddingGeneratorGLOVE, self).__init__()
self.config = config
print('Loa... |
# -*- coding: utf-8 -*-
import time as builtin_time
import pandas as pd
import numpy as np
# ==============================================================================
# ==============================================================================
# ===============================================================... |
import workalendar.africa
import workalendar.america
import workalendar.asia
import workalendar.europe
import workalendar.oceania
import workalendar.usa
from pywatts.core.exceptions.util_exception import UtilException
def _init_calendar(continent: str, country: str):
""" Check if continent and country are corre... |
from django.shortcuts import render
from morad.models import Car
from django.views.generic import (ListView,DetailView,DeleteView,UpdateView,CreateView)
from django.urls.base import reverse_lazy
class ListCars(ListView):
template_name = 'cars/cars.html'
model = Car
class DetailCar(DetailView):
template_nam... |
"""
Tests for string_utils.py
"""
import pytest
from django.test import TestCase
from common.djangoapps.util.string_utils import str_to_bool
class StringUtilsTest(TestCase):
"""
Tests for str_to_bool.
"""
def test_str_to_bool_true(self):
assert str_to_bool('True')
assert str_to_bool(... |
import sys
from datetime import timedelta
def print_expected_call_message(additional_message):
print(f"""{additional_message}
Expected application call:
python3 regex_text.py [searched phrase] [left_padding] [right_padding]
Example call:
python3 regex_text.py "I don't know" 2 3""")
def handle_arguments():
i... |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... |
from import_export import resources
from electricity.models import FeedBack
class FeedBackResource(resources.ModelResource):
class Meta:
model = FeedBack
|
from nose import with_setup
from pybbn.causality.ace import Ace
from pybbn.graph.dag import Bbn
from pybbn.graph.edge import Edge, EdgeType
from pybbn.graph.node import BbnNode
from pybbn.graph.variable import Variable
def setup():
"""
Setup.
:return: None.
"""
pass
def teardown():
"""
... |
__author__ = 'elsabakiu, neilthemathguy, dmorina'
from rest_framework import status, viewsets
from rest_framework.response import Response
from crowdsourcing.serializers.project import *
from rest_framework.decorators import detail_route, list_route
from crowdsourcing.models import Module, Category, Project, Requeste... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.