content stringlengths 5 1.05M |
|---|
#import theano
#theano.config.device = 'gpu'
#theano.config.floatX = 'float32'
import argparse
import csv
import numpy
from keras import backend as K
from keras.models import Sequential
from keras.layers import Dense
import pandas as pd
from ngram_classifier import NGramClassifier
from sklearn.metrics import precision... |
"""SyncFlow for HttpApi"""
import logging
from typing import Dict, List, TYPE_CHECKING
from samcli.lib.sync.flows.generic_api_sync_flow import GenericApiSyncFlow
from samcli.lib.providers.provider import ResourceIdentifier, Stack
from samcli.lib.providers.exceptions import MissingLocalDefinition
# BuildContext and De... |
def cantor_pairing(x, y):
return int((x + y) * (x + y + 1)/2 + y)
def cantor_pairing_nd(*args):
if len(args) == 2:
return cantor_pairing(args[0], args[1])
return cantor_pairing(cantor_pairing_nd(*args[:-1]), args[-1])
if __name__ == '__main__':
import collections
import matpl... |
import boto3
from botocore.exceptions import ClientError
s3 = boto3.resource('s3')
def get_buckets():
try:
buckets = list(s3.buckets.all())
except ClientError:
print("Couldn't get buckets.")
raise
else:
return buckets
def count_buckets():
count = 0
buckets = [b for... |
import pytest
@pytest.fixture()
def settings():
from pygluu.kubernetes.settings import SettingsHandler, unlink_settings_json
handler = SettingsHandler()
yield handler
unlink_settings_json()
|
#!/usr/bin/python -tt
#=======================================================================
# General Documentation
"""Single-function module.
See function docstring for description.
"""
from __future__ import absolute_import
#-------------------------------------------------------------... |
import sys
import os
import itertools
from qmla.exploration_strategies.nv_centre_spin_characterisation import nv_centre_full_access
import qmla.shared_functionality.probe_set_generation
import qmla.shared_functionality.expectation_value_functions
from qmla import construct_models
class SimulatedNVCentre(
nv_cent... |
# requires python3
import collections
# You are given the following information, but you may prefer to do some research for yourself.
#
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, rain or shine.
... |
from django.urls import path
from .views import (
IssueDetailView,
IssueUpdateView,
IssueDeleteView,
IssueCreateView,
)
urlpatterns = [
path('<int:issue_pk>/', IssueDetailView.as_view(), name="issue-detail"),
path('<int:issue_pk>/update/', IssueUpdateView.as_view(), name='issue-update'),
pa... |
from struct import unpack as struct_unpack
from typing import Any, BinaryIO, Callable, Iterator, Union
def _file_to_stream(file: BinaryIO, chunk_size=512):
while True:
# Read while not EOF
data = file.read(chunk_size)
if not data:
# EOF
break
# Yield eac... |
from model_statistics import ModelStatistics
class StatisticCollector(ModelStatistics):
def __init__(self, token, logger, save_path=None):
super().__init__(token, save_path)
self.logger = logger
def add(self, key, val):
super().add(key, val)
self.logger.info('StatisticCollecto... |
from typing import cast
from ymmsl import Reference
from libmuscle.mcp.client import Client
import libmuscle.mcp.pipe_multiplexer as mux
class PipeClient(Client):
"""A client for pipe-based communication.
"""
@staticmethod
def can_connect_to(location: str) -> bool:
"""Whether this client cla... |
import os
from contextlib import contextmanager
from typing import Generator
from alembic import command # type: ignore
from alembic.config import Config as AlembicConfig # type: ignore
from aiohttp_storage import StorageConfig
@contextmanager
def storage(config: StorageConfig, root: str) -> Generator[None, None,... |
# psdtags/psdtags.py
# Copyright (c) 2022, Christoph Gohlke
# 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... |
import httplib
import time
import json
import sys
import cfscrape
import os.path
import datetime
from model.coeff import Coeff
__author__ = 'mivanov'
class CoeffProvider:
_conn = httplib.HTTPConnection('egb.com')
def process_history(self, dao):
counter = 0
now = datetime.datetime.now()
... |
# -*- coding: utf-8 -*-
"""Test the manager's citation utilities."""
import os
import time
import unittest
from pybel import BELGraph
from pybel.constants import (
CITATION, CITATION_AUTHORS, CITATION_DATE, CITATION_JOURNAL, CITATION_TYPE_PUBMED,
)
from pybel.dsl import Protein
from pybel.manager.citation_utils ... |
#%%
#################
# This script takes as input the FAO country definitions
# and corresponding HuID regions, and returns different
# Earth projections containing the defined regions.
#
# Last updated: Dec 2020
# Author: Ignacio Lopez-Gomez
#
#################
import cartopy.crs as ccrs
import cartopy.feature as ... |
"""Prepares MSCOCO-like dataset for the im2txt model"""
from datetime import datetime
import json
import logging
from pathlib import Path
from random import choices
import re
import shutil
import sys
from typing import Iterable, List, Tuple
import click
from os import path, walk
COCO_SPLIT_PROPORTIONS = {'val': 0.3,... |
import uuid
import pytest
import stix2
from stix2.exceptions import (
AtLeastOnePropertyError, CustomContentError, DictionaryKeyError,
ExtraPropertiesError, ParseError,
)
from stix2.properties import (
DictionaryProperty, EmbeddedObjectProperty, ExtensionsProperty,
HashesProperty, IDProperty, ListProp... |
import copy
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from astromodels import Model, PointSource
from threeML.classicMLE.goodness_of_fit import GoodnessOfFit
from threeML.classicMLE.joint_likelihood import JointLikelihood
from threeML.data_list import DataList
from threeML.plugin_prototyp... |
from rest_framework import serializers
from .models import *
class AcquisitionSerializer(serializers.ModelSerializer):
class Meta:
model = Acquisition
fields = ['id', 'questions1', 'questions3', 'questions4', 'questions5',
'questions6', 'Contact', 'CommentaireQ5', 'CommentaireQ6',... |
""" An abstract class to inherit to tell it's a entry for topology discovery.
Right now, it only acts as a tag and does nothing.
"""
class TopologyEntry:
pass |
"""Confluence reports commands"""
import click
from damster.reports.confluence import ConfluenceChanges
from damster.utils import previous_month_range
import logging
log = logging.getLogger(__name__)
@click.command('changes', short_help='generate changes report')
@click.argument('from-date', required=Fal... |
from cbuild.core import template
import os
def invoke(pkg):
template.call_pkg_hooks(pkg, "init_extract")
template.run_pkg_func(pkg, "init_extract")
extract_done = pkg.statedir / f"{pkg.pkgname}__extract_done"
if extract_done.is_file():
return
template.call_pkg_hooks(pkg, "pre_extract")
... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible # needed to support Python 2
class Battle(models.Model):
battle_name = models.CharField(max_length=100)
hashtag... |
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, filters, status
from rest_framework.decorators import list_route
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from crisiscleanup.calls.api.serializers.gateway import Gat... |
class Solution(object):
def searchInsert(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length=len(nums)
l=0
r=length-1
while l<=r:
if l==r:
return l if nums[l]>=target else l+1
... |
from sympy import Integer as sp_Integer
from sympy import Float as sp_Float
from sympy.core.expr import Expr
from sympy.core.numbers import NegativeOne as sp_NegativeOne
from sympy.logic.boolalg import BooleanTrue as sp_BooleanTrue
from sympy.logic.boolalg import BooleanFalse as sp_BooleanFalse
from .basic ... |
import gc
from tenders.models import *
from project.models import Log
from django.utils import timezone
class Runner:
name = 'Проверка дублей'
alias = 'test-doubles'
def __init__(self):
# Загрузчик
self.updater = Updater.objects.take(
alias = self.alias,
name = self.name)
def run(self):
start ... |
import sys
import cv2 as cv
# defining face detector
face_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_eye.xml')
ds_factor = 0.6
class VideoCamera:
"""
No docs :)
"""
def __init__(... |
import six
import ubelt as ub
def compact_idstr(dict_):
"""
A short unique id string for a dict param config that is semi-interpretable
"""
from netharn import util
import ubelt as ub
short_keys = util.shortest_unique_prefixes(dict_.keys())
short_dict = ub.odict(sorted(zip(short_keys, dict... |
bill = int(input("Enter Total Bill: "))
tip_percentage = 0.20
tax_percentage = 0.067
tip = bill * tip_percentage
print(f"Tip: {tip}")
tax = bill * tax_percentage
print(f"Tax: {tax}")
total = bill + tip + tax
print(f"Total: {total}")
|
import pickle
# escribo en el codigo binario
"""
lista_nombres=["pedro", "ana" , "maria" , "isabel"]
fichero_binario=open("lista_binario", "wb")# write binaria
pickle.dump(lista_nombres, fichero_binario)# info volcar, name fichero a volcar in memory
fichero_binario.close()
del (fichero_binario)# delete of memory ""... |
from mcpi.minecraft import Minecraft
from mcpi.minecraft import ChatEvent
import time
import pycraft
import importlib
import sys
from pycraft import Player
import threading
mc = pycraft.new_minecraft()
def run_in_background(func, mc, player, kwargs):
player.unlock()
# TODO check if the function accepts the correct... |
import fandango as fn
from .api import HDBpp, MIN_FILE_SIZE
from .query import partition_prefixes
from .multi import *
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.urls import reverse
from .models import WasteCategory
from raddi_user.models import User
from .serializers import WasteCategorySerializer
from rest_framework.test import APIClient
from rest_framework import s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from autobahn.twisted.wamp import ApplicationRunner
from autobahn.twisted.wamp import ApplicationSession
from autobahn.twisted.util import sleep
from txzmq import ZmqEndpoint, ZmqFactory, ZmqPullConnection #ZmqPubConnection, ZmqSubConnection
import datetime
import cPickle ... |
import logging
import shrub
from tflite2onnx import getSupportedOperator
shrub.util.formatLogging(logging.DEBUG)
def test_supported_ops():
assert(len(getSupportedOperator()) > 0)
assert(getSupportedOperator(0) == 'ADD')
if __name__ == '__main__':
test_supported_ops()
|
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from xai import constants
def adjust_xtick_labels(ticks_length):
ticks_params = dict()
if ticks_length < 5:
ticks_params['rotation'] = 0
ticks_params['fontsize'] = 20
elif ticks_length < 10:
ticks_params['rotati... |
# Input arguments flag
import sys
sys.path.append('..')
_, *flag = sys.argv
# Parse arguments
import argparse
parser = argparse.ArgumentParser(prog='hs_trajectory', description='Save/plot trajectory TbT data for selected BPMs and plane.')
parser.add_argument('-p', '--plane', choices=('x', 'y', 'i'), help='data plane',... |
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.json import JSONEncoder
from datetime import date, datetime
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://%s:%s@localhost/csa?charset=utf8' % (
os.environ['CSA_DB_USERNAME'], os.environ['CSA_DB... |
import sys
from ttc_py.lexer import *
from ttc_py.emitter import *
class Parser:
def __init__(self, lexer, emitter):
self.lexer = lexer
self.emitter = emitter
self.curtoken = None
self.peektoken = None
self.symbols = set()
self.declared_labels = set()
self.g... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import json
from myuw.test.api import MyuwApiTest, require_url, fdao_mylib_override
@fdao_mylib_override
@require_url('myuw_library_api')
class TestLibrary(MyuwApiTest):
def get_library_response(self):
return self.get... |
from abc import abstractmethod
from typing import Any, Callable, List, Optional, Tuple
import ibis
import ibis.expr.types as ir
from fugue import DataFrame, DataFrames, ExecutionEngine
_ENGINE_FUNC: List[
Tuple[int, int, Callable[[ExecutionEngine, Any], Optional["IbisEngine"]]]
] = []
def register_ibis_engine(
... |
def mutually_exclusive(dice, call1, call2):
|
# Atbash
import sys
import string
mode = sys.argv[1] # -e | -d
txt = sys.argv[2].upper() # String
tmp = ""
# Alphabet
common = list(string.ascii_uppercase)
coded = sorted(string.ascii_uppercase, reverse=True)
# Execution:
if mode == "-e":
for c in txt:
if c in string.ascii_uppercase:
tmp += c... |
import bpy
import multivision as mv
from multivision.luxcore import LuxcoreProjector, init_luxcore
from multivision.common import Camera, delete_all
delete_all()
init_luxcore()
bpy.ops.mesh.primitive_plane_add()
luxcore_proj = LuxcoreProjector(pose=((0,0,3),(0,0,0))) |
""" Managers interactions between Fetching, Parsing, and Storing """
import logging
from src.parse.parse import Parse
from src.scrape.efd import EFD
from src.store.storage import Storage
from src.utility import hash_from_strings
class Controller:
""" Control interaction between Fetching, Parsing, and Storage """... |
#!/usr/bin/env python
import itertools
import pprint
import re
def tryint(s):
return int(s) if s.isdigit() else s
def natural_sort(string):
return [ tryint(c) for c in re.split('(\d+)', string) ]
class Host(object):
def __init__(self, name, ip, eth, switch, vlans):
self.name = name
self.... |
##############################################################################
# Written by: Cachen Chen <cachen@novell.com>
# Date: 10/31/2008
# Description: toolstrip.py wrapper script
# Used by the toolstrip-*.py tests
############################################################################... |
#!/usr/bin/env python
"""
Interface to Wikipedia. Their API is in beta and subject to change.
As a result, this code is also in beta and subject to unexpected brokenness.
http://en.wikipedia.org/w/api.php
http://github.com/j2labs/wikipydia
jd@j2labs.net
"""
import urllib
import json as simplejson
import calendar
i... |
from chainer.functions.connection import deconvolution_nd
from chainer import initializers
from chainer import link
from chainer.utils import conv_nd
from chainer import variable
class DeconvolutionND(link.Link):
"""N-dimensional deconvolution function.
This link wraps :func:`~chainer.functions.deconvolution... |
import os
import cv2
import torch
import torch.utils.data as data
class YCG09DataSet(data.Dataset):
def __init__(self, file_path, train_data=True, transform=None,
data_length=None, label_transform=None, start_index=0, split_char=' '):
super(YCG09DataSet, self).__init__()
self.img... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import random
BOARD_SIZE = 7 # how many pegs on the bottom-most row of the board
VIDEO_LENGTH = 10 # desired video length in seconds
FPS = 30 # frames per second for the video
diff = 0
def get_ball_bucket():
#... |
"""This module provides a high level interface for layer augmentation."""
import logging
from keras.models import clone_model
from condense.keras import wrappers
from condense.keras import support
from condense.optimizer import sparsity_functions
from copy import deepcopy
def wrap_model(model, sparsity_fn):
"""Th... |
"""
Generation of intrinsic information from dynamically executed instances
A kind of fuzzing, maybe
"""
import builtins
import sys
import operator
import functools
import tqdm
import typhon.core.type_system.type_repr as type_repr
from typhon.core.type_system.intrinsics import intrinsic_function
skip_types = {
# ... |
from . import ConditionType
from agentml.errors import VarNotDefinedError
class UserVarType(ConditionType):
"""
User Variable condition type
"""
def __init__(self):
"""
Initialize a new User Var Type instance
"""
super(UserVarType, self).__init__('user_var')
def ge... |
from collections import deque
from math import ceil
from types import SimpleNamespace
import cv2
import numpy as np
from face_recognition.detector import FaceDetectorModel
class ConfirmationWindowHandler:
def __init__(self):
self.cw = dict()
def add(self, key, value):
cw = self.get(key)
... |
from setuptools import find_packages, setup
import os
import sys
from distutils.sysconfig import get_python_lib
from setuptools import setup
CURRENT_PYTHON = sys.version_info[:2]
REQUIRED_PYTHON = (3, 8)
# This check and everything above must remain compatible with Python 2.7.
if CURRENT_PYTHON < REQUIRED_PYTHON:
... |
from layer import *
class Model:
def __init__(self, x, mosaic, mask, local_x, global_completion, local_completion, is_training, batch_size):
self.batch_size = batch_size
self.merged = x * (1 - mask) + mosaic * (mask)
self.imitation = self.generator(self.merged, is_training)
self.com... |
import factory
import factory.fuzzy
from blog.models import Post
from django.utils import timezone
from factory.django import DjangoModelFactory
from i18n.tests.factories import LanguageFactory
from pytest_factoryboy import register
from users.tests.factories import UserFactory
@register
class PostFactory(DjangoModel... |
"""
15096. Batter Up
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 68 ms
해결 날짜: 2020년 9월 25일
"""
def main():
input()
bats = map(int, input().split())
res = list(filter(lambda x: x != -1, bats))
print(sum(res) / len(res))
if __name__ == '__main__':
main() |
for i in range(7):
if i == 5:
break
print i
for i in range(8):
if i%2 == 0:
continue
print i
for i in range(10):
if i*i > 50:
break
elif i%3 == 0:
continue
else:
print i*i
|
import torch
import torch.testing as testing
import pytest
from spherical_distortion.nn import Unresample, InterpolationType
import utils
import parameters as params
bs = 3
channels = 3
kernel_size = 4
def test_unresample_nearest_integer_sampling_cpu():
# Basic Unresample layer
layer = Unresample(Interpo... |
from datetime import datetime
from typing import NamedTuple, Dict, Optional
from ppe import models
from ppe.data_mapping.types import ImportedRow, repr_no_raw, DataFile
from ppe.data_mapping.utils import (
parse_date,
asset_name_to_item,
ErrorCollector,
parse_int_or_zero)
from ppe.dataclasses import Or... |
from django.conf import settings
from django.core.cache import cache
from django.db.models.base import ModelBase
from django.db.models.signals import post_save
from django.dispatch import Signal
from django.utils import six
class RohypnolRegister(object):
def __init__(self):
# The _registry is a dictiona... |
"""
Player package.
Contains radio player methods.
"""
from player import Player
|
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
options = n // 2
sum = 0
for i in range(options+1):
sum += self.combinationfunc(i,n-i)
return sum
def combinationfunc(self,i,k):
return self.factorials(k) / (self.fac... |
# Generated by Django 3.2.8 on 2021-10-18 01:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ProfissionalEnc', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='profissionalenc',
options={'verbose_... |
from ...ut.bunch import bunchr, bunchset, bunchdel
from ..base import Mod
from ..mixins import (
ViewMixin,
NoEmptyQueryMixin,
make_blueprint_mixin,
IdentityGuessNameMixin,
make_field_guess_name_mixin
)
name = 'pixiv'
class Pixiv(
ViewMixin,
NoEmptyQueryMixin,
make_blueprint_mixin(__... |
from __future__ import print_function
# author - Richard Liao
# Dec 26 2016
import numpy as np
import pandas as pd
import pickle
from collections import defaultdict
import re
from bs4 import BeautifulSoup
import sys
import os
os.environ['KERAS_BACKEND']='tensorflow'
from keras.preprocessing.text import Tokenizer, ... |
import os
import smtplib # This module is defines an SMTP client session object that can be used to send mail
import imghdr #This module determines the type of image contained in a file
from email.message import EmailMessage
#Grab the credentials from Environment Variables locally stored on your system
Email_id = os... |
import Foundation
from PyObjCTools.TestSupport import TestCase, min_os_level
class TestNSURLCache(TestCase):
def testConstants(self):
self.assertEqual(Foundation.NSURLCacheStorageAllowed, 0)
self.assertEqual(Foundation.NSURLCacheStorageAllowedInMemoryOnly, 1)
self.assertEqual(Foundation.NS... |
"""
Functions for working with iRefIndex in terms of NetworkX graphs (instead of graph_tool)
"""
import numpy as np # for np.Inf TODO alternative?
import networkx as nx
import itertools
from .irefindex_parser import *
def get_ppi(fh, n_rows=None, hgnc=False):
"""Parse ppi network from irefindex
Parameters
----... |
import json
import re
from datetime import datetime, timedelta
def bytes2json(bytes_in):
return json.loads(bytes_in.decode('utf-8'))
def clean_js_timestamp(raw_js_datestring=None):
# test_string = '/Date(1431113400000-0700)/'
date_pattern = 'Date\((\d*)(\d{3})([-+]\d{2})00\)'
matches = re.search(date... |
from django.db import models
from django.db.models.signals import pre_save, post_save
from .utils import unique_slug_generator
from django.utils.dateformat import DateFormat, TimeFormat
from estatisticas_facebook.util.graph import *
def getPageInfo(page):
raw_json = getNewGraphApi(page.name).get_object(page.name)
... |
"""
Jacobian of a general hyperelliptic curve
"""
# ****************************************************************************
# Copyright (C) 2006 David Kohel <kohel@maths.usyd.edu>
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
# ************... |
import multiprocessing
import queue
from queue import Queue
import sys
from spats_shape_seq.pair import Pair
from spats_shape_seq.parse import FastqWriter, SamWriter
from spats_shape_seq.util import _debug, _warn
from spats_shape_seq.mask import PLUS_PLACEHOLDER, MINUS_PLACEHOLDER
class SpatsWorker(object):
'''... |
import os, grpc, codecs, requests
import lnt.rpc.rpc_pb2 as ln, lnt.rpc.rpc_pb2_grpc as lnrpc
def create_stub(ctx):
cfg = ctx.parent.parent.config['LND']
macaroon = codecs.encode(open(cfg['MacaroonPath'], 'rb').read(), 'hex')
os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
cert = open(cfg['TlsCert'... |
def test():
raise '\xf1'.encode('ASCII')
yield
|
"""
Defines some tools to handle events.
In particular :
-> defines events' types
-> defines functions to read events from binary .dat files using numpy
-> defines functions to write events to binary .dat files using numpy
Copyright: (c) 2019-2020 Prophesee
"""
from __future__ import print_function
import... |
from unittest import TestCase
from moceansdk.modules.command.content_builder.wa_sticker_content_builder import (
WaStickerConentBuilder,
)
class TestWaStickerContentBuilder(TestCase):
def test_type(self):
self.assertEqual(WaStickerConentBuilder().type(), "sticker")
def test_request_data(self):
... |
from typing import Dict
import pandas as pd
from gradetools.config import PYTHON_ALWAYS_INSERT_CONFIGS
from gradetools.excel.io import get_inputs_outputs_sheet_from_file_path, get_output_dict_from_output_range_dict
from gradetools.model_type import ModelType
from gradetools.project_3.config import EXCEL_OUTPUT_LOCATI... |
from hask3.lang.syntax import sig
from hask3.lang.syntax import H
from hask3.lang.syntax import t
from hask3.lang.syntax import instance
from hask3.lang import List
from hask3.Data.Functor import fmap
from hask3.Control.Applicative import Applicative
class Monad(Applicative):
"""Basic operations over a monad.
... |
#!/usr/bin/env python
#
# generatePathFromObj.py
# Core3D
#
# Created by Julian Mayer on 16.12.07.
# Copyright (c) 2010 A. Julian Mayer
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software witho... |
import dataclasses
from typing import Optional
from esque.io.data_types import NoData, UnknownDataType
from esque.io.messages import Data
from esque.io.serializers.base import DataSerializer, SerializerConfig
@dataclasses.dataclass(frozen=True)
class RawSerializerConfig(SerializerConfig):
pass
class RawSeriali... |
"""URLs for rendering app"""
from django.conf.urls import url
from rendering import views
# pylint: disable=invalid-name
urlpatterns = [
url(r'^preview/email/$',
views.EmailPreviewView.as_view(),
name='preview_email'),
url(r'^preview/block/$',
views.BlockPreviewView.as_view(),
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Code2Vec(nn.Module):
def __init__(self, nodes_dim, paths_dim, embedding_dim, output_dim, dropout):
super().__init__()
self.node_embedding = nn.Embedding(nodes_dim, embedding_dim)
self.path_embedding =... |
import torch
def linear(x, weight, bias=None):
out = torch.bmm(x, weight.transpose(-2, -1))
if bias is not None:
out = out + bias.unsqueeze(-2)
return out
|
import opentuner
from opentuner import ConfigurationManipulator
from opentuner import LogIntegerParameter
from opentuner import EnumParameter
from opentuner import MeasurementInterface
from opentuner import Result
FILE = '../programs/server/server2.py'
INTERPRETER = '../../../python3/bin/python3.7'
MODULO_THRESHOLD = ... |
import FWCore.ParameterSet.Config as cms
hiFJGridEmptyAreaCalculator = cms.EDProducer('HiFJGridEmptyAreaCalculator',
gridWidth = cms.double(0.05),
bandWidth = cms.double(0.2),
mapEtaEd... |
# Read from a file one line at a time.
# amwhaley@cisco.com
# twitter: @mandywhaley
# http://developer.cisco.com
# http://developer.cisco.com/learning
# Jan 15, 2015
# * THIS SAMPLE APPLICATION AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
# * OF ANY KIND BY CISCO, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT... |
from veripy.parser import syntax
from veripy.typecheck.types import to_ast_type
ArithOps = syntax.ArithOps
CompOps = syntax.CompOps
BoolOps = syntax.BoolOps
BINOP_DICT = {
'+' : ArithOps.Add,
'-' : ArithOps.Minus,
'*' : ArithOps.Mult,
'//': ArithOps.IntDiv,
'%' : ArithOps.Mod,
'... |
with open("hfs_superdrive", "rb") as f:
buf = f.read()
with open("superdrive", "wb") as f:
f.write(buf[0x400:])
|
# -*- coding: utf-8 -*-
"""
Wraps a connection to koji, managing the session, and providing convenience
methods for interacting with the koji api.
"""
import os
import koji
from koji_wrapper.base import KojiWrapperBase
class KojiWrapper(KojiWrapperBase):
def __init__(self, **kwargs):
self._pathinfo = ... |
from .registry import DeviceRegistry, DeviceEntry, MediaDeviceType, MediaDeviceDiscoveryEvent
from .events import DiscoveryEventType
__all__ = ['DeviceRegistry', 'DiscoveryEventType', 'DeviceEntry', 'MediaDeviceType', 'MediaDeviceDiscoveryEvent']
|
class JobResultExample(object):
IN_PROGRESS = {
"status": {
"state": "IN PROGRESS"
},
"configuration": {
"copy": {
"sourceTable": {
"projectId": "source_project_id",
"tableId": "source_table_id$123",
... |
from app import app, database
from util import random_string
from flask import request
from hashlib import sha1
import arrow
import json
@app.route('/api/v1/paste', methods=('POST',))
def paste():
paste = None
language = None
user = None
expiration = None
domain = 'https://zifb.in/'
try:
... |
from django.shortcuts import render,redirect
from .models import Cart
# Create your views here.
from products.models import Product
def cart_home(request):
cart_obj,new_obj = Cart.objects.new_or_get(request)
args = { "cart": cart_obj }
return render(request,"carts/cart_home.html",args)
def cart_update(request):
... |
# ov -> one variable
from .differentiable_function import DifferentiableFunction, T
from .constant import Constant
from .linear import Linear
from .trigonometry import Sin, Cos, sin, cos
from .exp import Exp, exp
from .log import Log, log
from .pow import Pow
__all__ = [
"cos",
"exp",
"log",
"sin",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.