text stringlengths 3 1.05M |
|---|
"use strict";
// Test these APIs as published in extension module 'fs-ext'
// fs.seek(fd, offset, whence, [callback])
//
// Asynchronous lseek(2).
//
// callback will be given two arguments (err, currFilePos).
//
// whence can be 0 (SEEK_SET) to set the new position in bytes to offset,
// 1 (SEEK_CUR) to set t... |
"""
Image grid saver, based on color_grid_vis from github.com/Newmu
and https://github.com/igul222/improved_wgan_training/blob/master/tflib/save_images.py
"""
import numpy as np
import scipy.misc
from scipy.misc import imsave
def save_images(X, save_path, n_rows=None, n_cols=None):
# [0, 1] -> [0,255]
#if isi... |
from typing import Any, List
from moa.models import TSettings
class Message:
class Meta:
abstract = True
def __init__(self, settings: TSettings, data: Any) -> None:
self.message_parts: List[str] = []
self.settings = settings
self.data = data
self.type = 'Message'
... |
#!/usr/bin/python2
# coding: utf-8
from clint.textui import progress
import requests
import json
import sys
def download(mp3_url, title):
filename = "%s.mp3" %(title)
print( "{*} Saving file to %s" %(filename))
try:
r = requests.get(url=mp3_url, stream=True)
with open(filename, 'wb') as f:
... |
#!/usr/bin/env python
import sys,os,time,re,datetime,smtplib
#########user section#########################
#user specific constants
username = "smith" #your cluster login name (use what shows up in qstatall)
useremail = "smith@biac.duke.edu" #email to send job notices to
template_f = file("extract_ROI... |
# Copyright (c) 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. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
from torch.nn.modules.loss import ... |
# -*- coding: utf-8 -*-
#
# IoC documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 29 01:43:00 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All con... |
import external from './../../externalModules.js';
import BaseAnnotationTool from '../base/BaseAnnotationTool.js';
// State
import { getToolState } from './../../stateManagement/toolState.js';
import toolStyle from './../../stateManagement/toolStyle.js';
import toolColors from './../../stateManagement/toolColors.js';
/... |
import GalleryDriver from '../drivers/reactDriver';
import { expect } from 'chai';
import { mergeNestedObjects } from 'pro-gallery-lib';
import { images2 } from '../drivers/mocks/items';
import { options, container } from '../drivers/mocks/styles';
import { getElementDimensions } from '../utils/utils';
describe('optio... |
import React, { useContext, useState } from "react";
import Avatar from "react-avatar";
import Button from "../../../../components/Button";
import Input from "../../../../components/Input";
import Colors from "../../../../config/colors";
import UserContext from "../../../../contexts/UserContext";
import UserService fro... |
#!/usr/bin/env python
#
# Copyright 2015 clowwindy
#
# 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 ... |
import { Plot } from '../../core/plot';
import { deepAssign } from '../../utils';
/**
* 默认配置项
*/
export var DEFAULT_OPTIONS = deepAssign({}, Plot.getDefaultOptions(), {
// @ts-ignore
columnStyle: {
stroke: '#FFFFFF',
},
tooltip: {
shared: true,
showMarkers: false,
},
in... |
const express = require('express');
const app = express();
const {Client} = require('pg');
const bodyParser = require('body-parser');
const cookieParser = require("cookie-parser");
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended:false}));
var nodemailer = require('nodemailer');
var smtpTransport=requir... |
/* eslint-disable */
import Vue from 'vue';
import Vuex from 'vuex';
import { stat } from 'fs';
import constants from './constants';
Vue.use(Vuex);
const initialState = {
deck: constants.EASY_CARDS,
pairs: constants.EASY_CARDS.length,
gameReady: false,
difficulty: 'easy',
cards: [],
playerTurn: 1,
sel... |
#!/usr/bin/evn python
import numpy as np
import scipy.linalg
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
# some 3-dim points
mean = np.array([0.0,0.0,0.0])
cov = np.array([[1.0,-0.5,0.8], [-0.5,1.1,0.0], [0.8,0.0,1.0]])
data = np.random.multivariate_normal(mean, cov, 50)
print(data)
# reg... |
//====================================================================================================================================================
// Copyright 2022 Lake Orion Robotics FIRST Team 302
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associ... |
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Ha Thach for Adafruit Industries
*
* 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 without restriction, including without limitation t... |
"""
pipenv run python -m unittest tests.integration.test_authorize
"""
from .constants import _
import unittest
from chalice.config import Config
from chalice.local import LocalGateway
import json
from app import app
from tests.integration.baseTestCase import BaseTestCase
class FormAdmin(BaseTestCase):
def test_a... |
/**
* Theme: Uplon Admin Template
* Author: Coderthemes
* Email: coderthemes@gmail.com
* Form Advanced
*/
$(document).ready(function () {
//advance multiselect start
$('#my_multi_select3').multiSelect({
selectableHeader: "<input type='text' class='form-control search-input' autocomplete='off' pla... |
from setuptools import setup, find_packages
import version
with open('README.md') as readme_file:
README = readme_file.read()
# To Build and Upload, Run:
# python3 setup.py sdist bdist_wheel
# twine upload dist/*
setup_args = dict(
name='pip-gui-tools',
version=version.__version__,
description='A to... |
/*
* This header is generated by classdump-dyld 1.5
* on Tuesday, November 10, 2020 at 10:07:02 PM Mountain Standard Time
* Operating System: Version 14.2 (Build 18K57)
* Image Source: /System/Library/PrivateFrameworks/CommonUti... |
import os
import toml
import yaml
from glob import glob
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
supported_families = [
"STM32F0",
'STM32F4',
'STM32G0',
... |
from httpx import Client
from datetime import datetime
from json import loads, dumps
from base64 import b64decode
from hashlib import sha1
from math import floor
from urllib import parse
from httpx_socks import SyncProxyTransport
from random import choice
OO0, O0O = open("proxies.txt", encoding='utf-8').readlines(), {... |
"""Sensor for Last.fm account status."""
import logging
import re
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_API_KEY, ATTR_ATTRIBUTION
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
RE... |
from . import default, alternative
SUPPORTED_SCHEMAS = {
# default
'beacon-info-v2.0.0-draft.2': default.beacon_info_v20,
'beacon-dataset-v2.0.0-draft.2': default.beacon_dataset_info_v20,
'beacon-variant-v2.0.0-draft.2': default.beacon_variant_v20,
'beacon-variant-annotation-v2.0.0-draft.2': defaul... |
# Copyright (c) 2016 Ofek Lev
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import requests
from core.meta import Unspent
DEFAULT_TIMEOUT = 50
def set_service_timeout(seconds):
global DEFAULT_TIMEOUT
DEFAULT_TIMEOUT = ... |
# Copyright 2015 OpenStack Foundation
# 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 requ... |
/*
* Kendo UI Web v2012.3.1114 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at
* https://www.kendoui.com/purchase/license-agreement/kendo-ui-web-commercial.aspx
* If you do not own a commercial license, this file shall be governed by the
* G... |
$(document).ready(function() {
var imgCounter = 0;
var audioCounter = 0;
var createDiv = function (x, y) {
var newDiv = $('<div>');
var newImg = $('<img>');
var imgNumArray = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15'];
var audioNumArray = ['01', '02... |
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, previousHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash();
}
calculateHash()... |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, find } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | each of', function(hooks) {
setupRenderingTest(hooks);
test('it is tagless', async function(as... |
import pandas as pd
import numpy as np
import pytest
from conftest import DATA_DIR, assert_series_equal
from numpy.testing import assert_allclose
from pvlib import temperature
@pytest.fixture
def sapm_default():
return temperature.TEMPERATURE_MODEL_PARAMETERS['sapm'][
'open_rack_glass_glass']
def test... |
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 ... |
/**
* Copyright 2015 The AMP HTML 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 require... |
#!/usr/bin/env python3
import os
import json
import sys
import pandas as pd
from tqdm import tqdm
def get_input_rev_ids(derived_data_dir):
# read in the sample dataframe
revision_sample_dir = os.path.join(derived_data_dir, 'revision_sample')
sample_filepath = os.path.join(revision_sample_dir, 'sample3_al... |
# This is a "null" plugin showing how to write your own.
# The procedure is as follows:
# 1 - Subclass B2YBank overriding the methods you need - typically just
# read_data(path_to_file). See docstrings below for explanations.
# 2 - provide build_bank(config_dict_bool) which should return an
# instance of yo... |
# -*- coding: utf-8 -*-
from past.builtins import basestring
import furl
from future.moves.urllib.parse import urlunsplit, urlsplit, parse_qs, urlencode
from distutils.version import StrictVersion
from hashids import Hashids
from django.utils.http import urlquote
from django.core.exceptions import ObjectDoesNotExist
f... |
# 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, software
# distributed under the... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import deque
import subprocess
import re
import pandas as pd
import copy, os
import numpy as np
import pickle
from pymatgen.core.structure import Structure
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
# np.seterr(all='raise')
kB = 8.... |
# -*- coding: utf-8 -*-
def guid(*args):
"""
Generates a universally unique ID.
Any arguments only create more randomness.
"""
from time import time
from random import random
import socket
from hashlib import md5
t = long(time() * 1000)
r = long(random()*100000000000000000L)
... |
import numpy as np
import mxnet as mx
from mxnet import nd, gluon
class NumericBlock(gluon.HybridBlock):
""" Single Dense layer that jointly embeds all numeric and one-hot features """
def __init__(self, params, **kwargs):
super(NumericBlock, self).__init__(**kwargs)
with self.name_scope():
... |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.escapeUriPath = void 0;
const escape_uri_1 = require("./escape-uri");
const escapeUriPath = (uri) => uri.split("/").map(escape_uri_1.escapeUri).join("/");
exports.escapeUriPath = escapeUriPath;
//# sourceMappingURL=data:application/jso... |
"""Asset data encoding and decoding utilities."""
from mypy_extensions import TypedDict
import eth_abi
from zero_ex.dev_utils import abi_utils
from zero_ex.dev_utils.type_assertions import assert_is_string, assert_is_int
ERC20_ASSET_DATA_BYTE_LENGTH = 36
ERC721_ASSET_DATA_MINIMUM_BYTE_LENGTH = 53
SELECTOR_LENGTH =... |
/** *************Init JS*********************
TABLE OF CONTENTS
---------------------------
Text Rotator
Notify Me
IE9 Pleaceholder Support
Contact Us Validation and Ajax Call
Bubble Effect
Preloader
Only Play Video on Desktop Devices
** ***************************************/
"use strict";
function miAp... |
#!/usr/bin/env python
import logging
import os
import shutil
import sys
import typing
from builder import exceptions as builder_exceptions
logger = logging.getLogger(__file__)
ENCODING: str = 'utf-8'
NOTEBOOK_DIR: str = os.path.join(os.getcwd(), 'notebooks')
RENDERED_NOTEBOOKS_DIR: str = os.path.join(os.getcwd(), '... |
#!/usr/bin/python
#
# Copyright 2020 Google 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 ag... |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const remix_astwalker_1 = require("@remix-project/remix-astwalker");
const remix_lib_1 = require("@remix-project/remix-lib");
/**
* Decompress the source mapping given by solc-bin.js
* s:l:f:j
*/
/**
* Decode the given @arg value
*
* @pa... |
'''Winny Commands.
See also Isamu Kaneko: The Technology of Winny.
http:/www.amazon.co.jp/exec/obidos/ASIN/4756145485
Command code table (copied from Poeny):
PROTOCOL_HEADER = 0,
SPEED = 1,
CONNECTION_TYPE = 2,
NODE_DETAILS ... |
from collections import deque
n, q = map(int, input().split()) # 頂点数と辺数
# グラフ入力受け取り (ここでは無向グラフを想定)
graph = [[] for _ in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
dist = [-1] * n # 全頂点を -1 (未訪問) に初期化
pos = deque() # キュー... |
/**
* The script is part of konpeito.
*
* AUTHOR:
* natade (http://twitter.com/natadea)
*
* LICENSE:
* The MIT license https://opensource.org/licenses/MIT
*/
import Polyfill from "../../tools/Polyfill.js";
import RoundingMode, {RoundingModeEntity} from "./RoundingMode.js";
/**
* Configuration class for ... |
# -*- coding:utf-8 -*-
"""
request 处理data
"""
import json
from django.shortcuts import HttpResponse
def get_request_data(request):
data = json.loads(request.body)
return data or {}
def get_right_response(raw_data):
if isinstance(raw_data, list):
#如果是 Model item 的 list 则转换
data =[]
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import datetime
import itertools
import socket
import sys
from ..interface import PluginInterface
from ...ctx import context
from ...conf import config
from ...utils.traceback_utils import get_traceback_string
from ...utils.conf_utils import Cmdline, Doc
from slash import config as slash_config
from slash import contex... |
/*
* Copyright 2009-2017 Alibaba Cloud 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... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2014-2020 BigML
#
# 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 requi... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
from setuptools import find_packages, setup
MAIN_REQUIREMENTS = [
"airbyte-cdk",
]
TEST_REQUIREMENTS = ["pytest~=6.1", "source-acceptance-test", "pytest-mock~=3.6", "requests_mock~=1.8"]
setup(
name="source_typeform",
description="Source impl... |
/**
* Copyright 2021 The Pennsylvania State University
* @license Apache-2.0, see License.md for full text.
*/
import { html, css, render, nothing } from "lit";
import { SimpleColors } from "@lrnwebcomponents/simple-colors/simple-colors.js";
import { I18NMixin } from "@lrnwebcomponents/i18n-manager/lib/I18NMixin.js"... |
/**
* Copyright 2016 The AMP HTML 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 require... |
r"""
The torch package contains data structures for multi-dimensional
tensors and defines mathematical operations over these tensors.
Additionally, it provides many utilities for efficient serializing of
Tensors and arbitrary types, and other useful utilities.
It has a CUDA counterpart, that enables you to run your t... |
# Copyright 2013-2021 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)
import os
import sys
from spack import *
class Vtk(CMakePackage):
"""The Visualization Toolkit (VTK) is an open-so... |
sap.ui.define([
"sap/ui/test/opaQunit"
], function (opaTest) {
"use strict";
//List of product ids used
var HT_1254 = "HT-1254", // Bending Screen 21HD
HT_1255 = "HT-1255", // Broad Screen 22HD
HT_1137 = "HT-1137"; // Flat XXL
QUnit.module("Comparison Journey");
//We are still on the second category
opaTe... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: geo/Province.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _... |
/*
* Copyright (с) 2015-present, SoftIndex LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import UIKernel from 'uikernel'
const validator = UIKernel.createValidator()
.field('name', UIKernel.Va... |
import os
from distutils.util import strtobool
from dotenv import load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))
def get_env_variable(name):
try:
return os.environ[name]
except KeyError:
message = f"Expected environment variable {na... |
#!/usr/bin/env python
"""Wrapper script for testing the performance of simple AI systems.
bm_ai.py runs the following little solvers:
- N-Queens
This used to contain an alphametics solver, but that was found to be bound
primarily by eval() performance.
"""
# Wanted by the alphametics solver.
from __future__ imp... |
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <asm/unistd.h>
#include <linux/time_types.h>
#include <poll.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/eventfd.h>
#include "../../kselftest_harness.h"
... |
# Copyright 2013-2020 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 PyWand(PythonPackage):
"""Wand is a ctypes-based simple ImageMagick binding for Python.
... |
"""CACHE DATA SOURCE
Cached local storages with TTL for Stops and Buses
"""
# # Native # #
from typing import Optional
# # Installed # #
from cachetools import TTLCache
# # Project # #
from vigobusapi.settings_handler import settings
from vigobusapi.exceptions import StopNotExist
from vigobusapi.entities import Stop... |
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function(){"use strict";function a(){return od.apply(null,arguments)}
function b(a){od=a}function c(a){return a instanceof Array||"[object Array]"===Object.prototype.... |
/**
* User: Jinqn
* Date: 14-04-08
* Time: 下午16:34
* 上传图片对话框逻辑代码,包括tab: 远程图片/上传图片/在线图片/搜索图片
*/
(function () {
var uploadFile,
onlineFile;
window.onload = function () {
initTabs();
initButtons();
};
function initTabs() {
var tabs = $G('tabhead').children;
... |
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const siteConfig = {
title: "Perspective" /* title for your website */,
tagline: "Streaming Analytics via WebAssembly",
url:... |
//
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <objc/NSObject.h>
#import "IDSSyncAsyncDecrypter-Protocol.h"
#import "IDSSyncEncrypter-Protocol.h"
@class IDSCertifiedDeliveryReplayCommi... |
hours = float(input('Hours: '))
rate = float(input('Rate per hour: '))
pay = hours * rate
print('Weekly earning is ', pay) # 21
|
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
# -*- coding: utf-8 -*-
import tensorflow as tf
# config = tf.ConfigProto()
# config.gpu_options.visible_device_list = "-1"
# # config.gpu_options.per_process_gpu_memory_fraction = 0.4
# config.allow_soft_placement = True
# confi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
import cv2
import numpy as np
from shapely.geometry import *
# Desktop Latin_embed.
vn_dict = [' ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@',
'A','Â','Ă','À'... |
import numpy as np
import os, sys
import subprocess
#results = []
#testdir = os.getcwd()
#for f in os.listdir(testdir):
# if f.endswith('.png') and f not in ["0.png", "1.png", "25.png", "26.png"]:
# results.append(f)
import itertools, sys
l1 = ["6.png", "7.png", "8.png"]
l2 = ["12.png", "14.png", "16.png"... |
Prism.languages.hxml = {
'comment': /#.*/,
'keyword': /-(cp|main|lib|D|v|debug|dce|swf-(version|header|lib|lib-extern)|java-lib|net-lib|net-std|c-arg|resource|prompt|cmd|version|help)/,
'attr-name': /--(next|each|no-traces|gen-hx-classes|display|no-output|times|no-inline|no-opt|php-(front|lib|prefix)|remap|int... |
#!/usr/bin/env python
"""
This code holds the solution for part 2 of day 12 of the Advent of Code for 2015.
"""
try:
import simplejson as json
except:
import json
import sys
def sum_of_items(item):
if isinstance(item, list):
# print "list"
return sum([sum_of_items(i) for i in item])
... |
from sspdatatables.utils.enum import TripleEnum
class BookEnum(TripleEnum):
"""
class to define a mapping
"""
ID = (1, "id", "id")
NAME = (2, "name", "name__icontains")
AUTHOR_NAME = (3, "author__name", "author__name__icontains")
AUTHOR_NATIONALITY = (4, "author__nationality", "author__nat... |
async function deleteOne(selector, deleteOptions) {
try {
const item = await this.connection.tools.deleteOne.call(
this,
selector,
deleteOptions
);
return {
success: true,
error: null,
item,
items: [item],
count: 1
};
} catch (error) {
console.log(error);
return false;
}
}
async ... |
import threading
def lock_class(funcs, lockfactory):
return lambda cls: make_threadsafe(cls, funcs, lockfactory)
def lock_func(func):
if getattr(func, '__is_locked', False):
raise TypeError(f'Method {func!r} is already locked!')
def locked_func(self, *args, **kwargs):
with self._lock:
... |
import argparse
import time
import boto3
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, size, regexp_replace, expr, to_json, struct
def list_s3_by_prefix(bucket, prefix, filter_func=None):
print(f"list_s3_by_prefix bucket: {bucket}, prefix: {prefix}")
s3_bucket = boto3.resource('... |
"""Test cases for variable fields
"""
import unittest
from lighty.templates import Template
from lighty.templates.filter import filter_manager
def simple_filter(value):
return str(value).upper()
filter_manager.register(simple_filter)
def argument_filter(value, arg):
return str(value) + ', ' + str(arg)
filt... |
/**
* Returns a number whose value is limited to the given range.
*
* Example: limit the output of this computation to between 0 and 255
* <pre>
* (x * 255).clamp(0, 255)
* </pre>
*
* @param {Number} min The lower boundary of the output range
* @param {Number} max The upper boundary of the output range
* @ret... |
import os
from sqlalchemy import create_engine, inspect, exc
from contextlib import contextmanager
from .connection import Connection
from pandas import DataFrame
class Database(object):
"""A Database. Encapsulates a url and an SQLAlchemy engine with a pool of
connections.
The url to the database can be p... |
# -*- coding:Utf-8 -*-
#####################################################################
#This file is part of RGPA.
#Foobar is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, ... |
import{r as i,c as t,h as a,g as e,H as o}from"./p-6b8b45ed.js";import{g as c}from"./p-cebd4de5.js";import{d as n,g as r,C as s}from"./p-f1686cee.js";import"./p-a4e6e35b.js";const l=class{constructor(a){i(this,a),this.calciteAccordionChange=t(this,"calciteAccordionChange",7),this.appearance="default",this.iconPosition=... |
a = int(input())
if(a >= 90 and a <= 100):
print('A')
elif(a >= 80 and a < 90):
print('B')
elif(a >= 70 and a < 80):
print('C')
elif(a >= 60 and a < 70):
print('D')
else:
print('F')
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _express = _interopRequireDefault(require("express"));
var _products = require("../controllers/products.controller");
... |
"""Test the dataset tag functionality."""
import pytest
from . import tmp_uuid_and_uri # NOQA
def test_tags_functional(tmp_uuid_and_uri): # NOQA
uuid, dest_uri = tmp_uuid_and_uri
from dtoolcore import ProtoDataSet, generate_admin_metadata
from dtoolcore import DataSet
name = "my_dataset"
ad... |
import argparse
import os
import re
import tarfile
import tempfile
import time
import zipfile
from functools import wraps
from typing import Any, Callable, Dict, List, Optional
import gitlab
TR = Callable[..., Any]
def retry(func: TR) -> TR:
"""
This wrapper will only catch several exception types associate... |
import os
import numpy as np
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
import matplotlib.pyplot as plt
from time import perf_counter
import imageio
from sklearn import metrics
from skimage import morphology as skmorphology
from sklearn.utils import class_weight
import re
fr... |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__CWE839_connect_socket_15.c
Label Definition File: CWE124_Buffer_Underwrite__CWE839.label.xml
Template File: sources-sinks-15.tmpl.c
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: connect_socket Read data using a connect s... |
/**
******************************************************************************
* @file GPIO/GPIO_IOToggle/Inc/stm32f4xx_hal_conf.h
* @author MCD Application Team
* @version V1.2.3
* @date 13-November-2015
* @brief HAL configuration file
********************************************************... |
"""
Given a filename create a dataframe
"""
from pyspark.sql import SQLContext
def filename_to_object(filename, context):
"""
Given a filename create a defoe.books.archive.Archive. If an error
arises during its creation this is caught and returned as a
string.
:param filename: filename
:type... |
import time
import pytest
import pytest_mock
import concurrency_limit
from test_base import *
def test_limit_without_concurrency(mocker: pytest_mock.MockerFixture):
mocker.patch('concurrency_limit.context_managers.get_redis', return_value=RedisMock())
with concurrency_limit.limit(
concurrency_li... |
import numpy as np
import math
import collections
from sklearn.impute import SimpleImputer
import pandas as pd
# fname = "/Users/chek_choi/Downloads/J269830.xlsx" # wealth
# fname = "/Users/chek_choi/Downloads/J269946.xlsx" # income
fname = "/Users/chek_choi/Downloads/J269947.xlsx" # earnings
# get downloaded data
... |
from Queue import Queue
from virtualisation.misc.jsonobject import JSONObject as JOb
import os
from rabbitmq import RabbitMQ
from threading import Timer, Thread, Lock
import argparse
__author__ = 'Marten Fischer'
class Reflector(object):
"""
This programm is only for development purposes. It re-s... |
/*=====================================================================*
| pi_init.c
| Copyright (c) 1988-1994, Applied Logic Systems, Inc.
|
| - Foreign interface initialization
| - a segment of the old pimain.c
| Revision History:
| 11/16/94, C. Houpt -- Added header file with prototype.
*==================... |