identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/yasinahmed81/Crypto/blob/master/CryptoTests/NetworkServiceTests.swift
|
Github Open Source
|
Open Source
|
MIT
| null |
Crypto
|
yasinahmed81
|
Swift
|
Code
| 400
| 1,229
|
//
// NetworkServiceTests.swift
// CryptoTests
//
// Created by Yasin Ahmed on 08/02/2021.
//
import XCTest
@testable import Crypto
final class NetworkServiceTests: XCTestCase {
var mockURLSession: MockURLSession!
var networkService: Resourcable!
override func setUp() {
super.setUp()
mockURLSession = MockURLSession()
networkService = NetworkService(session: mockURLSession, shouldExecuteCallbackOnMainThread: false)
}
override func tearDown() {
mockURLSession = nil
networkService = nil
super.tearDown()
}
func test_networkService_decodingModelParsesSuccessfully() {
mockURLSession.makeCoinsData()
mockURLSession.makeExpectedResponse()
networkService.request(Request.cryptoCurrencies, decodingModel: CurrenciesDataContainer.self) { result in
switch result {
case .success(let container):
let coins = container.data.coins
XCTAssertEqual(coins[0].name, "Bitcoin")
XCTAssertEqual(coins[1].iconUrl, "https://cdn.coinranking.com/rk4RKHOuW/eth.svg")
XCTAssertEqual(coins[2].symbol, "USDT")
XCTAssertEqual(coins[3].price, "16.79335847")
case .failure:
XCTFail("The test should hit the success case above.")
}
}
}
func test_networkService_didReceiveURLError() {
mockURLSession.makeError()
networkService.request(Request.cryptoCurrencies, decodingModel: CurrenciesDataContainer.self) { result in
switch result {
case .success:
XCTFail("The test should hit the failure case below.")
case .failure(let error):
if case .urlError = error {
XCTAssertEqual(error.description, "There was an error in the network request.\nReason: The operation couldn’t be completed. (NSURLErrorDomain error -1009.)")
} else {
XCTFail("The error should be a urlError.")
}
}
}
}
func test_networkService_didReceiveNoResponseError() {
networkService.request(Request.cryptoCurrencies, decodingModel: CurrenciesDataContainer.self) { result in
switch result {
case .success:
XCTFail("The test should hit the failure case below.")
case .failure(let error):
if case .noResponseReceived = error {
XCTAssertEqual(error.description, "There was no response received from the network request.")
} else {
XCTFail("The error should be noResponseReceived.")
}
}
}
}
func test_networkService_didReceiveNoDataError() {
mockURLSession.makeExpectedResponse()
networkService.request(Request.cryptoCurrencies, decodingModel: CurrenciesDataContainer.self) { result in
switch result {
case .success:
XCTFail("The test should hit the failure case below.")
case .failure(let error):
if case .noDataReceived = error {
XCTAssertEqual(error.description, "There was no data received from the network request.")
} else {
XCTFail("The error should be noDataReceived.")
}
}
}
}
func test_networkService_didReceiveDecodingError() {
mockURLSession.makeCorruptData()
mockURLSession.makeExpectedResponse()
networkService.request(Request.cryptoCurrencies, decodingModel: CurrenciesDataContainer.self) { result in
switch result {
case .success:
XCTFail("The test should hit the failure case below.")
case .failure(let error):
if case .decodingFailure = error {
XCTAssertEqual(error.description, "The data received from the network request could not be decoded.\nReason: The data couldn’t be read because it isn’t in the correct format.")
} else {
XCTFail("The error should be a decodingFailure.")
}
}
}
}
func test_networkService_didReceiveUnexpectedError() {
mockURLSession.makeCoinsData()
mockURLSession.makeUnexpectedResponse()
networkService.request(Request.cryptoCurrencies, decodingModel: CurrenciesDataContainer.self) { result in
switch result {
case .success:
XCTFail("The test should hit the failure case below.")
case .failure(let error):
if case .unexpectedResponse = error {
XCTAssertEqual(error.description, "There was an unexpected response from the network request.\nReason: HTTP status code was 404.")
} else {
XCTFail("The error should be an unexpectedResponse.")
}
}
}
}
}
| 48,014
|
https://github.com/NCIP/stats-application-commons/blob/master/src/gov/nih/nci/caintegrator/security/genepattern/EncryptionUtil.java
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, BSD-3-Clause
| 2,014
|
stats-application-commons
|
NCIP
|
Java
|
Code
| 312
| 1,105
|
/*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/stats-application-commons/LICENSE.txt for details.
*/
package gov.nih.nci.caintegrator.security.genepattern;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class EncryptionUtil
{
static final byte[] salt = { -87, -101, -56,
50, 86, 53, -29, 3 };
static final int iterationCount = 19;
static final DesEncrypter encrypter = new DesEncrypter("My Really Long Key");
public static String encrypt(String message)
{
return encrypter.encrypt(message);
}
public static String decrypt(String message)
{
return encrypter.decrypt(message);
}
public static void main(String[] args) {
String[] toEncrypt = { "RBTuser", "harrismic", "guruswamis", "liuh", "sahnih", "tester", "newuser" };
for (String s : toEncrypt) {
String e = encrypt(s + ":GP30:RBT");
System.out.println("The secret message " + s + " encrypted:" + e);
try {
System.out.println("URL encoded message:" + URLEncoder.encode(e, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
System.out.println("The secret message decoded:" + decrypt(e));
}
}
private static class DesEncrypter
{
Cipher ecipher;
Cipher dcipher;
DesEncrypter(String passPhrase)
{
try
{
PBEKeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(),
EncryptionUtil.salt, 19);
SecretKey key =
SecretKeyFactory.getInstance("PBEWithMD5AndDES")
.generateSecret(keySpec);
this.ecipher = Cipher.getInstance(key.getAlgorithm());
this.dcipher = Cipher.getInstance(key.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(EncryptionUtil.salt,
19);
this.ecipher.init(1, key, paramSpec);
this.dcipher.init(2, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException keySpec) {
} catch (java.security.spec.InvalidKeySpecException keySpec) {
} catch (javax.crypto.NoSuchPaddingException keySpec) {
} catch (java.security.NoSuchAlgorithmException keySpec) {
}
catch (java.security.InvalidKeyException keySpec) {
}
}
public String encrypt(String str) {
try {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = this.ecipher.doFinal(utf8);
return new BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException utf8) {
} catch (javax.crypto.IllegalBlockSizeException utf8) {
} catch (UnsupportedEncodingException utf8) {
}
return null;
}
public String decrypt(String str)
{
try {
byte[] dec = new BASE64Decoder().decodeBuffer(str);
byte[] utf8 = this.dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException dec) {
} catch (javax.crypto.IllegalBlockSizeException dec) {
} catch (UnsupportedEncodingException dec) {
} catch (java.io.IOException dec) {
}
return null;
}
}
}
| 23,504
|
https://github.com/facebookresearch/theseus/blob/master/tests/theseus_tests/optimizer/autograd/test_sparse_backward.py
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
theseus
|
facebookresearch
|
Python
|
Code
| 228
| 833
|
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import pytest # noqa: F401
import torch
from sksparse.cholmod import analyze_AAt
from torch.autograd import gradcheck
import theseus as th
from theseus.optimizer.autograd import CholmodSolveFunction
def _build_sparse_mat(batch_size):
torch.manual_seed(37)
all_cols = list(range(10))
col_ind = []
row_ptr = [0]
for i in range(12):
start = max(0, i - 2)
end = min(i + 1, 10)
col_ind += all_cols[start:end]
row_ptr.append(len(col_ind))
data = torch.randn(size=(batch_size, len(col_ind)), dtype=torch.double)
return 12, 10, data, col_ind, row_ptr
def test_sparse_backward_step():
void_objective = th.Objective()
void_ordering = th.VariableOrdering(void_objective, default_order=False)
solver = th.CholmodSparseSolver(
void_objective, linearization_kwargs={"ordering": void_ordering}, damping=0.01
)
linearization = solver.linearization
batch_size = 4
void_objective._batch_size = batch_size
num_rows, num_cols, data, col_ind, row_ptr = _build_sparse_mat(batch_size)
linearization.num_rows = num_rows
linearization.num_cols = num_cols
linearization.A_val = data
linearization.A_col_ind = col_ind
linearization.A_row_ptr = row_ptr
linearization.b = torch.randn(size=(batch_size, num_rows), dtype=torch.double)
linearization.A_val.requires_grad = True
linearization.b.requires_grad = True
# Only need this line for the test since the objective is a mock
solver._symbolic_cholesky_decomposition = analyze_AAt(
linearization.structure().mock_csc_transpose()
)
inputs = (
linearization.A_val,
linearization.b,
linearization.structure(),
solver._symbolic_cholesky_decomposition,
solver._damping,
)
assert gradcheck(CholmodSolveFunction.apply, inputs, eps=3e-4, atol=1e-3)
def test_float64_used():
data = torch.load("tests/theseus_tests/optimizer/autograd/bad_sparse_matrix.pth")
decomp = analyze_AAt(data["struct"].mock_csc_transpose())
delta = CholmodSolveFunction.apply(
data["a"],
data["b"],
data["struct"],
decomp,
1e-06,
)
# With this matrix, if CHOLMOD is not casted to 64-bits, this value is > 100.0
assert delta.abs().max() < 1.0
| 1,485
|
https://github.com/andrydwis/tugasakhir/blob/master/resources/views/components/index-submission.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
tugasakhir
|
andrydwis
|
PHP
|
Code
| 446
| 1,859
|
<div class="pb-2">
<div id="wrapper_dropdown" class="flex w-full p-3 bg-gray-200 rounded-full hover:bg-gray-300">
<div class="flex items-center gap-4">
@role('admin')
<a href="{{route('admin.course.submission.show', [$course, $slug])}}">
<div class="grid w-8 h-8 bg-gray-500 rounded-full md:w-12 md:h-12 place-items-center">
<i class="text-xs text-gray-200 hover:text-gray-400 md:text-xl fas fa-clipboard-list"></i>
</div>
</a>
@else
<a href="{{route('mentor.course.submission.show', [$course, $slug])}}">
<div class="grid w-8 h-8 bg-gray-500 rounded-full md:w-12 md:h-12 place-items-center">
<i class="text-xs text-gray-200 hover:text-gray-400 md:text-xl fas fa-clipboard-list"></i>
</div>
</a>
@endrole
<div class="flex flex-col">
@role('admin')
<a href="{{route('admin.course.submission.show', [$course, $slug])}}" class="line-clamp-1">
<span class="inline text-xs font-semibold text-gray-800 sm:hidden md:font-bold md:text-base">
{{ Str::limit($title, $limit = 14) }}
</span>
<span class="hidden text-sm font-semibold text-gray-800 sm:inline md:font-bold md:text-base">
{{ $title }}
</span>
</a>
@else
<a href="{{route('mentor.course.submission.show', [$course, $slug])}}" class="line-clamp-1">
<span class="inline text-xs font-semibold text-gray-800 sm:hidden md:font-bold md:text-base">
{{ Str::limit($title, $limit = 14) }}
</span>
<span class="hidden text-sm font-semibold text-gray-800 sm:inline md:font-bold md:text-base">
{{ $title }}
</span>
</a>
@endrole
<span class="text-xs text-gray-600 md:text-sm">Submission {{ $submission }} </span>
</div>
</div>
<div class="flex items-center justify-end flex-1" x-data="{ dropdown : false }">
<button @click="dropdown = !dropdown" class="mr-5 focus:outline-none">
<i class="text-sm text-gray-500 md:text-2xl fas fa-ellipsis-h"></i>
</button>
<!-- dropdown -->
<div x-cloak x-show.transition.origin.top="dropdown" @click.away="dropdown = false" class="absolute z-50 w-40 py-2 mt-5 ml-10 text-left text-gray-500 bg-white border border-gray-300 rounded shadow-md">
<!-- item -->
@role('admin')
<a href="{{route('admin.course.submission.show', [$course, $slug])}}" class="block px-4 py-2 text-sm font-medium tracking-wide capitalize transition-all duration-300 ease-in-out bg-white hover:bg-gray-200 hover:text-gray-900">
<i class="mr-1 text-xs fas fa-info"></i>
Detail
</a>
@else
<a href="{{route('mentor.course.submission.show', [$course, $slug])}}" class="block px-4 py-2 text-sm font-medium tracking-wide capitalize transition-all duration-300 ease-in-out bg-white hover:bg-gray-200 hover:text-gray-900">
<i class="mr-1 text-xs fas fa-info"></i>
Detail
</a>
@endrole
<!-- end item -->
<!-- item -->
@role('admin')
<a href="{{route('admin.course.submission.edit', [$course, $slug])}}" class="block px-4 py-2 text-sm font-medium tracking-wide capitalize transition-all duration-300 ease-in-out bg-white hover:bg-gray-200 hover:text-gray-900" href="#">
<i class="mr-1 text-xs fas fa-edit"></i>
Edit
</a>
@else
<a href="{{route('mentor.course.submission.edit', [$course, $slug])}}" class="block px-4 py-2 text-sm font-medium tracking-wide capitalize transition-all duration-300 ease-in-out bg-white hover:bg-gray-200 hover:text-gray-900" href="#">
<i class="mr-1 text-xs fas fa-edit"></i>
Edit
</a>
@endrole
<!-- end item -->
<!-- item -->
@role('admin')
<a href="{{route('admin.course.submission.review', [$course, $slug])}}" class="block px-4 py-2 text-sm font-medium tracking-wide capitalize transition-all duration-300 ease-in-out bg-white hover:bg-gray-200 hover:text-gray-900" href="#">
<i class="mr-1 text-sm fas fa-clipboard"></i>
Review
</a>
@else
<a href="{{route('mentor.course.submission.review', [$course, $slug])}}" class="block px-4 py-2 text-sm font-medium tracking-wide capitalize transition-all duration-300 ease-in-out bg-white hover:bg-gray-200 hover:text-gray-900" href="#">
<i class="mr-1 text-sm fas fa-clipboard"></i>
Review
</a>
@endrole
<!-- end item -->
<hr>
<!-- item -->
<!-- form di hidden -->
<div x-data>
@role('admin')
<form action="{{route('admin.course.submission.destroy', [$course, $slug])}}" method="post" class="hidden">
@csrf
@method('DELETE')
<button id="{{ $slug }}" type="submit">
Hapus
</button>
</form>
@else
<form action="{{route('mentor.course.submission.destroy', [$course, $slug])}}" method="post" class="hidden">
@csrf
@method('DELETE')
<button id="{{ $slug }}" type="submit">
Hapus
</button>
</form>
@endrole
<a href="#" @click.prevent="$('#{{ $slug }}').click();" class="block px-4 py-2 text-sm font-medium tracking-wide capitalize transition-all duration-300 ease-in-out bg-white hover:bg-gray-200 hover:text-gray-900">
<i class="mr-1 text-xs fas fa-trash"></i>
Hapus
</a>
</div>
<!-- end item -->
</div>
</div>
</div>
</div>
| 18,942
|
https://github.com/flyghost/OneOS-V2.1.0/blob/master/components/fs/source/vfs_fs.c
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
OneOS-V2.1.0
|
flyghost
|
C
|
Code
| 1,620
| 5,830
|
/**
***********************************************************************************************************************
* Copyright (c) 2021, China Mobile Communications Group 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 or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file vfs_fs.c
*
* @brief This file implements the basic operation of filesystem.
*
* @revision
* Date Author Notes
* 2021-02-05 OneOS Team First Version
***********************************************************************************************************************
*/
#include <string.h>
#include <oneos_config.h>
#include <os_memory.h>
#include <os_util.h>
#include <os_assert.h>
#include <os_spinlock.h>
#include <dlog.h>
#include <vfs.h>
#include <fcntl.h>
#include <sys/errno.h>
#include "vfs_private.h"
#ifdef OS_USING_VFS_DEVFS
#include <vfs_devfs.h>
#endif
#define MNT_PT_INITED (0x5A5A)
#define VFS_MKFS_MAX VFS_MOUNTPOINT_MAX
enum vfs_dev_ref_stat
{
DEV_REF_NONE,
DEV_REF_MOUNT,
DEV_REF_MKFS,
DEV_REF_NO_SPACE
};
static OS_DEFINE_SPINLOCK(gs_vfs_init_lock);
static unsigned short gs_vfs_init_flag = 0;
static const struct vfs_filesystem_ops *vfs_ops_table[VFS_FILESYSTEM_TYPES_MAX];
static struct vfs_mountpoint mnt_point_table[VFS_MOUNTPOINT_MAX];
static void *mkfs_dev_table[VFS_MKFS_MAX];
static const struct vfs_filesystem_ops *_vfs_fs_ops_get(const char *fs_name)
{
unsigned short i;
const struct vfs_filesystem_ops *fs_ops;
fs_ops = OS_NULL;
VFS_LOCK();
for (i = 0; i < VFS_FILESYSTEM_TYPES_MAX; i++)
{
if ((vfs_ops_table[i]) && (strcmp(vfs_ops_table[i]->fs_name, fs_name) == 0))
{
fs_ops = vfs_ops_table[i];
break;
}
}
VFS_UNLOCK();
return fs_ops;
}
static enum vfs_dev_ref_stat _vfs_mkfs_dev_ref(void *dev)
{
unsigned short i;
enum vfs_dev_ref_stat status;
status = DEV_REF_NONE;
VFS_LOCK();
/* Check whether this device has been mounted. */
for (i = 0; i < VFS_MOUNTPOINT_MAX; i++)
{
if (mnt_point_table[i].dev == dev)
{
status = DEV_REF_MOUNT;
break;
}
}
/* Check whether this device is doing mkfs. */
if (DEV_REF_NONE == status)
{
for (i = 0; i < VFS_MKFS_MAX; i++)
{
if (mkfs_dev_table[i] == dev)
{
status = DEV_REF_MKFS;
break;
}
}
}
/* Reference this device. */
if (DEV_REF_NONE == status)
{
for (i = 0; i < VFS_MKFS_MAX; i++)
{
if (!mkfs_dev_table[i])
{
mkfs_dev_table[i] = dev;
break;
}
}
if (i >= VFS_MKFS_MAX)
{
status = DEV_REF_NO_SPACE;
}
}
VFS_UNLOCK();
return status;
}
static void _vfs_mkfs_dev_deref(void *dev)
{
unsigned short i;
VFS_LOCK();
for (i = 0; i < VFS_MKFS_MAX; i++)
{
if (mkfs_dev_table[i] == dev)
{
mkfs_dev_table[i] = OS_NULL;
break;
}
}
VFS_UNLOCK();
}
static char *_vfs_mntpath_get(const char *path)
{
char *mnt_path;
mnt_path = vfs_create_absolute_path(OS_NULL, path);
if (mnt_path)
{
/* If not root dir and /dev, should check whether the directory exist. */
if ((0 != strcmp(mnt_path, "/")) && (0 != strcmp(mnt_path, DEVFS_PATH)))
{
struct vfs_dir *dp;
int ret;
ret = -1;
dp = dp_alloc();
if (dp)
{
dp_ref_inc(dp);
ret = do_opendir(dp, mnt_path, 0);
if (ret >= 0)
{
ret = do_closedir(dp);
}
dp_ref_dec(dp);
dp_free(dp);
}
if (ret < 0)
{
vfs_destroy_absolute_path(mnt_path);
mnt_path = OS_NULL;
}
}
}
return mnt_path;
}
static struct vfs_mountpoint *_vfs_mount_point_add(void *dev, char *mnt_path, const struct vfs_filesystem_ops *fs_ops)
{
unsigned short i;
os_bool_t use_flag;
struct vfs_mountpoint *mnt_point;
use_flag = OS_FALSE;
mnt_point = OS_NULL;
VFS_LOCK();
for (i = 0; i < VFS_MKFS_MAX; i++)
{
if (dev && (mkfs_dev_table[i] == dev))
{
LOG_E(VFS_TAG, "ERROR. This device is doing mkfs, please try later.");
use_flag = OS_TRUE;
break;
}
}
if (OS_FALSE == use_flag)
{
for (i = 0; i < VFS_MOUNTPOINT_MAX; i++)
{
if (mnt_point_table[i].ops)
{
/* Foreach item in mnt_point_table, if path already been mounted, return NULL. */
if ((strcmp(mnt_point_table[i].mnt_path, mnt_path) == 0)
|| (dev && (mnt_point_table[i].dev == dev)))
{
LOG_E(VFS_TAG, "ERROR. Path or device has been mounted before.");
mnt_point = OS_NULL;
break;
}
}
else
{
/* Use the first empty item. */
if (!mnt_point)
{
mnt_point = &mnt_point_table[i];
}
}
}
if (mnt_point)
{
mnt_point->mnt_path = mnt_path;
mnt_point->ops = fs_ops;
mnt_point->dev = dev;
}
}
VFS_UNLOCK();
return mnt_point;
}
static void _vfs_mount_point_set_init(struct vfs_mountpoint *mnt_point)
{
VFS_LOCK();
mnt_point->is_inited = MNT_PT_INITED;
VFS_UNLOCK();
}
static void _vfs_mount_point_del(struct vfs_mountpoint *mnt_point, char *mnt_path)
{
if (mnt_point)
{
VFS_LOCK();
memset(mnt_point, 0, sizeof(struct vfs_mountpoint));
VFS_UNLOCK();
}
if (mnt_path)
{
vfs_destroy_absolute_path(mnt_path);
}
}
static struct vfs_mountpoint *_vfs_mount_point_get_from_mntpath(const char* mnt_path)
{
unsigned short i;
struct vfs_mountpoint *mnt_point;
mnt_point = OS_NULL;
VFS_LOCK();
for (i = 0; i < VFS_MOUNTPOINT_MAX; i++)
{
if ((mnt_point_table[i].mnt_path) && (0 == strcmp(mnt_point_table[i].mnt_path, mnt_path)))
{
mnt_point = &mnt_point_table[i];
mnt_point->ref_cnt++;
break;
}
}
VFS_UNLOCK();
return mnt_point;
}
static int _vfs_mount_point_unmount(struct vfs_mountpoint *mnt_point)
{
int ret;
struct vfs_mountpoint mnt_point_tmp;
ret = -1;
VFS_LOCK();
if (1 == mnt_point->ref_cnt)
{
/* Back up this mnt_point info to allow to call specify filesystem's unmount.*/
memcpy(&mnt_point_tmp, mnt_point, sizeof(struct vfs_mountpoint));
/* Delete this mnt_point to prevent other task access this mnt_point when we do unmout. */
memset(mnt_point, 0, sizeof(struct vfs_mountpoint));
ret = 0;
}
else
{
mnt_point->ref_cnt--;
LOG_E(VFS_TAG, "Can't unmount now. This mount point was refereced, ref_cnt:%d.", mnt_point->ref_cnt);
LOG_E(VFS_TAG, "You may use cmd: fd_show to see whether referenced by opened file/dir.");
ret = (-EBUSY);
}
VFS_UNLOCK();
if (0 == ret)
{
ret = mnt_point_tmp.ops->unmount(&mnt_point_tmp);
if (ret >= 0)
{
vfs_destroy_absolute_path(mnt_point_tmp.mnt_path);
}
else /* If unfortunately unmount fail, we should restore it back to mnt_point_table. */
{
_vfs_mount_point_add(mnt_point_tmp.dev, mnt_point_tmp.mnt_path, mnt_point_tmp.ops);
}
}
return ret;
}
struct vfs_mountpoint *vfs_mount_point_find_and_ref(const char* abspath)
{
struct vfs_mountpoint *mnt_point;
unsigned short path_len;
unsigned short mnt_path_len;
unsigned short already_match_len;
unsigned short i;
mnt_point = OS_NULL;
already_match_len = 0;
if (abspath)
{
path_len = strlen(abspath);
VFS_LOCK();
for (i = 0; i < VFS_MOUNTPOINT_MAX; i++)
{
if ((!mnt_point_table[i].mnt_path) || (!mnt_point_table[i].ops) || (mnt_point_table[i].is_inited != MNT_PT_INITED))
{
continue;
}
mnt_path_len = strlen(mnt_point_table[i].mnt_path);
if ((mnt_path_len < already_match_len) || (mnt_path_len > path_len))
{
continue;
}
/* check whether path have directory separator '/' at the the mount_path end.*/
if ((mnt_path_len > 1) && (abspath[mnt_path_len] != '/') && (abspath[mnt_path_len] != '\0'))
{
continue;
}
if (strncmp(mnt_point_table[i].mnt_path, abspath, mnt_path_len) == 0)
{
mnt_point = &mnt_point_table[i];
if (mnt_path_len == path_len)
{
/* Find the best match mnt_path, break. */
break;
}
else/* mnt_path_len < path_len */
{
/* Find a match mnt_path, but maybe not the longest match,
record it, and then continue to search longger match.*/
already_match_len = mnt_path_len;
}
}
}
if (mnt_point)
{
mnt_point->ref_cnt++;
}
VFS_UNLOCK();
}
return mnt_point;
}
void vfs_mount_point_deref(struct vfs_mountpoint *mnt_point)
{
VFS_LOCK();
OS_ASSERT(mnt_point->ref_cnt > 0);
mnt_point->ref_cnt--;
VFS_UNLOCK();
}
int vfs_register(const struct vfs_filesystem_ops *fs_ops)
{
unsigned short i;
int ret;
ret = -1;
if (fs_ops)
{
VFS_LOCK();
for (i = 0; i < VFS_FILESYSTEM_TYPES_MAX; i++)
{
if (vfs_ops_table[i])
{
if (strcmp(vfs_ops_table[i]->fs_name, fs_ops->fs_name) == 0)
{
LOG_E(VFS_TAG, "Filesystem %s has already been registerd !", fs_ops->fs_name);
break;
}
}
else
{
vfs_ops_table[i] = fs_ops;
ret = 0;
break;
}
}
VFS_UNLOCK();
if (VFS_FILESYSTEM_TYPES_MAX == i)
{
LOG_E(VFS_TAG, "Filesytem ops table is not enough, you may increase VFS_FILESYSTEM_TYPES_MAX");
}
}
else
{
LOG_E(VFS_TAG, "Invaid fs_ops");
}
return ret;
}
int vfs_mount(const char *dev_name, const char *path, const char *fs_name, unsigned long mountflag, const void *data)
{
const struct vfs_filesystem_ops *fs_ops;
struct vfs_mountpoint *mnt_point;
char *mnt_path;
void *dev;
int ret;
fs_ops = OS_NULL;
mnt_point = OS_NULL;
mnt_path = OS_NULL;
dev = OS_NULL;
ret = 0;
if ((!path) || (!fs_name))
{
LOG_E(VFS_TAG, "Invalid path or fs_name !");
VFS_SET_ERRNO(-EINVAL);
ret = -1;
}
/* For some fs, dev_name may not mandatory. But if need dev_name, we should check device exist. */
if (dev_name)
{
dev = (void *)os_device_find(dev_name);
if (!dev)
{
VFS_SET_ERRNO(-ENODEV);
ret = -1;
}
}
/* Check whether the path exist.*/
if (0 == ret)
{
mnt_path = _vfs_mntpath_get(path);
if (!mnt_path)
{
VFS_SET_ERRNO(-ENOTDIR);
ret = -1;
}
}
/* Find the fs ops. */
if (0 == ret)
{
fs_ops = _vfs_fs_ops_get(fs_name);
if ((!fs_ops) || (!fs_ops->mount))
{
VFS_SET_ERRNO(-ENOSYS);
ret = -1;
}
}
/* Get an entry to save the mount point info. */
if (0 == ret)
{
mnt_point = _vfs_mount_point_add(dev, mnt_path, fs_ops);
if (!mnt_point)
{
VFS_SET_ERRNO(-ENOSPC);
ret = -1;
}
}
/* Mount the specific filesystem. */
if (0 == ret)
{
ret = fs_ops->mount(mnt_point, mountflag, data);
}
if (ret >= 0)
{
_vfs_mount_point_set_init(mnt_point);
LOG_I(VFS_TAG, "Mount %s to %s", fs_name, path);
}
else
{
VFS_SET_ERRNO(ret);
_vfs_mount_point_del(mnt_point, mnt_path);
}
ret = (ret < 0) ? (-1) : 0;
return ret;
}
int vfs_unmount(const char *path)
{
int ret;
char *mnt_path;
struct vfs_mountpoint *mnt_point;
ret = -1;
mnt_path = vfs_create_absolute_path(OS_NULL, path);
if (mnt_path)
{
mnt_point = _vfs_mount_point_get_from_mntpath(mnt_path);
if (mnt_point && mnt_point->ops && mnt_point->ops->unmount)
{
ret = _vfs_mount_point_unmount(mnt_point);
if (ret < 0)
{
VFS_SET_ERRNO(ret);
}
ret = (ret < 0) ? (-1) : 0;
}
else
{
VFS_SET_ERRNO(-ENOENT);
}
vfs_destroy_absolute_path(mnt_path);
}
else
{
VFS_SET_ERRNO(-ENOENT);
}
return ret;
}
int vfs_mkfs(const char *fs_name, const char *dev_name)
{
int ret;
void *dev;
const struct vfs_filesystem_ops *fs_ops;
enum vfs_dev_ref_stat status;
ret = -1;
dev = OS_NULL;
if (fs_name && dev_name)
{
dev = (void *)os_device_find(dev_name);
}
if (dev)
{
status = _vfs_mkfs_dev_ref(dev);
if (DEV_REF_MOUNT == status)
{
LOG_E(VFS_TAG, "This device has been mounted, you should unmount it before mkfs");
VFS_SET_ERRNO(-EBUSY);
}
else if (DEV_REF_MKFS == status)
{
LOG_E(VFS_TAG, "This device is already doing mkfs, you may try it later");
VFS_SET_ERRNO(-EBUSY);
}
else if (DEV_REF_NO_SPACE == status)
{
LOG_E(VFS_TAG, "Too many device is doing mkfs, you may try it later");
VFS_SET_ERRNO(-EBUSY);
}
else
{
fs_ops = _vfs_fs_ops_get(fs_name);
if (fs_ops && fs_ops->mkfs)
{
ret = fs_ops->mkfs(dev);
if (ret < 0)
{
VFS_SET_ERRNO(ret);
}
ret = (ret < 0) ? (-1) : 0;
}
else
{
LOG_E(VFS_TAG, "The file system (%s) mkfs function was not found", fs_name);
VFS_SET_ERRNO(-ENOSYS);
ret = -1;
}
_vfs_mkfs_dev_deref(dev);
}
}
else
{
LOG_E(VFS_TAG, "Device (%s) was not found", dev_name);
VFS_SET_ERRNO(-ENODEV);
}
return ret;
}
int vfs_init(void)
{
int ret;
os_spin_lock(&gs_vfs_init_lock);
if (0 == gs_vfs_init_flag)
{
gs_vfs_init_flag = 1;
os_spin_unlock(&gs_vfs_init_lock);
VFS_LOCK_INIT();
memset((void *)vfs_ops_table, 0, sizeof(vfs_ops_table));
memset((void *)mnt_point_table, 0, sizeof(mnt_point_table));
memset((void *)mkfs_dev_table, 0, sizeof(mkfs_dev_table));
working_dir_init();
fd_table_init();
#ifdef OS_USING_VFS_DEVFS
if (0 == vfs_devfs_init())
{
(void)vfs_mount(OS_NULL, DEVFS_PATH, "dev", 0, OS_NULL);
}
#endif
ret = 0;
}
else
{
LOG_E(VFS_TAG, "The VFS has already been inited. ");
ret = -1;
}
return ret;
}
OS_POSTCORE_INIT(vfs_init, OS_INIT_SUBLEVEL_HIGH);
| 34,631
|
https://github.com/Terenine/emacs_libs/blob/master/bin/unset_current_project
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
emacs_libs
|
Terenine
|
Shell
|
Code
| 4
| 15
|
#!/bin/sh
rm -f ~/.current_project
| 49,585
|
https://github.com/jparise/PINFuture/blob/master/PINFuture/Classes/PINFutureMap+Map.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
PINFuture
|
jparise
|
C
|
Code
| 55
| 250
|
//
// PINFutureMap+Map.h
// Pinterest
//
// Created by Chris Danford on 11/23/16.
// Copyright © 2016 Pinterest. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PINFuture.h"
#import "PINFutureMap.h"
NS_ASSUME_NONNULL_BEGIN
@interface PINFutureMap<FromType, ToType> (Map)
+ (PINFuture<ToType> *)map:(PINFuture<FromType> *)sourceFuture
executor:(id<PINExecutor>)executor
transform:(ToType (^)(FromType fromValue))transform PIN_WARN_UNUSED_RESULT;
@end
@interface PINFutureMap<FromType, ToType> (MapConvenience)
+ (PINFuture<ToType> *)mapToValue:(PINFuture<FromType> *)sourceFuture
value:(ToType)value PIN_WARN_UNUSED_RESULT;
@end
NS_ASSUME_NONNULL_END
| 50,673
|
https://github.com/Aman817/Linux-App/blob/master/lib/views/login.dart
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Linux-App
|
Aman817
|
Dart
|
Code
| 399
| 1,680
|
import 'package:Linux_App/views/home.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class LoginPage extends StatefulWidget {
LoginPage({Key key}) : super(key: key);
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final GlobalKey<FormState> _loginFormKey = GlobalKey<FormState>();
TextEditingController emailInputController;
TextEditingController passInputController;
@override
initState() {
emailInputController = new TextEditingController();
passInputController = new TextEditingController();
super.initState();
}
String emailValidator(String value) {
Pattern pattern =
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value)) {
return 'Email format is invalid';
} else {
return null;
}
}
String pwdValidator(String value) {
if (value.length < 8) {
return 'Password must be longer than 8 characters';
} else {
return null;
}
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Login',
style: GoogleFonts.lobster(
color: Colors.black,
fontSize: 40,
),
),
centerTitle: true,
elevation: 0.0,
),
body: Container(
padding: const EdgeInsets.all(20),
child: SingleChildScrollView(
child: Form(
key: _loginFormKey,
child: Column(
children: <Widget>[
SizedBox(
height: 40,
),
Card(
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
side: BorderSide(width: 5, color: Colors.white),
),
elevation: 30,
child: Column(
children: <Widget>[
SizedBox(
width: 400,
height: 200,
child: Column(
children: <Widget>[
SizedBox(
height: 150,
width: 300,
child: Image.asset("assets/images/redhat.png"),
),
Text(
"Red Hat App",
style: GoogleFonts.sansita(
color: Colors.black,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
],
),
)
],
),
),
SizedBox(
height: 40,
),
TextFormField(
autocorrect: true,
decoration: InputDecoration(
labelText: 'Email',
prefixIcon: Icon(
Icons.email,
color: Colors.redAccent[700],
),
labelStyle: TextStyle(fontSize: 15.0, color: Colors.black),
hintText: "Enter your Email",
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 3.0),
borderRadius: BorderRadius.circular(50.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50.0)),
),
keyboardType: TextInputType.emailAddress,
controller: emailInputController,
validator: emailValidator,
),
SizedBox(
height: 20,
),
TextFormField(
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: Icon(
Icons.security,
color: Colors.redAccent[700],
),
labelStyle: TextStyle(fontSize: 15.0, color: Colors.black),
hintText: "Enter your Password ",
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 3.0),
borderRadius: BorderRadius.circular(50.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50.0)),
),
keyboardType: TextInputType.visiblePassword,
obscureText: true,
controller: passInputController,
validator: pwdValidator,
),
SizedBox(
height: 20,
),
SizedBox(
width: 250,
child: RaisedButton(
child: Text(
"Submit",
style: TextStyle(color: Colors.white),
),
elevation: 20,
color: Colors.redAccent[700],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: BorderSide(color: Colors.black, width: 3)),
onPressed: () {
if (_loginFormKey.currentState.validate()) {
FirebaseAuth.instance
.signInWithEmailAndPassword(
email: emailInputController.text,
password: passInputController.text,
)
.then((currentUser) => Firestore.instance
.collection("user")
.document(currentUser.user.uid)
.get()
.then(
(DocumentSnapshot result) =>
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
),
),
)
.catchError((err) => print(err)))
.catchError((err) => print(err));
}
},
),
),
SizedBox(
height: 20,
),
Text("Don't have an account yet?"),
FlatButton(
child: Text("Register here!"),
onPressed: () {
Navigator.pushNamed(context, "/registration");
},
)
],
),
),
),
),
);
}
}
| 22,587
|
https://github.com/antoniaRohne/UnityProjects/blob/master/GTAbgabe1_ShotEmUp/Assets/Prefabs/AmmoPack.prefab
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
UnityProjects
|
antoniaRohne
|
Unity3D Asset
|
Code
| 292
| 1,358
|
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1001 &100100000
Prefab:
m_ObjectHideFlags: 1
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications: []
m_RemovedComponents: []
m_ParentPrefab: {fileID: 0}
m_RootGameObject: {fileID: 1841207592434654}
m_IsPrefabParent: 1
--- !u!1 &1841207592434654
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
serializedVersion: 5
m_Component:
- component: {fileID: 4125063360673342}
- component: {fileID: 33258999114589300}
- component: {fileID: 135343579263444224}
- component: {fileID: 23573492097708654}
- component: {fileID: 114376223162675040}
m_Layer: 0
m_Name: AmmoPack
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4125063360673342
Transform:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1841207592434654}
m_LocalRotation: {x: 0, y: -0.7071068, z: 0, w: 0.7071068}
m_LocalPosition: {x: -2.187, y: 0.264, z: 0.17578125}
m_LocalScale: {x: 0.29591417, y: 0.46765262, z: 0.88320076}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: -90, z: 0}
--- !u!23 &23573492097708654
MeshRenderer:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1841207592434654}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 2630edcd047fa7a40b4e74fb83295c2f, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!33 &33258999114589300
MeshFilter:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1841207592434654}
m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0}
--- !u!114 &114376223162675040
MonoBehaviour:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1841207592434654}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: cc9de7ee3bda78d46909310730d57071, type: 3}
m_Name:
m_EditorClassIdentifier:
--- !u!135 &135343579263444224
SphereCollider:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1841207592434654}
m_Material: {fileID: 0}
m_IsTrigger: 1
m_Enabled: 1
serializedVersion: 2
m_Radius: 0.5
m_Center: {x: 0, y: 0, z: 0}
| 50,056
|
https://github.com/rich-murphey/ballista/blob/master/rust/ballista/src/serde/logical_plan/to_proto.rs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
ballista
|
rich-murphey
|
Rust
|
Code
| 1,140
| 4,028
|
// Copyright 2020 Andy Grove
//
// 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 License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Serde code to convert Arrow schemas and DataFusion logical plans to Ballista protocol
//! buffer format, allowing DataFusion logical plans to be serialized and transmitted between
//! processes.
use std::convert::TryInto;
use crate::serde::{empty_expr_node, empty_logical_plan_node, protobuf, BallistaError};
use arrow::datatypes::{DataType, Schema};
use datafusion::datasource::parquet::ParquetTable;
use datafusion::datasource::CsvFile;
use datafusion::logical_plan::{Expr, JoinType, LogicalPlan};
use datafusion::physical_plan::aggregates::AggregateFunction;
use datafusion::scalar::ScalarValue;
impl TryInto<protobuf::LogicalPlanNode> for &LogicalPlan {
type Error = BallistaError;
fn try_into(self) -> Result<protobuf::LogicalPlanNode, Self::Error> {
match self {
LogicalPlan::TableScan {
table_name,
source,
projected_schema,
filters,
..
} => {
let schema = source.schema();
let source = source.as_any();
let columns = projected_schema
.fields()
.iter()
.map(|f| f.name().to_owned())
.collect();
let projection = Some(protobuf::ProjectionColumns { columns });
let schema: protobuf::Schema = schema.as_ref().try_into()?;
let filters: Vec<protobuf::LogicalExprNode> = filters
.iter()
.map(|filter| filter.try_into())
.collect::<Result<Vec<_>, _>>()?;
let mut node = empty_logical_plan_node();
if let Some(parquet) = source.downcast_ref::<ParquetTable>() {
node.parquet_scan = Some(protobuf::ParquetTableScanNode {
table_name: table_name.to_owned(),
path: parquet.path().to_owned(),
projection,
schema: Some(schema),
filters,
});
Ok(node)
} else if let Some(csv) = source.downcast_ref::<CsvFile>() {
node.csv_scan = Some(protobuf::CsvTableScanNode {
table_name: table_name.to_owned(),
path: csv.path().to_owned(),
projection,
schema: Some(schema),
has_header: csv.has_header(),
delimiter: csv.delimiter().to_string(),
file_extension: csv.file_extension().to_string(),
filters,
});
Ok(node)
} else {
Err(BallistaError::General(format!(
"logical plan to_proto unsupported table provider {:?}",
source
)))
}
}
LogicalPlan::Projection { expr, input, .. } => {
let input: protobuf::LogicalPlanNode = input.as_ref().try_into()?;
let mut node = empty_logical_plan_node();
node.input = Some(Box::new(input));
node.projection = Some(protobuf::ProjectionNode {
expr: expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<_>, BallistaError>>()?,
});
Ok(node)
}
LogicalPlan::Filter { predicate, input } => {
let input: protobuf::LogicalPlanNode = input.as_ref().try_into()?;
let mut node = empty_logical_plan_node();
node.input = Some(Box::new(input));
node.selection = Some(protobuf::SelectionNode {
expr: Some(predicate.try_into()?),
});
Ok(node)
}
LogicalPlan::Aggregate {
input,
group_expr,
aggr_expr,
..
} => {
let input: protobuf::LogicalPlanNode = input.as_ref().try_into()?;
let mut node = empty_logical_plan_node();
node.input = Some(Box::new(input));
node.aggregate = Some(protobuf::AggregateNode {
group_expr: group_expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<_>, BallistaError>>()?,
aggr_expr: aggr_expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<_>, BallistaError>>()?,
});
Ok(node)
}
LogicalPlan::Join {
left,
right,
on,
join_type,
..
} => {
let left: protobuf::LogicalPlanNode = left.as_ref().try_into()?;
let right: protobuf::LogicalPlanNode = right.as_ref().try_into()?;
let join_type = match join_type {
JoinType::Inner => protobuf::JoinType::Inner,
JoinType::Left => protobuf::JoinType::Left,
JoinType::Right => protobuf::JoinType::Right,
};
let left_join_column = on.iter().map(|on| on.0.to_owned()).collect();
let right_join_column = on.iter().map(|on| on.1.to_owned()).collect();
let mut node = empty_logical_plan_node();
node.join = Some(Box::new(protobuf::JoinNode {
left: Some(Box::new(left)),
right: Some(Box::new(right)),
join_type: join_type.into(),
left_join_column,
right_join_column,
}));
Ok(node)
}
LogicalPlan::Limit { input, n } => {
let input: protobuf::LogicalPlanNode = input.as_ref().try_into()?;
let mut node = empty_logical_plan_node();
node.input = Some(Box::new(input));
node.limit = Some(protobuf::LimitNode { limit: *n as u32 });
Ok(node)
}
LogicalPlan::Sort { input, expr } => {
let input: protobuf::LogicalPlanNode = input.as_ref().try_into()?;
let mut node = empty_logical_plan_node();
node.input = Some(Box::new(input));
let selection_expr: Vec<protobuf::LogicalExprNode> = expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<_>, BallistaError>>()?;
node.sort = Some(protobuf::SortNode {
expr: selection_expr,
});
Ok(node)
}
LogicalPlan::Repartition { .. } => unimplemented!(),
LogicalPlan::EmptyRelation { .. } => unimplemented!(),
LogicalPlan::CreateExternalTable { .. } => unimplemented!(),
LogicalPlan::Explain { .. } => unimplemented!(),
LogicalPlan::Extension { .. } => unimplemented!(),
// _ => Err(BallistaError::General(format!(
// "logical plan to_proto {:?}",
// self
// ))),
}
}
}
impl TryInto<protobuf::LogicalExprNode> for &Expr {
type Error = BallistaError;
fn try_into(self) -> Result<protobuf::LogicalExprNode, Self::Error> {
match self {
Expr::Column(name) => {
let mut expr = empty_expr_node();
expr.has_column_name = true;
expr.column_name = name.clone();
Ok(expr)
}
Expr::Alias(expr, alias) => {
let mut expr_node = empty_expr_node();
expr_node.alias = Some(Box::new(protobuf::AliasNode {
expr: Some(Box::new(expr.as_ref().try_into()?)),
alias: alias.to_owned(),
}));
Ok(expr_node)
}
Expr::Literal(value) => match value {
ScalarValue::Utf8(s) => {
let mut expr = empty_expr_node();
expr.has_literal_string = true;
expr.literal_string = s.as_ref().unwrap().to_owned(); //TODO remove unwrap
Ok(expr)
}
ScalarValue::Int8(n) => {
let mut expr = empty_expr_node();
expr.has_literal_i8 = true;
expr.literal_int = n.unwrap() as i64; // TODO remove unwrap
Ok(expr)
}
ScalarValue::Int16(n) => {
let mut expr = empty_expr_node();
expr.has_literal_i16 = true;
expr.literal_int = n.unwrap() as i64; // TODO remove unwrap
Ok(expr)
}
ScalarValue::Int32(n) => {
let mut expr = empty_expr_node();
expr.has_literal_i32 = true;
expr.literal_int = n.unwrap() as i64; // TODO remove unwrap
Ok(expr)
}
ScalarValue::Int64(n) => {
let mut expr = empty_expr_node();
expr.has_literal_i64 = true;
expr.literal_int = n.unwrap() as i64; // TODO remove unwrap
Ok(expr)
}
ScalarValue::UInt8(n) => {
let mut expr = empty_expr_node();
expr.has_literal_u8 = true;
expr.literal_uint = n.unwrap() as u64; // TODO remove unwrap
Ok(expr)
}
ScalarValue::UInt16(n) => {
let mut expr = empty_expr_node();
expr.has_literal_u16 = true;
expr.literal_uint = n.unwrap() as u64; // TODO remove unwrap
Ok(expr)
}
ScalarValue::UInt32(n) => {
let mut expr = empty_expr_node();
expr.has_literal_u32 = true;
expr.literal_uint = n.unwrap() as u64; // TODO remove unwrap
Ok(expr)
}
ScalarValue::UInt64(n) => {
let mut expr = empty_expr_node();
expr.has_literal_u64 = true;
expr.literal_uint = n.unwrap() as u64; // TODO remove unwrap
Ok(expr)
}
ScalarValue::Float32(n) => {
let mut expr = empty_expr_node();
expr.has_literal_f32 = true;
expr.literal_f32 = n.unwrap() as f32; // TODO remove unwrap
Ok(expr)
}
ScalarValue::Float64(n) => {
let mut expr = empty_expr_node();
expr.has_literal_f64 = true;
expr.literal_f64 = n.unwrap() as f64; // TODO remove unwrap
Ok(expr)
}
other => Err(BallistaError::General(format!(
"to_proto unsupported scalar value {:?}",
other
))),
},
Expr::BinaryExpr { left, op, right } => {
let mut expr = empty_expr_node();
expr.binary_expr = Some(Box::new(protobuf::BinaryExprNode {
l: Some(Box::new(left.as_ref().try_into()?)),
r: Some(Box::new(right.as_ref().try_into()?)),
op: format!("{:?}", op),
}));
Ok(expr)
}
Expr::AggregateFunction {
ref fun, ref args, ..
} => {
let mut expr = empty_expr_node();
let aggr_function = match fun {
AggregateFunction::Min => protobuf::AggregateFunction::Min,
AggregateFunction::Max => protobuf::AggregateFunction::Max,
AggregateFunction::Sum => protobuf::AggregateFunction::Sum,
AggregateFunction::Avg => protobuf::AggregateFunction::Avg,
AggregateFunction::Count => protobuf::AggregateFunction::Count,
};
let arg = &args[0];
expr.aggregate_expr = Some(Box::new(protobuf::AggregateExprNode {
aggr_function: aggr_function.into(),
expr: Some(Box::new(arg.try_into()?)),
}));
Ok(expr)
}
Expr::ScalarVariable(_) => unimplemented!(),
Expr::ScalarFunction { .. } => unimplemented!(),
Expr::ScalarUDF { .. } => unimplemented!(),
Expr::AggregateUDF { .. } => unimplemented!(),
Expr::Not(_) => unimplemented!(),
Expr::IsNull(_) => unimplemented!(),
Expr::IsNotNull(_) => unimplemented!(),
Expr::Between { .. } => unimplemented!(),
Expr::Negative(_) => unimplemented!(),
Expr::Case { .. } => unimplemented!(),
Expr::Cast { .. } => unimplemented!(),
Expr::Sort { .. } => unimplemented!(),
Expr::InList { .. } => unimplemented!(),
Expr::Wildcard => unimplemented!(),
// _ => Err(BallistaError::General(format!(
// "logical expr to_proto {:?}",
// self
// ))),
}
}
}
impl TryInto<protobuf::Schema> for &Schema {
type Error = BallistaError;
fn try_into(self) -> Result<protobuf::Schema, Self::Error> {
Ok(protobuf::Schema {
columns: self
.fields()
.iter()
.map(|field| {
let proto = to_proto_arrow_type(&field.data_type());
proto.map(|arrow_type| protobuf::Field {
name: field.name().to_owned(),
arrow_type: arrow_type.into(),
nullable: field.is_nullable(),
children: vec![],
})
})
.collect::<Result<Vec<_>, _>>()?,
})
}
}
fn to_proto_arrow_type(dt: &DataType) -> Result<protobuf::ArrowType, BallistaError> {
match dt {
DataType::Int8 => Ok(protobuf::ArrowType::Int8),
DataType::Int16 => Ok(protobuf::ArrowType::Int16),
DataType::Int32 => Ok(protobuf::ArrowType::Int32),
DataType::Int64 => Ok(protobuf::ArrowType::Int64),
DataType::UInt8 => Ok(protobuf::ArrowType::Uint8),
DataType::UInt16 => Ok(protobuf::ArrowType::Uint16),
DataType::UInt32 => Ok(protobuf::ArrowType::Uint32),
DataType::UInt64 => Ok(protobuf::ArrowType::Uint64),
DataType::Float32 => Ok(protobuf::ArrowType::Float),
DataType::Float64 => Ok(protobuf::ArrowType::Double),
DataType::Utf8 => Ok(protobuf::ArrowType::Utf8),
other => Err(BallistaError::General(format!(
"logical_plan::to_proto() Unsupported data type {:?}",
other
))),
}
}
| 15,489
|
https://github.com/sebastiaandekker/newdealseals-bedrock/blob/master/web/app/themes/Divi/includes/builder/module/woocommerce/AddToCart.php
|
Github Open Source
|
Open Source
|
MIT
| null |
newdealseals-bedrock
|
sebastiaandekker
|
PHP
|
Code
| 1,816
| 6,858
|
<?php
/**
* WooCommerce Modules: ET_Builder_Module_Woocommerce_Add_To_Cart class
*
* The ET_Builder_Module_Woocommerce_Add_To_Cart Class is responsible for rendering the
* Add To Cart markup using the WooCommerce template.
*
* @package Divi\Builder
*
* @since 3.29
*/
/**
* Class representing WooCommerce Add to cart component.
*/
class ET_Builder_Module_Woocommerce_Add_To_Cart extends ET_Builder_Module {
/**
* Initialize.
*/
public function init() {
$this->name = esc_html__( 'Woo Add To Cart', 'et_builder' );
$this->plural = esc_html__( 'Woo Add To Cart', 'et_builder' );
$this->slug = 'et_pb_wc_add_to_cart';
$this->vb_support = 'on';
$this->settings_modal_toggles = array(
'general' => array(
'toggles' => array(
'main_content' => et_builder_i18n( 'Content' ),
'elements' => et_builder_i18n( 'Elements' ),
),
),
'advanced' => array(
'toggles' => array(
'text' => array(
'title' => et_builder_i18n( 'Text' ),
'priority' => 45,
),
'header' => array(
'title' => esc_html__( 'Heading Text', 'et_builder' ),
'priority' => 49,
'tabbed_subtoggles' => true,
'sub_toggles' => array(
'h1' => array(
'name' => 'H1',
'icon' => 'text-h1',
),
'h2' => array(
'name' => 'H2',
'icon' => 'text-h2',
),
'h3' => array(
'name' => 'H3',
'icon' => 'text-h3',
),
'h4' => array(
'name' => 'H4',
'icon' => 'text-h4',
),
'h5' => array(
'name' => 'H5',
'icon' => 'text-h5',
),
'h6' => array(
'name' => 'H6',
'icon' => 'text-h6',
),
),
),
'width' => array(
'title' => et_builder_i18n( 'Sizing' ),
'priority' => 80,
),
),
),
);
$this->advanced_fields = array(
'fonts' => array(
'body' => array(
'label' => et_builder_i18n( 'Text' ),
'css' => array(
'main' => '%%order_class%%, %%order_class%% a, %%order_class%% label, %%order_class%%.et_pb_module .et_pb_module_inner .stock',
'important' => 'all',
),
'font_size' => array(
'default' => '14px',
),
'line_height' => array(
'default' => '1.3em',
),
'hide_text_align' => true,
'toggle_slug' => 'text',
'font' => array(
'default' => '|700|||||||',
),
),
),
'background' => array(
'settings' => array(
'color' => 'alpha',
),
),
'margin_padding' => array(
'css' => array(
'important' => 'all',
),
),
'text' => array(
'use_background_layout' => true,
'options' => array(
'text_orientation' => array(
'default' => 'left',
),
'background_layout' => array(
'default' => 'light',
'hover' => 'tabs',
),
),
),
'text_shadow' => array(
// Don't add text-shadow fields since they already are via font-options.
'default' => false,
),
'button' => array(
'button' => array(
'label' => et_builder_i18n( 'Button' ),
'css' => array(
'main' => '%%order_class%% .button',
'limited_main' => '%%order_class%% .button',
'alignment' => '%%order_class%% .et_pb_module_inner > form',
// Setting to TRUE since it only checks for the value's existence.
'important' => 'all',
),
/*
* Button inside add to cart module is rendered from WooCommerce's default
* template which makes its positioning isn't flexible. Thus button alignment
* is removed.
*/
'use_alignment' => false,
'box_shadow' => array(
'css' => array(
'main' => '%%order_class%% .button',
'important' => true,
),
),
'use_icon' => false,
'margin_padding' => array(
'css' => array(
'important' => 'all',
),
),
),
),
'form_field' => array(
'fields' => array(
'label' => esc_html__( 'Fields', 'et_builder' ),
'toggle_priority' => 67,
'css' => array(
'main' => '%%order_class%% input, %%order_class%% .quantity input.qty',
'background_color' => '%%order_class%% input, %%order_class%% .quantity input.qty',
'background_color_hover' => '%%order_class%% input:hover, %%order_class%% .quantity input.qty:hover',
'focus_background_color' => '%%order_class%% input:focus, %%order_class%% select:focus, %%order_class%% .quantity input.qty:focus',
'form_text_color' => '%%order_class%% input, %%order_class%% select, %%order_class%% .quantity input.qty',
'form_text_color_hover' => '%%order_class%% input[type="text"]:hover, %%order_class%% select:hover, %%order_class%% .quantity input.qty:hover',
'focus_text_color' => '%%order_class%% input:focus, %%order_class%% .quantity input.qty:focus',
'placeholder_focus' => '%%order_class%% input:focus::-webkit-input-placeholder, %%order_class%% input:focus::-moz-placeholder, %%order_class%% input:focus:-ms-input-placeholder, %%order_class%% textarea:focus::-webkit-input-placeholder, %%order_class%% textarea:focus::-moz-placeholder, %%order_class%% textarea:focus:-ms-input-placeholder',
'padding' => '%%order_class%% input',
'margin' => '%%order_class%%',
'important' => array(
'background_color',
'background_color_hover',
'focus_background_color',
'form_text_color',
'form_text_color_hover',
'text_color',
'focus_text_color',
'padding',
'margin',
),
),
'box_shadow' => array(
'name' => 'fields',
'css' => array(
'main' => '%%order_class%% input',
),
'default_on_fronts' => array(
'color' => '',
'position' => '',
),
),
'border_styles' => array(
'fields' => array(
'name' => 'fields',
'css' => array(
'main' => array(
'border_radii' => '%%order_class%% input, %%order_class%% .quantity input.qty',
'border_styles' => '%%order_class%% input, %%order_class%% .quantity input.qty',
'defaults' => array(
'border_radii' => 'on|3px|3px|3px|3px',
'border_styles' => array(
'width' => '0px',
'style' => 'none',
),
),
),
'important' => 'all',
),
'label_prefix' => esc_html__( 'Fields', 'et_builder' ),
),
'fields_focus' => array(
'name' => 'fields_focus',
'css' => array(
'main' => array(
'border_radii' => '%%order_class%% input:focus, %%order_class%% .quantity input.qty:focus',
'border_styles' => '%%order_class%% input:focus, %%order_class%% .quantity input.qty:focus',
),
'important' => 'all',
),
'label_prefix' => esc_html__( 'Fields Focus', 'et_builder' ),
),
),
'font_field' => array(
'css' => array(
'main' => array(
'%%order_class%% input, %%order_class%% .quantity input.qty',
),
'hover' => array(
'%%order_class%% input:hover',
'%%order_class%% input:hover::-webkit-input-placeholder',
'%%order_class%% input:hover::-moz-placeholder',
'%%order_class%% input:hover:-ms-input-placeholder',
),
'important' => 'all',
),
'font_size' => array(
'default' => '20px',
),
'line_height' => array(
'default' => '1em',
),
),
'margin_padding' => array(
'css' => array(
'main' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations tr',
'important' => array( 'custom_padding' ),
),
),
),
'dropdown_menus' => array(
'label' => esc_html__( 'Dropdown Menus', 'et_builder' ),
'toggle_priority' => 67,
'css' => array(
'main' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select',
'background_color' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select',
'background_color_hover' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select:hover',
'focus_background_color' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select:focus',
'form_text_color' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select',
'form_text_color_hover' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select + label:hover, %%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select:hover',
'focus_text_color' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select option:focus, %%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select + label',
'placeholder_focus' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select:focus, %%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select + label:focus',
'margin_padding' => array(
'css' => array(
'main' => '%%order_class%% select',
'important' => array( 'all' ),
),
),
'important' => array(
'text_color',
'form_text_color',
'margin_padding',
),
),
'margin_padding' => array(
'use_padding' => false,
),
'box_shadow' => array(
'name' => 'dropdown_menus',
'css' => array(
'main' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select',
),
),
'border_styles' => array(
'dropdown_menus' => array(
'name' => 'dropdown_menus',
'css' => array(
'main' => array(
'border_styles' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select',
'border_radii' => '%%order_class%%.et_pb_module .et_pb_module_inner form.cart .variations td select',
),
'important' => 'all',
),
'label_prefix' => esc_html__( 'Dropdown Menus', 'et_builder' ),
'use_radius' => false,
),
),
'font_field' => array(
'css' => array(
'main' => array(
'%%order_class%% select',
),
'hover' => array(
'%%order_class%% select:hover',
),
'important' => 'all',
),
'font_size' => array(
'default' => '12px',
),
'hide_line_height' => true,
'hide_text_align' => true,
),
),
),
);
$this->custom_css_fields = array(
'fields' => array(
'label' => esc_html__( 'Fields', 'et_builder' ),
'selector' => 'input',
),
'dropdown_menus' => array(
'label' => esc_html__( 'Dropdown Menus', 'et_builder' ),
'selector' => 'select',
),
'buttons' => array(
'label' => esc_html__( 'Buttons', 'et_builder' ),
'selector' => '.button',
),
);
$this->help_videos = array(
array(
'id' => '7X03vBPYJ1o',
'name' => esc_html__( 'Divi WooCommerce Modules', 'et_builder' ),
),
);
}
/**
* {@inheritdoc}
*/
public function get_fields() {
$fields = array(
'product' => ET_Builder_Module_Helper_Woocommerce_Modules::get_field(
'product',
array(
'default' => ET_Builder_Module_Helper_Woocommerce_Modules::get_product_default(),
'computed_affects' => array(
'__add_to_cart',
),
)
),
'product_filter' => ET_Builder_Module_Helper_Woocommerce_Modules::get_field(
'product_filter',
array(
'computed_affects' => array(
'__add_to_cart',
),
)
),
'show_quantity' => array(
'label' => esc_html__( 'Show Quantity Field', 'et_builder' ),
'type' => 'yes_no_button',
'option_category' => 'configuration',
'options' => array(
'on' => et_builder_i18n( 'On' ),
'off' => et_builder_i18n( 'Off' ),
),
'default' => 'on',
'toggle_slug' => 'elements',
'description' => esc_html__( 'Here you can choose whether the quantity field should be added before the Add to Cart button.', 'et_builder' ),
'mobile_options' => true,
'hover' => 'tabs',
),
'show_stock' => array(
'label' => esc_html__( 'Show Stock', 'et_builder' ),
'type' => 'yes_no_button',
'option_category' => 'configuration',
'options' => array(
'on' => et_builder_i18n( 'On' ),
'off' => et_builder_i18n( 'Off' ),
),
'default' => 'on',
'toggle_slug' => 'elements',
'description' => esc_html__( 'Here you can choose whether the stock (displayed when product inventory is managed) should be visible or not', 'et_builder' ),
'mobile_options' => true,
'hover' => 'tabs',
),
'__add_to_cart' => array(
'type' => 'computed',
'computed_callback' => array(
'ET_Builder_Module_Woocommerce_Add_To_Cart',
'get_add_to_cart',
),
'computed_depends_on' => array(
'product',
'product_filter',
),
'computed_minimum' => array(
'product',
),
),
);
return $fields;
}
/**
* Get add to cart markup as string
*
* @since 4.4.0 Fixed compatibility w/ WooCommerce Product Add-ons
* @see https://github.com/elegantthemes/Divi/issues/19116
*
* @param array $args Additional arguments.
*
* @return string
*/
public static function get_add_to_cart( $args = array() ) {
return et_builder_wc_render_module_template(
'woocommerce_template_single_add_to_cart',
$args,
array( 'product', 'post' )
);
}
/**
* Gets the Button classname.
*
* @used-by ET_Builder_Module_Helper_Woocommerce_Modules::add_custom_button_icons()
*
* @return string
*/
public function get_button_classname() {
return 'single_add_to_cart_button';
}
/**
* Adds Multi view attributes to the Outer wrapper.
*
* Since we do not have control over the WooCommerce Breadcrumb markup, we inject Multi view
* attributes on to the Outer wrapper.
*
* @param array $outer_wrapper_attrs
*
* @return array
*/
public function add_multi_view_attrs( $outer_wrapper_attrs ) {
$multi_view = et_pb_multi_view_options( $this );
$multi_view_attrs = $multi_view->render_attrs(
array(
'classes' => array(
'et_pb_hide_input_quantity' => array(
'show_quantity' => 'off',
),
'et_pb_hide_stock' => array(
'show_stock' => 'off',
),
),
),
false,
null,
true
);
if ( $multi_view_attrs && is_array( $multi_view_attrs ) ) {
$outer_wrapper_attrs = array_merge( $outer_wrapper_attrs, $multi_view_attrs );
}
return $outer_wrapper_attrs;
}
/**
* Calculates any required additional CSS.
*
* Dropdown menu's Bottom & Left margin affects the Dropdown arrow placement.
* This is handled using additional CSS.
*
* @param array $attrs
* @param string $render_slug
*
* @since 4.3.4
*/
public function add_additional_css( $attrs, $render_slug ) {
if ( ! is_array( $attrs ) || empty( $attrs ) ) {
return;
}
$prop = 'dropdown_menus_custom_margin';
$values = et_pb_responsive_options()->get_property_values( $attrs, $prop );
$hover_value = et_pb_hover_options()->get_value( $prop, $attrs, '' );
$processed_values = array();
foreach ( $values as $device => $value ) {
if ( empty( $value ) ) {
continue;
}
$processed_values[ $device ] = $this->calculate_dropdown_arrow_margin( $value );
}
// Generate style for desktop, tablet, and phone.
et_pb_responsive_options()->declare_responsive_css(
$processed_values,
'%%order_class%% form.cart .variations td.value span:after',
$render_slug
);
}
/**
* Calculates Dropdown's arrow margin values.
*
* The Dropdown's arrow margin values depend on the actual
* Dropdown margin values.
*
* @since 4.3.4
*
* @param $value
*
* @return string
*/
public function calculate_dropdown_arrow_margin( $value ) {
$dropdown_margin = explode( '|', $value );
$dropdown_bottom_margin = empty( $dropdown_margin[2] ) ? '0px' : $dropdown_margin[2];
$dropdown_left_margin = empty( $dropdown_margin[3] ) ? '0px' : $dropdown_margin[3];
$declarations = array(
sprintf( 'margin-top: calc( 3px - %s )', $dropdown_bottom_margin ),
sprintf( 'right: calc( 10px - %s )', $dropdown_left_margin ),
);
// The last declaration wouldn't have the `;`. So appending manually.
return implode( ';', $declarations ) . ';';
}
/**
* Renders the module output.
*
* @param array $attrs List of attributes.
* @param string $content Content being processed.
* @param string $render_slug Slug of module that is used for rendering output.
*
* @return string
*/
public function render( $attrs, $content = null, $render_slug ) {
$multi_view = et_pb_multi_view_options( $this );
$use_focus_border_color = $this->props['use_focus_border_color'];
// Module classnames.
if ( 'on' !== $multi_view->get_value( 'show_quantity' ) ) {
$this->add_classname( 'et_pb_hide_input_quantity' );
}
if ( 'on' !== $multi_view->get_value( 'show_stock' ) ) {
$this->add_classname( 'et_pb_hide_stock' );
}
if ( 'on' === $use_focus_border_color ) {
$this->add_classname( 'et_pb_with_focus_border' );
}
ET_Builder_Module_Helper_Woocommerce_Modules::process_background_layout_data( $render_slug, $this );
ET_Builder_Module_Helper_Woocommerce_Modules::process_custom_button_icons( $render_slug, $this );
$this->add_classname( $this->get_text_orientation_classname() );
$this->add_additional_css( $this->props, $render_slug );
add_filter( "et_builder_module_{$render_slug}_outer_wrapper_attrs", array( $this, 'add_multi_view_attrs' ) );
$output = self::get_add_to_cart( $this->props );
// Render empty string if no output is generated to avoid unwanted vertical space.
if ( '' === $output ) {
return '';
}
return $this->_render_module_wrapper( $output, $render_slug );
}
}
new ET_Builder_Module_Woocommerce_Add_To_Cart();
| 42,647
|
https://github.com/NASA-LIS/lisf-test/blob/master/lis/core/LIS_initialize_registries.F90
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
lisf-test
|
NASA-LIS
|
Fortran Free Form
|
Code
| 536
| 1,870
|
!-----------------------BEGIN NOTICE -- DO NOT EDIT-----------------------
! NASA Goddard Space Flight Center Land Information System (LIS) v7.2
!
! Copyright (c) 2015 United States Government as represented by the
! Administrator of the National Aeronautics and Space Administration.
! All Rights Reserved.
!-------------------------END NOTICE -- DO NOT EDIT-----------------------
!BOP
!
! !ROUTINE: LIS_initialize_registries
! \label{LIS_initialize_registries}
!
! !REVISION HISTORY:
! 19 Aug 2010: Sujay Kumar; Initial specification
! 17 Jan 2011: David Mocko, added max/min greenness & slope type
!
! !INTERFACE:
subroutine LIS_initialize_registries()
! !USES:
use ESMF
use LIS_param_pluginMod, only : LIS_laisai_plugin,&
LIS_alb_plugin, LIS_gfrac_plugin , LIS_roughness_plugin,&
LIS_emissivity_plugin
use LIS_runmode_pluginMod, only : LIS_runmode_plugin
use LIS_dataassim_pluginMod, only : LIS_dataassim_plugin
use LIS_biasEstimation_pluginMod, only : LIS_biasEstimation_plugin
use LIS_optUEAlgorithm_pluginMod, only : LIS_optUEAlgorithm_plugin
! use LIS_optUEType_pluginMod, only : LIS_optUEType_plugin
use LIS_lsmoptue_pluginMod, only : LIS_lsmoptue_plugin
use LIS_PEobs_pluginMod, only : LIS_PEobs_plugin
use LIS_ObjFunc_pluginMod, only : LIS_ObjFunc_plugin
use LIS_RTM_pluginMod, only : LIS_RTM_plugin
use LIS_rtmoptue_pluginMod, only : LIS_rtmoptue_plugin
use LIS_lsmrtm_pluginMod, only : LIS_lsmrtm_plugin
use LIS_landslidemodel_pluginMod, only : LIS_landslidemodel_plugin
use LIS_routing_pluginMod, only : LIS_routing_plugin
use LIS_lsmrouting_pluginMod, only : LIS_lsmrouting_plugin
use LIS_irrigationmodel_pluginMod, only : LIS_irrigationmodel_plugin
use LIS_lsmirrigation_pluginMod, only : LIS_lsmirrigation_plugin
use LIS_runoffdata_pluginMod, only : LIS_runoffdata_plugin
use LIS_DAobs_pluginMod, only : LIS_DAobs_plugin
use LIS_lakemodel_pluginMod, only : LIS_lakemodel_plugin
use LIS_forecastAlg_pluginMod
use LIS_lsm_pluginMod
use LIS_glaciermodel_pluginMod
use LIS_glacierrouting_pluginMod
use LIS_lsmcpl_pluginMod
use LIS_lsmda_pluginMod
use LIS_perturb_pluginMod
!
! !DESCRIPTION:
!
! The code in this file initializes registries that set up the component plugin
! definitions.
!
! The routines invoked are:
! \begin{description}
! \item[LIS\_runmode\_plugin](\ref{LIS_runmode_plugin}) \newline
! sets up function table registries for implemented runmodes
! \item[LIS\_laisai\_plugin](\ref{LIS_laisai_plugin}) \newline
! sets up function table registries for implemented LAI/SAI data sources
! \item[LIS\_alb\_plugin](\ref{LIS_alb_plugin}) \newline
! sets up function table registries for implemented
! albedo data sources
! \item[LIS\_gfrac\_plugin](\ref{LIS_gfrac_plugin}) \newline
! sets up function table registries for implemented
! greenness fraction data sources
! \item[LIS\_optUEAlgorithm\_plugin](\ref{LIS_optUEAlgorithm_plugin}) \newline
! sets up function table registries for implemented
! parameter estimation algorithms
! %\item[LIS\_optUEType\_plugin](\ref{LIS_optUEType_plugin}) \newline
! % sets up function table registries for implemented
! % parameter estimation types
! \item[LIS\_lsmoptue\_plugin](\ref{LIS_lsmoptue_plugin}) \newline
! sets up function table registries for implemented
! lsm plugins related to parameter estimation
! \item[LIS\_PEobs\_plugin](\ref{LIS_PEobs_plugin}) \newline
! sets up function table registries for implemented
! plugins for objective space handling related to parameter estimation
! \item[LIS\_DAobs\_plugin](\ref{LIS_DAobs_plugin}) \newline
! sets up function table registries for implemented
! observation sources to be assimilated.
! \item[LIS\_lakemodel\_plugin] (\ref{LIS_lakemodel_plugin}) \newline
! sets up function table registries for implemented land surface models
! \item[LIS\_lsm\_plugin] (\ref{LIS_lsm_plugin}) \newline
! sets up function table registries for implemented land surface models
! \item[LIS\_lsmcpl\_plugin] (\ref{LIS_lsmcpl_plugin}) \newline
! sets up function table registries for implemented land surface models
! used in coupled modes
! \item[LIS\_lsmda\_plugin] (\ref{LIS_lsmda_plugin}) \newline
! sets up function table registries for land surface models used
! in data assimilation
! \item[LIS\_perturb\_plugin](\ref{LIS_perturb_plugin}) \newline
! sets up the function table registries for implemented
! perturbation algorithms
! \end{description}
!EOP
implicit none
call LIS_RTM_plugin
call LIS_lsm_plugin
call LIS_lsmcpl_plugin
call LIS_lsmda_plugin
call LIS_lsmrtm_plugin
call LIS_landslidemodel_plugin
call LIS_routing_plugin
call LIS_lsmrouting_plugin
call LIS_runmode_plugin
call LIS_laisai_plugin
call LIS_alb_plugin
call LIS_gfrac_plugin
call LIS_roughness_plugin
call LIS_emissivity_plugin
call LIS_dataassim_plugin
call LIS_biasestimation_plugin
call LIS_optUEAlgorithm_plugin
! call LIS_optUEType_plugin
call LIS_lsmoptue_plugin
call LIS_rtmoptue_plugin
call LIS_PEobs_plugin
call LIS_ObjFunc_plugin
call LIS_DAobs_plugin
call LIS_irrigationmodel_plugin
call LIS_lsmirrigation_plugin
call LIS_runoffdata_plugin
call LIS_lakemodel_plugin
call LIS_glaciermodel_plugin
call LIS_glacierrouting_plugin
call LIS_perturb_plugin
call LIS_forecastAlg_plugin
end subroutine LIS_initialize_registries
| 4,261
|
https://github.com/trungngotdt/CaesarCipher/blob/master/CaesarCipher/Cipher.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
CaesarCipher
|
trungngotdt
|
C#
|
Code
| 126
| 307
|
using System.Text;
namespace CaesarCipher
{
public class Cipher
{
private string plaintext;
private int k;
private string ciphertext;
public string Plaintext { get => plaintext; set => plaintext = value; }
public int K { get => k; set => k = value; }
public string Ciphertext { get => ciphertext; set => ciphertext = value; }
public Cipher()
{
}
public string Encrypt()
{
return Encrypt(Plaintext, K);
}
public string Decrypt()
{
return Encrypt(Ciphertext, -K);
}
private string Encrypt(string plaintext,int key)
{
string text = "";
var listchar = plaintext.ToCharArray();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < listchar.Length; i++)
{
builder.Append(convertChar(listchar[i], key));
}
return builder.ToString();
}
private char convertChar(char c,int key)
{
return (char)((int)c + key);
}
}
}
| 19,163
|
https://github.com/NumEricR/VR-Friends-Rankings/blob/master/core/config.php
|
Github Open Source
|
Open Source
|
WTFPL
| 2,012
|
VR-Friends-Rankings
|
NumEricR
|
PHP
|
Code
| 114
| 512
|
<?php
// Boats list to display
$BOATS = array(
/*
Exemple :
'BOAT_NAME' => array('navigator' => 'PLAYER_FIRSTNAME', 'id' => ID),
*/
);
define(PAGE_TITLE, 'Classement Vendée Globe - Virtual Regatta');
define(ERROR_MSG_MULTIPLES_TIMES_UPDATE,
'Les classements récupérés ne sont pas tous établis à la même heure.<br /><br />' .
'<a href="?a=refreshCache">Regénérez le classement général</a>');
define(ERROR_MSG_BOATS_LIST,
'<p>La liste des bateaux est erronée, vérifiez que vous avez bien configuré le fichier core/config.php.</p>' .
'<p>La variable "BOATS" doit être remplie selon le modèle suivant (en remplaçant les valeurs en majuscules) :' .
'<code>\'BOAT_NAME\' => array(\'navigator\' => \'PLAYER_FIRSTNAME\', \'id\' => ID),</code></p>');
define(VR_PROFIL_URL, 'http://www.virtualregatta.com/player.php?id_player=');
define(BOAT_RANKING_SEARCH_URL, 'http://vr-annexe.akroweb.fr/vg12.php');
define(LINE_CLASSNAME, 'boat');
define(SEARCH_FIELD_NAME, 'vrbateaucherche');
define(CACHE_LIFETIME, 900); // Time in seconds (ex 900s = 15min)
define(CACHE_FILE, 'cache/rankings.frg.html');
?>
| 48,058
|
https://github.com/sghill/msl/blob/master/tests/src/test/cpp/util/MslContextTest.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
msl
|
sghill
|
C++
|
Code
| 267
| 1,183
|
/**
* Copyright (c) 2016-2017 Netflix, Inc. 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 applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <crypto/Key.h>
#include <gtest/gtest.h>
#include <util/MslContext.h>
#include <entityauth/EntityAuthenticationScheme.h>
#include <crypto/Random.h>
#include <crypto/OpenSslLib.h>
#include <io/MslEncoderFormat.h>
#include <util/MockMslContext.h>
using namespace std;
using namespace testing;
using namespace netflix::msl::entityauth;
namespace netflix {
namespace msl {
namespace util {
class MslContextTest : public ::testing::Test
{
};
// ---- ReauthCode
TEST_F(MslContextTest, ReauthCode_Value)
{
EXPECT_EQ(MslContext::ReauthCode::entity_reauth, MslContext::ReauthCode::ENTITY_REAUTH);
EXPECT_EQ(MslContext::ReauthCode::entitydata_reauth, MslContext::ReauthCode::ENTITYDATA_REAUTH);
}
TEST_F(MslContextTest, ReauthCode_ValueOf)
{
EXPECT_EQ(MslContext::ReauthCode::ENTITY_REAUTH, MslContext::ReauthCode::entity_reauth);
EXPECT_EQ(MslContext::ReauthCode::ENTITYDATA_REAUTH, MslContext::ReauthCode::entitydata_reauth);
EXPECT_EQ(MslContext::ReauthCode::ENTITY_REAUTH,
MslContext::ReauthCode::valueOf(MslConstants::ResponseCode::ENTITY_REAUTH));
EXPECT_EQ(MslContext::ReauthCode::ENTITYDATA_REAUTH,
MslContext::ReauthCode::valueOf(MslConstants::ResponseCode::ENTITYDATA_REAUTH));
}
TEST_F(MslContextTest, ReauthCode_FromString)
{
EXPECT_EQ(MslContext::ReauthCode::ENTITY_REAUTH, MslContext::ReauthCode::fromString("ENTITY_REAUTH"));
EXPECT_EQ(MslContext::ReauthCode::ENTITYDATA_REAUTH, MslContext::ReauthCode::fromString("ENTITYDATA_REAUTH"));
EXPECT_THROW(MslContext::ReauthCode::fromString("FOO"), IllegalArgumentException);
}
TEST_F(MslContextTest, ReauthCode_ToString)
{
EXPECT_EQ("ENTITY_REAUTH", MslContext::ReauthCode::ENTITY_REAUTH.toString());
EXPECT_EQ("ENTITYDATA_REAUTH", MslContext::ReauthCode::ENTITYDATA_REAUTH.toString());
}
// ---- end ReauthCode
TEST_F(MslContextTest, getTime)
{
MockMslContext ctx(EntityAuthenticationScheme::PSK, false);
ASSERT_GT(ctx.getTime(), 1461629597783ll);
}
TEST_F(MslContextTest, Random)
{
const crypto::SecretKey nullKey;
MockMslContext ctx(EntityAuthenticationScheme::PSK, false);
const size_t SIZE = 64;
// generate two random sequences and just test they are not equal
std::vector<uint8_t> bytes1(SIZE), bytes2(SIZE);
ctx.getRandom()->nextBytes(bytes1);
EXPECT_EQ(SIZE, bytes1.size());
ctx.getRandom()->nextBytes(bytes2);
EXPECT_EQ(SIZE, bytes2.size());
EXPECT_NE(bytes1, bytes2);
}
TEST_F(MslContextTest, equals)
{
shared_ptr<MslContext> ctx1 = make_shared<MockMslContext>(EntityAuthenticationScheme::PSK, false);
shared_ptr<MslContext> ctx2 = make_shared<MockMslContext>(EntityAuthenticationScheme::PSK, false);
EXPECT_TRUE(ctx1->equals(ctx1));
EXPECT_TRUE(ctx2->equals(ctx2));
EXPECT_FALSE(ctx1->equals(ctx2));
EXPECT_FALSE(ctx2->equals(ctx1));
}
} /* namespace util */
} /* namespace msl */
} /* namespace netflix */
| 16,585
|
https://github.com/borbalher/core-ui-tools/blob/master/src/common/core/normalizer/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
core-ui-tools
|
borbalher
|
JavaScript
|
Code
| 263
| 934
|
class Normalizer
{
constructor(composer, coreString)
{
this.composer = composer
this.coreString = coreString
}
denormalize(data, schemaName, entities)
{
const schema = this.composer.composeSchema(schemaName)
let dto = {}
for(const attribute in schema)
{
const
isEntity = this.isEntity(schema[attribute].schema),
isCollection = schema[attribute].collection,
type = schema[attribute].type
if(type === 'schema' && isEntity && isCollection)
{
dto[attribute] = []
for(const entityId of data[attribute])
{
const entity = this.getEntity(entities, schema[attribute].schema, entityId)
if(entity)
dto[attribute] = [...dto[attribute], this.denormalize(entity, schema[attribute].schema, entities)]
}
}
else if(type === 'schema' && isEntity)
{
const
entityId = data[attribute],
entity = this.getEntity(entities, schema[attribute].schema, entityId)
dto[attribute] = entityId ? this.denormalize(entity, schema[attribute].schema, entities) : undefined
}
else
{
dto[attribute] = data[attribute]
}
}
return dto
}
getEntityType(schemaName)
{
const match = /entity\/(.+)/.exec(schemaName)
if(match)
return this.coreString.camelCase(match[1])
}
isEntity(schemaName)
{
const match = /entity\/(.+)/.exec(schemaName)
return !!match
}
addEntity(entities, schemaName, entity)
{
const type = this.getEntityType(schemaName)
if(!entities[type])
entities[type] = { byId: {}, allIds: [] }
entities[type].byId[entity.id] = entity
entities[type].allIds = [...entities[type].allIds, entity.id]
return entities
}
getEntity(entities, schemaName, id)
{
const type = this.getEntityType(schemaName)
if(entities[type] && entities[type].byId[id])
return entities[type].byId[id]
return null
}
normalize(data, schemaName, entities = {})
{
const schema = this.composer.composeSchema(schemaName)
let dto = {}
for(const attribute in schema)
{
const
isEntity = this.isEntity(schema[attribute].schema),
isCollection = !!schema[attribute].collection,
type = schema[attribute].type
if(type === 'schema' && isEntity && isCollection)
{
dto[attribute] = []
for(const entity of data[attribute])
{
this.normalize(entity, schema[attribute].schema, entities)
dto[attribute] = [...dto[attribute], entity.id]
}
}
else if(type === 'schema' && isEntity)
{
const entity = data[attribute]
if(entity)
this.normalize(entity, schema[attribute].schema, entities)
dto[attribute] = entity ? entity.id : undefined
}
else
{
dto[attribute] = data[attribute]
}
}
this.addEntity(entities, schemaName, dto)
return entities
}
}
module.exports = Normalizer
| 44,074
|
https://github.com/benzap/ketornah/blob/master/dist/out/ketornah_client/search.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ketornah
|
benzap
|
JavaScript
|
Code
| 256
| 2,525
|
// Compiled by ClojureScript 1.9.495 {}
goog.provide('ketornah_client.search');
goog.require('cljs.core');
goog.require('cuerdas.core');
goog.require('clojure.string');
goog.require('ketornah_client.sql');
goog.require('ketornah_client.utils');
ketornah_client.search.init_food_cost = (function ketornah_client$search$init_food_cost(food){
return cljs.core.assoc.call(null,food,new cljs.core.Keyword(null,"cost","cost",-1094861735),1.0);
});
ketornah_client.search.search_terms = (function ketornah_client$search$search_terms(search_text){
var cleaned_text = cuerdas.core.strip.call(null,cuerdas.core.replace.call(null,cuerdas.core.replace.call(null,search_text,/'/,""),/\s+|[^a-zA-Z]+/," "));
return cljs.core.set.call(null,cljs.core.conj.call(null,cuerdas.core.split.call(null,cleaned_text),cleaned_text));
});
ketornah_client.search._STAR__cost = (function ketornah_client$search$_STAR__cost(food,ratio){
return cljs.core.update_in.call(null,food,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"cost","cost",-1094861735)], null),cljs.core._STAR_,ratio);
});
ketornah_client.search.modifier_starts_with = (function ketornah_client$search$modifier_starts_with(p__41260,search_term){
var map__41263 = p__41260;
var map__41263__$1 = ((((!((map__41263 == null)))?((((map__41263.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__41263.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__41263):map__41263);
var food = map__41263__$1;
var name = cljs.core.get.call(null,map__41263__$1,new cljs.core.Keyword(null,"name","name",1843675177));
if(cljs.core.truth_(cuerdas.core.starts_with_QMARK_.call(null,cuerdas.core.lower.call(null,name),[cljs.core.str.cljs$core$IFn$_invoke$arity$1(cuerdas.core.lower.call(null,search_term)),cljs.core.str.cljs$core$IFn$_invoke$arity$1(",")].join('')))){
return ketornah_client.search._STAR__cost.call(null,food,1.5);
} else {
if(cljs.core.truth_(cuerdas.core.starts_with_QMARK_.call(null,cuerdas.core.lower.call(null,name),[cljs.core.str.cljs$core$IFn$_invoke$arity$1(cuerdas.core.lower.call(null,search_term))].join('')))){
return ketornah_client.search._STAR__cost.call(null,food,1.3);
} else {
return ketornah_client.search._STAR__cost.call(null,food,1.0);
}
}
});
ketornah_client.search.modifier_index_of = (function ketornah_client$search$modifier_index_of(p__41265,search_term){
var map__41268 = p__41265;
var map__41268__$1 = ((((!((map__41268 == null)))?((((map__41268.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__41268.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__41268):map__41268);
var food = map__41268__$1;
var name = cljs.core.get.call(null,map__41268__$1,new cljs.core.Keyword(null,"name","name",1843675177));
var temp__4655__auto__ = clojure.string.index_of.call(null,name,search_term,(1));
if(cljs.core.truth_(temp__4655__auto__)){
var idx = temp__4655__auto__;
return ketornah_client.search._STAR__cost.call(null,food,(1.0 + (0.2 * ((cljs.core.count.call(null,name) - idx) / cljs.core.count.call(null,name)))));
} else {
return ketornah_client.search._STAR__cost.call(null,food,1.0);
}
});
ketornah_client.search.apply_modifiers = (function ketornah_client$search$apply_modifiers(food,search_term){
return ketornah_client.search.modifier_index_of.call(null,ketornah_client.search.modifier_starts_with.call(null,food,search_term),search_term);
});
ketornah_client.search.search_text_cost = (function ketornah_client$search$search_text_cost(food,search_text){
var search_terms = ketornah_client.search.search_terms.call(null,search_text);
var new_cost = cljs.core.apply.call(null,cljs.core._STAR_,cljs.core.map.call(null,new cljs.core.Keyword(null,"cost","cost",-1094861735),cljs.core.map.call(null,((function (search_terms){
return (function (p1__41270_SHARP_){
return ketornah_client.search.apply_modifiers.call(null,food,p1__41270_SHARP_);
});})(search_terms))
,search_terms,search_terms)));
return cljs.core.assoc.call(null,food,new cljs.core.Keyword(null,"cost","cost",-1094861735),new_cost);
});
ketornah_client.search.sort_search_items = (function ketornah_client$search$sort_search_items(search_items){
return cljs.core.reverse.call(null,cljs.core.sort_by.call(null,new cljs.core.Keyword(null,"cost","cost",-1094861735),search_items));
});
ketornah_client.search.process_costs = (function ketornah_client$search$process_costs(search_items,search_text){
return ketornah_client.search.sort_search_items.call(null,cljs.core.map.call(null,(function (p1__41271_SHARP_){
return ketornah_client.search.search_text_cost.call(null,p1__41271_SHARP_,search_text);
}),cljs.core.map.call(null,ketornah_client.search.init_food_cost,search_items)));
});
ketornah_client.search.update_food_search = (function ketornah_client$search$update_food_search(app_state,text){
ketornah_client.utils.set_title_BANG_.call(null,[cljs.core.str.cljs$core$IFn$_invoke$arity$1("Keto or Nah? - Search - "),cljs.core.str.cljs$core$IFn$_invoke$arity$1(text)].join(''));
cljs.core.swap_BANG_.call(null,app_state,cljs.core.merge,new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"querying?","querying?",1078116512),true,new cljs.core.Keyword(null,"search-items","search-items",731653300),cljs.core.PersistentVector.EMPTY,new cljs.core.Keyword(null,"search-text","search-text",1559451259),text], null));
return window.setTimeout((function (){
ketornah_client.utils.wait_for_database.call(null,app_state);
var map__41274 = cljs.core.deref.call(null,app_state);
var map__41274__$1 = ((((!((map__41274 == null)))?((((map__41274.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__41274.cljs$core$ISeq$)))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__41274):map__41274);
var database = cljs.core.get.call(null,map__41274__$1,new cljs.core.Keyword(null,"database","database",1849087575));
console.time("Search Query");
cljs.core.swap_BANG_.call(null,app_state,cljs.core.merge,new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"search-items","search-items",731653300),ketornah_client.search.process_costs.call(null,ketornah_client.sql.search_food.call(null,database,text),text),new cljs.core.Keyword(null,"querying?","querying?",1078116512),false], null));
return console.timeEnd("Search Query");
}),(600));
});
| 16,734
|
https://github.com/forki/hs-art-extractor/blob/master/HsArtExtractor/Unity/Objects/CardDef.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
hs-art-extractor
|
forki
|
C#
|
Code
| 289
| 972
|
using System;
using System.IO;
using HsArtExtractor.Util;
namespace HsArtExtractor.Unity.Objects
{
public class CardDef
{
public FilePointer GameObject { get; private set; }
public bool Enabled { get; private set; }
public FilePointer MonoScript { get; private set; }
public string Name { get; private set; }
public string PortratitTexturePath { get; private set; }
public string PremiumPortraitMaterialPath { get; private set; }
public string PremiumPortraitTexturePath { get; private set; }
public FilePointer DeckCardBarPortrait { get; private set; }
public FilePointer EnchantmentPortrait { get; private set; }
public FilePointer HistoryTileHalfPortrait { get; private set; }
public FilePointer HistoryTileFullPortrait { get; private set; }
public bool FailedToLoad { get; private set; } = false;
public CardDef(BinaryBlock b)
{
GameObject = new FilePointer(b.ReadInt(), b.ReadLong());
Enabled = b.ReadUnsignedByte() == 1 ? true : false;
b.Align(4);
MonoScript = new FilePointer(b.ReadInt(), b.ReadLong());
try
{
var unknown = b.ReadInt();
int size = b.ReadInt();
PortratitTexturePath = b.ReadFixedString(size);
b.Align(4);
size = b.ReadInt();
PremiumPortraitMaterialPath = b.ReadFixedString(size);
b.Align(4);
var unknown2 = b.ReadInt();
DeckCardBarPortrait = new FilePointer(b.ReadInt(), b.ReadLong());
EnchantmentPortrait = new FilePointer(b.ReadInt(), b.ReadLong());
HistoryTileHalfPortrait = new FilePointer(b.ReadInt(), b.ReadLong());
HistoryTileFullPortrait = new FilePointer(b.ReadInt(), b.ReadLong());
// Ignore rest of the file
}
catch (Exception e)
{
Logger.Log(LogLevel.DEBUG, $"CardDef Load failed {GameObject.PathID}, {MonoScript.PathID} ({e.Message})");
FailedToLoad = true;
}
}
public override string ToString()
{
return string.Format("Name: '{0}' Tex: '{1}'", PortratitTexturePath);
}
public void Save(string dir, string name = "default")
{
string outFile = Name;
if (string.IsNullOrEmpty(Name))
outFile = name;
outFile = StringUtils.GetFilenameNoOverwrite(
Path.Combine(dir, outFile + ".txt"));
using (StreamWriter sw = new StreamWriter(outFile, false))
{
sw.WriteLine("CardDef");
sw.WriteLine("\tGameObject: " + GameObject);
sw.WriteLine("\tName: " + Name);
sw.WriteLine("\tPortraitTexPath: " + PortratitTexturePath);
sw.WriteLine("\tPremiumMat: " + PremiumPortraitMaterialPath);
sw.WriteLine("\tPremiumTex: " + PremiumPortraitTexturePath);
sw.WriteLine("\tDeckCardBar: " + DeckCardBarPortrait);
sw.WriteLine("\tEnchantPortrait: " + EnchantmentPortrait);
sw.WriteLine("\tHistoryTileHalfPortrait: " + HistoryTileHalfPortrait);
sw.WriteLine("\tHistoryTileFullPortrait: " + HistoryTileFullPortrait);
}
}
}
}
| 13,993
|
https://github.com/CodingSpiderFox/daycaptain-systemtest/blob/master/src/test/java/com/daycaptain/systemtest/backend/daytasks/CreateDayTaskTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
daycaptain-systemtest
|
CodingSpiderFox
|
Java
|
Code
| 327
| 1,628
|
package com.daycaptain.systemtest.backend.daytasks;
import com.daycaptain.systemtest.backend.CollectionUtils;
import com.daycaptain.systemtest.backend.DayCaptainSystem;
import com.daycaptain.systemtest.backend.entity.Task;
import org.junit.jupiter.api.Test;
import org.threeten.extra.YearWeek;
import java.net.URI;
import java.time.LocalDate;
import java.util.List;
import static com.daycaptain.systemtest.backend.CollectionUtils.findTask;
import static org.assertj.core.api.Assertions.assertThat;
public class CreateDayTaskTest {
private final DayCaptainSystem dayCaptain = new DayCaptainSystem();
@Test
void testCreateDayTask() {
LocalDate date = LocalDate.of(2020, 5, 9);
URI taskId = dayCaptain.createDayTask("New task", date);
assertThat(taskId).isNotNull();
List<Task> tasks = dayCaptain.getDay(date).tasks;
Task task = CollectionUtils.findTask(tasks, taskId);
assertThat(task.string).isEqualTo("New task");
assertThat(task.note).isNull();
assertThat(task.assignedFromWeekTask).isNull();
assertThat(task.project).isNull();
assertThat(task.area).isNull();
assertThat(task.relatedProject).isNull();
assertThat(task.relatedArea).isNull();
assertThat(tasks.size()).isGreaterThan(2);
assertThat(task.priority).isEqualTo(tasks.size());
}
@Test
void testCreatePrioritizedDayTask() {
LocalDate date = LocalDate.of(2020, 5, 9);
URI taskId = dayCaptain.createDayTask("New task", date, true);
assertThat(taskId).isNotNull();
List<Task> tasks = dayCaptain.getDay(date).tasks;
Task task = CollectionUtils.findTask(tasks, taskId);
assertThat(tasks.size()).isGreaterThan(2);
assertThat(task.priority).isEqualTo(1);
}
@Test
void testCreateDayTaskAssignedFromRelatedProject() {
Task weekTask = findTask(dayCaptain.getWeek(YearWeek.of(2020, 19)).tasks, "Working on my project");
int assignedTaskSize = weekTask.assignedTasks.size();
LocalDate date = LocalDate.of(2020, 5, 9);
URI taskId = dayCaptain.createDayTask("New task, assigned from week task", date, weekTask);
assertThat(taskId).isNotNull();
Task task = findTask(dayCaptain.getDay(date).tasks, taskId);
assertThat(task.string).isEqualTo("New task, assigned from week task");
assertThat(task.assignedFromWeekTask).isEqualTo(weekTask._self);
assertThat(task.project).isNull();
assertThat(task.area).isNull();
assertThat(task.relatedProject).isEqualTo("Business idea");
assertThat(task.relatedArea).isEqualTo("Business");
weekTask = findTask(dayCaptain.getWeek(YearWeek.of(2020, 19)).tasks, "Working on my project");
assertThat(weekTask.assignedTasks).hasSize(assignedTaskSize + 1);
}
@Test
void testCreateDayTaskWithArea() {
Task weekTask = findTask(dayCaptain.getWeek(YearWeek.of(2020, 19)).tasks, "Something");
int assignedTaskSize = weekTask.assignedTasks.size();
LocalDate date = LocalDate.of(2020, 5, 9);
URI taskId = dayCaptain.createDayTaskWithArea("New task, with area", date, 60, "IT work", weekTask, false);
assertThat(taskId).isNotNull();
Task task = findTask(dayCaptain.getDay(date).tasks, taskId);
assertThat(task.string).isEqualTo("New task, with area");
assertThat(task.assignedFromWeekTask).isEqualTo(weekTask._self);
assertThat(task.project).isNull();
assertThat(task.area).isEqualTo("IT work");
assertThat(task.relatedProject).isNull();
assertThat(task.relatedArea).isEqualTo("IT work");
weekTask = findTask(dayCaptain.getWeek(YearWeek.of(2020, 19)).tasks, "Something");
assertThat(weekTask.assignedTasks).hasSize(assignedTaskSize + 1);
}
@Test
void testCreateDayTaskWithProject() {
Task weekTask = findTask(dayCaptain.getWeek(YearWeek.of(2020, 19)).tasks, "Something");
int assignedTaskSize = weekTask.assignedTasks.size();
LocalDate date = LocalDate.of(2020, 5, 9);
URI taskId = dayCaptain.createDayTaskWithProject("New task, with project", date, 60, "Business idea", weekTask, false);
assertThat(taskId).isNotNull();
Task task = findTask(dayCaptain.getDay(date).tasks, taskId);
assertThat(task.string).isEqualTo("New task, with project");
assertThat(task.assignedFromWeekTask).isEqualTo(weekTask._self);
assertThat(task.area).isNull();
assertThat(task.project).isEqualTo("Business idea");
assertThat(task.relatedArea).isEqualTo("Business");
assertThat(task.relatedProject).isEqualTo("Business idea");
weekTask = findTask(dayCaptain.getWeek(YearWeek.of(2020, 19)).tasks, "Something");
assertThat(weekTask.assignedTasks).hasSize(assignedTaskSize + 1);
}
@Test
void testCreateDayTaskWithNote() {
LocalDate date = LocalDate.of(2020, 5, 9);
URI taskId = dayCaptain.createDayTaskWithNote("New task, with note", date, "A note");
assertThat(taskId).isNotNull();
List<Task> tasks = dayCaptain.getDay(date).tasks;
Task task = CollectionUtils.findTask(tasks, taskId);
assertThat(task.string).isEqualTo("New task, with note");
assertThat(task.note).isEqualTo("A note");
assertThat(task.assignedFromWeekTask).isNull();
assertThat(task.project).isNull();
assertThat(task.area).isNull();
assertThat(task.relatedProject).isNull();
assertThat(task.relatedArea).isNull();
}
}
| 48,040
|
https://github.com/PichuChen/covid-19-taiwan-cdc-data/blob/master/fetch_inspections_summary.js
|
Github Open Source
|
Open Source
|
MIT
| null |
covid-19-taiwan-cdc-data
|
PichuChen
|
JavaScript
|
Code
| 62
| 553
|
// https://docs.google.com/spreadsheets/u/0/d/e/2CAIWO3el-HmgYwUDCtPq_lRifv9VeS5De_q1mFXBFN3IdI8fo4s9imGUqQGBwxlo-ETfBD_zxsbRQoCRyMg/gviz/chartiframe?oid=711912240
data = JSON.parse(chartData.chart.chartJson)
rows = data.dataTable.rows
時間標籤 = rows.map(function(it){return it.c[0].f})
嚴重特殊傳染性肺炎通報 = rows.map(function(it){return it.c[1].v})
居家檢疫送驗 = rows.map(function(it){return it.c[2].v})
疑似新冠病毒感染送驗 = rows.map(function(it){return it.c[3].v})
text嚴重特殊傳染性肺炎通報 = JSON.stringify(嚴重特殊傳染性肺炎通報, null, 20)
text居家檢疫送驗 = JSON.stringify(居家檢疫送驗, null, 20)
text疑似新冠病毒感染送驗 = JSON.stringify(疑似新冠病毒感染送驗, null, 20)
inspections_summary = {
date: (new Date()).toISOString(),
data: {
'嚴重特殊傳染性肺炎通報': 嚴重特殊傳染性肺炎通報,
'居家檢疫送驗': 居家檢疫送驗,
'疑似新冠病毒感染送驗': 疑似新冠病毒感染送驗,
},
labels: 時間標籤
}
text_inspections_summary = JSON.stringify(inspections_summary, null, 4)
| 4,871
|
https://github.com/jamesvillarrubia/mtc-api/blob/master/database/factories/ModelFactory.php
|
Github Open Source
|
Open Source
|
MIT
| null |
mtc-api
|
jamesvillarrubia
|
PHP
|
Code
| 127
| 406
|
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => bcrypt(str_random(10)),
'remember_token' => str_random(10),
];
});
$factory->define(App\Lesson::class, function (Faker\Generator $faker) {
$text = $faker->paragraph(3);
$html = '<p>'.$text.'</p>';
return [
'text' => $text,
'html' => $html,
'title'=> $faker->sentence(4),
'time'=> $faker->time('H:i:s','24:59:59')
];
});
$factory->define(App\Question::class, function (Faker\Generator $faker) {
$text = $faker->paragraph(2);
return [
'text' => $text,
];
});
$factory->define(App\ShortAnswer::class, function (Faker\Generator $faker) {
$text = $faker->paragraph(2);
return [
'text' => $text,
'rating' => $faker->numberBetween(700,1300),
];
});
| 8,815
|
https://github.com/zlike/overreact-core/blob/master/packages/demo/src/components/people-container.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
overreact-core
|
zlike
|
JavaScript
|
Code
| 77
| 221
|
import React, { useMemo } from 'react';
import {
useFetch,
useDataRefId,
} from '@microsoft/overreact';
import { peopleSpec } from '../hooks/people-spec';
import { PeopleView } from './people-view';
export function PeopleContainer(props) {
const { userName } = props;
const dataRefId = useDataRefId();
const variables = useMemo(() => ({
locator: {
descriptor: { people: userName },
order: ['people'],
},
}), [userName]);
const [data] = useFetch(dataRefId, peopleSpec, variables);
return (data ? (
<PeopleView
firstName={data.FirstName}
lastName={data.LastName}
address={data.AddressInfo[0]}
/>
) : null);
}
| 15,834
|
https://github.com/g-bridge-etners/admin-web/blob/master/routes/main.js
|
Github Open Source
|
Open Source
|
MIT
| null |
admin-web
|
g-bridge-etners
|
JavaScript
|
Code
| 208
| 768
|
const express = require('express');
const ejs = require('ejs');
const fs = require('fs');
const router = express.Router();
const connection = require('../models/connection')
const moment = require('moment');
const { RateLimiter } = require('limiter');
require('moment-timezone');
moment.tz.setDefault("Asia/Seoul");
const GetMainUI = (req, res) => {
let htmlstream = '';
htmlstream = fs.readFileSync(__dirname + '/../views/header.ejs', 'utf8');
htmlstream = htmlstream + fs.readFileSync(__dirname + '/../views/nav.ejs', 'utf8');
htmlstream = htmlstream + fs.readFileSync(__dirname + '/../views/report.ejs', 'utf8');
htmlstream = htmlstream + fs.readFileSync(__dirname + '/../views/footer.ejs', 'utf8');
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf8' });
res.write('<meta charset=utf8>');
var sql_str = "select * from gb_user as u inner join gb_commute as t on t.c_employee_number = u.u_employee_number ;";
connection.query(sql_str , (error, results, fields) => {
if (error) {
res.status(1064).end(" Can not insert data to DB. ");
} else {
for(var i=0; i < results.length; i++){
console.log( moment(results[i].c_date).format("YYYY년 MM월 DD일") );
results[i].c_date = moment(results[i].c_date).format('YYYY년 MM월 DD일');
var now = moment();
var since_hour = moment.duration(now.diff(results[i].c_clock_in)).hours();
var rate = new Array();
rate[i] = (since_hour / 9) * 100;
if (rate[i] > 100 || results[i].c_status == '퇴근완료'){
rate[i] = 100;
}
rate[i] = Math.round(rate[i]);
console.log(rate[i]);
results[i].rate = rate[i];
results[i].c_clock_in = moment(results[i].c_clock_in).format('LTS');
if (results[i].c_status =='출근중'){
results[i].c_clock_out = moment(results[i].c_clock_out).format(' ');
}else{
results[i].c_clock_out = moment(results[i].c_clock_out).format('LTS');
}
}
res.end(ejs.render(htmlstream, {
title: 'Eteners Admin',
data: results
}));
}
});
};
router.get('/', GetMainUI);
module.exports = router
| 25,100
|
https://github.com/bm98/GLCD_FontCreator/blob/master/GLCD_FontCreator/GDI/gdiDrawing.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
GLCD_FontCreator
|
bm98
|
C#
|
Code
| 243
| 539
|
/*
Part of GLCD_FontCreator - Copyright 2015 Martin Burri
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 License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace GLCD_FontCreator.GDI
{
class gdiDrawing
{
/*** CURENTLY NOT USED ***/
public static void RenderText( IDeviceContext hdc, string text, string fontFamily, Color color, Rectangle region, float size )
{
// create the handle of DC
var h = new HandleRef (null, hdc.GetHdc ());
// create the font
int emsize = - gdiNative.MulDiv ((int)size, gdiNative.GetDeviceCaps (h, gdiNative.LOGPIXELSY), 72);
var p = new HandleRef (null, gdiNative.CreateFont (emsize, 0, 0, 0, 0, 0, 0, 0, 1/*Ansi_encoding*/, 0, 0, 4, 0, fontFamily));
try {
// use the font in the DC
gdiNative.SelectObject( h, p.Handle );
// set the background to transparent
gdiNative.SetBkMode( h, 1 );
// set the color of the text
gdiNative.SetTextColor( h, color );
// draw the text to the region
gdiNative.DrawText( h, text, region, 0x0100 );
}
finally {
// release the resources
gdiNative.DeleteObject( p );
hdc.ReleaseHdc( );
}
}
}
}
| 15,101
|
https://github.com/pablodavid97/tutoring-api/blob/master/src/controllers/profesor.controller.js
|
Github Open Source
|
Open Source
|
MIT
| null |
tutoring-api
|
pablodavid97
|
JavaScript
|
Code
| 79
| 230
|
const database = require('../models/connection-manager');
const { logger } = require('../utils/logger');
const profesor = database.profesor;
const profesorController = {};
// SELECT *
profesorController.find = async () => {
try {
const prof = await profesor.findAll();
return prof;
} catch (error) {
logger.error(error.message);
}
};
profesorController.insertProfesor = async (userId, carrera) => {
try {
await profesor.create(
{
id: userId,
usuarioId: userId,
carreraId: carrera
},
{
fields: ['id', 'usuarioId', 'carreraId']
}
);
} catch (error) {
logger.error(error.message);
}
};
module.exports = profesorController;
| 32,251
|
https://github.com/maxschwe/PiCar/blob/master/pi/robot/servo.py
|
Github Open Source
|
Open Source
|
MIT
| null |
PiCar
|
maxschwe
|
Python
|
Code
| 75
| 294
|
import RPi.GPIO as GPIO
import time
from .robot_config import Config
class Servo:
def __init__(self, pin, init_pos=0):
self.pin = pin
self.cur_angle = init_pos
GPIO.setup(self.pin, GPIO.OUT)
self.out = GPIO.PWM(self.pin, 50)
self.init(init_pos)
def _conv_deg_duty(self, deg):
return Config.SERVO_Y_INTERCEPT + deg * Config.SERVO_M
def init(self, deg):
self.out.start(0)
self.move(deg, delay=1)
def move(self, deg, delay=None):
if delay is None:
delay = abs(deg - self.cur_angle) / 180
duty = self._conv_deg_duty(deg)
self.out.ChangeDutyCycle(duty)
time.sleep(delay)
self.out.ChangeDutyCycle(0)
self.cur_angle = deg
def test(self):
for i in range(180):
self.move(i)
| 48,754
|
https://github.com/xenois/overlap2d-runtime-libgdx/blob/master/src/com/uwsoft/editor/renderer/systems/action/data/ParallelData.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
overlap2d-runtime-libgdx
|
xenois
|
Java
|
Code
| 31
| 97
|
package com.uwsoft.editor.renderer.systems.action.data;
/**
* Created by ZeppLondon on 10/23/15.
*/
public class ParallelData extends ActionData {
public ActionData[] actionDatas;
public boolean complete;
public ParallelData(ActionData[] actionDatas) {
this.actionDatas = actionDatas;
}
}
| 13,105
|
https://github.com/JetBrains/intellij-community/blob/master/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/types/DfJvmIntegralType.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
intellij-community
|
JetBrains
|
Java
|
Code
| 413
| 1,567
|
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection.dataFlow.types;
import com.intellij.codeInspection.dataFlow.jvm.JvmPsiRangeSetUtil;
import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet;
import com.intellij.codeInspection.dataFlow.value.RelationType;
import com.intellij.psi.PsiPrimitiveType;
import com.intellij.psi.PsiTypes;
import com.intellij.psi.util.TypeConversionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Represents a JVM integral primitive (int or long)
*/
public interface DfJvmIntegralType extends DfIntegralType, DfPrimitiveType {
/**
* Cast this type to the specified primitive type
* @param type target type
* @return result of the cast
*/
@Override
default @NotNull DfType castTo(@NotNull PsiPrimitiveType type) {
if (getConstantOfType(Object.class) != null) {
return DfPrimitiveType.super.castTo(type);
}
if (type.equals(PsiTypes.doubleType()) || type.equals(PsiTypes.floatType())) {
// No widening support for doubles, so we translate the wide range
// to avoid diverged states if (int)(double)x cast is performed
LongRangeSet range = getWideRange();
if (range.isEmpty()) return DfType.BOTTOM;
return type.equals(PsiTypes.doubleType()) ?
DfTypes.doubleRange(range.min(), range.max()) :
DfTypes.floatRange(range.min(), range.max());
}
if (!TypeConversionUtil.isIntegralNumberType(type)) {
return DfPrimitiveType.super.castTo(type);
}
LongRangeSet range = JvmPsiRangeSetUtil.castTo(getRange(), type);
LongRangeSet wideRange = JvmPsiRangeSetUtil.castTo(getWideRange(), type);
return type.equals(PsiTypes.longType()) ? DfTypes.longRange(range, wideRange) : DfTypes.intRange(range, wideRange);
}
@Override
@NotNull
default DfType fromRelation(@NotNull RelationType relationType) {
if (relationType == RelationType.IS || relationType == RelationType.IS_NOT) {
return DfType.TOP;
}
return DfTypes.rangeClamped(getRange().fromRelation(relationType), getLongRangeType());
}
@Override
default boolean isSuperType(@NotNull DfType other) {
if (other == DfType.BOTTOM) return true;
if (!(other instanceof DfIntegralType integralType)) return false;
if (integralType.getLongRangeType() != getLongRangeType()) return false;
return getRange().contains(integralType.getRange()) &&
getWideRange().contains(integralType.getWideRange());
}
@NotNull
@Override
default DfType join(@NotNull DfType other) {
if (other == DfType.BOTTOM) return this;
if (!(other instanceof DfIntegralType)) return DfType.TOP;
if (((DfIntegralType)other).getLongRangeType() != getLongRangeType()) return DfType.TOP;
LongRangeSet range = ((DfIntegralType)other).getRange().join(getRange());
LongRangeSet wideRange = ((DfIntegralType)other).getWideRange().join(getWideRange());
return DfTypes.range(range, wideRange, getLongRangeType());
}
@Override
default @Nullable DfType tryJoinExactly(@NotNull DfType other) {
if (other == DfType.BOTTOM) return this;
if (other == DfType.TOP) return other;
if (!(other instanceof DfIntegralType)) return null;
if (((DfIntegralType)other).getLongRangeType() != getLongRangeType()) return null;
LongRangeSet range = ((DfIntegralType)other).getRange().tryJoinExactly(getRange());
LongRangeSet wideRange = ((DfIntegralType)other).getWideRange().tryJoinExactly(getWideRange());
if (range == null || wideRange == null) return null;
return DfTypes.range(range, wideRange, getLongRangeType());
}
@NotNull
@Override
default DfType meet(@NotNull DfType other) {
if (other == DfType.TOP) return this;
if (!(other instanceof DfIntegralType)) return DfType.BOTTOM;
if (((DfIntegralType)other).getLongRangeType() != getLongRangeType()) return DfType.BOTTOM;
LongRangeSet range = ((DfIntegralType)other).getRange().meet(getRange());
LongRangeSet wideRange = ((DfIntegralType)other).getWideRange().meet(getWideRange());
return DfTypes.range(range, wideRange, getLongRangeType());
}
@NotNull
@Override
default DfType meetRange(@NotNull LongRangeSet range) {
LongRangeSet resultRange = range.meet(getRange());
LongRangeSet wideRange = range.meet(getWideRange());
return DfTypes.range(resultRange, wideRange, getLongRangeType());
}
@Override
default DfType widen() {
LongRangeSet wideRange = getWideRange();
return wideRange.equals(getRange()) ? this : DfTypes.range(wideRange, null, getLongRangeType());
}
@Nullable
@Override
default DfType tryNegate() {
LongRangeSet range = getRange();
LongRangeSet res = getLongRangeType().fullRange().subtract(range);
return res.intersects(range) ? null : DfTypes.range(res, null, getLongRangeType());
}
}
| 10,102
|
https://github.com/dgant/PurpleWave/blob/master/src/Planning/Plans/GamePlans/Protoss/Standard/PvZ/ProtossVsZerg.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
PurpleWave
|
dgant
|
Scala
|
Code
| 30
| 145
|
package Planning.Plans.GamePlans.Protoss.Standard.PvZ
import Planning.Plans.GamePlans.ModalGameplan
class ProtossVsZerg extends ModalGameplan(
// Openings
new PvZ1BaseForgeTech,
new PvZFFE,
// Midgames
new PvZBisu,
new PvZ5GateGoon,
new PvZCorsairReaver,
// Late game
new PvZLateGameReaver,
new PvZLateGameTemplar,
)
| 26,075
|
https://github.com/cms-sw/cmssw/blob/master/Validation/GlobalHits/python/globalhits_prodhiststrip_cff.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
cmssw
|
cms-sw
|
Python
|
Code
| 29
| 77
|
# The following comments couldn't be translated into the new config version:
# needed backend
import FWCore.ParameterSet.Config as cms
# actual producer
from Validation.GlobalHits.globalhits_prodhiststrip_cfi import *
DQMStore = cms.Service("DQMStore")
| 6,641
|
https://github.com/kunlabora/antwerp-ui_angular/blob/master/packages/ngx-agenda/src/lib/services/sorting.service.spec.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
antwerp-ui_angular
|
kunlabora
|
TypeScript
|
Code
| 814
| 1,843
|
import { DateHelperService } from './date-helper.service';
import { SortingService } from './sorting.service';
import { EventInterface } from '../types/agenda.types';
describe('Sorting Service', () => {
const dateHelper = new DateHelperService();
const sortingService = new SortingService(dateHelper);
it('should sort events by startdate, event length and start time', () => {
// updated value of 'Event 20' because you can't trust sorting order when all values are the same.
const events: EventInterface[] = [
{ title: 'Event 11', startDate: new Date(2018, 0, 13, 15, 0), endDate: new Date(2018, 0, 13, 17, 0), },
{ title: 'Event 08', startDate: new Date(2018, 0, 10, 14, 0), endDate: new Date(2018, 0, 10, 17, 0), },
{ title: 'Event 04', startDate: new Date(2018, 0, 1, 14, 0), endDate: new Date(2018, 0, 2, 17, 0), },
{ title: 'Event 03', startDate: new Date(2017, 11, 27, 15, 0), endDate: new Date(2017, 11, 27, 17, 0), },
{ title: 'Event 02', startDate: new Date(2017, 11, 26, 15, 0), endDate: new Date(2018, 0, 2, 17, 0), },
{ title: 'Event 01', startDate: new Date(2017, 11, 7, 15, 0), endDate: new Date(2017, 11, 8, 17, 0), },
{ title: 'Event 20', startDate: new Date(2018, 2, 8, 17, 0), endDate: new Date(2018, 2, 23, 17, 0), },
{ title: 'Event 18', startDate: new Date(2018, 2, 8, 15, 0), endDate: new Date(2018, 2, 24, 17, 0), },
{ title: 'Event 19', startDate: new Date(2018, 2, 8, 17, 0), endDate: new Date(2018, 2, 24, 17, 0), },
{ title: 'Event 17', startDate: new Date(2018, 1, 8, 15, 0), endDate: new Date(2018, 1, 8, 17, 0), },
{ title: 'Event 16', startDate: new Date(2018, 1, 3, 15, 0), endDate: new Date(2018, 1, 5, 17, 0), },
{ title: 'Event 09', startDate: new Date(2018, 0, 11, 10, 0), endDate: new Date(2018, 0, 11, 16, 0), },
{ title: 'Event 14', startDate: new Date(2018, 0, 30, 10, 0), endDate: new Date(2018, 0, 30, 16, 0), },
{ title: 'Event 05', startDate: new Date(2018, 0, 8, 10, 0), endDate: new Date(2018, 0, 12, 17, 0), },
{ title: 'Event 12', startDate: new Date(2018, 0, 27, 10, 0), endDate: new Date(2018, 0, 30, 17, 0), },
{ title: 'Event 07', startDate: new Date(2018, 0, 10, 10, 0), endDate: new Date(2018, 0, 12, 12, 0), },
{ title: 'Event 15', startDate: new Date(2018, 1, 1, 10, 0), endDate: new Date(2018, 1, 1, 12, 0), },
{ title: 'Event 06', startDate: new Date(2018, 0, 10, 10, 0), endDate: new Date(2018, 0, 13, 12, 0), },
{ title: 'Event 13', startDate: new Date(2018, 0, 30, 10, 0), endDate: new Date(2018, 1, 2, 17, 0), },
{ title: 'Event 10', startDate: new Date(2018, 0, 13, 10, 0), endDate: new Date(2018, 0, 13, 17, 0), },
];
expect(sortingService.sortEvents(events)).toEqual([
{title: 'Event 01', startDate: new Date(2017, 11, 7, 15, 0), endDate: new Date(2017, 11, 8, 17, 0), },
{title: 'Event 02', startDate: new Date(2017, 11, 26, 15, 0), endDate: new Date(2018, 0, 2, 17, 0), },
{title: 'Event 03', startDate: new Date(2017, 11, 27, 15, 0), endDate: new Date(2017, 11, 27, 17, 0), },
{title: 'Event 04', startDate: new Date(2018, 0, 1, 14, 0), endDate: new Date(2018, 0, 2, 17, 0), },
{title: 'Event 05', startDate: new Date(2018, 0, 8, 10, 0), endDate: new Date(2018, 0, 12, 17, 0), },
{title: 'Event 06', startDate: new Date(2018, 0, 10, 10, 0), endDate: new Date(2018, 0, 13, 12, 0), },
{title: 'Event 07', startDate: new Date(2018, 0, 10, 10, 0), endDate: new Date(2018, 0, 12, 12, 0), },
{title: 'Event 08', startDate: new Date(2018, 0, 10, 14, 0), endDate: new Date(2018, 0, 10, 17, 0), },
{title: 'Event 09', startDate: new Date(2018, 0, 11, 10, 0), endDate: new Date(2018, 0, 11, 16, 0), },
{title: 'Event 10', startDate: new Date(2018, 0, 13, 10, 0), endDate: new Date(2018, 0, 13, 17, 0), },
{title: 'Event 11', startDate: new Date(2018, 0, 13, 15, 0), endDate: new Date(2018, 0, 13, 17, 0), },
{title: 'Event 12', startDate: new Date(2018, 0, 27, 10, 0), endDate: new Date(2018, 0, 30, 17, 0), },
{title: 'Event 13', startDate: new Date(2018, 0, 30, 10, 0), endDate: new Date(2018, 1, 2, 17, 0), },
{title: 'Event 14', startDate: new Date(2018, 0, 30, 10, 0), endDate: new Date(2018, 0, 30, 16, 0), },
{title: 'Event 15', startDate: new Date(2018, 1, 1, 10, 0), endDate: new Date(2018, 1, 1, 12, 0), },
{title: 'Event 16', startDate: new Date(2018, 1, 3, 15, 0), endDate: new Date(2018, 1, 5, 17, 0), },
{title: 'Event 17', startDate: new Date(2018, 1, 8, 15, 0), endDate: new Date(2018, 1, 8, 17, 0), },
{title: 'Event 18', startDate: new Date(2018, 2, 8, 15, 0), endDate: new Date(2018, 2, 24, 17, 0), },
{title: 'Event 19', startDate: new Date(2018, 2, 8, 17, 0), endDate: new Date(2018, 2, 24, 17, 0), },
{title: 'Event 20', startDate: new Date(2018, 2, 8, 17, 0), endDate: new Date(2018, 2, 23, 17, 0), },
]);
});
});
| 37,393
|
https://github.com/p-g-krish/deepmac-tracker/blob/master/data/js/f0/b0/22/00/00/00.24.js
|
Github Open Source
|
Open Source
|
CC-BY-4.0, MIT
| null |
deepmac-tracker
|
p-g-krish
|
JavaScript
|
Code
| 9
| 83
|
deepmacDetailCallback("f0b022000000/24",[{"d":"2020-03-05","t":"add","s":"ieee-oui.csv","a":"1-13-21 Tanashioda, Chuo-Ku Sagamihara-City Kanagawa JP 252-0245","c":"JP","o":"TOHO Electronics INC."}]);
| 22,601
|
https://github.com/jbescos/jaxb-api/blob/master/spec/src/main/asciidoc/appI-changelog.adoc
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
jaxb-api
|
jbescos
|
AsciiDoc
|
Code
| 2,724
| 5,464
|
//
// Copyright (c) 2020 Contributors to the Eclipse Foundation
//
[appendix]
== Change Log
=== Changes in Version 3
* Changed specification version and license.
* Package namespace changed to `jakarta.xml.bind.*`.
* Customization schema namespace changed to `https://jakarta.ee/xml/ns/jaxb`,
minimal supported version set to `3.0`.
* Relaxed requirements tight to JAXB 1.0
* Removed inclusion in Java SE from specification goals
=== Changes since Maintenance Release 2
* Section 4.2 added note related to Java Platform Module System.
* Added section 4.9 Implementation discovery.
* Added change logs for MR1 and MR2.
=== Changes since Maintenance Release 1
Details can be found at:
_https://jcp.org/aboutJava/communityprocess/maintenance/jsr222/222mr2.zip_
* Section 8.9.1.1 @XmlElement target extended for type PARAMETER
* Section 8.9.3.1 added required annotation element to @XmlElementRef
=== Changes since Final Draft
Details can be found at:
https://jcp.org/aboutJava/communityprocess/maintenance/jsr222/222changes.txt
* Section 7.1.3 External Binding Declaration @schemaLocation and @node are optional.
* Section E.2 3 and 3b updated.
* Section 3.5.2.1 constraint violation updated JAXB 2.0 implementation
delegate to the validation API in JAXP 1.3.
=== Changes since Proposed Final Draft
* Section 7.6.1.2, nameXmlTransform: Apply
customization [ _jaxb:nameXmlTransform]_ addition of prefix and/or
suffix after XML to Java name transformation is applied.
* Section 6.7.1-2 changed to allow generation
of element factory method for abstract element. Change was necessary to
support element substitution. The abstract element factory method is
generated so it can be annotated with JAXB program annotation that
enables element substitution, _@XmlElementDecl.substitutionHeadName_ .
* Section 7.7.3.5 fixed the example with
<class> customization. Made the corresponding change in Section 6.7.2 so
Objectfactory method creates an instance of generated class.
* Chapter 8 and appendix B:
@XmlJavaTypeAdapter on class, interface or enum type is mutually
exclusive with any other annotation.
* Chapter 8: added @XmlElement.required() for
schema generation
* Section 8.7.1.2: clarifications for no-arg
static factory method in @XmlType annotation.
* Section 8.9.13.2: Disallow use of @XmlList
on single valued property.
* Section 8.9.8.2, Table 8-30 :
@XmlAnyAttribute maps to anyAttribute with a namespace constraint with
##other.
* Section 8.9.1.2: If @XmlElement.namespace()
is different from that of the target namespace of the enclosing class,
require a global element to be generated in the namespace specified in
@XmlElement.namespace() to make the generated schema complete.
* Section 8.9.15: Allow @XmlMimeType on a
parameter.
* Section 8.9.16: Allow @XmlAttachmentRef on
a parameter.
* Chapter 8: removed constraint check that
namespace() annotation element must be a valid namespace URI from
different annotations.
* Chapter 8: Java Persistence and JAXB 2.0
alignment related changes. +
constructor requirement: public or protected no-arg constructor +
@AccessType renamed to @XmlAccessType. +
@AccessorOrder renamed to @XmlAccessOrder. +
@XmlTransient is mutually exclusive with other annotations. +
@A property or field that is transient or marked with @XmlTransient and
specified in @XmlType.propOrder is an error.
* Chapter 8: Clarifications for generics -
type variables with type bound, bounded wildcards and java.util.Map.
* Section 8.9: reworked constraints on the
properties to handle different use cases permitted by JavaBean design
pattern.
* Section 8: Take elementFormDefault into
account when determining the namespace for @XmlElement and
@XmlElementWrapper annotations.
* Section 8: Added missing mapping
constraints for @XmlElementWrapper. Also disallow use of @XmlIDREF with
@XmlElementWrapper.
* Chapter 9, “Compatibility”: clarified
schema generator and schema compiler requirements.
* Section B.2.5: Added marshalling of null
value as xsi:nil or empty element based upon @XmlElement.required and
@XmlElement.nillable annotation elements.
* Section B.5: Added new section and moved
runtime requirements on getters/setters to here.
=== Changes since Public Review
* Update link:jaxb.html#a3815[See
Compatibility]” for JAXB 2.0 technology. Additional requirements added
for Java Types to XML binding and the running of JAXB 1.0 application in
a JAXB 2.0 environment.
* Added external event callback mechanism,
_Unmarshaller.Listener_ and _Marshaller.Listener_ .
* Added new unmarshal method overloading,
unmarshal by declaredType, to _Unmarshaller_ and _Binder_ . Enables
unmarshalling a root element that corresponds with a local element
declaration in schema.
* Added link:jaxb.html#a1459[See
Modifying Schema-Derived Code]” describing use of annotation
_@javax.annotation.Generated_ to distinguish between generated and
user-modified code in schema-derived class.
* Element declaration with anonymous complex
type definition binds to _@XmlRootElement_ annotated class except for
cases in Section 6.7.3.1.
* Removed <jaxb:globalBindings
nullsInCollection>. The customization <jaxb:property
generateElementProperty=”true”> can achieve same desired result.
* Added clarification that mapping two or
more target namespaces to same java package can result in naming
collision that should be detected as an error by schema compiler.
* Added <jaxb:factoryMethod> customization to
enable the resolution of name collisions between factory methods.
* First parameter to any of the overloaded
Marshaller.marshal() methods must be a JAXB element; otherwise, method
must throw MarshalException. See updated Marshaller javadoc and
link:jaxb.html#a397[See Marshalling]” for details.
* Prepend “_”, not “Original”, to a Java
class name representing an XML Schema type definition that has been
redefined in link:jaxb.html#a1316[See Redefine]”.
* Format for class name in _jaxb.index_ file
clarified in JAXBConext.newInstance(String) method javadoc.
* Clarifications on @dom customization in
Section 7.12..
* Chapter 8: Added support for
@XmlJavaTypeAdapter at the package level.
* Chapter 8: Added new annotation
@XmlJavaTypeAdapters as a container for defining multiple
@XmlJavaTypeAdapters at the package level.
* Chapter 8: Added support for @XmlSchemaType
at the package level.
* Chapter 8: Added @XmlSchemaTypes as a
container annotation for defining multiple @XmlSchemaType annotations at
the package level.
* Chapter 8: added lists of annotations
allowed with each annotation.
* Chapter 8: Bug fixes and clarifications
related to mapping and mapping constraints.
* Chapter 8: Expanded collection types mapped
to java.util.Map and java.util.Collection.
* Appendix B. Incorporate event call backs
into unmarshalling process.
* Appendix B: Incorporate into unmarshalling
process additional unmarshal methods: Binder.unmarshal(..), unmarshal
methods that take a declaredType as a parameter - Binder.unmarshal(...,
declaredType) and Unmarshaller.unmarshal(...,declaredType).
=== Changes since Early Draft 2
* Simple type substitution support added in
Section 6.7.4.2.
* Updates to enum type binding. (Section
7.5.1, 7.5.5, 7.10, Appendix D.3)
* Optimized binary data.(Appendix H) and
schema customizations. (Section 7.13 and 7.10.5)
* Clarification for _<jaxb:globalBindings
underscoreHandling=”asCharInWord”>_ (Appendix D.2)
* Added Unmarshal and Marshal Callback Events
(Section 4.4.1,4.5.1)
* Clarification: xs:ID and xs:IDREF can not
bind to an enum type. (Section 6.2.3,7.10.5)
* Added schema customization: +
<jaxb:globalBinding localScoping=”nested”|”toplevel”> (Section 7.5.1) +
<jaxb:inlineBinaryData> (Section 7.13) +
<jaxb:property @attachmentRef/> (Section 7.8.1)
* Updated Section 6 and 7 with mapping
annotations that are generated on schema-derived JAXB
classes/properties/fields.
* Added jakarta.xml.bind.Binder class to
Section 4.8.2.
* Runtime generation of schema from JAXB
mapping annotations: JAXBContext.generateSchema().
* Chapter 8: added @XmlList: bind
property/field to simple list type
* Chapter 8: added @XmlAnyElement: bind
property/field to xs:any
* Chapter 8: added @XmlAnyAttribute - bind
property/field to xs:anyAttribute
* Chapter 8. added @XmlMixed - for mixed
content
* Chapter 8, added annotations for
attachment/MTOM support: @XmlMimeType, @XmlAttachmentRef
* Chapter 8: added @XmlAccessorOrder - to
specify default ordering.
* Chapter 8: added @XmlSchemaType mainly for
use in mapping XMLGregorianCalendar.
* Chapter 8: map java.lang.Object to
xs:anyType
* Chapter 8: added mapping of
XMLGregorianCalendar
* Chapter 8: added mapping of generics - type
variables, wildcardType
* Chapter 8: added mapping of binary data
types.
* Chapter 8: default mappings changed for
class, enum type.
* Chapter 8: default mapping of propOrder
specified.
* Chapter 8: mapping of classes - zero arg
constructor, factory method.
* Chapter 8: added Runtime schema generation
requirement.
* Chapter 8: Clarified mapping constraints
and other bug fixes.
* Added Appendix B new: Added Runtime
Processing Model to specify the marshalling/unmarshalling for dealing
with invalid XML content and schema evolution.
* Updated Appendix C to JAXB 2.0 binding
schema.
=== Changes since Early Draft
* Updated goals in Introduction.
* Update to Section 3 “Architecture”
introducing Java to Schema binding.
* section on portable annotation-driven
architecture.
* section on handling of invalid XML content
* Binding Framework
* Replaced _IXmlElement<T>_ interface with
_JAXBElement<T>_ class. (JAXBElement is used for schema to java binding)
* _JAXBIntrospector_ introduced _._
* Add flexible (by-name) unmarshal and
describe JAXB 1.0 structural unmarshalling.
* Moved deprecated on-demand validation,
accessible via jakarta.xml.bind.Validator, to Appendix H.
* XSD to Java Binding
* Bind complex type definition to value class
by default.
* Schema-derived code is annotated with JAXB
java annotations.
* Bind XSD simpleType with enum facet to J2SE
5.0 enum type. Change default for jaxb:globalBinding @typeEnumBase from
xs:NCName to xs:string.
* _ObjectFactory_ factory methods no longer
throws _JAXBException_ .
* Added customizations +
[jaxb:globalBindings] @generateValueClass, @generateElementClass,
@serializable, @optionalProperty, @nullInCollection +
[jaxb:property] @generateElementProperty
* Add binding support for redefine
* Simplified following bindings: +
- union by binding to String rather than Object. +
- Attribute Wildcard binds to portable abstraction of a
java.util.Map<QName, String>, not jakarta.xml.bind.AttributeMap. +
- bind xsd:anyType to java.lang.Object in JAXB property method
signatures and element factory method(support element/type substitution)
* Changes required for default and customized
binding in order to support flexible unmarshalling described in Section
4.4.3.
* Java to XSD Binding
* Added @XmlAccessorType for controlling
whether fields or properties are mapped by default.
* Added @XmlEnum and @XmlEnumValue for
mapping of enum types.
* Collections has been redesigned to allow
them to be used in annotation of schema derived code:
- removed @XmlCollectionItem and
@XmlCollection
- Added annotations parameters to @XmlElement
- added @XmlElementRef
- added @XmlElements and @XmlElementRefs as
containers for collections of @XmlElements or @XmlElementRefs.
- added @XmlElementWrapper for wrapping of
collections.
* Added mapping of anonymous types.
* Added mapping of nested classes to schema
* Added @XmlRootElement for annotating
classes. @XmlElement can now only be used to annotate properties/fields.
* Added @XmlElementRef for supporting schema
derived code as well as mapping of existing object model to XML
representation. javadoc for @XmlElementRef contains an example
* Added @XmlElementDecl on object factory
methods for supporting mapping of substitution groups for schema -> java
binding.
* Redesigned Adapter support for mapping of
non Java Beans.
- new package
jakarta.xml.bind.annotation.adapters for adapters.
- Added XmlAdapter base abstract class for
all adapters.
- redesigned and moved XmlJavaTypeAdapter to
the package.
* Moved default mapping from each section to
“Default Mapping” section.
* Consistent treatment of defaults
“##default”
* Removed JAX-RPC 1.1 Alignment. JAX-WS 2.0
is deferring its databinding to JAXB 2.0.
=== Changes for 2.0 +
Early Draft v0.4
* Updated link:jaxb.html#a2[See
Introduction]”.
* Added link:jaxb.html#a151[See
Requirements]”
* Added link:jaxb.html#a2236[See Java
Types To XML]” for Java Source to XML Schema mapping.
* XML Schema to schema-derived Java Binding
changes
* Element handling changes to support element
and type substitution in link:jaxb.html#a680[See Java Element
Representation Summary]”, link:jaxb.html#a1023[See Element
Declaration]” and link:jaxb.html#a630[See Element Property]”.
* Added link:jaxb.html#a1306[See
Attribute Wildcard]” binding
* Support binding all wildcard content in
link:jaxb.html#a1384[See Bind wildcard schema component]”.
* Addition/changes in
link:jaxb.html#a725[See Java Mapping for XML Schema Built-in
Types].
* XML Schema to Java Customization
* Added ability to doable databinding for an
XML Schema fragment in link:jaxb.html#a2165[See <dom>
Declaration]”.
=== Changes for 1.0 Final
* Added method
_jakarta.xml.bind.Marshaller.getNode(Object)_ which returns a DOM view of
the Java content tree. See method's javadoc for details.
=== Changes for Proposed Final
* Added link:jaxb.html#a3815[See
Compatibility].”
* Section 5.9.2, “General Content Property,”
removed value content list since it would not be tractable to support
when type and group substitution are supported by JAXB technology.
* Added the ability to associate
implementation specific property/value pairs to the unmarshal,
validation and JAXB instance creation. Changes impact Section 3.4
“Unmarshalling,” Section 3.5 “Validator” and the ObjectFactory
description in Section 4.2 “Java Package.”
* Section 6.12.10.1, “Bind a Top Level Choice
Model Group” was updated to handle Collection properties occurring
within a Choice value class.
* Section 6.12.11, “Model Group binding
algorithm” changed step 4(a) to bind to choice value class rather than
choice content property.
* link:jaxb.html#a595[See List
Property] and link:jaxb.html#a610[See isSet Property Modifier]”
updated so one can discard set value for a List property via calling
unset method.
* At end of Section 4, added an UML diagram
of the JAXB Java representation of XML content.
* Updated default binding handling in
link:jaxb.html#a996[See Model Group Definition].” Specifically,
value class, element classes and enum types are derived from the content
model of a model group definition are only bound once, not once per time
the group is referenced.
* Change link:jaxb.html#a1384[See
Bind wildcard schema component],” to bind to a JAXB property with a
basetype of _java.lang.Object,_ not _jakarta.xml.bind.Element._ Strict and
lax wildcard validation processing allows for contents constrained only
by _xsi:type_ attribute. Current APIs should allow for future support of
_xsi:type_ .
* Simplify anonymous simple type definition
binding to typesafe enum class. Replace incomplete approach to derive a
name with the requirement that the @name attribute for element
typesafeEnumClass is mandatory when associated with an anonymous simple
type definition.
* Changed link:jaxb.html#a1012[See
Deriving Class Names for Named Model Group Descendants]” to state that
all classes and interfaces generated for XML Schema component that
directly compose the content model for a model group, that these
classes/interfaces should be generated once as top-level interface/class
in a package, not in every content model that references the model
group.
* Current link:jaxb.html#a1580[See
<globalBindings> Declaration]”:
* Replaced _modelGroupAsClass_ with
_bindingStyle_ .
* Specified schema types that cannot be
listed in _typesafeEnumBase_ .
* link:jaxb.html#a1783[See <property>
Declaration]:
* Clarified the customization of model groups
with respect to _choiceContentProperty, elementBinding and
modelGroupBinding._ Dropped _choiceContentProperty_ from the
_<property>_ declaration.
* Added _<baseType>_ element and clarified
semantics.
* Added support for customization of simple
content.
* Added customization of simple types at
point of reference.
* Clarified restrictions and relationships
between different customizations.
* link:jaxb.html#a1981[See <javaType>
Declaration]”:
* Added
_jakarta.xml.bind.DatatypeConverterInterface_ interface.
* Added _jakarta.xml.bind.DatatypeConverter_
class for use by user specified parse and print methods.
* Added
_javax.xml.namespace.NamespaceContext_ class for processing of QNames.
* Clarified print and parse method
requirements.
* Added narrowing and widening conversion
requirements.
* Throughout link:jaxb.html#a1498[See
Customizing XML Schema to Java Representation Binding],” clarified the
handling of invalid customizations.
=== Changes for Public Draft 2
Many changes were prompted by inconsistencies
detected within the specification by the reference implementation
effort. Change bars indicate what has changed since Public Draft.
* Section 4.5.4, “isSetProperty Modifier,”
describes the customization required to enable its methods to he
generated.
* Section 5.7.2, “Binding of an anonymous
type definition,” clarifies the generation of value class and typesafe
enum classes from an anonymous type definition.
* Section 5.2.4, “List” Simple Type
Definition and the handling of list members within a union were added
since public draft.
* Clarification on typesafe enum global
customization “generateName” in Section 5.2.3.4, “XML Enumvalue
To Java Identifier Mapping.”
* Clarification of handling binding of
wildcard content in Section 5.9.4.
* Chapter6, “Customization,” resolved binding
declaration naming inconsistencies between specification and normative
binding schema.
* removed _enableValidation_ attribute (a
duplicate of _enableFailFastCheck)_ from < _globalBindings>_
declaration.
* Added default values for <
_globalBindings>_ declaration attributes.
* Changed _typesafeEnumBase_ to a list of
QNames. Clarified the binding to typesafe enum class.
* Clarified the usage and support for
_implClass_ attribute in _<class>_ declaration.
* Clarified the usage and support for
_enableFailFastCheck_ in the _<property>_ declaration.
* Added _<javadoc>_ to typesafe enum class,
member and property declarations.
* Mention that embedded HTML tags in
_<javadoc>_ declaration must be escaped.
* Fixed mistakes in derived Java code
throughout document.
* Added Section 7. Compatibility and updated
Appendix E.2 “Non required XML Schema Concepts” accordingly.
=== Changes for Public Draft
* link:jaxb.html#a1442[See Bind
single occurrence choice group to a choice content property],” replaced
overloading of choice content property setter method with a single
setter method with a value parameter with the common type of all members
of the choice. Since the resolution of overloaded method invocation is
performed using compile-time typing, not runtime typing, this
overloading was problematic. Same change was made to binding of union
types.
* Added details on how to construct factory
method signature for nested content and element classes.
* Section 3.3, default validation handler
does not fail on first warning, only on first error or fatal error.
* Add ID/IDREF handling in section 5.
* Updated name mapping in appendix C.
* link:jaxb.html#a572[See Indexed
Property], added getIDLenth() to indexed property.
* Removed ObjectFactory.setImplementation
method from link:jaxb.html#a482[See Java Package]. The negative
impact on implementation provided to be greater than the benefit it
provided the user.
* Introduced external binding declaration
format.
* Introduced a method to introduce extension
binding declarations.
* Added an appendix section describing JAXB
custom bindings that align JAXB binding with JAX-RPC binding from XML to
Java representation.
* Generate isID() accessor for boolean
property.
* Section 6, Customization has been
substantially rewritten.
| 9,978
|
https://github.com/polynomialchaos/basec/blob/master/src/Utils/include/basec/utils/utils_memory.h
|
Github Open Source
|
Open Source
|
MIT
| null |
basec
|
polynomialchaos
|
C
|
Code
| 215
| 588
|
/*******************************************************************************
* @file utils_memory.h
* @author Florian Eigentler
* @brief
* @version 1.0.0
* @date 2022-02-22
* @copyright Copyright (c) 2022 by Florian Eigentler.
* This work is licensed under terms of the MIT license (<LICENSE>).
******************************************************************************/
#ifndef UTILS_MEMORY_H
#define UTILS_MEMORY_H
#include <stdlib.h>
#include "basec/basec_macro.h"
#include "basec/basec_type.h"
/*******************************************************************************
* @brief A macro that allocates a portion of memory
* and pass file, line, function
******************************************************************************/
#define BM_ALLOCATE(size) allocate_pass(__PASS__, (size))
/*******************************************************************************
* @brief A macro that deallocates a portion of memory
******************************************************************************/
#define BM_DEALLOCATE(ptr) ( \
{ \
deallocate_wo_null((ptr)); \
(ptr) = NULL; \
})
/*******************************************************************************
* @brief A macro that reallocates a portion of memory
* and pass file, line, function
******************************************************************************/
#define BM_REALLOCATE(old, size) reallocate_pass(__PASS__, (old), (size))
/*******************************************************************************
* @brief Allocate portion of memory and pass file, line, function
* @param[in] _file
* @param[in] _line
* @param[in] _function
* @param[in] size
* @return void*
******************************************************************************/
void *allocate_pass(cstring_t _file, int _line, cstring_t _function,
size_t size);
/*******************************************************************************
* @brief Deallocate portion of memory
* @param[in] ptr
******************************************************************************/
void deallocate_wo_null(void *ptr);
/*******************************************************************************
* @brief Reallocate portion of memory and pass file, line, function
* @param[in] _file
* @param[in] _line
* @param[in] _function
* @param[in] old_ptr
* @param[in] size
* @return void*
******************************************************************************/
void *reallocate_pass(cstring_t _file, int _line, cstring_t _function,
void *old_ptr, size_t size);
#endif /* UTILS_MEMORY_H */
| 8,558
|
https://github.com/keycloak/keycloak/blob/master/docs/documentation/tests/src/test/java/org/keycloak/documentation/test/utils/Constants.java
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT, LicenseRef-scancode-unknown-license-reference, BSD-3-Clause
| 2,023
|
keycloak
|
keycloak
|
Java
|
Code
| 37
| 110
|
package org.keycloak.documentation.test.utils;
import java.util.concurrent.TimeUnit;
public class Constants {
public static final int HTTP_RETRY = 5;
public static final int HTTP_CONNECTION_TIMEOUT = 30000;
public static final int HTTP_READ_TIMEOUT = 300000;
public static final long LINK_CHECK_EXPIRATION = TimeUnit.DAYS.toMillis(1);
}
| 33,031
|
https://github.com/markjoseph454/opdms/blob/master/public/js/mss/report.js
|
Github Open Source
|
Open Source
|
MIT
| null |
opdms
|
markjoseph454
|
JavaScript
|
Code
| 316
| 1,738
|
$(document).ready(function(){
$('.generatemssreport').submit(function(){
$('.submitclassificationgenerate').css('display', 'block');
})
})
$(document).ready(function(){
var tot_ref = 0;
$('.refclass').each(function(index){
tot_ref += Number($(this).text());
})
$('.tot_ref').text(tot_ref);
var tot_orig = 0;
$('.origclass').each(function(index){
tot_orig += Number($(this).text());
})
$('.tot_orig').text(tot_orig);
var tot_cat = 0;
$('.catclass').each(function(index){
tot_cat += Number($(this).text());
})
$('.tot_cat').text(tot_cat);
var tot_four = 0;
$('.fourclass').each(function(index){
tot_four += Number($(this).text());
})
$('.tot_four').text(tot_four);
var tot_sect = 0;
$('.sectclass').each(function(index){
tot_sect += Number($(this).text());
})
$('.tot_sect').text(tot_sect);
var tot_classif = 0;
$('.classifclass').each(function(index){
tot_classif += Number($(this).text());
})
$('.tot_classif').text(tot_classif);
var tot_doh = 0;
$('.dohclass').each(function(index){
tot_doh += Number($(this).text());
})
$('.tot_doh').text(tot_doh);
/*=============================for referral*/
})
$(window).load(function(){
var gh = 0;
$('.gh').each(function(index){
gh += Number($(this).text());
})
$('.tot_gh').text(gh).css({'text-align': 'center', 'font-size': '12px'});
var phpc = 0;
$('.phpc').each(function(index){
phpc += Number($(this).text());
})
$('.tot_phpc').text(phpc).css({'text-align': 'center', 'font-size': '12px'});
var polit = 0;
$('.polit').each(function(index){
polit += Number($(this).text());
})
$('.tot_polit').text(polit).css({'text-align': 'center', 'font-size': '12px'});
var media = 0;
$('.media').each(function(index){
media += Number($(this).text());
})
$('.tot_media').text(media).css({'text-align': 'center', 'font-size': '12px'});
var hct = 0;
$('.hct').each(function(index){
hct += Number($(this).text());
})
$('.tot_hct').text(hct).css({'text-align': 'center', 'font-size': '12px'});
var ngo = 0;
$('.ngo').each(function(index){
ngo += Number($(this).text());
})
$('.tot_ngo').text(ngo).css({'text-align': 'center', 'font-size': '12px'});
var govt = 0;
$('.govt').each(function(index){
govt += Number($(this).text());
})
$('.tot_govt').text(govt).css({'text-align': 'center', 'font-size': '12px'});
var walkin = 0;
$('.walkin').each(function(index){
walkin += Number($(this).text());
})
$('.tot_walkin').text(walkin).css({'text-align': 'center', 'font-size': '12px'});
var other = 0;
$('.other').each(function(index){
other += Number($(this).text());
})
$('.tot_other').text(other).css({'text-align': 'center', 'font-size': '12px'});
var tot_totalperline = 0;
$('.tot_totalperline').each(function(index){
tot_totalperline += Number($(this).text());
})
$('.tot_totals').text(tot_totalperline).css({'text-align': 'center', 'font-size': '12px'});
var a = 0;
$('.a').each(function(index){
a += Number($(this).text());
})
$('.tot_a').text(a).css({'text-align': 'center', 'font-size': '12px'});
var b = 0;
$('.b').each(function(index){
b += Number($(this).text());
})
$('.tot_b').text(b).css({'text-align': 'center', 'font-size': '12px'});
var c1 = 0;
$('.c1').each(function(index){
c1 += Number($(this).text());
})
$('.tot_c1').text(c1).css({'text-align': 'center', 'font-size': '12px'});
var c2 = 0;
$('.c2').each(function(index){
c2 += Number($(this).text());
})
$('.tot_c2').text(c2).css({'text-align': 'center', 'font-size': '12px'});
var c3 = 0;
$('.c3').each(function(index){
c3 += Number($(this).text());
})
$('.tot_c3').text(c3).css({'text-align': 'center', 'font-size': '12px'});
var sc = 0;
$('.sc').each(function(index){
sc += Number($(this).text());
})
$('.tot_sc').text(sc).css({'text-align': 'center', 'font-size': '12px'});
var de = 0;
$('.de').each(function(index){
de += Number($(this).text());
})
$('.tot_de').text(de).css({'text-align': 'center', 'font-size': '12px'});
var totals = 0;
$('.totals').each(function(index){
totals += Number($(this).text());
})
$('.tot_total').text(totals).css({'text-align': 'center', 'font-size': '12px'});
})
| 49,618
|
https://github.com/yuanying/azash/blob/master/pkgs/books/book.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
azash
|
yuanying
|
Go
|
Code
| 446
| 1,489
|
package books
import (
"encoding/json"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/go-logr/logr"
"go.etcd.io/bbolt"
)
var (
booksBucket = []byte("BOOKS")
)
type BookList struct {
log logr.Logger
db *bbolt.DB
cache []Book
mux sync.Mutex
}
type Book struct {
ID string
Filename string
Artists []string
Categories []string
ModTime time.Time
}
func NewBookList(log logr.Logger, db *bbolt.DB) *BookList {
return &BookList{
log: log,
db: db,
}
}
func (b *BookList) Register(book Book) error {
b.db.Update(func(tx *bbolt.Tx) error {
if bucket, err := tx.CreateBucketIfNotExists(booksBucket); err != nil {
return err
} else {
bid := []byte(book.ID)
if bucket.Get(bid) == nil {
if raw, err := json.Marshal(book); err != nil {
return err
} else {
if err := bucket.Put(bid, raw); err != nil {
return err
}
b.mux.Lock()
b.cache = nil
b.mux.Unlock()
}
} else {
b.log.Info("Book is already registerd", "id", book.ID, "filename", book.Filename)
}
}
return nil
})
return nil
}
func (b *BookList) Get(id string) (*Book, error) {
book := &Book{}
b.db.View(func(tx *bbolt.Tx) error {
raw := tx.Bucket(booksBucket).Get([]byte(id))
if err := json.Unmarshal(raw, book); err != nil {
return err
}
return nil
})
return book, nil
}
func (b *BookList) All() ([]Book, error) {
b.mux.Lock()
defer b.mux.Unlock()
if b.cache != nil {
return b.cache, nil
}
var books []Book
if err := b.db.View(func(tx *bbolt.Tx) error {
c := tx.Bucket(booksBucket).Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
book := Book{}
if err := json.Unmarshal(v, &book); err != nil {
b.log.Info("Failed to marshal book", "id", k)
}
books = append(books, book)
}
return nil
}); err != nil {
b.log.Error(err, "Failed to read db", "type", "Book")
return nil, err
}
sort.Slice(books, func(i, j int) bool { return books[i].ModTime.After(books[j].ModTime) })
b.cache = books
return b.cache, nil
}
var titleRegExp = regexp.MustCompile(`^(\((?P<category>\S+)\))?\s*(\[(?P<rawArtists>[^\]]+)\])?\s*(.+)`)
func (book *Book) ParseFilename() error {
g := titleRegExp.FindStringSubmatch(book.Filename)
if g != nil {
catIndex := titleRegExp.SubexpIndex("category")
category := g[catIndex]
if category != "" {
book.Categories = []string{category}
}
artIndex := titleRegExp.SubexpIndex("rawArtists")
rawArtists := g[artIndex]
if rawArtists != "" {
book.Artists = abstractArtists(rawArtists)
}
}
return nil
}
var allNumber = regexp.MustCompile(`^\d+$`)
func (book *Book) ParsePath(path string) error {
parentDir := filepath.Base(filepath.Dir(path))
if !strings.Contains(parentDir, ".") && !strings.Contains(parentDir, "/") && parentDir != "temp" && !allNumber.MatchString(parentDir) {
for _, artist := range book.Artists {
if artist == parentDir {
return nil
}
}
book.Artists = append(book.Artists, parentDir)
}
return nil
}
var artistsRegExpWithGroup = regexp.MustCompile(`(?P<group>[^\(]+)\s*(\((?P<artist>.+)\))?`)
func abstractArtists(str string) []string {
var artists []string
g := artistsRegExpWithGroup.FindStringSubmatch(str)
if g != nil {
grpIndex := artistsRegExpWithGroup.SubexpIndex("group")
group := g[grpIndex]
if group != "" {
artists = append(artists, strings.TrimSpace(group))
}
artIndex := artistsRegExpWithGroup.SubexpIndex("artist")
artist := g[artIndex]
if artist != "" {
artists = append(artists, strings.TrimSpace(artist))
}
}
return artists
}
| 16,803
|
https://github.com/SkynetRTN/afterglow-access-server/blob/master/afterglow_core/views/public_api/v1/catalogs.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
afterglow-access-server
|
SkynetRTN
|
Python
|
Code
| 130
| 326
|
"""
Afterglow Core: API v1 catalog views
"""
from typing import Optional
from flask import Response
from .... import app, json_response
from ....auth import auth_required
from ....resources.catalogs import catalogs
from ....schemas.api.v1 import CatalogSchema
from ....errors.catalog import UnknownCatalogError
from . import url_prefix
resource_prefix = url_prefix + 'catalogs/'
@app.route(resource_prefix[:-1])
@app.route(resource_prefix + '<name>')
@auth_required('user')
def get_catalogs(name: Optional[str] = None) -> Response:
"""
Return available catalog description(s)
GET /catalogs
- return a list of all available catalogs
GET /catalogs/[name]
- return a single catalog with the given name
:param str name: catalog name
:return: JSON response containing the list of serialized catalog objects
when no name supplied or a single catalog otherwise
"""
if name is None:
# List all catalogs
return json_response([CatalogSchema(cat) for cat in catalogs.values()])
try:
return json_response(CatalogSchema(catalogs[name]))
except KeyError:
raise UnknownCatalogError(name=name)
| 11,457
|
https://github.com/rdbeazer/Linesiter/blob/master/Resources/libraries/Interfaces/IPlugin.vb
|
Github Open Source
|
Open Source
|
MIT
| null |
Linesiter
|
rdbeazer
|
Visual Basic
|
Code
| 46
| 109
|
Imports System
Imports System.Threading
Imports System.ComponentModel
Public Interface IPlugin
Sub Initialize(ByVal Host As IHost)
ReadOnly Property DescriptiveName() As String
ReadOnly Property Description() As String
ReadOnly Property ToolboxName() As String
Property CancelOp() As Boolean
Function Execute(ByVal ParameterArray() As String, ByVal worker As BackgroundWorker) As Object
End Interface
| 24,369
|
https://github.com/kang-donghoon-eland/FigmaSharp/blob/master/samples/FigmaSharp.Views/Graphics/Views/RectangleExampleView.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
FigmaSharp
|
kang-donghoon-eland
|
C#
|
Code
| 31
| 98
|
using FigmaSharp;
using FigmaSharp.Views.Cocoa;
namespace BasicGraphics.Cocoa
{
public class RectangleExampleView : View
{
public RectangleExampleView()
{
Size = new Size(120, 120);
//BorderRadius = 20;
BackgroundColor = Color.White;
}
}
}
| 43,458
|
https://github.com/ragnarokkrr/rgn_vm_containers/blob/master/vagrant_gluster_ubuntu/Vagrantfile
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
rgn_vm_containers
|
ragnarokkrr
|
Ruby
|
Code
| 437
| 1,969
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
#
GLUSTER_HOSTS = [
{ name: 'gluster-node1', disk1: 'gluster-node1-osd1.vdi', disk2: 'gluster-node1-osd2.vdi', disk3: 'gluster-node1-osd3.vdi'},
{ name: 'gluster-node2', disk1: 'gluster-node2-osd1.vdi', disk2: 'gluster-node2-osd2.vdi', disk3: 'gluster-node2-osd3.vdi'} ,
{ name: 'gluster-node3', disk1: 'gluster-node3-osd1.vdi', disk2: 'gluster-node3-osd2.vdi', disk3: 'gluster-node3-osd3.vdi'} ,
{ name: 'gluster-node4', disk1: 'gluster-node4-osd1.vdi', disk2: 'gluster-node4-osd2.vdi', disk3: 'gluster-node4-osd3.vdi'}
]
$script_gluster_server = <<SCRIPT
apt-get update && apt-get upgrade -y
echo "storage"
apt-get install xfsprogs -y
mkfs.xfs -i size=512 /dev/sdb
mkfs.xfs -i size=512 /dev/sdc
mkdir -p /storage/glusterfs/vol0/brick1/
mkdir -p /storage/glusterfs/vol0/brick2/
echo '/dev/sdb /storage/glusterfs/vol0/brick1 xfs defaults 1 2' >> /etc/fstab
echo '/dev/sdc /storage/glusterfs/vol0/brick2 xfs defaults 1 2' >> /etc/fstab
mount -a
echo "going to install gluster"
apt-get install glusterfs-server -y
service glusterfs-server status
SCRIPT
$script_gluster_client = <<SCRIPT
apt-get update && apt-get upgrade -y
apt-get install glusterfs-client -y
SCRIPT
Vagrant.configure(2) do |config|
#config.vm.box = "centos/7"
config.vm.box = "ubuntu/trusty64"
#config.vm.provider :virtualbox do |vb|
# vb.customize ["storagectl", :id, "--add", "sata", "--name", "SATA Controller",
# "--controller", "IntelAHCI", "--hostiocache", "on", "--portcount", 2]
#end
#
config.vm.define "gluster-client" do |gluster_client|
gluster_client.vm.network "private_network", ip: "192.168.57.20"
gluster_client.vm.hostname = "gluster-client"
gluster_client.vm.provision "shell", inline: $script_gluster_client
gluster_client.vm.provider :virtualbox do |vb|
vb.name = "gluster-client"
vb.gui = false
vb.memory = "256"
vb.cpus = 1
end
end
GLUSTER_HOSTS.each_with_index do |gluster_host, i|
config.vm.define gluster_host[:name] do |gluster_node|
gluster_node.vm.hostname = gluster_host[:name]
gluster_node.vm.network "private_network", ip: "192.168.57.1#{i}"
gluster_node.vm.network :forwarded_port, guest: 22, host: 2301 + i, auto_correct: false # for external provisioning
#gluster_node.vm.synced_folder "#{Dir.pwd}/data", "/home/vagrant/data", create: true
# https://github.com/oscar-stack/vagrant-hosts
# vagrant plugin install vagrant-hosts
gluster_node.vm.provision :hosts, :sync_hosts => true
gluster_node.vm.provider :virtualbox do |vb|
vb.name = gluster_host[:name]
vb.gui = false
vb.memory = "256"
vb.cpus = 1
file_to_disk1 = gluster_host[:disk1]
file_to_disk2 = gluster_host[:disk2]
#https://github.com/mitchellh/vagrant/issues/4015
unless File.exist?(File.expand_path("#{file_to_disk1}"))
# /dev/sda
vb.customize ['createhd', '--filename', file_to_disk1, '--format', 'VDI', '--size', 5 * 1024]
# /dev/sdb
vb.customize ['createhd', '--filename', file_to_disk2, '--format', 'VDI', '--size', 7 * 1024]
end
vb.customize ['storageattach', :id, '--storagectl', 'SATAController', '--port', 1,
'--device', 0, '--type', 'hdd', '--medium', file_to_disk1]
vb.customize ['storageattach', :id, '--storagectl', 'SATAController', '--port', 2,
'--device', 0, '--type', 'hdd', '--medium', file_to_disk2]
# change the network card hardware for better performance
vb.customize ["modifyvm", :id, "--nictype1", "virtio" ]
vb.customize ["modifyvm", :id, "--nictype2", "virtio" ]
# suggested fix for slow network performance
# see https://github.com/mitchellh/vagrant/issues/1807
vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
end
gluster_node.vm.provision "shell", inline: $script_gluster_server
end
end
ANSIBLE_GROUPS = {
# "gluster_nodes" => ["gluster-node[1:3]"],
"gluster_nodes" => ["gluster-node1", "gluster-node2", "gluster-node3", "gluster-node4"],
"gluster_primary_node" => ["gluster-node1"],
}
# https://github.com/MatthewMi11er/vai
# vagrant plugin install vai
config.vm.provision :vai do |ansible|
ansible.inventory_dir = 'inventory/'
ansible.inventory_filename='gen_inv'
ansible.groups = ANSIBLE_GROUPS
end
#config.vm.provision :ansible do |ansible|
# ansible.playbook = "provisioning/glusterfs-install.yml"
# ansible.sudo = true
# ansible.raw_arguments = ["--connection=paramiko"]
# ansible.groups = ANSIBLE_GROUPS
#ansible.extra_vars = {
# gluster_nodes_list: 'gluster_node1 gluster_node2 gluster_node3',
# ceph_primary_node: 'gluster_node1'
#}
#ansible.raw_arguments = ['-vvvv']
# end
end
| 47,311
|
https://github.com/bkw/multiredlock/blob/master/virt/apt.sh
|
Github Open Source
|
Open Source
|
MIT
| null |
multiredlock
|
bkw
|
Shell
|
Code
| 67
| 260
|
#!/bin/sh
cat >/etc/apt/sources.list <<EOL
deb http://archive.ubuntu.com/ubuntu trusty main universe
deb http://archive.ubuntu.com/ubuntu trusty-updates main universe
deb http://security.ubuntu.com/ubuntu trusty-security main universe
EOL
echo >/etc/apt/apt.conf.d/99translations <<EOL
Acquire::Languages "none";
EOL
export DEBIAN_FRONTEND=noninteractive
# latest docker
wget -qO- https://get.docker.io/gpg | apt-key add -
echo deb http://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get remove --yes node
apt-get install --yes --no-install-recommends \
lxc-docker \
git \
nodejs \
npm \
redis-server \
redis-tools
| 39,345
|
https://github.com/kwaiga/star-wars-backend/blob/master/test/app.e2e-spec.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
star-wars-backend
|
kwaiga
|
TypeScript
|
Code
| 571
| 2,285
|
import { expect } from 'chai';
import 'chai-http';
import * as chai from 'chai';
import { CreateEpisodeDto } from '../src/episodes/dto/create-episode.dto';
import { EpisodesService } from '../src/episodes/episodes.service';
import { Test } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Episode } from '../src/episodes/entities/episode.entity';
import { AppController } from '../src/app.controller';
import { AppModule } from '../src/app.module';
import { AppService } from '../src/app.service';
import { CharactersService } from '../src/characters/characters.service';
import { Character } from '../src/characters/entities/character.entity';
import { CreateCharacterDto } from '../src/characters/dto/create-character.dto';
chai.use(require('chai-http'));
describe('Test full flow of adding episodes to characters', () => {
let episodesService: EpisodesService;
let charactersService: CharactersService;
const LOCAL_DEV_URL = 'http://localhost:3000';
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [TypeOrmModule.forFeature([Episode, Character]), AppModule],
controllers: [AppController],
providers: [AppService, EpisodesService, CharactersService],
}).compile();
episodesService = module.get<EpisodesService>(EpisodesService);
charactersService = module.get<CharactersService>(CharactersService);
const episodeDto1: CreateEpisodeDto = {
name: 'YODA THE FINAL REVENGE',
productionYear: 2000,
};
const episodeDto2: CreateEpisodeDto = {
name: 'CHEWBACCA AWAKENS',
productionYear: 2090,
};
const characterDto: CreateCharacterDto = {
name: 'Baby Yoda',
race: 'Unknown humanoid',
};
await episodesService.create(episodeDto1);
await episodesService.create(episodeDto2);
await charactersService.create(characterDto);
});
describe('Episodes', () => {
it('should get all episodes', (done) => {
chai
.request(`${LOCAL_DEV_URL}/episodes`)
.get('/')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res).to.be.json;
expect(res.body).to.have.length(2);
expect(res.body[0].name).to.be.equal('YODA THE FINAL REVENGE');
expect(res.body[1].name).to.be.equal('CHEWBACCA AWAKENS');
expect(res.body[0].id).to.exist;
expect(res.body[1].id).to.exist;
done();
});
});
it('should get details about given episode', (done) => {
chai
.request(`${LOCAL_DEV_URL}/episodes`)
.get('/1')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body).to.be.eql({
id: 1,
name: 'YODA THE FINAL REVENGE',
productionYear: 2000,
});
done();
});
});
it('should successfully post episode', (done) => {
const newEpisode: CreateEpisodeDto = {
name: 'Han Solo fights solo',
productionYear: 2056,
};
chai
.request(`${LOCAL_DEV_URL}/episodes`)
.post('/')
.send(newEpisode)
.end((err, res) => {
expect(res).to.have.status(201);
expect(res).to.be.json;
expect(res.body.name).to.be.equal('HAN SOLO FIGHTS SOLO');
expect(res.body.productionYear).to.be.equal(2056);
expect(res.body.id).to.exist;
done();
});
});
});
describe('Characters', () => {
it('should successfully post character', (done) => {
const newCharacter: CreateCharacterDto = {
name: 'Sheev Palpatine',
race: 'human',
};
chai
.request(`${LOCAL_DEV_URL}/characters`)
.post('/')
.send(newCharacter)
.end((err, res) => {
expect(res).to.have.status(201);
expect(res).to.be.json;
expect(res.body.name).to.be.equal('Sheev Palpatine');
expect(res.body.race).to.be.equal('human');
expect(res.body.id).to.exist;
done();
});
});
it('should get details about given character', (done) => {
chai
.request(`${LOCAL_DEV_URL}/characters`)
.get('/1')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body).to.be.eql({
id: 1,
name: 'Baby Yoda',
race: 'Unknown humanoid',
});
done();
});
});
it('should get all characters including last added one', (done) => {
chai
.request(`${LOCAL_DEV_URL}/characters`)
.get('/')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body.items[0].name).to.equal('Baby Yoda');
expect(res.body.items[1].name).to.equal('Sheev Palpatine');
done();
});
});
});
describe('Add Episode to character', () => {
it('should successfully add episode to character', (done) => {
chai
.request(`${LOCAL_DEV_URL}/characters`)
.post(`/1/episodes/2`)
.end((err, res) => {
expect(res).to.have.status(201);
expect(res.body).to.eql({
id: 1,
name: 'Baby Yoda',
race: 'Unknown humanoid',
episodes: [
{ id: 2, name: 'CHEWBACCA AWAKENS', productionYear: 2090 },
],
});
done();
});
});
it('should successfully add second episode to character', (done) => {
chai
.request(`${LOCAL_DEV_URL}/characters`)
.post(`/1/episodes/3`)
.end((err, res) => {
expect(res).to.have.status(201);
done();
});
});
it('should display all episodes added to given character', (done) => {
chai
.request(`${LOCAL_DEV_URL}/characters`)
.get('/1/episodes')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res).to.be.json;
expect(res.body).to.have.length(2);
expect(res.body).to.eql([
{ name: 'CHEWBACCA AWAKENS', id: 2 },
{ name: 'HAN SOLO FIGHTS SOLO', id: 3 },
]);
done();
});
});
it('should display details of specific episode attached to given character', (done) => {
chai
.request(`${LOCAL_DEV_URL}/characters`)
.get('/1/episodes/3')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res).to.be.json;
expect(res.body).to.eql({
id: 3,
name: 'HAN SOLO FIGHTS SOLO',
productionYear: 2056,
});
done();
});
});
it('should display all characters with details including info of episodes', (done) => {
chai
.request(`${LOCAL_DEV_URL}/characters`)
.get('/details')
.end((err, res) => {
expect(res).to.have.status(200);
expect(res).to.be.json;
expect(res.body).to.eql([
{
name: 'Baby Yoda',
race: 'Unknown humanoid',
episodes: ['CHEWBACCA AWAKENS', 'HAN SOLO FIGHTS SOLO'],
},
{
name: 'Sheev Palpatine',
race: 'human',
episodes: [],
},
]);
done();
});
});
});
});
| 32,043
|
https://github.com/existeundelta/DeepLearningfromScratch2018/blob/master/3.7_Some_exercises_with_keras.ipynb
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
DeepLearningfromScratch2018
|
existeundelta
|
Jupyter Notebook
|
Code
| 362
| 1,187
|
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Some exercises with keras"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercice 1:\n",
"CIFAR10 small image classification\n",
"\n",
"The dataset consist of 50,000 32x32 color training images, labeled over 10 categories, and 10,000 test images. "
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Using TensorFlow backend.\n"
]
}
],
"source": [
"# Import MINST data\n",
"from keras.datasets import cifar10\n",
"from keras.utils import np_utils\n",
"from keras.models import Sequential\n",
"from keras.layers import Dense, Activation \n",
"from keras.optimizers import Adam"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercice 2\n",
"The learning rate of the optimizer can be modified with the following function:"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"adam.lr.assign(learning_rate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Modify the code in order to decrease the learning_rate value every 10 Epochs. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercice 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First of all, let's play a little bit with http://playground.tensorflow.org/"
]
},
{
"cell_type": "raw",
"metadata": {
"collapsed": false
},
"source": [
"Then create a mulitlayer perceptron with the following data and architecture you think is the best:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(600, 2)\n"
]
}
],
"source": [
"from sklearn.model_selection import train_test_split\n",
"# the data, shuffled and split between train and test sets\n",
"from sklearn.datasets import make_moons, make_circles, make_classification\n",
"X, y = make_moons(n_samples = 1000,noise=0.3, random_state=0)\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4, random_state=42)\n",
"print X_train.shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
| 3,349
|
https://github.com/brandonbraun653/Apollo/blob/master/lib/am335x_sdk/ti/starterware/include/date_time.h
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Apollo
|
brandonbraun653
|
C
|
Code
| 668
| 1,414
|
/**
* \file date_time.h
*
* \brief This file contains declarations of structures and enums
* which represent Time and Date information.
*/
/**
*
* \copyright Copyright (C) 2013 Texas Instruments Incorporated -
* http://www.ti.com/
*/
/*
* Redistribution and use 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 and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef DATE_TIME_H_
#define DATE_TIME_H_
/* ========================================================================== */
/* Include Files */
/* ========================================================================== */
/* None. */
#ifdef __cplusplus
extern "C" {
#endif
/* ========================================================================== */
/* Macros */
/* ========================================================================== */
/** \brief Enumerates the different Time modes. */
typedef enum timeMode
{
TIME_MODE_MIN = 0U,
/**< Minimum time mode used for input validation. */
TIME_MODE_24_HR = TIME_MODE_MIN,
/**< 12 Hour Time mode */
TIME_MODE_12_HR,
/**< 24 Hour Time mode */
TIME_MODE_MAX = TIME_MODE_24_HR
/**< Maximum time mode used for input validation. */
}timeMode_t;
/** \brief Enumerates the different Time Meridiem formats. */
typedef enum timeMeridiem
{
TIME_MERIDIEM_MIN = 0U,
/**< Minimum Time meridiem mode. */
TIME_MERIDIEM_AM = TIME_MERIDIEM_MIN,
/**< AM (Ante-Meridiem) Time Format */
TIME_MERIDIEM_PM,
/**< PM (Post-Meridiem) Time Format */
TIME_MERIDIEM_MAX = TIME_MERIDIEM_PM
}timeMeridiem_t;
/** \brief enumerates the different day of the week */
typedef enum weekDay
{
WEEK_DAY_MIN = 0U,
/**< Minimum value of the Week Day */
WEEK_DAY_SUNDAY = WEEK_DAY_MIN,
/**< Indicates Sunday */
WEEK_DAY_MONDAY,
/**< Indicates Monday */
WEEK_DAY_TUESDAY,
/**< Indicates Tuesday */
WEEK_DAY_WEDNESDAY,
/**< Indicates Wednesday */
WEEK_DAY_THURSDAY,
/**< Indicates Thursday */
WEEK_DAY_FRIDAY,
/**< Indicates Friday */
WEEK_DAY_SATURDAY,
/**< Indicates Saturday */
WEEK_DAY_MAX = WEEK_DAY_SATURDAY
/**< Maximum value of the Week Day */
}weekDay_t;
/** \brief Structure representing the Time information. */
typedef struct timeObj
{
uint32_t hours;
/**< Time value in hours. */
uint32_t minutes;
/**< Time value in minutes. */
uint32_t seconds;
/**< Time value in seconds */
uint32_t nanoSec;
/**< Time value in nano seconds */
timeMode_t timeMode;
/**< Hour Mode which can take any of the two values
from the enum #timeMode_t to represent either
12 Hour mode or 24 Hour mode. */
timeMeridiem_t meridiemMode;
/**< Meridiem type to indicate either AM mode or PM mode which
can take any of the values from the following enum
#timeMeridiem_t */
}timeObj_t;
/** \brief Structure representing the Date information. */
typedef struct dateObj
{
uint32_t day;
/**< Value to represent the Day. */
uint32_t month;
/**< Value to represent the Month. */
uint32_t year;
/**< Value to represent the Year. */
weekDay_t weekDay;
/**< Value to represent the day of the week which can
can take any of the values from the following enum
#weekDay_t */
}dateObj_t;
/* ========================================================================== */
/* Function Declarations */
/* ========================================================================== */
/* None */
#ifdef __cplusplus
}
#endif
#endif /* #ifndef DATE_TIME_H_ */
| 41,069
|
https://github.com/omingo-cn/keycloak-documentation-i18n/blob/master/i18n/po/ja_JP/authorization_services/topics/hello-world-before-start.ja_JP.po
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
keycloak-documentation-i18n
|
omingo-cn
|
Gettext Catalog
|
Code
| 242
| 1,008
|
# SOME DESCRIPTIVE TITLE
# Copyright (C) YEAR Nomura Research Institute, Ltd.
# This file is distributed under the same license as the keycloak-documentation-i18n package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: keycloak-documentation-i18n\n"
"Last-Translator: Kohei Tamura <ktamura.biz.80@gmail.com>, 2017\n"
"Language-Team: Japanese (Japan) (https://www.transifex.com/openstandia/teams/79437/ja_JP/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: ja_JP\n"
"Plural-Forms: nplurals=1; plural=0;\n"
#. type: Title =
#, no-wrap
msgid "Before You Start"
msgstr "始める前に"
#. type: Plain text
msgid ""
"This guide is based on the *{project_name} Demo Distribution*. Download the "
"demo distribution before proceeding."
msgstr "このガイドは、 *{project_name}のデモ配布物* に基づいています。続行する前にデモ配布物をダウンロードしてください。"
#. type: Plain text
msgid ""
"This guide assumes that you are already familiar with {project_name} and "
"that you are able to install and boot a {project_name} Server. For more "
"information, see https://keycloak.gitbooks.io/getting-started-"
"tutorials/content/[the Getting Started tutorials]."
msgstr ""
"このガイドでは、{project_name}についてすでに理解しており、{project_name}サーバーをインストールして起動できることを前提としています。詳細については、link:https://keycloak.gitbooks.io"
"/getting-started-tutorials/content/[Getting Startedチュートリアル]を参照してください。"
#. type: Plain text
msgid ""
"Ensure you have a {project_name} instance running; the default configuration"
" is http://localhost:8080/auth[http://localhost:8080/auth]. After logging in"
" to the Administration Console, a page similar to this one is displayed:"
msgstr ""
"{project_name}インスタンスを起動していることを確認してください。デフォルト設定はlink:http://localhost:8080/auth[http://localhost:8080/auth]です。管理コンソールにログインすると、次のようなページが表示されます。"
#. type: Block title
#, no-wrap
msgid "{project_name} Administration Console"
msgstr "{project_name}管理コンソール"
#. type: Plain text
msgid ""
"image:{project_images}/getting-started/kc-start-"
"page.png[alt=\"{project_name} Administration Console\"]"
msgstr ""
"image:{project_images}/getting-started/kc-start-"
"page.png[alt=\"{project_name}管理コンソール\"]"
#. type: Plain text
msgid ""
"The source code for the getting started tutorials can be obtained from the "
"demo distributions. The authorization-related examples are located at "
"*${KEYCLOAK_DEMO_SERVER_DIR}/examples/authz*."
msgstr ""
"初心者向けのチュートリアルのソースコードは、デモ配布物から入手できます。認可関連のサンプルは、 "
"*${KEYCLOAK_DEMO_SERVER_DIR}/examples/authz* にあります。"
| 22,220
|
https://github.com/JoshKarpel/euler-python/blob/master/problems/007.py
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
euler-python
|
JoshKarpel
|
Python
|
Code
| 13
| 50
|
from problems import primes
def solve():
return primes.find_n_primes(10001)[-1]
if __name__ == '__main__':
print(solve())
| 16,677
|
https://github.com/MananUpadhyay/ngraph/blob/master/src/ngraph/builder/quantization.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
ngraph
|
MananUpadhyay
|
C++
|
Code
| 558
| 2,472
|
//*****************************************************************************
// Copyright 2017-2018 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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <memory>
#include "ngraph/builder/quantization.hpp"
#include "ngraph/op/constant.hpp"
#include "quantization_util.hpp"
using namespace std;
using namespace ngraph;
namespace ngraph
{
namespace builder
{
std::shared_ptr<Node> ScaledQuantize(std::shared_ptr<Node> input,
std::shared_ptr<Node> min,
std::shared_ptr<Node> max,
const ngraph::element::Type& type,
const ngraph::AxisSet& axes,
op::Quantize::RoundMode round_mode)
{
auto offset = op::Constant::create(type, Shape{}, {0});
if (input->get_element_type() == element::f32)
{
float scale =
builder::quantization_util::get_quantization_scale<float>(min, max, type, true);
auto quantize_scale =
op::Constant::create(input->get_element_type(), Shape{}, {scale});
return make_shared<op::Quantize>(
input, quantize_scale, offset, type, axes, round_mode);
}
else if (input->get_element_type() == element::f64)
{
double scale = builder::quantization_util::get_quantization_scale<double>(
min, max, type, true);
auto quantize_scale =
op::Constant::create(input->get_element_type(), Shape{}, {scale});
return make_shared<op::Quantize>(
input, quantize_scale, offset, type, axes, round_mode);
}
else
{
throw ngraph_error("Unsupported quantization element type");
}
}
std::shared_ptr<Node> ScaledDequantize(std::shared_ptr<Node> input,
std::shared_ptr<Node> min,
std::shared_ptr<Node> max,
const ngraph::element::Type& type,
const ngraph::AxisSet& axes)
{
auto input_et = input->get_element_type();
auto offset = op::Constant::create(input_et, Shape{}, {0});
if (type == element::f32)
{
float scale =
builder::quantization_util::get_quantization_scale<float>(min, max, input_et);
auto dequantize_scale = op::Constant::create(type, Shape{}, {scale});
return make_shared<op::Dequantize>(input, dequantize_scale, offset, type, axes);
}
else if (type == element::f64)
{
double scale =
builder::quantization_util::get_quantization_scale<double>(min, max, input_et);
auto dequantize_scale = op::Constant::create(type, Shape{}, {scale});
return make_shared<op::Dequantize>(input, dequantize_scale, offset, type, axes);
}
else
{
throw ngraph_error("Unsupported dequantization element type");
}
}
std::shared_ptr<Node> ScaledQuantizedAvgPool(const std::shared_ptr<Node>& arg,
const Shape& window_shape,
const Strides& window_movement_strides,
const Shape& padding_below,
const Shape& padding_above,
bool include_padding_in_avg_computation,
const std::shared_ptr<Node> min,
const std::shared_ptr<Node> max)
{
return make_shared<op::QuantizedAvgPool>(arg,
window_shape,
window_movement_strides,
padding_below,
padding_above,
include_padding_in_avg_computation);
}
std::shared_ptr<Node>
ScaledQuantizedConvolutionBias(const std::shared_ptr<Node>& data_batch,
const std::shared_ptr<Node>& filters,
const std::shared_ptr<Node>& bias,
const Strides& window_movement_strides,
const Strides& window_dilation_strides,
const CoordinateDiff& padding_below,
const CoordinateDiff& padding_above,
const Strides& data_dilation_strides,
const std::shared_ptr<Node> min_input,
const std::shared_ptr<Node> max_input,
const std::shared_ptr<Node> min_filter,
const std::shared_ptr<Node> max_filter,
const std::shared_ptr<Node> min_freezed_output,
const std::shared_ptr<Node> max_freezed_output,
const bool with_relu)
{
float scale = builder::quantization_util::get_scale(min_input,
max_input,
min_filter,
max_filter,
min_freezed_output,
max_freezed_output);
auto requantization_scale = op::Constant::create(element::f32, Shape{1}, {scale});
return make_shared<op::QuantizedConvolutionBias>(data_batch,
filters,
bias,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
requantization_scale,
with_relu);
}
std::shared_ptr<Node>
ScaledQuantizedConvolutionRelu(const std::shared_ptr<Node>& data_batch,
const std::shared_ptr<Node>& filters,
const Strides& window_movement_strides,
const Strides& window_dilation_strides,
const CoordinateDiff& padding_below,
const CoordinateDiff& padding_above,
const Strides& data_dilation_strides,
const std::shared_ptr<Node> min_input,
const std::shared_ptr<Node> max_input,
const std::shared_ptr<Node> min_filter,
const std::shared_ptr<Node> max_filter,
const std::shared_ptr<Node> min_freezed_output,
const std::shared_ptr<Node> max_freezed_output)
{
float scale = builder::quantization_util::get_scale(min_input,
max_input,
min_filter,
max_filter,
min_freezed_output,
max_freezed_output);
auto requantization_scale = op::Constant::create(element::f32, Shape{1}, {scale});
return make_shared<op::QuantizedConvolutionRelu>(data_batch,
filters,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
requantization_scale);
}
std::shared_ptr<Node>
ScaledQuantizedConvolution(const std::shared_ptr<Node>& data_batch,
const std::shared_ptr<Node>& filters,
const Strides& window_movement_strides,
const Strides& window_dilation_strides,
const CoordinateDiff& padding_below,
const CoordinateDiff& padding_above,
const Strides& data_dilation_strides,
const std::shared_ptr<Node> min_input,
const std::shared_ptr<Node> max_input,
const std::shared_ptr<Node> min_filter,
const std::shared_ptr<Node> max_filter,
const std::shared_ptr<Node> min_freezed_output,
const std::shared_ptr<Node> max_freezed_output)
{
float scale = builder::quantization_util::get_scale(min_input,
max_input,
min_filter,
max_filter,
min_freezed_output,
max_freezed_output);
auto requantization_scale = op::Constant::create(element::f32, Shape{1}, {scale});
return make_shared<op::QuantizedConvolution>(data_batch,
filters,
window_movement_strides,
window_dilation_strides,
padding_below,
padding_above,
data_dilation_strides,
requantization_scale);
}
std::shared_ptr<Node> ScaledQuantizedMaxPool(const std::shared_ptr<Node>& arg,
const Shape& window_shape,
const Strides& window_movement_strides,
const Shape& padding_below,
const Shape& padding_above,
const std::shared_ptr<Node> min,
const std::shared_ptr<Node> max)
{
return make_shared<op::QuantizedMaxPool>(
arg, window_shape, window_movement_strides, padding_below, padding_above);
}
}
}
| 26,645
|
https://github.com/yujie2623/app_push/blob/master/src/views/dashboard/index.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
app_push
|
yujie2623
|
Vue
|
Code
| 1,065
| 4,744
|
<template>
<div class="dashboard-container">
<div class="dashboard">
<el-row :gutter="20" :class="{ 'loading': loading }">
<el-col :span="6">
<router-link to="/server/server">
<div class="grid-content bg-purple dashboard-server">
<div class="serverImage">
<svg-icon icon-class="serverSvg" />
</div>
<div class="serverData">
<p>{{ $t('home.childServerNum') }}</p>
<p>{{ indexData.termConnect }}</p>
</div>
</div>
</router-link>
</el-col>
<el-col :span="6">
<router-link to="/application/application">
<div class="grid-content bg-purple dashboard-server">
<div class="serverImage">
<svg-icon icon-class="appSvg" />
</div>
<div class="serverData">
<p>{{ $t('home.appNum') }}</p>
<p>{{ indexData.appnum }}</p>
</div>
</div>
</router-link>
</el-col>
<el-col :span="6">
<router-link to="/user/user">
<div class="grid-content bg-purple dashboard-server">
<div class="serverImage">
<svg-icon icon-class="userSvg" />
</div>
<div class="serverData">
<p>{{ $t('home.userCreated') }}</p>
<p>{{ indexData.usernum }}</p>
</div>
</div>
</router-link>
</el-col>
<el-col :span="6">
<router-link to="/user/user?status=1">
<div class="grid-content bg-purple dashboard-server">
<div class="serverImage">
<svg-icon icon-class="termSvg" />
</div>
<div class="serverData">
<p>{{ $t('home.linkTerm') }}</p>
<p>{{ indexData.servernum }}</p>
</div>
</div>
</router-link>
</el-col>
</el-row>
<div class="server-process">
<h5 class="termdata-title">{{ $t('home.mainServer') }}</h5>
<div class="dashboard-mainServer" :class="{ 'loading': loading }">
<div class="mainServer-left">
<p>{{ $t('home.serverIpAdrr', { 'n': serverlist.ip_addr }) }}</p>
<p>服务器备用IP地址: <span v-if="!isShowIp" @click="showInput">{{ serverlist.public_ip }} <i class="el-icon-edit" /></span>
<el-input v-if="isShowIp" v-model="public_ip" size="mini" style="width:150px" @blur="editIp" />
</p>
<p>{{ $t('home.serverConfig', { 'n': ipconf }) }}</p>
<p>{{ $t('home.disk_IO') }}:{{ retain(serverlist.io_read_speed) }}MB/S | {{ retain(serverlist.io_write_speed) }}MB/S</p>
<p>{{ $t('home.serverRunStatus', { 'n': $t('inOperation') }) }}
<el-button size="mini" @click.native="start">{{ $t('restart') }}</el-button>
<el-button size="mini" @click.native="shutdown">{{ $t('shutdown') }}</el-button>
</p>
</div>
<div class="mainServer-right">
<div>
<span>CPU</span>
<div><el-progress type="circle" :percentage="cpuscale" /></div>
<span>{{ $t('home.used') }}{{ cpuscale }}%</span>
</div>
<div>
<span>{{ $t('home.memory') }}</span>
<div><el-progress type="circle" :percentage="memscale" /></div>
<span>{{ $t('home.used1') }}{{ serverlist.mem_used }}G/{{ $t('home.total') }}{{ serverlist.mem_total }}G</span>
</div>
<div>
<span>{{ $t('home.storage') }}</span>
<div><el-progress type="circle" :percentage="diskscale" /></div>
<span>{{ $t('home.used1') }}{{ serverlist.disk_used }}G/{{ $t('home.total') }}{{ serverlist.disk_total }}G</span>
</div>
</div>
</div>
</div>
<el-row :gutter="20" class="dashboard-termdata">
<el-col :span="8">
<h5 class="termdata-title">{{ $t('home.termAuthorize') }}</h5>
<div class="termdata-chart" :class="{ 'loading': loading }">
<div v-if="authdata && authdata.length > 0" class="termdata-left">
<p>{{ $t('home.authorized') }}:{{ authdata[0].value }}</p>
<p>{{ $t('home.surplus') }}:{{ authdata[1].value }}</p>
</div>
<line-chart :chart-data="authdata" />
</div>
</el-col>
<el-col :span="16">
<h5 class="termdata-title">{{ $t('home.childServer') }}</h5>
<el-table :data="subserver" height="300" border style="width: 100%" :class="{ 'loading': loading }">
<el-table-column prop="name" :label="$t('home.serverName')" align="center" min-width="100" show-overflow-tooltip />
<el-table-column prop="gname" :label="$t('home.serverGroup')" align="center" min-width="100" show-overflow-tooltip />
<el-table-column prop="os_version" :label="$t('home.os')" align="center" min-width="100" show-overflow-tooltip />
<el-table-column prop="ip_addr" :label="$t('home.serverIp')" align="center" min-width="100" show-overflow-tooltip />
<el-table-column prop="cpu_load" :label="$t('home.cpuUsage')" align="center" min-width="100">
<template slot-scope="scope">
<span>{{ percentage(scope.row.cpu_load) }}%</span>
</template>
</el-table-column>
<el-table-column prop="mem_load" :label="$t('home.memoryUsage')" align="center" min-width="100">
<template slot-scope="scope">
<span>{{ percentage(scope.row.mem_load) }}%</span>
</template>
</el-table-column>
<el-table-column prop="disk_load" :label="$t('serverPage.diskUsage')" align="center" min-width="100" show-overflow-tooltip>
<template slot-scope="scope">
{{ percentage(scope.row.disk_load) }}%
</template>
</el-table-column>
<el-table-column prop="disk_load" :label="$t('serverPage.io') + '(MB/s)'" align="center" min-width="120" show-overflow-tooltip>
<template slot-scope="scope">
{{ retain(scope.row.io_read_speed) }}/{{ retain(scope.row.io_write_speed) }}
</template>
</el-table-column>
<el-table-column prop="run_state" :label="$t('home.runStatus')" align="center" min-width="100" show-overflow-tooltip>
<template slot-scope="scope">
<span v-if="scope.row.run_state === false">{{ $t('home.Shutdown') }}</span>
<span v-else>{{ $t('home.inOperation') }}</span>
</template>
</el-table-column>
</el-table>
</el-col>
</el-row>
<el-row :gutter="20" class="dashboard-termdata">
<el-col :span="24">
<h5 class="termdata-title">用户使用率</h5>
<div class="termdata-chart" :class="{ 'loading': loading }">
<div class="usetime">
<span>查询时间:</span>
<el-date-picker
v-model="usetime"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="yyyy-MM-dd"
:picker-options="pickerOptions1"
/>
<span style="padding-left:30px">
<el-button type="primary" plain @click.native="UseTimeFormat(0)">查询</el-button>
<el-button type="primary" plain @click.native="exportUseTime">导出</el-button>
</span>
</div>
<BrokenLine :chart-data="usedata" />
</div>
</el-col>
</el-row>
</div>
</div>
</template>
<script>
var time = null
import { mapGetters } from 'vuex'
import LineChart from './componet/LineChart'
import BrokenLine from './componet/BrokenLineChart'
import * as dashboard from '@/api/dashboard'
import { get_all_machine_list } from '@/api/server'
import { parseTime } from '@/utils/index.js'
export default {
name: 'Dashboard',
components: { LineChart, BrokenLine },
data() {
return {
public_ip: '',
isShowIp: false,
loading: true,
// 进度条百分比
cpuscale: 0,
memscale: 0,
diskscale: 0,
ipconf: '',
serverlist: {},
subserver: [],
authdata: [],
usedata: [],
usetime: [],
pickerOptions1: {
disabledDate(time) {
return time.getTime() > Date.now()
}
},
// 首页值
indexData: {
appnum: '',
termConnect: '',
usernum: '',
servernum: ''
}
}
},
computed: {
...mapGetters([
'name'
])
},
mounted() {
time = setInterval(() => {
this.get_index_info()
}, 5000)
this.get_index_info()
this.getParentServer()
this.UseTimeFormat()
},
destroyed() {
clearInterval(time)
},
methods: {
// 导出使用时间
exportUseTime() {
const url = process.env.VUE_APP_BASE_API + `/index/export_user_usage_rate?start_time=${this.usetime[0]}&end_time=${this.usetime[1]}`
window.open(url)
},
// 用户使用率 显示一周7天的时间
UseTimeFormat(v) {
if (v !== 0) {
const currentTime = parseTime(new Date().getTime(), '{y}-{m}-{d}')
const currentTimeAddSeven = parseTime(new Date().getTime() - 3600 * 1000 * 24 * 7, '{y}-{m}-{d}')
this.usetime = [currentTimeAddSeven, currentTime]
}
const query = Object.assign({}, { start_time: this.usetime[0], end_time: this.usetime[1] })
dashboard.getUserUsageRate(query).then(res => {
if (res.code === 0) {
this.usedata = res.data_list
}
})
},
showInput() {
this.isShowIp = true
this.public_ip = this.serverlist.public_ip
},
editIp() {
dashboard.setip({ public_ip: this.public_ip }).then(res => {
if (res.code === 0) {
this.get_index_info()
this.isShowIp = false
}
})
},
// 首页部分数据
get_index_info() {
dashboard.get_index_info().then(res => {
if (res.code === 0) {
// 获取应用数量
this.indexData.appnum = res.app_count
// 获取已连接终端数量
this.indexData.termConnect = res.machine_count
// 获取用户数量
this.indexData.usernum = res.user_count
// 获取节点数量
this.indexData.servernum = res.online_term_count
// 获取授权chart
this.authdata = [
{ value: res.term_license.used_num, name: this.$t('home.authorized') },
{ value: res.term_license.free, name: this.$t('home.surplus') }
]
// 获取所有的服务器
this.serverlist = res.server_dict
this.cpuscale = this.percentage(res.server_dict.cpu_load)
this.memscale = this.percentage(res.server_dict.mem_load)
this.diskscale = this.percentage(res.server_dict.disk_load)
this.ipconf = this.serverlist.cpu_info + '/' + this.serverlist.mem_total + 'G/' + this.serverlist.disk_used + 'G|' + this.serverlist.disk_total + 'G'
this.loading = false
}
})
},
getParentServer() {
get_all_machine_list().then(res => {
if (res.code === 0) {
this.subserver = res.list
}
})
},
// 转百分比
percentage(percentage) {
return Math.floor((percentage * 100) * 100) / 100
},
// 保留2位小数
retain(retain) {
return Math.floor(retain * 100) / 100
},
// 关机
shutdown() {
this.$confirm(this.$t('home.isShutdownTit'), this.$t('home.isShutdown'), {
confirmButtonText: this.$t('sure'),
cancelButtonText: this.$t('cancel'),
type: 'warning'
}).then(() => {
dashboard.poweroff().then(res => {
if (res.code === 0) {
this.$message.success('服务器即将关机')
} else {
this.$message.error(res.msg)
}
})
}).catch(() => {})
},
// 重启
start() {
this.$confirm(this.$t('home.isRestartTit'), this.$t('home.isRestart'), {
confirmButtonText: this.$t('sure'),
cancelButtonText: this.$t('cancel'),
type: 'warning'
}).then(() => {
dashboard.restart().then(res => {
if (res.code === 0) {
this.$message.success('服务器即将重启')
} else {
this.$message.error(res.msg)
}
})
}).catch(() => {})
}
}
}
</script>
<style lang="scss" scoped>
.server-process, .dashboard-termdata {
margin-top: 30px;
}
.termdata-title {
height: 40px;
margin: 0;
background: #eaeaea;
color: #303133;
font-weight: normal;
line-height: 40px;
padding-left: 20px;
}
.dashboard {
&-container {
margin: 30px;
}
&-server {
display: flex;
align-items: center;
border: 1px solid #dadada;
padding: 20px;
.serverImage {
flex-grow: 0;
svg {
font-size: 48px;
}
}
.serverData {
padding-left: 20px;
flex-grow: 1;
p {
line-height: 30px;
margin: 0;
white-space: nowrap;
width: 80%;
overflow: hidden;
text-overflow: ellipsis;
}
p:first-child {
color:#999;
}
p:last-child {
font-size: 24px;
}
}
}
.server-process {
border: 1px solid #eaeaea;
}
&-mainServer {
display: flex;
padding: 20px;
.mainServer {
&-left {
width: 40%;
}
&-right {
width: 60%;
display: flex;
>div {
display: flex;
flex-direction: column;
text-align: center;
flex-grow: 1;
span {
padding: 10px 0;
}
}
}
}
}
.dashboard-termdata {
.termdata {
&-title {
height: 40px;
margin: 0;
background: #eaeaea;
color: #303133;
font-weight: normal;
line-height: 40px;
padding-left: 20px;
}
&-chart {
position: relative;
border: 1px solid #EBEEF5;
// height: 300px;
.usetime {
display: flex;
align-items: center;
justify-content: center;
margin-top: 30px;
}
}
&-left {
position: absolute;
left: 30px;
top: 10%;
}
}
}
}
</style>
| 15,394
|
https://github.com/bcgov/sbc-pay/blob/master/jobs/payment-jobs/tasks/ejv_payment_task.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
sbc-pay
|
bcgov
|
Python
|
Code
| 1,051
| 3,361
|
# Copyright © 2019 Province of British Columbia
#
# 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 License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Task to create Journal Voucher for gov account payments."""
import time
from typing import List
from flask import current_app
from pay_api.models import DistributionCode as DistributionCodeModel
from pay_api.models import EjvFile as EjvFileModel
from pay_api.models import EjvHeader as EjvHeaderModel
from pay_api.models import EjvInvoiceLink as EjvInvoiceLinkModel
from pay_api.models import Invoice as InvoiceModel
from pay_api.models import InvoiceReference as InvoiceReferenceModel
from pay_api.models import PaymentAccount as PaymentAccountModel
from pay_api.models import db
from pay_api.utils.enums import DisbursementStatus, EjvFileType, InvoiceReferenceStatus, InvoiceStatus, PaymentMethod
from pay_api.utils.util import generate_transaction_number
from tasks.common.cgi_ejv import CgiEjv
class EjvPaymentTask(CgiEjv):
"""Task to create Journal Voucher for gov account payments."""
@classmethod
def create_ejv_file(cls):
"""Create JV files and upload to CGI.
Steps:
1. Find all accounts for GI or GA.
2. Find outstanding invoices for payment.
3. Group by account and create JD for each service fee and filing fee.
4. Upload the file to minio for future reference.
5. Upload to sftp for processing. First upload JV file and then a TRG file.
6. Update the statuses and create records to for the batch.
"""
cls._create_ejv_file_for_gov_account(batch_type='GI')
cls._create_ejv_file_for_gov_account(batch_type='GA')
@classmethod
def _create_ejv_file_for_gov_account(cls, batch_type: str): # pylint:disable=too-many-locals, too-many-statements
"""Create EJV file for the partner and upload."""
ejv_content: str = ''
batch_total: float = 0
control_total: int = 0
# Create a ejv file model record.
ejv_file_model: EjvFileModel = EjvFileModel(
file_type=EjvFileType.PAYMENT.value,
file_ref=cls.get_file_name(),
disbursement_status_code=DisbursementStatus.UPLOADED.value
).flush()
batch_number = cls.get_batch_number(ejv_file_model.id)
# Get all invoices which should be part of the batch type.
account_ids = cls._get_account_ids_for_payment(batch_type)
# JV Batch Header
batch_header: str = cls.get_batch_header(batch_number, batch_type)
current_app.logger.info('Processing accounts.')
for account_id in account_ids:
account_jv: str = ''
# Find all invoices for the gov account to pay.
invoices = cls._get_invoices_for_payment(account_id)
pay_account: PaymentAccountModel = PaymentAccountModel.find_by_id(account_id)
# If no invoices continue.
if not invoices or not pay_account.billable:
continue
disbursement_desc = f'{pay_account.name[:100]:<100}'
effective_date: str = cls.get_effective_date()
# Construct journal name
ejv_header_model: EjvFileModel = EjvHeaderModel(
payment_account_id=account_id,
disbursement_status_code=DisbursementStatus.UPLOADED.value,
ejv_file_id=ejv_file_model.id
).flush()
journal_name: str = cls.get_journal_name(ejv_header_model.id)
# Distribution code for the account.
debit_distribution_code: DistributionCodeModel = DistributionCodeModel.find_by_active_for_account(
account_id
)
debit_distribution = cls.get_distribution_string(debit_distribution_code) # Debit from GOV account GL
line_number: int = 0
total: float = 0
current_app.logger.info(f'Processing invoices for account_id: {account_id}.')
for inv in invoices:
# If it's a JV reversal credit and debit is reversed.
is_jv_reversal = inv.invoice_status_code == InvoiceStatus.REFUND_REQUESTED.value
# If it's reversal, If there is no COMPLETED invoice reference, then no need to reverse it.
# Else mark it as CANCELLED, as new invoice reference will be created
if is_jv_reversal:
if (inv_ref := InvoiceReferenceModel.find_by_invoice_id_and_status(
inv.id, InvoiceReferenceStatus.COMPLETED.value
)) is None:
continue
inv_ref.status_code = InvoiceReferenceStatus.CANCELLED.value
line_items = inv.payment_line_items
for line in line_items:
# Line can have 2 distribution, 1 for the total and another one for service fees.
line_distribution_code: DistributionCodeModel = DistributionCodeModel.find_by_id(
line.fee_distribution_id)
if line.total > 0:
total += line.total
line_distribution = cls.get_distribution_string(line_distribution_code)
flow_through = f'{line.invoice_id:<110}'
# Credit to BCREG GL
line_number += 1
control_total += 1
# If it's normal payment then the Line distribution goes as Credit,
# else it goes as Debit as we need to debit the fund from BC registry GL.
account_jv = account_jv + cls.get_jv_line(batch_type, line_distribution, disbursement_desc,
effective_date, flow_through, journal_name,
line.total,
line_number, 'C' if not is_jv_reversal else 'D')
# Debit from GOV ACCOUNT GL
line_number += 1
control_total += 1
# If it's normal payment then the Gov account GL goes as Debit,
# else it goes as Credit as we need to credit the fund back to ministry.
account_jv = account_jv + cls.get_jv_line(batch_type, debit_distribution, disbursement_desc,
effective_date, flow_through, journal_name,
line.total,
line_number, 'D' if not is_jv_reversal else 'C')
if line.service_fees > 0:
service_fee_distribution_code: DistributionCodeModel = DistributionCodeModel.find_by_id(
line_distribution_code.service_fee_distribution_code_id)
total += line.service_fees
service_fee_distribution = cls.get_distribution_string(service_fee_distribution_code)
flow_through = f'{line.invoice_id:<110}'
# Credit to BCREG GL
line_number += 1
control_total += 1
account_jv = account_jv + cls.get_jv_line(batch_type, service_fee_distribution,
disbursement_desc,
effective_date, flow_through, journal_name,
line.service_fees,
line_number, 'C' if not is_jv_reversal else 'D')
# Debit from GOV ACCOUNT GL
line_number += 1
control_total += 1
account_jv = account_jv + cls.get_jv_line(batch_type, debit_distribution, disbursement_desc,
effective_date, flow_through, journal_name,
line.service_fees,
line_number, 'D' if not is_jv_reversal else 'C')
batch_total += total
# Skip if we have no total from the invoices.
if total > 0:
# A JV header for each account.
control_total += 1
account_jv = cls.get_jv_header(batch_type, cls.get_journal_batch_name(batch_number),
journal_name, total) + account_jv
ejv_content = ejv_content + account_jv
# Create ejv invoice link records and set invoice status
current_app.logger.info('Creating ejv invoice link records and setting invoice status.')
for inv in invoices:
current_app.logger.debug(f'Creating EJV Invoice Link for invoice id: {inv.id}')
# Create Ejv file link and flush
ejv_invoice_link = EjvInvoiceLinkModel(invoice_id=inv.id, ejv_header_id=ejv_header_model.id,
disbursement_status_code=DisbursementStatus.UPLOADED.value)
db.session.add(ejv_invoice_link)
# Set distribution status to invoice
# Create invoice reference record
current_app.logger.debug(f'Creating Invoice Reference for invoice id: {inv.id}')
inv_ref = InvoiceReferenceModel(
invoice_id=inv.id,
invoice_number=generate_transaction_number(inv.id),
reference_number=None,
status_code=InvoiceReferenceStatus.ACTIVE.value
)
db.session.add(inv_ref)
db.session.flush() # Instead of flushing every entity, flush all at once.
if not ejv_content:
db.session.rollback()
return
# JV Batch Trailer
batch_trailer: str = cls.get_batch_trailer(batch_number, batch_total, batch_type, control_total)
ejv_content = f'{batch_header}{ejv_content}{batch_trailer}'
# Create a file add this content.
file_path_with_name, trg_file_path = cls.create_inbox_and_trg_files(ejv_content)
current_app.logger.info('Uploading to ftp.')
# Upload file and trg to FTP
cls.upload(ejv_content, cls.get_file_name(), file_path_with_name, trg_file_path)
# commit changes to DB
db.session.commit()
# Add a sleep to prevent collision on file name.
time.sleep(1)
@classmethod
def _get_account_ids_for_payment(cls, batch_type) -> List[int]:
"""Return account IDs for payment."""
# CREDIT : Distribution code against fee schedule
# DEBIT : Distribution code against account.
bc_reg_client_code = current_app.config.get('CGI_BCREG_CLIENT_CODE') # 112 #TODO
query = db.session.query(DistributionCodeModel.account_id) \
.filter(DistributionCodeModel.stop_ejv.is_(False) | DistributionCodeModel.stop_ejv.is_(None)) \
.filter(DistributionCodeModel.account_id.isnot(None))
if batch_type == 'GA':
# Rule for GA. Credit is 112 and debit is 112. For BCREG client code is 112
account_ids: List[int] = query.filter(DistributionCodeModel.client == bc_reg_client_code).all()
else:
# Rule for GI. Credit is 112 and debit is not 112. For BCREG client code is 112
account_ids: List[int] = query.filter(DistributionCodeModel.client != bc_reg_client_code).all()
return account_ids
@classmethod
def _get_invoices_for_payment(cls, account_id: int) -> List[InvoiceModel]:
"""Return invoices for payments."""
valid_statuses = (InvoiceStatus.APPROVED.value, InvoiceStatus.REFUND_REQUESTED.value)
invoice_ref_subquery = db.session.query(InvoiceReferenceModel.invoice_id). \
filter(InvoiceReferenceModel.status_code.in_((InvoiceReferenceStatus.ACTIVE.value,)))
invoices: List[InvoiceModel] = db.session.query(InvoiceModel) \
.filter(InvoiceModel.invoice_status_code.in_(valid_statuses)) \
.filter(InvoiceModel.payment_method_code == PaymentMethod.EJV.value) \
.filter(InvoiceModel.payment_account_id == account_id) \
.filter(InvoiceModel.id.notin_(invoice_ref_subquery)) \
.all()
return invoices
| 13,451
|
https://github.com/mastapegs/ji-cloud/blob/master/frontend/apps/crates/entry/module/legacy/play/src/base/activities/talk_type/dom.rs
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT
| null |
ji-cloud
|
mastapegs
|
Rust
|
Code
| 211
| 959
|
use super::state::*;
use crate::base::styles;
use crate::config::HINT_TIME_MS;
use dominator::{clone, html, with_node, Dom};
use futures_signals::signal::SignalExt;
use std::rc::Rc;
use utils::{
prelude::*,
resize::{resize_info_signal, ResizeInfo},
};
use components::overlay::handle::OverlayHandle;
use gloo_timers::future::TimeoutFuture;
impl TalkType {
pub fn render(self: Rc<Self>) -> Dom {
let state = self;
html!("div", {
.class(&*styles::FULL_STAGE)
.children_signal_vec(
resize_info_signal().map(clone!(state => move |resize_info| {
state.items
.iter()
.map(|item| item.clone().render_text_input(state.clone(), &resize_info))
.collect()
}))
.to_signal_vec()
)
})
}
}
impl TalkTypeItem {
pub fn render_text_input(
self: Rc<Self>,
parent: Rc<TalkType>,
resize_info: &ResizeInfo,
) -> Dom {
let state = self;
let bounds = state.bounds.denormalize(resize_info);
let mut abs_bounds = bounds;
abs_bounds.x += resize_info.x;
abs_bounds.y += resize_info.y;
html!("legacy-input-fit", {
.future(state.phase.signal().for_each(clone!(state => move |phase| {
clone!(state => async move {
if phase == TalkTypeItemPhase::Wrong {
TimeoutFuture::new(HINT_TIME_MS).await;
state.phase.set_neq(TalkTypeItemPhase::Input);
}
})
})))
.property("y", bounds.y)
.property("x", bounds.x)
.property("width", bounds.width)
.property("height", bounds.height)
.property_signal("value", state.value.signal_cloned())
.property_signal("color", state.phase.signal().map(|phase| {
match phase {
TalkTypeItemPhase::Wrong => "red",
TalkTypeItemPhase::Correct => "green",
_ => ""
}
}))
.event(clone!(state => move |_evt:events::Focus| {
state.play_audio();
}))
.event(clone!(state => move |evt:events::CustomInput| {
state.phase.set_neq(TalkTypeItemPhase::Input);
state.value.set_neq(evt.value())
}))
.event(clone!(state, parent => move |_evt:events::Enter| {
state.clone().evaluate(parent.clone())
}))
.with_node!(_elem => {
.apply_if(parent.raw.show_hints, OverlayHandle::lifecycle(clone!(state => move || {
html!("empty-fragment", {
.child_signal(state.phase.signal().map(clone!(state => move |phase| {
match phase {
TalkTypeItemPhase::Wrong => {
Some(html!("overlay-tooltip-bubble", {
.text(&state.hint_letters.borrow().to_string())
.property("target", web_sys::DomRect::from(abs_bounds))
.property("targetAnchor", "bm")
.property("contentAnchor", "oppositeV")
}))
},
_ => None
}
})))
})
})))
})
})
}
}
| 15,488
|
https://github.com/msaad1311/PDEs-using-NN/blob/master/multiscale_HiTS-master/scripts/sequence_generation_exp/.ipynb_checkpoints/flower-checkpoint.ipynb
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
PDEs-using-NN
|
msaad1311
|
Jupyter Notebook
|
Code
| 1,150
| 5,132
|
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Flower (Video)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### created by Yuying Liu, 06/09/2020"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"import os\n",
"import sys\n",
"import cv2\n",
"import torch\n",
"import numpy as np\n",
"import scipy as sp\n",
"from tqdm.notebook import tqdm\n",
"from matplotlib import animation\n",
"from IPython.display import Video\n",
"from IPython.display import HTML\n",
"from scipy.linalg import svd\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.gridspec as gridspec\n",
"\n",
"module_path = os.path.abspath(os.path.join('../../src/'))\n",
"if module_path not in sys.path:\n",
" sys.path.append(module_path)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# # # # # # # # # # # # # # # # # #\n",
"# global constants, paths, etc. #\n",
"# # # # # # # # # # # # # # # # # #\n",
"data_dir = '../data/Flower/'\n",
"model_dir = '../model/Flower/'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### process data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# retrieve data\n",
"cap = cv2.VideoCapture(os.path.join(data_dir, 'flower.mp4'))\n",
"frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n",
"frameWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n",
"frameHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n",
"data = np.empty((frameCount, frameHeight, frameWidth, 3), np.dtype('uint8'))\n",
"print(data.shape)\n",
"\n",
"ret = True\n",
"for i in tqdm(range(frameCount)):\n",
" if not ret:\n",
" break\n",
" else:\n",
" ret, data[i] = cap.read()\n",
"cap.release()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# animation of original video\n",
"def plot_images(img_list):\n",
" def init():\n",
" img.set_data(cv2.cvtColor(img_list[0], cv2.COLOR_BGR2RGB))\n",
" return (img,)\n",
" def animate(i):\n",
" img.set_data(cv2.cvtColor(img_list[i], cv2.COLOR_BGR2RGB))\n",
" return (img,)\n",
"\n",
" fig = plt.figure(figsize=(12, 8))\n",
" plt.axis('off')\n",
" ax = fig.gca()\n",
" img = ax.imshow(cv2.cvtColor(img_list[0], cv2.COLOR_BGR2RGB))\n",
" plt.close();\n",
" anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(img_list), interval=20, blit=True)\n",
" return anim\n",
"\n",
"imgs = [data[i, :, :, :] for i in range(frameCount)]\n",
"HTML(plot_images(imgs).to_html5_video())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# dimensionality reduction\n",
"raw_data = data.reshape(frameCount, -1).T\n",
"U, s, VT = svd(raw_data, full_matrices=False)\n",
"reduced_data = U[:, :64].dot(np.diag(s[:64]).dot(VT[:64, :])).T.reshape(frameCount, frameHeight, frameWidth, 3)\n",
"reduced_data[reduced_data < 0] = 0\n",
"reduced_data[reduced_data > 255] = 255\n",
"coord_dynamics = VT[:64, :]\n",
"np.save(os.path.join(data_dir, 'data.npy'), coord_dynamics)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# animation of low-dim reconstructed data\n",
"imgs = [reduced_data[i, :, :, :].astype('uint8') for i in range(frameCount)]\n",
"reduced_anim = plot_images(imgs)\n",
"# reduced_anim.save('flower_truth.mp4')\n",
"HTML(reduced_anim.to_html5_video())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(figsize=(12, 3))\n",
"plt.plot(reduced_data[:, 150:180, 250:280, 0].mean(-1).mean(-1), linewidth=8.0)\n",
"plt.xticks([], [])\n",
"plt.yticks([], [])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# fig = plt.figure(figsize=(12, 8))\n",
"# plt.axis('off')\n",
"# ax = fig.gca()\n",
"# img = ax.imshow(cv2.cvtColor(imgs[170], cv2.COLOR_BGR2RGB))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### coupled NNs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# coupled NN reconstruction\n",
"coupled_nn_V = np.load(os.path.join(data_dir, 'flower_couple_pred.npy'))\n",
"coupled_nn_data = U[:, :64].dot(np.diag(s[:64]).dot(coupled_nn_V.T)).T.reshape(frameCount, frameHeight, frameWidth, 3)\n",
"coupled_nn_data[coupled_nn_data < 0] = 0\n",
"coupled_nn_data[coupled_nn_data > 255] = 255\n",
"\n",
"print(((coupled_nn_V - VT[:64, :].T)**2).mean())\n",
"plt.figure(figsize = (16, 1))\n",
"plt.plot(((coupled_nn_V - VT[:64, :].T)**2).mean(0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# animation of reconstruction via coupled NNs\n",
"imgs = [coupled_nn_data[i, :, :, :].astype('uint8') for i in range(frameCount)]\n",
"coupled_anim = plot_images(imgs)\n",
"# coupled_anim.save('flower_DENNIST_pred.mp4')\n",
"HTML(coupled_anim.to_html5_video())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(figsize=(12, 3))\n",
"plt.plot(coupled_nn_data[:, 150:180, 250:280, 0].mean(-1).mean(-1), linewidth=8.0)\n",
"plt.xticks([], [])\n",
"plt.yticks([], [])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# fig = plt.figure(figsize=(12, 8))\n",
"# plt.axis('off')\n",
"# ax = fig.gca()\n",
"# img = ax.imshow(cv2.cvtColor(imgs[170], cv2.COLOR_BGR2RGB))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### lstm"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# lstm reconstruction\n",
"lstm_V = np.load(os.path.join(data_dir, 'flower_lstm_pred.npy'))\n",
"lstm_data = U[:, :64].dot(np.diag(s[:64]).dot(lstm_V.T)).T.reshape(frameCount, frameHeight, frameWidth, 3)\n",
"lstm_data[lstm_data < 0] = 0\n",
"lstm_data[lstm_data > 255] = 255\n",
"\n",
"print(((lstm_V - VT[:64, :].T)**2).mean())\n",
"plt.figure(figsize = (16, 1))\n",
"plt.plot(((lstm_V - VT[:64, :].T)**2).mean(0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# animation of reconstruction via lstm\n",
"imgs = [lstm_data[i, :, :, :].astype('uint8') for i in range(frameCount)]\n",
"lstm_anim = plot_images(imgs)\n",
"# lstm_anim.save('flower_LSTM_pred.mp4')\n",
"HTML(lstm_anim.to_html5_video())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(figsize=(12, 3))\n",
"plt.plot(lstm_data[:, 150:180, 250:280, 0].mean(-1).mean(-1), linewidth=8.0)\n",
"plt.xticks([], [])\n",
"plt.yticks([], [])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# fig = plt.figure(figsize=(12, 8))\n",
"# plt.axis('off')\n",
"# ax = fig.gca()\n",
"# img = ax.imshow(cv2.cvtColor(imgs[170], cv2.COLOR_BGR2RGB))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### reservoir"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# reservoir reconstruction\n",
"reservoir_V = np.load(os.path.join(data_dir, 'flower_reservoir_pred.npy'))\n",
"reservoir_data = U[:, :64].dot(np.diag(s[:64]).dot(reservoir_V.T)).T.reshape(frameCount, frameHeight, frameWidth, 3)\n",
"reservoir_data[reservoir_data < 0] = 0\n",
"reservoir_data[reservoir_data > 255] = 255\n",
"\n",
"print(((reservoir_V - VT[:64, :].T)**2).mean())\n",
"plt.figure(figsize = (16, 1))\n",
"plt.plot(((reservoir_V - VT[:64, :].T)**2).mean(0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# animation of reconstruction via reservoir\n",
"imgs = [reservoir_data[i, :, :, :].astype('uint8') for i in range(frameCount)]\n",
"reservoir_anim = plot_images(imgs)\n",
"# reservoir_anim.save('flower_Reservoir_pred.mp4')\n",
"HTML(reservoir_anim.to_html5_video())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(figsize=(12, 3))\n",
"plt.plot(reservoir_data[:, 150:180, 250:280, 0].mean(-1).mean(-1), linewidth=8.0)\n",
"plt.xticks([], [])\n",
"plt.yticks([], [])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# fig = plt.figure(figsize=(12, 8))\n",
"# plt.axis('off')\n",
"# ax = fig.gca()\n",
"# img = ax.imshow(cv2.cvtColor(imgs[170], cv2.COLOR_BGR2RGB))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### cwrnn"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# cwrnn reconstruction\n",
"cwrnn_V = np.load(os.path.join(data_dir, 'flower_cwrnn_pred.npy'))\n",
"cwrnn_data = U[:, :64].dot(np.diag(s[:64]).dot(cwrnn_V.T)).T.reshape(frameCount, frameHeight, frameWidth, 3)\n",
"cwrnn_data[cwrnn_data < 0] = 0\n",
"cwrnn_data[cwrnn_data > 255] = 255\n",
"\n",
"print(((cwrnn_V - VT[:64, :].T)**2).mean())\n",
"plt.figure(figsize = (16, 1))\n",
"plt.plot(((cwrnn_V - VT[:64, :].T)**2).mean(0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# animation of reconstruction via cwrnn\n",
"imgs = [cwrnn_data[i, :, :, :].astype('uint8') for i in range(frameCount)]\n",
"cwrnn_anim = plot_images(imgs)\n",
"# cwrnn_anim.save('flower_CWRNN_pred.mp4')\n",
"HTML(cwrnn_anim.to_html5_video())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(figsize=(12, 3))\n",
"plt.plot(cwrnn_data[:, 150:180, 250:280, 0].mean(-1).mean(-1), linewidth=8.0)\n",
"plt.xticks([], [])\n",
"plt.yticks([], [])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# fig = plt.figure(figsize=(12, 8))\n",
"# plt.axis('off')\n",
"# ax = fig.gca()\n",
"# img = ax.imshow(cv2.cvtColor(imgs[170], cv2.COLOR_BGR2RGB))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| 5,856
|
https://github.com/MateuVieira/bootcamp-gostack-desafio-02/blob/master/src/app/controllers/RecipientController.js
|
Github Open Source
|
Open Source
|
RSA-MD
| null |
bootcamp-gostack-desafio-02
|
MateuVieira
|
JavaScript
|
Code
| 443
| 1,085
|
import * as Yup from 'yup';
import Recipient from '../models/Recipient';
class RecipientController {
async index(req, res) {
const recipient = await Recipient.findAll();
return res.json(recipient);
}
async show(req, res) {
// If the help of Yup builder a schema to validate the request fields
const schema = Yup.object().shape({
id: Yup.number()
.positive()
.required(),
});
// Compare the schema with request fields
if (!(await schema.isValid(req.params))) {
return res.status(400).json({ error: 'Id invalid' });
}
// Receive id from request params
const { id } = req.params;
// Find recipient from id
const recipient = await Recipient.findOne({ where: { id } });
// Return the recipient to user
return res.json(recipient);
}
async store(req, res) {
// If the help of Yup builder a schema to validate the request fields
const schema = Yup.object().shape({
name: Yup.string().required(),
rua: Yup.string().required(),
numero: Yup.number()
.required()
.positive(),
complemento: Yup.string(),
estado: Yup.string().required(),
cidade: Yup.string().required(),
// Example: xxxxx-xxx
cep: Yup.string()
.required()
.length(9),
});
// Compare the schema with request fields
if (!(await schema.isValid(req.body))) {
return res.status(400).json({ error: 'Validation faild' });
}
// Insert the new recipient in the database
const { id, name, estado, cidade } = await Recipient.create(req.body);
// Return the id, name, state, city to user
return res.json({
id,
name,
estado,
cidade,
});
}
async update(req, res) {
// If the help of Yup builder a schema to validate the request fields
const schema = Yup.object().shape({
id: Yup.number()
.positive()
.required(),
name: Yup.string(),
rua: Yup.string(),
numero: Yup.number().positive(),
complemento: Yup.string(),
estado: Yup.string(),
cidade: Yup.string(),
cep: Yup.string().length(9),
});
// Compare the schema with request fields
if (!(await schema.isValid(req.body))) {
return res.status(400).json({ error: 'Validation faild' });
}
// Create a constant with the value of the id
const { id } = req.body;
// Search for the recipient of the id
const recipient = await Recipient.findByPk(id);
// If the recipient is not found return to the user id invalid
if (!recipient) {
return res.status(400).json({ error: 'Id invalid' });
}
// Update the recipient with the data in the body of the request
const { name, estado, cidade } = await recipient.update(req.body);
// Return the id, name, state, city to user
return res.json({
id,
name,
estado,
cidade,
});
}
async delete(req, res) {
// If the help of Yup builder a schema to validate the request fields
const schema = Yup.object().shape({
id: Yup.number()
.positive()
.required(),
});
// Compare the schema with request fields
if (!(await schema.isValid(req.params))) {
return res.status(400).json({ error: 'Id invalid' });
}
// Receive id from request params
const { id } = req.params;
// Delete recipient from id
await Recipient.destroy({ where: { id } });
// Return a message success to user
return res.json({ message: 'Recipient has been delete' });
}
}
export default new RecipientController();
| 17,313
|
https://github.com/yupiik/tools-maven-plugin/blob/master/minisite-core/src/main/resources/yupiik-tools-maven-plugin/minisite/blog-list.adoc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
tools-maven-plugin
|
yupiik
|
AsciiDoc
|
Code
| 4
| 19
|
= {{{title}}}
{{{items}}}
{{{links}}}
| 46,850
|
https://github.com/jussico/Reading-tips-2020-covid-edition/blob/master/ReadingTips/src/test/java/readingtips/database/BlogPostDaoTest.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Reading-tips-2020-covid-edition
|
jussico
|
Java
|
Code
| 300
| 1,100
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package readingtips.database;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import readingtips.entity.BlogPost;
/**
*
* @author tiitinha
*/
public class BlogPostDaoTest {
// test x
public static void main(String[] args) {
BlogPostDaoTest test = new BlogPostDaoTest();
test.setUp();
test.listBlogPosts();
test.insertBook();
}
private BlogPostDao dao;
@Before
public void setUp() {
DatabaseTestSetup dataBaseTestSetup = new DatabaseTestSetup();
dataBaseTestSetup.alustaTietokanta();
dao = new BlogPostDao();
}
@Test
public void insertBook() {
List<String> tags = Arrays.asList("tag1", "tag2");
List<String> courses = Arrays.asList("course1", "course2");
BlogPost video = new BlogPost("Muumi2020", "sairas tarina", "Toove", tags, courses, "muumit.com");
dao.create(video);
assertTrue(video.getId() > 0);
}
@Test
public void listBlogPosts() {
List<String> tags = Arrays.asList("tag1", "tag2");
List<String> courses = Arrays.asList("course1", "course2");
BlogPost blogPost = new BlogPost("Muumi2020", "sairas tarina", "Toove", tags, courses, "muumit.com");
// Integer id = dao.create(book);
dao.create(blogPost);
BlogPost blogPost2 = new BlogPost("Muumi2021", "sairas tarina2", "Toove", tags, courses, "muumit.com");
// Integer id2 = dao.create(book2);
dao.create(blogPost2);
List<BlogPost> list = dao.list();
assertTrue(list.size() > 1);
}
@Test
public void listBlogPostsContainsAddedBlogPost() {
List<String> tags = Arrays.asList("tag1", "tag2");
List<String> courses = Arrays.asList("course1", "course2");
BlogPost blogPost = new BlogPost("Muumi2020", "sairas tarina", "Toove", tags, courses, "muumit.com");
dao.create(blogPost);
BlogPost blogPost2 = new BlogPost("Muumi2021", "sairas tarina2", "Toove", tags, courses, "muumit.com");
dao.create(blogPost2);
List<BlogPost> list = dao.list();
assertTrue(blogPost.equals(list.get((0))));
}
@Test
public void updateBlogPostkUpdatesBlogPost() {
List<String> tags = Arrays.asList("tag1", "tag2");
List<String> courses = Arrays.asList("course1", "course2");
BlogPost blogPost = new BlogPost("Muumi2020", "sairas tarina", "Toove", tags, courses, "muumit.com");
dao.create(blogPost);
blogPost.setAuthor("sairas tarina2");
dao.update(blogPost);
List<BlogPost> list = dao.list();
assertTrue(blogPost.getAuthor().equals(list.get(0).getAuthor()));
}
@Test
public void deleteBookDeletesBook() {
List<String> tags = Arrays.asList("tag1", "tag2");
List<String> courses = Arrays.asList("course1", "course2");
BlogPost blogPost = new BlogPost("Muumi2020", "sairas tarina", "Toove", tags, courses, "muumit.com");
dao.create(blogPost);
dao.delete(blogPost);
List<BlogPost> list = dao.list();
assertTrue(list.size() == 0);
}
}
| 34,563
|
https://github.com/prmsrswt/fund-disbursal-backend/blob/master/src/config.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
fund-disbursal-backend
|
prmsrswt
|
TypeScript
|
Code
| 102
| 414
|
import dotenv from 'dotenv';
dotenv.config();
const {
HOST,
PORT,
MONGO_URI,
DB_NAME,
JWT_SECRET,
JWT_EXPIRY,
REFRESH_EXPIRY,
APP_ENV,
SMTP_HOST,
SMTP_USER,
SMTP_PASS,
STORAGE_BUCKET,
STORAGE_SIGNED_URI_EXPIRY,
STORAGE_PREFIX,
} = process.env;
const config = {
host: HOST || 'localhost',
port: Number(PORT) || 5000,
mongoURI: MONGO_URI,
DBName: DB_NAME || 'fund',
JWTSecret: JWT_SECRET,
JWTExpiry: JWT_EXPIRY || '15m',
refreshTokenExpiry: REFRESH_EXPIRY || '365d',
frontendOrigins: [/localhost/, /gov\.in/, /127\.0\.0\.1/],
isProd: APP_ENV === 'production',
smtp: {
host: SMTP_HOST,
port: 587,
secure: false,
auth: {
user: SMTP_USER,
pass: SMTP_PASS,
},
},
storage: {
bucket: STORAGE_BUCKET || 'fund-stg',
signedExpiry: STORAGE_SIGNED_URI_EXPIRY || '1h',
prefix: STORAGE_PREFIX || 'fund/', // Global prefix for objects on bucket
},
};
export default config;
| 50,480
|
https://github.com/Csaba79-coder/thinThere/blob/master/src/main/java/backend/thinthere/repository/ExerciseRepository.java
|
Github Open Source
|
Open Source
|
MIT
| null |
thinThere
|
Csaba79-coder
|
Java
|
Code
| 36
| 179
|
package backend.thinthere.repository;
import backend.thinthere.enums.Goal;
import backend.thinthere.enums.MuscleGroup;
import backend.thinthere.model.Exercise;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface ExerciseRepository extends JpaRepository<Exercise, Long> {
Optional<Exercise> findById(Long id);
Optional<Exercise> findByName(String name);
List<Exercise> findAll();
List<Exercise> findAllByMuscleGroup(MuscleGroup muscleGroup);
List<Exercise> findAllByGoal(Goal goal);
}
| 50,856
|
https://github.com/shahruslan/kuban-online/blob/master/src/Commands/ShowSpecialityListCommand.php
|
Github Open Source
|
Open Source
|
MIT
| null |
kuban-online
|
shahruslan
|
PHP
|
Code
| 82
| 310
|
<?php
namespace KubanOnline\Commands;
use KubanOnline\Service;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ShowSpecialityListCommand extends Command
{
private Service $service;
protected static $defaultName = 'speciality:list';
protected function configure(): void
{
$this
->setDescription('Показать список специальностей')
->setHelp('Показывает список специальностей и их идентификаторы')
;
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->service = new Service();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$specialities = $this->service->specialities();
foreach ($specialities as $speciality) {
$message = " <info>$speciality->id</info> \t $speciality->name (<comment>$speciality->tickets</comment>)";
$output->writeln($message);
}
return Command::SUCCESS;
}
}
| 31,218
|
https://github.com/manuelc10/mobiles/blob/master/packages/react-component-library/src/components/RangeSlider/Slider.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
mobiles
|
manuelc10
|
TypeScript
|
Code
| 252
| 1,069
|
import React, { useState } from 'react'
import classNames from 'classnames'
import {
Slider,
SliderProps,
Rail,
Handles,
Tracks,
Ticks,
} from 'react-compound-slider'
import { Handle, Track, Tick } from './index'
interface RangeSliderProps extends Omit<SliderProps, 'children' | 'disabled' | 'reversed'> {
hasLabels?: boolean
tracksLeft?: boolean
tracksRight?: boolean
tickCount?: number
IconLeft?: React.ElementType
IconRight?: React.ElementType
isDisabled?: boolean
isReversed?: boolean
}
export const RangeSlider: React.FC<RangeSliderProps> = ({
className,
domain,
step,
hasLabels,
tracksLeft = false,
tracksRight = false,
tickCount = 10,
IconLeft,
IconRight,
isReversed,
isDisabled,
values,
onUpdate,
...rest
}) => {
const [sliderValues, setSliderValues] = useState(values)
const onUpdateHandler = (newValues: ReadonlyArray<number>): void => {
setSliderValues(newValues)
onUpdate(newValues)
}
const classes = classNames('rn-rangeslider', className, {
'is-reversed': isReversed,
'is-disabled': isDisabled,
})
return (
<div className={classes} data-testid="rangeslider">
{IconLeft && (
<IconLeft
className="rn-rangeslider__icon rn-rangeslider__icon--left"
data-testid="rangeslider-icon-left"
/>
)}
<Slider
domain={domain}
reversed={isReversed}
disabled={isDisabled}
values={values}
step={step}
onUpdate={onUpdateHandler}
{...rest}
>
<Rail>
{({ getRailProps }) => (
<div className="rn-rangeslider__rail">
<div className="rn-rangeslider__rail-outer" {...getRailProps()} />
<div className="rn-rangeslider__rail-inner" />
</div>
)}
</Rail>
<Handles>
{({ activeHandleID, handles, getHandleProps }) => (
<div className="rn-rangeslider__handles">
{handles.map(handle => (
<Handle
key={handle.id}
handle={handle}
domain={domain}
activeHandleID={activeHandleID}
getHandleProps={getHandleProps}
/>
))}
</div>
)}
</Handles>
<Tracks left={tracksLeft} right={tracksRight}>
{({ tracks, getTrackProps }) => (
<div className="rn-rangeslider__tracks">
{tracks.map(({ id, source, target }) => (
<Track
id={id}
key={id}
source={source}
target={target}
getTrackProps={getTrackProps}
/>
))}
</div>
)}
</Tracks>
{step && (
<Ticks count={tickCount}>
{({ ticks }) => (
<div className="rn-rangeslider__ticks">
{ticks.map(tick => (
<Tick
key={tick.id}
tick={tick}
count={ticks.length}
hasLabels={hasLabels}
values={sliderValues}
domain={domain}
isReversed={isReversed}
/>
))}
</div>
)}
</Ticks>
)}
</Slider>
{IconRight && (
<IconRight
className="rn-rangeslider__icon rn-rangeslider__icon--right"
data-testid="rangeslider-icon-right"
/>
)}
</div>
)
}
RangeSlider.displayName = 'RangeSlider'
| 28,799
|
https://github.com/TravisSpomer/ivorytower.com/blob/master/src/routes/api/v1/hello.js
|
Github Open Source
|
Open Source
|
FSFAP
| 2,021
|
ivorytower.com
|
TravisSpomer
|
JavaScript
|
Code
| 17
| 56
|
export async function get()
{
return {
body:
{
version: 0.0001,
built: (new Date()).toISOString(),
}
}
}
| 39,946
|
https://github.com/rwalter215/toy-problems/blob/master/toy_problems/CodeWars/Mean.js
|
Github Open Source
|
Open Source
|
MIT
| null |
toy-problems
|
rwalter215
|
JavaScript
|
Code
| 74
| 196
|
function mean(lst) {
const result = [];
let string = '';
let total = 0;
for (let i = 0; i < lst.length; i++) {
if (isNaN(lst[i])) {
string += lst[i];
} else {
total += Number(lst[i]);
}
}
result[0] = total / 10;
result[1] = string;
return result;
}
mean(['u', '6', 'd', '1', 'i', 'w', '6', 's', 't', '4', 'a', '6', 'g', '1', '2', 'w', '8', 'o', '2', '0']);
// => [3.6, 'udiwstagwo']
| 6,513
|
https://github.com/kephircheek/wishlist/blob/master/static/components/ReservationCart.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
wishlist
|
kephircheek
|
JavaScript
|
Code
| 218
| 823
|
const ReservationCard = {
components: {
"input-copy-to-clipboard": InputCopyToClipboard
},
props: {
id: {
type: String,
required: true
},
secret: {
type: String,
required: true
},
title: String,
link: String,
},
computed: {
cancellationCode() {
return `${this.id}-${this.secret}`
}
},
data() {
return {
_title: this.title,
_link: this.link,
}
},
mounted() {
this.fetch()
},
methods: {
fetch() {
this.$root.model.get(`item/${this.id}`)
.then(r => {
this._title = r.data.title;
this._link = r.data.link;
})
.catch(this.$root.reporter);
},
},
template:
/*html*/
`
<div>
{{ this._title }} | {{ this._link }}
<strong>Cancelation code:</strong>
<input-copy-to-clipboard :value="this.cancellationCode" readonly />
</div>
`
}
const ReservationCart = {
components: {
"reservation-card": ReservationCard,
},
data() {
return {
_cancellationCode: null,
_reservations: [],
}
},
mounted() {
this.fetch()
},
computed: {
reservationId() {
return this._cancellationCode.split('-')[0]
},
reservationSecret() {
return this._cancellationCode.split('-')[1]
},
},
methods: {
fetch() {
this.$root.model.get('session/released')
.then(r => {
this._reservations = r.data
})
.catch(this.$root.reporter);
},
cancel() {
id = this.reservationId
secret = this.reservationSecret
this._cancellationCode = null
index = this._reservations.findIndex(r => r.id === id)
reservation = this._reservations.splice(index, 1) ? index > -1 : null
this.$root.model.delete(`item/${id}/release`, {params: {secret: secret}})
.then(r => {
this.$emit('cancellation', id)
console.log('cancel reservation')
})
.catch(e => {
if (reservation) {
this._reservations.splice(index, 0, reservation);
}
this.$root.reporter(e)
});
},
},
emits: [
'cancellation',
],
template:
/*html*/
`
<h3>Reservation Cart</h3>
<input v-model="this._cancellationCode" placeholder="Cancellation code"/>
<button @click="cancel">Cancel</button>
<reservation-card v-for="reservation in this._reservations" :key="reservation.id" v-bind="reservation" />
`
}
| 22,556
|
https://github.com/ops4j/org.ops4j.pax.carrot/blob/master/pax-carrot-spring/src/main/java/org/ops4j/pax/carrot/spring/ApplicationContextHolder.java
|
Github Open Source
|
Open Source
|
Apache-1.1
| null |
org.ops4j.pax.carrot
|
ops4j
|
Java
|
Code
| 224
| 483
|
/*
* Copyright 2013 Harald Wellmann
*
* 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 License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ops4j.pax.carrot.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
/**
* A test execution listener holding the current application context.
*
* @author Harald Wellmann
* @version $Rev: 53870 $ $Date: 2013-02-12 11:32:44 +0100 (Di, 12. Feb 2013) $
* @since 22.10.2013
*/
public class ApplicationContextHolder implements TestExecutionListener {
private ApplicationContext applicationContext;
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
}
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
this.applicationContext = testContext.getApplicationContext();
}
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
}
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
}
@Override
public void afterTestClass(TestContext testContext) throws Exception {
}
/**
* Gets the application context for the current test.
*
* @return Returns the {@link #applicationContext}.
*/
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
| 1,397
|
https://github.com/solana-labs/solana/blob/master/sdk/bpf/c/inc/deserialize_deprecated.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
solana
|
solana-labs
|
C
|
Code
| 2
| 15
|
#include <sol/deserialize_deprecated.h>
| 46,887
|
https://github.com/fossabot/Cangol-appcore/blob/master/appcore/src/main/java/mobi/cangol/mobile/service/upgrade/UpgradeServiceImpl.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Cangol-appcore
|
fossabot
|
Java
|
Code
| 813
| 2,702
|
/**
* Copyright (c) 2013 Cangol
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mobi.cangol.mobile.service.upgrade;
import android.app.Application;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dalvik.system.DexClassLoader;
import mobi.cangol.mobile.CoreApplication;
import mobi.cangol.mobile.http.download.DownloadHttpClient;
import mobi.cangol.mobile.http.download.DownloadResponseHandler;
import mobi.cangol.mobile.logging.Log;
import mobi.cangol.mobile.service.AppService;
import mobi.cangol.mobile.service.Service;
import mobi.cangol.mobile.service.ServiceProperty;
import mobi.cangol.mobile.service.conf.ConfigService;
import mobi.cangol.mobile.service.download.DownloadNotification;
import mobi.cangol.mobile.utils.AppUtils;
/**
* @author Cangol
*/
@Service("UpgradeService")
class UpgradeServiceImpl implements UpgradeService {
private static final String TAG = "UpgradeService";
private boolean debug = false;
private Application mContext = null;
private ServiceProperty mServiceProperty = null;
private ConfigService mConfigService;
private List<Integer> mIds = new ArrayList<>();
private Map<String, OnUpgradeListener> mOnUpgradeListeners;
private DownloadHttpClient mDownloadHttpClient;
@Override
public void onCreate(Application context) {
mContext = context;
mConfigService = (ConfigService) ((CoreApplication) mContext).getAppService(AppService.CONFIG_SERVICE);
mOnUpgradeListeners = new HashMap<>();
}
@Override
public void init(ServiceProperty serviceProperty) {
this.mServiceProperty = serviceProperty;
}
@Override
public String getName() {
return TAG;
}
@Override
public void onDestroy() {
if (debug) Log.d("onDestory");
if (mDownloadHttpClient != null)
mDownloadHttpClient.cancelAll();
final NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
for (final Integer id : mIds) {
notificationManager.cancel(id);
if (debug) Log.d("notification cancel " + id);
}
}
@Override
public ServiceProperty getServiceProperty() {
return mServiceProperty;
}
@Override
public ServiceProperty defaultServiceProperty() {
return new ServiceProperty(TAG);
}
@Override
public void setDebug(boolean mDebug) {
this.debug = mDebug;
}
@Override
public void upgrade(final String filename, String url, final boolean notification) {
upgrade(filename, url, notification, UpgradeType.APK, false, true);
}
@Override
public void upgrade(String filename, String url, boolean notification, boolean install) {
upgrade(filename, url, notification, UpgradeType.APK, install, true);
}
@Override
public void upgrade(String filename, String url, boolean notification, boolean install, boolean safe) {
upgrade(filename, url, notification, UpgradeType.APK, install, safe);
}
private void upgrade(final String filename, String url, final boolean notification, final UpgradeType upgradeType, final boolean install, final boolean safe) {
final String savePath = mConfigService.getUpgradeDir() + File.separator + filename;
final File saveFile = new File(savePath);
if (debug) Log.d("upgrade savePath:" + savePath);
if (saveFile.exists()) {
final boolean result=saveFile.delete();
if(!result)Log.d("delete oldFile fail:" + savePath);
} else {
try {
final boolean result=saveFile.createNewFile();
if(!result)Log.d("createNewFile fail:" + savePath);
} catch (IOException e) {
Log.e(e.getMessage());
}
}
final DownloadNotification downloadNotification = new DownloadNotification(mContext, filename, savePath, createFinishIntent(savePath, upgradeType));
if (notification) {
mIds.add(downloadNotification.getId());
}
mDownloadHttpClient = DownloadHttpClient.build(TAG, safe);
mDownloadHttpClient.send(filename, url, new DownloadResponseHandler() {
@Override
public void onWait() {
super.onWait();
if (notification) {
downloadNotification.createNotification();
}
}
@Override
public void onStart(long start, long length) {
Log.d(TAG, "onStart " + start + "/" + length);
}
@Override
public void onStop(long end) {
super.onStop(end);
if (notification) {
downloadNotification.cancelNotification();
mIds.remove(Integer.valueOf(downloadNotification.getId()));
}
notifyUpgradeFailure(filename, "stop");
}
@Override
public void onFinish(long end) {
super.onFinish(end);
if (notification) {
downloadNotification.finishNotification();
}
if (install) {
makeLoad(savePath, upgradeType);
}
notifyUpgradeFinish(filename, savePath);
}
@Override
public void onProgressUpdate(long end, int progress, int speed) {
super.onProgressUpdate(end, progress, speed);
if (notification) {
downloadNotification.updateNotification(progress, speed);
}
notifyUpgradeProgress(filename, speed, progress);
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
if (notification) {
downloadNotification.failureNotification();
}
notifyUpgradeFailure(filename, content);
}
}, saveFile.length(), savePath);
}
private void makeLoad(String savePath, UpgradeType upgradeType) {
switch (upgradeType) {
case APK:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final String authority = mContext.getPackageName() + ".fileprovider";
if (debug) Log.e("authority=" + authority);
final Uri contentUri = FileProvider.getUriForFile(mContext, authority, new File(savePath));
AppUtils.install(mContext, contentUri);
} else {
AppUtils.install(mContext, savePath);
}
break;
case RES:
break;
case DEX:
/**
DexClassLoader dexClassLoader = new DexClassLoader(savePath, mConfigService.getTempDir().getAbsolutePath(), null, mContext.getClassLoader());
try {
Class clazz = dexClassLoader.loadClass("className");
} catch (ClassNotFoundException e) {
Log.e(e.getMessage());
}**/
break;
case SO:
System.load(savePath);
break;
case OTHER:
new Intent();
break;
default:
break;
}
}
private Intent createFinishIntent(String savePath, UpgradeType upgradeType) {
Intent intent = null;
final File file = new File(savePath);
switch (upgradeType) {
case APK:
intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
final String authority = mContext.getPackageName() + ".fileprovider";
if (debug) Log.e("authority=" + authority);
final Uri contentUri = FileProvider.getUriForFile(mContext, authority, file);
if (debug) Log.e("uri=" + contentUri);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
break;
case RES:
break;
case DEX:
break;
case SO:
break;
case OTHER:
new Intent();
break;
default:
new Intent();
break;
}
return intent;
}
@Override
public void cancel(String filename) {
if (mDownloadHttpClient != null)
mDownloadHttpClient.cancelRequests(filename, true);
}
public void notifyUpgradeFinish(String filename, String filepath) {
if (mOnUpgradeListeners.containsKey(filename)) {
mOnUpgradeListeners.get(filename).onFinish(filepath);
}
}
public void notifyUpgradeProgress(String filename, int speed, int progress) {
if (mOnUpgradeListeners.containsKey(filename)) {
mOnUpgradeListeners.get(filename).progress(speed, progress);
}
}
public void notifyUpgradeFailure(String filename, String error) {
if (mOnUpgradeListeners.containsKey(filename)) {
mOnUpgradeListeners.get(filename).onFailure(error);
}
}
@Override
public void setOnUpgradeListener(String filename, OnUpgradeListener onUpgradeListener) {
if (!mOnUpgradeListeners.containsKey(filename)) {
mOnUpgradeListeners.put(filename, onUpgradeListener);
}
}
}
| 15,313
|
https://github.com/regularApproximation/newton/blob/master/c/src/datastructs/finite_automaton.cpp
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| null |
newton
|
regularApproximation
|
C++
|
Code
| 40
| 186
|
#include "finite_automaton.h"
#include <fa.h>
// struct fa* FiniteAutomaton::EMPTY_LANGUAGE = fa_make_basic(0); // magic number 0 for empty language
// FiniteAutomaton FiniteAutomaton::EMPTY_AUTOMATON = FiniteAutomaton(fa_make_basic(fa_basic::FA_EMPTY));
// FiniteAutomaton FiniteAutomaton::EPSILON_AUTOMATON = FiniteAutomaton(fa_make_basic(fa_basic::FA_EPSILON)); // magic number 1 for empty language
// const FiniteAutomaton FiniteAutomaton::UNIVERSE_AUTOMATON = FiniteAutomaton(fa_make_basic(fa_basic::FA_TOTAL));
| 15,662
|
https://github.com/huynhnhatthiep/ftcoffee/blob/master/ftCoffee/src/main/webapp/resources/JS/CRUD/ChiTietBan.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ftcoffee
|
huynhnhatthiep
|
JavaScript
|
Code
| 907
| 5,596
|
$(document).ready(function() {
viewPriceList();
$("#inBill").click(function() {
addChiTietBan();
inBill();
addVoucherLine($('#getTableNumberInBill').val());
setTimeout(() => {
viewListIndex();
}, 500);
});
$("#huyBan").click(function() {
huyBan($('#nameTable').val());
setTimeout(() => {
viewListIndex();
}, 500);
});
$("#thanhToan").click(function() {
showVoucherNumber();
});
});
function huyBan(id) {
var ojbect = JSON.parse(localStorage.getItem('cart'));
for (var i = 0; i < ojbect.length; i++) {
if (ojbect[i].idtable == id) {
console.log(ojbect[i]);
ojbect.splice(i, 1);
localStorage.setItem('cart', JSON.stringify(ojbect));
$("#listDongChungTu").html('');
viewPriceList();
$("#click-back").click();
break;
}
}
setTimeout(() => {
viewListIndex();
}, 100);
}
$(document).on('click','#showListProduct tr td a',function(){
var flag= true;
var id= $(this).attr('data-id');
var name= $(this).attr('data-name');
var dvt= $(this).attr('data-dvt');
var price= $(this).attr('data-price');
var idtable = $('#nameTable').val();
var menuitem= {
id:id,
name:name,
dvt:dvt,
qty:1,
price:price
}
if(localStorage.getItem('cart')){
var cart = JSON.parse(localStorage.getItem('cart'));
cart.forEach(function(item,index){
if(item.idtable == $('#nameTable').val()){
item.listmenu.forEach(function(element,index2){
if(element.id==id){
flag=false;
element.qty+=1;
}
});
if(flag==true){
item.listmenu.push(menuitem);
}
}
});
localStorage.setItem('cart',JSON.stringify(cart));
disPlayItem(idtable);
disPlayItemThanhToan(idtable);
}else{
}
});
function disPlayItem(idtable){
var data = "";
var cart = JSON.parse(localStorage.getItem('cart'));
cart.forEach(function(item,index){
if(item.idtable ==idtable){
item.listmenu.forEach(function(element,index2){
var idstr ='"' +element.id+'"';
data+="<tr><td>"+element.id+"</td><td>"+element.name+"</td><td>"+element.dvt+"</td><td>"+element.qty+"</td><td>"+element.price+"</td><td></td><td>"+element.qty*element.price+"</td><td><button class='btn btn-danger' onclick='deleteIem("+idstr+")'>Xóa</botton></td></tr>";
});
}
});
$('#listDongChungTu').html(data);
}
function disPlayItemThanhToan(idtable){
var data = "";
var tableNumber = $("#nameTable").val();
var numberCustomer = $("#numberCustomer").val();
var total =0;
var cart = JSON.parse(localStorage.getItem('cart'));
cart.forEach(function(item,index){
if(item.idtable ==idtable){
item.listmenu.forEach(function(element,index2){
total+=element.qty*element.price;
data+="<tr><td>"+element.id+"</td><td>"+element.name+"</td><td>"+element.dvt+"</td><td>"+element.qty+"</td><td>"+element.price+"</td><td></td><td>"+element.qty*element.price+"</td></tr>";
});
}
});
$('#total').val(total);
$('#totalInBill').val(total);
$("#thanhToan").click(function() {
$("#getTableNumberInBill").val(tableNumber);
$("#getNumberCustomerInBill").val(numberCustomer);
});
$('#listThanhToan').html(data);
}
function deleteIem(idmenu){
var idtable = $('#nameTable').val();
var cart = JSON.parse(localStorage.getItem('cart'));
cart.forEach(function(item,index){
if(item.idtable ==idtable){
item.listmenu.forEach(function(element,index2){
if(element.id==idmenu){
item.listmenu.splice(index2,1);
}
});
}
});
localStorage.setItem('cart',JSON.stringify(cart));
disPlayItem(idtable);
disPlayItemThanhToan(idtable);
}
function viewPriceList() {
var token = $("meta[name='_csrf']").attr("content");
var data = "";
$.ajax({
type : "POST",
url : "getPriceList",
headers: {
'X-CSRF-TOKEN':token,
},
cache : false,
success : function(data) {
$(function() {
$.each(data,
function(i, item) {
data += "<tr>" + "<td>" + '<a class="btn btn-success" data-id="'+item.SanPham.idProduct+'" data-name="'+item.SanPham.nameProduct+'" data-dvt="'+item.SanPham.idDVT+'" data-price="'+item.price+'"><i class="fa fa-plus" aria-hidden="true"></i></a>' + "</td>"
+ "<td>" + item.SanPham.idProduct + "</td>"
+ "<td>" + item.SanPham.nameProduct + "</td>"
+ "<td>" + item.SanPham.idDVT + "</td>"
+ "<td>" + item.price + "</td>"
+ "<td>" + '<input id="SL" type="number" class="form-control" placeholder="Số lượng" value="1" />' + "</td>"
+ "</tr>";
});
$('#showListProduct').html(data);
});
}
});
}
function showVoucherNumber() {
var token = $("meta[name='_csrf']").attr("content");
var data = "";
$.ajax({
type : "GET",
url : "length",
headers: {
'X-CSRF-TOKEN':token,
},
cache : false,
success : function(data) {
// var idNumber= Number(data) + 1
if (data == '') {
return data = 1;
}else{
$("#getIdNumberVoucher").val(data);
}
}
});
}
function getIdProduct(id) {
var token = $("meta[name='_csrf']").attr("content");
$.ajax({
type : "GET",
url : "getIdProduct/"+id+"",
headers: {
'X-CSRF-TOKEN':token,
},
dataType:"json",
cache : false,
success : function(data) {
$('#nameTable').val(data.tableNumber);
$('#nameBangGia').val(data.priceType.priceName);
},
error : function(e) {
Lobibox.notify('error', {
showClass: 'zoomInUp',
hideClass: 'zoomOutDown',
msg: 'Không tìm thấy'
});
}
});
}
function addChiTietBan() {
var token = $("meta[name='_csrf']").attr("content");
$.ajax({
type : "POST",
url : "addVoucher",
async:false,
headers: {
'X-CSRF-TOKEN':token,
},
cache : false,
data : {
tableNumber : $("#getTableNumberInBill").val(),
moneyAmount : $("#totalInBill").val(),
customerAmount : $("#getNumberCustomerInBill").val()
},
success : function(data) {
console.log(data);
if (data === "success") {
$("#ListBanPhong").html("");
Lobibox.notify('success', {
showClass : 'rollIn',
hideClass : 'rollOut',
msg : 'Thanh toán thành công'
});
viewListIndex();
} else {
Lobibox.notify('error', {
showClass: 'zoomInUp',
hideClass: 'zoomOutDown',
msg: 'Thêm thất bại'
});
}
},
error : function(e) {
Lobibox.notify('error', {
showClass: 'zoomInUp',
hideClass: 'zoomOutDown',
msg: 'Không được để traống'
});
},
});
}
function addVoucherLine(id) {
var ojbect = JSON.parse(localStorage.getItem('cart'));
for (var i = 0; i < ojbect.length; i++) {
if (ojbect[i].idtable == id) {
console.log(ojbect[i]);
for (var j = 0; j < ojbect[i].listmenu.length; j++) {
add(ojbect[i].listmenu[j].id, ojbect[i].listmenu[j].dvt, ojbect[i].listmenu[j].qty, ojbect[i].listmenu[j].price);
}
ojbect.splice(i, 1);
localStorage.setItem('cart', JSON.stringify(ojbect));
$("#listDongChungTu").html('');
$("#click-back").click();
return;
}
}
}
function add(id, dvt, qty, price){
var token = $("meta[name='_csrf']").attr("content");
$.ajax({
type : "POST",
url : "addVoucherLine",
async:false,
headers: {
'X-CSRF-TOKEN':token,
},
cache : false,
data : {
voucherNumber : $("#getIdNumberVoucher").val(),
idProduct : id,
idDVT : dvt,
amount : qty,
price : price
},
success : function(data) {
console.log(data);
if (data === "success") {
$("#listThanhToan").html("");
// Lobibox.notify('success', {
// showClass : 'rollIn',
// hideClass : 'rollOut',
// msg : 'Thêm thành công'
// });
viewPriceList();
} else {
Lobibox.notify('error', {
showClass: 'zoomInUp',
hideClass: 'zoomOutDown',
msg: 'Thêm thất bại'
});
}
},
error : function(e) {
Lobibox.notify('error', {
showClass: 'zoomInUp',
hideClass: 'zoomOutDown',
msg: 'Không được để traống'
});
},
});
}
function inBillTest() {
var mywindow = window.open('', 'PRINT', 'height=800,width=1000');
mywindow.document.write('<html><head>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h1 style="text-align:center">HÓA ĐƠN THANH TOÁN TẠM THỜI</h1>');
mywindow.document.write('<h2 style="text-align:center">500 SERVER ERROR COFFEE</h2>');
mywindow.document.write('<p style="text-align:center">Địa chỉ: FastTrack SE, P.Hòa Quý, Q.Ngũ Hành sơn, TP.Đà Nẵng</p>');
mywindow.document.write('<table>');
mywindow.document.write('<tr>');
mywindow.document.write('<th>');
mywindow.document.write('Số bàn:');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write(document.getElementById("getTableNumberInBill").value);
mywindow.document.write('</th>');
mywindow.document.write('<th style="with:100px">');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Số hóa đơn:');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write(document.getElementById("getIdNumberVoucher").value);
mywindow.document.write('<th>');
mywindow.document.write('</tr>');
mywindow.document.write('</table>');
mywindow.document.write('<br>');
mywindow.document.write('<table border="1" style="border-collapse: collapse">');
mywindow.document.write('<tr>');
mywindow.document.write('<th>');
mywindow.document.write('ID');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Tên hàng hóa, sản phẩm, dịch vụ');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('ĐVT');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Số lượng');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Đơn giá');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Giảm giá');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Thành tiền');
mywindow.document.write('</th>');
mywindow.document.write(document.getElementById("listThanhToan").innerHTML);
mywindow.document.write('</tr>');
mywindow.document.write('</table>');
mywindow.document.write('<br>');
mywindow.document.write('<div style="display:fex;margin-left:423px">');
mywindow.document.write('<span>');
mywindow.document.write('<b>');
mywindow.document.write('Tổng tiền:');
mywindow.document.write('</b>');
mywindow.document.write('</span>');
mywindow.document.write('<span>');
mywindow.document.write(document.getElementById("totalInBill").value);
mywindow.document.write('</span>');
mywindow.document.write('</div>');
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
}
function inBill() {
var mywindow = window.open('', 'PRINT', 'height=800,width=1000');
mywindow.document.write('<html><head>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h1 style="text-align:center">HÓA ĐƠN THANH TOÁN</h1>');
mywindow.document.write('<h2 style="text-align:center">500 SERVER ERROR COFFEE</h2>');
mywindow.document.write('<p style="text-align:center">Địa chỉ: FastTrack SE, P.Hòa Quý, Q.Ngũ Hành sơn, TP.Đà Nẵng</p>');
mywindow.document.write('<table>');
mywindow.document.write('<tr>');
mywindow.document.write('<th>');
mywindow.document.write('Số bàn:');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write(document.getElementById("getTableNumberInBill").value);
mywindow.document.write('</th>');
mywindow.document.write('<th style="with:100px">');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Số hóa đơn:');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write(document.getElementById("getIdNumberVoucher").value);
mywindow.document.write('<th>');
mywindow.document.write('</tr>');
mywindow.document.write('</table>');
mywindow.document.write('<br>');
mywindow.document.write('<table border="1" style="border-collapse: collapse">');
mywindow.document.write('<tr>');
mywindow.document.write('<th>');
mywindow.document.write('ID');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Tên hàng hóa, sản phẩm, dịch vụ');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('ĐVT');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Số lượng');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Đơn giá');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Giảm giá');
mywindow.document.write('</th>');
mywindow.document.write('<th>');
mywindow.document.write('Thành tiền');
mywindow.document.write('</th>');
mywindow.document.write(document.getElementById("listThanhToan").innerHTML);
mywindow.document.write('</tr>');
mywindow.document.write('</table>');
mywindow.document.write('<br>');
mywindow.document.write('<div style="display:fex;margin-left:465px">');
mywindow.document.write('<span>');
mywindow.document.write('<b>');
mywindow.document.write('Tổng tiền:');
mywindow.document.write('</b>');
mywindow.document.write('</span>');
mywindow.document.write('<span>');
mywindow.document.write(document.getElementById("totalInBill").value);
mywindow.document.write('</span>');
mywindow.document.write('</div>');
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
}
| 14,486
|
https://github.com/AhmedAliGad/students/blob/master/resources/views/admin/services/_form.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
students
|
AhmedAliGad
|
PHP
|
Code
| 293
| 1,162
|
<!-- Start Card Content -->
<div class="card-content">
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label required">اختيار الكلية</label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
<select-all :inputs="{{ $collages }}" forname="collages[]"
@if(isset($service) && $service->collages) :oldvalues="{{ $service->collages() }}" @endif>
</select-all>
</div>
</div>
</div>
</div>
<hr />
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label required">اسم الخدمة </label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
{!! Form::text('name', null, ['class' => 'input' , 'required'] )!!}
</div>
</div>
</div>
</div>
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label">اختيار الخدمة الرئيسية </label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
<div class="select is-fullwidth">
{!! Form::select('parent_id', $services, null) !!}
</div>
</div>
</div>
</div>
</div>
<hr />
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label">محتوي الخدمة</label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
<div class="select is-fullwidth">
{!! Form::select('type', ['page' => 'محتوي', 'link' => 'رابط خارجي'],
null, ['class' => 'input', 'required'] )!!}
</div>
</div>
</div>
</div>
</div>
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label">الرابط الخارجي للخدمة</label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
{!! Form::text('link', null, ['class' => 'input'] )!!}
</div>
</div>
</div>
</div>
<hr />
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label required">الترتيب</label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
{!! Form::number('priority', isset($service) ? $service->priority : \App\Models\Service::count()+1, ['class' => 'input', 'min' => 1] )!!}
</div>
</div>
</div>
</div>
<hr />
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label">الحالة</label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
<label class="radio">
<input type="radio" name="active" value="1" @if(isset($service) && $service->active) checked @else checked @endif>
مفعلة
</label>
<label class="radio">
<input type="radio" name="active" value="0" @if(isset($service) && !$service->active) checked @endif>
غير مفعلة
</label>
</div>
</div>
</div>
</div>
</div><!-- End Card Content -->
<!-- Start Card Footer -->
<div class="card-footer">
<div class="buttons has-addons">
<a class="button is-info" href="{{ route('admin.services.index') }}"> الغاء </a>
<button type="submit" class="button is-success">حفظ</button>
</div>
</div><!-- End Card Footer -->
| 36,141
|
https://github.com/mckennapsean/code-examples/blob/master/C/fileIO.c
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
code-examples
|
mckennapsean
|
C
|
Code
| 167
| 467
|
// changing case inspired by Cerolobo link below
// read input from a file
// must run in same directory as text file
#include <stdio.h>
// code for changing the case, by Cerolobo:
// http://www.dreamincode.net/forums/topic/44152-making-the-first-letter-of-a-string-uppercase/
char caseup(char entry){
if(entry >= 'a' && entry <= 'z')
entry -= 'a' - 'A';
return entry;
}
// turn an entire string upper-case
void allcaps(char string[]){
int i;
for(i = 0; i < 256; i++)
if(string[i] >= 'a' && string[i] <= 'z')
string[i] -= 'a' - 'A';
}
// main test of the input from a file
void main(){
FILE *inFile;
FILE *outFile;
inFile = fopen("fileIO.in", "r");
outFile = fopen("fileIO.out", "w");
char input[256];
char output[256];
// can use fscanf, or fgets
//fscanf(inFile, "%[^\n]\n", input);
fgets(input, 256, inFile);
printf("Your file contains: %s", input);
fgets(output, 256, inFile);
fclose(inFile);
// change the output as desired
//output = input;
allcaps(output);
//int i;
//for(i = 0; i < 256; i++){
// output[i] = caseup(output[i]);
//}
// write out the final output
fprintf(outFile, "%s\n", output);
fclose(outFile);
}
| 50,139
|
https://github.com/damiancarrillo/palette/blob/master/palette/src/encoding/mod.rs
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT
| null |
palette
|
damiancarrillo
|
Rust
|
Code
| 81
| 176
|
//! Various encoding traits, types and standards.
use float::Float;
use FromF64;
pub use self::gamma::{F2p2, Gamma};
pub use self::linear::Linear;
pub use self::srgb::Srgb;
pub mod gamma;
pub mod linear;
pub mod pixel;
pub mod srgb;
/// A transfer function to and from linear space.
pub trait TransferFn {
/// Convert the color component `x` from linear space.
fn from_linear<T: Float + FromF64>(x: T) -> T;
/// Convert the color component `x` into linear space.
fn into_linear<T: Float + FromF64>(x: T) -> T;
}
| 20,001
|
https://github.com/wapache-org/greenplum-gpdb/blob/master/contrib/pgcrypto/sql/crypt-xdes.sql
|
Github Open Source
|
Open Source
|
PostgreSQL, Apache-2.0
| 2,022
|
greenplum-gpdb
|
wapache-org
|
SQL
|
Code
| 126
| 281
|
--
-- crypt() and gen_salt(): extended des
--
SELECT crypt('', '_J9..j2zz');
SELECT crypt('foox', '_J9..j2zz');
-- check XDES handling of keys longer than 8 chars
SELECT crypt('longlongpassword', '_J9..j2zz');
-- error, salt too short
SELECT crypt('foox', '_J9..BWH');
-- error, count specified in the second argument is 0
SELECT crypt('password', '_........');
-- error, count will wind up still being 0 due to invalid encoding
-- of the count: only chars ``./0-9A-Za-z' are valid
SELECT crypt('password', '_..!!!!!!');
-- count should be non-zero here, will work
SELECT crypt('password', '_/!!!!!!!');
CREATE TABLE ctest (data text, res text, salt text);
INSERT INTO ctest VALUES ('password', '', '');
UPDATE ctest SET salt = gen_salt('xdes', 1001);
UPDATE ctest SET res = crypt(data, salt);
SELECT res = crypt(data, res) AS "worked"
FROM ctest;
DROP TABLE ctest;
| 1,476
|
https://github.com/Dynatrace-Adam-Gardner/keptn/blob/master/bridge/cypress/support/commands.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
keptn
|
Dynatrace-Adam-Gardner
|
TypeScript
|
Code
| 62
| 252
|
/* eslint-disable import/no-extraneous-dependencies */
import 'cypress-file-upload';
/* eslint-enable import/no-extraneous-dependencies */
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cypress {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Chainable<Subject> {
byTestId<E extends Node = HTMLElement>(id: string): Cypress.Chainable<JQuery<E>>;
clickOutside<E extends Node = HTMLElement>(): Cypress.Chainable<JQuery<E>>;
}
}
}
// Commands have to be added by hooking them to Cypress
Cypress.Commands.add('byTestId', (testId: string) => cy.get(`[uitestid="${testId}"]`));
Cypress.Commands.add('clickOutside', () => cy.get('body').click(0, 0));
| 14,607
|
https://github.com/man-anr/db-project/blob/master/lecturer/quiz/multiple/result.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
db-project
|
man-anr
|
PHP
|
Code
| 292
| 1,380
|
<?php
session_start();
include_once("../../../database/config.php");
include("../../../template/navs-lecturer.php");
$_SESSION['current_table'] = "quiz_marks";
$quiz_id = "";
$num_row = 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lecturer Dashboard</title>
</head>
<body class="bg-light ">
<!-- Main Container -->
<div class="container-fluid ">
<!-- Main row -->
<div class="row">
<!-- Main div -->
<main class="col">
<div class="table-responsive">
<div class="card my-4 shadow-sm">
<div class="card-header">
<span><i class="bi bi-table me-2"></i><?php echo $_GET['subject_id']?></span>
<span class="float-right"><?php echo " - Quiz ".$_GET['quiz_type']?> <i class="bi bi-toggle-off text-right"></i></span>
</div>
<div class="card-body">
<table class="table table-border table-hover data-table">
<thead class="">
<tr>
<th scope='col' >No</th>
<th scope='col' >ID</th>
<th scope='col' >Name</th>
<th scope='col' >Marks</th>
</tr>
</thead>
<tbody class="">
<?php
$student_marks = "
SELECT quiz_marks.enroll_id, enroll.workload_id, quiz_marks.quiz_id, enroll.student_id, student.name, quiz.type ,quiz_marks.marks
FROM (((quiz_marks
LEFT JOIN enroll
ON quiz_marks.enroll_id = enroll.id)
LEFT JOIN quiz
ON quiz_marks.quiz_id = quiz.id)
LEFT JOIN student
on enroll.student_id = student.id)
WHERE quiz.type = 'multiple' AND
enroll.workload_id = " . $_GET['workload_id'];
$result_student_marks = mysqli_query($con, $student_marks);
if($result_student_marks){
while($row_marks = mysqli_fetch_array($result_student_marks)){
$num_row++;
?>
<tr>
<td><?php echo $num_row?></td>
<td><?php echo $row_marks['student_id']?></td>
<td><?php echo $row_marks['name']?></td>
<td><?php echo $row_marks['marks']?></td>
</tr>
<?php
$quiz_id = $row_marks['quiz_id'];
}
}
?>
</tbody>
</table>
</div>
<div class="card-footer">
<?php
$check_passing_mark = "
SELECT * FROM mult_quiz WHERE quiz_id =
" . $quiz_id;
// echo $check_passing_mark;
$query_check_passing_mark = mysqli_query($con, $check_passing_mark);
$total_row_check_passing_mark = mysqli_num_rows($query_check_passing_mark);
// echo $total_row_check_passing_mark/2;
$get_mark_student_pass = "SELECT * FROM quiz_marks WHERE quiz_id = $quiz_id AND marks >= " . $total_row_check_passing_mark/2;
// echo $get_mark_student;
$query_get_mark_student_pass = mysqli_query($con, $get_mark_student_pass);
$total_row_get_mark_student_pass = mysqli_num_rows($query_get_mark_student_pass);
?>
<span class="">Number of student(s) pass:<span class="badge bg-success ms-2"><?php echo $total_row_get_mark_student_pass;?></span></span>
<?php
$get_mark_student_fail = "SELECT * FROM quiz_marks WHERE quiz_id = $quiz_id AND marks < " . $total_row_check_passing_mark/2;
// echo $get_mark_student;
$query_get_mark_student_fail = mysqli_query($con, $get_mark_student_fail);
$total_row_get_mark_student_fail = mysqli_num_rows($query_get_mark_student_fail);
?>
<span class="ms-4">Number of student(s) fail:<span class="badge bg-warning ms-2"><?php echo $total_row_get_mark_student_fail;?></span></span>
<?php
?>
</div>
</div>
</div>
</main>
<!-- Main div -->
</div>
</body>
</html>
| 37,874
|
https://github.com/DataObjects-NET/dataobjects-net/blob/master/Orm/Xtensive.Orm/Orm/Rse/Providers/Executable/ExecutableRawProvider.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
dataobjects-net
|
DataObjects-NET
|
C#
|
Code
| 146
| 497
|
// Copyright (C) 2008-2021 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
// Created by: Alexey Kochetov
// Created: 2008.05.08
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xtensive.Orm.Providers;
using Tuple = Xtensive.Tuples.Tuple;
namespace Xtensive.Orm.Rse.Providers
{
/// <summary>
/// Enumerates specified array of <see cref="Tuple"/> instances.
/// </summary>
[Serializable]
public sealed class ExecutableRawProvider : ExecutableProvider<Providers.RawProvider>
{
private const string CachedSourceName = "CachedSource";
/// <inheritdoc/>
protected internal override void OnBeforeEnumerate(EnumerationContext context)
{
base.OnBeforeEnumerate(context);
var parameterContext = ((Xtensive.Orm.Providers.EnumerationContext) context).ParameterContext;
SetValue(context, CachedSourceName, Origin.CompiledSource.Invoke(parameterContext));
}
/// <inheritdoc/>
protected internal override async Task OnBeforeEnumerateAsync(EnumerationContext context, CancellationToken token)
{
await base.OnBeforeEnumerateAsync(context, token).ConfigureAwait(false);
var parameterContext = ((Xtensive.Orm.Providers.EnumerationContext) context).ParameterContext;
SetValue(context, CachedSourceName, Origin.CompiledSource.Invoke(parameterContext));
}
/// <inheritdoc/>
protected internal override DataReader OnEnumerate(EnumerationContext context)
{
return new DataReader(GetValue<IEnumerable<Tuple>>(context, CachedSourceName));
}
// Constructors
public ExecutableRawProvider(Providers.RawProvider origin)
: base(origin)
{
}
}
}
| 41,302
|
https://github.com/Novartis/cellxgene-gateway/blob/master/tests/test_dir_util.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
cellxgene-gateway
|
Novartis
|
Python
|
Code
| 55
| 424
|
import unittest
from unittest.mock import MagicMock, patch
from cellxgene_gateway.dir_util import ensure_dir_exists, make_annotations, make_h5ad
class TestMakeH5ad(unittest.TestCase):
def test_GIVEN_annotation_dir_THEN_returns_h5ad(self):
self.assertEqual(make_h5ad("pbmc_annotations"), "pbmc.h5ad")
class TestMakeAnnotations(unittest.TestCase):
def test_GIVEN_h5ad_THEN_returns_annotations(self):
self.assertEqual(make_annotations("pbmc.h5ad"), "pbmc_annotations")
class TestMakeAnnotations(unittest.TestCase):
def test_GIVEN_h5ad_THEN_returns_annotations(self):
self.assertEqual(make_annotations("pbmc.h5ad"), "pbmc_annotations")
class TestEnsureDirExists(unittest.TestCase):
@patch("os.path.exists")
@patch("os.makedirs")
def test_GIVEN_existing_THEN_does_not_call_makedir(self, makedirsMock, existsMock):
existsMock.return_value = True
ensure_dir_exists("/foo")
makedirsMock.assert_not_called()
@patch("os.path.exists")
@patch("os.makedirs")
def test_GIVEN_not_existing_THEN_calls_makedir(self, makedirsMock, existsMock):
existsMock.return_value = False
ensure_dir_exists("/foo")
makedirsMock.assert_called_once_with("/foo")
| 2,753
|
https://github.com/fossabot/kargo/blob/master/log/logger.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
kargo
|
fossabot
|
Go
|
Code
| 327
| 915
|
package log
import (
"fmt"
"io"
"os"
"sync"
log "github.com/sirupsen/logrus"
pb "gopkg.in/cheggaaa/pb.v1"
)
func init() {
// Output to stdout instead of the default stderr
log.SetOutput(os.Stdout)
}
type Logger interface {
// Info outputs an info log message
Info(s string, fields ...Field)
// Warn outputs a warning log message
Warn(s string, fields ...Field)
// Error outputs an error log message
Error(s string, fields ...Field)
// Progress tracks progresses of r
Progress(s string, r io.Reader, size ...int64) io.ReadCloser
}
// New creates a new standard logger
func New(fields ...Field) Logger {
l := log.New()
l.SetLevel(log.InfoLevel)
return &ttyLogger{logger: l.WithFields(wrapFields(fields...))}
}
type ttyLogger struct {
mu sync.Mutex
logger *log.Entry
bar *bar
}
// Info outputs an info log message
func (l *ttyLogger) Info(s string, fields ...Field) {
l.logFunc(fields...).Info(s)
}
// Warn outputs a warning log message
func (l *ttyLogger) Warn(s string, fields ...Field) {
l.logFunc(fields...).Warn(s)
}
// Error outputs an error log message
func (l *ttyLogger) Error(s string, fields ...Field) {
l.logFunc(fields...).Error(s)
}
// Error outputs an error log message
func (l *ttyLogger) logFunc(fields ...Field) *log.Entry {
l.mu.Lock()
defer l.mu.Unlock()
if l.bar != nil {
l.bar.Close()
l.bar = nil
}
return l.logger.WithFields(wrapFields(fields...))
}
// Progress outputs and update a progress bar until it is being closed
// or another inbound log line interupts it
func (l *ttyLogger) Progress(
s string, r io.Reader, size ...int64,
) io.ReadCloser {
l.mu.Lock()
defer l.mu.Unlock()
if l.bar != nil {
l.bar.Close()
}
var total int64
if len(size) > 0 {
total = size[0]
}
b := pb.New64(total).SetUnits(pb.U_BYTES)
b.ShowTimeLeft = true
b.ShowPercent = false
b.ShowSpeed = true
b.SetMaxWidth(100)
b.Prefix(fmt.Sprintf("\x1b[36mINFO\x1b[0m %s", s))
b.Start()
l.bar = &bar{b, b.NewProxyReader(r)}
return l.bar
}
func wrapFields(fields ...Field) log.Fields {
lf := log.Fields{}
for _, field := range fields {
k, v := field.KV()
lf[k] = v
}
return lf
}
type bar struct {
*pb.ProgressBar
proxy io.Reader
}
func (b *bar) Close() error {
b.Finish()
return nil
}
func (b *bar) Read(p []byte) (n int, err error) {
return b.proxy.Read(p)
}
| 44,096
|
https://github.com/dwisuseno/tiket/blob/master/views/tiket/cektiket.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
tiket
|
dwisuseno
|
PHP
|
Code
| 134
| 683
|
<?php
/* @var $this yii\web\View */
/* @var $searchModel app\models\TiketSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
use yii\helpers\Html;
use kartik\export\ExportMenu;
use kartik\grid\GridView;
$this->title = 'Tiket';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="tiket-index">
<div class="alert alert-info" role="alert">
<table id='test' class="table table-striped table-bordered">
<thead>
<tr>
<th>No</th>
<th>Nama Event</th>
<th>Tanggal Event</th>
<th>Kode Pembayaran</th>
<th>Kode Tiket</th>
<th>Status</th>
<th>Harga Tiket</th>
<th>Tanggal Pembelian</th>
</tr>
</thead>
<tbody>
<?php for($i=0;$i<sizeof($model);$i++){ ?>
<tr>
<td><?= $i+1 ?></td>
<td><?php echo $model[$i]['nama_event'];?>
</td>
<td><?php echo Yii::$app->formatter->asDate($model[$i]['tgl_event'], 'dd-MM-yyyy');?>
</td>
<td><?php echo $model[$i]['kode_pembayaran'];?>
</td>
<td><?php if($model[$i]['status'] == '0'){
echo 'Silahkan melakukan pembayaran'; }
else {
echo $model[$i]['kode_tiket'];
}?>
</td>
<td><?php if($model[$i]['status'] == '0'){
echo "Belum Dibayar"; }
else {
echo "Sudah Dibayar | ";
echo "<a target='_blank' href='index.php?r=tiket/cetaktiket&id=".$model[$i]['id']."'>Cetak Tiket</a>";
}?></td>
<td>Rp<?php echo number_format($model[$i]['harga'],2,",","."); ?>
</td>
<td>
<?php echo Yii::$app->formatter->asDate($model[$i]['created_at'], 'dd-MM-yyyy');?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
| 27,901
|
https://github.com/AlexXChina/zpublic/blob/master/pellets/z_win_utils/environment_var.hpp
|
Github Open Source
|
Open Source
|
Unlicense
| 2,015
|
zpublic
|
AlexXChina
|
C++
|
Code
| 381
| 1,523
|
/*************************************************************************
* *
* I|*j^3Cl|a "+!*% qt Nd gW *
* l]{y+l?MM* !#Wla\NNP NW MM I| *
* PW ?E| tWg Wg sC! AW ~@v~ *
* NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim *
* CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ *
* #M aQ? MW M3 Mg Q( HQ YR IM| *
* Dq {Ql MH iMX Mg MM QP QM Eg *
* !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D *
* *
* Website: https://github.com/zpublic/zpublic *
* *
************************************************************************/
/**
* @file
* @brief 环境变量相关
*/
#pragma once
#include "win_utils_header.h"
#include "register.hpp"
#include "usid.hpp"
namespace zl
{
namespace WinUtils
{
/**
* @brief 环境变量常用操作
*/
class ZLEnvironmentVar
{
public:
enum EnvironmentType { SYSTEM_ENV, USER_ENV };
/**
* @brief 添加一个环境变量
* @param[in] t 指定是环境变量类型, 系统环境变量(SYSTEM_ENV)或用户环境变量(USER_ENV)
* @param[in] lpVarName 环境变量名
* @param[in] lpVar 环境变量值
* @return 成功返回TRUE, 失败返回FALSE
*/
static BOOL Add(EnvironmentType t, LPCTSTR lpVarName, LPCTSTR lpVar);
/**
* @brief 删除指定环境变量
* @param[in] t 指定是环境变量类型, 系统环境变量(SYSTEM_ENV)或用户环境变量(USER_ENV)
* @param[in] lpVarName 环境变量名
* @return 成功返回TRUE, 失败返回FALSE
*/
static BOOL Del(EnvironmentType t, LPCTSTR lpVarName);
private:
static BOOL _AddSysEnv(LPCTSTR lpVarName, LPCTSTR lpVar);
static BOOL _DelSysEnv(LPCTSTR lpVarName);
static BOOL _AddUserEnv(LPCTSTR lpVarName, LPCTSTR lpVar);
static BOOL _DelUserEnv(LPCTSTR lpVarName);
};
inline BOOL ZLEnvironmentVar::Add( EnvironmentType t, LPCTSTR lpVarName, LPCTSTR lpVar )
{
if (!lpVarName || !lpVar)
return FALSE;
switch (t)
{
case SYSTEM_ENV:
return _AddSysEnv(lpVarName, lpVar);
case USER_ENV:
return _AddUserEnv(lpVarName, lpVar);
}
return FALSE;
}
inline BOOL ZLEnvironmentVar::Del( EnvironmentType t, LPCTSTR lpVarName )
{
if (NULL == lpVarName)
return FALSE;
switch (t)
{
case SYSTEM_ENV:
return _DelSysEnv(lpVarName);
case USER_ENV:
return _DelUserEnv(lpVarName);
}
return FALSE;
}
inline BOOL ZLEnvironmentVar::_AddSysEnv( LPCTSTR lpVarName, LPCTSTR lpVar )
{
ZLRegister reg;
if (reg.Open(
HKEY_LOCAL_MACHINE,
_T("System\\CurrentControlSet\\Control\\Session Manager\\Environment"),
KEY_WRITE,
TRUE))
{
return reg.SetExpandSzValue(lpVarName, lpVar);
}
return FALSE;
}
inline BOOL ZLEnvironmentVar::_DelSysEnv( LPCTSTR lpVarName )
{
ZLRegister reg;
if (reg.Open(
HKEY_LOCAL_MACHINE,
_T("System\\CurrentControlSet\\Control\\Session Manager\\Environment"),
KEY_WRITE))
{
return reg.DelValue(lpVarName);
}
return FALSE;
}
inline BOOL ZLEnvironmentVar::_AddUserEnv( LPCTSTR lpVarName, LPCTSTR lpVar )
{
CString sSid;
if (ZLUsid::GetCurrentUserSID(sSid))
{
CString sSubKey = sSid + L"\\Environment";
ZLRegister reg;
if (reg.Open(HKEY_USERS, sSubKey, KEY_WRITE))
{
return reg.SetExpandSzValue(lpVarName, lpVar);
}
}
return FALSE;
}
inline BOOL ZLEnvironmentVar::_DelUserEnv( LPCTSTR lpVarName )
{
CString sSid;
if (ZLUsid::GetCurrentUserSID(sSid))
{
CString sSubKey = sSid + L"\\Environment";
ZLRegister reg;
if (reg.Open(HKEY_USERS, sSubKey, KEY_WRITE))
{
return reg.DelValue(lpVarName);
}
}
return FALSE;
}
}
}
| 48,226
|
https://github.com/maciejrosolowski/progressdatenbankderivate/blob/master/man/getData4o2p.min.Rd
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
progressdatenbankderivate
|
maciejrosolowski
|
R
|
Code
| 97
| 351
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/getData4o2p.min.R
\name{getData4o2p.min}
\alias{getData4o2p.min}
\title{Get data on the oxygen saturation.}
\usage{
getData4o2p.min(FRM_O2P)
}
\arguments{
\item{FRM_O2P}{data.table containing the table FRM_O2P from the database
of the PROGRESS study}
}
\value{
data.table with the ID of the patient (patstuid), and the
data on the oxygen saturation, in the wide format.
}
\description{
A minimum of the oxygen saturation levels, if there were several
measurements performed with different methods.
}
\examples{
\dontrun{
excel_fn <- paste0("/net/ifs1/san_projekte/projekte/",
"PROGRESS/Datenmanagement/Data_freezes/",
"20190320/PROGRESS-freeze_201903_01.xlsx")
FRM_O2P <- readxl::read_excel(excel_fn, 'FRM_O2P')
data.table::setDT(FRM_O2P)
toadd_o2p.min <- getData4o2p.min(FRM_O2P)
toadd_o2p.min
}
}
| 46,942
|
https://github.com/Azure-Samples/active-directory-dotnet-demo-tdlr/blob/master/TDLR/Controllers/ErrorController.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
active-directory-dotnet-demo-tdlr
|
Azure-Samples
|
C#
|
Code
| 42
| 113
|
using System.Web.Mvc;
using System.Web;
// The following libraries were added to this sample.
using Microsoft.Owin.Security;
namespace Tdlr.Controllers
{
public class ErrorController : Controller
{
public ActionResult ShowError(string errorMessage, string signIn)
{
ViewBag.SignIn = signIn;
ViewBag.ErrorMessage = errorMessage;
return View();
}
}
}
| 40,314
|
https://github.com/rethinkdb/rethinkdb-legacy/blob/master/src/unittest/geo_indexes.cc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
rethinkdb-legacy
|
rethinkdb
|
C++
|
Code
| 1,496
| 5,819
|
// Copyright 2010-2015 RethinkDB, all rights reserved.
#include <algorithm>
#include "btree/keys.hpp"
#include "concurrency/fifo_checker.hpp"
#include "containers/counted.hpp"
#include "debug.hpp"
#include "random.hpp"
#include "rdb_protocol/configured_limits.hpp"
#include "rdb_protocol/datum.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/geo/distances.hpp"
#include "rdb_protocol/geo/ellipsoid.hpp"
#include "rdb_protocol/geo/exceptions.hpp"
#include "rdb_protocol/geo/geojson.hpp"
#include "rdb_protocol/geo/lon_lat_types.hpp"
#include "rdb_protocol/geo/intersection.hpp"
#include "rdb_protocol/geo/primitives.hpp"
#include "rdb_protocol/minidriver.hpp"
#include "rdb_protocol/protocol.hpp"
#include "rdb_protocol/pseudo_time.hpp"
#include "rdb_protocol/shards.hpp"
#include "rdb_protocol/store.hpp"
#include "stl_utils.hpp"
#include "unittest/rdb_protocol.hpp"
#include "unittest/unittest_utils.hpp"
#include "unittest/gtest.hpp"
#include "utils.hpp"
using geo::S2Point;
using ql::datum_t;
namespace unittest {
datum_t generate_point(rng_t *rng) {
double lat = rng->randdouble() * 180.0 - 90.0;
double lon = rng->randdouble() * 360.0 - 180.0;
return construct_geo_point(lon_lat_point_t(lon, lat), ql::configured_limits_t());
}
datum_t generate_line(rng_t *rng) {
lon_lat_line_t l;
size_t num_vertices = rng->randint(63) + 2;
double granularity = rng->randdouble() * 0.1;
// Pick a starting point
double lat = rng->randdouble() * 180.0 - 90.0;
double lon = rng->randdouble() * 360.0 - 180.0;
l.push_back(lon_lat_point_t(lon, lat));
for (size_t i = 0; i < num_vertices; ++i) {
// Then continue from there with relatively small variations...
lat += rng->randdouble() * 2.0 * granularity - granularity;
if (lat > 90.0) {
lat -= 180.0;
} else if (lat < -90.0) {
lat += 180.0;
}
if (lon > 180.0) {
lon -= 360.0;
} else if (lon < -180.0) {
lon += 360.0;
}
lon += lat + rng->randdouble() * 2.0 * granularity - granularity;
l.push_back(lon_lat_point_t(lon, lat));
}
try {
datum_t res =
construct_geo_point(lon_lat_point_t(lon, lat), ql::configured_limits_t());
validate_geojson(res);
return res;
} catch (const geo_exception_t &e) {
// In case we ended up with an illegal line (e.g. with double vertices),
// we just start over. It shouldn't happen very often.
return generate_line(rng);
}
}
datum_t generate_polygon(rng_t *rng) {
// We just construct polygons out of circles for now. One outer circle:
size_t num_vertices = rng->randint(62) + 3;
double lat = rng->randdouble() * 180.0 - 90.0;
double lon = rng->randdouble() * 360.0 - 180.0;
double r = rng->randdouble() * 1000.0; // Up to 1 km radius
lon_lat_line_t shell =
build_circle(lon_lat_point_t(lon, lat), r, num_vertices, WGS84_ELLIPSOID);
// And maybe 1 or 2 holes...
std::vector<lon_lat_line_t> holes;
size_t num_holes = rng->randint(3);
for (size_t i = 0; i < num_holes; ++i) {
// Just some heuristics. These will not always lead to valid polygons.
size_t hole_num_vertices = rng->randint(30) + 3;
double hole_lat = lat + rng->randdouble() * r - (0.5 * r);
double hole_lon = lon + rng->randdouble() * r - (0.5 * r);
double hole_r = rng->randdouble() * (0.5 * r);
lon_lat_line_t hole =
build_circle(lon_lat_point_t(hole_lon, hole_lat), hole_r, hole_num_vertices,
WGS84_ELLIPSOID);
holes.push_back(hole);
}
try {
datum_t res =
construct_geo_polygon(shell, holes, ql::configured_limits_t());
validate_geojson(res);
return res;
} catch (const geo_exception_t &e) {
// In case we ended up with an illegal polygon (e.g. holes intersected),
// we just start over.
return generate_polygon(rng);
}
}
std::vector<datum_t> generate_data(size_t num_docs, rng_t *rng) {
std::vector<datum_t> result;
result.reserve(num_docs);
for (size_t i = 0; i < num_docs; ++i) {
if (i % 3 == 0) {
result.push_back(generate_point(rng));
} else if (i % 3 == 1) {
result.push_back(generate_line(rng));
} else {
result.push_back(generate_polygon(rng));
}
}
return result;
}
void insert_data(namespace_interface_t *nsi,
order_source_t *osource,
const std::vector<datum_t> &data) {
for (size_t i = 0; i < data.size(); ++i) {
store_key_t pk(strprintf("%zu", i));
write_t write(
point_write_t(pk, data[i]),
DURABILITY_REQUIREMENT_SOFT,
profile_bool_t::PROFILE,
ql::configured_limits_t());
write_response_t response;
cond_t interruptor;
nsi->write(
auth::user_context_t(auth::permissions_t(tribool::True, tribool::True, tribool::False, tribool::False)),
write,
&response,
osource->check_in("unittest::insert_data(geo_indexes.cc"),
&interruptor);
if (!boost::get<point_write_response_t>(&response.response)) {
ADD_FAILURE() << "got wrong type of result back";
} else if (boost::get<point_write_response_t>(&response.response)->result
!= point_write_result_t::STORED) {
ADD_FAILURE() << "failed to insert document";
}
}
}
void prepare_namespace(namespace_interface_t *nsi,
order_source_t *osource,
const std::vector<scoped_ptr_t<store_t> > *stores,
const std::vector<datum_t> &data) {
// Create an index
std::string index_id = "geo";
const ql::sym_t arg(1);
ql::minidriver_t r(ql::backtrace_id_t::empty());
ql::raw_term_t mapping = r.var(arg).root_term();
sindex_config_t sindex(
ql::map_wire_func_t(mapping, make_vector(arg)),
reql_version_t::LATEST,
sindex_multi_bool_t::SINGLE,
sindex_geo_bool_t::GEO);
cond_t non_interruptor;
for (const auto &store : *stores) {
store->sindex_create(index_id, sindex, &non_interruptor);
}
// Wait for it to become ready
wait_for_sindex(stores, index_id);
// Insert the test data
insert_data(nsi, osource, data);
}
std::vector<nearest_geo_read_response_t::dist_pair_t> perform_get_nearest(
lon_lat_point_t center,
uint64_t max_results,
double max_distance,
namespace_interface_t *nsi,
order_source_t *osource) {
std::string table_name = "test_table"; // This is just used to print error messages
std::string idx_name = "geo";
read_t read(
nearest_geo_read_t(
region_t::universe(),
center,
max_distance,
max_results,
WGS84_ELLIPSOID,
table_name,
idx_name,
serializable_env_t{
ql::global_optargs_t(),
auth::user_context_t(auth::permissions_t(tribool::True, tribool::False, tribool::False, tribool::False)),
ql::datum_t()}),
profile_bool_t::PROFILE,
read_mode_t::SINGLE);
read_response_t response;
cond_t interruptor;
nsi->read(
auth::user_context_t(auth::permissions_t(tribool::True, tribool::False, tribool::False, tribool::False)),
read,
&response,
osource->check_in("unittest::perform_get_nearest(geo_indexes.cc"),
&interruptor);
nearest_geo_read_response_t *geo_response =
boost::get<nearest_geo_read_response_t>(&response.response);
if (geo_response == nullptr) {
ADD_FAILURE() << "got wrong type of result back";
return std::vector<nearest_geo_read_response_t::dist_pair_t>();
}
if (boost::get<ql::exc_t>(&geo_response->results_or_error) != nullptr) {
ADD_FAILURE() << boost::get<ql::exc_t>(&geo_response->results_or_error)->what();
return std::vector<nearest_geo_read_response_t::dist_pair_t>();
}
return boost::get<nearest_geo_read_response_t::result_t>(geo_response->results_or_error);
}
bool nearest_pairs_less(
const std::pair<double, ql::datum_t> &p1,
const std::pair<double, ql::datum_t> &p2) {
// We only care about the distance, don't compare the actual data.
return p1.first < p2.first;
}
std::vector<nearest_geo_read_response_t::dist_pair_t> emulate_get_nearest(
lon_lat_point_t center,
uint64_t max_results,
double max_distance,
const std::vector<datum_t> &data) {
std::vector<nearest_geo_read_response_t::dist_pair_t> result;
result.reserve(data.size());
ql::datum_t point_center =
construct_geo_point(center, ql::configured_limits_t());
scoped_ptr_t<S2Point> s2_center = to_s2point(point_center);
for (size_t i = 0; i < data.size(); ++i) {
nearest_geo_read_response_t::dist_pair_t entry(
geodesic_distance(*s2_center, data[i], WGS84_ELLIPSOID), data[i]);
result.push_back(entry);
}
std::sort(result.begin(), result.end(), &nearest_pairs_less);
// Apply max_results and max_distance
size_t cut_off = std::min(static_cast<size_t>(max_results), result.size());
for (size_t i = 0; i < cut_off; ++i) {
if (result[i].first > max_distance) {
cut_off = i;
break;
}
}
result.resize(cut_off);
return result;
}
void test_get_nearest(lon_lat_point_t center,
const std::vector<datum_t> &data,
namespace_interface_t *nsi,
order_source_t *osource) {
const uint64_t max_results = 100;
const double max_distance = 5000000.0; // 5000 km
// 1. Run get_nearest
std::vector<nearest_geo_read_response_t::dist_pair_t> nearest_res =
perform_get_nearest(center, max_results, max_distance, nsi, osource);
// 2. Compute an equivalent result directly from data
std::vector<nearest_geo_read_response_t::dist_pair_t> reference_res =
emulate_get_nearest(center, max_results, max_distance, data);
// 3. Compare both results
ASSERT_EQ(nearest_res.size(), reference_res.size());
for (size_t i = 0; i < nearest_res.size() && i < reference_res.size(); ++i) {
// We only compare the distances. The odds that a wrong document
// happens to have the same distance are negligible.
// Also this avoids having to deal with two documents having the same distance,
// which could then be re-ordered (though that is extremely unlikely as well).
ASSERT_EQ(nearest_res[i].first, reference_res[i].first);
}
}
void run_get_nearest_test(
namespace_interface_t *nsi,
order_source_t *osource,
const std::vector<scoped_ptr_t<store_t> > *stores) {
// To reproduce a known failure: initialize the rng seed manually.
const int rng_seed = randint(INT_MAX);
debugf("Using RNG seed %i\n", rng_seed);
rng_t rng(rng_seed);
const size_t num_docs = 500;
std::vector<datum_t> data = generate_data(num_docs, &rng);
prepare_namespace(nsi, osource, stores, data);
try {
const int num_runs = 20;
for (int i = 0; i < num_runs; ++i) {
double lat = rng.randdouble() * 180.0 - 90.0;
double lon = rng.randdouble() * 360.0 - 180.0;
test_get_nearest(lon_lat_point_t(lon, lat), data, nsi, osource);
}
} catch (const geo_exception_t &e) {
debugf("Caught a geo exception: %s\n", e.what());
FAIL();
}
}
std::vector<datum_t> perform_get_intersecting(
const datum_t &query_geometry,
namespace_interface_t *nsi,
order_source_t *osource) {
std::string table_name = "test_table"; // This is just used to print error messages
std::string idx_name = "geo";
read_t read(
intersecting_geo_read_t(
optional<changefeed_stamp_t>(),
region_t::universe(),
serializable_env_t{
ql::global_optargs_t(),
auth::user_context_t(auth::permissions_t(tribool::True, tribool::False, tribool::False, tribool::False)),
datum_t()},
table_name,
ql::batchspec_t::all(),
std::vector<ql::transform_variant_t>(),
optional<ql::terminal_variant_t>(),
sindex_rangespec_t(
idx_name,
make_optional(region_t::universe()),
ql::datumspec_t(
ql::datum_range_t::universe()),
require_sindexes_t::NO),
query_geometry),
profile_bool_t::PROFILE,
read_mode_t::SINGLE);
read_response_t response;
cond_t interruptor;
nsi->read(
auth::user_context_t(auth::permissions_t(tribool::True, tribool::False, tribool::False, tribool::False)),
read,
&response,
osource->check_in("unittest::perform_get_intersecting(geo_indexes.cc"),
&interruptor);
rget_read_response_t *geo_response =
boost::get<rget_read_response_t>(&response.response);
if (geo_response == nullptr) {
ADD_FAILURE() << "got wrong type of result back";
return std::vector<datum_t>();
}
if (boost::get<ql::exc_t>(&geo_response->result) != nullptr) {
ADD_FAILURE() << boost::get<ql::exc_t>(&geo_response->result)->what();
return std::vector<datum_t>();
}
auto result = boost::get<ql::grouped_t<ql::stream_t> >(&geo_response->result);
if (result == nullptr) {
ADD_FAILURE() << "got wrong type of result back";
return std::vector<datum_t>();
}
std::vector<datum_t> result_datum;
if (result->size() == 0) {
return result_datum;
} else if (result->size() != 1) {
ADD_FAILURE() << "got grouped result for some reason";
return std::vector<datum_t>();
}
if (result->begin()->first != datum_t::null()) {
ADD_FAILURE() << "got grouped result for some reason";
return std::vector<datum_t>();
}
const ql::stream_t &stream = (*result)[datum_t::null()];
for (auto &&pair : stream.substreams) {
for (auto &&el : pair.second.stream) {
result_datum.push_back(el.data);
}
}
return result_datum;
}
std::vector<datum_t> emulate_get_intersecting(
const datum_t &query_geometry,
const std::vector<datum_t> &data) {
std::vector<datum_t> result;
result.reserve(data.size());
for (size_t i = 0; i < data.size(); ++i) {
if (geo_does_intersect(query_geometry, data[i])) {
result.push_back(data[i]);
}
}
return result;
}
void test_get_intersecting(const datum_t &query_geometry,
const std::vector<datum_t> &data,
namespace_interface_t *nsi,
order_source_t *osource) {
// 1. Run get_intersecting
std::vector<datum_t> intersecting_res =
perform_get_intersecting(query_geometry, nsi, osource);
// 2. Compute an equivalent result directly from data
std::vector<datum_t> reference_res =
emulate_get_intersecting(query_geometry, data);
// 3. Compare both results
ASSERT_EQ(intersecting_res.size(), reference_res.size());
for (size_t i = 0; i < intersecting_res.size() && i < reference_res.size(); ++i) {
ASSERT_EQ(intersecting_res[i], reference_res[i]);
}
}
void run_get_intersecting_test(
namespace_interface_t *nsi,
order_source_t *osource,
const std::vector<scoped_ptr_t<store_t> > *stores) {
// To reproduce a known failure: initialize the rng seed manually.
const int rng_seed = randint(INT_MAX);
debugf("Using RNG seed %i\n", rng_seed);
rng_t rng(rng_seed);
const size_t num_docs = 500;
std::vector<datum_t> data = generate_data(num_docs, &rng);
prepare_namespace(nsi, osource, stores, data);
try {
const int num_point_runs = 10;
const int num_line_runs = 10;
const int num_polygon_runs = 20;
for (int i = 0; i < num_point_runs; ++i) {
datum_t query_geometry = generate_point(&rng);
test_get_intersecting(query_geometry, data, nsi, osource);
}
for (int i = 0; i < num_line_runs; ++i) {
datum_t query_geometry = generate_line(&rng);
test_get_intersecting(query_geometry, data, nsi, osource);
}
for (int i = 0; i < num_polygon_runs; ++i) {
datum_t query_geometry = generate_polygon(&rng);
test_get_intersecting(query_geometry, data, nsi, osource);
}
} catch (const geo_exception_t &e) {
debugf("Caught a geo exception: %s\n", e.what());
FAIL();
}
}
// Test that `get_nearest` results agree with `distance`
TPTEST(GeoIndexes, GetNearest) {
run_with_namespace_interface(&run_get_nearest_test);
}
// Test that `get_intersecting` results agree with `intersects`
TPTEST(GeoIndexes, GetIntersecting) {
run_with_namespace_interface(&run_get_intersecting_test);
}
} /* namespace unittest */
| 35,878
|
https://github.com/ahmedEid1/Casting-Agnecy/blob/master/api/movies_endpoints.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Casting-Agnecy
|
ahmedEid1
|
Python
|
Code
| 131
| 649
|
from flask import request, jsonify, abort
from auth.auth import requires_auth
def setup_movies_endpoints(app, movie_model):
# get all movies
@app.route('/movies', methods=['GET'])
@requires_auth("get:movies")
def get_movies():
movies = [movie.format() for movie in movie_model.query.order_by().all()]
response = {
"movies": movies,
}
return jsonify(response)
# get movies by id
@app.route('/movies/<int:movie_id>', methods=["GET"])
@requires_auth("get:movies")
def get_movie(movie_id):
try:
movie = movie_model.query.get(movie_id)
return jsonify({"movie": movie.format()})
except:
abort(400)
# delete an actor
@app.route('/movies/<int:movie_id>', methods=["DELETE"])
@requires_auth("delete:movies")
def delete_movie(movie_id):
try:
movie = movie_model.query.get(movie_id)
movie.delete()
return jsonify({"id": movie_id})
except:
abort(400)
# add a movie
@app.route("/movies/add", methods=['POST'])
@requires_auth("add:movies")
def create_movie():
try:
movie = movie_model(
title=request.json['title'],
release_date=request.json['release_date']
)
movie.insert()
movies = movie_model.query.order_by(movie_model.id).all()
return jsonify(
{
"movie": movies[-1].format(),
}
)
except:
abort(400)
# add a movie
@app.route("/movies/edit/<int:movie_id>", methods=['PATCH'])
@requires_auth("edit:movies")
def edit_movie(movie_id):
try:
movie = movie_model.query.get(movie_id)
movie.title = request.json.get("title", movie.title)
movie.release_date = request.json.get("release_date", movie.release_date)
movie.update()
return jsonify({"movie": movie.format()})
except:
abort(400)
| 27,414
|
https://github.com/nao2b/jiji2/blob/master/sites/spec/specs/utils/observable-spec.js
|
Github Open Source
|
Open Source
|
Unlicense
| 2,022
|
jiji2
|
nao2b
|
JavaScript
|
Code
| 286
| 1,563
|
import Observable from "src/utils/observable"
describe("Observable", () => {
var target;
beforeEach(() => {
target = new Observable();
});
it("登録したObserverにイベントを通知できる", () => {
const log = [];
target.addObserver("a", (n, e) => log.push(e.value));
target.addObserver("a", (n, e) => log.push(e.value));
target.addObserver("b", (n, e) => log.push(e.value));
target.fire("a", {
value: "aa"
});
expect(log.length).toBe(2);
expect(log[0]).toBe("aa");
expect(log[1]).toBe("aa");
target.fire("b", {
value: "bb"
});
expect(log.length).toBe(3);
expect(log[0]).toBe("aa");
expect(log[1]).toBe("aa");
expect(log[2]).toBe("bb");
target.fire("c", {
value: "cc"
});
expect(log.length).toBe(3);
expect(log[0]).toBe("aa");
expect(log[1]).toBe("aa");
expect(log[2]).toBe("bb");
});
it("removeObserverでobserverを削除できる", () => {
const log = [];
const observer1 = (n, e) => log.push(e.value);
const observer2 = (n, e) => log.push(e.value+"2");
target.addObserver("a", observer1);
target.addObserver("a", observer2);
target.addObserver("b", observer1);
target.removeObserver( "a", observer1 );
target.fire("a", {
value: "aa"
});
expect(log.length).toBe(1);
expect(log[0]).toBe("aa2");
target.fire("b", {
value: "bb"
});
expect(log.length).toBe(2);
expect(log[0]).toBe("aa2");
expect(log[1]).toBe("bb");
target.removeObserver( "a", observer2 );
target.removeObserver( "b", observer1 );
target.fire("a", {
value: "aa"
});
target.fire("b", {
value: "bb"
});
expect(log.length).toBe(2);
});
it("receiverを指定して登録すると、removeAllObserversでreceiverに関連したObserverをまとめて削除できる", () => {
const receiver1 = {};
const receiver2 = {};
const log = [];
target.addObserver("a", (n, e) => log.push(e.value+"1"), receiver1);
target.addObserver("a", (n, e) => log.push(e.value+"2"), receiver2);
target.addObserver("a", (n, e) => log.push(e.value));
target.addObserver("b", (n, e) => log.push(e.value+"1"), receiver1);
target.removeAllObservers(receiver1);
target.fire("a", {
value: "aa"
});
expect(log.length).toBe(2);
expect(log[0]).toBe("aa2");
expect(log[1]).toBe("aa");
target.fire("b", {
value: "bb"
});
expect(log.length).toBe(2);
target.removeAllObservers(receiver2);
target.fire("a", {
value: "aa"
});
expect(log.length).toBe(3);
expect(log[0]).toBe("aa2");
expect(log[1]).toBe("aa");
expect(log[2]).toBe("aa");
});
describe("setProperty/getProperty", () => {
it("プロパティを更新できる", () => {
expect(target.getProperty("a")).toBe(undefined);
target.setProperty("a", "aa");
target.setProperty("b", 10);
expect(target.getProperty("a")).toBe("aa");
expect(target.getProperty("b")).toBe(10);
});
it("プロパティの変更がある場合、イベントが通知される", () => {
const log = [];
target.addObserver("propertyChanged", (n, e) => log.push(e));
target.setProperty("a", "aa");
expect(log.length).toBe(1);
expect(log[0].key).toBe("a");
expect(log[0].oldValue).toBe(undefined);
expect(log[0].newValue).toBe("aa");
target.setProperty("a", "bb");
expect(log.length).toBe(2);
expect(log[1].key).toBe("a");
expect(log[1].oldValue).toBe("aa");
expect(log[1].newValue).toBe("bb");
target.setProperty("a", "bb");
expect(log.length).toBe(2);
});
it("引数でcomparatorを指定できる", () => {
const log = [];
target.addObserver("propertyChanged", (n, e) => log.push(e));
target.setProperty("a", "aa");
expect(log.length).toBe(1);
expect(log[0].key).toBe("a");
expect(log[0].oldValue).toBe(undefined);
expect(log[0].newValue).toBe("aa");
target.setProperty("a", "bb", (a, b) => true );
expect(log.length).toBe(1);
target.setProperty("a", "aa", (a, b) => false );
expect(log.length).toBe(2);
expect(log[1].key).toBe("a");
expect(log[1].oldValue).toBe("aa");
expect(log[1].newValue).toBe("aa");
});
});
});
| 42,713
|
https://github.com/rammazzoti2000/Hacker-Rack-Challenges/blob/master/hackerranck_challenges/Extra/05_AngryProfessor.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Hacker-Rack-Challenges
|
rammazzoti2000
|
Ruby
|
Code
| 47
| 96
|
# AngryProfessor
# Main Solution
def angryProfessor(k, a)
count = a.select { |i| i <= 0 }.count >= k ? 'NO' : 'YES'
end
# Alternative Solution
def angryProfessor(k, a)
count = a.select { |i| i <= 0 }.count
count >= k ? 'NO' : 'YES'
end
| 45,290
|
https://github.com/Junglebobo/poker/blob/master/test/test_chen.py
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
poker
|
Junglebobo
|
Python
|
Code
| 97
| 419
|
import unittest
from pokeher.chen import *
from pokeher.cards import *
import pokeher.constants as C
class ChenScoreTest(unittest.TestCase):
def test_pair(self):
"""Tests that pairs are scored correctly"""
twotwo = Hand(Card(2, C.HEARTS), Card(2, C.SPADES))
self.assertTrue(twotwo.is_pair())
self.assertEquals(ChenScore(twotwo).score(), 5)
JJ = Hand(Card(C.JACK, C.DIAMONDS), Card(C.JACK, C.CLUBS))
self.assertTrue(JJ.is_pair())
self.assertEquals(ChenScore(JJ).score(), 12)
def test_suited(self):
"""Tests that suited cards get a bonus"""
AK = Hand(Card(C.ACE, C.SPADES), Card(C.KING, C.SPADES))
self.assertEquals(ChenScore(AK).score(), 12)
def test_gap_and_under_q(self):
"""Tests that 5-7H is scored correctly"""
five_seven = Hand(Card(5, C.HEARTS), Card(7, C.HEARTS))
self.assertEquals(ChenScore(five_seven).score(), 6)
def test_negative_score(self):
"""Tests that negative scores are reported correctly"""
two_seven = Hand(Card(2, C.CLUBS), Card(7, C.HEARTS))
self.assertEquals(ChenScore(two_seven).score(), -1)
if __name__ == '__main__':
unittest.main()
| 29,028
|
https://github.com/rsyh93/mdir.js/blob/master/src/panel/sftp/socks/common/receivebuffer.ts
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
mdir.js
|
rsyh93
|
TypeScript
|
Code
| 160
| 462
|
class ReceiveBuffer {
private buffer: Buffer;
private offset: number;
private originalSize: number;
constructor(size: number = 4096) {
this.buffer = Buffer.allocUnsafe(size);
this.offset = 0;
this.originalSize = size;
}
get length() {
return this.offset;
}
append(data: Buffer): number {
if (!Buffer.isBuffer(data)) {
throw new Error(
"Attempted to append a non-buffer instance to ReceiveBuffer.",
);
}
if (this.offset + data.length >= this.buffer.length) {
const tmp = this.buffer;
this.buffer = Buffer.allocUnsafe(
Math.max(
this.buffer.length + this.originalSize,
this.buffer.length + data.length,
),
);
tmp.copy(this.buffer);
}
data.copy(this.buffer, this.offset);
return (this.offset += data.length);
}
peek(length: number) {
if (length > this.offset) {
throw new Error(
"Attempted to read beyond the bounds of the managed internal data.",
);
}
return this.buffer.slice(0, length);
}
get(length: number): Buffer {
if (length > this.offset) {
throw new Error(
"Attempted to read beyond the bounds of the managed internal data.",
);
}
const value = Buffer.allocUnsafe(length);
this.buffer.slice(0, length).copy(value);
this.buffer.copyWithin(0, length, length + this.offset - length);
this.offset -= length;
return value;
}
}
export {ReceiveBuffer};
| 3,990
|
https://github.com/klc/translation/blob/master/src/TranslationFromDb.php
|
Github Open Source
|
Open Source
|
MIT
| null |
translation
|
klc
|
PHP
|
Code
| 43
| 140
|
<?php
namespace KLC;
use App\Models\Translation as TranslationModel;
class TranslationFromDb extends DataChain
{
/**
* @param array $params
* @return string
*/
protected function handle($params): string
{
$translation = TranslationModel::where('language_id', $params['language_id'])
->where('slug', $params['slug'])
->first();
if (!$translation) {
return $params['slug'];
}
return $translation->translation;
}
}
| 39,132
|
https://github.com/MatthewBelongia/tutorials/blob/master/spring-boot-modules/spring-boot-angular/src/main/java/com/baeldung/persistence/TestRepository.java
|
Github Open Source
|
Open Source
|
MIT
| null |
tutorials
|
MatthewBelongia
|
Java
|
Code
| 15
| 67
|
package com.baeldung.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TestRepository extends JpaRepository<TestEntity, Long> {
}
| 27,306
|
https://github.com/svebk/DeepSentiBank_memex/blob/master/workflows/dl-escorts-images/dl-escorts-images.py
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,017
|
DeepSentiBank_memex
|
svebk
|
Python
|
Code
| 310
| 1,125
|
import json
from StringIO import StringIO
from pyspark import SparkContext, SparkConf
image_column = "image"
def get_list_value(json_x,field_tuple):
return [x["value"] for x in json_x if x["columnFamily"]==field_tuple[0] and x["qualifier"]==field_tuple[1]]
def image_not_present(data):
return True
json_x = [json.loads(x) for x in data[1].split("\n")]
try:
row_image = get_list_value(json_x,("info",image_column))[0]
# Check for None here just to be safe
if row_image is None:
raise ValueError("Image invalid.")
# Image is there and valid, skipping to avoid re-download
return False
except: # Image is missing, we need to download
return True
def download_image(data):
import image_dl
key = data[0]
json_x = [json.loads(x) for x in data[1].split("\n")]
try:
# First check if we can get s3 url
s3_url = get_list_value(json_x,("info","s3_url"))[0].strip()
# Check for None here just to be safe
if s3_url is None or s3_url == u'None' or s3_url == 'None':
raise ValueError('[download_image: error] s3_url is None.')
# Download the image
data = image_dl.get_image_from_URL(unicode(s3_url))
outdata = StringIO(data).getvalue()
# Sanity check of sha1
sha1 = image_dl.get_SHA1_from_data(data)
if sha1 != key:
# May be due to an original image in png and s3 in .jpg?
raise ValueError('[download_image: error] sha1 has not the expected value {} != {}.'.format(sha1,key))
#print('[download_image: error] sha1 has not the expected value {} != {}.'.format(sha1,key))
return [(key, [key, "info", image_column, outdata])]
except Exception as inst:
print(inst)
return []
def fill_binary_image(hbase_man_in, hbase_man_out, nb_images_by_partition):
import numpy as np
in_rdd = hbase_man_in.read_hbase_table()
images_to_dl_rdd = in_rdd.filter(image_not_present)
nb_images_to_dl = images_to_dl_rdd.count()
nb_partitions = int(np.ceil(nb_images_to_dl/nb_images_by_partition))
print('We have {} images, we want a maximum of {} images by partition. So we will partition in {} partitions.'.format(nb_images_to_dl, nb_images_by_partition, nb_partitions))
out_rdd = images_to_dl_rdd.partitionBy(nb_partitions).flatMap(lambda x: download_image(x))
hbase_man_out.rdd2hbase(out_rdd)
nb_images_dled = out_rdd.count()
print('We have downloaded {} images.'.format(nb_images_dled))
print("[fill_binary_image] DONE.")
if __name__ == '__main__':
from hbase_manager import HbaseManager
job_conf = json.load(open("job_conf.json","rt"))
print job_conf
tab_sha1_name = job_conf["tab_sha1_name"]
hbase_host = job_conf["hbase_host"]
nb_images_by_partition = job_conf["nb_images_by_partition"]
sc = SparkContext(appName='dl_images_'+tab_sha1_name)
sc.setLogLevel("ERROR")
conf = SparkConf()
hbase_man_in = HbaseManager(sc, conf, hbase_host, tab_sha1_name, columns=["info:image", "info:s3_url"])
hbase_man_out = HbaseManager(sc, conf, hbase_host, tab_sha1_name)
fill_binary_image(hbase_man_in, hbase_man_out, nb_images_by_partition)
| 29,151
|
https://github.com/aadil1/terrascan/blob/master/pkg/policies/opa/rego/gcp/google_container_node_pool/cosNodeImageUsed.rego
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
terrascan
|
aadil1
|
Open Policy Agent
|
Code
| 13
| 59
|
package accurics
cosNodeImageUsed[api.id]{
api := input.google_container_node_pool[_]
node := api.config.node_config[_]
node.image_type != "cos"
}
| 32,757
|
https://github.com/hashgraph/hedera-sdk-java/blob/master/sdk/src/main/java/com/hedera/hashgraph/sdk/TransactionReceiptQuery.java
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference
| 2,023
|
hedera-sdk-java
|
hashgraph
|
Java
|
Code
| 671
| 1,870
|
/*-
*
* Hedera Java SDK
*
* Copyright (C) 2020 - 2023 Hedera Hashgraph, 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 in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.hedera.hashgraph.sdk;
import com.hedera.hashgraph.sdk.proto.CryptoServiceGrpc;
import com.hedera.hashgraph.sdk.proto.QueryHeader;
import com.hedera.hashgraph.sdk.proto.Response;
import com.hedera.hashgraph.sdk.proto.ResponseHeader;
import com.hedera.hashgraph.sdk.proto.TransactionGetReceiptQuery;
import io.grpc.MethodDescriptor;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Get the receipt of a transaction, given its transaction ID.
*
* <p>Once a transaction reaches consensus, then information about whether it succeeded or failed
* will be available until the end of the receipt period.
*
* <p>This query is free.
*/
public final class TransactionReceiptQuery
extends Query<TransactionReceipt, TransactionReceiptQuery> {
@Nullable
private TransactionId transactionId = null;
private boolean includeChildren = false;
private boolean includeDuplicates = false;
/**
* Constructor.
*/
public TransactionReceiptQuery() {
}
/**
* Extract the transaction id.
*
* @return the transaction id
*/
@Override
@Nullable
public TransactionId getTransactionIdInternal() {
return transactionId;
}
/**
* Set the ID of the transaction for which the receipt is being requested.
*
* @param transactionId The TransactionId to be set
* @return {@code this}
*/
public TransactionReceiptQuery setTransactionId(TransactionId transactionId) {
Objects.requireNonNull(transactionId);
this.transactionId = transactionId;
return this;
}
/**
* Should the children be included?
*
* @return should children be included
*/
public boolean getIncludeChildren() {
return includeChildren;
}
/**
* Whether the response should include the records of any child transactions spawned by the
* top-level transaction with the given transactionID.
*
* @param value The value that includeChildren should be set to; true to include children, false to exclude
* @return {@code this}
*/
public TransactionReceiptQuery setIncludeChildren(boolean value) {
includeChildren = value;
return this;
}
/**
* Should duplicates be included?
*
* @return should duplicates be included
*/
public boolean getIncludeDuplicates() {
return includeDuplicates;
}
/**
* Whether records of processing duplicate transactions should be returned along with the record
* of processing the first consensus transaction with the given id whose status was neither
* INVALID_NODE_ACCOUNT nor INVALID_PAYER_SIGNATURE or, if no such
* record exists, the record of processing the first transaction to reach consensus with the
* given transaction id.
*
* @param value The value that includeDuplicates should be set to; true to include duplicates, false to exclude
* @return {@code this}
*/
public TransactionReceiptQuery setIncludeDuplicates(boolean value) {
includeDuplicates = value;
return this;
}
@Override
boolean isPaymentRequired() {
return false;
}
@Override
void validateChecksums(Client client) throws BadEntityIdException {
if (transactionId != null) {
Objects.requireNonNull(transactionId.accountId).validateChecksum(client);
}
}
@Override
void onMakeRequest(com.hedera.hashgraph.sdk.proto.Query.Builder queryBuilder, QueryHeader header) {
var builder = TransactionGetReceiptQuery.newBuilder()
.setIncludeChildReceipts(includeChildren)
.setIncludeDuplicates(includeDuplicates);
if (transactionId != null) {
builder.setTransactionID(transactionId.toProtobuf());
}
queryBuilder.setTransactionGetReceipt(builder.setHeader(header));
}
@Override
Status mapResponseStatus(Response response) {
var preCheckCode = response.getTransactionGetReceipt().getHeader().getNodeTransactionPrecheckCode();
return Status.valueOf(preCheckCode);
}
@Override
TransactionReceipt mapResponse(Response response, AccountId nodeId, com.hedera.hashgraph.sdk.proto.Query request) {
var receiptResponse = response.getTransactionGetReceipt();
var duplicates = mapReceiptList(receiptResponse.getDuplicateTransactionReceiptsList());
var children = mapReceiptList(receiptResponse.getChildTransactionReceiptsList());
return TransactionReceipt.fromProtobuf(response.getTransactionGetReceipt().getReceipt(), duplicates, children, transactionId);
}
/**
* Create a list of transaction receipts from a protobuf.
*
* @param protoReceiptList the protobuf
* @return the list of transaction receipts
*/
private static List<TransactionReceipt> mapReceiptList(
List<com.hedera.hashgraph.sdk.proto.TransactionReceipt> protoReceiptList
) {
List<TransactionReceipt> outList = new ArrayList<>(protoReceiptList.size());
for (var protoReceipt : protoReceiptList) {
outList.add(TransactionReceipt.fromProtobuf(protoReceipt));
}
return outList;
}
@Override
QueryHeader mapRequestHeader(com.hedera.hashgraph.sdk.proto.Query request) {
return request.getTransactionGetReceipt().getHeader();
}
@Override
ResponseHeader mapResponseHeader(Response response) {
return response.getTransactionGetReceipt().getHeader();
}
@Override
MethodDescriptor<com.hedera.hashgraph.sdk.proto.Query, Response> getMethodDescriptor() {
return CryptoServiceGrpc.getGetTransactionReceiptsMethod();
}
@Override
ExecutionState getExecutionState(Status status, Response response) {
switch (status) {
case BUSY:
case UNKNOWN:
case RECEIPT_NOT_FOUND:
case RECORD_NOT_FOUND:
return ExecutionState.RETRY;
case OK:
break;
default:
return ExecutionState.REQUEST_ERROR;
}
var receiptStatus =
Status.valueOf(response.getTransactionGetReceipt().getReceipt().getStatus());
switch (receiptStatus) {
case BUSY:
case UNKNOWN:
case OK:
case RECEIPT_NOT_FOUND:
case RECORD_NOT_FOUND:
return ExecutionState.RETRY;
default:
return ExecutionState.SUCCESS;
}
}
}
| 35,604
|
https://github.com/tazmanrising/IntiotgAngular/blob/master/abundalife/wwwroot/bloodtest/old_at_root_4_aug_2014/newsite/Create_User-old.aspx.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
IntiotgAngular
|
tazmanrising
|
C#
|
Code
| 89
| 298
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace abundalife1001
{
public partial class Create_User : System.Web.UI.Page
{
clsData clsData = new clsData();
protected void SignOut(object sender, EventArgs e)
{
//delete the users auth cookie and sign out
FormsAuthentication.SignOut();
//redirect the user to their referring page
Response.Redirect(Request.UrlReferrer.ToString());
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = clsData.ins_user(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text);
}
}
}
| 15,642
|
https://github.com/guoweiwen/AudioVedioPlayer/blob/master/app/src/main/java/com/wyman/videoaudioplayer/camera/CameraManager.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
AudioVedioPlayer
|
guoweiwen
|
Java
|
Code
| 271
| 1,169
|
package com.wyman.videoaudioplayer.camera;
import android.hardware.Camera;
import android.opengl.GLSurfaceView;
import com.wyman.videoaudioplayer.filter.GPUFilter;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO;
/**
* 管理摄像头类
*/
public class CameraManager {
private CameraWraper mCamera;
private int mCameraId = -1;
private GLSurfaceView glSurfaceView;
private static CameraManager manager;
// private boolean preViewRuning;
private GLRender mRender;
public static CameraManager getManager(){
if(manager==null){
manager = new CameraManager();
}
return manager;
}
/**
* 初始化摄像头的信息
* */
public void init(){
if(manager != null){
//默认打开后置摄像头
int cameraType = Camera.CameraInfo.CAMERA_FACING_BACK;
manager.openCamera(cameraType);
Camera.Parameters parameters = mCamera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
Camera.Size preViewSize = CameraManager.getClosestSupportedSize(sizes,1280,720);
if(parameters.getSupportedFocusModes().contains(FOCUS_MODE_CONTINUOUS_VIDEO)){
parameters.setFocusMode(FOCUS_MODE_CONTINUOUS_VIDEO);
}
parameters.setPreviewSize(preViewSize.width,preViewSize.height);
parameters.setPreviewFrameRate(25);
parameters.setRecordingHint(true);
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(90);
}
}
public void CameraManger(){}
public CameraWraper openCamera(int facingTpe){
int cameraCount = Camera.getNumberOfCameras();
for(int i=0;i<cameraCount;i++){
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
Camera.getCameraInfo(i,cameraInfo);
if(cameraInfo.facing == facingTpe){
mCamera = CameraWraper.open(i);
mCameraId = i;
break;
}
}
if(mRender!=null){
mRender.setmCamera(mCamera);
}
return mCamera;
}
public void setGlSurfaceView(GLSurfaceView glSurfaceView) {
//关联 GLSurfaceView
this.glSurfaceView = glSurfaceView;
this.glSurfaceView.setEGLContextClientVersion(2);
mRender = new GLRender(mCamera,glSurfaceView);
this.glSurfaceView.setRenderer(mRender);
}
public void onPause(){
mCamera.stopPreview();
// glSurfaceView.onPause();
}
public void onResume(){
mCamera.startPreview();
// glSurfaceView.onResume();
}
public void setFilter(GPUFilter filter){
mRender.setmFilter(filter);
}
public void onDestory(){
mCamera.startPreview();
mRender.release();
mRender = null;
new Thread() {
@Override
public void run() {
super.run();
try {
Thread.sleep(500);//休眠0.5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
releaseCamera();
glSurfaceView.onPause();
}
}.start();
}
public void releaseCamera(){
if(mCamera == null) return;
if(mCamera.isPreViewing){
mCamera.stopPreview();
}
mCamera.release();
mCamera = null;
}
public static Camera.Size getClosestSupportedSize(List<Camera.Size> supportedSizes, final int requestedWidth, final int requestedHeight) {
return (Camera.Size) Collections.min(supportedSizes, new Comparator<Camera.Size>() {
private int diff(final Camera.Size size) {
return Math.abs(requestedWidth - size.width) + Math.abs(requestedHeight - size.height);
}
@Override
public int compare(final Camera.Size lhs, final Camera.Size rhs) {
return diff(lhs) - diff(rhs);
}
});
}
}
| 42,252
|
https://github.com/CESNET/perun/blob/master/perun-core/src/main/java/cz/metacentrum/perun/core/impl/modules/attributes/urn_perun_resource_attribute_def_def_defaultShell.java
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
perun
|
CESNET
|
Java
|
Code
| 355
| 1,226
|
package cz.metacentrum.perun.core.impl.modules.attributes;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.Resource;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import cz.metacentrum.perun.core.implApi.modules.attributes.ResourceAttributesModuleAbstract;
import cz.metacentrum.perun.core.implApi.modules.attributes.ResourceAttributesModuleImplApi;
import java.util.ArrayList;
import java.util.List;
/**
* Checks and fills default shells per resource.
*
* @date 28.4.2011 11:12:16
* @author Lukáš Pravda <luky.pravda@gmail.com>
*/
public class urn_perun_resource_attribute_def_def_defaultShell extends ResourceAttributesModuleAbstract implements ResourceAttributesModuleImplApi {
private static final String A_R_shells = AttributesManager.NS_RESOURCE_ATTR_DEF + ":shells";
/**
* Fills the default shell at specified resource. If the facility contains
* no shells, the exception is thrown otherwise some shell is picked.
*/
@Override
public Attribute fillAttribute(PerunSessionImpl perunSession, Resource resource, AttributeDefinition attribute) throws WrongAttributeAssignmentException {
Attribute atr = new Attribute(attribute);
Attribute resourceAttr;
try {
resourceAttr = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, resource, A_R_shells);
} catch (AttributeNotExistsException ex) {
throw new InternalErrorException("Attribute with list of shells from resource " + resource.getId() + " could not obtained.", ex);
}
if (resourceAttr.getValue() == null) {
return atr;
} else {
List<String> shells = (List<String>) resourceAttr.getValue();
if (!shells.isEmpty()) {
atr.setValue(shells.get(0));
return atr;
} else {
return atr;
}
}
}
/**
* Checks the attribute with a default shell at the specified resource. The
* new default shell must be included at specified resource.
*/
@Override
public void checkAttributeSemantics(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws WrongReferenceAttributeValueException, WrongAttributeAssignmentException {
if (attribute.getValue() == null) {
throw new WrongReferenceAttributeValueException(attribute, null, resource, null, "Attribute value is null.");
}
Attribute resourceAttr;
try {
resourceAttr = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, resource, A_R_shells);
} catch (AttributeNotExistsException ex) {
throw new InternalErrorException("Attribute with list of shells from resource " + resource.getId() + " could not obtained.", ex);
}
if (resourceAttr.getValue() == null) {
throw new WrongReferenceAttributeValueException(resourceAttr, null, resource, null, "Attribute with list of shells from resource has null value.");
}
List<String> shells = resourceAttr.valueAsList();
if (!shells.contains(attribute.valueAsString())) {
throw new WrongReferenceAttributeValueException(attribute, resourceAttr, resource, null, resource, null, "Shell " + attribute.getValue() + " is not at specified resource (" + resource + ")");
}
}
@Override
public List<String> getDependencies() {
List<String> dependecies = new ArrayList<>();
dependecies.add(A_R_shells);
return dependecies;
}
@Override
public AttributeDefinition getAttributeDefinition() {
AttributeDefinition attr = new AttributeDefinition();
attr.setNamespace(AttributesManager.NS_RESOURCE_ATTR_DEF);
attr.setFriendlyName("defaultShell");
attr.setDisplayName("Default shell");
attr.setType(String.class.getName());
attr.setDescription("Default shell for all members on this resource.");
return attr;
}
}
| 19,843
|
https://github.com/lgoldstein/communitychest/blob/master/development/src/main/java/net/community/chest/net/proto/text/ssh/message/auth/UserAuthPasswordChangeReq.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
communitychest
|
lgoldstein
|
Java
|
Code
| 217
| 954
|
/*
*
*/
package net.community.chest.net.proto.text.ssh.message.auth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.community.chest.net.proto.text.ssh.SSHMsgCode;
import net.community.chest.net.proto.text.ssh.SSHProtocol;
import net.community.chest.net.proto.text.ssh.io.SSHInputDataDecoder;
import net.community.chest.net.proto.text.ssh.io.SSHOutputDataEncoder;
import net.community.chest.net.proto.text.ssh.message.AbstractSSHMsgEncoder;
/**
* <P>Copyright as per GPLv2</P>
*
* @author Lyor G.
* @since Jul 12, 2009 10:31:43 AM
*/
public class UserAuthPasswordChangeReq extends AbstractSSHMsgEncoder<UserAuthPasswordChangeReq> {
/**
*
*/
private static final long serialVersionUID = 8248598106405113531L;
public UserAuthPasswordChangeReq ()
{
super(SSHMsgCode.SSH_MSG_USERAUTH_PASSWD_CHANGEREQ);
}
private String _prompt;
public String getPrompt ()
{
return _prompt;
}
public void setPrompt (String message)
{
_prompt = message;
}
private String _languageTag;
public String getLanguageTag ()
{
return _languageTag;
}
public void setLanguageTag (String languageTag)
{
_languageTag = languageTag;
}
/*
* @see net.community.chest.io.encode.ElementEncoder#read(java.io.InputStream)
*/
@Override
public UserAuthPasswordChangeReq read (InputStream in) throws IOException
{
setPrompt(SSHProtocol.readUTF8String(in));
setLanguageTag(SSHProtocol.readASCIIString(in));
return this;
}
/*
* @see net.community.chest.net.proto.text.ssh.SSHDataObjectEncoder#decode(net.community.chest.net.proto.text.ssh.io.SSHInputDataDecoder)
*/
@Override
public UserAuthPasswordChangeReq decode (SSHInputDataDecoder in) throws IOException
{
if (null == in)
throw new IOException("decode(" + getMsgCode() + ") no " + SSHInputDataDecoder.class.getSimpleName() + " instance");
setPrompt(in.readUTF());
setLanguageTag(in.readASCII());
return this;
}
/*
* @see net.community.chest.io.encode.ElementEncoder#write(java.io.OutputStream)
*/
@Override
public void write (OutputStream out) throws IOException
{
SSHProtocol.writeStringBytes(out, false, getPrompt());
SSHProtocol.writeStringBytes(out, true, getLanguageTag());
}
/*
* @see net.community.chest.net.proto.text.ssh.SSHDataObjectEncoder#encode(net.community.chest.net.proto.text.ssh.io.SSHOutputDataEncoder)
*/
@Override
public void encode (SSHOutputDataEncoder out) throws IOException
{
if (null == out)
throw new IOException("encode(" + getMsgCode() + ") no " + SSHOutputDataEncoder.class.getSimpleName() + " instance");
out.writeUTF(getPrompt());
out.writeASCII(getLanguageTag());
}
}
| 18,852
|
https://github.com/kubeflow/arena/blob/master/pkg/apis/serving/kserve_builder.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
arena
|
kubeflow
|
Go
|
Code
| 1,324
| 3,321
|
package serving
import (
"fmt"
"strings"
"github.com/kubeflow/arena/pkg/apis/types"
"github.com/kubeflow/arena/pkg/argsbuilder"
)
type KServeJobBuilder struct {
args *types.KServeArgs
argValues map[string]interface{}
argsbuilder.ArgsBuilder
}
func NewKServeJobBuilder() *KServeJobBuilder {
args := &types.KServeArgs{
CommonServingArgs: types.CommonServingArgs{
ImagePullPolicy: "IfNotPresent",
Replicas: 1,
Namespace: "default",
Shell: "sh",
},
}
return &KServeJobBuilder{
args: args,
argValues: map[string]interface{}{},
ArgsBuilder: argsbuilder.NewKServeArgsBuilder(args),
}
}
// Name is used to set job name,match option --name
func (b *KServeJobBuilder) Name(name string) *KServeJobBuilder {
if name != "" {
b.args.Name = name
}
return b
}
// Namespace is used to set job namespace,match option --namespace
func (b *KServeJobBuilder) Namespace(namespace string) *KServeJobBuilder {
if namespace != "" {
b.args.Namespace = namespace
}
return b
}
// Shell is used to set bash or sh
func (b *KServeJobBuilder) Shell(shell string) *KServeJobBuilder {
if shell != "" {
b.args.Shell = shell
}
return b
}
// Command is used to set job command
func (b *KServeJobBuilder) Command(args []string) *KServeJobBuilder {
b.args.Command = strings.Join(args, " ")
return b
}
// GPUCount is used to set count of gpu for the job,match the option --gpus
func (b *KServeJobBuilder) GPUCount(count int) *KServeJobBuilder {
if count > 0 {
b.args.GPUCount = count
}
return b
}
// GPUMemory is used to set gpu memory for the job,match the option --gpumemory
func (b *KServeJobBuilder) GPUMemory(memory int) *KServeJobBuilder {
if memory > 0 {
b.args.GPUMemory = memory
}
return b
}
// GPUCore is used to set gpu core for the job, match the option --gpucore
func (b *KServeJobBuilder) GPUCore(core int) *KServeJobBuilder {
if core > 0 {
b.args.GPUCore = core
}
return b
}
// Image is used to set job image,match the option --image
func (b *KServeJobBuilder) Image(image string) *KServeJobBuilder {
if image != "" {
b.args.Image = image
}
return b
}
// ImagePullPolicy is used to set image pull policy,match the option --image-pull-policy
func (b *KServeJobBuilder) ImagePullPolicy(policy string) *KServeJobBuilder {
if policy != "" {
b.args.ImagePullPolicy = policy
}
return b
}
// CPU assign cpu limits,match the option --cpu
func (b *KServeJobBuilder) CPU(cpu string) *KServeJobBuilder {
if cpu != "" {
b.args.Cpu = cpu
}
return b
}
// Memory assign memory limits,match option --memory
func (b *KServeJobBuilder) Memory(memory string) *KServeJobBuilder {
if memory != "" {
b.args.Memory = memory
}
return b
}
// Envs is used to set env of job containers,match option --env
func (b *KServeJobBuilder) Envs(envs map[string]string) *KServeJobBuilder {
if envs != nil && len(envs) != 0 {
envSlice := []string{}
for key, value := range envs {
envSlice = append(envSlice, fmt.Sprintf("%v=%v", key, value))
}
b.argValues["env"] = &envSlice
}
return b
}
// Replicas is used to set serving job replicas,match the option --replicas
func (b *KServeJobBuilder) Replicas(count int) *KServeJobBuilder {
if count > 0 {
b.args.Replicas = count
}
return b
}
// EnableIstio is used to enable istio,match the option --enable-istio
func (b *KServeJobBuilder) EnableIstio() *KServeJobBuilder {
b.args.EnableIstio = true
return b
}
// ExposeService is used to expose service,match the option --expose-service
func (b *KServeJobBuilder) ExposeService() *KServeJobBuilder {
b.args.ExposeService = true
return b
}
// Version is used to set serving job version,match the option --version
func (b *KServeJobBuilder) Version(version string) *KServeJobBuilder {
if version != "" {
b.args.Version = version
}
return b
}
// Tolerations is used to set tolerations for tolerate nodes,match option --toleration
func (b *KServeJobBuilder) Tolerations(tolerations []string) *KServeJobBuilder {
b.argValues["toleration"] = &tolerations
return b
}
// NodeSelectors is used to set node selectors for scheduling job,match option --selector
func (b *KServeJobBuilder) NodeSelectors(selectors map[string]string) *KServeJobBuilder {
if selectors != nil && len(selectors) != 0 {
selectorsSlice := []string{}
for key, value := range selectors {
selectorsSlice = append(selectorsSlice, fmt.Sprintf("%v=%v", key, value))
}
b.argValues["selector"] = &selectorsSlice
}
return b
}
// Annotations is used to add annotations for job pods,match option --annotation
func (b *KServeJobBuilder) Annotations(annotations map[string]string) *KServeJobBuilder {
if annotations != nil && len(annotations) != 0 {
s := []string{}
for key, value := range annotations {
s = append(s, fmt.Sprintf("%v=%v", key, value))
}
b.argValues["annotation"] = &s
}
return b
}
// Labels is used to add labels for job
func (b *KServeJobBuilder) Labels(labels map[string]string) *KServeJobBuilder {
if labels != nil && len(labels) != 0 {
s := []string{}
for key, value := range labels {
s = append(s, fmt.Sprintf("%v=%v", key, value))
}
b.argValues["label"] = &s
}
return b
}
// Datas is used to mount k8s pvc to job pods,match option --data
func (b *KServeJobBuilder) Datas(volumes map[string]string) *KServeJobBuilder {
if volumes != nil && len(volumes) != 0 {
s := []string{}
for key, value := range volumes {
s = append(s, fmt.Sprintf("%v:%v", key, value))
}
b.argValues["data"] = &s
}
return b
}
// DataDirs is used to mount host files to job containers,match option --data-dir
func (b *KServeJobBuilder) DataDirs(volumes map[string]string) *KServeJobBuilder {
if volumes != nil && len(volumes) != 0 {
s := []string{}
for key, value := range volumes {
s = append(s, fmt.Sprintf("%v:%v", key, value))
}
b.argValues["data-dir"] = &s
}
return b
}
// ConfigFiles is used to mapping config files form local to job containers,match option --config-file
func (b *KServeJobBuilder) ConfigFiles(files map[string]string) *KServeJobBuilder {
if files != nil && len(files) != 0 {
filesSlice := []string{}
for localPath, containerPath := range files {
filesSlice = append(filesSlice, fmt.Sprintf("%v:%v", localPath, containerPath))
}
b.argValues["config-file"] = &filesSlice
}
return b
}
// ModelFormat the ModelFormat being served.
func (b *KServeJobBuilder) ModelFormat(modelFormat *types.ModelFormat) *KServeJobBuilder {
if modelFormat != nil {
b.args.ModelFormat = modelFormat
}
return b
}
// Runtime specific ClusterServingRuntime/ServingRuntime name to use for deployment.
func (b *KServeJobBuilder) Runtime(runtime string) *KServeJobBuilder {
if runtime != "" {
b.args.Runtime = runtime
}
return b
}
// StorageUri is used to set storage uri,match the option --storage-uri
func (b *KServeJobBuilder) StorageUri(uri string) *KServeJobBuilder {
if uri != "" {
b.args.StorageUri = uri
}
return b
}
// RuntimeVersion of the predictor docker image
func (b *KServeJobBuilder) RuntimeVersion(runtimeVersion string) *KServeJobBuilder {
if runtimeVersion != "" {
b.args.RuntimeVersion = runtimeVersion
}
return b
}
// ProtocolVersion use by the predictor (i.e. v1 or v2 or grpc-v1 or grpc-v2)
func (b *KServeJobBuilder) ProtocolVersion(protocolVersion string) *KServeJobBuilder {
if protocolVersion != "" {
b.args.ProtocolVersion = protocolVersion
}
return b
}
// MinReplicas number of replicas, defaults to 1 but can be set to 0 to enable scale-to-zero.
func (b *KServeJobBuilder) MinReplicas(minReplicas int) *KServeJobBuilder {
if minReplicas >= 0 {
b.args.MinReplicas = minReplicas
}
return b
}
// MaxReplicas number of replicas for autoscaling.
func (b *KServeJobBuilder) MaxReplicas(maxReplicas int) *KServeJobBuilder {
if maxReplicas > 0 {
b.args.MaxReplicas = maxReplicas
}
return b
}
// ScaleTarget number of replicas for autoscaling.
func (b *KServeJobBuilder) ScaleTarget(scaleTarget int) *KServeJobBuilder {
if scaleTarget > 0 {
b.args.ScaleTarget = scaleTarget
}
return b
}
// ScaleMetric watched by autoscaler. possible values are concurrency, rps, cpu, memory. concurrency, rps are supported via KPA
func (b *KServeJobBuilder) ScaleMetric(scaleMetric string) *KServeJobBuilder {
if scaleMetric != "" {
b.args.ScaleMetric = scaleMetric
}
return b
}
// ContainerConcurrency specifies how many requests can be processed concurrently
func (b *KServeJobBuilder) ContainerConcurrency(containerConcurrency int64) *KServeJobBuilder {
if containerConcurrency > 0 {
b.args.ContainerConcurrency = containerConcurrency
}
return b
}
// TimeoutSeconds specifies the number of seconds to wait before timing out a request to the component.
func (b *KServeJobBuilder) TimeoutSeconds(timeoutSeconds int64) *KServeJobBuilder {
if timeoutSeconds > 0 {
b.args.TimeoutSeconds = timeoutSeconds
}
return b
}
// CanaryTrafficPercent defines the traffic split percentage between the candidate revision and the last ready revision
func (b *KServeJobBuilder) CanaryTrafficPercent(canaryTrafficPercent int64) *KServeJobBuilder {
if canaryTrafficPercent > 0 {
b.args.CanaryTrafficPercent = canaryTrafficPercent
}
return b
}
// Port the port of tcp listening port, default is 8080 in kserve
func (b *KServeJobBuilder) Port(port int) *KServeJobBuilder {
if port > 0 {
b.args.Port = port
}
return b
}
// Build is used to build the job
func (b *KServeJobBuilder) Build() (*Job, error) {
for key, value := range b.argValues {
b.AddArgValue(key, value)
}
if err := b.PreBuild(); err != nil {
return nil, err
}
if err := b.ArgsBuilder.Build(); err != nil {
return nil, err
}
return NewJob(b.args.Name, types.KServeJob, b.args), nil
}
| 29,085
|
https://github.com/peter-courcoux/zebra/blob/master/import/java/fulcrum-security-hivemind/src/main/java/org/apache/fulcrum/security/AbstractSecurityServiceTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,010
|
zebra
|
peter-courcoux
|
Java
|
Code
| 152
| 494
|
package org.apache.fulcrum.security;
import junit.framework.TestCase;
import org.apache.fulcrum.hivemind.RegistryManager;
public class AbstractSecurityServiceTest extends TestCase {
private SecurityService securityService;
private UserManager userManager;
private ModelManager modelManager;
private GroupManager groupManager;
private RoleManager roleManager;
private PermissionManager permissionManager;
public GroupManager getGroupManager() {
return groupManager;
}
public void setGroupManager(GroupManager groupManager) {
this.groupManager = groupManager;
}
public ModelManager getModelManager() {
return modelManager;
}
public void setModelManager(ModelManager modelManager) {
this.modelManager = modelManager;
}
public RoleManager getRoleManager() {
return roleManager;
}
public void setRoleManager(RoleManager roleManager) {
this.roleManager = roleManager;
}
public UserManager getUserManager() {
return userManager;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public void setUp() throws Exception{
securityService = (SecurityService) RegistryManager.getInstance().getRegistry().getService(SecurityService.class);
userManager = securityService.getUserManager();
groupManager = securityService.getGroupManager();
roleManager = securityService.getRoleManager();
modelManager = securityService.getModelManager();
permissionManager = securityService.getPermissionManager();
}
public SecurityService getSecurityService() {
return securityService;
}
public void setSecurityService(SecurityService securityService) {
this.securityService = securityService;
}
public PermissionManager getPermissionManager() {
return permissionManager;
}
public void setPermissionManager(PermissionManager permissionManager) {
this.permissionManager = permissionManager;
}
}
| 6,840
|
https://github.com/spraakbanken/sparv-pipeline/blob/master/sparv/core/config.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
sparv-pipeline
|
spraakbanken
|
Python
|
Code
| 1,363
| 3,681
|
"""Functions for parsing the Sparv configuration files."""
import copy
import logging
from collections import defaultdict
from functools import reduce
from pathlib import Path
from typing import Any, Optional
import yaml
import yaml.scanner
from sparv import util
from sparv.core import paths, registry
log = logging.getLogger(__name__)
DEFAULT_CONFIG = paths.default_config_file
PRESETS_DIR = paths.presets_dir
PARENT = "parent"
MAX_THREADS = "threads"
config = {} # Full configuration
presets = {} # Annotation presets
_config_user = {} # Local corpus config
_config_default = {} # Default config
# Dict with info about config structure, prepopulated with some module-independent keys
config_structure = {
"classes": {"_source": "core"},
"custom_annotations": {"_source": "core"},
"install": {"_source": "core"},
PARENT: {"_source": "core"},
MAX_THREADS: {"_source": "core"},
"preload": {"_source": "core"}
}
config_usage = defaultdict(set) # For each config key, a list of annotators using that key
class Unset:
"""Class used to represent a config value that isn't set."""
pass
def read_yaml(yaml_file):
"""Read YAML file and handle errors."""
try:
with open(yaml_file) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
except yaml.parser.ParserError as e:
raise util.SparvErrorMessage("Could not parse the configuration file:\n" + str(e))
except yaml.scanner.ScannerError as e:
raise util.SparvErrorMessage("An error occurred while reading the configuration file:\n" + str(e))
except FileNotFoundError:
raise util.SparvErrorMessage(f"Could not find the config file '{yaml_file}'")
return data or {}
def load_config(config_file: Optional[str], config_dict: Optional[dict] = None) -> None:
"""Load both default config and corpus config and merge into one config structure.
Args:
config_file: Path to corpus config file. If None, only the default config is read.
config_dict: Get corpus config from dictionary instead of config file.
"""
assert not (config_file and config_dict), "config_file and config_dict can not be used together"
# Read default config
global _config_default
if DEFAULT_CONFIG.is_file():
_config_default = read_yaml(DEFAULT_CONFIG)
else:
log.warning("Default config file is missing: {}".format(DEFAULT_CONFIG))
_config_default = {}
if config_file:
# Read corpus config
global _config_user
_config_user = read_yaml(config_file) or {}
def handle_parents(cfg, current_dir="."):
"""Combine parent configs recursively."""
combined_parents = {}
if cfg.get(PARENT):
parents = cfg[PARENT]
if isinstance(parents, str):
parents = [parents]
for parent in parents:
parent_path = Path(current_dir, parent)
config_parent = read_yaml(parent_path)
config_parent = handle_parents(config_parent, parent_path.parent)
combined_parents = _merge_dicts(config_parent, combined_parents)
cfg = _merge_dicts(cfg, combined_parents)
return cfg
# If parent configs are specified, inherit their contents
_config_user = handle_parents(_config_user)
elif config_dict:
_config_user = config_dict
else:
_config_user = {}
# Merge default and corpus config and save to global config variable
global config
config = _merge_dicts(copy.deepcopy(_config_user), _config_default)
# Make sure that the root level only contains dictionaries or lists to save us a lot of headache
for key in config:
if key == PARENT:
continue
if not isinstance(config[key], (dict, list)):
raise util.SparvErrorMessage(f"The config section '{key}' could not be parsed.", module="sparv",
function="config")
def dump_config(data, resolve_alias=False, sort_keys=False):
"""Dump config YAML to string.
Args:
data: The data to be dumped.
resolve_alias: Will replace aliases with their anchor's content if set to True.
sort_keys: Whether to sort the keys alphabetically.
"""
class IndentDumper(yaml.Dumper):
"""Customized YAML dumper that indents lists."""
def increase_indent(self, flow=False, indentless=False):
"""Force indentation."""
return super(IndentDumper, self).increase_indent(flow)
# Add custom string representer for prettier multiline strings
def str_presenter(dumper, data):
if len(data.splitlines()) > 1: # check for multiline string
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
return dumper.represent_scalar('tag:yaml.org,2002:str', data)
yaml.add_representer(str, str_presenter)
if resolve_alias:
# Resolve aliases and replace them with their anchors' contents
yaml.Dumper.ignore_aliases = lambda *args: True
return yaml.dump(data, sort_keys=sort_keys, allow_unicode=True, Dumper=IndentDumper, indent=4,
default_flow_style=False)
def _get(name: str, config_dict=None):
"""Try to get value from config, raising an exception if key doesn't exist."""
config_dict = config_dict if config_dict is not None else config
# Handle dot notation
return reduce(lambda c, k: c[k], name.split("."), config_dict)
def set_value(name: str, value: Any, overwrite=True, config_dict=None):
"""Set value in config, possibly using dot notation."""
keys = name.split(".")
prev = config_dict if config_dict is not None else config
for key in keys[:-1]:
prev.setdefault(key, {})
prev = prev[key]
if overwrite:
prev[keys[-1]] = value
else:
prev.setdefault(keys[-1], value)
def get(name: str, default=None):
"""Get value from config, or return the supplied 'default' if key doesn't exist."""
try:
return _get(name)
except KeyError:
return default
def set_default(name: str, default=None):
"""Set default value for config variable."""
# If config variable is already set to None but we get a better default value, replace the existing
if default is not None:
try:
if _get(name) is None:
set_value(name, default)
except KeyError:
set_value(name, default, overwrite=False)
else:
set_value(name, default, overwrite=False)
def extend_config(new_config):
"""Extend existing config with new values for missing keys."""
_merge_dicts(config, new_config)
def update_config(new_config):
"""Update existing config with new values, replacing existing values."""
global config
config = _merge_dicts(copy.deepcopy(new_config), config)
def _merge_dicts(user, default):
"""Merge corpus config with default config, letting user values override default values."""
if isinstance(user, dict) and isinstance(default, dict):
for k, v in default.items():
if k not in user:
user[k] = v
else:
user[k] = _merge_dicts(user[k], v)
return user
def add_to_structure(name, default=None, description=None, annotator: Optional[str] = None):
"""Add config variable to config structure."""
set_value(name,
{"_default": default,
"_description": description,
"_source": "module"},
config_dict=config_structure
)
if annotator:
add_config_usage(name, annotator)
def get_config_description(name):
"""Get description for config key."""
return _get(name, config_structure).get("_description")
def add_config_usage(config_key, annotator):
"""Add an annotator to the list of annotators that are using a given config key."""
config_usage[config_key].add(annotator)
def validate_module_config():
"""Make sure that modules don't try to access undeclared config keys."""
for config_key in config_usage:
try:
_get(config_key, config_structure)
except KeyError:
annotators = config_usage[config_key]
raise util.SparvErrorMessage(
"The annotator{} {} {} trying to access the config key '{}' which isn't declared anywhere.".format(
"s" if len(annotators) > 1 else "", ", ".join(annotators),
"are" if len(annotators) > 1 else "is", config_key), "sparv", "config")
def validate_config(config_dict=None, structure=None, parent=""):
"""Make sure the corpus config doesn't contain invalid keys."""
config_dict = config_dict or config
structure = structure or config_structure
for key in config_dict:
path = (parent + "." + key) if parent else key
if key not in structure:
if not parent:
raise util.SparvErrorMessage(f"Unknown key in config file: '{path}'. No module with that name found.",
module="sparv", function="config")
else:
module_name = parent.split(".", 1)[0]
raise util.SparvErrorMessage(f"Unknown key in config file: '{path}'. The module '{module_name}' "
f"doesn't have an option with that name.",
module="sparv", function="config")
elif not structure[key].get("_source"):
validate_config(config_dict[key], structure[key], path)
def load_presets(lang):
"""Read presets files, set global presets variable and return dictionary with preset classes."""
global presets
class_dict = {}
for f in PRESETS_DIR.rglob("*.yaml"):
presets_yaml = read_yaml(f)
# Skip preset if it is not valid for lang
if lang:
languages = presets_yaml.get("languages", [])
if languages and lang not in languages:
continue
# Make sure preset names are upper case
p_name = f.stem.upper()
c = presets_yaml.get("classes", {})
p = presets_yaml.get("presets", {})
for key, value in p.items():
if isinstance(value, list):
# Prefix all preset keys with preset name
for i, v in enumerate(value):
if v in p:
value[i] = f"{p_name}.{v}"
# Extend presets and class_dict
k_name = f"{p_name}.{key}"
presets[k_name] = value
if c:
class_dict[k_name] = c
return class_dict
def resolve_presets(annotations):
"""Resolve annotation presets into actual annotations."""
result = []
for annotation in annotations:
if annotation in presets:
result.extend(resolve_presets(presets[annotation]))
else:
result.append(annotation)
return result
def apply_presets():
"""Resolve annotations from presets and set preset classes."""
# Load annotation presets and classes
class_dict = load_presets(get("metadata.language"))
preset_classes = {} # Classes set by presets
# Go through annotation lists in config to find references to presets
for a in registry.annotation_sources:
annotations = get(a)
if not annotations:
continue
# Update classes set by presets
for annotation in annotations:
preset_classes.update(class_dict.get(annotation, {}))
# Resolve presets and update annotation list in config
set_value(a, resolve_presets(annotations))
# Update classes
default_classes = _config_default.get("classes", {})
user_classes = _config_user.get("classes", {}).copy()
combined_classes = _merge_dicts(preset_classes, default_classes)
classes = _merge_dicts(user_classes, combined_classes)
config["classes"] = classes
def handle_document_annotation():
"""Copy document annotation to text class."""
doc_elem = get("import.document_annotation")
# Make sure that if both classes.text and import.document_annotation are set, that they have the same value
if get("classes.text") and doc_elem and get("classes.text") != doc_elem:
raise util.SparvErrorMessage(
"The config keys 'classes.text' and 'import.document_annotation' can't have different values.",
"sparv", "config")
# If import.document_annotation is set, copy value to classes.text
if doc_elem:
set_default("classes.text", doc_elem)
def inherit_config(source: str, target: str) -> None:
"""Let 'target' inherit config values from 'source' for evey key that is supported and not already populated.
Only keys which are either missing or with a value of None in the target will inherit the source's value, meaning
that falsy values like empty strings or lists will not be overwritten.
Args:
source: Module name of source.
target: Module name of target.
"""
for key in config.get(source, []):
if key in config_structure.get(target, []):
value = None
try:
value = _get(f"{target}.{key}")
except KeyError:
pass
if value is None:
set_value(f"{target}.{key}", config[source][key])
| 33,359
|
https://github.com/problem-frames/openpf/blob/master/decreasoner.macosx/software/relsat-dist/gmp-3.1/mpz/kronsz.c
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
openpf
|
problem-frames
|
C
|
Code
| 519
| 1,408
|
/* mpz_si_kronecker -- Kronecker/Jacobi symbol. */
/*
Copyright (C) 1999, 2000 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
The GNU MP Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the GNU MP Library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
*/
#include "gmp.h"
#include "gmp-impl.h"
#include "longlong.h"
int
#if __STDC__
mpz_si_kronecker (long a, mpz_srcptr b)
#else
mpz_si_kronecker (a, b)
long a;
mpz_srcptr b;
#endif
{
int b_abs_size;
mp_srcptr b_ptr;
mp_limb_t b_low;
int twos;
int result_bit1;
b_abs_size = ABSIZ (b);
if (b_abs_size == 0)
return JACOBI_S0 (a); /* (a/0) */
b_ptr = PTR(b);
b_low = b_ptr[0];
/* (0/b) = 1 if b=+/-1, 0 otherwise */
if (a == 0)
return (b_abs_size == 1) & (b_low == 1);
/* account for the effect of the sign of b, so can then ignore it */
result_bit1 = JACOBI_BSGN_SZ_BIT1 (a, b);
if ((b_low & 1) == 0)
{
/* b even */
if ((a & 1) == 0)
return 0; /* (a/b)=0 if both a,b even */
/* Require MP_BITS_PER_LIMB even, so that (a/2)^MP_BITS_PER_LIMB = 1,
and so that therefore there's no need to account for how many zero
limbs are stripped. */
ASSERT ((BITS_PER_MP_LIMB & 1) == 0);
MPN_STRIP_LOW_ZEROS_NOT_ZERO (b_ptr, b_abs_size);
b_low = b_ptr[0];
if ((b_low & 1) == 0)
{
/* odd a, even b */
mp_limb_t b_shl_bit1;
count_trailing_zeros (twos, b_low);
/* b_shl_bit1 is b>>twos, but with only bit 1 guaranteed */
if (twos == BITS_PER_MP_LIMB-1)
b_shl_bit1 = (b_abs_size == 1) ? 0 : (b_ptr[1] << 1);
else
b_shl_bit1 = (b_low >> twos);
result_bit1 ^= JACOBI_ASGN_SU_BIT1 (a, b_shl_bit1);
a = ABS(a);
if (a == 1)
return JACOBI_BIT1_TO_PN (result_bit1); /* (1/b)=1 */
/* twos (a/2), reciprocity to (b/a), and (b/a) = (b mod a / b) */
return mpn_jacobi_base (mpn_mod_1_rshift (b_ptr, b_abs_size,
twos, a),
a,
result_bit1
^ JACOBI_TWOS_U_BIT1 (twos, a)
^ JACOBI_RECIP_UU_BIT1 (a, b_shl_bit1));
}
}
/* b odd */
result_bit1 ^= JACOBI_ASGN_SU_BIT1 (a, b_low);
a = ABS(a);
/* (a/1) = 1 for any a */
if (b_abs_size == 1 && b_low == 1)
return JACOBI_BIT1_TO_PN (result_bit1);
/* Note a is cast to unsigned because 0x80..00 doesn't fit in a signed. */
if ((a & 1) == 0)
{
count_trailing_zeros (twos, a);
a = ((unsigned long) a) >> twos;
result_bit1 ^= JACOBI_TWOS_U_BIT1 (twos, b_low);
}
if (a == 1)
return JACOBI_BIT1_TO_PN (result_bit1); /* (1/b)=1 */
/* reciprocity to (b/a), and (b/a) == (b mod a / a) */
return mpn_jacobi_base (mpn_mod_1 (b_ptr, b_abs_size, a), a,
result_bit1 ^ JACOBI_RECIP_UU_BIT1 (a, b_low));
}
| 48,660
|
https://github.com/switer/Zect/blob/master/lib/execute.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Zect
|
switer
|
JavaScript
|
Code
| 178
| 491
|
/**
* execute expression from template with specified Scope and ViewModel
*/
var util = require('./util')
var __$compile__ = require('./compile')
var __$compiledExprs___ = {}
/**
* Calc expression value
*/
function _execute($vm, $scope/*, expression, [label], [target]*/) {
/**
* $scope is passed when call instance method $compile,
* Each "scope" object maybe include "$parent, data, methods" properties
*/
// var $parent = $scope && $scope.$parent ? util.extend({}, $scope.$parent.methods, $scope.$parent.data) : {}
if ($scope && $scope.$parent) {
$scope.data.$parent = $scope.$parent.data
}
var __$expression__ = arguments[2]
var __$fn__ = __$compiledExprs___[__$expression__]
$scope = $scope || {}
$scope = util.extend({}, $vm.$methods, $vm.$data, $scope.methods, $scope.data)
try {
if (!__$fn__) {
__$fn__ = __$compiledExprs___[__$expression__] = __$compile__(__$expression__)
}
return util.immutable(__$fn__($scope))
} catch (e) {
__$expression__ = /^\{/.test(__$expression__)
? '. ' + __$expression__
: '. {' + __$expression__ + '}' // expr
// arguments[3] // label
// arguments[4] // target
switch (e.name) {
case 'ReferenceError':
console.warn(e.message + __$expression__)
break
default:
console.error(
(arguments[3] ? '\'' + arguments[3] + '\': ' : ''),
e.message + __$expression__,
arguments[4] || ''
)
}
return ''
}
}
module.exports = _execute
| 41,754
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.