text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* Copyright (C) 2016 Yusuke Suzuki <[email protected]>
* Copyright (C) 2016-2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
#include "config.h"
#include "BytecodeRewriter.h"
#include "HeapInlines.h"
#include "PreciseJumpTargetsInlines.h"
#include <wtf/BubbleSort.h>
// billming
#include "JSCJSValueInlines.h"
namespace JSC {
void BytecodeRewriter::applyModification()
{
for (size_t insertionIndex = m_insertions.size(); insertionIndex--;) {
Insertion& insertion = m_insertions[insertionIndex];
if (insertion.type == Insertion::Type::Remove)
m_writer.m_instructions.remove(insertion.index.bytecodeOffset, insertion.length());
else {
if (insertion.includeBranch == IncludeBranch::Yes) {
int finalOffset = insertion.index.bytecodeOffset + calculateDifference(m_insertions.begin(), m_insertions.begin() + insertionIndex);
adjustJumpTargetsInFragment(finalOffset, insertion);
}
m_writer.m_instructions.insertVector(insertion.index.bytecodeOffset, insertion.instructions.m_instructions);
}
}
m_insertions.clear();
}
void BytecodeRewriter::execute()
{
WTF::bubbleSort(m_insertions.begin(), m_insertions.end(), [] (const Insertion& lhs, const Insertion& rhs) {
return lhs.index < rhs.index;
});
m_codeBlock->applyModification(*this, m_writer);
}
void BytecodeRewriter::adjustJumpTargetsInFragment(unsigned finalOffset, Insertion& insertion)
{
for (auto& instruction : insertion.instructions) {
if (isBranch(instruction->opcodeID())) {
unsigned bytecodeOffset = finalOffset + instruction.offset();
updateStoredJumpTargetsForInstruction(m_codeBlock, finalOffset, instruction, [&](int32_t label) {
int absoluteOffset = adjustAbsoluteOffset(label);
return absoluteOffset - static_cast<int>(bytecodeOffset);
});
}
}
}
void BytecodeRewriter::insertImpl(InsertionPoint insertionPoint, IncludeBranch includeBranch, InstructionStreamWriter&& writer)
{
ASSERT(insertionPoint.position == Position::Before || insertionPoint.position == Position::After);
m_insertions.append(Insertion {
insertionPoint,
Insertion::Type::Insert,
includeBranch,
0,
WTFMove(writer)
});
}
int32_t BytecodeRewriter::adjustJumpTarget(InsertionPoint startPoint, InsertionPoint jumpTargetPoint)
{
if (startPoint < jumpTargetPoint) {
int jumpTarget = jumpTargetPoint.bytecodeOffset;
auto start = std::lower_bound(m_insertions.begin(), m_insertions.end(), startPoint, [&] (const Insertion& insertion, InsertionPoint startPoint) {
return insertion.index < startPoint;
});
if (start != m_insertions.end()) {
auto end = std::lower_bound(m_insertions.begin(), m_insertions.end(), jumpTargetPoint, [&] (const Insertion& insertion, InsertionPoint jumpTargetPoint) {
return insertion.index < jumpTargetPoint;
});
jumpTarget += calculateDifference(start, end);
}
return jumpTarget - startPoint.bytecodeOffset;
}
if (startPoint == jumpTargetPoint)
return 0;
return -adjustJumpTarget(jumpTargetPoint, startPoint);
}
// FIXME: unit test the logic in this method
// https://bugs.webkit.org/show_bug.cgi?id=190950
void BytecodeRewriter::adjustJumpTargets()
{
auto currentInsertion = m_insertions.begin();
auto outOfLineJumpTargets = m_codeBlock->replaceOutOfLineJumpTargets();
int offset = 0;
for (InstructionStream::Offset i = 0; i < m_writer.size();) {
int before = 0;
int after = 0;
int remove = 0;
while (currentInsertion != m_insertions.end() && static_cast<InstructionStream::Offset>(currentInsertion->index.bytecodeOffset) == i) {
auto size = currentInsertion->length();
if (currentInsertion->type == Insertion::Type::Remove)
remove += size;
else if (currentInsertion->index.position == Position::Before)
before += size;
else if (currentInsertion->index.position == Position::After)
after += size;
++currentInsertion;
}
offset += before;
if (!remove) {
auto instruction = m_writer.ref(i);
updateStoredJumpTargetsForInstruction(m_codeBlock, offset, instruction, [&](int32_t relativeOffset) {
return adjustJumpTarget(instruction.offset(), instruction.offset() + relativeOffset);
}, outOfLineJumpTargets);
i += instruction->size();
} else {
offset -= remove;
i += remove;
}
offset += after;
}
}
} // namespace JSC
|
{
"pile_set_name": "Github"
}
|
import { mount, Wrapper } from '@vue/test-utils';
import Vue from 'vue';
import Vuetify from 'vuetify';
import AccountBalances from '@/components/accounts/AccountBalances.vue';
import { Task, TaskMeta } from '@/model/task';
import { TaskType } from '@/model/task-type';
import store from '@/store/store';
import '../../i18n';
Vue.use(Vuetify);
describe('AccountBalances.vue', () => {
let vuetify: typeof Vuetify;
let wrapper: Wrapper<AccountBalances>;
beforeEach(() => {
vuetify = new Vuetify();
wrapper = mount(AccountBalances, {
store,
vuetify,
propsData: {
blockchain: 'ETH',
balances: [],
title: 'ETH balances'
}
});
});
afterEach(() => {
store.commit('session/reset');
});
test('table enters into loading state when balances load', async () => {
const payload: Task<TaskMeta> = {
id: 1,
type: TaskType.QUERY_BLOCKCHAIN_BALANCES,
meta: {
ignoreResult: false,
title: 'test'
}
};
store.commit('tasks/add', payload);
await wrapper.vm.$nextTick();
expect(
wrapper
.find('.account-balances__refresh')
.find('button')
.attributes('disabled')
).toBe('disabled');
expect(wrapper.find('.v-data-table__progress').exists()).toBeTruthy();
expect(wrapper.find('.v-data-table__empty-wrapper td').text()).toMatch(
'account_balances.data_table.loading'
);
store.commit('tasks/remove', 1);
await wrapper.vm.$nextTick();
expect(
wrapper
.find('.account-balances__refresh')
.find('button')
.attributes('disabled')
).toBeUndefined();
expect(wrapper.find('.v-data-table__progress').exists()).toBeFalsy();
expect(wrapper.find('.v-data-table__empty-wrapper td').text()).toMatch(
'No data available'
);
});
});
|
{
"pile_set_name": "Github"
}
|
package com.balsikandar.crashreporter.sample;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.balsikandar.crashreporter.CrashReporter;
import com.balsikandar.crashreporter.ui.CrashReporterActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Context context;
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.nullPointer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context = null;
context.getResources();
}
});
findViewById(R.id.indexOutOfBound).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<String> list = new ArrayList();
list.add("hello");
String crashMe = list.get(2);
}
});
findViewById(R.id.classCastExeption).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Object x = new Integer(0);
System.out.println((String)x);
}
});
findViewById(R.id.arrayStoreException).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Object x[] = new String[3];
x[0] = new Integer(0);
}
});
//Crashes and exceptions are also captured from other threads
new Thread(new Runnable() {
@Override
public void run() {
try {
context = null;
context.getResources();
} catch (Exception e) {
//log caught Exception
CrashReporter.logException(e);
}
}
}).start();
mContext = this;
findViewById(R.id.crashLogActivity).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CrashReporterActivity.class);
startActivity(intent);
}
});
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* allocator.cpp: custom allocator for search layers
*
* Author: Henry Daly, 2018
*
*/
/**
* Module Overview:
*
* This is a custom allocator to process allocation requests for NUMASK. It services
* index and intermediate layer node allocation requests. We deploy one instance per NUMA
* zone. The inherent latency of the OS call in numa_alloc_local (it mmaps per request)
* practically requires these. Our allocator consists of a linear allocator with three
* main alterations:
* - it can reallocate buffers, if necessary
* - allocations are made in a specific NUMA zone
* - requests are custom aligned for index and intermediate nodes to fit cache lines
*
* A basic linear allocator works as follows: upon initialization, a buffer is allocated.
* As allocations are requested, the pointer to the first free space is moved forward and
* the old value is returned.
*/
#include <stdio.h>
#include <numa.h>
#include "allocator.h"
#include "common.h"
/* Constructor */
numa_allocator::numa_allocator(unsigned ssize)
:buf_size(ssize), empty(false), num_buffers(0), buf_old(NULL),
other_buffers(NULL), last_alloc_half(false), cache_size(CACHE_LINE_SIZE)
{
buf_cur = buf_start = numa_alloc_local(buf_size);
}
/* Destructor */
numa_allocator::~numa_allocator() {
// free all the buffers
nreset();
}
/* nalloc() - service allocation request */
void* numa_allocator::nalloc(unsigned ssize) {
// get cache-line alignment for request
int alignment = (ssize <= cache_size / 2)? cache_size / 2: cache_size;
/* if the last allocation was half a cache line and we want a full cache line, we move
the free space pointer forward a half cache line so we don't spill over cache lines */
if(last_alloc_half && (alignment == cache_size)) {
buf_cur = (char*)buf_cur + (cache_size / 2);
last_alloc_half = false;
}
else if(!last_alloc_half && (alignment == cache_size / 2)) {
last_alloc_half = true;
}
// get alignment size
unsigned aligned_size = align(ssize, alignment);
// reallocate if not enough space left
if((char*)buf_cur + aligned_size > (char*)buf_start + buf_size) {
nrealloc();
}
// service allocation request
buf_old = buf_cur;
buf_cur = (char*)buf_cur + aligned_size;
return buf_old;
}
/* nfree() - "frees" space (in practice this does nothing unless the allocation was the last request) */
void numa_allocator::nfree(void *ptr, unsigned ssize) {
// get alignment size
int alignment = (ssize <= cache_size / 2)? cache_size / 2: cache_size;
unsigned aligned_size = align(ssize, alignment);
// only "free" if last allocation
if(!memcmp(ptr, buf_old, aligned_size)) {
buf_cur = buf_old;
memset(buf_cur, 0, aligned_size);
if(last_alloc_half && (alignment == cache_size / 2)) {
last_alloc_half = false;
}
}
}
/* nreset() - frees all memory buffers */
void numa_allocator::nreset(void) {
if(!empty) {
empty = true;
// free other_buffers, if used
if(other_buffers != NULL) {
int i = num_buffers - 1;
while(i >= 0) {
numa_free(other_buffers[i], buf_size);
i--;
}
free(other_buffers);
}
// free primary buffer
numa_free(buf_start, buf_size);
}
}
/* nrealloc() - allocates a new buffer */
void numa_allocator::nrealloc(void) {
// increase size of our old_buffers to store the previously allocated memory
num_buffers++;
if(other_buffers == NULL) {
assert(num_buffers == 1);
other_buffers = (void**)malloc(num_buffers * sizeof(void*));
*other_buffers = buf_start;
} else {
void** new_bufs = (void**)malloc(num_buffers * sizeof(void*));
for(int i = 0; i < num_buffers - 1; ++i) {
new_bufs[i] = other_buffers[i];
}
new_bufs[num_buffers-1] = buf_start;
free(other_buffers);
other_buffers = new_bufs;
}
// allocate new buffer & update pointers and total size
buf_cur = buf_start = numa_alloc_local(buf_size);
}
/* align() - gets the aligned size given requested size */
inline unsigned numa_allocator::align(unsigned old, unsigned alignment) {
return old + ((alignment - (old % alignment))) % alignment;
}
|
{
"pile_set_name": "Github"
}
|
<?php
use PayPal\PayPalAPI\BAUpdateRequestType;
use PayPal\PayPalAPI\BillAgreementUpdateReq;
use PayPal\Service\PayPalAPIInterfaceServiceService;
require_once('../PPBootStrap.php');
/*
* update billing agreement
*/
$BAUpdateRequest = new BAUpdateRequestType($_REQUEST['referenceID']);
$BAUpdateRequest->BillingAgreementStatus = $_REQUEST['billingAgreementStatus'];
$BAUpdateRequest->BillingAgreementDescription = $_REQUEST['billingAgreementDescription'];
$billingAgreementUpdateReq = new BillAgreementUpdateReq();
$billingAgreementUpdateReq->BAUpdateRequest = $BAUpdateRequest;
/*
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
*/
$paypalService = new PayPalAPIInterfaceServiceService(Configuration::getAcctAndConfig());
try {
/* wrap API method calls on the service object with a try catch */
$BAUpdatResponse = $paypalService->BillAgreementUpdate($billingAgreementUpdateReq);
} catch (Exception $ex) {
include_once("../Error.php");
exit;
}
if(isset($BAUpdatResponse)) {
echo "<table>";
echo "<tr><td>Ack :</td><td><div id='Ack'>$BAUpdatResponse->Ack</div> </td></tr>";
echo "</table>";
echo "<pre>";
print_r($BAUpdatResponse);
echo "</pre>";
}
require_once '../Response.php';
|
{
"pile_set_name": "Github"
}
|
package epic.features
import breeze.linalg.Counter
import breeze.util.{Encoder, Index}
import epic.framework.Feature
import scala.collection.immutable
/**
*
*
* @author dlwh
**/
class TransformedWordFeaturizer[W](initCounts: Counter[W, Double],
transform: W=>W,
unknownWordThreshold: Int = 2) extends WordFeaturizer[W] with Serializable {
private val wordCounts = {
val ctr = Counter[W, Double]()
for((w, v) <- initCounts.iterator) {
ctr(transform(w)) += v
}
ctr
}
def anchor(words: IndexedSeq[W]):WordFeatureAnchoring[W] = {
val w = words
new WordFeatureAnchoring[W] {
val indices = words.map(wordIndex)
def words = w
def featuresForWord(pos: Int): Array[Feature] = {
if (pos < 0 || pos >= words.length) {
boundaryFeatures
} else {
_minimalFeatures(pos)
}
}
private val _minimalFeatures: immutable.IndexedSeq[Array[Feature]] = words.indices.map { i =>
val index = indices(i)
if (index >= 0) {
minimalFeatures(index)
} else {
Array[Feature](Unk)
}
}
}
}
// more positional shapes to add
private val wordIndex = Index(wordCounts.keySet)
private val Unk = WordFeature("#UNK#", 'LowCount)
private val boundaryFeatures = Array[Feature](BoundaryFeature)
private val wordFeatures = Encoder.fromIndex(wordIndex).tabulateArray(s => if (wordCounts(s) > unknownWordThreshold) TransformedFeature(transform(s)) else Unk)
// caches
private val minimalFeatures = Array.tabulate[Array[Feature]](wordIndex.size){ i =>
val wc = wordCounts(transform(wordIndex.get(i)))
val w = wordFeatures(i)
if (wc > unknownWordThreshold) {
Array(w)
} else {
Array(Unk)
}
}
}
case class TransformedFeature(w: Any) extends Feature
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2012-2019 the original author or authors.
*
* 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
*
* https://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.springframework.boot.actuate.autoconfigure.env;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.actuate.env.EnvironmentEndpoint;
import org.springframework.boot.actuate.env.EnvironmentEndpointWebExtension;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* {@link EnableAutoConfiguration Auto-configuration} for the {@link EnvironmentEndpoint}.
*
* @author Phillip Webb
* @author Stephane Nicoll
* @since 2.0.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnAvailableEndpoint(endpoint = EnvironmentEndpoint.class)
@EnableConfigurationProperties(EnvironmentEndpointProperties.class)
public class EnvironmentEndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public EnvironmentEndpoint environmentEndpoint(Environment environment, EnvironmentEndpointProperties properties) {
EnvironmentEndpoint endpoint = new EnvironmentEndpoint(environment);
String[] keysToSanitize = properties.getKeysToSanitize();
if (keysToSanitize != null) {
endpoint.setKeysToSanitize(keysToSanitize);
}
return endpoint;
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(EnvironmentEndpoint.class)
public EnvironmentEndpointWebExtension environmentEndpointWebExtension(EnvironmentEndpoint environmentEndpoint) {
return new EnvironmentEndpointWebExtension(environmentEndpoint);
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_SYNC_BROWSER_SYNCED_WINDOW_DELEGATES_GETTER_H_
#define CHROME_BROWSER_UI_SYNC_BROWSER_SYNCED_WINDOW_DELEGATES_GETTER_H_
#include <set>
#include "base/macros.h"
#include "components/sessions/core/session_id.h"
#include "components/sync_sessions/synced_window_delegates_getter.h"
class Profile;
namespace browser_sync {
class SyncedWindowDelegate;
// This class defines how to access SyncedWindowDelegates on desktop.
class BrowserSyncedWindowDelegatesGetter : public SyncedWindowDelegatesGetter {
public:
explicit BrowserSyncedWindowDelegatesGetter(Profile* profile);
~BrowserSyncedWindowDelegatesGetter() override;
// SyncedWindowDelegatesGetter implementation
std::set<const SyncedWindowDelegate*> GetSyncedWindowDelegates() override;
const SyncedWindowDelegate* FindById(SessionID::id_type id) override;
private:
Profile* const profile_;
DISALLOW_COPY_AND_ASSIGN(BrowserSyncedWindowDelegatesGetter);
};
} // namespace browser_sync
#endif // CHROME_BROWSER_UI_SYNC_BROWSER_SYNCED_WINDOW_DELEGATES_GETTER_H_
|
{
"pile_set_name": "Github"
}
|
<component name="libraryTable">
<library name="Maven: net.minidev:accessors-smart:1.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/net/minidev/accessors-smart/1.2/accessors-smart-1.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/net/minidev/accessors-smart/1.2/accessors-smart-1.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/net/minidev/accessors-smart/1.2/accessors-smart-1.2-sources.jar!/" />
</SOURCES>
</library>
</component>
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using src.Models;
namespace src.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
{
"pile_set_name": "Github"
}
|
# Copyright (C) 2001-2006 Python Software Foundation
# Author: Anthony Baxter
# Contact: [email protected]
"""Class representing audio/* type MIME documents."""
__all__ = ['MIMEAudio']
import sndhdr
from cStringIO import StringIO
from email import encoders
from email.mime.nonmultipart import MIMENonMultipart
_sndhdr_MIMEmap = {'au' : 'basic',
'wav' :'x-wav',
'aiff':'x-aiff',
'aifc':'x-aiff',
}
# There are others in sndhdr that don't have MIME types. :(
# Additional ones to be added to sndhdr? midi, mp3, realaudio, wma??
def _whatsnd(data):
"""Try to identify a sound file type.
sndhdr.what() has a pretty cruddy interface, unfortunately. This is why
we re-do it here. It would be easier to reverse engineer the Unix 'file'
command and use the standard 'magic' file, as shipped with a modern Unix.
"""
hdr = data[:512]
fakefile = StringIO(hdr)
for testfn in sndhdr.tests:
res = testfn(hdr, fakefile)
if res is not None:
return _sndhdr_MIMEmap.get(res[0])
return None
class MIMEAudio(MIMENonMultipart):
"""Class for generating audio/* MIME documents."""
def __init__(self, _audiodata, _subtype=None,
_encoder=encoders.encode_base64, **_params):
"""Create an audio/* type MIME document.
_audiodata is a string containing the raw audio data. If this data
can be decoded by the standard Python `sndhdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific audio subtype via the
_subtype parameter. If _subtype is not given, and no subtype can be
guessed, a TypeError is raised.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
_subtype = _whatsnd(_audiodata)
if _subtype is None:
raise TypeError('Could not find audio MIME subtype')
MIMENonMultipart.__init__(self, 'audio', _subtype, **_params)
self.set_payload(_audiodata)
_encoder(self)
|
{
"pile_set_name": "Github"
}
|
package main
import (
"fmt"
"sync"
"time"
"gopnik"
"gopnikrpc"
"perflog"
)
type coordinator struct {
addrs []string
timeout time.Duration
connsWg sync.WaitGroup
tasks *plan
results chan perflog.PerfLogEntry
nodeQueueSize int
connStatuses map[string]bool
connStatusesMu sync.Mutex
monitors map[string]*monitor
}
type stop struct{}
func (self *stop) Error() string { return "Stop" }
func newCoordinator(addrs []string, timeout time.Duration, nodeQueueSize int, bboxes []gopnik.TileCoord) *coordinator {
self := new(coordinator)
self.addrs = addrs
self.timeout = timeout
self.results = make(chan perflog.PerfLogEntry)
self.nodeQueueSize = nodeQueueSize
self.tasks = newPlan(bboxes)
// Monitoring
self.connStatuses = make(map[string]bool)
self.monitors = make(map[string]*monitor)
for _, addr := range self.addrs {
self.monitors[addr] = newMonitor()
}
for _, addr := range self.addrs {
go self.monitorLoop(addr)
}
return self
}
func (self *coordinator) connF(addr string) error {
conn := newConnection(addr, self.timeout)
err := conn.Connect()
if err != nil {
return err
}
defer conn.Close()
for {
coord := self.tasks.GetTask()
if coord == nil {
return &stop{}
}
res, err := conn.ProcessTask(*coord)
if err != nil || res == nil {
self.tasks.FailTask(*coord)
return fmt.Errorf("%v on %v", err, coord)
}
self.tasks.DoneTask(*coord)
self.results <- *res
}
return nil
}
func (self *coordinator) monitorConnF(addr string, t time.Time) error {
conn := newConnection(addr, self.timeout)
err := conn.Connect()
if err != nil {
return err
}
defer conn.Close()
client := conn.Client()
data, err := client.Stat()
if err != nil {
self.setNodeStatus(addr, false)
return err
}
self.setNodeStatus(addr, true)
mon := self.NodeMonitor(addr)
for k, v := range data {
mon.AddPoint(k, t, v)
}
return nil
}
func (self *coordinator) connLoop(addr string) {
// Send 'done' for _current_ goroutine
defer self.connsWg.Done()
// Process tasks
for {
err := self.connF(addr)
if err != nil {
if _, ok := err.(*stop); ok {
return
}
if _, ok := err.(*gopnikrpc.QueueLimitExceeded); ok {
log.Error("%v on %v", err, addr)
time.Sleep(1 * time.Minute)
} else {
log.Error("Slave connection error: %v", err)
time.Sleep(10 * time.Second)
}
}
}
}
func (self *coordinator) monitorLoop(addr string) {
if err := self.monitorConnF(addr, time.Now()); err != nil {
log.Error("Connection [%v] error: %v", addr, err)
}
ticker := time.Tick(1 * time.Minute)
for now := range ticker {
if err := self.monitorConnF(addr, now); err != nil {
log.Error("Connection [%v] error: %v", addr, err)
}
}
}
func (self *coordinator) Start() <-chan perflog.PerfLogEntry {
for _, addr := range self.addrs {
for i := 0; i < self.nodeQueueSize; i++ {
self.connsWg.Add(1)
go self.connLoop(addr)
}
}
go self.wait()
return self.results
}
func (self *coordinator) wait() {
self.connsWg.Wait()
close(self.results)
}
func (self *coordinator) setNodeStatus(node string, status bool) {
self.connStatusesMu.Lock()
self.connStatuses[node] = status
self.connStatusesMu.Unlock()
}
func (self *coordinator) Nodes() []string {
return self.addrs
}
func (self *coordinator) NodeStatus(node string) bool {
self.connStatusesMu.Lock()
defer self.connStatusesMu.Unlock()
return self.connStatuses[node]
}
func (self *coordinator) NodeMonitor(node string) *monitor {
return self.monitors[node]
}
func (self *coordinator) DoneTasks() (done int, failed int, total int) {
done = self.tasks.DoneTasks()
failed = self.tasks.FailedTasks()
total = self.tasks.TotalTasks()
return
}
func (self *coordinator) ProgressTasksCoord() (coordInProg []gopnik.TileCoord) {
coordInProg = self.tasks.ProgressTasksCoord()
return
}
|
{
"pile_set_name": "Github"
}
|
/**
* @fileoverview JSLint XML reporter
* @author Ian Christian Myers
*/
"use strict";
const xmlEscape = require("../xml-escape");
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = function(results) {
let output = "";
output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
output += "<jslint>";
results.forEach(result => {
const messages = result.messages;
output += `<file name="${result.filePath}">`;
messages.forEach(message => {
output += [
`<issue line="${message.line}"`,
`char="${message.column}"`,
`evidence="${xmlEscape(message.source || "")}"`,
`reason="${xmlEscape(message.message || "")}${message.ruleId ? ` (${message.ruleId})` : ""}" />`
].join(" ");
});
output += "</file>";
});
output += "</jslint>";
return output;
};
|
{
"pile_set_name": "Github"
}
|
const tabs = require("sdk/tabs");
const config = require("sdk/simple-prefs");
const prefs = config.prefs;
const windows = require("sdk/windows").browserWindows;
var option = require("./option");
var Toggle = require("./button");
exports.init = function(goobserver) {
var toggle = new Toggle(prefs);
if(prefs.isRedirect) {
toggle.enable();
goobserver.register();
} else {
toggle.disable();
}
windows.on('close', function(w) {
if(prefs.isRedirect) {
goobserver.unregister();
}
});
config.on("setting", function() {
tabs.open(option.tabOptions);
});
config.on("isRedirect", function(prefName) {
if(prefs.isRedirect) {
toggle.enable();
goobserver.register();
} else {
toggle.disable();
goobserver.unregister();
}
});
}
exports.prefs = prefs;
|
{
"pile_set_name": "Github"
}
|
---
title: "Upgrading to Riak KV 2.0"
description: ""
project: "riak_kv"
project_version: "2.0.6"
menu:
riak_kv-2.0.6:
name: "Upgrading to 2.0"
identifier: "upgrading_version"
weight: 101
parent: "upgrading"
toc: true
aliases:
- /riak/2.0.6/upgrade-v20/
---
When upgrading to Riak 2.0 from an earlier version, we strongly
recommend reading each section of the following guide. This guide
explains which default Riak behaviors have changed and specific steps
to take for a successful upgrade.
For an overview of the new features and functionality
included in version 2.0, check out our guide to [Riak 2.0](/riak/kv/2.0.6/introduction).
## New Clients
To take advantage of the new features available in Riak 2.0, we
recommend upgrading your application to an official Basho client that
was built with those features in mind. There are official
2.0-compatible clients in the following languages:
* [Java](https://github.com/basho/riak-java-client)
* [Ruby](https://github.com/basho/riak-ruby-client)
* [Python](https://github.com/basho/riak-python-client)
* [Erlang](https://github.com/basho/riak-erlang-client)
While we strongly recommend using the newest versions of these clients,
older versions will still work with Riak 2.0, with the drawback that
those older clients will not able to take advantage of [new features](/riak/kv/2.0.6/introduction) like [data types](/riak/kv/2.0.6/developing/data-types) or the new [Riak Search](/riak/kv/2.0.6/using/reference/search).
## Bucket Types
In versions of Riak prior to 2.0, the location of objects was
determined by objects' [bucket](/riak/kv/2.0.6/learn/concepts/buckets) and [key](/riak/kv/2.0.6/learn/concepts/keys-and-objects), while all bucket-level configurations were managed by setting [bucket properties](/riak/kv/2.0.6/developing/usage/bucket-types/).
In Riak 2.0, [bucket types](/riak/kv/2.0.6/using/cluster-operations/bucket-types) are both an additional namespace for locating objects _and_ a new way of configuring bucket properties in a systematic fashion. More comprehensive details on usage can be found in the documentation on [using bucket types](/riak/kv/2.0.6/using/reference/bucket-types).
Here, we'll list some of the things to be aware of when upgrading.
#### Bucket types and object location
With the introduction of bucket types, the location of all Riak objects
is determined by:
* bucket type
* bucket
* key
This means there are 3 namespaces involved in object location instead of 2.
A full tutorial can be found in [Using Bucket Types](/riak/kv/2.0.6/using/reference/bucket-types).
If your application was written using a version of Riak
prior to 2.0, you should make sure that any endpoint in Riak targeting
a bucket/key pairing is changed to accommodate a bucket
type/bucket/key location.
If you're using a pre-2.0-specific client and targeting a location
specified only by bucket and key, Riak will use the default bucket
configurations. The following URLs are equivalent in Riak 2.0:
```
/buckets/<bucket>/keys/<key>
/types/default/buckets/<bucket>/keys/<key>
```
If you use object locations that don't specify a bucket type, you have
three options:
* Accept Riak's [default bucket configurations](/riak/kv/2.0.6/using/reference/bucket-types/#buckets-as-namespaces)
* Change Riak's defaults using your [configuration files](/riak/kv/2.0.6/configuring/reference/#default-bucket-properties)
* Manage multiple sets of bucket properties by specifying those
properties for all operations (not recommended)
#### Features that rely on bucket types
One reason we recommend using bucket types for Riak 2.0
and later is because many newer Riak features were built with
bucket types as a precondition:
* [Strong consistency](/riak/2.0.6/using/reference/strong-consistency) --- Using Riak's strong consistency subsystem
requires you to set the `consistent` parameter on a bucket type to
`true`
* [Riak Data Types](/riak/kv/2.0.6/developing/data-types) --- In order to use Riak Data
Types, you must [create bucket types](/riak/kv/2.0.6/developing/data-types/#setting-up-buckets-to-use-riak-data-types) specific to the
Data Type you are using
#### Bucket types and downgrades
If you decide to use bucket types, please remember that you
cannot [downgrade](/riak/kv/2.0.6/setup/downgrade) your cluster to a version of
Riak prior to 2.0 if you have both created and activated a
bucket type.
## New allow_mult Behavior
One of the biggest changes in version 2.0 regarding
application development involves Riak's default
[siblings](/riak/kv/2.0.6/learn/concepts/causal-context/#siblings) behavior.
In versions prior to 2.0, the
`allow_mult` setting was set to `false` by default for all buckets.
So Riak's default behavior was to resolve
object replica [conflicts](/riak/kv/2.0.6/developing/usage/conflict-resolution) between nodes on its
own; relieving connecting clients of the need to resolve those
conflicts.
**In 2.0, `allow_mult` is set to `true` for any bucket type that you
create and activate.**
This means that the default when [using bucket types](/riak/kv/2.0.6/using/reference/bucket-types/) is to handle [conflict resolution](/riak/kv/2.0.6/developing/usage/conflict-resolution) on the client side using
either traditional [vector clocks](/riak/kv/2.0.6/learn/concepts/causal-context/#vector-clocks) or the newer [dotted version vectors](/riak/kv/2.0.6/learn/concepts/causal-context/#dotted-version-vector).
If you wish to set `allow_mult` to `false` in version 2.0, you have two
options:
* Set your bucket type's `allow_mult` property to `false`.
* Don't use bucket types.
More information on handling siblings can be found in our documentation
on [conflict resolution](/riak/kv/2.0.6/developing/usage/conflict-resolution).
## Enabling Security
The [authentication and authorization](/riak/kv/2.0.6/using/security/basics) mechanisms included with Riak 2.0 should only be turned
on after careful testing in a non-production environment. Security
changes the way all applications interact with Riak.
## When Downgrading is No Longer an Option
If you decide to upgrade to version 2.0, you can still downgrade your
cluster to an earlier version of Riak if you wish, _unless_ you perform
one of the following actions in your cluster:
* Index data to be used in conjunction with the new [Riak Search](/riak/kv/2.0.6/using/reference/search).
* Create _and_ activate one or more [bucket types](/riak/kv/2.0.6/using/reference/bucket-types/). By extension, you will not be able to downgrade your cluster if you have used the following features, both of which rely on bucket types:
- [Strong consistency](/riak/2.0.6/using/reference/strong-consistency)
- [Riak Data Types](/riak/kv/2.0.6/developing/data-types)
If you use other new features, such as [Riak Security](/riak/kv/2.0.6/using/security/basics) or the new [configuration files](/riak/kv/2.0.6/configuring/reference/), you can still
downgrade your cluster, but you will no longer be able to use those
features after the downgrade.
## Upgrading Your Configuration System
Riak 2.0 offers a new configuration system that both simplifies
configuration syntax and uses one configuration file, `riak.conf`,
instead of the two files, `app.config` and `vm.args`, required by the
older system. Full documentation of the new system can be found in
[Configuration Files](/riak/kv/2.0.6/configuring/reference/).
If you're upgrading to Riak 2.0 from an earlier version, you have two
configuration options:
1. Manually port your configuration from the older system into the new
system.
2. Keep your configuration files from the older system, which are still
recognized in Riak 2.0.
If you choose the first option, make sure to consult the
[configuration files](/riak/kv/2.0.6/configuring/reference/) documentation, as many configuration parameters have changed names, some no longer exist, and others have been added that were not previously available.
If you choose the second option, Riak will automatically determine that
the older configuration system is being used. You should be aware,
however, that some settings must be set in an `advanced.config` file.
For a listing of those parameters, see our documentation on [advanced configuration](/riak/kv/2.0.6/configuring/reference/#advanced-configuration).
If you choose to keep the existing `app.config` files, you _must_ add the
following additional settings in the `riak_core` section:
```appconfig
{riak_core,
[{default_bucket_props,
[{allow_mult,false}, %% or the same as an existing setting
{dvv_enabled,false}]},
%% other settings
]
},
```
This is to ensure backwards compatibility with 1.4 for these bucket properties.
## Upgrading LevelDB
If you are using LevelDB and upgrading to 2.0, no special steps need to
be taken, _unless_ you wish to use your old `app.config` file for
configuration. If so, make sure that you set the
`total_leveldb_mem_percent` parameter in the `eleveldb` section of the
file to 70.
```appconfig
{eleveldb, [
%% ...
{total_leveldb_mem_percent, 70},
%% ...
]}
```
If you do not assign a value to `total_leveldb_mem_percent`, Riak will
default to a value of `15`, which can cause problems in some clusters.
## Upgrading Search
Information on upgrading Riak Search to 2.0 can be found in our
[Search upgrade guide](/riak/kv/2.0.6/setup/upgrading/search).
## Migrating from Short Names
Although undocumented, versions of Riak prior to 2.0 did not prevent the
use of the Erlang VM's `-sname` configuration parameter. As of 2.0 this
is no longer permitted. Permitted in 2.0 are `nodename` in `riak.conf`
and `-name` in `vm.args`. If you are upgrading from a previous version
of Riak to 2.0 and are using `-sname` in your `vm.args`, the below steps
are required to migrate away from `-sname`.
1. Upgrade to Riak
[1.4.12](http://docs.basho.com/riak/1.4.12/downloads/).
2. Back up the ring directory on each node, typically located in
`/var/lib/riak/ring`.
3. Stop all nodes in your cluster.
4. Run [`riak-admin reip <old_nodename> <new_nodename>`](/riak/kv/2.0.6/using/admin/riak-admin/#reip) on each node in your cluster, for each node in your
cluster. For example, in a 5 node cluster this will be run 25 total
times, 5 times on each node. The `<old_nodename>` is the current
shortname, and the `<new_nodename>` is the new fully qualified hostname.
5. Change `riak.conf` or `vm.args`, depending on which configuration
system you're using, to use the new fully qualified hostname on each
node.
6. Start each node in your cluster.
|
{
"pile_set_name": "Github"
}
|
package org.tests.cache;
import io.ebean.BaseTestCase;
import io.ebean.Ebean;
import org.junit.Test;
import org.tests.model.basic.OCachedBean;
import org.tests.model.basic.OCachedBeanChild;
import static org.junit.Assert.assertEquals;
/**
* Test class testing deleting/invalidating of cached beans
*/
public class TestCacheDelete extends BaseTestCase {
/**
* When deleting a cached entity all entities with a referenced OneToMany relation must also be invalidated!
*/
@Test
public void testCacheDeleteOneToMany() {
// arrange
OCachedBeanChild child = new OCachedBeanChild();
OCachedBeanChild child2 = new OCachedBeanChild();
OCachedBean parentBean = new OCachedBean();
parentBean.getChildren().add(child);
parentBean.getChildren().add(child2);
Ebean.save(parentBean);
// confirm there are 2 children loaded from the parent
assertEquals(2, Ebean.find(OCachedBean.class, parentBean.getId()).getChildren().size());
// ensure cache has been populated
Ebean.find(OCachedBeanChild.class, child.getId());
child2 = Ebean.find(OCachedBeanChild.class, child2.getId());
parentBean = Ebean.find(OCachedBean.class, parentBean.getId());
// act
Ebean.delete(child2);
awaitL2Cache();
OCachedBean beanFromCache = Ebean.find(OCachedBean.class, parentBean.getId());
assertEquals(1, beanFromCache.getChildren().size());
}
}
|
{
"pile_set_name": "Github"
}
|
Testing X queries
Mrv1722703051710352D
7 7 0 0 0 0 999 V2000
4.4643 2.9456 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
3.7498 2.5330 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
3.7498 1.7080 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
4.4643 1.2955 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
5.1788 1.7080 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
5.1788 2.5330 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
5.8932 2.9455 0.0000 X 0 0 0 0 0 0 0 0 0 0 0 0
1 2 1 0 0 0 0
2 3 2 0 0 0 0
3 4 1 0 0 0 0
4 5 2 0 0 0 0
5 6 1 0 0 0 0
1 6 2 0 0 0 0
6 7 1 0 0 0 0
M END
|
{
"pile_set_name": "Github"
}
|
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create Portable Globes and Maps — Google Earth Enterprise 5.3.3 documentation</title>
<link rel="stylesheet" href="../../static/bizstyle.css" type="text/css" />
<link rel="stylesheet" href="../../static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../static/documentation_options.js"></script>
<script type="text/javascript" src="../../static/jquery.js"></script>
<script type="text/javascript" src="../../static/underscore.js"></script>
<script type="text/javascript" src="../../static/doctools.js"></script>
<script type="text/javascript" src="../../static/bizstyle.js"></script>
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
<link rel="next" title="Create composite globes and maps" href="createCompositeGlobesMaps.html" />
<link rel="prev" title="Custom POI Search plug-in Python code sample" href="customPOISearchPluginSample.html" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!--[if lt IE 9]>
<script type="text/javascript" src="static/css3-mediaqueries.js"></script>
<![endif]-->
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="createCompositeGlobesMaps.html" title="Create composite globes and maps"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="customPOISearchPluginSample.html" title="Custom POI Search plug-in Python code sample"
accesskey="P">previous</a> |</li>
<li class="nav-item nav-item-0"><a href="../../index.html">Google Earth Enterprise 5.3.3 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../geeServerAdmin.html" accesskey="U">GEE Server administration</a> »</li>
</ul>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="customPOISearchPluginSample.html"
title="previous chapter">Custom POI Search plug-in Python code sample</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="createCompositeGlobesMaps.html"
title="next chapter">Create composite globes and maps</a></p>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="create-portable-globes-and-maps">
<h1>Create Portable Globes and Maps<a class="headerlink" href="#create-portable-globes-and-maps" title="Permalink to this headline">¶</a></h1>
<div class="docutils container">
<div class="content docutils container">
<p><a class="reference internal" href="../../images/googlelogo_color_260x88dp4.png"><img alt="Google logo" src="../../images/googlelogo_color_260x88dp4.png" style="width: 130px; height: 44px;" /></a></p>
<p>When you are out in the field and you need a globe or map that can
easily be stored and accessed from a desktop or laptop, you can
create a portable globe or map by creating a <em>cut</em> of one of your
databases. A portable globe or map is a single file (<code class="docutils literal notranslate"><span class="pre">.glb</span></code> or
<code class="docutils literal notranslate"><span class="pre">.glc</span></code>) that stores all the geospatial data available within
your specified area of interest—including all high-resolution
imagery, terrain, vector data, KML files, and searchable point of
interest (POI) locations. Outside the specified area of interest,
the globe or map stores only low-resolution imagery and terrain.
You specify the levels of resolution when you cut the globe or
map.</p>
<p>You can <a class="reference internal" href="#"><span class="doc">create portable globes and maps</span></a> with the
<a class="reference internal" href="settingsPage.html"><span class="doc">cutter tool</span></a> feature of the <a class="reference internal" href="signInAdminConsole.html"><span class="doc">Google Earth Enterprise (GEE) Server</span></a>,
from existing GEE portable files, or you can obtain them from third-party
vendors. Depending on your area of coverage, it can take only a
few minutes to specify and generate a globe or map and then save
it to the GEE Portable maps directory.</p>
<p class="rubric">Cut globes and maps from existing portable files</p>
<p>With GEE 5.x, you can also cut globes and maps from existing
portable files, which is convenient when you want to view a limited region
of a previously cut globe or map, especially when your portable
files are very large. This feature is often useful when you want
to combine portable files with other <code class="docutils literal notranslate"><span class="pre">.glb</span></code> or <code class="docutils literal notranslate"><span class="pre">.glc</span></code> files to
create a layered composite globe using the Assembly tool.</p>
<p>To cut a globe or map from an existing portable file, first you
must <a class="reference internal" href="publishDatabasesPortables.html#register-publish-portable-map-globe"><span class="std std-ref">register and publish</span></a> it on <a class="reference internal" href="signInAdminConsole.html"><span class="doc">GEE Server</span></a>.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p>Cutting globes and maps from existing portable files is a new
feature in GEE 5.x and is available with portable files that
have been built using GEE 5.x only.</p>
<p>If you attempt to cut a portable file that was created using
GEE 4.x, the cutting process will fail. However, you can serve
portable files created using previous versions.</p>
<p class="last">To determine which version of GEE was used to create a portable
file, the timestamp information for the file is available for
served globes or maps via
<code class="docutils literal notranslate"><span class="pre">http://localhost:9335/earth/info.txt</span></code> on a local Portable
Server, or <code class="docutils literal notranslate"><span class="pre">http://<server>/<mount_point>/earth/info.txt</span></code> on
Earth Server. In addition you can get the timestamp information
using <code class="docutils literal notranslate"><span class="pre">geglxinfo</span></code>, the GEE tool for inspecting portable
files.</p>
</div>
<p class="rubric">Inspect portable files for timestamp information</p>
<p>To help you identify which version of GEE was used to create a
portable file, you can use the portable inspection tool,
<code class="docutils literal notranslate"><span class="pre">geglxinfo</span></code>, to get the timestamp for when the portable file was
created. This information should give you a good idea of which
version of GEE was used to create the file. Extract and output the
<code class="docutils literal notranslate"><span class="pre">earth/info.txt</span></code> file, as in the following example use of the
command:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>$ geglxinfo --glx tutorial_3d.glc --extract_file earth/info.txt --output /tmp/info.txt
$ cat /tmp/info.txt
Portable Globe
Copyright 2013 Google Inc. All Rights Reserved.
2014-01-15 16:03:15 GMT
2014-01-15 08:03:15
Globe description: Simple container for tutorial glb with gray marble backdrop.
2014-01-15 08:03:15
Executing: /opt/google/bin/gecreatemetadbroot --output="/tmp/cutter/glc_20598_1389801795.111116/metadbroot" --layers="/tmp/cutter/glc_20598_1389801795.111116/earth/dbroot_layer_info.txt" --has_base_imagery
2014-01-15 08:03:15
SUCCESS
2014-01-15 08:03:15
Executing: /opt/google/bin/geportableglcpacker --layer_info="/tmp/cutter/glc_20598_1389801795.111116/earth/layer_info.txt" --output="/tmp/cutter/glc_20598_1389801795.111116/temp.glc" --make_copy
</pre></div>
</div>
<p class="rubric">Composite globes and maps</p>
<p>Portable globes and maps can also be assembled into layers to
create a composite globe or map, a single file (<code class="docutils literal notranslate"><span class="pre">.glc</span></code>) that
contains all the geospatial data for assembled layers. To assemble
a composite file, you supply a KML polygon to cut your area of
interest, then specify the layers and the order in which they display.
See <a class="reference internal" href="createCompositeGlobesMaps.html"><span class="doc">Create composite globes and maps</span></a>.</p>
<p class="rubric">Create a portable globe or map</p>
<p>Cutting a globe or map is accomplished with a simple web
interface. You import a KML, or use your mouse, to define a polygon,
which defines your “area of interest.” This polygon not only
defines the area that displays high-resolution imagery, but is
also used by Fusion to create a localized search database.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The cutting processes are CPU- and disk-intensive, as
they are retrieving all data within the specified polygon from
the Earth Enterprise Server. This can affect the overall
performance of the Server, including slowing end-user access.</p>
<p>To mitigate performance impact to end users, you may consider:</p>
<ul class="simple">
<li>Limiting the number of users with access to cutting.</li>
<li>Creating pre-cut portable globes to host as downloadable
files for portable users.</li>
<li>Operating a separate GEE Server specifically to support
on-demand cutting needs.</li>
</ul>
<p class="last">Please contact the Google Earth Enterprise Support team for
further information or questions about these procedures.</p>
</div>
<p class="rubric">Before you begin</p>
<p class="rubric">Enable the cutter</p>
<p>Before cutting a globe, you must enable the cutter from the
command line:</p>
<ul class="simple">
<li>In GEE 5.x: <code class="docutils literal notranslate"><span class="pre">gecutter</span> <span class="pre">enable</span></code></li>
<li>In earlier versions: <code class="docutils literal notranslate"><span class="pre">geserveradmin</span> <span class="pre">--enable_cutter</span></code></li>
</ul>
<p>For more information about <code class="docutils literal notranslate"><span class="pre">geserveradmin</span></code>, see the <a class="reference internal" href="../fusionAdministration/commandReference.html"><span class="doc">Command reference</span></a>.</p>
<p><strong>Note about authentication and SSL</strong>: Cutting is not currently
supported on globes or maps that require end-user authentication,
such as LDAP. One workaround is to allow unauthenticated access
from localhost on your Earth Enterprise Server. Refer to Apache
documentation to enable such a configuration. Cutting of a globe
over HTTPS is supported; however, the SSL certificate of the target
server will not be verified during cutting.</p>
<p class="rubric">The globe cutter interface</p>
<p class="rubric">To create a portable globe:</p>
<ol class="arabic">
<li><p class="first">Access the Google Earth Enterprise Server Admin console in a
browser window by going to <em>myserver.mydomainname</em>.com/admin,
replacing <em>myserver</em> and <em>mydomainname</em> with your server and
domain.</p>
</li>
<li><p class="first">Sign in with the default credentials or the username and
password assigned to you:</p>
<ul class="simple">
<li>Default username: geapacheuser</li>
<li>Default password: geeadmin</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you do not know your username and password,
contact your Google Earth Enterprise Server System
Administrator.</p>
</div>
</li>
<li><p class="first">Click <strong>Databases</strong> to display the list of databases and
portables pushed to the Server.</p>
</li>
<li><p class="first">Click the <img alt="Settings button" src="../../images/cutterSettingsButton.png" /> <strong>Settings</strong> button in the top right of the window
and select <strong>Launch Cutter</strong> from the <strong>Tools</strong> menu.</p>
<p>A new browser tab opens with the GEE Server — Cutting Tool and
the <strong>Create new offline map</strong> window appears.</p>
<p><img alt="GEE Cutter create offline map window" src="../../images/cutterTools.png" /></p>
<p class="rubric">Map or globe name</p>
</li>
<li><p class="first">Use the drop-down menu to select the database or portable you wish
to cut to create your offline map or globe.</p>
</li>
<li><p class="first">Enter a name for the offline map or globe.</p>
<p>The name defines the file name for your offline map or globe.
Offline maps are created as <code class="docutils literal notranslate"><span class="pre">.glm</span></code> files; offline globes are
created as <code class="docutils literal notranslate"><span class="pre">.glb</span></code> files. Both file types are a single-file
format for sharing Google Earth Enterprise maps and globes.
Spaces, slashes, and double dots (..) will be converted to
underscores in the saved globe name.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Building an offline map or globe will overwrite any existing
offline maps or globes with the same name. If multiple users
are cutting maps or globes, we recommend assigning unique
prefixes to each user for their globe names to ensure that
files are not accidentally overwritten.</p>
</div>
</li>
<li><p class="first">Enter a description to be associated with the offline map or
globe.</p>
<p>We recommend adding sufficient descriptive information for each
offline map or globe, so that others will know what geographic
area, or what mission, they were created for.</p>
</li>
<li><p class="first">If you are overwriting an existing cut, select <strong>Yes</strong> for <strong>Overwrite?</strong>.</p>
</li>
</ol>
<p class="rubric">Drawing the polygon</p>
<p>Once the globe or map name has been specified, you can define the
geographic region to be cut by drawing a polygon on the globe.
There are two ways to draw the polygon.</p>
<p class="rubric">Hand drawing the polygon</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">When cutting a 3D globe this method is only available if you
are running the discontinued Google Earth Plug-in in your
browser. This method works for cutting 2D maps from your
browser.</p>
</div>
<ol class="arabic">
<li><p class="first">By default, you draw a polygon by hand so the <strong>Select Region</strong>
drop-down list is set to <strong>Manual</strong>.</p>
</li>
<li><p class="first">Use the <img alt="Pan tool" src="../../images/cutterHandTool2.png" /> <strong>Hand</strong> tool to pan, then, using the navigation
controls in the plug-in, zoom in to the region of interest.</p>
</li>
<li><p class="first">To use your mouse to define the polygon, click the <img alt="Polygon icon" src="../../images/cutterPolygonTool.png" /> polygon icon
in the globe window.</p>
</li>
<li><p class="first">Click on the map or globe to define each point. You can use the
navigation controls on the right to move the globe or change
zoom levels while drawing.</p>
</li>
<li><p class="first">Click the final point at the point of origin to complete the polygon selection.</p>
<p><img alt="Polygon example" src="../../images/cutterPolygonExample.png" /></p>
</li>
<li><p class="first">If you need to redraw the polygon, click <strong>Clear</strong> to delete the polygon you just created.</p>
</li>
</ol>
<p class="rubric">Defining the polygon with KML</p>
<p>You can also use KML to define the polygon(s). The KML should be
complete, and may contain single or multiple elements.</p>
<p><strong>To insert your KML:</strong></p>
<ol class="arabic">
<li><p class="first">From the <strong>Select Region</strong> drop-down list, select <strong>Paste
KML</strong>. The Paste KML window appears.</p>
</li>
<li><p class="first">Paste your KML into the text field, then click <strong>Use KML</strong>.</p>
<p>GEE Server validates the KML and then draws the polygon using
the KML data you provided. Your polygon appears on the map or
globe (the latter only if you have the discontinued Google
Earth plug-in running in your browser).</p>
</li>
</ol>
<p class="rubric">Globe resolution</p>
<p>The polygon you specified in the previous step defines your <em>area of
interest</em>. This area contains high-resolution imagery and data,
and search tabs are created for vector data within this zone. The
maximum and minimum resolutions are specified as integers between
1 and 24. These correspond to the zoom levels that are used in the
Fusion server. Setting a resolution of 24 results in a cut of the
entire globe.</p>
<div class="warning docutils container">
<strong>Caution:</strong> Setting a resolution of 24 to cut an entire globe
may result in a very large file.</div>
<p class="rubric" id="world-level-resolution">World level resolution</p>
<p>The area outside of the defined polygon is included in the globe
at a lower resolution, which you set using <strong>World level</strong>. Areas
near the polygon may be included at a higher resolution.</p>
<ul class="simple">
<li>To set the world level resolution, select a value from the
<strong>World level</strong> drop-down list.</li>
</ul>
<p>A minimum zoom level of 5-7 presents a decent-looking world to the
user and is most likely to include vector layers such as
international boundaries and state boundaries and main cities
without affecting the size of the <code class="docutils literal notranslate"><span class="pre">.glb</span></code> file very much. For
example:</p>
<ul class="simple">
<li>A cut globe with minimum and maximum resolution values set to 5
is 10 MB.</li>
<li>A cut globe with minimum and maximum resolution values set to 6
is 41 MB.</li>
<li>A cut globe with minimum and maximum resolution values set to 7
is 120 MB.</li>
</ul>
<p>These numbers are small in comparison to the overall size of your
globe when a suitable maximum resolution has been selected. For
example, a globe that contains all of the city of Atlanta, GA, USA
in 1-foot resolution requires approximately 5 GB of storage. Even
level 7 imagery, at 120 MB, is a small percentage of the overall
globe size. You can also leave this field blank to use the highest
available imagery.</p>
<p class="rubric">Region level resolution</p>
<p>The zoom level for the polygon area is set using <strong>Region level</strong>.</p>
<p>The maximum resolution of the cut polygon area is no higher than
the maximum resolution of the source map or globe. For example, if
the maximum resolution in the cutter is specified at 24, but the
source imagery is at 18 (approximately 1-meter resolution), the
cut map or globe will contain level 18 imagery. You can leave this
field blank to use the highest available imagery.</p>
<p>You may enter a lower number to reduce the size of your map or
globe by not including the highest resolution imagery.</p>
<p class="rubric">Advanced Settings</p>
<p class="rubric">Polygon Resolution</p>
<p>The <strong>Advanced</strong> option provides an additional globe-cutting
option, namely <em>Polygon Resolution</em>. This setting is useful when
cutting with large polygons. For example, you may use 12 for a
country-sized polygon or 18 for a city-sized polygon.</p>
<p class="rubric">To set the polygon resolution:</p>
<ul class="simple">
<li>Click <strong>Advanced</strong> to display the <strong>Polygon Resolution</strong> option.</li>
<li>Click the drop-down list to set the resolution value you want.</li>
</ul>
<p class="rubric">Continue Past Empty Levels</p>
<p>This option only applies to portable maps (2D databases). If a
portable map does not contain imagery in the polygon at the
resolution that you think it should, try recreating the portable
map with this option set to <strong>Yes</strong>. This option will likely increase
the build time, possibly significantly.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Additional advanced settings may be offered in future
versions. Use caution when changing them as they may
dramatically increase build times and globe sizes.</p>
</div>
<p class="rubric">Building the map or globe</p>
<p>Depending on the size of your polygon, building a cut map or
globe can take a few minutes to a few hours; likewise, file
size varies widely depending on the area selected and the desired
resolution.</p>
<p class="rubric">To build the map or globe:</p>
<ul>
<li><p class="first">Click <strong>Cut map</strong> to start the build process.</p>
<p>The progress of the build appears in the <strong>Build</strong> window.</p>
<p>When the build is finished, a <code class="docutils literal notranslate"><span class="pre">.glb</span></code> file is created in the
default globes directory,
<code class="docutils literal notranslate"><span class="pre">/opt/google/gehttpd/htdocs/cutter/globes</span></code>, and a download
link appears to the file’s location on GEE Server.</p>
</li>
</ul>
<p class="rubric">KML files</p>
<p>When a portable globe is cut from a source containing KML links
in the Layer panel:</p>
<ul class="simple">
<li>KML files that are stored locally on the primary Earth
Server will be bundled into the portable globe. Only the
main KML file will be copied, not any links or files that
are embedded as links in the main KML file. The default copy
is not recursive.</li>
<li>KML links that refer to servers other than the primary Earth
Server are not copied. The layer will be visible in the
client, but clicking the link will not cause any data to be
displayed. If access to external servers is needed, a small
KML file should be stored locally on the primary Earth
Server. This KML file should contain a link to the intended
external server.</li>
</ul>
<p class="rubric">Historical Imagery</p>
<p>Historical Imagery is not supported in the portable globe as of
Fusion 4.2.</p>
<p>There are, however, two situations in which historic imagery
will be displayed:</p>
<ul class="simple">
<li>When the computer running the portable globe has a
connection to the Earth server from which the globe was cut.
In this case, historic imagery can be streamed from the
Earth server. Once in the field, however, and disconnected
from the Earth server, no historic imagery will be
displayed.</li>
<li>If historic imagery has been cached on the portable globe
machine.</li>
</ul>
<p>Otherwise, the following error message will appear:</p>
<blockquote>
<div><strong>Google Earth can’t contact the imagery server to download
new images.</strong>
You will be able to see areas that you have been to recently,
but new image areas may appear blurry.</div></blockquote>
<p class="rubric">Learn more</p>
<ul class="simple">
<li><a class="reference internal" href="../portable/portableUserGuideWinLinux.html#serve-globe-map-gee-portable"><span class="std std-ref">Serve a globe or map from GEE Portable</span></a></li>
<li><a class="reference internal" href="../portable/portableUserGuideWinLinux.html#connect-gee-portable"><span class="std std-ref">Connect with GEE Portable</span></a> for
different ways you can connect to GEE Portable to view your
offline maps and globes.</li>
<li><a class="reference internal" href="../portable/portableDeveloperGuide.html"><span class="doc">Portable Developer Guide</span></a> for ways
to customize or extend GEE Portable, or create applications
that work with it.</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="createCompositeGlobesMaps.html" title="Create composite globes and maps"
>next</a> |</li>
<li class="right" >
<a href="customPOISearchPluginSample.html" title="Custom POI Search plug-in Python code sample"
>previous</a> |</li>
<li class="nav-item nav-item-0"><a href="../../index.html">Google Earth Enterprise 5.3.3 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../geeServerAdmin.html" >GEE Server administration</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright 2019, Open GEE Contributors.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.5.
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
var error = require('@prairielearn/prairielib/error');
module.exports = function(req, res, next) {
if (!res.locals.is_administrator) {
return next(error.make(403, 'Requires administrator privileges', {locals: res.locals}));
}
next();
};
|
{
"pile_set_name": "Github"
}
|
(function () {
var Testem = window.Testem
var regex = /^((?:not )?ok) (\d+) (.+)$/
Testem.useCustomAdapter(tapAdapter)
function tapAdapter(socket){
var results = {
failed: 0
, passed: 0
, total: 0
, tests: []
}
socket.emit('tests-start')
Testem.handleConsoleMessage = function(msg){
var m = msg.match(regex)
if (m) {
var passed = m[1] === 'ok'
var test = {
passed: passed ? 1 : 0,
failed: passed ? 0 : 1,
total: 1,
id: m[2],
name: m[3],
items: []
}
if (passed) {
results.passed++
} else {
console.error("failure", m)
results.failed++
}
results.total++
// console.log("emitted test", test)
socket.emit('test-result', test)
results.tests.push(test)
} else if (msg === '# ok' || msg.match(/^# tests \d+/)){
// console.log("emitted all test")
socket.emit('all-test-results', results)
}
// return false if you want to prevent the console message from
// going to the console
// return false
}
}
}())
|
{
"pile_set_name": "Github"
}
|
/* Block out what is behind the fixed column's header and footer */
table.DTFC_Cloned thead,
table.DTFC_Cloned tfoot {
background-color: white;
}
/* Block out the gap above the scrollbar on the right, when there is a fixed
* right column
*/
div.DTFC_Blocker {
background-color: white;
}
div.DTFC_LeftWrapper table.dataTable,
div.DTFC_RightWrapper table.dataTable {
margin-bottom: 0;
z-index: 2;
}
div.DTFC_LeftWrapper table.dataTable.no-footer,
div.DTFC_RightWrapper table.dataTable.no-footer {
border-bottom: none;
}
|
{
"pile_set_name": "Github"
}
|
#include "om.hpp"
#include "om/code_point.hpp"
#include "om/copyable.hpp"
#include "om/default_copyable.hpp"
#include "om/default_giveable.hpp"
#include "om/default_moveable.hpp"
#include "om/giveable.hpp"
#include "om/language.hpp"
#include "om/list.hpp"
#include "om/macro.hpp"
#include "om/moveable.hpp"
#include "om/owner.hpp"
#include "om/shareable.hpp"
#include "om/sink.hpp"
#include "om/source.hpp"
#include "om/taker.hpp"
#include "om/utf8.hpp"
#include "om/language/atom.hpp"
#include "om/language/consumer.hpp"
#include "om/language/default_atom.hpp"
#include "om/language/default_consumer.hpp"
#include "om/language/default_element.hpp"
#include "om/language/default_program.hpp"
#include "om/language/element.hpp"
#include "om/language/environment.hpp"
#include "om/language/evaluation.hpp"
#include "om/language/evaluator.hpp"
#include "om/language/expression.hpp"
#include "om/language/form.hpp"
#include "om/language/lexicon.hpp"
#include "om/language/literal.hpp"
#include "om/language/null.hpp"
#include "om/language/operand.hpp"
#include "om/language/operation.hpp"
#include "om/language/operator.hpp"
#include "om/language/pair.hpp"
#include "om/language/producer.hpp"
#include "om/language/program.hpp"
#include "om/language/reader.hpp"
#include "om/language/separator.hpp"
#include "om/language/symbol.hpp"
#include "om/language/system.hpp"
#include "om/language/translator.hpp"
#include "om/language/writer.hpp"
#include "om/language/operation/back_pull_character_operation.hpp"
#include "om/language/operation/back_pull_code_point_operation.hpp"
#include "om/language/operation/back_pull_element_operation.hpp"
#include "om/language/operation/back_pull_form_operation.hpp"
#include "om/language/operation/back_pull_operand_operation.hpp"
#include "om/language/operation/back_pull_operator_operation.hpp"
#include "om/language/operation/back_pull_pair_operation.hpp"
#include "om/language/operation/back_pull_separator_operation.hpp"
#include "om/language/operation/back_pull_term_operation.hpp"
#include "om/language/operation/choose_operation.hpp"
#include "om/language/operation/copy_operation.hpp"
#include "om/language/operation/decode_operation.hpp"
#include "om/language/operation/default_incomplete_operation.hpp"
#include "om/language/operation/define_operation.hpp"
#include "om/language/operation/dequote_operation.hpp"
#include "om/language/operation/do_operation.hpp"
#include "om/language/operation/drop_operation.hpp"
#include "om/language/operation/encode_operation.hpp"
#include "om/language/operation/environment_operation.hpp"
#include "om/language/operation/equals_operation.hpp"
#include "om/language/operation/evaluate_operation.hpp"
#include "om/language/operation/expression_back_push_operation.hpp"
#include "om/language/operation/expression_front_push_operation.hpp"
#include "om/language/operation/expression_operation.hpp"
#include "om/language/operation/fill_operation.hpp"
#include "om/language/operation/find_operation.hpp"
#include "om/language/operation/front_pull_character_operation.hpp"
#include "om/language/operation/front_pull_code_point_operation.hpp"
#include "om/language/operation/front_pull_element_operation.hpp"
#include "om/language/operation/front_pull_form_operation.hpp"
#include "om/language/operation/front_pull_operand_operation.hpp"
#include "om/language/operation/front_pull_operator_operation.hpp"
#include "om/language/operation/front_pull_pair_operation.hpp"
#include "om/language/operation/front_pull_separator_operation.hpp"
#include "om/language/operation/front_pull_term_operation.hpp"
#include "om/language/operation/front_push_operation.hpp"
#include "om/language/operation/incomplete_operation.hpp"
#include "om/language/operation/inject_operation.hpp"
#include "om/language/operation/lexicon_back_push_operation.hpp"
#include "om/language/operation/lexicon_front_push_operation.hpp"
#include "om/language/operation/lexicon_operation.hpp"
#include "om/language/operation/literal_back_push_operation.hpp"
#include "om/language/operation/literal_front_push_operation.hpp"
#include "om/language/operation/normalize_operation.hpp"
#include "om/language/operation/operand_operation.hpp"
#include "om/language/operation/operator_back_push_operation.hpp"
#include "om/language/operation/operator_front_push_operation.hpp"
#include "om/language/operation/operator_operation.hpp"
#include "om/language/operation/pair_operation.hpp"
#include "om/language/operation/program_operation.hpp"
#include "om/language/operation/pull_operation.hpp"
#include "om/language/operation/quote_operation.hpp"
#include "om/language/operation/rearrange_operation.hpp"
#include "om/language/operation/separator_operation.hpp"
#include "om/language/operation/skip_operation.hpp"
#include "om/language/operation/substitute_operation.hpp"
#include "om/language/operation/swap_operation.hpp"
#include "om/language/operation/system_operation.hpp"
#include "om/language/operation/translate_operation.hpp"
#include "om/language/symbol/operand_symbol.hpp"
#include "om/language/symbol/operator_symbol.hpp"
#include "om/language/symbol/separator_symbol.hpp"
#include "om/sink/code_point_sink.hpp"
#include "om/sink/container_back_sink.hpp"
#include "om/sink/container_front_sink.hpp"
#include "om/sink/default_sink.hpp"
#include "om/sink/iterator_sink.hpp"
#include "om/sink/sink.hpp"
#include "om/sink/stream_sink.hpp"
#include "om/source/code_point_source.hpp"
#include "om/source/code_point_string_back_source.hpp"
#include "om/source/code_point_string_front_source.hpp"
#include "om/source/collection_back_source.hpp"
#include "om/source/collection_front_source.hpp"
#include "om/source/container_back_source.hpp"
#include "om/source/container_front_source.hpp"
#include "om/source/default_source.hpp"
#include "om/source/empty_source.hpp"
#include "om/source/iterator_pair_source.hpp"
#include "om/source/iterator_source.hpp"
#include "om/source/singleton_source.hpp"
#include "om/source/source.hpp"
#include "om/source/stream_source.hpp"
|
{
"pile_set_name": "Github"
}
|
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
struct job{
int a,b,d;
job(){}
bool operator < (job X)const{
if(d != X.d) return d < X.d;
return a > X.a;
}
}J[100000];
double eps = 1e-10;
int main(){
int T,n;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for(int i = 0;i < n;++i)
scanf("%d %d %d",&J[i].a,&J[i].b,&J[i].d);
sort(J,J + n);
priority_queue< pair<int, double> > Q;
pair<int, double> P;
double T = 0,ans = 0,x;
for(int i = 0;i < n;++i){
T += J[i].b;
Q.push(make_pair(J[i].a,(double)J[i].b / J[i].a));
while(T > J[i].d){
P = Q.top();
Q.pop();
if(T - P.first * P.second > J[i].d){
T -= P.first * P.second;
ans += P.second;
}else{
x = (T - J[i].d) / P.first;
T -= P.first * x;
ans += x;
Q.push(make_pair(P.first,P.second - x));
}
}
}
printf("%.2f\n",ans);
}
return 0;
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "call/rtp_demuxer.h"
#include "call/rtp_packet_sink_interface.h"
#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
#include "modules/rtp_rtcp/source/rtp_packet_received.h"
#include "rtc_base/checks.h"
#include "rtc_base/logging.h"
#include "rtc_base/strings/string_builder.h"
namespace webrtc {
namespace {
template <typename Container, typename Value>
size_t RemoveFromMultimapByValue(Container* multimap, const Value& value) {
size_t count = 0;
for (auto it = multimap->begin(); it != multimap->end();) {
if (it->second == value) {
it = multimap->erase(it);
++count;
} else {
++it;
}
}
return count;
}
template <typename Map, typename Value>
size_t RemoveFromMapByValue(Map* map, const Value& value) {
size_t count = 0;
for (auto it = map->begin(); it != map->end();) {
if (it->second == value) {
it = map->erase(it);
++count;
} else {
++it;
}
}
return count;
}
} // namespace
RtpDemuxerCriteria::RtpDemuxerCriteria() = default;
RtpDemuxerCriteria::~RtpDemuxerCriteria() = default;
std::string RtpDemuxerCriteria::ToString() const {
rtc::StringBuilder sb;
sb << "{mid: " << (mid.empty() ? "<empty>" : mid)
<< ", rsid: " << (rsid.empty() ? "<empty>" : rsid) << ", ssrcs: [";
for (auto ssrc : ssrcs) {
sb << ssrc << ", ";
}
sb << "], payload_types = [";
for (auto pt : payload_types) {
sb << pt << ", ";
}
sb << "]}";
return sb.Release();
}
// static
std::string RtpDemuxer::DescribePacket(const RtpPacketReceived& packet) {
rtc::StringBuilder sb;
sb << "PT=" << packet.PayloadType() << " SSRC=" << packet.Ssrc();
std::string mid;
if (packet.GetExtension<RtpMid>(&mid)) {
sb << " MID=" << mid;
}
std::string rsid;
if (packet.GetExtension<RtpStreamId>(&rsid)) {
sb << " RSID=" << rsid;
}
std::string rrsid;
if (packet.GetExtension<RepairedRtpStreamId>(&rrsid)) {
sb << " RRSID=" << rrsid;
}
return sb.Release();
}
RtpDemuxer::RtpDemuxer() = default;
RtpDemuxer::~RtpDemuxer() {
RTC_DCHECK(sink_by_mid_.empty());
RTC_DCHECK(sink_by_ssrc_.empty());
RTC_DCHECK(sinks_by_pt_.empty());
RTC_DCHECK(sink_by_mid_and_rsid_.empty());
RTC_DCHECK(sink_by_rsid_.empty());
}
bool RtpDemuxer::AddSink(const RtpDemuxerCriteria& criteria,
RtpPacketSinkInterface* sink) {
RTC_DCHECK(!criteria.payload_types.empty() || !criteria.ssrcs.empty() ||
!criteria.mid.empty() || !criteria.rsid.empty());
RTC_DCHECK(criteria.mid.empty() || IsLegalMidName(criteria.mid));
RTC_DCHECK(criteria.rsid.empty() || IsLegalRsidName(criteria.rsid));
RTC_DCHECK(sink);
// We return false instead of DCHECKing for logical conflicts with the new
// criteria because new sinks are created according to user-specified SDP and
// we do not want to crash due to a data validation error.
if (CriteriaWouldConflict(criteria)) {
RTC_LOG(LS_ERROR) << "Unable to add sink = " << sink
<< " due conflicting criteria " << criteria.ToString();
return false;
}
if (!criteria.mid.empty()) {
if (criteria.rsid.empty()) {
sink_by_mid_.emplace(criteria.mid, sink);
} else {
sink_by_mid_and_rsid_.emplace(std::make_pair(criteria.mid, criteria.rsid),
sink);
}
} else {
if (!criteria.rsid.empty()) {
sink_by_rsid_.emplace(criteria.rsid, sink);
}
}
for (uint32_t ssrc : criteria.ssrcs) {
sink_by_ssrc_.emplace(ssrc, sink);
}
for (uint8_t payload_type : criteria.payload_types) {
sinks_by_pt_.emplace(payload_type, sink);
}
RefreshKnownMids();
RTC_LOG(LS_INFO) << "Added sink = " << sink << " for criteria "
<< criteria.ToString();
return true;
}
bool RtpDemuxer::CriteriaWouldConflict(
const RtpDemuxerCriteria& criteria) const {
if (!criteria.mid.empty()) {
if (criteria.rsid.empty()) {
// If the MID is in the known_mids_ set, then there is already a sink
// added for this MID directly, or there is a sink already added with a
// MID, RSID pair for our MID and some RSID.
// Adding this criteria would cause one of these rules to be shadowed, so
// reject this new criteria.
if (known_mids_.find(criteria.mid) != known_mids_.end()) {
RTC_LOG(LS_INFO) << criteria.ToString()
<< " would conflict with known mid";
return true;
}
} else {
// If the exact rule already exists, then reject this duplicate.
const auto sink_by_mid_and_rsid = sink_by_mid_and_rsid_.find(
std::make_pair(criteria.mid, criteria.rsid));
if (sink_by_mid_and_rsid != sink_by_mid_and_rsid_.end()) {
RTC_LOG(LS_INFO) << criteria.ToString()
<< " would conflict with existing sink = "
<< sink_by_mid_and_rsid->second
<< " by mid+rsid binding";
return true;
}
// If there is already a sink registered for the bare MID, then this
// criteria will never receive any packets because they will just be
// directed to that MID sink, so reject this new criteria.
const auto sink_by_mid = sink_by_mid_.find(criteria.mid);
if (sink_by_mid != sink_by_mid_.end()) {
RTC_LOG(LS_INFO) << criteria.ToString()
<< " would conflict with existing sink = "
<< sink_by_mid->second << " by mid binding";
return true;
}
}
}
for (uint32_t ssrc : criteria.ssrcs) {
const auto sink_by_ssrc = sink_by_ssrc_.find(ssrc);
if (sink_by_ssrc != sink_by_ssrc_.end()) {
RTC_LOG(LS_INFO) << criteria.ToString()
<< " would conflict with existing sink = "
<< sink_by_ssrc->second << " binding by SSRC=" << ssrc;
return true;
}
}
// TODO(steveanton): May also sanity check payload types.
return false;
}
void RtpDemuxer::RefreshKnownMids() {
known_mids_.clear();
for (auto const& item : sink_by_mid_) {
const std::string& mid = item.first;
known_mids_.insert(mid);
}
for (auto const& item : sink_by_mid_and_rsid_) {
const std::string& mid = item.first.first;
known_mids_.insert(mid);
}
}
bool RtpDemuxer::AddSink(uint32_t ssrc, RtpPacketSinkInterface* sink) {
RtpDemuxerCriteria criteria;
criteria.ssrcs.insert(ssrc);
return AddSink(criteria, sink);
}
void RtpDemuxer::AddSink(const std::string& rsid,
RtpPacketSinkInterface* sink) {
RtpDemuxerCriteria criteria;
criteria.rsid = rsid;
AddSink(criteria, sink);
}
bool RtpDemuxer::RemoveSink(const RtpPacketSinkInterface* sink) {
RTC_DCHECK(sink);
size_t num_removed = RemoveFromMapByValue(&sink_by_mid_, sink) +
RemoveFromMapByValue(&sink_by_ssrc_, sink) +
RemoveFromMultimapByValue(&sinks_by_pt_, sink) +
RemoveFromMapByValue(&sink_by_mid_and_rsid_, sink) +
RemoveFromMapByValue(&sink_by_rsid_, sink);
RefreshKnownMids();
bool removed = num_removed > 0;
if (removed) {
RTC_LOG(LS_INFO) << "Removed sink = " << sink << " bindings";
}
return removed;
}
bool RtpDemuxer::OnRtpPacket(const RtpPacketReceived& packet) {
RtpPacketSinkInterface* sink = ResolveSink(packet);
if (sink != nullptr) {
sink->OnRtpPacket(packet);
return true;
}
return false;
}
RtpPacketSinkInterface* RtpDemuxer::ResolveSink(
const RtpPacketReceived& packet) {
// See the BUNDLE spec for high level reference to this algorithm:
// https://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-38#section-10.2
// RSID and RRID are routed to the same sinks. If an RSID is specified on a
// repair packet, it should be ignored and the RRID should be used.
std::string packet_mid, packet_rsid;
bool has_mid = use_mid_ && packet.GetExtension<RtpMid>(&packet_mid);
bool has_rsid = packet.GetExtension<RepairedRtpStreamId>(&packet_rsid);
if (!has_rsid) {
has_rsid = packet.GetExtension<RtpStreamId>(&packet_rsid);
}
uint32_t ssrc = packet.Ssrc();
// The BUNDLE spec says to drop any packets with unknown MIDs, even if the
// SSRC is known/latched.
if (has_mid && known_mids_.find(packet_mid) == known_mids_.end()) {
return nullptr;
}
// Cache information we learn about SSRCs and IDs. We need to do this even if
// there isn't a rule/sink yet because we might add an MID/RSID rule after
// learning an MID/RSID<->SSRC association.
std::string* mid = nullptr;
if (has_mid) {
mid_by_ssrc_[ssrc] = packet_mid;
mid = &packet_mid;
} else {
// If the packet does not include a MID header extension, check if there is
// a latched MID for the SSRC.
const auto it = mid_by_ssrc_.find(ssrc);
if (it != mid_by_ssrc_.end()) {
mid = &it->second;
}
}
std::string* rsid = nullptr;
if (has_rsid) {
rsid_by_ssrc_[ssrc] = packet_rsid;
rsid = &packet_rsid;
} else {
// If the packet does not include an RRID/RSID header extension, check if
// there is a latched RSID for the SSRC.
const auto it = rsid_by_ssrc_.find(ssrc);
if (it != rsid_by_ssrc_.end()) {
rsid = &it->second;
}
}
// If MID and/or RSID is specified, prioritize that for demuxing the packet.
// The motivation behind the BUNDLE algorithm is that we trust these are used
// deliberately by senders and are more likely to be correct than SSRC/payload
// type which are included with every packet.
// TODO(steveanton): According to the BUNDLE spec, new SSRC mappings are only
// accepted if the packet's extended sequence number is
// greater than that of the last SSRC mapping update.
// https://tools.ietf.org/html/rfc7941#section-4.2.6
if (mid != nullptr) {
RtpPacketSinkInterface* sink_by_mid = ResolveSinkByMid(*mid, ssrc);
if (sink_by_mid != nullptr) {
return sink_by_mid;
}
// RSID is scoped to a given MID if both are included.
if (rsid != nullptr) {
RtpPacketSinkInterface* sink_by_mid_rsid =
ResolveSinkByMidRsid(*mid, *rsid, ssrc);
if (sink_by_mid_rsid != nullptr) {
return sink_by_mid_rsid;
}
}
// At this point, there is at least one sink added for this MID and an RSID
// but either the packet does not have an RSID or it is for a different
// RSID. This falls outside the BUNDLE spec so drop the packet.
return nullptr;
}
// RSID can be used without MID as long as they are unique.
if (rsid != nullptr) {
RtpPacketSinkInterface* sink_by_rsid = ResolveSinkByRsid(*rsid, ssrc);
if (sink_by_rsid != nullptr) {
return sink_by_rsid;
}
}
// We trust signaled SSRC more than payload type which is likely to conflict
// between streams.
const auto ssrc_sink_it = sink_by_ssrc_.find(ssrc);
if (ssrc_sink_it != sink_by_ssrc_.end()) {
return ssrc_sink_it->second;
}
// Legacy senders will only signal payload type, support that as last resort.
return ResolveSinkByPayloadType(packet.PayloadType(), ssrc);
}
RtpPacketSinkInterface* RtpDemuxer::ResolveSinkByMid(const std::string& mid,
uint32_t ssrc) {
const auto it = sink_by_mid_.find(mid);
if (it != sink_by_mid_.end()) {
RtpPacketSinkInterface* sink = it->second;
AddSsrcSinkBinding(ssrc, sink);
return sink;
}
return nullptr;
}
RtpPacketSinkInterface* RtpDemuxer::ResolveSinkByMidRsid(
const std::string& mid,
const std::string& rsid,
uint32_t ssrc) {
const auto it = sink_by_mid_and_rsid_.find(std::make_pair(mid, rsid));
if (it != sink_by_mid_and_rsid_.end()) {
RtpPacketSinkInterface* sink = it->second;
AddSsrcSinkBinding(ssrc, sink);
return sink;
}
return nullptr;
}
RtpPacketSinkInterface* RtpDemuxer::ResolveSinkByRsid(const std::string& rsid,
uint32_t ssrc) {
const auto it = sink_by_rsid_.find(rsid);
if (it != sink_by_rsid_.end()) {
RtpPacketSinkInterface* sink = it->second;
AddSsrcSinkBinding(ssrc, sink);
return sink;
}
return nullptr;
}
RtpPacketSinkInterface* RtpDemuxer::ResolveSinkByPayloadType(
uint8_t payload_type,
uint32_t ssrc) {
const auto range = sinks_by_pt_.equal_range(payload_type);
if (range.first != range.second) {
auto it = range.first;
const auto end = range.second;
if (std::next(it) == end) {
RtpPacketSinkInterface* sink = it->second;
AddSsrcSinkBinding(ssrc, sink);
return sink;
}
}
return nullptr;
}
void RtpDemuxer::AddSsrcSinkBinding(uint32_t ssrc,
RtpPacketSinkInterface* sink) {
if (sink_by_ssrc_.size() >= kMaxSsrcBindings) {
RTC_LOG(LS_WARNING) << "New SSRC=" << ssrc
<< " sink binding ignored; limit of" << kMaxSsrcBindings
<< " bindings has been reached.";
return;
}
auto result = sink_by_ssrc_.emplace(ssrc, sink);
auto it = result.first;
bool inserted = result.second;
if (inserted) {
RTC_LOG(LS_INFO) << "Added sink = " << sink
<< " binding with SSRC=" << ssrc;
} else if (it->second != sink) {
RTC_LOG(LS_INFO) << "Updated sink = " << sink
<< " binding with SSRC=" << ssrc;
it->second = sink;
}
}
} // namespace webrtc
|
{
"pile_set_name": "Github"
}
|
package constx
// msgid
const (
MsgConnectReq = 101
MsgNodeHeartBeatResp = 1001
MsgTestStepUpdateResp = 1002
MsgWorkerHeartBeatResp = 1003
)
// mode
const (
ModeSingle = "single"
ModeMultiple = "multiple"
)
|
{
"pile_set_name": "Github"
}
|
a1ee087329ef524229a8eb3dadc33265a0d30288
|
{
"pile_set_name": "Github"
}
|
Warning: No rules/facts defined for relation D in file union_types.dl at line 18
.decl D (i:three)
------^-----------
Error: Atom's argument type is not a subtype of its declared type in file union_types.dl at line 33
G(X) :- E(X). // error
--^--------------------
The argument's declared type is one in file union_types.dl at line 20
.decl G (i:one)
-----------^----
Error: Atom's argument type is not a subtype of its declared type in file union_types.dl at line 36
E(X) :- F(X), !A(X), !B(X). // error.
-----------------^--------------------
The argument's declared type is one in file union_types.dl at line 15
.decl A (i:one)
-----------^----
Error: Atom's argument type is not a subtype of its declared type in file union_types.dl at line 36
E(X) :- F(X), !A(X), !B(X). // error.
------------------------^-------------
The argument's declared type is two in file union_types.dl at line 16
.decl B (i:two)
-----------^----
Error: Unable to deduce type for variable X in file union_types.dl at line 37
E(X) :- F(X), A(X), B(X). // error
--^--------------------------------
Error: Unable to deduce type for variable X in file union_types.dl at line 37
E(X) :- F(X), A(X), B(X). // error
----------^------------------------
Error: Unable to deduce type for variable X in file union_types.dl at line 37
E(X) :- F(X), A(X), B(X). // error
----------------^------------------
Error: Unable to deduce type for variable X in file union_types.dl at line 37
E(X) :- F(X), A(X), B(X). // error
----------------------^------------
Error: Unable to deduce type for variable X in file union_types.dl at line 39
C(X) :- D(X), !A(X). // error
--^---------------------------
Error: Unable to deduce type for variable X in file union_types.dl at line 39
C(X) :- D(X), !A(X). // error
----------^-------------------
Error: Unable to deduce type for variable X in file union_types.dl at line 39
C(X) :- D(X), !A(X). // error
-----------------^------------
10 errors generated, evaluation aborted
|
{
"pile_set_name": "Github"
}
|
""" Python Character Mapping Codec iso8859_5 generated from 'MAPPINGS/ISO8859/8859-5.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='iso8859-5',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> NULL
u'\x01' # 0x01 -> START OF HEADING
u'\x02' # 0x02 -> START OF TEXT
u'\x03' # 0x03 -> END OF TEXT
u'\x04' # 0x04 -> END OF TRANSMISSION
u'\x05' # 0x05 -> ENQUIRY
u'\x06' # 0x06 -> ACKNOWLEDGE
u'\x07' # 0x07 -> BELL
u'\x08' # 0x08 -> BACKSPACE
u'\t' # 0x09 -> HORIZONTAL TABULATION
u'\n' # 0x0A -> LINE FEED
u'\x0b' # 0x0B -> VERTICAL TABULATION
u'\x0c' # 0x0C -> FORM FEED
u'\r' # 0x0D -> CARRIAGE RETURN
u'\x0e' # 0x0E -> SHIFT OUT
u'\x0f' # 0x0F -> SHIFT IN
u'\x10' # 0x10 -> DATA LINK ESCAPE
u'\x11' # 0x11 -> DEVICE CONTROL ONE
u'\x12' # 0x12 -> DEVICE CONTROL TWO
u'\x13' # 0x13 -> DEVICE CONTROL THREE
u'\x14' # 0x14 -> DEVICE CONTROL FOUR
u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x16 -> SYNCHRONOUS IDLE
u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x1a' # 0x1A -> SUBSTITUTE
u'\x1b' # 0x1B -> ESCAPE
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> DELETE
u'\x80' # 0x80 -> <control>
u'\x81' # 0x81 -> <control>
u'\x82' # 0x82 -> <control>
u'\x83' # 0x83 -> <control>
u'\x84' # 0x84 -> <control>
u'\x85' # 0x85 -> <control>
u'\x86' # 0x86 -> <control>
u'\x87' # 0x87 -> <control>
u'\x88' # 0x88 -> <control>
u'\x89' # 0x89 -> <control>
u'\x8a' # 0x8A -> <control>
u'\x8b' # 0x8B -> <control>
u'\x8c' # 0x8C -> <control>
u'\x8d' # 0x8D -> <control>
u'\x8e' # 0x8E -> <control>
u'\x8f' # 0x8F -> <control>
u'\x90' # 0x90 -> <control>
u'\x91' # 0x91 -> <control>
u'\x92' # 0x92 -> <control>
u'\x93' # 0x93 -> <control>
u'\x94' # 0x94 -> <control>
u'\x95' # 0x95 -> <control>
u'\x96' # 0x96 -> <control>
u'\x97' # 0x97 -> <control>
u'\x98' # 0x98 -> <control>
u'\x99' # 0x99 -> <control>
u'\x9a' # 0x9A -> <control>
u'\x9b' # 0x9B -> <control>
u'\x9c' # 0x9C -> <control>
u'\x9d' # 0x9D -> <control>
u'\x9e' # 0x9E -> <control>
u'\x9f' # 0x9F -> <control>
u'\xa0' # 0xA0 -> NO-BREAK SPACE
u'\u0401' # 0xA1 -> CYRILLIC CAPITAL LETTER IO
u'\u0402' # 0xA2 -> CYRILLIC CAPITAL LETTER DJE
u'\u0403' # 0xA3 -> CYRILLIC CAPITAL LETTER GJE
u'\u0404' # 0xA4 -> CYRILLIC CAPITAL LETTER UKRAINIAN IE
u'\u0405' # 0xA5 -> CYRILLIC CAPITAL LETTER DZE
u'\u0406' # 0xA6 -> CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I
u'\u0407' # 0xA7 -> CYRILLIC CAPITAL LETTER YI
u'\u0408' # 0xA8 -> CYRILLIC CAPITAL LETTER JE
u'\u0409' # 0xA9 -> CYRILLIC CAPITAL LETTER LJE
u'\u040a' # 0xAA -> CYRILLIC CAPITAL LETTER NJE
u'\u040b' # 0xAB -> CYRILLIC CAPITAL LETTER TSHE
u'\u040c' # 0xAC -> CYRILLIC CAPITAL LETTER KJE
u'\xad' # 0xAD -> SOFT HYPHEN
u'\u040e' # 0xAE -> CYRILLIC CAPITAL LETTER SHORT U
u'\u040f' # 0xAF -> CYRILLIC CAPITAL LETTER DZHE
u'\u0410' # 0xB0 -> CYRILLIC CAPITAL LETTER A
u'\u0411' # 0xB1 -> CYRILLIC CAPITAL LETTER BE
u'\u0412' # 0xB2 -> CYRILLIC CAPITAL LETTER VE
u'\u0413' # 0xB3 -> CYRILLIC CAPITAL LETTER GHE
u'\u0414' # 0xB4 -> CYRILLIC CAPITAL LETTER DE
u'\u0415' # 0xB5 -> CYRILLIC CAPITAL LETTER IE
u'\u0416' # 0xB6 -> CYRILLIC CAPITAL LETTER ZHE
u'\u0417' # 0xB7 -> CYRILLIC CAPITAL LETTER ZE
u'\u0418' # 0xB8 -> CYRILLIC CAPITAL LETTER I
u'\u0419' # 0xB9 -> CYRILLIC CAPITAL LETTER SHORT I
u'\u041a' # 0xBA -> CYRILLIC CAPITAL LETTER KA
u'\u041b' # 0xBB -> CYRILLIC CAPITAL LETTER EL
u'\u041c' # 0xBC -> CYRILLIC CAPITAL LETTER EM
u'\u041d' # 0xBD -> CYRILLIC CAPITAL LETTER EN
u'\u041e' # 0xBE -> CYRILLIC CAPITAL LETTER O
u'\u041f' # 0xBF -> CYRILLIC CAPITAL LETTER PE
u'\u0420' # 0xC0 -> CYRILLIC CAPITAL LETTER ER
u'\u0421' # 0xC1 -> CYRILLIC CAPITAL LETTER ES
u'\u0422' # 0xC2 -> CYRILLIC CAPITAL LETTER TE
u'\u0423' # 0xC3 -> CYRILLIC CAPITAL LETTER U
u'\u0424' # 0xC4 -> CYRILLIC CAPITAL LETTER EF
u'\u0425' # 0xC5 -> CYRILLIC CAPITAL LETTER HA
u'\u0426' # 0xC6 -> CYRILLIC CAPITAL LETTER TSE
u'\u0427' # 0xC7 -> CYRILLIC CAPITAL LETTER CHE
u'\u0428' # 0xC8 -> CYRILLIC CAPITAL LETTER SHA
u'\u0429' # 0xC9 -> CYRILLIC CAPITAL LETTER SHCHA
u'\u042a' # 0xCA -> CYRILLIC CAPITAL LETTER HARD SIGN
u'\u042b' # 0xCB -> CYRILLIC CAPITAL LETTER YERU
u'\u042c' # 0xCC -> CYRILLIC CAPITAL LETTER SOFT SIGN
u'\u042d' # 0xCD -> CYRILLIC CAPITAL LETTER E
u'\u042e' # 0xCE -> CYRILLIC CAPITAL LETTER YU
u'\u042f' # 0xCF -> CYRILLIC CAPITAL LETTER YA
u'\u0430' # 0xD0 -> CYRILLIC SMALL LETTER A
u'\u0431' # 0xD1 -> CYRILLIC SMALL LETTER BE
u'\u0432' # 0xD2 -> CYRILLIC SMALL LETTER VE
u'\u0433' # 0xD3 -> CYRILLIC SMALL LETTER GHE
u'\u0434' # 0xD4 -> CYRILLIC SMALL LETTER DE
u'\u0435' # 0xD5 -> CYRILLIC SMALL LETTER IE
u'\u0436' # 0xD6 -> CYRILLIC SMALL LETTER ZHE
u'\u0437' # 0xD7 -> CYRILLIC SMALL LETTER ZE
u'\u0438' # 0xD8 -> CYRILLIC SMALL LETTER I
u'\u0439' # 0xD9 -> CYRILLIC SMALL LETTER SHORT I
u'\u043a' # 0xDA -> CYRILLIC SMALL LETTER KA
u'\u043b' # 0xDB -> CYRILLIC SMALL LETTER EL
u'\u043c' # 0xDC -> CYRILLIC SMALL LETTER EM
u'\u043d' # 0xDD -> CYRILLIC SMALL LETTER EN
u'\u043e' # 0xDE -> CYRILLIC SMALL LETTER O
u'\u043f' # 0xDF -> CYRILLIC SMALL LETTER PE
u'\u0440' # 0xE0 -> CYRILLIC SMALL LETTER ER
u'\u0441' # 0xE1 -> CYRILLIC SMALL LETTER ES
u'\u0442' # 0xE2 -> CYRILLIC SMALL LETTER TE
u'\u0443' # 0xE3 -> CYRILLIC SMALL LETTER U
u'\u0444' # 0xE4 -> CYRILLIC SMALL LETTER EF
u'\u0445' # 0xE5 -> CYRILLIC SMALL LETTER HA
u'\u0446' # 0xE6 -> CYRILLIC SMALL LETTER TSE
u'\u0447' # 0xE7 -> CYRILLIC SMALL LETTER CHE
u'\u0448' # 0xE8 -> CYRILLIC SMALL LETTER SHA
u'\u0449' # 0xE9 -> CYRILLIC SMALL LETTER SHCHA
u'\u044a' # 0xEA -> CYRILLIC SMALL LETTER HARD SIGN
u'\u044b' # 0xEB -> CYRILLIC SMALL LETTER YERU
u'\u044c' # 0xEC -> CYRILLIC SMALL LETTER SOFT SIGN
u'\u044d' # 0xED -> CYRILLIC SMALL LETTER E
u'\u044e' # 0xEE -> CYRILLIC SMALL LETTER YU
u'\u044f' # 0xEF -> CYRILLIC SMALL LETTER YA
u'\u2116' # 0xF0 -> NUMERO SIGN
u'\u0451' # 0xF1 -> CYRILLIC SMALL LETTER IO
u'\u0452' # 0xF2 -> CYRILLIC SMALL LETTER DJE
u'\u0453' # 0xF3 -> CYRILLIC SMALL LETTER GJE
u'\u0454' # 0xF4 -> CYRILLIC SMALL LETTER UKRAINIAN IE
u'\u0455' # 0xF5 -> CYRILLIC SMALL LETTER DZE
u'\u0456' # 0xF6 -> CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I
u'\u0457' # 0xF7 -> CYRILLIC SMALL LETTER YI
u'\u0458' # 0xF8 -> CYRILLIC SMALL LETTER JE
u'\u0459' # 0xF9 -> CYRILLIC SMALL LETTER LJE
u'\u045a' # 0xFA -> CYRILLIC SMALL LETTER NJE
u'\u045b' # 0xFB -> CYRILLIC SMALL LETTER TSHE
u'\u045c' # 0xFC -> CYRILLIC SMALL LETTER KJE
u'\xa7' # 0xFD -> SECTION SIGN
u'\u045e' # 0xFE -> CYRILLIC SMALL LETTER SHORT U
u'\u045f' # 0xFF -> CYRILLIC SMALL LETTER DZHE
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2012, Rasmus Andersson. All rights reserved. Use of this source
// code is governed by a MIT-style license that can be found in the LICENSE file.
// Expressions
#ifndef HUE__AST_EXPRESSION_H
#define HUE__AST_EXPRESSION_H
#include "Node.h"
#include "Type.h"
#include "Variable.h"
#include "../Logger.h"
#include "../Text.h"
#include <vector>
namespace hue { namespace ast {
class FunctionType;
class Expression;
typedef std::vector<Expression*> ExpressionList;
// Base class for all expression nodes.
class Expression : public Node {
public:
Expression(NodeTypeID t, const Type* resultType) : Node(t), resultType_(resultType) {}
Expression(NodeTypeID t = TExpression, Type::TypeID resultTypeID = Type::Unknown)
: Node(t), resultType_(new Type(resultTypeID)) {}
virtual ~Expression() {}
// Type of result from this expression
virtual const Type *resultType() const { return resultType_; }
virtual void setResultType(const Type* T) {
resultType_ = T;
}
virtual std::string toString(int level = 0) const {
std::ostringstream ss;
ss << "(?)";
return ss.str();
}
protected:
const Type* resultType_;
};
// Numeric integer literals like "3".
class IntLiteral : public Expression {
Text value_;
const uint8_t radix_;
public:
IntLiteral(Text value, uint8_t radix = 10)
: Expression(TIntLiteral, Type::Int), value_(value), radix_(radix) {}
const Text& text() const { return value_; }
const uint8_t& radix() const { return radix_; }
virtual std::string toString(int level = 0) const {
std::ostringstream ss;
ss << value_;
return ss.str();
}
};
// Numeric fractional literals like "1.2".
class FloatLiteral : public Expression {
Text value_;
public:
FloatLiteral(Text value) : Expression(TFloatLiteral, Type::Float), value_(value) {}
const Text& text() const { return value_; }
virtual std::string toString(int level = 0) const {
std::ostringstream ss;
ss << value_;
return ss.str();
}
};
// Boolean literal, namely "true" or "false"
class BoolLiteral : public Expression {
bool value_;
public:
BoolLiteral(bool value) : Expression(TBoolLiteral, Type::Bool), value_(value) {}
inline bool isTrue() const { return value_; }
virtual std::string toString(int level = 0) const {
std::ostringstream ss;
ss << (value_ ? "true" : "false");
return ss.str();
}
};
/// Assigning a value to a symbol or variable, e.g. foo = 5
class Assignment : public Expression {
public:
Assignment(Variable *var, Expression *rhs)
: Expression(TAssignment), var_(var), rhs_(rhs) {}
const Variable* variable() const { return var_; };
Expression* rhs() const { return rhs_; }
virtual const Type *resultType() const {
if (rhs_ && var_->hasUnknownType()) {
// rloge("CASE 1 ret " << rhs_->resultType()->toString()
// << " from " << rhs_->toString() << " (" << rhs_->typeName() << ")");
return rhs_->resultType();
} else {
//rloge("CASE 2 ret " << var_->type()->toString());
return var_->type();
}
}
virtual void setResultType(const Type* T) throw(std::logic_error) {
throw std::logic_error("Can not set type for compound 'Assignment' expression");
}
virtual std::string toString(int level = 0) const {
std::ostringstream ss;
//NodeToStringHeader(level, ss);
ss << "(= "
<< var_->toString(level+1)
<< " "
<< rhs_->toString(level+1)
<< ')';
return ss.str();
}
private:
Variable* var_;
Expression* rhs_;
};
}} // namespace hue::ast
#endif // HUE__AST_EXPRESSION_H
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2009-2020 Weasis Team and other contributors.
*
* This program and the accompanying materials are made available under the terms of the Eclipse
* Public License 2.0 which is available at http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.weasis.dicom.explorer.pref.node;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.NumberFormat;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.weasis.core.api.gui.util.JMVUtils;
import org.weasis.core.api.util.LocalUtil;
import org.weasis.core.util.StringUtil;
import org.weasis.dicom.explorer.Messages;
import org.weasis.dicom.explorer.pref.node.AbstractDicomNode.UsageType;
public class DicomWebNodeDialog extends JDialog {
private static final Logger LOGGER = LoggerFactory.getLogger(DicomWebNodeDialog.class);
private JLabel urlLabel;
private JTextField urlTf;
private JButton cancelButton;
private JLabel descriptionLabel;
private JTextField descriptionTf;
private JButton okButton;
private final DicomWebNode dicomNode;
private JComboBox<DicomWebNode> nodesComboBox;
private JPanel footPanel;
private JLabel lblType;
private JComboBox<DicomWebNode.WebType> comboBox;
private JButton btnHttpHeaders;
public DicomWebNodeDialog(Window parent, String title, DicomWebNode dicomNode,
JComboBox<DicomWebNode> nodeComboBox) {
super(parent, title, ModalityType.APPLICATION_MODAL);
initComponents();
this.nodesComboBox = nodeComboBox;
if(dicomNode == null){
this.dicomNode = new DicomWebNode("", (DicomWebNode.WebType) comboBox.getSelectedItem(), null, null); //$NON-NLS-1$
nodesComboBox.addItem(this.dicomNode);
nodesComboBox.setSelectedItem(this.dicomNode);
}
else {
this.dicomNode = dicomNode;
descriptionTf.setText(dicomNode.getDescription());
urlTf.setText(dicomNode.getUrl().toString());
comboBox.setSelectedItem(dicomNode.getWebType());
}
pack();
}
private void initComponents() {
final JPanel rootPane = new JPanel();
rootPane.setBorder(new EmptyBorder(10, 15, 10, 15));
this.setContentPane(rootPane);
final JPanel content = new JPanel();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
rootPane.setLayout(new BorderLayout(0, 0));
GridBagLayout gridBagLayout = new GridBagLayout();
content.setLayout(gridBagLayout);
descriptionLabel = new JLabel();
GridBagConstraints gbcDescriptionLabel = new GridBagConstraints();
gbcDescriptionLabel.insets = new Insets(0, 0, 5, 5);
gbcDescriptionLabel.gridx = 0;
gbcDescriptionLabel.gridy = 0;
content.add(descriptionLabel, gbcDescriptionLabel);
descriptionLabel.setText(Messages.getString("PrinterDialog.desc") + StringUtil.COLON); //$NON-NLS-1$
descriptionTf = new JTextField();
GridBagConstraints gbcDescriptionTf = new GridBagConstraints();
gbcDescriptionTf.anchor = GridBagConstraints.LINE_START;
gbcDescriptionTf.insets = new Insets(0, 0, 5, 0);
gbcDescriptionTf.gridx = 1;
gbcDescriptionTf.gridy = 0;
content.add(descriptionTf, gbcDescriptionTf);
descriptionTf.setColumns(20);
lblType = new JLabel(Messages.getString("DicomNodeDialog.lblType.text") + StringUtil.COLON); //$NON-NLS-1$
GridBagConstraints gbcLblType = new GridBagConstraints();
gbcLblType.anchor = GridBagConstraints.EAST;
gbcLblType.insets = new Insets(0, 0, 5, 5);
gbcLblType.gridx = 0;
gbcLblType.gridy = 1;
content.add(lblType, gbcLblType);
comboBox = new JComboBox<>(new DefaultComboBoxModel<>(DicomWebNode.WebType.values()));
GridBagConstraints gbcComboBox = new GridBagConstraints();
gbcComboBox.anchor = GridBagConstraints.LINE_START;
gbcComboBox.insets = new Insets(0, 0, 5, 0);
gbcComboBox.gridx = 1;
gbcComboBox.gridy = 1;
content.add(comboBox, gbcComboBox);
urlLabel = new JLabel();
urlLabel.setText("URL" + StringUtil.COLON); //$NON-NLS-1$
GridBagConstraints gbcAeTitleLabel = new GridBagConstraints();
gbcAeTitleLabel.anchor = GridBagConstraints.SOUTHEAST;
gbcAeTitleLabel.insets = new Insets(0, 0, 5, 5);
gbcAeTitleLabel.gridx = 0;
gbcAeTitleLabel.gridy = 2;
content.add(urlLabel, gbcAeTitleLabel);
urlTf = new JTextField();
urlTf.setColumns(30);
GridBagConstraints gbcAeTitleTf = new GridBagConstraints();
gbcAeTitleTf.anchor = GridBagConstraints.WEST;
gbcAeTitleTf.insets = new Insets(0, 0, 5, 0);
gbcAeTitleTf.gridx = 1;
gbcAeTitleTf.gridy = 2;
content.add(urlTf, gbcAeTitleTf);
NumberFormat myFormat = LocalUtil.getNumberInstance();
myFormat.setMinimumIntegerDigits(0);
myFormat.setMaximumIntegerDigits(65535);
myFormat.setMaximumFractionDigits(0);
this.getContentPane().add(content, BorderLayout.CENTER);
btnHttpHeaders = new JButton(Messages.getString("DicomWebNodeDialog.httpHeaders")); //$NON-NLS-1$
GridBagConstraints gbcBtnHttpHeaders = new GridBagConstraints();
gbcBtnHttpHeaders.anchor = GridBagConstraints.WEST;
gbcBtnHttpHeaders.insets = new Insets(2, 0, 7, 0);
gbcBtnHttpHeaders.gridx = 1;
gbcBtnHttpHeaders.gridy = 3;
content.add(btnHttpHeaders, gbcBtnHttpHeaders);
btnHttpHeaders.addActionListener(e -> manageHeader());
footPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) footPanel.getLayout();
flowLayout.setVgap(15);
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setHgap(20);
getContentPane().add(footPanel, BorderLayout.SOUTH);
okButton = new JButton();
footPanel.add(okButton);
okButton.setText(Messages.getString("PrinterDialog.ok")); //$NON-NLS-1$
okButton.addActionListener(e -> okButtonActionPerformed());
cancelButton = new JButton();
footPanel.add(cancelButton);
cancelButton.setText(Messages.getString("PrinterDialog.cancel")); //$NON-NLS-1$
cancelButton.addActionListener(e -> dispose());
}
private void manageHeader() {
HttpHeadersEditor dialog = new HttpHeadersEditor(this, dicomNode);
JMVUtils.showCenterScreen(dialog);
}
private void okButtonActionPerformed() {
String desc = descriptionTf.getText();
String url = urlTf.getText();
DicomWebNode.WebType webType = (DicomWebNode.WebType) comboBox.getSelectedItem();
if (!StringUtil.hasText(desc) || !StringUtil.hasText(url)) {
JOptionPane.showMessageDialog(this, Messages.getString("PrinterDialog.fill_message"), //$NON-NLS-1$
Messages.getString("PrinterDialog.error"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$
return;
}
URL validUrl;
try {
validUrl = new URL(url);
} catch (MalformedURLException e) {
LOGGER.warn("Non valid url", e); //$NON-NLS-1$
JOptionPane.showMessageDialog(this, "This URL is not valid", Messages.getString("PrinterDialog.error"), //$NON-NLS-1$//$NON-NLS-2$
JOptionPane.ERROR_MESSAGE);
return;
}
UsageType usageType = DicomWebNode.getUsageType(webType);
dicomNode.setDescription(desc);
dicomNode.setWebType(webType);
dicomNode.setUrl(validUrl);
dicomNode.setUsageType(usageType);
nodesComboBox.repaint();
AbstractDicomNode.saveDicomNodes(nodesComboBox, AbstractDicomNode.Type.WEB);
dispose();
}
}
|
{
"pile_set_name": "Github"
}
|
// * ———————————————————————————————————————————————————————— * //
// * Enduro Admin Security
// * ———————————————————————————————————————————————————————— * //
const admin_security = function () {}
// * vendor dependencies
const Promise = require('bluebird')
const crypto = require('crypto')
// * enduro dependencies
const logger = require(enduro.enduro_path + '/libs/logger')
const flat = require(enduro.enduro_path + '/libs/flat_db/flat')
// * ———————————————————————————————————————————————————————— * //
// * get user by username
// * @param {string} username - username of user to be returned
// * @return {object} - User as defiend in the user file
// * ———————————————————————————————————————————————————————— * //
admin_security.prototype.get_user_by_username = function (username) {
return new Promise(function (resolve, reject) {
// load up all admins
return flat.load(enduro.config.admin_secure_file)
.then((raw_userlist) => {
// if there are no users
if (!raw_userlist.users) {
return reject('no users found')
}
// find user with specified username
const selected_user = raw_userlist.users.filter((user) => {
if (user.username == username) {
return user
}
})
// resolve/reject based on if user was found
selected_user.length
? resolve(selected_user[0])
: reject('user not found')
})
})
}
// * ———————————————————————————————————————————————————————— * //
// * get all users
// * @return {list} - list of all user names
// * ———————————————————————————————————————————————————————— * //
admin_security.prototype.get_all_users = function () {
// load up the user file
return flat.load(enduro.config.admin_secure_file)
.then((raw_userlist) => {
// return empty array if no users found
if (!raw_userlist.users) {
return []
}
// return just usernames
return raw_userlist.users.map(function (user) {
return user.username
})
})
}
// * ———————————————————————————————————————————————————————— * //
// * login by password
// * @param {string} username
// * @param {string} plaintext password
// * @return {promise} - resolves if login successful and returns user
// * ———————————————————————————————————————————————————————— * //
admin_security.prototype.login_by_password = function (username, password) {
const self = this
return new Promise(function (resolve, reject) {
// if username or password is missing
if (!username || !password) {
return reject({success: false, message: 'username or password not provided'})
}
// gets user with specified username
self.get_user_by_username(username)
.then((user) => {
// hashes password
const hashed_input_password = hash(password, user.salt)
// compares hashed password with stored hash
if (hashed_input_password == user.hash) {
resolve(user)
} else {
// reject if provided password does not match the stored one
reject({success: false, message: 'wrong password'})
}
}, () => {
// reject if user does not exist
reject({success: false, message: 'wrong username'})
})
})
}
// * ———————————————————————————————————————————————————————— * //
// * add addmin
// * @param {string} username
// * @param {string} plaintext password
// * @return {promise} - resolves/rejects based on if the creation was successful
// * ———————————————————————————————————————————————————————— * //
admin_security.prototype.add_admin = function (username, password, tags) {
const self = this
return new Promise(function (resolve, reject) {
// sets username to 'root' if no username is provided
if (!username || typeof username == 'object') {
username = 'root'
}
// generate random password if no password is provided
password = password || Math.random().toString(10).substring(10)
// put empty tag if no tags are provided
tags = tags
? tags.split(',')
: []
const logincontext = {
username: username,
password: password,
tags: tags
}
self.get_user_by_username(logincontext.username)
.then(() => {
logger.err_block('User \'' + username + '\' already exists')
reject()
}, () => {
salt_and_hash(logincontext)
timestamp(logincontext)
return flat.upsert(enduro.config.admin_secure_file, {users: [logincontext]})
})
.then(() => {
// Let the user know the project was created successfully
logger.init('ENDURO - Creating admin user')
logger.log('Username:', false)
logger.tablog(username, true)
logger.log('Password:', false)
logger.tablog(password, true)
logger.end()
resolve()
})
})
}
admin_security.prototype.remove_all_users = function () {
return flat.save('.users', {})
}
// private functions
// * ———————————————————————————————————————————————————————— * //
// * hash
// * @param {string} plaintext password
// * @param {string} salt
// * @return {string} - hashed password
// * ———————————————————————————————————————————————————————— * //
function hash (password, salt) {
return require('crypto').createHash('sha256').update(password + salt, 'utf8').digest('hex')
}
// * ———————————————————————————————————————————————————————— * //
// * salt and hash
// * @param {object} logincontext
// * @return {} - nothing, just adds salt and hash to logincontext
// * ———————————————————————————————————————————————————————— * //
function salt_and_hash (logincontext) {
if (!logincontext || !logincontext.username || !logincontext.password) {
return
}
// adds salt
logincontext.salt = crypto.randomBytes(16).toString('hex')
// adds hash
logincontext.hash = hash(logincontext.password, logincontext.salt)
// deletes plain password
delete logincontext.password
}
// * ———————————————————————————————————————————————————————— * //
// * timestamp
// * @param {object} logincontext
// * @return {} - nothing, just adds timestamp to logincontext
// * ———————————————————————————————————————————————————————— * //
function timestamp (logincontext) {
logincontext.user_created_timestamp = Date.now()
return logincontext
}
module.exports = new admin_security()
|
{
"pile_set_name": "Github"
}
|
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// Assert operator for runtime checking of constraints. Assert operators have a list
// of constraints to be checked, and corresponding error messages to print in the
// event of constraint violation.
//
// For example:
// clang-format off
//
// +--CPhysicalAssert (Error code: 23514)
// |--CPhysicalAssert (Error code: 23502)
// | |--CPhysical [...]
// | +--CScalarAssertConstraintList
// | +--CScalarAssertConstraint (ErrorMsg: Not null constraint for column b of table r violated)
// | +--CScalarBoolOp (EboolopNot)
// | +--CScalarNullTest
// | +--CScalarIdent "b" (2)
// +--CScalarAssertConstraintList
// |--CScalarAssertConstraint (ErrorMsg: Check constraint r_check for table r violated)
// | +--CScalarIsDistinctFrom (=)
// | |--CScalarCmp (<)
// | | |--CScalarIdent "d" (4)
// | | +--CScalarIdent "c" (3)
// | +--CScalarConst (0)
// +--CScalarAssertConstraint (ErrorMsg: Check constraint r_c_check for table r violated)
// +--CScalarIsDistinctFrom (=)
// |--CScalarCmp (>)
// | |--CScalarIdent "c" (3)
// | +--CScalarConst (0)
// +--CScalarConst (0)
// clang-format on
#ifndef GPOPT_CPhysicalAssert_H
#define GPOPT_CPhysicalAssert_H
#include "gpos/base.h"
#include "naucrates/dxl/errorcodes.h"
#include "gpopt/operators/CPhysical.h"
namespace gpopt
{
//---------------------------------------------------------------------------
// @class:
// CPhysicalAssert
//
// @doc:
// Assert operator
//
//---------------------------------------------------------------------------
class CPhysicalAssert : public CPhysical
{
private:
// exception
CException *m_pexc;
// private copy ctor
CPhysicalAssert(const CPhysicalAssert &);
public:
// ctor
CPhysicalAssert(CMemoryPool *mp, CException *pexc);
// dtor
virtual
~CPhysicalAssert();
// ident accessors
virtual
EOperatorId Eopid() const
{
return EopPhysicalAssert;
}
// operator name
virtual
const CHAR *SzId() const
{
return "CPhysicalAssert";
}
// exception
CException *Pexc() const
{
return m_pexc;
}
// match function
virtual
BOOL Matches(COperator *pop) const;
// sensitivity to order of inputs
virtual
BOOL FInputOrderSensitive() const
{
return true;
}
//-------------------------------------------------------------------------------------
// Required Plan Properties
//-------------------------------------------------------------------------------------
// compute required output columns of the n-th child
virtual
CColRefSet *PcrsRequired
(
CMemoryPool *mp,
CExpressionHandle &exprhdl,
CColRefSet *pcrsRequired,
ULONG child_index,
CDrvdPropArray *pdrgpdpCtxt,
ULONG ulOptReq
);
// compute required ctes of the n-th child
virtual
CCTEReq *PcteRequired
(
CMemoryPool *mp,
CExpressionHandle &exprhdl,
CCTEReq *pcter,
ULONG child_index,
CDrvdPropArray *pdrgpdpCtxt,
ULONG ulOptReq
)
const;
// compute required sort order of the n-th child
virtual
COrderSpec *PosRequired
(
CMemoryPool *mp,
CExpressionHandle &exprhdl,
COrderSpec *posRequired,
ULONG child_index,
CDrvdPropArray *pdrgpdpCtxt,
ULONG ulOptReq
)
const;
// compute required distribution of the n-th child
virtual
CDistributionSpec *PdsRequired
(
CMemoryPool *mp,
CExpressionHandle &exprhdl,
CDistributionSpec *pdsRequired,
ULONG child_index,
CDrvdPropArray *pdrgpdpCtxt,
ULONG ulOptReq
)
const;
// compute required rewindability of the n-th child
virtual
CRewindabilitySpec *PrsRequired
(
CMemoryPool *mp,
CExpressionHandle &exprhdl,
CRewindabilitySpec *prsRequired,
ULONG child_index,
CDrvdPropArray *pdrgpdpCtxt,
ULONG ulOptReq
)
const;
// compute required partition propagation of the n-th child
virtual
CPartitionPropagationSpec *PppsRequired
(
CMemoryPool *mp,
CExpressionHandle &exprhdl,
CPartitionPropagationSpec *pppsRequired,
ULONG child_index,
CDrvdPropArray *pdrgpdpCtxt,
ULONG ulOptReq
);
// check if required columns are included in output columns
virtual
BOOL FProvidesReqdCols(CExpressionHandle &exprhdl, CColRefSet *pcrsRequired, ULONG ulOptReq) const;
//-------------------------------------------------------------------------------------
// Derived Plan Properties
//-------------------------------------------------------------------------------------
// derive sort order
virtual
COrderSpec *PosDerive(CMemoryPool *mp, CExpressionHandle &exprhdl) const;
// derive distribution
virtual
CDistributionSpec *PdsDerive(CMemoryPool *mp, CExpressionHandle &exprhdl) const;
// derive rewindability
virtual
CRewindabilitySpec *PrsDerive(CMemoryPool *mp, CExpressionHandle &exprhdl) const;
// derive partition index map
virtual
CPartIndexMap *PpimDerive
(
CMemoryPool *, // mp
CExpressionHandle &exprhdl,
CDrvdPropCtxt * //pdpctxt
)
const
{
return PpimPassThruOuter(exprhdl);
}
// derive partition filter map
virtual
CPartFilterMap *PpfmDerive
(
CMemoryPool *, // mp
CExpressionHandle &exprhdl
)
const
{
return PpfmPassThruOuter(exprhdl);
}
//-------------------------------------------------------------------------------------
// Enforced Properties
//-------------------------------------------------------------------------------------
// return order property enforcing type for this operator
virtual
CEnfdProp::EPropEnforcingType EpetOrder
(
CExpressionHandle &exprhdl,
const CEnfdOrder *peo
) const;
// return rewindability property enforcing type for this operator
virtual
CEnfdProp::EPropEnforcingType EpetRewindability
(
CExpressionHandle &exprhdl,
const CEnfdRewindability *per
)
const;
// return true if operator passes through stats obtained from children,
// this is used when computing stats during costing
virtual
BOOL FPassThruStats() const
{
return true;
}
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
// conversion function
static
CPhysicalAssert *PopConvert
(
COperator *pop
)
{
GPOS_ASSERT(NULL != pop);
GPOS_ASSERT(EopPhysicalAssert == pop->Eopid());
return reinterpret_cast<CPhysicalAssert*>(pop);
}
// debug print
IOstream &OsPrint(IOstream &os) const;
}; // class CPhysicalAssert
}
#endif // !GPOPT_CPhysicalAssert_H
// EOF
|
{
"pile_set_name": "Github"
}
|
# Default values for aws-load-balancer-controller.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
replicaCount: 1
image:
repository: amazon/aws-alb-ingress-controller
tag: v2.0.0-rc2
pullPolicy: Always
imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""
# The name of the Kubernetes cluster. A non-empty value is required
clusterName:
serviceAccount:
# Specifies whether a service account should be created
create: true
# Annotations to add to the service account
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name:
rbac:
# Specifies whether rbac resources should be created
create: true
podSecurityContext:
fsGroup: 65534
securityContext: {}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000
# Time period for the controller pod to do a graceful shutdown
terminationGracePeriodSeconds: 10
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi
nodeSelector: {}
tolerations: []
affinity: {}
# Enable cert-manager
enableCertManager: false
|
{
"pile_set_name": "Github"
}
|
<html><head>
<title>GLGE</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="../../glge-compiled-min.js"></script>
<style>
body{background-color: #000;color: #fff;font-family:arial}
</style>
</head><body>
<div id="dump"></div>
<div>
<div style="width:900px;margin:auto;position:relative" id="container">
<canvas id="canvas" width="900"
height="500"></canvas>
<img src="images/glgelogo.png" alt="GLGElogo" style="position:absolute;top: 450px; left: 750px;border 1px solid red;" />
<div id="framerate" style="position:absolute; left: 750px; top: 20px; background-color: #000; opacity: 0.5;height: 30px; width: 130px; border-radius: 5px; -moz-border-radius5px;-webkit-border-radius:5px;border: 1px solid #fff;">
<div id="debug" style="padding: 5px"></div>
</div>
</div>
</div>
<script type="text/javascript">
var gameScene;
var doc = new GLGE.Document();
doc.onLoad=function(){
//create the renderer
var gameRenderer=new GLGE.Renderer(document.getElementById('canvas'));
gameScene=new GLGE.Scene();
gameScene=doc.getElement("mainscene");
boom=doc.getElement("boom");
boom2=doc.getElement("boom2");
gameRenderer.setScene(gameScene);
var mouse=new GLGE.MouseInput(document.getElementById('canvas'));
var keys=new GLGE.KeyInput();
var mouseovercanvas;
var hoverobj;
function mouselook(){
if(mouseovercanvas){
var mousepos=mouse.getMousePosition();
mousepos.x=mousepos.x-document.getElementById("container").offsetLeft;
mousepos.y=mousepos.y-document.getElementById("container").offsetTop;
var camera=gameScene.camera;
camerarot=camera.getRotation();
inc=(mousepos.y-(document.getElementById('canvas').offsetHeight/2))/500;
var trans=GLGE.mulMat4Vec4(camera.getRotMatrix(),[0,0,-1,1]);
var mag=Math.pow(Math.pow(trans[0],2)+Math.pow(trans[1],2),0.5);
trans[0]=trans[0]/mag;
trans[1]=trans[1]/mag;
camera.setRotX(1.56-trans[1]*inc);
camera.setRotZ(-trans[0]*inc);
var width=document.getElementById('canvas').offsetWidth;
if(mousepos.x<width*0.3){
var turn=Math.pow((mousepos.x-width*0.3)/(width*0.3),2)*0.005*(now-lasttime);
camera.setRotY(camerarot.y+turn);
}
if(mousepos.x>width*0.7){
var turn=Math.pow((mousepos.x-width*0.7)/(width*0.3),2)*0.005*(now-lasttime);
camera.setRotY(camerarot.y-turn);
}
}
}
function checkkeys(){
var camera=gameScene.camera;
var camerapos=camera.getPosition();
var camerarot=camera.getRotation();
var mat=camera.getRotMatrix();
var trans=GLGE.mulMat4Vec4(mat,[0,0,-1,1]);
var mag=Math.pow(Math.pow(trans[0],2)+Math.pow(trans[1],2),0.5);
trans[0]=trans[0]/mag;
trans[1]=trans[1]/mag;
var yinc=0;
var xinc=0;
if(keys.isKeyPressed(GLGE.KI_M)) {addduck();}
if(keys.isKeyPressed(GLGE.KI_W)) {yinc=yinc+parseFloat(trans[1]);xinc=xinc+parseFloat(trans[0]);}
if(keys.isKeyPressed(GLGE.KI_S)) {yinc=yinc-parseFloat(trans[1]);xinc=xinc-parseFloat(trans[0]);}
if(keys.isKeyPressed(GLGE.KI_A)) {yinc=yinc+parseFloat(trans[0]);xinc=xinc-parseFloat(trans[1]);}
if(keys.isKeyPressed(GLGE.KI_D)) {yinc=yinc-parseFloat(trans[0]);xinc=xinc+parseFloat(trans[1]);}
if(keys.isKeyPressed(GLGE.KI_SPACE)) {if(playervel==0) playervel=35;}
if(xinc!=0 || yinc!=0){
var origin=[camerapos.x,camerapos.y,camerapos.z];
dist2=gameScene.ray(origin,[-xinc,0,0]);
dist3=gameScene.ray(origin,[0,-yinc,0]);
if(dist2 && dist2.distance<5) xinc=0;
if(dist3 && dist3.distance<5) yinc=0;
if(xinc!=0 || yinc!=0){
camera.setLocY(camerapos.y+yinc*0.05*(now-lasttime));camera.setLocX(camerapos.x+xinc*0.05*(now-lasttime));
if(playervel==0) playervel=0.001;
}
}
}
var lasttime=0;
var frameratebuffer=60;
var playervel=-1;
var gravity=-98;
start=parseInt(new Date().getTime());
lasttime=start;
var now;
function render(){
now=parseInt(new Date().getTime());
//do the players gravity
frameratebuffer=Math.round(((frameratebuffer*9)+1000/(now-lasttime))/10);
document.getElementById("debug").innerHTML="Frame Rate:"+frameratebuffer;
mouselook();
checkkeys();
if(playervel!=0 || now%10==0){
playervel+=gravity*(now-lasttime)/1000;
var camerapos=gameScene.camera.getPosition();
var origin=[camerapos.x,camerapos.y,camerapos.z];
var ray=gameScene.ray(origin,[0,0,1]);
var dist=ray.distance;
inc=playervel*(now-lasttime)/1000;
if(dist+inc<8){
inc=8-dist;
playervel=0;
};
if(inc<0.01&& inc>-0.01) inc=0;
if(!ray.object){
inc=0;
}else if(ray.object.parent.animation){
if(dist<10) playervel=11;
}
gameScene.camera.setLocZ(camerapos.z+inc);
}
gameRenderer.render();
lasttime=now;
requestAnimationFrame(render)
}
render();
var inc=0.2;
document.getElementById("canvas").onmouseover=function(e){mouseovercanvas=true;}
document.getElementById("canvas").onmouseout=function(e){mouseovercanvas=false;}
document.onmousedown=function(e){
var mousepos=mouse.getMousePosition();
mousepos.x=mousepos.x-document.getElementById("container").offsetLeft;
mousepos.y=mousepos.y-document.getElementById("container").offsetTop;
if(mousepos.x && mousepos.y){
var result=gameScene.pick(mousepos.x,mousepos.y);
boom.setLoc(result.coord[0],result.coord[1],result.coord[2]);
boom2.setLoc(result.coord[0],result.coord[1],result.coord[2]);
boom.reset();boom2.reset();
}
}
}
doc.load("particles.xml");
</script>
</body></html>
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright 2020 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.
*******************************************************************************/
#ifndef COMMON_INTERNAL_DEFS_HPP
#define COMMON_INTERNAL_DEFS_HPP
#if defined(DNNL_DLL)
#define DNNL_WEAK DNNL_HELPER_DLL_EXPORT
#else
#if defined(__GNUC__) || defined(__clang__)
#define DNNL_WEAK __attribute__((weak))
#else
#define DNNL_WEAK
#endif
#endif
#if defined(DNNL_DLL)
#define DNNL_STRONG DNNL_HELPER_DLL_EXPORT
#else
#define DNNL_STRONG
#endif
#endif
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// 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.
#pragma once
#include "rsocket/internal/ScheduledSubscription.h"
#include <folly/io/async/EventBase.h>
#include "yarpl/flowable/Subscriber.h"
namespace rsocket {
//
// A decorator of the Subscriber object which schedules the method calls on the
// provided EventBase.
// This class should be used to wrap a Subscriber returned to the application
// code so that calls to on{Subscribe,Next,Complete,Error} are scheduled on the
// right EventBase.
//
template <typename T>
class ScheduledSubscriber : public yarpl::flowable::Subscriber<T> {
public:
ScheduledSubscriber(
std::shared_ptr<yarpl::flowable::Subscriber<T>> inner,
folly::EventBase& eventBase)
: inner_(std::move(inner)), eventBase_(eventBase) {}
void onSubscribe(
std::shared_ptr<yarpl::flowable::Subscription> subscription) override {
if (eventBase_.isInEventBaseThread()) {
inner_->onSubscribe(std::move(subscription));
} else {
eventBase_.runInEventBaseThread(
[inner = inner_, subscription = std::move(subscription)] {
inner->onSubscribe(std::move(subscription));
});
}
}
// No further calls to the subscription after this method is invoked.
void onComplete() override {
if (eventBase_.isInEventBaseThread()) {
inner_->onComplete();
} else {
eventBase_.runInEventBaseThread(
[inner = inner_] { inner->onComplete(); });
}
}
void onError(folly::exception_wrapper ex) override {
if (eventBase_.isInEventBaseThread()) {
inner_->onError(std::move(ex));
} else {
eventBase_.runInEventBaseThread(
[inner = inner_, ex = std::move(ex)]() mutable {
inner->onError(std::move(ex));
});
}
}
void onNext(T value) override {
if (eventBase_.isInEventBaseThread()) {
inner_->onNext(std::move(value));
} else {
eventBase_.runInEventBaseThread(
[inner = inner_, value = std::move(value)]() mutable {
inner->onNext(std::move(value));
});
}
}
private:
const std::shared_ptr<yarpl::flowable::Subscriber<T>> inner_;
folly::EventBase& eventBase_;
};
//
// A decorator of a Subscriber object which schedules the method calls on the
// provided EventBase.
// This class is to wrap the Subscriber provided from the application code to
// the library. The Subscription passed to onSubscribe method needs to be
// wrapped in the ScheduledSubscription since the application code calls
// request and cancel from any thread.
//
template <typename T>
class ScheduledSubscriptionSubscriber : public yarpl::flowable::Subscriber<T> {
public:
ScheduledSubscriptionSubscriber(
std::shared_ptr<yarpl::flowable::Subscriber<T>> inner,
folly::EventBase& eventBase)
: inner_(std::move(inner)), eventBase_(eventBase) {}
void onSubscribe(
std::shared_ptr<yarpl::flowable::Subscription> sub) override {
auto scheduled =
std::make_shared<ScheduledSubscription>(std::move(sub), eventBase_);
inner_->onSubscribe(std::move(scheduled));
}
void onNext(T value) override {
inner_->onNext(std::move(value));
}
void onComplete() override {
auto inner = std::move(inner_);
inner->onComplete();
}
void onError(folly::exception_wrapper ew) override {
auto inner = std::move(inner_);
inner->onError(std::move(ew));
}
private:
std::shared_ptr<yarpl::flowable::Subscriber<T>> inner_;
folly::EventBase& eventBase_;
};
} // namespace rsocket
|
{
"pile_set_name": "Github"
}
|
require_relative '../../../spec_helper'
require_relative 'shared/constants'
describe "Digest::SHA512#==" do
it "equals itself" do
cur_digest = Digest::SHA512.new
cur_digest.should == cur_digest
end
it "equals the string representing its hexdigest" do
cur_digest = Digest::SHA512.new
cur_digest.should == SHA512Constants::BlankHexdigest
end
it "equals the appropriate object that responds to to_str" do
# blank digest
cur_digest = Digest::SHA512.new
(obj = mock(SHA512Constants::BlankHexdigest)).should_receive(:to_str).and_return(SHA512Constants::BlankHexdigest)
cur_digest.should == obj
# non-blank digest
cur_digest = Digest::SHA512.new
cur_digest << "test"
d_value = cur_digest.hexdigest
(obj = mock(d_value)).should_receive(:to_str).and_return(d_value)
cur_digest.should == obj
end
it "equals the same digest for a different object" do
cur_digest = Digest::SHA512.new
cur_digest2 = Digest::SHA512.new
cur_digest.should == cur_digest2
end
end
|
{
"pile_set_name": "Github"
}
|
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "c-interface/c-interface.h"
//------------------------------------------------------------------------------
ConsoleMethod(GuiTreeViewCtrl, findItemByName, S32, 3, 3, "(name) Find item by name\n"
"@param name The name of the desired object.\n"
"@return Returns the ID of the object, or -1 on failure (not found).")
{
return(object->findItemByName(argv[2]));
}
ConsoleMethod(GuiTreeViewCtrl, insertItem, S32, 4, 8, "(TreeItemId parent, name, value, icon, normalImage=0, expandedImage=0) Adds item to tree control.\n"
"@param parent The new item's parent.\n"
"@param name The name of the new item.\n"
"@param value The new item's value.\n"
"@param icon The new item's icon\n"
"@return Returns the new item's ID.")
{
S32 norm = 0, expand = 0;
if (argc > 6)
{
norm = dAtoi(argv[6]);
if (argc > 7)
expand = dAtoi(argv[7]);
}
return(object->insertItem(dAtoi(argv[2]), argv[3], argv[4], argv[5], norm, expand));
}
ConsoleMethod(GuiTreeViewCtrl, lockSelection, void, 2, 3, "([bool lock]) Set whether the selection is to be locked."
"@param lock Boolean flag for whether or not the current selected object should be locked\n"
"@return No return value.")
{
bool lock = true;
if (argc == 3)
lock = dAtob(argv[2]);
object->lockSelection(lock);
}
ConsoleMethod(GuiTreeViewCtrl, clearSelection, void, 2, 2, "() Clear selection\n"
"@return No return value.")
{
object->clearSelection();
}
ConsoleMethod(GuiTreeViewCtrl, deleteSelection, void, 2, 2, "() Delete all selected items.\n"
"@return No return value.\n")
{
object->deleteSelection();
}
ConsoleMethod(GuiTreeViewCtrl, addSelection, void, 3, 3, "(string ID) Select an item"
"@param ID The ID of the item to select.\n"
"@return No return value.")
{
S32 id = dAtoi(argv[2]);
object->addSelection(id);
}
ConsoleMethod(GuiTreeViewCtrl, addChildSelectionByValue, void, 4, 4, "(TreeItemId parent, value)")
{
S32 id = dAtoi(argv[2]);
GuiTreeViewCtrl::Item* parentItem = object->getItem(id);
if (parentItem)
{
GuiTreeViewCtrl::Item* child = parentItem->findChildByValue(argv[3]);
if (child)
object->addSelection(child->getID());
}
}
ConsoleMethod(GuiTreeViewCtrl, removeSelection, void, 3, 3, "(string ID) Deselects given item.\n"
"@param ID The ID of the item to deselect.\n"
"@return No return value.")
{
S32 id = dAtoi(argv[2]);
object->removeSelection(id);
}
ConsoleMethod(GuiTreeViewCtrl, removeChildSelectionByValue, void, 4, 4, "removeChildSelectionByValue(TreeItemId parent, value)")
{
S32 id = dAtoi(argv[2]);
GuiTreeViewCtrl::Item* parentItem = object->getItem(id);
if (parentItem)
{
GuiTreeViewCtrl::Item* child = parentItem->findChildByValue(argv[3]);
if (child)
object->removeSelection(child->getID());
}
}
ConsoleMethod(GuiTreeViewCtrl, selectItem, bool, 3, 4, "(TreeItemId item, [bool select=true]) Selects item.")
{
S32 id = dAtoi(argv[2]);
bool select = true;
if (argc == 4)
select = dAtob(argv[3]);
return(object->setItemSelected(id, select));
}
ConsoleMethod(GuiTreeViewCtrl, expandItem, bool, 3, 4, "(TreeItemId item, [bool expand=true]) Deselects item")
{
S32 id = dAtoi(argv[2]);
bool expand = true;
if (argc == 4)
expand = dAtob(argv[3]);
return(object->setItemExpanded(id, expand));
}
// Make the given item visible.
ConsoleMethod(GuiTreeViewCtrl, scrollVisible, void, 3, 3, "(TreeItemId item) Make the given item visible.\n"
"@param ID of the desired item.\n"
"@return No return value.")
{
object->scrollVisible(dAtoi(argv[2]));
}
ConsoleMethod(GuiTreeViewCtrl, buildIconTable, bool, 3, 3, "(string icons) Icons should be designated by the bitmap/png file names (minus the file extensions) "
"and separated by colons (:). This list should be synchronized with the Icons enum.\n"
"@param icons The list of icons to add sepated by colons.\n"
"@return Returns true on success, false otherwise.")
{
const char * icons = argv[2];
return object->buildIconTable(icons);
}
ConsoleMethod(GuiTreeViewCtrl, open, void, 3, 4, "(SimSet obj, bool okToEdit=true) Set the root of the tree view to the specified object, or to the root set.")
{
SimSet *treeRoot = NULL;
SimObject* target = Sim::findObject(argv[2]);
bool okToEdit = true;
if (argc == 4)
okToEdit = dAtob(argv[3]);
if (target)
treeRoot = dynamic_cast<SimSet*>(target);
if (!treeRoot)
Sim::findObject(RootGroupId, treeRoot);
object->inspectObject(treeRoot, okToEdit);
}
ConsoleMethod(GuiTreeViewCtrl, getItemText, const char *, 3, 3, "(TreeItemId item)")
{
return(object->getItemText(dAtoi(argv[2])));
}
ConsoleMethod(GuiTreeViewCtrl, getItemValue, const char *, 3, 3, "(TreeItemId item)")
{
return(object->getItemValue(dAtoi(argv[2])));
}
ConsoleMethod(GuiTreeViewCtrl, editItem, bool, 5, 5, "(TreeItemId item, string newText, string newValue)")
{
return(object->editItem(dAtoi(argv[2]), argv[3], argv[4]));
}
ConsoleMethod(GuiTreeViewCtrl, removeItem, bool, 3, 3, "(TreeItemId item)")
{
return(object->removeItem(dAtoi(argv[2])));
}
ConsoleMethod(GuiTreeViewCtrl, removeAllChildren, void, 3, 3, "removeAllChildren(TreeItemId parent)")
{
object->removeAllChildren(dAtoi(argv[2]));
}
ConsoleMethod(GuiTreeViewCtrl, clear, void, 2, 2, "() - empty tree")
{
object->removeItem(0);
}
ConsoleMethod(GuiTreeViewCtrl, getFirstRootItem, S32, 2, 2, "Get id for root item.")
{
return(object->getFirstRootItem());
}
ConsoleMethod(GuiTreeViewCtrl, getChild, S32, 3, 3, "(TreeItemId item)")
{
return(object->getChildItem(dAtoi(argv[2])));
}
ConsoleMethod(GuiTreeViewCtrl, buildVisibleTree, void, 3, 3, "Build the visible tree")
{
object->buildVisibleTree(dAtob(argv[2]));
}
ConsoleMethod(GuiTreeViewCtrl, getParent, S32, 3, 3, "(TreeItemId item)")
{
return(object->getParentItem(dAtoi(argv[2])));
}
ConsoleMethod(GuiTreeViewCtrl, getNextSibling, S32, 3, 3, "(TreeItemId item)")
{
return(object->getNextSiblingItem(dAtoi(argv[2])));
}
ConsoleMethod(GuiTreeViewCtrl, getPrevSibling, S32, 3, 3, "(TreeItemId item)")
{
return(object->getPrevSiblingItem(dAtoi(argv[2])));
}
ConsoleMethod(GuiTreeViewCtrl, getItemCount, S32, 2, 2, "() @return Returns the number of items in control")
{
return(object->getItemCount());
}
ConsoleMethod(GuiTreeViewCtrl, getSelectedItem, S32, 2, 2, "() @return Returns the ID of the selected item.")
{
return (object->getSelectedItem());
}
ConsoleMethod(GuiTreeViewCtrl, getSelectedObject, S32, 2, 2, "() @return Returns the currently selected simObject in inspector mode or -1")
{
GuiTreeViewCtrl::Item *item = object->getItem(object->getSelectedItem());
if (item != NULL && item->isInspectorData())
{
SimObject *obj = item->getObject();
if (obj != NULL)
return object->getId();
}
return -1;
}
ConsoleMethod(GuiTreeViewCtrl, moveItemUp, void, 3, 3, "(TreeItemId item)")
{
object->moveItemUp(dAtoi(argv[2]));
}
ConsoleMethod(GuiTreeViewCtrl, getSelectedItemsCount, S32, 2, 2, "")
{
return (object->getSelectedItemsCount());
}
ConsoleMethod(GuiTreeViewCtrl, moveItemDown, void, 3, 3, "(TreeItemId item)")
{
object->moveItemDown(dAtoi(argv[2]));
}
//-----------------------------------------------------------------------------
ConsoleMethod(GuiTreeViewCtrl, getTextToRoot, const char*, 4, 4, "(TreeItemId item,Delimiter=none) gets the text from the current node to the root, concatenating at each branch upward, with a specified delimiter optionally")
{
if (argc < 4)
{
Con::warnf("GuiTreeViewCtrl::getTextToRoot - Invalid number of arguments!");
return ("");
}
S32 itemId = dAtoi(argv[2]);
StringTableEntry delimiter = argv[3];
return object->getTextToRoot(itemId, delimiter);
}
ConsoleMethod(GuiTreeViewCtrl, getSelectedItemList, const char*, 2, 2, "returns a space seperated list of mulitple item ids")
{
char* buff = Con::getReturnBuffer(1024);
dSprintf(buff, 1024, "");
for (int i = 0; i < object->mSelected.size(); i++)
{
S32 id = object->mSelected[i];
//get the current length of the buffer
U32 len = dStrlen(buff);
//the start of the buffer where we want to write
char* buffPart = buff + len;
//the size of the remaining buffer (-1 cause dStrlen doesn't count the \0)
S32 size = 1024 - len - 1;
//write it:
if (size < 1)
{
Con::errorf("GuiTreeViewCtrl::getSelectedItemList - Not enough room to return our object list");
return buff;
}
dSprintf(buffPart, size, "%d ", id);
}
//mSelected
return buff;
}
//------------------------------------------------------------------------------
ConsoleMethod(GuiTreeViewCtrl, findItemByObjectId, S32, 3, 3, "(find item by object id and returns the mId)")
{
return(object->findItemByObjectId(dAtoi(argv[2])));
}
//------------------------------------------------------------------------------
ConsoleMethod(GuiTreeViewCtrl, scrollVisibleByObjectId, S32, 3, 3, "(show item by object id. returns true if sucessful.)")
{
return(object->scrollVisibleByObjectId(dAtoi(argv[2])));
}
extern "C"{
DLL_PUBLIC GuiTreeViewCtrl* GuiTreeViewCtrlCreateInstance()
{
return new GuiTreeViewCtrl();
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetTabSize(GuiTreeViewCtrl* ctrl)
{
return ctrl->getTabSize();
}
DLL_PUBLIC void GuiTreeViewCtrlSetTabSize(GuiTreeViewCtrl* ctrl, S32 size)
{
ctrl->setTabSize(size);
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetTextOffset(GuiTreeViewCtrl* ctrl)
{
return ctrl->getTextOffset();
}
DLL_PUBLIC void GuiTreeViewCtrlSetTextOffset(GuiTreeViewCtrl* ctrl, S32 offset)
{
ctrl->setTextOffset(offset);
}
DLL_PUBLIC bool GuiTreeViewCtrlGetFullRowSelect(GuiTreeViewCtrl* ctrl)
{
return ctrl->getFullRowSelect();
}
DLL_PUBLIC void GuiTreeViewCtrlSetFullRowSelect(GuiTreeViewCtrl* ctrl, bool fullRowSelect)
{
ctrl->setFullRowSelect(fullRowSelect);
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetItemHeight(GuiTreeViewCtrl* ctrl)
{
return ctrl->getItemHeight();
}
DLL_PUBLIC void GuiTreeViewCtrlSetItemHeight(GuiTreeViewCtrl* ctrl, S32 height)
{
ctrl->setItemHeight(height);
}
DLL_PUBLIC bool GuiTreeViewCtrlGetDestroyTreeOnSleep(GuiTreeViewCtrl* ctrl)
{
return ctrl->getDestroyOnSleep();
}
DLL_PUBLIC void GuiTreeViewCtrlSetDestroyTreeOnSleep(GuiTreeViewCtrl* ctrl, bool destroyOnSleep)
{
ctrl->setDestroyOnSleep(destroyOnSleep);
}
DLL_PUBLIC bool GuiTreeViewCtrlGetMouseDragging(GuiTreeViewCtrl* ctrl)
{
return ctrl->getSupportMouseDragging();
}
DLL_PUBLIC void GuiTreeViewCtrlSetMouseDragging(GuiTreeViewCtrl* ctrl, bool allowDragging)
{
ctrl->setSupportMouseDragging(allowDragging);
}
DLL_PUBLIC bool GuiTreeViewCtrlGetMultipleSelections(GuiTreeViewCtrl* ctrl)
{
return ctrl->getMultipleSelections();
}
DLL_PUBLIC void GuiTreeViewCtrlSetMultipleSelections(GuiTreeViewCtrl* ctrl, bool multipleSelections)
{
ctrl->setMultipleSelections(multipleSelections);
}
DLL_PUBLIC bool GuiTreeViewCtrlGetDeleteObjectAllowed(GuiTreeViewCtrl* ctrl)
{
return ctrl->getDeleteObjectAllowed();
}
DLL_PUBLIC void GuiTreeViewCtrlSetDeleteObjectAllowed(GuiTreeViewCtrl* ctrl, bool allowDelete)
{
ctrl->setDeleteObjectAllowed(allowDelete);
}
DLL_PUBLIC bool GuiTreeViewCtrlGetDragToItemAllowed(GuiTreeViewCtrl* ctrl)
{
return ctrl->getDragToItemAllowed();
}
DLL_PUBLIC void GuiTreeViewCtrlSetDragToItemAllowed(GuiTreeViewCtrl* ctrl, bool allowDrag)
{
ctrl->setDragToItemAllowed(allowDrag);
}
DLL_PUBLIC S32 GuiTreeViewCtrlFindItemByName(GuiTreeViewCtrl* ctrl, const char* name)
{
return ctrl->findItemByName(name);
}
//CTODO default values
DLL_PUBLIC S32 GuiTreeViewCtrlInsertItem(GuiTreeViewCtrl* ctrl, S32 parent, const char* name, const char* value, const char* icon, S32 norm, S32 expand)
{
return ctrl->insertItem(parent, name, value, icon, norm, expand);
}
DLL_PUBLIC void GuiTreeViewCtrlLockSelection(GuiTreeViewCtrl* ctrl, bool locked)
{
ctrl->lockSelection(locked);
}
DLL_PUBLIC void GuiTreeViewCtrlClearSelection(GuiTreeViewCtrl* ctrl)
{
ctrl->clearSelection();
}
DLL_PUBLIC void GuiTreeViewCtrlDeleteSelection(GuiTreeViewCtrl* ctrl)
{
ctrl->deleteSelection();
}
DLL_PUBLIC void GuiTreeViewCtrlAddSelection(GuiTreeViewCtrl* ctrl, S32 ID)
{
ctrl->addSelection(ID);
}
DLL_PUBLIC void GuiTreeViewCtrlAddChildSelectionByValue(GuiTreeViewCtrl* ctrl, S32 parent, const char* value)
{
GuiTreeViewCtrl::Item* parentItem = ctrl->getItem(parent);
if (parentItem)
{
GuiTreeViewCtrl::Item* child = parentItem->findChildByValue(value);
if (child)
ctrl->addSelection(child->getID());
}
}
DLL_PUBLIC void GuiTreeViewCtrlRemoveSelection(GuiTreeViewCtrl* ctrl, S32 ID)
{
ctrl->removeSelection(ID);
}
DLL_PUBLIC void GuiTreeViewCtrlRemoveChildSelectionByValue(GuiTreeViewCtrl* ctrl, S32 parent, const char* value)
{
GuiTreeViewCtrl::Item* parentItem = ctrl->getItem(parent);
if (parentItem)
{
GuiTreeViewCtrl::Item* child = parentItem->findChildByValue(value);
if (child)
ctrl->removeSelection(child->getID());
}
}
//CTODO default vlaue
DLL_PUBLIC bool GuiTreeViewCtrlSelectItem(GuiTreeViewCtrl* ctrl, S32 item, bool select)
{
return ctrl->setItemSelected(item, select);
}
//CTODO default value
DLL_PUBLIC bool GuiTreeViewCtrlExpandItem(GuiTreeViewCtrl* ctrl, S32 item, bool expand)
{
return ctrl->setItemExpanded(item, expand);
}
DLL_PUBLIC void GuiTreeViewCtrlScrollVisible(GuiTreeViewCtrl* ctrl, S32 item)
{
ctrl->scrollVisible(item);
}
DLL_PUBLIC bool GuiTreeViewCtrlBuildIconTable(GuiTreeViewCtrl* ctrl, const char* icons)
{
return ctrl->buildIconTable(icons);
}
//CTODO default value
DLL_PUBLIC void GuiTreeViewCtrlOpen(GuiTreeViewCtrl* ctrl, SimSet* target, bool okToEdit)
{
if (!target)
Sim::findObject(RootGroupId, target);
ctrl->inspectObject(target, okToEdit);
}
DLL_PUBLIC const char* GuiTreeViewCtrlGetItemText(GuiTreeViewCtrl* ctrl, S32 item)
{
return ctrl->getItemText(item);
}
DLL_PUBLIC const char* GuiTreeViewCtrlGetItemValue(GuiTreeViewCtrl* ctrl, S32 item)
{
return ctrl->getItemValue(item);
}
DLL_PUBLIC bool GuiTreeViewCtrlEditItem(GuiTreeViewCtrl* ctrl, S32 item, const char* newText, const char* newValue)
{
return ctrl->editItem(item, newText, newValue);
}
DLL_PUBLIC bool GuiTreeViewCtrlRemoveItem(GuiTreeViewCtrl* ctrl, S32 item)
{
return ctrl->removeItem(item);
}
DLL_PUBLIC void GuiTreeViewCtrlRemoveAllChildren(GuiTreeViewCtrl* ctrl, S32 parent)
{
ctrl->removeAllChildren(parent);
}
DLL_PUBLIC void GuiTreeViewCtrlClear(GuiTreeViewCtrl* ctrl)
{
ctrl->removeItem(0);
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetFirstRootItem(GuiTreeViewCtrl* ctrl)
{
return ctrl->getFirstRootItem();
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetChild(GuiTreeViewCtrl* ctrl, S32 item)
{
return ctrl->getChildItem(item);
}
//CTODO default value
DLL_PUBLIC void GuiTreeViewCtrlBuildVisibleTree(GuiTreeViewCtrl* ctrl, bool forceFullUpdate)
{
ctrl->buildVisibleTree(forceFullUpdate);
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetParent(GuiTreeViewCtrl* ctrl, S32 item)
{
return ctrl->getParentItem(item);
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetNextSibling(GuiTreeViewCtrl* ctrl, S32 item)
{
return ctrl->getNextSiblingItem(item);
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetPrevSibling(GuiTreeViewCtrl* ctrl, S32 item)
{
return ctrl->getPrevSiblingItem(item);
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetItemCount(GuiTreeViewCtrl* ctrl)
{
return ctrl->getItemCount();
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetSelectedItem(GuiTreeViewCtrl* ctrl)
{
return ctrl->getSelectedItem();
}
DLL_PUBLIC SimObject* GuiTreeViewCtrlGetSelectedObject(GuiTreeViewCtrl* ctrl)
{
GuiTreeViewCtrl::Item *item = ctrl->getItem(ctrl->getSelectedItem());
if (item != NULL && item->isInspectorData())
{
SimObject *obj = item->getObject();
if (obj != NULL)
return obj;
}
return NULL;
}
DLL_PUBLIC void GuiTreeViewCtrlMoveItemUp(GuiTreeViewCtrl* ctrl, S32 item)
{
ctrl->moveItemUp(item);
}
DLL_PUBLIC void GuiTreeViewCtrlMoveItemDown(GuiTreeViewCtrl* ctrl, S32 item)
{
ctrl->moveItemDown(item);
}
DLL_PUBLIC S32 GuiTreeViewCtrlGetSelectedItemsCount(GuiTreeViewCtrl* ctrl)
{
return ctrl->getSelectedItemsCount();
}
//CTODO default value
DLL_PUBLIC const char* GuiTreeViewCtrlGetTextToRoot(GuiTreeViewCtrl* ctrl, S32 item, const char* delimiter)
{
return ctrl->getTextToRoot(item, delimiter);
}
//CTODO list
DLL_PUBLIC const char* GuiTreeViewCtrlGetSelectedItemList(GuiTreeViewCtrl* ctrl)
{
char* buff = Con::getReturnBuffer(1024);
dSprintf(buff, 1024, "");
for (int i = 0; i < ctrl->mSelected.size(); i++)
{
S32 id = ctrl->mSelected[i];
//get the current length of the buffer
U32 len = dStrlen(buff);
//the start of the buffer where we want to write
char* buffPart = buff + len;
//the size of the remaining buffer (-1 cause dStrlen doesn't count the \0)
S32 size = 1024 - len - 1;
//write it:
if (size < 1)
{
Con::errorf("GuiTreeViewCtrl::getSelectedItemList - Not enough room to return our object list");
return buff;
}
dSprintf(buffPart, size, "%d ", id);
}
return buff;
}
DLL_PUBLIC S32 GuiTreeViewCtrlFindItemByObject(GuiTreeViewCtrl* ctrl, SimObject* obj)
{
return ctrl->findItemByObjectId(obj->getId());
}
DLL_PUBLIC S32 GuiTreeViewCtrlScrollVisibleByObject(GuiTreeViewCtrl* ctrl, SimObject* obj)
{
return ctrl->scrollVisibleByObjectId(obj->getId());
}
}
|
{
"pile_set_name": "Github"
}
|
package net.i2p.data.i2cp;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* with no warranty of any kind, either expressed or implied.
* It probably won't make your computer catch on fire, or eat
* your children, but it might. Use at your own risk.
*
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.data.TunnelId;
/**
* Defines the message a router sends to a client to request that
* a leaseset be created and signed. The reply is a CreateLeaseSetMessage.
*
* @author jrandom
*/
public class RequestLeaseSetMessage extends I2CPMessageImpl {
private static final long serialVersionUID = 1L;
public final static int MESSAGE_TYPE = 21;
private SessionId _sessionId;
// ArrayList is Serializable, List is not
private final ArrayList<TunnelEndpoint> _endpoints;
private Date _end;
public RequestLeaseSetMessage() {
_endpoints = new ArrayList<TunnelEndpoint>();
}
public SessionId getSessionId() {
return _sessionId;
}
/**
* Return the SessionId for this message.
*
* @since 0.9.21
*/
@Override
public SessionId sessionId() {
return _sessionId;
}
public void setSessionId(SessionId id) {
_sessionId = id;
}
public int getEndpoints() {
return _endpoints.size();
}
public Hash getRouter(int endpoint) {
if ((endpoint < 0) || (_endpoints.size() <= endpoint)) return null;
return _endpoints.get(endpoint).getRouter();
}
public TunnelId getTunnelId(int endpoint) {
if ((endpoint < 0) || (_endpoints.size() <= endpoint)) return null;
return _endpoints.get(endpoint).getTunnelId();
}
/** @deprecated unused - presumably he meant remove? */
@Deprecated
public void remoteEndpoint(int endpoint) {
if ((endpoint >= 0) && (endpoint < _endpoints.size())) _endpoints.remove(endpoint);
}
public void addEndpoint(Hash router, TunnelId tunnel) {
if (router == null) throw new IllegalArgumentException("Null router (tunnel=" + tunnel +")");
if (tunnel == null) throw new IllegalArgumentException("Null tunnel (router=" + router +")");
_endpoints.add(new TunnelEndpoint(router, tunnel));
}
public Date getEndDate() {
return _end;
}
public void setEndDate(Date end) {
_end = end;
}
@Override
protected void doReadMessage(InputStream in, int size) throws I2CPMessageException, IOException {
try {
_sessionId = new SessionId();
_sessionId.readBytes(in);
int numTunnels = in.read();
// EOF will be caught below
_endpoints.clear();
for (int i = 0; i < numTunnels; i++) {
//Hash router = new Hash();
//router.readBytes(in);
Hash router = Hash.create(in);
TunnelId tunnel = new TunnelId();
tunnel.readBytes(in);
_endpoints.add(new TunnelEndpoint(router, tunnel));
}
_end = DataHelper.readDate(in);
} catch (DataFormatException dfe) {
throw new I2CPMessageException("Unable to load the message data", dfe);
}
}
@Override
protected byte[] doWriteMessage() throws I2CPMessageException, IOException {
if (_sessionId == null)
throw new I2CPMessageException("Unable to write out the message as there is not enough data");
ByteArrayOutputStream os = new ByteArrayOutputStream(256);
try {
_sessionId.writeBytes(os);
os.write((byte) _endpoints.size());
for (int i = 0; i < _endpoints.size(); i++) {
Hash router = getRouter(i);
router.writeBytes(os);
TunnelId tunnel = getTunnelId(i);
tunnel.writeBytes(os);
}
DataHelper.writeDate(os, _end);
} catch (DataFormatException dfe) {
throw new I2CPMessageException("Error writing out the message data", dfe);
}
return os.toByteArray();
}
public int getType() {
return MESSAGE_TYPE;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("[RequestLeaseSetMessage: ");
buf.append("\n\tSessionId: ").append(getSessionId());
buf.append("\n\tTunnels:");
for (int i = 0; i < getEndpoints(); i++) {
buf.append("\n\t\tRouterIdentity: ").append(getRouter(i));
buf.append("\n\t\tTunnelId: ").append(getTunnelId(i));
}
buf.append("\n\tEndDate: ").append(getEndDate());
buf.append("]");
return buf.toString();
}
private static class TunnelEndpoint implements Serializable {
private static final long serialVersionUID = 1L;
private final Hash _router;
private final TunnelId _tunnelId;
public TunnelEndpoint(Hash router, TunnelId id) {
_router = router;
_tunnelId = id;
}
public Hash getRouter() {
return _router;
}
public TunnelId getTunnelId() {
return _tunnelId;
}
}
}
|
{
"pile_set_name": "Github"
}
|
{
"_args": [
[
"[email protected]",
"/Users/eshanker/Code/fsevents"
]
],
"_from": "[email protected]",
"_id": "[email protected]",
"_inBundle": true,
"_integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=",
"_location": "/fsevents/caseless",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "[email protected]",
"name": "caseless",
"escapedName": "caseless",
"rawSpec": "0.12.0",
"saveSpec": null,
"fetchSpec": "0.12.0"
},
"_requiredBy": [
"/fsevents/request"
],
"_resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
"_spec": "0.12.0",
"_where": "/Users/eshanker/Code/fsevents",
"author": {
"name": "Mikeal Rogers",
"email": "[email protected]"
},
"bugs": {
"url": "https://github.com/mikeal/caseless/issues"
},
"description": "Caseless object set/get/has, very useful when working with HTTP headers.",
"devDependencies": {
"tape": "^2.10.2"
},
"homepage": "https://github.com/mikeal/caseless#readme",
"keywords": [
"headers",
"http",
"caseless"
],
"license": "Apache-2.0",
"main": "index.js",
"name": "caseless",
"repository": {
"type": "git",
"url": "git+https://github.com/mikeal/caseless.git"
},
"scripts": {
"test": "node test.js"
},
"test": "node test.js",
"version": "0.12.0"
}
|
{
"pile_set_name": "Github"
}
|
name=Dragon's Claw
image=https://magiccards.info/scans/en/m12/206.jpg
value=2.385
rarity=U
type=Artifact
cost={2}
ability=Whenever a player casts a red spell, you may gain 1 life.
timing=artifact
oracle=Whenever a player casts a red spell, you may gain 1 life.
|
{
"pile_set_name": "Github"
}
|
---
Description: Defines the number of the code layer to be generated.
ms.assetid: ad67a6fb-4bb6-4550-a9e9-f5219f3868c6
title: layerNumber element
ms.topic: reference
ms.date: 05/31/2018
---
# layerNumber element
Defines the number of the code layer to be generated.
## Usage
``` syntax
<layerNumber/>
```
## Attributes
There are no attributes.
## Child elements
There are no child elements.
## Parent elements
| Element | Description |
|---------------------------------------------|--------------------------------------------------------------------------------------|
| [**wsdCodeGen**](wsdcodegen.md)<br/> | The root element of an WSDAPI code generator XML script file.<br/> <br/> |
## Remarks
Layer numbers are used in runtime tables to distinguish one layer of code for another. WSDAPI itself uses generated code that has a layer number of 0.
Typically, this value will be 1, indicating that the generated code is layered on top of WSDAPI and no other layer. In some cases, higher numbers may be used. For example, if one company produces code for a device class (numbered layer 1), a particular hardware vendor may want to add an additional layer numbered layer 2.
Legal values, except in the case of WSDAPI itself are greater than 0 and less than 16.
## Element information
| | |
|-------------------------------------|---------------|
| Minimum supported system<br/> | Windows Vista |
| Can be empty | Yes |
|
{
"pile_set_name": "Github"
}
|
From c7ab998ec52b09d61ec3c0ea62aa07cd26077ea3 Mon Sep 17 00:00:00 2001
From: Romain Naour <[email protected]>
Date: Mon, 3 Jul 2017 14:43:02 +0200
Subject: [PATCH] libunwind-arm: fix build failure due to asm()
The gcc documentation [1] suggest to use __asm__ instead of asm.
Fixes:
http://autobuild.buildroot.net/results/3ef/3efe156b6494e4392b6c31de447ee2c72acc1a53
[1] https://gcc.gnu.org/onlinedocs/gcc/Alternate-Keywords.html#Alternate-Keywords
Signed-off-by: Romain Naour <[email protected]>
Cc: Bernd Kuhls <[email protected]>
---
include/libunwind-arm.h | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/include/libunwind-arm.h b/include/libunwind-arm.h
index f208487..1c856fa 100644
--- a/include/libunwind-arm.h
+++ b/include/libunwind-arm.h
@@ -265,7 +265,7 @@ unw_tdep_context_t;
#ifndef __thumb__
#define unw_tdep_getcontext(uc) (({ \
unw_tdep_context_t *unw_ctx = (uc); \
- register unsigned long *unw_base asm ("r0") = unw_ctx->regs; \
+ register unsigned long *unw_base __asm__ ("r0") = unw_ctx->regs; \
__asm__ __volatile__ ( \
"stmia %[base], {r0-r15}" \
: : [base] "r" (unw_base) : "memory"); \
@@ -273,7 +273,7 @@ unw_tdep_context_t;
#else /* __thumb__ */
#define unw_tdep_getcontext(uc) (({ \
unw_tdep_context_t *unw_ctx = (uc); \
- register unsigned long *unw_base asm ("r0") = unw_ctx->regs; \
+ register unsigned long *unw_base __asm__ ("r0") = unw_ctx->regs; \
__asm__ __volatile__ ( \
".align 2\nbx pc\nnop\n.code 32\n" \
"stmia %[base], {r0-r15}\n" \
--
2.9.4
|
{
"pile_set_name": "Github"
}
|
A message has been posted to the {ForumName} forum at {SiteName}.
Follow this link to reply or see the full conversation: {MessageLink}
You are receiving this message because you indicated that you wanted to be notified of such messages.
If you don't want to be notified when others reply to this post click this link {UnsubscribeForumThreadLink}
If you no longer wish to be notified of new topics in this forum click this link {UnsubscribeForumLink}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2016 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#ifndef __MMHUB_V1_0_H__
#define __MMHUB_V1_0_H__
u64 mmhub_v1_0_get_fb_location(struct amdgpu_device *adev);
int mmhub_v1_0_gart_enable(struct amdgpu_device *adev);
void mmhub_v1_0_gart_disable(struct amdgpu_device *adev);
void mmhub_v1_0_set_fault_enable_default(struct amdgpu_device *adev,
bool value);
void mmhub_v1_0_init(struct amdgpu_device *adev);
int mmhub_v1_0_set_clockgating(struct amdgpu_device *adev,
enum amd_clockgating_state state);
void mmhub_v1_0_get_clockgating(struct amdgpu_device *adev, u32 *flags);
void mmhub_v1_0_initialize_power_gating(struct amdgpu_device *adev);
void mmhub_v1_0_update_power_gating(struct amdgpu_device *adev,
bool enable);
#endif
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Core
* @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Model for working with system.xml module files
*
* @category Mage
* @package Mage_Core
* @author Magento Core Team <[email protected]>
*/
class Mage_Core_Model_Config_System extends Mage_Core_Model_Config_Base
{
function __construct($sourceData=null)
{
parent::__construct($sourceData);
}
public function load($module)
{
$file = Mage::getConfig()->getModuleDir('etc', $module).DS.'system.xml';
$this->loadFile($file);
return $this;
}
}
|
{
"pile_set_name": "Github"
}
|
_________________________________________________________________
Copyright and Licensing Information for ACE(TM), TAO(TM), CIAO(TM),
DAnCE(TM), and CoSMIC(TM)
[1]ACE(TM), [2]TAO(TM), [3]CIAO(TM), DAnCE(TM), and [4]CoSMIC(TM)
(henceforth referred to as "DOC software") are copyrighted by
[5]Douglas C. Schmidt and his [6]research group at [7]Washington
University, [8]University of California, Irvine, and [9]Vanderbilt
University, Copyright (c) 1993-2012, all rights reserved. Since DOC
software is open-source, freely available software, you are free to
use, modify, copy, and distribute--perpetually and irrevocably--the
DOC software source code and object code produced from the source, as
well as copy and distribute modified versions of this software. You
must, however, include this copyright statement along with any code
built using DOC software that you release. No copyright statement
needs to be provided if you just ship binary executables of your
software products.
You can use DOC software in commercial and/or binary software releases
and are under no obligation to redistribute any of your source code
that is built using DOC software. Note, however, that you may not
misappropriate the DOC software code, such as copyrighting it yourself
or claiming authorship of the DOC software code, in a way that will
prevent DOC software from being distributed freely using an
open-source development model. You needn't inform anyone that you're
using DOC software in your software, though we encourage you to let
[10]us know so we can promote your project in the [11]DOC software
success stories.
The [12]ACE, [13]TAO, [14]CIAO, [15]DAnCE, and [16]CoSMIC web sites
are maintained by the [17]DOC Group at the [18]Institute for Software
Integrated Systems (ISIS) and the [19]Center for Distributed Object
Computing of Washington University, St. Louis for the development of
open-source software as part of the open-source software community.
Submissions are provided by the submitter ``as is'' with no warranties
whatsoever, including any warranty of merchantability, noninfringement
of third party intellectual property, or fitness for any particular
purpose. In no event shall the submitter be liable for any direct,
indirect, special, exemplary, punitive, or consequential damages,
including without limitation, lost profits, even if advised of the
possibility of such damages. Likewise, DOC software is provided as is
with no warranties of any kind, including the warranties of design,
merchantability, and fitness for a particular purpose,
noninfringement, or arising from a course of dealing, usage or trade
practice. Washington University, UC Irvine, Vanderbilt University,
their employees, and students shall have no liability with respect to
the infringement of copyrights, trade secrets or any patents by DOC
software or any part thereof. Moreover, in no event will Washington
University, UC Irvine, or Vanderbilt University, their employees, or
students be liable for any lost revenue or profits or other special,
indirect and consequential damages.
DOC software is provided with no support and without any obligation on
the part of Washington University, UC Irvine, Vanderbilt University,
their employees, or students to assist in its use, correction,
modification, or enhancement. A [20]number of companies around the
world provide commercial support for DOC software, however. DOC
software is Y2K-compliant, as long as the underlying OS platform is
Y2K-compliant. Likewise, DOC software is compliant with the new US
daylight savings rule passed by Congress as "The Energy Policy Act of
2005," which established new daylight savings times (DST) rules for
the United States that expand DST as of March 2007. Since DOC software
obtains time/date and calendaring information from operating systems
users will not be affected by the new DST rules as long as they
upgrade their operating systems accordingly.
The names ACE(TM), TAO(TM), CIAO(TM), DAnCE(TM), CoSMIC(TM),
Washington University, UC Irvine, and Vanderbilt University, may not
be used to endorse or promote products or services derived from this
source without express written permission from Washington University,
UC Irvine, or Vanderbilt University. This license grants no permission
to call products or services derived from this source ACE(TM),
TAO(TM), CIAO(TM), DAnCE(TM), or CoSMIC(TM), nor does it grant
permission for the name Washington University, UC Irvine, or
Vanderbilt University to appear in their names.
If you have any suggestions, additions, comments, or questions, please
let [21]me know.
[22]Douglas C. Schmidt
_________________________________________________________________
Back to the [23]ACE home page.
References
1. http://www.cs.wustl.edu/~schmidt/ACE.html
2. http://www.cs.wustl.edu/~schmidt/TAO.html
3. http://www.dre.vanderbilt.edu/CIAO/
4. http://www.dre.vanderbilt.edu/cosmic/
5. http://www.dre.vanderbilt.edu/~schmidt/
6. http://www.cs.wustl.edu/~schmidt/ACE-members.html
7. http://www.wustl.edu/
8. http://www.uci.edu/
9. http://www.vanderbilt.edu/
10. mailto:[email protected]
11. http://www.cs.wustl.edu/~schmidt/ACE-users.html
12. http://www.cs.wustl.edu/~schmidt/ACE.html
13. http://www.cs.wustl.edu/~schmidt/TAO.html
14. http://www.dre.vanderbilt.edu/CIAO/
15. http://www.dre.vanderbilt.edu/~schmidt/DOC_ROOT/DAnCE/
16. http://www.dre.vanderbilt.edu/cosmic/
17. http://www.dre.vanderbilt.edu/
18. http://www.isis.vanderbilt.edu/
19. http://www.cs.wustl.edu/~schmidt/doc-center.html
20. http://www.cs.wustl.edu/~schmidt/commercial-support.html
21. mailto:[email protected]
22. http://www.dre.vanderbilt.edu/~schmidt/
23. http://www.cs.wustl.edu/ACE.html
|
{
"pile_set_name": "Github"
}
|
package logs
import (
"bytes"
"io"
"github.com/litmuschaos/litmus/litmus-portal/cluster-agents/subscriber/pkg/k8s"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
)
func GetLogs(podName, namespace, container string) (string, error) {
conf, err := k8s.GetKubeConfig()
podLogOpts := v1.PodLogOptions{}
if container != "" {
podLogOpts.Container = container
}
if err != nil {
return "", err
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(conf)
if err != nil {
return "", err
}
req := clientset.CoreV1().Pods(namespace).GetLogs(podName, &podLogOpts)
podLogs, err := req.Stream()
if err != nil {
return "", err
}
defer podLogs.Close()
buf := new(bytes.Buffer)
_, err = io.Copy(buf, podLogs)
if err != nil {
return "", err
}
str := buf.String()
return str, nil
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.prefs;
import java.io.NotSerializableException;
/**
* An event emitted by a <tt>Preferences</tt> node to indicate that
* a child of that node has been added or removed.<p>
*
* Note, that although NodeChangeEvent inherits Serializable interface from
* java.util.EventObject, it is not intended to be Serializable. Appropriate
* serialization methods are implemented to throw NotSerializableException.
*
* @author Josh Bloch
* @see Preferences
* @see NodeChangeListener
* @see PreferenceChangeEvent
* @since 1.4
* @serial exclude
*/
public class NodeChangeEvent extends java.util.EventObject {
/**
* The node that was added or removed.
*
* @serial
*/
private Preferences child;
/**
* Constructs a new <code>NodeChangeEvent</code> instance.
*
* @param parent The parent of the node that was added or removed.
* @param child The node that was added or removed.
*/
public NodeChangeEvent(Preferences parent, Preferences child) {
super(parent);
this.child = child;
}
/**
* Returns the parent of the node that was added or removed.
*
* @return The parent Preferences node whose child was added or removed
*/
public Preferences getParent() {
return (Preferences) getSource();
}
/**
* Returns the node that was added or removed.
*
* @return The node that was added or removed.
*/
public Preferences getChild() {
return child;
}
/**
* Throws NotSerializableException, since NodeChangeEvent objects are not
* intended to be serializable.
*/
private void writeObject(java.io.ObjectOutputStream out)
throws NotSerializableException {
throw new NotSerializableException("Not serializable.");
}
/**
* Throws NotSerializableException, since NodeChangeEvent objects are not
* intended to be serializable.
*/
private void readObject(java.io.ObjectInputStream in)
throws NotSerializableException {
throw new NotSerializableException("Not serializable.");
}
// Defined so that this class isn't flagged as a potential problem when
// searches for missing serialVersionUID fields are done.
private static final long serialVersionUID = 8068949086596572957L;
}
|
{
"pile_set_name": "Github"
}
|
#ifdef BLOG_CURRENT_CHANNEL
#undef BLOG_CURRENT_CHANNEL
#endif
#define BLOG_CURRENT_CHANNEL BLOG_CHANNEL_ncd_net_ipv4_addr_in_network
|
{
"pile_set_name": "Github"
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:e126e58442748049e5fee162d4c854d7679e601c0ffc6b5b7ed0ba70ffc93457
size 2401190
|
{
"pile_set_name": "Github"
}
|
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#endif
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# 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 Google Inc. 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.
"""Verifies that test shuffling works."""
__author__ = '[email protected] (Zhanyong Wan)'
import os
import gtest_test_utils
# Command to run the gtest_shuffle_test_ program.
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_')
# The environment variables for test sharding.
TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
TEST_FILTER = 'A*.A:A*.B:C*'
ALL_TESTS = []
ACTIVE_TESTS = []
FILTERED_TESTS = []
SHARDED_TESTS = []
SHUFFLED_ALL_TESTS = []
SHUFFLED_ACTIVE_TESTS = []
SHUFFLED_FILTERED_TESTS = []
SHUFFLED_SHARDED_TESTS = []
def AlsoRunDisabledTestsFlag():
return '--gtest_also_run_disabled_tests'
def FilterFlag(test_filter):
return '--gtest_filter=%s' % (test_filter,)
def RepeatFlag(n):
return '--gtest_repeat=%s' % (n,)
def ShuffleFlag():
return '--gtest_shuffle'
def RandomSeedFlag(n):
return '--gtest_random_seed=%s' % (n,)
def RunAndReturnOutput(extra_env, args):
"""Runs the test program and returns its output."""
environ_copy = os.environ.copy()
environ_copy.update(extra_env)
return gtest_test_utils.Subprocess([COMMAND] + args, env=environ_copy).output
def GetTestsForAllIterations(extra_env, args):
"""Runs the test program and returns a list of test lists.
Args:
extra_env: a map from environment variables to their values
args: command line flags to pass to gtest_shuffle_test_
Returns:
A list where the i-th element is the list of tests run in the i-th
test iteration.
"""
test_iterations = []
for line in RunAndReturnOutput(extra_env, args).split('\n'):
if line.startswith('----'):
tests = []
test_iterations.append(tests)
elif line.strip():
tests.append(line.strip()) # 'TestCaseName.TestName'
return test_iterations
def GetTestCases(tests):
"""Returns a list of test cases in the given full test names.
Args:
tests: a list of full test names
Returns:
A list of test cases from 'tests', in their original order.
Consecutive duplicates are removed.
"""
test_cases = []
for test in tests:
test_case = test.split('.')[0]
if not test_case in test_cases:
test_cases.append(test_case)
return test_cases
def CalculateTestLists():
"""Calculates the list of tests run under different flags."""
if not ALL_TESTS:
ALL_TESTS.extend(
GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])
if not ACTIVE_TESTS:
ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])
if not FILTERED_TESTS:
FILTERED_TESTS.extend(
GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])
if not SHARDED_TESTS:
SHARDED_TESTS.extend(
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[])[0])
if not SHUFFLED_ALL_TESTS:
SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations(
{}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])
if not SHUFFLED_ACTIVE_TESTS:
SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1)])[0])
if not SHUFFLED_FILTERED_TESTS:
SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])
if not SHUFFLED_SHARDED_TESTS:
SHUFFLED_SHARDED_TESTS.extend(
GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[ShuffleFlag(), RandomSeedFlag(1)])[0])
class GTestShuffleUnitTest(gtest_test_utils.TestCase):
"""Tests test shuffling."""
def setUp(self):
CalculateTestLists()
def testShufflePreservesNumberOfTests(self):
self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS))
self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS))
self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS))
self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS))
def testShuffleChangesTestOrder(self):
self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS)
self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS,
SHUFFLED_FILTERED_TESTS)
self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS,
SHUFFLED_SHARDED_TESTS)
def testShuffleChangesTestCaseOrder(self):
self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
GetTestCases(SHUFFLED_ALL_TESTS))
self.assert_(
GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),
GetTestCases(SHUFFLED_ACTIVE_TESTS))
self.assert_(
GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),
GetTestCases(SHUFFLED_FILTERED_TESTS))
self.assert_(
GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),
GetTestCases(SHUFFLED_SHARDED_TESTS))
def testShuffleDoesNotRepeatTest(self):
for test in SHUFFLED_ALL_TESTS:
self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_ACTIVE_TESTS:
self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_FILTERED_TESTS:
self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test),
'%s appears more than once' % (test,))
for test in SHUFFLED_SHARDED_TESTS:
self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test),
'%s appears more than once' % (test,))
def testShuffleDoesNotCreateNewTest(self):
for test in SHUFFLED_ALL_TESTS:
self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_ACTIVE_TESTS:
self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_FILTERED_TESTS:
self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,))
for test in SHUFFLED_SHARDED_TESTS:
self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,))
def testShuffleIncludesAllTests(self):
for test in ALL_TESTS:
self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))
for test in ACTIVE_TESTS:
self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))
for test in FILTERED_TESTS:
self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,))
for test in SHARDED_TESTS:
self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))
def testShuffleLeavesDeathTestsAtFront(self):
non_death_test_found = False
for test in SHUFFLED_ACTIVE_TESTS:
if 'DeathTest.' in test:
self.assert_(not non_death_test_found,
'%s appears after a non-death test' % (test,))
else:
non_death_test_found = True
def _VerifyTestCasesDoNotInterleave(self, tests):
test_cases = []
for test in tests:
[test_case, _] = test.split('.')
if test_cases and test_cases[-1] != test_case:
test_cases.append(test_case)
self.assertEqual(1, test_cases.count(test_case),
'Test case %s is not grouped together in %s' %
(test_case, tests))
def testShuffleDoesNotInterleaveTestCases(self):
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS)
self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS)
def testShuffleRestoresOrderAfterEachIteration(self):
# Get the test lists in all 3 iterations, using random seed 1, 2,
# and 3 respectively. Google Test picks a different seed in each
# iteration, and this test depends on the current implementation
# picking successive numbers. This dependency is not ideal, but
# makes the test much easier to write.
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
# Make sure running the tests with random seed 1 gets the same
# order as in iteration 1 above.
[tests_with_seed1] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1)])
self.assertEqual(tests_in_iteration1, tests_with_seed1)
# Make sure running the tests with random seed 2 gets the same
# order as in iteration 2 above. Success means that Google Test
# correctly restores the test order before re-shuffling at the
# beginning of iteration 2.
[tests_with_seed2] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(2)])
self.assertEqual(tests_in_iteration2, tests_with_seed2)
# Make sure running the tests with random seed 3 gets the same
# order as in iteration 3 above. Success means that Google Test
# correctly restores the test order before re-shuffling at the
# beginning of iteration 3.
[tests_with_seed3] = GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(3)])
self.assertEqual(tests_in_iteration3, tests_with_seed3)
def testShuffleGeneratesNewOrderInEachIteration(self):
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
{}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
self.assert_(tests_in_iteration1 != tests_in_iteration2,
tests_in_iteration1)
self.assert_(tests_in_iteration1 != tests_in_iteration3,
tests_in_iteration1)
self.assert_(tests_in_iteration2 != tests_in_iteration3,
tests_in_iteration2)
def testShuffleShardedTestsPreservesPartition(self):
# If we run M tests on N shards, the same M tests should be run in
# total, regardless of the random seeds used by the shards.
[tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '0'},
[ShuffleFlag(), RandomSeedFlag(1)])
[tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '1'},
[ShuffleFlag(), RandomSeedFlag(20)])
[tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
SHARD_INDEX_ENV_VAR: '2'},
[ShuffleFlag(), RandomSeedFlag(25)])
sorted_sharded_tests = tests1 + tests2 + tests3
sorted_sharded_tests.sort()
sorted_active_tests = []
sorted_active_tests.extend(ACTIVE_TESTS)
sorted_active_tests.sort()
self.assertEqual(sorted_active_tests, sorted_sharded_tests)
if __name__ == '__main__':
gtest_test_utils.Main()
|
{
"pile_set_name": "Github"
}
|
FixedPointy
===========
A simple fixed-point math library for C#.
All standard math functions are implemented, with the exception of hyperbolic trig.
Precision can be configured by adjusting the FractionalBits constant in Fix.cs,
ranging from Q9.22 through Q23.8 formats.
Available under MIT license. See LICENSE.txt for details.
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
# coding:utf-8
# author: LandGrey
"""
Copyright (c) 2016-2017 LandGrey (https://github.com/LandGrey/pydictor)
License: GNU GENERAL PUBLIC LICENSE Version 3
"""
from __future__ import unicode_literals
from os.path import isfile
from lib.fun.decorator import magic
from lib.data.data import pyoptions
from lib.fun.fun import cool, finishcounter
def uniqifer_magic(*args):
"""[file]"""
args = list(args[0])
if len(args) == 2:
original_file_path = args[1]
if not isfile(original_file_path):
exit(pyoptions.CRLF + cool.red("[-] File: {} don't exists".format(original_file_path)))
else:
exit(pyoptions.CRLF + cool.fuchsia("[!] Usage: {} {}".format(args[0], pyoptions.tools_info.get(args[0]))))
@magic
def uniqifer():
with open(original_file_path) as o_f:
for item in o_f.readlines():
yield item.strip()
print("[+] Source of :{0} lines".format(cool.orange(finishcounter(original_file_path))))
|
{
"pile_set_name": "Github"
}
|
# SPDX-License-Identifier: GPL-2.0-only
obj-y += i2s_pll_clock.o
obj-y += pll_clock.o
|
{
"pile_set_name": "Github"
}
|
Bitcoin Core version 0.9.0 is now available from:
https://bitcoin.org/bin/0.9.0/
This is a new major version release, bringing both new features and
bug fixes.
Please report bugs using the issue tracker at github:
https://github.com/bitcoin/bitcoin/issues
How to Upgrade
--------------
If you are running an older version, shut it down. Wait until it has completely
shut down (which might take a few minutes for older versions), uninstall all
earlier versions of Bitcoin, then run the installer (on Windows) or just copy
over /Applications/Bitcoin-Qt (on Mac) or bitcoind/bitcoin-qt (on Linux).
If you are upgrading from version 0.7.2 or earlier, the first time you run
0.9.0 your blockchain files will be re-indexed, which will take anywhere from
30 minutes to several hours, depending on the speed of your machine.
On Windows, do not forget to uninstall all earlier versions of the Bitcoin
client first, especially if you are switching to the 64-bit version.
Windows 64-bit installer
-------------------------
New in 0.9.0 is the Windows 64-bit version of the client. There have been
frequent reports of users running out of virtual memory on 32-bit systems
during the initial sync. Because of this it is recommended to install the
64-bit version if your system supports it.
NOTE: Release candidate 2 Windows binaries are not code-signed; use PGP
and the SHA256SUMS.asc file to make sure your binaries are correct.
In the final 0.9.0 release, Windows setup.exe binaries will be code-signed.
OSX 10.5 / 32-bit no longer supported
-------------------------------------
0.9.0 drops support for older Macs. The minimum requirements are now:
* A 64-bit-capable CPU (see http://support.apple.com/kb/ht3696);
* Mac OS 10.6 or later (see https://support.apple.com/kb/ht1633).
Downgrading warnings
--------------------
The 'chainstate' for this release is not always compatible with previous
releases, so if you run 0.9 and then decide to switch back to a
0.8.x release you might get a blockchain validation error when starting the
old release (due to 'pruned outputs' being omitted from the index of
unspent transaction outputs).
Running the old release with the -reindex option will rebuild the chainstate
data structures and correct the problem.
Also, the first time you run a 0.8.x release on a 0.9 wallet it will rescan
the blockchain for missing spent coins, which will take a long time (tens
of minutes on a typical machine).
Rebranding to Bitcoin Core
---------------------------
To reduce confusion between Bitcoin-the-network and Bitcoin-the-software we
have renamed the reference client to Bitcoin Core.
OP_RETURN and data in the block chain
-------------------------------------
On OP_RETURN: There was been some confusion and misunderstanding in
the community, regarding the OP_RETURN feature in 0.9 and data in the
blockchain. This change is not an endorsement of storing data in the
blockchain. The OP_RETURN change creates a provably-prunable output,
to avoid data storage schemes -- some of which were already deployed --
that were storing arbitrary data such as images as forever-unspendable
TX outputs, bloating bitcoin's UTXO database.
Storing arbitrary data in the blockchain is still a bad idea; it is less
costly and far more efficient to store non-currency data elsewhere.
Autotools build system
-----------------------
For 0.9.0 we switched to an autotools-based build system instead of individual
(q)makefiles.
Using the standard "./autogen.sh; ./configure; make" to build Bitcoin-Qt and
bitcoind makes it easier for experienced open source developers to contribute
to the project.
Be sure to check doc/build-*.md for your platform before building from source.
Bitcoin-cli
-------------
Another change in the 0.9 release is moving away from the bitcoind executable
functioning both as a server and as a RPC client. The RPC client functionality
("tell the running bitcoin daemon to do THIS") was split into a separate
executable, 'bitcoin-cli'. The RPC client code will eventually be removed from
bitcoind, but will be kept for backwards compatibility for a release or two.
`walletpassphrase` RPC
-----------------------
The behavior of the `walletpassphrase` RPC when the wallet is already unlocked
has changed between 0.8 and 0.9.
The 0.8 behavior of `walletpassphrase` is to fail when the wallet is already unlocked:
> walletpassphrase 1000
walletunlocktime = now + 1000
> walletpassphrase 10
Error: Wallet is already unlocked (old unlock time stays)
The new behavior of `walletpassphrase` is to set a new unlock time overriding
the old one:
> walletpassphrase 1000
walletunlocktime = now + 1000
> walletpassphrase 10
walletunlocktime = now + 10 (overriding the old unlock time)
Transaction malleability-related fixes
--------------------------------------
This release contains a few fixes for transaction ID (TXID) malleability
issues:
- -nospendzeroconfchange command-line option, to avoid spending
zero-confirmation change
- IsStandard() transaction rules tightened to prevent relaying and mining of
mutated transactions
- Additional information in listtransactions/gettransaction output to
report wallet transactions that conflict with each other because
they spend the same outputs.
- Bug fixes to the getbalance/listaccounts RPC commands, which would report
incorrect balances for double-spent (or mutated) transactions.
- New option: -zapwallettxes to rebuild the wallet's transaction information
Transaction Fees
----------------
This release drops the default fee required to relay transactions across the
network and for miners to consider the transaction in their blocks to
0.01mBTC per kilobyte.
Note that getting a transaction relayed across the network does NOT guarantee
that the transaction will be accepted by a miner; by default, miners fill
their blocks with 50 kilobytes of high-priority transactions, and then with
700 kilobytes of the highest-fee-per-kilobyte transactions.
The minimum relay/mining fee-per-kilobyte may be changed with the
minrelaytxfee option. Note that previous releases incorrectly used
the mintxfee setting to determine which low-priority transactions should
be considered for inclusion in blocks.
The wallet code still uses a default fee for low-priority transactions of
0.1mBTC per kilobyte. During periods of heavy transaction volume, even this
fee may not be enough to get transactions confirmed quickly; the mintxfee
option may be used to override the default.
0.9.0 Release notes
=======================
RPC:
- New notion of 'conflicted' transactions, reported as confirmations: -1
- 'listreceivedbyaddress' now provides tx ids
- Add raw transaction hex to 'gettransaction' output
- Updated help and tests for 'getreceivedby(account|address)'
- In 'getblock', accept 2nd 'verbose' parameter, similar to getrawtransaction,
but defaulting to 1 for backward compatibility
- Add 'verifychain', to verify chain database at runtime
- Add 'dumpwallet' and 'importwallet' RPCs
- 'keypoolrefill' gains optional size parameter
- Add 'getbestblockhash', to return tip of best chain
- Add 'chainwork' (the total work done by all blocks since the genesis block)
to 'getblock' output
- Make RPC password resistant to timing attacks
- Clarify help messages and add examples
- Add 'getrawchangeaddress' call for raw transaction change destinations
- Reject insanely high fees by default in 'sendrawtransaction'
- Add RPC call 'decodescript' to decode a hex-encoded transaction script
- Make 'validateaddress' provide redeemScript
- Add 'getnetworkhashps' to get the calculated network hashrate
- New RPC 'ping' command to request ping, new 'pingtime' and 'pingwait' fields
in 'getpeerinfo' output
- Adding new 'addrlocal' field to 'getpeerinfo' output
- Add verbose boolean to 'getrawmempool'
- Add rpc command 'getunconfirmedbalance' to obtain total unconfirmed balance
- Explicitly ensure that wallet is unlocked in `importprivkey`
- Add check for valid keys in `importprivkey`
Command-line options:
- New option: -nospendzeroconfchange to never spend unconfirmed change outputs
- New option: -zapwallettxes to rebuild the wallet's transaction information
- Rename option '-tor' to '-onion' to better reflect what it does
- Add '-disablewallet' mode to let bitcoind run entirely without wallet (when
built with wallet)
- Update default '-rpcsslciphers' to include TLSv1.2
- make '-logtimestamps' default on and rework help-message
- RPC client option: '-rpcwait', to wait for server start
- Remove '-logtodebugger'
- Allow `-noserver` with bitcoind
Block-chain handling and storage:
- Update leveldb to 1.15
- Check for correct genesis (prevent cases where a datadir from the wrong
network is accidentally loaded)
- Allow txindex to be removed and add a reindex dialog
- Log aborted block database rebuilds
- Store orphan blocks in serialized form, to save memory
- Limit the number of orphan blocks in memory to 750
- Fix non-standard disconnected transactions causing mempool orphans
- Add a new checkpoint at block 279,000
Wallet:
- Bug fixes and new regression tests to correctly compute
the balance of wallets containing double-spent (or mutated) transactions
- Store key creation time. Calculate whole-wallet birthday.
- Optimize rescan to skip blocks prior to birthday
- Let user select wallet file with -wallet=foo.dat
- Consider generated coins mature at 101 instead of 120 blocks
- Improve wallet load time
- Don't count txins for priority to encourage sweeping
- Don't create empty transactions when reading a corrupted wallet
- Fix rescan to start from beginning after importprivkey
- Only create signatures with low S values
Mining:
- Increase default -blockmaxsize/prioritysize to 750K/50K
- 'getblocktemplate' does not require a key to create a block template
- Mining code fee policy now matches relay fee policy
Protocol and network:
- Drop the fee required to relay a transaction to 0.01mBTC per kilobyte
- Send tx relay flag with version
- New 'reject' P2P message (BIP 0061, see
https://gist.github.com/gavinandresen/7079034 for draft)
- Dump addresses every 15 minutes instead of 10 seconds
- Relay OP_RETURN data TxOut as standard transaction type
- Remove CENT-output free transaction rule when relaying
- Lower maximum size for free transaction creation
- Send multiple inv messages if mempool.size > MAX_INV_SZ
- Split MIN_PROTO_VERSION into INIT_PROTO_VERSION and MIN_PEER_PROTO_VERSION
- Do not treat fFromMe transaction differently when broadcasting
- Process received messages one at a time without sleeping between messages
- Improve logging of failed connections
- Bump protocol version to 70002
- Add some additional logging to give extra network insight
- Added new DNS seed from bitcoinstats.com
Validation:
- Log reason for non-standard transaction rejection
- Prune provably-unspendable outputs, and adapt consistency check for it.
- Detect any sufficiently long fork and add a warning
- Call the -alertnotify script when we see a long or invalid fork
- Fix multi-block reorg transaction resurrection
- Reject non-canonically-encoded serialization sizes
- Reject dust amounts during validation
- Accept nLockTime transactions that finalize in the next block
Build system:
- Switch to autotools-based build system
- Build without wallet by passing `--disable-wallet` to configure, this
removes the BerkeleyDB dependency
- Upgrade gitian dependencies (libpng, libz, libupnpc, boost, openssl) to more
recent versions
- Windows 64-bit build support
- Solaris compatibility fixes
- Check integrity of gitian input source tarballs
- Enable full GCC Stack-smashing protection for all OSes
GUI:
- Switch to Qt 5.2.0 for Windows build
- Add payment request (BIP 0070) support
- Improve options dialog
- Show transaction fee in new send confirmation dialog
- Add total balance in overview page
- Allow user to choose data directory on first start, when data directory is
missing, or when the -choosedatadir option is passed
- Save and restore window positions
- Add vout index to transaction id in transactions details dialog
- Add network traffic graph in debug window
- Add open URI dialog
- Add Coin Control Features
- Improve receive coins workflow: make the 'Receive' tab into a form to request
payments, and move historical address list functionality to File menu.
- Rebrand to `Bitcoin Core`
- Move initialization/shutdown to a thread. This prevents "Not responding"
messages during startup. Also show a window during shutdown.
- Don't regenerate autostart link on every client startup
- Show and store message of normal bitcoin:URI
- Fix richtext detection hang issue on very old Qt versions
- OS X: Make use of the 10.8+ user notification center to display Growl-like
notifications
- OS X: Added NSHighResolutionCapable flag to Info.plist for better font
rendering on Retina displays.
- OS X: Fix bitcoin-qt startup crash when clicking dock icon
- Linux: Fix Gnome bitcoin: URI handler
Miscellaneous:
- Add Linux script (contrib/qos/tc.sh) to limit outgoing bandwidth
- Add '-regtest' mode, similar to testnet but private with instant block
generation with 'setgenerate' RPC.
- Add 'linearize.py' script to contrib, for creating bootstrap.dat
- Add separate bitcoin-cli client
Credits
--------
Thanks to everyone who contributed to this release:
- Andrey
- Ashley Holman
- b6393ce9-d324-4fe1-996b-acf82dbc3d53
- bitsofproof
- Brandon Dahler
- Calvin Tam
- Christian Decker
- Christian von Roques
- Christopher Latham
- Chuck
- coblee
- constantined
- Cory Fields
- Cozz Lovan
- daniel
- Daniel Larimer
- David Hill
- Dmitry Smirnov
- Drak
- Eric Lombrozo
- fanquake
- fcicq
- Florin
- frewil
- Gavin Andresen
- Gregory Maxwell
- gubatron
- Guillermo Céspedes Tabárez
- Haakon Nilsen
- HaltingState
- Han Lin Yap
- harry
- Ian Kelling
- Jeff Garzik
- Johnathan Corgan
- Jonas Schnelli
- Josh Lehan
- Josh Triplett
- Julian Langschaedel
- Kangmo
- Lake Denman
- Luke Dashjr
- Mark Friedenbach
- Matt Corallo
- Michael Bauer
- Michael Ford
- Michagogo
- Midnight Magic
- Mike Hearn
- Nils Schneider
- Noel Tiernan
- Olivier Langlois
- patrick s
- Patrick Strateman
- paveljanik
- Peter Todd
- phantomcircuit
- phelixbtc
- Philip Kaufmann
- Pieter Wuille
- Rav3nPL
- R E Broadley
- regergregregerrge
- Robert Backhaus
- Roman Mindalev
- Rune K. Svendsen
- Ryan Niebur
- Scott Ellis
- Scott Willeke
- Sergey Kazenyuk
- Shawn Wilkinson
- Sined
- sje
- Subo1978
- super3
- Tamas Blummer
- theuni
- Thomas Holenstein
- Timon Rapp
- Timothy Stranex
- Tom Geller
- Torstein Husebø
- Vaclav Vobornik
- vhf / victor felder
- Vinnie Falco
- Warren Togami
- Wil Bown
- Wladimir J. van der Laan
|
{
"pile_set_name": "Github"
}
|
/**
* (C) Copyright 2020 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.
*
* GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE
* The Government's rights to use, modify, reproduce, release, perform, display,
* or disclose this software are subject to the terms of the Apache License as
* provided in Contract No. B609815.
* Any reproduction of computer software, computer software documentation, or
* portions thereof marked with this legend must also reproduce the markings.
*/
/**
* This file is part of the DAOS profile.
*/
#define D_LOGFAC DD_FAC(common)
#include <daos/common.h>
#include <daos/profile.h>
#include <daos_errno.h>
#include <gurt/list.h>
#define PF_MAX_NAME_SIZE 64
#define DEFAULT_CHUNK_SIZE 10240
#define DEFAULT_CHUNK_CNT_LIMIT 100
char *profile_op_names[] = {
[OBJ_PF_UPDATE_PREP] = "update_prep",
[OBJ_PF_UPDATE_DISPATCH] = "update_dispatch",
[OBJ_PF_UPDATE_LOCAL] = "update_local",
[OBJ_PF_UPDATE_END] = "update_end",
[OBJ_PF_BULK_TRANSFER] = "bulk_transfer",
[OBJ_PF_UPDATE_REPLY] = "update_repl",
[OBJ_PF_UPDATE] = "update",
[VOS_UPDATE_END] = "vos_update_end",
};
static void
profile_chunk_destroy(struct daos_profile_chunk *chunk)
{
d_list_del(&chunk->dpc_chunk_list);
D_FREE(chunk->dpc_chunks);
D_FREE_PTR(chunk);
}
static struct daos_profile_chunk *
profile_chunk_alloc(int chunk_size)
{
struct daos_profile_chunk *chunk;
D_ALLOC_PTR(chunk);
if (chunk == NULL)
return NULL;
D_INIT_LIST_HEAD(&chunk->dpc_chunk_list);
D_ALLOC(chunk->dpc_chunks, chunk_size * sizeof(*chunk->dpc_chunks));
chunk->dpc_chunk_size = chunk_size;
chunk->dpc_chunk_offset = 0;
if (chunk->dpc_chunks == NULL) {
profile_chunk_destroy(chunk);
return NULL;
}
return chunk;
}
static struct daos_profile *
profile_alloc(int op_cnt)
{
struct daos_profile *dp;
D_ALLOC_PTR(dp);
if (dp == NULL)
return NULL;
D_ALLOC_ARRAY(dp->dp_ops, op_cnt);
if (dp->dp_ops == NULL) {
D_FREE_PTR(dp);
return NULL;
}
dp->dp_ops_cnt = op_cnt;
return dp;
}
void
daos_profile_destroy(struct daos_profile *dp)
{
struct daos_profile_chunk *dpc;
struct daos_profile_chunk *tmp;
int i;
for (i = 0; i < dp->dp_ops_cnt; i++) {
struct daos_profile_op *dpo;
dpo = &dp->dp_ops[i];
d_list_for_each_entry_safe(dpc, tmp, &dpo->dpo_chunk_list,
dpc_chunk_list)
profile_chunk_destroy(dpc);
d_list_for_each_entry_safe(dpc, tmp, &dpo->dpo_chunk_idle_list,
dpc_chunk_list)
profile_chunk_destroy(dpc);
}
if (dp->dp_dir_path)
D_FREE(dp->dp_dir_path);
D_FREE_PTR(dp);
}
static int
profile_get_new_chunk(struct daos_profile_op *dpo)
{
struct daos_profile_chunk *chunk;
if (!d_list_empty(&dpo->dpo_chunk_idle_list)) {
/* Try to get one from idle list */
chunk = d_list_entry(dpo->dpo_chunk_idle_list.next,
struct daos_profile_chunk,
dpc_chunk_list);
d_list_move_tail(&chunk->dpc_chunk_list, &dpo->dpo_chunk_list);
dpo->dpo_chunk_cnt++;
D_ASSERT(chunk->dpc_chunk_offset == 0);
D_ASSERT(dpo->dpo_chunk_cnt <= dpo->dpo_chunk_total_cnt);
} else if (dpo->dpo_chunk_total_cnt < DEFAULT_CHUNK_CNT_LIMIT) {
/* Allocate new one */
chunk = profile_chunk_alloc(DEFAULT_CHUNK_SIZE);
if (chunk == NULL)
return -DER_NOMEM;
d_list_add_tail(&chunk->dpc_chunk_list,
&dpo->dpo_chunk_list);
dpo->dpo_chunk_total_cnt++;
dpo->dpo_chunk_cnt++;
} else {
/* Reach the limit, Let's reuse the oldest (i.e. 1st) in list */
chunk = d_list_entry(dpo->dpo_chunk_list.next,
struct daos_profile_chunk,
dpc_chunk_list);
D_DEBUG(DB_TRACE, "Reuse the old profile buffer %p\n", chunk);
}
dpo->dpo_current_chunk = chunk;
return 0;
}
static int
profile_op_init(struct daos_profile_op *dpo, int id, char *name)
{
int rc;
dpo->dpo_op = id;
dpo->dpo_op_name = name;
D_INIT_LIST_HEAD(&dpo->dpo_chunk_list);
D_INIT_LIST_HEAD(&dpo->dpo_chunk_idle_list);
dpo->dpo_acc_cnt = 0;
dpo->dpo_acc_val = 0;
dpo->dpo_chunk_total_cnt = 0;
dpo->dpo_chunk_cnt = 0;
rc = profile_get_new_chunk(dpo);
return rc;
}
static void
profile_chunk_next(struct daos_profile_op *dpo)
{
struct daos_profile_chunk *chunk = dpo->dpo_current_chunk;
if (dpo->dpo_acc_cnt == 0)
return;
D_ASSERT(chunk != NULL);
D_ASSERT(chunk->dpc_chunk_offset <= chunk->dpc_chunk_size);
chunk->dpc_chunks[chunk->dpc_chunk_offset] =
dpo->dpo_acc_val / dpo->dpo_acc_cnt;
chunk->dpc_chunk_offset++;
dpo->dpo_acc_val = 0;
dpo->dpo_acc_cnt = 0;
}
static int
profile_dump_chunk(struct daos_profile_op *dpo, FILE *file,
struct daos_profile_chunk *dpc)
{
char string[PF_MAX_NAME_SIZE] = { 0 };
int rc = 0;
int i;
for (i = 0; i < dpc->dpc_chunk_offset; i++) {
size_t size;
memset(string, 0, PF_MAX_NAME_SIZE);
/* Dump name and time cost to the file */
snprintf(string, PF_MAX_NAME_SIZE, "%s "DF_U64"\n",
dpo->dpo_op_name, dpc->dpc_chunks[i]);
size = fwrite(string, 1, strlen(string), file);
if (size != strlen(string)) {
D_ERROR("dump failed: %s\n", strerror(errno));
rc = daos_errno2der(errno);
break;
}
}
return rc;
}
void
daos_profile_dump(struct daos_profile *dp)
{
FILE *file;
char name[PF_MAX_NAME_SIZE] = { 0 };
char *path;
int rc;
int i;
if (dp->dp_dir_path) {
D_ALLOC(path, strlen(dp->dp_dir_path) + PF_MAX_NAME_SIZE);
if (path == NULL) {
rc = -DER_NOMEM;
D_ERROR("start dump ult failed: rc "DF_RC"\n",
DP_RC(rc));
return;
}
sprintf(name, "/profile-%d-%d.dump", dp->dp_rank, dp->dp_xid);
strcpy(path, dp->dp_dir_path);
strcat(path, name);
} else {
sprintf(name, "./profile-%d-%d.dump", dp->dp_rank, dp->dp_xid);
path = name;
}
file = fopen(path, "a");
if (file == NULL) {
rc = daos_errno2der(errno);
D_ERROR("open %s: %s\n", path, strerror(errno));
goto out;
}
for (i = 0; i < dp->dp_ops_cnt; i++) {
struct daos_profile_op *dpo;
struct daos_profile_chunk *dpc;
struct daos_profile_chunk *tmp;
dpo = &dp->dp_ops[i];
d_list_for_each_entry_safe(dpc, tmp,
&dpo->dpo_chunk_list,
dpc_chunk_list) {
if (dpc == dpo->dpo_current_chunk)
/* Close the current one */
profile_chunk_next(&dp->dp_ops[i]);
if (dpc->dpc_chunk_offset > 0)
dp->dp_empty = 0;
rc = profile_dump_chunk(dpo, file, dpc);
if (rc)
break;
/* move the spc to idle list */
dpo->dpo_chunk_cnt--;
dpc->dpc_chunk_offset = 0;
d_list_move_tail(&dpc->dpc_chunk_list,
&dpo->dpo_chunk_idle_list);
}
}
fclose(file);
if (dp->dp_empty)
unlink(path);
out:
if (path != name)
free(path);
}
int
daos_profile_init(struct daos_profile **dp_p, char *path, int avg, int rank,
int tgt_id)
{
struct daos_profile *dp;
int i;
int rc;
dp = profile_alloc(PF_MAX_CNT);
if (dp == NULL)
return -DER_NOMEM;
dp->dp_empty = 1;
D_ASSERT(ARRAY_SIZE(profile_op_names) == PF_MAX_CNT);
for (i = 0; i < PF_MAX_CNT; i++) {
rc = profile_op_init(&dp->dp_ops[i], i, profile_op_names[i]);
if (rc)
D_GOTO(out, rc);
}
if (path != NULL) {
D_ALLOC(dp->dp_dir_path, strlen(path) + 1);
if (dp->dp_dir_path == NULL)
D_GOTO(out, rc = -DER_NOMEM);
strcpy(dp->dp_dir_path, path);
}
dp->dp_avg = avg;
dp->dp_xid = tgt_id;
dp->dp_rank = rank;
*dp_p = dp;
out:
if (rc && dp != NULL)
daos_profile_destroy(dp);
return rc;
}
int
daos_profile_count(struct daos_profile *dp, int id, int val)
{
struct daos_profile_chunk *current;
struct daos_profile_op *dpo;
dpo = &dp->dp_ops[id];
dpo->dpo_acc_val += val;
dpo->dpo_acc_cnt++;
if (dpo->dpo_acc_cnt >= dp->dp_avg && dp->dp_avg != -1) {
D_ASSERT(dpo->dpo_current_chunk != NULL);
current = dpo->dpo_current_chunk;
/* Current profile chunk is full, get a new one */
if (current->dpc_chunk_offset == current->dpc_chunk_size) {
int rc;
rc = profile_get_new_chunk(dpo);
if (rc)
return rc;
}
profile_chunk_next(dpo);
}
return 0;
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h>
#include <Box2D/Common/b2BlockAllocator.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <new>
using namespace std;
b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
{
void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact));
return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB);
}
void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
{
((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact();
allocator->Free(contact, sizeof(b2PolygonAndCircleContact));
}
b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
: b2Contact(fixtureA, 0, fixtureB, 0)
{
b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon);
b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
}
void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
{
b2CollidePolygonAndCircle( manifold,
(b2PolygonShape*)m_fixtureA->GetShape(), xfA,
(b2CircleShape*)m_fixtureB->GetShape(), xfB);
}
|
{
"pile_set_name": "Github"
}
|
{
"name": "KeenClient",
"version": "3.2.2",
"license": "MIT",
"platforms": {
"ios": null
},
"summary": "Keen iOS client library.",
"homepage": "https://github.com/keenlabs/KeenClient-iOS",
"authors": {
"Daniel Kador": "[email protected]"
},
"source": {
"git": "https://github.com/keenlabs/KeenClient-iOS.git",
"tag": "v3.2.2"
},
"description": "The Keen iOS client is designed to be simple to develop with, yet incredibly flexible. Our goal is to let you decide what events are important to you, use your own vocabulary to describe them, and decide when you want to send them to Keen service.",
"source_files": "KeenClient",
"ios": {
"frameworks": "CoreLocation"
},
"dependencies": {
"JSONKit": [
"~> 1.4"
],
"ISO8601DateFormatter": [
">= 0.6"
]
},
"requires_arc": false
}
|
{
"pile_set_name": "Github"
}
|
title: DataStax Node.js Driver
summary: DataStax Node.js Driver for Apache Cassandra
theme: datastax
swiftype_drivers: nodejsdrivers
sections:
- title: Features
prefix: /features
type: markdown
files: 'doc/features/**/*.md'
- title: Frequently Asked Questions
prefix: /faq
type: markdown
files: 'doc/faq/**/*.md'
- title: Getting Started
prefix: /getting-started
type: markdown
files: 'doc/getting-started/**/*.md'
- title: Three simple rules for coding with the driver
prefix: /coding-rules
type: markdown
files: 'doc/coding-rules/**/*.md'
- title: Upgrade Guide
prefix: /upgrade-guide
type: markdown
files: 'doc/upgrade-guide/**/*.md'
- title: API docs
prefix: /api
type: jsdoc
config: doc/jsdoc.json
links:
- title: Code
href: https://github.com/datastax/nodejs-driver/
- title: Issues
href: https://datastax-oss.atlassian.net/projects/NODEJS/issues
- title: Mailing List
href: https://groups.google.com/a/lists.datastax.com/forum/#!forum/nodejs-driver-user
- title: Npm
href: https://www.npmjs.org/package/cassandra-driver
versions:
- name: '4.6'
ref: 'master'
- name: '4.5'
ref: '4.5'
- name: '4.4'
ref: '4.4'
- name: '4.3'
ref: '4.3'
- name: '4.2'
ref: '4.2'
- name: '4.1'
ref: '4.1'
- name: '4.0'
ref: '4.0'
- name: '3.6'
ref: '3.6'
- name: '3.5'
ref: '3.5'
- name: '3.4'
ref: '3.4'
- name: '3.3'
ref: '3.3'
- name: '3.2'
ref: '3.2'
- name: '3.1'
ref: '3.1'
- name: '3.0'
ref: '3.0'
|
{
"pile_set_name": "Github"
}
|
# Copyright (C) 2007, 2011, One Laptop Per Child
# Copyright (C) 2014, Ignacio Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
from gettext import gettext as _
from gi.repository import GObject
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gdk
import pickle
import xapian
import json
import tempfile
import shutil
from sugar3.graphics.radiotoolbutton import RadioToolButton
from sugar3.graphics.palette import Palette
from sugar3.graphics import style
from sugar3 import env
from sugar3 import profile
from jarabe.journal import model
from jarabe.journal.misc import get_mount_icon_name
from jarabe.journal.misc import get_mount_color
from jarabe.view.palettes import VolumePalette
_JOURNAL_0_METADATA_DIR = '.olpc.store'
def _get_id(document):
"""Get the ID for the document in the xapian database."""
tl = document.termlist()
try:
term = tl.skip_to('Q').term
if len(term) == 0 or term[0] != 'Q':
return None
return term[1:]
except StopIteration:
return None
def _convert_entries(root):
"""Convert entries written by the datastore version 0.
The metadata and the preview will be written using the new
scheme for writing Journal entries to removable storage
devices.
- entries that do not have an associated file are not
converted.
- if an entry has no title we set it to Untitled and rename
the file accordingly, taking care of creating a unique
filename
"""
try:
database = xapian.Database(os.path.join(root, _JOURNAL_0_METADATA_DIR,
'index'))
except xapian.DatabaseError:
logging.exception('Convert DS-0 Journal entries: error reading db: %s',
os.path.join(root, _JOURNAL_0_METADATA_DIR, 'index'))
return
metadata_dir_path = os.path.join(root, model.JOURNAL_METADATA_DIR)
if not os.path.exists(metadata_dir_path):
try:
os.mkdir(metadata_dir_path)
except EnvironmentError:
logging.error('Convert DS-0 Journal entries: '
'error creating the Journal metadata directory.')
return
for posting_item in database.postlist(''):
try:
document = database.get_document(posting_item.docid)
except xapian.DocNotFoundError as e:
logging.debug('Convert DS-0 Journal entries: error getting '
'document %s: %s', posting_item.docid, e)
continue
_convert_entry(root, document)
def _convert_entry(root, document):
try:
metadata_loaded = pickle.loads(document.get_data())
except pickle.PickleError as e:
logging.debug('Convert DS-0 Journal entries: '
'error converting metadata: %s', e)
return
if not ('activity_id' in metadata_loaded and
'mime_type' in metadata_loaded and
'title' in metadata_loaded):
return
metadata = {}
uid = _get_id(document)
if uid is None:
return
for key, value in list(metadata_loaded.items()):
metadata[str(key)] = str(value[0])
if 'uid' not in metadata:
metadata['uid'] = uid
filename = metadata.pop('filename', None)
if not filename:
return
if not os.path.exists(os.path.join(root, filename)):
return
if not metadata.get('title'):
metadata['title'] = _('Untitled')
fn = model.get_file_name(metadata['title'],
metadata['mime_type'])
new_filename = model.get_unique_file_name(root, fn)
os.rename(os.path.join(root, filename),
os.path.join(root, new_filename))
filename = new_filename
preview_path = os.path.join(root, _JOURNAL_0_METADATA_DIR,
'preview', uid)
if os.path.exists(preview_path):
preview_fname = filename + '.preview'
new_preview_path = os.path.join(root,
model.JOURNAL_METADATA_DIR,
preview_fname)
if not os.path.exists(new_preview_path):
shutil.copy(preview_path, new_preview_path)
metadata_fname = filename + '.metadata'
metadata_path = os.path.join(root, model.JOURNAL_METADATA_DIR,
metadata_fname)
if not os.path.exists(metadata_path):
(fh, fn) = tempfile.mkstemp(dir=root)
os.write(fh, json.dumps(metadata))
os.close(fh)
os.rename(fn, metadata_path)
logging.debug('Convert DS-0 Journal entries: entry converted: '
'file=%s metadata=%s',
os.path.join(root, filename), metadata)
class VolumesToolbar(Gtk.Toolbar):
__gtype_name__ = 'VolumesToolbar'
__gsignals__ = {
'volume-changed': (GObject.SignalFlags.RUN_FIRST, None,
([str])),
'volume-error': (GObject.SignalFlags.RUN_FIRST, None,
([str, str])),
}
def __init__(self):
Gtk.Toolbar.__init__(self)
self._mount_added_hid = None
self._mount_removed_hid = None
button = JournalButton()
button.connect('toggled', self._button_toggled_cb)
self.insert(button, 0)
button.show()
self._volume_buttons = [button]
self.connect('destroy', self.__destroy_cb)
GLib.idle_add(self._set_up_volumes)
def __destroy_cb(self, widget):
volume_monitor = Gio.VolumeMonitor.get()
volume_monitor.disconnect(self._mount_added_hid)
volume_monitor.disconnect(self._mount_removed_hid)
def _set_up_volumes(self):
self._set_up_documents_button()
volume_monitor = Gio.VolumeMonitor.get()
self._mount_added_hid = volume_monitor.connect('mount-added',
self.__mount_added_cb)
self._mount_removed_hid = volume_monitor.connect(
'mount-removed',
self.__mount_removed_cb)
for mount in volume_monitor.get_mounts():
self._add_button(mount)
def _set_up_documents_button(self):
documents_path = model.get_documents_path()
if documents_path is not None:
button = DocumentsButton(documents_path)
button.props.group = self._volume_buttons[0]
button.set_palette(Palette(_('Documents')))
button.connect('toggled', self._button_toggled_cb)
button.show()
position = self.get_item_index(self._volume_buttons[-1]) + 1
self.insert(button, position)
self._volume_buttons.append(button)
self.show()
def __mount_added_cb(self, volume_monitor, mount):
self._add_button(mount)
def __mount_removed_cb(self, volume_monitor, mount):
self._remove_button(mount)
def _add_button(self, mount):
logging.debug('VolumeToolbar._add_button: %r', mount.get_name())
if os.path.exists(os.path.join(mount.get_root().get_path(),
_JOURNAL_0_METADATA_DIR)):
logging.debug('Convert DS-0 Journal entries: starting conversion')
GLib.idle_add(_convert_entries, mount.get_root().get_path())
button = VolumeButton(mount)
button.props.group = self._volume_buttons[0]
button.connect('toggled', self._button_toggled_cb)
button.connect('volume-error', self.__volume_error_cb)
position = self.get_item_index(self._volume_buttons[-1]) + 1
self.insert(button, position)
button.show()
self._volume_buttons.append(button)
if len(self.get_children()) > 1:
self.show()
def __volume_error_cb(self, button, strerror, severity):
self.emit('volume-error', strerror, severity)
def _button_toggled_cb(self, button):
if button.props.active:
self.emit('volume-changed', button.mount_point)
def _get_button_for_mount(self, mount):
mount_point = mount.get_root().get_path()
for button in self.get_children():
if button.mount_point == mount_point:
return button
logging.error('Couldnt find button with mount_point %r', mount_point)
return None
def _remove_button(self, mount):
button = self._get_button_for_mount(mount)
self._volume_buttons.remove(button)
self.remove(button)
self.get_children()[0].props.active = True
if len(self.get_children()) < 2:
self.hide()
def set_active_volume(self, mount):
button = self._get_button_for_mount(mount)
button.props.active = True
class BaseButton(RadioToolButton):
__gsignals__ = {
'volume-error': (GObject.SignalFlags.RUN_FIRST, None,
([str, str])),
}
def __init__(self, mount_point):
RadioToolButton.__init__(self)
self.mount_point = mount_point
self.drag_dest_set(Gtk.DestDefaults.ALL,
[Gtk.TargetEntry.new('journal-object-id', 0, 0)],
Gdk.DragAction.COPY)
self.connect('drag-data-received', self._drag_data_received_cb)
def _drag_data_received_cb(self, widget, drag_context, x, y,
selection_data, info, timestamp):
object_id = selection_data.get_data()
metadata = model.get(object_id)
file_path = model.get_file(metadata['uid'])
if not file_path or not os.path.exists(file_path):
logging.warn('Entries without a file cannot be copied.')
self.emit('volume-error',
_('Entries without a file cannot be copied.'),
_('Warning'))
return
try:
model.copy(metadata, self.mount_point)
except IOError as e:
logging.exception('Error while copying the entry. %s', e.strerror)
self.emit('volume-error',
_('Error while copying the entry. %s') % e.strerror,
_('Error'))
class VolumeButton(BaseButton):
def __init__(self, mount):
self._mount = mount
mount_point = mount.get_root().get_path()
BaseButton.__init__(self, mount_point)
self.props.icon_name = get_mount_icon_name(mount,
Gtk.IconSize.LARGE_TOOLBAR)
# TODO: retrieve the colors from the owner of the device
self.props.xo_color = get_mount_color(self._mount)
def create_palette(self):
palette = VolumePalette(self._mount)
# palette.props.invoker = FrameWidgetInvoker(self)
# palette.set_group_id('frame')
return palette
class JournalButton(BaseButton):
def __init__(self):
BaseButton.__init__(self, mount_point='/')
self.props.icon_name = 'activity-journal'
self.props.xo_color = profile.get_color()
def create_palette(self):
palette = JournalButtonPalette(self)
return palette
class JournalButtonPalette(Palette):
def __init__(self, mount):
Palette.__init__(self, _('Journal'))
grid = Gtk.Grid(orientation=Gtk.Orientation.VERTICAL,
margin=style.DEFAULT_SPACING,
row_spacing=style.DEFAULT_SPACING)
self.set_content(grid)
grid.show()
self._progress_bar = Gtk.ProgressBar()
grid.add(self._progress_bar)
self._progress_bar.show()
self._free_space_label = Gtk.Label()
self._free_space_label.set_alignment(0.5, 0.5)
grid.add(self._free_space_label)
self._free_space_label.show()
self.connect('popup', self.__popup_cb)
def __popup_cb(self, palette):
stat = os.statvfs(env.get_profile_path())
free_space = stat[0] * stat[4]
total_space = stat[0] * stat[2]
fraction = (total_space - free_space) / float(total_space)
self._progress_bar.props.fraction = fraction
self._free_space_label.props.label = _('%(free_space)d MiB Free') % \
{'free_space': free_space / (1024 * 1024)}
class DocumentsButton(BaseButton):
def __init__(self, documents_path):
BaseButton.__init__(self, mount_point=documents_path)
self.props.icon_name = 'user-documents'
self.props.xo_color = profile.get_color()
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2013-2014 EditShare, 2013-2015 Skytechnology sp. z o.o.
This file is part of LizardFS.
LizardFS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3.
LizardFS 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with LizardFS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common/platform.h"
#include "common/io_limits_config_loader.h"
#include <limits>
#include "common/exceptions.h"
#include "common/io_limit_group.h"
inline static bool streamReadFailed(const std::istream& stream) {
return stream.eof() || stream.fail() || stream.bad();
}
void IoLimitsConfigLoader::load(std::istream&& stream) {
limits_.clear();
bool cgroupsInUse = false;
while (!stream.eof()) {
std::string command;
std::string group;
uint64_t limit;
stream >> command;
if (streamReadFailed(stream)) {
if (stream.eof()) {
break;
}
throw ParseException("Unexpected end of file.");
}
if (command == "subsystem") {
stream >> subsystem_;
if (streamReadFailed(stream)) {
throw ParseException("Incorrect file format.");
}
} else if (command == "limit") {
stream >> group >> limit;
if (streamReadFailed(stream)) {
throw ParseException("Incorrect file format.");
} else if (limits_.find(group) != limits_.end()) {
throw ParseException("Limit for group '" + group +
"' specified more then once.");
}
limits_[group] = limit;
cgroupsInUse |= (group != kUnclassified);
} else if (!command.empty() && command.front() == '#') {
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} else {
throw ParseException("Unknown keyword '" + command + "'.");
}
}
if (cgroupsInUse && subsystem_.empty()) {
throw ParseException("Subsystem not specified.");
}
}
|
{
"pile_set_name": "Github"
}
|
export const environment = {
production: true
};
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html class='reftest-wait'>
<link rel='stylesheet' type='text/css' href='style.css'>
<script>
function loadHandler()
{
document.getElementById('t').removeAttribute('placeholder');
document.getElementById('moz').removeAttribute('placeholder');
document.documentElement.className = '';
}
</script>
<body onload='loadHandler();'>
<textarea id='t' placeholder='foo'></textarea>
<textarea id='moz' placeholder='bar'></textarea>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MyDll")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MyDll")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("711cc3c2-07db-46ca-b34b-ba06f4edcbcd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: a8e5fc2691065574f92a65bac244d4f1
timeCreated: 1504416773
licenseType: Free
NativeFormatImporter:
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Ui\Component\Form\Element;
use Magento\Framework\Data\OptionSourceInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
/**
* Base abstract form element.
*
* phpcs:disable Magento2.Classes.AbstractApi
* @api
* @since 100.1.0
*/
abstract class AbstractOptionsField extends AbstractElement
{
/**
* @var array|OptionSourceInterface|null
* @since 100.1.0
*/
protected $options;
/**
* Constructor
*
* @param ContextInterface $context
* @param array|OptionSourceInterface|null $options
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
$options = null,
array $components = [],
array $data = []
) {
$this->options = $options;
parent::__construct($context, $components, $data);
}
/**
* Prepare component configuration
*
* @return void
* @since 100.1.0
*/
public function prepare()
{
$config = $this->getData('config');
if (isset($this->options)) {
if (!isset($config['options'])) {
$config['options'] = [];
}
if ($this->options instanceof OptionSourceInterface) {
$options = $this->options->toOptionArray();
} else {
$options = array_values($this->options);
}
if (empty($config['rawOptions'])) {
$options = $this->convertOptionsValueToString($options);
}
array_walk(
$options,
function (&$item) {
$item['__disableTmpl'] = true;
}
);
$config['options'] = array_values(array_replace_recursive($config['options'], $options));
}
$this->setData('config', (array)$config);
parent::prepare();
}
/**
* Check if option value
*
* @param string $optionValue
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
* @since 100.1.0
*/
abstract public function getIsSelected($optionValue);
/**
* Convert options value to string
*
* @param array $options
* @return array
* @since 100.1.0
*/
protected function convertOptionsValueToString(array $options)
{
array_walk(
$options,
function (&$value) {
if (isset($value['value']) && is_scalar($value['value'])) {
$value['value'] = (string)$value['value'];
}
}
);
return $options;
}
}
|
{
"pile_set_name": "Github"
}
|
from __future__ import print_function
import traceback
import dsz
import ops
from util.DSZPyLogger import DSZPyLogger
DEFAULT_LOG = 'OPS'
_debug_enabled = False
_pass_through = {}
def register_passthrough(extype, content):
if (extype not in _pass_through):
_pass_through[extype] = []
tcontent = (content if (type(content) is tuple) else (content,))
if (tcontent not in _pass_through[extype]):
_pass_through[extype].append(tcontent)
class CriticalError(Exception, ):
pass
CRITICAL_ERROR_TEXT = 'Critical error. Script should terminate.'
BUGCATCHER_CAUGHT = '::caught by bugcatcher::'
USER_QUIT_SCRIPT_TEXT = 'User QUIT script'
register_passthrough(RuntimeError, USER_QUIT_SCRIPT_TEXT)
register_passthrough(CriticalError, CRITICAL_ERROR_TEXT)
def error(s, log=DEFAULT_LOG):
logger = DSZPyLogger().getLogger(log)
logger.error(s)
def warn(s, log=DEFAULT_LOG):
logger = DSZPyLogger().getLogger(log)
logger.warn(s)
def debug(s, log=DEFAULT_LOG):
if _debug_enabled:
logger = DSZPyLogger().getLogger(log)
logger.debug(s)
return _debug_enabled
def bugcatcher(bug_func, bug_log=DEFAULT_LOG, bug_critical=True, **kwargs):
ret = None
try:
return (True, bug_func(**kwargs))
except Exception as e:
dsz.script.CheckStop()
if (type(e) in _pass_through):
for i in _pass_through[type(e)]:
if (e.args == i):
raise
print()
if bug_critical:
error((((((str(type(e)) + ' : ') + ''.join([(i.encode('utf8') if (type(i) is unicode) else str(i)) for i in e.args])) + '\n--\n') + traceback.format_exc()) + '--\n'), bug_log)
print('This is considered a critical functionality error. Script will not continue.')
else:
warn((((((str(type(e)) + ' : ') + ''.join([(i.encode('utf8') if (type(i) is unicode) else str(i)) for i in e.args])) + '\n--\n') + traceback.format_exc()) + '--\n'), bug_log)
print('This is considered a non-critical functionality error.')
print(("An error report for this problem as been automatically generated in OPLOGS '%s'" % bug_log))
if (not bug_critical):
print('Verify it is safe to continue. The default response here is to assume it is not and quit.')
else:
print('Assuming it is not safe to continue under these conditions.')
if (bug_critical or (not dsz.ui.Prompt('Is it safe to continue running this script?', False))):
raise CriticalError(CRITICAL_ERROR_TEXT, BUGCATCHER_CAUGHT)
return (False, e)
def wasCaught(e):
return (e.args == (CRITICAL_ERROR_TEXT, BUGCATCHER_CAUGHT))
def userQuitScript(e):
return (e.args == (USER_QUIT_SCRIPT_TEXT,))
if (__name__ == '__main__'):
def testfunc():
raise RuntimeError, 'foo'
try:
print(bugcatcher((lambda : dsz.ui.Prompt('Yes/No/Quit?')), 'TEST'))
print(bugcatcher(testfunc, 'TEST'))
except Exception as e:
if (not wasCaught(e)):
raise
|
{
"pile_set_name": "Github"
}
|
/*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
import MapKit
/// A protocol used by the `MessagesViewController` to customize the appearance of a `MessageContentCell`.
public protocol MessagesDisplayDelegate: AnyObject {
// MARK: - All Messages
/// Specifies the `MessageStyle` to be used for a `MessageContainerView`.
///
/// - Parameters:
/// - message: The `MessageType` that will be displayed by this cell.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// The default value returned by this method is `MessageStyle.bubble`.
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle
/// Specifies the background color of the `MessageContainerView`.
///
/// - Parameters:
/// - message: The `MessageType` that will be displayed by this cell.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// The default value is `UIColor.clear` for emoji messages.
/// For all other `MessageKind` cases, the color depends on the `Sender`.
///
/// Current sender: Green
///
/// All other senders: Gray
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor
/// The section header to use for a given `IndexPath`.
///
/// - Parameters:
/// - message: The `MessageType` that will be displayed for this header.
/// - indexPath: The `IndexPath` of the header.
/// - messagesCollectionView: The `MessagesCollectionView` in which this header will be displayed.
func messageHeaderView(for indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageReusableView
/// The section footer to use for a given `IndexPath`.
///
/// - Parameters:
/// - indexPath: The `IndexPath` of the footer.
/// - messagesCollectionView: The `MessagesCollectionView` in which this footer will be displayed.
func messageFooterView(for indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageReusableView
/// Used to configure the `AvatarView`‘s image in a `MessageContentCell` class.
///
/// - Parameters:
/// - avatarView: The `AvatarView` of the cell.
/// - message: The `MessageType` that will be displayed by this cell.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// The default image configured by this method is `?`.
func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView)
// MARK: - Text Messages
/// Specifies the color of the text for a `TextMessageCell`.
///
/// - Parameters:
/// - message: A `MessageType` with a `MessageKind` case of `.text` to which the color will apply.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// The default value returned by this method is determined by the messages `Sender`.
///
/// Current sender: UIColor.white
///
/// All other senders: UIColor.darkText
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor
/// Specifies the `DetectorType`s to check for the `MessageType`'s text against.
///
/// - Parameters:
/// - message: A `MessageType` with a `MessageKind` case of `.text` or `.attributedText` to which the detectors will apply.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// This method returns an empty array by default.
func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType]
/// Specifies the attributes for a given `DetectorType`
///
/// - Parameters:
/// - detector: The `DetectorType` for the applied attributes.
/// - message: A `MessageType` with a `MessageKind` case of `.text` or `.attributedText` to which the detectors will apply.
/// - indexPath: The `IndexPath` of the cell.
func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedString.Key: Any]
// MARK: - Location Messages
/// Used to configure a `LocationMessageSnapshotOptions` instance to customize the map image on the given location message.
///
/// - Parameters:
/// - message: A `MessageType` with a `MessageKind` case of `.location`.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` requesting the information.
/// - Returns: The LocationMessageSnapshotOptions instance with the options to customize map style.
func snapshotOptionsForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> LocationMessageSnapshotOptions
/// Used to configure the annoation view of the map image on the given location message.
///
/// - Parameters:
/// - message: A `MessageType` with a `MessageKind` case of `.location`.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` requesting the information.
/// - Returns: The `MKAnnotationView` to use as the annotation view.
func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView?
/// Ask the delegate for a custom animation block to run when whe map screenshot is ready to be displaied in the given location message.
/// The animation block is called with the `UIImageView` to be animated.
///
/// - Parameters:
/// - message: A `MessageType` with a `MessageKind` case of `.location`.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` requesting the information.
/// - Returns: The animation block to use to apply the location image.
func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)?
// MARK: - Media Messages
/// Used to configure the `UIImageView` of a `MediaMessageCell.
///
/// - Parameters:
/// - imageView: The `UIImageView` of the cell.
/// - message: The `MessageType` that will be displayed by this cell.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
func configureMediaMessageImageView(_ imageView: UIImageView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView)
}
public extension MessagesDisplayDelegate {
// MARK: - All Messages Defaults
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
return .bubble
}
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
switch message.kind {
case .emoji:
return .clear
default:
guard let dataSource = messagesCollectionView.messagesDataSource else { return .white }
return dataSource.isFromCurrentSender(message: message) ? .outgoingGreen : .incomingGray
}
}
func messageHeaderView(for indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageReusableView {
return messagesCollectionView.dequeueReusableHeaderView(MessageReusableView.self, for: indexPath)
}
func messageFooterView(for indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageReusableView {
return messagesCollectionView.dequeueReusableFooterView(MessageReusableView.self, for: indexPath)
}
func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
avatarView.initials = "?"
}
// MARK: - Text Messages Defaults
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
guard let dataSource = messagesCollectionView.messagesDataSource else {
fatalError(MessageKitError.nilMessagesDataSource)
}
return dataSource.isFromCurrentSender(message: message) ? .white : .darkText
}
func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] {
return []
}
func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedString.Key: Any] {
return MessageLabel.defaultAttributes
}
// MARK: - Location Messages Defaults
func snapshotOptionsForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> LocationMessageSnapshotOptions {
return LocationMessageSnapshotOptions()
}
func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
return MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
}
func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
return nil
}
// MARK: - Media Message Defaults
func configureMediaMessageImageView(_ imageView: UIImageView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
}
}
|
{
"pile_set_name": "Github"
}
|
30.times do |i|
puts "Test case #{i}..."
system "ruby gen.rb > rand.in"
system "./ac < rand.in > right.out"
system "./ana < rand.in > wrong.out"
system "diff right.out wrong.out"
unless $?.success?
break
end
end
system "rm right.out wrong.out"
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <SystemUIPlugin/NSMenuExtra.h>
#import "NSMachPortDelegate-Protocol.h"
#import "NSMenuDelegate-Protocol.h"
@class CLKClockExtraPreferences, CLKParentalControls, NSMachPort, NSMenuItem, NSString, NSTimer;
@interface AppleClockExtra : NSMenuExtra <NSMachPortDelegate, NSMenuDelegate>
{
CLKClockExtraPreferences *preferences;
CLKParentalControls *parentalControls;
NSMachPort *calendarChangedReceiveMachPort;
NSTimer *systemDateChangedTimer;
NSTimer *updateOpenMenuTimer;
NSMenuItem *fullClockMenuItem;
NSMenuItem *parentalControlsTitleMenuItem;
NSMenuItem *parentalControlsTimeLimitMenuItem;
NSMenuItem *parentalControlsSeparatorMenuItem;
NSMenuItem *switchToAnalogMenuItem;
NSMenuItem *switchToDigitalMenuItem;
}
- (void)runSelfTest:(unsigned int)arg1 duration:(double)arg2;
- (void)_runSelfTest:(unsigned int)arg1 duration:(double)arg2 iteration:(int)arg3 pauseBetweenTests:(double)arg4;
- (void)_testDigitalClockFormatByShowingSeconds:(BOOL)arg1 showAMPM:(BOOL)arg2 showDayOfTheWeek:(BOOL)arg3 showDayOfTheMonth:(BOOL)arg4 showMonth:(BOOL)arg5 use24Hours:(BOOL)arg6 flashDateSeparators:(BOOL)arg7 iteration:(int)arg8;
- (void)_testSwitchToAnalog:(BOOL)arg1 expectedViewClass:(Class)arg2 iteration:(int)arg3;
- (void)_testSleep:(double)arg1;
- (BOOL)convertedForNewUI;
- (id)AXDescription;
- (id)AXValue;
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4;
- (void)setupClockExtraByDeferringViewSwap:(BOOL)arg1;
- (void)_setup;
- (void)_forceToUpdateSuperviews;
- (void)willUnload;
- (void)_bindView:(id)arg1;
- (void)_unbindAndInvalidateView;
- (void)dealloc;
- (void)finalize;
- (id)initWithBundle:(id)arg1;
- (void)menuDidClose:(id)arg1;
- (void)menuWillOpen:(id)arg1;
- (void)_stopUpdateOpenMenuTimer;
- (void)_startUpdateOpenMenuTimer;
- (void)_updateOpenMenuTimer:(id)arg1;
- (void)_menuActionOpenPrefPane:(id)arg1;
- (void)_menuActionSwitchToDigital:(id)arg1;
- (void)_menuActionSwitchToAnalog:(id)arg1;
- (id)menu;
- (void)_updateParentalControlsMenuItems;
- (void)_updateFullClockMenuItem;
- (id)_dateFormatterForMenu;
- (id)_buildMenu;
- (void)_unregisterForSystemAwakeNotification;
- (void)_registerForSystemAwakeNotification;
- (void)_systemAwakeNotification:(id)arg1;
- (void)_unregisterForSystemDateNotifications;
- (void)_registerForSystemDateNotifications;
- (void)_systemDateNotificationHandler:(id)arg1;
- (void)_unregisterForLegacyClockNotification;
- (void)_registerForLegacyClockNotification;
- (void)_legacyClockNotificationHandler:(id)arg1;
- (void)_clockSettingsDidChange:(id)arg1;
- (void)_startSystemDateChangedTimer;
- (void)_stopSystemDateChangedTimer;
- (void)_systemDateChangedTimerCallback:(id)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
{
"pile_set_name": "Github"
}
|
<template>
<div class="entry-title">
<h1 itemprop="title">
<factor-link :path="postLink(post._id)">{{ post.title }}</factor-link>
</h1>
<span
v-if="post.jobLocation"
itemprop="jobLocation"
itemscope
itemtype="http://schema.org/Place"
class="location"
>{{ post.jobLocation }}</span>
</div>
</template>
<script lang="ts">
import { factorLink } from "@factor/ui"
import { stored, postLink } from "@factor/api"
export default {
components: { factorLink },
props: {
postId: { type: String, default: "" },
},
computed: {
post(this: any) {
return stored(this.postId) || {}
},
},
methods: { postLink },
}
</script>
<style lang="less">
.plugin-jobs {
.entry-title {
display: grid;
grid-template-columns: 1fr 200px;
h1 {
display: inline-block;
max-width: 65%;
font-size: 1.6em;
font-weight: var(--font-weight-bold, 700);
line-height: 1.2;
a {
color: inherit;
}
@media (max-width: 767px) {
display: block;
max-width: 100%;
}
}
.location {
float: right;
font-size: 0.9em;
line-height: 1.8em;
color: var(--color-text-secondary);
letter-spacing: 0.1em;
text-transform: uppercase;
text-align: right;
@media (max-width: 767px) {
float: none;
text-align: left;
}
}
@media (max-width: 767px) {
display: flex;
flex-direction: column-reverse;
}
}
}
</style>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.sasl;
import javax.security.auth.callback.CallbackHandler;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;
/**
* A static class for creating SASL clients and servers.
*<p>
* This class defines the policy of how to locate, load, and instantiate
* SASL clients and servers.
*<p>
* For example, an application or library gets a SASL client by doing
* something like:
*<blockquote><pre>
* SaslClient sc = Sasl.createSaslClient(mechanisms,
* authorizationId, protocol, serverName, props, callbackHandler);
*</pre></blockquote>
* It can then proceed to use the instance to create an authentication connection.
*<p>
* Similarly, a server gets a SASL server by using code that looks as follows:
*<blockquote><pre>
* SaslServer ss = Sasl.createSaslServer(mechanism,
* protocol, serverName, props, callbackHandler);
*</pre></blockquote>
*
* @since 1.5
*
* @author Rosanna Lee
* @author Rob Weltman
*/
public class Sasl {
// Cannot create one of these
private Sasl() {
}
/**
* The name of a property that specifies the quality-of-protection to use.
* The property contains a comma-separated, ordered list
* of quality-of-protection values that the
* client or server is willing to support. A qop value is one of
* <ul>
* <li>{@code "auth"} - authentication only</li>
* <li>{@code "auth-int"} - authentication plus integrity protection</li>
* <li>{@code "auth-conf"} - authentication plus integrity and confidentiality
* protection</li>
* </ul>
*
* The order of the list specifies the preference order of the client or
* server. If this property is absent, the default qop is {@code "auth"}.
* The value of this constant is {@code "javax.security.sasl.qop"}.
*/
public static final String QOP = "javax.security.sasl.qop";
/**
* The name of a property that specifies the cipher strength to use.
* The property contains a comma-separated, ordered list
* of cipher strength values that
* the client or server is willing to support. A strength value is one of
* <ul>
* <li>{@code "low"}</li>
* <li>{@code "medium"}</li>
* <li>{@code "high"}</li>
* </ul>
* The order of the list specifies the preference order of the client or
* server. An implementation should allow configuration of the meaning
* of these values. An application may use the Java Cryptography
* Extension (JCE) with JCE-aware mechanisms to control the selection of
* cipher suites that match the strength values.
* <BR>
* If this property is absent, the default strength is
* {@code "high,medium,low"}.
* The value of this constant is {@code "javax.security.sasl.strength"}.
*/
public static final String STRENGTH = "javax.security.sasl.strength";
/**
* The name of a property that specifies whether the
* server must authenticate to the client. The property contains
* {@code "true"} if the server must
* authenticate the to client; {@code "false"} otherwise.
* The default is {@code "false"}.
* <br>The value of this constant is
* {@code "javax.security.sasl.server.authentication"}.
*/
public static final String SERVER_AUTH =
"javax.security.sasl.server.authentication";
/**
* The name of a property that specifies the bound server name for
* an unbound server. A server is created as an unbound server by setting
* the {@code serverName} argument in {@link #createSaslServer} as null.
* The property contains the bound host name after the authentication
* exchange has completed. It is only available on the server side.
* <br>The value of this constant is
* {@code "javax.security.sasl.bound.server.name"}.
*/
public static final String BOUND_SERVER_NAME =
"javax.security.sasl.bound.server.name";
/**
* The name of a property that specifies the maximum size of the receive
* buffer in bytes of {@code SaslClient}/{@code SaslServer}.
* The property contains the string representation of an integer.
* <br>If this property is absent, the default size
* is defined by the mechanism.
* <br>The value of this constant is {@code "javax.security.sasl.maxbuffer"}.
*/
public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer";
/**
* The name of a property that specifies the maximum size of the raw send
* buffer in bytes of {@code SaslClient}/{@code SaslServer}.
* The property contains the string representation of an integer.
* The value of this property is negotiated between the client and server
* during the authentication exchange.
* <br>The value of this constant is {@code "javax.security.sasl.rawsendsize"}.
*/
public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize";
/**
* The name of a property that specifies whether to reuse previously
* authenticated session information. The property contains "true" if the
* mechanism implementation may attempt to reuse previously authenticated
* session information; it contains "false" if the implementation must
* not reuse previously authenticated session information. A setting of
* "true" serves only as a hint: it does not necessarily entail actual
* reuse because reuse might not be possible due to a number of reasons,
* including, but not limited to, lack of mechanism support for reuse,
* expiration of reusable information, and the peer's refusal to support
* reuse.
*
* The property's default value is "false". The value of this constant
* is "javax.security.sasl.reuse".
*
* Note that all other parameters and properties required to create a
* SASL client/server instance must be provided regardless of whether
* this property has been supplied. That is, you cannot supply any less
* information in anticipation of reuse.
*
* Mechanism implementations that support reuse might allow customization
* of its implementation, for factors such as cache size, timeouts, and
* criteria for reusability. Such customizations are
* implementation-dependent.
*/
public static final String REUSE = "javax.security.sasl.reuse";
/**
* The name of a property that specifies
* whether mechanisms susceptible to simple plain passive attacks (e.g.,
* "PLAIN") are not permitted. The property
* contains {@code "true"} if such mechanisms are not permitted;
* {@code "false"} if such mechanisms are permitted.
* The default is {@code "false"}.
* <br>The value of this constant is
* {@code "javax.security.sasl.policy.noplaintext"}.
*/
public static final String POLICY_NOPLAINTEXT =
"javax.security.sasl.policy.noplaintext";
/**
* The name of a property that specifies whether
* mechanisms susceptible to active (non-dictionary) attacks
* are not permitted.
* The property contains {@code "true"}
* if mechanisms susceptible to active attacks
* are not permitted; {@code "false"} if such mechanisms are permitted.
* The default is {@code "false"}.
* <br>The value of this constant is
* {@code "javax.security.sasl.policy.noactive"}.
*/
public static final String POLICY_NOACTIVE =
"javax.security.sasl.policy.noactive";
/**
* The name of a property that specifies whether
* mechanisms susceptible to passive dictionary attacks are not permitted.
* The property contains {@code "true"}
* if mechanisms susceptible to dictionary attacks are not permitted;
* {@code "false"} if such mechanisms are permitted.
* The default is {@code "false"}.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.policy.nodictionary"}.
*/
public static final String POLICY_NODICTIONARY =
"javax.security.sasl.policy.nodictionary";
/**
* The name of a property that specifies whether mechanisms that accept
* anonymous login are not permitted. The property contains {@code "true"}
* if mechanisms that accept anonymous login are not permitted;
* {@code "false"}
* if such mechanisms are permitted. The default is {@code "false"}.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.policy.noanonymous"}.
*/
public static final String POLICY_NOANONYMOUS =
"javax.security.sasl.policy.noanonymous";
/**
* The name of a property that specifies whether mechanisms that implement
* forward secrecy between sessions are required. Forward secrecy
* means that breaking into one session will not automatically
* provide information for breaking into future sessions.
* The property
* contains {@code "true"} if mechanisms that implement forward secrecy
* between sessions are required; {@code "false"} if such mechanisms
* are not required. The default is {@code "false"}.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.policy.forward"}.
*/
public static final String POLICY_FORWARD_SECRECY =
"javax.security.sasl.policy.forward";
/**
* The name of a property that specifies whether
* mechanisms that pass client credentials are required. The property
* contains {@code "true"} if mechanisms that pass
* client credentials are required; {@code "false"}
* if such mechanisms are not required. The default is {@code "false"}.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.policy.credentials"}.
*/
public static final String POLICY_PASS_CREDENTIALS =
"javax.security.sasl.policy.credentials";
/**
* The name of a property that specifies the credentials to use.
* The property contains a mechanism-specific Java credential object.
* Mechanism implementations may examine the value of this property
* to determine whether it is a class that they support.
* The property may be used to supply credentials to a mechanism that
* supports delegated authentication.
*<br>
* The value of this constant is
* {@code "javax.security.sasl.credentials"}.
*/
public static final String CREDENTIALS = "javax.security.sasl.credentials";
/**
* Creates a {@code SaslClient} using the parameters supplied.
*
* This method uses the
* {@extLink security_guide_jca JCA Security Provider Framework},
* described in the
* "Java Cryptography Architecture (JCA) Reference Guide", for
* locating and selecting a {@code SaslClient} implementation.
*
* First, it
* obtains an ordered list of {@code SaslClientFactory} instances from
* the registered security providers for the "SaslClientFactory" service
* and the specified SASL mechanism(s). It then invokes
* {@code createSaslClient()} on each factory instance on the list
* until one produces a non-null {@code SaslClient} instance. It returns
* the non-null {@code SaslClient} instance, or null if the search fails
* to produce a non-null {@code SaslClient} instance.
*<p>
* A security provider for SaslClientFactory registers with the
* JCA Security Provider Framework keys of the form <br>
* {@code SaslClientFactory.}<em>{@code mechanism_name}</em>
* <br>
* and values that are class names of implementations of
* {@code javax.security.sasl.SaslClientFactory}.
*
* For example, a provider that contains a factory class,
* {@code com.wiz.sasl.digest.ClientFactory}, that supports the
* "DIGEST-MD5" mechanism would register the following entry with the JCA:
* {@code SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory}
*<p>
* See the
* "Java Cryptography Architecture API Specification & Reference"
* for information about how to install and configure security service
* providers.
*
* @implNote
* The JDK Reference Implementation additionally uses the
* {@code jdk.security.provider.preferred}
* {@link Security#getProperty(String) Security} property to determine
* the preferred provider order for the specified algorithm. This
* may be different than the order of providers returned by
* {@link Security#getProviders() Security.getProviders()}.
*
* @param mechanisms The non-null list of mechanism names to try. Each is the
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param authorizationId The possibly null protocol-dependent
* identification to be used for authorization.
* If null or empty, the server derives an authorization
* ID from the client's authentication credentials.
* When the SASL authentication completes successfully,
* the specified entity is granted access.
*
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
*
* @param serverName The non-null fully-qualified host name of the server
* to authenticate to.
*
* @param props The possibly null set of properties used to
* select the SASL mechanism and to configure the authentication
* exchange of the selected mechanism.
* For example, if {@code props} contains the
* {@code Sasl.POLICY_NOPLAINTEXT} property with the value
* {@code "true"}, then the selected
* SASL mechanism must not be susceptible to simple plain passive attacks.
* In addition to the standard properties declared in this class,
* other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a {@code NameCallback}.
* The password is requested by using a {@code PasswordCallback}.
* The realm is requested by using a {@code RealmChoiceCallback} if there is a list
* of realms to choose from, and by using a {@code RealmCallback} if
* the realm must be entered.
*
*@return A possibly null {@code SaslClient} created using the parameters
* supplied. If null, cannot find a {@code SaslClientFactory}
* that will produce one.
*@exception SaslException If cannot create a {@code SaslClient} because
* of an error.
*/
public static SaslClient createSaslClient(
String[] mechanisms,
String authorizationId,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
SaslClient mech = null;
SaslClientFactory fac;
Service service;
String mechName;
for (int i = 0; i < mechanisms.length; i++) {
if ((mechName=mechanisms[i]) == null) {
throw new NullPointerException(
"Mechanism name cannot be null");
} else if (mechName.length() == 0) {
continue;
}
String type = "SaslClientFactory";
Provider[] provs = Security.getProviders(type + "." + mechName);
if (provs != null) {
for (Provider p : provs) {
service = p.getService(type, mechName);
if (service == null) {
// no such service exists
continue;
}
fac = (SaslClientFactory) loadFactory(service);
if (fac != null) {
mech = fac.createSaslClient(
new String[]{mechanisms[i]}, authorizationId,
protocol, serverName, props, cbh);
if (mech != null) {
return mech;
}
}
}
}
}
return null;
}
private static Object loadFactory(Service service)
throws SaslException {
try {
/*
* Load the implementation class with the same class loader
* that was used to load the provider.
* In order to get the class loader of a class, the
* caller's class loader must be the same as or an ancestor of
* the class loader being returned. Otherwise, the caller must
* have "getClassLoader" permission, or a SecurityException
* will be thrown.
*/
return service.newInstance(null);
} catch (InvalidParameterException | NoSuchAlgorithmException e) {
throw new SaslException("Cannot instantiate service " + service, e);
}
}
/**
* Creates a {@code SaslServer} for the specified mechanism.
*
* This method uses the
* {@extLink security_guide_jca JCA Security Provider Framework},
* described in the
* "Java Cryptography Architecture (JCA) Reference Guide", for
* locating and selecting a {@code SaslClient} implementation.
*
* First, it
* obtains an ordered list of {@code SaslServerFactory} instances from
* the registered security providers for the "SaslServerFactory" service
* and the specified mechanism. It then invokes
* {@code createSaslServer()} on each factory instance on the list
* until one produces a non-null {@code SaslServer} instance. It returns
* the non-null {@code SaslServer} instance, or null if the search fails
* to produce a non-null {@code SaslServer} instance.
*<p>
* A security provider for SaslServerFactory registers with the
* JCA Security Provider Framework keys of the form <br>
* {@code SaslServerFactory.}<em>{@code mechanism_name}</em>
* <br>
* and values that are class names of implementations of
* {@code javax.security.sasl.SaslServerFactory}.
*
* For example, a provider that contains a factory class,
* {@code com.wiz.sasl.digest.ServerFactory}, that supports the
* "DIGEST-MD5" mechanism would register the following entry with the JCA:
* {@code SaslServerFactory.DIGEST-MD5 com.wiz.sasl.digest.ServerFactory}
*<p>
* See the
* "Java Cryptography Architecture API Specification & Reference"
* for information about how to install and configure security
* service providers.
*
* @implNote
* The JDK Reference Implementation additionally uses the
* {@code jdk.security.provider.preferred}
* {@link Security#getProperty(String) Security} property to determine
* the preferred provider order for the specified algorithm. This
* may be different than the order of providers returned by
* {@link Security#getProviders() Security.getProviders()}.
*
* @param mechanism The non-null mechanism name. It must be an
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param protocol The non-null string name of the protocol for which
* the authentication is being performed (e.g., "ldap").
* @param serverName The fully qualified host name of the server, or null
* if the server is not bound to any specific host name. If the mechanism
* does not allow an unbound server, a {@code SaslException} will
* be thrown.
* @param props The possibly null set of properties used to
* select the SASL mechanism and to configure the authentication
* exchange of the selected mechanism.
* For example, if {@code props} contains the
* {@code Sasl.POLICY_NOPLAINTEXT} property with the value
* {@code "true"}, then the selected
* SASL mechanism must not be susceptible to simple plain passive attacks.
* In addition to the standard properties declared in this class,
* other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored,
* including any map entries with non-String keys.
*
* @param cbh The possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library
* to complete the authentication. For example, a SASL mechanism might
* require the authentication ID, password and realm from the caller.
* The authentication ID is requested by using a {@code NameCallback}.
* The password is requested by using a {@code PasswordCallback}.
* The realm is requested by using a {@code RealmChoiceCallback} if there is a list
* of realms to choose from, and by using a {@code RealmCallback} if
* the realm must be entered.
*
*@return A possibly null {@code SaslServer} created using the parameters
* supplied. If null, cannot find a {@code SaslServerFactory}
* that will produce one.
*@exception SaslException If cannot create a {@code SaslServer} because
* of an error.
**/
public static SaslServer
createSaslServer(String mechanism,
String protocol,
String serverName,
Map<String,?> props,
javax.security.auth.callback.CallbackHandler cbh)
throws SaslException {
SaslServer mech = null;
SaslServerFactory fac;
Service service;
if (mechanism == null) {
throw new NullPointerException("Mechanism name cannot be null");
} else if (mechanism.length() == 0) {
return null;
}
String type = "SaslServerFactory";
Provider[] provs = Security.getProviders(type + "." + mechanism);
if (provs != null) {
for (Provider p : provs) {
service = p.getService(type, mechanism);
if (service == null) {
throw new SaslException("Provider does not support " +
mechanism + " " + type);
}
fac = (SaslServerFactory) loadFactory(service);
if (fac != null) {
mech = fac.createSaslServer(
mechanism, protocol, serverName, props, cbh);
if (mech != null) {
return mech;
}
}
}
}
return null;
}
/**
* Gets an enumeration of known factories for producing {@code SaslClient}.
* This method uses the same algorithm for locating factories as
* {@code createSaslClient()}.
* @return A non-null enumeration of known factories for producing
* {@code SaslClient}.
* @see #createSaslClient
*/
public static Enumeration<SaslClientFactory> getSaslClientFactories() {
Set<Object> facs = getFactories("SaslClientFactory");
final Iterator<Object> iter = facs.iterator();
return new Enumeration<SaslClientFactory>() {
public boolean hasMoreElements() {
return iter.hasNext();
}
public SaslClientFactory nextElement() {
return (SaslClientFactory)iter.next();
}
};
}
/**
* Gets an enumeration of known factories for producing {@code SaslServer}.
* This method uses the same algorithm for locating factories as
* {@code createSaslServer()}.
* @return A non-null enumeration of known factories for producing
* {@code SaslServer}.
* @see #createSaslServer
*/
public static Enumeration<SaslServerFactory> getSaslServerFactories() {
Set<Object> facs = getFactories("SaslServerFactory");
final Iterator<Object> iter = facs.iterator();
return new Enumeration<SaslServerFactory>() {
public boolean hasMoreElements() {
return iter.hasNext();
}
public SaslServerFactory nextElement() {
return (SaslServerFactory)iter.next();
}
};
}
private static Set<Object> getFactories(String serviceName) {
HashSet<Object> result = new HashSet<Object>();
if ((serviceName == null) || (serviceName.length() == 0) ||
(serviceName.endsWith("."))) {
return result;
}
Provider[] provs = Security.getProviders();
Object fac;
for (Provider p : provs) {
Iterator<Service> iter = p.getServices().iterator();
while (iter.hasNext()) {
Service s = iter.next();
if (s.getType().equals(serviceName)) {
try {
fac = loadFactory(s);
if (fac != null) {
result.add(fac);
}
} catch (Exception ignore) {
}
}
}
}
return Collections.unmodifiableSet(result);
}
}
|
{
"pile_set_name": "Github"
}
|
(*
Copyright © 2011, 2012 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with Opa. If not, see <http://www.gnu.org/licenses/>.
*)
(*
-------------------
| cactUTF section |
-------------------
*)
(*
* Note of the authors:
*
* Beware of the stings !
**)
type unicode = int
type unicode_index = int
type bytes_index = int
let (@>) s pos =
int_of_char(s.[pos])
(*
FIXME: wild error management, incorrect
*)
exception Error of string
let myerror s = raise (Error s)
let warning_or_error s =
if true then prerr_endline s else myerror s
(* END OF FIXME *)
exception Lenbytes of int
let pre_lenbytes i =
if (i < 128) then
1
else if (i < 192) then
raise (Lenbytes i)
else if (i < 224) then
2
else if (i < 240) then
3
else
4
(*
For one Unicode code, return the number of bytes needed for
a representation in UTF-8.
*)
let lenbytes i =
try
pre_lenbytes i
with
Lenbytes i ->
warning_or_error (Printf.sprintf "bslCactutf.lenbytes : invalid UTF8 opcode: %d" i);
1
(* determine if a bytechar is the first of a utf-8 char *)
let is_first_char i = i < 128 || 192 <= i
let is_middle_char i = 128 <= i && i < 192
(*
** prev()
** Return the index of the first utf8-char before or at the given char.
*)
let prev_first_char str i =
let len = Bytes.length str in
if i>= len then myerror (Printf.sprintf "prev_first_char : index too big (i=%d, len=%d)" i len);
let rec aux i =
if i<0 then myerror "prev_first_char : reach the begin of the string"
else (if is_middle_char (str @> i) then aux (i-1) else i)
in aux i
(*
(*register prev : string -> int -> int*)
let prev_first_char s n =
let i4 = s @> (n - 1)
in
if (i4 < 128) then (* one byte *)
n - 1
else if (i4 >= 192) then (* 0b11xxxxxx *)
myerror "cactutf.opa : prev : error in UTF8 [1]"
else
let i3 = s @> (n - 2)
in
if (i3 < 128) then (* 0b0xxxxxxx *)
myerror "cactutf.opa : prev : error in UTF8 [2]"
else if (i3 >= 224) then (* 0b111xxxxx *)
myerror "cactutf.opa : prev : error in UTF8 [3]"
else if (i3 < 192) then (* 0b110xxxxx *)
n - 2
else
let i2 = s @> (n - 3)
in
if (i2 < 128) then
myerror "cactutf.opa : prev : error in UTF8 [4]"
else if (i2 >= 224) then (* three bytes *)
n - 3
else if (i2 >= 192) then
myerror "cactutf.opa : prev : error in UTF8 [5]"
else
let i1 = s @> (n - 4)
in
if (i1 >= 224) then (* four bytes *)
n - 4
else
myerror "cactutf.opa : prev : error in UTF8 [6]"
*)
(* a light version of next *)
let pre_next str n = n + lenbytes (str @> n)
let check str =
let len = Bytes.length str in
let rec aux i =
if i<len then aux (pre_next str i)
else if i=len then true
else false
in
try aux 0 with Error _ -> false
let mess_invalid_char str n =
let v = str @> n in Printf.sprintf "the char at raw position %d is invalid [code is %d] : <<%c>> , global string validity is %b" n v (str.[n]) (check str)
let length_until s pos =
let rec aux s c i len =
if (i >= len) then
c
else
let n = s @> i
in
let k = lenbytes n
in
aux s (c + 1) (i + k) len
in
aux s 0 0 pos
let length s =
length_until s (Bytes.length s)
(*
** next()
** Return the index of the next Unicode character.
*)
(*##register next : string -> int -> int*)
let next str n =
try
n + pre_lenbytes (str @> n)
with Lenbytes _ -> warning_or_error ("bslCactutf.next : "^(mess_invalid_char str n)); n+1
(*
** prev()
** Return the index of the previous Unicode character.
*)
(*##register prev : string -> int -> int*)
let prev str n =
(* FIND THE PREVIOUS CHAR *)
let i = prev_first_char str (n-1) in
if i<0 then ( warning_or_error ("bslCactutf.prev"); i )
else i
(*
** nth()
** Return the index of the n-th Unicode character.
** use a cache to speed-up similar calls
** memoize last n-th caracter position and restart from it
*)
let nth =
let cache_s = ref "" in
let cache_th= ref 0 in
let cache_i = ref 0 in
fun str th ->
try
let len = Bytes.length str in
if not(!cache_s == str) then begin
(* if str change then start from begining
TODO could start from begin or end to be at least 2x faster
*)
cache_th:= 0;
cache_i := 0;
cache_s := str;
end;
(* TODO could start from begin or end to be faster if previous cache is not adapted *)
(* disabled this warning since it floods TT and is useless if nobody works on improving it
* if !cache_th < th-100 || !cache_th > th+100 then (Printf.printf "bslCactutf.nth may slow you"; flush stdout);*)
if !cache_th < th then (
while !cache_th<th && (!cache_i) < len do
cache_th := !cache_th +1;
cache_i := next str !cache_i;
done;
!cache_i
) else (
while !cache_th > th && (!cache_i)>= 0 do
cache_th := !cache_th -1;
cache_i := prev str !cache_i;
done;
!cache_i
)
with _ ->
warning_or_error (Printf.sprintf "bslCactutf.nth : utf-8 position %d[=>%d], global string validity is %b" (!cache_th) (!cache_i) (check str));
!cache_i
type range_validity =
| Invalid_range of string (* an error message is given *)
| Valid_range (* the requested substring *)
(*
* Return a pair
* - a flag saying if the requested substring was valid
* - the unicode substring (clipped to the size of the string if needed)
*)
let sub_no_failure s i n =
if n = 0 then (Valid_range, "") else (* used to work that way, should be improved
* bacause n = 0 and i < 0 is not valid
* but when n = 0, and i = 0, we say
* [pj = nth s (-1)] which prints an unwanted
* error ! *)
let len = Bytes.length s in
let pi = nth s i in
let pj = nth s (i+n-1) in
let pi' = max pi 0 in
let pj' =
if pj >= len then
len - pi'
else
min (pj-pi'+lenbytes (s @> pj)) (len-pi') in
let substring = Bytes.sub s pi' pj' in
let validity =
if i < 0 then
Invalid_range "cactutf.opa : sub(_, i<0 ,_) : index is negative"
else if n < 0 then
Invalid_range "cactutf.opa : sub(_, n<0 ,_) : index is negative"
else if n = 0 then
Valid_range
else if pi >= len then
Invalid_range (Printf.sprintf "cactutf.opa : sub(s, i=%d>utf_length(s)=%d ,_) : the index is too big, cryptic info=(%d,%d)" i (length s) pi len)
else if pj >= len then
Invalid_range (Printf.sprintf "cactutf.opa : sub(s, i=%d ,n=%d | i+n=%d>utf_length(s)=%d ) : the required length is too big, cryptic info=(%d,%d)" i n (i+n) (length s) pj len)
else
Valid_range in
(validity, substring)
(*
** sub()
** Return an Unicode sub-Bytes.
*)
(*##register sub : string -> int -> int -> string*)
let sub s i n =
let validity, substring = sub_no_failure s i n in
( match validity with
| Invalid_range s -> warning_or_error s
| Valid_range -> ()
);
substring
(*##register sub_opt : string -> int -> int -> string option*)
let sub_opt s i n =
match sub_no_failure s i n with
| (Invalid_range _, _) -> None
| (Valid_range, s) -> Some s
let one_byte b1 = b1
(*
** two_bytes()
** Encode two bytes into one Unicode character.
** 0b110xxxx 0b10xxxxxx
*)
let two_bytes b1 b2 =
(((b1 - 192) * 64) + (b2 - 128))
(*
** three bytes()
*)
let three_bytes b1 b2 b3 =
(((b1 - 224) * 4096) + ((b2 - 128) * 64) + (b3 - 128))
(*
** four bytes()
*)
let four_bytes b1 b2 b3 b4 =
(((b1 - 240) * 262144) + ((b2 - 128) * 4096) + ((b3 - 128) * 64) + (b4 - 128))
(*
** charutf8()
** Return the Unicode code at the index in a Bytes.
*)
(*register charutf8 : string -> int -> int*)
let charutf8 str pos =
let i = str @> pos
in
let len = lenbytes i
in
if (len = 1) then
i
else if (len = 2) then
two_bytes i (str @> (pos + 1))
else if (len = 3) then
three_bytes i (str @> (pos + 1)) (str @> (pos + 2))
else
four_bytes i (str @> (pos + 1)) (str @> (pos + 2)) (str @> (pos + 3))
(*
** get()
** Return the Unicode code of the nth Unicode character.
*)
(*##register get : string -> int -> int*)
let get str n =
charutf8 str (nth str n)
(*
** look()
** Return the Unicode code using the index (and not the nth).
** A lot faster, but only when using index instead of position.
*)
(*##register look : string -> int -> int*)
let look str i =
charutf8 str i
(*
*)
let csize n =
if (n < 128) then
1
else if (n < 2048) then
2
else if (n < 65536) then
3
else
4
(*
** cons()
** Build a new string from a character.
*)
(*##register cons : int -> string*)
let cons c =
let c = if c < 0 then 0 else c in
let s = csize c in
let str = Bytes.create s in
if (s = 1) then
(Bytes.set str 0 (char_of_int c);
str)
else if (s = 2) then
let n1 = c / 64 in
let n2 = c - (n1 * 64) in
Bytes.set str 0 (char_of_int(n1 + 192));
Bytes.set str 1 (char_of_int(n2 + 128));
str
else if (s = 3) then
let n1 = c / 4096 in
let n2 = (c - (n1 * 4096)) / 64 in
let n3 = (c - (n1 * 4096) - (n2 * 64)) in
Bytes.set str 0 (char_of_int(n1 + 224));
Bytes.set str 1 (char_of_int(n2 + 128));
Bytes.set str 2 (char_of_int(n3 + 128));
str
else
let n1 = c / 262144 in
let n2 = (c - (n1 * 262144)) / 4096 in
let n3 = (c - (n1 * 262144) - (n2 * 4096)) / 64 in
let n4 = (c - (n1 * 262144) - (n2 * 4096)) - (n3 * 64) in
Bytes.set str 0 (char_of_int(n1 + 240));
Bytes.set str 1 (char_of_int(n2 + 128));
Bytes.set str 2 (char_of_int(n3 + 128));
Bytes.set str 3 (char_of_int(n4 + 128));
str
(*
** uppercase()
** Return an Uppercase version of the Bytes.
** Beware of the Braille and some greeks caracters.
*)
(*##register uppercase : string -> string*)
let uppercase str =
let myupp i =
if ((i >= 97) && (i <= 123)) (* US-ASCII *)
|| ((i >= 224) && (i <= 246)) (* ISO-8859-1 (latin-1) v *)
|| ((i >= 248) && (i <= 254)) (* ISO-8859-1 (latin-1) ^ *)
|| ((i >= 65345) && (i <= 65370)) (* caracteres demi/pleine chasse *)
|| ((i >= 944) && (i <= 974)) (* grec *)
|| ((i >= 1072) && (i <= 1103)) then (* cyrillique *)
i - 32
else if ((i >= 257) && (i <= 319) && ((i mod 2) = 1)) (* latin étendu A v *)
|| ((i >= 314) && (i <= 328) && ((i mod 2) = 0))
|| ((i >= 331) && (i <= 375) && ((i mod 2) = 1))
|| (i = 378) || (i = 380) || (i = 382) (* latin étendu A ^ *)
|| (i = 389) || (i = 392) || (i = 396) || (i = 402) (* latin étendu B v *)
|| (i = 409) || (i = 417) || (i = 419) || (i = 421)
|| (i = 424) || (i = 429) || (i = 432) || (i = 434)
|| (i = 436) || (i = 438) || (i = 453) || (i = 456)
|| (i = 459)
|| ((i >= 462) && (i <= 476) && ((i mod 2) = 0))
|| ((i >= 479) && (i <= 495) && ((i mod 2) = 1))
|| (i = 498)
|| ((i >= 501) && (i <= 563) && ((i mod 2) = 1))
|| (i = 572) || (i = 578) || (i = 585) || (i = 587)
|| (i = 589) || (i = 591) (* latin étendu B ^ *)
|| ((i >= 7680) && (i <= 7935) && ((i mod 2) = 1)) (* latin étendu additionnel *)
|| (i = 8580) (* nombre latin : facteur 10 *)
|| ((i >= 977) && (i <= 1007) && ((i mod 2) = 1)) (* grec avec accents *)
|| ((i >= 1120) && (i <= 1153) && ((i mod 2) = 1)) (* cyrillique v *)
|| ((i >= 1163) && (i <= 1215) && ((i mod 2) = 1))
|| ((i >= 1217) && (i <= 1230) && ((i mod 2) = 0))
|| ((i >= 1232) && (i <= 1279) && ((i mod 2) = 1)) (* cyrillique ^ *)
|| ((i >= 1280) && (i <= 1299) && ((i mod 2) = 1)) then (* cyrillique additionnel *)
i - 1
else if (i = 454) || (i = 457) || (i = 460) || (i = 499) then (* latin étendu B doubles lettres *)
i - 2
else if (i = 255) then (* special case : ÿ. Latin 1&A.*)
376
else if ((i >= 9424) && (i <= 9449)) then (* lettres pastilles *)
i - 26
else if ((i >= 1104) && (i <= 1119)) then (* cyrillique *)
i - 80
else if ((i >= 7936) && (i <= 8047) && ((i mod 16) <= 7)) (* grec polytonique v *)
|| ((i >= 8064) && (i <= 8111) && ((i mod 16) <= 7)) then (* grev polytonique ^ *)
i + 8
else if ((i >= 1377) && (i <= 1414)) then (* arménien *)
i - 48
else if ((i >= 8560) && (i <= 8575)) then (* nombres latins *)
i - 16
else
i
in
let rec aux len pos accu =
if (len = 0) then
accu
else
aux (len - 1) (next str pos) (accu ^ cons (myupp (look str pos)))
in
aux (length str) 0 ""
(*
** lowercase()
** See uppercase().
*)
(*##register lowercase : string -> string*)
let lowercase str =
let mylow i =
if ((i >= 65) && (i <= 91)) (* US-ASCII *)
|| ((i >= 192) && (i <= 214)) (* ISO-8859-1 (latin-1) v *)
|| ((i >= 216) && (i <= 222)) (* ISO-8859-1 (latin-1) ^ *)
|| ((i >= 65313) && (i <= 65338)) (* caracteres demi/pleine chasse *)
|| ((i >= 912) && (i <= 942)) (* grec *)
|| ((i >= 1040) && (i <= 1071)) then (* cyrillique *)
i + 32
else if ((i >= 256) && (i <= 319) && ((i mod 2) = 0)) (* latin étendu A v *)
|| ((i >= 313) && (i <= 328) && ((i mod 2) = 1))
|| ((i >= 330) && (i <= 375) && ((i mod 2) = 0))
|| (i = 377) || (i = 379) || (i = 381) (* latin étendu A ^ *)
|| (i = 388) || (i = 391) || (i = 395) || (i = 401) (* latin étendu B v *)
|| (i = 408) || (i = 416) || (i = 418) || (i = 420)
|| (i = 423) || (i = 428) || (i = 431) || (i = 433)
|| (i = 435) || (i = 437) || (i = 453) || (i = 456)
|| (i = 459)
|| ((i >= 461) && (i <= 476) && ((i mod 2) = 1))
|| ((i >= 478) && (i <= 495) && ((i mod 2) = 0))
|| (i = 498)
|| ((i >= 500) && (i <= 563) && ((i mod 2) = 0))
|| (i = 571) || (i = 577) || (i = 584) || (i = 586)
|| (i = 588) || (i = 590) (* latin étendu B ^ *)
|| ((i >= 7680) && (i <= 7935) && ((i mod 2) = 0)) (* latin étendu additionnel *)
|| (i = 8579) (* nombre latin : facteur 10 *)
|| ((i >= 976) && (i <= 1007) && ((i mod 2) = 0)) (* grec avec accents *)
|| ((i >= 1120) && (i <= 1153) && ((i mod 2) = 0)) (* cyrillique v *)
|| ((i >= 1162) && (i <= 1215) && ((i mod 2) = 0))
|| ((i >= 1217) && (i <= 1230) && ((i mod 2) = 1))
|| ((i >= 1232) && (i <= 1279) && ((i mod 2) = 0)) (* cyrillique ^ *)
|| ((i >= 1280) && (i <= 1299) && ((i mod 2) = 0)) then (* cyrillique additionnel *)
i + 1
else if (i = 452) || (i = 455) || (i = 458) || (i = 497) then (* latin étendu B doubles lettres *)
i + 2
else if (i = 376) then (* special case : ÿ. Latin 1&A.*)
255
else if ((i >= 9398) && (i <= 9423)) then (* lettres pastilles *)
i + 26
else if ((i >= 1024) && (i <= 1039)) then (* cyrillique *)
i + 80
else if ((i >= 7936) && (i <= 8047) && ((i mod 16) > 7)) (* grec polytonique v *)
|| ((i >= 8064) && (i <= 8111) && ((i mod 16) > 7)) then (* grev polytonique ^ *)
i - 8
else if ((i >= 1329) && (i <= 1366)) then (* arménien *)
i + 48
else if ((i >= 8544) && (i <= 8559)) then (* nombres latins *)
i + 16
else
i
in
let rec aux len pos accu =
if (len = 0) then
accu
else
aux (len - 1) (next str pos) (accu ^ cons (mylow (look str pos)))
in
aux (length str) 0 ""
exception Done
(*
let remove_accents s =
let buffer = Buffer.create (Bytes.length s) in
let add = Buffer.add_char buffer in
let add_array a ~start ~length=
for i = 0 to length - 1 do
Utf8.store buffer a.(start + i)
done
in
let lex_one_char = lexer
| [ 192 193 194 195 196 197 65 (*ÀÁÂÃÄÅA*) ] -> add 'A'
| [ 224 225 226 227 228 229 97 (*àáâãäåa*) ] -> add 'a'
| [ 210 211 212 213 214 216 79 (*ÒÓÔÕÖØO*) ] -> add 'O'
| [ 242 243 244 245 246 248 111 (*òóôõöøo*) ]-> add 'o'
| [ 200 201 202 203 69 (*ÈÉÊËE*) ] -> add 'E'
| [ 232 233 234 235 101 (*èéêëe*) ] -> add 'e'
| [ 199 67 (*ÇC*) ] -> add 'C'
| [ 231 99 (*çc*) ] -> add 'c'
| [ 204 205 206 207 73 (*ÌÍÎÏI*) ] -> add 'I'
| [ 236 237 238 239 105 (*ìíîïi*) ] -> add 'i'
| [ 217 218 219 220 85 (*ÙÚÛÜU*) ] -> add 'U'
| [ 249 250 251 252 117 (*ùúûüu*) ] -> add 'u'
| [ 255 121 (*ÿy*) ] -> add 'y'
| [ 209 78 (*ÑN*) ] -> add 'N'
| [ 241 110 (*ñn*) ] -> add 'n'
| eof -> raise Done
| _ -> add_array (Ulexing.get_buf lexbuf) ~start:(Ulexing.get_start lexbuf) ~length:(Ulexing.lexeme_length lexbuf)
in
try
let lexbuf = Ulexing.from_utf8_string s in
while true do
lex_one_char lexbuf
done;
assert false
with
Done -> Buffer.contents buffer
*)
(*##endmodule*)
|
{
"pile_set_name": "Github"
}
|
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
end
|
{
"pile_set_name": "Github"
}
|
{
"type": "Live2D Model Setting",
"name": "33-2017-newyear",
"label": "33",
"model": "33.v2.moc",
"textures": [
"33.1024/closet.default.v2/texture_00.png",
"33.1024/closet.2017.newyear/texture_01.png",
"33.1024/closet.2017.newyear/texture_02.png",
"33.1024/closet.2017.newyear/texture_03.png"
],
"layout": { "center_x": 0, "center_y": 0.1, "width": 2.3, "height": 2.3 },
"motions": {
"idle": [
{
"file": "motions/33.v2.idle-01.mtn",
"fade_in": 2000,
"fade_out": 2000
},
{
"file": "motions/33.v2.idle-02.mtn",
"fade_in": 2000,
"fade_out": 2000
},
{
"file": "motions/33.v2.idle-03.mtn",
"fade_in": 100,
"fade_out": 100
}
],
"tap_body": [
{
"file": "motions/33.v2.touch.mtn",
"fade_in": 500,
"fade_out": 200
}
],
"thanking": [
{
"file": "motions/33.v2.thanking.mtn",
"fade_in": 2000,
"fade_out": 2000
}
]
}
}
|
{
"pile_set_name": "Github"
}
|
{
"name": "ng-boilerplate",
"version": "0.3.2",
"devDependencies": {
"angular": "~1.3.0",
"angular-mocks": "~1.3.0",
"angular-route": "~1.3.0",
"jquery": "latest",
"lodash": "latest",
"FullScreenMario": "[email protected]:blnight/FullScreenMario.git#mario-presentation-game",
"reveal.js": "latest",
"animate.css": "latest"
},
"dependencies": {}
}
|
{
"pile_set_name": "Github"
}
|
//
// RSEAN8Generator.h
// RSBarcodes
//
// Created by zhangxi on 13-12-26.
// http://zhangxi.me
// Copyright (c) 2013年 P.D.Q. All rights reserved.
//
#import "RSEANGenerator.h"
@interface RSEAN8Generator : RSEANGenerator
@end
|
{
"pile_set_name": "Github"
}
|
/*CFG Analyzer, version 03/12/2007
A word in the intersection of L(G1) ... L(G2) is, e.g., "cccde" of length 5
*/
var hampiStringVar : 5;
cfg A := B D E ;
cfg B := "a" | "c" | "c" A ;
cfg D := "a" B | "d" | "c" D ;
cfg E := "c" "e" | "d" "e" | "e" ;
reg limit := fix(A, 5);
assert hampiStringVar in limit;
|
{
"pile_set_name": "Github"
}
|
#include "symbols.h"
const int symbols_nelts = 0;
const struct symbols symbols[] = {{0,0}};
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
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.
-->
<resources>
<string name="app_name">Jumping Jack</string>
<string name="reset_counter">Reset Counter</string>
</resources>
|
{
"pile_set_name": "Github"
}
|
/* eslint-env jest */
// mock config for testing
jest.mock('../src/config', () => require('./__mocks__/config'));
// npm packages
const nock = require('nock');
const sinon = require('sinon');
const inquirer = require('inquirer');
// our packages
const {handler: update} = require('../src/commands/update');
const {userConfig} = require('../src/config');
// test update
test('Should update traefik', done => {
// handle correct request
const updateServer = nock('http://localhost:8080').post('/update/traefik').reply(200, {updated: true});
// spy on console
const consoleSpy = sinon.spy(console, 'log');
// execute login
update({target: 'traefik'}).then(() => {
// make sure log in was successful
// check that server was called
expect(updateServer.isDone()).toBeTruthy();
// first check console output
expect(consoleSpy.args).toMatchSnapshot();
// restore console
console.log.restore();
updateServer.done();
done();
});
});
// test update
test('Should update server', done => {
// handle correct request
const updateServer = nock('http://localhost:8080').post('/update/server').reply(200, {updated: true});
// spy on console
const consoleSpy = sinon.spy(console, 'log');
// execute login
update({target: 'server'}).then(() => {
// make sure log in was successful
// check that server was called
expect(updateServer.isDone()).toBeTruthy();
// first check console output
expect(consoleSpy.args).toMatchSnapshot();
// restore console
console.log.restore();
updateServer.done();
done();
});
});
// test update error
test('Should display update error', done => {
// handle correct request
const response = {updated: false, error: 'Test error', log: 'log'};
const updateServer = nock('http://localhost:8080').post('/update/traefik').reply(500, response);
// spy on console
const consoleSpy = sinon.spy(console, 'log');
// execute login
update({target: 'traefik'}).then(() => {
// make sure log in was successful
// check that server was called
expect(updateServer.isDone()).toBeTruthy();
// first check console output
expect(consoleSpy.args).toMatchSnapshot();
// restore console
console.log.restore();
updateServer.done();
done();
});
});
// test version check
test('Should display versions', done => {
// handle correct request
const response = {
server: '0.18.0',
latestServer: '0.19.1',
serverUpdate: true,
traefik: 'v1.3.0',
latestTraefik: 'v1.3.2',
traefikUpdate: true,
};
const updateServer = nock('http://localhost:8080').get('/version').reply(200, response);
// spy on console
const consoleSpy = sinon.spy(console, 'log');
// stup inquirer answers
sinon.stub(inquirer, 'prompt').callsFake(() => Promise.resolve({upServer: false, upTraefik: false}));
// execute login
update({}).then(() => {
// make sure log in was successful
// check that server was called
expect(updateServer.isDone()).toBeTruthy();
// first check console output
expect(consoleSpy.args).toMatchSnapshot();
// restore console
console.log.restore();
// restore inquirer
inquirer.prompt.restore();
// cleanup server
updateServer.done();
done();
});
});
// test version check
test('Should update all on user prompt', done => {
// handle correct request
const response = {
server: '0.18.0',
latestServer: '0.19.1',
serverUpdate: true,
traefik: 'v1.3.0',
latestTraefik: 'v1.3.2',
traefikUpdate: true,
};
const updateInfoServer = nock('http://localhost:8080').get('/version').reply(200, response);
const updateServerRun = nock('http://localhost:8080').post('/update/server').reply(200, {updated: true});
const updateTraefikRun = nock('http://localhost:8080').post('/update/traefik').reply(200, {updated: true});
// spy on console
const consoleSpy = sinon.spy(console, 'log');
// stup inquirer answers
sinon.stub(inquirer, 'prompt').callsFake(() => Promise.resolve({upServer: true, upTraefik: true}));
// execute login
update({}).then(() => {
// make sure log in was successful
// check that servers were called
expect(updateInfoServer.isDone()).toBeTruthy();
expect(updateServerRun.isDone()).toBeTruthy();
expect(updateTraefikRun.isDone()).toBeTruthy();
// first check console output
expect(consoleSpy.args).toMatchSnapshot();
// restore console
console.log.restore();
// restore inquirer
inquirer.prompt.restore();
// cleanup server
updateInfoServer.done();
updateServerRun.done();
updateTraefikRun.done();
done();
});
});
// test deauth
test('Should deauth on 401', done => {
// handle correct request
const updateServer = nock('http://localhost:8080').post(`/update/traefik`).reply(401);
// spy on console
const consoleSpy = sinon.spy(console, 'log');
// execute login
update({target: 'traefik'}).then(() => {
// make sure log in was successful
// check that server was called
expect(updateServer.isDone()).toBeTruthy();
// first check console output
expect(consoleSpy.args).toMatchSnapshot();
// check config
expect(userConfig.user).toBeUndefined();
expect(userConfig.token).toBeUndefined();
// restore console
console.log.restore();
// tear down nock
updateServer.done();
done();
});
});
|
{
"pile_set_name": "Github"
}
|
package ftl.config.android
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import ftl.args.yml.AppTestPair
import ftl.args.yml.IYmlKeys
import ftl.args.yml.ymlKeys
import ftl.config.Config
import picocli.CommandLine
/** Flank specific parameters for Android */
@JsonIgnoreProperties(ignoreUnknown = true)
data class AndroidFlankConfig @JsonIgnore constructor(
@JsonIgnore
override val data: MutableMap<String, Any?>
) : Config {
@CommandLine.Option(
names = ["--additional-app-test-apks"],
split = ",",
description = ["A list of app & test apks to include in the run. " +
"Useful for running multiple module tests within a single Flank run."]
)
fun additionalAppTestApks(map: Map<String, String>?) {
if (map.isNullOrEmpty()) return
if (additionalAppTestApks == null) additionalAppTestApks = mutableListOf()
val appApk = map["app"]
val testApk = map["test"]
if (testApk != null) {
additionalAppTestApks?.add(
AppTestPair(
app = appApk,
test = testApk
)
)
}
}
@set:JsonProperty("additional-app-test-apks")
var additionalAppTestApks: MutableList<AppTestPair>? by data
@set:CommandLine.Option(
names = ["--legacy-junit-result"],
description = ["Fallback for legacy xml junit results parsing."]
)
@set:JsonProperty("legacy-junit-result")
var useLegacyJUnitResult: Boolean? by data
constructor() : this(mutableMapOf<String, Any?>().withDefault { null })
companion object : IYmlKeys {
override val group = IYmlKeys.Group.FLANK
override val keys by lazy {
AndroidFlankConfig::class.ymlKeys
}
fun default() = AndroidFlankConfig().apply {
additionalAppTestApks = null
useLegacyJUnitResult = false
}
}
}
|
{
"pile_set_name": "Github"
}
|
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 1999 - 2019 Intel Corporation. */
#include "ixgbe.h"
#ifdef HAVE_IXGBE_DEBUG_FS
#include <linux/debugfs.h>
#include <linux/module.h>
static struct dentry *ixgbe_dbg_root;
static char ixgbe_dbg_reg_ops_buf[256] = "";
/**
* ixgbe_dbg_reg_ops_read - read for reg_ops datum
* @filp: the opened file
* @buffer: where to write the data for the user to read
* @count: the size of the user's buffer
* @ppos: file position offset
**/
static ssize_t ixgbe_dbg_reg_ops_read(struct file *filp, char __user *buffer,
size_t count, loff_t *ppos)
{
struct ixgbe_adapter *adapter = filp->private_data;
char *buf;
int len;
/* don't allow partial reads */
if (*ppos != 0)
return 0;
buf = kasprintf(GFP_KERNEL, "%s: %s\n",
adapter->netdev->name,
ixgbe_dbg_reg_ops_buf);
if (!buf)
return -ENOMEM;
if (count < strlen(buf)) {
kfree(buf);
return -ENOSPC;
}
len = simple_read_from_buffer(buffer, count, ppos, buf, strlen(buf));
kfree(buf);
return len;
}
/**
* ixgbe_dbg_reg_ops_write - write into reg_ops datum
* @filp: the opened file
* @buffer: where to find the user's data
* @count: the length of the user's data
* @ppos: file position offset
**/
static ssize_t ixgbe_dbg_reg_ops_write(struct file *filp,
const char __user *buffer,
size_t count, loff_t *ppos)
{
struct ixgbe_adapter *adapter = filp->private_data;
int len;
/* don't allow partial writes */
if (*ppos != 0)
return 0;
if (count >= sizeof(ixgbe_dbg_reg_ops_buf))
return -ENOSPC;
len = simple_write_to_buffer(ixgbe_dbg_reg_ops_buf,
sizeof(ixgbe_dbg_reg_ops_buf)-1,
ppos,
buffer,
count);
if (len < 0)
return len;
ixgbe_dbg_reg_ops_buf[len] = '\0';
if (strncmp(ixgbe_dbg_reg_ops_buf, "write", 5) == 0) {
u32 reg, value;
int cnt;
cnt = sscanf(&ixgbe_dbg_reg_ops_buf[5], "%x %x", ®, &value);
/* check format and bounds check register access */
if (cnt == 2 && reg <= IXGBE_HFDR) {
IXGBE_WRITE_REG(&adapter->hw, reg, value);
value = IXGBE_READ_REG(&adapter->hw, reg);
e_dev_info("write: 0x%08x = 0x%08x\n", reg, value);
} else {
e_dev_info("write <reg> <value>\n");
}
} else if (strncmp(ixgbe_dbg_reg_ops_buf, "read", 4) == 0) {
u32 reg, value;
int cnt;
cnt = sscanf(&ixgbe_dbg_reg_ops_buf[4], "%x", ®);
/* check format and bounds check register access */
if (cnt == 1 && reg <= IXGBE_HFDR) {
value = IXGBE_READ_REG(&adapter->hw, reg);
e_dev_info("read 0x%08x = 0x%08x\n", reg, value);
} else {
e_dev_info("read <reg>\n");
}
} else {
e_dev_info("Unknown command %s\n", ixgbe_dbg_reg_ops_buf);
e_dev_info("Available commands:\n");
e_dev_info(" read <reg>\n");
e_dev_info(" write <reg> <value>\n");
}
return count;
}
static const struct file_operations ixgbe_dbg_reg_ops_fops = {
.owner = THIS_MODULE,
.open = simple_open,
.read = ixgbe_dbg_reg_ops_read,
.write = ixgbe_dbg_reg_ops_write,
};
static char ixgbe_dbg_netdev_ops_buf[256] = "";
/**
* ixgbe_dbg_netdev_ops_read - read for netdev_ops datum
* @filp: the opened file
* @buffer: where to write the data for the user to read
* @count: the size of the user's buffer
* @ppos: file position offset
**/
static ssize_t ixgbe_dbg_netdev_ops_read(struct file *filp,
char __user *buffer,
size_t count, loff_t *ppos)
{
struct ixgbe_adapter *adapter = filp->private_data;
char *buf;
int len;
/* don't allow partial reads */
if (*ppos != 0)
return 0;
buf = kasprintf(GFP_KERNEL, "%s: %s\n",
adapter->netdev->name,
ixgbe_dbg_netdev_ops_buf);
if (!buf)
return -ENOMEM;
if (count < strlen(buf)) {
kfree(buf);
return -ENOSPC;
}
len = simple_read_from_buffer(buffer, count, ppos, buf, strlen(buf));
kfree(buf);
return len;
}
/**
* ixgbe_dbg_netdev_ops_write - write into netdev_ops datum
* @filp: the opened file
* @buffer: where to find the user's data
* @count: the length of the user's data
* @ppos: file position offset
**/
static ssize_t ixgbe_dbg_netdev_ops_write(struct file *filp,
const char __user *buffer,
size_t count, loff_t *ppos)
{
struct ixgbe_adapter *adapter = filp->private_data;
int len;
/* don't allow partial writes */
if (*ppos != 0)
return 0;
if (count >= sizeof(ixgbe_dbg_netdev_ops_buf))
return -ENOSPC;
len = simple_write_to_buffer(ixgbe_dbg_netdev_ops_buf,
sizeof(ixgbe_dbg_netdev_ops_buf)-1,
ppos,
buffer,
count);
if (len < 0)
return len;
ixgbe_dbg_netdev_ops_buf[len] = '\0';
if (strncmp(ixgbe_dbg_netdev_ops_buf, "tx_timeout", 10) == 0) {
#ifdef HAVE_NET_DEVICE_OPS
adapter->netdev->netdev_ops->ndo_tx_timeout(adapter->netdev);
#else
adapter->netdev->tx_timeout(adapter->netdev);
#endif /* HAVE_NET_DEVICE_OPS */
e_dev_info("tx_timeout called\n");
} else {
e_dev_info("Unknown command: %s\n", ixgbe_dbg_netdev_ops_buf);
e_dev_info("Available commands:\n");
e_dev_info(" tx_timeout\n");
}
return count;
}
static struct file_operations ixgbe_dbg_netdev_ops_fops = {
.owner = THIS_MODULE,
.open = simple_open,
.read = ixgbe_dbg_netdev_ops_read,
.write = ixgbe_dbg_netdev_ops_write,
};
/**
* ixgbe_dbg_adapter_init - setup the debugfs directory for the adapter
* @adapter: the adapter that is starting up
**/
void ixgbe_dbg_adapter_init(struct ixgbe_adapter *adapter)
{
const char *name = pci_name(adapter->pdev);
struct dentry *pfile;
adapter->ixgbe_dbg_adapter = debugfs_create_dir(name, ixgbe_dbg_root);
if (adapter->ixgbe_dbg_adapter) {
pfile = debugfs_create_file("reg_ops", 0600,
adapter->ixgbe_dbg_adapter, adapter,
&ixgbe_dbg_reg_ops_fops);
if (!pfile)
e_dev_err("debugfs reg_ops for %s failed\n", name);
pfile = debugfs_create_file("netdev_ops", 0600,
adapter->ixgbe_dbg_adapter, adapter,
&ixgbe_dbg_netdev_ops_fops);
if (!pfile)
e_dev_err("debugfs netdev_ops for %s failed\n", name);
} else {
e_dev_err("debugfs entry for %s failed\n", name);
}
}
/**
* ixgbe_dbg_adapter_exit - clear out the adapter's debugfs entries
* @adapter: board private structure
**/
void ixgbe_dbg_adapter_exit(struct ixgbe_adapter *adapter)
{
if (adapter->ixgbe_dbg_adapter)
debugfs_remove_recursive(adapter->ixgbe_dbg_adapter);
adapter->ixgbe_dbg_adapter = NULL;
}
/**
* ixgbe_dbg_init - start up debugfs for the driver
**/
void ixgbe_dbg_init(void)
{
ixgbe_dbg_root = debugfs_create_dir(ixgbe_driver_name, NULL);
if (ixgbe_dbg_root == NULL)
pr_err("init of debugfs failed\n");
}
/**
* ixgbe_dbg_exit - clean out the driver's debugfs entries
**/
void ixgbe_dbg_exit(void)
{
debugfs_remove_recursive(ixgbe_dbg_root);
}
#endif /* HAVE_IXGBE_DEBUG_FS */
|
{
"pile_set_name": "Github"
}
|
open CommonTypes
open Operators
open SourceCode
open SourceCode.WithPos
open Sugartypes
open Utility
(* Import module signatures. *)
module type Pos = SugarConstructorsIntf.Pos
module type SugarConstructorsSig = SugarConstructorsIntf.SugarConstructorsSig
(* Actual implementation of smart constructors as a functor on a Pos module. *)
module SugarConstructors (Position : Pos)
: (SugarConstructorsSig with type t := Position.t) = struct
(** Convenient aliases for functions operating on positions. *)
let pos = Position.pos
let with_pos = Position.with_pos
let dp = Position.dp
(** Attach a dummy position to a node. *)
let with_dummy_pos node = with_pos dp node
(** Generation of fresh type variables. *)
let type_variable_counter = ref 0
let fresh_type_variable freedom : SugarTypeVar.t =
incr type_variable_counter;
let name = "_" ^ string_of_int (!type_variable_counter) in
SugarTypeVar.mk_unresolved name None freedom
(** Helper data types and functions for passing arguments to smart
constructors. *)
(* Stores either a name of variable to be used in a binding pattern or the
pattern itself. Used for passing an argument to val_binding. *)
type name_or_pat = PatName of Name.t | Pat of Pattern.with_pos
(* Optionally stores a datatype signature. Isomporphic to Option. *)
type signature = (Name.t WithPos.t * datatype') WithPos.t option
(* Produces a datatype if a name is accompanied by a signature. Raises an
exception if name does not match a name in a signature. *)
let datatype_opt_of_sig_opt sig_opt name =
match sig_opt with
| Some {node=({node=signame; _}, datatype); pos} ->
(* Ensure that name in a signature matches name in a declaration. *)
if signame <> name then
raise (ConcreteSyntaxError (pos,
Printf.sprintf "Signature for `%s' should precede definition of `%s', not `%s'."
signame signame name));
Some datatype
| None -> None
(** Common stuff *)
let var ?(ppos=dp) name = with_pos ppos (Var name)
let freeze_var ?(ppos=dp) name = with_pos ppos (FreezeVar name)
(* Create a Block from block_body. *)
let block_node block_contents = Block block_contents
let block ?(ppos=dp) block_contents =
with_pos ppos (block_node block_contents)
let datatype d = (d, None)
(* Create a record with a given list of labels. *)
let record ?(ppos=dp) ?exp lbls = with_pos ppos (RecordLit (lbls, exp))
(* Create a tuple *)
let tuple ?(ppos=dp) = function
| es -> with_pos ppos (TupleLit es)
(* Create a tuple for orderby clauses (includes a hack to ensure
that 1-tuples are preserved) *)
let orderby_tuple ?(ppos=dp) = function
| [e] -> record ~ppos [("1", e)]
| es -> with_pos ppos (TupleLit es)
let cp_unit ppos = with_pos ppos (CPUnquote ([], tuple ~ppos []))
let list ?(ppos=dp) ?ty elems =
with_pos ppos (ListLit (elems, ty))
let constructor ?(ppos=dp) ?body ?ty name =
with_pos ppos (ConstructorLit (name, body, ty))
(** Constants **)
let constant ?(ppos=dp) c = with_pos ppos (Constant c)
let constant_str ?(ppos=dp) s = with_pos ppos (Constant (Constant.String s))
let constant_char ?(ppos=dp) c = with_pos ppos (Constant (Constant.Char c))
(** Binders **)
let binder ?(ppos=dp) ?ty name = with_pos ppos (Binder.make ~name ?ty ())
(** Imports **)
let import ?(ppos=dp) ?(pollute=false) names = with_pos ppos (Import { path = names; pollute })
(** Patterns *)
(* Create a variable pattern with a given name. *)
let variable_pat ?(ppos=dp) ?ty name =
with_pos ppos (Pattern.Variable (binder ~ppos ?ty name))
(* Create a tuple pattern. *)
let tuple_pat ?(ppos=dp) pats =
with_pos ppos (Pattern.Tuple pats)
let any_pat ppos = with_pos ppos Pattern.Any
(** Fieldspec *)
let present = Datatype.Present (WithPos.dummy Datatype.Unit)
let wild_present = ("wild", present)
let hear_present p = ("hear", Datatype.Present p)
(** Rows *)
let row_with field (fields, row_var) = (field::fields, row_var)
let row_with_wp fields = row_with wild_present fields
let hear_arrow_prefix presence fields =
row_with wild_present (row_with (hear_present presence) fields)
(** Various phrases *)
(* Create a Normal FunLit. *)
let fun_lit ?(ppos=dp) ?args ?(location=loc_unknown) linearity pats blk =
with_pos ppos (FunLit (args, linearity, NormalFunlit (pats, blk), location))
let switch_fun_lit ?(ppos=dp) ?args ?(location=loc_unknown) linearity pats switch_funlit_body =
with_pos ppos (FunLit (args, linearity, SwitchFunlit (pats, switch_funlit_body), location))
(* Create a Spawn. *)
let spawn ?(ppos=dp) ?row spawn_kind location blk =
with_pos ppos (Spawn (spawn_kind, location, blk, row))
let fn_appl_node ?(ppos=dp) name tyvars vars =
FnAppl (with_pos ppos (tappl (FreezeVar name, tyvars)), vars)
let fn_appl ?(ppos=dp) name tyvars vars =
with_pos ppos (fn_appl_node ~ppos name tyvars vars)
let fn_appl_var ?(ppos=dp) var1 var2 =
fn_appl ~ppos var1 [] [var ~ppos var2]
(** Bindings *)
(* Create a function binding. *)
let fun_binding ?(ppos=dp) sig_opt ?(unsafe_sig=false) ((linearity, frozen), bndr, args, location, blk) =
let fun_signature = datatype_opt_of_sig_opt sig_opt bndr in
with_pos ppos (Fun { fun_binder = binder bndr;
fun_linearity = linearity;
fun_definition = ([], NormalFunlit (args, blk));
fun_location = location;
fun_signature;
fun_frozen = frozen;
fun_unsafe_signature = unsafe_sig })
let fun_binding' ?(ppos=dp) ?(linearity=dl_unl) ?(tyvars=[])
?(location=loc_unknown) ?annotation bndr fnlit =
with_pos ppos (Fun { fun_binder = bndr;
fun_linearity = linearity;
fun_definition = (tyvars, fnlit);
fun_location = location;
fun_signature = annotation;
fun_frozen = false;
fun_unsafe_signature = false })
let switch_fun_binding ?(ppos=dp) sig_opt ?(unsafe_sig=false) ((linearity, frozen), bndr, args, location, blk) =
let fun_signature = datatype_opt_of_sig_opt sig_opt bndr in
with_pos ppos (Fun { fun_binder = binder bndr;
fun_linearity = linearity;
fun_definition = ([], SwitchFunlit (args, blk));
fun_location = location;
fun_signature;
fun_frozen = frozen;
fun_unsafe_signature = unsafe_sig })
(* Create a Val binding. This function takes either a name for a variable
pattern or an already constructed pattern. In the latter case no signature
should be passed. *)
let val_binding' ?(ppos=dp) sig_opt (name_or_pat, phrase, location) =
let pat, datatype = match name_or_pat with
| PatName name ->
let pat = variable_pat ~ppos name in
let datatype = datatype_opt_of_sig_opt sig_opt name in
(pat, datatype)
| Pat pat ->
assert (sig_opt = None);
(pat, None) in
with_pos ppos (Val (pat, ([], phrase), location, datatype))
(* A commonly used wrapper around val_binding *)
let val_binding ?(ppos=dp) pat phrase =
val_binding' ~ppos None (Pat pat, phrase, loc_unknown)
(* Create a module binding. *)
let module_binding ?(ppos=dp) binder members =
with_pos ppos (Module { binder; members })
(** Database queries *)
(* Create a list of labeled database expressions. *)
let db_exps ?(ppos=dp) exps =
list ~ppos [record ~ppos exps]
(* Is the list of labeled database expressions empty? *)
let is_empty_db_exps : phrase -> bool = function
| {node=ListLit ([{node=RecordLit ([], _);_}], _);_} -> true
| _ -> false
(* Create a database insertion query. Raises an exception when the list of
labeled expression is empty and the returning variable has not been named.
*)
let db_insert ?(ppos=dp) ins_exp lbls exps var_opt =
if is_empty_db_exps exps && var_opt == None then
raise (ConcreteSyntaxError (pos ppos, "Invalid insert statement. " ^
"Either provide a nonempty list of labeled expression or a return " ^
"variable."));
with_pos ppos (DBInsert (ins_exp, lbls, exps,
opt_map (fun name -> constant_str ~ppos name) var_opt))
(* Create a query. *)
let query ?(ppos=dp) phrases_opt policy blk =
with_pos ppos (Query (phrases_opt, policy, blk, None))
(** Operator applications *)
(* Apply a binary infix operator. *)
let infix_appl' ?(ppos=dp) arg1 op arg2 =
with_pos ppos (InfixAppl (([], op), arg1, arg2))
(* Apply a binary infix operator with a specified name. *)
let infix_appl ?(ppos=dp) arg1 op arg2 =
infix_appl' ~ppos arg1 (BinaryOp.Name op) arg2
(* Apply an unary operator. *)
let unary_appl ?(ppos=dp) op arg =
with_pos ppos (UnaryAppl (([], op), arg))
(** XML *)
let validate_xml ?tags e = match e with
| {node=Xml (name, attr_list, blk_opt, _); pos} ->
(* check whether opening and closing tags match *)
let () = match tags with
| Some (opening, closing) when opening = closing -> ()
| Some (opening, closing) ->
raise (ConcreteSyntaxError (pos,
Printf.sprintf "Closing tag '%s' does not match start tag '%s'."
closing opening))
| _ -> () in
(* Check uniqueness of attributes *)
let xml_sugar_error pos message =
let open Errors in
raise (desugaring_error ~pos ~stage:CheckXML ~message) in
let () =
let attr_names = fst (List.split attr_list) in
if ListUtils.has_duplicates attr_names then
xml_sugar_error pos
(Printf.sprintf "XML tag '%s' has duplicate attributes" name) in
(* Check that XML forests don't have attributes *)
let () =
if name = "#" && (List.length attr_list != 0 || blk_opt <> None) then
xml_sugar_error pos
"XML forest literals cannot have attributes" in
()
| _ -> assert false
(* Create an XML tree. Raise an exception if opening and closing tags don't
match. *)
let xml ?(ppos=dp) ?tags name attr_list blk_opt contents =
let node = with_pos ppos (Xml (name, attr_list, blk_opt, contents)) in
let () = validate_xml ?tags node in
node
(** Handlers *)
let untyped_handler ?(val_cases = []) ?parameters expr eff_cases depth =
{ sh_expr = expr;
sh_effect_cases = eff_cases;
sh_value_cases = val_cases;
sh_descr = {
shd_depth = depth;
shd_types = ( Types.make_empty_closed_row (), Types.Not_typed
, Types.make_empty_closed_row (), Types.Not_typed);
shd_raw_row = Types.make_empty_closed_row ();
shd_params = opt_map (fun pps -> {shp_bindings = pps; shp_types = []})
parameters
};
}
end
(* Positions module based on standard Sugartypes positions. *)
module SugartypesPos : Pos with type t = Position.t = struct
(* Sugartypes position *)
type t = Position.t
(* Identity - positions in this module are alread Sugartypes positions *)
let pos p = p
(* Construct a node with position *)
let with_pos pos node = WithPos.make ~pos node
(* Default (dummy) position *)
let dp = Position.dummy
end
(* Positions module based on dummy/unit positions. Prevents attaching any
kind of meaningful positions to nodes. *)
module DummyPos : Pos with type t = unit = struct
type t = unit
let pos () = Position.dummy
let with_pos () node = WithPos.dummy node
let dp = ()
end
module SugartypesPositions = SugarConstructors(SugartypesPos)
module DummyPositions = SugarConstructors(DummyPos )
(*
Note [Attaching positions to nodes]
===================================
Positions represent locations of tokens inside a source file (roughly: filename
+ line number + column offset) and are attached to most nodes in an AST -
c.f. datatype definitions in Sugartypes. During various stages of the
compilation pipeline we change the structure of an AST, often creating new nodes
that don't really correspond to any tokens in the source files. In theory these
nodes should have dummy positions attached to them but in practice we often
maintain positions to know from which source code location a given node was
derived. This is mostly used when debugging the compiler.
All that being said, there are two modules providing concrete access to
SugarConstructors:
* SugartypesPositions provides constructors that allow to attach normal
Sugartypes positions to nodes. Used to traverse the AST and to propagate
positions to derived nodes.
* DummyPositions provides constructors that allow only to attach dummy
positions to nodes. Used to erase positions in derived nodes.
Note that all smart constructors have an optional position argument that
defaults to a dummy position. These default arguments are usually only provided
in the parser, so the main difference between using SugartypesPositions and
DummyPositions lies in the usage of with_pos function.
All of this is a bit inconsistent at the moment. There are no strict rules when
to propagate positions to derived nodes and when to discard them, so use your
best judgement.
*)
|
{
"pile_set_name": "Github"
}
|
---
# ===========================================================
# OWASP SAMM2 Security Practice - Operational Management
# ===========================================================
#Link to the model, using its unique identifier
function: 942d679b0c9e41909f8bde728fdb1259
#Unique identifier (GUID) used to refer to this practice.
#Please generate another identifier for your specific practice.
id: 8f07145b5ea74388b2217895d5e7b5c2
#Official name of this practice
name: Operational Management
#Abbreviation of this practice
shortName: OM
#A one sentence description of the security practice
shortDescription: This practice focuses on operational support activities required to maintain security throughout the product lifecycle.
#A multi-paragraph description of the security practice
longDescription: |
The Operational Management (OM) practice focuses on activities to ensure security is maintained throughout operational support functions. Although these functions are not performed directly by an application, the overall security of the application and its data depends on their proper performance. Deploying an application on an unsupported operating system with unpatched vulnerabilities, or failing to store backup media securely, can make the protections built into that application irrelevant.
The functions covered by this practice include, but are not limited to: system provisioning, administration, and decommissioning; database provisioning and administration; and data backup, restore, and archival.
#The relative order of this practice in the business function
order: 3
#Who's the "owner" of this practice
assignee: John DiLeo
#Indication of progress to keep track of overall status
progress: 80
#Type Classification of the Document
type: Practice
|
{
"pile_set_name": "Github"
}
|
/* ioapi.h -- IO base function header for compress/uncompress .zip
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
Changes
Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this)
Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
More if/def section may be needed to support other platforms
Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
(but you should use iowin32.c for windows instead)
*/
#ifndef _ZLIBIOAPI64_H
#define _ZLIBIOAPI64_H
#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
// Linux needs this to support file operation on files larger then 4+GB
// But might need better if/def to select just the platforms that needs them.
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include "zlib.h"
#if defined(USE_FILE32API)
#define fopen64 fopen
#define ftello64 ftell
#define fseeko64 fseek
#else
#ifdef __FreeBSD__
#define fopen64 fopen
#define ftello64 ftello
#define fseeko64 fseeko
#endif
#ifdef _MSC_VER
#define fopen64 fopen
#if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
#define ftello64 _ftelli64
#define fseeko64 _fseeki64
#else // old MSC
#define ftello64 ftell
#define fseeko64 fseek
#endif
#endif
#endif
/*
#ifndef ZPOS64_T
#ifdef _WIN32
#define ZPOS64_T fpos_t
#else
#include <stdint.h>
#define ZPOS64_T uint64_t
#endif
#endif
*/
#ifdef HAVE_MINIZIP64_CONF_H
#include "mz64conf.h"
#endif
/* a type choosen by DEFINE */
#ifdef HAVE_64BIT_INT_CUSTOM
typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T;
#else
#ifdef HAS_STDINT_H
#include "stdint.h"
typedef uint64_t ZPOS64_T;
#else
/* Maximum unsigned 32-bit value used as placeholder for zip64 */
#define MAXU32 0xffffffff
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 ZPOS64_T;
#else
typedef unsigned long long int ZPOS64_T;
#endif
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define ZLIB_FILEFUNC_SEEK_CUR (1)
#define ZLIB_FILEFUNC_SEEK_END (2)
#define ZLIB_FILEFUNC_SEEK_SET (0)
#define ZLIB_FILEFUNC_MODE_READ (1)
#define ZLIB_FILEFUNC_MODE_WRITE (2)
#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
#define ZLIB_FILEFUNC_MODE_EXISTING (4)
#define ZLIB_FILEFUNC_MODE_CREATE (8)
#ifndef ZCALLBACK
#if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
#define ZCALLBACK CALLBACK
#else
#define ZCALLBACK
#endif
#endif
typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
/* here is the "old" 32 bits structure structure */
typedef struct zlib_filefunc_def_s
{
open_file_func zopen_file;
read_file_func zread_file;
write_file_func zwrite_file;
tell_file_func ztell_file;
seek_file_func zseek_file;
close_file_func zclose_file;
testerror_file_func zerror_file;
voidpf opaque;
} zlib_filefunc_def;
typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode));
typedef struct zlib_filefunc64_def_s
{
open64_file_func zopen64_file;
read_file_func zread_file;
write_file_func zwrite_file;
tell64_file_func ztell64_file;
seek64_file_func zseek64_file;
close_file_func zclose_file;
testerror_file_func zerror_file;
voidpf opaque;
} zlib_filefunc64_def;
void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
/* now internal definition, only for zip.c and unzip.h */
typedef struct zlib_filefunc64_32_def_s
{
zlib_filefunc64_def zfile_func64;
open_file_func zopen32_file;
tell_file_func ztell32_file;
seek_file_func zseek32_file;
} zlib_filefunc64_32_def;
#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))
//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))
#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream))
#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream))
voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32);
#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode)))
#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream)))
#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
#ifdef __cplusplus
}
#endif
#endif
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2016 Network New Technologies Inc.
*
* 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.networknt.oauth.service.handler;
import com.hazelcast.core.IMap;
import com.networknt.body.BodyHandler;
import com.networknt.config.Config;
import com.networknt.handler.LightHttpHandler;
import com.networknt.oauth.cache.CacheStartupHookProvider;
import com.networknt.oauth.cache.model.Service;
import com.networknt.oauth.cache.model.ServiceEndpoint;
import com.networknt.oauth.cache.model.User;
import com.networknt.status.Status;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* create or update a list of endpoints for the serviceId
*
* @author Steve Hu
*/
public class Oauth2ServiceServiceIdEndpointPostHandler extends ServiceAuditHandler implements LightHttpHandler {
private static final Logger logger = LoggerFactory.getLogger(Oauth2ServiceServiceIdEndpointPostHandler.class);
static final String SERVICE_NOT_FOUND = "ERR12015";
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
List<Map<String, Object>> body = (List)exchange.getAttachment(BodyHandler.REQUEST_BODY);
String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
if(logger.isDebugEnabled()) logger.debug("post serviceEndpoints for serviceId " + serviceId);
// ensure that the serviceId exists
IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
if(services.get(serviceId) == null) {
setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
processAudit(exchange);
return;
}
IMap<String, List<ServiceEndpoint>> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints");
List<ServiceEndpoint> list = new ArrayList<>();
for(Map<String, Object> m: body) {
list.add(Config.getInstance().getMapper().convertValue(m, ServiceEndpoint.class));
}
serviceEndpoints.set(serviceId, list);
processAudit(exchange);
}
}
|
{
"pile_set_name": "Github"
}
|
//
// AIStrategyCast.h
// WizardWar
//
// Created by Sean Hess on 8/24/13.
// Copyright (c) 2013 Orbital Labs. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AITactic.h"
// casts a single kind of spell?
@interface AITCast : NSObject <AITactic>
@property (nonatomic, strong) NSString * spellType;
+(id)spell:(NSString*)spellType;
@end
|
{
"pile_set_name": "Github"
}
|
#ShadowsocksR Droid 协议和混淆插件开发规范v1.0
### ShadowSocksR(下称SSR)插件分为```协议```和```混淆```两种。
####开发步骤
#####准备:
1. 挑选您熟悉的语言:C,C++,Java,Kotlin。
2. 如果使用C/C++则需要利用JNI间接调用。
3. 如果使用Java或Kotlin则可以直接上手了。
#####协议插件:
1. 协议插件应写在com.proxy.shadowsocksr.impl.plugin.proto包下,并继承AbsProtocol类。根据协议类型,类名以Verify或Auth开头,以Protocol结尾。如:AuthSimpleProtocol。
2. AbsProtocol类已保存构造器参数,子类可以直接访问,如无特殊需要则无需再次保存。
3. shareParam用于存储协议用于每个连接的公用数据。
4. 在资源文件arrays.xml中,tcp\_protocol\_entry为协议插件对用户显示的名字,tcp\_protocol\_value为协议插件被App识别的名字,二者顺序要对应。
5. 修改ProtocolChooser类,使其可以识别您写的协议或混淆插件。
#####混淆插件:
1. 混淆插件应写在com.proxy.shadowsocksr.impl.plugin.obfs包下,并继承AbsObfs类。以Obfs结尾。如:HttpSimpleObfs。
2. AbsObfs类已保存构造器参数,子类可以直接访问,如无特殊需要则无需再次保存。
3. 在资源文件arrays.xml中,obfs\_method\_entry为混淆插件对用户显示的名字,obfs\_method\_value为混淆插件被App识别的名字,二者顺序要对应。
4. 修改ObfsChooser类,使其可以识别您写的协议或混淆插件。
5. 如果您的混淆插件需要用户输入字符串参数,请修改PrefFragment类的configSpecialPref()、setPrefEnabled(boolean isEnable)以及loadCurrentPref()方法,以便App可以正确启用EditTextPreference供用户输入。
####提示
1. 由于添加了协议,可能会产生由协议本身导致的断包,粘包的问题,这些问题需由插件自己处理。
2. 尽可能减少异常抛出,不必要的内存拷贝以保证效率。
3. 在数据解析出错时,返回byte\[0\]而不是null。
####如果您既想使用我们开发的SSR Droid,又想用自己写的插件(或是协议,混淆的思路)并且愿意公开它,那么欢迎Pull Request或通过任何你能联系到我们的方式来提交您的智慧结晶,我们会视情况将其加入并发布出来。
|
{
"pile_set_name": "Github"
}
|
module Rouge
module Lexers
class Perl < RegexLexer
desc "The Perl scripting language (perl.org)"
tag 'perl'
aliases 'pl'
filenames '*.pl', '*.pm'
mimetypes 'text/x-perl', 'application/x-perl'
def self.analyze_text(text)
return 1 if text.shebang? 'perl'
return 0.4 if text.include? 'my $'
end
keywords = %w(
case continue do else elsif for foreach if last my next our
redo reset then unless until while use print new BEGIN CHECK
INIT END return
)
builtins = %w(
abs accept alarm atan2 bind binmode bless caller chdir chmod
chomp chop chown chr chroot close closedir connect continue cos
crypt dbmclose dbmopen defined delete die dump each endgrent
endhostent endnetent endprotoent endpwent endservent eof eval
exec exists exit exp fcntl fileno flock fork format formline getc
getgrent getgrgid getgrnam gethostbyaddr gethostbyname gethostent
getlogin getnetbyaddr getnetbyname getnetent getpeername
getpgrp getppid getpriority getprotobyname getprotobynumber
getprotoent getpwent getpwnam getpwuid getservbyname getservbyport
getservent getsockname getsockopt glob gmtime goto grep hex
import index int ioctl join keys kill last lc lcfirst length
link listen local localtime log lstat map mkdir msgctl msgget
msgrcv msgsnd my next no oct open opendir ord our pack package
pipe pop pos printf prototype push quotemeta rand read readdir
readline readlink readpipe recv redo ref rename require reverse
rewinddir rindex rmdir scalar seek seekdir select semctl semget
semop send setgrent sethostent setnetent setpgrp setpriority
setprotoent setpwent setservent setsockopt shift shmctl shmget
shmread shmwrite shutdown sin sleep socket socketpair sort splice
split sprintf sqrt srand stat study substr symlink syscall sysopen
sysread sysseek system syswrite tell telldir tie tied time times
tr truncate uc ucfirst umask undef unlink unpack unshift untie
utime values vec wait waitpid wantarray warn write
)
re_tok = Str::Regex
state :balanced_regex do
rule %r(/(\\\\|\\/|[^/])*/[egimosx]*)m, re_tok, :pop!
rule %r(!(\\\\|\\!|[^!])*![egimosx]*)m, re_tok, :pop!
rule %r(\\(\\\\|[^\\])*\\[egimosx]*)m, re_tok, :pop!
rule %r({(\\\\|\\}|[^}])*}[egimosx]*), re_tok, :pop!
rule %r(<(\\\\|\\>|[^>])*>[egimosx]*), re_tok, :pop!
rule %r(\[(\\\\|\\\]|[^\]])*\][egimosx]*), re_tok, :pop!
rule %r[\((\\\\|\\\)|[^\)])*\)[egimosx]*], re_tok, :pop!
rule %r(@(\\\\|\\\@|[^\@])*@[egimosx]*), re_tok, :pop!
rule %r(%(\\\\|\\\%|[^\%])*%[egimosx]*), re_tok, :pop!
rule %r(\$(\\\\|\\\$|[^\$])*\$[egimosx]*), re_tok, :pop!
end
state :root do
rule /#.*?$/, Comment::Single
rule /^=[a-zA-Z0-9]+\s+.*?\n=cut/, Comment::Multiline
rule /(?:#{keywords.join('|')})\b/, Keyword
rule /(format)(\s+)([a-zA-Z0-9_]+)(\s*)(=)(\s*\n)/ do
groups Keyword, Text, Name, Text, Punctuation, Text
push :format
end
rule /(?:eq|lt|gt|le|ge|ne|not|and|or|cmp)\b/, Operator::Word
# common delimiters
rule %r(s/(\\\\|\\/|[^/])*/(\\\\|\\/|[^/])*/[egimosx]*), re_tok
rule %r(s!(\\\\|\\!|[^!])*!(\\\\|\\!|[^!])*![egimosx]*), re_tok
rule %r(s\\(\\\\|[^\\])*\\(\\\\|[^\\])*\\[egimosx]*), re_tok
rule %r(s@(\\\\|\\@|[^@])*@(\\\\|\\@|[^@])*@[egimosx]*), re_tok
rule %r(s%(\\\\|\\%|[^%])*%(\\\\|\\%|[^%])*%[egimosx]*), re_tok
# balanced delimiters
rule %r(s{(\\\\|\\}|[^}])*}\s*), re_tok, :balanced_regex
rule %r(s<(\\\\|\\>|[^>])*>\s*), re_tok, :balanced_regex
rule %r(s\[(\\\\|\\\]|[^\]])*\]\s*), re_tok, :balanced_regex
rule %r[s\((\\\\|\\\)|[^\)])*\)\s*], re_tok, :balanced_regex
rule %r(m?/(\\\\|\\/|[^/\n])*/[gcimosx]*), re_tok
rule %r(m(?=[/!\\{<\[\(@%\$])), re_tok, :balanced_regex
rule %r(((?<==~)|(?<=\())\s*/(\\\\|\\/|[^/])*/[gcimosx]*),
re_tok, :balanced_regex
rule /\s+/, Text
rule /(?:#{builtins.join('|')})\b/, Name::Builtin
rule /((__(DATA|DIE|WARN)__)|(STD(IN|OUT|ERR)))\b/,
Name::Builtin::Pseudo
rule /<<([\'"]?)([a-zA-Z_][a-zA-Z0-9_]*)\1;?\n.*?\n\2\n/m, Str
rule /__END__\b/, Comment::Preproc, :end_part
rule /\$\^[ADEFHILMOPSTWX]/, Name::Variable::Global
rule /\$[\\"'\[\]&`+*.,;=%~?@$!<>(^\|\/-](?!\w)/, Name::Variable::Global
rule /[$@%#]+/, Name::Variable, :varname
rule /0_?[0-7]+(_[0-7]+)*/, Num::Oct
rule /0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*/, Num::Hex
rule /0b[01]+(_[01]+)*/, Num::Bin
rule /(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?/i,
Num::Float
rule /\d+(_\d*)*e[+-]?\d+(_\d*)*/i, Num::Float
rule /\d+(_\d+)*/, Num::Integer
rule /'(\\\\|\\'|[^'])*'/, Str
rule /"(\\\\|\\"|[^"])*"/, Str
rule /`(\\\\|\\`|[^`])*`/, Str::Backtick
rule /<([^\s>]+)>/, re_tok
rule /(q|qq|qw|qr|qx)\{/, Str::Other, :cb_string
rule /(q|qq|qw|qr|qx)\(/, Str::Other, :rb_string
rule /(q|qq|qw|qr|qx)\[/, Str::Other, :sb_string
rule /(q|qq|qw|qr|qx)</, Str::Other, :lt_string
rule /(q|qq|qw|qr|qx)([^a-zA-Z0-9])(.|\n)*?\2/, Str::Other
rule /package\s+/, Keyword, :modulename
rule /sub\s+/, Keyword, :funcname
rule /\[\]|\*\*|::|<<|>>|>=|<=|<=>|={3}|!=|=~|!~|&&?|\|\||\.{1,3}/,
Operator
rule /[-+\/*%=<>&^\|!\\~]=?/, Operator
rule /[()\[\]:;,<>\/?{}]/, Punctuation
rule(/(?=\w)/) { push :name }
end
state :format do
rule /\.\n/, Str::Interpol, :pop!
rule /.*?\n/, Str::Interpol
end
state :name_common do
rule /\w+::/, Name::Namespace
rule /[\w:]+/, Name::Variable, :pop!
end
state :varname do
rule /\s+/, Text
rule /\{/, Punctuation, :pop! # hash syntax
rule /\)|,/, Punctuation, :pop! # arg specifier
mixin :name_common
end
state :name do
mixin :name_common
rule /[A-Z_]+(?=[^a-zA-Z0-9_])/, Name::Constant, :pop!
rule(/(?=\W)/) { pop! }
end
state :modulename do
rule /[a-z_]\w*/i, Name::Namespace, :pop!
end
state :funcname do
rule /[a-zA-Z_]\w*[!?]?/, Name::Function
rule /\s+/, Text
# argument declaration
rule /(\([$@%]*\))(\s*)/ do
groups Punctuation, Text
end
rule /.*?{/, Punctuation, :pop!
rule /;/, Punctuation, :pop!
end
[[:cb, '\{', '\}'],
[:rb, '\(', '\)'],
[:sb, '\[', '\]'],
[:lt, '<', '>']].each do |name, open, close|
tok = Str::Other
state :"#{name}_string" do
rule /\\[#{open}#{close}\\]/, tok
rule /\\/, tok
rule(/#{open}/) { token tok; push }
rule /#{close}/, tok, :pop!
rule /[^#{open}#{close}\\]+/, tok
end
end
state :end_part do
# eat the rest of the stream
rule /.+/m, Comment::Preproc, :pop!
end
end
end
end
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (C) 2016 AppTik Project
#
# 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.
#
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
POM_URL=https://github.com/apptik/multiview/tree/master/extras
POM_SCM_URL=https://github.com/apptik/multiview/tree/master/extras
POM_NAME=Extras toolkit library for RecyclerView
POM_ARTIFACT_ID=extras
|
{
"pile_set_name": "Github"
}
|
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { IEdge, INode, ITooltip, IZoom } from 'viser-graph';
class Props {}
// tslint:disable-next-line:max-classes-per-file
class SubComponent<T = {}> extends React.Component<Props & T, any> {
public static contextTypes = {
centralizedUpdates: PropTypes.func,
hasInViews: PropTypes.bool,
viewId: PropTypes.string,
viewType: PropTypes.string,
};
public displayName = 'SubComponent';
constructor(props: Props & T) {
super(props);
}
public componentDidUpdate() {
this.context.centralizedUpdates(this);
}
public componentDidMount() {
this.context.centralizedUpdates(this);
}
public render() {
return null;
}
}
// tslint:disable-next-line:max-classes-per-file
export class Zoom extends SubComponent<IZoom> { public displayName = 'Zoom'; }
// tslint:disable-next-line:max-classes-per-file
export class Node extends SubComponent<INode> { public displayName = 'Node'; }
// tslint:disable-next-line:max-classes-per-file
export class Edge extends SubComponent<IEdge> { public displayName = 'Edge'; }
// tslint:disable-next-line:max-classes-per-file
export class Tooltip extends SubComponent<ITooltip> { public displayName = 'Tooltip'; }
|
{
"pile_set_name": "Github"
}
|
#pragma once
#include "stdafx.h"
#include <Xinput.h>
class Console;
class XInputManager
{
private:
shared_ptr<Console> _console;
vector<shared_ptr<XINPUT_STATE>> _gamePadStates;
vector<uint8_t> _gamePadConnected;
public:
XInputManager(shared_ptr<Console> console);
bool NeedToUpdate();
void UpdateDeviceList();
void RefreshState();
bool IsPressed(uint8_t gamepadPort, uint8_t button);
};
|
{
"pile_set_name": "Github"
}
|
@if-sdf = 0
sdf 101, 0
msg -1, -1, -1
pic 0, 4
ex1 1, 1, -1
ex2 -1, -1, -1
goto 2
@death = 1
sdf -1, -1
msg 0, 1, -1
pic 0, 4
ex1 0, 1, -1
ex2 -1, -1, -1
goto -1
@once-disp-msg = 2
sdf 6, 0
msg 2, 3, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@block-move = 3
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 0, -1, -1
ex2 0, -1, -1
goto 4
@once-dlog = 4
sdf -1, -1
msg 4, -1, 1
pic 16, 3
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@once-disp-msg = 5
sdf 6, 1
msg 10, 11, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@once-disp-msg = 6
sdf 6, 2
msg 12, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@once-disp-msg = 7
sdf 6, 3
msg 13, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@once-disp-msg = 8
sdf 6, 4
msg 14, 15, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@block-move = 9
sdf -1, -1
msg 16, 17, -1
pic 0, 4
ex1 0, -1, -1
ex2 0, -1, -1
goto 10
@change-ter = 10
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 44, 16, -1
ex2 128, -1, -1
goto -1
@disp-msg = 11
sdf -1, -1
msg 18, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@block-move = 12
sdf -1, -1
msg 19, -1, -1
pic 0, 4
ex1 0, -1, -1
ex2 0, -1, -1
goto -1
@disp-msg = 13
sdf -1, -1
msg 20, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@once-dlog = 14
sdf 6, 5
msg 21, -1, 1
pic 133, 1
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@if-spec-item = 15
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 5, 17, -1
ex2 -1, -1, -1
goto 16
@disp-msg = 16
sdf -1, -1
msg 27, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@once-dlog = 17
sdf -1, -1
msg 28, -1, 1
pic 107, 1
ex1 45, 18, -1
ex2 -1, -1, -1
goto -1
@once-dlog = 18
sdf -1, -1
msg 34, -1, 1
pic 16, 3
ex1 -1, -1, -1
ex2 -1, -1, -1
goto 19
@anim-explode = 19
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 30, 10, -1
ex2 0, -1, -1
goto 20
@anim-explode = 20
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 32, 7, -1
ex2 0, -1, -1
goto 21
@anim-explode = 21
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 32, 11, -1
ex2 0, -1, -1
goto 22
@once-dlog = 22
sdf -1, -1
msg 40, -1, 1
pic 17, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto 23
@damage = 23
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 8, 8, -1
ex2 4, 0, -1
goto 24
@once-dlog = 24
sdf -1, -1
msg 46, -1, 1
pic 107, 1
ex1 -1, -1, -1
ex2 -1, -1, -1
goto 34
@once-disp-msg = 25
sdf 6, 6
msg 52, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@if-sdf = 26
sdf 0, 6
msg -1, -1, -1
pic 0, 4
ex1 1, 27, -1
ex2 -1, -1, -1
goto 28
@disp-msg = 27
sdf -1, -1
msg 53, -1, -1
pic 0, 4
ex1 -1, -1, -1
ex2 -1, -1, -1
goto -1
@if-spec-item = 28
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 12, 29, -1
ex2 -1, -1, -1
goto -1
@once-give-spec-item = 29
sdf -1, -1
msg 54, 55, -1
pic 0, 4
ex1 12, 1, -1
ex2 -1, -1, -1
goto 30
@set-sdf = 30
sdf 0, 6
msg -1, -1, -1
pic 0, 4
ex1 1, -1, -1
ex2 -1, -1, -1
goto 31
@gold = 31
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 10, 0, -1
ex2 -1, -1, -1
goto 32
@xp = 32
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 5, 0, -1
ex2 -1, -1, -1
goto -1
@stair = 33
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 1, 23, -1
ex2 9, 1, -1
goto -1
@once-give-spec-item = 34
sdf -1, -1
msg -1, -1, -1
pic 0, 4
ex1 5, 1, -1
ex2 -1, -1, -1
goto 35
@set-sdf = 35
sdf 101, 0
msg -1, -1, -1
pic 0, 4
ex1 1, -1, -1
ex2 -1, -1, -1
goto 33
|
{
"pile_set_name": "Github"
}
|
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may 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.
//
// @@@ END COPYRIGHT @@@
//
**********************************************************************/
#ifndef _RU_SQL_MULTI_TXN_REFRESH_COMPOSER_H_
#define _RU_SQL_MULTI_TXN_REFRESH_COMPOSER_H_
/* -*-C++-*-
******************************************************************************
*
* File: RuSQLMultiTxnRefreshComposer.h
* Description: Definition of class CRUSQLRefreshComposer
*
*
* Created: 08/17/2000
* Language: C++
*
*
*
******************************************************************************
*/
#include "RuSQLRefreshComposer.h"
class REFRESH_LIB_CLASS CRUSQLMultiTxnRefreshComposer : public CRUSQLRefreshComposer {
public:
CRUSQLMultiTxnRefreshComposer(CRURefreshTask *pTask);
virtual ~CRUSQLMultiTxnRefreshComposer() {}
public:
void ComposeRefresh(Int32 phase, BOOL catchup);
private:
void AddNRowsClause(Int32 phase, BOOL catchup);
};
#endif
|
{
"pile_set_name": "Github"
}
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.envers.internal.entities.mapper.relation.query;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.envers.configuration.internal.AuditEntitiesConfiguration;
import org.hibernate.envers.configuration.internal.GlobalConfiguration;
import org.hibernate.envers.internal.entities.mapper.relation.MiddleComponentData;
import org.hibernate.envers.internal.entities.mapper.relation.MiddleIdData;
import org.hibernate.envers.internal.tools.query.Parameters;
import org.hibernate.envers.internal.tools.query.QueryBuilder;
import org.hibernate.envers.strategy.AuditStrategy;
import org.hibernate.internal.util.StringHelper;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.DEL_REVISION_TYPE_PARAMETER;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.INDEX_ENTITY_ALIAS;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.INDEX_ENTITY_ALIAS_DEF_AUD_STR;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.MIDDLE_ENTITY_ALIAS;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.REFERENCED_ENTITY_ALIAS;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.REFERENCED_ENTITY_ALIAS_DEF_AUD_STR;
import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.REVISION_PARAMETER;
/**
* Selects data from a relation middle-table and a two related versions entity.
*
* @author Adam Warski (adam at warski dot org)
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
* @author Chris Cranford
*/
public final class ThreeEntityQueryGenerator extends AbstractRelationQueryGenerator {
private final MiddleIdData referencedIdData;
private final MiddleIdData indexIdData;
private final MiddleComponentData[] componentDatas;
public ThreeEntityQueryGenerator(
GlobalConfiguration globalCfg,
AuditEntitiesConfiguration verEntCfg,
AuditStrategy auditStrategy,
String versionsMiddleEntityName,
MiddleIdData referencingIdData,
MiddleIdData referencedIdData,
MiddleIdData indexIdData,
boolean revisionTypeInId,
String orderBy,
MiddleComponentData... componentData) {
super(
globalCfg,
verEntCfg,
auditStrategy,
versionsMiddleEntityName,
referencingIdData,
revisionTypeInId,
orderBy
);
this.referencedIdData = referencedIdData;
this.indexIdData = indexIdData;
this.componentDatas = componentData;
/*
* The valid query that we need to create:
* SELECT new list(ee, e, f) FROM versionsReferencedEntity e, versionsIndexEntity f, middleEntity ee
* WHERE
* (entities referenced by the middle table; id_ref_ed = id of the referenced entity)
* ee.id_ref_ed = e.id_ref_ed AND
* (entities referenced by the middle table; id_ref_ind = id of the index entity)
* ee.id_ref_ind = f.id_ref_ind AND
* (only entities referenced by the association; id_ref_ing = id of the referencing entity)
* ee.id_ref_ing = :id_ref_ing AND
* (selecting e entities at revision :revision)
* --> for DefaultAuditStrategy:
* e.revision = (SELECT max(e2.revision) FROM versionsReferencedEntity e2
* WHERE e2.revision <= :revision AND e2.id = e.id)
*
* --> for ValidityAuditStrategy:
* e.revision <= :revision and (e.endRevision > :revision or e.endRevision is null)
*
* AND
*
* (selecting f entities at revision :revision)
* --> for DefaultAuditStrategy:
* f.revision = (SELECT max(f2.revision) FROM versionsIndexEntity f2
* WHERE f2.revision <= :revision AND f2.id_ref_ed = f.id_ref_ed)
*
* --> for ValidityAuditStrategy:
* f.revision <= :revision and (f.endRevision > :revision or f.endRevision is null)
*
* AND
*
* (the association at revision :revision)
* --> for DefaultAuditStrategy:
* ee.revision = (SELECT max(ee2.revision) FROM middleEntity ee2
* WHERE ee2.revision <= :revision AND ee2.originalId.* = ee.originalId.*)
*
* --> for ValidityAuditStrategy:
* ee.revision <= :revision and (ee.endRevision > :revision or ee.endRevision is null)
* and ( strtestent1_.REVEND>? or strtestent1_.REVEND is null )
* and ( strtestent1_.REVEND>? or strtestent1_.REVEND is null )
* and ( ternarymap0_.REVEND>? or ternarymap0_.REVEND is null )
*
* (only non-deleted entities and associations)
* ee.revision_type != DEL AND
* e.revision_type != DEL AND
* f.revision_type != DEL
*/
}
@Override
protected QueryBuilder buildQueryBuilderCommon(SessionFactoryImplementor sessionFactory) {
final String originalIdPropertyName = verEntCfg.getOriginalIdPropName();
final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName;
// SELECT new list(ee) FROM middleEntity ee
final QueryBuilder qb = new QueryBuilder( entityName, MIDDLE_ENTITY_ALIAS, sessionFactory );
qb.addFrom( referencedIdData.getAuditEntityName(), REFERENCED_ENTITY_ALIAS, false );
qb.addFrom( indexIdData.getAuditEntityName(), INDEX_ENTITY_ALIAS, false );
qb.addProjection(
"new list", MIDDLE_ENTITY_ALIAS + ", " + REFERENCED_ENTITY_ALIAS + ", " + INDEX_ENTITY_ALIAS,
null, false
);
// WHERE
final Parameters rootParameters = qb.getRootParameters();
// ee.id_ref_ed = e.id_ref_ed
referencedIdData.getPrefixedMapper().addIdsEqualToQuery(
rootParameters, eeOriginalIdPropertyPath, referencedIdData.getOriginalMapper(),
REFERENCED_ENTITY_ALIAS + "." + originalIdPropertyName
);
// ee.id_ref_ind = f.id_ref_ind
indexIdData.getPrefixedMapper().addIdsEqualToQuery(
rootParameters, eeOriginalIdPropertyPath, indexIdData.getOriginalMapper(),
INDEX_ENTITY_ALIAS + "." + originalIdPropertyName
);
// ee.originalId.id_ref_ing = :id_ref_ing
referencingIdData.getPrefixedMapper().addNamedIdEqualsToQuery( rootParameters, originalIdPropertyName, true );
// ORDER BY
// Hibernate applies @OrderBy on map elements, not the key.
// So here we apply it to the referenced entity, not the actual index entity that represents the key.
if ( !StringHelper.isEmpty( orderBy ) ) {
qb.addOrderFragment( REFERENCED_ENTITY_ALIAS, orderBy );
}
return qb;
}
@Override
protected void applyValidPredicates(QueryBuilder qb, Parameters rootParameters, boolean inclusive) {
final String revisionPropertyPath = verEntCfg.getRevisionNumberPath();
final String originalIdPropertyName = verEntCfg.getOriginalIdPropName();
final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName;
final String revisionTypePropName = getRevisionTypePath();
// (selecting e entities at revision :revision)
// --> based on auditStrategy (see above)
auditStrategy.addEntityAtRevisionRestriction(
globalCfg,
qb,
rootParameters,
REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath,
REFERENCED_ENTITY_ALIAS + "." + verEntCfg.getRevisionEndFieldName(),
false,
referencedIdData,
revisionPropertyPath,
originalIdPropertyName,
REFERENCED_ENTITY_ALIAS,
REFERENCED_ENTITY_ALIAS_DEF_AUD_STR,
true
);
// (selecting f entities at revision :revision)
// --> based on auditStrategy (see above)
auditStrategy.addEntityAtRevisionRestriction(
globalCfg,
qb,
rootParameters,
INDEX_ENTITY_ALIAS + "." + revisionPropertyPath,
INDEX_ENTITY_ALIAS + "." + verEntCfg.getRevisionEndFieldName(),
false,
indexIdData,
revisionPropertyPath,
originalIdPropertyName,
INDEX_ENTITY_ALIAS,
INDEX_ENTITY_ALIAS_DEF_AUD_STR,
true
);
// (with ee association at revision :revision)
// --> based on auditStrategy (see above)
auditStrategy.addAssociationAtRevisionRestriction(
qb,
rootParameters,
revisionPropertyPath,
verEntCfg.getRevisionEndFieldName(),
true,
referencingIdData,
entityName,
eeOriginalIdPropertyPath,
revisionPropertyPath,
originalIdPropertyName,
MIDDLE_ENTITY_ALIAS,
inclusive,
componentDatas
);
// ee.revision_type != DEL
rootParameters.addWhereWithNamedParam( revisionTypePropName, "!=", DEL_REVISION_TYPE_PARAMETER );
// e.revision_type != DEL
rootParameters.addWhereWithNamedParam(
REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName,
false,
"!=",
DEL_REVISION_TYPE_PARAMETER
);
// f.revision_type != DEL
rootParameters.addWhereWithNamedParam(
INDEX_ENTITY_ALIAS + "." + revisionTypePropName,
false,
"!=",
DEL_REVISION_TYPE_PARAMETER
);
}
@Override
protected void applyValidAndRemovePredicates(QueryBuilder remQb) {
final Parameters disjoint = remQb.getRootParameters().addSubParameters( "or" );
// Restrictions to match all valid rows.
final Parameters valid = disjoint.addSubParameters( "and" );
// Restrictions to match all rows deleted at exactly given revision.
final Parameters removed = disjoint.addSubParameters( "and" );
final String revisionPropertyPath = verEntCfg.getRevisionNumberPath();
final String revisionTypePropName = getRevisionTypePath();
// Excluding current revision, because we need to match data valid at the previous one.
applyValidPredicates( remQb, valid, false );
// ee.revision = :revision
removed.addWhereWithNamedParam( revisionPropertyPath, "=", REVISION_PARAMETER );
// e.revision = :revision
removed.addWhereWithNamedParam(
REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath,
false,
"=",
REVISION_PARAMETER
);
// f.revision = :revision
removed.addWhereWithNamedParam(
INDEX_ENTITY_ALIAS + "." + revisionPropertyPath,
false,
"=",
REVISION_PARAMETER
);
// ee.revision_type = DEL
removed.addWhereWithNamedParam( revisionTypePropName, "=", DEL_REVISION_TYPE_PARAMETER );
// e.revision_type = DEL
removed.addWhereWithNamedParam(
REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName,
false,
"=",
DEL_REVISION_TYPE_PARAMETER
);
// f.revision_type = DEL
removed.addWhereWithNamedParam(
INDEX_ENTITY_ALIAS + "." + revisionTypePropName,
false,
"=",
DEL_REVISION_TYPE_PARAMETER
);
}
}
|
{
"pile_set_name": "Github"
}
|
/*
*
* Copyright (c) 2006-2020, Speedment, 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.
*/
package com.speedment.tool.core.internal.util;
import com.speedment.common.logger.Logger;
import com.speedment.common.logger.LoggerManager;
import javafx.stage.Stage;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
/**
* Utility class for method related to window settings, such as size, position
* and whether the window was maximized or not.
*
* @author Simon Jonasson
* @since 3.0.0
*/
final class WindowSettingUtil {
private static final Logger LOGGER = LoggerManager.getLogger(WindowSettingUtil.class);
private static final Preferences PREFERENCES = Preferences.userNodeForPackage(WindowSettingUtil.class);
private static final String WINDOW_WIDTH = "windowWidth";
private static final String WINDOW_HEIGHT = "windowHeight";
private static final String WINDOW_X_POS = "windowXPos";
private static final String WINDOW_Y_POS = "windowYPos";
private static final String WINDOW_MAXIMIZED = "windowMaximized";
private static final double DEFUALT_WIDTH = 1280;
private static final double DEFUALT_HEIHGT = 720;
private static final double DEFUALT_X = 0;
private static final double DEFUALT_Y = 0;
private WindowSettingUtil() {}
/**
* Retrieves data about he window settings from the previous session and applies
* them to the stage. These settings include window size, position and if
* it was maximized or not.
*
* @param stage the stage to apply these settings to
* @param name the name under which we stored the settings
*/
static void applyStoredDisplaySettings(Stage stage, String name){
try {
if( PREFERENCES.nodeExists(name) ){
Preferences stagePreferences = PREFERENCES.node(name);
boolean wasMaximized = stagePreferences.getBoolean(WINDOW_MAXIMIZED, false);
if( wasMaximized ){
stage.setMaximized(true);
} else {
stage.setX( stagePreferences.getDouble(WINDOW_X_POS, DEFUALT_X));
stage.setY( stagePreferences.getDouble(WINDOW_Y_POS, DEFUALT_Y));
stage.setWidth( stagePreferences.getDouble(WINDOW_WIDTH, DEFUALT_WIDTH));
stage.setHeight(stagePreferences.getDouble(WINDOW_HEIGHT, DEFUALT_HEIHGT));
}
}
} catch (BackingStoreException ex) {
LOGGER.error(ex, "Could not access preferences for window " + name);
}
}
/**
* Adds an OnCloseRequest handle to the window which will store the position,
* size and maximized status of the window.
*
* @param stage the stage to read settings from
* @param name the name under which we store the settings
*/
static void applySaveOnCloseMethod(Stage stage, String name){
stage.setOnCloseRequest( ev -> {
try {
Preferences stagePreferences = PREFERENCES.node(name);
if( stage.isMaximized() ){
stagePreferences.putBoolean(WINDOW_MAXIMIZED, true);
} else {
stagePreferences.putBoolean(WINDOW_MAXIMIZED, false);
stagePreferences.putDouble(WINDOW_X_POS, stage.getX());
stagePreferences.putDouble(WINDOW_Y_POS, stage.getY());
stagePreferences.putDouble(WINDOW_WIDTH, stage.getWidth());
stagePreferences.putDouble(WINDOW_HEIGHT, stage.getHeight());
}
stagePreferences.flush();
} catch (final BackingStoreException ex) {
LOGGER.error(ex, "Could not flush preferences for window " + name);
}
});
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2011-2016 OpenDungeons Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CREATURESKILLMELEEFIGHT_H
#define CREATURESKILLMELEEFIGHT_H
#include "creatureskill/CreatureSkill.h"
#include <cstdint>
#include <iosfwd>
#include <string>
class Creature;
class GameMap;
class CreatureSkillMeleeFight : public CreatureSkill
{
public:
// Constructors
CreatureSkillMeleeFight() :
mCreatureLevelMin(0),
mPhyAtk(0.0),
mPhyAtkPerLvl(0.0),
mMagAtk(0.0),
mMagAtkPerLvl(0.0),
mEleAtk(0.0),
mEleAtkPerLvl(0.0)
{}
virtual ~CreatureSkillMeleeFight()
{}
virtual const std::string& getSkillName() const override;
virtual double getRangeMax(const Creature* creature, GameEntity* entityAttack) const override
{ return 1.0; }
virtual bool canBeUsedBy(const Creature* creature) const override;
virtual bool tryUseSupport(GameMap& gameMap, Creature* creature) const override
{ return false; }
virtual bool tryUseFight(GameMap& gameMap, Creature* creature, float range,
GameEntity* attackedObject, Tile* attackedTile, bool ko, bool notifyPlayerIfHit) const override;
virtual CreatureSkillMeleeFight* clone() const override;
virtual bool isEqual(const CreatureSkill& creatureSkill) const override;
virtual void getFormatString(std::string& format) const override;
virtual void exportToStream(std::ostream& os) const override;
virtual bool importFromStream(std::istream& is) override;
private:
uint32_t mCreatureLevelMin;
double mPhyAtk;
double mPhyAtkPerLvl;
double mMagAtk;
double mMagAtkPerLvl;
double mEleAtk;
double mEleAtkPerLvl;
};
#endif // CREATURESKILLMELEEFIGHT_H
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.