content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################
# File: main.py
# Created Date: Tuesday April 28th 2020
# Author: Chen Xuanhong
# Email: chenxuanhongzju@outlook.com
# Last Modified: Wednesday, 20th January 2021 2:09:59 pm
# Modified By: Chen Xuanhong
# Copyri... |
import unittest
import os
import os.path
from programy.storage.stores.file.store.nodes import FilePatternNodeStore
from programy.storage.stores.file.engine import FileStorageEngine
from programy.storage.stores.file.config import FileStorageConfiguration
from programy.parser.pattern.factory import PatternNodeFactory
fr... |
# -*- coding: utf-8 -*-
"""
.. module:: Handlers.Streetlight.handler
:platform: Unix, Windows
.. moduleauthor:: Aki Mäkinen <aki.makinen@outlook.com>
"""
__author__ = 'Aki Mäkinen'
import re
import urllib
import json
from RESThandlers.HandlerInterface.Exceptions import GenericDBError, ObjectNotFound
from RESThan... |
{
'name': "Paypal - Unsupported Currency Support",
'summary': """
Pay unsupported currencies with Paypal""",
'summary_vi_VN': """
Thanh toán Paypal cho các khoản tiền tệ không nằm trong danh mục tiền tệ được Paypal hỗ trợ
""",
'description': """
The problem
===========
Paypal supports a limited ... |
import argparse
import os
import time
from collections import Counter
import logging
from omnidata import load_mnist
from omnimodel import Statistician
from omniplot import save_test_grid
from torch import optim
from torch.autograd import Variable
from torch.nn import functional as F
from torch.utils import data
from ... |
#!/usr/local/bin/python2.7
# -*- coding: utf-8 -*-
#
# 研发管理MIS系统:行为分析
# =========================
# 2019.2.13 @Chengdu
#
#
from __future__ import unicode_literals
import handler
try:
import configparser as configparser
except Exception:
import ConfigParser as configparser
import sys
reload(sys)
sys.s... |
# -*- coding: utf-8 -*-
import os, re
from ComputeFDR import Compute_FDR
def PeptideLvlFDRout(S2_OutputFiles, S2_peplvl_FDR, ProteoStormLOG):
def checkfloat(number):
try:
float(number)
except ValueError:
return False
return True
#['#SpecFilename','Scan'... |
from time import sleep
from rethreader._rethreader import KeyThread
def action():
for i in range(10):
print(i)
sleep(0.4)
if __name__ == '__main__':
kt = KeyThread(None, action).start()
sleep(1)
print(1)
kt.kill()
|
from django.urls import reverse
from rest_framework import status
from django.test import TestCase, Client
from django.db import IntegrityError
from rest_framework.test import APITestCase
from tm_api.models import (
Machine,
BaseScript,
MasterScenario,
Scenario,
Test,
DryRunData
)
from tm_api.se... |
# -*- coding: utf-8 -*-
from qlazy.UnitaryOperator import UnitaryOperator
class PauliProduct(UnitaryOperator):
""" Pauli Product
Attributes
----------
qid : list of int
list of qubit id.
pauli_list : list of str
list of pauli operators.
"""
def __init__(self, pau... |
from django.conf.urls import patterns, include, url
from django.conf import settings
from .views import RootTextView, HomeView
urlpatterns = patterns('',
url(r'^$',
HomeView.as_view(),
name='home'),
(r'^(?i)favicon.ico$', 'django.views.static.serve', {'path':'favicon.ico','document_root'... |
import numpy as np
from pyquil import Program
from pyquil.gates import MEASURE, I, CNOT, X, H, Z, RZ, RY
import sys
from pyquil.api import QVMConnection
from pyquil.quil import DefGate
import basic_tests
import stabilizer_code
import stabilizer_check_matrices
import noise_models_kraus
import matplotlib.pyplot as plt... |
from rest_framework import serializers
from bluebottle.bluebottle_utils.validators import validate_postal_code
from .models import DocDataPaymentOrder
class DocDataOrderProfileSerializer(serializers.ModelSerializer):
# TODO Generate country list from docdata api and use ChoiceField.
country = serializers.Char... |
class QFunction:
def __init__(self, round_digits):
self.round_digits = round_digits
self.q_table = {}
def register(self, observations, action, registration_value):
index = self._get_index(observations, action)
self.q_table[index] = registration_value
def get_value(self, ... |
import uuid
from auditlog.registry import auditlog
from django.conf import settings
from django.contrib.gis.db import models
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from enumfields import Enum, EnumField, EnumIntegerField
... |
from typing import Optional
from chalice import Chalice, Cron
import slack
import os
from datetime import datetime, timedelta
app = Chalice(app_name='autostatus')
def set_status(status_text: str, status_emoji: str = ":no_bell:",
expiration_min: Optional[int] = None, dnd: bool = False) -> None:
"""... |
"""Utility functions to test `backpack.core.derivatives`"""
import torch
from backpack.core.derivatives import derivatives_for
def get_available_devices():
"""Return CPU and, if present, GPU device.
Returns:
[torch.device]: Available devices for `torch`.
"""
devices = [torch.device("cpu")]
... |
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import torchvision
from matplotlib import font_manager, rc
from PIL import Image, ImageDraw, ImageFont
from piq import psnr, ssim
from data_management import (
AlmostFixedMaskDataset,
CropOrPadAndResimulate,
Fla... |
import itertools
class LCD:
""" """
def __init__(self, Waveshare = False):
if Waveshare == True: import st7735s as controller
else: import st7735s_mock as controller
self.lcd = controller.ST7735S()
def draw(self, layout):
self.lcd.draw(layout.get_... |
import asyncio
from ..utils import hex_to_dec
class TxpoolMixin:
@asyncio.coroutine
def txpool_content(self):
"""https://github.com/ethereum/go-ethereum/wiki/Management-APIs#txpool_content
:rtype: dict
"""
result = yield from self.rpc_call('txpool_content')
# TODO: U... |
raise NotImplementedError("mutex is not yet implemented in Skulpt")
|
"""
Model(s) for behavior_instance resource on HUE bridge.
https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_behavior_instance
"""
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional
from .behavior_script import BehaviorScriptMetadata
from .resource import... |
"""Example of linear regression."""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from alchina.optimizers import MBGD
from alchina.regressors import LinearRegressor
from sklearn import datasets
# Load the Boston house prices dataset
houses = datasets.load_boston()
# Create the input featu... |
from pypsql import pyPsql
|
"""
There is a collection of input strings and a collection of query strings.
For each query string, determine how many times it occurs in the list of input strings.
Example given a input strings = ['ab', 'ab', 'abc'] and
queries = ['ab',' abc', 'bc'] we find 2 instances of 'ab',
1 of 'abc' and 0 of 'bc'. For each q... |
from mlgames.player import Player
import random
class CompositePlayer(Player):
def __init__(self, primary, secondary, primaryness):
self.primary = primary
self.secondary = secondary
self.primaryness = primaryness
def name(self):
return "({:.2f}%) {} + ({:.2f}%) {}".format(self.primaryness * 100, self.prima... |
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import json
import urllib2
import string
from alfred import Feedback
from settings import PROTOCOL, HOSTNAME
from http_server import stop
def device_collector(query=""):
stop()
feedback = Feedback()
args = string.split(query, " ")
command = args[-1]
if len(command) < 1:
command = args[-... |
#!/usr/bin/python3.4
#
#SCRIPT: integer.py
#AUTHOR: Severin Kaderli
#PURPOSE: Some calculations in python
#USAGE: ./integer.py
from math import sqrt
# String ausgeben
print("--------------------")
print("Hello Python!")
print("--------------------")
#Integer: Pythogaras
print("Integer:")
print("Pythagoras a^2+b^2=c^... |
from pathlib import Path
from sphinx_hyperhelp import HelpFile, HelpIndex, HelpTopic
def test_prune():
index = HelpIndex("SphinxTest", "nice tests", Path("."))
index.help_files["keep_all.txt"] = HelpFile()
index.help_files["keep_all.txt"].topics.append(
HelpTopic("keep_all", aliases=["keep_all_bi... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from lasagne.layers import DropoutLayer
from lasagne.nonlinearities import softmax
from lasagne... |
__licence__ = 'MIT'
__author__ = 'kuyaki'
__credits__ = ['kuyaki']
__maintainer__ = 'kuyaki'
__date__ = '2021/03/30'
from unittest import TestCase
from program_slicing.graph.statement import Statement, StatementType
from program_slicing.graph.point import Point
class StatementTestCase(TestCase):
def test_repr_... |
# Generated by Django 2.2.1 on 2019-09-06 00:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('persons', '0002_auto_20190905_2122'),
('locations', '0002_remove_address_city'),
]
operations = [
migrations.DeleteModel(
name='... |
"""Support for monitoring the qBittorrent API."""
from __future__ import annotations
import logging
from qbittorrent.client import Client, LoginRequired
from requests.exceptions import RequestException
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
S... |
import os
def getTasks(name):
r = os.popen('tasklist /v').read().strip().split('\n')
print ('# of tasks is %s' % (len(r)))
for i in range(len(r)):
s = r[i]
if name in r[i]:
print ('%s in r[i]' %(name))
return r[i]
return []
if __name__ == '__main__':
'''
... |
"""Implements memory network encoder.
Author(s): Satwik Kottur
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import torch
import torch.nn as nn
from tools import rnn_support as rnn
from tools import torch_support as support
import models.encoders as encode... |
import time
import requests
import json
COMMENT_KARMA_MULTIPLYER = 1.0
LINK_KARMA_MULTIPLYER = 0.8
def get_json_from_url(username):
reddit_url = "http://www.reddit.com/user/{}/about.json".format(username.strip())
user_agent = {'User-agent': 'Mozilla/5.0'}
return requests.get(reddit_url, headers= user_agent).text
... |
__doc__ = """
Makes Reviews more simplified(stopword removal etc) for Analysis
"""
from nltk import WordNetLemmatizer
from pymongo import MongoClient
from nltk.corpus import stopwords
import nltk
from Constants import Parameters
import os
import time
import json
corpus_collection = \
... |
from datetime import datetime
def easter_sunday(year):
y = year
a = y % 19
b = y / 100
c = y % 100
d = b / 4
e = b % 4
g = (8 * b + 13) / 25
h = (19 * a + b - d - g + 15) % 30
j = c / 4
k = c % 4
m = (a + 11 * h) / 319
r = (2 * e + 2 * j - k - h + m + 32) % 7
n = int((h - m + r + 90) / 25) # mes
p = int(... |
from lib import action
class ConsulAclListAction(action.ConsulBaseAction):
def run(self, consul_profile=None, token=None):
self._create_client(consul_profile)
# Action parameter "token" defaults to an empty string when no input is provided.
# Consul-Python tests for None to use the agent's... |
"""
https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html
generate image data
"""
import argparse
import os
import sys
from keras.preprocessing.image import (
ImageDataGenerator,
img_to_array,
load_img,
)
def generate(
from_dir: str,
file: str,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# the above line is to avoid 'SyntaxError: Non-UTF-8 code starting with' error
'''
author:
raja
source: (if any)
https://stackoverflow.com/questions/3277503/in-python-how-do-i-read-a-file-line-by-line-into-a-list
'''
import requests
import db_util as dbu
import M... |
"""This is a script to create k8s clusters using Platform9 Qbert and Packet Baremetal."""
import openstack
import qbert
import uuid
import re
import os
import json
from async_tasks import create_terraform_stack, delete_terraform_stack, authorize_cluster
def delete_cluster(endpoint, user, pw, tenant, region, cluster_... |
import chess
#Used to count how many board states have beeen visited on a search
COUNT = 0
def evaluate_board(board):
#Score telling us the state of the game, positive means white is winning, negative means black is winning
score = 0
'''
Adding the value of the white pieces to our board score
boar... |
import logging
from haystack import indexes
from api.v2.models.Topic import Topic as TopicModel
from api.v2.search.index import TxnAwareSearchIndex
LOGGER = logging.getLogger(__name__)
class TopicIndex(TxnAwareSearchIndex, indexes.Indexable):
document = indexes.CharField(document=True)
topic_source_id = i... |
import json
ctakesJsonFile=open("/Users/charanshampur/Sites/MyHtml/circle.json","r")
locOrgFile=open("output.json","w")
jsonStr=ctakesJsonFile.readline()
jsonLoad=json.loads(jsonStr)
locGraph={}
for doc in jsonLoad:
if "Geographic_NAME" in doc and "NER_ORGANIZATION" in doc:
if doc["Geographic_NAME"] not... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 11:23:26 2021
@author: alpha
"""
import numpy as np
aList = list(range(1000))
finalSize = 500
## Method for downsizing list to a apecific len by even spacing of elements
idx = np.round(np.linspace(0, len(aList) - 1, finalSize)).astype(int)
idx = list(idx) |
import numpy as np
import math
import cv2
import random
import os
from utils import load_config, extract_filename, load_base_xml, write_base_cml
# project setting
project = "line/"
project_path = "../projects/" + project
# load config
cfg = load_config(project_path)
cfg["train_data_dir"] = project_path + "datasets/" ... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
nodeRec = []
... |
"""Logger factory abstraction
The provided AbstractLoggerFactory has to be implemented as a base class
for your project's classes. That way, all your objects will have a `logger`
property which is in fact a `logging.Logger`
"""
from ._constants import Level
import abc
import logging
import typing
class AbstractLog... |
# Copyright 2015 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... |
import json
from pathlib import Path
import gspread
import numpy as np
import pandas as pd
from oauth2client.service_account import ServiceAccountCredentials
LOCAL_DATA_PATH = Path(__file__).parents[2] / 'data'
SECRET_FILE = Path(__file__).parents[2] / 'secrets/google-sheets-key.json'
def load_project_db(fn=None, s... |
import datetime
import json
import logging
import re
import requests
import urllib
from certification_management.business import Level
from certification_management.business import User
from certification_management.business import UserCertification
from certification_management.business import Voucher
from slackclient... |
import fnmatch
import os
import pathlib
import shutil
import subprocess
import re
from os.path import abspath, join
PWD = pathlib.Path(__file__).parent.resolve()
# The folder where the protobuf files live:
proto_path = abspath(join(PWD, "..", "proto", "src"))
# Output folder (where the python definitions will be ge... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-28 01:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('catalog', '0002_auto_20160228_0141'),
... |
from CNNectome.networks import ops3d
from CNNectome.utils import config_loader
import tensorflow as tf
import json
import logging
import numpy as np
from simpleference.inference.inference import run_inference_zarr_multi_crop
from simpleference.inference.util import *
from simpleference.backends.gunpowder.tensorflow.bac... |
from advertorch.attacks import Attack
import torch
from tqdm import tqdm
from torch import optim
import ipdb
import sys
from __init__ import data_and_model_setup, load_data
from __init__ import eval as eval_attacker
import wandb
import torch
from torch import autograd
from torch.distributions.bernoulli import Bernoulli... |
import numpy as np
from bokeh.io import output_file, show
from bokeh.layouts import column
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import HoverTool
# Data for plot a
x = [0, 100, 1000, 2000, 3000, 5000, 10000]
class_methods = [0, 0.3757, 2.1785, 4.2088, 6.3451, 10.4275, 21.1682]
class_ext... |
import os
import json
import csv
from os import listdir
from os.path import isfile, join
# Constants
BASE_DATASET_DIR = 'dataset'
BASE_TASKS_DIR = join(BASE_DATASET_DIR, 'tasks_json')
# Read each task
all_descriptions = []
task_fns = [f for f in listdir(BASE_TASKS_DIR) if isfile(join(BASE_TASKS_DIR, f))]
for task_fn... |
from django.conf import settings
from django.contrib import admin
from django.utils.html import format_html
from organizations.base_admin import (
BaseOrganizationAdmin,
BaseOrganizationUserAdmin,
BaseOwnerInline,
)
from .models import Organization, OrganizationOwner, OrganizationUser
ORGANIZATION_LIST_FI... |
#!/usr/bin/python
import sys
import time
import httplib
import urllib
import re
import serial
import json
APIKEY = 'Y1JUZC930YOKH5JA'
def upload(temperature, humidity, UV_value, light_value):
params = urllib.urlencode({'field1': temperature, 'field2': humidity, 'field3': UV_value, 'field4': light_value, 'key... |
import logging
from os import linesep
from twisted.internet import stdio
from twisted.protocols import basic
from brutal.protocols.core import ProtocolBackend
class TestConsoleClient(basic.LineReceiver):
delimiter = linesep
#delimiter = '\n' # unix terminal style newlines
def __init__(self, backend):
... |
import numpy as np
from distributionLib import Dist
pois = Dist.poissonDist
xBar = Dist.expt
var = Dist.var
coolPrint = Dist.coolPrint
#test-1
'''
https://en.wikipedia.org/wiki/Poisson_distribution
Example
Ugarte and colleagues report that the average number of goals in a World Cup
soccer match is approximately 2.5 an... |
# Copyright (C) 2012 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of so... |
from mp_api.core.resource import Resource
from mp_api.tasks.models import TaskDoc
from mp_api.tasks.utils import calcs_reversed_to_trajectory
from mp_api.materials.models.doc import MaterialsCoreDoc
from mp_api.core.query_operator import PaginationQuery, SortQuery, SparseFieldsQuery
from mp_api.materials.query_operat... |
# !/usr/bin/env python3
"""
author: Apeiria
contact: apeiriaStar@outlook.com
file: TSP_solve.py
function: solve the traveling salesman problem
"""
# ---------------------------------- import --------------------------------- #
import os
import sys
import random
import ray
# Problem impor... |
"""
Gradient descent within the simplex
Method inspired by the qustion "what would a water droplet stuckin insise the
positive simplex go when pulled in the direction of the gradient which would
otherwise take the droplet outside of the simplex
"""
# pylint: disable=invalid-name
import numpy as np
from numpy import (... |
# Copyright 2020 Half-Shot
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Copyright 2012-2021 Smartling, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/li... |
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "example@example.com"
idn = input("Enter ID:")
handle = Entrez.efetch(db="nucleotide", id = idn, rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
idnT = input("Enter ID:")
handlet = Entrez.efetch(db="nucleotide", id = idnT, rettype="... |
import numpy as np
def run_microphone(shared_resources):
shared_resources.get_numpy_resources()
import sounddevice as sd
import time as pytime
shared_resources.resources["logging_queue"].put("[run microphone] Running the audio stream")
# Assign the nice microphone to be default input
sd.defa... |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: clonecopy.py
#
# Tests: the CloneWindow function.
#
# Defect ID: VisIt00003027
#
# Programmer: Brad Whitlock
# Date: Wed Feb 12 11:59:14 PDT 2003
#
# Modifications:
# Kathleen Bonnell,... |
# ltbvc -- script that produces lilypond files and target files
# for single voices, a complete score, a midi file, audio and
# video files based on a configuration file from a lilypond
# music fragment file
#
# author: Dr. Thomas Tensi, 2006 - 2018
#====================
# IMPORTS
#=========... |
def div_canon(expr, args):
del expr
# x / y == x * y**(-1).
return args[0] - args[1], []
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020, 04, 18, 20, 53
# @Author : Allen Zhang
# @File : ~/a2g-wordsbook/main/a2g-wordsbook.py
# @Description :
#
"""
```
usage: a2g-wordsbook.py [-h] [-i 输入文件名]
[--parse-type {txt,transcribe_json,pdf,word}]
[-... |
"""Test code for simulating rise curves
"""
import numpy as np
import pytest
import yaml
import spowtd.simulate_rise as simulate_rise_mod
import spowtd.specific_yield as specific_yield_mod
from spowtd.test import conftest
@pytest.mark.parametrize(
'sy_type, expected_curve',
[
('peatclsm', [
... |
# Generated by Django 4.0.1 on 2022-06-05 08:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# 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... |
# =============================================
# MPL CLASS
# =============================================
import ctypes
import logging
import math
from madgraph import MG5DIR
from madgraph.various import misc
logger=logging.getLogger("SubtractionCurrents")
import madgraph.various.math_tools.mpl as MP... |
import gd
import time
import os
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume
import sys
def main():
try:
app_to_mute = sys.argv[1]
except IndexError:
app_to_mute = "Discord.exe"
# setup volume
volume = None; vol = None
sessions = AudioUtilities.GetAllSessions(... |
"""
File: inversion_mutation.py
Created by ngocjr7 on 2020-10-05 22:06
Email: ngocjr7@gmail.com
Github: https://github.com/ngocjr7
Description:
"""
from __future__ import absolute_import
from geneticpython.models.int_individual import IntIndividual
from geneticpython.core.operators.mutation.mutation import Mutation... |
import math
import turtle
def iterc(c):
iters = 0
z = 0 + 0j
while iters < 16 and math.hypot(z.real, z.imag) < 2:
z = z * z + c
iters += 1
return iters
def getcolour(pos):
x = iterc(pos)
colournum = int(x * 6.25)
return 'gray{}'.format(colournum)
def drawpixel(x, y, colo... |
import csv
def naiveSampler(file_path, header, nb_rows):
file_to_sample = open(file_path, 'r')
reader = csv.reader(file_to_sample)
next(reader)
output_file = open("./outputs/naive_sampled_"+str(nb_rows)+".csv", 'w+')
output_file.write(header)
for row in reader:
output_file.write(','.j... |
import importlib
import os
import sys
import time
from functools import wraps
from itertools import groupby
from operator import itemgetter
from types import MethodType
def identity(x):
return x
def compose(*functions):
def inner(arg):
for f in reversed(functions):
arg = f(arg)
... |
"""
=============================
Customized Colorbars Tutorial
=============================
This tutorial shows how to build and customize standalone colorbars, i.e.
without an attached plot.
Customized Colorbars
====================
A `~.Figure.colorbar` needs a "mappable" (`matplotlib.cm.ScalarMappable`)
object ... |
from __future__ import print_function
#
# This example tries to load a decompiler plugin corresponding to the current
# architecture (and address size) right after auto-analysis is performed,
# and then tries to decompile the function at the first entrypoint.
#
# It is particularly suited for use with the '-S' flag.
#
... |
import torchvision.transforms as T
from torchvision import datasets
from ..utils import common_functions as c_f
from ..utils.constants import IMAGENET_MEAN, IMAGENET_STD
from ..utils.transforms import GrayscaleToRGB
from .combined_source_and_target import CombinedSourceAndTargetDataset
from .concat_dataset import Conc... |
from servee.wysiwyg.panels import InsertPanel
from django.template.loader import render_to_string
from oldcontrib.media.gallery.models import Gallery
class GalleryPanel(InsertPanel):
name = 'Gallery'
has_content = True
def nav_title(self):
return 'Gallery'
def title(self):
re... |
from .. import blueprint
from flask import request, make_response, jsonify
from cerberus import Validator
from lib.db import session
from lib.request import is_json
from core.accounts import Account
@blueprint.route('/', methods=['GET'])
def get_accounts():
"""Returns all the accounts registered"""
account... |
from datetime import datetime
import csv
import os
class StorageRepository:
PATH = 'storage/'
def save(self, todos):
for i in range(len(todos)):
user_id = todos[i]["userId"]
id = todos[i]["id"]
title = todos[i]["title"]
completed = todos[i]["completed"... |
# -*- coding: utf-8 -*-
from simmate.workflows import all as all_workflows
def get_list_of_all_workflows():
"""
Returns a list of all the workflows located in the workflows.all module
"""
workflow_names = [n for n in dir(all_workflows) if "__" not in n]
return workflow_names
|
#===============================================================================
# Copyright 2014-2022 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... |
import logging
from collections import defaultdict
from langid.langid import LanguageIdentifier, model
# https://github.com/saffsd/langid.py
from aleph.core import language_whitelist
from aleph.analyze.analyzer import Analyzer
log = logging.getLogger(__name__)
THRESHOLD = 0.9
CUTOFF = 50
class LanguageAnalyzer(Ana... |
import json
import re
import datetime
import time
import random
from shutil import copyfile
from pathlib import Path
from os import listdir, path
from os.path import join
from yoloannotator.models import OpenCVBBoxConfidenceModel
from yoloannotator.image import Image
from typing import List
def get_image_json_dummy(... |
from fileinput import filename
import logging
import click
from pathlib import Path
from gammapy.scripts.download import progress_download
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
BASE_URL = "https://github.com/gammapy/gammapy-data/raw/master/"
PATH = Path(__file__).parent.parent
PATH... |
import memory_profiler as mem_profile
import random
import time
names = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']
# print('Memory (Before): {}Mb '.format(mem_profile.memory_usage_psutil()))
print('Memory (Before): ' + str(mem_profile.memory_us... |
from .models import Profile, Projects
from django import forms
from django.contrib.auth.models import User
class PostProjectForm(forms.ModelForm):
class Meta:
model = Projects
exclude = ['posted_by', 'date_posted']
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
... |
import tests.config as config
service = config.service
environment = config.environment
# input for preprocessing
# https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateProcessingJob.html
pretraining_input = {}
preinference_input = {}
# input for modeling
# https://docs.aws.amazon.com/sagemaker/latest... |
"""Default settings for tests."""
import os
import pkg_resources as pkg
import numpy as np
###################################################################################################
###################################################################################################
# Define general settings... |
"""
Unit tests against the real profile server
"""
from __future__ import absolute_import
import os
import unittest
from django.conf import settings
from ...docker_settings import (
PROFILE_SERVER,
PROFILE_SERVER_KEY,
PROFILE_SERVER_SECRET,
)
from ...webservice import UserWebService
settings_monkeypatc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.