text stringlengths 957 885k |
|---|
#!/usr/bin/env python
# Author: b0yd
# Ex: AppJailLauncher.exe /outbound /key:flag.txt /port:4444 ConsoleApplication2.exe
from pwn import *
import sys
import binascii
#####
##Uncomment the following code to use BugId as the test harness while trying to catch crashes
#
#sBaseFolderPath = "C:\Users\user\Documents\GitHu... |
<filename>oxasl_multite/api.py
"""
OXASL plugin for processing multiphase ASL data
Copyright (c) 2019 Univerisity of Oxford
"""
import math
import numpy as np
from fsl.wrappers import LOAD
from fsl.data.image import Image
from oxasl import basil
from oxasl.options import OptionCategory, IgnorableOptionGroup
from oxa... |
"""
Code borrowed from https://gist.github.com/alper111/8233cdb0414b4cb5853f2f730ab95a49#file-vgg_perceptual_loss-py-L5
"""
import torch
import torchvision
from models.vggface import VGGFaceFeats
def cos_loss(fi, ft):
return 1 - torch.nn.functional.cosine_similarity(fi, ft).mean()
class VGGPerceptualLoss(torch.... |
<gh_stars>0
from .soc_algo import _SamplingAndOcclusionAlgo
from .lm import BiGRULanguageModel
from .train_lm import do_train_lm
import os, logging, torch, pickle
import json
logger = logging.getLogger(__name__)
class SamplingAndOcclusionExplain:
def __init__(self, model, configs, tokenizer, output_path, device, ... |
#!/usr/bin/env python3
#
# Copyright (c) 2018, Cisco and/or its affiliates
# All rights reserved.
#__maintainer__ = '<NAME>'
#__email__ = '<EMAIL>'
#__date__ = 'January 2019'
#__version__ = 1.0
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followi... |
import graphene
from graphene_django import DjangoObjectType
from .models import User, Post
class UserType(DjangoObjectType):
class Meta:
model = User
fields = ("id", "name", "email")
class PostType(DjangoObjectType):
class Meta:
model = Post
fields = ("id", "title", "content... |
<reponame>arjunshibu/catalyst
from typing import Any, Callable, Dict, List, Mapping, Union
from collections import OrderedDict
from copy import deepcopy
import torch
from torch import nn
from torch.utils.data import DataLoader
from catalyst.contrib.data.augmentor import Augmentor, AugmentorCompose
from catalyst.core.... |
import numpy as np
import matplotlib.pyplot as plt
import h5py
import torch
import os
from klampt.model.trajectory import Trajectory
from klampt.io.loader import save
from pdb import set_trace
def plot_pushing_error(bg, max_horiz=100):
test_data = bg.T.MTEST
test_ans = bg.MTestAnswers
test_structures = bg.... |
import pygame
import os
import time
class Walls:
def __init__(self, pos, size, color):
self.pos = pos
self.size = size
self.color = color
self.rect = pygame.Rect(pos[0], pos[1], size[0], size[1])
def draw(self):
pygame.draw.rect(screen, self.color, (self.p... |
<filename>DFA.py<gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 1 14:35:26 2017
@author: picku
This code carries out multifractal detrended fluctuation analysis (MF-DFA) as
described in:
Kantelhardt, <NAME>., et al. "Multifractal detrended fluctuation analysis of
nonstationary timer serie... |
"""Read Brainvoyager srf & smp files to compute cortical magnification."""
import os
import numpy as np
from copy import copy
import bvbabel
FILE_SRF = "/home/faruk/Documents/test_bvbabel/SRF/surface.srf"
FILE_SMP = "/home/faruk/Documents/test_bvbabel/SRF/maps.smp"
# These values are required to compute vertex-wise... |
<reponame>Alex-Roudjiat/Federated-ML-AI-Federated-ML-
import os
import sys
from sklearn.utils import shuffle
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../")))
from fedml_api.data_preprocessing.NUS_WIDE.nus_wide_dataset import NUS_WIDE_load_two_party_data
from fedml_api.standalone.classical_... |
<reponame>LisaWillig/UDKM_Beamprofiler
"""
.. module: uc480.uc480_h
:platform: Windows, Linux
.. moduleauthor:: <NAME> <<EMAIL>>
Thorlabs' uc480 header file translated to python.
..
This file is part of the uc480 python module.
The uc480 python module is free software: you can redistribute it and/or modify
... |
from pprint import pprint
races = [
"dwarf",
"elf",
"halfling",
"human",
"dragonborn",
"gnome",
"half-elf",
"half-orc",
"tiefling"
]
classes = [
"artificer",
"barbarian",
"bard",
"cleric",
"druid",
"fighter",
"monk",
"paladin",
"ranger",
"rog... |
#
# gaussInterp_slow routine -- Gaussian weighted smoothing in lat, lon, and time
#
# Based on <NAME>'s routines. Pure python implementation.
#
#
# Gaussian weighting = exp( vfactor * (((x - x0)/sx)^2 + ((y - y0)/sy)^2 + ((t - t0)/st)^2 ))
#
# where deltas are distances in lat, lon and time and sx, sy, st are one e... |
<gh_stars>10-100
"""
Manage downloading of GTFS files over multiple locations.
This file handles
- Reading in gtfs-sources.yaml that describes data sources
- Checking already-downloaded data
- Downloading data, if it is time to do so again
For running the weekly periodic download, use:
python pipeline/downloads.... |
# This file is part of the clacks framework.
#
# http://clacks-project.org
#
# Copyright:
# (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de
#
# License:
# GPL-2: http://www.gnu.org/licenses/gpl-2.0.html
#
# See the LICENSE file in the project's top-level directory for details.
"""
The *HTTPService* and t... |
<reponame>dreamflasher/client
# -*- coding: utf-8 -*-
"""
pygments.lexers.crystal
~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Crystal.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import ExtendedRegexLexer, inc... |
from enum import Enum
from logging import getLogger
from typing import List, Union
from eth_account.signers.local import LocalAccount
from hexbytes import HexBytes
from web3 import Web3
from gnosis.eth import EthereumClient
from gnosis.eth.contracts import get_multi_send_contract
from gnosis.eth.ethereum_client impor... |
import numpy as np
import pytest
from astropy import units as u
from astropy.constants import c
from astropy.tests.helper import assert_quantity_allclose
import plasmapy.particles.exceptions
from plasmapy.formulary.braginskii import Coulomb_logarithm
from plasmapy.formulary.collisions import (
Knudsen_number,
... |
# -*- coding: utf-8 -*-
'''
create by: 小宝
mail: <EMAIL>
create date: 2019.8.3
Purpose: base class be used to app extends
'''
import sys
import re
import random
import time
import base64
from PIL import Image
sys.path.append('../')
from common.auto_adb import auto_adb
from common import config
from com... |
<reponame>en0/pyavl3
from typing import Hashable, Tuple, Iterator, Iterable, Union, Dict
from .avl_node import AVLNode
from .interface import ADTInterface
from .traversal import InOrderTraversal, BreadthFirstTraversal
class AVLTree(ADTInterface):
# Used for iterator
traversal = InOrderTraversal
@proper... |
<filename>stompy/model/delft/dflow_grid.py
# see how involved a NEFIS reader in native python/numpy would be
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import memoize
import matplotlib.tri as tri
class DflowGrid2D(object):
def __init__(self,xcor,ycor,xz,yz,active):
self.xcor=x... |
<filename>hecate/engine/world/floor.py
import random
import arcade
from ...assets.sprites import FLOOR, ALTAR, FLOOR_DECO
class Floor(arcade.Sprite):
def __init__(self, direction):
super().__init__(scale=1)
# For readability
self.wall_directions = []
if 1 & direction == 1:
... |
#!/usr/bin/env python3
#coding=utf-8
__author__ = 'kk'
import sys
import time
import random
import xlrd, xlwt
import arrow
from requests import Session
import bs4
LOGIN_INFO = {
"username": "chenyk",
"password": "<PASSWORD>"
}
req_headers = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0... |
import json
from httptesting.library.scripts import (
get_datetime_str,
retry,
get_yaml_field,
parse_args_func
)
from requests.exceptions import (HTTPError, ConnectionError, ConnectTimeout)
from httptesting.globalVar import gl
from httptesting.library.Multipart import MultipartFormData
from httpte... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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... |
import ea
import leggedwalker
import numpy as np
import math
from jason.rl_ctrnn import RL_CTRNN
from jason.ctrnn import CTRNN
from walking_task2 import WalkingTask
import warnings
from scipy.ndimage.interpolation import shift
import matplotlib.pyplot as plt
from matplotlib import cm
import os
import time
from matplotl... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import os
import shutil # which
from typing import Dict, List, Tuple
import warnings
from dace import dtypes, memlet as mm, data as dt
from dace.sdfg import nodes, SDFG, SDFGState, ScopeSubgraphView, graph as gr
from dace.sdfg.utils import df... |
import os
import argparse
import numpy as np
from skimage.morphology import disk
from jicbioimage.core.io import AutoName, AutoWrite
from jicbioimage.core.image import Image
from jicbioimage.core.transform import transformation
from jicbioimage.transform import (
threshold_otsu,
remove_small_objects,
er... |
<reponame>bschilder/public-resources
import re
import mygene
def label_txt_formatter(label, max_len = None):
'''
Given a label text, return an abbreviated text
(for figure)
'''
replace_strs = [
('_', ' '),
(r'\(right\)$', '(R)'),
(r'\(left\)$', '(L)'),
(r'percent... |
<filename>check-10.10-yosemite-compatibility.py
#!/usr/bin/env python
# encoding: utf-8
# ================================================================================
# check-yosemite-compatibility.py
#
# This script checks if the current system is compatible with OS X 10.10 Yosemite.
# These checks are based on t... |
<gh_stars>1-10
import asyncio
import inspect
import json
import logging
import os
from typing import Dict, Final, Mapping, Optional, TYPE_CHECKING, Tuple, Type
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_USERNAME
from homeassistant.core import callback
from homeassistant.h... |
# coding: utf-8
r"""iteration.py module
Summary
-------
This module helps looping through topology
"""
import OCC.BRep
import aocutils.topology
import aocutils.brep.edge
class EdgePairsFromWire(object):
r"""Helper class to loop through a wire and return ordered pairs of edges
Parameters
----------
... |
#!/usr/bin/python3
# number of output figures = 4
import random
import numpy as np
import helper.basis
from helper.figure import Figure
import helper.grid
import helper.plot
def getChain(l1, i1, l2, i2, T):
chain = [(np.array(l1), np.array(i1))]
for t in T:
lNext, iNext = chain[-1]
lNext, iNext = n... |
import urllib2
import urllib
import urlparse
import json
import mimetypes
import mimetools
class MapLargeConnector(object):
###
# Creates a connection to a MapLarge API server
###
###
# When NO_WEB_CALLS is true all MapLargeConnectors will not make remote
# calls. Instead, the response will b... |
<reponame>iqDF/Django-Custom-User<gh_stars>1-10
from django.urls import reverse
from django.contrib.auth import get_user_model
from django.test.client import Client
from rest_framework import status
from rest_framework.test import APITestCase
from utils.random_support import RandomSupport
from duty_api.serializers i... |
<reponame>Huda-Hakami/Context-Guided-Relation-Embeddings
import numpy as np
from wordreps import WordReps
from algebra import cosine, normalize
import tensorflow as tf
import random
from dataset import DataSet
import NLRA_Model
from Eval import eval_SemEval
import sklearn.preprocessing
# ============ End Imports ====... |
<reponame>BU-ISCIII/opentrons_web
import os
from django.conf import settings
##### Allow to import the configuration samba files from configuration folder
import sys
sys.path.append('../')
try:
from .url_configuration import DOMAIN_SERVER
except:
DOMAIN_SERVER = 'localhost'
############## FOLDER SETTINGS ###... |
<reponame>RainEggplant/id3_tag_downloader
# -*- coding:utf-8 -*-
import argparse
import os
import re
import urllib.request
from datetime import datetime
from mutagen.easyid3 import EasyID3
from mutagen.id3 import ID3, APIC
from PIL import Image
from ncm_api import CloudApi
def extract_file_name_id_pairs(directory):
... |
<reponame>gajanlee/cat-pi-monitor
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: monitor.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection ... |
#!/usr/bin/env python
# Full license can be found in License.md
# Full author list can be found in .zenodo.json file
# DOI:10.5281/zenodo.1199703
# ----------------------------------------------------------------------------
import copy
import datetime as dt
import errno
import functools
import importlib
import inspect... |
# coding=utf8
"""
MP3 Voice Stamp
Athletes' companion: adds synthetized voice overlay with various
info and on-going timer to your audio files
Copyright ©2018 <NAME> <mail [@] <EMAIL>>
https://github.com/MarcinOrlowski/Mp3VoiceStamp
"""
from __future__ import print_function
import os
import shutil
import t... |
import logging
from datetime import datetime, timedelta
from cerberus import Validator
from conf import settings
from records.record import InvalidRecord, InvalidRecordLength, InvalidRecordProperty, Record
from tools.csv_helpers import TabDialect, CommaDialect
class MigrationChecklistType(object):
""" class that... |
<filename>tidalclassifier/cnn/metric_utils.py
import os
import json
import warnings
from collections import namedtuple
import matplotlib
# matplotlib.use('Agg') # Force matplotlib to not use any Xwindows backend.
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from tidalcl... |
# coding=utf-8
from bs4 import BeautifulSoup
import re
def unstandard_count(soup,tag_name,tag,standard_format):
subjects=soup.select(tag_name)
print("length subs info: ",len(subjects))
sum_all = 0
for sub in subjects:
tags=sub.find_all(tag)
style_tag=sub.find_all(tag,{"style":re.compile... |
import _pickle as cPickle
import gzip
import random
import numpy as np
import os,time,subprocess,glob
from stackPH import lifeVect,histVect
from scipy.ndimage.morphology import distance_transform_edt
from skimage.filters import threshold_otsu
from skimage.transform import resize
import matplotlib.pyplot as plt
from mpl... |
import unittest
from testfixtures import LogCapture
from openid import kvform
class KVDictTest(unittest.TestCase):
def runTest(self):
for kv_data, result, expected_warnings in kvdict_cases:
# Convert KVForm to dict
with LogCapture() as logbook:
d = kvform.kvToDic... |
<gh_stars>0
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.... |
<filename>phase4_analysis/metrics.py
# <NAME> (<EMAIL>)
import numpy as np
import scipy.stats as ss
#from diagnostics import MIN_ESS
MIN_ESS_PER_CHAIN = 1.0 # TODO limit dupes
def stack_first(X):
assert(X.ndim == 3)
# Equivalent to:
# Y = np.concatenate([X[ii, :, :] for ii in xrange(X.shape[0])], axis=0... |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from PIL import Image
import io
User = get_user_model()
"""Images of products to use online"""
class ProductFigure(mode... |
# First Party
# Third Party
import pytest
from smdebug.profiler.analysis.utils.pandas_data_analysis import (
PandasFrameAnalysis,
Resource,
StatsBy,
)
from smdebug.profiler.analysis.utils.profiler_data_to_pandas import PandasFrame
@pytest.mark.parametrize("framework", ["tf2", "pt"])
def test_pandas_frame... |
<reponame>hayden4r4/Gemini-API-Wrapper-Python
import requests
import json
import base64
import hmac
import hashlib
import datetime
import time
class gemini_kit:
def __init__(self, gemini_api_key: str, gemini_api_secret: str, account: str = None, sandbox: bool = False):
self.gemini_api_key = gemini_api_ke... |
import pandas as pd
import sqlite3
from pyecharts import options as opts
from pyecharts.charts import Timeline, Grid, Bar, Map, Pie, Line
from pyecharts.globals import WarningType
from pyecharts.globals import ThemeType
from pyecharts.commons.utils import JsCode
from typing import List
import math
import platform
impor... |
# Copyright (c) 2022 PaddlePaddle 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 appli... |
import logging
import torch
from pybrid import utils
from pybrid.models.base import BaseModel
from pybrid.layers import FCLayer
class HybridModel(BaseModel):
def __init__(
self,
nodes,
amort_nodes,
act_fn,
mu_dt=0.01,
use_bias=False,
kaiming_init=False,
... |
<gh_stars>1-10
import os
import sys
import time
import math
import requests
# Might have to change this
base_url = "https://api.kennasecurity.com/assets"
ASSETS_PER_PAGE = 500
#
def get_asset_page(page_num):
page_param = "?page=" + str(page_num)
url = base_url + page_param
# Obtain the specified page.
... |
# --------------------------------------------------------------------------
# Copyright 2020 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/l... |
# Credit to @stelar7, this python implementation is a port of his original javascript implementation
from base64 import b32decode, b32encode
from io import BytesIO
MAX_KNOWN_VERSION = 20
class Base32:
@staticmethod
def decode(b32string):
s = Base32.add_padding(b32string)
return b32decode(s)
... |
import operator as op
import pytest
import sidekick.api as sk
from sidekick import X
from sidekick.seq.testing import VALUE, LL
class TestBasic:
def test_fail_with_empty_lists(self, empty):
fail = [sk.uncons, sk.first, sk.second, sk.last, sk.nth(0), sk.nth(1)]
for func in fail:
with... |
import os
import aiohttp
from aiohttp import web
from gidgethub import aiohttp as gh_aiohttp
from gidgethub import routing
from gidgethub import sansio
router = routing.Router()
routes = web.RouteTableDef()
BOT_NAME = "marvin-mk2"
# secrets and configurations configured through the environment
WEBHOOK_SECRET = os.en... |
<reponame>sidorenkov-v-a/polls
from rest_framework.reverse import reverse
from rest_framework.test import APIClient
from polls.models import Poll
from .common import create_poll_data
class TestPoll:
url_list = reverse('poll-list')
@property
def url_detail(self, pk=1):
return reverse('poll-detai... |
# -*- coding: utf-8 -*-
from configurations import Configuration
from django.contrib.messages import constants as messages
from kaio import Options
from kaio.mixins import CachesMixin, DatabasesMixin, LogsMixin, PathsMixin, SecurityMixin, DebugMixin, WhiteNoiseMixin
opts = Options()
class Base(CachesMixin, Databas... |
<filename>src/blpapi/request.py
# request.py
"""Defines a request which can be sent for a service.
This file defines a class 'Request' which represents a request sent through the
Session.
"""
import weakref
from .element import Element
from .exception import _ExceptionUtil
from . import internals
from .chandle impo... |
class Config:
JAC_RAISE1 = 0.017 #Prognozētā vidējā gaisa temperatūra
JAC_RAISE2 = 0.016 #Prognozētais vidējais nokrišņu daudzums
JAC_RAISE3 = 0.013 #Karsto dienu skaits
JAC_RAISE4 = 0.017 #Meža tips
JAC_RAISE5 = 0.006 #Vēsturisko ugunsgrēku skaits
JAC_RAISE6 = 0.002 #Attālums no dzelzceļa
J... |
"""Methods used to setup the Hamiltonian of the system."""
import numpy as np
from basis import msg
from basis.potential import Potential
class Hamiltonian(object):
"""Represents the Hamliltonian for a 1D quantum potential.
Args:
potcfg (str): path to the potential configuration file.
n_basi... |
import uuid
from chaosplt_experiment.storage import ExperimentStorage, ExecutionStorage
from chaosplt_experiment.storage.model import Experiment, Execution
from chaosplt_relational_storage.db import orm_session
def test_create_experiment(experiment_storage: ExperimentStorage):
with orm_session() as session:
... |
<gh_stars>1-10
import sys, logging, threading
from typing import List
import time
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# IMPORTANT Path to IHC_PMS_Lib dlls
sys.path.append("/home/for/dev/IHC_PMS_Lib_1.9.2.0/bin")
... |
<reponame>Chen188/chalice
import os
import re
import mock
import sys
import click
import pytest
from six import StringIO
from hypothesis.strategies import text
from hypothesis import given
import string
from dateutil import tz
from datetime import datetime
from chalice import utils
class TestUI(object):
def set... |
<reponame>neilalbrock/python-uic920<gh_stars>1-10
# -*- coding: utf-8 -*-
import re
from numbers import Integral
from collections import namedtuple
__all__ = ["countries"]
Country = namedtuple('Country', 'name, iso, uic')
_records = [
Country(u"Finland", "FI", "10"),
Country(u"Russian Federation", "RU", "20... |
<reponame>jkmcpherson/ncov
import argparse
from augur.io import open_file, read_metadata
import csv
import os
from pathlib import Path
import pandas as pd
import re
import sys
from tempfile import NamedTemporaryFile
from utils import extract_tar_file_contents
# Define all possible geographic scales we could expect in... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2021, <NAME> and <NAME>.
#
# Distributed under the 3-clause BSD license, see accompanying file LICENSE
# or https://github.com/scikit-hep/particle for details.
import pytest
# Backport needed if Python 2 is used
from enum import IntEnum
class PDGIDsEnum(IntEnum):
"""... |
<gh_stars>1-10
from __future__ import annotations
import os
import uuid
from django.db import models
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
from ggongsul.member.models import Member
from ggongsul.visitation.models import Visitation
from ggongsul.pa... |
import os
import unittest
import datetime
from unittest import mock
from bullets.portfolio.portfolio import Portfolio
from bullets.portfolio.transaction import Transaction, Status
from bullets.data_source.data_source_interface import DataSourceInterface, Resolution
from bullets.data_source.data_source_fmp import FmpDat... |
#!/usr/bin/env python
from typing import Dict
from decimal import Decimal
from uuid import uuid4
import requests
import json
# Internal Import
from sslcommerz_python_api.base import SSLCommerz
class SSLCSession(SSLCommerz):
def __init__(self,
sslc_is_sandbox: bool = True,
sslc_store_id: str = '',
sslc_... |
<reponame>rainbow-mind-machine/rainbow-mind-machine<gh_stars>1-10
import rainbowmindmachine as rmm
from unittest import TestCase
import logging
import os, subprocess
from .utils import captured_output
"""
Test Keymaker classes
"""
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
logging.getLogger('... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.nn import init
import dgl.function as fn
# Sends a message of node feature h
# Equivalent to => return {'m': edges.src['h']}
# randwalk_msg = fn.copy_src(src='h', out='m')
# def randw... |
import pandas as pd
import numpy as np
import tensorflow as tf
import random
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from tensorflow.contrib.layers import flatten
import csv
import cv2
from resizeimage import resizeimage
from PIL import Image
###### STEP 0: Load the Data ##################... |
import numpy as np
import scipy
import sklearn.metrics
def precision_at_n(adj_test, adj_true, n):
assert (len(adj_test.shape) == 1) and (len(adj_true.shape) == 1), "Expect 1-dimensional arrays"
sorted_args = np.argsort(adj_test)[::-1]
return np.sum(adj_true[sorted_args][:n] > 0) / n
def true_positive(ad... |
<filename>bosm2015/registration/forms.py<gh_stars>1-10
from registration.models import UserProfile
from django.contrib.auth.models import User
from nocaptcha_recaptcha.fields import NoReCaptchaField
from django import forms
cities= (
('Alwar','Alwar'),
('Bahadurgarh','Bahadurgarh'),
('Bangalore','Bangalore... |
import json
from ocdskingfisher.database import DatabaseStore
class Store:
def __init__(self, config, database):
self.config = config
self.collection_id = None
self.database = database
def load_collection(self, collection_source, collection_data_version, collection_sample):
s... |
<filename>env/lib/python2.7/site-packages/tests/main.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
from subprocess import CalledProcessError
from mock import patch
from djangocms_installer import config, install, main
from .base import Isola... |
<gh_stars>0
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# <NAME>
# Contact: <EMAIL>
#
import logging
import os
import random
import string
from secrets import choice
from Cryptodome.Random.random import shuffle
PW_SPECIAL_CH... |
#!/usr/bin/env python3
import os
import sys
import itertools
import glob
import argparse
from utils import read_wav
from interface import ModelInterface
def get_args():
desc = "Speaker Recognition Command Line Tool"
epilog = """
Wav files in each input directory will be labeled as the basename of the director... |
<filename>yaxil/__init__.py
import io
import os
import csv
import sys
import gzip
import json
import time
import arrow
import random
import sqlite3
import zipfile
import logging
import requests
from requests_toolbelt.adapters.socket_options import TCPKeepAliveAdapter
import itertools
import getpass as gp
import tempfil... |
<filename>fatiando/gui/simple.py
"""
Simple GUIs using the interactive capabilities of :mod:`matplotlib`
**Interactive gravimetric modeling**
* :class:`~fatiando.gui.simple.Moulder`
* :class:`~fatiando.gui.simple.BasinTrap`
* :class:`~fatiando.gui.simple.BasinTri`
**Interactive modeling of layered media**
* :class:... |
"""
Utility functions for views.
"""
import os
import json
import traceback
import logging
import fnmatch
import sh
from werkzeug.utils import secure_filename
from nephele2.nephele.upload_file import uploadfile
from nephele2.infra.utils.map_validator import MapType
LOGGER = logging.getLogger()
def get_remote_file_l... |
<filename>lystener/task.py
# -*- encoding:utf-8 -*-
# © <NAME>
import os
import sys
import json
import queue
import sqlite3
import hashlib
import traceback
import threading
import importlib
from lystener import logMsg, loadJson, DATA, JSON
def initDB():
database = os.path.join(DATA, "database.d... |
<reponame>RelationRx/pyrelational
"""Unit tests for data manager
"""
import pytest
import torch
from pyrelational.data import GenericDataManager
from tests.test_utils import DiabetesDataset, get_classification_dataset
def test_init_and_basic_details():
gdm = get_classification_dataset(50)
assert gdm.loader_b... |
<reponame>cdek11/PLS
# coding: utf-8
# In[ ]:
# Code to implement the initial version of the PLS Algorithm
import pandas as pd
import numpy as np
def pls(path, path_test, predictors, response):
'''Function that takes a dataframe and runs partial least squares on numeric predictors for a numeric response.
R... |
<reponame>kostenickj/lumberyard
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if prov... |
"""
This file is part of YAOS and is licenced under the MIT licence.
"""
import gettext
gettext.bindtextdomain('yaosapp', '/lang')
gettext.textdomain('yaosapp')
_ = gettext.gettext
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib, Gio, Gdk, GdkPixbuf
import sys, time, rando... |
#
# Copyright (C) 2021 Sellers Industry
# distributed under the MIT License
#
# author: <NAME> <<EMAIL>>
# date: Wed Jan 06 2021
# file: __main__.py
# project: Bubble Gom (Go Manager)
# purpose: Go manager allows you to build go modules from anywhere
#
#
import argparse
import os
import json
from dateti... |
<reponame>RoverRobotics/openrover_python
import abc
import enum
import functools
import re
from typing import NamedTuple, Optional
class ReadDataFormat(abc.ABC):
python_type = None
@abc.abstractmethod
def description(self):
raise NotImplementedError
@abc.abstractmethod
def unpack(self, b... |
<reponame>anibadde/opacus
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from functools import partial
from typing import Iterable, List, Tuple
import torch
import torch.nn as nn
from opacus.layers.dp_rnn import DPRNNBase, DPRNNCellBase, RNNLinear
from opacus.utils.module... |
<gh_stars>0
import datetime
import json
import time
import os
import sys
import urllib
from functools import wraps
from io import BytesIO
from types import SimpleNamespace
import logging
from typing import Dict
import urllib3
from capturer import CaptureOutput
from lumigo_tracer import lumigo_tracer, LumigoChalice, u... |
"""
Client for communicating with the beamformer receiver on kat-dc2.karoo
Author: <NAME>
Date: 2014-01-03
Modified:
"""
from katcp import *
import logging
log = logging.getLogger("katcp")
class FBFClient(BlockingClient):
# class FBFClient(CallbackClient):
"""Client for communicating Beamformer receiver
... |
<reponame>Ahmedjjj/dataset-distillation<filename>fed_distill/config/parser.py
from typing import Iterable, Optional, Tuple, Union
import numpy as np
from omegaconf import DictConfig
from torch import nn
from torch.utils.data import Dataset
from torchvision.datasets import CIFAR10
import torch
from fed_distill.cifar10... |
<filename>test_extract_pdf.py<gh_stars>10-100
import pytest
from unittest.mock import MagicMock, patch
import email
from users import UserModel
import lambda_main
class MockUserModel(UserModel):
def exists(self):
return True
def create_table(self, wait=True):
return True
mock_register_user =... |
# Support Vector Machines
## Introduction
A Support Vector Machine (SVM) is a very powerful and versatile
Machine Learning method, capable of performing linear or nonlinear
classification, regression, and even outlier detection. It is one of
the most popular models in Machine Learning, and anyone interested in
Machin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.