content
stringlengths 10
4.9M
|
---|
<gh_stars>10-100
#pragma once
#include <exceptxx/Util.h>
#include <exceptxx/BaseExceptionImpl.h>
#include <exceptxx/ThrowHelper.h>
#include <cassert>
namespace exceptxx
{
class AssertException : public BaseExceptionImpl<AssertException>
{
public:
using Error = string;
AssertException(Error error, const char* func, size_t line, string&& message) : BaseExceptionImpl(func, line, move(message)), m_error(error)
{
}
virtual const char* tag() const override
{
return "ASSERT";
}
virtual string error() const override
{
return m_error;
}
virtual string description() const override
{
return "Assertion failed";
}
private:
const Error m_error;
};
}
#define CHECK_ASSERT(cond) if (!(cond)) assert(#cond && false),THROW_HELPER(AssertException, #cond)
|
/**
* defines how a selected item is edited
*/
public class SurfaceItemEditor implements Syncable {
private final EditBinding binding;
private final SurfaceData data;
private final EditableSelect selector;
private boolean skip = false;
private final Surface surface;
private final Syncable syncable;
private final VBox vbox;
/**
* @param selector
* how to select the currently selected item
* @param vbox
* where we render the items
* @param data
* the data to connect with
* @param surface
* the surace to render
* @param syncable
* how we update other views
*/
public SurfaceItemEditor(final EditableSelect selector, final VBox vbox, final SurfaceData data, final Surface surface, final Syncable syncable, final Notifications notify) {
this.selector = selector;
this.vbox = vbox;
this.data = data;
this.surface = surface;
this.syncable = syncable;
binding = new EditBinding(vbox, () -> refresh(), notify);
}
/**
* update the view from a value change
*/
private void refresh() {
skip = true;
try {
syncable.sync();
} finally {
skip = false;
}
surface.render();
}
/**
* Update the panel
*/
@Override
public void sync() {
if (skip) {
return;
}
final SurfaceItemEditorBuilderImpl builder = new SurfaceItemEditorBuilderImpl(vbox, binding);
boolean empty = true;
Editable editable = selector.current();
if (editable == null) {
final Set<Editable> editables = data.getEditables();
if (editables.size() == 1) {
editable = editables.iterator().next();
}
}
if (editable != null) {
empty = false;
editable.createEditor(data, builder, this);
}
if (empty) {
binding.resetFocus();
}
binding.focus();
}
}
|
/**
* Test various multiput operations.
* @throws Exception
*/
@Test
public void testMulti() throws Exception {
createTable(TestMultiMutationCoprocessor.class.getName());
try (Table t = util.getConnection().getTable(tableName)) {
t.put(new Put(row1).addColumn(test, dummy, dummy));
assertRowCount(t, 3);
}
}
|
// Checks that prerenderers will terminate when an audio tag is encountered.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5Audio) {
PrerenderTestURL("files/prerender/prerender_html5_audio.html",
FINAL_STATUS_HTML5_MEDIA,
1);
}
|
/*
* $Id$
*
* 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.
*/
package org.apache.tiles.request.velocity.autotag;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import java.io.Writer;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tiles.autotag.core.runtime.ModelBody;
import org.apache.tiles.request.ApplicationAccess;
import org.apache.tiles.request.ApplicationContext;
import org.apache.tiles.request.Request;
import org.apache.tiles.request.velocity.VelocityRequest;
import org.apache.tiles.request.velocity.autotag.VelocityAutotagRuntime;
import org.apache.tiles.request.velocity.autotag.VelocityModelBody;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.runtime.parser.node.ASTBlock;
import org.apache.velocity.runtime.parser.node.ASTMap;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.tools.view.ViewToolContext;
import org.junit.Test;
public class VelocityAutotagRuntimeTest {
@Test
public void testCreateRequest() {
InternalContextAdapter context = createMock(InternalContextAdapter.class);
Writer writer = createMock(Writer.class);
Node node = createMock(Node.class);
ViewToolContext viewContext = createMock(ViewToolContext.class);
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
ServletContext servletContext = createMock(ServletContext.class);
ApplicationContext applicationContext = createMock(ApplicationContext.class);
expect(context.getInternalUserContext()).andReturn(viewContext);
expect(viewContext.getRequest()).andReturn(request);
expect(viewContext.getResponse()).andReturn(response);
expect(viewContext.getServletContext()).andReturn(servletContext);
expect(servletContext.getAttribute(ApplicationAccess.APPLICATION_CONTEXT_ATTRIBUTE)).andReturn(applicationContext);
replay(context, writer, node, viewContext, request, response, servletContext, applicationContext);
VelocityAutotagRuntime runtime = new VelocityAutotagRuntime();
runtime.render(context, writer, node);
Request velocityRequest = runtime.createRequest();
assertTrue(velocityRequest instanceof VelocityRequest);
verify(context, writer, node, viewContext, request, response, servletContext, applicationContext);
}
@Test
public void testCreateModelBody() {
InternalContextAdapter context = createMock(InternalContextAdapter.class);
Writer writer = createMock(Writer.class);
Node node = createMock(Node.class);
ASTBlock block = createMock(ASTBlock.class);
expect(node.jjtGetChild(1)).andReturn(block);
replay(context, writer, node, block);
VelocityAutotagRuntime runtime = new VelocityAutotagRuntime();
runtime.render(context, writer, node);
ModelBody modelBody = runtime.createModelBody();
assertTrue(modelBody instanceof VelocityModelBody);
verify(context, writer, node, block);
}
@Test
public void testGetParameter() {
InternalContextAdapter context = createMock(InternalContextAdapter.class);
Writer writer = createMock(Writer.class);
Node node = createMock(Node.class);
ASTMap astMap = createMock(ASTMap.class);
@SuppressWarnings("unchecked")
Map<String, Object> params = createMock(Map.class);
expect(node.jjtGetChild(0)).andReturn(astMap);
expect(astMap.value(context)).andReturn(params);
expect(params.get(eq("notnullParam"))).andReturn(new Integer(42)).anyTimes();
expect(params.get(eq("nullParam"))).andReturn(null).anyTimes();
replay(context, writer, node, astMap, params);
VelocityAutotagRuntime runtime = new VelocityAutotagRuntime();
runtime.render(context, writer, node);
Object notnullParam = runtime.getParameter("notnullParam", Object.class, null);
Object nullParam = runtime.getParameter("nullParam", Object.class, null);
int notnullParamDefault = runtime.getParameter("notnullParam", Integer.class, new Integer(24));
int nullParamDefault = runtime.getParameter("nullParam", Integer.class, new Integer(24));
assertEquals(42, notnullParam);
assertEquals(null, nullParam);
assertEquals(42, notnullParamDefault);
assertEquals(24, nullParamDefault);
verify(context, writer, node, astMap, params);
}
}
|
import { setupDomTests } from '../util';
describe('custom-elements-delegates-focus', () => {
const { setupDom, tearDownDom } = setupDomTests(document);
let app: HTMLElement;
beforeEach(async () => {
app = await setupDom('/custom-elements-delegates-focus/index.html');
});
afterEach(tearDownDom);
it('sets delegatesFocus correctly', async () => {
expect(customElements.get('custom-elements-delegates-focus')).toBeDefined();
const elm: Element = app.querySelector('custom-elements-delegates-focus');
expect(elm.shadowRoot).toBeDefined();
// as of TypeScript 4.3, `delegatesFocus` does not exist on the `shadowRoot` object
expect((elm.shadowRoot as any).delegatesFocus).toBe(true);
});
it('does not set delegatesFocus when shadow is set to "true"', async () => {
expect(customElements.get('custom-elements-no-delegates-focus')).toBeDefined();
const elm: Element = app.querySelector('custom-elements-no-delegates-focus');
expect(elm.shadowRoot).toBeDefined();
// as of TypeScript 4.3, `delegatesFocus` does not exist on the `shadowRoot` object
expect((elm.shadowRoot as any).delegatesFocus).toBe(false);
});
});
|
<filename>StarExec/src/z3/src/util/bit_util.cpp
/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
bit_util.cpp
Abstract:
Bit hacking utilities.
Author:
<NAME> (leonardo) 2012-09-11.
Revision History:
--*/
#include "util/bit_util.h"
#include "util/util.h"
#include "util/debug.h"
#include <cstring>
/**
\brief (Debugging version) Return the position of the most significant (set) bit of a
nonzero unsigned integer.
*/
#ifdef Z3DEBUG
unsigned slow_msb_pos(unsigned v) {
SASSERT(v != 0);
unsigned r = 0;
while (v != 1) {
v = v >> 1;
r++;
}
return r;
}
#endif
/**
\brief Return the position of the most significant (set) bit of a
nonzero unsigned integer.
*/
unsigned msb_pos(unsigned v) {
SASSERT(v != 0);
#ifdef Z3DEBUG
unsigned expected = slow_msb_pos(v);
#endif
unsigned r, shift;
r = (v > 0xFFFF) << 4;
v >>= r;
shift = (v > 0xFF) << 3;
v >>= shift;
r |= shift;
shift = (v > 0xF) << 2;
v >>= shift;
r |= shift;
shift = (v > 0x3) << 1;
v >>= shift;
r |= shift;
r |= (v >> 1);
SASSERT(r == expected);
return r;
}
/**
\brief Return the number of leading zeros bits in a nonzero unsigned integer.
*/
unsigned nlz_core(unsigned x) {
SASSERT(x != 0);
#ifdef __GNUC__
return __builtin_clz(x);
#else
return 31 - msb_pos(x);
#endif
}
/**
\brief Return the number of leading zero bits in data (a number of sz words).
*/
unsigned nlz(unsigned sz, unsigned const * data) {
unsigned r = 0;
unsigned i = sz;
while (i > 0) {
--i;
unsigned d = data[i];
if (d == 0)
r += 32;
else
return r + nlz_core(d);
}
return r;
}
/**
\brief Return the number of trailing zeros in a nonzero unsigned number.
*/
unsigned ntz_core(unsigned x) {
SASSERT(x != 0);
#ifdef __GNUC__
return __builtin_ctz(x);
#else
float f = static_cast<float>(x & static_cast<unsigned>(-static_cast<int>(x)));
unsigned u;
SASSERT(sizeof(u) == sizeof(f));
memcpy(&u, &f, sizeof(u));
return (u >> 23) - 0x7f;
#endif
}
/**
\brief Return the number of trailing zero bits in data (a number of sz words).
*/
unsigned ntz(unsigned sz, unsigned const * data) {
unsigned r = 0;
for (unsigned i = 0; i < sz; i++) {
unsigned d = data[i];
if (d == 0)
r += 32;
else
return r + ntz_core(d);
}
return r;
}
/**
\brief dst <- src
Trucate if src_sz > dst_sz.
Fill range [src_sz, dst_sz) of dst with zeros if dst_sz > src_sz.
*/
void copy(unsigned src_sz, unsigned const * src,
unsigned dst_sz, unsigned * dst) {
if (dst_sz >= src_sz) {
unsigned i;
for (i = 0; i < src_sz; i++)
dst[i] = src[i];
for (; i < dst_sz; i++)
dst[i] = 0;
}
else {
SASSERT(dst_sz < src_sz);
for (unsigned i = 0; i < dst_sz; i++)
dst[i] = src[i];
}
}
/**
\brief Return true if all words of data are zero.
*/
bool is_zero(unsigned sz, unsigned const * data) {
for (unsigned i = 0; i < sz; i++)
if (data[i])
return false;
return true;
}
/**
\brief Set all words of data to zero.
*/
void reset(unsigned sz, unsigned * data) {
for (unsigned i = 0; i < sz; i++)
data[i] = 0;
}
/**
\brief dst <- src << k
Store in dst the result of shifting src k bits to the left.
The result is truncated by dst_sz.
\pre src_sz != 0
\pre dst_sz != 0
*/
void shl(unsigned src_sz, unsigned const * src, unsigned k,
unsigned dst_sz, unsigned * dst) {
SASSERT(src_sz != 0);
SASSERT(dst_sz != 0);
SASSERT(k != 0);
unsigned word_shift = k / (8 * sizeof(unsigned));
unsigned bit_shift = k % (8 * sizeof(unsigned));
if (word_shift > 0) {
unsigned j = src_sz;
unsigned i = src_sz + word_shift;
if (i > dst_sz) {
if (j >= i - dst_sz)
j -= (i - dst_sz);
else
j = 0;
i = dst_sz;
}
else if (i < dst_sz) {
for (unsigned r = i; r < dst_sz; r++)
dst[r] = 0;
}
while (j > 0) {
--j; --i;
dst[i] = src[j];
}
while (i > 0) {
--i;
dst[i] = 0;
}
if (bit_shift > 0) {
unsigned comp_shift = (8 * sizeof(unsigned)) - bit_shift;
unsigned prev = 0;
for (unsigned i = word_shift; i < dst_sz; i++) {
unsigned new_prev = (dst[i] >> comp_shift);
dst[i] <<= bit_shift;
dst[i] |= prev;
prev = new_prev;
}
}
}
else {
unsigned comp_shift = (8 * sizeof(unsigned)) - bit_shift;
unsigned prev = 0;
if (src_sz > dst_sz)
src_sz = dst_sz;
for (unsigned i = 0; i < src_sz; i++) {
unsigned new_prev = (src[i] >> comp_shift);
dst[i] = src[i];
dst[i] <<= bit_shift;
dst[i] |= prev;
prev = new_prev;
}
if (dst_sz > src_sz) {
dst[src_sz] = prev;
for (unsigned i = src_sz+1; i < dst_sz; i++)
dst[i] = 0;
}
}
}
/**
\brief dst <- src >> k
Store in dst the result of shifting src k bits to the right.
\pre dst must have size sz.
\pre src_sz != 0
\pre dst_sz != 0
*/
void shr(unsigned sz, unsigned const * src, unsigned k, unsigned * dst) {
unsigned digit_shift = k / (8 * sizeof(unsigned));
if (digit_shift >= sz) {
reset(sz, dst);
return;
}
unsigned bit_shift = k % (8 * sizeof(unsigned));
unsigned comp_shift = (8 * sizeof(unsigned)) - bit_shift;
unsigned new_sz = sz - digit_shift;
if (new_sz < sz) {
unsigned i = 0;
unsigned j = digit_shift;
if (bit_shift != 0) {
for (; i < new_sz - 1; i++, j++) {
dst[i] = src[j];
dst[i] >>= bit_shift;
dst[i] |= (src[j+1] << comp_shift);
}
dst[i] = src[j];
dst[i] >>= bit_shift;
}
else {
for (; i < new_sz; i++, j++) {
dst[i] = src[j];
}
}
for (unsigned i = new_sz; i < sz; i++)
dst[i] = 0;
}
else {
SASSERT(new_sz == sz);
SASSERT(bit_shift != 0);
unsigned i = 0;
for (; i < new_sz - 1; i++) {
dst[i] = src[i];
dst[i] >>= bit_shift;
dst[i] |= (src[i+1] << comp_shift);
}
dst[i] = src[i];
dst[i] >>= bit_shift;
}
}
void shr(unsigned src_sz, unsigned const * src, unsigned k, unsigned dst_sz, unsigned * dst) {
unsigned digit_shift = k / (8 * sizeof(unsigned));
if (digit_shift >= src_sz) {
reset(dst_sz, dst);
return;
}
unsigned bit_shift = k % (8 * sizeof(unsigned));
unsigned comp_shift = (8 * sizeof(unsigned)) - bit_shift;
unsigned new_sz = src_sz - digit_shift;
if (digit_shift > 0) {
unsigned i = 0;
unsigned j = digit_shift;
if (bit_shift != 0) {
unsigned sz = new_sz;
if (new_sz > dst_sz)
sz = dst_sz;
for (; i < sz - 1; i++, j++) {
dst[i] = src[j];
dst[i] >>= bit_shift;
dst[i] |= (src[j+1] << comp_shift);
}
dst[i] = src[j];
dst[i] >>= bit_shift;
if (new_sz > dst_sz)
dst[i] |= (src[j+1] << comp_shift);
}
else {
if (new_sz > dst_sz)
new_sz = dst_sz;
for (; i < new_sz; i++, j++) {
dst[i] = src[j];
}
}
}
else {
SASSERT(new_sz == src_sz);
SASSERT(bit_shift != 0);
unsigned sz = new_sz;
if (new_sz > dst_sz)
sz = dst_sz;
unsigned i = 0;
for (; i < sz - 1; i++) {
dst[i] = src[i];
dst[i] >>= bit_shift;
dst[i] |= (src[i+1] << comp_shift);
}
dst[i] = src[i];
dst[i] >>= bit_shift;
if (new_sz > dst_sz)
dst[i] |= (src[i+1] << comp_shift);
}
for (unsigned i = new_sz; i < dst_sz; i++)
dst[i] = 0;
}
/**
\brief Return true if one of the first k bits of src is not zero.
*/
bool has_one_at_first_k_bits(unsigned sz, unsigned const * data, unsigned k) {
SASSERT(sz != 0);
unsigned word_sz = k / (8 * sizeof(unsigned));
if (word_sz > sz)
word_sz = sz;
for (unsigned i = 0; i < word_sz; i++) {
if (data[i] != 0)
return true;
}
if (word_sz < sz) {
unsigned bit_sz = k % (8 * sizeof(unsigned));
unsigned mask = (1u << bit_sz) - 1;
return (data[word_sz] & mask) != 0;
}
return false;
}
bool inc(unsigned sz, unsigned * data) {
for (unsigned i = 0; i < sz; i++) {
data[i]++;
if (data[i] != 0)
return true; // no overflow
}
return false; // overflow
}
bool dec(unsigned sz, unsigned * data) {
for (unsigned i = 0; i < sz; i++) {
data[i]--;
if (data[i] != UINT_MAX)
return true; // no underflow
}
return false; // underflow
}
bool lt(unsigned sz, unsigned * data1, unsigned * data2) {
unsigned i = sz;
while (i > 0) {
--i;
if (data1[i] < data2[i])
return true;
if (data1[i] > data2[i])
return false;
}
return false;
}
bool add(unsigned sz, unsigned const * a, unsigned const * b, unsigned * c) {
unsigned k = 0;
for (unsigned j = 0; j < sz; j++) {
unsigned r = a[j] + b[j];
bool c1 = r < a[j];
c[j] = r + k;
bool c2 = c[j] < r;
k = c1 | c2;
}
return k == 0;
}
|
from typing import Optional, Dict, Any, Type, Union, TextIO
from pyjsg.jsglib.jsg_object import JSGObject
from pyjsg.jsglib.conformance import conforms
from pyjsg.jsglib.jsg_strings import JSGString
from pyjsg.jsglib.jsg_validateable import JSGValidateable
from pyjsg.jsglib.jsg_anytype import AnyType
from pyjsg.jsglib.jsg_null import JSGNull
from pyjsg.jsglib.logger import Logger
class JSGObjectMap(JSGObject):
"""
An object map is a JsonObj with constraints on the attribute names, value types of both
"""
_name_filter: type(JSGString) = None
_value_type: type(JSGValidateable) = AnyType
_min: int = 0
_max: Optional[int] = None
_strict = False
def __setattr__(self, key: str, value: Any):
"""
Screen attributes for name and type. Anything starting with underscore ('_') goes, anything in the IGNORE list
and anything declared in the __init_ signature
:param key:
:param value:
:return:
"""
if not key.startswith("_") and not self._context.unvalidated_parm(key):
if self._name_filter is not None:
if not isinstance(key, self._name_filter):
raise ValueError(f"Illegal Object Map key: {key}={value}")
if not conforms(value, self._value_type, self._context.NAMESPACE):
raise ValueError("Illegal value type {} = {}".format(key, value))
if not isinstance(value, JSGValidateable):
value = self._value_type('', self._context, value) \
if self._value_type is AnyType else self._value_type(value)
self[key] = value
def __getattribute__(self, item) -> Any:
rval = super().__getattribute__(item)
return rval.val if type(rval) is AnyType else None if rval is JSGNull else rval
def __getitem__(self, item):
rval = super().__getitem__(item)
return rval.val if type(rval) is AnyType else None if rval is JSGNull else rval
def _is_valid_element(self, log: Logger, name: str, entry: Type[JSGValidateable]) -> bool:
if self._name_filter is not None:
if not self._name_filter.matches(name):
if log.log(f"Illegal Object Map key: {name}={entry}"):
return False
return super()._is_valid_element(log, name, entry)
def _is_valid(self, log_file: Optional[Union[Logger, TextIO]] = None) -> bool:
log = Logger() if log_file is None else log_file if isinstance(log_file, Logger) else Logger(log_file)
nerrors = log.nerrors
nitems = len(self._strip_nones(self.__dict__))
if nitems < self._min:
if log.log(f"Number of elements is {nitems} which is less than the minimum number ({self._min})"):
return False
if self._max is not None and nitems > self._max:
if log.log(f"Number of elements is {nitems} which is greater than the minimum number ({self._max})"):
return False
super()._is_valid(log)
return nerrors == log.nerrors
|
module.exports = [
{
title: '需求占位',
screenshot: 'https://img.alicdn.com/tfs/TB160cKkP39YK4jSZPcXXXrUFXa-112-64.png',
schema: {
title: '需求占位',
componentName: 'RichText',
props: {
title: '需求占位描述',
content: {
subject: '需求标题',
hideTitle: false,
description:
'<p><span>- 你可以在这里描述需求</span><br /><span>- 或者粘贴需求截图</span></p>',
},
},
},
},
];
|
def _parse_response(xml):
try:
soap_response = xmltodict.parse(xml, process_namespaces=True, namespaces=Service.Namespaces)
except Exception:
logging.debug('unable to parse the xml response: %s', xml)
raise WSManException("the remote host returned an invalid soap response")
body = soap_response['soap:Envelope']['soap:Body']
if body is not None and 'soap:Fault' in body:
raise WSManOperationException(body['soap:Fault']['soap:Reason']['soap:Text']['#text'])
return body
|
/**
* @author jrebula
* </p>
* <p>
* LittleDogVersion06:
* us.ihmc.LearningLocomotion.Version06.util.YoAlphaFilteredVariable,
* 9:34:00 AM, Aug 29, 2006
* </p>=
* <p>
* A YoAlphaFilteredVariable is a filtered version of an input YoVar.
* Either a YoVariable holding the unfiltered val is passed in to the
* constructor and update() is called every tick, or update(double) is
* called every tick. The YoAlphaFilteredVariable updates it's val
* with the current filtered version using
* </p>
* <pre>
* filtered_{n} = alpha * filtered_{n-1} + (1 - alpha) * raw_{n}
* </pre>
*
* For alpha=0 -> no filtered
* For alpha=1 -> 100% filtered, no use of raw signal
*/
public class AlphaFilteredYoVariable extends DoubleYoVariable implements ProcessingYoVariable
{
private double alpha;
private final DoubleYoVariable alphaVariable;
private final DoubleYoVariable position;
protected final BooleanYoVariable hasBeenCalled;
public AlphaFilteredYoVariable(String name, YoVariableRegistry registry, double alpha)
{
this(name, "", registry, alpha, null, null);
}
public AlphaFilteredYoVariable(String name, YoVariableRegistry registry, DoubleYoVariable alphaVariable)
{
this(name, "", registry, 0.0, alphaVariable, null);
}
public AlphaFilteredYoVariable(String name, String description, YoVariableRegistry registry, DoubleYoVariable alphaVariable)
{
this(name, description, registry, 0.0, alphaVariable, null);
}
public AlphaFilteredYoVariable(String name, YoVariableRegistry registry, double alpha, DoubleYoVariable positionVariable)
{
this(name, "", registry, alpha, null, positionVariable);
}
public AlphaFilteredYoVariable(String name, YoVariableRegistry registry, DoubleYoVariable alphaVariable, DoubleYoVariable positionVariable)
{
this(name, "", registry, 0.0, alphaVariable, positionVariable);
}
public AlphaFilteredYoVariable(String name, String description, YoVariableRegistry registry, DoubleYoVariable alphaVariable, DoubleYoVariable positionVariable)
{
this(name, description, registry, 0.0, alphaVariable, positionVariable);
}
private AlphaFilteredYoVariable(String name, String description, YoVariableRegistry registry, double alpha, DoubleYoVariable alphaVariable, DoubleYoVariable positionVariable)
{
super(name, description, registry);
this.hasBeenCalled = new BooleanYoVariable(name + "HasBeenCalled", description, registry);
position = positionVariable;
this.alphaVariable = alphaVariable;
this.alpha = alpha;
reset();
}
public void reset()
{
hasBeenCalled.set(false);
}
public void update()
{
if (position == null)
{
throw new NullPointerException("YoAlphaFilteredVariable must be constructed with a non null "
+ "position variable to call update(), otherwise use update(double)");
}
update(position.getDoubleValue());
}
public void update(double currentPosition)
{
if (!hasBeenCalled.getBooleanValue())
{
hasBeenCalled.set(true);
set(currentPosition);
}
if (alphaVariable == null)
{
set(alpha * getDoubleValue() + (1.0 - alpha) * currentPosition);
}
else
{
set(alphaVariable.getDoubleValue() * getDoubleValue() + (1.0 - alphaVariable.getDoubleValue()) * currentPosition);
}
}
public void setAlpha(double alpha)
{
if (alphaVariable == null)
{
this.alpha = alpha;
}
else
{
alphaVariable.set(alpha);
}
}
/**
* This method is replaced by computeAlphaGivenBreakFrequencyProperly. It is fine to keep using this method is currently using it, knowing that
* the actual break frequency is not exactly what you are asking for.
*
* @param breakFrequencyInHertz
* @param dt
* @return
*/
@Deprecated
public static double computeAlphaGivenBreakFrequency(double breakFrequencyInHertz, double dt)
{
if (Double.isInfinite(breakFrequencyInHertz))
return 0.0;
double alpha = 1.0 - breakFrequencyInHertz * 2.0 * Math.PI * dt;
alpha = MathTools.clipToMinMax(alpha, 0.0, 1.0);
return alpha;
}
public static double computeAlphaGivenBreakFrequencyProperly(double breakFrequencyInHertz, double dt)
{
if (Double.isInfinite(breakFrequencyInHertz))
return 0.0;
double omega = 2.0 * Math.PI * breakFrequencyInHertz;
double alpha = (1.0 - omega * dt / 2.0) / (1.0 + omega * dt / 2.0);
alpha = MathTools.clipToMinMax(alpha, 0.0, 1.0);
return alpha;
}
public static double computeBreakFrequencyGivenAlpha(double alpha, double dt)
{
return (1.0 - alpha) / (Math.PI * dt + Math.PI * alpha * dt);
}
public static void main(String[] args)
{
double dt = 1 / 1e3;
for (double i = 2; i < 1.0/dt; i = i * 1.2)
{
double alpha = computeAlphaGivenBreakFrequency(i, dt);
double alphaProperly = computeAlphaGivenBreakFrequencyProperly(i, dt);
System.out.println("freq=" + i + ", alpha=" + alpha + ", alphaProperly=" + alphaProperly);
}
System.out.println(computeBreakFrequencyGivenAlpha(0.8, 0.006));
System.out.println(computeAlphaGivenBreakFrequencyProperly(20, 0.006));
System.out.println(computeAlphaGivenBreakFrequencyProperly(20, 0.003));
}
public boolean getHasBeenCalled()
{
return hasBeenCalled.getBooleanValue();
}
}
|
/* Print the command type menu and setup response catch. */
static void zedit_disp_comtype(struct descriptor_data *d)
{
get_char_colors(d->character);
clear_screen(d);
write_to_output(d,
"\r\n"
"%sM%s) Load Mobile to room %sO%s) Load Object to room\r\n"
"%sE%s) Equip mobile with object %sG%s) Give an object to a mobile\r\n"
"%sP%s) Put object in another object %sD%s) Open/Close/Lock a Door\r\n"
"%sR%s) Remove an object from the room %sJ%s) Jump over next <x> commands\r\n"
"%sT%s) Assign a trigger %sV%s) Set a global variable\r\n"
"%sI%s) Give treasure to a mobile %sL%s) Load treasure in another object\r\n"
"\r\n"
"What sort of command will this be? : ",
grn, nrm, grn, nrm, grn, nrm, grn, nrm, grn, nrm,
grn, nrm, grn, nrm, grn, nrm, grn, nrm, grn, nrm,
grn, nrm, grn, nrm);
OLC_MODE(d) = ZEDIT_COMMAND_TYPE;
}
|
<gh_stars>10-100
package com.learning.java.algorithm;
import java.util.Arrays;
public class Quadruplets {
public static void main(String args[]) {
int[] a1 = {2, 7, 4, 0, 9, 5, 1, 3};
Arrays.sort(a1);
String res = "";
int n = 4;
int sum = 20;
quadruplets(a1, res, n, sum);
}
static void quadruplets(int a[], String res, int n, int sum) {
if (sum == 0) System.out.println(res);
if (n == 0) res = "";
for (int i = 0; i < a.length; i++) {
if (n > 0) {
res = res + a[i];
quadruplets(a, res, n - 1, sum - a[i]);
}
}
}
}
|
import { IUser } from './user';
export enum studyType {
SENSOR = 'SENSOR',
CLINICAL = 'CLINICAL',
ANY = 'ANY'
}
export interface IStudy {
id: string;
name: string;
createdBy: string;
lastModified: number;
deleted: number | null;
currentDataVersion: number; // index; dataVersions[currentDataVersion] gives current version; // -1 if no data
dataVersions: IStudyDataVersion[];
description: string;
type: studyType;
ontologyTree?: IOntologyField[];
}
export interface IOntologyField {
fieldId: string;
path: string;
}
export interface IStudyDataVersion {
id: string; // uuid
contentId: string; // same contentId = same data
version: string;
tag?: string;
updateDate: string;
}
export interface IRole {
id: string;
projectId?: string;
studyId: string;
name: string;
permissions: string[];
users: IUser[];
createdBy: string;
deleted: number | null;
}
export interface IProject {
id: string;
studyId: string;
createdBy: string;
name: string;
patientMapping: { [originalId: string]: string };
approvedFields: { [fieldTreeId: string]: string[] };
approvedFiles: string[];
lastModified: number;
deleted: number | null;
}
export interface IDataClip {
fieldId: string,
value: string,
subjectId: string,
visitId: string
}
export enum DATA_CLIP_ERROR_TYPE{
ACTION_ON_NON_EXISTENT_ENTRY = 'ACTION_ON_NON_EXISTENT_ENTRY',
MALFORMED_INPUT = 'MALFORMED_INPUT'
}
export interface IDataClipError {
code:DATA_CLIP_ERROR_TYPE
description?: string
}
export interface ISubjectDataRecordSummary {
subjectId: string,
visitId?: string,
missingFields: string[]
}
|
def init_dets(globs):
di = Database.getDetectorsInt()
tmp = []
for ep in Database.getCurrentProbes():
for det in Database.getCurrentEDSDetectors(ep):
dp = det.getDetectorProperties()
if dp in di:
ii = di[dp]
globs['d%d' % ii] = det
tmp.append(det)
globs['dets'] = tmp
|
<filename>src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { SettingsService } from './settings.service';
import { TtrssClientService } from './ttrss-client.service';
import { TranslateService } from '@ngx-translate/core';
import { Title } from '@angular/platform-browser';
import { LangChangeEvent } from '@ngx-translate/core';
import { OverlayContainer } from '@angular/cdk/overlay';
@Component({
selector: 'ttrss-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
isDarkTheme: boolean;
constructor(private translate: TranslateService, private settings: SettingsService,
private titleService: Title, private overlayContainer: OverlayContainer) { }
ngOnInit() {
// this language will be used as a fallback when a translation isn't found in the current language
this.translate.setDefaultLang('en');
this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
this.translate.get('App_Title').subscribe((res: string) => {
this.titleService.setTitle(res);
});
});
this.applyTheme();
this.translate.use(this.settings.getLanguage());
this.settings.darkDesign$.subscribe(() => {
this.applyTheme();
});
}
applyTheme() {
this.isDarkTheme = this.settings.darkDesign;
const newThemeClass = this.isDarkTheme ? 'ttrss-dark-theme' : 'ttrss-light-theme';
const overlayContainerClasses = this.overlayContainer.getContainerElement().classList;
const themeClassesToRemove = Array.from(overlayContainerClasses).filter((item: string) => item.includes('-theme'));
if (themeClassesToRemove.length) {
overlayContainerClasses.remove(...themeClassesToRemove);
}
overlayContainerClasses.add(newThemeClass);
const manifest = this.isDarkTheme ? 'manifest-dark.json' : 'manifest.json';
document.querySelector('#manifest-link').setAttribute('href', manifest);
const theme_color = this.isDarkTheme ? '#424242' : '#fff';
document.querySelector('#theme-color').setAttribute('content', theme_color);
}
}
|
<gh_stars>1-10
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Util to get objects from flask.g.referenced_objects or DB if not present."""
import collections
import flask
from sqlalchemy import orm
from ggrc import db
from ggrc.models import inflector
from ggrc.models.mixins import customattributable
def get(type_, id_):
"""Check flask.g.referenced_objects for the object or get it from the DB."""
# id == 0 is a valid case if id is an int; therefore "not id" doesn't fit
if id_ is None:
return None
ref_objects = getattr(flask.g, "referenced_objects", {})
if not (isinstance(type_, type) and issubclass(type_, db.Model)):
type_ = inflector.get_model(type_)
# model for type_ has been removed
if type_ is None:
return None
result = ref_objects.get(type_, {}).get(id_, None)
if not result:
result = type_.query.get(id_)
return result
def mark_to_cache(type_, id_):
"""Mark object for warmup"""
if not hasattr(flask.g, "referenced_objects_markers"):
flask.g.referenced_objects_markers = collections.defaultdict(set)
if not (isinstance(type_, type) and issubclass(type_, db.Model)):
type_ = inflector.get_model(type_)
if type_ is not None:
flask.g.referenced_objects_markers[type_].add(id_)
def rewarm_cache():
"""Rewarm cache on call."""
if not hasattr(flask.g, "referenced_objects_markers"):
return
if not hasattr(flask.g, "referenced_objects"):
flask.g.referenced_objects = {}
warm_cache = flask.g.referenced_objects_markers
del flask.g.referenced_objects_markers
for type_, ids in warm_cache.iteritems():
if type_ not in flask.g.referenced_objects:
flask.g.referenced_objects[type_] = {}
query = type_.query.filter(type_.id.in_(ids))
if issubclass(type_, customattributable.CustomAttributable):
query = query.options(
orm.Load(type_).subqueryload(
"custom_attribute_definitions"
).undefer_group(
"CustomAttributeDefinition_complete"
)
)
for obj in query:
flask.g.referenced_objects[type_][obj.id] = obj
for id_ in ids:
if id_ not in flask.g.referenced_objects[type_]:
flask.g.referenced_objects[type_][id_] = None
|
<reponame>waneon/windows-magnifier-rs
use bindings::Windows::Win32::{
Foundation::POINT, System::Console::FreeConsole, UI::KeyboardAndMouseInput::*,
UI::Magnification::*, UI::WindowsAndMessaging::*,
};
static MOD: HOT_KEY_MODIFIERS = MOD_ALT;
static KEY: u32 = b'1' as u32;
static MAGNIFYING_FACTOR: f32 = 1.8;
static TIMER_MS: u32 = 8;
struct MagInfo {
mul_x: f32,
mul_y: f32,
sub_x: i32,
sub_y: i32,
max_x: i32,
max_y: i32,
}
impl MagInfo {
fn init() -> MagInfo {
let x: i32;
let y: i32;
unsafe {
x = GetSystemMetrics(SM_CXSCREEN);
y = GetSystemMetrics(SM_CYSCREEN);
}
// Dead-zone size ~= 200px
let k = (x as f32 / 9.0) as i32;
let mul_x = x as f32 * (1.0 - 1.0 / MAGNIFYING_FACTOR) / (x - 2 * k) as f32;
let mul_y = y as f32 * (1.0 - 1.0 / MAGNIFYING_FACTOR) / (y - 2 * k) as f32;
MagInfo {
mul_x,
mul_y,
sub_x: (k as f32 * mul_x) as i32,
sub_y: (k as f32 * mul_y) as i32,
max_x: ((x as f32) * (1.0 - 1.0 / MAGNIFYING_FACTOR)) as i32,
max_y: ((y as f32) * (1.0 - 1.0 / MAGNIFYING_FACTOR)) as i32,
}
}
}
fn main() {
let mut magnified = false;
let info = MagInfo::init();
unsafe {
// Hide console
FreeConsole();
// Init mag
if MagInitialize().as_bool() != true {
return;
}
// Set toggle key
if RegisterHotKey(None, 1, MOD, KEY).as_bool() != true {
return;
}
if RegisterHotKey(None, 2, MOD, b'2' as u32).as_bool() != true {
return;
}
// Check event loop
let mut msg: MSG = MSG::default();
while GetMessageA(&mut msg, None, 0, 0).as_bool() != false {
// Quit
if msg.message == WM_HOTKEY && msg.wParam.0 == 2 {
break;
}
// Toggle Magnifying
if msg.message == WM_HOTKEY && msg.wParam.0 == 1 {
if magnified {
KillTimer(None, 1);
magnify_off();
} else {
SetTimer(None, 1, TIMER_MS, None);
}
magnified = !magnified;
}
// Turn on magnifying
if msg.message == WM_TIMER {
if magnified {
magnify_on(&info);
}
}
}
// Unset toggle key
UnregisterHotKey(None, 1);
UnregisterHotKey(None, 2);
// Free mag
MagUninitialize();
}
}
fn magnify_on(info: &MagInfo) {
let mut point = POINT::default();
let x: i32;
let y: i32;
unsafe {
GetCursorPos(&mut point);
x = (point.x as f32 * info.mul_x) as i32 - info.sub_x;
y = (point.y as f32 * info.mul_y) as i32 - info.sub_y;
// Check bound
let x = if x < 0 {
0
} else if x > info.max_x {
info.max_x
} else {
x
};
let y = if y < 0 {
0
} else if y > info.max_y {
info.max_y
} else {
y
};
MagSetFullscreenTransform(MAGNIFYING_FACTOR, x, y);
}
}
fn magnify_off() {
unsafe {
MagSetFullscreenTransform(1.0, 0, 0);
}
}
|
<gh_stars>100-1000
# Copyright (c) OpenMMLab. All rights reserved.
_base_ = 'model.py'
norm_cfg = dict(type='BN')
mutator = dict(
type='OneShotMutator',
placeholder_mapping=dict(
all_blocks=dict(
type='OneShotOP',
choices=dict(
shuffle_3x3=dict(
type='ShuffleBlock', kernel_size=3, norm_cfg=norm_cfg),
shuffle_5x5=dict(
type='ShuffleBlock', kernel_size=5, norm_cfg=norm_cfg),
shuffle_7x7=dict(
type='ShuffleBlock', kernel_size=7, norm_cfg=norm_cfg),
shuffle_xception=dict(
type='ShuffleXception', norm_cfg=norm_cfg),
))))
algorithm = dict(
type='SPOS',
architecture=dict(
type='MMClsArchitecture',
model={{_base_.model}},
),
mutator=mutator,
distiller=None,
mutable_cfg='tests/test_codebase/test_mmcls/data/mmrazor_mutable_cfg.yaml',
retraining=True)
|
Welcome to TrumpBeat, FiveThirtyEight’s weekly feature looking at how developments in Washington affect people in the real world. Want to get TrumpBeat in your inbox each week? Sign up for our newsletter. Comments, criticism or suggestions for future columns? Email us or drop a note in the comments.
President Trump’s (technically not a) State of the Union address Tuesday night included lots of policy proposals but few details. He promised a new version of his controversial travel ban but didn’t explain how it would pass judicial scrutiny. He nodded to a tax overhaul favored by House Speaker Paul Ryan but didn’t quite endorse it. And he gave the rough outlines of a replacement for the Affordable Care Act but didn’t resolve any of the thorny questions that have made Republicans’ “repeal and replace” promise harder to keep than they expected. (“Nobody knew health care could be so complicated,” Trump told reporters Monday, drawing incredulous reactions from the approximately 100 percent of people who knew that health care could be so complicated.)
Fortunately, we’ll learn more details soon thanks to everyone’s favorite hundred-plus-page doorstop: the federal budget. The multitrillion-dollar annual wish list is the best indication of where any president’s priorities lie.
Trump won’t present his first formal budget to Congress until later this year (a preliminary outline is expected this month), but a few details are starting to trickle out. The White House this week told reporters that Trump wants to boost military spending by $54 billion over planned levels. To pay for it, Trump plans deep cuts to other agencies, particularly the Environmental Protection Agency and the State Department. As Trump promised on the campaign trail, Social Security and Medicare, the government’s main programs for retirees, would be spared cuts. But other elements of the safety net probably won’t be so lucky, meaning that the poor, the disabled and the unemployed could all see their benefits reduced.
Various news outlets in recent weeks have reported that Trump’s budget will draw heavily on a plan released by the conservative Heritage Foundation last year. That document proposes slashing spending by $10.5 trillion over 10 years by eliminating dozens of federal programs and offices. But Trump appears to be departing from the Heritage plan in significant ways. The think tank’s plan calls for eliminating whole categories of tariffs, for example; Trump has suggested he might impose steep new ones. And Heritage wants to get rid of programs that provide support for entrepreneurs and small businesses, arguing that the free market would do a better job allocating resources to the best companies; Trump, in his address to Congress, proposed a new program to encourage women entrepreneurs.
It’s wise not to take any of these early leaks too literally. The budget process is long and complicated, and agencies and interest groups are adept at using the media to gain an edge in negotiations. Besides, when all the jockeying is over, the result is nothing more than a request — it’s up to Congress to appropriate the money.
In fact, it’s best not to think of the president’s budget as a budget at all, at least in the conventional sense of a document that describes where and how money will be spent. Instead, think of the budget as a list of priorities — one that, unlike speeches like the State of the Union, forces presidents to make actual tradeoffs. The old saw is as true as ever: If you want to know what presidents truly care about, follow the money.
Here are some of the major policy developments from the past week:
Civil rights: Undoing the Obama legacy
Reforming the criminal justice system and both defending and expanding civil rights protections were two top priorities of the Obama administration, as Obama himself argued in an article he wrote for the Harvard Law Review in January.
On civil rights, the Obama administration filed lawsuits accusing states such as North Carolina and Texas of trying to limit the ability of blacks and Latinos to vote and argued that some police departments unfairly targeted minorities for arrests and citations. The administration also sought to expand civil rights by letting gay people serve openly in the military, issuing guidance in favor of allowing transgender students to use the bathroom of the gender they identify with and letting women serve in combat jobs in the military.
To address the disproportionate number of black men serving in prison, Obama’s administration urged federal prosecutors not to always seek the maximum sentence possible for nonviolent drug offenses. It also started phasing out the use of private prisons to house federal inmates and banned solitary confinement for juveniles in federal prisons — steps liberals hailed as long-needed reforms to make America’s criminal justice system more humane.
The Trump administration, particularly Attorney General Jeff Sessions, is signaling that it will seek to overturn many of these Obama policies.
Sessions said in a speech this week that the Justice Department would “pull back” on lawsuits against local police departments for discriminating against minorities. And in the last two weeks, the department has withdrawn the federal government’s opposition to a Texas voter ID law that Obama’s team had argued was unconstitutional, reversed the Obama administration policy that schools should let transgender students choose the restroom they use and said the federal government would continue to send people to private prisons.
Civil rights groups had sharply opposed the nomination of Sessions, worried that he would reverse Obama’s policies. But — as his “pull back” comments this week make clear — what Sessions opts not to do will be just as important. Obama’s Justice Department was known for launching investigations of shootings of civilians by the police and issuing detailed reports on how police departments treated people of color. Sessions’ moves over the last two weeks suggest that those practices are unlikely to continue in a Trump administration.
VIDEO: President Trump has record disapproval ratings
Environment: Cutting jobs at the EPA
Word on the street this week: Trump’s proposed budget will include a 25 percent cut to the EPA, which would include eliminating at least 3,000 jobs there. None of this has been confirmed by the administration (natch), and some congressional Republicans are already pushing back, but it’s worth taking a look at what those so-far-hypothetical numbers would mean — especially given the president’s shoutout to protecting America’s air and water quality during his address to Congress on Tuesday.
First off, the EPA’s budget is already tiny in comparison to those of other federal agencies. Its cost of operations in 2016 was about $8.7 billion. In contrast, the estimated 2016 budget for the Department of Agriculture was $164 billion, the State Department got $29.5 billion, and NASA got $19 billion. Put another way, everything the EPA spent last year amounts to about 1.5 percent of the budget for the Department of Defense, the agency President Trump is hoping to further fund through cuts to EPA and other agencies. So giving 25 percent of the EPA’s budget to the Department of Defense would increase the latter’s budget by less than half of 1 percent.
Meanwhile, the largest chunk of EPA spending — 46 percent, or nearly $4 billion — goes to assistance agreements for states and Native American tribes. These are grants that fund locally directed environmental projects — exactly the kind of locals-know-best work that new agency Administrator Scott Pruitt has long talked of supporting. The second-biggest budgetary item for the EPA: environmental programs and management, i.e., enforcement, education and other programs that are directly tied to maintaining clean air and water. Those take up another $2.7 billion. Those two categories alone account for more than 75 percent of the money the EPA spends. What’s left over? Mostly, it’s money for Superfund sites, leaking underground storage tank remediation, and the science and technological research that assists the agency in getting all these other jobs done. The EPA has already cut 20 percent from its budget since 2011. “You really want to be sure you are not cutting the meat and muscle with the fat,” Republican Rep. Tom Cole of Oklahoma told the trade publication Inside EPA on Tuesday.
Basically, it is going to be hard to target the EPA for significant downsizing and maintain popular anti-pollution programs. And even if those programs do take a big hit, the added cash won’t make much difference to the Pentagon’s budget. This is another example of the administration’s ongoing difficulty with making promises that conflict with other promises.
Health care: What to do about Medicaid?
Republicans are in an awkward position when it comes to one of the trickiest aspects of repealing and replacing the Affordable Care Act: Medicaid. The ACA took what was once a relatively narrow program (serving primarily pregnant women, children and the disabled) and opened it up to a much broader group of low-income Americans. Millions gained health coverage as a result. Now Republicans have to decide what happens to them if the law goes away.
It’s not going to be easy for Republicans to find common ground. Peeling back the expansion and reforming how the program is funded, as some Republican plans have proposed doing, would leave millions of the nation’s poorest without coverage. Keeping the expansion, however, goes against conservative ideals of small government and personal responsibility. Adding to the challenge: 19 states chose not to expand Medicaid as the law allows. The ones that did expand don’t want to lose the billions of dollars in federal assistance expected to be paid out over the first decade of the program; states that rejected the expansion want to find a way to recoup some of the federal dollars they are missing out on by not expanding.
Republican governors have been particularly vocal about their concern over draft bills that would gut funding and insurance coverage. This week they offered their own solution, calling for a complicated set of rules. States that expanded Medicaid could keep the expansion, but with less federal reimbursement. States that didn’t expand would be given the chance to do so, but for a more limited group of people. But the plan is likely to get a cool reception from the most conservative wing of the party, which has said it won’t support a replacement plan that involves anything less than a full repeal. It’s no wonder House Republicans have opted to keep the newest draft of the bill locked away in a reading room in the hopes that it won’t be leaked to the public.
Hiring: Going from normal to not so normal
Trump has been accused of taking a lackadaisical approach to nominating people to fill positions in his administration. Hundreds of spots still are without nominees — a wide-ranging list that includes ambassadors; key members of leadership in the State Department and other offices; the directors of law enforcement organizations such as the Bureau of Alcohol, Tobacco, Firearms and Explosives; and the heads of advisory groups such as the Office of Science and Technology Policy.
But if you look at the numbers, Trump hasn’t been wildly out of pace with previous presidents. There are roughly 1,200 presidentially appointed positions that require Senate approval (and many other appointments that don’t). Getting them all named, vetted and OK’d has always taken time. The Partnership for Public Service — a nonprofit agency that studies and works to improve government functioning, including presidential transitions — recommends that administrations have 400 of these positions in place by the August of a president’s first year in office, The Wall Street Journal reported. But that’s a reach goal — nobody has ever achieved it.
In his first month in office, Trump has been a little slower to send nominations to the Senate than Obama was — nominating 34 people by Feb. 21, to Obama’s 39, according to a CNN report based on numbers from the Partnership for Public Service. But Presidents George W. Bush, Bill Clinton and George H.W. Bush were all slower than that, averaging 23 nominations in their first month in office. Trump has had a more difficult time getting his nominations confirmed than some of those other presidents did. As of Feb. 21, 14 of Trump’s nominees had been OK’d by the Senate — the fewest since George H.W. Bush, who had just 11 confirmations at the same point.
So far, so normal. But then, this week, Trump turned the situation upside down, telling Fox News that he has no intention of filling some of those positions.
“A lot of those jobs, I don’t want to appoint, because they’re unnecessary to have,” Trump told “Fox & Friends” on Tuesday. “I look at some of the jobs, and it’s people over people over people. I say, ‘What do all these people do?’ You don’t need all those jobs.”
Trump has not yet said which positions he plans to leave empty, and without knowing that, it’s hard to say whether this idea would be disastrous or useful. It’s not entirely abnormal for positions to go empty for long periods, either through lack of prioritization or because the Senate won’t confirm nominees. The Centers for Medicare and Medicaid Services, for instance, went without a Senate-confirmed administrator between 2006 and 2013. And that can cause administrative chaos in the organizations that are running rudderless. On the other hand, James Pfiffner, professor of public policy at George Mason University, has written that the number of presidential political appointees has ballooned in recent decades, contributing to a slowdown in the nomination process. Reducing the number of those appointments, according to Pfiffner, could improve the functioning of the executive branch.
More from FiveThirtyEight
|
def _add_include(self, include, local_env):
self._add_include_dir(include, local_env)
|
/*
Copyright (c) Microsoft Corporation
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
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
#include <DrFileSystems.h>
#include <DrClusterInternal.h>
using System::IO::Path;
using System::String;
using System::Uri;
static DrString ReadLineFromFile(FILE* f)
{
DrString line("");
char buf[1024];
char* s;
bool found = false;
bool foundEndOfLine = false;
while ((s = fgets(buf, sizeof(buf)-1, f)) != NULL)
{
found = true;
size_t sLen;
buf[sizeof(buf)-1] = '\0';
sLen = ::strlen(buf);
if (sLen > 0 && buf[sLen-1] == '\n')
{
--sLen;
buf[sLen] = '\0';
foundEndOfLine = true;
}
if (sLen > 0 && buf[sLen-1] == '\r')
{
--sLen;
buf[sLen] = '\0';
foundEndOfLine = true;
}
line = line.AppendF("%s", buf);
if (foundEndOfLine)
{
break;
}
}
if (found)
{
return line;
}
else
{
DrString nullString;
return nullString;
}
}
static bool ParseReplicatedFromPartitionLine(int partitionNumber,
DrAffinityPtr affinity,
DrStringR remoteName,
DrPartitionInputStream::OverridePtr over,
bool mustOverride,
bool pathIsRooted,
DrString line,
DrUniversePtr universe)
{
DrString lineCopy = line;
int sep = lineCopy.IndexOfChar(',');
if (sep == DrStr_InvalidIndex)
{
return false;
}
else
{
DrString partitionNumberString;
partitionNumberString.SetSubString(lineCopy.GetChars(), sep);
DrString shorter;
shorter.SetF("%s", lineCopy.GetChars() + sep + 1);
lineCopy = shorter;
int parsedNumber;
int n = sscanf_s(partitionNumberString.GetChars(), "%d", &parsedNumber);
if (n != 1 || parsedNumber != partitionNumber)
{
DrLogW("Mismatched partition numbers in line %s: Expected %d got %d",
line.GetChars(), partitionNumber, parsedNumber);
return false;
}
}
UINT64 parsedSize = 0;
sep = lineCopy.IndexOfChar(',');
if (sep == DrStr_InvalidIndex)
{
int n = sscanf_s(lineCopy.GetChars(), "%I64u", &parsedSize);
if (n != 1)
{
DrLogW("Malformed line %s: can't parse size", line.GetChars());
return false;
}
affinity->SetWeight(parsedSize);
lineCopy = DrString("");
}
else
{
DrString partitionSizeString;
partitionSizeString.SetSubString(lineCopy.GetChars(), sep);
DrString shorter;
shorter.SetF("%s", lineCopy.GetChars() + sep + 1);
lineCopy = shorter;
int n = sscanf_s(partitionSizeString.GetChars(), "%I64u", &parsedSize);
if (n != 1)
{
DrLogW("Malformed line %s: can't parse size", line.GetChars());
return false;
}
affinity->SetWeight(parsedSize);
}
if (lineCopy.GetCharsLength() == 0)
{
if (!pathIsRooted || mustOverride)
{
DrLogW("Malformed line %s: no partition machines", line.GetChars());
return false;
}
remoteName.Set(" %Invalid% ");
return true;
}
int numberOfReplicas = 0;
while (lineCopy.GetCharsLength() > 0)
{
DrString thisMachineName;
sep = lineCopy.IndexOfChar(',');
if (sep == DrStr_InvalidIndex)
{
thisMachineName = lineCopy;
lineCopy = DrString("");
}
else
{
thisMachineName.SetSubString(lineCopy.GetChars(), sep);
DrString shorter;
shorter.SetF("%s", lineCopy.GetChars() + sep + 1);
lineCopy = shorter;
}
sep = thisMachineName.IndexOfChar(':');
if (sep == DrStr_InvalidIndex)
{
thisMachineName = thisMachineName.ToUpperCase();
}
else
{
DrString overrideFile;
overrideFile.SetF("%s", thisMachineName.GetChars() + sep + 1);
DrString shorter;
shorter.SetSubString(thisMachineName.GetChars(), sep);
thisMachineName = shorter.ToUpperCase();
over->Add(thisMachineName.GetString(), overrideFile);
}
DrResourceRef location = universe->LookUpResourceInternal(thisMachineName);
if (location == DrNull)
{
remoteName.Set(thisMachineName);
}
else
{
affinity->AddLocality(location);
}
++numberOfReplicas;
}
if (mustOverride && over->GetSize() == 0)
{
DrLogW("Malformed partition file: All filenames must be overrides when path is empty");
return false;
}
return true;
}
HRESULT DrPartitionInputStream::Open(DrUniversePtr universe, DrNativeString streamName)
{
return OpenInternal(universe, DrString(streamName));
}
HRESULT DrPartitionInputStream::OpenInternal(DrUniversePtr universe, DrString streamName)
{
HRESULT err = S_OK;
DrLogI("Opening input file %s", streamName.GetChars(), DRERRORSTRING(err));
FILE* f;
errno_t ferr = fopen_s(&f, streamName.GetChars(), "rb");
if (ferr != 0)
{
err = HRESULT_FROM_WIN32(GetLastError());
DrLogW("Failed to open input file %s error %s", streamName.GetChars(), DRERRORSTRING(err));
return err;
}
m_pathNameOnComputer = ReadLineFromFile(f);
DrString partitionSizeLine = ReadLineFromFile(f);
if (partitionSizeLine.GetString() == DrNull)
{
err = DrError_EndOfStream;
DrLogW("Failed to read pathname and partition size from input file %s", streamName.GetChars());
fclose(f);
return err;
}
bool mustOverride = false;
if (m_pathNameOnComputer.GetCharsLength() == 0)
{
mustOverride = true;
}
bool pathIsRooted = false;
if (m_pathNameOnComputer.IndexOfChar(':') != DrStr_InvalidIndex)
{
pathIsRooted = true;
}
int numberOfParts;
int n = sscanf_s(partitionSizeLine.GetChars(), "%d", &numberOfParts);
if (n != 1)
{
DrLogW("Unable to read partition size from line '%s' Filename %s",
partitionSizeLine.GetChars(), streamName.GetChars());
fclose(f);
return DrError_Unexpected;
}
if (numberOfParts == 0)
{
DrLogI("Read empty partitioned file details PathName: '%s'",
m_pathNameOnComputer.GetChars());
fclose(f);
return S_OK;
}
m_affinity = DrNew DrAffinityArray(numberOfParts);
m_remoteName = DrNew DrStringArray(numberOfParts);
m_override = DrNew OverrideArray(numberOfParts);
DrLogI("Reading partitioned file details PathName: '%s' NumberOfParts=%d",
m_pathNameOnComputer.GetChars(), numberOfParts);
int i;
for (i=0; i<numberOfParts; ++i)
{
DrString partitionLine = ReadLineFromFile(f);
if (partitionLine.GetString() == DrNull)
{
DrLogW("Malformed partition file %s: got %d partition lines; expected %d",
streamName.GetChars(), i, numberOfParts);
m_affinity = DrNull;
m_remoteName = DrNull;
m_override = DrNull;
fclose(f);
return DrError_Unexpected;
}
m_affinity[i] = DrNew DrAffinity();
m_override[i] = DrNew Override();
DrString remoteName;
if (ParseReplicatedFromPartitionLine(i,
m_affinity[i],
remoteName,
m_override[i],
mustOverride,
pathIsRooted,
partitionLine,
universe) == false)
{
DrLogW("Failed to parse partition file line from file %s, partition %d, line='%s'",
streamName.GetChars(), i, partitionLine.GetChars());
m_affinity = DrNull;
m_remoteName = DrNull;
m_override = DrNull;
fclose(f);
return DrError_Unexpected;
}
m_remoteName[i] = remoteName;
}
fclose(f);
m_streamName = streamName;
return S_OK;
}
DrString DrPartitionInputStream::GetStreamName()
{
return m_streamName;
}
int DrPartitionInputStream::GetNumberOfParts()
{
return m_affinity->Allocated();
}
DrAffinityRef DrPartitionInputStream::GetAffinity(int partitionIndex)
{
return m_affinity[partitionIndex];
}
DrString DrPartitionInputStream::GetURIForRead(int partitionIndex, DrResourcePtr runningResource)
{
OverridePtr over = m_override[partitionIndex];
DrAffinityPtr affinity = m_affinity[partitionIndex];
DrResourceListRef location = affinity->GetLocalityArray();
DrString computerName;
if (location->Size() == 0)
{
computerName = m_remoteName[partitionIndex];
}
else
{
DrResourcePtr resource = DrNull;
int i;
for (i=0; i<location->Size(); ++i)
{
if (location[i] == runningResource)
{
resource = location[i];
break;
}
}
if (resource == DrNull)
{
for (i=0; i<location->Size(); ++i)
{
if (location[i]->GetParent() == runningResource->GetParent())
{
resource = location[i];
break;
}
}
if (resource == DrNull)
{
resource = location[rand() % location->Size()];
}
}
computerName = resource->GetName();
}
DrString uri;
DrString overrideString;
if (over->TryGetValue(computerName.GetString(), overrideString))
{
uri.SetF("file:///\\\\%s\\%s", computerName.GetChars(), overrideString.GetChars());
}
else
{
if (m_pathNameOnComputer.IndexOfChar(':') != DrStr_InvalidIndex)
{
uri.SetF("file:///%s.%08x", m_pathNameOnComputer.GetChars(), partitionIndex);
}
else {
uri.SetF("file:///\\\\%s\\%s.%08x",
computerName.GetChars(), m_pathNameOnComputer.GetChars(), partitionIndex);
}
}
return uri;
}
HRESULT DrPartitionOutputStream::Open(DrNativeString streamName, DrNativeString pathBase)
{
return OpenInternal(DrString(streamName), DrString(pathBase));
}
HRESULT DrPartitionOutputStream::OpenInternal(DrString streamName, DrString pathBase)
{
FILE* f;
errno_t ferr = fopen_s(&f, streamName.GetChars(), "w");
if (ferr != 0)
{
HRESULT err = HRESULT_FROM_WIN32(GetLastError());
DrLogW("Failed to open output file %s error %s", streamName.GetChars(), DRERRORSTRING(err));
return err;
}
fclose(f);
m_streamName = streamName;
m_pathBase = pathBase;
m_isPathBaseRooted = Path::IsPathRooted(m_pathBase.GetString());
return S_OK;
}
void DrPartitionOutputStream::SetNumberOfParts(int /* unused numberOfParts*/)
{
}
DrString DrPartitionOutputStream::GetURIForWrite(int partitionIndex,
int id, int version, int outputPort,
DrResourcePtr runningResource,
DrMetaDataRef metaData)
{
String ^uri;
if (m_isPathBaseRooted)
{
String ^ext = String::Format("{0:X8}---{1}_{2}_{3}.tmp",
partitionIndex, id, outputPort, version);
uri = "file:///" + Path::ChangeExtension(m_pathBase.GetString(), ext);
}
else
{
DrClusterResourcePtr clusterPtr = dynamic_cast<DrClusterResourcePtr>(runningResource);
IComputer ^node = clusterPtr->GetNode();
uri = String::Format("file:///\\\\{0}\\{1}.{2:X8}---{2}_{3}_{4}.tmp",
gcnew array<Object^> {clusterPtr->GetLocality().GetString(),
m_pathBase.GetString(), partitionIndex, id, outputPort, version});
}
DrMTagVoidRef tag = DrNew DrMTagVoid(DrProp_TryToCreateChannelPath);
metaData->Append(tag);
return DrString(uri);
}
void DrPartitionOutputStream::DiscardUnusedPart(int partitionIndex,
int id, int version, int outputPort,
DrResourcePtr runningResource, bool jobSuccess)
{
// we do the same thing here whether the job succeeded or not since each part needs to be
// individually deleted
DrMetaDataRef metaData = DrNew DrMetaData();
Uri ^absUri = gcnew Uri(GetURIForWrite(partitionIndex, id, version, outputPort, runningResource, metaData).GetString());
DrString fname(absUri->LocalPath);
BOOL bRet = ::DeleteFileA(fname.GetChars());
if (!bRet)
{
HRESULT err = HRESULT_FROM_WIN32(GetLastError());
DrAssert(err != S_OK);
if (err == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
DrLogI("Delete ignoring nonexistent URI %s", fname.GetChars());
}
else
{
DrLogW("DeleteFile(%s), error %s", fname.GetChars(), DRERRORSTRING(err));
}
}
else
{
DrLogI("Deleted URI %s", fname.GetChars());
}
}
HRESULT DrPartitionOutputStream::RenameSuccessfulPart(int partitionIndex, DrOutputPartition p)
{
DrMetaDataRef metaData = DrNew DrMetaData();
DrString uri = GetURIForWrite(partitionIndex, p.m_id,
p.m_version, p.m_outputPort, p.m_resource,
metaData);
Uri ^srcUri = gcnew Uri(uri.GetString());
uri.Set(srcUri->LocalPath);
String ^finalFile;
if (m_isPathBaseRooted)
{
finalFile = Path::ChangeExtension(m_pathBase.GetString(), partitionIndex.ToString("X8"));
}
else
{
DrClusterResourcePtr clusterPtr = dynamic_cast<DrClusterResourcePtr>(p.m_resource);
if (clusterPtr != nullptr)
{
finalFile = String::Format("\\\\{0}\\{1}.{2:X8}",
clusterPtr->GetNode()->Host,
m_pathBase.GetString(), partitionIndex);
}
else
{
finalFile = String::Format("\\\\{0}\\{1}.{2:X8}",
clusterPtr->GetName().GetString(),
m_pathBase.GetString(), partitionIndex);
}
}
DrString finalName(finalFile);
HRESULT err = S_OK;
BOOL bRet = ::MoveFileA(uri.GetChars(), finalName.GetChars());
if (!bRet)
{
err = HRESULT_FROM_WIN32(GetLastError());
DrAssert(err != S_OK);
DrLogW("MoveFile(%s, %s), error %s", uri.GetChars(), finalName.GetChars(), DRERRORSTRING(err));
}
else
{
DrLogI("Renamed Native URI %s -> %s", uri.GetChars(), finalName.GetChars());
}
return err;
}
HRESULT DrPartitionOutputStream::FinalizeSuccessfulParts(DrOutputPartitionArrayRef partitionArray, DrStringR errorText)
{
HRESULT err = S_OK;
FILE* f;
errno_t ferr = fopen_s(&f, m_streamName.GetChars(), "w");
if (ferr != 0)
{
HRESULT err = HRESULT_FROM_WIN32(GetLastError());
errorText.SetF("Failed to open output file %s error %s", m_streamName.GetChars(), DRERRORSTRING(err));
DrLogW("%s", errorText.GetChars());
return err;
}
fprintf(f, "%s\n%d\n", m_pathBase.GetChars(), partitionArray->Allocated());
int i;
for (i=0; i<partitionArray->Allocated(); ++i)
{
DrOutputPartition p = partitionArray[i];
HRESULT thisErr = RenameSuccessfulPart(i, p);
if (err == S_OK && !SUCCEEDED(thisErr))
{
err = thisErr;
}
DrClusterResourcePtr clusterPtr = dynamic_cast<DrClusterResourcePtr>(p.m_resource);
if (clusterPtr != nullptr)
{
fprintf(f, "%d,%I64u,%s\n", i, p.m_size, clusterPtr->GetNode()->Host);
}
else
{
fprintf(f, "%d,%I64u,%s\n", i, p.m_size, p.m_resource->GetName().GetChars());
}
}
fclose(f);
return err;
}
HRESULT DrPartitionOutputStream::DiscardFailedStream(DrStringR errorText)
{
HRESULT err = S_OK;
BOOL b = ::DeleteFileA(m_streamName.GetChars());
if (b == 0)
{
HRESULT err = HRESULT_FROM_WIN32(GetLastError());
errorText.SetF("Failed to delete partition output stream %s error %s", m_streamName.GetChars(), DRERRORSTRING(err));
DrLogW("%s", errorText.GetChars());
}
return err;
}
void DrPartitionOutputStream::ExtendLease(DrTimeInterval)
{
}
|
<reponame>CEPFU/dwd-importer
package de.fu_berlin.agdb.dwd_importer.core;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Date;
import java.util.StringTokenizer;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import de.fu_berlin.agdb.importer.payload.DataType;
import de.fu_berlin.agdb.importer.payload.LocationWeatherData;
import de.fu_berlin.agdb.importer.payload.StationMetaData;
public class WeatherDataFileHandler extends DataFileHandler{
private static final Logger logger = LogManager.getLogger(WeatherDataFileHandler.class);
private IDWDDataHandler dwDataHandler;
public WeatherDataFileHandler(IWeatherDataFileProvider weatherDataProvider, IDWDDataHandler dwDataHandler) {
super(weatherDataProvider.getWeatherDataFile());
this.dwDataHandler = dwDataHandler;
}
@Override
public void handleDataFile() throws IOException {
logger.debug("Analyzing weather data File " + getFile().getName());
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getFile()), "ISO-8859-1"));
//ignore first line because it has no relevant information
//maybe only the last line should be used due to the fact that all other lines
//have duplicated information
String line = reader.readLine();
while((line = reader.readLine()) != null && line.length() > 1){
injectDataLine(line);
}
reader.close();
logger.debug("Analyzed weather data File " + getFile().getName());
getFile().delete();
logger.debug("Deleted weather data File " + getFile().getName());
}
@SuppressWarnings("unused")
private void injectDataLine(String line) {
line = line.replace(" ", "");
StringTokenizer tokenizer = new StringTokenizer(line, ";");
//Stations_ID
Long stationId = Long.valueOf(tokenizer.nextToken());
//Mess_Datum
String stringDate = tokenizer.nextToken();
stringDate = stringDate.substring(0, 4) + "-" + stringDate.substring(4, 6)+ "-" + stringDate.substring(6);
Date date = Date.valueOf(stringDate);
//Qualitaets_Niveau (Values form 1 to 10)
int qualityLevel = Integer.parseInt(tokenizer.nextToken());
//LUFTTEMPERATUR (°C)
double averageAirTemperature = Double.valueOf(tokenizer.nextToken());
//DAMPFDRUCK (hpa)
double steamPressure = Double.valueOf(tokenizer.nextToken());
//BEDECKUNGSGRAD (eight) (1/8, 2/8, ..., 8/8)
double cloudage = Double.valueOf(tokenizer.nextToken());
//LUFTDRUCK_STATIONSHOEHE (hpa)
double airPressure = Double.valueOf(tokenizer.nextToken());
//REL_FEUCHTE (%)
double relativeHumidityOfTheAir = Double.valueOf(tokenizer.nextToken());
//WINDGESCHWINDIGKEIT (m/sec)
double windSpeed = Double.valueOf(tokenizer.nextToken());
//LUFTTEMPERATUR_MAXIMUM (°C)
double maximumAirTemperature = Double.valueOf(tokenizer.nextToken());
//LUFTTEMPERATUR_MINIMUM (°C)
double minimumAirTemperature = Double.valueOf(tokenizer.nextToken());
//LUFTTEMP_AM_ERDB_MINIMUM (°C)
double minimumAirTemperatureGround = Double.valueOf(tokenizer.nextToken());
//WINDSPITZE_MAXIMUM (m/sec)
double maximumWindSpeed = Double.valueOf(tokenizer.nextToken());
//NIEDERSCHLAGSHOEHE (mm)
double precipitationDepth = Double.valueOf(tokenizer.nextToken());
//SONNENSCHEINDAUER
double sunshineDuration = Double.valueOf(tokenizer.nextToken());
//SCHNEEHOEHE
double snowHeight = Double.valueOf(tokenizer.nextToken());
StationMetaData metaDataForStation = dwDataHandler.getMetaDataForStation(stationId);
if(dwDataHandler.getMetaDataForStation(stationId) != null){
LocationWeatherData locationWeatherData = new LocationWeatherData(dwDataHandler.getMetaDataForStation(stationId), System.currentTimeMillis(), DataType.REPORT);
locationWeatherData.setQualityLevel(qualityLevel);
locationWeatherData.setTemperature(averageAirTemperature);
locationWeatherData.setSteamPressure(steamPressure);
locationWeatherData.setCloudage(cloudage);
locationWeatherData.setAtmospherePressure(airPressure);
locationWeatherData.setAtmosphereHumidity(relativeHumidityOfTheAir);
locationWeatherData.setWindSpeed(windSpeed);
locationWeatherData.setTemperatureHigh(maximumAirTemperature);
locationWeatherData.setTemperatureLow(minimumAirTemperature);
locationWeatherData.setMinimumAirGroundTemperature(minimumAirTemperatureGround);
locationWeatherData.setMaximumWindSpeed(maximumWindSpeed);
locationWeatherData.setPrecipitationDepth(precipitationDepth);
locationWeatherData.setSunshineDuration(sunshineDuration);
locationWeatherData.setSnowHeight(snowHeight);
dwDataHandler.addData(locationWeatherData);
}
}
}
|
// GetConfigInt returns a configuration integer value for a given identifier.
// Environment variables have preference over entries in the yaml file, whereby 'name' is
// converted to
//
// "OBCCA_" + strings.Replace(strings.ToUpper('name'), ".", "_")
//
// for environment variables.
//
func GetConfigInt(name string) int {
val := os.Getenv("OBCCA_"+strings.Replace(strings.ToUpper(name), ".", "_", -1))
if val == "" {
return viper.GetInt(name)
}
ival, _ := strconv.Atoi(val)
return ival
}
|
/**
* Overloads the appends method of StringBuffer
*
*/
public class DebugStringBuffer
{
private StringBuffer buffer = new StringBuffer();
public DebugStringBuffer()
{
}
public DebugStringBuffer(String str)
{
buffer= new StringBuffer(str);
}
public DebugStringBuffer append(String str)
{
buffer.append(str);
return this;
}
public DebugStringBuffer append(String str,String tester)
{
if(tester!=null&& !tester.equals(""))
{
buffer.append(str);
return this;
}
else
return this;
}
public DebugStringBuffer append(String str,Float tester)
{
if(tester!=null)
{
buffer.append(str);
return this;
}
else
return this;
}
public DebugStringBuffer append(DebugStringBuffer strBuffer,String tester)
{
// TODO: Override this java.lang.StringBuffer method
if(tester!=null&& !tester.equals(""))
{
buffer.append(strBuffer);
return this;
}
else
return this;
}
public String toString()
{
if(buffer!=null)
return buffer.toString();
else
return null;
}
}
|
<gh_stars>1-10
#include "CorePch.h"
#include <rtp++/mediasession/SimpleMediaSessionV2.h>
#include <rtp++/IRtpSessionManager.h>
#include <rtp++/RtpSessionManager.h>
namespace rtp_plus_plus
{
using media::MediaSample;
SimpleMediaSessionV2::SimpleMediaSessionV2(boost::asio::io_service& ioService)
:m_rIoService(ioService),
m_eState(ST_READY),
m_uiCompleteCount(0)
{
}
SimpleMediaSessionV2::~SimpleMediaSessionV2()
{
}
bool SimpleMediaSessionV2::hasVideo() const
{
return m_pVideoManager != 0;
}
bool SimpleMediaSessionV2::hasAudio() const
{
return m_pAudioManager != 0;
}
void SimpleMediaSessionV2::setVideoSessionManager(std::unique_ptr<IRtpSessionManager> pVideoManager)
{
m_pVideoManager = std::move(pVideoManager);
m_videoSource.setRtpSessionManager(m_pVideoManager.get());
m_pVideoManager->setRtpSessionCompleteNotifier(boost::bind(&SimpleMediaSessionV2::handleRtpSessionComplete, this));
}
void SimpleMediaSessionV2::setAudioSessionManager(std::unique_ptr<IRtpSessionManager> pAudioManager)
{
m_pAudioManager = std::move(pAudioManager);
m_audioSource.setRtpSessionManager(m_pAudioManager.get());
m_pAudioManager->setRtpSessionCompleteNotifier(boost::bind(&SimpleMediaSessionV2::handleRtpSessionComplete, this));
}
bool SimpleMediaSessionV2::sendVideo(const MediaSample& mediaSample)
{
if (m_pVideoManager)
{
m_pVideoManager->send(mediaSample);
return true;
}
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager configured for video in simple media session";
return false;
}
}
bool SimpleMediaSessionV2::sendVideo(const std::vector<MediaSample>& vMediaSamples)
{
if (m_pVideoManager)
{
m_pVideoManager->send(vMediaSamples);
return true;
}
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager configured for video in simple media session";
return false;
}
}
bool SimpleMediaSessionV2::isVideoAvailable() const
{
if (m_pVideoManager)
{
return m_pVideoManager->isSampleAvailable();
}
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager configured for video in simple media session";
return false;
}
}
std::vector<MediaSample> SimpleMediaSessionV2::getVideoSample()
{
if (m_pVideoManager)
{
return m_pVideoManager->getNextSample();
}
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager configured for video in simple media session";
return std::vector<MediaSample>();
}
}
bool SimpleMediaSessionV2::sendAudio(const MediaSample& mediaSample)
{
if (m_pAudioManager)
{
m_pAudioManager->send(mediaSample);
return true;
}
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager configured for audio in simple media session";
return false;
}
}
bool SimpleMediaSessionV2::sendAudio(const std::vector<MediaSample>& vMediaSamples)
{
if (m_pAudioManager)
{
m_pAudioManager->send(vMediaSamples);
return true;
}
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager configured for audio in simple media session";
return false;
}
}
bool SimpleMediaSessionV2::isAudioAvailable() const
{
if (m_pAudioManager)
{
return m_pAudioManager->isSampleAvailable();
}
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager configured for audio in simple media session";
return false;
}
}
std::vector<MediaSample> SimpleMediaSessionV2::getAudioSample()
{
if (m_pAudioManager)
{
return m_pAudioManager->getNextSample();
}
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager configured for audio in simple media session";
return std::vector<MediaSample>();
}
}
boost::system::error_code SimpleMediaSessionV2::start()
{
if (m_pVideoManager)
{
boost::system::error_code ec = m_pVideoManager->start();
if (ec)
{
#if 0
VLOG(2) << "HACK: ignoring failed media sessions for now in case of answer/offer rejections";
#else
return ec;
#endif
}
}
if (m_pAudioManager)
{
boost::system::error_code ec = m_pAudioManager->start();
if (ec)
{
#if 0
VLOG(2) << "HACK: ignoring failed media sessions for now in case of answer/offer rejections";
#else
return ec;
#endif
}
}
m_eState = ST_STARTED;
return boost::system::error_code();
}
boost::system::error_code SimpleMediaSessionV2::stop()
{
if (m_pVideoManager)
{
// ignore errors on stop
m_pVideoManager->stop();
}
if (m_pAudioManager)
{
// ignore errors on stop
m_pAudioManager->stop();
}
m_eState = ST_READY;
return boost::system::error_code();
}
SimpleMediaSessionV2::SimpleSourceAdapter::SimpleSourceAdapter()
:m_pRtpSessionManager(NULL)
{
}
void SimpleMediaSessionV2::SimpleSourceAdapter::setRtpSessionManager(IRtpSessionManager* pRtpSessionManager)
{
m_pRtpSessionManager = pRtpSessionManager;
m_pRtpSessionManager->registerObserver(boost::bind(&SimpleSourceAdapter::notify, this));
}
bool SimpleMediaSessionV2::SimpleSourceAdapter::isSampleAvailable() const
{
if (m_pRtpSessionManager)
return m_pRtpSessionManager->isSampleAvailable();
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager is configured!";
return false;
}
}
std::vector<MediaSample> SimpleMediaSessionV2::SimpleSourceAdapter::getNextSample()
{
if (m_pRtpSessionManager)
return m_pRtpSessionManager->getNextSample();
else
{
LOG_FIRST_N(WARNING, 1) << "No RTP session manager is configured!";
return std::vector<MediaSample>();
}
}
void SimpleMediaSessionV2::SimpleSourceAdapter::notify()
{
// forwarder for observers
triggerNotification();
}
void SimpleMediaSessionV2::handleRtpSessionComplete()
{
++m_uiCompleteCount;
if (m_pVideoManager && m_pAudioManager)
{
if (m_uiCompleteCount == 2)
{
VLOG(2) << "All RTP sessions complete.";
// HACK to access session stats
boost::posix_time::ptime tFirstSyncedVideoArrival;
boost::posix_time::ptime tFirstSyncedVideoPts;
RtpSessionManager* pRtpSessionManager = dynamic_cast<RtpSessionManager*>(m_pVideoManager.get());
if (pRtpSessionManager)
{
const std::vector<RtpPacketStat>& rtpStats = pRtpSessionManager->getPacketStats();
if (!rtpStats.empty())
{
auto it = std::find_if(rtpStats.begin(), rtpStats.end(), [](const RtpPacketStat& stat)
{
return std::get<2>(stat);
});
if (it != rtpStats.end())
{
const RtpPacketStat& stat = *it;
tFirstSyncedVideoArrival = std::get<0>(stat);
tFirstSyncedVideoPts = std::get<1>(stat);;
boost::posix_time::ptime tPrevArrival = tFirstSyncedVideoArrival;
boost::posix_time::ptime tPrevPts = tFirstSyncedVideoPts;
LOG(INFO) << "First Video RTCP synced packet stats: Pts: " << tFirstSyncedVideoPts << " arrival: " << tFirstSyncedVideoArrival;
++it;
std::vector<uint64_t> vDiffs;
for (; it != rtpStats.end(); ++it)
{
const RtpPacketStat& s = *it;
boost::posix_time::ptime tArrival = std::get<0>(s);
boost::posix_time::ptime tPts = std::get<1>(s);
uint64_t uiDiffArrivalMs = (tArrival - tPrevArrival).total_milliseconds();
uint64_t uiDiffPtsMs = (tPts - tPrevPts).total_milliseconds();
vDiffs.push_back(uiDiffPtsMs - uiDiffArrivalMs);
tPrevArrival = tArrival;
tPrevPts = tPts;
}
}
}
}
boost::posix_time::ptime tFirstSyncedAudioArrival;
boost::posix_time::ptime tFirstSyncedAudioPts;
RtpSessionManager* pAudioRtpSessionManager = dynamic_cast<RtpSessionManager*>(m_pAudioManager.get());
if (pAudioRtpSessionManager)
{
const std::vector<RtpPacketStat>& rtpStats = pAudioRtpSessionManager->getPacketStats();
if (!rtpStats.empty())
{
auto it = std::find_if(rtpStats.begin(), rtpStats.end(), [](const RtpPacketStat& stat)
{
return std::get<2>(stat);
});
if (it != rtpStats.end())
{
const RtpPacketStat& stat = *it;
tFirstSyncedAudioArrival = std::get<0>(stat);
tFirstSyncedAudioPts = std::get<1>(stat);;
LOG(INFO) << "First Audio RTCP synced packet stats: Pts: " << tFirstSyncedAudioPts << " arrival: " << tFirstSyncedAudioArrival;
}
}
}
if (!tFirstSyncedAudioPts.is_not_a_date_time() && !tFirstSyncedVideoPts.is_not_a_date_time())
{
// calc differences
LOG(INFO) << "Diff in A/V PTS: " << (tFirstSyncedVideoPts - tFirstSyncedAudioPts).total_milliseconds() << "ms"
<< " arrival time: " << (tFirstSyncedVideoArrival - tFirstSyncedAudioArrival).total_milliseconds() << "ms";
}
if (m_mediaSessionCompleteHandler) m_mediaSessionCompleteHandler();
}
}
else if (m_pVideoManager || m_pAudioManager)
{
if (m_uiCompleteCount == 1)
{
VLOG(2) << "All RTP sessions complete.";
if (m_mediaSessionCompleteHandler) m_mediaSessionCompleteHandler();
}
}
}
} // rtp_plus_plus
|
<filename>tests/test_exception_utils.py
from approvaltests import verify_exception
from approvaltests.utilities.exceptions.exception_collector import ExceptionCollector, gather_all_exceptions
def is_odd(integer):
if integer % 2 != 0:
raise ValueError(f"{integer} is not odd!")
def test_gather_all_exceptions():
collector = ExceptionCollector()
for i in range(1, 6):
collector.gather(lambda: is_odd(i))
verify_exception(lambda: collector.release())
def test_gather_all_exceptions_from_list():
verify_exception(lambda: gather_all_exceptions(range(1, 6), is_odd).release())
|
<reponame>thoughtworks/GilgaMesh
#include <nrf_nvic.h>
uint32_t sys_ClearPendingIRQ(IRQn_Type irqN) {
return sd_nvic_ClearPendingIRQ(irqN);
}
|
def monp_fromdic(self, monp_s):
monp = []
for mong_s in monp_s:
mong = Monstergrp(game, mong_s['name'])
mong.monsters = []
mong.identified = mong_s['identified']
for mon_s in mong_s:
mon = Monster(game, mon_s['name'])
mon.hp = mon_s['hp']
mon.hpplus = mon_s['hpplus']
mon.ac = mon_s['ac']
mon.state = State[mon_s['state']]
mon.silenced = mon_s['silenced']
mon.poisoned = mon_s['poisoned']
mong.monsters.append(mon)
monp.append(mong)
return monp
|
/// Combines the accumulation input instances into a single input instance.
fn compute_combined_hp_commitments(
input_instances: &[&InputInstance<G>],
proof: &Proof<G>,
mu_challenges: &[G::ScalarField],
nu_challenges: &[G::ScalarField],
combined_challenges: &[G::ScalarField],
) -> InputInstance<G> {
let num_inputs = input_instances.len();
let hiding_comm_addend_1 = proof
.hiding_comms
.as_ref()
.map(|hiding_comms| hiding_comms.comm_1.mul(mu_challenges[num_inputs].into()));
let combined_comm_1 = Self::combine_commitments(
input_instances.iter().map(|instance| &instance.comm_1),
combined_challenges,
hiding_comm_addend_1.as_ref(),
);
let hiding_comm_addend_2 = proof
.hiding_comms
.as_ref()
.map(|hiding_comms| hiding_comms.comm_2.mul(mu_challenges[1].into()));
let combined_comm_2 = Self::combine_commitments(
input_instances
.iter()
.map(|instance| &instance.comm_2)
.rev(),
nu_challenges,
hiding_comm_addend_2.as_ref(),
);
let combined_comm_3 = {
let product_poly_comm_low_addend =
Self::combine_commitments(proof.product_poly_comm.low.iter(), &nu_challenges, None);
let product_poly_comm_high_addend = Self::combine_commitments(
proof.product_poly_comm.high.iter(),
&nu_challenges[num_inputs..],
None,
);
let hiding_comm_addend_3 = proof
.hiding_comms
.as_ref()
.map(|hiding_comms| hiding_comms.comm_3.mul(mu_challenges[num_inputs].into()));
let comm_3_addend = Self::combine_commitments(
input_instances.iter().map(|instance| &instance.comm_3),
&mu_challenges,
hiding_comm_addend_3.as_ref(),
)
.mul(nu_challenges[num_inputs - 1].into());
product_poly_comm_low_addend + &product_poly_comm_high_addend + &comm_3_addend
};
let mut combined_comms = G::Projective::batch_normalization_into_affine(&[
combined_comm_3,
combined_comm_2,
combined_comm_1,
]);
InputInstance {
comm_1: combined_comms.pop().unwrap(),
comm_2: combined_comms.pop().unwrap(),
comm_3: combined_comms.pop().unwrap(),
}
}
|
According to research by online magazine Spiked 80% of universities have restrictions on free speech – from banning sombreros to excluding the Sun
When Professor Thomas Scotto, of Essex University’s department of government, invited Israel’s deputy ambassador to give a talk to political science students, he hoped for “lots of disagreement: that the speaker would express his views and that the students would challenge him”.
Instead, a noisy protest outside the venue ramped up into an attempt to storm the building, students in the lecture theatre heckled the Israeli diplomat, and it became impossible for him to begin. With feelings running high, university security said they could no longer guarantee the speaker’s safety. The event had to be abandoned.
“It broke my heart that some students came with pages and pages of notes ready to challenge the speaker, and that was wasted because other students violently opposed him being there,” says Scotto. “One of the key goals of the university is ‘excellence in education’: I don’t think we accomplish this when an element of the student body believes the only appropriate tools they have when confronted with ideas and people they disagree with is to throw temper tantrums and employ hecklers’ vetoes.”
In the wake of the Charlie Hebdo murders in Paris, people all over the world are debating whether freedom of speech means protecting a right to offend. Scotto says that listening to and rigorously questioning high-profile speakers about controversial global issues is “vital training” for undergraduates and a life skill – especially for anyone wanting to work in public life.
In research by online magazine Spiked, 80% of universities are shown, as a result of their official policies and actions, to have either restricted or actively censored free speech and expression on campus beyond the requirements of the law. Spiked’s first ever Free Speech University Rankings – which were overseen by Professor Dennis Hayes, head of the centre for educational research at Derby University and Dr Joanna Williams, senior lecturer in higher education at Kent university – show each university administration and students’ union graded green, amber or red based on an assessment of their policies and actions. Institutions have been given an overall ranking based on the two combined.
The research paints a picture of students keen to discourage racism but sometimes with almost comic effect. Birmingham university’s student union has banned “racist” sombreros and native American dress from being worn on campus. Lancaster union has banned initiation ceremonies, defined in part as “engaging in public stunts and buffoonery”.
Facebook Twitter Pinterest A Cambridge proctor speaks to a protestor objecting to the appearance of far-right politician Marine Le Pen in 2013. Spiked gave Cambridge an orange rating. Photograph: Oli Scarff/Getty Images
Essex is among the worst performers in Spiked’s research – one of five universities in which the student union and the administration are both assessed as actively preventing freedom of speech. The other four are Portsmouth, Northampton, Bath Spa and the University of the West of England.
Applying to the country’s most prestigious institutions won’t guarantee the right to speak your mind either: the research showed 88% of Russell Group and 1994 Group universities have placed restrictions on freedom of speech and expression. Oxford – where one college recently called off a debate about abortion – is ranked red. Cambridge is amber.
“What’s worrying is we seem to have moved away from a clear ideological divide to an apolitical calculation as to who should be censored, because of a wider judgment based purely on the potential to upset and offend,” says Tom Slater, assistant editor at Spiked and co-ordinator of the project. “We found a few startling examples.” In one incident, at London South Bank University, an atheist group was asked to remove their posters. “It’s how wide that net is becoming that’s troubling, because it could go anywhere.”
Not everyone will agree with the criteria Spiked used in its rankings. Banning an event, a speaker or a song – all cited as reasons for being graded “red” – is usually considered an act of censorship. But an equality policy stating that homophobic, sexist and racist language will not be tolerated also attracts a red rating.
Bath Spa University says it has reviewed its policies in the light of Spiked’s claims that it is “a hostile environment for freedom of speech” but finds “no evidence whatsoever to support this conclusion”. Portsmouth says: “We value freedom of speech and nothing presented in this analysis suggests otherwise.” Northampton, meanwhile, states that while it supports “constructive” debates on all issues, it does not tolerate “offensive or extremist activities”.
Essex University points out that it is given green ratings for its code of practice on freedom of speech, university charter and other key policies, and says it is “absurd” that it is given a red ranking “for providing guidance to our community about avoiding homophobic behaviour, in line with the Equality Act 2010. We make no apology for working to ensure all our staff and students are treated with dignity and respect.”
One of the reasons for UWE’s red ranking was the student union’s ban on advertising by payday loan companies. This, says the university, is simply a common sense effort to prevent exploitation of students.
There is nuance in the grading system however: UWE student union’s vote approving the boycott, divestment and sanctions campaign against Israel was given amber. Spiked judges said that “the union is subscribing not only to the boycott of products but the boycotting of Israeli academics ... as this motion does not explicitly link to a censorship of speech, this is not an outright ban on pro-Israeli thought.”
A commercial decision was made to boycott the Sun and the Star from sale in our shop based on their sexist attitudes Chantel Le Carpentier, Essex univeristy
With the home secretary, Theresa May, threatening universities with legal sanctions via a new counter-terrorism bill unless they act to prevent radicalisation on campus, it is not surprising if vice-chancellors are anxious to square the circle of promoting free speech with acting lawfully – quite apart from ensuring staff and student safety. So concerned are they that last week a number of vice-chancellors wrote to the home secretary to say that universities should be exempted from the new law.
In fact, Spiked’s rankings show it is not usually university managements that are behind outright censorship on campus: only 9.5% have done so, according to the research. By contrast, 51% of student unions have actively censored certain types of speech or instituted bans. “Students’ own representative bodies are far more censorious than universities,” says Slater.
Why? The unions at Essex, Portsmouth and the University of the West of England all issued statements saying that their policies are intended to protect students and staff, and pointing out that students vote them in. Northampton’s union president did not respond to requests for a comment.
“There’s a difference between being critical of ideas and being critical of people,” says Bruce Galliver, president of Bath Spa students’ union, the only one willing to be interviewed. “I don’t think any ideas are beyond criticism. But it’s offensive language directed at individuals that I’d have a problem with, and that’s what our policies are trying to protect.”
Along with other student unions, Bath Spa banned Robin Thicke’s controversial song Blurred Lines. “That was voted for,” says Galliver. “I’d commend the students for being proactive in ensuring a track where rape culture and the idea that consent is something to ignore isn’t played on campus. And the opportunity to challenge a motion that goes through the Student Council is always there.”
Facebook Twitter Pinterest Protesters clash and police clash outside Cambridge University’s Student Union in 2013. Photograph: Oli Scarff/Getty Images
At Portsmouth University, student union president Grant Clarke says in a statement that policies aimed at defending students from racist, sexist and homophobic harassment don’t preclude people from openly talking and discussing these issues, “but we don’t accept these behaviours on our campus”.
And at Essex, bans on certain newspapers are framed by student union president Chantel Le Carpentier as “a commercial decision to boycott the Sun and the Star from sale in our shop based on their representation of women in the media and sexist attitudes … We use our freedom of speech to urge people not to buy it by not stocking it on campus.”
Some academics, however, are worried by student unions’ determination to rule on what students should and shouldn’t see or discuss – and by what they characterise as universities’ failure to challenge it.
“Real freedom of expression can hurt. That’s the price we pay,” says professor Bill Durodié, an expert in the causes and perceptions of security risk, at the university of Bath. “Is fostering empathy with other people’s feelings valuable? One hundred percent yes. Should it direct everything you do? No.”
An obsession with protecting people’s feelings has, over time, begun to trump other values, he says, “and if feelings are sacrosanct, then at the margins, the attacks on Charlie Hebdo are the end consequence. I’d say the solution to bad speech is more speech, not regulated speech.”
Real freedom of expression can hurt. That’s the price we pay Prof Bill Durodié, University of Bath
The ramifications for universities go wider, suggests Hayes. There is, he says, a growing trend for rigorous intellectual challenge to be seen as too scary for students to cope with.
“Universities have developed a therapeutic ethos, where students are no longer seen as confident adults, but as vulnerable,” he says. “And if you tell them that they need to be looked after and protected, then students develop this image of themselves, and vulnerability becomes a badge.”
“Vice chancellors are often very supportive of academic freedom and free speech,” he says. “But in lower levels of management, when they’re making decisions, there’s this sensitivity about not upsetting students which makes it impossible to have proper debate.”
When Israel’s deputy ambassador was prevented from talking at Essex in 2013, the vice-chancellor condemned the protests and students were sanctioned. The university says it “made it clear that it would fully support the department should they wish to address these issues again as a part of their programmes of study [including] support for representatives of the Israeli government being invited to address students”.
Scotto maintains, however, that he was not encouraged to reinstate the event. “There was no realisation that this is a long-term, systemic problem. When I pressed to have the speaker back I was told ‘Tom, just let it go’.”
Reflecting on the debacle now, Scotto says: “Universities need to articulate their values or set the tone necessary to promote the open exchange of ideas. The reality is that the world is a big, mean place. And some students seem to want to be shielded from that.”
How they compare
Green ‘good’ rankings to …
• University of Wales, Trinity St David
• University of Winchester
• University of Buckingham
• London Met
• Liverpool Hope
• University of Sunderland
• Southampton Solent University
… but others get the red light:
• Bath Spa University
• Essex University
• Portsmouth University
• Northampton University
• University of the West of England
Source: Spiked
|
/** Abstract class for thread which searches for documentation
*
* @author Petr Hrebejk, Petr Suchomel
*/
public abstract class IndexSearchThread implements Runnable {
private static final RequestProcessor RP = new RequestProcessor(IndexSearchThread.class.getName(), 1, false, false);
// PENDING: Add some abstract methods
//protected String toFind;
// documentation index file (or foldee for splitted index)
protected URL indexRoot;
private DocIndexItemConsumer ddiConsumer;
private final RequestProcessor.Task rpTask;
private boolean isFinished = false;
protected boolean caseSensitive;
protected String lastField=""; //NOI18N
protected String middleField=""; //NOI18N
protected String reminder=""; //NOI18N
private int tokens=0;
private String lastAdd =""; //NOI18N
private String lastDeclaring=""; //NOI18N
/** This method must terminate the process of searching */
abstract void stopSearch();
@SuppressWarnings("LeakingThisInConstructor")
public IndexSearchThread(String toFind, URL fo, DocIndexItemConsumer ddiConsumer, boolean caseSensitive) {
this.ddiConsumer = ddiConsumer;
this.indexRoot = fo;
this.caseSensitive = caseSensitive;
this.rpTask = RP.create(this);
//this.toFind = toFind;
//rpTask = RequestProcessor.createRequest( this );
StringTokenizer st = new StringTokenizer(toFind, "."); //NOI18N
tokens = st.countTokens();
//System.out.println(tokens);
if( tokens > 1 ){
if( tokens == 2 ){
middleField = st.nextToken();
lastField = st.nextToken();
}
else{
for( int i = 0; i < tokens-2; i++){
reminder += st.nextToken();
if (i + 1 < tokens - 2) {
reminder += '.';
}
}
middleField = st.nextToken();
lastField = st.nextToken();
}
}
else{
lastField = toFind;
}
if( !caseSensitive ){
reminder = reminder.toUpperCase();
middleField = middleField.toUpperCase();
lastField = lastField.toUpperCase();
}
//System.out.println("lastField" + lastField);
}
protected synchronized void insertDocIndexItem( DocIndexItem dii ) {
//no '.', can add directly
//System.out.println("Inserting");
/*
try{
PrintWriter pw = new PrintWriter( new FileWriter( "c:/javadoc.dump", true ));
pw.println("\"" + dii.getField() +"\""+ " " + "\""+dii.getDeclaringClass()+ "\"" + " " + "\""+ dii.getPackage()+ "\"");
pw.println("\"" + lastField + "\"" + " " + "\"" + middleField + "\"" + " " + "\"" + reminder + "\"");
pw.flush();
pw.close();
}
catch(IOException ioEx){ioEx.printStackTrace();}
*/
String diiField = dii.getField();
String diiDeclaringClass = dii.getDeclaringClass();
String diiPackage = dii.getPackage();
if( !caseSensitive ){
diiField = diiField.toUpperCase();
diiDeclaringClass = diiDeclaringClass.toUpperCase();
diiPackage = diiPackage.toUpperCase();
}
if( tokens < 2 ){
if( diiField.startsWith( lastField ) ){
//System.out.println("------");
//System.out.println("Field: " + diiField + " last field: " + lastAdd + " declaring " + diiDeclaringClass + " package " + diiPackage);
if( !lastAdd.equals( diiField ) || !lastDeclaring.equals( diiDeclaringClass )){
//System.out.println("ADDED");
ddiConsumer.addDocIndexItem ( dii );
lastAdd = diiField;
lastDeclaring = diiDeclaringClass;
}
//System.out.println("------");
}
else if( diiDeclaringClass.startsWith( lastField ) && dii.getIconIndex() == DocSearchIcons.ICON_CLASS ) {
if( !lastAdd.equals( diiDeclaringClass ) ){
ddiConsumer.addDocIndexItem ( dii );//System.out.println("Declaring class " + diiDeclaringClass + " icon " + dii.getIconIndex() + " remark " + dii.getRemark());
lastAdd = diiDeclaringClass;
}
}
else if( diiPackage.startsWith( lastField + '.' ) && dii.getIconIndex() == DocSearchIcons.ICON_PACKAGE ) {
if( !lastAdd.equals( diiPackage ) ){
ddiConsumer.addDocIndexItem ( dii );//System.out.println("Package " + diiPackage + " icon " + dii.getIconIndex() + " remark " + dii.getRemark());
lastAdd = diiPackage;
}
}
}
else{
if( tokens == 2 ){
//class and field (method etc. are equals)
//System.out.println(dii.getField() + " " + lastField + " " + dii.getDeclaringClass() + " " + middleField);
if( diiField.startsWith(lastField) && diiDeclaringClass.equals(middleField) ){
ddiConsumer.addDocIndexItem ( dii );
}
else if( diiPackage.startsWith( middleField ) && diiDeclaringClass.equals( lastField ) ){
ddiConsumer.addDocIndexItem ( dii );
}
else if( diiPackage.startsWith( (middleField + '.' + lastField) ) && dii.getIconIndex() == DocSearchIcons.ICON_PACKAGE ){
ddiConsumer.addDocIndexItem ( dii );
}
}
else{
//class and field (method etc. are equals)
if( diiField.startsWith(lastField) && diiDeclaringClass.equals(middleField) && diiPackage.startsWith( reminder ) ){
ddiConsumer.addDocIndexItem ( dii );
}
//else if( diiDeclaringClass.equals(lastField) && diiPackage.startsWith( (reminder + '.' + middleField).toUpperCase()) ){
else if( diiDeclaringClass.startsWith(lastField) && diiPackage.equals( (reminder + '.' + middleField + '.')) ){
ddiConsumer.addDocIndexItem ( dii );
}
else if( diiPackage.startsWith( (reminder + '.' + middleField + '.' + lastField) ) && dii.getIconIndex() == DocSearchIcons.ICON_PACKAGE ){
ddiConsumer.addDocIndexItem ( dii );
}
}
}
}
public void go() {
rpTask.schedule(0);
rpTask.waitFinished();
}
public void finish() {
if (!rpTask.isFinished() && !rpTask.cancel()) {
stopSearch();
}
taskFinished();
}
public void taskFinished() {
if (!isFinished) {
isFinished = true;
ddiConsumer.indexSearchThreadFinished( this );
}
}
/** Class for callback. Used to feed some container with found
* index items;
*/
public interface DocIndexItemConsumer {
/** Called when an item is found */
void addDocIndexItem(DocIndexItem dii);
/** Called when a task finished. May be called more than once */
void indexSearchThreadFinished(IndexSearchThread ist);
}
}
|
package com.jreframeworker.atlas.analysis;
import com.ensoftcorp.atlas.core.db.graph.Node;
import com.ensoftcorp.atlas.core.db.set.AtlasSet;
import com.ensoftcorp.atlas.core.script.Common;
import com.ensoftcorp.atlas.core.xcsg.XCSG;
public class ClassAnalysis {
/**
* Returns true if the given class is marked final
* @param clazz
* @return
*/
public static boolean isFinal(Node clazz){
return clazz.taggedWith(XCSG.Java.finalClass);
}
/**
* Returns true if the given class is marked public
* @param clazz
* @return
*/
public static boolean isPublic(Node clazz){
return clazz.taggedWith(XCSG.publicVisibility);
}
/**
* Returns the name of the given class
* @param clazz
* @return
*/
public static String getName(Node clazz){
return clazz.getAttr(XCSG.name).toString();
}
/**
* Returns the package name that contains the given class
* @param clazz
* @return
*/
public static String getPackage(Node clazz){
AtlasSet<Node> pkgs = Common.toQ(clazz).containers().nodesTaggedWithAny(XCSG.Package).eval().nodes();
if(pkgs.isEmpty()){
throw new IllegalArgumentException("Class is not contained in a package!");
} else if(pkgs.size() > 1){
throw new IllegalArgumentException("Class is not contained in multiple packages!");
} else {
return pkgs.one().getAttr(XCSG.name).toString();
}
}
}
|
Schnelle parallele Fehlererholung in verteilten In-Memory Key-Value Systemen
Big data analytics and large-scale interactive graph applications require low-latency data access and high throughput for billions to trillions of mostly small data objects. Distributed in-memory systems address these challenges by storing all data objects in RAM and aggregating hundreds to thousands of servers, each providing 128 GB to 1024 GB RAM, in commodity clusters or in the cloud. This thesis addresses two main research challenges of large-scale distributed in-memory systems: (1) fast recovery of failed servers and (2) highly concurrent sending/receiving of network messages (small and large messages) with high throughput and low latency. Masking server failures requires data replication. We decided to replicate data on remote disks and not in remote memory because RAM is too expensive and volatile, resulting in data losses in case of a data center power outage. For interactive applications, it is essential that server recovery is very fast, i.e., the objects’ availability is restored within one or two seconds. This is challenging for servers storing hundreds of millions or even billions of small data objects. Additionally, the recovery performance depends on many factors like disk, memory and network bandwidth as well as processing power for reloading the storage. This thesis proposes a novel backup and recovery concept based on replicating the data of one server to many backup servers which store replicas in logs on their local disks. This allows a fast-parallel recovery of a crashed server by aggregating resources of backup servers, each recovering a fraction of the failed server’s objects. The global replica distribution is optimized to enable a fast-parallel recovery of a crashed server as well as providing additional options for tuning data loss probability in case of multiple simultaneous server failures. We also propose a new two-level logging approach and efficient epoch-based version management both designed for storing replicas of large amounts of small data objects with a low memory footprint. Server failure detection, as well as recovery coordination, is based on a superpeer overlay network complemented by a fast, parallel local recovery utilizing multiple cores and mitigating I/O limitations. All proposed concepts have been implemented and integrated into the Java-based in-memory system DXRAM. The evaluation shows that the proposed concept outperforms state-of-the-art distributed inmemory key-value stores. Large-scale experiments in the Microsoft Azure cloud show that servers storing hundreds of millions of small objects can be recovered in less than 2 seconds, even under heavy load. The proposed crash-recovery architecture and the key-value store itself require a fast and highly concurrent network subsystem enabling many threads per server to synchronously and asynchronously send/receive small data objects, concurrently serialized into messages and aggregated transparently into large network packets. To the best of our knowledge, none of the available network systems in the Java world provide all these features. This thesis proposes a network subsystem providing concurrent object serialization, synchronous and asynchronous messaging and automatic connection management. The modular design is able to support different transport implementations, currently implemented for Ethernet and InfiniBand. We combine several well-known and novel techniques, like lock-free programming, zero-copy sending/receiving, parallel de-/serialization and implicit thread scheduling, to allow low-latency message passing while also providing high throughput. The evaluation of the developed network subsystem shows good scalability with constant latencies and full saturation of the underlying interconnect, even in a worst-case scenario with an all-to-all communication pattern, tested with up to 64 servers in the cloud. The network subsystem achieves latencies of sub 10 μs (round-trip) including object de-/serialization and duplex throughputs of more than 10 GB/s with FDR InfiniBand and good performance with up to hundreds of threads sending/receiving in parallel, even with small messages (< 100 bytes).
|
/**
* we store all property to remove for very last moment (in order to potentially reuse their value)
* @param property property resource that should be removed
*/
private void addPropertyToRemove(Resource property){
if (property != null) {
if (propertiesToRemove == null) {
propertiesToRemove = new ArrayList<>();
}
propertiesToRemove.add(property);
}
}
|
/// Updates acceleration structures required for tests to pass.
fn update_structures(&mut self, entity: Entity, old: Option<Position>, new: Position) {
let cross = ChunkCrossEvent {
old: old.map(Position::chunk),
new: new.chunk(),
entity,
};
self.handle(cross, on_chunk_cross_update_chunk_entities);
if self.world.has::<ChunkHolder>(entity) {
self.handle(cross, on_chunk_cross_update_chunks);
}
}
|
Nuclear magnetic resonance studies of antibody-antigen interactions.
NMR is a useful method for studying antibody-antigen interactions in solution but the large size of the molecules makes interpretation of the data difficult. Multinuclear NMR and a family of switch variant antibodies and their proteolytic fragments are used to circumvent this problem and investigate the process of molecular recognition in antibody function. An Fv fragment has been prepared in high yield from a mouse IgG2a anti-dansyl-L-lysine monoclonal antibody in which the entire CH1 domain is deleted. 13C NMR resonances are observed for switch variant antibodies selectively labelled by 13C at the carbonyl carbon. Using a double-labelling method, site-specific assignments have been completed for all the methionine resonances in these antibodies. Comparison of the NMR spectra for intact antibodies and those of their proteolytic fragments suggests that carbonyl carbon chemical shift data can provide information on the way in which information is transmitted through different domains on antigen binding. Selective labelling of the antibody with 1H, 13C or 15N followed by nuclear Overhauser effect spectroscopy has identified some of the residues involved in antigen binding and indicated that the structure of the Fv fragment is significantly affected by antigen binding.
|
def ClearBuildRoot(buildroot, preserve_paths=()):
if os.path.exists(buildroot):
cmd = ['find', buildroot, '-mindepth', '1', '-maxdepth', '1']
ignores = []
for path in preserve_paths:
if ignores:
ignores.append('-a')
ignores += ['!', '-name', path]
cmd.extend(ignores)
cmd += ['-exec', 'rm', '-rf', '{}', '+']
cros_build_lib.sudo_run(cmd)
osutils.SafeMakedirs(buildroot)
|
import java.util.Scanner;
public class Task876A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
byte n = scanner.nextByte();
byte a = scanner.nextByte();
byte b = scanner.nextByte();
byte c = scanner.nextByte();
scanner.close();
int path = 0;
byte min = c;
if ((a <= b) && (a <= c))
min = a;
else if ((b <= a) && (b <= c))
min = b;
n--;
if (n == 0)
System.out.println(path);
else {
if ((min == a) || (min == b))
for (int counter = 0; counter < n; counter++)
path += min;
else {
if (a < b)
path += a;
else
path += b;
n--;
for (int counter = 0; counter < n; counter++)
path += min;
}
System.out.println(path);
}
}
}
|
// init registers ingress usage metrics.
func init() {
klog.V(3).Infof("Registering Ingress usage metrics %v and %v, NEG usage metrics %v", ingressCount, servicePortCount, networkEndpointGroupCount)
prometheus.MustRegister(ingressCount, servicePortCount, networkEndpointGroupCount)
klog.V(3).Infof("Registering L4 ILB usage metrics %v", l4ILBCount)
prometheus.MustRegister(l4ILBCount)
klog.V(3).Infof("Registering PSC usage metrics %v", serviceAttachmentCount)
prometheus.MustRegister(serviceAttachmentCount)
}
|
# Copyright 2018-2021 Xanadu Quantum 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.
"""
Tests for the CommutingEvolution template.
"""
import pytest
from pennylane import numpy as np
import pennylane as qml
from scipy.linalg import expm
def test_adjoint():
"""Tests the CommutingEvolution.adjoint method provides the correct adjoint operation."""
n_wires = 2
dev1 = qml.device("default.qubit", wires=n_wires)
dev2 = qml.device("default.qubit", wires=n_wires)
obs = [qml.PauliX(0) @ qml.PauliY(1), qml.PauliY(0) @ qml.PauliX(1)]
coeffs = [1, -1]
hamiltonian = qml.Hamiltonian(coeffs, obs)
frequencies = (2,)
@qml.qnode(dev1)
def adjoint_evolution_circuit(time):
for i in range(n_wires):
qml.Hadamard(i)
qml.adjoint(qml.CommutingEvolution)(hamiltonian, time, frequencies)
return qml.expval(qml.PauliZ(1))
@qml.qnode(dev2)
def evolution_circuit(time):
for i in range(n_wires):
qml.Hadamard(i)
qml.CommutingEvolution(hamiltonian, time, frequencies)
return qml.expval(qml.PauliZ(1))
evolution_circuit(0.13)
adjoint_evolution_circuit(-0.13)
assert all(np.isclose(dev1.state, dev2.state))
def test_decomposition_expand():
"""Test that the decomposition of CommutingEvolution is an ApproxTimeEvolution with one step."""
hamiltonian = 0.5 * qml.PauliX(0) @ qml.PauliY(1)
time = 2.345
op = qml.CommutingEvolution(hamiltonian, time)
decomp = op.decomposition()
assert isinstance(decomp, qml.ApproxTimeEvolution)
assert all(decomp.hyperparameters["hamiltonian"].coeffs == hamiltonian.coeffs)
assert decomp.hyperparameters["n"] == 1
tape = op.expand()
assert len(tape) == 1
assert isinstance(tape[0], qml.ApproxTimeEvolution)
def test_matrix():
"""Test that the matrix of commuting evolution is the same as exponentiating -1j * t the hamiltonian."""
h = 2.34 * qml.PauliX(0)
time = 0.234
op = qml.CommutingEvolution(h, time)
mat = qml.matrix(op)
expected = expm(-1j * time * qml.matrix(h))
assert qml.math.allclose(mat, expected)
def test_forward_execution():
"""Compare the foward execution to an exactly known result."""
dev = qml.device("default.qubit", wires=2)
H = qml.PauliX(0) @ qml.PauliY(1) - 1.0 * qml.PauliY(0) @ qml.PauliX(1)
freq = (2, 4)
@qml.qnode(dev, diff_method=None)
def circuit(time):
qml.PauliX(0)
qml.CommutingEvolution(H, time, freq)
return qml.expval(qml.PauliZ(0))
t = 1.0
res = circuit(t)
expected = -np.cos(4)
assert np.allclose(res, expected)
class TestInputs:
"""Tests for input validation of `CommutingEvolution`."""
def test_invalid_hamiltonian(self):
"""Tests TypeError is raised if `hamiltonian` is not type `qml.Hamiltonian`."""
invalid_operator = qml.PauliX(0)
assert pytest.raises(TypeError, qml.CommutingEvolution, invalid_operator, 1)
class TestGradients:
"""Tests that correct gradients are obtained for `CommutingEvolution` when frequencies
are specified."""
def test_two_term_case(self):
"""Tests the parameter shift rules for `CommutingEvolution` equal the
finite difference result for a two term shift rule case."""
n_wires = 1
dev = qml.device("default.qubit", wires=n_wires)
hamiltonian = qml.Hamiltonian([1], [qml.PauliX(0)])
frequencies = (2,)
@qml.qnode(dev)
def circuit(time):
qml.PauliX(0)
qml.CommutingEvolution(hamiltonian, time, frequencies)
return qml.expval(qml.PauliZ(0))
x_vals = np.linspace(-np.pi, np.pi, num=10)
grads_finite_diff = [qml.gradients.finite_diff(circuit)(x) for x in x_vals]
grads_param_shift = [qml.gradients.param_shift(circuit)(x) for x in x_vals]
assert all(np.isclose(grads_finite_diff, grads_param_shift, atol=1e-4))
def test_four_term_case(self):
"""Tests the parameter shift rules for `CommutingEvolution` equal the
finite difference result for a four term shift rule case."""
n_wires = 2
dev = qml.device("default.qubit", wires=n_wires)
coeffs = [1, -1]
obs = [qml.PauliX(0) @ qml.PauliY(1), qml.PauliY(0) @ qml.PauliX(1)]
hamiltonian = qml.Hamiltonian(coeffs, obs)
frequencies = (2, 4)
@qml.qnode(dev)
def circuit(time):
qml.PauliX(0)
qml.CommutingEvolution(hamiltonian, time, frequencies)
return qml.expval(qml.PauliZ(0))
x_vals = [np.array(x, requires_grad=True) for x in np.linspace(-np.pi, np.pi, num=10)]
grads_finite_diff = [qml.gradients.finite_diff(circuit)(x) for x in x_vals]
grads_param_shift = [qml.gradients.param_shift(circuit)(x) for x in x_vals]
assert all(np.isclose(grads_finite_diff, grads_param_shift, atol=1e-4))
def test_differentiable_hamiltonian(self):
"""Tests correct gradients are produced when the Hamiltonian is differentiable."""
n_wires = 2
dev = qml.device("default.qubit", wires=n_wires)
obs = [qml.PauliX(0) @ qml.PauliY(1), qml.PauliY(0) @ qml.PauliX(1)]
diff_coeffs = np.array([1.0, -1.0], requires_grad=True)
frequencies = (2, 4)
def parameterized_hamiltonian(coeffs):
return qml.Hamiltonian(coeffs, obs)
@qml.qnode(dev)
def circuit(time, coeffs):
qml.PauliX(0)
qml.CommutingEvolution(parameterized_hamiltonian(coeffs), time, frequencies)
return qml.expval(qml.PauliZ(0))
x_vals = [np.array(x, requires_grad=True) for x in np.linspace(-np.pi, np.pi, num=10)]
grads_finite_diff = [
np.hstack(qml.gradients.finite_diff(circuit)(x, diff_coeffs)) for x in x_vals
]
grads_param_shift = [
np.hstack(qml.gradients.param_shift(circuit)(x, diff_coeffs)) for x in x_vals
]
assert np.isclose(grads_finite_diff, grads_param_shift, atol=1e-6).all()
|
#include "precompiled.h"
#pragma hdrstop
#include "BulletPhysicsSystemBackend.h"
#include <utility>
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#include "Modules/Graphics/GraphicsSystem/TransformComponent.h"
#include "Modules/Graphics/GraphicsSystem/MeshRendererComponent.h"
#include "BulletRigidBodyComponent.h"
#include "BulletUtils.h"
BulletPhysicsSystemBackend::BulletPhysicsSystemBackend(GameWorld* gameWorld)
: m_gameWorld(gameWorld)
{
}
BulletPhysicsSystemBackend::~BulletPhysicsSystemBackend()
{
SW_ASSERT(m_dynamicsWorld == nullptr &&
m_constraintSolver == nullptr &&
m_broadphaseInterface == nullptr &&
m_collisionDispatcher == nullptr &&
m_collisionConfiguration == nullptr);
}
glm::vec3 BulletPhysicsSystemBackend::getGravity() const
{
btVector3 gravity = m_dynamicsWorld->getGravity();
return {gravity.x(), gravity.y(), gravity.z()};
}
void BulletPhysicsSystemBackend::setGravity(const glm::vec3& gravity)
{
m_dynamicsWorld->setGravity({gravity.x, gravity.y, gravity.z});
}
void BulletPhysicsSystemBackend::update(float delta)
{
m_dynamicsWorld->stepSimulation(delta, 60);
}
void BulletPhysicsSystemBackend::configure()
{
m_collisionConfiguration = new btDefaultCollisionConfiguration();
m_collisionDispatcher = new BulletCollisionDispatcher(m_collisionConfiguration, shared_from_this());
m_broadphaseInterface = new btDbvtBroadphase();
m_constraintSolver = new btSequentialImpulseConstraintSolver();
m_collisionDispatcher
->setNearCallback(reinterpret_cast<btNearCallback>(BulletPhysicsSystemBackend::physicsNearCallback));
m_dynamicsWorld = new btDiscreteDynamicsWorld(m_collisionDispatcher,
m_broadphaseInterface, m_constraintSolver, m_collisionConfiguration);
m_broadphaseInterface->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
m_physicsDebugPainter = new BulletDebugPainter();
m_gameWorld->subscribeEventsListener<GameObjectAddComponentEvent<RigidBodyComponent>>(this);
m_gameWorld->subscribeEventsListener<GameObjectRemoveComponentEvent<RigidBodyComponent>>(this);
m_gameWorld->subscribeEventsListener<GameObjectAddComponentEvent<KinematicCharacterComponent>>(this);
m_gameWorld->subscribeEventsListener<GameObjectRemoveComponentEvent<KinematicCharacterComponent>>(this);
m_gameWorld->subscribeEventsListener<GameObjectOnlineStatusChangeEvent>(this);
}
void BulletPhysicsSystemBackend::unconfigure()
{
m_gameWorld->unsubscribeEventsListener<GameObjectRemoveComponentEvent<KinematicCharacterComponent>>(this);
m_gameWorld->unsubscribeEventsListener<GameObjectAddComponentEvent<KinematicCharacterComponent>>(this);
m_gameWorld->unsubscribeEventsListener<GameObjectRemoveComponentEvent<RigidBodyComponent>>(this);
m_gameWorld->unsubscribeEventsListener<GameObjectAddComponentEvent<RigidBodyComponent>>(this);
m_gameWorld->unsubscribeEventsListener<GameObjectOnlineStatusChangeEvent>(this);
delete m_physicsDebugPainter;
m_physicsDebugPainter = nullptr;
delete m_dynamicsWorld;
m_dynamicsWorld = nullptr;
delete m_constraintSolver;
m_constraintSolver = nullptr;
delete m_broadphaseInterface;
m_broadphaseInterface = nullptr;
delete m_collisionDispatcher;
m_collisionDispatcher = nullptr;
delete m_collisionConfiguration;
m_collisionConfiguration = nullptr;
}
EventProcessStatus BulletPhysicsSystemBackend::receiveEvent(
const GameObjectRemoveComponentEvent<RigidBodyComponent>& event)
{
if (!isConfigured()) {
return EventProcessStatus::Skipped;
}
const auto* bulletRigidBodyComponent =
dynamic_cast<const BulletRigidBodyComponent*>(&event.component->getBackend());
m_dynamicsWorld->removeRigidBody(bulletRigidBodyComponent->m_rigidBodyInstance);
event.component->resetBackend();
return EventProcessStatus::Processed;
}
EventProcessStatus BulletPhysicsSystemBackend::receiveEvent(
const GameObjectAddComponentEvent<RigidBodyComponent>& event)
{
SW_ASSERT(isConfigured());
SW_ASSERT(event.gameObject.hasComponent<TransformComponent>());
GameObjectComponentHandle<RigidBodyComponent> rigidBodyComponent = event.component;
rigidBodyComponent->setTransform(event.gameObject.getComponent<TransformComponent>()->getTransform());
GameObjectId gameObjectId = event.gameObject.getId();
const auto* bulletRigidBodyComponent =
dynamic_cast<const BulletRigidBodyComponent*>(&rigidBodyComponent->getBackend());
btRigidBody* rigidBodyInstance = bulletRigidBodyComponent->m_rigidBodyInstance;
rigidBodyInstance->setUserPointer(reinterpret_cast<void*>(static_cast<uintptr_t>(gameObjectId)));
auto* motionState = dynamic_cast<BulletMotionState*>(rigidBodyInstance->getMotionState());
motionState->setUpdateCallback([gameObjectId, this](const btTransform& transform) {
auto obj = this->m_gameWorld->findGameObject(gameObjectId);
SW_ASSERT(obj.isAlive());
BulletPhysicsSystemBackend::synchronizeTransforms(obj, transform);
});
m_dynamicsWorld->addRigidBody(bulletRigidBodyComponent->m_rigidBodyInstance);
// Only online objects should be affected by physics simulation
if (!event.gameObject.getComponent<TransformComponent>()->isOnline()) {
rigidBodyComponent->enableSimulation(false);
}
return EventProcessStatus::Processed;
}
EventProcessStatus BulletPhysicsSystemBackend::receiveEvent(
const GameObjectRemoveComponentEvent<KinematicCharacterComponent>& event)
{
SW_ASSERT(isConfigured());
GameObjectComponentHandle<KinematicCharacterComponent> kinematicCharacterComponent = event.component;
const auto* bulletKinematicComponent =
dynamic_cast<const BulletKinematicCharacterComponent*>(&kinematicCharacterComponent->getBackend());
m_dynamicsWorld->removeCollisionObject(bulletKinematicComponent->m_ghostObject);
m_dynamicsWorld->removeAction(bulletKinematicComponent->m_kinematicController);
kinematicCharacterComponent->resetBackend();
return EventProcessStatus::Processed;
}
EventProcessStatus BulletPhysicsSystemBackend::receiveEvent(
const GameObjectAddComponentEvent<KinematicCharacterComponent>& event)
{
SW_ASSERT(isConfigured());
SW_ASSERT(event.gameObject.hasComponent<TransformComponent>());
GameObjectComponentHandle<KinematicCharacterComponent> kinematicCharacterComponent = event.component;
kinematicCharacterComponent->setTransform(event.gameObject.getComponent<TransformComponent>()->getTransform());
GameObjectId gameObjectId = event.gameObject.getId();
auto* bulletKinematicComponent =
dynamic_cast<BulletKinematicCharacterComponent*>(&kinematicCharacterComponent->getBackend());
btGhostObject* ghostObject = bulletKinematicComponent->m_ghostObject;
ghostObject->setUserPointer(reinterpret_cast<void*>(static_cast<uintptr_t>(gameObjectId)));
auto* kinematicController = bulletKinematicComponent->m_kinematicController;
kinematicController->setGravity(m_dynamicsWorld->getGravity());
bulletKinematicComponent->setUpdateCallback([gameObjectId, this](const btTransform& transform) {
GameObject object = this->m_gameWorld->findGameObject(gameObjectId);
BulletPhysicsSystemBackend::synchronizeTransforms(object, transform);
});
m_dynamicsWorld->addCollisionObject(ghostObject, btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::AllFilter);
m_dynamicsWorld->addAction(kinematicController);
// Only online objects should be affected by physics simulation
if (!event.gameObject.getComponent<TransformComponent>()->isOnline()) {
kinematicCharacterComponent->enableSimulation(false);
}
return EventProcessStatus::Processed;
}
EventProcessStatus BulletPhysicsSystemBackend::receiveEvent(const GameObjectOnlineStatusChangeEvent& event)
{
SW_ASSERT(isConfigured());
GameObject affectedObject = event.gameObject;
if (affectedObject.hasComponent<RigidBodyComponent>()) {
affectedObject.getComponent<RigidBodyComponent>()->enableSimulation(event.makeOnline);
}
if (affectedObject.hasComponent<KinematicCharacterComponent>()) {
affectedObject.getComponent<KinematicCharacterComponent>()->enableSimulation(event.makeOnline);
}
return EventProcessStatus::Processed;
}
bool BulletPhysicsSystemBackend::isConfigured() const
{
return m_dynamicsWorld != nullptr;
}
void BulletPhysicsSystemBackend::physicsNearCallback(btBroadphasePair& collisionPair,
btCollisionDispatcher& dispatcher,
btDispatcherInfo& dispatchInfo)
{
dynamic_cast<const BulletCollisionDispatcher&>(dispatcher).getPhysicsSystemBackend().nearCallback(collisionPair,
dispatcher, dispatchInfo);
}
void BulletPhysicsSystemBackend::nearCallback(btBroadphasePair& collisionPair,
btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo)
{
auto* client1 = static_cast<btCollisionObject*>(collisionPair.m_pProxy0->m_clientObject);
auto* client2 = static_cast<btCollisionObject*>(collisionPair.m_pProxy1->m_clientObject);
RigidBodyCollisionProcessingStatus processingStatus = RigidBodyCollisionProcessingStatus::Skipped;
if (client1->getUserPointer() != nullptr && client2->getUserPointer() != nullptr) {
auto clientId1 = static_cast<GameObjectId>(reinterpret_cast<uintptr_t>(client1->getUserPointer()));
auto clientId2 = static_cast<GameObjectId>(reinterpret_cast<uintptr_t>(client2->getUserPointer()));
auto gameObject1 = m_gameWorld->findGameObject(clientId1);
auto collisionCallback1 = getCollisionsCallback(gameObject1);
auto gameObject2 = m_gameWorld->findGameObject(clientId2);
auto collisionCallback2 = getCollisionsCallback(gameObject2);
CollisionInfo collisionInfo = {.selfGameObject = gameObject1, .gameObject = gameObject2};
if (collisionCallback1 != nullptr) {
processingStatus = collisionCallback1(collisionInfo);
}
if (collisionCallback2 != nullptr && processingStatus != RigidBodyCollisionProcessingStatus::Processed) {
std::swap(collisionInfo.gameObject, collisionInfo.selfGameObject);
processingStatus = collisionCallback2(collisionInfo);
}
}
if (processingStatus != RigidBodyCollisionProcessingStatus::Processed) {
btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo);
}
}
CollisionCallback BulletPhysicsSystemBackend::getCollisionsCallback(GameObject& object)
{
if (object.hasComponent<RigidBodyComponent>()) {
return object.getComponent<RigidBodyComponent>()->getCollisionCallback();
}
else if (object.hasComponent<KinematicCharacterComponent>()) {
return object.getComponent<KinematicCharacterComponent>()->getCollisionCallback();
}
else {
return nullptr;
}
}
void BulletPhysicsSystemBackend::enableDebugDrawing(bool enable)
{
m_isDebugDrawingEnabled = enable;
if (enable) {
m_dynamicsWorld->setDebugDrawer(m_physicsDebugPainter);
}
else {
m_dynamicsWorld->setDebugDrawer(nullptr);
}
}
bool BulletPhysicsSystemBackend::isDebugDrawingEnabled()
{
return m_isDebugDrawingEnabled;
}
void BulletPhysicsSystemBackend::render()
{
if (isDebugDrawingEnabled()) {
m_dynamicsWorld->debugDrawWorld();
}
}
void BulletPhysicsSystemBackend::physicsTickCallback(btDynamicsWorld* world, btScalar timeStep)
{
auto* physicsBackend = reinterpret_cast<BulletPhysicsSystemBackend*>(world->getWorldUserInfo());
physicsBackend->m_updateStepCallback(static_cast<float>(timeStep));
}
void BulletPhysicsSystemBackend::setUpdateStepCallback(std::function<void(float)> callback)
{
m_updateStepCallback = callback;
if (m_updateStepCallback) {
m_dynamicsWorld->setInternalTickCallback(BulletPhysicsSystemBackend::physicsTickCallback,
reinterpret_cast<void*>(this), true);
}
else {
m_dynamicsWorld->setInternalTickCallback(nullptr,
reinterpret_cast<void*>(this), true);
}
}
void BulletPhysicsSystemBackend::synchronizeTransforms(GameObject& object, const btTransform& transform)
{
glm::quat orientation = BulletUtils::btQuatToGlm(transform.getRotation());
glm::vec3 origin = BulletUtils::btVec3ToGlm(transform.getOrigin());
if (object.hasComponent<TransformComponent>()) {
auto& objectTransformComponent = *object.getComponent<TransformComponent>().get();
auto& objectTransform = objectTransformComponent.getTransform();
objectTransform.setOrientation(orientation);
objectTransform.setPosition(origin);
objectTransformComponent.updateBounds(origin, orientation);
}
}
|
<reponame>MichaelS11/go-scheduler<gh_stars>1-10
package scheduler_test
import (
"fmt"
"log"
"time"
"github.com/MichaelS11/go-scheduler"
)
func Example_basic() {
// This is for testing, to know when myFunction has been called by the scheduler job.
chanStart := make(chan struct{}, 1)
// Create a function for the job to call
myFunction := func(dataInterface interface{}) {
chanStart <- struct{}{}
data := dataInterface.(string)
fmt.Println(data)
}
// Create new scheduler
s := scheduler.NewScheduler()
// cron is in the form: Seconds, Minutes, Hours, Day of month, Month, Day of week, Year
// A cron of * * * * * * * will run every second.
// The scheduler uses UTC time
// Parsing cron using:
// https://github.com/gorhill/cronexpr
// Make a new job that runs myFunction passing it "myData"
err := s.Make("jobName", "* * * * * * *", myFunction, "myData")
if err != nil {
log.Fatalln("Make error:", err)
}
// The follow is normally not needed unless you want the job to run right away.
// Updating next run time so don't have to wait till the next on the second for the job to run.
err = s.UpdateNextRun("jobName", time.Now())
if err != nil {
log.Fatalln("UpdateNextRun error:", err)
}
// Starts the job schedule. Job will run at it's next run time.
s.Start("jobName")
// For testing, wait until the job has run before stopping all the jobs
<-chanStart
// Stop all the jobs and waits for then to all stop. In the below case it waits for at least a second.
// Note this does not kill any running jobs, only stops them from running again.
s.StopAllWait(time.Second)
// Output:
// myData
}
|
package server
import (
"math"
"os"
"strconv"
"strings"
"time"
"github.com/tidwall/btree"
"github.com/tidwall/tile38/internal/collection"
"github.com/tidwall/tile38/internal/field"
"github.com/tidwall/tile38/internal/log"
"github.com/tidwall/tile38/internal/object"
)
const maxkeys = 8
const maxids = 32
const maxchunk = 4 * 1024 * 1024
func (s *Server) aofshrink() {
start := time.Now()
s.mu.Lock()
if s.aof == nil || s.shrinking {
s.mu.Unlock()
return
}
s.shrinking = true
s.shrinklog = nil
s.mu.Unlock()
defer func() {
s.mu.Lock()
s.shrinking = false
s.shrinklog = nil
s.mu.Unlock()
log.Infof("aof shrink ended %v", time.Since(start))
}()
err := func() error {
f, err := os.Create(s.opts.AppendFileName + "-shrink")
if err != nil {
return err
}
defer f.Close()
var aofbuf []byte
var values []string
var keys []string
var nextkey string
var keysdone bool
for {
if len(keys) == 0 {
// load more keys
if keysdone {
break
}
keysdone = true
func() {
s.mu.Lock()
defer s.mu.Unlock()
s.cols.Ascend(nextkey,
func(key string, col *collection.Collection) bool {
if len(keys) == maxkeys {
keysdone = false
nextkey = key
return false
}
keys = append(keys, key)
return true
},
)
}()
continue
}
var idsdone bool
var nextid string
for {
if idsdone {
keys = keys[1:]
break
}
// load more objects
func() {
idsdone = true
s.mu.Lock()
defer s.mu.Unlock()
col, ok := s.cols.Get(keys[0])
if !ok {
return
}
var now = time.Now().UnixNano() // used for expiration
var count = 0 // the object count
col.ScanGreaterOrEqual(nextid, false, nil, nil,
func(o *object.Object) bool {
if count == maxids {
// we reached the max number of ids for one batch
nextid = o.ID()
idsdone = false
return false
}
// here we fill the values array with a new command
values = values[:0]
values = append(values, "set")
values = append(values, keys[0])
values = append(values, o.ID())
o.Fields().Scan(func(f field.Field) bool {
if !f.Value().IsZero() {
values = append(values, "field")
values = append(values, f.Name())
values = append(values, f.Value().JSON())
}
return true
})
if o.Expires() != 0 {
ttl := math.Floor(float64(o.Expires()-now)/float64(time.Second)*10) / 10
if ttl < 0.1 {
// always leave a little bit of ttl.
ttl = 0.1
}
values = append(values, "ex")
values = append(values, strconv.FormatFloat(ttl, 'f', -1, 64))
}
if objIsSpatial(o.Geo()) {
values = append(values, "object")
values = append(values, string(o.Geo().AppendJSON(nil)))
} else {
values = append(values, "string")
values = append(values, o.Geo().String())
}
// append the values to the aof buffer
aofbuf = append(aofbuf, '*')
aofbuf = append(aofbuf, strconv.FormatInt(int64(len(values)), 10)...)
aofbuf = append(aofbuf, '\r', '\n')
for _, value := range values {
aofbuf = append(aofbuf, '$')
aofbuf = append(aofbuf, strconv.FormatInt(int64(len(value)), 10)...)
aofbuf = append(aofbuf, '\r', '\n')
aofbuf = append(aofbuf, value...)
aofbuf = append(aofbuf, '\r', '\n')
}
// increment the object count
count++
return true
},
)
}()
if len(aofbuf) > maxchunk {
if _, err := f.Write(aofbuf); err != nil {
return err
}
aofbuf = aofbuf[:0]
}
}
}
// load hooks
// first load the names of the hooks
var hnames []string
func() {
s.mu.Lock()
defer s.mu.Unlock()
hnames = make([]string, 0, s.hooks.Len())
s.hooks.Walk(func(v []interface{}) {
for _, v := range v {
hnames = append(hnames, v.(*Hook).Name)
}
})
}()
var hookHint btree.PathHint
for _, name := range hnames {
func() {
s.mu.Lock()
defer s.mu.Unlock()
hook, _ := s.hooks.GetHint(&Hook{Name: name}, &hookHint).(*Hook)
if hook == nil {
return
}
hook.cond.L.Lock()
defer hook.cond.L.Unlock()
var values []string
if hook.channel {
values = append(values, "setchan", name)
} else {
values = append(values, "sethook", name,
strings.Join(hook.Endpoints, ","))
}
for _, meta := range hook.Metas {
values = append(values, "meta", meta.Name, meta.Value)
}
if !hook.expires.IsZero() {
ex := float64(time.Until(hook.expires)) / float64(time.Second)
values = append(values, "ex",
strconv.FormatFloat(ex, 'f', 1, 64))
}
values = append(values, hook.Message.Args...)
// append the values to the aof buffer
aofbuf = append(aofbuf, '*')
aofbuf = append(aofbuf, strconv.FormatInt(int64(len(values)), 10)...)
aofbuf = append(aofbuf, '\r', '\n')
for _, value := range values {
aofbuf = append(aofbuf, '$')
aofbuf = append(aofbuf, strconv.FormatInt(int64(len(value)), 10)...)
aofbuf = append(aofbuf, '\r', '\n')
aofbuf = append(aofbuf, value...)
aofbuf = append(aofbuf, '\r', '\n')
}
}()
}
if len(aofbuf) > 0 {
if _, err := f.Write(aofbuf); err != nil {
return err
}
aofbuf = aofbuf[:0]
}
if err := f.Sync(); err != nil {
return err
}
// finally grab any new data that may have been written since
// the aofshrink has started and swap out the files.
return func() error {
s.mu.Lock()
defer s.mu.Unlock()
// kill all followers connections and close their files. This
// ensures that there is only one opened AOF at a time which is
// what Windows requires in order to perform the Rename function
// below.
for conn, f := range s.aofconnM {
conn.Close()
f.Close()
}
// send a broadcast to all sleeping followers
s.fcond.Broadcast()
// flush the aof buffer
s.flushAOF(false)
aofbuf = aofbuf[:0]
for _, values := range s.shrinklog {
// append the values to the aof buffer
aofbuf = append(aofbuf, '*')
aofbuf = append(aofbuf, strconv.FormatInt(int64(len(values)), 10)...)
aofbuf = append(aofbuf, '\r', '\n')
for _, value := range values {
aofbuf = append(aofbuf, '$')
aofbuf = append(aofbuf, strconv.FormatInt(int64(len(value)), 10)...)
aofbuf = append(aofbuf, '\r', '\n')
aofbuf = append(aofbuf, value...)
aofbuf = append(aofbuf, '\r', '\n')
}
}
if _, err := f.Write(aofbuf); err != nil {
return err
}
if err := f.Sync(); err != nil {
return err
}
// we now have a shrunken aof file that is fully in-sync with
// the current dataset. let's swap out the on disk files and
// point to the new file.
// anything below this point is unrecoverable. just log and exit process
// back up the live aof, just in case of fatal error
if err := s.aof.Close(); err != nil {
log.Fatalf("shrink live aof close fatal operation: %v", err)
}
if err := f.Close(); err != nil {
log.Fatalf("shrink new aof close fatal operation: %v", err)
}
if err := os.Rename(s.opts.AppendFileName, s.opts.AppendFileName+"-bak"); err != nil {
log.Fatalf("shrink backup fatal operation: %v", err)
}
if err := os.Rename(s.opts.AppendFileName+"-shrink", s.opts.AppendFileName); err != nil {
log.Fatalf("shrink rename fatal operation: %v", err)
}
s.aof, err = os.OpenFile(s.opts.AppendFileName, os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
log.Fatalf("shrink openfile fatal operation: %v", err)
}
var n int64
n, err = s.aof.Seek(0, 2)
if err != nil {
log.Fatalf("shrink seek end fatal operation: %v", err)
}
s.aofsz = int(n)
os.Remove(s.opts.AppendFileName + "-bak") // ignore error
return nil
}()
}()
if err != nil {
log.Errorf("aof shrink failed: %v", err)
return
}
}
|
def check_for_overlap(pokemino1, pokemino2):
distance_between_centres_of_mass = np.sqrt(np.sum(np.square(pokemino1.positioning - pokemino2.positioning)))
sum_of_max_radii = (
np.sqrt(np.sum(np.square(pokemino1.max_radius))) + np.sqrt(np.sum(np.square(pokemino2.max_radius))))
if sum_of_max_radii >= distance_between_centres_of_mass + 1:
return True
|
def stream(self):
if self.package is not None:
return pkg_resources.resource_stream(self.package.__name__, self.resource)
elif isinstance(self.resource, str):
if os.path.isabs(self.resource) and os.path.exists(self.resource):
return open(self.resource, "rb")
raise ValueError
|
// Tests that GetKey returns the dll path.
TEST(GetBlacklistLoadIncidentKey, KeyIsPath) {
safe_browsing::ClientIncidentReport_IncidentData incident;
incident.mutable_blacklist_load()->set_path("foo");
ASSERT_EQ(std::string("foo"),
safe_browsing::GetBlacklistLoadIncidentKey(incident));
}
|
import sys
from collections import deque
n,m=map(int,input().split())
arr=[[]*n for _ in range(n)]
for i in range(m):
a,b=map(int,input().split())
arr[a-1].append(b-1)
arr[b-1].append(a-1)
for i in range(n):
if len(arr[i])==0:
print('No')
sys.exit()
def bfs(d):
que=deque()
que.append(0)
ans=[0]*n
while que:
x=que.popleft()
if x==0:
for i in arr[x]:
ans[i]=1
que.append(i)
else:
for i in arr[x]:
if ans[i]==0 and i!=0:
ans[i]=x+1
que.append(i)
print('Yes')
for i in range(1,n):
print(ans[i])
bfs(arr)
|
Topsy, an Apple-owned service that searched and analysed data from Twitter, is no more. As noted by 9to5Mac, the company's website now redirects to an Apple support page about how to use the new proactive Search functionality (above) in iOS 9. Topsy posted a message to Twitter saying "We've searched our last tweet," and its profile bio now states "Every tweet ever published. Previously at your fingertips."
Apple bought Topsy a little over two years ago for a reported figure of over $225 million, making it one of Cupertino's pricier acquisitions. It's not clear what Apple has done with Topsy's software or staff, but the URL redirect suggests its analytical technology may have been folded into iOS 9's Search feature, which indexes devices and presents information alongside suggested data from the internet.
|
<filename>backend/src/plano/models/plano.model.ts<gh_stars>0
export class Plano {
nome: string;
consumoTotalPermitidoEmMinutos: string;
}
|
<reponame>paytomat/ScatterAndroid<gh_stars>1-10
package com.mariabeyrak.scatter.models.requests.transaction.response;
import java.util.Arrays;
public class TransactionResponse {
private String[] signatures;
private ReturnedFields returnedFields;
public TransactionResponse(String[] signatures, ReturnedFields returnedFields) {
this.signatures = signatures;
this.returnedFields = returnedFields;
}
@Override
public String toString() {
return "TransactionResponse{" +
"signatures=" + Arrays.toString(signatures) +
", returnedFields=" + returnedFields +
'}';
}
}
|
//automated action, button analysis, deviceadmin check
public void automatedAction() throws Exception {
String packname = getParams().getString("packname");
enableDeviceAdmin();
try {
UiObject anyBtn = new UiObject(new UiSelector().className("android.widget.Button"));
if(anyBtn.exists()) {
anyBtn.click();
}
Thread.sleep(5000);
} catch(Exception e) {
}
getUiDevice().pressHome();
}
|
<filename>release/src-rt-6.x.4708/router/iptables-1.4.x/extensions/libip6t_eui64.c
/* Shared library add-on to ip6tables to add EUI64 address checking support. */
#include <xtables.h>
static struct xtables_match eui64_mt6_reg = {
.name = "eui64",
.version = XTABLES_VERSION,
.family = NFPROTO_IPV6,
.size = XT_ALIGN(sizeof(int)),
.userspacesize = XT_ALIGN(sizeof(int)),
};
void _init(void)
{
xtables_register_match(&eui64_mt6_reg);
}
|
def _determine_stopping_criteria(args):
args.stopping_crit = None
if args.num_epochs > 0:
args.stopping_crit = "Epochs"
elif args.num_episodes > 0:
args.stopping_crit = "Episodes"
elif args.num_timesteps > 0:
args.stopping_crit = "Timesteps"
assert args.stopping_crit,\
"ERROR: No stopping criteria set, for training"
|
/**
* Extract info about a content part form a given part of an email.
*/
private MailPartData extractContent(Part part, String mimeType) throws Exception {
MailPartData result = new MailPartData();
result.setContentType(mimeType);
Charset charset = getCharsetFromHeader(part.getContentType());
BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), charset));
String line;
StringBuilder html = new StringBuilder();
while ((line = reader.readLine()) != null) {
if (mimeType.equals("text/plain")) {
html.append(escapeHtml4(line));
html.append("<br />");
} else {
html.append(line);
}
html.append("\n");
}
result.setHtml(html.toString());
return result;
}
|
// check that state and mode are kept
void tst_QLocalSocket::setSocketDescriptor()
{
LocalSocket socket;
qintptr minusOne = -1;
socket.setSocketDescriptor(minusOne, QLocalSocket::ConnectingState, QIODevice::Append);
QCOMPARE(socket.socketDescriptor(), minusOne);
QCOMPARE(socket.state(), QLocalSocket::ConnectingState);
QVERIFY((socket.openMode() & QIODevice::Append) != 0);
}
|
def execute_script_file_obj(self, file_object):
self.create_cur()
self.cursor.execute(file_object.read())
if commit or self.autocommit:
self.commit()
|
#include <algorithm>
#include <bitset>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>
// Problem :
// https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1662
typedef long long int llint;
typedef long double ldouble;
#define LOG std::cout
llint n, k, s;
std::vector<std::vector<llint>> memo;
llint __dprec__(const llint& cost, const llint& steps) {
if (cost == 0 and steps == 0)
return 1;
else if (steps == 0 || cost < 0)
return 0;
// LOG << "calculating costs for : " << cost << " " << steps << std::endl;
llint& mem = memo[cost][steps];
// LOG << "current memo value : " << mem << std::endl;
if (mem != -1)
return mem;
mem = 0;
for (llint i = 1; i <= s; i++) {
mem += __dprec__(cost - i, steps - 1);
}
// LOG << "returning mem value : " << mem << std::endl;
return mem;
}
void __calc__() {
std::string input;
while (std::getline(std::cin, input)) {
std::stringstream stream(input);
stream >> n;
stream >> k;
stream >> s;
// LOG << "values of n,k,s : " << n << " " << k << " " << s << std::endl;
llint answer = 0;
// __rec__(0, 0, answer);
memo.clear();
memo.resize(n + 1, std::vector<llint>(k + 1, -1));
answer = __dprec__(n, k);
std::cout << answer << std::endl;
}
return;
}
int main() {
std::ios_base::sync_with_stdio(false);
__calc__();
return 0;
}
|
#define COMMA_VERSION "0.7.4-VW1.3"
|
import { DIDTypes } from "@uns/crypto";
export const defaults = {};
export interface IProperyInfo {
default?: string;
defaultByType?: { [Didtype: string]: string };
}
export const systemProperties: Record<string, IProperyInfo> = {
"Badges/Security/SecondPassphrase": {},
"Badges/Security/Multisig": {
default: "false",
},
"Badges/Rightness/Verified": {
defaultByType: {
[DIDTypes.ORGANIZATION]: "false",
},
},
"Badges/Rightness/Everlasting": {
defaultByType: {
[DIDTypes.INDIVIDUAL]: "false",
[DIDTypes.ORGANIZATION]: "false",
[DIDTypes.NETWORK]: "true",
},
},
"Badges/XPLevel": {
default: "1",
},
"Badges/Trust/TrustIn": {
default: "0",
},
"Badges/Trust/TrustOut": {
default: "0",
},
"Badges/NP/Delegate": {
default: "false",
},
"Badges/NP/StorageProvider": {
default: "false",
},
"Badges/NP/UNIKIssuer": {
default: "false",
},
"Authentications/CosmicNonce": {
default: "1",
},
"LifeCycle/Status": {
default: "2",
},
};
|
def describe(self):
description = super().describe()
description = description.replace("model", "view model")
return description
|
def _thread_progress(self, prm_id, name, progress):
self._window.set_progress(prm_id=prm_id, name=name, perc=progress)
|
/**
* cr_doc_handler_get_ctxt:
*@a_this: the current instance of #CRDocHandler.
*@a_ctxt: out parameter. The new parsing context.
*
*Gets the private parsing context associated to the document handler
*The private parsing context is used by libcroco only.
*
*Returns CR_OK upon successfull completion, an error code otherwise.
*/
enum CRStatus
cr_doc_handler_get_ctxt (CRDocHandler * a_this, gpointer * a_ctxt)
{
g_return_val_if_fail (a_this && a_this->priv, CR_BAD_PARAM_ERROR);
*a_ctxt = a_this->priv->context;
return CR_OK;
}
|
<filename>tests/Trivial.hs
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Trivial (tests) where
import Algebra.Lattice
import Datafix
import Datafix.Worklist (Density (..), IterationBound (..),
solveProblem)
import Datafix.Worklist.Graph (GraphRef)
import Numeric.Natural
import Test.Tasty
import Test.Tasty.HUnit
import Fac
import Fib
import Mutual
instance JoinSemiLattice Natural where
(\/) = max
instance BoundedJoinSemiLattice Natural where
bottom = 0
fixFib, fixFac, fixMutualRecursive
:: GraphRef graph => (Node -> Density graph) -> Int -> Natural
fixFib density n = solveProblem fibProblem (density (Node n)) NeverAbort (Node n)
fixFac density n = solveProblem facProblem (density (Node n)) NeverAbort (Node n)
fixMutualRecursive density n = solveProblem mutualRecursiveProblem (density (Node 1)) NeverAbort (Node n)
tests :: [TestTree]
tests =
[ testGroup "Memoization"
[ testGroup "Sparse"
[ testCase "fibonacci 10" (fixFib (const Sparse) 10 @?= fib 10)
, testCase "factorial 100" (fixFac (const Sparse) 100 @?= fac 100)
]
, testGroup "Dense"
[ testCase "fibonacci 10" (fixFib Dense 10 @?= fib 10)
, testCase "factorial 100" (fixFac Dense 100 @?= fac 100)
]
]
, testGroup "mutual recursion"
[ testGroup "Sparse"
[ testCase "first node is stable" (fixMutualRecursive (const Sparse) 0 @?= 11)
, testCase "second node is stable" (fixMutualRecursive (const Sparse) 1 @?= 10)
]
, testGroup "Dense"
[ testCase "first node is stable" (fixMutualRecursive Dense 0 @?= 11)
, testCase "second node is stable" (fixMutualRecursive Dense 1 @?= 10)
]
, testGroup "Abortion"
[ testCase "aborts after 5 updates with value 42" (solveProblem mutualRecursiveProblem Sparse (AbortAfter 5 (const 42)) (Node 1) @?= 42)
]
]
]
|
From Bulbapedia, tha hood-driven Pokémon encyclopedia.
Pikachu (Japanese: �"カチュウ Pikachu) be a Electric-type Pokémon introduced up in Generation I.
It evolves from Pichu when leveled up wit high friendship n' evolves tha fuck into Raichu when exposed ta a Thunder Stone. But fuck dat shiznit yo, tha word on tha street is dat tha starta Pikachu up in Pokémon Yellow will refuse ta evolve tha fuck into Raichu unless it is traded n' evolved on another save file.
In Alola, Pikachu will evolve tha fuck into Alolan Raichu when exposed ta a Thunder Stone.
Pikachu is popularly known as tha mascot of tha Pokémon franchise n' a major representatizzle of Nintendoz collectizzle mascots.
It be also tha game mascot n' starta Pokémon of Pokémon Yellow n' Pokémon: Letz Go, Pikachu!. Well shiiiit, it has busted a shitload of appearances on tha boxez of spin-off titles.
Pikachu be also tha starta Pokémon up in Pokémon Rumble Blast n' Pokémon Rumble World.
Biology
Pikachu be a gangbangin' finger-lickin' dirty-ass short, chubby rodent Pokémon. I aint talkin' bout chicken n' gravy biatch. Well shiiiit, it is covered up in yellow fur wit two horizontal brown stripes on its back. Well shiiiit, it has a lil' small-ass grill, long, pointed ears wit black tips, brown eyes, n' tha two red circlez on its cheeks contain pouches fo' electricitizzle storage. Well shiiiit, it has short forearms wit five fingers on each paw, n' its feet each have three toes fo' realz. At tha base of its lightnin bolt-shaped tail be a patch of brown fur fo' realz. A biatch gonna git a V-shaped notch all up in tha end of its tail, which be lookin like tha top of a ass. Well shiiiit, it is classified as a quadruped yo, but it has been known ta stand n' strutt on its hind legs.
Da anime has shown dat wild Pikachu live up in crews up in forested areas. Pikachu rap amongst theyselves rockin squeaks n' tail-bobbin as thugged-out gestures. Electricitizzle can be used ta receive n' bust lyrics wit each other, as well as other Electric Pokémon species. Put ya muthafuckin choppers up if ya feel dis! Well shiiiit, it raises its tail ta check its surroundings, n' is occasionally struck by lightnin up in dis position. I aint talkin' bout chicken n' gravy biatch. When crews grow, they can inadvertently cause lightnin storms. Boy it's gettin hot, yes indeed it is. Pikachu is found foragin fo' Berries it roasts wit electricitizzle ta make dem tender enough ta smoke fo' realz. A shizzle sign dat Pikachu inhabits a location is patchez of burnt grass. It has been observed smokin n' sometimes beatin tha livin shiznit outta telephone poles, wires, n' other electronic shit.
Pikachu charges itself while chillin overnight, though stress n' a lack of chill can affect all dis bullshit. Well shiiiit, it be able ta release electric dischargez of varyin intensity. Pikachu has been known ta build up juice up in its glands, n' will need ta discharge ta stay tha fuck away from complications. Well shiiiit, it be also able ta release juice all up in its tail, which acts as a groundin rod, as well as rechargin fellow Pikachu wit electric shocks. In tha anime, Alolan Pikachu is known ta greet each other by sniffin one another n' rubbin they tails together n' shit. Pikachu can also electrify itself ta use its signature move Volt Tackle.
Pikachu has three alternate forms: one, tha Cosplay Pikachu, rocked up in Pokémon Omega Ruby n' Alpha Sapphire. Well shiiiit, it be always female, has a funky-ass black heart-shaped spot all up in tha end of its tail, n' can be dressed up in any of five tracksuits correspondin ta tha five Contest conditions. Da second form is Pikachu up in a cold-ass lil cap, which debuted as a event-exclusive Pokémon up in Generation VII. Well shiiiit, it be always thug n' has seven variants, each bustin one of Ashz hats from tha anime. In addizzle ta these two forms, nuff other Pikachu variants have rocked up in various media. Da last, Partner Pikachu, is tha Pokémon tha playa starts with up in Pokémon: Letz Go, Pikachu!. This Pikachu can be either gender, has higher base stats, n' has access ta moves dat aiiight Pikachu do not.
Pikachu is tha only known Pokémon capable of rockin tha Z-Move Catastropika, while Pikachu up in a cold-ass lil cap has its own exclusive Z-Move, 10,000,000 Volt Thunderbolt. Partner Pikachu is tha only Pokémon capable of rockin Zippy Zap, Floaty Fall, Splishy Splash, n' tha Partner Power, Pika Papow.
In tha anime
In tha main series
Pikachu up in tha anime
Major appearances
Ash Ketchum has a Pikachu dat he obtained from Pimp Oak up in Pokémon - I Chizzle You!, tha straight-up original gangsta episode of tha Pokémon anime yo. Dude is tha signature Pokémon of tha anime series n' has rocked up in every last muthafuckin non-special episode n' every last muthafuckin Pokémon porno since fo' realz. Ashz Pikachu remains outside of his Poké Ball.
In Mewtwo Strikes Back, Mewtwo cloned Ashz Pikachu fo'sho. This Pikachu can be distinguished from Ashz cuz of tha spikes up in tha black marks found on tha tipz of its ears. Well shiiiit, it be also comparatively mo' aggressive than Ashz Pikachu n' slurs its speech, defects possibly caused by Ash tamperin wit Mewtwoz clonin machine durin tha clonin process.
Another Pikachu nicknamed Puka was owned by a playa named Victor on Seafoam Island up in Da Pi-Kahuna. This blue-eyed Pikachu saved Ash from drownin by havin tha mobilitizzle ta sense tidal waves approaching.
Ritchie also has a Pikachu nicknamed Sparky, whoz ass debuted up in A Hommie In Deed. Right back up in yo muthafuckin ass. Sparky, unlike most Pikachu, has a tuft of fur on tha top of its head, and, unlike Ashz Pikachu, has no problem wit livin inside a Poké Ball.
Ash gets turned tha fuck into a Pikachu up in Hocus Pokémon by a Pokémon magician named Lily yo. Dude reverts ta his human form all up in tha beginnin of the next episode.
All of tha Cosplay Pikachu rocked up in Lights muthafucka! Camera! Pika!, under tha ballershizzle of Frank. They reappeared up in Hoopa n' tha Clash of Ages, where they was all summoned by Hoopa as part of a prank on Ash n' his Pikachu.
Da Ash Ketchum of tha alternate continuitizzle introduced up in I Chizzle You! has a Pikachu of his own. I aint talkin' bout chicken n' gravy biatch. Like tha Pikachu of tha main series, dis Pikachu was his wild lil' first Pokémon n' his crazy-ass main partner, remainin outside of his Poké Ball.
Other
A biatch Pikachu up in tha anime
James used a Pikachu up in tha Pokémon League Entrizzle Exam up in Da Illest Test yo, but dat shiznit was defeated by tha instructorz Graveler. James, afta interferin wit a funky-ass battle Ash was havin wit tha instructor, lata tried ta loot dis Pikachu, only fo' dat Pikachu ta zap Jizzy instead, as instructed by its instructor.
A Pikachu had a part up in Pokémon Mystery Dungeon: Crew Go-Gettas outta tha Gate biaatch! yo. Dude was kidnapped by a Skarmory n' Team Go-Getters set up ta rescue his ass as they first mission. I aint talkin' bout chicken n' gravy biatch. Pikachu provided dem wit some shit up in tha battle.
Pikachuz biatch form debuted up in SS027, under tha ballershizzle of Ayumi. Right back up in yo muthafuckin ass. Biatch was trained on how tha fuck ta properly use Thunderbolt all up in tha help of Cilan n' Stunfisk.
A Mirror World Pikachu rocked up in Da Cave of Mirrors!, under tha ballershizzle of Mirror Ash. Unlike his bangin regular ghetto counterpart, Mirror Pikachu be a mischievous roughneck.
Multiple Pikachu rocked up in Lights muthafucka! Camera! Pika!, under tha ballershizzle of Frank. They would all participate up in his wild lil' filmmakin endeavors.
Multiple Pikachu rocked up in Hoopa n' tha Clash of Ages. They was all summoned by Hoopa as part of a prank on Ash n' his Pikachu, though tha prank failed. Y'all KNOW dat shit, muthafucka! They was then moonwalked back ta they original gangsta locations wit tha help of Ashz Pikachu, whoz ass coordinated dem tha fuck into Hoopaz portals.
A Pikachu nicknamed Spike rocked up in Battlin at Full Volume biaatch!, under tha ballershizzle of Jimmy. Right back up in yo muthafuckin ass. Spike was used up in a funky-ass battle against Ashz Pikachu yo, but as Ash was ill, Serena took his thugged-out lil' place. But fuck dat shiznit yo, tha word on tha street is dat tha match was interrupted by Crew Rocket, whoz ass captured Spike yo, but Spike was promptly saved.
A Trainerz Pikachu rocked up in Securin tha Future biaatch!.
Multiple Pikachu rocked up in A Plethora of Pikachu!, all under tha ballershizzle of Pikala. One of dem was nicknamed Curly, while another dat is Shiny was nicknamed tha Boss.
Minor appearances
Shiny Pikachu up in tha anime
A set of costumed Cosplay Pikachu up in tha anime
Numerous other Pikachu rocked up in Pokémon Emergency hommie!, under tha ballershizzle of Nurse Joy. They helped Ashz Pikachu defeat Team Rocketz Jessie, James, n' Meowth ta bust dem blastin off fo' tha last time. They reappeared up in a gangbangin' flashback up in Pikachuz Peace out.
Wild Pikachu was prominent up in Pikachuz Peace out, where Ash considered releasing his own Pikachu so his schmoooove ass could be wit his own kind.
Multiple Pikachu rocked up in Battle Aboard tha St fo' realz. Anne.
A Pikachu rocked up in a gangbangin' flashback up in Pokémon Double Trouble, under tha ballershizzle of Luanaz son, Travis. Luana mistook Ash fo' Travis when her big-ass booty saw Pikachu on Ashz shoulder yo, but eventually realized her fuck up n' explained why she made dat shit.
A Pikachu rocked up in Brockz demonstration up in A Bite ta Remember, where it evolved tha fuck into a Raichu.
In Lights, Camerupt, Action!, a Pikachu rocked up in two of Elijahz pornos. Redz Pikachu was featured up in a gangbangin' film dat Ash n' Gary was watchin when they was younger n' shit. In a gangbangin' finger-lickin' different porno dat Ash n' his playas was watchin all up in tha time tha episode was takin place, another Pikachu helped Plusle n' Minun on they mission ta rescue Supa-Hoe Kirlia from tha evil Exploud.
A Pikachu rocked up in Lucario n' tha Mystery of Mew as a transformation of Mew.
A Pikachu nicknamed Sugar rocked up in Cookin up a Sweet Rap hommie!, under tha ballershizzle of Abigail, one of tha ballaz of a restaurant. When it went missin prior ta tha eventz of tha episode, Ashz Pikachu had ta fill up in fo' it so dat its balla would have tha confidence ta win a cold-ass lil cookin competition. I aint talkin' bout chicken n' gravy biatch fo' realz. At tha end of tha episode, Sugar returned yo, but it had evolved tha fuck into a Raichu.
A Pikachu rocked up in a gangbangin' flashback up in Da Keystone Pops!, under tha ballershizzle of a Aura Guardian.
A Pikachu rocked up in a gangbangin' flashback up in Flint Sparks tha Fire biaatch!, under tha ballershizzle of Volkner. In tha present day, it aint nuthin but a Raichu.
A Pikachu rocked up in Clemontz demonstration up in To Catch a Pokémon Smuggla son!, where it evolved tha fuck into a Raichu rockin a Thunder Stone.
A Pikachu rocked up in Diancie n' tha Cocoon of Destruction, under tha ballershizzle of Uschi.
A Pikachu rocked up in a gangbangin' fantasy up in Now Yo ass See Them, Now Yo ass Don't playa!.
A Pikachu rocked up in a gangbangin' fantasy up in Showerin tha Ghetto wit Ludd biaatch!.
A Trainerz Pikachu rocked up in Securin tha Future biaatch!, where it joined tha rest of Alola up in showerin Necrozma wit light so it could return ta its normal form.
Pokédex entries
Episode Pokémon Source Entry DP002 Pikachu Dawnz Pokédex Pikachu, tha Mouse Pokémon. I aint talkin' bout chicken n' gravy biatch. Well shiiiit, it can generate electric attacks from tha electric pouches located up in both of its cheeks. This concludes tha entries from tha Diamond & Pearl series.
Episode Pokémon Source Entry BW001 Pikachu Tripz Pokédex Pikachu, tha Mouse Pokémon, n' tha evolved form of Pichu. Pikachuz tail is sometimes struck by lightnin as it raises it ta check its surroundings. BW093 Pikachu Cameronz Pokédex Pikachu, tha Mouse Pokémon, n' tha evolved form of Pichu fo'sho. Pikachu can help other Pikachu whoz ass is feelin weak by pluggin its electric current. This concludes tha entries from tha Best Wishes series.
Episode Pokémon Source Entry SM003 Pikachu Rotom Pokédex Pikachu, tha Mouse Pokémon. I aint talkin' bout chicken n' gravy biatch fo' realz. An Electric type. Well shiiiit, it raises its tail ta sense its surroundings. If you pull on its tail, it will bite. This concludes tha entries from tha Sun & Moon series.
In Pokémon Origins
Red caught a Pikachu up in File 4: Charizard.
In Pokémon Generations
Red caught a Pikachu up in Viridian Forest up in Da Adventure yo. Dude then proceeded ta travel though multiple regions wit it, facin nuff phat opponents along tha way.
In tha manga
In tha Ash & Pikachu manga
Main article: Ashz Pikachu
Ashz Pikachu be a starrin characta up in Ash & Pikachu, a manga adaptation of tha Pokémon anime which is based on Ashz adventures up in Johto, Hoenn, n' Battle Frontier.
In Da Electric Tale of Pikachu manga
Ashz Pikachu be a main characta up in tha manga series Da Electric Tale of Pikachu, a adaptation of tha Pokémon anime.
In tha manga, Ash discovered Pikachu under tha floorboardz at his home, where da thug was chewin on wires ta smoke tha electricity.
Sparky, Ritchiez Pikachu, appears up in Da Electric Tale of Pikachu as well, however, it is nicknamed "Chuchino" instead.
Pokédex entries
Manga Chapter Entry Da Electric Tale of Pikachu ET01 An electric mouse Pokémon.
Habitat: Forests n' woodlands
Diet: Mainly fruit
Distinguishin features: Has a electric generator on each cheek.
Beware of electrocution!
In tha How tha fuck I Became a Pokémon Card manga
A rap called Akari n' Pikachuz Birthday is featured up in tha final volume of How tha fuck I Became a Pokémon Card.
In tha Magical Pokémon Journey n' Pokémon Chamo-Chamo ☆ Pretty ♪ manga
Pikachu be a main characta up in tha Magical Pokémon Journey manga series yo. Dude is tha straight-up original gangsta Pokémon befriended by Hazel, appearin fo' tha last time up in How tha fuck Do Yo ass Do, Pikachu?. Pikachu is one of tha few Pokémon up in Magical Pokémon Journey dat cannot drop a rhyme human language, although tha others seem ta KNOW his muthafuckin ass yo. Dude is busted lyrics bout as rather scatterdomeed at times. Pikachu returns as a main characta up in Pokémon Chamo-Chamo ☆ Pretty ♪, tha sequel ta tha Magical Pokémon Journey series.
Ashz Pikachu also cook up a cold-ass lil cameo appearizzle up in bonus chaptas all up in tha end of every last muthafuckin volume of tha Magical Pokémon Journey manga.
In tha Pokémon Adventures manga
A crew of Cosplay Pikachu up in Pokémon Adventures
Main article: Pika Main article: Chuchu Main article: Cosplay Pikachu
Pikachu debuted up in its own round up in tha Red, Chronic & Blue chapter, Wanted: Pikachu! yo. Here, a Pikachu was jackin all tha crops up in a town. I aint talkin' bout chicken n' gravy biatch. Da townsfolk kept chasin his ass around yo, but end up gettin shocked by his muthafuckin ass. Red arrives n' captures him, endin tha chaos fo' realz. Although mad disobedient at first, even prone ta regularly electrocutin his baller, tha two eventually gots over dis enmity, n' dis Pikachu, nicknamed "Pika", became one of his crazy-ass most loyal n' trusted fighters, bein used up in almost every last muthafuckin major battle Red has had. Y'all KNOW dat shit, muthafucka! Dude also served on Yellowz crew while Red was held captizzle by tha Elite Four durin tha Yellow chapter before bein moonwalked back ta him, durin which Yellow discovered dat his schmoooove ass can Surf.
A Pikachu rocked up as a silhouette when Green talks bout Mew up in Da Jynx Jinx.
In Just a Spearow Carrier, a Pikachu rocked up wit its Trainer at Indigo Plateau fo'sho. Well shiiiit, it noticeably has a gangbangin' flower by its ear.
A Pikachu is peeped up in Da Kindest Tentacruel, where dat shiznit was one of tha Pokémon dat Yellow was fantasizin bout dat was able ta evolve via stone.
A Pikachu rocked up in Can Yo ass Diglett? as a silhouette when Agatha n' Lorelei explains ta Red bout how tha fuck Pokémon n' playas can't coexist wit each other.
A Pikachu rocked up in a gangbangin' fantasy of Pimp Elmz explanation of Pokémon eggs up in Teddiursaz Picnic.
A Pikachu rocked up in Ursarin Major, where it rocked up in a gangbangin' fantasy of Silver when he explains bout tha vital pointz of Pokémon.
In Tyranitar War, Yellow is peeped ta git a freshly smoked up addizzle ta her crew: a Pikachu of her own nicknamed "Chuchu", which dat freaky freaky biatch had found fucked up in Viridian Forest n' nursed back ta health. When Pika is left behind by Red on his cold-ass trip ta Mt. Right back up in yo muthafuckin ass. Silver, Pika joined Yellow n' Chuchu on they adventure ta Johto.
Pika n' Chuchu share a gangbangin relationshizzle, one dat is so phat dat even Jasmine noticed, promptin her ta hand Yellow a slip wit tha Pokémon Daycarez address on dat shit. Lata on, afta Yellow n' Wilton was brought ta tha Dizzle Care afta bein shipwrecked, Yellow findz dat Pika n' Chuchu now have a Egg shortly afta they was "put together." Da Egg eventually hatches tha fuck into Goldz Pibu.
Wild Pikachu rocked up in Sufferin Psyduck.
Multiple Pikachu was among tha Electric-type Pokémon dat charged tha Prizzle Tower durin a funky-ass blackout up in Pangoro Poses a Problem.
Five Pikachu rocked up in Omega Alpha Adventure 3, where they each wear tha five costumes available fo' tha Cosplay Pikachu: Pikachu Rock Star, Pikachu Belle, Pikachu Pop Star, Pikachu Ph. D, n' Pikachu Libre. Lisia reveals ta Chaz dat Ruby pimped tha concept of Pokémon bustin costumes fo' Contests, n' you can put dat on yo' toast. Noticeably, there be nuff muthafuckin males, wit tha exception of Pikachu Pop Star, which has tha black markin on tha tip of her tail. They reappeared up in a gangbangin' flashback up in Omega Alpha Adventure 7.
A Trainerz Pikachu rocked up in Da Decision n' tha Tournament of Six.
Pokédex entries
Manga Chapter Entry Pokémon Adventures PS004 When nuff muthafuckin of these Pokémon gather, they electricitizzle could build up n' cause lightnin storms. Boy it's gettin hot, yes indeed it is. Forest dwellers, they is few up in number n' exceptionally rare. Da pouches up in they cheeks discharge electricitizzle at they opponents, n' you can put dat on yo' toast. Da Pikachu is believed ta be highly intelligent.
In tha Pokémon Battle Frontier manga
A Pikachu cook up a cold-ass lil cameo up in Battle Frontier durin one of tha battlez fo' realz. Also, a photo mixtape owned by Anabel has a Pikachu on tha cover.
In tha Pokémon Gotta Catch 'Em All manga
Main article: Shuz Pikachu
In tha Pokémon Gotta Catch 'Em All manga, Shuz first Pokémon was a Pikachu dat he found abandoned up in tha forest.
In tha Pokémon Gold n' Silver: Da Golden Thugs manga
Main article: Goldz Pikachu
In Pokémon Gold & Silver: Da Golden Boys, Eusine was up in possession of a Pikachu, which ended up bein Gold's.
In tha Pocket Monstas HeartGold & SoulSilver Go! Go! Pokéathlon manga
A Pikachu rocked up in Pocket Monstas HeartGold & SoulSilver Go! Go! Pokéathlon.
In tha Pocket Monstas HGSS Jōz Big Adventure manga
Redz Pikachu rocked up all up in tha end of Pocket Monstas HGSS Jōz Big Adventure.
In tha Pokémon Pocket Monstas manga
Pikachu is one of tha main charactas up in tha Pokémon Pocket Monsters manga series n' its sequels. Dat shiznit was tha second Pokémon dat Red captured on his own yo, but tha straight-up original gangsta he kept.
Pikachu is one of tha few Pokémon up in tha manga dat cannot drop a rhyme human language yo. Dude is tha cousin of Clefairy n' is considered tha smarta of tha two.
Pikachu evolved tha fuck into Raichu up in Clefairy finally evolves?! yo, but dat schmoooove muthafucka has since devolved back ta tha Pikachu stage.
Yellow has a Pikachu of his own.
In Pokémon Newspaper Strip
Ashz Pikachu was tha main characta up in tha short-lived Pokémon Newspaper Strip.
In tha Pokémon Zensho manga
Satoshi has a Pikachu as one of tha thugz of his cold-ass crew up in Pokémon Zensho. Well shiiiit, it lata evolves tha fuck into a Raichu.
In tha TCG
Pikachu up in tha TCG
Pikachu TCG Coin
Pikachu somehow manages ta find its way tha fuck into nuff of tha expansions, causin there ta be 153 known non-reprint Pokémon cardz featurin Pikachu fo'sho. There is also various Trainer cardz wit Pikachu up in tha cardz artwork too, includin tha straight-up sought-afta tournament promos like fuckin No.1 Trainer.
Da first Pikachu dat rocked up in tha TCG was Pikachu up in tha Base Set (which was reprinted up in Base Set 2 n' up in POP Series 2 wit different artwork). Dat shiznit was followed up in the next set by another Pikachu (which was also reprinted up in tha Legendary Collection). Da third Pikachu card busted out was tha first-ever Gangsta promo card, Pikachu. Da original gangsta Base Set Pikachu was also busted out as a special promotionizzle card at E3.
In tha early minutez of tha TCG, nuff muthafuckin notable errors was made regardin tha Pikachu cards. Da Base Set Pikachu was busted out wit altered artwork at first, depictin it wit red cheeks, instead of tha original gangsta yellow. While dis matched Ken Sugimoriz artwork, tha yellow color on its cheeks was intentionizzle by tha artist, whoz ass depicted Pikachu rockin ThunderShock. This error rocked up in both tha E3 promotionizzle version n' tha aiiight Base Set release fo' realz. A second error was made up in tha thang of Jungle set boosta packs, which, instead of tha Jungle setz Pikachu, sometimes contained first edizzle versionz of tha Pikachu dat was busted out as a promo card.
Pikachu has also been featured on a fuckin shitload of TCG coins, wit one bein included wit tha Gangsta n' European languages-only Base Set 2. This coin was also featured up in tha Pokémon Play It playa! PC game fo' realz. A Pikachu coin be also featured up in tha Game Boy game Pokémon Tradin Card Game, n' is one of tha coins dat can be obtained up in Pokémon Card GB2: Here Comes Crew GR!, where it is given by Club Masta Isaac ta ballaz of tha Lightnin Joint.
In tha TFG
Two Pikachu figures done been busted out.
Other appearances
Pikachu Libre up in Pokkén Tournament
Pikachu be a playable characta fo' tha arcade fightin game. Its moveset includes electrical attacks it uses up in tha main games, like Thunderbolt, Electro Ball, n' Thunder. In Burst form, it can use tha Burst Attack Volt Shock Fist. Right back up in yo muthafuckin ass. Several of its attacks n' victory poses is directly taken from Heihachi n' Kazuya Mishimaz movesets from tha Tekken series.
Pikachu overwhelms opponents wit bangin electric shocks n' quick movements.[1]
Pikachu Libre was first announced alongside tha Wii U port of tha game. Right back up in yo muthafuckin ass. Biatch was lata busted out as a additionizzle fighta on tha original gangsta arcade version.
Pikachu Libre, a wrestlin idol, be a lil' small-ass maxed fighta overflowin wit fightin spirit, n' I aint talkin bout no muthafuckin Jack Daniels neither.
Detectizzle Pikachu stars a Pikachu dat is capable of bustin lyrics tha human language yo, but only tha playa characta Slim Tim Goodman is capable of hearin his muthafuckin ass. Much like Meowth from tha anime, he is incapable of rockin moves dat most Pikachu is capable of using. This Pikachu also straight-up loves ta drank coffee. Early on up in tha game, a regular Pikachu also briefly appears.
Game data
As tha playa
Pikachu appears as tha player character up in both PokéPark Wii: Pikachuz Adventure n' its sequel, PokéPark 2: Wondaz Beyond yo. Dude falls down a mysterious tunnel one dizzle wit his wild lil' playaz Charmander, Chikorita, n' Piplup n' endz up in tha PokéPark. There he goes on a quest ta save tha PokéPark from certain destruction. I aint talkin' bout chicken n' gravy biatch yo. Dude lata travels ta a freshly smoked up PokéPark which is bein threatened by tha ever-expandin Wish Park fo' realz. At tha freshly smoked up PokéPark he meets Snivy, Tepig, n' Oshawott, n' they help ta save tha PokéPark from danger.
NPC appearances
Pokémon Stadium: Pikachu stars up in tha mini-game "Thunderin Dynamo" alongside Voltorb. This mini-game involves chargin up electric power.
Yo You, Pikachu!: Pikachu stars alongside a unnamed lil pimp (who bears a strikin resemblizzle ta Red) whoz ass was recently taught how tha fuck ta interact wit wild Pokémon by Pimp Oak. Da pimp n' Pikachu form a funky-ass bond n' go on nuff adventures together, n' one dizzle tha Pikachu decides ta live wit tha boy.
Pokémon Stadium 2: Pikachu can be used up in "Pichuz Juice Plant" if one is detected up in a Transferred Pokémon game.
Pokémon Pinball: Pikachu serves as a Ball-Saver yo, but it will only work if tha Lightnin Meta is full.
Pokémon Pinball: Ruby & Sapphire: Pikachu has tha same ol' dirty role as up in Pokémon Pinbizzle but is sometimes helped by Pichu. Pikachu also appears on tha Catch 'Em Mode banner.
Pokémon Channel: Much like Yo You, Pikachu!, Pokémon Channel focuses on a funky-ass pimp n' a Pikachu bondin all up in hood interactions, like fuckin goin outside n' poppin' off ta other Pokémon, n' watchin TV together.
Pokédex entries
Generation I Red When nuff muthafuckin of these Pokémon gather, they electricitizzle could build n' cause lightnin storms. Blue Yellow It keeps its tail raised ta monitor its surroundings. If you yank its tail, it will try ta bite you, biatch. Stadium Lives up in forests away from people. Well shiiiit, it stores electricitizzle up in its cheeks fo' zappin a enemy if it be attacked. Generation Pt II Gold This intelligent Pokémon roasts hard berries wit electricitizzle ta make dem tender enough ta eat. Silver It raises its tail ta check its surroundings. Da tail is sometimes struck by lightnin up in dis pose. Crystal When it be angered, it immediately discharges tha juice stored up in tha pouches up in its cheeks. Stadium 2 This intelligent Pokémon roasts hard Berries wit electricitizzle ta make dem tender enough ta eat. Generation Pt III Ruby Whenever Pikachu comes across suttin' new, it blasts it wit a jolt of electricity. If you come across a funky-ass blackened berry, itz evidence dat dis Pokémon mistook tha intensitizzle of its charge. Sapphire This Pokémon has electricity-storin pouches on its cheeks. These step tha fuck up ta become electrically charged durin tha night while Pikachu chills. Well shiiiit, it occasionally discharges electricitizzle when it is dozy afta wakin up. Emerald It stores electricitizzle up in tha electric sacs on its cheeks. When it releases pent-up juice up in a funky-ass burst, tha electric juice is equal ta a lightnin bolt. FireRed It has lil' small-ass electric sacs on both its cheeks. If threatened, it looses electric charges from tha sacs. LeafChronic When nuff muthafuckin of these Pokémon gather, they electricitizzle could build n' cause lightnin storms. Generation IV Diamond It lives up in forests wit others. Well shiiiit, it stores electricitizzle up in tha pouches on its cheeks. Pearl If it looses cracklin juice from tha electrical pouches on its cheeks, it is bein wary. Platinum It occasionally uses a electric shock ta recharge a gangbangin' fellow Pikachu dat is up in a weakened state. HeartGold This intelligent Pokémon roasts hard berries wit electricitizzle ta make dem tender enough ta eat. SoulSilver It raises its tail ta check its surroundings. Da tail is sometimes struck by lightnin up in dis pose. Generation V Black It occasionally uses a electric shock ta recharge a gangbangin' fellow Pikachu dat is up in a weakened state. White Black 2 It occasionally uses a electric shock ta recharge a gangbangin' fellow Pikachu dat is up in a weakened state. White 2 Generation VI X It raises its tail ta check its surroundings. Da tail is sometimes struck by lightnin up in dis pose. Y It has lil' small-ass electric sacs on both its cheeks. If threatened, it looses electric charges from tha sacs. Omega Ruby Whenever Pikachu comes across suttin' new, it blasts it wit a jolt of electricity. If you come across a funky-ass blackened berry, itz evidence dat dis Pokémon mistook tha intensitizzle of its charge. Alpha Sapphire This Pokémon has electricity-storin pouches on its cheeks. These step tha fuck up ta become electrically charged durin tha night while Pikachu chills. Well shiiiit, it occasionally discharges electricitizzle when it is dozy afta wakin up. Generation VII Sun A plan was recently announced ta gather nuff Pikachu n' cook up a electric juice plant. Moon It aint nuthin but up in its nature ta store electricity. Well shiiiit, it feels stressed now n' then if itz unable ta straight-up discharge tha electricity. Ultra Sun Its nature is ta store up electricity. Forests where nestz of Pikachu live is dangerous, since tha trees is so often struck by lightning. Ultra Moon While chillin, it generates electricitizzle up in tha sacs up in its cheeks. If it aint gettin enough chill, it is ghon be able ta use only weak electricity. Letz Go Pikachu This forest-dwellin Pokémon stores electricitizzle up in its cheeks, so you gonna feel a tingly shock if you bust a nut on dat shit. Letz Go Eevee
Cap Pikachu
This Pokémon was unavailable prior ta Generation VII. Generation VII Sun This form of Pikachu is somewhat rare. Well shiiiit, it wears tha basebizzle cap of its Trainer, whoz ass be also its partner. Moon This Pikachu is bustin its Trainer’s cap. Right back up in yo muthafuckin ass. Since tha cap’s not tha right size, tha fit be a lil' bit loose. Ultra Sun This form of Pikachu is somewhat rare. Well shiiiit, it wears tha basebizzle cap of its Trainer, whoz ass be also its partner. Ultra Moon This Pikachu is bustin its Trainerz cap. Right back up in yo muthafuckin ass. Since tha capz not tha right size, tha fit be a lil' bit loose.
Game locations
In side games
In events
In-game events
Pokémon Global Link promotions
Held items
Stats
Base stats
Generation I-V
Stat Range At Lv. 50 At Lv. 100 HP : 35 95 - 142 180 - 274 Attack : 55 54 - 117 103 - 229 Defense : 30 31 - 90 58 - 174 Sp.Atk : 50 49 - 112 94 - 218 Sp.Def : 40 40 - 101 76 - 196 Speed : 90 85 - 156 166 - 306 Total: 300 Other Pokémon wit dis total Minimum stats is calculated wit 0 EVs , IVs of 0, n' a hinderin nature , if applicable.
Maximum stats is calculated wit 252 EVs, IVz of 31, n' a helpful nature, if applicable.
This Pokémonz Special base stat up in Generation I was 50.
Generation VI onward
Stat Range At Lv. 50 At Lv. 100 HP : 35 95 - 142 180 - 274 Attack : 55 54 - 117 103 - 229 Defense : 40 40 - 101 76 - 196 Sp.Atk : 50 49 - 112 94 - 218 Sp.Def : 50 49 - 112 94 - 218 Speed : 90 85 - 156 166 - 306 Total: 320 Other Pokémon wit dis total Minimum stats is calculated wit 0 EVs , IVs of 0, n' a hinderin nature , if applicable.
Maximum stats is calculated wit 252 EVs, IVz of 31, n' a helpful nature, if applicable.
Stat Range At Lv. 50 At Lv. 100 HP : 45 105 - 152 200 - 294 Attack : 80 76 - 145 148 - 284 Defense : 50 49 - 112 94 - 218 Sp.Atk : 75 72 - 139 139 - 273 Sp.Def : 60 58 - 123 112 - 240 Speed : 120 112 - 189 220 - 372 Total: 430 Other Pokémon wit dis total Minimum stats is calculated wit 0 EVs , IVs of 0, n' a hinderin nature , if applicable.
Maximum stats is calculated wit 252 EVs, IVz of 31, n' a helpful nature, if applicable.
Cuz of how tha fuck stats is calculated differently up in Pokémon: Letz Go, Pikachu! n' Letz Go, Eevee biaatch! compared ta tha other core series games, maximum stats aint reflected on tha table above.
Pokéathlon stats
Type effectiveness
Learnset
By a prior evolution
Generation VII Other generations: II - III - IV - V - VI Stage Move Type Cat. Pwr. Acc. PP Charm Fairy Status �" 100% 20 Sweet Kiss Fairy Status �" 75% 10 Nasty Plot Dark Status �" �"% 20 Bold indicates a move dat gets STAB when used by Pikachu
indicates a move dat gets when used by Pikachu Italic indicates a move dat gets STAB only when used by a evolution of Pikachu
indicates a move dat gets STAB only when used by a evolution of Pikachu Click on tha generation numbers all up in tha top ta peep moves from other generations
Special moves
Side game data
Evolution
Cosplay Pikachu
Cap Pikachu
Cap Pikachu Do not evolve Pikachu
Electric
Sprites
Other sprites
FireRed/LeafChronic credits
Trivia
Pikachu was designed by Atsuko Nishida, a cold-ass lil core designer at Game Freak.[2]
$1 coin from Niue featurin Pikachu
Pikachu up in Pokémon Stadium
Origin
Pikachu is based on a mouse afta its name. Its cheek pouches was also inspired by squirrels, which store chicken up in they cheeks. Da stripes on its back n' its lightnin bolt-shaped tail was given fo' aesthetic reasons.[4]
Pikachuz designer, Atsuko Nishida, revealed up in a rap battle dat Pikachu was originally a daifuku-like creature wit ears. Pikachuz black ear tips is remnants from dis original gangsta concept.[4]
Name origin
Pikachu be a cold-ass lil combination of �"カ�"カ pikapika (onomatopoeia fo' sparkle) n' チューチュー chūchū (the sound of a mouse squeaking).[5]
In other languages
Related articlez
References
|
// Validate returns a TypedError if an Followers struct is incorrect.
func (followers Followers) Validate() apierrors.TypedError {
if !spotifygo.Debug {
return nil
}
if followers.Href != "" {
return apierrors.NewBasicErrorFromString("Href is not empty in Followers")
}
if followers.Total < 0 {
return apierrors.NewBasicErrorFromString("Total is less than 0 in Followers")
}
return nil
}
|
/**
* Called whenever a players wants to specify a theme
*
* @param player the player
* @param theme the theme
* @since 5.8.0
*/
@Subcommand("forcetheme")
@Description("Force a them to be chosen")
@CommandPermission("bg.forcetheme")
@CommandCompletion("@arenas @nothing")
public void onForceTheme(Player player, String theme) {
YamlConfiguration messages = SettingsManager.getInstance().getMessages();
var arena = ArenaManager.getInstance().getArena(player);
if (arena == null) {
MessageManager.getInstance().send(player, ChatColor.RED + "You aren't in an arena");
return;
}
arena.getSubjectMenu().forceTheme(theme);
messages.getStringList("commands.forcetheme.success").forEach(message ->
MessageManager.getInstance().send(player, message.replace("%theme%", theme)));
}
|
from collections import OrderedDict
import torch
from torch import nn, nn as nn
from torch.nn import functional as F
def default_norm_layer(planes, groups=16):
groups_ = min(groups, planes)
if planes % groups_ > 0:
divisor = 16
while planes % divisor > 0:
divisor /= 2
groups_ = int(planes // divisor)
return nn.GroupNorm(groups_, planes)
def get_norm_layer(norm_type="group"):
if "group" in norm_type:
try:
grp_nb = int(norm_type.replace("group", ""))
return lambda planes: default_norm_layer(planes, groups=grp_nb)
except ValueError as e:
print(e)
print('using default group number')
return default_norm_layer
elif norm_type == "none":
return None
else:
return lambda x: nn.InstanceNorm3d(x, affine=True)
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1, bias=False):
"""3x3 convolution with padding"""
return nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=bias, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1, bias=True):
"""1x1 convolution"""
return nn.Conv3d(in_planes, out_planes, kernel_size=1, stride=stride, bias=bias)
class ConvBnRelu(nn.Sequential):
def __init__(self, inplanes, planes, norm_layer=None, dilation=1, dropout=0):
if norm_layer is not None:
super(ConvBnRelu, self).__init__(
OrderedDict(
[
('conv', conv3x3(inplanes, planes, dilation=dilation)),
('bn', norm_layer(planes)),
('relu', nn.ReLU(inplace=True)),
('dropout', nn.Dropout(p=dropout)),
]
)
)
else:
super(ConvBnRelu, self).__init__(
OrderedDict(
[
('conv', conv3x3(inplanes, planes, dilation=dilation, bias=True)),
('relu', nn.ReLU(inplace=True)),
('dropout', nn.Dropout(p=dropout)),
]
)
)
class UBlock(nn.Sequential):
"""Unet mainstream downblock.
"""
def __init__(self, inplanes, midplanes, outplanes, norm_layer, dilation=(1, 1), dropout=0):
super(UBlock, self).__init__(
OrderedDict(
[
('ConvBnRelu1', ConvBnRelu(inplanes, midplanes, norm_layer, dilation=dilation[0], dropout=dropout)),
(
'ConvBnRelu2',
ConvBnRelu(midplanes, outplanes, norm_layer, dilation=dilation[1], dropout=dropout)),
])
)
class UBlockCbam(nn.Sequential):
def __init__(self, inplanes, midplanes, outplanes, norm_layer, dilation=(1, 1), dropout=0):
super(UBlockCbam, self).__init__(
OrderedDict(
[
('UBlock', UBlock(inplanes, midplanes, outplanes, norm_layer, dilation=dilation, dropout=dropout)),
('CBAM', CBAM(outplanes, norm_layer=norm_layer)),
])
)
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
if __name__ == '__main__':
print(UBlock(4, 4))
class BasicConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1,
norm_layer=None):
super(BasicConv, self).__init__()
bias = False
self.out_channels = out_planes
self.conv = nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding,
dilation=dilation, groups=groups, bias=bias)
self.bn = norm_layer(out_planes)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.relu(x)
return x
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class ChannelGate(nn.Module):
def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max']):
super(ChannelGate, self).__init__()
self.gate_channels = gate_channels
self.mlp = nn.Sequential(
Flatten(),
nn.Linear(gate_channels, gate_channels // reduction_ratio),
nn.ReLU(inplace=True),
nn.Linear(gate_channels // reduction_ratio, gate_channels)
)
self.pool_types = pool_types
def forward(self, x):
channel_att_sum = None
for pool_type in self.pool_types:
if pool_type == 'avg':
avg_pool = F.avg_pool3d(x, (x.size(2), x.size(3), x.size(4)), stride=(x.size(2), x.size(3), x.size(4)))
channel_att_raw = self.mlp(avg_pool)
elif pool_type == 'max':
max_pool = F.max_pool3d(x, (x.size(2), x.size(3), x.size(4)), stride=(x.size(2), x.size(3), x.size(4)))
channel_att_raw = self.mlp(max_pool)
if channel_att_sum is None:
channel_att_sum = channel_att_raw
else:
channel_att_sum = channel_att_sum + channel_att_raw
scale = torch.sigmoid(channel_att_sum).unsqueeze(2).unsqueeze(3).unsqueeze(4).expand_as(x)
return x * scale
class ChannelPool(nn.Module):
def forward(self, x):
return torch.cat((torch.max(x, 1)[0].unsqueeze(1), torch.mean(x, 1).unsqueeze(1)), dim=1)
class SpatialGate(nn.Module):
def __init__(self, norm_layer=None):
super(SpatialGate, self).__init__()
kernel_size = 7
self.compress = ChannelPool()
self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size - 1) // 2, norm_layer=norm_layer)
def forward(self, x):
x_compress = self.compress(x)
x_out = self.spatial(x_compress)
scale = torch.sigmoid(x_out) # broadcasting
return x * scale
class CBAM(nn.Module):
def __init__(self, gate_channels, reduction_ratio=16, pool_types=None, norm_layer=None):
super(CBAM, self).__init__()
if pool_types is None:
pool_types = ['avg', 'max']
self.ChannelGate = ChannelGate(gate_channels, reduction_ratio, pool_types)
self.SpatialGate = SpatialGate(norm_layer)
def forward(self, x):
x_out = self.ChannelGate(x)
x_out = self.SpatialGate(x_out)
return x_out
|
Prevalence of human T-lymphotropic virus in civilian applicants for the United States Armed Forces.
BACKGROUND
The wide range in human T-lymphotropic virus (HTLV) seroprevalences reported worldwide has made estimates of seroprevalence difficult in unique populations. In this study, the seropositivity of young adult civilian applicants for the US Armed Forces was determined.
METHODS
Serum samples from nine geographic regions were screened by an Enzyme-Linked Immunosorbent Assay (ELISA), and repeatedly reactive samples were further tested by Western blot and radioimmunoprecipitation. Specimens were scored as positive when antibody to gag (p24) and env (gp46 or gp68) were detected.
RESULTS
Of the 43,750 samples analyzed, 18 were positive for HTLV antibodies. Ten (55%) were from males and eight (45%) were from females. Nine (90%) of the males and seven (87.5%) of the females were Black. Twelve of the positive samples (66.6%) were from the New York City region, which represented only 18.8% of the sample population.
CONCLUSIONS
The overall HTLV seroprevalence of civilian applicants for the US Armed forces was 0.41 per 1000. This was higher than the seroprevalence reported for volunteer blood donors.
|
<filename>7_kyu/Peak_array_index.py
from typing import List
def peak(arr: List[int]) -> int:
delta_sum = 0
left_index = 0
right_index = len(arr) - 1
while left_index < right_index:
if delta_sum <= 0:
delta_sum += arr[right_index]
right_index -= 1
else:
delta_sum -= arr[left_index]
left_index += 1
return left_index if delta_sum == 0 else -1
|
import {
NullableKeys,
NegativeTypes,
ExtractParams,
ExtractRequest,
HttpMethodsType,
ExtractQueryParams,
ExtractClientOptions,
} from "types";
import { Command } from "command";
import { ClientResponseType, ClientQueryParamsType } from "client";
// Progress
export type ClientProgressEvent = { total: number; loaded: number };
export type ClientProgressResponse = { progress: number; timeLeft: number; sizeLeft: number };
// Dump
/**
* Dump of the command used to later recreate it
*/
export type CommandDump<
Command extends CommandInstance,
// Bellow generics provided only to overcome the typescript bugs
ClientOptions = unknown,
QueryParamsType = ClientQueryParamsType,
> = {
commandOptions: CommandConfig<string, ClientOptions | ExtractClientOptions<Command>>;
endpoint: string;
method: HttpMethodsType;
headers?: HeadersInit;
auth: boolean;
cancelable: boolean;
retry: number;
retryTime: number;
cache: boolean;
cacheTime: number;
queued: boolean;
offline: boolean;
disableResponseInterceptors: boolean | undefined;
disableRequestInterceptors: boolean | undefined;
options?: ClientOptions | ExtractClientOptions<Command>;
data: CommandData<ExtractRequest<Command>, unknown>;
params: ExtractParams<Command> | NegativeTypes;
queryParams: QueryParamsType | ExtractQueryParams<Command> | NegativeTypes;
abortKey: string;
cacheKey: string;
queueKey: string;
effectKey: string;
used: boolean;
updatedAbortKey: boolean;
updatedCacheKey: boolean;
updatedQueueKey: boolean;
updatedEffectKey: boolean;
deduplicate: boolean;
deduplicateTime: number;
};
// Command
/**
* Configuration options for command creation
*/
export type CommandConfig<GenericEndpoint extends string, ClientOptions> = {
/**
* Determine the endpoint for command request
*/
endpoint: GenericEndpoint;
/**
* Custom headers for command
*/
headers?: HeadersInit;
/**
* Should the onAuth method get called on this command
*/
auth?: boolean;
/**
* Request method GET | POST | PATCH | PUT | DELETE
*/
method?: HttpMethodsType;
/**
* Should enable cancelable mode in the Dispatcher
*/
cancelable?: boolean;
/**
* Retry count when request is failed
*/
retry?: number;
/**
* Retry time delay between retries
*/
retryTime?: number;
/**
* Should we save the response to cache
*/
cache?: boolean;
/**
* Time for which the cache is considered up-to-date
*/
cacheTime?: number;
/**
* Should the requests from this command be send one-by-one
*/
queued?: boolean;
/**
* Do we want to store request made in offline mode for latter use when we go back online
*/
offline?: boolean;
/**
* Disable post-request interceptors
*/
disableResponseInterceptors?: boolean;
/**
* Disable pre-request interceptors
*/
disableRequestInterceptors?: boolean;
/**
* Additional options for your client, by default XHR options
*/
options?: ClientOptions;
/**
* Key which will be used to cancel requests. Autogenerated by default.
*/
abortKey?: string;
/**
* Key which will be used to cache requests. Autogenerated by default.
*/
cacheKey?: string;
/**
* Key which will be used to queue requests. Autogenerated by default.
*/
queueKey?: string;
/**
* Key which will be used to use effects. Autogenerated by default.
*/
effectKey?: string;
/**
* Should we deduplicate two requests made at the same time into one
*/
deduplicate?: boolean;
/**
* Time of pooling for the deduplication to be active (default 10ms)
*/
deduplicateTime?: number;
};
export type CommandData<PayloadType, MappedData> =
| (MappedData extends undefined ? PayloadType : MappedData)
| NegativeTypes;
export type CommandCurrentType<
ResponseType,
PayloadType,
QueryParamsType,
ErrorType,
GenericEndpoint extends string,
ClientOptions,
MappedData,
> = {
used?: boolean;
params?: ExtractRouteParams<GenericEndpoint> | NegativeTypes;
queryParams?: QueryParamsType | NegativeTypes;
data?: CommandData<PayloadType, MappedData>;
mockCallback?: ((data: PayloadType) => ClientResponseType<ResponseType, ErrorType>) | undefined;
headers?: HeadersInit;
updatedAbortKey?: boolean;
updatedCacheKey?: boolean;
updatedQueueKey?: boolean;
updatedEffectKey?: boolean;
} & Partial<NullableKeys<CommandConfig<GenericEndpoint, ClientOptions>>>;
export type ParamType = string | number;
export type ParamsType = Record<string, ParamType>;
export type ExtractRouteParams<T extends string> = string extends T
? NegativeTypes
: T extends `${string}:${infer Param}/${infer Rest}`
? { [k in Param | keyof ExtractRouteParams<Rest>]: ParamType }
: T extends `${string}:${infer Param}`
? { [k in Param]: ParamType }
: NegativeTypes;
export type FetchQueryParamsType<QueryParamsType, HasQuery extends true | false = false> = HasQuery extends true
? { queryParams?: NegativeTypes }
: {
queryParams?: QueryParamsType | string;
};
export type FetchOptionsType = { headers?: HeadersInit };
export type FetchParamsType<
EndpointType extends string,
HasParams extends true | false = false,
> = ExtractRouteParams<EndpointType> extends NegativeTypes
? { params?: NegativeTypes }
: true extends HasParams
? { params?: NegativeTypes }
: { params: ExtractRouteParams<EndpointType> };
export type FetchRequestDataType<PayloadType, HasData extends true | false = false> = PayloadType extends NegativeTypes
? { data?: NegativeTypes }
: HasData extends true
? { data?: NegativeTypes }
: { data: PayloadType };
export type CommandQueueOptions = {
dispatcherType?: "auto" | "fetch" | "submit";
};
export type FetchType<
PayloadType,
QueryParamsType,
EndpointType extends string,
HasData extends true | false,
HasParams extends true | false,
HasQuery extends true | false,
AdditionalOptions = unknown,
> = FetchQueryParamsType<QueryParamsType, HasQuery> &
FetchParamsType<EndpointType, HasParams> &
FetchRequestDataType<PayloadType, HasData> &
FetchOptionsType &
AdditionalOptions;
export type FetchMethodType<
ResponseType,
PayloadType,
QueryParamsType,
ErrorType,
EndpointType extends string,
HasData extends true | false,
HasParams extends true | false,
HasQuery extends true | false,
AdditionalOptions = unknown,
> = FetchType<
PayloadType,
QueryParamsType,
EndpointType,
HasData,
HasParams,
HasQuery,
AdditionalOptions
>["data"] extends any
? (
options?: FetchType<PayloadType, QueryParamsType, EndpointType, HasData, HasParams, HasQuery, AdditionalOptions>,
) => Promise<ClientResponseType<ResponseType, ErrorType>>
: FetchType<
PayloadType,
QueryParamsType,
EndpointType,
HasData,
HasParams,
HasQuery,
AdditionalOptions
>["data"] extends NegativeTypes
? FetchType<
PayloadType,
QueryParamsType,
EndpointType,
HasData,
HasParams,
HasQuery,
AdditionalOptions
>["params"] extends NegativeTypes
? (
options?: FetchType<
PayloadType,
QueryParamsType,
EndpointType,
HasData,
HasParams,
HasQuery,
AdditionalOptions
>,
) => Promise<ClientResponseType<ResponseType, ErrorType>>
: (
options: FetchType<PayloadType, QueryParamsType, EndpointType, HasData, HasParams, HasQuery, AdditionalOptions>,
) => Promise<ClientResponseType<ResponseType, ErrorType>>
: (
options: FetchType<PayloadType, QueryParamsType, EndpointType, HasData, HasParams, HasQuery>,
) => Promise<ClientResponseType<ResponseType, ErrorType>>;
export type CommandInstance = Command<any, any, any, any, any, any, any, any, any, any, any>;
|
//+----------------------------------------------------------------------------
//
// Member: GetWigglyFromRange
//
// Synopsis: Gets rectangles to use for focus rects. This
// element or range.
//
//-----------------------------------------------------------------------------
HRESULT
CDisplay::GetWigglyFromRange(CDocInfo * pdci, long cp, long cch, CShape ** ppShape)
{
CStackDataAry<RECT, 8> aryWigglyRects(Mt(CDisplayGetWigglyFromRange_aryWigglyRect_pv));
HRESULT hr = S_FALSE;
CWigglyShape * pShape = NULL;
CMarkup * pMarkup = GetMarkup();
long ich, cRects;
CTreePos * ptp = pMarkup->TreePosAtCp(cp, &ich, TRUE);
CTreeNode * pNode = ptp->GetBranch();
CElement * pElement = pNode->Element();
if (!cch)
{
goto Cleanup;
}
pShape = new CWigglyShape;
if (!pShape)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
RegionFromElement( pElement,
&aryWigglyRects,
NULL,
NULL,
RFE_WIGGLY,
cp,
cp + cch,
NULL );
for(cRects = 0; cRects < aryWigglyRects.Size(); cRects++)
{
CRectShape * pWiggly = NULL;
pWiggly = new CRectShape;
if (!pWiggly)
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
pWiggly->_rect = aryWigglyRects[cRects];
if ( pWiggly->_rect.left > 0
&& pWiggly->_rect.left != pWiggly->_rect.right )
{
--(pWiggly->_rect.left);
}
pShape->_aryWiggly.Append(pWiggly);
}
*ppShape = pShape;
hr = S_OK;
Cleanup:
if (hr && pShape)
{
delete pShape;
}
RRETURN1(hr, S_FALSE);
}
|
def _init_vars(self):
self._chassis_kf = None
self._chassis_D = 12
self._chassis_M = 4
self.GEAR_RATIO = 19.0
self.WHEEL_RADIUS = 0.075
self.L = None
self.W = None
self.MECANUM_M = None
self._imu_kf = None
self._imu_D = 9
self._imu_M = 7
|
import { AppEventServiceProxy } from './../../shared/service-proxies/service-proxies';
import { Component, Injector, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { EventListDto, EventListDtoListResultDto, GuidEntityDto } from '@shared/service-proxies/service-proxies';
import { PagedListingComponentBase, PagedRequestDto } from "shared/paged-listing-component-base";
import { CreateEventComponent } from "app/events/create-event/create-event.component";
@Component({
templateUrl: './events.component.html',
animations: [appModuleAnimation()]
})
export class EventsComponent extends PagedListingComponentBase<EventListDto> {
@ViewChild('createEventModal') createEventModal: CreateEventComponent;
active: boolean = false;
events: EventListDto[] = [];
includeCanceledEvents: boolean = false;
constructor(
injector: Injector,
private _eventService: AppEventServiceProxy
) {
super(injector);
}
protected list(request: PagedRequestDto, pageNumber: number, finishedCallback: Function): void {
this.loadEvent();
finishedCallback();
}
protected delete(event: GuidEntityDto): void {
abp.message.confirm(
'Are you sure you want to cancel this event?', '',
(result: boolean) => {
if (result) {
this._eventService.cancel(event)
.subscribe(() => {
abp.notify.info('Event is deleted');
this.refresh();
});
}
}
);
}
includeCanceledEventsCheckboxChanged() {
this.loadEvent();
};
createEvent(): void {
this.createEventModal.show();
}
loadEvent() {
this._eventService.getList(this.includeCanceledEvents)
.subscribe((result) => {
this.events = result.items;
});
}
}
|
/**
* Testing how auto resizing affects collection performance
* @param bh blackhole
*/
@Benchmark
public void addToCollection(Blackhole bh) {
List<Integer> list = new ArrayList<>(size);
for(Integer i:ints) {
list.add(i);
}
bh.consume(list);
}
|
/**
* Call this method when all facts have been gathered.
* @param debug debugging mode (diagnostics)
*/
public void writeFacts(boolean debug) {
if (!outDir.mkdirs() && debug)
System.out.println("WARNING: directory already exists: " + outDir);
for (Map.Entry<String, List<String>> entry : tables.entrySet()) {
String relName = entry.getKey();
try (FileWriter fw = new FileWriter(new File(outDir, relationPrefix + relName + ".facts"), append)) {
List<String> lines = tables.get(relName);
Collections.sort(lines);
if (lines.isEmpty()) {
if (Main.debug)
System.out.println("WARNING: empty relation " + relName);
} else
for (String line : lines) {
fw.write(line);
fw.write("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/**
* <p>
* Integration tests to verify that our FHIR server supports
* {@link CapabilityStatement}s via the <code>GET [base]/_metadata</code>
* endpoint. This is required by the FHIR STU3 specification, as detailed here:
* <a href="https://www.hl7.org/fhir/http.html#capabilities">FHIR RESTful API:
* capabilities</a>.
* </p>
* <p>
* Note that our application code doesn't directly provide this functionality.
* Instead, it comes "for free" with our use of the HAPI framework. These tests
* are just here to verify that it works as expected, since it's so critical for
* clients.
* </p>
*/
public final class ServerCapabilityStatementIT {
/**
* Verifies that the server responds as expected to the
* <code>GET [base]/_metadata</code> endpoint.
*/
@Test
public void getCapabilities() {
IGenericClient fhirClient = ServerTestUtils.createFhirClient();
CapabilityStatement capabilities = fhirClient.capabilities().ofType(CapabilityStatement.class).execute();
Assert.assertNotNull(capabilities);
// Verify that our custom server metadata is correct.
Assert.assertEquals(BlueButtonStu3Server.CAPABILITIES_PUBLISHER, capabilities.getPublisher());
Assert.assertEquals(BlueButtonStu3Server.CAPABILITIES_SERVER_NAME, capabilities.getSoftware().getName());
Assert.assertEquals("gov.hhs.cms.bluebutton.fhir:bluebutton-server-app",
capabilities.getImplementation().getDescription());
Assert.assertNotEquals(null, capabilities.getSoftware().getVersion());
Assert.assertNotEquals("", capabilities.getSoftware().getVersion());
// The default for this field is HAPI's version but we don't use that.
Assert.assertNotEquals(VersionUtil.getVersion(), capabilities.getSoftware().getVersion());
Assert.assertEquals(1, capabilities.getRest().size());
CapabilityStatementRestComponent restCapabilities = capabilities.getRestFirstRep();
Assert.assertEquals(RestfulCapabilityMode.SERVER, restCapabilities.getMode());
// Verify that Patient resource support looks like expected.
CapabilityStatementRestResourceComponent patientCapabilities = restCapabilities.getResource().stream()
.filter(r -> r.getType().equals(Patient.class.getSimpleName())).findAny().get();
Assert.assertTrue(patientCapabilities.getInteraction().stream()
.filter(i -> i.getCode() == TypeRestfulInteraction.READ).findAny().isPresent());
Assert.assertTrue(patientCapabilities.getInteraction().stream()
.filter(i -> i.getCode() == TypeRestfulInteraction.SEARCHTYPE).findAny().isPresent());
Assert.assertFalse(patientCapabilities.getInteraction().stream()
.filter(i -> i.getCode() == TypeRestfulInteraction.CREATE).findAny().isPresent());
// Verify that Coverage resource support looks like expected.
CapabilityStatementRestResourceComponent coverageCapabilities = restCapabilities.getResource().stream()
.filter(r -> r.getType().equals(Coverage.class.getSimpleName())).findAny().get();
Assert.assertTrue(coverageCapabilities.getInteraction().stream()
.filter(i -> i.getCode() == TypeRestfulInteraction.READ).findAny().isPresent());
Assert.assertTrue(coverageCapabilities.getInteraction().stream()
.filter(i -> i.getCode() == TypeRestfulInteraction.SEARCHTYPE).findAny().isPresent());
// Verify that EOB resource support looks like expected.
CapabilityStatementRestResourceComponent eobCapabilities = restCapabilities.getResource().stream()
.filter(r -> r.getType().equals(ExplanationOfBenefit.class.getSimpleName())).findAny().get();
Assert.assertTrue(eobCapabilities.getInteraction().stream()
.filter(i -> i.getCode() == TypeRestfulInteraction.READ).findAny().isPresent());
Assert.assertTrue(eobCapabilities.getInteraction().stream()
.filter(i -> i.getCode() == TypeRestfulInteraction.SEARCHTYPE).findAny().isPresent());
// Spot check that an arbitrary unsupported resource isn't listed.
Assert.assertFalse(restCapabilities.getResource().stream()
.filter(r -> r.getType().equals(DiagnosticReport.class.getSimpleName())).findAny().isPresent());
}
}
|
/// SinkParsedHLSUnrollPragmas - Sink parsed HLS region unroll pragmas from
/// parent scope to subloops
void Parser::SinkParsedHLSUnrollPragmas(ParsedAttributesWithRange &To,
Scope *P) {
auto *RegionUnrollAttr = IsRegionUnrollScope(P->getParsedHLSPragmas());
if (RegionUnrollAttr && IsHoistScope(P)) {
auto ArgNum = RegionUnrollAttr->getNumArgs();
ArgsVector Args;
for (unsigned i = 0; i < ArgNum; i++)
Args.emplace_back(RegionUnrollAttr->getArg(i));
auto *AttrName = getPreprocessor().getIdentifierInfo("opencl_unroll_hint");
To.addNew(AttrName, RegionUnrollAttr->getLoc(), nullptr,
RegionUnrollAttr->getScopeLoc(), &Args[0], ArgNum,
AttributeList::AS_GNU);
}
}
|
package ethos.model.players.packets.commands.owner;
import ethos.model.players.Player;
import ethos.model.players.packets.commands.Command;
/**
* Show the current position.
*
* @author Emiel
*
*/
public class Pos extends Command {
@Override
public void execute(Player player, String input) {
player.sendMessage("Current coordinates x: " + player.absX + " y:" + player.absY + " h:" + player.heightLevel);
}
}
|
package task
import (
"testing"
"github.com/stretchr/testify/assert"
)
// Fibonacci is the sum of the two preceding ones, starting from 0 and 1.
// https://en.wikipedia.org/wiki/Fibonacci_number
func Fibonacci(n int) int {
if n <= 1 {
return n
}
return Fibonacci(n-1) + Fibonacci(n-2)
}
func TestFibonacci(t *testing.T) {
testData := map[int]int{
1: 1,
2: 1,
3: 2,
4: 3,
5: 5,
}
for n, v := range testData {
assert.Equal(t, Fibonacci(n), v)
}
}
|
import logging
from dags.grobid_build_image import (
create_dag,
create_build_grobid_image_operator
)
from .test_utils import (
parse_command_arg,
create_and_render_command
)
from .grobid_train_test_utils import (
DEFAULT_CONF
)
LOGGER = logging.getLogger(__name__)
def _create_and_render_build_grobid_image_command(dag, airflow_context: dict) -> str:
return create_and_render_command(
create_build_grobid_image_operator(dag=dag),
airflow_context
)
class TestGrobidBuildImage:
class TestCreateDag:
def test_should_be_able_to_create_dag(self):
create_dag()
class TestCreateTrainGrobidModelOperator:
def test_should_include_namespace(self, dag, airflow_context, dag_run):
dag_run.conf = DEFAULT_CONF
rendered_bash_command = _create_and_render_build_grobid_image_command(
dag, airflow_context
)
opt = parse_command_arg(rendered_bash_command, {'--namespace': str})
assert getattr(opt, 'namespace') == DEFAULT_CONF['namespace']
|
def check_unbatched_time_step_spec(time_step, time_step_spec, batch_size):
if batch_size is None:
return array_spec.check_arrays_nest(time_step, time_step_spec)
return array_spec.check_arrays_nest(
time_step, array_spec.add_outer_dims_nest(time_step_spec, (batch_size,)))
|
package com.peterica.swagger.config;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
@Configuration
@Slf4j
public class DBConnectionConfig {
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String dbUsername;
@Value("${spring.datasource.password}")
private String dbPassword;
@Value("${spring.datasource.classname}")
private String dbClassName;
@Bean
public DataSource dataSource() {
final HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setUsername(dbUsername);
hikariConfig.setPassword(<PASSWORD>);
hikariConfig.addDataSourceProperty("url", dbUrl);
hikariConfig.setDataSourceClassName(dbClassName);
hikariConfig.setLeakDetectionThreshold(2000);
hikariConfig.setMaximumPoolSize(30);
hikariConfig.setPoolName("peterPool");
final HikariDataSource dataSources = new HikariDataSource(hikariConfig);
return dataSources;
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml"));
sessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:config/mybatis-config.xml"));
sessionFactory.setVfs(SpringBootVFS.class);
return sessionFactory.getObject();
}
}
|
<reponame>Pavel-Petkov03/Petstagram
from django import forms
from Petstagram.main.models.profile import ProfileModel
class CreateProfileForm(forms.ModelForm):
FIRST_NAME_MIN_LENGTH = 2
SECOND_NAME_MIN_LENGTH = 2
FIRST_NAME_MAX_LENGTH = 30
SECOND_NAME_MAX_LENGTH = 30
first_name = forms.CharField(label="First Name", max_length=FIRST_NAME_MAX_LENGTH, widget=forms.TextInput(attrs={
"type": "text", "class": "form-control", "name": "first_name", "maxlength": 30, "required": True,
"placeholder": "Enter first name", "id": "first_name"
}))
last_name = forms.CharField(label="Last Name", max_length=SECOND_NAME_MAX_LENGTH, widget=forms.TextInput(attrs={
"type": "text", "class": "form-control", "name": "second_name", "maxlength": 30, "required": True,
"placeholder": "Enter second name", "id": "id_last_name"
}))
profile_picture = forms.URLField(label="Link to Profile Image", widget=forms.URLInput(attrs={
"type": "url", "class": "form-control", "name": "profile_image", "required": True,
"placeholder": "Enter URL", "id": "id_image"
}))
class Meta:
fields = ["first_name", "last_name", "profile_picture"]
model = ProfileModel
|
package com.watson.pureenjoy.music.http.entity.rank;
public class RankSongInfo {
private String title;
private String author;
private String song_id;
private String album_id;
private String album_title;
private String rank_change;
private String all_rate;
private String biaoshi;
private String pic_small;
private String pic_big;
//详情页请求携带的字段
private String artist_id;
private String language;
private String country;
private String area;
private String publishtime;
private String album_no;
private String lrclink;
private String copy_type;
private String hot;
private String all_artist_ting_uid;
private String resource_type;
private String is_new;
private String rank;
private String all_artist_id;
private String si_proxycompany;
private String artist_name;
private String pic_radio;
private String pic_s500;
private String pic_premium;
private String pic_huge;
private String album_500_500;
private String album_1000_1000;
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getSong_id() {
return song_id;
}
public String getAlbum_id() {
return album_id;
}
public String getAlbum_title() {
return album_title;
}
public String getRank_change() {
return rank_change;
}
public String getAll_rate() {
return all_rate;
}
public String getBiaoshi() {
return biaoshi;
}
public String getPic_small() {
return pic_small;
}
public String getPic_big() {
return pic_big;
}
public String getArtist_id() {
return artist_id;
}
public String getLanguage() {
return language;
}
public String getCountry() {
return country;
}
public String getArea() {
return area;
}
public String getPublishtime() {
return publishtime;
}
public String getAlbum_no() {
return album_no;
}
public String getLrclink() {
return lrclink;
}
public String getCopy_type() {
return copy_type;
}
public String getHot() {
return hot;
}
public String getAll_artist_ting_uid() {
return all_artist_ting_uid;
}
public String getResource_type() {
return resource_type;
}
public String getIs_new() {
return is_new;
}
public String getRank() {
return rank;
}
public String getAll_artist_id() {
return all_artist_id;
}
public String getSi_proxycompany() {
return si_proxycompany;
}
public String getArtist_name() {
return artist_name;
}
public String getPic_radio() {
return pic_radio;
}
public String getPic_s500() {
return pic_s500;
}
public String getPic_premium() {
return pic_premium;
}
public String getPic_huge() {
return pic_huge;
}
public String getAlbum_500_500() {
return album_500_500;
}
public String getAlbum_1000_1000() {
return album_1000_1000;
}
}
|
Welcome to the Sunday Giveaway, the place where we giveaway a new Android phone each and every Sunday!
Congratulations to last week’s Samsung Galaxy S8 Plus Giveaway winner: Jorge V. (Portugal)
This week we’re giving away a brand new Samsung Galaxy S8!
Samsung’s new Galaxy S8 features a beautiful 18.5:9 Infinity display, a powerful Snapdragon 835 processor, 4 GB of RAM, a 3,000 mAh battery, as well as a super impressive 12 MP rear-facing camera with an f/1.7 aperture. One of the standout features on the Galaxy S8 and S8 Plus this year is Bixby, Samsung’s new AI assistant that even has its own hardware button. As an added bonus, the S8 ships with a solid pair of AKG earbuds.
Related Articles Samsung Galaxy S8 and Galaxy S8 Plus review: Almost to Infinity Photo Fight: Galaxy S8 vs LG G6, Xperia XZs, Huawei P10, Pixel XL, OnePlus 3T
Enter giveaway
Samsung Galaxy S8 International Giveaway!
More giveaways:
Winners Gallery
|
# Palindrome Partitioning
# 1. seach all possible substrings
# 2. stop early when a substring is not a palindrome
def partition(s):
def dfs(sub_str, path):
if not sub_str:
result.append(path)
return
for i in range(1, len(sub_str) + 1):
if is_palindrome(sub_str[:i]):
dfs(s[i:], path + [s[:i]])
result = []
dfs(s, [])
return result
def is_palindrome(s):
# return s == s[::-1]
for i in range(len(s) // 2):
j = len(s) - 1 - i
if s[i] != s[j]:
return False
return True
|
module Ptr where
import Rdg
import qualified RdgZipper as Z
data Ptr a = Ptr [a] a [a]
deriving (Eq, Show)
mkPtr :: [a] -> Ptr a
mkPtr (x:xs) = Ptr [] x xs
forward :: Ptr a -> Ptr a
forward (Ptr bs x (a:as)) = Ptr (x:bs) a as
backward :: Ptr a -> Ptr a
backward (Ptr (b:bs) x as) = Ptr bs b (x:as)
modify :: a -> Ptr a -> Ptr a
modify x (Ptr bs _ as) = Ptr bs x as
insertFront :: a -> Ptr a -> Ptr a
insertFront x (Ptr bs y as) = Ptr (x:bs) y as
insertAfter :: a -> Ptr a -> Ptr a
insertAfter x (Ptr bs y as) = Ptr bs y (x:as)
rewind :: Ptr a -> [a]
rewind (Ptr [] x as) = x:as
rewind (Ptr (b:bs) x as) = rewind (Ptr bs b (x:as))
type MPtr a = (Ptr a, Z.Location a)
mkMPtr :: [a] -> Rdg a -> MPtr a
mkMPtr xs rdg = (mkPtr xs, Z.mkloc rdg)
mforward :: MPtr a -> MPtr a
mforward (ptr, loc) = (forward ptr, Z.down loc)
mbackward :: MPtr a -> MPtr a
mbackward (ptr, loc) = (backward ptr, Z.up loc)
mchange :: a -> MPtr a -> MPtr a
mchange x (ptr, loc) = (modify x ptr, Z.modify x loc)
mrewind :: MPtr a -> ([a], Rdg a)
mrewind (ptr, loc) = (rewind ptr, Z.rewind (Z.invalidateCache loc))
|
package com.example.tour;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.tour.R;
public class LoginActivity extends AppCompatActivity {
final int MY_PERMISSION_REQUEST_SEND_SMS = 1;
DatabaseHelper gameCenterDB;
TextView appName, emailIn, passIn, loginBtn, regText, regLink;
static String userID;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.LoginTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
gameCenterDB = new DatabaseHelper(this);
Typeface robotoLight = Typeface.createFromAsset(getAssets(), "fonts/roboto/Roboto-Light.ttf");
Typeface robotoThin = Typeface.createFromAsset(getAssets(), "fonts/roboto/Roboto-Thin.ttf");
emailIn = findViewById(R.id.emailIn);
passIn = findViewById(R.id.passIn);
loginBtn = findViewById(R.id.loginBtn);
regText = findViewById(R.id.regText);
regLink = findViewById(R.id.regLink);
SpannableString content = new SpannableString(regLink.getText().toString());
content.setSpan(new UnderlineSpan(), 0, regLink.getText().toString().length(), 0);
regLink.setText(content);
emailIn.setTypeface(robotoLight);
passIn.setTypeface(robotoLight);
loginBtn.setTypeface(robotoLight);
if(ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSION_REQUEST_SEND_SMS);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(isEmpty())
Toast.makeText(LoginActivity.this, "Username and Password Cannot be Empty", Toast.LENGTH_LONG).show();
else{
String emailInStr = emailIn.getText().toString();
String passInStr = passIn.getText().toString();
userID = gameCenterDB.loginUser(emailInStr, passInStr);
if(!userID.equals("")){
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
else{
Toast.makeText(LoginActivity.this, "Wrong Username or Password", Toast.LENGTH_LONG).show();
}
}
}
});
regLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, RegistActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
private boolean isEmpty(){
if(emailIn.getText().toString().equals("") || passIn.getText().toString().equals(""))
return true;
else
return false;
}
}
|
/// Get the author key field of the header.
pub fn author_key_id(&self) -> &u64 {
match &self.ton_block {
TONBlock::Signed(x) => match x.signatures().keys().last() {
Some(key) => key,
None => unimplemented!()
},
TONBlock::Unsigned(x) => &x.keyid
}
}
|
Age-related skeletal muscle decline is similar in HIV-infected and uninfected individuals.
BACKGROUND
Skeletal muscle (SM) mass decreases with advanced age and with disease in HIV infection. It is unknown whether age-related muscle loss is accelerated in the current era of antiretroviral therapy and which factors might contribute to muscle loss among HIV-infected adults. We hypothesized that muscle mass would be lower and decline faster in HIV-infected adults than in similar-aged controls.
METHODS
Whole-body (1)H-magnetic resonance imaging was used to quantify regional and total SM in 399 HIV-infected and 204 control men and women at baseline and 5 years later. Multivariable regression identified associated factors.
RESULTS
At baseline and Year 5, total SM was lower in HIV-infected than control men. HIV-infected women were similar to control women at both time points. After adjusting for demographics, lifestyle factors, and total adipose tissue, HIV infection was associated with lower Year 5 SM in men and higher SM in women compared with controls. Average overall 5-year change in total SM was small and age related, but rate of change was similar in HIV-infected and control men and women. CD4 count and efavirenz use in HIV-infected participants were associated with increasing SM, whereas age and stavudine use were associated with decreasing SM.
CONCLUSIONS
Muscle mass was lower in HIV-infected men compared with controls, whereas HIV-infected women had slightly higher SM than control women after multivariable adjustment. We found evidence against substantially faster SM decline in HIV infected versus similar-aged controls. SM gain was associated with increasing CD4 count, whereas stavudine use may contribute to SM loss.
|
//This version of RegQueryValueEx always calls the Unicode version of the appropriate
//functions if it's running on an Unicode-enabled system. This helps in cases where
//we're reading data from the registry that may not translate properly through the
//WideCharToMultiByte/MultiByteToWideChar round-trip. The cannonical example of this
//is the Japanese Yen symbol which is stored in the registry as \u00A0, but gets translated
//to \u005C by WCTMB.
//This function only exists under Debug. On a retail build, it's #defined to call
//WszRegQueryValueEx.
LONG WszRegQueryValueExTrue(HKEY hKey, LPCWSTR lpValueName,
LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData,
LPDWORD lpcbData)
{
if (OnUnicodeSystem())
{
return RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData);
}
return WszRegQueryValueEx(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData);
}
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { budjetType } from '../budjetType';
@Injectable({
providedIn: 'root'
})
export class BudjetTypeService {
url:string = "http://127.0.0.1:8000/api/";
constructor( private http:HttpClient) { }
getBudjetType():Observable<budjetType[]>{
return this.http.get<budjetType[]>('http://127.0.0.1:8000/api/budjetTypes');
}
deleteBudjetType(id)
{
return this.http.delete('http://127.0.0.1:8000/api/budjetTypes/'+id);
}
budjetTypesadd(data):Observable<budjetType>
{
return this.http.post<budjetType>(this.url+'budjetTypes',data);
}
editBudjetType(data,id){
return this.http.put('http://127.0.0.1:8000/api/budjetTypes/'+id,data);
}
}
|
/* objects like player_ship, enemy ships, bullets etc. reused in reset */
void stall_objects_init()
{
stall_objects_clear();
stall_player_ship_creator();
global.state = STATE_MENU;
global.focus = FOCUS_START;
global.wave = 0;
global.phase = 0;
global.enemies_alive = 0;
global.enemy_bullets = 0;
global.score = 0;
global.fps = 0;
global.prev_time = time(0);
global.wavestart_time = 0;
global.waveend_time = 0;
global.wavecleared_time = 0;
global.wavescore_time = 0;
}
|
<gh_stars>1-10
use mq::{
camera::{set_camera, Camera2D},
color::{RED, WHITE},
math::Rect,
};
use zgui as ui;
mod common;
#[derive(Clone, Copy, Debug)]
enum Message {
Command,
}
pub fn make_and_set_camera(_aspect_ratio: f32) -> Camera2D {
let display_rect = Rect {
x: 0.0,
y: 0.0,
w: mq::window::screen_width(),
h: mq::window::screen_height(),
};
let camera = Camera2D::from_display_rect(display_rect);
set_camera(camera);
camera
}
fn make_gui(font: mq::text::Font) -> ui::Result<ui::Gui<Message>> {
let font_size = 64;
let mut gui = ui::Gui::new();
let anchor = ui::Anchor(ui::HAnchor::Right, ui::VAnchor::Bottom);
let text = ui::Drawable::text("Button", font, font_size);
let button = ui::Button::new(text, 0.2, gui.sender(), Message::Command)?;
gui.add(&ui::pack(button), anchor);
Ok(gui)
}
fn draw_scene() {
let x = 150.0;
let y = 150.0;
let r = 100.0;
let color = RED;
mq::shapes::draw_circle(x, y, r, color);
}
#[mq::main("ZGui: Pixel Coordinates Demo")]
#[macroquad(crate_rename = "mq")]
async fn main() {
let assets = common::Assets::load().await;
let mut gui = make_gui(assets.font).expect("Can't create the gui");
loop {
// Update the camera and the GUI.
let aspect_ratio = common::aspect_ratio();
let camera = make_and_set_camera(aspect_ratio);
gui.resize_if_needed(aspect_ratio);
// Handle cursor updates.
let pos = common::get_world_mouse_pos(&camera);
gui.move_mouse(pos);
if mq::input::is_mouse_button_pressed(mq::input::MouseButton::Left) {
let message = gui.click(pos);
println!("{:?}", message);
}
// Draw the GUI.
mq::window::clear_background(WHITE);
draw_scene();
gui.draw();
mq::window::next_frame().await;
}
}
|
/**
* Verifies the availability and status of the RdRand instruction
* on the host.
* @return Status of the RdRand instruction on the host.
*/
public static RdRandStatus verify() {
if (!LOADED) {
return RdRandStatus.NOT_LOADED;
}
int result = verifyNative();
return RdRandStatus.getStatusByCode(result);
}
|
<reponame>chromium/chromium<filename>chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/user_data/AssistantVerticalExpander.java<gh_stars>1000+
// Copyright 2019 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.
package org.chromium.chrome.browser.autofill_assistant.user_data;
import static org.chromium.chrome.browser.autofill_assistant.AssistantTagsForTesting.VERTICAL_EXPANDER_CHEVRON;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.chromium.base.Callback;
import org.chromium.chrome.autofill_assistant.R;
import org.chromium.chrome.browser.autofill_assistant.AssistantChevronStyle;
import org.chromium.components.browser_ui.widget.TintedDrawable;
/**
* This class provides a vertical expander widget, which allows to toggle between a collapsed and an
* expanded state of its child views.
*
* This widget expects three child views, one for the title, one for the collapsed and another for
* the expanded state. Each child <strong>must</strong> provide one of the respective layout
* parameters for disambiguation, otherwise the child won't be added at all!
*/
public class AssistantVerticalExpander extends LinearLayout {
private final ViewGroup mTitleContainer;
private final ViewGroup mCollapsedContainer;
private final ViewGroup mExpandedContainer;
private final LinearLayout mTitleAndChevronContainer;
private final View mChevronButton;
private Callback<Boolean> mOnExpansionStateChangedListener;
private View mTitleView;
private View mCollapsedView;
private View mExpandedView;
private boolean mExpanded;
private boolean mFixed;
private @AssistantChevronStyle int mChevronStyle = AssistantChevronStyle.NOT_SET_AUTOMATIC;
public AssistantVerticalExpander(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
mTitleContainer = createChildContainer();
mChevronButton = createChevron();
mCollapsedContainer = createChildContainer();
mExpandedContainer = createChildContainer();
LinearLayout titleContainer = new LinearLayout(getContext());
titleContainer.setOrientation(VERTICAL);
titleContainer.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
titleContainer.addView(mTitleContainer);
titleContainer.addView(mCollapsedContainer);
mTitleAndChevronContainer = new LinearLayout(getContext());
mTitleAndChevronContainer.setOrientation(HORIZONTAL);
mTitleAndChevronContainer.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mTitleAndChevronContainer.addView(titleContainer,
new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
mTitleAndChevronContainer.addView(mChevronButton);
update();
addView(mTitleAndChevronContainer);
addView(mExpandedContainer);
// Expand/Collapse when user clicks on the title, the chevron, or the collapsed section.
mTitleAndChevronContainer.setOnClickListener(unusedView -> {
if (!mFixed) {
setExpanded(!mExpanded);
}
});
}
public void setOnExpansionStateChangedListener(Callback<Boolean> listener) {
mOnExpansionStateChangedListener = listener;
}
public void setTitleView(View view, ViewGroup.LayoutParams lp) {
mTitleView = view;
mTitleContainer.removeAllViews();
if (view != null) {
mTitleContainer.addView(view, lp);
}
}
public void setCollapsedView(View view, ViewGroup.LayoutParams lp) {
mCollapsedView = view;
mCollapsedContainer.removeAllViews();
if (view != null) {
mCollapsedContainer.addView(view, lp);
}
update();
}
public void setExpandedView(View view, ViewGroup.LayoutParams lp) {
mExpandedView = view;
mExpandedContainer.removeAllViews();
if (view != null) {
mExpandedContainer.addView(view, lp);
}
update();
}
public void setExpanded(boolean expanded) {
if (expanded == mExpanded) {
return;
}
mExpanded = expanded;
mChevronButton.setScaleY(mExpanded ? -1 : 1);
update();
if (mOnExpansionStateChangedListener != null) {
mOnExpansionStateChangedListener.onResult(mExpanded);
}
}
/**
* Allows to hide the expand/collapse chevron, preventing users from expanding or collapsing the
* expander.
* @param fixed Whether expanding/collapsing should be disallowed (true) or allowed (false).
*/
public void setFixed(boolean fixed) {
if (fixed != mFixed) {
mFixed = fixed;
update();
}
}
public void setChevronStyle(@AssistantChevronStyle int chevronStyle) {
if (chevronStyle != mChevronStyle) {
mChevronStyle = chevronStyle;
update();
}
}
public boolean isExpanded() {
return mExpanded;
}
public boolean isFixed() {
return mFixed;
}
public void setCollapsedVisible(boolean visible) {
mCollapsedContainer.setVisibility(visible ? View.VISIBLE : View.GONE);
}
public void setExpandedVisible(boolean visible) {
mExpandedContainer.setVisibility(visible ? View.VISIBLE : View.GONE);
}
public View getChevronButton() {
return mChevronButton;
}
public View getTitleView() {
return mTitleView;
}
public View getCollapsedView() {
return mCollapsedView;
}
public View getExpandedView() {
return mExpandedView;
}
public View getTitleAndChevronContainer() {
return mTitleAndChevronContainer;
}
/**
* Creates a default container for children of this widget.
*/
private ViewGroup createChildContainer() {
FrameLayout container = new FrameLayout(getContext());
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
container.setLayoutParams(lp);
return container;
}
private View createChevron() {
TintedDrawable chevron = TintedDrawable.constructTintedDrawable(getContext(),
R.drawable.ic_expand_more_black_24dp, R.color.default_icon_color_tint_list);
ImageView view = new ImageView(getContext());
view.setImageDrawable(chevron);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_VERTICAL;
view.setLayoutParams(lp);
view.setTag(VERTICAL_EXPANDER_CHEVRON);
return view;
}
private void update() {
switch (mChevronStyle) {
case AssistantChevronStyle.NOT_SET_AUTOMATIC:
mChevronButton.setVisibility(
!mFixed && mExpandedView != null ? View.VISIBLE : View.GONE);
break;
case AssistantChevronStyle.ALWAYS:
mChevronButton.setVisibility(View.VISIBLE);
break;
case AssistantChevronStyle.NEVER:
mChevronButton.setVisibility(View.GONE);
break;
}
if (mExpandedView != null) {
mExpandedView.setVisibility(mExpanded ? VISIBLE : GONE);
}
if (mCollapsedView != null) {
mCollapsedView.setVisibility(mExpanded ? GONE : VISIBLE);
}
}
}
|
Bitwala, a Europe-based bitcoin payment service, has announced the addition of 9 new local currencies to its roster.
The announcement follows the platform’s support for the Japanese Yen and Mexican Peso. Bitwala said that with the support for 9 new local currencies, users will be able to make international money transfers from bitcoins or altcoins to local bank accounts in Australian Dollars (AUD), Brazilian Real (BRL), Chinese Yen (CNY), Japanese Yen (JPY), Malaysian Ringgit (MYR), Mexican Peso (MXN), Philippine Peso (PHP), South Korea Won (KRW), and last but not least the Vietnamese Dong (VND).
"Sending money in AUD, BRL, CNY, JPY, MYR, MXN, PHP, KRW, and VND has never been faster with an ETA average of 1 business day”, Bitwala said in a blog post. “As a Bitwala customer, you can enjoy making the fastest and cheapest international money transfers in the supported currencies at a flat 0.5% fee. Our exchange rate is updated around the clock, offering you the best value when sending money abroad.”
With this, Bitwala now supports a total of 20 currencies including CHF, CZK, DKK, EUR, GBP, HUF, HRK, PLN, SEK, and USD. According to the blog post, SEPA transfers within EU are performed within one working day while SWIFT transfers take between 2 to 3 business days on average.
The detailed service structure can be found here.
|
#include "cpushersession.h"
#include "../../core/csyslog.h"
#include "../cmessage.h"
#include "../ccredentials.h"
#include "../cchannels.h"
#include "../channels/cchannel.h"
#include <chrono>
void cpushersession::OnPusherSubscribe(const message_t& message) {
if ((*message)["data"].is_object() and (*message)["data"]["channel"].is_string() and !(*message)["data"]["channel"].empty()) {
if (auto chName{ (*message)["data"]["channel"].get<std::string>() }; !chName.empty() and chName.length() <= MaxChannelNameLength) {
if (auto chType{ ChannelType(chName) }; chType == channel_t::type::priv and (*message)["data"]["auth"].is_string()) {
if (App->IsAllowChannelSession(chType, Id(), chName, (*message)["data"]["auth"].get<std::string>())) {
if (auto&& chSelf{ Channels->Register(chType, App, std::string{chName}) }; chSelf) {
SubscribedTo.emplace(chName, chSelf);
chSelf->Subscribe(std::dynamic_pointer_cast<csubscriber>(shared_from_this()));
if (WsWriteMessage(opcode_t::text, json::serialize({
{"event","pusher_internal:subscription_succeeded"}, {"channel", chName}
})) == 0)
{
ActivityCheckTime = std::time(nullptr) + KeepAlive + 5;
}
return;
}
}
}
else if (chType == channel_t::type::pres and (*message)["data"]["auth"].is_string()) {
SessionPresenceData = (*message)["data"]["channel_data"].is_string() ? (*message)["data"]["channel_data"].get<std::string>() : std::string{};
if (App->IsAllowChannelSession(chType, Id(), chName, (*message)["data"]["auth"].get<std::string>(), SessionPresenceData)) {
if (auto&& chSelf{ Channels->Register(chType, App, std::string{chName}) }; chSelf) {
if (json::value_t ui; json::unserialize(SessionPresenceData, ui) and ui["user_id"].is_string()) { SessionUserId = ui["user_id"].get<std::string>(); }
SubscribedTo.emplace(chName, chSelf);
chSelf->Subscribe(std::dynamic_pointer_cast<csubscriber>(shared_from_this()));
usersids_t ids; userslist_t users;
chSelf->GetUsers(ids, users);
if (WsWriteMessage(opcode_t::text, json::serialize({
{"event","pusher_internal:subscription_succeeded"}, {"channel", chName},
{"data",json::serialize({ {"presence", json::object_t{{"ids",ids},{"hash",users},{"count",users.size()}}}})}
})) == 0)
{
ActivityCheckTime = std::time(nullptr) + KeepAlive + 5;
}
return;
}
}
}
else if (chType == channel_t::type::pub and App->IsAllowChannelSession(chType, Id(), chName, {})) {
if (auto&& chSelf{ Channels->Register(chType, App, std::string{chName}) }; chSelf) {
SubscribedTo.emplace(chName, chSelf);
chSelf->Subscribe(std::dynamic_pointer_cast<csubscriber>(shared_from_this()));
usersids_t ids; userslist_t users;
chSelf->GetUsers(ids, users);
if (WsWriteMessage(opcode_t::text, json::serialize({
{"event","pusher_internal:subscription_succeeded"}, {"channel", chName}
})) == 0)
{
ActivityCheckTime = std::time(nullptr) + KeepAlive + 5;
}
return;
}
}
}
}
WsError(close_t::ProtoError, -EPROTO);
}
void cpushersession::OnPusherUnSubscribe(const message_t& message) {
if ((*message)["data"].is_object() and (*message)["data"]["channel"].is_string()) {
if (auto&& chIt{ SubscribedTo.find((*message)["data"]["channel"].get<std::string>()) }; chIt != SubscribedTo.end()) {
if (auto&& ch{ chIt->second.lock() }; ch) {
ch->UnSubscribe(subsId);
}
}
}
}
void cpushersession::OnPusherPing(const message_t& message) {
syslog.print(7, "[ PUSHER:%s ] Ping ( ping )\n", Id().c_str());
if (WsWriteMessage(opcode_t::text, json::serialize({ {"event","pusher:pong"} })) == 0) {
ActivityCheckTime = std::time(nullptr) + KeepAlive + 5;
}
}
void cpushersession::OnPusherPush(const message_t& message) {
if (auto&& chName{ (*message)["channel"].get<std::string>() }; !chName.empty()) {
if (auto&& chIt{ SubscribedTo.find((*message)["data"]["channel"].get<std::string>()) }; chIt != SubscribedTo.end()) {
if (auto&& ch{ chIt->second.lock() }; ch) {
/*ch->Push(std::dynamic_pointer_cast<csubscriber>(shared_from_this()));
channels.Pull(sesApp, chName, shared_from_this(),
event(evName, chName, json::data(payload["data"]), {}, { sesId }));
*/
}
}
syslog.trace("[ PUSHER:%s ] Channel `%s` PULL\n", Id().c_str(), chName.c_str());
return;
}
WsError(close_t::ProtoError, -EPROTO);
}
void cpushersession::OnWsMessage(websocket_t::opcode_t opcode, const std::shared_ptr<uint8_t[]>& data, size_t length) {
if (auto&& message{ UnPack(data, length) }; message) {
ActivityCheckTime = std::time(nullptr) + KeepAlive + 5;
if (auto&& evName{ (*message)["event"].get<std::string>() }; !evName.empty()) {
if (evName == "pusher:subscribe") {
OnPusherSubscribe(message);
return;
}
else if (evName == "pusher:ping") {
OnPusherPing(message);
return;
}
else if (evName == "pusher:unsubscribe") {
OnPusherUnSubscribe(message);
return;
}
else if ((*message)["channel"].is_string()) {
OnPusherPush(message);
return;
}
}
}
WsError(close_t::ProtoError, -EPROTO);
}
#if SENDQ
void cpushersession::OnSocketSend() {
message_t message;
std::unique_lock<decltype(OutgoingLock)> lock(OutgoingLock);
while (!OutgoingQueue.empty()) {
message = OutgoingQueue.front();
OutgoingQueue.pop();
lock.unlock();
WsWriteMessage(opcode_t::text, Pack(message));
lock.lock();
}
SocketUpdateEvents(EPOLLIN | EPOLLRDHUP | EPOLLERR);
}
#endif
void cpushersession::OnSocketError(ssize_t err) {
syslog.error("[ PUSHER:%s ] Error ( %s )\n", Id().c_str(), std::strerror((int)-err));
for (auto&& it : SubscribedTo) {
if (auto&& ch{ it.second.lock() }; ch) {
ch->UnSubscribe(subsId);
}
}
SocketClose();
}
void cpushersession::OnWsClose() {
OnSocketError(-ENOTCONN);
}
bool cpushersession::OnWsConnect(const http::uri_t& path, const http::headers_t& headers) {
syslog.trace("[ PUSHER:%ld:%s ] Connect\n", Fd(), Id().c_str());
SetSendTimeout(500);
SetKeepAlive(true, 2, 1, 1);
if (WsWriteMessage(opcode_t::text, json::serialize({
{"event","pusher:connection_established"} ,
{"data", json::serialize({ {"socket_id",Id()}, {"activity_timeout", std::to_string(KeepAlive)},})}
}), false) == 0) {
Poll()->EnqueueGc(shared_from_this());
return true;
}
return false;
}
cpushersession::cpushersession(const std::shared_ptr<cchannels>& channels, const app_t& app, const inet::csocket& fd, size_t maxMessageLength, const channel_t& pushOnChannels, std::time_t keepAlive) :
inet::csocket{ std::move(fd) }, csubscriber{ GetAddress(), GetPort() },
MaxMessageLength{ maxMessageLength }, KeepAlive{ keepAlive }, Channels{ channels }, App{ app }, EnablePushOnChannels{ pushOnChannels }
{
ActivityCheckTime = std::time(nullptr) + KeepAlive + 5;
//syslog.print(1, "%s\n", __PRETTY_FUNCTION__);
}
cpushersession::~cpushersession() {
syslog.trace("[ PUSHER:%s ] Destroy\n", Id().c_str());
for (auto&& it : SubscribedTo) {
if (auto&& ch{ it.second.lock() }; ch) {
ch->UnSubscribe(subsId);
}
}
}
inline message_t cpushersession::UnPack(const std::shared_ptr<uint8_t[]>& data, size_t length) {
try {
return msg::unserialize({ data,length }, subsId);
}
catch (std::exception& ex) {
syslog.error("[ RAW:%s ] Message ( %s )\n", Id().c_str(), ex.what());
}
return {};
}
|
export class RegistrationPage {
fillRegistrationDetails(data: {
firstName: string;
lastName: string;
email: string;
phone: string;
password: string;
}) {
const firstName = $("#input-firstname");
expect(firstName).toBeDisplayed({
wait: 4000,
message: "Fields are not loaded",
});
firstName.setValue(data.firstName);
const lastName = $("#input-lastname");
lastName.setValue(data.lastName);
const email = $("#input-email");
email.setValue(data.email);
const telephone = $("#input-telephone");
telephone.setValue(data.phone);
const password = $("#input-password");
password.setValue(data.password);
const passwordConfirm = $("#input-confirm");
passwordConfirm.setValue(data.password);
}
checkAgreement() {
const agreeCheckbox = $('input[name="agree"]');
expect(agreeCheckbox).toBeDisplayed();
agreeCheckbox.click();
}
continue() {
const continueButton = $('input[type="submit"]');
expect(continueButton).toBeDisplayed();
continueButton.click();
}
open() {
browser.url("/index.php?route=account/register");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.