text stringlengths 957 885k |
|---|
# -*- coding: utf-8 -*-
import argparse
import sys
import numpy as np
from gensim.models import word2vec
from gensim.models.doc2vec import Word2Vec
from keras.layers import Activation, Embedding, Merge, Reshape
from keras.models import Sequential
from keras.preprocessing.sequence import skipgrams, make_sampling_table
... |
import json
import requests
import time
from discord_webhook import DiscordWebhook, DiscordEmbed
webhook_url = 'https://discordapp.com/api/webhooks/672159508675690497/4UtaClAc7rKMJsEvbR4iYf-Razv4M3ZWtkYDOxBzLfiDzJhI7RSFpoLn6iijBiRcaNOR'
webhook = DiscordWebhook(webhook_url)
pid = '508214-660'
headers = {
'Connecti... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
MLM datasets
"""
import random
import torch
from torch.nn.utils.rnn import pad_sequence
from toolz.sandbox import unzip
from .data import (mlm_DetectFeatTxtTokDataset, TxtTokLmdb,
pad_tensors, get_gather_index)
from pytorch_p... |
<reponame>mightyang/yangTools<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : yangTools.py
# Author : yang <<EMAIL>>
# Date : 31.12.2018
# Last Modified Date: 14.03.2019
# Last Modified By : yang <<EMAIL>>
import nuke
import ytEnvInit
from PySide2 import QtWid... |
import curses
from curses import wrapper
#from collections import OrderedDict
from curses.textpad import Textbox, rectangle
import vault
from vault import * # из за загрузки pickle'ом ??? он не видит модули?
import random
def makeWin(x, y, w, h):
win = curses.newwin(h, w, y, x)
win.border()
win.bkgd(curses... |
# -----------------------------------------------------------------------------
# ply: lex.py
#
# Copyright (C) 2001-2015,
# <NAME> (Dabeaz LLC)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
... |
<gh_stars>10-100
import math
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import data
import model
import matplotlib.pyplot as plt
class ArgsClass:
pass
args = ArgsClass()
args.data = './data/' # path of the corpus
args.checkpoint = '' # checkpoint to use
args.mo... |
<gh_stars>0
import numpy as np
import tensorflow as tf
import gym
import ray
from collections import deque
import random
from attempt.utilities.utils import env_extract_dims, flatten_goal_observation
from attempt.models.models import Critic_gen, Actor_gen
from attempt.utilities.her import HERGoalEnvWrapper, HER
from a... |
<reponame>mlubin/SCIP.jl
#!/usr/bin/env python2.7
from collections import OrderedDict
from jinja2 import Template
from lxml import etree
from itertools import chain
import os
import sys
import time
# TODO: add xml dir to source
def log(msg):
print '[%s] %s' % (time.asctime(), msg)
class SCIPXMLParser(object):
... |
# Copyright 2019 Elasticsearch BV
#
# 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 os
class Vertice:
def __init__(self, valor):
self.valor = valor
self.lista_adyacentes = []
def get_valor(self):
return self.valor
def set_numero(self, valor):
self.valor = valor
def get_lista_adyacentes(self):
return self.lista_adyacentes
def set_l... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from... |
import os
from sys import argv
from getpass import getuser
from argparse import ArgumentParser
def user_defaults(mode):
user = getuser()
defaults = {}
###########################################################################
## Add your username here if you want to change default args
###########... |
<filename>chapter06/demo_6.4.py
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2018/12/8 下午3:59
# 6.4 用TensorFlow实现单层神经网络
# 1. 创建计算图会话,导入必要的编程库
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets
# 2. 加载Iris数据集,存储花萼长度作为目标值,然后开始一个计算图会话
... |
import sys
sys.dont_write_bytecode = True
import os
import json
import torch
import torchvision
import torch.nn.parallel
import torch.optim as optim
import numpy as np
from tensorboardX import SummaryWriter
import core.utils.opts as opts
from core.data.datasets.dataset import VideoDataSet, ProposalDataSet
from core.mod... |
#<NAME>
# Algoritmo do banqueiro
# Número de processos
P = 5
# Número de recursos
R = 3
# Função para encontrar a necessidade de cada processo
def calculateprecisa(precisa, max, alocacao):
# Calculando a necessidade de cada P ->processo
for i in range(P):
for j in range(R):
... |
<reponame>AllVides/DB_EDD_G9
from tkinter import *
from tkinter import ttk
from tkinter import messagebox # message box
from LoadData import Data as Cargar
from tkinter import filedialog
from tkinter import Image
class StorageGui(Frame):
def __init__(self, master=None):
super().__init__(master)
... |
<filename>tests/test_adapter.py<gh_stars>0
import random
import unittest
import torch
from datasets import load_dataset
from tests.test_adapter_embeddings import EmbeddingTestMixin
from transformers import (
AutoModel,
AutoModelForSeq2SeqLM,
BartConfig,
BertConfig,
DistilBertConfig,
EncoderDec... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'addSubjectDialogUi.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_AddSubject(object):
def setupUi(self, AddSubject):
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys, os
import argparse
import re
import zipfile
import tempfile
import logging
from evmlab import reproduce, utils
from evmlab import vm as VMUtils
logger = logging.getLogger(__name__)
try:
import flask
app = flask.Flask(__name__, template_folder=os.path... |
<filename>chip8/cpu.py
from .display import Display
from . import instr
import urllib.request
from time import sleep
class Registers:
V = bytearray(16)
I = 0x00
PC = 0x200 # Program counter
SP = 0x00 # Stack pointer
# Sound and display timers
ST = 0x00
DT = 0x00
class CPU(object):
... |
# # Desafio Semantix
# Responda as seguintes questões devem ser desenvolvidas em Spark utilizando a sua linguagem de preferência.
#
#
# 1) Número de hosts únicos.
# r) 161884
# In[2]:
#testando variavel do Spark
sc
# In[3]:
#Acessando arquivo Julho
base = sc.textFile("C:/Users/h_eiz/desafio... |
<reponame>jorisvandenbossche/pydov
# -*- coding: utf-8 -*-
"""Module containing the search classes to retrieve DOV borehole data."""
import pandas as pd
from pydov.search.abstract import AbstractSearch
from pydov.types.fields import _WfsInjectedField
from pydov.types.grondmonster import Grondmonster
from pydov.util im... |
### after training with bce resnet101, try to use lstm to further improve the performance
import logging
from datetime import datetime
import argparse
import os
from munkres import Munkres
from scipy.stats import logistic
from future.utils import iteritems
import numpy as np
from collections import OrderedDict
from skl... |
import logging
from typing import Union
class CodingString:
def __init__(self, hex_string: str, endian: str = "little") -> None:
"""
Work with Hexstring
:param hex_string:string Format shall be like "23A4", an hexstring has to be an even-number!
:param endian: str: possible: "lit... |
<gh_stars>100-1000
"""
Utilities for populating the dataset for bounding box collection.
You will need to insert an image and category collection into the database.
The instructions dict consists of:
{
id : str
title : str
description : str
instructions: url
examples: [url]
}
Where instructions is a url to ... |
<gh_stars>0
"""
**CollectionCost.py**
- Created by <NAME> for Offshore BOS
- Refactored by <NAME> for LandBOSSE
NREL - 05/31/2019
This module consists of two classes:
- The first class in this module is the parent class Cable, with a sublass Array that inherits from Cable
- The second class is the ArraySystem class... |
<reponame>lidofinance/AVotesParser<gh_stars>0
"""
Decoding payload of aragon votes.
"""
from dataclasses import dataclass
from typing import (
Union, Tuple,
List, Any,
Dict, Optional
)
import web3
from .ABI.storage import (
CachedStorage, ABI, ABIKey
)
from .pretty_printed import PrettyPrinted
from .s... |
# Copyright 2018 Tile, Inc. All Rights Reserved.
#
# The MIT License
#
# 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, ... |
<filename>top_daily_run.py
"""
Top level python launcher
User must define a few constant:
_PYTHON : the complete path to your Python exe
_ROOT_DIR: the complete path to the location of this repository
"""
from datetime import datetime
import os
import key as pconst
import top_runner_util as util
_ROOT_DIR = os.get... |
<reponame>wtsi-hgi/warden
import json
import urllib.request
import datetime
import base64
import ldap
import socket
import flask
app = flask.Flask(__name__, static_url_path="/treeserve/static")
# group:IP mapping for active instances
ACTIVE_INSTANCES = {}
def isUserHumgen():
"""
Determines whether the user ... |
<filename>models/NASFPN/builder.py
import mxnet as mx
import mxnext as X
from mxnext.complicate import normalizer_factory
from symbol.builder import Neck
def merge_sum(f1, f2, name):
"""
:param f1: feature 1
:param f2: feature 2, major feature
:param name: name
:return: sum(f1, f2), feature map s... |
<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2017, Data61
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# ABN 41 687 119 230.
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# ... |
<reponame>seznam/flexp
"""Inspector has the ability to print out data flowing through any module.
Usage: Chain([inspect(MyModule())])
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import collections
import ppri... |
import sys
seed = 42
eps = sys.float_info.min
log_eps = sys.float_info.min_exp
min_x = 0.001
max_x = 3.501
n_bins = 10
n_gals = 4
cat_out_rate = 0.1
cat_out_mean = 1.
cat_out_sigma = 0.01
constant_sigma = 0.03
constant_bias = 0.003
gr_threshold = 1.2
n_accepted = 3
n_burned = 2
plot_colors = 5
dpi = 250
def c... |
<reponame>kalekundert/linersock
class Conversation:
"""
Manages a messaging system that allows two participants to carry out brief
conversations. During the conversation, each participant can easily
transition back and forth between sending requests and waiting for
responses. These transitions ... |
from pyrosetta import init, create_score_function
from pyrosetta import rosetta
from pyrosetta.rosetta.core.pose import setPoseExtraScore
from pyrosetta import pose_from_file
from pyrosetta.rosetta.core.scoring import CA_rmsd
from pyrosetta.rosetta.protocols import rosetta_scripts
from pyrosetta.rosetta.core.scoring im... |
# coding=utf-8
# Copyright 2019 The SEED 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 or agre... |
import logging
from claf.metric.glue import pearson_and_spearman
from claf.metric.regression import mse
from claf.model.base import ModelBase
logger = logging.getLogger(__name__)
class Regression:
""" Regression Mixin Class """
def make_predictions(self, output_dict):
"""
Make predictions ... |
<reponame>SmartDogHouse/SmartDogHouse-Software
from secret import MQTT_HOST
from pins import VALVE_PIN, WATER_SENSOR_PIN, SCALE_PIN_SCK, SCALE_PIN_DT, MOTOR_PIN, B_MOTOR_PIN, F_MOTOR_PIN, LIGHT_SENSOR_PIN
from pins import LASER_PIN, LIMIT_SWITCH_OPEN_PIN, LIMIT_SWITCH_CLOSE_PIN, DS18x20_PIN, HEARTBEAT_PIN
from static_v... |
<gh_stars>1-10
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, TextInput, CheckboxButtonGroup
from bokeh.plotting import figure
# Set up widgets
text = TextInput(title="title", value='Sound Interfer... |
<reponame>birkin/reporting_project
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Django settings for reporting_project.
Environmental variables triggered in project's env_ts_rprt/bin/activate, when using runserver,
or env_ts_rprt/bin/activate_this.py, when using apache via passenger.
"""
impo... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from deepke.model import BasicModule, Embedding
class CNN(BasicModule):
def __init__(self, vocab_size, config):
super(CNN, self).__init__()
self.model_name = 'CNN'
self.vocab_size = vocab_size
self.word_dim = config... |
<filename>rbac/ledger_sync/subscriber.py
# Copyright 2018 Contributors to Hyperledger Sawtooth
#
# 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... |
<reponame>hubbs5/public_drl_sc
# <NAME>
# 29.01.2018
# Update 16.05.2018
# Adjust the inventory portion of the state representation to be the inventory
# divided by the order required within the planning horizon.
# This function takes a network as an argument to generate schedules.
import numpy as np
from ... |
<reponame>JRC1995/Continuous-RvNN
class optimizer_config:
def __init__(self):
# optimizer config
self.max_grad_norm = 1
self.batch_size = 128
self.train_batch_size = 128
self.dev_batch_size = 128
self.bucket_size_factor = 10
self.DataParallel = True
se... |
import traceback
import wx, wx.xrc
from WikiExceptions import *
# from wxHelper import *
from . import MiscEvent
from .Utilities import DUMBTHREADSTOP
from .wxHelper import GUI_ID, XrcControls, autosizeColumn, wxKeyFunctionSink
from .WikiPyparsing import buildSyntaxNode
try:
from EnchantD... |
"""
To test the performance of Fine Tuned ResNet-50
"""
from __future__ import print_function
#To reduce verbosity
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']= '3'
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils
from keras.callbacks import ReduceLROnPlateau, CSVLogger, Earl... |
<gh_stars>10-100
from . import SubCommand
from .common import *
from media_management_scripts.tvdb_api import TVDB
from media_management_scripts.utils import create_metadata_extractor
from media_management_scripts.support.metadata import Metadata
from media_management_scripts.support.episode_finder import extract
from... |
<reponame>Adeikalam/projet_trading_auto<gh_stars>1-10
import os
import re
import sys
import warnings
from colorsys import hls_to_rgb, rgb_to_hls
from itertools import cycle, combinations
from functools import partial
from typing import Callable, List, Union
import numpy as np
import pandas as pd
from bokeh.colors imp... |
import boto3
'''
How to use:
Modify the event and profile variable definitions and execute the script
python3 ./Create_MediaPackage_Channel.py
What does it do:
This script will create a MediaLive Input, one of two prerequisies for
creating a MediaLive Channel.
Dependencies:
This script assumes an appropriate Lambda e... |
<filename>convert.py<gh_stars>1-10
# Quick to write and slow to run Doxygen to XML Comment converter.
# <NAME> 2011
def endComment():
"""
@brief Reset the values for the next comment block.
"""
global sEType, sEVar, sEData, iIndent
sEType = BRIEF
sEVar = None
sEData = ""
iIndent = -1
def handleEx... |
import sys, pickle, os, time, yaml
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(cur_dir, 'scholar_py'))
import scholar
cache_file = os.path.join(cur_dir, 'papers.pkl')
yaml_cache_file = os.path.join(cur_dir, 'papers_cache.yml')
def get_paper_data(querier, paper):
if type(paper... |
#!/usr/bin/python3
'''A set of convenience functions for converting among different phone codes.
Usage:
import phondler
print phondler.CODES # the known phone codes
print phondler.LANGUAGES # the known languages
s1 = phondler.convert(s0, code0, code1, language)
# s0 and s1 are strings containing in... |
from PyQt5.QtCore import QPoint
from PyQt5.QtCore import Qt, pyqtSlot, pyqtSignal
from PyQt5.QtGui import QContextMenuEvent
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QAction
from PyQt5.QtWidgets import QActionGroup
from PyQt5.QtWidgets import QMenu
from PyQt5.QtWidge... |
import matplotlib
matplotlib.use("TKAgg")
import matplotlib.pyplot as plt
from matplotlib import animation
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
import random
def move2str(move):
return str(move).replace('player ', '')
class Tree(object):
def __init__(self):
self.trees =... |
# !/usr/bin/env python
"""
Copyright (C) 2018 Intel Corporation
?
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
?
http://www.apache.org/licenses/LICENSE-2.0
?
Unless required by applicable law or a... |
from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import dataflow_fft4
expected_verilog = """
module test
(
);
reg CLK;
reg RST;
reg signed [16-1:0] din0re;
reg signed [16-1:0] din0im;
reg signed [16-1:0] din1re;
reg signed [16-1:0] din1im;
reg signed [16-1... |
"""AIGER circuit class based on
https://github.com/mvcisback/py-aiger/blob/main/aiger/parser.py"""
import re
class Header:
def __init__(self, max_var_id: int, num_inputs: int, num_latches: int,
num_outputs: int, num_ands: int):
self.max_var_id = max_var_id
self.num_inputs = num_... |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
.. image:: https://user-images.githubusercontent.com/32848391/46815773-dc919500-cd7b-11e8-8e80-8b83f760a303.png
A python module for scientific analysis and visualization of 3D objects and point clouds based on VTK and numpy.
"""
__author__ = "<NAME>"
_... |
<reponame>sannidhiteredesai/PersonalAccountant<filename>test/pa/test_report15g.py<gh_stars>1-10
from unittest import TestCase
from pa.pa.report15g import *
import pa.pa.report15g as report15g
from datetime import date
import datetime
class MockDateTime(datetime.datetime):
@classmethod
def now(cls): return cls... |
<reponame>zairwolf/pilot
# --------------------------------------------------------------------------- #
# #
# from: https://github.com/jyoung8607/openpilot/tree/vw-community-private-pq #
# verify: <EMAIL>(https://shop442817640.taobao.com) ... |
<gh_stars>1-10
from typing import Union, Optional, List, Dict, Any
import datasets
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from transformers import RobertaTokenizer, PreTrainedTokenizerBase
from loguru import logger
from dataclasses import dataclass
from transformers.file_utils import Pad... |
<reponame>rowedenny/ULTRA_pytorch<filename>ultra/learning_algorithm/pairwise_debias.py
"""Training and testing the Pairwise Debiasing algorithm for unbiased learning to rank.
See the following paper for more information on the Pairwise Debiasing algorithm.
* <NAME>, <NAME>, <NAME>, and <NAME>. "Unbiased LambdaMAR... |
#
# Copyright (c) 2009-2015 <NAME> <<EMAIL>>
#
# See the file LICENSE.txt for your full rights.
#
"""Driver for sqlite"""
from __future__ import with_statement
import os.path
# Import sqlite3. If it does not support the 'with' statement, then
# import pysqlite2, which might...
import sqlite3
if not hasattr(sql... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2015 CNRS
# 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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Raspiled - HTTP Listener
Listens on HTTP port 9090 for commands. Passes them on to any classes
running.
@requires: twisted
"""
from __future__ import unicode_literals
import os
import sys
# Add some gymnastics so we can use import... |
<reponame>sraaphorst/gem_adapt_queue
# <NAME> 17 July 2018
# This module contains the individual weight function components.
# obsweight is the main function.
import numpy as np
import astropy.units as u
def radist(ra, tot_time, obs_time, verbose = False):
"""
Compute weighting factors for RA distribution of... |
<filename>ckanext/activity/tests/logic/test_action.py
# -*- coding: utf-8 -*-
import copy
import datetime
import time
import pytest
import ckan.plugins.toolkit as tk
import ckan.tests.helpers as helpers
import ckan.tests.factories as factories
from ckanext.activity.model.activity import Activity, package_activity_... |
# # ⚠ Warning
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA... |
# Copyright 2016 OVH SAS
# 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 appli... |
<filename>src/email_verification/views.py
import base64
import io
import os
import re
import json
import time
from datetime import datetime
import qrcode
import requests
from django.http import (
JsonResponse,
HttpResponse,
HttpResponseRedirect,
HttpResponseBadRequest,
)
from django.template import l... |
# coding=utf-8
# Copyright (c) 2020 Alibaba PAI team and The HuggingFace Inc. team.
#
# 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
#
# Unle... |
# Copyright 2018 BigBitBus 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 ... |
import appdaemon.plugins.hass.hassapi as hass
class PresenceAggregator(hass.Hass):
"""App to determine current presence for a person.
Args:
trackers: List of device_trackers to use to determine presence. Each should use a unique method of tracking.
presence_select: The input_select object to change when... |
<filename>sc-project/SC101_Assignment3_DS/stanCodoshop.py
"""
File: stanCodoshop.py
----------------------------------------------
SC101_Assignment3
Adapted from <NAME>'s
Ghost assignment by <NAME>.
-----------------------------------------------
The code in the function solve(images) mainly uses a double for loop to... |
<reponame>harewei/reinforcement_learning<filename>agents/DDQN.py
# Double DQN. Compared to DQN, it uses q_network rather than target_q_network
# when selecting next action when extracting next q value.
import numpy as np
import os
import random
from agent import Agent
import tensorflow as tf
tf.compat.v1.disable_eag... |
# 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 agreed to ... |
<gh_stars>0
import flatbuffers
import File
import numpy
from websocket import create_connection
from time import time
# 1.99 GB
#BUFFER_SIZE = 1990000000
# 1.99 MB
BUFFER_SIZE = 1990000
# 50 MB
#BUFFER_SIZE = 500000000
START_TIME = time()
# TO-DO:
# filen är seg som satan
# timea de olika delarna och kolla vad s... |
"""
File: chapter04/mqtt_led.py
A full life-cycle Python + MQTT program to control an LED.
Dependencies:
pip3 install paho-mqtt gpiozero pigpio
Built and tested with Python 3.7 on Raspberry Pi 4 Model B
"""
import logging
import signal
import sys
import json
from time import sleep
from gpiozero impo... |
# pylint: disable=unnecessary-pass,logging-fstring-interpolation,logging-format-interpolation,raise-missing-from, unused-argument, line-too-long, too-many-arguments, no-self-use,missing-function-docstring,protected-access
"""Common functions used in BDD"""
import json
import boto3
import time
import botocore.exceptions... |
# coding=utf-8
# @Author : zhzhx2008
# @Time : 18-10-9
# Reference: https://github.com/airalcorn2/Recurrent-Convolutional-Neural-Network-Text-Classifier
import os
import warnings
import jieba
import keras.backend as K
import numpy as np
from keras import Input
from keras import Model
from keras.callbacks import... |
<reponame>nikolarobottesla/PyLTSpice<gh_stars>0
# -------------------------------------------------------------------------------
# Name: Histogram.py
# Purpose: Make an histogram plot based on the results of LTSpice.py
#
# Author: <NAME> (<EMAIL>)
#
# Created: 17-01-2017
# Licence: Free
... |
import os
from skimage.filters import gaussian
from PIL import Image
import numpy as np
import cv2
def compress_JPG_image(image, path_original, size=(1920, 1080)) -> str:
"""Convert a given file to JPG file"""
width, height = size
name = os.path.basename(path_original).split(".")
first_name = os.path... |
import json
import time
from random import uniform
import pandas as pd
from processing.utils import infer_gender_image, infer_gender_name, download_images
import os
import re
from bs4 import BeautifulSoup
import pandas as pd
import requests
from constants import *
import urllib
from pathlib import Path
import datetime
... |
<filename>aphla/gui/elempickdlg.py
#!/usr/bin/env python
from __future__ import print_function, division, absolute_import
"""
:author: <NAME> <<EMAIL>>
A dialog for picking elements.
"""
# Copyright (c) 2011 Lingyun Yang @ BNL.
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import (Qt, SIGNAL)
class ElementPick... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
<gh_stars>0
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.template import loader
import json
import logging
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Max
from django.db import transaction
fro... |
<gh_stars>10-100
import json
from rest_framework import authentication
from django.http import *
from rest_framework.authentication import *
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import *
from rest_framework.response import Response
from rest_framework.views import APIView
... |
import re
import tempfile
import pandas as pd
import camelot
import pandas as pd
import requests
import us
import textract
from can_tools.scrapers.official.base import StateDashboard
from can_tools.scrapers import variables, CMU
from typing import Any, Dict
class FloridaCountyVaccine(StateDashboard):
has_locatio... |
<filename>src/Modules/Computer/Mqtt/mqtt_xml.py
"""
@name: PyHouse/src/Modules/Computer/Mqtt/mqtt_xml.py
@author: <NAME>
@contact: <EMAIL>
@copyright: (c) 2015-2016 by <NAME>
@license: MIT License
@note: Created on Jun 4, 2015
@Summary:
"""
# Import system type stuff
import xml.etree.Ele... |
# -*- coding: utf-8 -*-
# 1 2 3 4 5 6 7 |
# 23456789012345678901234567890123456789012345678901234567890123456789012
#
# sim-C-on-Cu-w-Img.py
# jrm 2015-07-08 - use mc3 to simulate C on Cu
import sys
sys.packageManager.makeJavaPackage("gov.nist.microanalysis.NISTMo... |
"""
Module that extracts product values from pyccd results.
All functions assume the proleptic Gregorian ordinal,
where January 1 of year 1 has ordinal 1.
"""
import numpy as np
from datetime import date
def lastchange(pyccd_result, ordinal):
"""
Number of days since last detected change.
Defaults to 0 ... |
import cv2
import numpy as np
def find_lane_pixels(image):
histogram = np.sum(image[image.shape[0] // 2:, :], axis=0)
out_img = np.dstack((image, image, image)) * 255
midpoint = np.int(histogram.shape[0] // 2)
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]... |
from turtle import *
import math
w = Screen()
w.tracer(0)
siz = 20
def turset(t) : t.ht() ; t.color("black") ; t.pu()
def multitask() : w.update()
def A(x=0,y=0,t = Turtle(),tt = Turtle(),ttt = Turtle(),z = siz) :
T = (t,tt,ttt)
for _ in T : turset(_)
t.goto(x,y+z) ; t.setheading(... |
# -*- coding: utf-8 -*-
import logging
from datetime import datetime
from pathlib import Path
from _pytest.logging import LogCaptureFixture
from snooze.parser import SnoozeMatch, SnoozeParser
def test__file_ext() -> None:
assert SnoozeParser._file_ext(Path("foo/bar.py")) == "py"
assert SnoozeParser._file_ex... |
import math
from pyspark import SparkConf, SparkContext
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel
def para_set(training_RDD,validation_for_predict_RDD):
res_rank = []
iterations = 5
seed = 5L
regularization_parameter = 0.1
for rank in range(1,10):
model = ALS.tr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import fontforge
import psMat
import os
import sys
import math
import glob
from datetime import datetime
ASCENT = 1600
DESCENT = 400
SOURCE = os.getenv("JULIAMONO_SB2_SOURCE_FONTS_PATH", "./sourceFonts")
LICENSE = open("./LICENSE.txt").read()
COPYRIGHT = "Copyright (c) 202... |
import sys
sys.path.append('/home/ggoyal/code/yarp/build/lib/python3')
import yarp
import numpy as np
import cv2
import experimenting
import event_library as el
import torch
from os.path import join
from experimenting.utils.visualization import plot_skeleton_2d, plot_skeleton_3d, plot_skeleton_2d_lined
from experiment... |
<reponame>prculley/GeoFinder
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2019. <NAME>
#
# 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; either version 2 of the L... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.