content stringlengths 5 1.05M |
|---|
import random
def gen_param(size):
mapping = list(range(size))
random.shuffle(mapping)
ops = list(random.choices(range(7),k=size))
return {"mapping":mapping, "ops":ops}
def fold(value, new_size, mapping, ops):
assert type(value) == str, "value must be string"
assert len(mapping) == len(ops... |
import asyncio
import collections
from datetime import datetime
from typing import ClassVar, Sequence, Tuple, Union
import telethon as tg
import tomlkit
from tomlkit.toml_document import TOMLDocument
from .. import command, module, util
Exchange = collections.namedtuple("Exchange", ["command", "response"])
class B... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from fnmatch import fnmatch
import mimetypes
import os
from api_data_source import APIDataSource
from api_list_data_source import APIListDataSource
from... |
from MyMainPackage.some_main_script import report_main #some_main_script is module name and report_main is function name
from MyMainPackage.SubPackage import mysubscript#SubPackage is module name and mysubscript is function name
report_main()
mysubscript.sub_report()
|
from bisect import bisect
from collections import deque
import logging
from multiprocessing import Queue
import os
import queue
from statistics import fmean
from typing import Deque, Iterable, List, Optional, Tuple, Union
import numpy as np # type: ignore
import pygame # type: ignore
from pygame.locals import * # t... |
from setuptools import setup, find_packages
setup(
name="go-optouts",
version="0.1.2",
url='http://github.com/praekelt/go-optouts-api',
license='BSD',
description="An API for managing Vumi Go opt outs.",
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
auth... |
from flask import Flask
app = Flask("mini-amazon", static_folder="./mini_amazon/static",
static_url_path="",
template_folder="./mini_amazon/templates")
from mini_amazon import api, views
|
import beluga
import logging
import numpy as np
bfr_diameter = 9
Hscale = 8.44e3
bfr_thrust0_sea = 1.993e6*31
bfr_thrust0_vac = 2.295e6*31
bfr_thrust1_sea = 1.993e6*7
bfr_thrust1_vac = 2.295e6*7
bfr_mass0 = 4400e3
bfr_mass0f = 1335e3
bfr_mass1 = 1335e3
bfr_mass1f = 85e3
bfr_massflow0 = -615.8468*31
bfr_massflow1 =... |
#!/usr/bin/env python
"""
Apply a patch that adds Rust doc comments to bindgen-generated Rust source.
To run unittests:
python -m unittest -v add_doc_comments
"""
# pylint: disable=too-few-public-methods
from __future__ import print_function
import argparse
import logging
import re
import unittest
INDENT_PAT... |
from flask import request, jsonify, session
from app.app import db
from passlib.hash import pbkdf2_sha256
from functools import wraps
from Users.user_schema import user_profile_schema,org_profile_schema
from Topics.model import Topics
from Events.model import Events
import uuid
import jwt
import os
class User:
de... |
import pygame
class Player():
def __init__(self, x, y, w, h, speed, life):
self.x = x
self.y = y
self.w = w
self.h = h
self.speed = speed
self.life = life
self.max_life = life
def tick(self, screen):
self.back(screen.get_width(), screen.get... |
# Copyright (c) 2020-20201, LE GOFF Vincent
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions... |
import sys
sys.path.append("../classifier")
import classifier
from detection_process import DetectionProcess
from heat_map import HeatMap
from detector import Detector
from search_windows_factory import SearchWindowsFactory
from sklearn.externals import joblib
car_id = 1 # TODO: grab from saved model
hei... |
from django.core.validators import EmailValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from core.models import BaseAbstractModel
from core.utils import PhoneNumberValidator
class PetOwner(BaseAbstractModel):
phone_number_validator = PhoneNumberValidator()
email... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#=============================================================================
# ProjectName: leetcode
# FileName: test_longest_substring_without_repeating_characters
# Desc: 测试查找字符串中的最长子串
# Author: seekplum
# Email: 1131909224m@sina.cn
# ... |
import copy
import os
import ray
import torch
'''
self.checkpoint = {
"step_counter": 0,
"weights": None,
"optimizer_state": None,
"total_reward": 0,
"episode_length": 0,
"mean_value": 0,
"training_step": 0,
"lr": 0,
... |
#assign bilangan kelipatan 2
for y in range(2, 120000, 2):
print('y=', y) |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# Copyright (c) 2008 Emanuele Olivetti <emanuele@relativita.com>
# See COPYING file distributed along with the PyMVPA pac... |
'''
iox
interface VirtualPortGroup0
ip address 192.168.1.1 255.255.255.0
app-hosting appid guestshell
app-vnic gateway0 virtualportgroup 0 guest-interface 0
guest-ipaddress 192.168.1.2 netmask 255.255.255.0
app-default-gateway 192.168.1.1 guest-interface 0
name-server0 8.8.8.8
event manager applet WANKIM3
e... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import __future__
import sys
print("===" * 30)
print("SAMPLE INPUT:")
print("===" * 30)
print(open("./challenge_sample_input", 'r').read())
sys.stdin = open("./challenge_sample_input", 'r')
print("===" * 30)
print("SAMPLE OUTPUT:")
print("===" * 30)
print(open("./challenge_... |
from __future__ import unicode_literals
from .common import InfoExtractor
class AlJazeeraIE(InfoExtractor):
_VALID_URL = r'http://www\.aljazeera\.com/programmes/.*?/(?P<id>[^/]+)\.html'
_TEST = {
'url': 'http://www.aljazeera.com/programmes/the-slum/2014/08/deliverance-201482883754237240.html',
... |
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability import distributions as tfd
import numpy as np
DistLambda = tfp.layers.DistributionLambda
def smooth_relu(x, c=np.log(np.expm1(1.)), eps=1e-5):
"""
Exponentiating real values so that the resulting quantity is positive c... |
from abc import ABC, abstractmethod
class StrategyTemplate(ABC):
minimum_period = 100
indicators = []
df = None
@abstractmethod
def setUp(self, df, symbol):
""" Computes the indicators for the given dataframe
(usually gets called by the bot controller when recent candlestick
... |
#!/usr/bin/env python3
"""Pick targets recommended for testing."""
import argparse
import logging
from adapt import alignment
from adapt.prepare import cluster
from adapt import target_search
from adapt.utils import formatting
from adapt.utils import guide
from adapt.utils import log
from adapt.utils import seq_io
_... |
from tkinter import *
import pymysql
def deleteTransport():
root = Tk()
connection = pymysql.connect(host = "localhost", user = "root", passwd = "shaurya3027#", database = "test")
cursor = connection.cursor()
def delete():
delquery2 = "Delete from bus where Trans_ID = %s;"
delquery3 = "Delete from t... |
# -*- coding: utf-8 -*-
'''
********************
sonic.server.command
********************
Modulo que contiene los comandos de las aplicaciones servidor del juego.
'''
from flask import current_app
from flask_script import Command, Option, prompt, prompt_bool
class RunServerCommand(Command):
'''Runs the Flask deve... |
from ..basestore import CatalogError, DuplicateKeyError
class PipelineCreateFailure(CatalogError):
pass
class DuplicatePipelineError(CatalogError):
pass
class PipelineUpdateFailure(CatalogError):
pass
|
import torch
from torch import nn
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
# convolution layers
self.conv1 = nn.Conv2d(
in_channels=1,
out_channels=6,
kernel_size=(5,5),
stride=(1,1),
padding=(0,0)
)
self.conv2 = nn.Conv2d(
i... |
import abc
import numpy as np
import pandas as pd
class LabViewTimings(metaclass=abc.ABCMeta):
"""A class for storing pixel-level timing information for an ROI."""
def __init__(self, relative_times_path, roi_path, dwell_time):
self.dwell_time = dwell_time
self._read_relative_times_file(relat... |
# $Id$
# to use a shader on an actor, do this first before export:
# a = vtk.vtkRIBProperty()
# a.SetVariable('Km', 'float')
# a.SetParameter('Km', '1')
# a.SetDisplacementShader('dented')
# actor.SetProperty(a)
import os
import tempfile
import vtk
className = obj.__class__.__name__
if className == 'slice3dVWR':
... |
from mitra.api import account
from mitra.api import entry
from mitra.api import category
|
# Copyright (C) 2011 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
# Simple WSGI module intended to be used by uWSGI, e.g.:
# uwsgi -w acoustid.wsgi --pythonpath ~/acoustid/ --env ACOUSTID_CONFIG=~/acoustid/acoustid.conf --http :9090
# uwsgi -w acoustid.wsgi --pythonpath ~/acous... |
import time
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tqdm import tqdm
from cont_evaluate import evaluate_policy
from algorithms.klac import ReplayBuffer
from algorithms.sac import apply_squashing_func
class RegularActor(tf.keras.layers.Layer):
def __init__(self, acti... |
#!/usr/bin/python
#Imports as before:
import numpy as np
from matplotlib.pyplot import figure,legend
from matplotlib.mlab import csv2rec
from nitime.timeseries import UniformTimeSeries
from nitime.utils import percent_change
import nitime.viz
reload(nitime.viz)
from nitime.viz import matshow_roi
#This time Import the... |
import time
import pygame
margin = 0.05
class Display:
def __init__(self, board, width = 1440, height = 900):
self.board = board
pygame.init()
self.surface = pygame.display.set_mode((width, height))
self.width = width
self.height = height
self.x0 = width * margin... |
import numpy as np
import tensorflow as tf
def crop_and_resize(featuremap, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
featuremap: NHWC
boxes: nx4, x1y1x2y2
box_ind: (n,)
... |
"""Helper functions for numpy"""
import numpy as np
def rolling_window(a, size):
shape = a.shape[:-1] + (a.shape[-1] - size + 1, size)
strides = a.strides + (a. strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
def find_sub_array_in_2D_array(sub_array, array):
""... |
from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.contrib.auth import logout
from survey.forms.aboutus_form import AboutUsForm, SuccessStoriesForm
from survey... |
import xml.dom.minidom
doc = xml.dom.minidom.parse('mercury.xml')
print doc.toxml('utf-8')
|
from ..util.crypt import crypt, verify
class UserPasswordMixin(object):
_password = None
@property
def password(self):
return self._password
@password.setter
def password(self, password):
self._password = crypt(password)
def validate_password(self, password):
if self.... |
# Topology is very simple:
# A --- B --- C
topo = { 'A' : ['B'],
'B' : ['A', 'C'],
'C' : ['B'] }
|
import os
import random
import numpy as np
import torch
import torch.nn as nn
def Netpara(net: nn.Module):
'''
detect the paramaters info of the pytorch net(torch.nn.Module type)
zhuyijie @2019.5.19
'''
k=0
for name, param in net.named_parameters():
if param.requires_grad:
... |
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
# support custom user models in django 1.7+
# https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#substituting-... |
import os
import tarfile
import pytest
# Workaround for no os.path.commonpath in py27 or py3 < 3.5
def commonpath(l):
prefix = os.path.commonprefix(l)
prefix = prefix if os.path.sep in prefix else prefix + os.path.sep
return os.path.split(prefix)[0]
HERE = os.path.dirname(__file__)
DATA = os.path.join(H... |
# Copyright 2014-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions ... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RVipor(RPackage):
"""Plot Categorical Data Using Quasirandom Noise and Density Estimates""... |
from migen.fhdl.std import *
from migen.flow.actor import *
from migen.actorlib.fifo import AsyncFIFO
from mimisc.actors.plumbing import Relax
from ezusbfifo.actor import USBActor
class AsyncUSBActor(Module):
def __init__(self, fx2_fifo, width=16, pktend_delay=15, fifo_depth=16):
self.submodules.usb_actor... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.common.except... |
class A():
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print (self.x + ' ' + foo)
a = A()
print(a.method_a('may'))
|
from __future__ import division, print_function
# LIBTBX_SET_DISPATCHER_NAME phenix.omegalyze
# LIBTBX_SET_DISPATCHER_NAME molprobity.omegalyze
###
###import sys
###from mmtbx.validation import omegalyze
###
###if __name__ == "__main__":
### omegalyze.run(sys.argv[1:])
import sys
from iotbx.cli_parser import CCTBXPa... |
# -*- coding: UTF-8 -*-
# ------------------------(max to 80 columns)-----------------------------------
# author by : (学员ID)
# created: 2019.11
# Description:
# 初步学习 WinForm 编程 ( Radio Button )
# ------------------------(max to 80 columns)-----------------------------------
import tkinter as tk
from tkinter impo... |
from .captcha import *
from .email import *
|
import unittest
import tests.settings_mock as settings_mock
from tests.activity.classes_mock import FakeLogger
from workflow.workflow_PubRouterDeposit import workflow_PubRouterDeposit
class TestWorkflowPubRouterDeposit(unittest.TestCase):
def setUp(self):
self.workflow = workflow_PubRouterDeposit(
... |
#
# Copyright (c) 2018 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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
#
# h... |
import sys
from datetime import datetime
class TimePromptPS1(object):
def __str__(self):
return "[%s] >>> " % (datetime.now().strftime('%H:%M'))
def __len__(self):
return len(str(self))
class TimePromptPS2(object):
def __str__(self):
width = len(sys.ps1)
return "... ".... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2019 Jan-Philip Gehrcke. See LICENSE file for details.
from __future__ import unicode_literals
import string
from logger import log
class FontManager(object):
def __init__(self):
self.fonts = dict()
# serif
# self.add_font([... |
>>> n = 3 # integer number
>>> address = "221b Baker Street, NW1 6XE, London" # Sherlock Holmes' address
>>> employee = {
... 'age': 45,
... 'role': 'CTO',
... 'SSN': 'AB1234567',
... }
>>> # let's print them
>>> n
3
>>> address
'221b Baker Street, NW1 6XE, London'
>>> employee
{'age': 45, 'role': 'CTO', ... |
import string
# File paths
tweetsFile = "../raw_data/retrieved_tweets.txt"
wordsFile = "../raw_data/abusive_words.txt"
timblTrainFile = "../features/timbl_feature_matrix_train"
timblTestFile = "../features/timbl_feature_matrix_test"
def extract_manual_features(tweet):
'''
Takes a not-yet-processed tweet in t... |
# Copyright 2019 Elasticsearch BV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
for i in range(1,101):
fizz = 'Fizz' if i%3==0 else ''
buzz = 'Buzz' if i%5==0 else ''
print(f'{fizz}{buzz}' or i)
|
# Copyright 2019 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 pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
@pytest.fixture
def driver(request):
wd = webdriver.Chrome()
request.addfinalizer(wd.quit)... |
#
# Copyright 2021 Nebulon, Inc.
# All Rights Reserved.
#
# DISCLAIMER: THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
# EVENT SHALL THE AUTHORS OR COPYRIG... |
"""An implementation of Prioritized Experience Replay (PER).
This implementation is based on the paper "Prioritized Experience Replay"
by Tom Schaul et al. (2015).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .uniform_replay_buffer import *
from... |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.optim.lr_scheduler import StepLR
import numpy as np
import time
from .test import *
def train_step(epoch, train_acc, model, trainloader, optimizer):
device = 'cuda:0' if t... |
from os import path, makedirs
import json
from .log import Logger
METADATA_PATH = './data/meta'
logger = Logger('meta-data')
class MetaData:
def __init__(self, name: str):
self.name: str = name
self.path: str = path.join(METADATA_PATH, f"{name}.json")
self._dataCache = None
if p... |
# coding=utf-8
#
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis-python
#
# Most of this work is copyright (C) 2013-2018 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may ho... |
import json
import pytest
import requests
from sqlalchemy.exc import IntegrityError
import bauble.db as db
from bauble.model import Report
import test.api as api
@pytest.fixture
def setup(organization, session):
setup.organization = session.merge(organization)
setup.user = setup.organization.owners[0]
se... |
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import sys
import os
import numpy as np
import pytest
from mmgroup import MM0, MMV
from mmgroup.mm_crt_space import MMVectorCRT
from mmgroup.tests.test_axes.get_sample_axes import import_sample_axes
from m... |
#清空所有文件夹
import os
def delete_all_file(dir):
for i in os.listdir(dir):
path_file = os.path.join(dir, i)
os.remove(path_file)
dir1 = '/Users/yicc/Desktop/code/可运行版本/fa_detect/get_image/file_test/'
dir2 = '/Users/yicc/Desktop/code/可运行版本/fa_detect/get_image/file_detect/'
dir3 = '/Users/yicc/D... |
"""
Example using sksym to find asymmetry in a step function distribution.
"""
import os
import lightgbm
import numpy
from matplotlib import pyplot
import sksym
RNG = numpy.random.Generator(numpy.random.Philox(0xD1CE))
PREFIX = os.path.basename(__file__)[:-3]
def main():
ndata = 5_000
def filter_(x):
... |
#!/usr/bin/env python
import argparse
import cPickle
import traceback
import logging
import time
import sys
import numpy
import theano
from collections import OrderedDict
import experiments.nmt
from experiments.nmt import\
RNNEncoderDecoder,\
prototype_phrase_state,\
parse_input
from experiments.nmt.num... |
from functools import wraps
from ploceidae.constants import BINDINGS
from ploceidae.dependency_management.dependency_resolution_methods import DependencyResolutionMethods
class DependencyWrapperHelperMethods(object):
@classmethod
def input_validation_for_dependency_object(cls, decorated_object):
cls.... |
# Generated by h2py from /usr/include/sys/stropts.h
# Included from sys/feature_tests.h
_POSIX_C_SOURCE = 1
_LARGEFILE64_SOURCE = 1
_LARGEFILE_SOURCE = 1
_FILE_OFFSET_BITS = 32
_XOPEN_VERSION = 4
_XOPEN_VERSION = 3
# Included from sys/types.h
# Included from sys/isa_defs.h
_CHAR_ALIGNMENT = 1
_SHORT_ALIGNMENT = 2
_I... |
#!/usr/bin/env python
"""
Sms2Mqtt script called by smsd(smstools) when a sms is send or received
Usage:
sms2mqtt <action> <filename> [<messageid>]
"""
import logging
import logging.handlers
import json
import sys
from docopt import docopt
import paho.mqtt.client as mqttw
logger = None
def mqttpublish( number... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('plea', '0014_auto_20151119_1136'),
]
operations = [
migrations.CreateModel(
name='DataValidation',
f... |
LOSS_CLIPPING = 0.2
ENTROPY_LOSS = 1e-3
LR = 0.0003
HIDDEN_SIZE = 128
NUM_LAYERS = 1
NOISE = 0.01
BATCH_SIZE = 200
|
import re
import pytest
from aiohttp import web
async def test_middleware_modifies_response(loop, test_client):
async def handler(request):
return web.Response(body=b'OK')
@web.middleware
async def middleware(request, handler):
resp = await handler(request)
assert 200 == resp.st... |
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
resp_text = f"""<h1>Hello World!</h1>
<p>Client address: {self.client_address}</p>
<p>Command: {self.command}</p>
<p>Path: {self.path}</p>
... |
#!/usr/bin/python
import time
import smbus2
from sensors.i2c import i2cLock
from sensors.auxiliary import SmartSensor
def validate_config(type: str):
"""Checks if all required parameter are available in the passed config dictionary.
:param type: (mandatory, str) type of the light sensor
:return: None
... |
import sys
already_dead = {1: False, 2: False}
# These are just big numbers to keep track of the player stocks
# during melee time mode which doesn't offer stocks
p1_stocks = 9223372036854775807
p2_stocks = 9223372036854775807
# def get_reward(state, prev_state):
def get_stocks(gamestate, player):
return gamest... |
"""
The Parsing package contains classes which can be used to read the proxy file. The proxy file contains information
about the proxies that will be used during de DOS attack. The proxy file is supplied be the user in a supported
format.
This package contains the ProxyExtractor and the Readers sub-pac... |
#!/usr/bin/env python
"""
Created by: Lee Bergstrand (2017)
Description: The step class.
"""
from pygenprop.genome_property import GenomeProperty
class Step(object):
"""A class representing a step that supports the existence of a genome property."""
def __init__(self, number, functional_elements: list=Non... |
"""
This contains all the defined values and types within this compile run.
"""
import itertools
import logging
from . import types
LOGGER = logging.getLogger('spc.symbols')
#
# This module comes out of the realization that namespaces are fundamentally
# global objects.
#
# The compiler doesn't attach symbol tables ... |
from .. import platform
def choose_subset(labels, path, labels_per_column=100):
import ipywidgets as widgets
saved_labels=[]
import os.path
if os.path.isfile(path):
with open(path) as label_file:
saved_labels = [line.rstrip('\n') for line in label_file.readlines()]
label_set = s... |
from django import template
from webpage.metadata import PROJECT_METADATA as PM
register = template.Library()
@register.simple_tag
def projects_metadata(key):
return PM[key]
|
"""Wrapper macro around tsc cli for typechecking"""
load("@npm//typescript:index.bzl", _tsc_test = "tsc_test")
def typecheck_test(name, tsconfig, **kwargs):
"""Wrapper macro around tsc cli for typechecking
Args:
name: name
tsconfig: tsconfig
**kwargs: **kwargs
"""
args = kwarg... |
class Atom:
#This class represents propositional logic variables in modal logic formulas.
def __init__(self, name):
self.name = name
def __eq__(self, other):
return isinstance(other, Atom) and other.name == self.name
def __str__(self):
return str(self.name)
class Im... |
# -*- coding: utf-8 -*-
import pandas as pd
from cartoframes.data import Dataset
from cartoframes.data.dataset.dataset_info import DatasetInfo
from cartoframes.data.dataset.registry.dataframe_dataset import DataFrameDataset
from cartoframes.data.dataset.registry.query_dataset import QueryDataset
from cartoframes.data... |
import abc
class Reactor(metaclass=abc.ABCMeta):
@abc.abstractmethod
def loop(self) -> None:
pass # pragma: no cover
|
import logging
import json
import boto3
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
print('Loading Lambda function')
runtime = boto3.Session().client('sagemaker-runtime')
def lambda_handler(event, context):
endpoint_name = event['endpoint'] if 'endpoint' in event else 'pyto... |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from torch.autograd import Variable
def l2_loss(feat):
return feat.pow(2).sum()/(2.0*feat.si... |
import sys
import get_data
def get_id(args):
assert(len(args) == 4)
dim_length = 4
args = [int(i) for i in args]
idx = 0
for i, v in enumerate(args[::-1]):
idx += v * (dim_length**i)
return idx
# 20-> 000020.SZ
def get_stock_code(idx: int):
return (6-len(str(idx))) * '0' + str(idx... |
from __future__ import print_function
from os import pardir
from os.path import abspath, basename, dirname, join
from optparse import make_option
from django.template import Context, Template
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
option... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
plt.style.use('seaborn')
def well_track(plot_logs, depth, zmin, zmax, zones, zone_colors=[], tracks={}, figsize=(20,10)):
"""
Display a one-well log section defined with a 2-level dict
Parameters:
plot_logs ... |
##########################################################################
# NSAp - Copyright (C) CEA, 2013
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########... |
class Solution(object):
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
intersection = set(list1) & set(list2)
dict1 = {val: i + 1 for i, val in enumerate(list1) if val in intersection}
d... |
#!/usr/bin/python3
"""Send an OSC message to capinibal"""
# see http://das.nasophon.de/pyliblo/examples.html
import liblo, sys, argparse
import pandas as pd
import time
parser = argparse.ArgumentParser(description='Send an OSC message to capinibal.')
parser.add_argument('--host', help='IP Address', default='127.0... |
#Required imports
import os
import firebase_admin
from flask import redirect,Flask,render_template, request, session, url_for, make_response
import firebase_admin
from firebase_admin import db
import urllib.request
from PIL import Image
import img2pdf
# import pyrebase
#Initialize Flask app
app = Flask(__name__)
app.se... |
from nilearn.maskers.nifti_maps_masker import * # noqa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.