repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
0xProject/p2p_incentives | test/node/test_rank_neighbors.py | """
This module contains unit test of rank_neighbors().
"""
from typing import List
import pytest
from node import Peer
from ..__init__ import SCENARIO_SAMPLE, ENGINE_SAMPLE, create_test_peers
@pytest.mark.parametrize("scenario,engine", [(SCENARIO_SAMPLE, ENGINE_SAMPLE)])
def test_rank_neighbors(scenario, engine) -... |
0xProject/p2p_incentives | test/data_processing/test_average_lists.py | """
This module contains unit tests of average_lists()
"""
from typing import List, Tuple
import pytest
from data_processing import average_lists
from data_types import InvalidInputError, SpreadingRatio
from .__init__ import RATIO_LIST
# test normal cases
CASES_AVERAGE_LISTS: List[Tuple[List[SpreadingRatio], List[f... |
0xProject/p2p_incentives | plot.py | <filename>plot.py<gh_stars>1-10
"""
This module contains the function that plots the performance results.
"""
from typing import List
import matplotlib.pyplot as plt
import data_processing
from performance import Performance
from data_types import (
MultiRunPerformanceResult,
OrderSpreading,
Fairness,
... |
0xProject/p2p_incentives | data_types.py | <reponame>0xProject/p2p_incentives<gh_stars>1-10
"""
This module defines code specific data types for Scenario, Engine, and Performance.
It also contains the definitions of self-defined data types.
"""
from typing import NamedTuple, List, Optional, Union, Dict
from mypy_extensions import TypedDict
from typing_extensio... |
0xProject/p2p_incentives | test/node/test_init_functions.py | <reponame>0xProject/p2p_incentives
"""
This module contains unit tests of peer and order initialization functions.
"""
from typing import Set
import pytest
from message import Order
from node import Peer
from ..__init__ import (
create_a_test_order,
create_test_orders,
create_a_test_peer,
SCENARIO_SA... |
0xProject/p2p_incentives | test/engine/__init__.py | """
We put a helper function in this __init__.py.
"""
from typing import Tuple, List
from scenario import Scenario
from engine import Engine
from node import Peer, Neighbor
from ..__init__ import create_a_test_peer, create_test_peers
def create_a_peer_and_two_neighbors_helper(
scenario: Scenario, engine: Engine
... |
0xProject/p2p_incentives | setup.py | <filename>setup.py<gh_stars>1-10
#!/usr/bin/env python
"""setuptools module for p2p_incentives package."""
# pylint: disable=C0415
# we import things outside of top-level because 3rd party libs may not yet be
# installed when you invoke this script
import glob
import subprocess # nosec
from shutil import rmtree
fro... |
0xProject/p2p_incentives | test/engine/test_store_first.py | """
This module contains unit tests of store_first().
"""
from typing import List
import pytest
from node import Peer
from message import Order, OrderInfo
from scenario import Scenario
from engine import Engine
import engine_candidates
from ..__init__ import (
ENGINE_SAMPLE,
SCENARIO_SAMPLE,
create_a_te... |
0xProject/p2p_incentives | test/single_and_multi_run/test_peer_departure.py | """
This module contains unit tests of peer_departure().
"""
from typing import Iterator
import pytest
from single_run import SingleRun
from node import Peer
from message import Order
from scenario import Scenario
from engine import Engine
from performance import Performance
from ..__init__ import (
SCENARIO_SAMP... |
0xProject/p2p_incentives | multi_run_in_parallel.py | """
This module contains class MultiRunInParallel only.
"""
from multiprocessing import Pool
from typing import List, Tuple, TYPE_CHECKING
from single_run import SingleRun
from data_types import SingleRunPerformanceResult, MultiRunPerformanceResult
if TYPE_CHECKING:
from scenario import Scenario
from engine ... |
0xProject/p2p_incentives | test/performance_candidates/test_order_num_stat_on_age.py | <filename>test/performance_candidates/test_order_num_stat_on_age.py
"""
This module contains unit tests of order_num_stat_on_age().
"""
from typing import List, NamedTuple
import pytest
from message import Order
from scenario import Scenario
import performance_candidates
from ..__init__ import SCENARIO_SAMPLE, create_... |
0xProject/p2p_incentives | data_processing.py | <filename>data_processing.py
"""
This module contains data processing tools (e.g., finding the max, min, average, frequency...)
to work on performance evaluation results.
"""
import statistics
import itertools
from typing import List, Iterator, Tuple
from data_types import SpreadingRatio, BestAndWorstLists, InvalidInp... |
0xProject/p2p_incentives | test/node/test_send_orders_to_on_chain_check.py | <gh_stars>1-10
"""
This module contains unit tests of send_orders_to_on_chain_check().
"""
from typing import List
import pytest
from message import Order
from node import Peer
from ..__init__ import (
SCENARIO_SAMPLE,
ENGINE_SAMPLE,
create_a_test_peer,
create_test_orders,
)
@pytest.mark.parametrize(... |
0xProject/p2p_incentives | test/node/test_share_orders.py | """
This module contains unit tests of share_order().
"""
import random
from typing import List
import pytest
from node import Peer
from ..__init__ import (
create_test_peers,
create_a_test_peer,
SCENARIO_SAMPLE,
ENGINE_SAMPLE,
)
@pytest.mark.parametrize("scenario,engine", [(SCENARIO_SAMPLE, ENGINE_... |
0xProject/p2p_incentives | engine.py | <gh_stars>1-10
"""
This module contains the class Engine only.
"""
from typing import Set, TYPE_CHECKING, cast, List
import engine_candidates
from data_types import (
EngineParameters,
EngineOptions,
PreferenceOption,
PriorityOption,
ExternalOption,
InternalOption,
StoreOption,
ShareOpt... |
0xProject/p2p_incentives | engine_candidates.py | <filename>engine_candidates.py
"""
This module contains all possible realizations of functions in the Engine class.
"""
import random
from typing import Set, List, TYPE_CHECKING
from data_types import Preference, Priority
if TYPE_CHECKING:
from node import Peer, Neighbor
from message import Order, OrderInfo
... |
0xProject/p2p_incentives | test/engine/test_all_new_selected_old.py | <gh_stars>1-10
"""
This module contains unit tests of all_new_selected_old().
"""
from typing import NamedTuple, Tuple, List
import pytest
from node import Peer
from message import Order
from scenario import Scenario
from engine import Engine
import engine_candidates
from ..__init__ import (
SCENARIO_SAMPLE,
... |
0xProject/p2p_incentives | test/data_processing/__init__.py | <gh_stars>1-10
"""
This init file contains input data for the unit tests of data_processing.py
"""
from typing import List
from data_types import SpreadingRatio
# constructing input data
RATIO_LIST: List[SpreadingRatio] = [[] for _ in range(15)]
RATIO_LIST[0] = [0.1, 0.2, 0.3, 0.4]
RATIO_LIST[1] = [0.1, 0.2, 0.3, ... |
0xProject/p2p_incentives | run.py | <filename>run.py<gh_stars>1-10
"""
This is the single main file that runs the simulator.
"""
import example
import multi_run_in_parallel
import plot
if __name__ == "__main__":
for my_scenario in example.SCENARIOS:
for my_engine in example.ENGINES:
for my_performance in example.PERFORMANCES:
... |
0xProject/p2p_incentives | test/engine/test_weighted_sum.py | """
This module contains unit tests of weighted_sum().
"""
from typing import List
from collections import deque
import pytest
import engine_candidates
from scenario import Scenario
from engine import Engine
from ..__init__ import ENGINE_SAMPLE, SCENARIO_SAMPLE
from .__init__ import create_a_peer_and_two_neighbors_he... |
0xProject/p2p_incentives | test/node/test_receive_internal.py | <gh_stars>1-10
"""
This module contains unit tests of receive_order_internal().
"""
from typing import List
import pytest
from node import Peer
from message import Order
from ..__init__ import (
create_test_peers,
create_a_test_order,
SCENARIO_SAMPLE,
ENGINE_SAMPLE,
)
@pytest.mark.parametrize("scena... |
0xProject/p2p_incentives | test/node/test_should_accept_neighbor_request.py | <reponame>0xProject/p2p_incentives<gh_stars>1-10
"""
This module contains unit tests of should_accept_neighbor_request().
"""
from typing import List
import pytest
from node import Peer
from ..__init__ import (
SCENARIO_SAMPLE,
ENGINE_SAMPLE,
create_a_test_peer,
create_test_peers,
)
@pytest.mark.par... |
0xProject/p2p_incentives | test/performance_candidates/test_order_spreading_ratio_stat.py | """
This module contains unit tests of order_spreading_ratio_stat().
"""
import copy
from typing import List, NamedTuple, Tuple
import pytest
from node import Peer
from message import Order
from scenario import Scenario
from engine import Engine
from data_types import SpreadingRatio
import performance_candidates
from ... |
0xProject/p2p_incentives | test/single_and_multi_run/test_peer_arrival.py | """
This module contains unit tests of peer_arrival().
"""
import pytest
from scenario import Scenario
from engine import Engine
from performance import Performance
from node import Peer
from single_run import SingleRun
from ..__init__ import SCENARIO_SAMPLE, ENGINE_SAMPLE, PERFORMANCE_SAMPLE
@pytest.mark.parametr... |
0xProject/p2p_incentives | message.py | """
This module defines Order and OrderInfo classes
"""
from typing import TYPE_CHECKING, Optional, Set
from data_types import (
Category,
Priority,
OrderTypeName,
SettleParameters,
ConcaveParameters,
CancelParameters,
AgeBasedParameters,
)
if TYPE_CHECKING:
from scenario import Scenar... |
0xProject/p2p_incentives | test/single_and_multi_run/test_update_global_orderbook.py | <filename>test/single_and_multi_run/test_update_global_orderbook.py<gh_stars>1-10
"""
This module contains unit tests of update_global_orderbook().
"""
from typing import Tuple
import pytest
from single_run import SingleRun
from node import Peer
from message import Order
from scenario import Scenario
from engine impo... |
anirudh-chakravarthy/ObjProp | mmdet/models/prop_heads/prop_head.py | <filename>mmdet/models/prop_heads/prop_head.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from mmdet.core import delta2bbox, multiclass_nms, bbox_target, auto_fp16
from mmdet.core import force_fp32
from ..registry import HEADS
import pdb
from PIL import Image
from torchvision... |
anirudh-chakravarthy/ObjProp | mmdet/models/prop_heads/__init__.py | from .prop_head import PropHead
__all__ = ['PropHead']
|
anirudh-chakravarthy/ObjProp | mmdet/datasets/ytvos.py | import numpy as np
import os.path as osp
import random
import mmcv
import cv2
from .custom import CustomDataset
from .extra_aug import ExtraAugmentation
from .registry import DATASETS
from .transforms import (ImageTransform, BboxTransform, MaskTransform,
SegMapTransform, Numpy2Tensor)
from pyco... |
anirudh-chakravarthy/ObjProp | mmdet/models/mask_heads/__init__.py | from .fcn_mask_head import FCNMaskHead
__all__ = ['FCNMaskHead'] |
anirudh-chakravarthy/ObjProp | mmdet/models/anchor_heads/__init__.py | <gh_stars>1-10
from .anchor_head import AnchorHead
from .rpn_head import RPNHead
from .retina_head import RetinaHead
from .ssd_head import SSDHead
__all__ = ['AnchorHead', 'RPNHead', 'RetinaHead', 'SSDHead'] |
anirudh-chakravarthy/ObjProp | mmdet/datasets/loader/__init__.py | <reponame>anirudh-chakravarthy/ObjProp<filename>mmdet/datasets/loader/__init__.py
from .build_loader import build_dataloader
from .sampler import DistributedGroupSampler, GroupSampler
from .video_sampler import GroupVideoSampler
__all__ = ['GroupSampler', 'DistributedGroupSampler', 'build_dataloader']
|
anirudh-chakravarthy/ObjProp | mmdet/models/detectors/two_stage.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler
from mmdet.core import bbox_overlaps, bbox2result_with_id
from mmdet.core import multiclass_nms
from .. import builder
from ..registry import DETECTORS
from .base import BaseDe... |
anirudh-chakravarthy/ObjProp | mmdet/version.py | # GENERATED VERSION FILE
# TIME: Sat Feb 6 13:55:43 2021
__version__ = '1.0.rc0+ff39298'
short_version = '1.0.rc0'
|
anirudh-chakravarthy/ObjProp | mmdet/datasets/loader/video_sampler.py | from __future__ import division
import math
import torch
import numpy as np
import random
from torch.distributed import get_world_size, get_rank
from torch.utils.data.sampler import Sampler
class GroupVideoSampler(Sampler):
def __init__(self, dataset, samples_per_gpu=1):
assert hasattr(dataset, 'flag')... |
anirudh-chakravarthy/ObjProp | mmdet/models/losses/label_smoothing_loss.py | <filename>mmdet/models/losses/label_smoothing_loss.py
# Adapted from https://github.com/pytorch/pytorch/issues/7455#issuecomment-513062631
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
from .utils import weight_reduce_loss
@LOSSES.register_module
class LabelSmoothin... |
anirudh-chakravarthy/ObjProp | mmdet/models/track_heads/track_head.py | <filename>mmdet/models/track_heads/track_head.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from mmdet.core import delta2bbox, multiclass_nms, bbox_target, auto_fp16
from ..builder import build_loss
from ..losses import accuracy
from ..registry import HEADS
@HEADS.register_m... |
anirudh-chakravarthy/ObjProp | mmdet/models/backbones/__init__.py | from .resnet import ResNet
from .resnext import ResNeXt
from .ssd_vgg import SSDVGG
__all__ = ['ResNet', 'ResNeXt', 'SSDVGG'] |
anirudh-chakravarthy/ObjProp | mmdet/datasets/augmentor.py | # https://github.com/zudi-lin/pytorch_connectomics/blob/master/connectomics/data/augmentation/augmentor.py
import numpy as np
class DataAugment(object):
"""
DataAugment interface.
A data transform needs to conduct the following steps:
1. Set :attr:`sample_params` at initialization to compute required ... |
dtiarks/pg_agents | utils/utils.py | <reponame>dtiarks/pg_agents
import numpy as np
def flatten_array_list(a_list):
return np.concatenate([l.ravel() for l in a_list])
def unflatten_array_list(array, shapes):
c = 0
l = []
for s in shapes:
tmp = np.array(array[c:c + np.prod(s)])
reshaped = np.reshape(tmp, s)
c += ... |
dtiarks/pg_agents | experiment.py | import numpy as np
import tensorflow as tf
import argparse
import time
import os
import sys
import pylab as plt
import importlib
import gym
import roboschool
# import pybullet_envs
# import pybullet_envs.bullet.racecarGymEnv as re
# from pybullet_envs.bullet.kukaGymEnv import KukaGymEnv
sys.path.append('/'.join(str.... |
dtiarks/pg_agents | gae/linear_baseline.py | <filename>gae/linear_baseline.py
from __future__ import print_function
import numpy as np
#####schulman code
class LinearBaseline(object):
def __init__(self, sess, env, name, params, train=True):
self._coeffs = None
self._reg_coeff = 1e-5
def _features(self, times, observations):
o ... |
dtiarks/pg_agents | algos/trpo.py | <gh_stars>1-10
import numpy as np
from pg_agents.algos.tnpg import TNPG
class TRPO(TNPG):
def compute_step_len(self, x, b, hv_prod):
prod = np.abs(2 / np.dot(x, hv_prod(x)))
l = np.sqrt(self.params["kl_penalty"] * prod)
return l
def update_policy(self, returns, observations, action... |
dtiarks/pg_agents | gae/gae.py | <reponame>dtiarks/pg_agents
import tensorflow as tf
from pg_agents.algos.vpg import VPGMiniBatch
from pg_agents.utils.kl_div import kl_div
class GAE(VPGMiniBatch):
def init_loss(self):
self.kl_div = tf.reduce_mean(kl_div(self.policy_old, self.policy, self.actiondim))
self.loss = -1.*tf.losses.m... |
dtiarks/pg_agents | utils/kl_div.py | <reponame>dtiarks/pg_agents
import tensorflow as tf
def mvn_kl_div_full(a, b, dim):
co0 = a.co
co1 = b.co
co1_i = tf.matrix_inverse(co1)
mu = b.means - a.means
k = dim
A = tf.trace(tf.matmul(co0, co1_i))
B = tf.squeeze(tf.matmul(tf.matmul(tf.expand_dims(mu, 1), co1_i), tf.expand_dims(mu, ... |
dtiarks/pg_agents | algos/vpg.py | <gh_stars>1-10
import numpy as np
from pg_agents.algos.batchalgo import BatchAlgo
class VPG(BatchAlgo):
def update_policy(self, returns, observations, actions):
fd = {self.lr_plh: -self.params['learningrate'],
self.input_placeholder: observations,
self.action_placeholder: acti... |
dtiarks/pg_agents | policies/gaussian_policy.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 26 11:05:35 2017
@author: daniel
"""
import numpy as np
import tensorflow as tf
import tensorflow.contrib.distributions as ds
class GaussPolicy(object):
def __init__(self, sess, env, name, input_plh, action_plh, params, train=True, std_val=No... |
dtiarks/pg_agents | algos/tnpg.py | import tensorflow as tf
import numpy as np
import pg_agents.utils.utils as utils
from pg_agents.algos.batchalgo import BatchAlgo
class TNPG(BatchAlgo):
def compute_step_len(self, x, b, hv_prod):
prod = np.abs(1 / np.dot(b, hv_prod(b)))
l = np.sqrt(self.params["kl_penalty"] * prod)
retu... |
dtiarks/pg_agents | algos/batchalgo.py | import tensorflow as tf
from tensorflow.python.ops.gradients_impl import _hessian_vector_product
import numpy as np
import datetime
import os
from pg_agents.utils.kl_div import kl_div
from pg_agents.policies.gaussian_policy import GaussPolicy
class BatchAlgo(object):
def __init__(self, sess, env, params, action... |
dtiarks/pg_agents | algos/ppo.py | import tensorflow as tf
from pg_agents.algos.vpg import VPGMiniBatch
from pg_agents.utils.kl_div import kl_div
class PPO(VPGMiniBatch):
def init_loss(self):
self.kl_div = tf.reduce_mean(kl_div(self.policy_old, self.policy, self.actiondim))
rat = tf.exp(self.policy.lp-self.policy_old.lp)
... |
AnthonyEdvalson/parseltongue | connection.py | <filename>connection.py
import select
import socket
import struct
import threading
from enum import Enum
HEADER_FORMAT = "<QQ"
HEADER_SIZE = 16
class ConnectionState(Enum):
Disconnected = 0
Connecting = 1
Open = 2
Busy = 3
Closing = 4
def unwrap_header(header):
return struct.unpack(HEADER_F... |
AnthonyEdvalson/parseltongue | __init__.py | <filename>__init__.py
import select
import socket
import threading
from typing import Callable, Tuple
from parseltongue.connection import ClientConnection, ServerConnection, recv
class Client:
def __init__(self):
self.connections = []
def connect(self, addr: Tuple[str, int]) -> ClientConnection:
... |
AnthonyEdvalson/parseltongue | tests/test_load.py | <reponame>AnthonyEdvalson/parseltongue<gh_stars>0
import os
import random
import time
from threading import Thread, Event
from parseltongue import Client, Server
class TestEnv:
def __init__(self, client_count=1):
self.client_count = client_count
def __enter__(self):
self.server = Server(self.... |
mehdikosaca/yuz_tanima | yuz_tanima.py | import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import os
def print_utf8_text(image, xy, text, color): #utf-8 karakterleri
#fontName = "FreeSerif.ttf" #'FreeSansBold.ttf' # 'FreeMono.ttf' 'FreeSerifBold.ttf'
font = ImageFont.truetype("arial.ttf", 24) # font seçimi
img_pil =Image.... |
mehdikosaca/yuz_tanima | yuz_egitimi.py | import cv2
import numpy as np
from PIL import Image
import os
#Verilerin yolu
path = "veriseti"
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
#imajların alınması ve etiketlenmesi için fonksiyon
def getImageAndLabels(pa... |
mehdikosaca/yuz_tanima | yuz_veriseti.py | import cv2
import os
try:
os.mkdir("egitim")
except:
pass
kamera = cv2.VideoCapture(0)
kamera.set(3,640) #video genişliğini belirler.
kamera.set(4,480) #video yüksekliğini belirler.
face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
imagePaths = [os.path.join(... |
ktinubu/python-design-patterns | design_pattern_language.py | #python design pattern
#language neutral, dynamic and incomplete by design to promote customization
"""
Creational:
USed to create objects in a systematic way
Benefits: Flexibility
Structural:
used to establish usefull relationships between software comonents in certain configs
To accomplish a goal: both functio... |
ktinubu/python-design-patterns | singleton.py | # only one instance
#gloaal variable in an oop way
#borg design pattern
class Borg:
"""Borg class making class attributes global"""
_shared_state = {} #Attribute dictionary
class Singleton(Borg): #inherits from the Borg class
""" This class now shares all its attributes among its various instances """
#This esse... |
ktinubu/python-design-patterns | creation_patterns.py | <reponame>ktinubu/python-design-patterns
"""
Abstract FACTORY:
Problem:
Uncertainties in types of bjects
decisions to be made at runtime regarding what classes to use
"""
class Dog:
def speak(self):
return "Woof!"
def __str__(self):
return 'Dog'
class DogFactory:
"""Concrete Factory."""
def get_pet(... |
ktinubu/python-design-patterns | builder.py |
# Good for building complex objects
"""
Director:
Abstract Builer: interfaces
Concrete Builer: immplements the interfae
Product:object being built
"""
# use case, build a car object
class Director():
"""Director"""
def __init__(self, builder):
self._builder = builder
def construct_car(self):
self._builder.... |
ktinubu/python-design-patterns | factory.py | """
FACTORY:
Problem:
Uncertainties in types of bjects
decisions to be made at runtime regarding what classes to use
"""
class Dog:
""" A simple Dog Class"""
def __init__(self, name):
self.name = name
def speak(self):
return 'woof!'
class Cat:
""" A simple Dog Class"""
def __init__(self, name):
... |
gayatriprasad/critical-learning | model.py | <reponame>gayatriprasad/critical-learning<filename>model.py
import torch
from torch import nn
import torch.nn.functional as F
import torch.nn.init as init
import numpy as np
from helper_functions import *
def _weights_init(m):
classname = m.__class__.__name__
if isinstance(m, nn.Linear) or isinstance(m, nn.C... |
gayatriprasad/critical-learning | train_main.py | <filename>train_main.py
# torch import
from torch.utils.data import DataLoader
import torch
import torch.nn as nn
from torch import optim
from torchvision import transforms
from torch.optim.lr_scheduler import StepLR, MultiStepLR
# other libraries
import argparse
# Import from local files
from cifar_dataset import Ci... |
gayatriprasad/critical-learning | fisher.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import functional as F
from model import OrgCifarModel
from cifar_dataset import CifarDataset
from torch.nn import Linear, Conv2d
from torch.utils.data import DataLoader
import copy
from helper_functions import export_history
from copy import ... |
gayatriprasad/critical-learning | modules.py | <gh_stars>0
import torch
import numpy as np
from torch import no_grad
from torch.autograd import Variable
from helper_functions import export_history
TRAIN_HEADER = ['true_class', 'plane_(0)', 'car_(1)', 'bird_(2)', 'cat_(3)',
'deer_(4)', 'dog_(5)', 'frog_(6)', 'horse_(7)', 'ship_(8)', 'truck_(9)']
d... |
gayatriprasad/critical-learning | cifar_dataset.py | # import libraries
import torch
from torch import from_numpy
from torchvision import transforms
from torch.utils.data.dataset import Dataset
from helper_functions import unpickle, horizontal_flip, crop_and_pad, change_brightness
import numpy as np
import random
import copy
from PIL import Image
class CifarDataset(Dat... |
gayatriprasad/critical-learning | fisher_ewc.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import functional as F
from model import OrgCifarModel
from cifar_dataset import CifarDataset
from torch.nn import Linear, Conv2d
from torch.utils.data import DataLoader
import copy
from helper_functions import export_history
from copy import ... |
gayatriprasad/critical-learning | helper_functions.py | import os
import csv
import torch
import pickle
import copy
from copy import deepcopy
import random
import pandas as pd
import numpy as np
import glob
import matplotlib.pyplot as plt
import torch
import numpy as np
from torch import no_grad
from torch.autograd import Variable
def diag_fisher(model, dataset, dataloade... |
silviodc/S4-Reactjs-Flask | server/myapp/rest-server.py | <reponame>silviodc/S4-Reactjs-Flask
#!flask/bin/python
import six
from flask import Flask, jsonify, abort, request, make_response, url_for
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
@app.errorhandler(400)
@cross_origin()
def bad_request(error):
return make_response(jsonify({'error... |
fetchplus/digital-street-title-api | title_api/app.py | <filename>title_api/app.py
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.after_request
def after_request(response):
# Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the
# API manual. A major version update... |
fetchplus/digital-street-title-api | title_api/views/title_v1.py | <gh_stars>0
import datetime
import json
from flask import Blueprint, Response, current_app, request
from flask_negotiate import consumes, produces
from jsonschema import FormatChecker, RefResolver, ValidationError, validate
from sqlalchemy import exc
from title_api.exceptions import ApplicationError
from title_api.ext... |
fetchplus/digital-street-title-api | title_api/models.py | <reponame>fetchplus/digital-street-title-api
from title_api.extensions import db
from sqlalchemy.sql import func
from datetime import datetime
import json
class Segment(db.Model):
__tablename__ = 'segment'
# Fields
segment_id = db.Column(db.Integer, primary_key = True)
created_at = db.Column(db.Da... |
fetchplus/digital-street-title-api | unit_tests/test_owner.py | from unittest import TestCase, mock
from title_api.main import app
from title_api.extensions import db
from title_api.models import Owner, Address
owner_address = Address("1", "Digital Street", "Bristol", "Avon", "England", "BS2 8EN")
owner = Owner(1, "Lisa", "White", "<EMAIL>", "07123456780", 'individual', owner_addr... |
fetchplus/digital-street-title-api | title_api/views/conveyancer_v1.py | import json
from flask import Blueprint, Response, current_app
from flask_negotiate import produces
from title_api.exceptions import ApplicationError
from title_api.models import Conveyancer
# This is the blueprint object that gets registered into the app in blueprints.py.
conveyancer_v1 = Blueprint('conveyancer_v1'... |
fetchplus/digital-street-title-api | title_api/blueprints.py | # Import every blueprint file
from title_api.views import general, title_v1, conveyancer_v1, owner_v1
def register_blueprints(app):
"""Adds all blueprint objects into the app."""
app.register_blueprint(general.general)
app.register_blueprint(title_v1.title_v1, url_prefix='/v1')
app.register_blueprint(... |
fetchplus/digital-street-title-api | unit_tests/test_title.py | <filename>unit_tests/test_title.py<gh_stars>0
from unittest import TestCase, mock
from title_api.main import app
from title_api.extensions import db
from title_api.models import Title, Owner, Address
import json
owner_address = Address("1", "Digital Street", "Bristol", "Avon", "England", "BS2 8EN")
title_address = Ad... |
fetchplus/digital-street-title-api | migrations/versions/e9545aad30c2_init.py | <reponame>fetchplus/digital-street-title-api
"""empty message
Revision ID: e9545aad30c2
Revises:
Create Date: 2018-11-20 11:43:07.108432
"""
from alembic import op, context
from flask import current_app
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e9545aad30c2'
down_revision = None
... |
fetchplus/digital-street-title-api | title_api/views/owner_v1.py | import json
from flask import Blueprint, Response, current_app, request
from flask_negotiate import produces
from title_api.exceptions import ApplicationError
from title_api.models import Owner
# This is the blueprint object that gets registered into the app in blueprints.py.
owner_v1 = Blueprint('owner_v1', __name__)... |
fetchplus/digital-street-title-api | unit_tests/test_conveyancer.py | from unittest import TestCase, mock
from title_api.main import app
from title_api.extensions import db
from title_api.models import Conveyancer
conveyancer = Conveyancer("O=Conveyancer1,L=Plymouth,C=GB", "ConveyIt")
conveyancer_x500_dict = {
"organisation": "Conveyancer1",
"organisational_unit": None,
"co... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/guess_number.py | <reponame>annisanadia/Simple-Command-line-Programs-in-Python
### Created on 09-01-2019
import random
print('### Choose Level ###')
print('### Easy | Medium | Hard ###')
level = input('Enter level: ').lower()
if level == 'easy':
chance = 10
elif level == 'medium':
chance = 6
elif level == 'hard':
... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/simple_calculator.py | ### Created on 07-01-2019
# This function returns the result of the calculation of two numbers
def final_result(n, m):
if user_choice == '+':
result = n + m
elif user_choice == '-':
result = n - m
elif user_choice == '*':
result = n * m
else:
result = n / m
return re... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/rock_paper_scissors.py | ### Created on 15-1-2019
from random import choice
# Determines whether the player wins, loses, or draws
def result(player_choice, comp_choice):
if player_choice == comp_choice:
print('Tie!!')
elif player_choice == 'Rock':
if comp_choice == 'Paper':
print('You lose!\n', comp_choice... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/even_odd_checker.py | ### Created on 15-04-2019
while True:
num = input('Enter a number (blank to quit): ')
if num == '':
break
num = int(num)
if num % 2 == 0:
print(str(num) + ' is even\n')
else:
print(str(num) + ' is odd\n') |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/average.py | <filename>mini_programs/average.py
### Created on 12-05-2019
nums = input('Enter some numbers (separate by space): ').split()
# Calculate the average
sum_of_nums = 0
for num in nums:
sum_of_nums += float(num)
avg = sum_of_nums / len(nums)
# Display the numbers & the average
print('\nYou entered:', *nums, end='... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/word_counter.py | <filename>mini_programs/word_counter.py<gh_stars>1-10
### Created on 29-12-2017
# Count the words
def count_words(s):
num_of_words = len(s.split())
return num_of_words
# Count the words in the file
def count_words_file(filepath):
file = open(filepath, 'rt', encoding='utf-8')
lines = (line.strip() for ... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/char_counter.py | <reponame>annisanadia/Simple-Command-line-Programs-in-Python
### Created on 11-1-2019
while True:
print('\nEnter text (blank to quit): ')
text = input()
# Stop the program
if text == '':
break
count = {}
for char in text:
if char not in count:
count[char] = 0
... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/fibonacci.py | <reponame>annisanadia/Simple-Command-line-Programs-in-Python
### Created on 11-04-2019
while True:
n = int(input('\nHow many fibonacci numbers do you want? (0 to quit)\n'))
if n == 0:
break
elif n < 0:
print('Invalid input. Enter a positive number.')
else:
a = 0
b =... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/prime_number.py | <reponame>annisanadia/Simple-Command-line-Programs-in-Python<filename>mini_programs/prime_number.py
### Created on 10-04-2019
import math
print('######################################')
print('### PRIME NUMBER GENERATOR ###')
print('######################################')
print('### ... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/reverse_string.py | <gh_stars>1-10
### Created on 28-12-2017
def reverse_string(string):
return string[::-1]
while True:
text = input('Type text (blank to quit): ')
# Stop the program
if text == '':
break
print(reverse_string(text) + '\n')
|
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/split_even_odd.py | ### Created on 16-04-2019
nums = []
even = []
odd = []
while True:
num = input('Enter a number (blank to stop entering number): ')
if num == '':
break
else:
num = int(num)
nums.append(num)
for num in nums:
if num % 2 == 0:
even.append(num)
else:
odd.append... |
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/palindrome.py | <gh_stars>1-10
### Created on 26-04-2019
while True:
text = input('Enter a text (blank to stop): ').lower()
rev_text = text[::-1]
if text == '':
break
elif text == rev_text:
print('It is palindrome.\n')
else:
print('It is not palindrome.\n')
|
annisanadia/Simple-Command-line-Programs-in-Python | mini_programs/matrix_operations.py | ### Created on 25-05-2019
def input_matrix(matrix, row, col):
for i in range(row): # Loop for row entries
r = []
for j in range(col): # Loop for column entries
r.append(int(input('Entry in row ' + str(i+1) + ' col ' + str(j+1) + ': ')))
matrix.append(r)
def add_matrix(mat... |
mosesnah-shared/whip-project-targeting | MuJoCo/run.py | <reponame>mosesnah-shared/whip-project-targeting
#!/usr/bin/env python3
"""
# ============================================================================= #
| Project: [M3X Whip Project]
| Title: mujoco-py scripts for running a whip-targeting simuation
| Author: <NAME>
| Email: [Moses... |
mosesnah-shared/whip-project-targeting | MuJoCo/modules/simulation.py | """
[PYTHON NAMING CONVENTION]
module_name, package_name, ClassName, method_name, ExceptionName, function_name,
GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name,
local_var_name.
"""
import sys, os
import cv2
import re
import pprint
import shutil
import numpy as np
import... |
mosesnah-shared/whip-project-targeting | MuJoCo/modules/traj_funcs.py | # [Built-in modules]
# [3rd party modules]
import numpy as np
import sympy as sp
from modules.constants import Constants
try:
import sympy as sp
from sympy.utilities.lambdify import lambdify, implemented_function
except ImportError as e:
raise error.DependencyNotInstalled( "{}. (HINT: you need to install... |
mosesnah-shared/whip-project-targeting | MuJoCo/modules/utils.py | # [Built-in modules]
import os
import re
import sys
import shutil
import time, datetime
import math as myMath
import glob
# [3rd party modules]
import cv2
import numpy as np
import xml.etree.ElementTree as ET
import sympy as sp
from sympy.utilities.lambdify import lambdify, implemented_function
from... |
mosesnah-shared/whip-project-targeting | MuJoCo/modules/objectives.py | import re
import numpy as np
import pprint
from modules.utils import length_elem2elem
try:
import mujoco_py as mjPy
except ImportError as e:
raise error.DependencyNotInstalled( "{}. (HINT: you need to install mujoco_py, \
and also perform the setup instructions her... |
mosesnah-shared/whip-project-targeting | MuJoCo/quick_debug.py | import mujoco_py as mjPy
import numpy as np
from modules.constants import Constants as C
from modules.utils import my_print
from scipy.spatial.transform import Rotation as R
def main( ):
model_name = "1_3D_model_update.xml"
mjModel = mjPy.load_model_from_path( C.MODEL_DIR + model_name... |
mosesnah-shared/whip-project-targeting | MuJoCo/modules/constants.py | <filename>MuJoCo/modules/constants.py
class Constants:
PROJECT_NAME = '[M3X] Whip Project'
VERSION = '1.0.1'
UPDATE_DATE = '2021.07.31'
AUTHOR_GITHUB = 'mosesnah-shared'
AUTHOR_FULL_NAME = '<NAME>'
DESCRIPTION = "mujoco-py scrip... |
wasade/docs | source/sphinx_extensions/external_links.py | <gh_stars>0
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.