content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import os
import pickle
from tqdm import tqdm
from config import data_file, thchs30_folder
# split in ['train', 'test', 'dev']
def get_thchs30_data(split):
print('loading {} samples...'.format(split))
data_dir = os.path.join(thchs30_folder, 'data')
wave_dir = os.path.join(thchs30_folder, split)
sa... | python |
#!/bin/env python2
import cairo
import os.path
this = os.path.dirname(__file__)
def millimeters_to_poscript_points(mm):
inches = mm / 25.4
return inches * 72
def css_px_to_poscript_points(px):
inches = px / 96.
return inches * 72
cairo.PDFSurface(os.path.join(this, "A4_one_empty_page.pdf"),
... | python |
import numpy as np
from torch.utils.data import Subset
from sklearn.model_selection import train_test_split
def split_data(dataset,splits=(0.8,0.2),seed=None):
assert np.sum(splits) == 1
assert (len(splits)==2) | (len(splits)==3)
if len(splits) == 2:
train_idx, test_idx, _, _ = train_test_split(ra... | python |
from __future__ import print_function
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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
#
# ... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Matching(nn.Module):
def __init__(self, vis_dim, lang_dim, jemb_dim, jemb_drop_out):
super(Matching, self).__init__()
self.vis_emb_fc = nn.Sequential(nn.Linear(vis_dim, jemb_dim),
nn.B... | python |
import torch
import torch.nn as nn
class LeNet(torch.nn.Module):
"""This is improved version of LeNet
"""
def __init__(self):
super(LeNet, self).__init__()
self.network = nn.Sequential(nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.ReLU(),
nn.MaxPool2d(... | python |
# -*- test-case-name: twisted.positioning.test -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
The Twisted positioning framework.
@since: 14.0
"""
| python |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Libpam(AutotoolsPackage):
"""Example PAM module demonstrating two-factor authentic... | python |
# Copyright 2020 The TensorFlow 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 applica... | python |
'''
This code loads the results and prepares Fig8a.
(c) Efrat Shimron, UC Berkeley, 2021
'''
import os
import matplotlib.pyplot as plt
import numpy as np
R = 4
pad_ratio_vec = np.array([1, 2])
print('============================================================================== ')
print(' ... | python |
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.paginator import Paginator
from go.base import utils
from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper
from go.vumitools.api import VumiAp... | python |
import py
from pypy.translator.cli.test.runtest import compile_function
from pypy.translator.oosupport.test_template.backendopt import BaseTestOptimizedSwitch
class TestOptimizedSwitch(BaseTestOptimizedSwitch):
def getcompiled(self, fn, annotation):
return compile_function(fn, annotation, backendopt=True)
| python |
"""
Low level *Skype for Linux* interface implemented using *XWindows messaging*.
Uses direct *Xlib* calls through *ctypes* module.
This module handles the options that you can pass to `Skype.__init__`
for Linux machines when the transport is set to *X11*.
No further options are currently supported.
Warning PyGTK fr... | python |
#! /usr/bin/env python3
# encoding: UTF-8
#
# Python Workshop - Conditionals etc #2
#
# We'll later cover learn what happens here
import random
#
# Guess a number
# Find a random number between 0 and 100 inclusive
target = random.randint(0, 100)
# TODO:
# Write a while loop that repeatedly asks the user to guess th... | python |
#! /usr/bin/env python
import cyvcf2
import argparse
import sys
from collections import defaultdict, Counter
import pandas as pd
import signal
import numpy as np
from shutil import copyfile
import pyfaidx
from random import choice
from pyliftover import LiftOver
from Bio.Seq import reverse_complement
from mutyper imp... | python |
###############################################################################
# $Id$
# $Author$
#
# Routines to create the inquisitor plots.
#
###############################################################################
# system import
import threading
import string
import os
# enstore imports
import Trace
impor... | python |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
import pytest
from .. import Backend
from . import AVAILABLE_BACKENDS
@pytest.mark.parametrize('key', AVAILABLE_BACKENDS)
def test_Dummy(key):
be = Backend(key)
d0 = be.Dummy()
d1 = be.Dummy()
assert d0 == d0
... | python |
# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang
# Mingshuang Luo)
#
# See ../../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licen... | python |
import time
import cv2
import numpy as np
import tflite_runtime.interpreter as tflite
def _inference(interpreter, input_details, input_data):
'''Inference (internal function)
TensorFlow Lite inference
the inference result can be get to use interpreter.get_tensor
Arguments:
- interpreter: tflite... | python |
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
import subprocess
import sys
import os.path as path
from typing import List, Optional
def run_python_command(local_path: str, args: List[str], python_binary: Optional[str] = None, notbash = True):
"""
run a python subprocess
:param local_path:... | python |
import numpy
from numpy.testing import *
from prettyplotting import *
from algopy.utpm import *
# STEP 0: setting parameters and general problem definition
############################################################
# Np = number of parameters p
# Nq = number of control variables q
# Nm = number of measurements
# P ... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Day 2 of AdventOfCode.com: iterating over arrays doing simple arithmetic"""
import os
from numpy import product
def present_wrap_area(dimensions):
"""
:param dimensions: list of 3 floats: length, width and height
:return: area of wrapping
"""
wrap_area... | python |
# Copy from web_set_price.py of Trading Stock Thailand
# Objective : Create Program to store financial data of company
# From set.or.th
# sk 2018-12-05
import urllib
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
from os.path import join, exists
from os import remove, makedirs
import urllib2 #s... | python |
import nltk
import json
import argparse
from collections import Counter
def build_word2id(seq_path, min_word_count):
"""Creates word2id dictionary.
Args:
seq_path: String; text file path
min_word_count: Integer; minimum word count threshold
Returns:
word2id: Dictionary; word-to-i... | python |
# -*- coding:utf-8 -*-
# Python 字典类型转换为JSON对象
data1 = {
'no': 1,
'name':'Runoob',
'url':'http://www.runoob.com'
}
# 对数据进行编码
import json
json_str = json.dumps(data1)
print("Python原始数据:", repr(data1))
print("JSON对象:", json_str)
# 将JSON对象转换为Python字典
# 对数据进行解码
data2 = json.loads(json_str)
print("data2... | python |
import re
def checkIP(IP):
regex='^([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2}$)'
return re.match(regex,IP)
def checkIP2(n):
return n<=255
a=['123.4.2.222', '0.0.0.0', '14.123.444.2', '1.1.1.1']
print "***** CHECK USI... | python |
#!/usr/bin/env python
import wx
import pcbnew
import os
import time
from .kifind_plugin_gui import kifind_gui
from .kifind_plugin_action import FindAll, DoSelect, __version__
class KiFindDialog(kifind_gui):
"""Class that gathers all the Gui control"""
def __ShowAll(self, do_tracks, do_mm):
self.list... | python |
from app import app
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pandas as pd
import time
import json
from flask import jsonify
@app.route('/')
@app.route('/home', methods=['GET'])
def home():
navegador = webdriver.Chrome()
pessoas = ["Brain+Lag", "Why", "Dankpot7", "Ro... | python |
# Copyright (c) 2019 Horizon Robotics. 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 applicab... | python |
from profiles.models import *
from django.contrib import admin
admin.site.register(FriendGroup)
admin.site.register(UserProfile)
| python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models.query import QuerySet
class CategoryQuerySet(QuerySet):
def by_author(self, user):
return self.filter(author=user)
| python |
seq = input()
a = [(int(seq[i]) + int(seq[i+1]))/2.0 for i in range(len(seq)-1)]
print(a) | python |
#######################################################################
# Tests for applications.py module
#######################################################################
from auto_process_ngs.applications import *
import unittest
try:
from cStringIO import StringIO
except ImportError:
# cStringIO not a... | python |
#!/usr/bin/env python
#
# This examples show how to use accessors to associate scalar data to mesh elements,
# and how to read and write those data from/to mesh files using ViennaGrid's readers
# and writers.
from __future__ import print_function
# In this example, we will illustrate how to read and write scalar dat... | python |
########## Single softmax layer NN build for digit recognition ###################
############ Import modules #################
import mnistdata
import tensorflow as tf
tf.set_random_seed(0)
# Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels)
mnist = mnistdata.read... | python |
import os
os.environ['DJANGO_COLORS'] = 'nocolor'
from django.core.management import call_command
from django.db import connection
from django.apps import apps
from io import StringIO
commands = StringIO()
cursor = connection.cursor()
for app in apps.get_app_configs():
call_command('sqlsequencereset', app.label... | python |
import discord
import os
import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix=':', self_bot=True, help_command=None)
@client.event
async def on_ready():
# Playing
# await client.change_presence(activity=discord.Game(name="a game"))
# Streaming
# await bot.change_pr... | python |
"""
globals.py
File that holds some important static dictionary look-up tables, and some useful
functions used repeatedly in the codebase.
"""
import numpy as np
import pandas as pd
from scipy.special import logit
"""
get_prec_df
Reads in the precinct df given the state and the year.
NOTE: also adds in no... | python |
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'bonn',
'norway':'oslo', 'italy':'rome', 'poland':'warsaw',
'australia':'vienna' }
# Update capital of germany
europe['germany'] = 'berlin'
# Remove australia
del(europe['australia'])
# Print europe
pri... | python |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"f1score": "00_utils.ipynb",
"df_preproc": "00_utils.ipynb",
"load_data": "00_utils.ipynb",
"TestModel": "00_utils.ipynb",
"transform": "00_utils.ipynb",
"windows_... | python |
from __future__ import absolute_import
from collections import OrderedDict
import logging
from tabulate import tabulate
from numpy import asarray
from numpy import sqrt
from numpy import ones
from numpy_sugar.linalg import economic_svd
from ...tool.kinship import gower_normalization
from ...tool.normalize import ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Eric Winn
# @Email : eng.eric.winn@gmail.com
# @Time : 19-9-3 上午7:19
# @Version : 1.0
# @File : __init__.py
# @Software : PyCharm | python |
from typing import Optional
from django.urls import reverse
from django.views.generic import CreateView
from django.http import Http404
from django.utils.functional import cached_property
from task.forms import TaskCreateForm
from ..models import Member
from ..querysets import get_user_teams, get_team_with_members
fr... | python |
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from common.config import Config, workstation_methods
from panel.common.CommonWidgets import *
class WorkstationConfiguration(QWidget):
def __init__(self, workstation_name, workstation_type):
super(WorkstationConfiguration, self).__init__()
... | python |
"""
Digital Communications Function Module
Copyright (c) March 2017, Mark Wickert
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notic... | python |
def validMountainArray(arr):
N = len(arr)
i = 0
while i + 1 < N and arr[i] < arr[i+1]:
i += 1
if i == 0 or i == N-1:
return False
while i + 1 < N and arr[i] > arr [i+1]:
i += 1
return i == N-1
arr = [2,1]
x = validMountainArray(arr)
print(x)
arr1 = [3,5,5]
x = v... | python |
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.generics import (
CreateAPIView,
DestroyAPIView,
ListAPIView,
UpdateAPIView,
RetrieveAPIView
)
from posts.models import Post
from .serializers import (
PostCreateSerializer,
PostListSerializer,... | python |
import bayesnewton
import objax
import numpy as np
import matplotlib.pyplot as plt
import time
# load graviational wave data
data = np.loadtxt('../data/ligo.txt') # https://www.gw-openscience.org/events/GW150914/
np.random.seed(12345)
x = data[:, 0]
y = data[:, 1]
x_test = x
y_test = y
x_plot = x
var_f = 1.0 # G... | python |
import numpy as np
import tinkerbell.app.plot as tbapl
import tinkerbell.app.rcparams as tbarc
from matplotlib import pyplot as plt
fname_img = 'img/time_stage_lstm.png'
def xy_from_npy(fname):
data = np.load(fname)
return (data[0], data[1])
xmax = tbarc.rcparams['shale.lstm_stage.xmax']
y0 = tbarc.rcparams... | python |
# ----------* CHALLENGE 74 *----------
# Enter a list of ten colours. Ask the user for a starting number between 0 and 4
# and an end number between 5 and 9. Display the list for those colours
# between the start and end numbers the user input.
list_colours = ["red", "blue", "green", "yellow", "orange", "purple"... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Classical Heisenberg model Monte Carlo simulator
"""
import json
import os
import shutil
import time
import numpy as np
from kent_distribution.kent_distribution import kent2
from skdylib.spherical_coordinates import sph_urand, xyz2sph
from thermalspin.heisenberg_sy... | python |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'employees.ui'
##
## Created by: Qt User Interface Compiler version 5.15.1
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################... | python |
import pygame, sys, noise, math
from pygame.locals import *
from random import randint, random
pygame.init()
try:
windowSize = int(input("Enter size of window in pixels (e.g. 400): "))
except:
# Give default size of 400px if invalid value entered
windowSize = 400
windowSurface = pygame.displa... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created by Anand Sivaramakrishnan anand@stsci.edi 2018 12 28
This file is licensed under the Creative Commons Attribution-Share Alike
license versions 3.0 or higher, see
http://creativecommons.org/licenses/by-sa/3.0/
Python 3
matrixDFT.perform(): (also matrixDF... | python |
import os
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from .hooks import hookset
from .managers import PublishedPageManager
class Page(models.Model):
STATUS_CHOICES = (
(1, _("Draft")),
(2... | python |
#!/usr/bin/env python
"""
Bookizer
==========
Bookizer get's an almost uncertain number of CSV files and converts them into a big CSV/ODS/XLS/XLSX file
"""
import sys
from setuptools import setup
if sys.version_info.major < 3:
raise RuntimeError(
'Bookizer does not support Python 2.x anymo... | python |
#
# SDK-Blueprint module
# Code written by Cataldo Calò (cataldo.calo@mail.polimi.it) and Mirco Manzoni (mirco.manzoni@mail.polimi.it)
#
# Copyright 2018-19 Politecnico di Milano
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License... | python |
from office365.sharepoint.ui.applicationpages.client_people_picker import \
ClientPeoplePickerWebServiceInterface, ClientPeoplePickerQueryParameters
from tests import test_user_principal_name
from tests.sharepoint.sharepoint_case import SPTestCase
class TestSPPeoplePicker(SPTestCase):
@classmethod
def se... | python |
"""Build indexing using extracted features
"""
import numpy as np
import os, os.path
import pickle
import scipy.spatial
from scipy.spatial.distance import pdist, squareform
"""Build index
Given feature matrix feature_mat,
k is the number of nearest neighbors to choose
"""
def build_index(feature_mat, k):
sample_c... | python |
import sys
import os
import random
import math
import bpy
import numpy as np
from os import getenv
from os import remove
from os.path import join, dirname, realpath, exists
from mathutils import Matrix, Vector, Quaternion, Euler
from glob import glob
from random import choice
from pickle import load
from b... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 21 17:08:55 2020
@author: anon
"""
import subprocess
import numpy as np
import h5py
clear = np.zeros((100000, 2))
noisy = np.zeros((100000, 2))
for i in range(1, len(clear)):
clear[i] = clear[i-1] + np.array([1.,1.])
noisy[i] = clear[i] ... | python |
import sys
from pyramid.config import Configurator
from pyramid.i18n import get_localizer, TranslationStringFactory
from pyramid.threadlocal import get_current_request
def add_renderer_globals(event):
request = event.get('request')
if request is None:
request = get_current_request()
event['_'] ... | python |
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 2
class S... | python |
#!/usr/bin/env python3
# for now assuming the 'derived' repo is just checked out
import fire, yaml, git, os, shutil, sys, pathlib, subprocess, unidiff, time, logging
from neotermcolor import colored
def bold_yellow(text):
return colored(text, color='yellow', attrs='bold')
conf_file = ".differant.yml"
def dird... | python |
from __future__ import print_function
import os
from importlib import import_module
def split_path(path):
decomposed_path = []
while 1:
head, tail = os.path.split(path)
if head == path: # sentinel for absolute paths
decomposed_path.insert(0, head)
break
elif t... | python |
import pytest
from constructure.constructors import RDKitConstructor
from constructure.scaffolds import SCAFFOLDS
@pytest.mark.parametrize("scaffold", SCAFFOLDS.values())
def test_default_scaffolds(scaffold):
# Make sure the number of R groups in the `smiles` pattern matches the `r_groups`
# attributes.
... | python |
from capturewrap.builders import CaptureWrapBuilder
from capturewrap.models import CaptureResult | python |
import flask
from hacktech import auth_utils
from hacktech import app_year
import hacktech.modules.judging.helpers as judging_helpers
from hacktech.modules.applications.helpers import allowed_file
from werkzeug.utils import secure_filename
import os
import PyPDF2
def get_waiver_status(user_id, waiver_type):
query... | python |
from bflib import dice, units
from bflib.items import coins, listing
from bflib.items.ammunition.common import ShortbowArrow, LongbowArrow
from bflib.items.weapons.ranged.base import RangedWeapon
from bflib.rangeset import RangeSet
from bflib.sizes import Size
@listing.register_type
class Bow(RangedWeapon):
pass
... | python |
# Authors: Guillaume Favelier <guillaume.favelier@gmail.com>
#
# License: Simplified BSD
from ...fixes import nullcontext
from ._pyvista import _Renderer as _PyVistaRenderer
from ._pyvista import \
_close_all, _set_3d_view, _set_3d_title # noqa: F401 analysis:ignore
class _Renderer(_PyVistaRenderer):
def __... | python |
import matplotlib.pyplot as plt
import numpy as np
tolerance = 1e-1
radius = np.pi
# missile 1
x_m1, y_m1 = -np.pi, 0
v_m1 = 5
# missile 2
x_m2, y_m2 = 0, np.pi
v_m2 = v_m1
# missile 3
x_m3, y_m3 = np.pi, 0
v_m3 = v_m1
# missile 4
x_m4, y_m4 = 0, -np.pi
v_m4 = v_m1
plt.figure(figsize=(10, 10), dpi=80)
plt.title(" mi... | python |
import framebuf
gc.collect()
import time
gc.collect()
import machine
gc.collect()
import neopixel
gc.collect()
import network
gc.collect()
import urequests
gc.collect()
import utime
gc.collect()
from machine import RTC, I2C, Pin
#from ssd1306 import SSD1306_I2C
import sh1106 #Oled
gc.collect()
impor... | python |
# Import modules
import datetime
import spiceypy
import numpy as np
import pandas as pd
# Load the SPICE kernels via a meta file
spiceypy.furnsh('kernel_meta.txt')
# We want to compute miscellaneous positions w.r.t. the centre of
# the Sun for a certain time interval.
# First, we set an initial time in UTC.
INIT_TIME... | python |
r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | python |
from __future__ import annotations
from typing import List
from dataclasses import dataclass
from ..model import Pos
@dataclass
class SingleCandidate:
pos: Pos
number: int
reason: str = 'unkown'
def __str__(self):
return f'{self.pos.idx}, {self.number}'
@dataclass
class MultiCandidate:
... | python |
"""
Gui for image_dialog
Author: Gerd Duscher
"""
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas
from matplotlib.figure import Figure
from pyTEMlib.microscope import microscope
class MySICanvas(Canvas):
def __init__... | python |
import os
import neuralbody.utils.geometry as geometry
import numpy as np
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class SMPL(nn.Module):
def __init__(self, data_root, gender='neutral', spec='', beta=None):
super(SMPL, self).__init__()
file_path = os.path.join(
... | python |
# Problem Description:-https://leetcode.com/problems/longest-palindromic-substring/
class Solution:
def helper(self, s, left, right):
while left>=0 and right<len(s) and (s[left]==s[right]):
left-=1
right+=1
return s[left+1:right]
def longestPalindrome(self, s: str) -> s... | python |
from builtins import range
from .base import MLClassifierBase
import copy
import numpy as np
class RepeatClassifier(MLClassifierBase):
"""Simple classifier for handling cases where """
def __init__(self):
super(RepeatClassifier, self).__init__()
def fit(self, X, y):
self.value_to_repeat ... | python |
import cv2
import numpy as np
import matplotlib.pyplot as plt
#from matplotlib import pyplot as plt
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files",".*"),("jpg files"... | python |
import numpy as np
from gym.spaces import Box
from gym.spaces import Discrete
import copy
from rlkit.envs.wrappers import ProxyEnv
class ParticleEnv(ProxyEnv):
def __init__(
self,
env,
):
ProxyEnv.__init__(self, env)
self.num_agent = self._wrapped_env.n
self.act... | python |
# ==================================================================
# Copyright (c) 2007,2008,2009 Metaweb Technologies, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistribut... | python |
import numpy as np
import deepdish as dd
from scipy.signal import welch
def interaction_band_pow(epochs, config):
"""Get the band power (psd) of the interaction forces/moments.
Parameters
----------
subject : string
subject ID e.g. 7707.
trial : string
trial e.g. HighFine, AdaptFi... | python |
'''
Priority Queue implementation using binary heaps
https://www.youtube.com/watch?v=eVq8CmoC1x8&list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu&index=17
This code is done without using reverse mapping - takes O(n) time for remove_elem(elem)
Can be improved by implementing it - https://www.youtube.com/watch?v=eVq8CmoC1x8&li... | python |
"""
hyperopt search spaces for each prediction method
"""
import numpy as np
from hyperopt import hp
from hyperopt.pyll.base import scope
from src.jobs.models import Job
from src.predictive_model.classification.models import CLASSIFICATION_RANDOM_FOREST, CLASSIFICATION_KNN, \
CLASSIFICATION_XGBOOST, CLASSIFICATIO... | python |
import logging
from datetime import date
from flask import request, render_template, jsonify, redirect, url_for
from weight import app
from weight.db import SessionScope
from weight.forms import WeightForm
from weight.db.queries import (
add_weight_data,
edit_weight_data,
delete_weight_data,
get_weight... | python |
## 旋转数组
# 方法一: 暴力法, 循环嵌套 时间:O(k*n) 空间:O(1)
# class Solution:
# def rotate(self, nums: List[int], k: int) -> None:
# n = len(nums) - 1
# j = 0
# while j < k:
# i = n
# temp = nums[n]
# while i > 0:
# nums[i] = nums[i-1]
# i... | python |
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def plot_matrix(clf, X_test, y_test):
plt.clf()
plt.imshow(confusion_matrix(clf.predict(X_test), y_test),
interpolation='nearest', cmap=plt.cm.Blues)
plt.colorbar()
plt.xlabel("true label")
plt.ylabel("predi... | python |
import subprocess
class ShellCommandExecuter:
def __init__(self, current_working_directory, args):
self.current_working_directory = current_working_directory
self.args = args
def execute_for_output(self):
process = subprocess.run(self.args, stdout=subprocess.PIPE, cwd=self.curren... | python |
#Addition of a new dot.
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
#Initial state. Base dataset.
##def __init__ visualizer(self):
##Falta que lo clasifique.
def add_dot(sepal_width, sepal_length, color):
df = px.data.iris()
newDyc = {"sepal_width": sepal_width, "sepal... | python |
import codecs
import csv
import sys
import pickle
import os
try:
from . import config_wv
from . import pre_util
except:
sys.path.append("/Users/tdong/git/lg-flask/tasks/lgutil/pre_processing_wv/config_wv")
import config_wv
import pre_util
def get_all_lines(fname, encoding='utf8'):
with codecs... | python |
# Print out 2 to the 65536 power
# (try doing the same thing in the JS console and see what it outputs)
bignum = 2 ** 65536
print(bignum) | python |
from .cifar import CIFAR10NoisyLabels, CIFAR100NoisyLabels
__all__ = ('CIFAR10NoisyLabels', 'CIFAR100NoisyLabels')
| python |
dict1 = dict(One = 1, Two = 2, Three = 3, Four = 4, Five = 5)
print(dict1['Four'])
dict1['Three'] = 3.1
print(dict1)
del dict1['Two']
print(dict1) | python |
from __future__ import annotations
import pandas as pd
import numpy as np
from typing import List, Union, TYPE_CHECKING
from whyqd.base import BaseSchemaAction
if TYPE_CHECKING:
from ..models import ColumnModel, ModifierModel, FieldModel
class Action(BaseSchemaAction):
"""
Create a new field by iteratin... | python |
from zipfile import ZipFile
import os
class ExtractFiles:
def __init__(self):
self.ends_with = '.zip'
self._backup_dir = r"C:\dev\integratedSystem\all_images"
def handler_files(self, file_name):
if file_name.endswith(self.ends_with):
return self.extract_zips(file_name)
... | python |
import sys
import mechanics.colors as colors
from tcod import image_load
from tcod import console
from loader_functions.initialize_new_game import get_constants, get_game_variables
from loader_functions.data_loaders import load_game, save_game
from mechanics.menus import main_menu, messsage_box
from mechanics.game_stat... | python |
#!/usr/bin/python
# Classification (U)
"""Program: main.py
Description: Unit testing of main in daemon_rmq_2_isse.py.
Usage:
test/unit/daemon_rmq_2_isse/main.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import unittest... | python |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.